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
harden(session-host): security-review follow-ups (F1–F4)
enes2d89d20de7f1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8545a3c3c..11befae61 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -54,5 +54,8 @@ jobs:- name: Type checkrun: npm run typecheck+ - name: Build session host+ run: npm run host:build+- name: Windows-relevant tests- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts+ run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.tsdiff --git a/src/core/session-host-client.ts b/src/core/session-host-client.tsindex bdc556cd0..a40bef0ab 100644--- a/src/core/session-host-client.ts+++ b/src/core/session-host-client.ts@@ -492,7 +492,15 @@ export class SessionHostClient {}}const onHandshakeData = (chunk: Buffer): void => {- const frames = framer.push<SessionHostFrame>(chunk.toString('utf8'))+ let frames: SessionHostFrame[]+ try {+ frames = framer.push<SessionHostFrame>(chunk.toString('utf8'))+ } catch (error) {+ // Whatever is bound to the endpoint streamed an oversized un-terminated line — a broken+ // or impostor host. Fail the handshake rather than buffer it unbounded.+ failHandshake(asError(error))+ return+ }for (let index = 0; index < frames.length; index++) {const frame = frames[index]if ('type' in frame || frame.id !== helloId) continue@@ -549,7 +557,16 @@ export class SessionHostClient {this.everConnected = trueconst framer = new LineFramer()socket.on('data', (chunk: Buffer) => {- for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {+ let frames: SessionHostFrame[]+ try {+ frames = framer.push<SessionHostFrame>(chunk.toString('utf8'))+ } catch (error) {+ // Oversized un-terminated line from the host — drop and destroy so a broken/impostor peer+ // cannot grow this process's buffer without limit.+ this.dropSocket(socket, asError(error), true)+ return+ }+ for (const frame of frames) {this.handleFrame(socket, frame)}})diff --git a/src/session-host/hello-probe.ts b/src/session-host/hello-probe.tsindex 3f8c4baf6..c66390943 100644--- a/src/session-host/hello-probe.ts+++ b/src/session-host/hello-probe.ts@@ -32,7 +32,16 @@ export function trySessionHostHello(})const framer = new LineFramer()socket.on('data', (chunk: Buffer) => {- for (const frame of framer.push<{ id: number; ok?: boolean }>(chunk.toString('utf8'))) {+ let frames: { id: number; ok?: boolean }[]+ try {+ frames = framer.push<{ id: number; ok?: boolean }>(chunk.toString('utf8'))+ } catch {+ // Whatever answered streamed an oversized un-terminated line — treat the probe as a+ // negative (this endpoint is not a healthy host) rather than buffer it.+ finish(false)+ return+ }+ for (const frame of frames) {if (frame.id !== HELLO_PROBE_ID) continuefinish(frame.ok === true)}diff --git a/src/session-host/host-routing.test.ts b/src/session-host/host-routing.test.tsindex df6f1dcd7..9d2205895 100644--- a/src/session-host/host-routing.test.ts+++ b/src/session-host/host-routing.test.ts@@ -152,6 +152,18 @@ describe('bundled session-host request boundaries', () => {socket.write(encodeFrame({ id: 0, cmd: 'hello', token }))await expect(connected.response(0)).resolves.toMatchObject({ id: 0, ok: true })+ // A second connection presenting the WRONG token is refused and dropped — the bearer token+ // is the only command gate, so this is the load-bearing negative. A same-length wrong token+ // exercises the constant-time compare's real path rather than the length short-circuit.+ const impostor = await connectFrames(state.endpoint)+ try {+ const wrong = 'f'.repeat(token.length)+ impostor.socket.write(encodeFrame({ id: 0, cmd: 'hello', token: wrong }))+ await expect(impostor.response(0)).resolves.toMatchObject({ id: 0, ok: false, error: 'unauthorized' })+ } finally {+ impostor.socket.destroy()+ }+const spawnOptions: SessionHostSpawnOptions = {cwd: '.',shell: 'fake-shell',diff --git a/src/session-host/host.ts b/src/session-host/host.tsindex 10d57a5f3..444b00204 100644--- a/src/session-host/host.ts+++ b/src/session-host/host.ts@@ -49,6 +49,18 @@ import { killHostSession } from './kill-session'* briefly drops to zero sessions (closing every node, or a launcher racing a real create) does* not tear down a host that is about to be handed a fresh session moments later. */const GRACE_EXIT_MS = 30_000++/** Constant-time bearer-token comparison. The token is 256 bits of hex, so a timing side-channel+ * over noisy local IPC is not practically exploitable — but the check is trivial to get right,+ * and a non-string `req.token` (a hostile client can send any JSON) must compare false without+ * throwing. Unequal lengths short-circuit false; equal lengths go through `timingSafeEqual`. */+function tokenMatches(received: unknown, expected: string): boolean {+ if (typeof received !== 'string') return false+ const a = Buffer.from(received)+ const b = Buffer.from(expected)+ return a.length === b.length && crypto.timingSafeEqual(a, b)+}+const COMPLETED_KILL_TTL_MS = 10 * 60_000const MAX_COMPLETED_KILLS = 1_024const REPLACEMENT_RESERVATION_TTL_MS = 30_000@@ -891,7 +903,15 @@ async function main(): Promise<void> {}}socket.on('data', (chunk: Buffer) => {- const frames = framer.push<SessionHostRequest>(chunk.toString('utf8'))+ let frames: SessionHostRequest[]+ try {+ frames = framer.push<SessionHostRequest>(chunk.toString('utf8'))+ } catch {+ // A single line past MAX_FRAME_BYTES with no terminator: a hostile or broken peer, pre- or+ // post-auth. Drop the connection rather than keep buffering it.+ socket.destroy()+ return+ }for (const req of frames) {if (!authed) {const requestedVersion =@@ -900,7 +920,7 @@ async function main(): Promise<void> {: undefinedif (req.cmd === 'hello' &&- req.token === token &&+ tokenMatches(req.token, token) &&(requestedVersion === undefined ||requestedVersion === 1 ||requestedVersion === currentProtocolVersion())@@ -923,7 +943,7 @@ async function main(): Promise<void> {)} else {const error =- req.cmd === 'hello' && req.token === token+ req.cmd === 'hello' && tokenMatches(req.token, token)? `incompatible session-host protocol: expected ${currentProtocolVersion()}`: 'unauthorized'writeSessionHostFrame(@@ -951,6 +971,10 @@ async function main(): Promise<void> {)continue}+ // A JSON primitive/null that parsed cleanly (e.g. `5`) is not a request: `'name' in req`+ // would throw `TypeError` here — post-auth, inside the data handler, caught only by the+ // process-level logger, silently dropping the rest of this chunk's frames. Skip it.+ if (typeof req !== 'object' || req === null) continueif ('name' in req) void requestQueue.enqueue(req.name, () => dispatchAndRespond(req))else void dispatchAndRespond(req)}@@ -1020,6 +1044,18 @@ async function main(): Promise<void> {const token = crypto.randomBytes(32).toString('hex')server.listen(paths.endpoint, () => {+ // Defence in depth: the 0600 token already gates every command, but a process running under a+ // permissive umask would otherwise publish the AF_UNIX socket world-writable, letting a co-user+ // at least connect() (and reach the pre-auth framer). Pin it to owner-only. Windows named pipes+ // have their own default ACL and no fs mode, so this is POSIX-only; a failure here is not fatal+ // — the token still protects the endpoint — so it is best-effort and logged, not aborted.+ if (process.platform !== 'win32') {+ try {+ fs.chmodSync(paths.endpoint, 0o700)+ } catch (e) {+ log(`warning: could not restrict socket permissions: ${String(e)}`)+ }+ }try {fs.writeFileSync(paths.tokenPath, token, { mode: 0o600 })} catch (e) {diff --git a/src/session-host/protocol.test.ts b/src/session-host/protocol.test.tsnew file mode 100644index 000000000..472559950--- /dev/null+++ b/src/session-host/protocol.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest'+import { LineFramer, FrameTooLargeError, MAX_FRAME_BYTES, encodeFrame } from './protocol'++describe('LineFramer', () => {+ it('reassembles a frame split across chunks and drops a corrupt line without wedging', () => {+ const framer = new LineFramer()+ expect(framer.push<any>('{"a":1')).toEqual([])+ expect(framer.push<any>('}\nnot json\n{"b":2}\n')).toEqual([{ a: 1 }, { b: 2 }])+ })++ it('caps an un-terminated line instead of buffering it without bound (pre-auth DoS)', () => {+ const framer = new LineFramer()+ // A peer streaming bytes with no newline: each push must not accumulate past the cap.+ const halfCap = 'x'.repeat(MAX_FRAME_BYTES / 2 + 1)+ expect(framer.push<any>(halfCap)).toEqual([]) // under the cap: buffered, no throw+ expect(() => framer.push<any>(halfCap)).toThrow(FrameTooLargeError) // crosses the cap: refused+ })++ it('a huge but newline-delimited stream is fine — only the un-terminated tail is bounded', () => {+ const framer = new LineFramer()+ // Many small complete frames whose total exceeds the cap must still parse: the guard checks+ // the residual tail, not the chunk size.+ const many = Array.from({ length: 1000 }, (_, i) => encodeFrame({ n: i })).join('')+ const big = many.repeat(70) // > MAX_FRAME_BYTES total, but every line is terminated+ expect(framer.push<any>(big).length).toBe(70_000)+ })++ it('recovers after refusing an oversized line: the buffer is cleared, not poisoned', () => {+ const framer = new LineFramer()+ expect(() => framer.push<any>('y'.repeat(MAX_FRAME_BYTES + 1))).toThrow(FrameTooLargeError)+ expect(framer.push<any>('{"ok":true}\n')).toEqual([{ ok: true }])+ })+})diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.tsindex 9d4886155..5bf518c68 100644--- a/src/session-host/protocol.ts+++ b/src/session-host/protocol.ts@@ -199,13 +199,36 @@ export interface ListSessionsResult {* across TCP/pipe chunks — the whole reason a delimiter-based framing needs a stateful parser* instead of `JSON.parse(chunk)`. Shared by both ends so the framing rule is written exactly once.*/+/** Hard cap on a single un-terminated line. This framer runs BEFORE the `hello` auth check on+ * the host, and on the client against whatever is bound to the endpoint, so an unbounded buffer+ * is a pre-auth memory-exhaustion DoS: a peer that streams bytes with no `\n` would grow `buf`+ * without limit. No legitimate frame is anywhere near this — the largest is a full-scrollback+ * capture, comfortably under a few MB — so a line past the cap is a hostile or broken peer and+ * the connection is abandoned rather than buffered. */+export const MAX_FRAME_BYTES = 64 * 1024 * 1024++/** Thrown when a single line exceeds `MAX_FRAME_BYTES`; both ends destroy the socket on it. */+export class FrameTooLargeError extends Error {+ constructor() {+ super('session-host frame exceeded the maximum size')+ this.name = 'FrameTooLargeError'+ }+}+export class LineFramer {private buf = ''/** Feed a raw chunk; returns every complete frame it now contains, in arrival order. A* malformed line is DROPPED rather than thrown — one corrupt frame must never wedge every- * frame that follows it on the same connection. */+ * frame that follows it on the same connection. A line that grows past `MAX_FRAME_BYTES`+ * without terminating throws `FrameTooLargeError`; the caller destroys the connection. */push<T>(chunk: string): T[] {this.buf += chunk+ // Only an un-terminated tail can grow unbounded — a chunk full of `\n` splits fine however+ // large. Check before split so a peer cannot force a huge allocation one byte at a time.+ if (this.buf.length > MAX_FRAME_BYTES && !this.buf.includes('\n')) {+ this.buf = ''+ throw new FrameTooLargeError()+ }const lines = this.buf.split('\n')this.buf = lines.pop() ?? ''const out: T[] = []