Merge #832: a replayed Discord reply is typed once, and a store failure never costs a reply

Each allowed Discord reply is claimed by its message id in a small private store (discord-reply-dedupe.json, 0600) before the rate-limit and exited-agent checks; when the store fails the bridge falls back to memory and still types the reply.
This commit is contained in:
Codeman maintainer committed 2026-11-20 04:05:22 +01:00
commit a9ed3f55c3
7 files changed
+313 -6

No files matched your search

+8 -1
View File
@@ -4,7 +4,10 @@
* Split like webhook-notify.ts, so the parts that matter are testable without a network:
* - pure: `sanitiseReply`, `threadNameFor`, `buildPost`, `discordConfigProblem`, `maskToken`
* - store: `~/.codeman/discord.json` (bot token, 0600 via tmp+rename) and
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret)
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret) and
* `~/.codeman/discord-reply-dedupe.json` (bounded reply IDs/timestamps, private).
* Allowed replies are claimed before attachments or typing; store failures never cost a reply.
* An unreadable file is never overwritten; invalid readable ID metadata can heal.
* - IO: `DiscordApi` (REST, injected fetch), `DiscordGateway` (inbound WebSocket, injected
* socket factory) and `DiscordBridge` (the rules that tie them to sessions)
*
@@ -27,6 +30,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 +828,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 +862,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);
}
@@ -1301,6 +1307,7 @@ export class DiscordBridge {
if (!this.cfg.allowedUserIds.includes(m.author?.id)) return;
const sessionId = Object.keys(this.threads).find((k) => this.threads[k] === m.channel_id);
if (!sessionId) return;
if (!(await this.replies.claim(m.guild_id, m.channel_id, m.id))) return;
const t = this.now();
const prev = this.lastReply.get(sessionId);
if (prev !== undefined && t - prev < REPLY_MIN_INTERVAL_MS) {
+91
View File
@@ -0,0 +1,91 @@
/** @fileoverview 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 dirty = 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 (discord-reply-dedupe.json); 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;
if (!this.loaded) {
let contentRead = false;
try {
const st = await fs.lstat(path);
if (!st.isFile() || st.isSymbolicLink()) throw Object.assign(new Error('Unsafe metadata'), { code: 'EINVAL' });
if (st.size > 512 * 1024) {
contentRead = true; // A known oversized regular file is invalid metadata, not an IO failure.
throw new Error('Oversized metadata');
}
const text = await fs.readFile(path, 'utf8');
contentRead = true;
const rows: unknown = JSON.parse(text);
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]);
}
// Older disk rows precede newer claims made while reads were unavailable.
this.seen = new Map([...recovered, ...this.seen]);
this.loaded = true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') this.loaded = true;
else {
this.report();
// Invalid content is recoverable ID-only metadata; unreadable/unsafe files stay untouched.
if (contentRead && !(err as NodeJS.ErrnoException).code) {
this.loaded = true;
this.dirty = true;
}
}
}
}
for (const [key, at] of this.seen) if (at < cutoff) this.seen.delete(key);
const key = `${guild}:${channel}:${message}`;
const fresh = !this.seen.has(key);
if (fresh) {
this.seen.set(key, this.now());
this.dirty = true;
} // 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 || !this.dirty) return fresh; // 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;
this.dirty = false;
} catch {
this.report();
} finally {
await fs.rm(tmp, { force: true }).catch(() => undefined);
}
return fresh;
}
private report(): void {
if (!this.warned) this.warn();
this.warned = true;
}
}