From 77b6a40d6914286935fd22779b6955566910b935 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Wed, 6 May 2026 17:57:30 +0300 Subject: [PATCH] test --- index.mjs | 36 ++++-- package.json | 6 +- src/dashboard/Dashboard.mjs | 196 ++++++++++++++++++++++++++---- src/dashboard/DatabaseManager.mjs | 55 --------- src/dashboard/RedisHandler.mjs | 146 +++++++++++++++++----- 5 files changed, 316 insertions(+), 123 deletions(-) delete mode 100644 src/dashboard/DatabaseManager.mjs diff --git a/index.mjs b/index.mjs index 9897b42..3072a0a 100644 --- a/index.mjs +++ b/index.mjs @@ -1547,12 +1547,24 @@ export class Remix { } getSharedServers(user) { - // guild.members.cache.has() only works for cached members (requires privileged intents). - // Instead, use the settings guilds map — any guild the bot is in and has settings for - // is one we actually serve, which is a reliable proxy for "shared server". - const mutualGuilds = this.client.guilds.filter(g => - this.settingsMgr.guilds.has(g.id) - ); + if (!user) return Promise.resolve([]); + + // Filter guilds to only those the specified user is actually a member of. + // This prevents leaking the full bot server list to unauthorized users. + const mutualGuilds = this.client.guilds.filter(g => { + // The bot must have settings for the guild (proves it's an active server) + if (!this.settingsMgr.guilds.has(g.id)) return false; + // The user must be a known member of the guild + if (g.members?.has?.(user.id)) return true; + // Fallback: check observed voice users for this guild + const cleanGuildId = String(g.id).replace(/\D/g, ""); + for (const [, info] of (this.observedVoiceUsers ?? [])) { + const infoGuild = String(info.guildId ?? "").replace(/\D/g, ""); + if (infoGuild === cleanGuildId) return true; + } + return false; + }); + return Promise.resolve([...mutualGuilds.values()].map(guild => ({ name: guild.name, id: guild.id, @@ -1560,7 +1572,7 @@ export class Remix { ? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp` : null, voiceChannels: guild.channels - .filter(c => c.isVoiceBased()) + .filter(c => c.isVoiceBased?.() ?? false) .map(c => ({ name: c.name, id: c.id, icon: null })), }))); } @@ -1622,7 +1634,7 @@ process.on("uncaughtExceptionMonitor", (err, origin) => { }); // ── Session Reboot Recovery Hooks ─────────────────────────────────────────── -const saveAndExit = () => { +const saveAndExit = async () => { logger.recovery("\n[Shutdown] Saving active sessions for reboot recovery..."); try { const state = remix.buildRecoveryState(); @@ -1630,6 +1642,14 @@ const saveAndExit = () => { } catch (e) { logger.error("[Shutdown] Failed to save recovery state:", e.message); } + // Gracefully close Redis connections before exiting + try { + if (remix.dashboard?.redis?.destroy) { + await remix.dashboard.redis.destroy(); + } + } catch (e) { + logger.error("[Shutdown] Failed to close Redis:", e.message); + } process.exit(0); }; diff --git a/package.json b/package.json index 428fc3d..f11adf3 100644 --- a/package.json +++ b/package.json @@ -4,18 +4,16 @@ "@fluxerjs/core": "^1.3.0", "@fluxerjs/voice": "^1.3.0", "@livekit/rtc-node": "^0.13.24", - "bcryptjs": "^3.0.3", - "express": "^4.18.2", + "bcryptjs": "^2.4.3", "ffmpeg-static": "^5.1.0", "ffprobe-static": "^3.1.0", "follow-redirects": "^1.15.2", "genius-lyrics": "^4.4.3", "moonlink.js": "^5.2.0", "mysql": "^2.18.1", - "mysql2": "^3.22.3", + "mysql2": "^3.9.0", "redis": "^5.12.1", "revoice.js": "^0.2.1696", - "util": "^0.12.5", "ws": "^8.19.0" }, "scripts": { diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 6cd7cbb..2d7778d 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -24,6 +24,12 @@ const FLUXER_API_DEFAULTS = { export class Dashboard { enabled = false; + // Rate limiter for token exchange — prevents abuse of the OAuth2 code→token endpoint. + // Tracks recent exchange timestamps per IP/request and rejects if exceeded. + _tokenExchangeTimestamps = []; + _tokenExchangeMaxPerWindow = 10; // max exchanges + _tokenExchangeWindowMs = 60_000; // per 60s window + /** * @param {Remix} remix * @param {Object} opts @@ -63,10 +69,11 @@ export class Dashboard { return Dashboard.convertUser(user); } - case "sharedServers": - return await this.remix.getSharedServers( - await this.remix.client.users.fetch(data.key).catch(() => null) - ); + case "sharedServers": { + const sharedUser = await this.remix.client.users.fetch(data.key).catch(() => null); + if (!sharedUser) return { error: "User not found" }; + return await this.remix.getSharedServers(sharedUser); + } case "server": { try { @@ -123,11 +130,10 @@ export class Dashboard { case "fluxerToken": { // Backend sends an authorization code — bot exchanges it for tokens. - // This is useful if the bot wants to perform the code→token exchange - // itself rather than relying on the backend to do it. + // Rate-limited to prevent token exchange abuse. const code = data.code; if (!code) return { error: "Missing authorization code" }; - return await this.exchangeFluxerCode(code); + return await this.rateLimitedExchange(code); } } }); @@ -187,6 +193,33 @@ export class Dashboard { } } + /** + * Exchange an OAuth2 authorization code for access/refresh tokens. + * This calls the Fluxer token endpoint directly. + * + * @param {string} code Authorization code from the OAuth2 redirect + * @returns {Promise} Token data or error + */ + /** + * Rate-limited wrapper around exchangeFluxerCode. + * Allows a maximum of _tokenExchangeMaxPerWindow exchanges per sliding window. + * @param {string} code Authorization code + * @returns {Promise} Token data or error + */ + async rateLimitedExchange(code) { + const now = Date.now(); + // Prune timestamps outside the current window + this._tokenExchangeTimestamps = this._tokenExchangeTimestamps.filter( + ts => now - ts < this._tokenExchangeWindowMs + ); + if (this._tokenExchangeTimestamps.length >= this._tokenExchangeMaxPerWindow) { + console.log("[Dashboard] Token exchange rate limit hit"); + return { error: "Rate limit exceeded. Try again later." }; + } + this._tokenExchangeTimestamps.push(now); + return await this.exchangeFluxerCode(code); + } + /** * Exchange an OAuth2 authorization code for access/refresh tokens. * This calls the Fluxer token endpoint directly. @@ -256,6 +289,7 @@ export class Dashboard { } switch (params.func) { case "join": { + if (!user) return { error: "Invalid user" }; let voiceChannel, textChannel; try { voiceChannel = await this.remix.client.channels.fetch(params.data.channel); @@ -264,7 +298,9 @@ export class Dashboard { console.log(e); return { error: "Invalid Channel" }; } - if (!user) return { error: "Invalid user" }; + // Verify the user has permission to join the voice channel + const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId); + if (authErr) return { error: authErr }; if (this.remix.players.playerMap.has(voiceChannel.id)) return { message: "Already Connected" }; const fakeMsg = { channel: { channel: textChannel, guildId: voiceChannel.guildId }, message: { guildId: voiceChannel.guildId } }; this.remix.players.initPlayer(fakeMsg, voiceChannel.id); @@ -272,45 +308,63 @@ export class Dashboard { } case "pausePlayback": { - let player = this._getPlayerById(params.data.player); + const player = this._getPlayerById(params.data.player); if (!player) return { error: "Player not found" }; - let msg = player.pause() || "Paused successfully"; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const msg = player.pause() || "Paused successfully"; return { message: msg }; } case "resumePlayback": { - let player = this._getPlayerById(params.data.player); + const player = this._getPlayerById(params.data.player); if (!player) return { error: "Player not found" }; - let msg = player.resume() || "Resumed successfully"; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const msg = player.resume() || "Resumed successfully"; return { message: msg }; } case "skip": { - let player = this._getPlayerById(params.data.player); + const player = this._getPlayerById(params.data.player); if (!player) return { error: "Player not found" }; - let msg = player.skip() || "Skipped song"; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const msg = player.skip() || "Skipped song"; return { message: msg }; } case "volume": { - let player = this._getPlayerById(params.data.player); + const player = this._getPlayerById(params.data.player); if (!player) return { error: "Player not found" }; - let msg = player.setVolume(params.data.volume); + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const vol = Number(params.data.volume); + if (isNaN(vol) || vol < 0 || vol > 150) return { error: "Volume must be between 0 and 150" }; + const msg = player.setVolume(vol); return { message: msg }; } case "addToQueue": { - let player = this._getPlayerById(params.data.player); + const player = this._getPlayerById(params.data.player); if (!player) return { error: "Player not found" }; if (!user) return { error: "Invalid user" }; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; const type = params.data.type; const query = params.data.query; + if (!query || typeof query !== "string") return { error: "Missing or invalid query" }; + if (query.length > 500) return { error: "Query too long (max 500 characters)" }; if (type === "radio") { const radio = this.remix.config.radio.find(e => e.name === query); if (!radio) return { error: "Invalid radio station" }; player.playRadio(radio); return { message: "Adding radio station" }; } + // Sanitize: reject obviously malicious patterns (JavaScript URLs, data URIs) + if (/^(javascript|data|vbscript):/i.test(query.trim())) { + return { error: "Invalid query protocol" }; + } player.play(query); return { message: "Adding to queue" }; } @@ -318,6 +372,67 @@ export class Dashboard { case "testConnection": { return { success: true }; } + + default: + return { error: "Unknown function: " + (params.func ?? "(none)") }; + } + } + + // ── Authorization helpers ────────────────────────────────────────────── + + /** + * Check if a user is a bot owner, or is in the same voice channel as the player. + * Bot owners are always allowed. Otherwise the user must be physically in the + * player's voice channel to control it. + * + * @param {import("discord.js").User|null} user + * @param {Player} player + * @returns {string|null} Error message, or null if authorized + */ + _authorizePlayerControl(user, player) { + // Bot owners bypass all checks + if (user && this.remix.handler?.owners?.includes?.(user.id)) return null; + + if (!user) return "User not provided"; + + const cleanUserId = String(user.id).replace(/\D/g, ""); + const cleanChanId = String(player._channelId ?? "").replace(/\D/g, ""); + if (!cleanChanId) return "Player has no active channel"; + + // Check observed voice users — the authoritative voice state map. + // Map key is userId, value is { channelId, guildId }. + const observed = this.remix.observedVoiceUsers; + if (observed) { + for (const [mapUserId, info] of observed) { + if (String(mapUserId).replace(/\D/g, "") === cleanUserId) { + const infoChannelId = String(info.channelId ?? "").replace(/\D/g, ""); + if (infoChannelId === cleanChanId) return null; // authorized + } + } + } + + return "You must be in the same voice channel as the bot to control playback"; + } + + /** + * Verify the user has permission to perform an action in the target guild. + * Bot owners are always allowed. Otherwise the user must be a member of the guild. + * + * @param {import("discord.js").User} user + * @param {string} guildId + * @returns {Promise} Error message, or null if authorized + */ + async _authorizeUserInGuild(user, guildId) { + if (this.remix.handler?.owners?.includes?.(user.id)) return null; + + try { + const guild = this.remix.client.guilds.get(guildId); + if (!guild) return "Server not found"; + const member = await guild.members.fetch(user.id).catch(() => null); + if (!member) return "You are not a member of this server"; + return null; + } catch (e) { + return "Failed to verify membership: " + e.message; } } @@ -442,6 +557,22 @@ export class Dashboard { }; } + /** + * Lightweight server summary for player payloads. + * Unlike convertServer(), this omits the full channels array to keep + * per-player Redis messages small (especially for large guilds). + * @param {import("discord.js").Guild} guild + */ + static convertServerSummary(guild) { + return { + name: guild.name, + id: guild.id, + icon: typeof guild.iconURL === "function" ? guild.iconURL() : null, + description: guild.description ?? null, + ownerId: guild.ownerId, + }; + } + /** * @param {Player} player */ @@ -476,7 +607,10 @@ export class Dashboard { return ids; })(), channel: channel ? Dashboard.convertChannel(channel) : null, - server: guild ? Dashboard.convertServer(guild) : null, + // Use lightweight server summary to avoid serializing hundreds of channels + // per player update. The frontend should fetch full server details via + // the "server" request type when needed. + server: guild ? Dashboard.convertServerSummary(guild) : null, }; } @@ -518,18 +652,34 @@ export class Dashboard { // ── Pub/Sub broadcast helpers ───────────────────────────────────────────── + // Debounce map for playerUpdate — prevents flooding Redis with rapid updates. + _playerUpdateTimers = new Map(); + /** * Global player update (broadcast to all dashboard listeners) + * Debounced: rapid successive calls for the same player are coalesced + * into a single publish every 500ms. * @param {Object} details * @param {Player} player */ playerUpdate(details, player) { if (!this.enabled) return; - const serialised = Dashboard.convertPlayer(player); - this.redis.send(this.redis.platform + ":players", JSON.stringify({ - ...details, - player: serialised, - })); + const key = player._channelId ?? player._guildId ?? "unknown"; + if (this._playerUpdateTimers.has(key)) { + clearTimeout(this._playerUpdateTimers.get(key)); + } + this._playerUpdateTimers.set(key, setTimeout(() => { + this._playerUpdateTimers.delete(key); + try { + const serialised = Dashboard.convertPlayer(player); + this.redis.send(this.redis.platform + ":players", JSON.stringify({ + ...details, + player: serialised, + })); + } catch (e) { + console.log("[Dashboard] playerUpdate error:", e.message); + } + }, 500)); } /** diff --git a/src/dashboard/DatabaseManager.mjs b/src/dashboard/DatabaseManager.mjs deleted file mode 100644 index 80f7896..0000000 --- a/src/dashboard/DatabaseManager.mjs +++ /dev/null @@ -1,55 +0,0 @@ -import { compare, genSalt, hash } from "bcryptjs"; -import { createPool } from "mysql2/promise"; -import mysql2 from "mysql2/promise"; -const { FieldPacket, PoolOptions, QueryResult } = mysql2; - -export class DatabaseManager { - /** - * @param {PoolOptions} config Based on https://sidorares.github.io/node-mysql2/docs#using-connection-pools - */ - constructor(config) { - this.db = createPool({ - connectionLimit: 15, - ...config - }); - } - /** - * @param {string} query - * @returns {Promise<[QueryResult, FieldPacket[]]>} - */ - async query(query) { - return this.db.query(query); - } - /** - * @param {string} query - * @param {string[]} [data] - * @returns {Promise} - */ - async execute(query, data) { - const [res, _fields] = await this.db.execute(query, data); - return res; - } - /** - * @param {string} plain - * @returns {Promise} - */ - async hash(plain) { - const salt = await genSalt(10); - return hash(plain, salt); - } - /** - * @param {string} plain - * @param {string} hash - * @returns {Promise} - */ - async compareHash(plain, hash) { - return await compare(plain, hash); - } - /** - * Gracefully closes any database connections - * @returns {Promise} - */ - close() { - return this.db.end(); - } -} diff --git a/src/dashboard/RedisHandler.mjs b/src/dashboard/RedisHandler.mjs index 6cf6471..7490283 100644 --- a/src/dashboard/RedisHandler.mjs +++ b/src/dashboard/RedisHandler.mjs @@ -1,59 +1,126 @@ import { createClient } from "redis"; +/** + * Default retry strategy: exponential backoff starting at 500ms, max 5s, max 20 retries. + * @param {Object} options + * @returns {number} Delay in ms before next retry, or an Error to stop retrying + */ +const DEFAULT_RETRY_STRATEGY = (options) => { + if (options.totalRetryTime > 60_000) { + // Stop retrying after 60s total — something is fundamentally wrong + return new Error("Redis reconnection exhausted after 60s"); + } + return Math.min(options.attempt * 500, 5_000); +}; + export class RedisHandler { platform = "fluxer"; + + /** @type {import("redis").RedisClientType|null} */ + client = null; + /** @type {import("redis").RedisClientType|null} */ + subscriber = null; + /** Whether the handler has been explicitly destroyed */ + _destroyed = false; + /** - * * @param {Object} opts - * @param {import("redis").RedisClientOptions} opts + * @param {import("redis").RedisClientOptions} opts Redis client options + * @param {string} [opts.platform] Platform identifier for channel namespacing */ - constructor(opts) { - this.client = createClient(opts); + constructor(opts = {}) { + this.platform = opts.platform ?? "fluxer"; + + const clientOpts = { + ...opts, + socket: { + ...(opts.socket ?? {}), + reconnectStrategy: DEFAULT_RETRY_STRATEGY, + }, + }; + + this.client = createClient(clientOpts); this.client.on("error", (err) => { - console.log("[Redis/Main] Error: ", err); - }); - this.client.connect().then(() => { - console.log("[RedisMain] Connected"); - this.readyMessage(); + console.log("[Redis/Main] Error:", err.message); }); this.subscriber = this.client.duplicate(); this.subscriber.on("error", (err) => { - console.log("[Redis/Subscriber] Error: ", err); - }); - this.subscriber.connect().then(() => { - console.log("[Redis/Subscriber] Connected"); - this.subscriber.subscribe("request", async (m) => { - const payload = JSON.parse(m); - if (payload.platform !== this.platform) return; - const result = await this.handleRequest(payload.content); - this.send("response", JSON.stringify({ - id: payload.id, - content: result - })); - }); - this.subscriber.subscribe("info", (m) => { - const data = JSON.parse(m); - if (data.platform !== "backend") return; - if (data.type !== "requestConnected") return; - this.readyMessage(); - }); + console.log("[Redis/Subscriber] Error:", err.message); }); + + this._connect(); } + + /** + * Connect both publisher and subscriber with reconnection support. + * Wrapped in a method so it can be called once from the constructor. + */ + async _connect() { + try { + await this.client.connect(); + console.log("[Redis/Main] Connected"); + this.readyMessage(); + } catch (e) { + console.log("[Redis/Main] Initial connection failed:", e.message); + } + + try { + await this.subscriber.connect(); + console.log("[Redis/Subscriber] Connected"); + + this.subscriber.subscribe("request", async (m) => { + if (this._destroyed) return; + try { + const payload = JSON.parse(m); + if (payload.platform !== this.platform) return; + if (typeof this.handleRequest !== "function") return; + const result = await this.handleRequest(payload.content); + this.send("response", JSON.stringify({ + id: payload.id, + content: result, + })); + } catch (e) { + console.log("[Redis/Subscriber] Request handler error:", e.message); + } + }); + + this.subscriber.subscribe("info", (m) => { + if (this._destroyed) return; + try { + const data = JSON.parse(m); + if (data.platform !== "backend") return; + if (data.type !== "requestConnected") return; + this.readyMessage(); + } catch (e) { + console.log("[Redis/Subscriber] Info handler error:", e.message); + } + }); + } catch (e) { + console.log("[Redis/Subscriber] Initial connection failed:", e.message); + } + } + readyMessage() { + if (this._destroyed) return; this.send("info", JSON.stringify({ - platform: "fluxer", - type: "connected" + platform: this.platform, + type: "connected", })); } + /** - * + * Publish a message to a Redis channel. * @param {string} channel * @param {string} message - * @returns {Promise} + * @returns {Promise} Number of subscribers that received the message */ send(channel, message) { - return this.client.publish(channel, message); + if (this._destroyed || !this.client?.isReady) return Promise.resolve(0); + return this.client.publish(channel, message).catch((e) => { + console.log("[Redis/Main] Publish error:", e.message); + return 0; + }); } /** @@ -63,10 +130,23 @@ export class RedisHandler { * @returns {Promise} */ handleRequest; + /** * @param {RequestCallback} handler */ setRequestHandler(handler) { this.handleRequest = handler; } + + /** + * Gracefully close both Redis connections. + * Should be called on process shutdown to avoid abrupt connection drops. + * @returns {Promise} + */ + async destroy() { + this._destroyed = true; + try { await this.subscriber?.quit(); } catch (_) {} + try { await this.client?.quit(); } catch (_) {} + console.log("[Redis] Connections closed gracefully"); + } }