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): deliver gateway/custom env off-argv via tmux update-environment
enes902e4974d857
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex e30c00f23..76e8140a9 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -26,6 +26,7 @@ import {localKillSockets,localTmuxKillArgs,remoteTmuxPtyArgs,+ type RemoteSessionEnv,remotePasteDelivery,remoteFramedDelivery,remoteCapturePaneArgs,@@ -82,7 +83,17 @@ import { clearNode as clearNodeAgentStatus } from './agent-status-mirror'import { hasSharedIdentity, setCustomAgentBaseResolver, type AgentId } from '../shared/agents/config'import { findCustomAgent } from '../shared/agents/custom-agent'import { applyCustomAgentEnv, customAgentEnvArgs } from './custom-agent-env'-import { modelGatewayEnv } from '../shared/agents/model-gateway'+import {+ MODEL_GATEWAY_ENV_KEYS,+ modelGatewayEnv,+ tmuxUpdateEnvironmentLine+} from '../shared/agents/model-gateway'+import {+ remoteSessionEnvAvailable,+ remoteSessionEnvPath,+ sessionEnvFileContent,+ stageRemoteSessionEnv+} from './remote-ssh/session-env'import { foregroundProcessGroup, parsePaneProcess } from './pane-process'import { isShellCommand } from '../shared/agents/pane'@@ -192,6 +203,11 @@ set -g default-terminal "xterm-256color"set -sg escape-time 10set -g destroy-unattached offsetw -g aggressive-resize on+# Credentials travel HERE, not on argv: gateway env vars ride the tmux client's process+# environment and update-environment copies them into the session at create/attach. The old+# '-e KEY=VALUE' route parked the API key on the long-lived attached client's command line —+# world-readable in /proc/<pid>/cmdline on any multi-user host (the PR #195 leak class).+${tmuxUpdateEnvironmentLine()}# Copy to the SYSTEM clipboard via OSC 52 (the client's terminal writes it). BOTH lines are needed# on tmux 3.2+ — see tmuxConf's doc comment before touching either.# MIGRATION — do not remove. Older versions of this file blanked smcup/rmcup/indn via@@ -1267,6 +1283,53 @@ export class PtyManager {return this.tmuxPath}+ /** `update-environment` names already pushed to the running server this app-run (plus the+ * conf-baked set), so a custom agent's spawn costs at most one `set-option` per NEW key. */+ private updateEnvKeys: Set<string> | null = null++ /** Make the shared tmux server copy these client-env names into new sessions. The conf bakes+ * the fixed gateway list; a CUSTOM agent's env keys are user-defined and can only be appended+ * at runtime. Names ride the `set-option` argv — names only, values never (values reach tmux+ * through the client's process environment; that is the point of this whole path). Failure is+ * fail-open twice over: with NO server running, the session about to spawn starts the server+ * itself and its panes inherit the client env directly; a name that cannot be appended costs+ * that var on a shared server, never the terminal. */+ private ensureUpdateEnvKeys(names: string[]): void {+ if (!this.tmuxPath) return+ const wanted = names.filter(+ (n) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(n) && n !== 'PATH' && n !== 'LANG'+ )+ if (!wanted.length) return+ if (!this.updateEnvKeys) {+ this.updateEnvKeys = new Set(MODEL_GATEWAY_ENV_KEYS)+ try {+ const out = execFileSync(+ this.tmuxPath,+ ['-L', TMUX_SOCKET, 'show-options', '-g', 'update-environment'],+ { stdio: ['ignore', 'pipe', 'ignore'] }+ ).toString()+ for (const m of out.matchAll(/update-environment\[\d+\]\s+(\S+)/g)) {+ this.updateEnvKeys.add(m[1])+ }+ } catch {+ /* no server yet — the conf list is what a fresh server will have */+ }+ }+ for (const name of wanted) {+ if (this.updateEnvKeys.has(name)) continue+ try {+ execFileSync(+ this.tmuxPath,+ ['-L', TMUX_SOCKET, 'set-option', '-ga', 'update-environment', name],+ { stdio: 'ignore' }+ )+ this.updateEnvKeys.add(name)+ } catch {+ /* no server yet — fresh-server sessions inherit the client env directly */+ }+ }+ }+registerIpc(): void {platform().handleWithSender(IPC.ptyCreate,@@ -2054,11 +2117,13 @@ export class PtyManager {// the account path set). ${env:VAR} is expanded against the live process env. Only the LOCAL// path merges into `env` here; the remote (ssh) path threads the same vars into the tmux `-e`// list below (the local ssh client's env does not propagate to the remote tmux session).+ let customEnvMerged: Record<string, string> = {}if (!options.sshRemote) {const custom = findCustomAgent(this.getSettings().customAgents, options.agentId ?? '')const merged = applyCustomAgentEnv(env, custom, process.env as Record<string, string | undefined>)for (const [k, v] of Object.entries(merged.env)) env[k] = vfor (const w of merged.warnings) console.warn(w)+ customEnvMerged = merged.env}const settings = this.getSettings()@@ -2137,10 +2202,10 @@ export class PtyManager {? accountTmuxEnvArgs(remoteAccountConfigDirAbs(options.sshRemote.remoteHome, options.accountId)): []// Custom-agent env for a REMOTE node: expand ${env:VAR} against the LOCAL process env (the- // key stays local; only the resolved VALUE travels over SSH) and thread the results into the- // remote tmux `-e` list. PATH is skipped — the local machine can't see the remote box's PATH,- // so a locally-resolved PATH would break CLI resolution on the host (recovering it is out of- // scope). Applied AFTER the account env so custom env still wins, mirroring the local path.+ // key stays local; only the resolved VALUE travels over SSH). PATH is skipped — the local+ // machine can't see the remote box's PATH, so a locally-resolved PATH would break CLI+ // resolution on the host (recovering it is out of scope). Applied AFTER the account env so+ // custom env still wins, mirroring the local path.const remoteCustom = findCustomAgent(this.getSettings().customAgents, options.agentId ?? '')const remoteCustomEnv = customAgentEnvArgs(remoteCustom,@@ -2148,11 +2213,43 @@ export class PtyManager {{ skipPath: true })for (const w of remoteCustomEnv.warnings) console.warn(w)- const remoteCustomEnvArgs = remoteCustomEnv.args.flatMap((kv) => ['-e', kv])- const remoteGatewayEnvArgs = Object.entries(gatewayEnv).flatMap(([k, v]) => [- '-e',- `${k}=${v}`- ])+ // Gateway + custom env VALUES never touch an argv (the old `-e KEY=VALUE` route parked the+ // gateway API key on the local ssh client's command line for the whole session — the PR #195+ // leak class, on the machine AND on the remote process table at creation). They ride a 0600+ // per-session file staged over the ControlMaster; the remote command sources + deletes it,+ // and the remote conf's `update-environment` copies the names into the session env. Gated on+ // the validated remote $HOME and on a wired uploader — absent either, the vars are simply+ // not delivered and the agent fails loudly in its pane (fail-open, never a fallback to argv).+ const remoteEnvPairs: Record<string, string> = { ...gatewayEnv }+ for (const kv of remoteCustomEnv.args) {+ const eq = kv.indexOf('=')+ if (eq > 0) remoteEnvPairs[kv.slice(0, eq)] = kv.slice(eq + 1)+ }+ let remoteSessionEnv: RemoteSessionEnv | undefined+ if (+ Object.keys(remoteEnvPairs).length &&+ options.sshRemote.remoteHome &&+ remoteSessionEnvAvailable()+ ) {+ const envFile = remoteSessionEnvPath(+ options.sshRemote.remoteHome,+ sessionName(options.persistKey)+ )+ stageRemoteSessionEnv(+ options.sshRemote.controlPath,+ envFile,+ sessionEnvFileContent(remoteEnvPairs)+ )+ const baked = new Set<string>(MODEL_GATEWAY_ENV_KEYS)+ remoteSessionEnv = {+ file: envFile,+ extraKeys: Object.keys(remoteEnvPairs).filter((k) => !baked.has(k))+ }+ } else if (Object.keys(remoteEnvPairs).length) {+ console.warn(+ '[pty] remote session env skipped (no remote home or no uploader) — agent will launch without gateway/custom env'+ )+ }args = remoteTmuxPtyArgs(options.sshRemote.conn,options.sshRemote.controlPath,@@ -2164,15 +2261,11 @@ export class PtyManager {// place a foreign value is most at home.reqShell,options.shellArgs,- [- ...hookExtraEnv,- ...remoteAccountEnv,- ...remoteGatewayEnvArgs,- ...remoteCustomEnvArgs- ],+ [...hookExtraEnv, ...remoteAccountEnv],// Source nodeterm's remote tmux.conf via `-f` (written on connect, Task 2) so a cold-start// session gets mouse/clipboard/scrollback. Fail-open: undefined → remote tmux host defaults.- options.sshRemote.tmuxConfPath+ options.sshRemote.tmuxConfPath,+ remoteSessionEnv)} else if (this.tmuxPath && settings.tmuxEnabled && options.persistKey) {// attach-or-create the persistent session for this node.@@ -2198,12 +2291,15 @@ export class PtyManager {// The account config dir must ride `-e` like the hook env: the tmux server is shared// and long-lived, so session env comes from creation args, not client inheritance.const accountEnvArgs = accountDir ? accountTmuxEnvArgs(accountDir) : []- // The shared tmux server outlives the app, so the gateway cannot rely on the tmux client's- // inherited process env. Emit only the centrally-mapped keys explicitly; read their FINAL- // values from `env` so a custom agent override retains last-write precedence.- const gatewayEnvArgs = Object.keys(gatewayEnv).flatMap((key) =>- typeof env[key] === 'string' ? ['-e', `${key}=${env[key]}`] : []- )+ // Gateway env deliberately has NO `-e` pairs: the values are in this tmux CLIENT's process+ // environment (merged above) and the conf's `update-environment` list copies them into the+ // session at create/attach — measured on tmux 3.4, including the removal case (a plain+ // terminal's client lacks the vars, so tmux strips them from its session even on a server+ // another node's env seeded). `-e KEY=VALUE` parked the API key on the long-lived attached+ // client's argv — world-readable in /proc/<pid>/cmdline on a multi-user host, the exact+ // PR #195 leak class. Custom-agent env keys OUTSIDE the baked gateway list still need the+ // option appended at runtime on a shared server (the conf assignment cannot know them):+ this.ensureUpdateEnvKeys(Object.keys(customEnvMerged))const attachFlags = tmuxAttachFlags(!!sinks)args = ['-L',@@ -2216,7 +2312,6 @@ export class PtyManager {...pathEnvArgs,...langEnvArgs,...accountEnvArgs,- ...gatewayEnvArgs,'-c',cwd,'-s',diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.tsindex 21baa5b1e..43711ff66 100644--- a/src/core/pty-single-user.test.ts+++ b/src/core/pty-single-user.test.ts@@ -259,14 +259,11 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () ='https://bifrost.example.test/anthropic')expect(spawnArgs[0].env.ANTHROPIC_AUTH_TOKEN).toBe('vk-secret')- expect(spawnArgs[0].args).toEqual(- expect.arrayContaining([- '-e',- 'ANTHROPIC_BASE_URL=https://bifrost.example.test/anthropic',- '-e',- 'ANTHROPIC_AUTH_TOKEN=vk-secret'- ])- )+ // NEVER on argv: the tmux client's command line is world-readable in /proc/<pid>/cmdline+ // for the whole session on a multi-user host (the PR #195 leak class). The session gets the+ // values through the conf's update-environment list reading this client's process env.+ expect(spawnArgs[0].args.join(' ')).not.toContain('vk-secret')+ expect(spawnArgs[0].args.join(' ')).not.toContain('ANTHROPIC_AUTH_TOKEN')expect(spawnArgs[0].args.join(' ')).not.toContain('${env:')} finally {if (inherited === undefined) delete process.env.NODETERM_TEST_GATEWAY_KEY@@ -296,14 +293,10 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =COPILOT_PROVIDER_WIRE_MODEL: 'openai/gpt-5.5',COPILOT_PROVIDER_WIRE_API: 'responses'})- expect(spawnArgs[0].args).toEqual(- expect.arrayContaining([- '-e',- 'COPILOT_PROVIDER_MODEL_ID=gpt-5.5',- '-e',- 'COPILOT_PROVIDER_WIRE_MODEL=openai/gpt-5.5'- ])- )+ // The BYOK env — key included — reaches the session via the client env + update-environment,+ // never the argv (see the claude case above for why).+ expect(spawnArgs[0].args.join(' ')).not.toContain('vk-secret')+ expect(spawnArgs[0].args.join(' ')).not.toContain('COPILOT_PROVIDER')expect(spawnArgs[0].args.join(' ')).not.toContain('--model')})@@ -328,9 +321,8 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =OPENAI_BASE_URL: 'https://bifrost.example.test/openai/v1',OPENAI_API_KEY: 'stored-gateway-key'})- expect(spawnArgs[0].args).toEqual(- expect.arrayContaining(['-e', 'OPENAI_API_KEY=stored-gateway-key'])- )+ // The stored key must not surface on the tmux client's argv either — same #195 class.+ expect(spawnArgs[0].args.join(' ')).not.toContain('stored-gateway-key')})it('never exposes gateway credentials to a plain terminal', async () => {diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 2bab11d45..a63034964 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -312,6 +312,41 @@ describe('remoteTmuxPtyArgs', () => {const cmd = args[args.length - 1]expect(cmd).toContain(`-f '/home/u/.nodeterm/tmux.conf' new-session -A`)})++ describe('sessionEnv prologue (argv-free credential delivery)', () => {+ it('prepends a bounded wait + source + rm before the tmux command', () => {+ const args = remoteTmuxPtyArgs(+ conn, '/s.sock', 'nt-x', '/srv/app', undefined, undefined, [], '/home/u/.nodeterm/tmux.conf',+ { file: '/home/u/.nodeterm/env/nt-x.env', extraKeys: [] }+ )+ const cmd = args[args.length - 1]+ // The credential file is SOURCED, then removed — never a value on the command line.+ expect(cmd).toContain(". '/home/u/.nodeterm/env/nt-x.env'")+ expect(cmd).toContain("rm -f '/home/u/.nodeterm/env/nt-x.env'")+ expect(cmd).toMatch(/while \[ ! -f '\/home\/u\/\.nodeterm\/env\/nt-x\.env' \]/)+ // The prologue runs BEFORE the tmux new-session it guards.+ expect(cmd.indexOf(". '")).toBeLessThan(cmd.indexOf('new-session'))+ })++ it('appends custom (non-gateway) env NAMES to update-environment — names only, never values', () => {+ const args = remoteTmuxPtyArgs(+ conn, '/s.sock', 'nt-x', '/srv/app', undefined, undefined, [], undefined,+ { file: '/h/.nodeterm/env/nt-x.env', extraKeys: ['MY_CUSTOM_TOKEN'] }+ )+ const cmd = args[args.length - 1]+ expect(cmd).toContain('set-option -ga update-environment MY_CUSTOM_TOKEN')+ })++ it('drops a non-identifier env name at the splice point (belt to session-env.ts braces)', () => {+ const args = remoteTmuxPtyArgs(+ conn, '/s.sock', 'nt-x', '/srv/app', undefined, undefined, [], undefined,+ { file: '/h/.nodeterm/env/nt-x.env', extraKeys: ['BAD;NAME', 'GOOD_ONE'] }+ )+ const cmd = args[args.length - 1]+ expect(cmd).toContain('update-environment GOOD_ONE')+ expect(cmd).not.toContain('BAD;NAME')+ })+ })})describe('hook forwarding', () => {diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex e5a5757f1..ef0ffd52a 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -718,7 +718,8 @@ export function remoteTmuxPtyArgs(program?: string,programArgs?: string[],extraEnv: string[] = [],- confPath?: string+ confPath?: string,+ sessionEnv?: RemoteSessionEnv): string[] {let cmd = remoteTmuxCommand({ sessionId, remoteCwd, program, programArgs, socket: RMT_TMUX_SOCKET, confPath })if (extraEnv.length)@@ -731,5 +732,48 @@ export function remoteTmuxPtyArgs(// was remote code execution EVEN WITH the posixQuote above. A function replacement is never// pattern-expanded, so the quoted bytes land verbatim. See control-master.injection.test.ts.cmd = cmd.replace('new-session -A ', () => `new-session -A ${extraEnv.map(posixQuote).join(' ')} `)+ if (sessionEnv) cmd = `${remoteSessionEnvPrologue(sessionEnv, confPath)}${cmd}`return ['-t', ...childArgs(conn, controlPath, cmd)]}++/** Credentials for a remote session, delivered WITHOUT argv: a 0600 file (staged over the+ * ControlMaster, content via stdin) that the remote command sources into the tmux client's env+ * and deletes, plus the key NAMES (never values) the remote server's `update-environment` must+ * learn at runtime — the conf bakes the fixed gateway list, but a custom agent's keys are+ * user-defined. See session-env.ts for the whole design. */+export interface RemoteSessionEnv {+ /** Absolute remote path of the staged env file (built from the validated remote $HOME). */+ file: string+ /** Env names OUTSIDE the conf-baked gateway list to append to `update-environment`. */+ extraKeys: string[]+}++/** The shell prologue spliced before the remote tmux command. POSIX-sh only, one line. The+ * wait-loop bridges the staging race (the upload is fire-and-forget from a synchronous spawn+ * path); its budget is 40×50ms = 2s, after which the launch proceeds env-less and the agent+ * fails loudly in the pane — fail-open never leaks and never wedges a terminal on a dead+ * upload. The `rm -f` runs unconditionally so a late-landing file cannot linger at rest. */+function remoteSessionEnvPrologue(sessionEnv: RemoteSessionEnv, confPath?: string): string {+ const f = posixQuote(sessionEnv.file)+ const t = `tmux -L ${RMT_TMUX_SOCKET}`+ const parts: string[] = []+ // Names only ever come from isSafeEnvName-shaped keys, but this builder is exported territory —+ // re-filter at the splice point, the same idiom every other remote builder here uses.+ const keys = sessionEnv.extraKeys.filter((k) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(k))+ if (keys.length) {+ // The option must exist on the server BEFORE new-session copies the client env, so start the+ // server (a no-op when warm) with the same conf new-session would use. The grep guard keeps a+ // long-lived server's array from accumulating one duplicate per spawn.+ parts.push(`${t}${confPath ? ` -f ${posixQuote(confPath)}` : ''} start-server 2>/dev/null;`)+ for (const k of keys) {+ parts.push(+ `${t} show-options -g update-environment 2>/dev/null | grep -q ' ${k}$' || ${t} set-option -ga update-environment ${k} 2>/dev/null;`+ )+ }+ }+ parts.push(+ `_nte=0; while [ ! -f ${f} ] && [ "$_nte" -lt 40 ]; do sleep 0.05; _nte=$((_nte+1)); done;`,+ `[ -f ${f} ] && . ${f} >/dev/null 2>&1; rm -f ${f};`+ )+ return parts.join(' ') + ' '+}diff --git a/src/core/remote-ssh/session-env.test.ts b/src/core/remote-ssh/session-env.test.tsnew file mode 100644index 000000000..a527a77d6--- /dev/null+++ b/src/core/remote-ssh/session-env.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest'+import {+ isSafeEnvName,+ remoteSessionEnvPath,+ sessionEnvFileContent+} from './session-env'++describe('sessionEnvFileContent', () => {+ it('renders `export K=\'v\'` with values single-quoted so metacharacters are inert', () => {+ const out = sessionEnvFileContent({+ ANTHROPIC_AUTH_TOKEN: 'vk-123',+ OPENAI_BASE_URL: 'https://gw.example/v1'+ })+ expect(out).toBe(+ "export ANTHROPIC_AUTH_TOKEN='vk-123'\nexport OPENAI_BASE_URL='https://gw.example/v1'\n"+ )+ })++ it('fences a hostile value into a single-quoted literal (no command substitution escapes)', () => {+ const out = sessionEnvFileContent({ K: "a'; rm -rf ~; echo '" })+ // The embedded quote is closed/escaped/reopened, never terminating the assignment.+ expect(out).toBe("export K='a'\\''; rm -rf ~; echo '\\'''\n")+ })++ it('drops a pair whose NAME is not a shell identifier (a name is spliced bare)', () => {+ const out = sessionEnvFileContent({ 'BAD;NAME': 'x', GOOD: 'y' })+ expect(out).toBe("export GOOD='y'\n")+ })+})++describe('isSafeEnvName', () => {+ it('accepts identifiers, rejects anything that could break out of the left-hand side', () => {+ expect(isSafeEnvName('ANTHROPIC_AUTH_TOKEN')).toBe(true)+ expect(isSafeEnvName('_x1')).toBe(true)+ expect(isSafeEnvName('1BAD')).toBe(false)+ expect(isSafeEnvName('BAD;NAME')).toBe(false)+ expect(isSafeEnvName('BAD NAME')).toBe(false)+ expect(isSafeEnvName('')).toBe(false)+ })+})++describe('remoteSessionEnvPath', () => {+ it('builds a per-session path under the validated remote home', () => {+ expect(remoteSessionEnvPath('/home/deploy', 'nt-abc')).toBe(+ '/home/deploy/.nodeterm/env/nt-abc.env'+ )+ })+})diff --git a/src/core/remote-ssh/session-env.ts b/src/core/remote-ssh/session-env.tsnew file mode 100644index 000000000..f83ae388d--- /dev/null+++ b/src/core/remote-ssh/session-env.ts@@ -0,0 +1,74 @@+// Argv-free env delivery for REMOTE agent sessions.+//+// The problem this solves: a remote node's gateway/custom env used to ride the ssh command as+// tmux `-e KEY=VALUE` pairs — parking the gateway API key on the LOCAL ssh client's argv for the+// whole session (world-readable /proc/<pid>/cmdline on a multi-user host, the PR #195 leak+// class) and on the remote process table at session creation. Now the VALUES travel in a 0600+// file staged over the ControlMaster (content via stdin — no argv anywhere), the remote command+// sources it into the tmux CLIENT's environment and deletes it, and the remote tmux conf's+// `update-environment` list copies the names into the session env at create/attach. Names (never+// values) may additionally ride a `set-option` argv for user-defined custom keys.+//+// The staging write is fire-and-forget from the spawn path (the same seam-injection pattern as+// node-token-service's remote writer: core cannot run ssh, main can). The remote command bridges+// the race with a bounded wait for the file; a file that never lands means the agent launches+// without its env and fails LOUDLY in the pane — fail-open never leaks and never hangs a spawn.++import { shellSingleQuote } from '../../shared/shell-quote'++export type RemoteSessionEnvWriter = (+ controlPath: string,+ remotePath: string,+ content: string+) => void++let writer: RemoteSessionEnvWriter | null = null++/** main (the ssh runner's owner) injects the actual uploader; the Server Edition wires nothing+ * and staging degrades to the bounded-wait timeout + env-less launch. */+export function setRemoteSessionEnvWriter(w: RemoteSessionEnvWriter | null): void {+ writer = w+}++/** Fire-and-forget, fail-open: nothing here may throw into a pty spawn. */+export function stageRemoteSessionEnv(+ controlPath: string,+ remotePath: string,+ content: string+): void {+ try {+ writer?.(controlPath, remotePath, content)+ } catch {+ /* fail-open */+ }+}++/** Whether a writer is wired — the spawn path skips the remote wait-loop entirely when staging+ * can never happen (Server Edition), instead of making every remote agent pay the full timeout. */+export function remoteSessionEnvAvailable(): boolean {+ return writer !== null+}++/** Env var names must be shell-identifier-shaped before they touch a sourced file or a+ * `set-option` argv. Anything else is dropped (and the pair with it). */+export function isSafeEnvName(name: string): boolean {+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)+}++/** The per-session env file path under the validated remote $HOME. The session name is+ * `nt-<sanitized>` (tmux-naming), so the joined path needs no further quoting decisions here —+ * callers still `posixQuote` it at the splice point. */+export function remoteSessionEnvPath(remoteHome: string, session: string): string {+ return `${remoteHome}/.nodeterm/env/${session}.env`+}++/** Render `export K='v'` lines. Values go through the same single-quote fence every typed+ * command uses; unsafe NAMES are dropped entirely (a name is spliced bare on the left of `=`). */+export function sessionEnvFileContent(pairs: Record<string, string>): string {+ const lines: string[] = []+ for (const [k, v] of Object.entries(pairs)) {+ if (!isSafeEnvName(k)) continue+ lines.push(`export ${k}=${shellSingleQuote(v)}`)+ }+ return lines.join('\n') + '\n'+}diff --git a/src/core/session-env.realtmux.test.ts b/src/core/session-env.realtmux.test.tsnew file mode 100644index 000000000..494326ab3--- /dev/null+++ b/src/core/session-env.realtmux.test.ts@@ -0,0 +1,138 @@+// ARGV-FREE CREDENTIAL DELIVERY, PROVEN AGAINST A REAL TMUX.+//+// The subject is the B3 fix of the dkattan-stack integration: gateway/custom env reaches an+// agent's tmux session through `update-environment` (values in the CLIENT's process env, names in+// the conf) — never through `-e KEY=VALUE` pairs parked on a long-lived client argv. Unit tests+// can only assert what the builders emit; whether tmux actually copies the values into the pane,+// and actually strips them for a client that lacks them, is a property of tmux — so it is+// measured here, on this tmux, with the EXACT conf text `tmuxConf()` ships.+//+// Also proven: the remote prologue (`remoteSessionEnvPrologue` via `remoteTmuxPtyArgs`) run+// through a real /bin/sh — the staged file is sourced into the tmux client's env, deleted, and+// its values land in the pane; a file that never appears costs 2s and nothing else.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { tmuxConf } from './pty-manager'+import { sessionEnvFileContent } from './remote-ssh/session-env'++/** A private socket — never the live-session sockets. */+const SOCKET = `nt-envtest-${process.pid}`++let tmp: string+let conf: string+let tmuxOk = false++function tmux(args: string[], env?: Record<string, string>): string {+ return execFileSync('tmux', ['-L', SOCKET, ...args], {+ env: { ...process.env, ...env },+ stdio: ['ignore', 'pipe', 'pipe']+ }).toString()+}++beforeAll(() => {+ try {+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })+ tmuxOk = true+ } catch {+ return // no tmux on this host — every test below self-skips+ }+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-envtest-'))+ conf = path.join(tmp, 'tmux.conf')+ fs.writeFileSync(conf, tmuxConf(2000))+})++afterAll(() => {+ if (!tmuxOk) return+ try {+ tmux(['kill-server'])+ } catch {+ /* already gone */+ }+ fs.rmSync(tmp, { recursive: true, force: true })+})++const waitFor = async (file: string, ms = 3000): Promise<string> => {+ const t0 = Date.now()+ for (;;) {+ if (fs.existsSync(file)) return fs.readFileSync(file, 'utf8')+ if (Date.now() - t0 > ms) throw new Error(`timed out waiting for ${file}`)+ await new Promise((r) => setTimeout(r, 25))+ }+}++describe('update-environment delivery (the argv-free gateway path)', () => {+ it('a client carrying the var in its process env hands it to the pane — argv stays clean', async () => {+ if (!tmuxOk) return+ const out = path.join(tmp, 'claude-pane')+ // The spawn args mirror the local branch: conf via -f, NO -e for the credential.+ tmux(+ ['-f', conf, 'new-session', '-d', '-s', 'agent', `echo "TOKEN=[$ANTHROPIC_AUTH_TOKEN]" > ${out}; sleep 5`],+ { ANTHROPIC_AUTH_TOKEN: 'vk-live-secret' }+ )+ expect(await waitFor(out)).toBe('TOKEN=[vk-live-secret]\n')+ // And the value is recorded in the SESSION env (tmux server memory), where later windows+ // read it — not on any argv.+ expect(tmux(['show-environment', '-t', 'agent'])).toContain(+ 'ANTHROPIC_AUTH_TOKEN=vk-live-secret'+ )+ })++ it('a plain terminal (client withOUT the var) gets it STRIPPED, even on a seeded server', async () => {+ if (!tmuxOk) return+ // The server above was STARTED by a client whose env carried the token, i.e. the worst case:+ // server-global env is seeded with the secret. update-environment must still remove it for a+ // session created by a credential-less client — this is what keeps one node's gateway key out+ // of every plain terminal.+ const out = path.join(tmp, 'plain-pane')+ const env = { ...process.env }+ delete env.ANTHROPIC_AUTH_TOKEN+ execFileSync(+ 'tmux',+ ['-L', SOCKET, 'new-session', '-d', '-s', 'plain', `echo "TOKEN=[$ANTHROPIC_AUTH_TOKEN]" > ${out}`],+ { env, stdio: ['ignore', 'pipe', 'pipe'] }+ )+ expect(await waitFor(out)).toBe('TOKEN=[]\n')+ })+})++describe('the remote prologue, run through a real /bin/sh', () => {+ it('sources the staged 0600 file into the tmux client env, deletes it, and the pane sees the value', async () => {+ if (!tmuxOk) return+ const envFile = path.join(tmp, 'nt-remote.env')+ fs.writeFileSync(envFile, sessionEnvFileContent({ ANTHROPIC_AUTH_TOKEN: "vk-remote'; echo pwned" }), {+ mode: 0o600+ })+ const out = path.join(tmp, 'remote-pane')+ // The exact prologue shape remoteSessionEnvPrologue emits (single quotes in the path are+ // impossible by construction; asserted against the builder in control-master tests). The+ // hostile value in the file proves sessionEnvFileContent's quoting: it must arrive as DATA.+ const prologue = `_nte=0; while [ ! -f '${envFile}' ] && [ "$_nte" -lt 40 ]; do sleep 0.05; _nte=$((_nte+1)); done; [ -f '${envFile}' ] && . '${envFile}' >/dev/null 2>&1; rm -f '${envFile}';`+ execFileSync(+ '/bin/sh',+ ['-c', `${prologue} tmux -L ${SOCKET} new-session -d -s remote 'echo "TOKEN=[$ANTHROPIC_AUTH_TOKEN]" > ${out}'`],+ { stdio: ['ignore', 'pipe', 'pipe'] }+ )+ expect(await waitFor(out)).toBe("TOKEN=[vk-remote'; echo pwned]\n")+ // Sourced and GONE: nothing at rest on the host after the launch.+ expect(fs.existsSync(envFile)).toBe(false)+ })++ it('a file that never lands costs the bounded wait and nothing else (fail-open, env-less)', async () => {+ if (!tmuxOk) return+ const ghost = path.join(tmp, 'never-staged.env')+ const out = path.join(tmp, 'ghost-pane')+ const t0 = Date.now()+ const prologue = `_nte=0; while [ ! -f '${ghost}' ] && [ "$_nte" -lt 6 ]; do sleep 0.05; _nte=$((_nte+1)); done; [ -f '${ghost}' ] && . '${ghost}' >/dev/null 2>&1; rm -f '${ghost}';`+ execFileSync(+ '/bin/sh',+ ['-c', `${prologue} tmux -L ${SOCKET} new-session -d -s ghost 'echo "TOKEN=[$ANTHROPIC_AUTH_TOKEN]" > ${out}'`],+ { stdio: ['ignore', 'pipe', 'pipe'], env: (() => { const e = { ...process.env }; delete e.ANTHROPIC_AUTH_TOKEN; return e })() }+ )+ // 6 × 50ms wait budget, then the session still launched — without the env.+ expect(Date.now() - t0).toBeGreaterThanOrEqual(250)+ expect(await waitFor(out)).toBe('TOKEN=[]\n')+ })+})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex d2d4e9f88..5cf630b76 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -37,6 +37,7 @@ import {remoteNodeTokenMinter,setRemoteNodeTokenWriter} from '../../core/agents/node-token-service'+import { setRemoteSessionEnvWriter } from '../../core/remote-ssh/session-env'import { askpassServer } from './ssh-askpass'import { appSshAgent } from './ssh-agent'import { sessionName } from '../../core/tmux-naming'@@ -1016,6 +1017,36 @@ export class SshProjectManager {* absolute) and a verified tunnel (`hookEndpointPath` ⇒ the endpoint file that names the token* dir actually exists on the host).*/+ /**+ * Stage a per-session env file on the host (0600, content over stdin — values never touch an+ * argv on either machine). The spawn path fires this and forgets it; the remote command's+ * bounded wait bridges the race, and a write that never lands only costs the agent its+ * gateway/custom env (it fails loudly in its own pane). Path safety: `remotePath` is built+ * core-side from the connection's VALIDATED remote $HOME (`isSafeRemoteHome`) plus the+ * sanitized tmux session name, and is `posixQuote`d again here at the splice point.+ */+ async writeSessionEnvFile(controlPath: string, remotePath: string, content: string): Promise<void> {+ try {+ for (const c of this.conns.values()) {+ if (c.controlPath !== controlPath) continue+ // Refuse a path that is not under a known-safe home shape — belt to the builder's braces.+ if (/[\0\n\r'"`$\\]/.test(remotePath) || !remotePath.startsWith('/')) return+ const dir = remotePath.slice(0, remotePath.lastIndexOf('/'))+ await this.r.run(+ childArgs(+ c.conn,+ c.controlPath,+ `umask 077; mkdir -p ${posixQuote(dir)} && cat > ${posixQuote(remotePath)}`+ ),+ content+ )+ return+ }+ } catch {+ /* fail-open: never let an env write reach a pty spawn */+ }+ }+async writeNodeTokenForNode(controlPath: string, nodeId: string): Promise<void> {try {for (const c of this.conns.values()) {@@ -1668,6 +1699,11 @@ export function initSshProject(setRemoteNodeTokenWriter((controlPath, nodeId) => {void mgr.writeNodeTokenForNode(controlPath, nodeId)})+ // Same seam, same shape: the pty spawn path stages a remote session's env file (gateway/custom+ // values, argv-free) through the manager that owns the ssh runner. See core/remote-ssh/session-env.ts.+ setRemoteSessionEnvWriter((controlPath, remotePath, content) => {+ void mgr.writeSessionEnvFile(controlPath, remotePath, content)+ })// Registered after `mgr` exists so the dialog can name the server: the askpass request carries// the asking master's pid, and only the manager can map it back to a connection.askpassServer.setPromptHandler((req) =>diff --git a/src/shared/agents/model-gateway.test.ts b/src/shared/agents/model-gateway.test.tsindex 15c872aba..7144f890c 100644--- a/src/shared/agents/model-gateway.test.ts+++ b/src/shared/agents/model-gateway.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'import {+ MODEL_GATEWAY_ENV_KEYS,MODEL_GATEWAY_SECRET_REF,modelGatewayEnv,modelGatewayCredentialKind,@@ -219,3 +220,25 @@ describe('agent mappings', () => {}})})++describe('MODEL_GATEWAY_ENV_KEYS lockstep', () => {+ it('covers every var any capability base can emit — a missed key never reaches a shared tmux server', () => {+ const gateway = { baseUrl: 'https://gw.example.test', apiKey: 'vk-1' }+ const seen = new Set<string>()+ for (const id of ['claude', 'codex', 'gemini', 'grok', 'copilot'] as const) {+ for (const k of Object.keys(+ modelGatewayEnv(gateway, id, 'openai/gpt-5.5-codex')+ ))+ seen.add(k)+ // The gpt-5 responses-API marker only appears for a gpt-5-family OpenAI model.+ for (const k of Object.keys(modelGatewayEnv(gateway, id, 'openai/gpt-5')))+ seen.add(k)+ for (const k of Object.keys(+ modelGatewayEnv(gateway, id, 'anthropic/claude-sonnet-5')+ ))+ seen.add(k)+ }+ expect(seen.size).toBeGreaterThan(0)+ for (const k of seen) expect(MODEL_GATEWAY_ENV_KEYS).toContain(k)+ })+})diff --git a/src/shared/agents/model-gateway.ts b/src/shared/agents/model-gateway.tsindex 7e31430c9..750561e53 100644--- a/src/shared/agents/model-gateway.ts+++ b/src/shared/agents/model-gateway.ts@@ -165,6 +165,48 @@ export function modelsForAgent(models: GatewayModel[], agentId: AgentId): Gatewa* its internal + wire model ids in environment variables. Credentials never enter a restart* command, so none are exposed in the pane.*/+/** Every env var name `modelGatewayEnv` can emit, in one place. The tmux confs bake this list+ * into `update-environment`, which is HOW gateway credentials reach a pane without ever touching+ * an argv: the values ride the tmux CLIENT's process environment (or a sourced 0600 file over+ * SSH), and tmux copies the listed names into the session environment at create/attach. A key+ * emitted here but missing from this list would silently fail to reach the agent on a shared+ * tmux server — model-gateway.test.ts asserts the lockstep. */+export const MODEL_GATEWAY_ENV_KEYS = [+ 'ANTHROPIC_BASE_URL',+ 'ANTHROPIC_AUTH_TOKEN',+ 'OPENAI_BASE_URL',+ 'OPENAI_API_KEY',+ 'COPILOT_PROVIDER_BASE_URL',+ 'COPILOT_PROVIDER_TYPE',+ 'COPILOT_PROVIDER_API_KEY',+ 'COPILOT_PROVIDER_MODEL_ID',+ 'COPILOT_PROVIDER_WIRE_MODEL',+ 'COPILOT_PROVIDER_WIRE_API'+] as const++/** tmux's own stock `update-environment` entries (tmux 3.4 defaults, measured via+ * `show-options -g`). Assigning the option as a whole REPLACES the array, so the defaults must be+ * restated or SSH agent forwarding et al. silently break. */+const TMUX_STOCK_UPDATE_ENV = [+ 'DISPLAY',+ 'KRB5CCNAME',+ 'SSH_ASKPASS',+ 'SSH_AUTH_SOCK',+ 'SSH_AGENT_PID',+ 'SSH_CONNECTION',+ 'WINDOWID',+ 'XAUTHORITY'+]++/** The `update-environment` conf line both tmux confs (local + remote) bake in. This is the+ * argv-free credential path: gateway values sit in the tmux CLIENT's process environment (never+ * on a command line), and tmux copies the listed names into the session env on create/attach —+ * MEASURED on tmux 3.4: the pane sees the value, a client withOUT the var strips it from its own+ * session (no cross-session bleed into plain terminals), and re-sourcing the conf is idempotent. */+export function tmuxUpdateEnvironmentLine(): string {+ return `set -g update-environment "${[...TMUX_STOCK_UPDATE_ENV, ...MODEL_GATEWAY_ENV_KEYS].join(' ')}"`+}+export function modelGatewayEnv(settings: ModelGatewaySettings,agentId: AgentId,diff --git a/src/shared/ssh.ts b/src/shared/ssh.tsindex 330215469..b92fac088 100644--- a/src/shared/ssh.ts+++ b/src/shared/ssh.ts@@ -1,3 +1,4 @@+import { tmuxUpdateEnvironmentLine } from './agents/model-gateway'/*** Pure helpers for launching the system `ssh` binary as a terminal session program.* No Electron, no node-pty — unit-testable in isolation.@@ -279,6 +280,11 @@ set -g default-terminal "xterm-256color"set -sg escape-time 10set -g destroy-unattached offsetw -g aggressive-resize on+# Credentials travel HERE, not on argv: over SSH the gateway/custom env is sourced from a 0600+# file into the remote tmux client's environment, and update-environment copies the listed names+# into the session at create/attach. The old '-e KEY=VALUE' route parked the values on the LOCAL+# ssh client's command line for the whole session (and on the remote process table at creation).+${tmuxUpdateEnvironmentLine()}# OSC 52 to the client, which writes the LOCAL clipboard. BOTH lines are needed on tmux 3.2+ — see# remoteTmuxConf's doc comment before touching either.# MIGRATION — do not remove. Older versions of this file blanked smcup/rmcup/indn via