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(relay): exact tmux targets for every node-keyed verb; a guest's new node unlocks only its own spawn
review1f2017bef9d1
diff --git a/src/core/pty-exact-target.realtmux.test.ts b/src/core/pty-exact-target.realtmux.test.tsnew file mode 100644index 000000000..3207da79a--- /dev/null+++ b/src/core/pty-exact-target.realtmux.test.ts@@ -0,0 +1,180 @@+// Security audit F1/F2 (2026-10) — every node-keyed tmux verb resolves its target EXACTLY.+//+// tmux resolves a BARE `-t name` by exact name, then fnmatch, then PREFIX on a miss. A relay peer that+// could name a prefix of another node's id (a scoped Team Access guest records any id no project holds+// as "its new node"; a hosted Viewer's shared node whose own session is gone) reached the LONGER, live+// session through send-text, capture, pane-command / pane-cwd, the pane-owner read, send-keys and+// terminate-foreground — for an SSH-project guest, the host's LOCAL sessions, where it was granted no+// shell at all. The fix is `=name:` / `=name` everywhere (tmux-naming.ts `exactPaneTarget`).+//+// This suite drives a REAL `PtyManager` against a REAL tmux: a victim session `nt-<base>-victim12` is+// alive, and every verb is asked about `<base>-victim1` — a node id with NO session of its own, the+// shape of the attack. A CONTROL asks the same verbs about the victim's own id, so a harness that+// cannot see an injection (or a capture) cannot pass by accident. And it measures the one thing the+// fix must not change: for an EXISTING session, `=name:` names the same pane the bare name did.+//+// WHERE IT BINDS. `PtyManager` hardcodes `-L node-terminal` (TMUX_SOCKET), so that is the name this+// suite must use; `test/setup/tmux-sandbox.ts` re-points `TMUX_TMPDIR` for the whole run and the+// `beforeAll` below REFUSES to run unless that sandbox is in effect (issue #629). Its own sessions are+// per-run unique and killed by exact target, never `kill-server`. Allowlisted in+// tmux-socket-isolation.guard.test.ts with that reason.+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'+import { execFile } from 'child_process'+import { promisify } from 'util'+import { existsSync, promises as fs, readFileSync } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { DEFAULT_SETTINGS } from '../shared/types'+import { TMUX_SOCKET, sessionName } from './tmux-naming'+import { SANDBOX_ENV, tmuxSocketPath } from './tmux-test-socket'++const run = promisify(execFile)+const TMUX =+ ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux'].find((p) => existsSync(p)) ?? null++vi.mock('./session-host-backend', async () => (await import('./__fixtures__/no-session-host')).noSessionHost())+vi.mock('node-pty', () => ({+ spawn: () => ({+ onData: () => {},+ onExit: () => {},+ write: () => {},+ resize: () => {},+ pause: () => {},+ resume: () => {},+ kill: () => {},+ pid: 4321+ })+}))+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))++describe.skipIf(!TMUX || process.platform === 'win32')('node-keyed tmux verbs resolve their target exactly', () => {+ const base = `sxt${process.pid}${Date.now().toString(36)}`+ const victimKey = `${base}-victim12`+ /** A PROPER PREFIX of the victim's node id: no session of its own exists. */+ const prefixKey = `${base}-victim1`+ const multiKey = `${base}-multi`+ let dir: string+ let victimOut: string+ let manager: import('./pty-manager').PtyManager++ const tmux = (args: string[]) => run(TMUX!, ['-L', TMUX_SOCKET, ...args], { encoding: 'utf8' })+ const victimSaw = (): string => (existsSync(victimOut) ? readFileSync(victimOut, 'utf8') : '')++ beforeAll(async () => {+ // The socket NAME is the live one; only `TMUX_TMPDIR` keeps it off the live SERVER (issue #629).+ const sandbox = process.env[SANDBOX_ENV]+ expect(sandbox, 'tmux sandbox not in effect — see test/setup/tmux-sandbox.ts').toBeTruthy()+ expect(process.env.TMUX_TMPDIR).toBe(sandbox)+ expect(tmuxSocketPath(sandbox!, process.getuid?.() ?? 0, TMUX_SOCKET)).not.toBe(+ tmuxSocketPath('/tmp', process.getuid?.() ?? 0, TMUX_SOCKET)+ )+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-exact-'))+ victimOut = path.join(dir, 'victim.out')+ initPlatform(fakePlatform({ userDataDir: dir }))+ // The victim: prints a marker (so a capture can be recognised), then records every line it is+ // typed. `cat` reads the tty in cooked mode, so a paste + Enter lands as one line in the file.+ await tmux([+ 'new-session', '-d', '-s', sessionName(victimKey), '-x', '100', '-y', '20',+ `sh -c 'echo VICTIM_SCREEN_MARK; exec cat >> ${victimOut}'`+ ])+ // A session with three windows and a split, for the semantics check.+ await tmux(['new-session', '-d', '-s', sessionName(multiKey), '-x', '100', '-y', '30'])+ await tmux(['new-window', '-t', `=${sessionName(multiKey)}:`])+ await tmux(['new-window', '-t', `=${sessionName(multiKey)}:`])+ await tmux(['select-window', '-t', `=${sessionName(multiKey)}:1`])+ await tmux(['split-window', '-t', `=${sessionName(multiKey)}:1`])+ await tmux(['split-window', '-t', `=${sessionName(multiKey)}:1`])+ await tmux(['select-pane', '-t', `=${sessionName(multiKey)}:1.1`])+ await sleep(300)+ const { PtyManager } = await import('./pty-manager')+ manager = new PtyManager()+ manager.init(() => DEFAULT_SETTINGS)+ })++ afterAll(async () => {+ for (const key of [victimKey, multiKey, prefixKey]) {+ try {+ await tmux(['kill-session', '-t', `=${sessionName(key)}`])+ } catch {+ /* not running — the expected case for the prefix */+ }+ }+ resetPlatformForTests()+ if (dir) await fs.rm(dir, { recursive: true, force: true })+ })++ it('the trap is real: a BARE target prefix-matches the victim (control for everything below)', async () => {+ const { stdout } = await tmux(['display-message', '-p', '-t', sessionName(prefixKey), '#{session_name}'])+ expect(stdout.trim()).toBe(sessionName(victimKey))+ })++ it('send-text to the prefix id types NOTHING into the victim; to the victim\'s own id it does', async () => {+ expect(await manager.sendText(prefixKey, 'INJECTED_BY_PREFIX', { enter: true })).toBe(false)+ expect(await manager.sendKeys(prefixKey, [{ digit: '7' }, { name: 'Enter' }])).toBe(false)+ await sleep(400)+ expect(victimSaw()).not.toContain('INJECTED_BY_PREFIX')+ expect(victimSaw()).not.toContain('7')+ // Control: the harness sees an injection when one happens.+ expect(await manager.sendText(victimKey, 'OWN_ID_LINE', { enter: true })).toBe(true)+ await vi.waitFor(() => expect(victimSaw()).toContain('OWN_ID_LINE'), { timeout: 10_000 })+ // A failed paste leaves no buffer of ours behind in the server (the sweep ran).+ await vi.waitFor(async () => {+ const { stdout } = await tmux(['list-buffers', '-F', '#{buffer_name}']).catch(() => ({ stdout: '' }))+ expect(stdout).not.toMatch(/nt-paste-/)+ })+ })++ it('capture, pane command, pane cwd and the pane-owner read answer nothing for the prefix id', async () => {+ expect(await manager.captureSession(prefixKey)).toBe('')+ expect(await manager.captureSnapshot(prefixKey)).toBe('')+ expect(await manager.paneCommand(prefixKey)).toBeNull()+ expect(await manager.paneCwd(prefixKey)).toBeNull()+ expect(await manager.paneOwner(prefixKey)).toBeNull()+ expect(await manager.sessionExists(prefixKey)).toBe(false)+ // Control: the same verbs DO answer for the victim's own id.+ expect(await manager.captureSession(victimKey)).toContain('VICTIM_SCREEN_MARK')+ expect(await manager.paneCommand(victimKey)).toBeTruthy()+ expect(await manager.paneCwd(victimKey)).toBeTruthy()+ expect(await manager.sessionExists(victimKey)).toBe(true)+ })++ it('terminate-foreground never signals anything for the prefix id, and the victim keeps running', async () => {+ expect(await manager.terminateForeground(prefixKey)).toBe(false)+ await expect(tmux(['has-session', '-t', `=${sessionName(victimKey)}`])).resolves.toBeTruthy()+ })++ it('for an EXISTING session the exact form names the same pane the bare name did', async () => {+ const fmt = '#{window_index}.#{pane_index}|#{pane_id}'+ const bare = async () => (await tmux(['display-message', '-p', '-t', sessionName(multiKey), fmt])).stdout.trim()+ const exact = async () =>+ (await tmux(['display-message', '-p', '-t', `=${sessionName(multiKey)}:`, fmt])).stdout.trim()+ expect(await exact()).toBe(await bare())+ expect((await exact()).startsWith('1.1|')).toBe(true)+ // Move the selection: both follow it, still identically.+ await tmux(['select-window', '-t', `=${sessionName(multiKey)}:2`])+ expect(await exact()).toBe(await bare())+ expect((await exact()).startsWith('2.0|')).toBe(true)+ // And the production read agrees with tmux about which pane that is.+ expect(await manager.paneCommand(multiKey)).toBeTruthy()+ })++ it('a NEW-ONLY create never joins or reattaches a session that already runs under the name', async () => {+ const r = await manager.createHeadless({ persistKey: victimKey, cols: 80, rows: 24, newOnly: true })+ expect(r).toEqual({ sessionId: '', fresh: false, unavailable: 'new-only' })+ // The victim is untouched (still alive, nothing typed).+ await expect(tmux(['has-session', '-t', `=${sessionName(victimKey)}`])).resolves.toBeTruthy()+ // Where nothing runs under the EXACT name (a prefix of a live one included), it spawns fresh.+ const fresh = await manager.createHeadless({ persistKey: prefixKey, cols: 80, rows: 24, newOnly: true })+ expect(fresh.unavailable).toBeUndefined()+ expect(fresh.fresh).toBe(true)+ expect(fresh.sessionId).not.toBe('')+ manager.releaseHeadless(prefixKey)+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex a075ed67e..28c702bf7 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -121,6 +121,8 @@ import {TMUX_SOCKET,sessionName,isSessionName,+ exactPaneTarget,+ exactSessionTarget,localPasteDelivery,localTmuxEnterArgs,pasteBufferName,@@ -2588,6 +2590,12 @@ export class PtyManager {pendingRecycle.waiters.push({ clientId, options, resolve, reject })})}+ // A NEW-ONLY create (a relay guest's node it introduced, `PtyCreateOptions.newOnly`) may only+ // spawn: a spawn already in flight for this name, or a session this process already holds for it+ // (the co-attach `join` below, a plain shell that carries the id as `nodeId`), is somebody's+ // terminal, and joining it is exactly what this option exists to refuse.+ if (options.newOnly && (this.inflight.get(key) || this.liveSessionForNode(key)))+ return { sessionId: '', fresh: false, unavailable: 'new-only' }// Same-tick race: spawnNew() awaits a `tmux has-session` SUBPROCESS (tens of ms, not a// microtask) before spawnSession registers the session in `byPersistKey`, so two clients// opening the same node in that window would BOTH miss the index and both spawn — and the@@ -2886,7 +2894,7 @@ export class PtyManager {// the create on to `new-session -A`, which CREATES the session if it was really gone, and the// owner's next open then reads `fresh:false` and skips its cold restore.const joinOnlyLocalVerdict =- options.joinOnly && !options.sshRemote && !warmWindowsBackend && tmuxBacked+ (options.joinOnly || options.newOnly) && !options.sshRemote && !warmWindowsBackend && tmuxBacked? await this.strictTmuxVerdict(options.persistKey as string): undefined// The same strict question for a node whose terminals live in the SESSION HOST (Windows, or no@@ -2952,6 +2960,24 @@ export class PtyManager {zellijChoice?.state === 'unknown'if (options.joinOnly && joinRefused)return { sessionId: '', fresh: false, unavailable: 'join-only' }+ // A NEW-ONLY create spawns only where nothing runs under this name: a session we positively saw+ // ABSENT (the strict local probe, the remote listing, Zellij's own answer). A live session, and a+ // probe that could not answer, are both refused — never `new-session -A`, which would attach to+ // (and `-D` detach the other clients of) whatever holds the name. The session host's own+ // attach-or-create IS its probe, so it is asked first, strictly, and re-checked after `ready`.+ if (options.newOnly) {+ const newRefused = options.sshRemote+ ? remoteVerdict !== 'absent'+ : zellijChoice?.use+ ? !zellijChoice.fresh+ : zellijChoice?.state === 'unknown' ||+ (tmuxBacked && joinOnlyLocalVerdict !== 'absent') ||+ (!tmuxBacked &&+ !!options.persistKey &&+ this.hostBackendEligible() &&+ (await sessionHostHasSession(sessionName(options.persistKey)).catch(() => true)))+ if (newRefused) return { sessionId: '', fresh: false, unavailable: 'new-only' }+ }// A watcher's own client is a read-only TMUX client (`attach-session -E -f ignore-size,read-only`),// and a Zellij session has no such client to spawn: refused, never a Zellij attach (which would be// a full, typing client). A watcher still co-attaches to a Zellij session this process holds (the@@ -3121,6 +3147,13 @@ export class PtyManager {// (`persisted` in spawnSession) — i.e. exactly "this session survives losing its client",// which is what the renderer's cache-dispose levers must not assume. See PtyCreateResult.const persistent = !!spawned?.persistKey+ // A NEW-ONLY create that turned out to land on an existing session (the session host answers+ // `fresh` only from its own attach, and a name can appear between our probe and the spawn): drop+ // this client's view of it — the session itself keeps running untouched — and refuse.+ if (options.newOnly && !fresh) {+ this.kill(clientId, sessionId, options.viewerId)+ return { sessionId: '', fresh: false, unavailable: 'new-only' }+ }// Stale-cwd probe (issue #464), WARM local-tmux reattach only: `new-session -A` reattached a// session whose shell may sit on a DELETED directory inode (a re-created same-named folder is// a different inode, so the getcwd errors never self-heal). A fresh spawn already validated@@ -3643,7 +3676,10 @@ export class PtyManager {private async tmuxSessionExists(persistKey: string): Promise<boolean> {if (!this.tmuxPath) return falsetry {- await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'has-session', '-t', sessionName(persistKey)], {+ // Exact (`=name`): a bare target prefix-matches a LONGER live session when this one is gone,+ // which read as "warm" and skipped this node's cold restore (and, for a relay peer's prefix+ // id, admitted a session it does not own). See `exactSessionTarget`.+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'has-session', '-t', exactSessionTarget(sessionName(persistKey))], {timeout: PROBE_TIMEOUT_MS})return true@@ -3658,8 +3694,7 @@ export class PtyManager {/*** Is the tmux session for `persistKey` running, by the EXACT target (`=nt-<id>`)? Public for* `team resume`, which must never start a second agent on a conversation whose session exists.- * `sessionExists` cannot answer this: its tmux leg prefix-matches, and it folds "could not tell"- * into "exists". No tmux at all answers 'absent' (nothing can be running there).+ * `sessionExists` cannot answer this: it folds "could not tell" into "exists". No tmux at all answers 'absent' (nothing can be running there).*/sessionVerdict(persistKey: string): Promise<'present' | 'absent' | 'unknown'> {return this.strictTmuxVerdict(persistKey)@@ -3681,7 +3716,7 @@ export class PtyManager {try {await this.confirmedProcessRun(this.tmuxPath,- ['-L', TMUX_SOCKET, 'has-session', '-t', `=${sessionName(persistKey)}`],+ ['-L', TMUX_SOCKET, 'has-session', '-t', exactSessionTarget(sessionName(persistKey))],{ timeout: PROBE_TIMEOUT_MS })return 'present'@@ -3699,7 +3734,7 @@ export class PtyManager {try {await this.confirmedProcessRun(this.tmuxPath,- ['-L', TMUX_SOCKET, 'has-session', '-t', sessionName(persistKey)],+ ['-L', TMUX_SOCKET, 'has-session', '-t', exactSessionTarget(sessionName(persistKey))],{ timeout: PROBE_TIMEOUT_MS })return true@@ -4105,7 +4140,7 @@ export class PtyManager {if (!(await sessionHostWriteDetached(target, rawKeyBytes(key)))) return false}} else {- await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, ...tmuxKeyArgs(key)])+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', exactPaneTarget(target), ...tmuxKeyArgs(key)])}} catch {return false@@ -4147,7 +4182,7 @@ export class PtyManager {try {const { stdout } = await runAsync(this.tmuxPath,- ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey)],+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', exactPaneTarget(sessionName(persistKey))],{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 })return stdout@@ -4812,7 +4847,9 @@ export class PtyManager {// `-d` detaches other clients, so it follows `tmuxAttachFlags`' mirror rule....(sinks || options.joinOnly ? [] : ['-d']),'-t',- sessionName(options.persistKey)+ // Exact: an attach-only reattach must reach THIS node's proven session, never a longer+ // one its name prefixes (`exactSessionTarget`).+ exactSessionTarget(sessionName(options.persistKey))]} else if (isWatcherCreate(options)) {// A live link watcher's own client: attach-only, `-E`, `ignore-size,read-only`, exact target@@ -5769,7 +5806,7 @@ export class PtyManager {try {const { stdout } = await runAsync(this.tmuxPath,- ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-t', sessionName(persistKey), '-S', full ? '-' : '-200'],+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-t', exactPaneTarget(sessionName(persistKey)), '-S', full ? '-' : '-200'],{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 })return stdout@@ -6290,7 +6327,7 @@ export class PtyManager {'display-message','-p','-t',- target,+ exactPaneTarget(target),'#{cursor_x} #{cursor_y} #{cursor_flag}'])return parsePaneCursor(stdout)@@ -6367,7 +6404,7 @@ export class PtyManager {try {const { stdout } = await runAsync(this.tmuxPath,- ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', '-1500'],+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', exactPaneTarget(sessionName(persistKey)), '-S', '-1500'],{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 })return stdout ? await this.writeScrollbackIfChanged(persistKey, stdout) : true@@ -6790,7 +6827,7 @@ export class PtyManager {'display-message','-p','-t',- target,+ exactPaneTarget(target),'#{pane_current_command}'])return stdout.trim() || null@@ -6841,7 +6878,7 @@ export class PtyManager {'display-message','-p','-t',- target,+ exactPaneTarget(target),'#{pane_current_path}'])return stdout.trim() || null@@ -6981,7 +7018,7 @@ export class PtyManager {'display-message','-p','-t',- target,+ exactPaneTarget(target),'#{pane_pid}|#{pane_current_command}'])const pane = parsePaneProcess(stdout)@@ -7093,7 +7130,7 @@ export class PtyManager {'display-message','-p','-t',- target,+ exactPaneTarget(target),PANE_OWNER_FMT])const identity = parsePaneOwner(first.stdout)diff --git a/src/core/pty-relay-launch.test.ts b/src/core/pty-relay-launch.test.tsindex 782a0463b..08085729c 100644--- a/src/core/pty-relay-launch.test.ts+++ b/src/core/pty-relay-launch.test.ts@@ -249,8 +249,9 @@ describe('sendKeys into a session-host pane', () => {// A LOCAL node with no client held still goes to the local socket, as before.expect(await m.sendKeys('local-n', [{ digit: '1' }, { name: 'Enter' }])).toBe(true)expect(fs.readFileSync(log, 'utf8').trim().split('\n')).toEqual([- '-L node-terminal send-keys -t nt-local-n -l 1',- '-L node-terminal send-keys -t nt-local-n Enter'+ // The EXACT target (`=name:`): a bare one prefix-matches a longer session on a miss.+ '-L node-terminal send-keys -t =nt-local-n: -l 1',+ '-L node-terminal send-keys -t =nt-local-n: Enter'])} finally {fs.rmSync(dir, { recursive: true, force: true })diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.tsindex d03910a35..a4e3f39e9 100644--- a/src/core/pty-shadow.test.ts+++ b/src/core/pty-shadow.test.ts@@ -81,7 +81,9 @@ vi.mock('child_process', () => {const cb = (typeof a === 'function' ? a : b) as Cb | undefinedconst ok = (stdout: string): void => cb?.(null, { stdout, stderr: '' })if (args.includes('has-session')) {- const target = args[args.indexOf('-t') + 1]+ // Production asks with the EXACT form (`=nt-…`); tmux matches it against the bare name.+ const raw = args[args.indexOf('-t') + 1]+ const target = raw.startsWith('=') ? raw.slice(1).replace(/:$/, '') : rawif (liveTmuxSessions.has(target)) ok('')else cb?.(Object.assign(new Error('no such session'), { code: 1 }))} else if (args[0] === '-ilc') {@@ -232,7 +234,8 @@ describe('control-mode shadow clients for released sessions', () => {fake.senderListeners[IPC.ptyKill](clientId, sessionId)/** Run the sweep past the idle threshold (it only decides on its own ticks). */const idle = (ms = REAP_IDLE_MS + REAP_SWEEP_MS) => vi.advanceTimersByTime(ms)- const attachArgs = (key: string) => ['-L', TMUX_SOCKET, '-C', 'attach-session', '-t', sessionName(key)]+ // Exact (`=name`): a bare target prefix-matches a longer session when this one is gone.+ const attachArgs = (key: string) => ['-L', TMUX_SOCKET, '-C', 'attach-session', '-t', `=${sessionName(key)}`]it('shadows a session the reap stranded — over pipes, taking no pty device', async () => {const m = await tmuxManager()diff --git a/src/core/relay-keys.test.ts b/src/core/relay-keys.test.tsindex a30577761..ad4a1d092 100644--- a/src/core/relay-keys.test.ts+++ b/src/core/relay-keys.test.ts@@ -50,7 +50,7 @@ describe('key encodings', () => {it('the remote send-keys line names only the closed set', () => {const conn = { host: 'box.test', user: 'u' }const args = remoteSendKeyArgs(conn, '/tmp/cm', 'nt-n1', ['-l', '1'])- expect(args[args.length - 1]).toContain('tmux -L nodeterm-rmt send-keys -t nt-n1 -l 1')+ expect(args[args.length - 1]).toContain("tmux -L nodeterm-rmt send-keys -t '=nt-n1:' -l 1")expect(() => remoteSendKeyArgs(conn, '/tmp/cm', 'nt-n1', ['-l', '1;id'])).toThrow()expect(() => remoteSendKeyArgs(conn, '/tmp/cm', 'nt n1', ['Enter'])).toThrow()})diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex 7552f950c..a18fd6ea9 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -72,6 +72,7 @@ const PATH_OUTSIDE = 'Only files inside the shared project folder are reachable.const NO_ROOT = 'This shared project has no folder on the host.'const HOST_DATA = "The host app's own data folder is not reachable."const NOT_SCOPED = 'That is not available in a shared-project session.'+const TOO_MANY_NEW = 'Too many new nodes in this session. Reconnect to add more.'const defaultRealpath = (p: string): string | null => {try {@@ -89,24 +90,72 @@ const defaultLexists = (p: string): boolean => {}}+/**+ * A node id THIS guest introduced over `canvas:mut` while no project held it (the host renderer saves+ * on a debounce, so a brand-new terminal's first `pty:create` routinely arrives before the node is+ * on disk).+ * - `pending`: introduced, but its terminal is not proven to be the guest's own. It reaches+ * `canvas:mut` and a `pty:create` that may only SPAWN (`newOnly`) — never a node-keyed pty verb,+ * never the outbound stream, and that holds even after the host has saved the node into the+ * shared project: being on the canvas is the guest's own doing, not evidence of ownership.+ * - `created`: this session's own `pty:create` for it spawned a FRESH session (the response said+ * so: `fresh: true`, see `noteCreate`). From then on it is a node of the shared project.+ *+ * Why pending is not enough (security audit F1, 2026-10): `canvas:mut` is a cast, admitted before+ * the reflector validates anything, so ANY id no project holds could be recorded — a PREFIX of+ * another project's node id (tmux then prefix-matched the longer, live session on every bare+ * `-t`), an orphan session's exact id, or an id an unreadable project's file holds. For an SSH+ * project's guest, whose own terminals never run locally, that reached the host's LOCAL sessions.+ * Exact tmux targets (tmux-naming.ts `exactPaneTarget`) close the prefix half; this closes the+ * "claim a live session by naming it" half: a pending id unlocks only a spawn of its own.+ */+type Introduced = 'pending' | 'created'++/** How many ids one session may introduce. A memory bound, not a security one (a pending id grants+ * nothing but its own spawn); past it, new ids are refused until the guest reconnects. */+export const INTRODUCED_MAX = 256+/** Everything a check needs about ONE session, built once per session. */interface Scope {projectId: stringdeps: Required<Pick<ScopedGuestDeps, 'realpath' | 'lexists'>> & ScopedGuestDeps- /** Node ids this guest introduced into the shared project over `canvas:mut` that no persisted- * canvas holds yet (the host renderer saves on a debounce, so a brand-new terminal's first- * `pty:create` routinely arrives before the node is on disk). Only ids NO project holds are- * recorded, so this can never adopt another project's node. */- newNodes: Set<string>+ /** See `Introduced`. Bounded at INTRODUCED_MAX; insertion order = age. */+ introduced: Map<string, Introduced>}-/** Every project holding `id`, with this session's own fresh nodes counted as the shared project's. */+const NO_PROJECTS: readonly string[] = Object.freeze([])++/**+ * Every project holding `id` as far as THIS session may act on it. A pending id holds nothing (see+ * `Introduced`) whatever the persisted canvases say; a created one counts as the shared project's+ * until a save puts it on disk.+ */function projectsOf(id: string, s: Scope): readonly string[] {+ const mine = s.introduced.get(id)+ if (mine === 'pending') return NO_PROJECTSconst held = s.deps.projectsOfNode(id)if (held.length > 0) return held- return s.newNodes.has(id) ? [s.projectId] : held+ return mine === 'created' ? [s.projectId] : held+}++/** A pending id this guest may still spawn its own terminal for: introduced here, and no OTHER+ * project has taken the id since (a git pull can put it in one). */+function pendingHere(id: unknown, s: Scope): id is string {+ return (+ typeof id === 'string' &&+ s.introduced.get(id) === 'pending' &&+ s.deps.projectsOfNode(id).every((p) => p === s.projectId)+ )}+/**+ * The alphabet a guest-introduced node id may use: the ids the app itself mints (`nextId`,+ * `uuid()`), never a character `sessionName` rewrites. `nt-` + id is then the session name with no+ * substitution, so two different ids cannot name one tmux session (`a.b` and `a_b` both map to+ * `nt-a_b`). Ids that already exist in a project are not judged by it.+ */+const INTRODUCIBLE_ID = /^[A-Za-z0-9-]{1,128}$/+/** A node is in scope only when EVERY project holding its id is the shared one: node ids travel in* git-shared project files, so an id copied into another project must not ride this session. */export function nodeInScope(id: unknown, s: Scope): boolean {@@ -254,7 +303,12 @@ const ptyCreate: Check = (a, s) => {const o = a[0]if (!o || typeof o !== 'object' || Array.isArray(o)) return no(NODE_OUTSIDE)const opts = { ...(o as Record<string, unknown>) }- if (!nodeInScope(opts.persistKey, s)) return no(NODE_OUTSIDE)+ // A node this guest introduced and has not yet proven: the create may only SPAWN a fresh session+ // (`newOnly`: core refuses a join, a reattach and any session that already exists under that+ // name). Its response, read in `noteCreate`, is what promotes the id to `created`.+ const pending = pendingHere(opts.persistKey, s)+ if (!pending && !nodeInScope(opts.persistKey, s)) return no(NODE_OUTSIDE)+ if (pending) opts.newOnly = trueif (opts.ownerProjectId !== undefined && opts.ownerProjectId !== s.projectId) return no(OUTSIDE)delete opts.sshRemote// The local-login exemption from the SSH-project refusal is this machine's own UI's mark, never@@ -286,8 +340,12 @@ const canvasMut: Check = (a, s) => {const id = mut.op === 'remove' ? mut.id : mut.node?.idif (typeof id !== 'string' || !id) return no(OUTSIDE)if (nodeInScope(id, s)) return OK- if (mut.op === 'upsert' && s.deps.projectsOfNode(id).length === 0) {- s.newNodes.add(id)+ // Its own new node, still pending: moving or removing it is a canvas edit like any other.+ if (pendingHere(id, s)) return OK+ if (mut.op === 'upsert' && s.deps.projectsOfNode(id).length === 0 && !s.introduced.has(id)) {+ if (!INTRODUCIBLE_ID.test(id)) return no(NODE_OUTSIDE)+ if (s.introduced.size >= INTRODUCED_MAX) return no(TOO_MANY_NEW)+ s.introduced.set(id, 'pending')return OK}return no(NODE_OUTSIDE)@@ -525,10 +583,25 @@ function makeScope(projectId: string, deps: ScopedGuestDeps): Scope {return {projectId,deps: { ...deps, realpath: deps.realpath ?? defaultRealpath, lexists: deps.lexists ?? defaultLexists },- newNodes: new Set()+ introduced: new Map()}}+/**+ * A `pty:create` this session asked for came back. Promote its node from pending to created only on+ * the core's own word that it SPAWNED the session: `fresh: true`, no `unavailable`, no+ * `freshUnverified`, and a session id the pty manager maps to that node. Anything else (a refusal,+ * a join, a guess) leaves it pending. Exported for the test.+ */+export function noteCreate(result: unknown, s: Scope): void {+ if (result === null || typeof result !== 'object') return+ const r = result as { sessionId?: unknown; fresh?: unknown; unavailable?: unknown; freshUnverified?: unknown }+ if (r.fresh !== true || r.unavailable !== undefined || r.freshUnverified === true) return+ if (typeof r.sessionId !== 'string' || !r.sessionId) return+ const node = s.deps.nodeOfSession(r.sessionId)+ if (node !== undefined && pendingHere(node, s)) s.introduced.set(node, 'created')+}+function decideWith(method: string, args: unknown[], s: Scope): AccessDecision {if (typeof method !== 'string' || !Object.hasOwn(SCOPED, method)) return no(NOT_SCOPED)return SCOPED[method](Array.isArray(args) ? args : [], s)@@ -617,7 +690,10 @@ export function scopedGuestHooks(projectId: string, deps: ScopedGuestDeps): RelabufferedAmount: () => sink.bufferedAmount?.() ?? 0}},- narrowResponse: (_session, method, result) => narrowResponseForRole(method, result, viewCtx(s))+ narrowResponse: (_session, method, result) => {+ if (method === IPC.ptyCreate) noteCreate(result, s)+ return narrowResponseForRole(method, result, viewCtx(s))+ }}}diff --git a/src/core/remote-ssh/control-master.injection.test.ts b/src/core/remote-ssh/control-master.injection.test.tsindex 2960c6267..72c57b27e 100644--- a/src/core/remote-ssh/control-master.injection.test.ts+++ b/src/core/remote-ssh/control-master.injection.test.ts@@ -257,7 +257,7 @@ describe('remotePaneOwnerCombinedArgs: one script, every splice accounted for',// The CONSTANT, not a copy of it — "verbatim" is the property under test, so it is compared// against the thing the local leg actually sends, quoted so the remote shell hands tmux the// string rather than parsing its metacharacters ({, }, |).- expect(script).toContain(`display-message -p -t nt-n1 '${PANE_OWNER_FMT}'`)+ expect(script).toContain(`display-message -p -t '=nt-n1:' '${PANE_OWNER_FMT}'`)expect(PANE_OWNER_FMT).toMatch(/[{}|]/)})diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex cd2bf788a..647cbb404 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -190,14 +190,14 @@ describe('remoteTmuxPasteArgs', () => {...childPrefix,`${TP}${TMUX} load-buffer -b ${BUF} - ';' ` +- `if-shell -F -t nt-x '#{pane_in_mode}' 'send-keys -t nt-x -X cancel' ';' ` +- `paste-buffer -d -p -r -b ${BUF} -t nt-x ';' send-keys -t nt-x Enter`+ `if-shell -F -t '=nt-x:' '#{pane_in_mode}' 'send-keys -t =nt-x: -X cancel' ';' ` ++ `paste-buffer -d -p -r -b ${BUF} -t '=nt-x:' ';' send-keys -t '=nt-x:' Enter`])})it('omits the Enter for a dictation insert (enter:false)', () => {- expect(cmd('nt-x', false)).not.toContain('send-keys -t nt-x Enter')- expect(cmd('nt-x', false).endsWith(`paste-buffer -d -p -r -b ${BUF} -t nt-x`)).toBe(true)+ expect(cmd('nt-x', false)).not.toContain('Enter')+ expect(cmd('nt-x', false).endsWith(`paste-buffer -d -p -r -b ${BUF} -t '=nt-x:'`)).toBe(true)})// The rule this PR is here to enforce: the payload is not on the command line at all, so there@@ -205,7 +205,7 @@ describe('remoteTmuxPasteArgs', () => {it('carries NO payload — the text reaches the remote tmux over stdin', () => {const line = cmd('nt-x', true)expect(line).toContain(`load-buffer -b ${BUF} -`)- expect(line).not.toContain('send-keys -t nt-x -l')+ expect(line).not.toContain(' -l')expect(line).not.toContain('set-buffer')})@@ -229,7 +229,7 @@ describe('remoteTmuxPasteArgs', () => {// as one tmux argument. Both are single-quoted, and `control-master.realsh.test.ts`'s sibling// (`tmux-paste.realtmux.test.ts`) runs this very line through a real sh into a real tmux.it('quotes the format and the inner command so the remote shell passes them through', () => {- expect(cmd('nt-x', true)).toContain(`if-shell -F -t nt-x '#{pane_in_mode}' 'send-keys -t nt-x -X cancel'`)+ expect(cmd('nt-x', true)).toContain(`if-shell -F -t '=nt-x:' '#{pane_in_mode}' 'send-keys -t =nt-x: -X cancel'`)})it('refuses a session id this app did not generate — it is spliced unquoted', () => {@@ -250,7 +250,7 @@ describe('remoteTmuxEnterArgs', () => {expect(remoteTmuxEnterArgs(conn, '/s.sock', 'nt-x')).toEqual([...childPrefix,- `${TP}tmux -L ${RMT_TMUX_SOCKET} send-keys -t nt-x Enter`+ `${TP}tmux -L ${RMT_TMUX_SOCKET} send-keys -t '=nt-x:' Enter`])})})@@ -258,11 +258,11 @@ describe('remoteTmuxEnterArgs', () => {describe('remoteCapturePaneArgs', () => {it('captures the whole scrollback (-S -) when full', () => {const args = remoteCapturePaneArgs(conn, '/s.sock', 'nt-x', true)- expect(args[args.length - 1]).toBe(`${TP}tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t nt-x -S -`)+ expect(args[args.length - 1]).toBe(`${TP}tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t '=nt-x:' -S -`)})it('captures the recent ~200 lines (-S -200) when not full', () => {const args = remoteCapturePaneArgs(conn, '/s.sock', 'nt-x', false)- expect(args[args.length - 1]).toBe(`${TP}tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t nt-x -S -200`)+ expect(args[args.length - 1]).toBe(`${TP}tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t '=nt-x:' -S -200`)})})@@ -316,7 +316,7 @@ describe('remotePaneCommandArgs', () => {it('asks the remote tmux for the pane_current_command of the session', () => {const args = remotePaneCommandArgs(conn, '/s.sock', 'nt-x')expect(args[args.length - 1]).toBe(- `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t nt-x '#{pane_current_command}'`+ `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '=nt-x:' '#{pane_current_command}'`)})})@@ -325,7 +325,7 @@ describe('remotePaneCwdArgs', () => {it('asks the remote tmux for the pane_current_path of the session', () => {const args = remotePaneCwdArgs(conn, '/s.sock', 'nt-x')expect(args[args.length - 1]).toBe(- `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t nt-x '#{pane_current_path}'`+ `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '=nt-x:' '#{pane_current_path}'`)})})@@ -334,7 +334,7 @@ describe('remote foreground process termination', () => {it('reads pane pid + command through the existing ControlMaster', () => {const args = remotePaneProcessArgs(conn, '/s.sock', 'nt-x')expect(args[args.length - 1]).toBe(- `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t nt-x '#{pane_pid}|#{pane_current_command}'`+ `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '=nt-x:' '#{pane_pid}|#{pane_current_command}'`)})@@ -619,7 +619,7 @@ describe('killing a session by name (both sockets, exact target)', () => {expect(localTmuxKillArgs('node-terminal', 'nt-a-1')).toEqual(['-L', 'node-terminal', 'kill-session', '-t', '=nt-a-1'])- expect(remoteTmuxKillArgs(conn, '/s.sock', 'nt-a-1').at(-1)).toContain('-t =nt-a-1')+ expect(remoteTmuxKillArgs(conn, '/s.sock', 'nt-a-1').at(-1)).toContain("-t '=nt-a-1'")})it('aims a local destroy at the socket we hold, whatever the caller asked for', () => {@@ -639,10 +639,10 @@ describe('killing a session by name (both sockets, exact target)', () => {it('keeps the remote default on the ssh socket, and overrides it explicitly', () => {expect(remoteTmuxKillArgs(conn, '/s.sock', 'nt-x').at(-1)).toBe(- `${TP}tmux -L ${RMT_TMUX_SOCKET} kill-session -t =nt-x`+ `${TP}tmux -L ${RMT_TMUX_SOCKET} kill-session -t '=nt-x'`)expect(remoteTmuxKillArgs(conn, '/s.sock', 'nt-x', 'node-terminal').at(-1)).toBe(- `${TP}tmux -L node-terminal kill-session -t =nt-x`+ `${TP}tmux -L node-terminal kill-session -t '=nt-x'`)})@@ -650,8 +650,8 @@ describe('killing a session by name (both sockets, exact target)', () => {const runs = remoteTmuxKillEverySocketArgs(conn, '/s.sock', 'nt-x')expect(runs).toHaveLength(2)expect(runs.map((r) => r.at(-1)).sort()).toEqual([- `${TP}tmux -L node-terminal kill-session -t =nt-x`,- `${TP}tmux -L ${RMT_TMUX_SOCKET} kill-session -t =nt-x`+ `${TP}tmux -L node-terminal kill-session -t '=nt-x'`,+ `${TP}tmux -L ${RMT_TMUX_SOCKET} kill-session -t '=nt-x'`])// Each is a complete child-ssh argv, not a bare command.for (const r of runs) expect(r.slice(0, childPrefix.length)).toEqual(childPrefix)diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 83e33aec1..6e2ce1624 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -14,6 +14,7 @@ import {TMUX_SOCKET,assertPasteTarget,assertPasteBuffer,+ exactPaneTarget,pasteBufferName,type PasteDelivery} from '../tmux-naming'@@ -342,11 +343,16 @@ export function remoteTmuxPasteArgs(): string[] {assertPasteTarget(sessionId, buffer)const tmux = `tmux -L ${RMT_TMUX_SOCKET}`+ // EXACT target (`exactPaneTarget`): a bare name prefix-matches a longer session on a miss.+ // Quoted for the remote shell where it is a word of its own (zsh expands a leading `=`); inside+ // the single-quoted `if-shell` body tmux's own lexer reads it.+ const pane = exactPaneTarget(sessionId)+ const t = posixQuote(pane)let cmd =`${tmux} load-buffer -b ${buffer} - ';' ` +- `if-shell -F -t ${sessionId} '#{pane_in_mode}' 'send-keys -t ${sessionId} -X cancel' ';' ` +- `paste-buffer -d -p -r -b ${buffer} -t ${sessionId}`- if (enter) cmd += ` ';' send-keys -t ${sessionId} Enter`+ `if-shell -F -t ${t} '#{pane_in_mode}' 'send-keys -t ${pane} -X cancel' ';' ` ++ `paste-buffer -d -p -r -b ${buffer} -t ${t}`+ if (enter) cmd += ` ';' send-keys -t ${t} Enter`return childArgs(conn, controlPath, tmuxCmd(cmd))}@@ -400,7 +406,11 @@ export function remoteTmuxEnterArgs(sessionId: string): string[] {assertPasteTarget(sessionId)- return childArgs(conn, controlPath, tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} send-keys -t ${sessionId} Enter`))+ return childArgs(+ conn,+ controlPath,+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} send-keys -t ${posixQuote(exactPaneTarget(sessionId))} Enter`)+ )}/** `delete-buffer` on the REMOTE server — the sweep for a remote paste that never ran. */@@ -514,7 +524,8 @@ export function remoteTmuxKillArgs(sessionId: string,socket: string = RMT_TMUX_SOCKET): string[] {- return childArgs(conn, controlPath, tmuxCmd(`tmux -L ${socket} kill-session -t ${exactTarget(sessionId)}`))+ // Quoted: on a zsh login shell an unquoted word starting with `=` is a command-path lookup.+ return childArgs(conn, controlPath, tmuxCmd(`tmux -L ${socket} kill-session -t ${posixQuote(exactTarget(sessionId))}`))}/**@@ -538,7 +549,7 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,return childArgs(conn,controlPath,- tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S ${full ? '-' : '-200'}`)+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${posixQuote(exactPaneTarget(sessionId))} -S ${full ? '-' : '-200'}`))}/**@@ -649,7 +660,7 @@ export function remotePaneCommandArgs(conn: SshConnection, controlPath: string,return childArgs(conn,controlPath,- tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_current_command}'`)+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${posixQuote(exactPaneTarget(sessionId))} '#{pane_current_command}'`))}@@ -669,7 +680,7 @@ export function remoteSendKeyArgs(return childArgs(conn,controlPath,- tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} send-keys -t ${sessionId} ${keyArgs.join(' ')}`)+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} send-keys -t ${posixQuote(exactPaneTarget(sessionId))} ${keyArgs.join(' ')}`))}@@ -678,7 +689,7 @@ export function remotePaneCwdArgs(conn: SshConnection, controlPath: string, sessreturn childArgs(conn,controlPath,- tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_current_path}'`)+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${posixQuote(exactPaneTarget(sessionId))} '#{pane_current_path}'`))}@@ -691,7 +702,7 @@ export function remotePaneProcessArgs(return childArgs(conn,controlPath,- tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_pid}|#{pane_current_command}'`)+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${posixQuote(exactPaneTarget(sessionId))} '#{pane_pid}|#{pane_current_command}'`))}@@ -758,7 +769,7 @@ export function remotePaneOwnerCombinedArgs(assertPasteTarget(sessionId)const ps = PS_FOREGROUND_FLAGS.join(' ')const script =- `o=$(${tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '${PANE_OWNER_FMT}'`)}) || exit 9; ` ++ `o=$(${tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${posixQuote(exactPaneTarget(sessionId))} '${PANE_OWNER_FMT}'`)}) || exit 9; ` +`printf '%s\\n' "${COMBINED_PANE_MARKER.trimEnd()} $o"; ` +'tty=${o#*|}; tty=${tty%%|*}; ' +`case "$tty" in /dev/*) ps ${ps} -t "$tty" 2>/dev/null || : ;; esac`@@ -789,7 +800,7 @@ export function remotePaneCursorArgs(return childArgs(conn,controlPath,- tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{cursor_x} #{cursor_y} #{cursor_flag}'`)+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${posixQuote(exactPaneTarget(sessionId))} '#{cursor_x} #{cursor_y} #{cursor_flag}'`))}export function tmuxProbeArgs(conn: SshConnection, controlPath: string): string[] {diff --git a/src/core/tmux-control-client.test.ts b/src/core/tmux-control-client.test.tsindex 2443b88ca..44e33fc07 100644--- a/src/core/tmux-control-client.test.ts+++ b/src/core/tmux-control-client.test.ts@@ -83,7 +83,7 @@ describe('ControlModeClient.start', () => {expect(spawner.calls).toEqual([{bin: '/opt/homebrew/bin/tmux',- args: ['-L', 'node-terminal', '-C', 'attach-session', '-t', 'nt-term-1']+ args: ['-L', 'node-terminal', '-C', 'attach-session', '-t', '=nt-term-1']}])})@@ -129,7 +129,7 @@ describe('ControlModeClient.sendKeys', () => {it('writes the hex send-keys line and resolves true on an ok reply', async () => {const { client, child } = makeClient()const p = client.sendKeys('ls\n')- expect(child.writes).toEqual(['send-keys -t nt-term-1 -H 6c 73 0a\n'])+ expect(child.writes).toEqual(['send-keys -t =nt-term-1: -H 6c 73 0a\n'])child.feed(reply(1))await expect(p).resolves.toBe(true)})@@ -142,7 +142,7 @@ describe('ControlModeClient.sendKeys', () => {it('can target another session on the same server', async () => {const { client, child } = makeClient()const p = client.sendKeys('x', 'nt-term-9')- expect(child.writes).toEqual(['send-keys -t nt-term-9 -H 78\n'])+ expect(child.writes).toEqual(['send-keys -t =nt-term-9: -H 78\n'])child.feed(reply(1))await expect(p).resolves.toBe(true)})diff --git a/src/core/tmux-control-client.ts b/src/core/tmux-control-client.tsindex c517d714e..634283776 100644--- a/src/core/tmux-control-client.ts+++ b/src/core/tmux-control-client.ts@@ -9,6 +9,7 @@import { spawn as nodeSpawn } from 'child_process'import { StringDecoder } from 'string_decoder'import { createControlDecoder, encodeSendKeysHex, type ControlEvent } from './tmux-control'+import { exactSessionTarget } from './tmux-naming'/*** The child-process seam. Deliberately the smallest surface the client needs — stdout is handed over@@ -101,7 +102,8 @@ export class ControlModeClient {/** Attach: `tmux -L <socket> -C attach-session -t <session>`. Calling twice is a no-op. */start(): void {if (this.proc || this.disposed) return- const args = ['-L', this.opts.socket, '-C', 'attach-session', '-t', this.opts.sessionName]+ // Exact (`=name`): a bare name prefix-matches a longer session when this one is gone.+ const args = ['-L', this.opts.socket, '-C', 'attach-session', '-t', exactSessionTarget(this.opts.sessionName)]this.proc = this.spawner.spawn(this.opts.tmuxBin, args)this.proc.stdout.on('data', (b) => this.onChunk(b))this.proc.on('exit', () => this.die('control-mode client exited'))diff --git a/src/core/tmux-control.test.ts b/src/core/tmux-control.test.tsindex 60642e827..331fca8b0 100644--- a/src/core/tmux-control.test.ts+++ b/src/core/tmux-control.test.ts@@ -61,10 +61,17 @@ describe('createControlDecoder', () => {})describe('encodeSendKeysHex', () => {- it('encodes bytes as hex send-keys arguments', () => {- expect(encodeSendKeysHex('nt-term-1', 'ls\n')).toBe('send-keys -t nt-term-1 -H 6c 73 0a')+ it('encodes bytes as hex send-keys arguments, on the EXACT target', () => {+ expect(encodeSendKeysHex('nt-term-1', 'ls\n')).toBe('send-keys -t =nt-term-1: -H 6c 73 0a')})it('encodes multi-byte UTF-8 per byte', () => {- expect(encodeSendKeysHex('s', 'ç')).toBe('send-keys -t s -H c3 a7')+ expect(encodeSendKeysHex('nt-s', 'ç')).toBe('send-keys -t =nt-s: -H c3 a7')+ })+ // The target is spliced UNQUOTED into a control-mode line, and a bare name prefix-matches a+ // longer session: a name this app did not generate is refused, never sent.+ it('refuses a target that is not one of our session names', () => {+ for (const bad of ['s', 'nt-', 'nt-a b', 'nt-a;kill-server', '=nt-a:']) {+ expect(() => encodeSendKeysHex(bad, 'x'), bad).toThrow()+ }})})diff --git a/src/core/tmux-control.ts b/src/core/tmux-control.tsindex b2118b72a..4c806a45c 100644--- a/src/core/tmux-control.ts+++ b/src/core/tmux-control.ts@@ -12,6 +12,8 @@// and is unrecoverable). Latin1 is lossless byte↔char, which is what makes `decodeOctal`'s// byte-per-char output re-assemblable into correct UTF-8 downstream.+import { exactPaneTarget } from './tmux-naming'+export type ControlEvent =| { kind: 'output'; paneId: string; data: string }| { kind: 'reply'; num: number; ok: boolean; body: string[] }@@ -34,13 +36,15 @@ export function decodeOctal(s: string): string {}/**- * A `send-keys` command line that types `data` into `target`. Hex (`-H`) because a control-mode- * command must fit on ONE text line: it sidesteps every quoting/UTF-8 hazard that `-l` literal mode- * would need shell-grade escaping for.+ * A `send-keys` command line that types `data` into the session NAMED `target`. Hex (`-H`) because a+ * control-mode command must fit on ONE text line: it sidesteps every quoting/UTF-8 hazard that `-l`+ * literal mode would need shell-grade escaping for. The target is the EXACT form (`=name:`,+ * tmux-naming.ts `exactPaneTarget`, which also refuses a name this app did not generate): a bare+ * name prefix-matches a longer session on a miss.*/export function encodeSendKeysHex(target: string, data: string): string {const bytes = [...Buffer.from(data, 'utf8')].map((b) => b.toString(16).padStart(2, '0'))- return `send-keys -t ${target} -H ${bytes.join(' ')}`+ return `send-keys -t ${exactPaneTarget(target)} -H ${bytes.join(' ')}`}/**diff --git a/src/core/tmux-naming.test.ts b/src/core/tmux-naming.test.tsindex 56be50659..3e0d56a03 100644--- a/src/core/tmux-naming.test.ts+++ b/src/core/tmux-naming.test.ts@@ -5,6 +5,8 @@ import {pasteBufferName,sessionName,isSessionName,+ exactPaneTarget,+ exactSessionTarget,TMUX_SOCKET} from './tmux-naming'@@ -27,7 +29,7 @@ describe('localTmuxEnterArgs', () => {'sock','send-keys','-t',- 'nt-x',+ '=nt-x:','Enter'])expect(localTmuxEnterArgs(TMUX_SOCKET, 'nt-x')).not.toContain('-l')@@ -45,9 +47,9 @@ describe('localTmuxPasteArgs', () => {expect(localTmuxPasteArgs('sock', 'nt-x', BUF, true)).toEqual(['-L', 'sock','load-buffer', '-b', BUF, '-',- ';', 'if-shell', '-F', '-t', 'nt-x', '#{pane_in_mode}', 'send-keys -t nt-x -X cancel',- ';', 'paste-buffer', '-d', '-p', '-r', '-b', BUF, '-t', 'nt-x',- ';', 'send-keys', '-t', 'nt-x', 'Enter'+ ';', 'if-shell', '-F', '-t', '=nt-x:', '#{pane_in_mode}', 'send-keys -t =nt-x: -X cancel',+ ';', 'paste-buffer', '-d', '-p', '-r', '-b', BUF, '-t', '=nt-x:',+ ';', 'send-keys', '-t', '=nt-x:', 'Enter'])})@@ -91,3 +93,26 @@ describe('localTmuxPasteArgs', () => {// the messaging envelope now rides `localPasteDelivery` (enter=true) like every other write —// tmux ≥ 3.7 passes paste-buffer content through vis(3), so a payload-carried frame cannot// arrive as escapes. See the tombstone in tmux-naming.ts.++/**+ * The exact targets every node-keyed tmux verb uses (security audit F1/F2). A bare `-t nt-x-1` whose+ * session is gone reaches a live `nt-x-12`; `pty-exact-target.realtmux.test.ts` measures that on a+ * real tmux. Here: the spelling, and the refusal of anything this app did not generate.+ */+describe('exactPaneTarget / exactSessionTarget', () => {+ it('spells the exact pane and session forms', () => {+ expect(exactPaneTarget('nt-term-abc-1')).toBe('=nt-term-abc-1:')+ expect(exactSessionTarget('nt-term-abc-1')).toBe('=nt-term-abc-1')+ expect(exactPaneTarget(sessionName('a.b'))).toBe('=nt-a_b:')+ })+ it('refuses a name that did not come from sessionName — it is spliced unquoted', () => {+ for (const bad of ['', 'nt-', 'x', 'nt-a b', 'nt-a;kill-server', 'nt-a\nx', '=nt-a:', 'nt-a:0']) {+ expect(() => exactPaneTarget(bad), JSON.stringify(bad)).toThrow()+ expect(() => exactSessionTarget(bad), JSON.stringify(bad)).toThrow()+ }+ })+ it('every builder that names a pane uses the exact form', () => {+ expect(localTmuxEnterArgs('sock', 'nt-x')).not.toContain('nt-x')+ expect(localTmuxPasteArgs('sock', 'nt-x', 'nt-paste-ab', true).filter((a) => a === 'nt-x')).toEqual([])+ })+})diff --git a/src/core/tmux-naming.ts b/src/core/tmux-naming.tsindex 98b5a6afa..815ba571c 100644--- a/src/core/tmux-naming.ts+++ b/src/core/tmux-naming.ts@@ -26,6 +26,41 @@ export function isSessionName(target: string): boolean {return /^nt-[A-Za-z0-9_-]+$/.test(target)}+/**+ * ── EXACT TARGETS: every node id that becomes a tmux `-t` goes through one of these two ─────────+ *+ * tmux resolves a BARE target by exact name, then fnmatch, then PREFIX on a miss. Node ids end in a+ * counter or a random tail, so `nt-x-1` is a prefix of `nt-x-12`: a bare `-t nt-x-1` whose own+ * session is gone (or never existed) reaches the LONGER, unrelated session. Measured on tmux 3.4+ * with only `nt-term-abc-12` alive:+ * display-message -p -t nt-term-abc-1 '#{session_name}' → nt-term-abc-12, exit 0 (the trap)+ * has-session -t nt-term-abc-1 → exit 0 (the trap)+ * send-keys / capture-pane / paste-buffer -t =nt-term-abc-1: → "can't find session", exit 1+ * display-message -p -t =nt-term-abc-1: '<fmt>' → exit 0, every format EMPTY+ * so a miss is a failed command, or an empty read that every parser here answers null for. A relay+ * peer that could name a PREFIX of another project's node id reached that terminal through every+ * node-keyed pty verb (security audit F1/F2, 2026-10).+ *+ * For an EXISTING session `=name:` resolves exactly like the bare name did: the session's current+ * window, its active pane (re-measured with three windows and a split, the selection moved between+ * reads — `pty-exact-target.realtmux.test.ts`).+ *+ * Both throw for a name this app did not generate: the result is spliced UNQUOTED into tmux command+ * text (`if-shell` bodies, control-mode lines). On a REMOTE command line it must still be+ * single-quoted (`posixQuote`): zsh's EQUALS option expands a word that STARTS with `=` as a command+ * path (`=nt-x:` → "nt-x: not found").+ */+export function exactPaneTarget(session: string): string {+ if (!isSessionName(session)) throw new Error(`not a session name of ours: ${JSON.stringify(session)}`)+ return `=${session}:`+}++/** The session-target form (`has-session`, `attach-session`, `kill-session`): `=name`, exact. */+export function exactSessionTarget(session: string): string {+ if (!isSessionName(session)) throw new Error(`not a session name of ours: ${JSON.stringify(session)}`)+ return `=${session}`+}+/*** ── DELETED: `localTmuxSendKeysArgs` ────────────────────────────────────────────────────────────*@@ -56,7 +91,7 @@ export function isSessionName(target: string): boolean {*/export function localTmuxEnterArgs(socket: string, target: string): string[] {assertPasteTarget(target)- return ['-L', socket, 'send-keys', '-t', target, 'Enter']+ return ['-L', socket, 'send-keys', '-t', exactPaneTarget(target), 'Enter']}/**@@ -143,6 +178,9 @@ export function localTmuxPasteArgs(enter: boolean): string[] {assertPasteTarget(target, buffer)+ // `target` is the session NAME (asserted above); tmux is handed the EXACT form, never the bare+ // name, which prefix-matches a longer session on a miss (see `exactPaneTarget`).+ const t = exactPaneTarget(target)const args = ['-L',socket,@@ -155,9 +193,9 @@ export function localTmuxPasteArgs('if-shell','-F','-t',- target,+ t,'#{pane_in_mode}',- `send-keys -t ${target} -X cancel`,+ `send-keys -t ${t} -X cancel`,';',// -d: drop our private buffer afterwards, so the user's paste stack is untouched// -p: tmux decides framing from the pane's REAL bracketed-paste state@@ -169,12 +207,12 @@ export function localTmuxPasteArgs('-b',buffer,'-t',- target+ t]// Same invocation as the paste, so the Enter can never be re-chunked into it — and, because// tmux aborts a command list at the first failure, a paste that did not happen can never leave// a lone Enter behind to submit whatever the human had composed.- if (enter) args.push(';', 'send-keys', '-t', target, 'Enter')+ if (enter) args.push(';', 'send-keys', '-t', t, 'Enter')return args}diff --git a/src/core/tmux-socket-isolation.guard.test.ts b/src/core/tmux-socket-isolation.guard.test.tsindex ec709ac54..d48c7f96f 100644--- a/src/core/tmux-socket-isolation.guard.test.ts+++ b/src/core/tmux-socket-isolation.guard.test.ts@@ -104,6 +104,11 @@ const REAL_SOCKET_ALLOWED = new Map<string, string>(['src/main/remote/host-destroy-tmux.test.ts','PtyManager binds TMUX_SOCKET itself, so the verb can only be measured on that name'],+ [+ 'src/core/pty-exact-target.realtmux.test.ts',+ 'drives a real PtyManager (which binds TMUX_SOCKET itself) to prove every node-keyed verb uses an ' ++ 'exact target; its own per-run unique nt-sxt<pid>… sessions, killed by exact target, never the server'+ ],['test/server/canvas-control-boot-e2e.test.ts','boots a real Server Edition, whose PtyManager binds TMUX_SOCKET itself: the assertion is that ' +diff --git a/src/core/typed-input.ts b/src/core/typed-input.tsindex 53551b217..3889d0b99 100644--- a/src/core/typed-input.ts+++ b/src/core/typed-input.ts@@ -1,5 +1,5 @@import type { TextDeliveryResult } from '../shared/text-delivery'-import { assertPasteTarget } from './tmux-naming'+import { assertPasteTarget, exactPaneTarget } from './tmux-naming'import { ENVELOPE_SETTLE_POLLS, ENVELOPE_SETTLE_POLL_MS, type SettleOptions } from './settled-submit'/**@@ -58,15 +58,21 @@ export function typedInputScript(tmux: string, socket: string, target: string, bassertPasteTarget(target, buffer)if (!/^[A-Za-z0-9._-]+$/.test(socket)) throw new Error(`unsafe tmux socket: ${JSON.stringify(socket)}`)const t = `${tmux} -L ${socket}`+ // The EXACT target (tmux-naming.ts `exactPaneTarget`): a bare name prefix-matches a longer session+ // on a miss. Single-quoted for the shell (`sh -c` here, and the same text runs on an SSH host): a+ // word starting with `=` is a command lookup under zsh's EQUALS option. Inside the `if-shell` body+ // (already single-quoted for the shell) tmux's own lexer reads it unquoted.+ const pane = exactPaneTarget(target)+ const q = `'${pane}'`return [// Leave copy mode first, like the paste path: keys typed into copy mode drive IT, not the app.- `${t} if-shell -F -t ${target} '#{pane_in_mode}' 'send-keys -t ${target} -X cancel' || exit 1`,+ `${t} if-shell -F -t ${q} '#{pane_in_mode}' 'send-keys -t ${pane} -X cancel' || exit 1`,'first=1','while IFS= read -r line; do',- ` if [ "$first" = 1 ]; then first=0; else ${t} send-keys -t ${target} M-Enter || exit 1; fi`,+ ` if [ "$first" = 1 ]; then first=0; else ${t} send-keys -t ${q} M-Enter || exit 1; fi`,' if [ -n "$line" ]; then',` printf '%s' "$line" | ${t} load-buffer -b ${buffer} - || exit 1`,- ` ${t} paste-buffer -d -r -b ${buffer} -t ${target} || { ${t} delete-buffer -b ${buffer} 2>/dev/null; exit 1; }`,+ ` ${t} paste-buffer -d -r -b ${buffer} -t ${q} || { ${t} delete-buffer -b ${buffer} 2>/dev/null; exit 1; }`,' fi','done'].join('\n')diff --git a/src/core/watch-link/pane-input.ts b/src/core/watch-link/pane-input.tsindex bb8ef3ae3..21d6fe622 100644--- a/src/core/watch-link/pane-input.ts+++ b/src/core/watch-link/pane-input.ts@@ -78,7 +78,7 @@ import { posixQuote } from '../../shared/ssh'import { sanitizePasteText } from '../paste-injection'import {assertPasteBuffer,- isSessionName,+ exactPaneTarget,localTmuxDeleteBufferArgs,pasteBufferName,type PasteDelivery@@ -118,12 +118,10 @@ export const KEYS_PER_COMMAND = 1024* "Exactly this session, its active pane". Node ids end in a counter, so `nt-a-1` is a prefix of* `nt-a-12`, and tmux resolves a bare target by prefix on a miss: a bare target would type into* ANOTHER node. `=name:` is exact and resolves (capture-route.ts has the measurement). Throws for a- * name this app did not generate: the target is spliced UNQUOTED into tmux command text.+ * name this app did not generate: the target is spliced UNQUOTED into tmux command text. ONE+ * definition (tmux-naming.ts), shared with every other node-keyed tmux verb.*/-export function exactPaneTarget(session: string): string {- if (!isSessionName(session)) throw new Error(`not a session name of ours: ${JSON.stringify(session)}`)- return `=${session}:`-}+export { exactPaneTarget }/** The stdin of `tmux source-file -`: leave any mode, then type each byte literally. */export function keysCommandText(session: string, data: string): string {diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex d6a28d0ac..df1bcf7aa 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -3713,7 +3713,9 @@ export function TerminalNode({// "Refresh terminal" re-asks on demand. `held-elsewhere` is the same shape: core found// this remote node's id held by a session that is not on its host and did not join it —// nothing is offline, and "Try again" would refuse again while that session runs.- if (unavailable === 'join-only' || unavailable === 'held-elsewhere') {+ // `new-only` too: a relay guest's create for a node it added found a session already+ // running under that name and was refused (core/relay/scoped-guest-policy.ts).+ if (unavailable === 'join-only' || unavailable === 'held-elsewhere' || unavailable === 'new-only') {setCo(termKey, {offline: false,spawnError: null,diff --git a/src/renderer/nodes/join-only-refusal-wiring.test.ts b/src/renderer/nodes/join-only-refusal-wiring.test.tsindex b8e9d20ef..f67773699 100644--- a/src/renderer/nodes/join-only-refusal-wiring.test.ts+++ b/src/renderer/nodes/join-only-refusal-wiring.test.ts@@ -17,7 +17,7 @@ const src = fs.readFileSync(path.resolve(__dirname, 'TerminalNode.tsx'), 'utf8')/** The body of the `'join-only'` / `'held-elsewhere'` branch, up to its `return`. */function joinOnlyBranch(): string {- const start = src.indexOf("if (unavailable === 'join-only' || unavailable === 'held-elsewhere') {")+ const start = src.indexOf("if (unavailable === 'join-only' || unavailable === 'held-elsewhere' || unavailable === 'new-only') {")expect(start, 'the join-only branch must still exist').toBeGreaterThan(-1)const end = src.indexOf('return', start)expect(end).toBeGreaterThan(start)diff --git a/src/shared/pty-refusal.test.ts b/src/shared/pty-refusal.test.tsindex 1063e866e..f89d886da 100644--- a/src/shared/pty-refusal.test.ts+++ b/src/shared/pty-refusal.test.ts@@ -32,4 +32,13 @@ describe('PTY refusal presentation', () => {"a session with this terminal's id is already running somewhere other than its host, so it was not joined — nothing was started"})})+ // A relay guest's create for a node it added found a session already running under that name. The+ // project is healthy: read as `connectionLost` the node would show "not connected" and retry into+ // the same refusal.+ it('a new-only refusal is not a lost connection, and says nothing was joined or started', () => {+ expect(ptyRefusal('new-only')).toEqual({+ connectionLost: false,+ message: "a session with this terminal's id already exists on the host, so it was not joined — nothing was started"+ })+ })})diff --git a/src/shared/pty-refusal.ts b/src/shared/pty-refusal.tsindex d75655562..d3b6324a9 100644--- a/src/shared/pty-refusal.ts+++ b/src/shared/pty-refusal.ts@@ -32,5 +32,15 @@ export function ptyRefusal(unavailable: NonNullable<PtyCreateResult['unavailableconnectionLost: false}}+ // A relay guest's create for a node it added itself found a session already running under that+ // node's name (or could not check). Joining it would hand the guest a terminal it did not start;+ // nothing is offline, and retrying refuses again while that session runs.+ if (unavailable === 'new-only') {+ return {+ message:+ "a session with this terminal's id already exists on the host, so it was not joined — nothing was started",+ connectionLost: false+ }+ }return { message: 'not connected — nothing was started locally', connectionLost: true }}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 700292504..78edece5a 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -230,6 +230,15 @@ export interface PtyCreateOptions {* proceeds. Set only by the relay access policy (src/core/relay/access-policy.ts).*/joinOnly?: boolean+ /**+ * The opposite of `joinOnly`: this create may only SPAWN a brand-new session. A co-attach join, a+ * reattach to a live tmux / session-host / Zellij session under this node's name, and a create+ * whose existence probe cannot answer are all refused (`unavailable: 'new-only'`), so the caller's+ * `fresh: true` means "this create made the session". Set only by the relay scoped-guest policy+ * (src/core/relay/scoped-guest-policy.ts) for a node id the guest introduced itself: naming a node+ * id must never be a way to take over a session somebody else is running under it.+ */+ newOnly?: boolean/*** `false`: this view never constrains the shared pty's size (a viewer's small window must not* shrink everyone's terminal). It is still a subscriber and is told the authoritative size.@@ -430,8 +439,12 @@ export interface PtyCreateResult {* `'join-only'`: `PtyCreateOptions.joinOnly` was set (a hosted-relay viewer) and no running* session could be confirmed to join or reattach to — either it is gone, or its existence could* not be checked — so nothing was started. Not a lost connection.+ *+ * `'new-only'`: `PtyCreateOptions.newOnly` was set (a relay guest's create for a node it+ * introduced) and a session already exists under this node's name, or its existence could not be+ * checked. Nothing was joined or started, and the existing session was left untouched.*/- unavailable?: 'ssh' | 'codex-account' | 'join-only' | 'held-elsewhere'+ unavailable?: 'ssh' | 'codex-account' | 'join-only' | 'held-elsewhere' | 'new-only'}/** Payload of `pty:recycled` — see IPC.ptyRecycled and `recycleAction` in the renderer. */