Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(presence): bound untrusted input before spreading it, cap the WS frame size
enes8795c54eff0c
diff --git a/src/server/ws.test.ts b/src/server/ws.test.tsindex 92f0f9732..63d2f7ba8 100644--- a/src/server/ws.test.ts+++ b/src/server/ws.test.ts@@ -6,7 +6,7 @@ import path from 'path'import WebSocket from 'ws'import { Auth } from './auth'import { ServerPlatform } from './platform-server'-import { attachWsServer } from './ws'+import { attachWsServer, WS_MAX_PAYLOAD } from './ws'import { SESSION_COOKIE } from './http'import { initPlatform, resetPlatformForTests } from '../core/platform'import { presenceHub } from '../core/presence/hub'@@ -159,6 +159,24 @@ describe('ws endpoint', () => {ws.close()})+ it('refuses an oversized frame instead of buffering it (maxPayload), and never dispatches it', async () => {+ // Without an explicit maxPayload, `ws` defaults to 100 MiB: any client holding the single+ // shared password could push 100 MB frames in a loop and OOM the process, killing every+ // user's ptys. The cap must be enforced by the receiver, before the frame reaches dispatch.+ const casts: unknown[] = []+ platform.on('fire', (v: unknown) => casts.push(v))+ const ws = await connect({ cookie })+ ws.on('error', () => {}) // the server closes the socket under us — expected++ const huge = 'a'.repeat(WS_MAX_PAYLOAD + 1024)+ ws.send(JSON.stringify({ t: 'cast', method: 'fire', args: [huge] }))++ // 1009 = "message too big" — the protocol-level refusal.+ const code = await new Promise<number>((resolve) => ws.on('close', resolve))+ expect(code).toBe(1009)+ expect(casts).toEqual([])+ })+it('heartbeat: terminates a socket that never answers a ping, dropping its presence peer', async () => {// Its own listener, so the heartbeat can run at test speed (production: WS_HEARTBEAT_MS).const hbServer = http.createServer((_q, s) => { s.statusCode = 404; s.end() })diff --git a/src/server/ws.ts b/src/server/ws.tsindex 989adac04..ba6b8d940 100644--- a/src/server/ws.ts+++ b/src/server/ws.ts@@ -31,6 +31,27 @@ import { presenceHub } from '../core/presence/hub'*/export const WS_HEARTBEAT_MS = 30_000+/**+ * Largest client→server frame the receiver will accept (8 MiB). `ws` defaults to 100 MiB, which is+ * a remote DoS on a process that is shared by every user of the box: one client holding the single+ * Server Edition password can loop 100 MB frames and OOM the server, taking down everyone's ptys,+ * the hook server and the workspace store. The receiver drops an oversized frame with close code+ * 1009 before it ever reaches dispatch, so nothing buffers it.+ *+ * Why 8 MiB — what actually rides this socket, client→server:+ * - `pty:write` casts: keystrokes and clipboard pastes (kilobytes; a giant paste is not a thing+ * a terminal survives anyway),+ * - presence casts: cursor points, and chat/name/focus strings the hub itself caps at 200 / 32 /+ * 128 code points,+ * - RPC requests, of which the biggest by far is `fs:write` — an editor node saving its file,+ * JSON-escaped. 8 MiB comfortably covers any text file a Monaco editor is usable on (a 1 MB+ * source file is already an outlier, and JSON escaping roughly doubles it in the worst case),+ * plus `workspace:save` (a whole canvas: nodes + sticky text, tens of KB).+ * That leaves ~an order of magnitude of headroom over the largest legitimate frame while cutting+ * the worst case a single frame can cost the process by ~12×.+ */+export const WS_MAX_PAYLOAD = 8 * 1024 * 1024+export interface WsServerOpts {platform: ServerPlatformauth: Auth@@ -63,7 +84,7 @@ function upgradeAllowed(req: http.IncomingMessage, auth: Auth): boolean {export function attachWsServer(server: http.Server, opts: WsServerOpts): void {const { platform, auth, heartbeatMs = WS_HEARTBEAT_MS } = opts- const wss = new WebSocketServer({ noServer: true })+ const wss = new WebSocketServer({ noServer: true, maxPayload: WS_MAX_PAYLOAD })// Liveness heartbeat. Node enables no TCP keepalive on an upgraded socket, so a browser that// simply VANISHES (laptop asleep, wifi dropped, NAT idle-reap) leaves a half-open socket: no FINdiff --git a/src/shared/presence.test.ts b/src/shared/presence.test.tsindex 8752e6826..c4e4791d5 100644--- a/src/shared/presence.test.ts+++ b/src/shared/presence.test.ts@@ -1,10 +1,12 @@import { describe, it, expect } from 'vitest'import {PRESENCE_COLORS,+ capCodePoints,defaultNameFor,nextFreeColor,peersOnProject,sanitizeIdentity,+ CHAT_MAX_LEN,NAME_MAX_LEN,type PeerDiff,type PeerState@@ -112,6 +114,48 @@ describe('sanitizeIdentity', () => {})})+describe('capCodePoints (the one truncation rule — and the one untrusted-length door)', () => {+ it('caps by code point and leaves a short string alone', () => {+ expect(capCodePoints('hello', 10)).toBe('hello')+ expect(capCodePoints('hello', 3)).toBe('hel')+ expect(capCodePoints('', 3)).toBe('')+ expect(capCodePoints('abc', 0)).toBe('')+ })++ it('never cuts a surrogate pair in half, wherever the cap lands', () => {+ // Every code point is astral: the cap in code UNITS would be 2× the cap in code POINTS, so an+ // implementation that bounds the input by code units must still not hand back half a pair.+ const emoji = '😀'.repeat(500)+ const out = capCodePoints(emoji, 200)+ expect([...out]).toHaveLength(200)+ expect(out).toBe('😀'.repeat(200))+ expect(out).not.toMatch(/[\uD800-\uDFFF]/u)++ // A pair straddling the max*2 code-unit boundary of a bounded implementation.+ const straddle = 'a' + '😀'.repeat(500)+ const cut = capCodePoints(straddle, 200)+ expect([...cut]).toHaveLength(200)+ expect(cut).toBe('a' + '😀'.repeat(199))+ expect(cut).not.toMatch(/[\uD800-\uDFFF]/u)+ })++ it('caps a huge hostile string WITHOUT materializing it (cost is O(max), not O(input))', () => {+ // A client can cast a `presence:chat` of whatever size the socket accepts. The old+ // `[...text].slice(0, max)` spread the WHOLE string into an array of code points first: for a+ // 40 MB frame that is ~20M array elements — seconds of blocked event loop and ~1 GB of heap,+ // i.e. a trivial remote DoS on the shared Server Edition process. Bounding the input first+ // makes the work proportional to `max`, so this is milliseconds.+ const hostile = 'a'.repeat(40_000_000)+ const started = performance.now()+ const out = capCodePoints(hostile, CHAT_MAX_LEN)+ const elapsed = performance.now() - started+ expect(out).toBe('a'.repeat(CHAT_MAX_LEN))+ // Generous by two orders of magnitude: the bounded implementation runs in µs, while the+ // spreading one cannot get near this even on a fast machine.+ expect(elapsed).toBeLessThan(200)+ })+})+describe('peersOnProject (the one project filter: cursors, bubbles, node chips)', () => {const peers = [peer(1, 'web'), peer(2, 'api'), peer(3, null), peer(4, 'web')]diff --git a/src/shared/presence.ts b/src/shared/presence.tsindex d905ebe03..b5fedf664 100644--- a/src/shared/presence.ts+++ b/src/shared/presence.ts@@ -89,9 +89,24 @@ export function peersOnProject(peers: PeerState[], projectId: string | null): Pe/** Cap a string at `max` *code points*, not UTF-16 code units: `slice` would cut a surrogate* pair (emoji, CJK extensions) in half and leave a lone surrogate, which renders as "�" in* every peer's facepile / chat bubble. The single truncation rule for the whole feature — the- * hub caps chat with it (CHAT_MAX_LEN) and capName caps names with it. */+ * hub caps chat with it (CHAT_MAX_LEN) and capName caps names with it.+ *+ * COST IS O(max), NOT O(text) — deliberately. This is a door for UNTRUSTED input (any client can+ * cast a `presence:chat` / `presence:focus` of whatever size the socket accepts), and the obvious+ * `[...text].slice(0, max)` spreads the WHOLE string into an array of code points BEFORE capping:+ * a multi-MB frame would block the event loop for seconds and balloon the heap — a trivial remote+ * DoS on the shared Server Edition process. A code point is at most 2 UTF-16 code units, so the+ * first `max` code points always live inside the first `max * 2` code units: bound the input with+ * a (O(1), no-copy) `slice` first, and only spread that. The bounded slice may end on a lone high+ * surrogate, but that surrogate can only ever land at index >= max in the spread, so the cap+ * drops it — no half-emoji can survive. */export function capCodePoints(text: string, max: number): string {- return [...text].slice(0, max).join('')+ if (max <= 0) return ''+ // Fewer code units than the cap ⇒ fewer code points than the cap. Nothing to do.+ if (text.length <= max) return text+ const bounded = [...text.slice(0, max * 2)]+ if (bounded.length <= max) return bounded.join('')+ return bounded.slice(0, max).join('')}/** Cap a name at NAME_MAX_LEN code points. Trim runs again AFTER the cut, so a truncation