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): send hook credentials over stdin, never on curl's command line

Claude Codeb673aae75fe0
diff --git a/.superpowers/sdd/node-identity/task-argv-clients-report.md b/.superpowers/sdd/node-identity/task-argv-clients-report.md
new file mode 100644
index 000000000..d84b0f69c
--- /dev/null
+++ b/.superpowers/sdd/node-identity/task-argv-clients-report.md
@@ -0,0 +1,141 @@
+# task: hook credentials off curl's command line
+
+Status: **done**, committed to `feat/node-identity`.
+
+## The leak
+
+Every generated curl client passed both credentials as `-H` arguments:
+
+```
+curl … -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" -H "X-Nodeterm-Node-Token: ${nt_node_token}"
+```
+
+A command line is not private. `ps` and `/proc/<pid>/cmdline` are world-readable on a stock Linux,
+so for the life of each curl any other account on the machine could read both the app-wide bearer
+and *this node's* per-node capability. That applies locally and — worse — on every SSH host, where
+these same scripts are installed for remote agent nodes and the other accounts are strangers.
+Scraping a node token out of the process table is exactly the impersonation the per-node token
+exists to prevent, so the identity series was not actually closed until this was fixed.
+
+## The fix
+
+One shared POSIX-sh helper, `HOOK_CURL_HEADERS_SH` in **`src/core/agents/hook-curl-config-sh.ts`**,
+emitting:
+
+```sh
+nt_hook_headers() {
+ printf 'header = "X-Nodeterm-Hook-Token: %s"\n' "$(printf %s "$NODETERM_HOOK_TOKEN" | tr -d '\\"\n\r')"
+ printf 'header = "X-Nodeterm-Node-Token: %s"\n' "$(printf %s "$nt_node_token" | tr -d '\\"\n\r')"
+}
+```
+
+piped into `curl … --config -` at every call site. This is the pattern already used by
+`src/core/usage/remote-claude-usage.ts` and `src/core/codex-identity-proxy.ts`, not a new one. It
+lives in one module because three clients send the same two headers and three copies of an escaping
+rule is how one of them stays wrong.
+
+Call sites converted (8):
+
+| file | sites |
+| --- | --- |
+| `src/core/agents/hooks/managed-script.ts` | request POST (unix socket + TCP) and the backgrounded "answered" POST (unix socket + TCP) |
+| `src/main/canvas-control-core.ts` | `CONTROL_SHIM_SCRIPT`, both transports |
+| `src/core/context-link-core.ts` | `CONTEXT_SHIM_SCRIPT`, both transports |
+
+### Behaviour deliberately preserved
+
+- **Exit codes.** POSIX says a pipeline's status is its last command's, so `nt_hook_headers | curl …`
+ still returns curl's status — which is what `nt_send_request` reads to decide whether to fail over,
+ and what the shims' `nt_code` capture depends on. The `else return 1` no-transport arm is untouched.
+- **Endpoint re-source per POST**, `nt_pick_fallback`'s single retry, and its **post-fallback token
+ re-read** — the helper reads `$NODETERM_HOOK_TOKEN`/`$nt_node_token` at call time, not once at the
+ top, so the fallback leg still presents the adopted endpoint's token.
+- **Empty header = legacy.** Verified against real curl 8.5: `header = "X-…-Token: "` in a config file
+ behaves identically to `-H "X-…-Token: "` — curl sends *no header at all* when there is nothing
+ after the colon. Nothing sends a literal `""`. The server keeps reading absent and empty alike.
+- **Socket-vs-TCP branch selection**, `--connect-timeout`/`--max-time` budgets, backgrounding (`&`),
+ and `>/dev/null 2>&1` redirections are unchanged.
+
+### Escaping
+
+A curl config file is line-based and its quoted values understand backslash escapes, so four
+characters could end a header line and inject a directive of their own: `"`, `\`, LF and CR. All four
+are **stripped**. None can occur in a value we send today — the per-node token is `kid.mac` over
+`[A-Za-z0-9._-]` and the bearer is a UUID — which is precisely what makes stripping (rather than
+escaping) safe: nothing legitimate is altered, and a value that somehow acquired one still cannot
+break out of its own header line. Covered by a test that feeds `ab"\nuser-agent = "pwned` as the
+bearer and asserts no `user-agent` directive appears in the config curl reads.
+
+POSIX sh only: `printf` + a pipe + `tr`. No bashisms, no process substitution. All three generated
+scripts pass `sh -n` and `dash -n`.
+
+## Tests
+
+Red-first shape: the fake `curl` in the two existing failover tests used to *assert the credentials
+were in `$*`* — i.e. the old suite asserted the leak. It now records **both** channels (`ARGV …` /
+`CFG …` / `END`) and asserts the credentials are only ever on stdin.
+
+New/extended coverage:
+
+- `managed-script.test.ts`
+ - both failover legs: neither `dead-token`, `live-token`, `PRIMARY-NODE-TOKEN` nor
+ `FALLBACK-NODE-TOKEN` appears in argv; each leg's config on stdin carries the right pair
+ (socket transport + TCP transport + the failover path, in one run).
+ - a **passthrough** curl shim (record argv + stdin, then exec the real curl) against the real hook
+ server: `verified: true` still recorded, and argv contains neither token nor even the header
+ names.
+ - a source assertion covering the fourth block (the "answered" POST, unreachable without an answer
+ file): 4 curls, 4 `nt_hook_headers |`, 4 `--config -`, zero `-H "X-Nodeterm-*-Token`.
+- `canvas-control-shim.test.ts` — passthrough curl over TCP **and** over the unix socket; server
+ still sees both headers; argv clean; plus the quote/newline breakout case.
+- `context-link.cli.test.ts` — same two transports, plus the "no token file" case proving the
+ header is still dropped entirely (server sees `''`).
+
+The recording shim only attaches a stdin reader when it sees `--config -`; otherwise a regression
+would hang on an unclosed stdin and the failure would read as a timeout rather than an assertion.
+
+### Mutation check
+
+Reverting a single call site to the `-H` form and re-running:
+
+| mutation | result |
+| --- | --- |
+| `context-link-core.ts` TCP branch → `-H` | 2 failed — `expected '-sS -o …' not to contain 'SECRET-BEARER'` |
+| `managed-script.ts` TCP request POST → `-H` | 3 failed — argv contained the real node token; both failover configs empty |
+| `canvas-control-core.ts` unix-socket branch → `-H` | 1 failed — `expected '-sS -o …' not to contain 'SECRET-BEARER'` |
+
+All three restored afterwards; the working tree contains no mutation.
+
+## opencode plugin
+
+**No change needed, and none made.** `src/core/agents/hooks/opencode.ts` generates a JavaScript
+plugin, not a shell script: it sets `x-nodeterm-hook-token` / `x-nodeterm-node-token` in a `headers`
+object handed to `fetch(…)` or `http.request(…)` inside the opencode process. Those values never
+become process arguments, so there is nothing on any command line to leak. (It was also the file
+most at risk from the template-literal trap, which is a second reason not to touch it.)
+
+## Gates
+
+- `npx vitest run src/core/agents src/main/canvas-control-shim.test.ts src/core/context-link.cli.test.ts src/core/no-electron.test.ts src/server/no-electron.test.ts`
+ → **24 files, 308 tests, all passing**
+- `npm run typecheck` → **clean** (both `tsconfig.node.json` and `tsconfig.web.json`)
+- Also re-run green as collateral: `context-link.handler`, `context-link-core`,
+ `server/context-link`, `canvas-control-core`, `test/server/hook-install-guard`,
+ `src/main/remote-ssh` → 15 files, 307 tests.
+
+## Remaining credential-on-a-command-line in the repo
+
+One, out of this task's scope:
+
+- **`src/main/remote-ssh/ssh-askpass.ts:117`** — the generated SSH askpass helper still does
+ `curl … -H "X-Nodeterm-Askpass-Token: ${NODETERM_ASKPASS_TOKEN}"`. Same class of leak, local-only
+ (the socket is `~/.nodeterm/askpass/*.sock`, 0600 in a 0700 dir), but the bearer is visible in `ps`
+ for the life of that curl — which, for a passphrase prompt, is up to `--max-time 300`. The same
+ `printf … | curl --config -` shape applies unchanged; `nt_hook_headers` is not directly reusable
+ because the header name and variable differ.
+
+Checked and clean: `codex-identity-proxy.ts` and `remote-claude-usage.ts` (already stdin);
+`remote-hooks.ts` probe (already stdin); the tmux `-e` channel (closed earlier in this series —
+`hook-server.ts` deliberately omits `NODETERM_HOOK_TOKEN`/`PORT` from the session env); endpoint
+files and node-token files (0600 on disk, not argv); `relay-socket.ts` (token in a WebSocket URL
+built in-process, never argv).
diff --git a/src/core/agents/hook-curl-config-sh.ts b/src/core/agents/hook-curl-config-sh.ts
new file mode 100644
index 000000000..2a3c2ef5c
--- /dev/null
+++ b/src/core/agents/hook-curl-config-sh.ts
@@ -0,0 +1,41 @@
+/**
+ * The one POSIX-sh helper every generated curl client uses to hand its credentials to curl.
+ *
+ * WHY IT EXISTS: a command line is not private. `ps` and `/proc/<pid>/cmdline` are world-readable
+ * on a stock Linux, so `curl -H "X-Nodeterm-Node-Token: <token>"` publishes that token to every
+ * other account on the machine for as long as the curl lives — locally AND on every SSH host,
+ * where the hook clients are installed for remote agent nodes. The per-node token exists precisely
+ * to answer "which node is calling?"; a co-tenant who scrapes one out of the process table can
+ * impersonate that node, and the app-wide bearer alongside it is the key to the whole hook API.
+ * So both headers are written into a curl config file on stdin (`--config -`) instead, the same
+ * way `usage/remote-claude-usage.ts` and the codex launcher in `codex-identity-proxy.ts` already
+ * do it. There is deliberately no argv fallback for an ancient curl: `--config` has been there
+ * since the 1990s, and a silent downgrade to argv would be the leak wearing a compatibility hat.
+ *
+ * ONE COPY, THREE CLIENTS: the managed hook script, the canvas-control shim and the context-link
+ * shim all send the same two headers. They used to carry three copies of the header lines; three
+ * copies of an escaping rule is how one of them stays wrong.
+ *
+ * `nt_node_token` is the caller's variable (each client reads it from the token dir the endpoint
+ * file advertises, keyed by its own node id) — it is read here, not passed, because the failover
+ * in the managed script RE-READS it between POSTs and the helper must see the current value.
+ */
+export const HOOK_CURL_HEADERS_SH = `# Both credentials go to curl on STDIN as a config file, never in argv: a command line is
+# world-readable through \`ps\` / /proc/<pid>/cmdline for the life of the process, locally and on
+# every SSH host, so an argv header hands the app-wide bearer — and this node's own capability —
+# to any co-tenant who looks at the process table. Reading another node's token out of \`ps\` is
+# exactly the impersonation the per-node token exists to prevent.
+#
+# Quoting: a curl config file is LINE-based and its quoted values understand backslash escapes, so
+# four characters could end a header line and start a directive of their own — \`"\`, \`\\\`, and the
+# two line breaks. All four are stripped before the value is written. None can occur in a value we
+# send today — the per-node token is kid.mac over [A-Za-z0-9._-] and the bearer is a UUID — which
+# is what makes STRIPPING (rather than escaping) safe here: nothing legitimate is altered, and a
+# value that somehow acquired one still could not break out of its own header line.
+#
+# An EMPTY value keeps the legacy contract exactly as \`-H\` did: curl sends no header at all when
+# there is nothing after the colon, and the server reads absent and empty identically as \`legacy\`.
+nt_hook_headers() {
+ printf 'header = "X-Nodeterm-Hook-Token: %s"\\n' "$(printf %s "$NODETERM_HOOK_TOKEN" | tr -d '\\\\"\\n\\r')"
+ printf 'header = "X-Nodeterm-Node-Token: %s"\\n' "$(printf %s "$nt_node_token" | tr -d '\\\\"\\n\\r')"
+}`
diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.ts
index d8b428507..35f4ccf43 100644
--- a/src/core/agents/hooks/managed-script.test.ts
+++ b/src/core/agents/hooks/managed-script.test.ts
@@ -31,6 +31,18 @@ describe('buildManagedScript', () => {
expect(s).not.toContain('if [ -z "$NODETERM_HOOK_TOKEN" ] || [ -z "$NODETERM_NODE_ID" ]; then')
})
+ // The executed tests below cover the request POST on both transports and the failover leg; this
+ // one covers the FOURTH block too — the backgrounded "answered" POST, which fires only after a
+ // phone/canvas answer file appears and is therefore hard to reach under /bin/sh. All four must
+ // read their credentials from a config on stdin; none may name a token header in argv.
+ it('never names a credential header on curl\'s command line, in any POST block', () => {
+ expect(s).not.toContain('-H "X-Nodeterm-Hook-Token')
+ expect(s).not.toContain('-H "X-Nodeterm-Node-Token')
+ expect((s.match(/\n *curl -sS/g) ?? []).length).toBe(4)
+ expect((s.match(/\n *nt_hook_headers \|/g) ?? []).length).toBe(4)
+ expect((s.match(/--config -/g) ?? []).length).toBe(4)
+ })
+
describe('deterministic hook-reply approvals (PermissionRequest wait branch)', () => {
it('gates the wait branch on NODETERM_PERM_WAIT_SECS > 0', () => {
expect(s).toContain('[ -n "$NODETERM_PERM_WAIT_SECS" ] && [ "$NODETERM_PERM_WAIT_SECS" -gt 0 ]')
@@ -179,6 +191,54 @@ describe('buildManagedScript', () => {
})
})
+/**
+ * A stand-in `curl` that records BOTH channels of every invocation: its argv (`$*`) and whatever
+ * it was fed on stdin (the `--config -` file). One log, three line kinds per call:
+ *
+ * ARGV <the command line>
+ * CFG <each line of the config read from stdin>
+ * END
+ *
+ * Recording stdin is the point. A test that only inspected argv could not tell "the credential
+ * moved to stdin" from "the credential was dropped"; a test that only inspected the server could
+ * not tell "sent on stdin" from "sent on the command line". Both together pin the fix.
+ */
+function fakeCurlScript(log: string, tail = ''): string {
+ return [
+ '#!/bin/sh',
+ `printf 'ARGV %s\\n' "$*" >> ${JSON.stringify(log)}`,
+ `sed 's/^/CFG /' >> ${JSON.stringify(log)}`,
+ `printf 'END\\n' >> ${JSON.stringify(log)}`,
+ tail,
+ 'exit 0',
+ ''
+ ].join('\n')
+}
+
+interface CurlCall {
+ /** The command line, exactly as `ps` would show it. */
+ argv: string
+ /** The curl config file curl read from stdin. */
+ cfg: string
+}
+
+function curlCalls(log: string): CurlCall[] {
+ const out: CurlCall[] = []
+ let argv = ''
+ let cfg: string[] = []
+ for (const line of readFileSync(log, 'utf8').split('\n')) {
+ if (line.startsWith('ARGV ')) {
+ argv = line.slice(5)
+ cfg = []
+ } else if (line.startsWith('CFG ')) {
+ cfg.push(line.slice(4))
+ } else if (line === 'END') {
+ out.push({ argv, cfg: cfg.join('\n') })
+ }
+ }
+ return out
+}
+
// Generated shell no compiler checks: run it for real against a fake $HOME + a fake curl, the
// same discipline as the canvas-control shim and the remote-usage command. This is the ONLY thing
// that proves the glob candidate actually expands (a quoted pattern passes every string assertion
@@ -225,7 +285,7 @@ describe('buildManagedScript endpoint failover, executed under /bin/sh', () => {
// Fake curl: log every invocation, fail the unix-socket transport (dead tunnel), succeed on TCP.
writeFileSync(
join(bin, 'curl'),
- `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(log)}\ncase "$*" in *--unix-socket*) exit 7 ;; esac\nexit 0\n`,
+ fakeCurlScript(log, 'case "$*" in *--unix-socket*) exit 7 ;; esac'),
{ encoding: 'utf8', mode: 0o755 }
)
const script = join(dir, 'claude.sh')
@@ -244,22 +304,35 @@ describe('buildManagedScript endpoint failover, executed under /bin/sh', () => {
}
})
expect(res.status).toBe(0)
- const calls = readFileSync(log, 'utf8').trim().split('\n')
+ const calls = curlCalls(log)
expect(calls).toHaveLength(2)
// 1st: the dead primary over its socket. 2nd: the retry against the live project's endpoint.
- expect(calls[0]).toContain('--unix-socket')
- expect(calls[0]).toContain('dead-token')
- expect(calls[1]).toContain('http://127.0.0.1:45999/hook/claude')
- expect(calls[1]).toContain('live-token')
- expect(calls[1]).toContain('nodeId=node-1')
+ expect(calls[0].argv).toContain('--unix-socket')
+ expect(calls[1].argv).toContain('http://127.0.0.1:45999/hook/claude')
+ expect(calls[1].argv).toContain('nodeId=node-1')
// The dead transport must not survive into the retry (SOCK/PORT are cleared before sourcing).
- expect(calls[1]).not.toContain('--unix-socket')
+ expect(calls[1].argv).not.toContain('--unix-socket')
+ // BOTH credentials arrive on stdin as a curl config, and NEITHER is on the command line —
+ // on the failover leg as much as the primary one. `ps` on a shared host is readable by every
+ // other account, and a leaked per-node token is a leaked node identity.
+ expect(calls[0].cfg).toContain('header = "X-Nodeterm-Hook-Token: dead-token"')
+ expect(calls[1].cfg).toContain('header = "X-Nodeterm-Hook-Token: live-token"')
+ for (const c of calls) {
+ for (const secret of [
+ 'dead-token',
+ 'live-token',
+ 'PRIMARY-NODE-TOKEN',
+ 'FALLBACK-NODE-TOKEN'
+ ]) {
+ expect(c.argv).not.toContain(secret)
+ }
+ }
// The per-node token follows the ENDPOINT, not the process: the primary POST carries the
// primary dir's token, and the retry carries the FALLBACK dir's — a stale token dir would
// send our kid to an instance that cannot judge it.
- expect(calls[0]).toContain('X-Nodeterm-Node-Token: PRIMARY-NODE-TOKEN')
- expect(calls[1]).toContain('X-Nodeterm-Node-Token: FALLBACK-NODE-TOKEN')
- expect(calls[1]).not.toContain('PRIMARY-NODE-TOKEN')
+ expect(calls[0].cfg).toContain('header = "X-Nodeterm-Node-Token: PRIMARY-NODE-TOKEN"')
+ expect(calls[1].cfg).toContain('header = "X-Nodeterm-Node-Token: FALLBACK-NODE-TOKEN"')
+ expect(calls[1].cfg).not.toContain('PRIMARY-NODE-TOKEN')
}
)
@@ -288,11 +361,10 @@ describe('buildManagedScript endpoint failover, executed under /bin/sh', () => {
'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=live-token\nNODETERM_HOOK_VERSION=1\n',
'utf8'
)
- writeFileSync(
- join(bin, 'curl'),
- `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(log)}\ncase "$*" in *--unix-socket*) exit 7 ;; esac\nexit 0\n`,
- { encoding: 'utf8', mode: 0o755 }
- )
+ writeFileSync(join(bin, 'curl'), fakeCurlScript(log, 'case "$*" in *--unix-socket*) exit 7 ;; esac'), {
+ encoding: 'utf8',
+ mode: 0o755
+ })
const script = join(dir, 'claude2.sh')
writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })
const res = spawnSync('sh', [script], {
@@ -307,11 +379,18 @@ describe('buildManagedScript endpoint failover, executed under /bin/sh', () => {
}
})
expect(res.status).toBe(0)
- const calls = readFileSync(log, 'utf8').trim().split('\n')
+ const calls = curlCalls(log)
expect(calls).toHaveLength(2)
- expect(calls[0]).toContain('X-Nodeterm-Node-Token: PRIMARY-ONLY-TOKEN')
- expect(calls[1]).toContain('live-token')
- expect(calls[1]).not.toContain('PRIMARY-ONLY-TOKEN')
+ expect(calls[0].cfg).toContain('header = "X-Nodeterm-Node-Token: PRIMARY-ONLY-TOKEN"')
+ expect(calls[1].cfg).toContain('header = "X-Nodeterm-Hook-Token: live-token"')
+ // Nothing was carried over — and neither leg put a credential on the command line.
+ expect(calls[1].cfg).toContain('header = "X-Nodeterm-Node-Token: "')
+ expect(calls[1].cfg).not.toContain('PRIMARY-ONLY-TOKEN')
+ for (const c of calls) {
+ for (const secret of ['dead-token', 'live-token', 'PRIMARY-ONLY-TOKEN']) {
+ expect(c.argv).not.toContain(secret)
+ }
+ }
})
})
@@ -448,6 +527,60 @@ describe('managed script presents the per-node token', () => {
expect(raws).toEqual([{ nodeId: NODE, verified: false }])
})
+ // The leak this fix closes: both credentials used to ride on `curl -H …`, i.e. on a command
+ // line, and a command line is world-readable through `ps` / /proc/<pid>/cmdline for the life of
+ // the process — locally AND on every SSH host, where this exact script is installed. A co-tenant
+ // who scrapes another node's token out of the process table can impersonate that node, which is
+ // the one thing the per-node token exists to stop.
+ //
+ // The shim is a PASSTHROUGH: it records argv + stdin and then runs the real curl, so one case
+ // proves the leak is gone AND that delivery still works (the server's own verdict below). A test
+ // that only checked the server would pass with the leak fully intact.
+ it.skipIf(!shAvailable)('sends both credentials on stdin, never on curl\'s command line', async () => {
+ const realCurl = spawnSync('sh', ['-c', 'command -v curl'], { encoding: 'utf8' }).stdout.trim()
+ const bin = join(dir, 'argv-bin')
+ mkdirSync(bin, { recursive: true })
+ const argvLog = join(dir, 'argv-curl.argv')
+ const stdinLog = join(dir, 'argv-curl.stdin')
+ writeFileSync(
+ join(bin, 'curl'),
+ [
+ '#!/bin/sh',
+ `printf '%s\\n' "$*" >> ${JSON.stringify(argvLog)}`,
+ // Only a curl told to read its config from stdin gets a reader, so a regression that put
+ // the headers back on argv fails on the assertions below rather than blocking on a stdin
+ // nobody closes.
+ 'case "$*" in',
+ ` *"--config -"*) tee -a ${JSON.stringify(stdinLog)} | ${JSON.stringify(realCurl)} "$@" ;;`,
+ ` *) ${JSON.stringify(realCurl)} "$@" </dev/null ;;`,
+ 'esac',
+ ''
+ ].join('\n'),
+ { encoding: 'utf8', mode: 0o755 }
+ )
+ // Truncated up front: a regression must fail on the assertions, not on a missing file.
+ writeFileSync(argvLog, '')
+ writeFileSync(stdinLog, '')
+ const token = nodeAuthToken(SECRET, NODE)
+ const tokens = tokenDirWith('tokens-argv', { [NODE]: token })
+ expect(
+ await runHook(newHome('home-argv'), {
+ NODETERM_NODE_TOKEN_DIR: tokens,
+ PATH: `${bin}:${process.env.PATH ?? ''}`
+ })
+ ).toBe(0)
+ // Delivery is unchanged: the server still verified this node from the header it received.
+ expect(raws).toEqual([{ nodeId: NODE, verified: true }])
+ const argv = readFileSync(argvLog, 'utf8')
+ const stdin = readFileSync(stdinLog, 'utf8')
+ expect(argv).not.toContain(token)
+ expect(argv).not.toContain(hookServer.getToken())
+ expect(argv).not.toContain('X-Nodeterm-Node-Token')
+ expect(argv).not.toContain('X-Nodeterm-Hook-Token')
+ expect(stdin).toContain(`header = "X-Nodeterm-Hook-Token: ${hookServer.getToken()}"`)
+ expect(stdin).toContain(`header = "X-Nodeterm-Node-Token: ${token}"`)
+ })
+
// THE failover subtlety: after adopting another instance's endpoint file, the token must be
// RE-READ from that instance's dir. The primary's dir here holds a FOREIGN token (minted from a
// different secret): if it survived the fallback — because the dir was not cleared, or because
diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.ts
index 397209b8e..dd3594366 100644
--- a/src/core/agents/hooks/managed-script.ts
+++ b/src/core/agents/hooks/managed-script.ts
@@ -58,6 +58,7 @@
*/
import { codexThreadIdentityResolverSh } from '../../codex-thread-identity-sh'
import { codexThreadIdentityRoot } from '../../codex-identity-proxy'
+import { HOOK_CURL_HEADERS_SH } from '../hook-curl-config-sh'
function safeIdentityRoot(): string | null {
try {
@@ -90,6 +91,7 @@ export function buildManagedScript(
' fi',
'}',
'nt_read_node_token',
+ HOOK_CURL_HEADERS_SH,
'# Gate on the NODE ID only — it is what marks a nodeterm-spawned session (a user\'s own',
'# terminal has neither var and exits here, bit-for-bit legacy no-op). The token is NOT',
'# required at this point: a phone-spawned session whose endpoint was empty/dead at spawn',
@@ -160,21 +162,21 @@ export function buildManagedScript(
'# endpoint) so that case also tries a fallback.',
'nt_request_post() {',
' if [ -n "$NODETERM_HOOK_SOCK" ]; then',
+ // The pipeline\'s exit status IS curl\'s (POSIX: the status of a pipeline is its last command),
+ // which is what nt_send_request below reads to decide whether to fail over.
+ ' nt_hook_headers |',
` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,
- ' --connect-timeout 0.5 --max-time 1.5 \\',
+ ' --connect-timeout 0.5 --max-time 1.5 --config - \\',
' -H "Content-Type: application/x-www-form-urlencoded" \\',
- ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
- ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
' --data-urlencode "payload=${payload}" >/dev/null 2>&1',
' elif [ -n "$NODETERM_HOOK_PORT" ]; then',
+ ' nt_hook_headers |',
` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
- ' --connect-timeout 0.5 --max-time 1.5 \\',
+ ' --connect-timeout 0.5 --max-time 1.5 --config - \\',
' -H "Content-Type: application/x-www-form-urlencoded" \\',
- ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
- ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
@@ -224,22 +226,20 @@ export function buildManagedScript(
' # nodeterm_answered=<decision>; only for a valid allow/deny (no POST on a bad/timed-out answer).',
' if [ "$nt_decision" = "allow" ] || [ "$nt_decision" = "deny" ]; then',
' if [ -n "$NODETERM_HOOK_SOCK" ]; then',
+ ' nt_hook_headers |',
` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,
- ' --connect-timeout 0.5 --max-time 1 \\',
+ ' --connect-timeout 0.5 --max-time 1 --config - \\',
' -H "Content-Type: application/x-www-form-urlencoded" \\',
- ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
- ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
' --data-urlencode "nodeterm_answered=${nt_decision}" \\',
' --data-urlencode "payload=${payload}" >/dev/null 2>&1 &',
' elif [ -n "$NODETERM_HOOK_PORT" ]; then',
+ ' nt_hook_headers |',
` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
- ' --connect-timeout 0.5 --max-time 1 \\',
+ ' --connect-timeout 0.5 --max-time 1 --config - \\',
' -H "Content-Type: application/x-www-form-urlencoded" \\',
- ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
- ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.ts
index 476687026..f1f00a1fc 100644
--- a/src/core/context-link-core.ts
+++ b/src/core/context-link-core.ts
@@ -3,6 +3,7 @@
// (and CLI_SCRIPT) are unit-testable. The electron/fs/ipc wiring lives in context-link.ts.
import type { ContextLinkInfo } from '../shared/types'
import { sessionName } from './tmux-naming'
+import { HOOK_CURL_HEADERS_SH } from './agents/hook-curl-config-sh'
// nodeId -> latest known transcript path, fed from the raw hook listener (see index.ts).
const nodeTranscript = new Map<string, string>()
@@ -165,6 +166,8 @@ if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then
nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)
fi
+${HOOK_CURL_HEADERS_SH}
+
nt_verb="list"
if [ $# -gt 0 ]; then nt_verb="$1"; shift; fi
@@ -188,18 +191,16 @@ done
nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-context.$$")
if [ -n "$NODETERM_HOOK_SOCK" ]; then
- nt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\
+ nt_code=$(nt_hook_headers |
+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\
--unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/context-link/$nt_verb" \\
-H "Accept: text/plain" \\
- -H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\
- -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\
--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
elif [ -n "$NODETERM_HOOK_PORT" ]; then
- nt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\
+ nt_code=$(nt_hook_headers |
+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\
"http://127.0.0.1:\${NODETERM_HOOK_PORT}/context-link/$nt_verb" \\
-H "Accept: text/plain" \\
- -H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\
- -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\
--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
else
rm -f "$nt_out"
diff --git a/src/core/context-link.cli.test.ts b/src/core/context-link.cli.test.ts
index c902b0985..c74ac2afb 100644
--- a/src/core/context-link.cli.test.ts
+++ b/src/core/context-link.cli.test.ts
@@ -4,7 +4,7 @@
// for the behavior it inherited, plus the remote (SSH) case the old shape could not express.
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { execFile } from 'node:child_process'
-import { mkdirSync, mkdtempSync, writeFileSync, rmSync, chmodSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync, chmodSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
@@ -334,3 +334,129 @@ describe('context-link shim presents the per-node token', () => {
expect(seen).toEqual([{ path: '/context-link/list', nodeToken: '' }])
})
})
+
+// `ps` and /proc/<pid>/cmdline are world-readable, so a credential passed as `curl -H …` is
+// published to every other account on the host for the life of that curl — and this shim is
+// installed on SSH hosts, where the other accounts are strangers. Both headers go in on stdin.
+//
+// The recording curl is a PASSTHROUGH (log argv + stdin, then run the real curl), so each case
+// proves the credential left argv AND that it still reached the server. Checking only the server's
+// headers would pass with the leak entirely intact.
+describe('context-link shim keeps credentials off curl\'s command line', () => {
+ const seen: { hookToken: string; nodeToken: string }[] = []
+ let tcp: import('node:http').Server
+ let unix: import('node:http').Server
+ let tcpPort = 0
+ let sock = ''
+ let binDir = ''
+ let tokenDir = ''
+ let argvLog = ''
+ let stdinLog = ''
+
+ beforeAll(async () => {
+ const http = await import('node:http')
+ const handler = (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse): void => {
+ req.resume()
+ req.on('end', () => {
+ seen.push({
+ hookToken: String(req.headers['x-nodeterm-hook-token'] ?? ''),
+ nodeToken: String(req.headers['x-nodeterm-node-token'] ?? '')
+ })
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
+ res.end('ok\n')
+ })
+ }
+ tcp = http.createServer(handler)
+ unix = http.createServer(handler)
+ await new Promise<void>((r) => tcp.listen(0, '127.0.0.1', r))
+ tcpPort = (tcp.address() as { port: number }).port
+ sock = join(dir, 'ctx-argv-probe.sock')
+ await new Promise<void>((r) => unix.listen(sock, r))
+ tokenDir = join(dir, 'ctx-argv-tokens')
+ mkdirSync(tokenDir, { recursive: true })
+ writeFileSync(join(tokenDir, 'node-A'), 'SECRET-NODE-TOKEN\n', { mode: 0o600 })
+ binDir = join(dir, 'ctx-argv-bin')
+ mkdirSync(binDir, { recursive: true })
+ argvLog = join(binDir, 'argv.log')
+ stdinLog = join(binDir, 'stdin.log')
+ const realCurl = (await run('/bin/sh', ['-c', 'command -v curl'])).stdout.trim()
+ writeFileSync(
+ join(binDir, 'curl'),
+ [
+ '#!/bin/sh',
+ `printf '%s\\n' "$*" >> ${JSON.stringify(argvLog)}`,
+ // Only a curl told to read its config from stdin gets a reader. A regression that put the
+ // headers back on argv would otherwise leave `tee` waiting on a stdin nobody ever closes,
+ // and the failure would read as a timeout instead of the assertion it really is.
+ 'case "$*" in',
+ ` *"--config -"*) tee -a ${JSON.stringify(stdinLog)} | ${JSON.stringify(realCurl)} "$@" ;;`,
+ ` *) ${JSON.stringify(realCurl)} "$@" </dev/null ;;`,
+ 'esac',
+ ''
+ ].join('\n'),
+ { mode: 0o755 }
+ )
+ })
+
+ afterAll(() => {
+ tcp.close()
+ unix.close()
+ })
+
+ async function record(env: Record<string, string>): Promise<{ argv: string; stdin: string }> {
+ // Truncated, not deleted: a regression must fail on the assertion below, not on a missing file.
+ writeFileSync(argvLog, '')
+ writeFileSync(stdinLog, '')
+ seen.length = 0
+ await run('/bin/sh', [shim, 'list'], {
+ env: {
+ PATH: `${binDir}:${process.env.PATH ?? ''}`,
+ NODETERM_NODE_ID: 'node-A',
+ NODETERM_HOOK_TOKEN: 'SECRET-BEARER',
+ NODETERM_NODE_TOKEN_DIR: tokenDir,
+ ...env
+ }
+ })
+ return { argv: readFileSync(argvLog, 'utf8'), stdin: readFileSync(stdinLog, 'utf8') }
+ }
+
+ it('names no credential header in the generated source at all', () => {
+ expect(CONTEXT_SHIM_SCRIPT).not.toContain('-H "X-Nodeterm-Hook-Token')
+ expect(CONTEXT_SHIM_SCRIPT).not.toContain('-H "X-Nodeterm-Node-Token')
+ expect((CONTEXT_SHIM_SCRIPT.match(/--config -/g) ?? []).length).toBe(2)
+ })
+
+ it('over TCP: neither token is in argv, both arrive on stdin and reach the server', async () => {
+ const { argv, stdin } = await record({ NODETERM_HOOK_PORT: String(tcpPort) })
+ expect(seen).toEqual([{ hookToken: 'SECRET-BEARER', nodeToken: 'SECRET-NODE-TOKEN' }])
+ expect(argv).not.toContain('SECRET-BEARER')
+ expect(argv).not.toContain('SECRET-NODE-TOKEN')
+ expect(argv).not.toContain('X-Nodeterm-Hook-Token')
+ expect(argv).not.toContain('X-Nodeterm-Node-Token')
+ expect(stdin).toContain('header = "X-Nodeterm-Hook-Token: SECRET-BEARER"')
+ expect(stdin).toContain('header = "X-Nodeterm-Node-Token: SECRET-NODE-TOKEN"')
+ })
+
+ // The SSH transport — the one where the process table belongs to somebody else.
+ it('over the unix socket: neither token is in argv, both arrive on stdin', async () => {
+ const { argv, stdin } = await record({ NODETERM_HOOK_PORT: '', NODETERM_HOOK_SOCK: sock })
+ expect(seen).toEqual([{ hookToken: 'SECRET-BEARER', nodeToken: 'SECRET-NODE-TOKEN' }])
+ expect(argv).toContain('--unix-socket')
+ expect(argv).not.toContain('SECRET-BEARER')
+ expect(argv).not.toContain('SECRET-NODE-TOKEN')
+ expect(stdin).toContain('header = "X-Nodeterm-Hook-Token: SECRET-BEARER"')
+ expect(stdin).toContain('header = "X-Nodeterm-Node-Token: SECRET-NODE-TOKEN"')
+ })
+
+ // "No token" still means legacy: curl sends no header at all when there is nothing after the
+ // colon, exactly as the `-H` form behaved, and the server reads absent and empty alike.
+ it('still calls with no node token at all when the file is missing', async () => {
+ const { argv, stdin } = await record({
+ NODETERM_HOOK_PORT: String(tcpPort),
+ NODETERM_NODE_TOKEN_DIR: join(dir, 'ctx-argv-none')
+ })
+ expect(seen).toEqual([{ hookToken: 'SECRET-BEARER', nodeToken: '' }])
+ expect(stdin).toContain('header = "X-Nodeterm-Node-Token: "')
+ expect(argv).not.toContain('X-Nodeterm-Node-Token')
+ })
+})
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.ts
index 45ea2b1ae..831ee5333 100644
--- a/src/main/canvas-control-core.ts
+++ b/src/main/canvas-control-core.ts
@@ -1,6 +1,7 @@
// Pure core for agent canvas control: the verb model, request validation, and the standalone
// CLI source. No electron imports, so this module + CONTROL_CLI_SCRIPT are unit-testable.
// Electron/ipc/server wiring lives in canvas-control.ts + index.ts + hook-server.ts.
+import { HOOK_CURL_HEADERS_SH } from '../core/agents/hook-curl-config-sh'
export type ControlVerb =
| 'list'
@@ -238,6 +239,8 @@ if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then
nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)
fi
+${HOOK_CURL_HEADERS_SH}
+
nt_verb="list"
if [ $# -gt 0 ]; then nt_verb="$1"; shift; fi
@@ -271,18 +274,16 @@ done
nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-control.$$")
if [ -n "$NODETERM_HOOK_SOCK" ]; then
- nt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\
+ nt_code=$(nt_hook_headers |
+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\
--unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/control/$nt_verb" \\
-H "Accept: text/plain" \\
- -H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\
- -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\
--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
elif [ -n "$NODETERM_HOOK_PORT" ]; then
- nt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\
+ nt_code=$(nt_hook_headers |
+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\
"http://127.0.0.1:\${NODETERM_HOOK_PORT}/control/$nt_verb" \\
-H "Accept: text/plain" \\
- -H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\
- -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\
--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
else
rm -f "$nt_out"
diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.ts
index 86458d903..fc12e4830 100644
--- a/src/main/canvas-control-shim.test.ts
+++ b/src/main/canvas-control-shim.test.ts
@@ -335,6 +335,133 @@ describe('canvas-control shim presents the per-node token', () => {
})
})
+// A command line is not private: `ps` and /proc/<pid>/cmdline are world-readable, so `curl -H
+// "X-Nodeterm-Node-Token: …"` published this node's capability (and the app-wide bearer) to every
+// other account on the machine — and this shim is installed on SSH hosts, where "every other
+// account" is a stranger. Both headers therefore go in on stdin as a curl config.
+//
+// The shim below is a PASSTHROUGH — it records argv + stdin, then execs the REAL curl — so each
+// case proves the credential left argv AND that the server still received it. Asserting only the
+// server's headers would pass with the leak completely intact.
+describe('canvas-control shim keeps credentials off curl\'s command line', () => {
+ const seen: { hookToken: string; nodeToken: string }[] = []
+ let tcp: import('node:http').Server
+ let unix: import('node:http').Server
+ let tcpPort = 0
+ let sock = ''
+ let binDir = ''
+ let tokenDir = ''
+ const argvLog = (): string => path.join(binDir, 'argv.log')
+ const stdinLog = (): string => path.join(binDir, 'stdin.log')
+
+ beforeAll(async () => {
+ const http = await import('node:http')
+ const handler = (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse): void => {
+ req.resume()
+ req.on('end', () => {
+ seen.push({
+ hookToken: String(req.headers['x-nodeterm-hook-token'] ?? ''),
+ nodeToken: String(req.headers['x-nodeterm-node-token'] ?? '')
+ })
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
+ res.end('ok\n')
+ })
+ }
+ tcp = http.createServer(handler)
+ unix = http.createServer(handler)
+ await new Promise<void>((r) => tcp.listen(0, '127.0.0.1', r))
+ tcpPort = (tcp.address() as { port: number }).port
+ sock = path.join(dir, 'argv-probe.sock')
+ await new Promise<void>((r) => unix.listen(sock, r))
+ tokenDir = path.join(dir, 'argv-node-tokens')
+ fs.mkdirSync(tokenDir, { recursive: true })
+ fs.writeFileSync(path.join(tokenDir, 'node-1'), 'SECRET-NODE-TOKEN\n', { mode: 0o600 })
+ binDir = path.join(dir, 'argv-bin')
+ fs.mkdirSync(binDir, { recursive: true })
+ const realCurl = (await run('/bin/sh', ['-c', 'command -v curl'])).stdout.trim()
+ fs.writeFileSync(
+ path.join(binDir, 'curl'),
+ [
+ '#!/bin/sh',
+ `printf '%s\\n' "$*" >> ${JSON.stringify(argvLog())}`,
+ // Only a curl that was told to read its config from stdin gets a reader. A regression that
+ // put the headers back on argv would otherwise leave `tee` waiting on a stdin nobody ever
+ // closes, and the failure would read as a timeout instead of the assertion it really is.
+ 'case "$*" in',
+ ` *"--config -"*) tee -a ${JSON.stringify(stdinLog())} | ${JSON.stringify(realCurl)} "$@" ;;`,
+ ` *) ${JSON.stringify(realCurl)} "$@" </dev/null ;;`,
+ 'esac',
+ ''
+ ].join('\n'),
+ { mode: 0o755 }
+ )
+ })
+
+ afterAll(() => {
+ tcp.close()
+ unix.close()
+ })
+
+ /** Runs the shim with the recording curl first on PATH and returns both captured channels. */
+ async function record(env: Record<string, string>): Promise<{ argv: string; stdin: string }> {
+ // Truncated, not deleted: a regression must fail on the assertion below, not on a missing file.
+ fs.writeFileSync(argvLog(), '')
+ fs.writeFileSync(stdinLog(), '')
+ seen.length = 0
+ await callShim(['list'], {
+ PATH: `${binDir}:${process.env.PATH ?? ''}`,
+ NODETERM_HOOK_TOKEN: 'SECRET-BEARER',
+ NODETERM_NODE_TOKEN_DIR: tokenDir,
+ ...env
+ })
+ return { argv: fs.readFileSync(argvLog(), 'utf8'), stdin: fs.readFileSync(stdinLog(), 'utf8') }
+ }
+
+ it('names no credential header in the generated source at all', () => {
+ expect(CONTROL_SHIM_SCRIPT).not.toContain('-H "X-Nodeterm-Hook-Token')
+ expect(CONTROL_SHIM_SCRIPT).not.toContain('-H "X-Nodeterm-Node-Token')
+ expect((CONTROL_SHIM_SCRIPT.match(/--config -/g) ?? []).length).toBe(2)
+ })
+
+ it('over TCP: neither token is in argv, both arrive on stdin and reach the server', async () => {
+ const { argv, stdin } = await record({ NODETERM_HOOK_PORT: String(tcpPort) })
+ expect(seen).toEqual([{ hookToken: 'SECRET-BEARER', nodeToken: 'SECRET-NODE-TOKEN' }])
+ expect(argv).not.toContain('SECRET-BEARER')
+ expect(argv).not.toContain('SECRET-NODE-TOKEN')
+ expect(argv).not.toContain('X-Nodeterm-Hook-Token')
+ expect(argv).not.toContain('X-Nodeterm-Node-Token')
+ expect(stdin).toContain('header = "X-Nodeterm-Hook-Token: SECRET-BEARER"')
+ expect(stdin).toContain('header = "X-Nodeterm-Node-Token: SECRET-NODE-TOKEN"')
+ })
+
+ // The SSH transport — the one where the process table belongs to somebody else.
+ it('over the unix socket: neither token is in argv, both arrive on stdin', async () => {
+ const { argv, stdin } = await record({ NODETERM_HOOK_PORT: '', NODETERM_HOOK_SOCK: sock })
+ expect(seen).toEqual([{ hookToken: 'SECRET-BEARER', nodeToken: 'SECRET-NODE-TOKEN' }])
+ expect(argv).toContain('--unix-socket')
+ expect(argv).not.toContain('SECRET-BEARER')
+ expect(argv).not.toContain('SECRET-NODE-TOKEN')
+ expect(stdin).toContain('header = "X-Nodeterm-Hook-Token: SECRET-BEARER"')
+ expect(stdin).toContain('header = "X-Nodeterm-Node-Token: SECRET-NODE-TOKEN"')
+ })
+
+ // Belt and braces on the config-file quoting: a curl config is line-based, so a value carrying a
+ // `"`, a `\` or a line break could end its header line and inject a directive of its own. None of
+ // those can occur today — the token is kid.mac over [A-Za-z0-9._-] and the bearer is a UUID —
+ // which is exactly why they are STRIPPED rather than escaped: nothing legitimate is altered.
+ it('cannot be broken out of the config file by a quote or a newline in a credential', async () => {
+ const { argv, stdin } = await record({
+ NODETERM_HOOK_PORT: String(tcpPort),
+ NODETERM_HOOK_TOKEN: 'ab"\nuser-agent = "pwned'
+ })
+ // The whole hostile value collapses onto the one header line it was given.
+ expect(stdin).toContain('header = "X-Nodeterm-Hook-Token: abuser-agent = pwned"')
+ expect(stdin.split('\n').some((l) => l.trim().startsWith('user-agent'))).toBe(false)
+ expect(argv).not.toContain('pwned')
+ expect(seen).toHaveLength(1)
+ })
+})
+
describe('parseControlBody', () => {
it('reads the shim dialect: nodeId plus arg.<name> fields', () => {
expect(