mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
testing this for a day if its bad i just wast my time
This commit is contained in:
1 parent
fd58343ce9
commit
656cbfe149
33 files changed
+726
-102
No files matched your search
@@ -33,6 +33,8 @@ export class CommandHandler extends EventEmitter {
|
||||
pingPrefix = true;
|
||||
/** @type {string[]} Bot owner user IDs. */
|
||||
owners = [];
|
||||
/** When false (default) messages from other bots/webhooks never trigger commands (set config.allowBotCommands = true to allow). */
|
||||
allowBotCommands = false;
|
||||
|
||||
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
|
||||
messages;
|
||||
@@ -131,6 +133,8 @@ export class CommandHandler extends EventEmitter {
|
||||
*/
|
||||
messageHandler(msg) {
|
||||
if (!msg || !msg.content) return;
|
||||
const author = msg.message?.author ?? msg.author;
|
||||
if (author?.bot && !this.allowBotCommands) return;
|
||||
const trimmed = msg.content.trim();
|
||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||
const botId = this.client.user?.id;
|
||||
@@ -244,7 +248,7 @@ export class CommandHandler extends EventEmitter {
|
||||
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
|
||||
* @returns {object|undefined} The command run payload.
|
||||
*/
|
||||
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||
processCommand(cmd, args, msg, previous = false, external = false, requirementsChecked = false) {
|
||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||
|
||||
if (!external) {
|
||||
@@ -266,8 +270,8 @@ export class CommandHandler extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
if (cmd.requirements.length > 0 && !external) {
|
||||
if (!this.assertRequirements(cmd, msg)) return;
|
||||
if (cmd.requirements.length > 0 && !external && !requirementsChecked) {
|
||||
if (!this.assertRequirements(cmd, msg, args, previous)) return;
|
||||
}
|
||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||
@@ -444,7 +448,7 @@ export class CommandHandler extends EventEmitter {
|
||||
* @param {Message} msg
|
||||
* @returns {boolean}
|
||||
*/
|
||||
assertRequirements(cmd, msg) {
|
||||
assertRequirements(cmd, msg, args = null, previous = false) {
|
||||
const authorId = msg.message?.author?.id;
|
||||
const isOwner = this.owners.includes(authorId);
|
||||
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
@@ -477,12 +481,19 @@ export class CommandHandler extends EventEmitter {
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
} else {
|
||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix2 = this.getPrefix(guildId2);
|
||||
const rawContent = msg.message.content;
|
||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
this.processCommand(cmd, args, msg, false, true);
|
||||
let dispatchArgs = args;
|
||||
if (!dispatchArgs) {
|
||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix2 = this.getPrefix(guildId2);
|
||||
const rawContent = msg.message.content;
|
||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||
dispatchArgs = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
}
|
||||
try {
|
||||
this.processCommand(cmd, dispatchArgs, msg, previous, false, true);
|
||||
} catch (e) {
|
||||
logger.error("[CommandHandler] Command failed after async permission check:", e);
|
||||
}
|
||||
}
|
||||
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
||||
return false;
|
||||
|
||||
+18
-4
@@ -25,6 +25,7 @@ import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
||||
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
||||
import { RejoinBackoff } from "../voice/gateway/RejoinBackoff.mjs";
|
||||
import { LastFmManager } from "../services/lastfm/LastFmManager.mjs";
|
||||
import { FluxerListManager } from "../services/FluxerListManager.mjs";
|
||||
import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs";
|
||||
@@ -220,7 +221,12 @@ class Remix {
|
||||
}
|
||||
);
|
||||
};
|
||||
commands.owners = config.owners ?? [];
|
||||
const ownerList = [].concat(config.owners ?? []);
|
||||
if (ownerList.some((id) => typeof id === "number")) {
|
||||
logger.warn("[Config] owners contains a JSON number. Snowflake IDs exceed 2^53 and are corrupted as numbers: write each ID as a quoted string.");
|
||||
}
|
||||
commands.owners = ownerList.map((id) => String(id).trim()).filter(Boolean);
|
||||
commands.allowBotCommands = config.allowBotCommands === true;
|
||||
|
||||
this.lavalink = null;
|
||||
let lavalinkInitialised = false;
|
||||
@@ -241,6 +247,8 @@ class Remix {
|
||||
this.intentionalLeaves = new Map();
|
||||
/** Bot-level 24/7 rejoin timers (channelId → Timeout). Owned by Remix, not by Players. */
|
||||
this._247RejoinTimers = new Map();
|
||||
/** Escalating per-channel cool-down so the 24/7 watchdog stops hammering channels it cannot join. */
|
||||
this.rejoinBackoff = new RejoinBackoff();
|
||||
|
||||
this.gatewayHandler = new GatewayHandler(this);
|
||||
this.gatewayHandler.setupEventHandlers();
|
||||
@@ -333,9 +341,15 @@ class Remix {
|
||||
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||
} catch (e) {
|
||||
logger.warn("[Git] comhash error:", e?.message);
|
||||
this.comHash = "Newest";
|
||||
this.comHashLong = null;
|
||||
const sha = process.env.GIT_SHA?.trim();
|
||||
if (sha) {
|
||||
this.comHash = sha.slice(0, 7);
|
||||
this.comHashLong = sha;
|
||||
} else {
|
||||
logger.warn("[Git] comhash error:", e?.message);
|
||||
this.comHash = "Newest";
|
||||
this.comHashLong = null;
|
||||
}
|
||||
}
|
||||
|
||||
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||
|
||||
@@ -17,6 +17,15 @@ import { remove247ChannelMode, isPlayerConnectionDead, detachPlayerFromManager,
|
||||
import { logger } from "./Logger.mjs";
|
||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||
|
||||
/** Reject if `promise` has not settled within `ms` (the timer is always cleared). */
|
||||
function withTimeout(promise, ms, label) {
|
||||
let timer;
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); }),
|
||||
]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Voice/channel mixin — applied to Remix.
|
||||
@@ -390,6 +399,7 @@ const BotVoiceMixin = {
|
||||
|
||||
this.players.playerMap.set(cleanChannelId, player);
|
||||
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
||||
this.rejoinBackoff?.recordSuccess(cleanChannelId);
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.delete(cleanChannelId);
|
||||
}
|
||||
@@ -444,9 +454,29 @@ const BotVoiceMixin = {
|
||||
logger.player(`[Restore] ${rows.length} saved player(s) found — restoring ${local.length} on this shard.`);
|
||||
if (!local.length) return;
|
||||
|
||||
for (let i = 0; i < local.length; i++) {
|
||||
const { guildId, data: snap } = local[i];
|
||||
if (i > 0) await new Promise((r) => setTimeout(r, 1_500));
|
||||
const rc = this.config?.restore ?? {};
|
||||
const num = (v, d) => (Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : d);
|
||||
const spacingMs = num(rc.spacingMs, 1_500);
|
||||
const startTimeoutMs = num(rc.startTimeoutMs, 20_000);
|
||||
const seekSettleMs = num(rc.seekSettleMs, 800);
|
||||
const spawnTimeoutMs = num(rc.spawnTimeoutMs, 60_000);
|
||||
const rawHours = Number(rc.maxAgeHours);
|
||||
const maxAgeHours = rawHours > 0 ? rawHours : 12;
|
||||
|
||||
const toRestore = [];
|
||||
for (const r of local) {
|
||||
if (Number.isFinite(r.ageMs) && r.ageMs > maxAgeHours * 3_600_000) {
|
||||
logger.player(`[Restore] Snapshot for guild ${r.guildId} is ${(r.ageMs / 3_600_000).toFixed(1)}h old (limit ${maxAgeHours}h), dropping it.`);
|
||||
try { await store.clearSnapshot(r.guildId); } catch (_) {}
|
||||
} else {
|
||||
toRestore.push(r);
|
||||
}
|
||||
}
|
||||
if (!toRestore.length) return;
|
||||
|
||||
for (let i = 0; i < toRestore.length; i++) {
|
||||
const { guildId, data: snap } = toRestore[i];
|
||||
if (i > 0) await new Promise((r) => setTimeout(r, spacingMs));
|
||||
|
||||
try {
|
||||
const channelId = cleanId(snap.channelId);
|
||||
@@ -459,7 +489,7 @@ const BotVoiceMixin = {
|
||||
continue;
|
||||
}
|
||||
|
||||
const player = await this._spawnPlayer(guildId, channelId);
|
||||
const player = await withTimeout(this._spawnPlayer(guildId, channelId), spawnTimeoutMs, "Voice join");
|
||||
|
||||
const tcId = cleanId(snap.textChannelId);
|
||||
if (tcId) {
|
||||
@@ -497,11 +527,25 @@ const BotVoiceMixin = {
|
||||
system: true,
|
||||
});
|
||||
|
||||
await player.playNext();
|
||||
await new Promise((resolve) => {
|
||||
const timer = setTimeout(() => { player.off("startplay", onStart); resolve(); }, startTimeoutMs);
|
||||
const onStart = () => { clearTimeout(timer); player.off("startplay", onStart); resolve(); };
|
||||
player.once("startplay", onStart);
|
||||
player.playNext().then(onStart, (e) => {
|
||||
logger.warn(`[Restore] playNext failed for guild ${guildId}:`, e?.message ?? e);
|
||||
onStart();
|
||||
});
|
||||
});
|
||||
|
||||
if (current && pos > 0 && dur > 0) {
|
||||
await new Promise((r) => setTimeout(r, 800)); // let the bridge settle
|
||||
try { await player.seekToPosition(pos); } catch (_) {}
|
||||
(async () => {
|
||||
const deadline = Date.now() + 15_000;
|
||||
while (Date.now() < deadline && player._audioBridge?._playing !== true) {
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, seekSettleMs)); // let the bridge settle
|
||||
try { await player.seekToPosition(pos); } catch (_) {}
|
||||
})().catch(() => {});
|
||||
}
|
||||
|
||||
logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* @module src/core/Heartbeat
|
||||
* @description Liveness heartbeat for the container HEALTHCHECK.
|
||||
*
|
||||
* The old healthcheck was `pgrep -f "node .*index.mjs"`, which (a) needs `procps`, not present in
|
||||
* the slim Node image, and (b) can only say "the process exists", never "the bot is working". This
|
||||
* writes a timestamp to a file every few seconds, but only while the Node event loop is actually
|
||||
* running timers AND the bot is logged in. `docker/healthcheck.mjs` fails when the file is missing
|
||||
* or stale, so a blocked event loop or a bot that never logged in now shows up as unhealthy.
|
||||
* It does nothing unless HEARTBEAT_FILE is set (the Dockerfile sets it).
|
||||
*/
|
||||
import { writeFile } from "node:fs";
|
||||
|
||||
/**
|
||||
* @param {object} [o]
|
||||
* @param {string} [o.file=process.env.HEARTBEAT_FILE] - Heartbeat file; no file means no heartbeat.
|
||||
* @param {number} [o.intervalMs=15000]
|
||||
* @param {() => boolean} [o.isReady] - Only beat while this returns true (e.g. "logged in").
|
||||
* @param {() => number} [o.now]
|
||||
* @returns {NodeJS.Timeout|null} The (unref'd) interval, or null when disabled.
|
||||
*/
|
||||
export function startHeartbeat({ file = process.env.HEARTBEAT_FILE, intervalMs = 15_000, isReady = () => true, now = Date.now } = {}) {
|
||||
if (!file) return null;
|
||||
const beat = () => {
|
||||
let ready = false;
|
||||
try { ready = Boolean(isReady()); } catch (_) {}
|
||||
if (ready) writeFile(file, String(now()), () => {});
|
||||
};
|
||||
beat();
|
||||
const timer = setInterval(beat, intervalMs);
|
||||
timer.unref?.();
|
||||
return timer;
|
||||
}
|
||||
|
||||
export default { startHeartbeat };
|
||||
@@ -209,12 +209,14 @@ export class PlayerStateStore {
|
||||
|
||||
/**
|
||||
* Load every snapshot belonging to this bot.
|
||||
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number}>>}
|
||||
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number, ageMs: number|null}>>}
|
||||
* ageMs = time since the row was last written, measured by the DATABASE clock (immune to
|
||||
* bot/DB clock skew); null when it cannot be determined.
|
||||
*/
|
||||
async loadAll() {
|
||||
await this.init();
|
||||
const rows = await this._exec(
|
||||
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ?`,
|
||||
`SELECT guild_id, data, position_ms, TIMESTAMPDIFF(SECOND, updated_at, NOW()) AS age_s FROM player_state WHERE bot_id = ?`,
|
||||
[this.botId]
|
||||
);
|
||||
const out = [];
|
||||
@@ -222,7 +224,11 @@ export class PlayerStateStore {
|
||||
try {
|
||||
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
|
||||
if (parsed && parsed.channelId) {
|
||||
out.push({ guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0 });
|
||||
const ageS = row.age_s == null ? NaN : Number(row.age_s);
|
||||
out.push({
|
||||
guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0,
|
||||
ageMs: Number.isFinite(ageS) ? Math.max(0, ageS) * 1000 : null,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
|
||||
|
||||
+16
-3
@@ -172,6 +172,9 @@ export class RemoteSettingsManager extends SettingsManager {
|
||||
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
|
||||
_debounceTimers = new Map();
|
||||
|
||||
/** @private @type {Map<string, Set<string>>} Keys changed since the last flush, per guild: one debounce window can span several keys. */
|
||||
_dirtyKeys = new Map();
|
||||
|
||||
/** @private @type {boolean} True after shutdown() is called. */
|
||||
_shuttingDown = false;
|
||||
|
||||
@@ -210,6 +213,7 @@ export class RemoteSettingsManager extends SettingsManager {
|
||||
.filter(Boolean);
|
||||
for (const [, timer] of this._debounceTimers) clearTimeout(timer);
|
||||
this._debounceTimers.clear();
|
||||
this._dirtyKeys?.clear();
|
||||
if (pendingServers.length > 0) {
|
||||
logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`);
|
||||
}
|
||||
@@ -475,20 +479,28 @@ export class RemoteSettingsManager extends SettingsManager {
|
||||
}
|
||||
const s = this.guilds.get(server.id);
|
||||
s.data[key] = server.data[key];
|
||||
this._dirtyKeys ??= new Map();
|
||||
if (key === 'stay_247') {
|
||||
const existing = this._debounceTimers.get(server.id);
|
||||
if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); }
|
||||
this._dirtyKeys.delete(server.id);
|
||||
this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message));
|
||||
return;
|
||||
}
|
||||
let dirty = this._dirtyKeys.get(server.id);
|
||||
if (!dirty) { dirty = new Set(); this._dirtyKeys.set(server.id, dirty); }
|
||||
dirty.add(key);
|
||||
const existing = this._debounceTimers.get(server.id);
|
||||
if (existing) clearTimeout(existing);
|
||||
this._debounceTimers.set(server.id, setTimeout(() => {
|
||||
this._debounceTimers.delete(server.id);
|
||||
const keys = [...(this._dirtyKeys.get(server.id) ?? [])];
|
||||
this._dirtyKeys.delete(server.id);
|
||||
const target = this.guilds.get(server.id);
|
||||
if (target) {
|
||||
this.remoteUpdate(target, key).catch(e =>
|
||||
logger.error(`[Settings] debounced update error (guild ${server.id}, key "${key}"):`, e?.message)
|
||||
if (!target) return;
|
||||
for (const k of keys) {
|
||||
this.remoteUpdate(target, k).catch(e =>
|
||||
logger.error(`[Settings] debounced update error (guild ${server.id}, key "${k}"):`, e?.message)
|
||||
);
|
||||
}
|
||||
}, 80));
|
||||
@@ -529,6 +541,7 @@ export class RemoteSettingsManager extends SettingsManager {
|
||||
removeServer(id) {
|
||||
const timer = this._debounceTimers.get(id);
|
||||
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
|
||||
this._dirtyKeys?.delete(id);
|
||||
this.guilds.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,10 @@ export class LavalinkManager extends EventEmitter {
|
||||
this._client = client;
|
||||
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
|
||||
|
||||
if (["youshallnotpass", "change-me-nodelink"].includes(nodeCfg.password ?? "youshallnotpass")) {
|
||||
logger.warn("[Lavalink] NodeLink is using a well-known/placeholder password. Set a strong one in config.json (nodelink.password) and as NODELINK_PASSWORD in docker/.env.");
|
||||
}
|
||||
|
||||
this.lavalink = new LavalinkClientManager({
|
||||
nodes: [
|
||||
{
|
||||
|
||||
@@ -220,7 +220,10 @@ export class PlayerManager {
|
||||
try {
|
||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||
if (guildId && textChannelId) {
|
||||
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
||||
const announceSrv = this.settings.getServer(guildId);
|
||||
if (announceSrv && announceSrv.get("announcementChannelId") !== textChannelId) {
|
||||
announceSrv.set("announcementChannelId", textChannelId);
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||
@@ -256,7 +259,10 @@ export class PlayerManager {
|
||||
try {
|
||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||
if (cleanGuildId && textChannelId) {
|
||||
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
||||
const announceSrv = this.settings.getServer(cleanGuildId);
|
||||
if (announceSrv && announceSrv.get("announcementChannelId") !== textChannelId) {
|
||||
announceSrv.set("announcementChannelId", textChannelId);
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
const _settings = {
|
||||
/** @type {boolean} @description Whether the legacy /v4/loadstream route may be used (server-side seek, filters, MP3/AAC decode). Disabled by default: playback runs on /v4/trackstream only. */
|
||||
allowLoadstream: false,
|
||||
/** @type {boolean} @description Whether direct audio URLs typed by users may point at private/loopback/link-local addresses (LAN radio, a home Icecast...). Off by default so %play cannot be used to probe internal services. Admin-configured radio stations and the local Bilibili proxy are always trusted. */
|
||||
allowPrivateUrls: false,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -15,6 +17,8 @@ const _settings = {
|
||||
export function configureAudio(section = null) {
|
||||
const raw = section?.allowLoadstream;
|
||||
_settings.allowLoadstream = raw === true || raw === "true";
|
||||
const rawPrivate = section?.allowPrivateUrls;
|
||||
_settings.allowPrivateUrls = rawPrivate === true || rawPrivate === "true";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,4 +37,11 @@ export function isLoadstreamEnabled() {
|
||||
return _settings.allowLoadstream === true;
|
||||
}
|
||||
|
||||
export default { configureAudio, getAudioSettings, isLoadstreamEnabled };
|
||||
/**
|
||||
* @returns {boolean} Whether user-supplied direct URLs may target private/internal addresses.
|
||||
*/
|
||||
export function isPrivateUrlsAllowed() {
|
||||
return _settings.allowPrivateUrls === true;
|
||||
}
|
||||
|
||||
export default { configureAudio, getAudioSettings, isLoadstreamEnabled, isPrivateUrlsAllowed };
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Readable } from "node:stream";
|
||||
import { applyMixins } from "../../utils/mixins.mjs";
|
||||
import { isLoadstreamEnabled } from "./AudioSettings.mjs";
|
||||
import { isLoadstreamEnabled, isPrivateUrlsAllowed } from "./AudioSettings.mjs";
|
||||
import { openPublicStream } from "./SafeHttp.mjs";
|
||||
import StreamPipeline from "./StreamPipeline.mjs";
|
||||
import HttpStreams from "./HttpStreams.mjs";
|
||||
|
||||
@@ -168,15 +168,12 @@ export class FluxerAudioBridge extends EventEmitter {
|
||||
// source page.
|
||||
if (!trackInfo.encoded && trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
|
||||
const response = await fetch(trackInfo.url, {
|
||||
const { stream, req: sourceReq } = await openPublicStream(trackInfo.url, {
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
||||
redirect: "follow",
|
||||
allowPrivate: trackInfo.trusted === true || isPrivateUrlsAllowed(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
|
||||
}
|
||||
const stream = Readable.fromWeb(response.body);
|
||||
this._sourceStream = stream;
|
||||
this._sourceReq = sourceReq;
|
||||
|
||||
const routed = await this._routeByMagic(stream);
|
||||
if (routed.kind === "webm") {
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* @module src/music/audio/SafeHttp
|
||||
* @description Public-internet-only HTTP streaming for URLs that users type into `%play`.
|
||||
*
|
||||
* Direct audio links are fetched by the bot process itself, which sits next to MySQL, Redis
|
||||
* and NodeLink. Without a guard, `%play http://169.254.169.254/x.ogg` (or a public URL that
|
||||
* redirects there) makes the bot issue requests into the internal network. This module:
|
||||
* - allows only http/https,
|
||||
* - refuses loopback / private / link-local / CGNAT / multicast / reserved addresses,
|
||||
* - validates EVERY redirect hop (redirects are followed manually),
|
||||
* - validates at connect time through a custom DNS `lookup`, so a hostname that resolves to
|
||||
* a private address (or flips between lookups: DNS rebinding) is still refused,
|
||||
* - uses a fresh agent per request so a pooled socket can never bypass the check,
|
||||
* - applies connect-to-headers and idle timeouts, so a silent server cannot hang playback.
|
||||
*/
|
||||
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import dns from "node:dns";
|
||||
import net from "node:net";
|
||||
|
||||
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
|
||||
|
||||
/** Thrown when a URL (or one of its redirects / DNS answers) points at a blocked address. */
|
||||
export class BlockedAddressError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = "BlockedAddressError";
|
||||
this.code = "EBLOCKEDADDR";
|
||||
}
|
||||
}
|
||||
|
||||
function isPrivateV4(ip) {
|
||||
const [a, b, c] = ip.split(".").map(Number);
|
||||
if (a === 0) return true;
|
||||
if (a === 10) return true;
|
||||
if (a === 127) return true;
|
||||
if (a === 169 && b === 254) return true;
|
||||
if (a === 172 && b >= 16 && b <= 31) return true;
|
||||
if (a === 192 && b === 168) return true;
|
||||
if (a === 100 && b >= 64 && b <= 127) return true;
|
||||
if (a === 192 && b === 0 && (c === 0 || c === 2)) return true;
|
||||
if (a === 198 && (b === 18 || b === 19)) return true;
|
||||
if (a === 198 && b === 51 && c === 100) return true;
|
||||
if (a === 203 && b === 0 && c === 113) return true;
|
||||
if (a >= 224) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Expand an IPv6 literal (incl. "::" compression and a dotted-IPv4 tail) to 8 numeric hextets. */
|
||||
function expandV6(ip) {
|
||||
let s = ip.toLowerCase();
|
||||
const tail = s.match(/(\d{1,3}(?:\.\d{1,3}){3})$/);
|
||||
if (tail) {
|
||||
const p = tail[1].split(".").map(Number);
|
||||
s = s.slice(0, -tail[1].length) + ((p[0] << 8) | p[1]).toString(16) + ":" + ((p[2] << 8) | p[3]).toString(16);
|
||||
}
|
||||
const halves = s.split("::");
|
||||
const head = halves[0] ? halves[0].split(":") : [];
|
||||
const rest = halves.length > 1 && halves[1] ? halves[1].split(":") : [];
|
||||
const parts = halves.length > 1
|
||||
? [...head, ...Array(Math.max(0, 8 - head.length - rest.length)).fill("0"), ...rest]
|
||||
: head;
|
||||
return parts.map((h) => parseInt(h || "0", 16));
|
||||
}
|
||||
|
||||
const v4From = (hi, lo) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
|
||||
|
||||
/**
|
||||
* @param {string} input - An IP literal (IPv4/IPv6, optionally bracketed or with a %zone).
|
||||
* @returns {boolean} true when the address must NOT be reachable from a user-supplied URL.
|
||||
* Anything that is not a valid IP literal is also reported as unsafe.
|
||||
*/
|
||||
export function isPrivateAddress(input) {
|
||||
let ip = String(input ?? "").trim();
|
||||
if (ip.startsWith("[") && ip.endsWith("]")) ip = ip.slice(1, -1);
|
||||
const zone = ip.indexOf("%");
|
||||
if (zone !== -1) ip = ip.slice(0, zone);
|
||||
const family = net.isIP(ip);
|
||||
if (family === 0) return true;
|
||||
if (family === 4) return isPrivateV4(ip);
|
||||
|
||||
const h = expandV6(ip);
|
||||
if (h.length !== 8 || h.some((x) => Number.isNaN(x))) return true;
|
||||
const zeros = (from, to) => h.slice(from, to).every((x) => x === 0);
|
||||
|
||||
if (zeros(0, 8)) return true;
|
||||
if (zeros(0, 7) && h[7] === 1) return true;
|
||||
if (zeros(0, 5) && h[5] === 0xffff) return isPrivateV4(v4From(h[6], h[7]));
|
||||
if (zeros(0, 6)) return isPrivateV4(v4From(h[6], h[7]));
|
||||
if (h[0] === 0x64 && h[1] === 0xff9b && zeros(2, 6)) return isPrivateV4(v4From(h[6], h[7]));
|
||||
if (h[0] === 0x2002) return isPrivateV4(v4From(h[1], h[2]));
|
||||
if ((h[0] & 0xfe00) === 0xfc00) return true;
|
||||
if ((h[0] & 0xffc0) === 0xfe80) return true;
|
||||
if ((h[0] & 0xffc0) === 0xfec0) return true;
|
||||
if ((h[0] & 0xff00) === 0xff00) return true;
|
||||
if (h[0] === 0x2001 && h[1] === 0x0db8) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a `lookup` function for http(s).request that refuses disallowed addresses.
|
||||
* Checking the address Node is about to connect to (rather than pre-resolving) is what
|
||||
* defeats DNS-rebinding.
|
||||
* @param {(address: string) => boolean} isAllowed
|
||||
*/
|
||||
export function createSafeLookup(isAllowed) {
|
||||
return function safeLookup(hostname, options, callback) {
|
||||
if (typeof options === "function") { callback = options; options = {}; }
|
||||
options = options || {};
|
||||
dns.lookup(hostname, options, (err, address, family) => {
|
||||
if (err) return callback(err);
|
||||
const list = Array.isArray(address) ? address : [{ address, family }];
|
||||
const bad = list.find((a) => !isAllowed(a.address));
|
||||
if (bad) {
|
||||
return callback(new BlockedAddressError(
|
||||
`Refusing to connect to ${bad.address} (resolved from ${hostname}): private/internal addresses are not allowed`));
|
||||
}
|
||||
if (options.all) return callback(null, list);
|
||||
return callback(null, list[0].address, list[0].family);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function requestOnce(u, { headers, lookup, connectTimeoutMs, idleTimeoutMs }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const mod = u.protocol === "https:" ? https : http;
|
||||
let settled = false;
|
||||
let timer = null;
|
||||
const req = mod.request(u, {
|
||||
method: "GET",
|
||||
agent: false,
|
||||
lookup,
|
||||
headers: { Accept: "*/*", "Accept-Encoding": "identity", ...headers },
|
||||
}, (res) => {
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
res.setTimeout(idleTimeoutMs, () => res.destroy(new Error("Stream idle for " + idleTimeoutMs + "ms")));
|
||||
resolve({ res, req });
|
||||
});
|
||||
timer = setTimeout(() => {
|
||||
if (!settled) req.destroy(new Error("Timed out waiting for response headers (" + connectTimeoutMs + "ms)"));
|
||||
}, connectTimeoutMs);
|
||||
req.on("error", (err) => {
|
||||
clearTimeout(timer);
|
||||
if (!settled) { settled = true; reject(err); }
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a streaming GET to a user-supplied URL, public internet only.
|
||||
* @param {string} url
|
||||
* @param {object} [opts]
|
||||
* @param {object} [opts.headers] - Extra request headers.
|
||||
* @param {boolean} [opts.allowPrivate=false] - Skip the address checks (trusted sources only).
|
||||
* @param {(address: string) => boolean} [opts.addressFilter] - Custom allow-rule (overrides allowPrivate).
|
||||
* @param {number} [opts.maxRedirects=5]
|
||||
* @param {number} [opts.connectTimeoutMs=15000] - Max wait for response headers.
|
||||
* @param {number} [opts.idleTimeoutMs=30000] - A response that goes silent this long is destroyed.
|
||||
* @returns {Promise<{stream: import("node:http").IncomingMessage, req: import("node:http").ClientRequest, finalUrl: string}>}
|
||||
* @throws {BlockedAddressError} when a hop targets a blocked address.
|
||||
*/
|
||||
export async function openPublicStream(url, {
|
||||
headers = {},
|
||||
allowPrivate = false,
|
||||
addressFilter = null,
|
||||
maxRedirects = 5,
|
||||
connectTimeoutMs = 15_000,
|
||||
idleTimeoutMs = 30_000,
|
||||
} = {}) {
|
||||
const isAllowed = typeof addressFilter === "function"
|
||||
? addressFilter
|
||||
: allowPrivate ? () => true : (a) => !isPrivateAddress(a);
|
||||
const lookup = createSafeLookup(isAllowed);
|
||||
|
||||
let current = String(url);
|
||||
for (let hop = 0; hop <= maxRedirects; hop++) {
|
||||
const u = new URL(current);
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
||||
throw new Error("Blocked URL scheme: " + u.protocol);
|
||||
}
|
||||
const host = u.hostname.replace(/^\[|\]$/g, "");
|
||||
if (net.isIP(host) && !isAllowed(host)) {
|
||||
throw new BlockedAddressError(`Refusing to connect to ${host}: private/internal addresses are not allowed`);
|
||||
}
|
||||
const { res, req } = await requestOnce(u, { headers, lookup, connectTimeoutMs, idleTimeoutMs });
|
||||
if (REDIRECT_STATUS.has(res.statusCode) && res.headers.location) {
|
||||
res.resume();
|
||||
current = new URL(res.headers.location, u).toString();
|
||||
continue;
|
||||
}
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
res.resume();
|
||||
throw new Error("HTTP " + res.statusCode + " for " + url);
|
||||
}
|
||||
return { stream: res, req, finalUrl: u.toString() };
|
||||
}
|
||||
throw new Error("Too many redirects (" + maxRedirects + ")");
|
||||
}
|
||||
|
||||
export default { openPublicStream, isPrivateAddress, createSafeLookup, BlockedAddressError };
|
||||
@@ -26,6 +26,11 @@ const PCM_FRAME_SIZE = 960;
|
||||
/** @type {number} @description Opus encoding bitrate. */
|
||||
const OPUS_BITRATE = 128000;
|
||||
|
||||
/** @type {number} @description Max wait for the first bytes of a stream when sniffing its container. */
|
||||
const PEEK_TIMEOUT_MS = 15_000;
|
||||
/** @type {number} @description Max wait for an OpusHead before an Ogg stream is declared "not Ogg/Opus". */
|
||||
const OGG_HEAD_TIMEOUT_MS = 10_000;
|
||||
|
||||
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
|
||||
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
||||
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
|
||||
@@ -168,7 +173,7 @@ const StreamPipeline = {
|
||||
* @returns {Promise<Buffer>}
|
||||
* @private
|
||||
*/
|
||||
_peek(stream, n) {
|
||||
_peek(stream, n, timeoutMs = PEEK_TIMEOUT_MS) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tryRead = () => {
|
||||
const chunks = [];
|
||||
@@ -189,7 +194,9 @@ const StreamPipeline = {
|
||||
const onReadable = () => { cleanup(); tryRead(); };
|
||||
const onEnd = () => { cleanup(); tryRead(); };
|
||||
const onError = (err) => { cleanup(); reject(err); };
|
||||
let timer = null;
|
||||
const cleanup = () => {
|
||||
if (timer) { clearTimeout(timer); timer = null; }
|
||||
stream.off("readable", onReadable);
|
||||
stream.off("end", onEnd);
|
||||
stream.off("error", onError);
|
||||
@@ -197,6 +204,10 @@ const StreamPipeline = {
|
||||
stream.once("readable", onReadable);
|
||||
stream.once("end", onEnd);
|
||||
stream.once("error", onError);
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error("Timed out waiting for stream data (" + timeoutMs + "ms)"));
|
||||
}, timeoutMs);
|
||||
tryRead();
|
||||
});
|
||||
},
|
||||
@@ -248,20 +259,37 @@ const StreamPipeline = {
|
||||
* @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>}
|
||||
* @private
|
||||
*/
|
||||
async _remuxOggToWebM(oggStream) {
|
||||
async _remuxOggToWebM(oggStream, { headTimeoutMs = OGG_HEAD_TIMEOUT_MS } = {}) {
|
||||
const demuxer = new PrismOggDemuxer();
|
||||
const muxer = new WebMOpusMuxer();
|
||||
muxer.on("error", () => {});
|
||||
oggStream.on("error", (err) => demuxer.destroy(err));
|
||||
demuxer.on("error", (err) => muxer.destroy(err));
|
||||
let frameCount = 0;
|
||||
demuxer.on("data", () => { frameCount++; });
|
||||
let headTimer = null;
|
||||
const headPromise = new Promise((resolve, reject) => {
|
||||
demuxer.once("head", () => resolve());
|
||||
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
|
||||
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
|
||||
demuxer.once("end", () => reject(new Error("Ogg stream ended without an OpusHead (not Ogg/Opus)")));
|
||||
demuxer.once("close", () => reject(new Error("Ogg demuxer closed before an OpusHead was seen")));
|
||||
headTimer = setTimeout(
|
||||
() => reject(new Error("Timed out waiting for an OpusHead (" + headTimeoutMs + "ms): not Ogg/Opus or the source stalled")),
|
||||
headTimeoutMs
|
||||
);
|
||||
});
|
||||
oggStream.pipe(demuxer).pipe(muxer);
|
||||
await headPromise;
|
||||
try {
|
||||
await headPromise;
|
||||
} catch (err) {
|
||||
try { oggStream.destroy(); } catch (_) {}
|
||||
try { demuxer.destroy(); } catch (_) {}
|
||||
try { muxer.destroy(); } catch (_) {}
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(headTimer);
|
||||
}
|
||||
const wrapper = Object.create(muxer);
|
||||
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
||||
return wrapper;
|
||||
|
||||
@@ -122,6 +122,7 @@ const PlaybackMixin = {
|
||||
if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext;
|
||||
const songData = this.queue.next();
|
||||
if (!songData) {
|
||||
this._consecutiveErrors = 0;
|
||||
this.emit("stopplay");
|
||||
this.emit("queueEnd");
|
||||
|
||||
@@ -171,7 +172,6 @@ const PlaybackMixin = {
|
||||
this._paused = false;
|
||||
this._pausedAt = null;
|
||||
this._queueEndedSent = false;
|
||||
this._consecutiveErrors = 0;
|
||||
this._radioReconnects = 0;
|
||||
|
||||
if (songData.type !== "radio" || !this._radioAnnounced) {
|
||||
@@ -214,6 +214,8 @@ const PlaybackMixin = {
|
||||
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
|
||||
}
|
||||
|
||||
this._consecutiveErrors = 0;
|
||||
|
||||
if (trackOptMatch && trackOptMatch.endMs > 0) {
|
||||
const elapsedMs = Date.now() - this.startedPlaying;
|
||||
const remainingMs = trackOptMatch.endMs - elapsedMs;
|
||||
@@ -313,6 +315,7 @@ const PlaybackMixin = {
|
||||
url: bridgeUrl,
|
||||
title: songData.title,
|
||||
guildId: this._guildId,
|
||||
trusted: songData.type === "radio" || songData.type === "bilibili",
|
||||
}, {
|
||||
seekSeconds: options.seekSeconds ?? 0,
|
||||
durationMs,
|
||||
|
||||
@@ -67,7 +67,7 @@ export class Queue extends EventEmitter {
|
||||
* @returns {string} Result message indicating success or out-of-bounds error.
|
||||
*/
|
||||
remove(idx) {
|
||||
if (idx < 0 || idx >= this.data.length) return "Index out of bounds";
|
||||
if (!Number.isInteger(idx) || idx < 0 || idx >= this.data.length) return "Index out of bounds";
|
||||
const title = this.data[idx].title;
|
||||
const removed = this.data.splice(idx, 1);
|
||||
this.emit("queue", { type: "remove", data: { index: idx, old: this.data.slice(), removed, new: this.data } });
|
||||
@@ -81,8 +81,8 @@ export class Queue extends EventEmitter {
|
||||
* @returns {string} Result message indicating success or error.
|
||||
*/
|
||||
move(from, to) {
|
||||
if (from < 0 || from >= this.data.length) return "Source index out of bounds";
|
||||
if (to < 0 || to >= this.data.length) return "Target index out of bounds";
|
||||
if (!Number.isInteger(from) || from < 0 || from >= this.data.length) return "Source index out of bounds";
|
||||
if (!Number.isInteger(to) || to < 0 || to >= this.data.length) return "Target index out of bounds";
|
||||
if (from === to) return "Track is already in that position";
|
||||
const [track] = this.data.splice(from, 1);
|
||||
this.data.splice(to, 0, track);
|
||||
|
||||
@@ -34,6 +34,10 @@ export class LastFmManager {
|
||||
|
||||
this._mysqlConfig = mysqlConfig;
|
||||
this._pool = null;
|
||||
/** @private True once the tables exist (a pool without ready tables is never handed out). */
|
||||
this._poolReady = false;
|
||||
/** @private In-flight pool+table initialisation shared by concurrent callers. */
|
||||
this._poolInit = null;
|
||||
|
||||
this.botId = null;
|
||||
this._hasBotIdColumn = false;
|
||||
@@ -138,19 +142,41 @@ export class LastFmManager {
|
||||
|
||||
/** @private @async Get or create the MySQL connection pool. @returns {Promise<object>} */
|
||||
async _getPool() {
|
||||
if (this._pool) return this._pool;
|
||||
const mysql = await import("mysql2/promise");
|
||||
this._pool = mysql.createPool({
|
||||
...MYSQL_POOL_DEFAULTS,
|
||||
host: this._mysqlConfig.host,
|
||||
port: this._mysqlConfig.port ?? 3306,
|
||||
user: this._mysqlConfig.user,
|
||||
password: this._mysqlConfig.password,
|
||||
database: this._mysqlConfig.database,
|
||||
});
|
||||
attachMysqlPoolGuard(this._pool, "LastFm");
|
||||
await this._initTable();
|
||||
return this._pool;
|
||||
if (this._pool && this._poolReady) return this._pool;
|
||||
if (!this._poolInit) {
|
||||
this._poolInit = (async () => {
|
||||
if (!this._pool) {
|
||||
const mysql = await import("mysql2/promise");
|
||||
const cfg = this._mysqlConfig ?? {};
|
||||
const extra = {};
|
||||
for (const k of ["ssl", "socketPath", "charset", "timezone", "connectTimeout", "localAddress", "flags"]) {
|
||||
if (cfg[k] !== undefined) extra[k] = cfg[k];
|
||||
}
|
||||
this._pool = mysql.createPool({
|
||||
...MYSQL_POOL_DEFAULTS,
|
||||
...extra,
|
||||
host: cfg.host,
|
||||
port: cfg.port ?? 3306,
|
||||
user: cfg.user,
|
||||
password: cfg.password,
|
||||
database: cfg.database,
|
||||
});
|
||||
attachMysqlPoolGuard(this._pool, "LastFm");
|
||||
}
|
||||
try {
|
||||
await this._initTable();
|
||||
this._poolReady = true;
|
||||
} catch (err) {
|
||||
const failed = this._pool;
|
||||
this._pool = null;
|
||||
this._poolReady = false;
|
||||
try { await failed?.end(); } catch (_) {}
|
||||
throw err;
|
||||
}
|
||||
return this._pool;
|
||||
})().finally(() => { this._poolInit = null; });
|
||||
}
|
||||
return this._poolInit;
|
||||
}
|
||||
|
||||
/** @private @async Create the lastfm_users and lastfm_stats tables if they don't exist. */
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @module src/utils/Redact
|
||||
* @description Value-based secret redaction. The eval command used to redact only by property
|
||||
* NAME on objects, so `this.config.token` (a plain string) came back in clear. These helpers
|
||||
* collect the actual secret values from the config and mask them wherever they appear in text.
|
||||
*
|
||||
* This is a safety net against ACCIDENTAL leaks (dumping `this.client` into a channel), not a
|
||||
* security boundary: anyone who can run eval can transform a secret before printing it.
|
||||
*/
|
||||
|
||||
const SECRET_KEY = /token|secret|passw(or)?d|api_?key|authorization|credential|webhook|sessdata|cookie|session_?key|private_?key|key$/i;
|
||||
const URL_WITH_CREDS = /^[a-z][a-z0-9+.-]*:\/\/[^/\s:@]*:[^@\s]+@/i;
|
||||
|
||||
/**
|
||||
* Collect secret-looking string values from a config-like object.
|
||||
* @param {*} root - Usually the bot's config object.
|
||||
* @param {{minLength?: number, maxDepth?: number}} [opts]
|
||||
* @returns {string[]} Distinct secret values, longest first (so partial overlaps mask fully).
|
||||
*/
|
||||
export function collectSecrets(root, { minLength = 6, maxDepth = 8 } = {}) {
|
||||
const found = new Set();
|
||||
const seen = new WeakSet();
|
||||
const walk = (node, depth) => {
|
||||
if (depth > maxDepth || node === null || typeof node !== "object" || seen.has(node)) return;
|
||||
seen.add(node);
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (typeof value === "string") {
|
||||
if (value.length >= minLength && (SECRET_KEY.test(key) || URL_WITH_CREDS.test(value))) found.add(value);
|
||||
} else if (value && typeof value === "object") {
|
||||
walk(value, depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(root, 0);
|
||||
return [...found].sort((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace every occurrence of every secret in `text`.
|
||||
* @param {string} text
|
||||
* @param {string[]} secrets
|
||||
* @param {string} [mask="[REDACTED]"]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function redactSecrets(text, secrets, mask = "[REDACTED]") {
|
||||
let out = String(text);
|
||||
for (const s of secrets ?? []) if (s) out = out.split(s).join(mask);
|
||||
return out;
|
||||
}
|
||||
|
||||
export default { collectSecrets, redactSecrets };
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* @module src/voice/gateway/RejoinBackoff
|
||||
* @description Per-channel failure memory for 24/7 rejoin attempts.
|
||||
*
|
||||
* The 24/7 watchdog sweeps every minute and re-arms a rejoin for every saved channel that has
|
||||
* no live player. For a channel that can never be joined (the bot lost the Connect permission,
|
||||
* the channel is full or locked) that meant a join attempt - three of them, with retries - every
|
||||
* minute, forever. This keeps a small escalating cool-down per channel: after each failed attempt
|
||||
* cycle the watchdog skips the channel for 2, 4, 8, 16, 32 minutes, then once an hour. Any
|
||||
* successful join clears the entry. Event-driven rejoins (the bot was just disconnected) are
|
||||
* deliberately NOT throttled by this.
|
||||
*/
|
||||
export class RejoinBackoff {
|
||||
/**
|
||||
* @param {object} [o]
|
||||
* @param {number} [o.baseMs=120000] - Cool-down after the first failed attempt cycle (doubles each time).
|
||||
* @param {number} [o.maxMs=3600000] - Upper bound for the cool-down.
|
||||
* @param {number} [o.maxEntries=5000] - Safety cap on remembered channels (oldest evicted first).
|
||||
* @param {() => number} [o.now] - Clock (injectable for tests).
|
||||
*/
|
||||
constructor({ baseMs = 120_000, maxMs = 3_600_000, maxEntries = 5_000, now = Date.now } = {}) {
|
||||
this.baseMs = baseMs;
|
||||
this.maxMs = maxMs;
|
||||
this.maxEntries = maxEntries;
|
||||
this.now = now;
|
||||
/** @type {Map<string, {failures: number, nextAt: number}>} */
|
||||
this._entries = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a failed attempt cycle for a channel.
|
||||
* @param {string} channelId
|
||||
* @returns {{failures: number, delayMs: number}} The new failure count and the cool-down applied.
|
||||
*/
|
||||
recordFailure(channelId) {
|
||||
const key = String(channelId);
|
||||
const failures = (this._entries.get(key)?.failures ?? 0) + 1;
|
||||
const delayMs = Math.min(this.maxMs, this.baseMs * 2 ** (failures - 1));
|
||||
this._entries.delete(key);
|
||||
this._entries.set(key, { failures, nextAt: this.now() + delayMs });
|
||||
while (this._entries.size > this.maxEntries) this._entries.delete(this._entries.keys().next().value);
|
||||
return { failures, delayMs };
|
||||
}
|
||||
|
||||
/** Forget a channel (a join succeeded, or the channel is no longer relevant). */
|
||||
recordSuccess(channelId) {
|
||||
this._entries.delete(String(channelId));
|
||||
}
|
||||
|
||||
/** @returns {number} Milliseconds until the watchdog may try this channel again (0 = go ahead). */
|
||||
remainingMs(channelId) {
|
||||
const e = this._entries.get(String(channelId));
|
||||
return e ? Math.max(0, e.nextAt - this.now()) : 0;
|
||||
}
|
||||
|
||||
/** @returns {number} Consecutive failed attempt cycles recorded for the channel. */
|
||||
failures(channelId) {
|
||||
return this._entries.get(String(channelId))?.failures ?? 0;
|
||||
}
|
||||
|
||||
get size() { return this._entries.size; }
|
||||
}
|
||||
|
||||
export default RejoinBackoff;
|
||||
@@ -129,10 +129,14 @@ const RejoinManager = {
|
||||
|
||||
try {
|
||||
const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin");
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
if (player) {
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
remix.rejoinBackoff?.recordSuccess(cleanChannelId);
|
||||
} else {
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
const { failures, delayMs } = remix.rejoinBackoff?.recordFailure(cleanChannelId) ?? {};
|
||||
if (failures) {
|
||||
logger.warn(`[Rejoin] Channel ${cleanChannelId} failed ${failures} attempt cycle(s) in a row; the watchdog will wait ${Math.round(delayMs / 60_000)} min before retrying (missing Connect permission or a full channel?).`);
|
||||
}
|
||||
}
|
||||
return player;
|
||||
} finally {
|
||||
|
||||
@@ -213,6 +213,11 @@ const Watchdog247 = {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((remix.rejoinBackoff?.remainingMs(channelId) ?? 0) > 0) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof remix.schedule247Rejoin === "function") {
|
||||
remix.schedule247Rejoin(channelId, guildId);
|
||||
healed++;
|
||||
|
||||
Reference in new issue
Block a user