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

+1
View File
@@ -57,6 +57,7 @@ describe('runNotify', () => {
expect(
(await runNotify({ message: 'x' }, ENV, '/w', fake(400, 'The file must be inside the session folder'))).err
).toBe('Could not post to Discord: The file must be inside the session folder');
expect((await runNotify({ message: 'x' }, ENV, '/w', fake(429))).err).toMatch(/Too many messages/);
expect((await runNotify({ message: 'x' }, ENV, '/w', fake(500))).err).toBe('Could not post to Discord (HTTP 500)');
expect((await runNotify({ message: 'x' }, ENV, '/w', fake(0))).err).toBe('Could not post to Discord');
});
+33 -8
View File
@@ -477,6 +477,39 @@ describe('DiscordBridge', () => {
});
});
describe('sendTest', () => {
it('posts with the config it is given and leaves the live config alone', async () => {
const auth: string[] = [];
const b = bridge({}, async (_url, init) => {
auth.push(String((init.headers as Record<string, string>).Authorization));
return jsonRes({ id: 'msg' });
});
await b.reload();
expect((await b.sendTest({ ...CFG, token: 'test-token' }))?.ok).toBe(true);
// A save that landed during the test must not be undone: the live token is still the saved one.
await b.notify(MSG);
expect(auth[0]).toBe('Bot test-token');
expect(auth.slice(1).every((a) => a === `Bot ${CFG.token}`)).toBe(true);
b.stop();
});
});
it('names a thread that Discord answers without an id, instead of reporting an old result', async () => {
const b = bridge({}, async (url) => (String(url).endsWith('/threads') ? jsonRes({}) : jsonRes({ id: 'msg' })));
const r = await b.notify(MSG);
expect(r).toMatchObject({ ok: false });
b.stop();
});
it('does not rename a thread to the name it already has on first sight', async () => {
const b = bridge();
await b.notify(MSG);
posts.length = 0;
await b.sessionRenamed('s1', 'w1-app');
expect(posts).toHaveLength(0);
b.stop();
});
describe('per-tab state', () => {
const internals = (b: DiscordBridge) =>
b as unknown as { names: Map<string, string>; lastReply: Map<string, number>; fresh: Set<string> };
@@ -722,14 +755,6 @@ describe('DiscordBridge files and startup hint', () => {
b.stop();
});
it('does not hint a resumed tab, even though it was created just now', async () => {
const b = await make();
await b.sessionCreated('s6', 'resumed', t - 1000, true);
await b.sessionIdle('s6', true);
expect(sent).toHaveLength(0);
b.stop();
});
it('does not save a file for a message id that is not a snowflake, and says so', async () => {
const b = await make();
await b.onGatewayMessage(reply({ id: '../../x' }));
+1 -9
View File
@@ -92,7 +92,7 @@ describe('broadcast -> Discord tab lifecycle', () => {
it('routes created, updated and deleted by kind, reading both payload shapes', () => {
const s = server();
s.broadcast(SseEvent.SessionCreated, { session: { id: 's1', name: 'w1', createdAt: 123 } });
expect(s.discordBridge.sessionCreated).toHaveBeenCalledWith('s1', 'w1', 123, false);
expect(s.discordBridge.sessionCreated).toHaveBeenCalledWith('s1', 'w1', 123);
s.broadcast(SseEvent.SessionUpdated, { id: 's1', name: 'renamed' });
expect(s.discordBridge.sessionRenamed).toHaveBeenCalledWith('s1', 'renamed');
});
@@ -111,14 +111,6 @@ describe('broadcast -> Discord tab lifecycle', () => {
expect(s.discordBridge.sessionDeleted).toHaveBeenCalledWith('gone');
});
it('marks a resumed tab as resumed, so it is never sent the typed hint', () => {
const s = server();
s.broadcast(SseEvent.SessionCreated, { session: { id: 's9', name: 'w9', createdAt: 5, resumeSessionId: 'abc' } });
expect(s.discordBridge.sessionCreated).toHaveBeenCalledWith('s9', 'w9', 5, true);
s.broadcast(SseEvent.SessionCreated, { session: { id: 's8', name: 'w8', createdAt: 6 } });
expect(s.discordBridge.sessionCreated).toHaveBeenLastCalledWith('s8', 'w8', 6, false);
});
it('ignores an event with no session id', () => {
const s = server();
s.broadcast(SseEvent.SessionUpdated, {});
+28 -1
View File
@@ -7,7 +7,7 @@ import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync }
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createRouteTestHarness } from './_route-test-utils.js';
import { registerDiscordRoutes } from '../../src/web/routes/discord-routes.js';
import { _resetNotifyBuckets, registerDiscordRoutes } from '../../src/web/routes/discord-routes.js';
import { DiscordBridge, discordConfigPath, readDiscordConfig, type DiscordFetch } from '../../src/discord-bridge.js';
const TOKEN = 'MTA1.secret.token-value-1234567890';
@@ -37,6 +37,7 @@ async function harness(authUser?: { username: string; role: 'admin' | 'user' })
}
beforeEach(() => {
_resetNotifyBuckets();
dir = mkdtempSync(join(tmpdir(), 'discord-routes-'));
fetchImpl = vi.fn<DiscordFetch>(
async () => new Response(JSON.stringify({ id: '444444444444444444' }), { status: 200 })
@@ -174,6 +175,23 @@ describe('POST /api/sessions/:id/discord-notify', () => {
bridge.stop();
});
it('answers 429 RATE_LIMITED once a tab posts more than its share in a minute', async () => {
const { app, bridge } = await harness();
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
const codes: number[] = [];
for (let i = 0; i < 8; i++) {
codes.push(
(await app.inject({ method: 'POST', url, payload: { message: `ping ${i}`, urgent: true } })).statusCode
);
}
expect(codes.slice(0, 6)).toEqual([200, 200, 200, 200, 200, 200]);
expect(codes.slice(6)).toEqual([429, 429]);
const limited = await app.inject({ method: 'POST', url, payload: { message: 'again' } });
expect(limited.json().errorCode).toBe('RATE_LIMITED');
expect(limited.headers['retry-after']).toBe('60');
bridge.stop();
});
it('rejects an empty or oversized message', async () => {
const { app } = await harness();
const url = `/api/sessions/test-session-1/discord-notify`;
@@ -229,6 +247,15 @@ describe('discord-notify with a file', () => {
bridge.stop();
});
it('refuses to send when the session folder is not a directory it can probe', async () => {
const { app, ctx, bridge } = await ready();
(ctx.sessions.get('test-session-1') as unknown as { workingDir: string }).workingDir = join(work, 'run.log');
const res = await post(app, join(work, 'run.log'));
expect(res.statusCode).toBe(400);
expect(res.json().error).toMatch(/session folder/);
bridge.stop();
});
it('refuses a symlink that points outside the folder', async () => {
const { app, bridge } = await ready();
mkdirSync(join(work, 'sub'));