fix(discord): rate limit discord-notify, bound the folder probe, stop sendTest swapping the live config

- discord-notify: per-session token bucket (6 a minute), 429 RATE_LIMITED, plain line from codeman notify
- fileProblem probes the working folder with the bounded probe before realpath
- sendTest uses its own DiscordApi and leaves this.cfg alone
- drop the resumed-tab check from the typed hint (only Claude's field was read)
- first sessionRenamed per session records the name without a PATCH
- boot goes through ensureLoaded, so one gateway starts
- a thread created without an id reports the failure
This commit is contained in:
Devvyn committed 2026-10-30 03:47:25 +08:00
1 parent 2d4036cf1e
commit 0db9b55961
13 files changed
+123 -44

No files matched your search

+2
View File
@@ -99,5 +99,7 @@ export async function runNotify(
if (status >= 200 && status < 300) return { code: 0, out: 'Posted to Discord' };
// The bridge being off is not a failure: the caller just says it in the terminal.
if (status === 409) return { code: 0, out: 'The Discord bridge is off. Say it in the terminal instead.' };
if (status === 429)
return { code: 1, err: 'Too many messages to Discord from this tab. Wait a minute, then send one.' };
return { code: 1, err: `Could not post to Discord${error ? `: ${error}` : status ? ` (HTTP ${status})` : ''}` };
}
+13 -16
View File
@@ -682,7 +682,7 @@ export class DiscordBridge {
return this.gateway?.lastError ?? null;
}
private async ensureLoaded(): Promise<void> {
async ensureLoaded(): Promise<void> {
if (this.loaded) return;
this.firstLoad ??= this.reload();
await this.firstLoad;
@@ -756,7 +756,10 @@ export class DiscordBridge {
const p = (async () => {
try {
const t = await this.api.createThread(this.cfg.parentChannelId, threadNameFor(name, sessionId));
if (!t?.id) return null;
if (!t?.id) {
this.last = this.fail(new Error('Discord did not return a thread'));
return null;
}
this.threads[sessionId] = t.id;
await this.persistThreads();
return t.id;
@@ -821,10 +824,10 @@ export class DiscordBridge {
/** A deliberate test send to the parent channel: bypasses `enabled`, scope and dedupe. */
async sendTest(cfg: DiscordConfig, host?: string): Promise<DiscordResult> {
const saved = this.cfg;
this.cfg = cfg;
// Its own client: swapping this.cfg would undo a save that lands while the post is in flight.
const api = new DiscordApi(() => cfg.token, this.deps.fetchImpl, this.deps.sleep);
try {
await this.api.post(
await api.post(
cfg.parentChannelId,
buildPost(
{
@@ -840,22 +843,14 @@ export class DiscordBridge {
return (this.last = { ok: true, at: this.now() });
} catch (err) {
return (this.last = this.fail(err));
} finally {
this.cfg = saved;
}
}
/** Session tab created: make its thread now when `threadCreation` is `onSessionStart`. */
async sessionCreated(
sessionId: string,
name: string | undefined,
createdAt?: number,
resumed = false
): Promise<void> {
async sessionCreated(sessionId: string, name: string | undefined, createdAt?: number): Promise<void> {
await this.ensureLoaded();
// Only a tab made just now: the same event also fires for sessions restored at server start.
// A resumed tab is created now too, but its conversation is not new, so it is never hinted.
if (!resumed && createdAt !== undefined && this.now() - createdAt < 60_000) this.fresh.add(sessionId);
if (createdAt !== undefined && this.now() - createdAt < 60_000) this.fresh.add(sessionId);
if (!this.cfg.enabled || this.cfg.threadCreation !== 'onSessionStart') return;
await this.threadFor(sessionId, name);
}
@@ -873,8 +868,10 @@ export class DiscordBridge {
}
async sessionRenamed(sessionId: string, name: string | undefined): Promise<void> {
if (this.names.get(sessionId) === (name ?? '')) return;
const seen = this.names.get(sessionId);
this.names.set(sessionId, name ?? '');
// First sight only records the name: the thread was made with it, so a PATCH would spend a rename for nothing.
if (seen === undefined || seen === (name ?? '')) return;
const thread = this.threads[sessionId];
if (!thread || !this.cfg.enabled) return;
await this.api.rename(thread, threadNameFor(name, sessionId)).catch(() => undefined);
+1 -1
View File
@@ -3296,7 +3296,7 @@
<div class="set-row">
<div class="set-row-text">
<span class="set-row-label">Also tell other CLIs, as a first message</span>
<span class="set-row-desc">Sends the same note once as a message to a brand-new Codex, OpenCode or similar tab when it first becomes idle. Costs one model turn per tab, and for a spawned worker or a scheduled run it arrives with the first real prompt. Never sent to shell, restored, resumed, remote or Docker tabs. Off by default.</span>
<span class="set-row-desc">Sends the same note once as a message to a brand-new Codex, OpenCode or similar tab when it first becomes idle. Costs one model turn per tab, and for a spawned worker or a scheduled run it arrives with the first real prompt. Never sent to shell, restored, remote or Docker tabs. Off by default.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="discordTypedHint"><span class="slider"></span></label>
</div>
+36
View File
@@ -18,6 +18,7 @@ import { ApiErrorCode, createErrorResponse, getErrorMessage, type ApiResponse }
import { findSessionOrFail, isAdmin, parseBody } from '../route-helpers.js';
import type { SessionPort } from '../ports/session-port.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { describeUnknownPath, probePathKind } from '../../utils/bounded-path-probe.js';
import { DiscordNotifySchema, DiscordUpdateSchema } from '../schemas.js';
import {
discordConfigProblem,
@@ -56,6 +57,29 @@ function resolveSessionId(ctx: SessionPort, id: string): string {
return hits.length === 1 ? hits[0] : id;
}
// A loop or a prompt-injected agent must not ping the phones until Discord answers 429, nor hold 8 MB
// uploads in memory without bound. Per session, refilled continuously (the same shape as paste-image's).
const NOTIFY_PER_MINUTE = 6;
const notifyBuckets = new Map<string, { tokens: number; at: number }>();
function consumeNotifyToken(sessionId: string, now: number = Date.now()): boolean {
if (notifyBuckets.size > 1000) {
for (const [k, b] of notifyBuckets) if (now - b.at > 3_600_000) notifyBuckets.delete(k);
}
const b = notifyBuckets.get(sessionId) ?? { tokens: NOTIFY_PER_MINUTE, at: now };
b.tokens = Math.min(NOTIFY_PER_MINUTE, b.tokens + ((now - b.at) * NOTIFY_PER_MINUTE) / 60_000);
b.at = now;
notifyBuckets.set(sessionId, b);
if (b.tokens < 1) return false;
b.tokens -= 1;
return true;
}
/** Test hook: forget every bucket between runs. */
export function _resetNotifyBuckets(): void {
notifyBuckets.clear();
}
/**
* A file a session may send: a regular file, at most MAX_FILE_BYTES, whose REAL path (symlinks
* followed) lies inside the session's working folder. Anything else is refused, so a CLI cannot be
@@ -68,6 +92,10 @@ async function fileProblem(
): Promise<{ name: string; data: Uint8Array } | string> {
if (remote) return 'Files can only be sent from a local session';
if (!isAbsolute(file)) return 'The file path must be absolute';
// Bounded first: realpath on a dead mount would hang the request.
if ((await probePathKind(workingDir, { pastCap: true })) !== 'directory') {
return describeUnknownPath('The session folder', workingDir, { pastCap: true });
}
try {
const [root, real] = await Promise.all([realpath(workingDir), realpath(file)]);
const rel = relative(root, real);
@@ -151,6 +179,14 @@ export function registerDiscordRoutes(app: FastifyInstance, deps: DiscordRouteDe
const id = resolveSessionId(deps.ctx, rawId);
const { message, urgent, file } = parseBody(DiscordNotifySchema, req.body, 'Invalid Discord message');
const session = findSessionOrFail(deps.ctx, id, req);
if (!consumeNotifyToken(session.id)) {
reply.code(429);
reply.header('Retry-After', '60');
return createErrorResponse(
ApiErrorCode.RATE_LIMITED,
`Too many messages (${NOTIFY_PER_MINUTE} per minute per session)`
);
}
let upload: { name: string; data: Uint8Array } | undefined;
if (file !== undefined) {
const problem = await fileProblem(session.workingDir, !!session.remote, file);
+3 -4
View File
@@ -1356,7 +1356,7 @@ export class WebServer extends EventEmitter {
ctx,
hostTitle: () => this.windowTitle,
});
if (!this.testMode) void this.discordBridge.reload().catch(() => undefined);
if (!this.testMode) void this.discordBridge.ensureLoaded().catch(() => undefined);
registerDoctorRoutes(this.app);
registerCustomModelRoutes(this.app);
registerCliRegistryRoutes(this.app);
@@ -2754,8 +2754,7 @@ export class WebServer extends EventEmitter {
id?: string;
name?: string;
createdAt?: number;
resumeSessionId?: string;
session?: { id?: string; name?: string; createdAt?: number; resumeSessionId?: string };
session?: { id?: string; name?: string; createdAt?: number };
};
const s = d.session ?? d;
if (!s.id) return;
@@ -2766,7 +2765,7 @@ export class WebServer extends EventEmitter {
this.discordBridge.sessionIdle(id, this.isHintableSession(id))
: event === SseEvent.SessionCreated
? this.discordBridge
.sessionCreated(id, s.name, s.createdAt, !!s.resumeSessionId)
.sessionCreated(id, s.name, s.createdAt)
.then(() => this.discordBridge.sessionRenamed(id, s.name))
: this.discordBridge.sessionRenamed(id, s.name);
void run.catch(() => undefined);