Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(security): send the askpass token over stdin, not curl's command line
Claude Codee251753cca04
diff --git a/src/core/agents/hook-curl-config-sh.ts b/src/core/agents/hook-curl-config-sh.tsindex 2a3c2ef5c..edc7d5d7e 100644--- a/src/core/agents/hook-curl-config-sh.ts+++ b/src/core/agents/hook-curl-config-sh.ts@@ -7,20 +7,62 @@* 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+ * So the 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.+ * ONE COPY OF THE ESCAPING RULE, FOUR CLIENTS: the managed hook script, the canvas-control shim+ * and the context-link shim all send the same two hook headers (`HOOK_CURL_HEADERS_SH` below);+ * the SSH askpass helper in `main/remote-ssh/ssh-askpass.ts` sends a different, single header and+ * builds its own emitter from `curlHeaderConfigSh`. They all go through `headerLine`, because four+ * copies of a quoting rule is how one of them stays wrong.+ */++/**+ * One `header = "<name>: <value>"` line for a curl config file, emitted by `printf` so the value+ * is read from its sh variable AT CALL TIME (callers such as the managed script's failover re-read+ * their token between POSTs, and the emitter must see the current value, not one captured once).+ *+ * `valueRef` is the sh expression holding the value, e.g. `$NODETERM_HOOK_TOKEN` — it is expanded+ * inside double quotes here, so it is never word-split or globbed.+ */+function headerLine(name: string, valueRef: string): string {+ return ` printf 'header = "${name}: %s"\\n' "$(printf %s "${valueRef}" | tr -d '\\\\"\\n\\r')"`+}++/**+ * Build a POSIX-sh function that writes a curl config file (for `curl --config -`) carrying+ * `headers`, to be piped into curl. `note` is the client-specific comment placed above it.*- * `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.+ * The quoting rule lives here and nowhere else: 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 from a value+ * before it is written.*/-export const HOOK_CURL_HEADERS_SH = `# Both credentials go to curl on STDIN as a config file, never in argv: a command line is+export function curlHeaderConfigSh(+ fnName: string,+ headers: { name: string; valueRef: string }[],+ note: string+): string {+ return [+ note,+ `${fnName}() {`,+ ...headers.map((h) => headerLine(h.name, h.valueRef)),+ '}'+ ].join('\n')+}++export const HOOK_CURL_HEADERS_SH = curlHeaderConfigSh(+ 'nt_hook_headers',+ [+ { name: 'X-Nodeterm-Hook-Token', valueRef: '$NODETERM_HOOK_TOKEN' },+ // The caller's variable (each client reads it from the token dir the endpoint file advertises,+ // keyed by its own node id) — read here, not passed, because the failover in the managed+ // script RE-READS it between POSTs and the emitter must see the current value.+ { name: 'X-Nodeterm-Node-Token', valueRef: '$nt_node_token' }+ ],+ `# 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@@ -34,8 +76,5 @@ export const HOOK_CURL_HEADERS_SH = `# Both credentials go to curl on STDIN as 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')"-}`+# there is nothing after the colon, and the server reads absent and empty identically as \`legacy\`.`+)diff --git a/src/main/remote-ssh/ssh-askpass.test.ts b/src/main/remote-ssh/ssh-askpass.test.tsindex f8ac14ca7..4ae1ecd24 100644--- a/src/main/remote-ssh/ssh-askpass.test.ts+++ b/src/main/remote-ssh/ssh-askpass.test.ts@@ -1,9 +1,16 @@-import { afterEach, describe, expect, it } from 'vitest'+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'import { request as httpRequest } from 'http'+import { execFile } from 'child_process'import { promises as fsp } from 'fs'import os from 'os'import path from 'path'-import { AskpassServer, buildAskpassScript, classifyPrompt, type AskpassPromptRequest } from './ssh-askpass'+import {+ AskpassServer,+ buildAskpassScript,+ classifyPrompt,+ ensureAskpassScript,+ type AskpassPromptRequest+} from './ssh-askpass'/** ssh's real passphrase prompt (sshconnect2.c), byte-identical on every retry. */const passphrasePrompt = (key: string) => `Enter passphrase for key '${key}': `@@ -72,6 +79,173 @@ describe('buildAskpassScript', () => {})})+// A command line is not private: `ps` and /proc/<pid>/cmdline are world-readable, so+// `curl -H "X-Nodeterm-Askpass-Token: …"` published this app instance's askpass bearer to every+// other account on the machine. And this is the longest-lived curl nodeterm generates — it waits+// out `--max-time 300` for a human to type a passphrase — so the window was minutes, not the+// milliseconds a hook POST takes. The bearer therefore goes in on stdin as a curl config.+//+// The recording curl below is a PASSTHROUGH — it logs argv + stdin, then execs the REAL curl —+// so each case proves the bearer left argv AND that the socket still accepted the request.+// Asserting only that the server got its header would pass with the leak completely intact.+describe('the askpass helper keeps its bearer off curl\'s command line', () => {+ let dir = ''+ let script = ''+ let binDir = ''+ const argvLog = (): string => path.join(binDir, 'argv.log')+ const stdinLog = (): string => path.join(binDir, 'stdin.log')++ /** Run a command, resolving (never rejecting) with its exit code: the failure paths below are+ * the point of the test, and a non-zero exit is data here, not an error. */+ function run(+ cmd: string,+ args: string[],+ env?: Record<string, string>+ ): Promise<{ code: number; stdout: string; stderr: string }> {+ return new Promise((resolve) => {+ execFile(cmd, args, env ? { env } : {}, (err, stdout, stderr) => {+ const code = err ? Number((err as NodeJS.ErrnoException).code ?? 1) : 0+ resolve({ code, stdout, stderr })+ })+ })+ }++ beforeAll(async () => {+ dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'nt-askpass-argv-'))+ // The real generator + the real 0700 write, not a hand-rolled copy of the script.+ script = await ensureAskpassScript(dir)+ binDir = path.join(dir, 'bin')+ await fsp.mkdir(binDir, { recursive: true })+ const realCurl = (await run('/bin/sh', ['-c', 'command -v curl'])).stdout.trim()+ await fsp.writeFile(+ 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 header 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.+ // `tee | curl` also keeps the shim's exit status curl's own, which is what -f depends on.+ 'case "$*" in',+ ` *"--config -"*) tee -a ${JSON.stringify(stdinLog())} | ${JSON.stringify(realCurl)} "$@" ;;`,+ ` *) ${JSON.stringify(realCurl)} "$@" </dev/null ;;`,+ 'esac',+ ''+ ].join('\n'),+ { mode: 0o755 }+ )+ })++ afterAll(async () => {+ await fsp.rm(dir, { recursive: true, force: true })+ })++ /** Runs the real script under the real /bin/sh, with the recording curl first on PATH. */+ async function record(+ s: AskpassServer,+ opts: { token?: string; prompt?: string; identity?: string } = {}+ ): Promise<{ code: number; stdout: string; stderr: string; argv: string; stdin: string }> {+ // Truncated, not deleted: a regression must fail on the assertion below, not a missing file.+ await fsp.writeFile(argvLog(), '')+ await fsp.writeFile(stdinLog(), '')+ const identity = opts.identity ?? '/home/u/.ssh/id_ed25519'+ const res = await run('/bin/sh', [script, opts.prompt ?? passphrasePrompt(identity)], {+ PATH: `${binDir}:${process.env.PATH ?? ''}`,+ NODETERM_ASKPASS_SOCK: s.getSockPath(),+ NODETERM_ASKPASS_TOKEN: opts.token ?? s.getToken(),+ NODETERM_ASKPASS_IDENTITY: identity+ })+ return {+ ...res,+ argv: await fsp.readFile(argvLog(), 'utf8'),+ stdin: await fsp.readFile(stdinLog(), 'utf8')+ }+ }++ let server: AskpassServer | undefined+ afterEach(() => {+ server?.stop()+ server = undefined+ })+ async function serve(handler: (req: AskpassPromptRequest) => Promise<string | null>) {+ const s = new AskpassServer()+ s.setPromptHandler(handler)+ await s.start(tmpSock())+ server = s+ return s+ }++ it('names the header nowhere on the command line, and is valid POSIX sh', async () => {+ const src = buildAskpassScript()+ expect(src).not.toContain('-H "X-Nodeterm-Askpass-Token')+ expect((src.match(/--config -/g) ?? []).length).toBe(1)+ // The long wait is exactly what made an argv header so bad here; it must survive the change.+ expect(src).toContain('--max-time 300')+ // dash, not bash: the helper runs under whatever /bin/sh the user (or the SSH host) has.+ expect((await run('/usr/bin/env', ['dash', '-n', script])).code).toBe(0)+ })++ it('sends the bearer on stdin, not in argv, and still gets the passphrase back', async () => {+ const s = await serve(async () => 'correct horse battery staple')+ const r = await record(s)+ // End to end: the socket accepted the request and the answer reached ssh's stdout unchanged.+ expect(r.code).toBe(0)+ expect(r.stdout).toBe('correct horse battery staple')+ // THE assertion. Reverting the fix to `-H "X-Nodeterm-Askpass-Token: …"` fails right here.+ expect(r.argv).not.toContain(s.getToken())+ expect(r.argv).not.toContain('X-Nodeterm-Askpass-Token')+ expect(r.stdin).toContain(`header = "X-Nodeterm-Askpass-Token: ${s.getToken()}"`)+ // The rest of the request is unchanged, and the socket is still what it talks to.+ expect(r.argv).toContain('--unix-socket')+ expect(r.argv).toContain('identity=/home/u/.ssh/id_ed25519')+ })++ it('works identically with the plain system curl, no recording shim in the way', async () => {+ const s = await serve(async () => 'plain-curl-answer')+ const r = await run('/bin/sh', [script, passphrasePrompt('/home/u/.ssh/id_ed25519')], {+ PATH: process.env.PATH ?? '',+ NODETERM_ASKPASS_SOCK: s.getSockPath(),+ NODETERM_ASKPASS_TOKEN: s.getToken(),+ NODETERM_ASKPASS_IDENTITY: '/home/u/.ssh/id_ed25519'+ })+ expect(r.code).toBe(0)+ expect(r.stdout).toBe('plain-curl-answer')+ })++ it('still reports a rejected bearer as a non-zero exit with the breadcrumb', async () => {+ // The exit code now comes out of a PIPELINE (`nt_askpass_headers | curl`). POSIX makes a+ // pipeline's status its last command's, so -f's 403 must still reach `[ $? -eq 0 ]` — if it+ // did not, a stale token would read to ssh as "no passphrase" and die silently.+ const s = await serve(async () => 'never-reached')+ const r = await record(s, { token: 'a-stale-token-from-another-instance' })+ expect(r.code).toBe(1)+ expect(r.stdout).toBe('')+ expect(r.stderr).toContain('nodeterm-askpass: no answer from the app')+ })++ it('passes a decline through as the empty answer ssh needs, exit 0', async () => {+ const s = await serve(async () => null)+ const r = await record(s)+ expect(r.code).toBe(0)+ expect(r.stdout).toBe('')+ })++ // 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 can occur today — the bearer is a randomUUID() — which is exactly why they are STRIPPED+ // rather than escaped: nothing legitimate is ever altered.+ it('cannot be broken out of the config file by a quote or a newline in the bearer', async () => {+ const s = await serve(async () => 'never-reached')+ const r = await record(s, { token: 'ab"\nuser-agent = "pwned' })+ // The whole hostile value collapses onto the one header line it was given.+ expect(r.stdin).toContain('header = "X-Nodeterm-Askpass-Token: abuser-agent = pwned"')+ expect(r.stdin.split('\n').some((l) => l.trim().startsWith('user-agent'))).toBe(false)+ expect(r.argv).not.toContain('pwned')+ // And it is still just a wrong token: rejected, loudly.+ expect(r.code).toBe(1)+ })+})+describe('AskpassServer', () => {let server: AskpassServer | undefineddiff --git a/src/main/remote-ssh/ssh-askpass.ts b/src/main/remote-ssh/ssh-askpass.tsindex d66301846..61e5e88d0 100644--- a/src/main/remote-ssh/ssh-askpass.ts+++ b/src/main/remote-ssh/ssh-askpass.ts@@ -40,6 +40,7 @@ import { promises as fs, rmSync } from 'fs'import os from 'os'import path from 'path'import { instanceSockId } from './ssh-agent'+import { curlHeaderConfigSh } from '../../core/agents/hook-curl-config-sh'const ASKPASS_SCRIPT_NAME = 'ssh-askpass.sh'/** A passphrase prompt body is a few bytes; cap generously against a misbehaving caller. */@@ -108,13 +109,45 @@ function askpassSockPath(): string {return path.join(os.homedir(), '.nodeterm', 'askpass', `${instanceSockId()}.sock`)}+/**+ * The bearer that authenticates this helper to the socket, handed to curl on STDIN as a config+ * file rather than as an `-H` argument. Same emitter (and same stripping rule) as the hook clients+ * — see `core/agents/hook-curl-config-sh.ts` for why a command line is not a private channel.+ *+ * This one is the WORST of the family to leak by duration: a passphrase prompt sits on+ * `--max-time 300`, so an argv header here is readable in `ps` / /proc/<pid>/cmdline for up to+ * five minutes, not the milliseconds a hook POST takes. Whoever reads it can drive this socket's+ * /prompt endpoint themselves — i.e. make the app pop passphrase dialogs — for as long as the app+ * runs. (The 0600 socket in its 0700 dir already keeps a co-tenant off the socket itself; this is+ * the second factor, and a second factor everyone can read is not one.)+ */+const ASKPASS_CURL_HEADERS_SH = curlHeaderConfigSh(+ 'nt_askpass_headers',+ [{ name: 'X-Nodeterm-Askpass-Token', valueRef: '$NODETERM_ASKPASS_TOKEN' }],+ `# The bearer goes 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, and this curl+# lives up to --max-time 300 waiting for a human to type a passphrase.+#+# Quoting: a curl config file is LINE-based, so a \`"\`, a \`\\\` or either line break in the value+# could end the header line and start a directive of its own; all four are stripped. Belt and+# braces — the token is a randomUUID(), i.e. hex and dashes, so none of them can ever occur, which+# is exactly what makes STRIPPING rather than escaping safe: nothing legitimate is altered.+#+# An EMPTY value behaves as \`-H\` did: nothing after the colon means curl sends no header, the+# server answers 403, and -f turns that into the non-zero exit the breadcrumb below reports.`+)+export function buildAskpassScript(): string {return ['#!/bin/sh',+ ASKPASS_CURL_HEADERS_SH,// -f: an HTTP error (403 from a stale token after another instance rebound the socket) must// exit non-zero and hit the breadcrumb below, not read as "empty answer" and die silently.- 'answer=$(curl -sSf --max-time 300 --unix-socket "${NODETERM_ASKPASS_SOCK}" -X POST "http://localhost/prompt" \\',- ' -H "X-Nodeterm-Askpass-Token: ${NODETERM_ASKPASS_TOKEN}" \\',+ // The status of a pipeline is its LAST command's (POSIX), so `$?` below is still curl's own+ // exit code, exactly as when curl was the only command in this substitution.+ 'answer=$(nt_askpass_headers |',+ ' curl -sSf --max-time 300 --unix-socket "${NODETERM_ASKPASS_SOCK}" -X POST "http://localhost/prompt" \\',+ ' --config - \\',' --data-urlencode "identity=${NODETERM_ASKPASS_IDENTITY}" \\',' --data-urlencode "caller=$PPID" \\',' --data-urlencode "prompt=$1")',