From 0db9b55961f94a70d1c15aaf533384523c0c6678 Mon Sep 17 00:00:00 2001 From: Devvyn <22340871+opticon454@users.noreply.github.com> Date: Fri, 30 Oct 2026 03:47:25 +0800 Subject: [PATCH] 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 --- CLAUDE.md | 2 +- docs/api-reference.md | 2 +- docs/discord-bridge.md | 4 +-- docs/wiki/Discord-Bridge.md | 2 +- src/cli-notify.ts | 2 ++ src/discord-bridge.ts | 29 ++++++++++----------- src/web/public/index.html | 2 +- src/web/routes/discord-routes.ts | 36 ++++++++++++++++++++++++++ src/web/server.ts | 7 +++-- test/cli-notify.test.ts | 1 + test/discord-bridge.test.ts | 41 ++++++++++++++++++++++++------ test/discord-push-glue.test.ts | 10 +------- test/routes/discord-routes.test.ts | 29 ++++++++++++++++++++- 13 files changed, 123 insertions(+), 44 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 505d511b..b47e846a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -131,7 +131,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Agent CLI (`codeman agent …`, `src/cli-agent.ts`)**: the command-line client for the wait primitives and the session verbs, for agents the skill does not reach (pi, shell, no `jq`; `seedAgentSessionPreamble` covers every local session whose CLI takes the skill, `capabilities.agentSkillDir`; every pane still exports `CODEMAN_MUX`/`CODEMAN_SESSION_ID`/`CODEMAN_API_URL`). It is an HTTP CLIENT: inspection and guarded stage/submit use the ownership-checked `agent-session-routes.ts` module (experimental, behind `agentCoordinationEnabled`, SYNCED, default OFF: all three routes answer `403 FORBIDDEN` naming it while off, and the CLI shows that verbatim); the other verbs reuse existing routes, with no second transport (the plan's "Socket API" non-goal stands), every call carries `X-Codeman-Parent-Session`, only `spawn`'s quick-start carries `X-Codeman-Agent-Origin` (pinned in test/cli-agent.test.ts), while `spawn` without a case (cwd or `--working-dir`) is `POST /api/v1/sessions` plus `/interactive` or `/shell` without that header, so no agent-case marker, and refuses (exit 4, before any request) an empty `--working-dir` and a bare spawn from a HOME cwd, since it always sends an explicit `workingDir` and the server's no-`workingDir` hooks skip cannot apply (test/cli-agent-project-spawn.test.ts), auth (`src/codeman-credentials.ts`, shared with `codeman attach` and the TUI) from `CODEMAN_PASSWORD` or the data dir's `.env` (the same reader `codeman attach` uses — `readCodemanEnvFile`). Verbs return exit codes (`0` ok / `1` error / `2` timeout / `3` exited / `4` refused) instead of calling `process.exit`, so `test/cli-agent.test.ts` drives every verb against a recording fake transport plus the real `httpRequest` against a local server. ⚠️ Three guards live in code, not prose, and the tests pin them: refuse without `CODEMAN_MUX=1`+`CODEMAN_API_URL` (never guess a URL); `send` transmits printable text + `\r` only (`inputRefusal`: any byte < 0x20 or DEL refuses BEFORE the transport — opencode's `Ctrl+C` is `app_exit`), ESC exists solely as `interrupt` with no `\r`; `rm` fails closed (`deleteRefusal`: empty id, self shorter than 8, prefix match in EITHER direction, re-checked on the resolved id). ⚠️ The routes accept FULL ids only — an 8-char prefix is a 404 (measured live) — while `ls` prints prefixes, so `resolveSessionId` maps a short id through `GET /api/v1/sessions` and refuses an ambiguous one. It also refuses any id under 8 characters (exit 4, on every verb, before any request), the same floor as the server's `PARENT_SESSION_ID_MIN_PREFIX`, so `rm 9` can never pick an arbitrary session. ⚠️ A 400 for `--until stop` on a hook-less mode is passed through verbatim, never papered over: the marker path is the answer there. `spawn` on a readiness timeout exits 2 and LEAVES the session for inspection (the skill's `spawn_worker` deletes it; the CLI's caller is often a human); its stdout is the id ALONE (prose on stderr) so `SID=$(…)` works. ⚠️ Two server answers that look like success and are not: `delivered:false` without `duplicate` (the bytes went into a dead pane — the field exists so a client says "restart" instead of "wait longer") and `wait.ended:true, signal:null` (the worker died during a `stop`/`idle` wait: the registry satisfies only waiters that listed `exit`, then cancels the rest) — both exit 3, checked BEFORE the happy paths in `waitExitCode`. → README "`codeman agent`", `docs/api-reference.md` -**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token and is never returned; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); the alert tail is the RENDERED tmux screen (`screenTail`), never the raw stream, which a full-screen UI repaints in place. Inbound replies are typed through `session.writeViaMux`. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter, capped and rate limited; posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) and, only with the separate `typedHint` setting (default OFF), is typed once as a first message to brand-new external CLI tabs on their first idle (`sessionIdle`; never a shell, a restored tab, a resumed one, or a remote (ssh) or Docker tab, which have no `codeman` on their PATH). `codeman notify "" [--urgent] [--file ]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md` +**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token and is never returned; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); the alert tail is the RENDERED tmux screen (`screenTail`), never the raw stream, which a full-screen UI repaints in place. Inbound replies are typed through `session.writeViaMux`. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter, capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) and, only with the separate `typedHint` setting (default OFF), is typed once as a first message to brand-new external CLI tabs on their first idle (`sessionIdle`; never a shell, a restored tab, or a remote (ssh) or Docker tab, which have no `codeman` on their PATH). `codeman notify "" [--urgent] [--file ]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md` **MCP server (`codeman mcp`, `src/mcp-server.ts`)**: a Model Context Protocol server on stdio for any MCP client, a CLIENT of the HTTP API like `codeman agent` (reuses its `httpRequest`, `inputRefusal`, `buildSendBody`; the MCP server adds no routes). Seven tools: `list_sessions`, `start_session`, `send_prompt`, `wait_for_session`, `read_output`, `interrupt_session`, `delete_session`. ⚠️ Dual-era: answers the legacy `initialize` handshake (2024-11-05 to 2025-11-25) AND the 2026-07-28 revision (per-request `_meta` with `protocolVersion` + `clientCapabilities`, `server/discover`, `resultType: "complete"` on every modern result); a modern `tools/list`/`server/discover` MUST carry `ttlMs` + `cacheScope` (Claude Code 2.1.296 drops every tool without them: measured). ⚠️ stdout is protocol only; logs go to stderr. ⚠️ The URL comes from `--url`/`CODEMAN_API_URL`, never a guess, and unconfigured it still lists tools (registries introspect) while every call answers how to configure it. ⚠️ Prompt/interrupt/delete only sessions the PROCESS started (in-memory allowlist, so a restart fails closed) or, inside a pane, the calling session's own children, unless `--allow-any-session`; never its own session. ⚠️ `read_output` returns text ONLY, no `structuredContent` (a client that prefers it showed the model metadata instead of the output: measured). Waits default 45 s (Codex's MCP tool timeout is 60 s). Registry manifest `config/mcp-registry/server.json` (`mcpName` in package.json, version kept by `scripts/sync-plugin.mjs`). Tests: `test/mcp-server.test.ts`. diff --git a/docs/api-reference.md b/docs/api-reference.md index 9216522a..52f2929e 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1495,7 +1495,7 @@ One thread per tab in a private Discord channel, alerts out and replies typed ba | `GET` | `/api/discord` | none | Config without the token, plus `hasToken`, `tokenMasked`, `gateway` (`off` \| `connecting` \| `connected` \| `error`), `gatewayError` and `lastResult`. | | `PUT` | `/api/discord` | `{ enabled?, token?, guildId?, parentChannelId?, allowedUserIds?, threadCreation?, onSessionDelete?, pingMode?, scope?, startupHint?, typedHint? }` (strict) | `threadCreation`: `lazy` \| `onSessionStart`. `onSessionDelete`: `keep` \| `archive` \| `delete`. `pingMode`: `off` \| `critical` \| `all`. `scope`: `attention` \| `all`. An absent `token` keeps the saved one; `""` clears it. `400` for a non-numeric id or enabling without a token, guild, channel and at least one allowed user. | | `POST` | `/api/discord/test` | none | Posts one message to the parent channel with the saved config, even while disabled. `200` with `data.ok`; `400` if no token or channel is saved. | -| `POST` | `/api/sessions/:id/discord-notify` | `{ message, urgent?, file? }` (strict, message 1 to 1500 characters) | A CLI asks for the user: posts into that tab's thread, pinging when `urgent`. `file` is an absolute path inside the tab's working folder (real path, regular file, at most 8 MB, local sessions only) uploaded with the post; `400` otherwise. `409` while the bridge is disabled. The `codeman notify "message" [--urgent] [--file path]` command wraps this route. | +| `POST` | `/api/sessions/:id/discord-notify` | `{ message, urgent?, file? }` (strict, message 1 to 1500 characters) | A CLI asks for the user: posts into that tab's thread, pinging when `urgent`. `file` is an absolute path inside the tab's working folder (real path, regular file, at most 8 MB, local sessions only) uploaded with the post; `400` otherwise. `409` while the bridge is disabled, `429` past 6 posts a minute per tab. The `codeman notify "message" [--urgent] [--file path]` command wraps this route. | Only replies from `allowedUserIds`, in `guildId`, inside a thread the bridge created are typed into a session, as one printable line plus Enter, at most one per second per tab. Attached files are saved under `.codeman-discord/` in the tab's folder and their paths appended to that line (see [discord-bridge.md](discord-bridge.md)). diff --git a/docs/discord-bridge.md b/docs/discord-bridge.md index f257e0a2..5e29c3cc 100644 --- a/docs/discord-bridge.md +++ b/docs/discord-bridge.md @@ -10,7 +10,7 @@ Codeman can post to a private Discord server when a session needs you, give ever - Posts when a session asks for permission, asks a question, goes idle, stops or errors. - Creates one thread per tab in a single parent channel, so a reply always reaches exactly one session. - Types your reply into that session as a single line followed by Enter. -- Lets a CLI post a deliberate message (for example "press the reset button on the case") with the `codeman notify` command, which calls `POST /api/sessions/:id/discord-notify`. +- Lets a CLI post a deliberate message (for example "press the reset button on the case") with the `codeman notify` command, which calls `POST /api/sessions/:id/discord-notify`. Each tab may post 6 a minute; past that the command says "too many messages", so a looping agent cannot ping your phone without end. - Saves files you attach in a thread into that tab's working folder and tells the CLI the path. A CLI can send a file back with `codeman notify "message" --file `. - Tells each CLI about `codeman notify` (see [Telling the CLIs](#telling-the-clis)). @@ -102,7 +102,7 @@ In the Discord mobile app set the server to **All Messages**. Discord's own push A CLI only posts deliberately if it knows it can. While the bridge is on: - **Claude** (`startupHint`, on by default) is launched with `--append-system-prompt`, so nothing shows in the conversation. -- **Every other CLI** is sent nothing unless you turn on `typedHint` (off by default: it costs one model turn per tab, and for a spawned worker or a scheduled run it arrives together with the first real prompt). With it on, the same text is sent once, as a message, the first time a brand-new tab becomes idle. Tabs that are restored when Codeman starts, resumed tabs, shell tabs, and remote (ssh) and Docker tabs (which have no `codeman` command) are never sent it. +- **Every other CLI** is sent nothing unless you turn on `typedHint` (off by default: it costs one model turn per tab, and for a spawned worker or a scheduled run it arrives together with the first real prompt). With it on, the same text is sent once, as a message, the first time a brand-new tab becomes idle. Tabs that are restored when Codeman starts, shell tabs, and remote (ssh) and Docker tabs (which have no `codeman` command) are never sent it. The text explains `codeman notify "message" --urgent`. `codeman` is already on the PATH of every session and reads `CODEMAN_SESSION_ID` and `CODEMAN_API_URL`, so no other setup is needed. Without a bridge it prints that the bridge is off and exits cleanly. Tabs started before the bridge was enabled are not told; use the skill or `CLAUDE.md` for those. diff --git a/docs/wiki/Discord-Bridge.md b/docs/wiki/Discord-Bridge.md index 2e5c94ce..79ff7001 100644 --- a/docs/wiki/Discord-Bridge.md +++ b/docs/wiki/Discord-Bridge.md @@ -56,7 +56,7 @@ An agent only posts deliberately if it knows it can: - **Claude** is launched with the instruction as part of its system prompt (**Tell Claude how to reach you**, on by default), so nothing shows in the chat. - **Every other CLI** is told only if you turn on **Also tell other CLIs, as a message** (off by default: it costs one model turn per tab, and for a spawned worker or a scheduled run it arrives with the first real prompt). Then the same text is sent once, as a message, the first time a brand-new tab goes idle. - Restored tabs, resumed tabs, shell tabs, and remote (ssh) and Docker tabs (which have no `codeman` command) are never sent it. + Restored tabs, shell tabs, and remote (ssh) and Docker tabs (which have no `codeman` command) are never sent it. Tabs that were already open when you turned the bridge on are not told. The alerts still reach Discord for them; only the agent-initiated `codeman notify` habit is missing. diff --git a/src/cli-notify.ts b/src/cli-notify.ts index 957e0bc1..d14f102f 100644 --- a/src/cli-notify.ts +++ b/src/cli-notify.ts @@ -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})` : ''}` }; } diff --git a/src/discord-bridge.ts b/src/discord-bridge.ts index 4ee46016..c6e65268 100644 --- a/src/discord-bridge.ts +++ b/src/discord-bridge.ts @@ -682,7 +682,7 @@ export class DiscordBridge { return this.gateway?.lastError ?? null; } - private async ensureLoaded(): Promise { + async ensureLoaded(): Promise { 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 { - 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 { + async sessionCreated(sessionId: string, name: string | undefined, createdAt?: number): Promise { 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 { - 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); diff --git a/src/web/public/index.html b/src/web/public/index.html index 5a00822d..fee13f87 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -3296,7 +3296,7 @@
Also tell other CLIs, as a first message - 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. + 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.
diff --git a/src/web/routes/discord-routes.ts b/src/web/routes/discord-routes.ts index 96b62e4e..42b63a7a 100644 --- a/src/web/routes/discord-routes.ts +++ b/src/web/routes/discord-routes.ts @@ -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(); + +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); diff --git a/src/web/server.ts b/src/web/server.ts index 42ea4967..8b913e3d 100644 --- a/src/web/server.ts +++ b/src/web/server.ts @@ -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); diff --git a/test/cli-notify.test.ts b/test/cli-notify.test.ts index b6b7f7d7..fa20caee 100644 --- a/test/cli-notify.test.ts +++ b/test/cli-notify.test.ts @@ -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'); }); diff --git a/test/discord-bridge.test.ts b/test/discord-bridge.test.ts index 25eb0879..c9a577c9 100644 --- a/test/discord-bridge.test.ts +++ b/test/discord-bridge.test.ts @@ -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).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; lastReply: Map; fresh: Set }; @@ -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' })); diff --git a/test/discord-push-glue.test.ts b/test/discord-push-glue.test.ts index 74220a84..96d1e9c9 100644 --- a/test/discord-push-glue.test.ts +++ b/test/discord-push-glue.test.ts @@ -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, {}); diff --git a/test/routes/discord-routes.test.ts b/test/routes/discord-routes.test.ts index c4c33ff7..052ed50a 100644 --- a/test/routes/discord-routes.test.ts +++ b/test/routes/discord-routes.test.ts @@ -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( 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'));