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(security): a pasted payload must not be able to escape its bracketed-paste frame
enesf1ec8559f62c
diff --git a/src/core/paste-injection.realtty.test.ts b/src/core/paste-injection.realtty.test.tsnew file mode 100644index 000000000..0a83bc299--- /dev/null+++ b/src/core/paste-injection.realtty.test.ts@@ -0,0 +1,247 @@+// SECURITY — the framed injection, delivered to a REAL bracketed-paste-aware reader.+//+// The sibling `paste-injection.test.ts` asserts on the produced BYTES. This file trusts no parser+// of ours: it spawns a real pty running a real bash (readline turns bracketed paste on and+// announces it with `ESC[?2004h`, which is exactly the `bracket_paste_flag` the delivery paths+// probe for), writes the framed body into it, and then asks the filesystem whether the attacker's+// trailing bytes were executed as KEYS.+//+// It exists for the reason `control-master.realsh.test.ts` exists: a structural test can only+// catch the tricks it was taught, and this repo has twice shipped a defect that a hand-rolled+// parser passed and the real thing caught. A paste frame is a promise made to somebody else's+// parser, so somebody else's parser has to be the judge.+//+// The SSH case goes the whole way: the remote command line `remoteTmuxSendKeysArgs` builds is run+// through a real /bin/sh with a stub `tmux` on PATH, and the bytes that stub receives — what the+// remote tmux would inject into the pane — are what get delivered to bash. Real quoting, then a+// real reader.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import * as pty from 'node-pty'+import { bracketedInjection, PASTE_END } from './paste-injection'+import { remoteTmuxSendKeysArgs } from './remote-ssh/control-master'++const ESC = '\x1b'+/** readline says "I have requested bracketed paste" with this — the same DECSET tmux tracks. */+const PASTE_ON = `${ESC}[?2004h`+/** Its output is not its own source text, so seeing it cannot be an echo of the input line. */+const SENTINEL_CMD = "printf 'NTDONE%s\\n' 42\r"+const SENTINEL_OUT = 'NTDONE42'++/**+ * bash's readline only implements bracketed paste from 5.1. macOS ships bash 3.2 as /bin/bash, so+ * look for a good one on PATH before falling back — and when there is none, say so loudly rather+ * than pretend the suite covered this.+ */+function findPasteAwareBash(): string | null {+ for (const candidate of ['/usr/local/bin/bash', '/opt/homebrew/bin/bash', '/bin/bash', '/usr/bin/bash']) {+ if (!fs.existsSync(candidate)) continue+ try {+ const v = execFileSync(candidate, ['-c', 'echo "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}"'], {+ encoding: 'utf8'+ }).trim()+ const [maj, min] = v.split('.').map((n) => Number(n))+ if (maj > 5 || (maj === 5 && min >= 1)) return candidate+ } catch {+ // not a usable bash — try the next candidate+ }+ }+ return null+}++const BASH = findPasteAwareBash()++let work: string+let markerDir: string+let binDir: string++beforeAll(() => {+ work = fs.mkdtempSync(path.join(os.tmpdir(), 'ntpaste-'))+ markerDir = path.join(work, 'm')+ binDir = path.join(work, 'bin')+ fs.mkdirSync(markerDir)+ fs.mkdirSync(binDir)+ // Stub tmux for the SSH path: answers the bracket_paste_flag probe with 1 and prints the body+ // of a `send-keys` verbatim — i.e. exactly the bytes the remote tmux would put in the pane.+ fs.writeFileSync(+ path.join(binDir, 'tmux'),+ [+ '#!/bin/sh',+ 'for a in "$@"; do',+ ' last="$a"',+ ' case "$a" in display-message) dm=1;; send-keys) sk=1;; esac',+ 'done',+ '[ -n "$dm" ] && { printf 1; exit 0; }',+ '[ -n "$sk" ] && { if [ "$last" = Enter ]; then printf "\\r"; else printf %s "$last"; fi; }',+ 'exit 0'+ ].join('\n') + '\n',+ { mode: 0o755 }+ )+})++afterAll(() => {+ if (work) fs.rmSync(work, { recursive: true, force: true })+})++const marker = (name: string): string => path.join(markerDir, name)++/**+ * Write `bytes` into a real bash on a real pty, then abort the line and run a sentinel command.+ *+ * The sentinel is what makes this deterministic rather than a sleep: bash consumes its input in+ * order, so once the sentinel's OUTPUT has appeared, anything the payload could have executed has+ * already executed. It doubles as the check that the frame actually CLOSED — a payload that+ * swallowed the closing marker leaves readline still collecting a paste, the sentinel never runs,+ * and this rejects.+ */+function deliver(bytes: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const term = pty.spawn(BASH as string, ['--norc', '--noprofile', '-i'], {+ name: 'xterm-256color',+ cols: 200,+ rows: 40,+ cwd: work,+ env: { ...process.env, PS1: 'RDY> ', HISTFILE: '/dev/null', TERM: 'xterm-256color' }+ })+ let out = ''+ let stage: 'wait-ready' | 'wait-sentinel' | 'done' = 'wait-ready'+ const finish = (fn: () => void): void => {+ stage = 'done'+ clearTimeout(timer)+ try {+ term.kill()+ } catch {+ // the shell may already be gone+ }+ fn()+ }+ const timer = setTimeout(() => {+ if (stage !== 'done') {+ finish(() =>+ reject(+ new Error(+ `bash never reached the sentinel — the paste frame may still be open. Output so far: ${JSON.stringify(out.slice(-400))}`+ )+ )+ )+ }+ }, 15_000)+ term.onData((d) => {+ out += d+ if (stage === 'wait-ready' && out.includes(PASTE_ON)) {+ stage = 'wait-sentinel'+ term.write(bytes)+ // ctrl-c clears whatever is composed, then the sentinel runs from a fresh prompt.+ setTimeout(() => term.write('\x03'), 120)+ setTimeout(() => term.write(SENTINEL_CMD), 200)+ return+ }+ if (stage === 'wait-sentinel' && out.includes(`${SENTINEL_OUT}\r\n`)) {+ finish(() => resolve(out))+ }+ })+ })+}++/** The local delivery: `PtyManager.sendText`'s framed branch hands exactly this to send-keys. */+const localBody = (text: string, enter: boolean): string => bracketedInjection(text, enter)++/** The SSH delivery: build the remote line, run it through a real sh, keep what tmux received. */+function sshBody(text: string, enter: boolean): string {+ const cmd = remoteTmuxSendKeysArgs(+ { host: 'h.example.com', user: 'deploy', port: 22, identityFile: '/k/id' },+ '/s.sock',+ 'nt-x',+ text,+ enter+ ).slice(-1)[0]+ return execFileSync('/bin/sh', ['-c', cmd], {+ env: { PATH: `${binDir}:/usr/bin:/bin`, HOME: work },+ encoding: 'utf8'+ })+}++const PATHS: Record<string, (text: string, enter: boolean) => string> = {+ local: localBody,+ ssh: sshBody+}++const suite = BASH ? describe : describe.skip++suite('REAL bash: an escaping payload is never interpreted as keys', () => {+ for (const [pathName, build] of Object.entries(PATHS)) {+ it(+ `${pathName}: the end marker + Enter + a command does NOT run the command (dictation insert, enter=false)`,+ async () => {+ const m = marker(`${pathName}-cmd`)+ // The escape: close the paste early, submit, and run something.+ const body = build(`hello${PASTE_END}\rtouch ${m}\r`, false)+ const out = await deliver(body)+ expect(fs.existsSync(m), 'the payload EXECUTED — it escaped the frame').toBe(false)+ // …and the text still arrived, as content. The ESC is gone, its printable tail is not.+ expect(out).toContain('hello[201~')+ expect(out).not.toContain('command not found')+ },+ 20_000+ )++ it(+ `${pathName}: the end marker + ctrl-u + a command does NOT run it, even with Enter appended`,+ async () => {+ const m = marker(`${pathName}-ctrlu`)+ // No newline anywhere in the payload: the whole attack is the early frame close plus+ // ctrl-u (kill-line), which would wipe the benign prefix and leave only the command for+ // the Enter that this delivery appends itself. The trailing ` #` comments out the frame's+ // own closing marker, which under the escape arrives as typed characters after the+ // command — without it the corrupted argument would hide the hit.+ const body = build(`SAFE${PASTE_END}\x15touch ${m} #`, true)+ await deliver(body)+ expect(fs.existsSync(m), 'ctrl-u was read as a KEY — the payload escaped the frame').toBe(+ false+ )+ },+ 20_000+ )++ it(+ // A guard rather than a discriminator: bash's own parser survives ESC-ESC, so this one+ // passes with or without the sanitizer. It is here because not every receiver is bash, and+ // the byte-level test next door is the one that fails when the rule goes away.+ `${pathName}: a trailing bare ESC does not swallow the closing marker`,+ async () => {+ const m = marker(`${pathName}-tail`)+ // If the payload's trailing ESC joins the marker's own, the frame never closes and every+ // later byte — including the sentinel — is eaten as pasted text; `deliver` rejects then.+ const body = build(`hello${ESC}`, false)+ const out = await deliver(body)+ expect(out).toContain(SENTINEL_OUT)+ expect(fs.existsSync(m)).toBe(false)+ },+ 20_000+ )++ it(+ `${pathName}: an embedded paste-START does not re-open the frame`,+ async () => {+ const m = marker(`${pathName}-start`)+ const body = build(`a${ESC}[200~b${PASTE_END}\rtouch ${m}\r`, false)+ await deliver(body)+ expect(fs.existsSync(m)).toBe(false)+ },+ 20_000+ )+ }++ it('control: the SAME attack DOES execute when the payload is framed unsanitized', async () => {+ // The mutation check, run rather than described: this is the shipped framer with the+ // sanitizer removed. If this ever stops creating the marker, the tests above prove nothing.+ const m = marker('control')+ const payload = `hello${PASTE_END}\rtouch ${m}\r`+ const unsanitized = `${ESC}[200~${payload}${ESC}[201~`+ await deliver(unsanitized)+ expect(fs.existsSync(m), 'the attack no longer works — these tests are vacuous').toBe(true)+ }, 20_000)+})diff --git a/src/core/paste-injection.test.ts b/src/core/paste-injection.test.tsindex 587919daa..c01906d32 100644--- a/src/core/paste-injection.test.ts+++ b/src/core/paste-injection.test.ts@@ -1,5 +1,14 @@import { describe, it, expect } from 'vitest'-import { bracketedInjection, PASTE_START, PASTE_END } from './paste-injection'+import {+ bracketedInjection,+ sanitizePasteText,+ PASTE_START,+ PASTE_END+} from './paste-injection'++const ESC = '\x1b'+/** The 8-bit C1 form of CSI — no glyph, same structural meaning to an 8-bit-clean parser. */+const C1_CSI = '\u009b'describe('bracketedInjection', () => {it('frames the text in paste markers with the Enter in the same body', () => {@@ -14,3 +23,78 @@ describe('bracketedInjection', () => {expect(body.indexOf('\r')).toBe(body.length - 1)})})++/**+ * SECURITY — the payload cannot express paste structure.+ *+ * The invariant every case below reduces to: the produced body contains exactly TWO ESC bytes,+ * the frame's own, at its two ends. A parser cannot see structure in bytes that contain none.+ */+describe('bracketedInjection: a payload cannot escape its frame', () => {+ const escCount = (s: string): number => s.split(ESC).length - 1++ const ATTACKS: Record<string, string> = {+ // The escape itself: end the paste, then submit whatever follows as keys.+ endMarker: `hello${PASTE_END}\rrm -rf ~\r`,+ // …with a control KEY rather than a command, so the damage needs no newline.+ endMarkerThenCtrlU: `SAFE${PASTE_END}\x15echo pwned`,+ // A second paste-START: apps that track "in a paste" as a boolean can re-open or nest.+ startMarker: `hello${PASTE_START}world`,+ // Both, in the order that first closes then re-opens — the frame looks balanced again.+ closeThenReopen: `a${PASTE_END}b${PASTE_START}c`,+ // A bare ESC at the very END, positioned to join the marker's own ESC that follows it.+ trailingEsc: `hello${ESC}`,+ // A partial CSI at the end — the same trick, one byte further along.+ trailingPartialCsi: `hello${ESC}[20`,+ // The 8-bit C1 form of CSI.+ c1Csi: `hello${C1_CSI}201~\rid\r`,+ // A payload that is nothing but the marker.+ markerOnly: PASTE_END,+ // Repeated, so a single-shot replace cannot be mistaken for a fix.+ repeated: `${PASTE_END}${PASTE_END}${PASTE_END}`,+ // Overlapping: a naive non-global replace leaves a whole marker behind.+ overlapping: `${ESC}${ESC}[[200~201~${PASTE_END}`+ }++ for (const [name, payload] of Object.entries(ATTACKS)) {+ for (const enter of [true, false]) {+ it(`${name} (enter=${enter}): the body carries only the frame's own escapes`, () => {+ const body = bracketedInjection(payload, enter)+ expect(escCount(body), 'an ESC byte from the payload survived').toBe(2)+ expect(body.startsWith(PASTE_START)).toBe(true)+ // Exactly one end marker, and it closes the frame.+ expect(body.split(PASTE_END)).toHaveLength(2)+ expect(body.endsWith(enter ? `${PASTE_END}\r` : PASTE_END)).toBe(true)+ // No paste-start other than the frame's own.+ expect(body.indexOf(PASTE_START, 1)).toBe(-1)+ expect(body).not.toContain(C1_CSI)+ // The last byte before the closing marker is never an ESC that could swallow it.+ const inner = body.slice(PASTE_START.length, body.length - (enter ? 1 : 0) - PASTE_END.length)+ expect(inner.endsWith(ESC)).toBe(false)+ })+ }+ }++ it('with enter, the ONLY \\r outside the payload is the final submit', () => {+ const body = bracketedInjection(`hi${PASTE_END}\rid`, true)+ // The payload's own \r stays inside the frame as content; the submit is the last byte.+ expect(body).toBe(`${PASTE_START}hi[201~\rid${PASTE_END}\r`)+ expect(body.lastIndexOf('\r')).toBe(body.length - 1)+ })+})++describe('sanitizePasteText', () => {+ it('leaves ordinary text — including newlines and tabs — byte-for-byte', () => {+ const text = 'line one\nline two\r\n\tindented — ünïcode 🎉 $(id) `id` \'quotes\''+ expect(sanitizePasteText(text)).toBe(text)+ })+ it('keeps every PRINTABLE character of an escape sequence, dropping only the invisible ESC', () => {+ // A pasted transcript that documents bracketed paste still reads.+ expect(sanitizePasteText(`start ${PASTE_START} end ${PASTE_END}`)).toBe('start [200~ end [201~')+ expect(sanitizePasteText(`${ESC}[31mred${ESC}[0m`)).toBe('[31mred[0m')+ })+ it('is idempotent', () => {+ const once = sanitizePasteText(`a${PASTE_END}b`)+ expect(sanitizePasteText(once)).toBe(once)+ })+})diff --git a/src/core/paste-injection.ts b/src/core/paste-injection.tsindex 05affcf06..b18e0a25a 100644--- a/src/core/paste-injection.ts+++ b/src/core/paste-injection.ts@@ -8,11 +8,56 @@// injection the way paste-aware apps expect: the text framed in paste markers and the Enter// appended in the SAME write, so the composer sees a definitive paste boundary and the Enter// can never be re-chunked into the paste. Apps that never requested bracketed paste keep the-// legacy two-step delivery bit-for-bit.+// legacy two-step delivery.export const PASTE_START = '\x1b[200~'export const PASTE_END = '\x1b[201~'+/**+ * SECURITY — the payload must not be able to become structure.+ *+ * A frame built as `ESC[200~ + text + ESC[201~` promises the receiving app that everything+ * between the markers is CONTENT. A payload that itself contains `ESC[201~` breaks that promise:+ * the app ends the paste early and reads the rest as raw KEY INPUT — Enter, ctrl-u, ctrl-c, any+ * escape sequence the author chose. That is not only a human pasting a terminal transcript; the+ * canvas-control `write` verb hands an AGENT's text to the same framer, and the confirm dialog a+ * human approves it in renders ESC as nothing at all, so the escape is invisible to the approver.+ * The same shape is live in the herdr multiplexer (`api_helpers.rs`), so treat it as real.+ *+ * The rule is one line and it removes ESC (and its 8-bit C1 equivalent U+009B), not the marker+ * string:+ *+ * - Removing the literal `ESC[201~` only would leave `ESC[200~` (a second paste-start, which+ * re-opens or nests the frame in apps that track a boolean) and a payload ending in a bare+ * `ESC` (which a lenient parser can join with the marker's own ESC that follows it) still+ * live. All three fall out of the one rule, and no fourth trick has to be enumerated: with+ * zero ESC bytes in the payload, no byte of it can express paste structure at all.+ * - It is not lossy the way dropping the marker string is. ESC has no glyph; every printable+ * character of the payload survives, in order. A pasted transcript that documents bracketed+ * paste still reads as `[201~` — which is what real terminals do with clipboard content+ * (xterm's `disallowedPasteControls`, VTE) rather than an invention of ours.+ * - Splitting and re-framing around the marker was rejected: emitting the literal `ESC[201~`+ * *outside* a frame is the injection, just performed by us.+ * - Refusing the write was rejected for the callers that matter: `sendText` answers a boolean,+ * so a refused note push or dictation insert — the two payloads most likely to carry a real+ * transcript — would fail silently, and the sequence appears in legitimate text.+ *+ * Applied to the legacy (non-bracketed) delivery too, so `sendText`'s contract does not depend on+ * a runtime probe of the receiver: the same payload must land as content whichever way it is+ * delivered. Nothing nodeterm sends through `sendText` — slash commands, note pushes, dictation+ * transcripts, launch commands, chat messages — carries ESC on purpose, so in practice this+ * changes no byte anyone was sending.+ *+ * NOT in scope, and still open: a payload carrying `\r`/`\n` into a caller that believed it was+ * sending ONE line (`/rename <title>` built from an agent-supplied title). Newlines are legitimate+ * paste CONTENT — the multiline injection the tests pin depends on it — so that belongs at those+ * call sites, not here.+ */+export function sanitizePasteText(text: string): string {+ // eslint-disable-next-line no-control-regex+ return text.replace(/[\x1b\u009b]/g, '')+}+/** The single-write injection body for a bracketed-paste-aware target. */export function bracketedInjection(text: string, enter: boolean): string {- return PASTE_START + text + PASTE_END + (enter ? '\r' : '')+ return PASTE_START + sanitizePasteText(text) + PASTE_END + (enter ? '\r' : '')}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 7ff2c900c..2fe805c4f 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -44,7 +44,7 @@ import { REAP_SWEEP_MS, shouldReap } from './pty-reap'import { ControlModeClient, type ControlSpawn } from './tmux-control-client'import { TMUX_SOCKET, sessionName, isSessionName } from './tmux-naming'import { encodeSendKeysHex } from './tmux-control'-import { bracketedInjection } from './paste-injection'+import { bracketedInjection, sanitizePasteText } from './paste-injection'import { releasePty, type ReleasablePty } from './pty-release'import { effectiveSize, type PtySize } from './pty-size'import { machOArch, archMismatch } from './macho-arch'@@ -2821,7 +2821,18 @@ export class PtyManager {return true}// The literal text and the Enter (when sent) must go in order, so await sequentially.- await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, '-l', text])+ // Sanitized like the framed body: which branch runs is decided by a runtime probe of the+ // RECEIVER, so a payload must not become key input just because the target happens not to+ // have requested bracketed paste (`sanitizePasteText`).+ await runAsync(this.tmuxPath, [+ '-L',+ TMUX_SOCKET,+ 'send-keys',+ '-t',+ target,+ '-l',+ sanitizePasteText(text)+ ])if (enter) {await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, 'Enter'])}diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 5b9d02efb..6aa24634d 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -182,6 +182,17 @@ describe('remoteTmuxSendKeysArgs', () => {const args = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', '-not-an-option', false)expect(args[args.length - 1]).toContain(`${TMUX} send-keys -t nt-x -l -- '-not-an-option'`)})+ // SECURITY: a payload carrying the paste-END marker would close the frame early and turn the+ // rest into key input. BOTH branches sanitize — which one runs is decided by a probe of the+ // RECEIVER, so the payload must not become keys just because the target never asked for+ // bracketed paste. `paste-injection.realtty.test.ts` proves the framed body against a real bash.+ it('strips a payload ESC from BOTH branches — the frame is the only structure left', () => {+ const cmd = remoteTmuxSendKeysArgs(conn, '/s.sock', 'nt-x', 'a\x1b[201~\rid\r', true).slice(-1)[0]+ expect(cmd).toContain(`${TMUX} send-keys -t nt-x -l -- '\x1b[200~a[201~\rid\r\x1b[201~\r'`)+ expect(cmd).toContain(`${TMUX} send-keys -t nt-x -l -- 'a[201~\rid\r' && ${TMUX} send-keys -t nt-x Enter`)+ // Only the frame's own two escapes survive anywhere in the remote line.+ expect(cmd.split('\x1b')).toHaveLength(3)+ })})describe('remoteCapturePaneArgs', () => {diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 2c6d05570..8c1422f7f 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -6,7 +6,7 @@ import { createHash } from 'crypto'import { posixQuote, quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'import { TMUX_SOCKET } from '../tmux-naming'import { canControlCanvas } from '../../shared/agents/config'-import { bracketedInjection } from '../paste-injection'+import { bracketedInjection, sanitizePasteText } from '../paste-injection'// Dependency-free (no node-pty): safe to import from these pure builders./** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */@@ -226,6 +226,10 @@ export function parseRemoteSessionNames(stdout: string): string[] {* Otherwise the legacy two-step send runs, joined with `&&`, not `;`: Enter only fires if the* text send actually succeeded, so a failed text send can never leave a lone Enter to submit* whatever was already composed in a live agent prompt.+ *+ * BOTH branches run the payload through `sanitizePasteText` — the same one function the local+ * path calls — so the remote and local deliveries cannot drift on the rule that keeps a payload+ * from escaping its paste frame and being read as key input. Drift is how that survived here.*/export function remoteTmuxSendKeysArgs(conn: SshConnection,@@ -236,7 +240,7 @@ export function remoteTmuxSendKeysArgs(): string[] {const tmux = `tmux -L ${RMT_TMUX_SOCKET}`const framed = `${tmux} send-keys -t ${sessionId} -l -- ${posixQuote(bracketedInjection(text, enter))}`- let legacy = `${tmux} send-keys -t ${sessionId} -l -- ${posixQuote(text)}`+ let legacy = `${tmux} send-keys -t ${sessionId} -l -- ${posixQuote(sanitizePasteText(text))}`if (enter) legacy += ` && ${tmux} send-keys -t ${sessionId} Enter`const cmd = `if [ "$(${tmux} display-message -p -t ${sessionId} '#{bracket_paste_flag}' 2>/dev/null)" = 1 ]; then ${framed}; else ${legacy}; fi`return childArgs(conn, controlPath, cmd)