mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-20 13:09:33 +01:00
This commit is contained in:
1 parent
ba4a1c16e2
commit
7343274d5f
5 files changed
+105
-26
No files matched your search
+38
-24
@@ -1,4 +1,4 @@
|
||||
/** Best-effort replay protection. A metadata-store failure must never block a person's reply. */
|
||||
/** @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';
|
||||
@@ -8,13 +8,14 @@ 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; using in-memory deduplication')
|
||||
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));
|
||||
@@ -26,46 +27,59 @@ export class DiscordReplyDedupe {
|
||||
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;
|
||||
if (!this.loaded) {
|
||||
let contentRead = false;
|
||||
try {
|
||||
const st = await fs.lstat(path);
|
||||
if (!st.isFile() || st.isSymbolicLink() || st.size > 512 * 1024)
|
||||
throw Object.assign(new Error('Unsafe metadata'), { code: 'EINVAL' });
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
} 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.
|
||||
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) return true; // Do not overwrite a journal we could not read.
|
||||
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 true;
|
||||
return fresh;
|
||||
}
|
||||
private report(): void {
|
||||
if (!this.warned) this.warn();
|
||||
|
||||
Reference in new issue
Block a user