fix(discord): tolerate reply dedupe storage failures (#218, #258)

This commit is contained in:
Saqeb Akhter committed 2026-11-17 23:25:43 +04:00
1 parent e99b42c387
commit ba4a1c16e2
5 files changed
+199 -2

No files matched your search

+4
View File
@@ -27,6 +27,7 @@ import { join } from 'node:path';
import { probePathKind } from './utils/bounded-path-probe.js';
import { DISCORD_RECEIVED_DIR } from './web/paste-image-gc.js';
import WebSocket from 'ws';
import { DiscordReplyDedupe } from './discord-reply-dedupe.js';
import { WEBHOOK_SCOPES, type WebhookUrgency } from './types/push.js';
import {
DISCORD_ON_DELETE,
@@ -824,6 +825,7 @@ export interface DiscordBridgeDeps {
}
export class DiscordBridge {
private readonly replies: DiscordReplyDedupe;
private cfg: DiscordConfig = { ...DEFAULT_DISCORD_CONFIG };
private threads: Record<string, string> = {};
private loaded = false;
@@ -857,6 +859,7 @@ export class DiscordBridge {
constructor(private readonly deps: DiscordBridgeDeps) {
this.now = deps.now ?? Date.now;
this.replies = new DiscordReplyDedupe(deps.configDir, this.now);
this.api = new DiscordApi(() => this.cfg.token, deps.fetchImpl, deps.sleep);
}
@@ -1312,6 +1315,7 @@ export class DiscordBridge {
await this.say(m.channel_id, 'The agent in that tab has exited, so nothing was typed.');
return;
}
if (!(await this.replies.claim(m.guild_id, m.channel_id, m.id))) return;
this.lastReply.set(sessionId, t);
const saved = await this.saveAttachments(sessionId, m);
const text = sanitiseReply(m.content ?? '', saved.paths);
+74
View File
@@ -0,0 +1,74 @@
/** Best-effort replay protection. A metadata-store failure must never block a person's reply. */
import fs from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
const LIMIT = 2048;
const RETENTION_MS = 7 * 24 * 60 * 60_000;
export class DiscordReplyDedupe {
private seen = new Map<string, number>();
private loaded = false;
private warned = false;
private chain: Promise<unknown> = Promise.resolve();
constructor(
private readonly dir: string,
private readonly now: () => number = Date.now,
private readonly warn: () => void = () =>
console.warn('Discord reply metadata unavailable; using in-memory deduplication')
) {}
claim(guild: string, channel: string, message: string): Promise<boolean> {
const run = this.chain.then(() => this.take(guild, channel, message));
this.chain = run.catch(() => undefined);
return run;
}
private async take(guild: string, channel: string, message: string): Promise<boolean> {
// Restored legacy configurations and malformed gateway IDs must not poison the store.
if (![guild, channel, message].every((id) => /^\d{15,25}$/.test(id))) return true;
const path = join(this.dir, 'discord-reply-dedupe.json');
const cutoff = this.now() - RETENTION_MS;
try {
if (!this.loaded) {
try {
const st = await fs.lstat(path);
if (!st.isFile() || st.isSymbolicLink() || st.size > 512 * 1024) throw new Error('Unsafe metadata');
const rows: unknown = JSON.parse(await fs.readFile(path, 'utf8'));
if (!Array.isArray(rows) || rows.length > LIMIT) throw new Error('Invalid metadata');
const recovered = new Map<string, number>();
for (const row of rows) {
if (!Array.isArray(row) || !/^\d{15,25}:\d{15,25}:\d{15,25}$/.test(row[0]) || !Number.isFinite(row[1]))
throw new Error('Invalid metadata');
if (row[1] >= cutoff) recovered.set(row[0], row[1]);
}
for (const [key, at] of recovered) if (!this.seen.has(key)) this.seen.set(key, at);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
}
this.loaded = true;
}
} catch {
this.report(); // Retry the read on the next reply; never memoize a failed load.
}
for (const [key, at] of this.seen) if (at < cutoff) this.seen.delete(key);
const key = `${guild}:${channel}:${message}`;
if (this.seen.has(key)) return false;
this.seen.set(key, this.now()); // Before awaiting IO or typing, including during an outage.
while (this.seen.size > LIMIT) this.seen.delete(this.seen.keys().next().value!);
if (!this.loaded) return true; // Do not overwrite a journal we could not read.
const tmp = `${path}.${randomUUID()}.tmp`;
try {
await fs.mkdir(this.dir, { recursive: true });
await fs.writeFile(tmp, JSON.stringify([...this.seen]), { mode: 0o600, flag: 'wx' });
await fs.rename(tmp, path);
this.warned = false;
} catch {
this.report();
} finally {
await fs.rm(tmp, { force: true }).catch(() => undefined);
}
return true;
}
private report(): void {
if (!this.warned) this.warn();
this.warned = true;
}
}