From 8b4bf9ff804387022ef508197cbc2667d37ce9b5 Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sun, 18 Oct 2026 00:50:37 -0700 Subject: [PATCH] fix: harden agent launcher environment and private setup writes --- packages/cli/README.md | 20 ++++++- packages/cli/src/commands/agent.ts | 6 +- packages/cli/src/lib/agent-launcher.ts | 22 +++++-- packages/cli/src/lib/agent-setup.ts | 33 ++++++++--- .../cli/tests/agent-setup-windows.test.ts | 16 +++-- packages/cli/tests/agent-setup.test.ts | 58 ++++++++++++++++++- 6 files changed, 130 insertions(+), 25 deletions(-) diff --git a/packages/cli/README.md b/packages/cli/README.md index 516385f..43c75ce 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -24,9 +24,12 @@ entries exclude backups and `.affitor/.env`. Updates use atomic replacement and read-back, rolling back prior writes on failure. Backups and their local ignore guard are kept on failure so a restored root `.gitignore` cannot expose them. An existing backup guard must contain only `*`; negation or extra rules are refused. +It is installed before any merged config is written. Temporary writes stay under +this private, ignored backup directory, including after abrupt process termination. Credential and backup ignore rules are appended at the end of both the root `.gitignore` and `.affitor/.gitignore`, preserving earlier custom rules while -overriding negations. Existing files are backed up before changing them. +overriding negations. Existing files are backed up before changing them. The child +guard also protects `credentials.json` when a project directory is your home. A concurrent edit is preserved; inspect the files and private backups before retrying. This protects ordinary local edits, not a hostile process racing filesystem operations. @@ -46,7 +49,8 @@ A recovery skill is installed in `.claude/skills/affitor/` or `.cursor/skills/af Codex gets `.agents/skills/affitor/` and a printed `codex mcp add` command; setup does not edit its TOML config or run that command. Review it, then run it yourself. If you move the project, run setup again to update absolute paths. The printed -command uses POSIX shell quoting on macOS/Linux. On Windows, no shell command +command uses POSIX shell quoting on macOS/Linux. Plan notes flag machine-specific +absolute paths: keep generated MCP configs local or regenerate on each machine. On Windows, no shell command is generated: add the MCP in Codex settings using `command: "node"` and the exact absolute path from the preview's `entry.args` as one argument. Do not paste POSIX commands into cmd.exe. @@ -57,7 +61,11 @@ or prove the key works. It returns `aligned`/`stale`/`missing`/`manual`/`invalid per client and `present_unverified`/`missing` for credentials. With no selection, doctor checks existing JSON client configs; an agent caller checks itself. Exit0 means all selected static checks align and a credential is present; -otherwise exit1. Restart the agent and ask it to call `affitor_readiness`, checking +otherwise exit1. A `credential_tracked` warning also returns exit1: doctor checks +Git when available without changing its index, including when the repository root is above the +project. Rotate an exposed key and remove it from tracking/history using your +repository process; adding an ignore rule does not untrack a credential. +Restart the agent and ask it to call `affitor_readiness`, checking the program identity before integration. Only report the readiness checks that pass. Doctor and the launcher use the same credential parser: empty, duplicate and @@ -65,6 +73,12 @@ interpolated assignments fail closed. An explicit nonempty environment value takes precedence and is validated without reading a file. On Windows, the launcher runs `npx.cmd` through `cmd.exe` with a constant command; project paths and credentials are passed through `cwd`/environment, outside shell text. +`NoDefaultCurrentDirectoryInExePath=1` prevents a project-root `npx.cmd` from +shadowing the PATH executable. The child receives only runtime paths, home/temp, +locale/terminal settings and the program key; parent proxy, Node options, npm +overrides and unrelated credentials are dropped. The public npm registry is +explicit. Project code, the generated launcher, PATH and project `.npmrc` still +belong to your trusted local environment; this installer is not a sandbox. This local installer uses an existing program key. Per-agent key issuance, pairing, connection telemetry, and the dashboard Agents page are separate work; diff --git a/packages/cli/src/commands/agent.ts b/packages/cli/src/commands/agent.ts index f070a07..a34d7c4 100644 --- a/packages/cli/src/commands/agent.ts +++ b/packages/cli/src/commands/agent.ts @@ -32,7 +32,7 @@ export function registerAgentCommands(program: Command) { project: plan.project, clients, caller: callerClient(process.env) ?? null, entry: plan.entry, mcpVersion: plan.mcpVersion, actions: plan.actions.map(({ path, operation, backup }) => ({ path, operation, backup })), - manual: plan.manual, + manual: plan.manual, notes: plan.notes, }; let status = opts.dryRun ? "planned" : "needs_confirmation"; if (!flags.json) process.stdout.write(JSON.stringify(preview, null, 2) + "\n"); @@ -69,8 +69,8 @@ export function registerAgentCommands(program: Command) { const clients = selectedClients(opts.client ?? [], process.env); const configured = CLIENTS.filter(client => client !== "codex" && existsSync(join(process.cwd(), client === "claude_code" ? ".mcp.json" : ".cursor/mcp.json"))); const results = doctor(process.cwd(), clients.length ? clients : configured.length ? configured : ["claude_code", "cursor"]); - const healthy = results.every(result => result.status === "aligned" && result.credential === "present_unverified"); - const result = { status: healthy ? "aligned" : "needs_attention", mode: "static", clients: results, next: "Restart the selected agent and call affitor_readiness. Static checks do not prove a live connection or integration readiness." }; + const healthy = results.every(result => result.status === "aligned" && result.credential === "present_unverified" && result.warnings.length === 0); + const result = { status: healthy ? "aligned" : "needs_attention", mode: "static", clients: results, next: "Restart the selected agent and call affitor_readiness. A credential_tracked warning requires rotating the key and removing it from Git tracking/history through your repository process. Static checks do not prove a live connection or integration readiness." }; if (getFlags(cmd).json) process.stdout.write(JSON.stringify(result) + "\n"); else process.stdout.write(JSON.stringify(result, null, 2) + "\n"); process.exitCode = healthy ? 0 : 1; diff --git a/packages/cli/src/lib/agent-launcher.ts b/packages/cli/src/lib/agent-launcher.ts index 7784355..49a738e 100644 --- a/packages/cli/src/lib/agent-launcher.ts +++ b/packages/cli/src/lib/agent-launcher.ts @@ -17,6 +17,20 @@ export function parseProgramCredential(envKey: unknown, readText: () => string | } catch { return null; } } +/** Minimal runtime environment; never forward parent networking, Node or npm overrides. */ +export function agentChildEnvironment(source: NodeJS.ProcessEnv, key: string): NodeJS.ProcessEnv { + const allowed = ["PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT", "TMP", "TEMP", "TMPDIR", "LANG", "TERM", "COLORTERM", "NO_COLOR", "FORCE_COLOR"]; + const env: NodeJS.ProcessEnv = {}; + for (const [name, value] of Object.entries(source)) { + const canonical = name.toUpperCase(); + if (allowed.includes(canonical) || /^LC_[A-Z_]+$/.test(canonical)) env[canonical] = value; + } + env.NoDefaultCurrentDirectoryInExePath = "1"; + env.AFFITOR_API_KEY = key; + env.AFFITOR_MCP_WRITE = "0"; + return env; +} + export const AGENT_LAUNCHER = `// Generated by affitor agent setup. Contains no credentials. const { readFileSync, lstatSync } = require('node:fs'); const { join, resolve } = require('node:path'); @@ -34,15 +48,13 @@ if (!key) { process.exit(1); } // Setup never opts into the sale/refund tools, including through inherited env. -const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => - !['AFFITOR_API_URL', 'AFFITOR_API_KEY', 'AFFITOR_MCP_WRITE'].includes(name.toUpperCase()))); -env.AFFITOR_API_KEY = key; -env.AFFITOR_MCP_WRITE = '0'; +const agentChildEnvironment = ${agentChildEnvironment.toString()}; +const env = agentChildEnvironment(process.env, key); // Windows batch files require cmd.exe. The command contains constants only: // project paths and credentials travel through cwd/env, never shell text. const windows = process.platform === 'win32'; const command = windows ? (process.env.ComSpec || 'cmd.exe') : 'npx'; -const args = windows ? ['/d', '/s', '/c', 'npx.cmd -y @affitor/mcp@${MCP_VERSION}'] : ['-y', '@affitor/mcp@${MCP_VERSION}']; +const args = windows ? ['/d', '/s', '/c', 'npx.cmd --registry=https://registry.npmjs.org -y @affitor/mcp@${MCP_VERSION}'] : ['--registry=https://registry.npmjs.org', '-y', '@affitor/mcp@${MCP_VERSION}']; const child = spawn(command, args, { cwd: project, env, stdio: 'inherit', shell: false, windowsHide: true }); child.on('error', () => { process.stderr.write('Affitor: could not start the pinned MCP. Check Node.js, npm and network access.\\n'); process.exitCode = 1; }); child.on('exit', (code, signal) => { process.exitCode = signal ? 1 : (code ?? 1); }); diff --git a/packages/cli/src/lib/agent-setup.ts b/packages/cli/src/lib/agent-setup.ts index e421c0b..23c99d6 100644 --- a/packages/cli/src/lib/agent-setup.ts +++ b/packages/cli/src/lib/agent-setup.ts @@ -1,7 +1,8 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join, relative, resolve } from "node:path"; import { randomUUID } from "node:crypto"; -import { AGENT_LAUNCHER, AGENT_SKILL, MCP_VERSION, parseProgramCredential } from "./agent-launcher.js"; +import { spawnSync } from "node:child_process"; +import { AGENT_LAUNCHER, AGENT_SKILL, MCP_VERSION, parseProgramCredential, agentChildEnvironment } from "./agent-launcher.js"; export const CLIENTS = ["claude_code", "cursor", "codex"] as const; export type AgentClient = typeof CLIENTS[number]; @@ -20,6 +21,7 @@ export interface SetupPlan { entry: { command: string; args: string[] }; actions: FileAction[]; manual: string[]; + notes: string[]; } const snapshots = new WeakMap>(); @@ -78,7 +80,7 @@ export function planSetup(cwd: string, clients: AgentClient[]): SetupPlan { const project = realpathSync(resolve(cwd)); const launcher = join(project, ".affitor/agent-mcp.cjs"); const entry = { command: "node", args: [launcher] }; - const plan: SetupPlan = { project, clients, entry, mcpVersion: MCP_VERSION, actions: [], manual: [] }; + const plan: SetupPlan = { project, clients, entry, mcpVersion: MCP_VERSION, actions: [], manual: [], notes: clients.length ? ["MCP entries contain this machine's absolute project path. Keep configs local or regenerate them on each teammate's machine."] : [] }; const before = new Map(); const add = (rel: string, content: string, expectedOriginal?: string | null) => { const path = join(project, rel); @@ -124,8 +126,8 @@ export function planSetup(cwd: string, clients: AgentClient[]): SetupPlan { // The final matching rule wins at each directory level. Existing negations // must not cancel protection; a child guard also outranks root ignore rules. for (const [rel, entries] of [ - [".gitignore", ["/.affitor/.env", "/.affitor/backups/"]], - [".affitor/.gitignore", ["/.env", "/backups/"]], + [".gitignore", ["/.affitor/.env", "/.affitor/backups/", "/.affitor/credentials.json"]], + [".affitor/.gitignore", ["/.env", "/backups/", "/credentials.json"]], ] as const) { const raw = readTarget(project, join(project, rel)); const prior = raw ?? ""; @@ -133,7 +135,7 @@ export function planSetup(cwd: string, clients: AgentClient[]): SetupPlan { add(rel, prior.endsWith(suffix) ? prior : prior + (prior && !prior.endsWith("\n") ? "\n" : "") + suffix, raw); } } - if (plan.actions.some(action => action.backup)) { + if (clients.length) { const guard = join(project, ".affitor/backups/.gitignore"); const raw = readTarget(project, guard); if (raw !== null && !["*", "*\n", "*\r\n"].includes(raw)) throw new Error("Unsafe setup backup directory: its .gitignore must contain only the '*' rule."); @@ -148,8 +150,16 @@ export function planSetup(cwd: string, clients: AgentClient[]): SetupPlan { function atomicWrite(project: string, path: string, content: string) { safePath(project, path); + const guard = join(project, ".affitor/backups/.gitignore"); + // The guard bootstrap contains only '*'. Every later temp is protected before + // merged config bytes reach disk, even if the process exits before finally. + if (path !== guard) { + const raw = readTarget(project, guard); + if (raw === null || !["*", "*\n", "*\r\n"].includes(raw)) throw new Error("Unsafe setup temporary directory guard."); + } mkdirSync(dirname(path), { recursive: true }); - const temporary = `${path}.affitor-${randomUUID()}.tmp`; + const temporary = join(project, ".affitor/backups", `.temporary-${randomUUID()}.tmp`); + safePath(project, temporary); try { writeFileSync(temporary, content, { mode: 0o600, flag: "wx" }); safePath(project, path); @@ -200,6 +210,13 @@ export function applySetup(plan: SetupPlan, beforeWrite?: (action: FileAction) = } } +function credentialWarnings(project: string): string[] { + const env = agentChildEnvironment(process.env, ""); + delete env.AFFITOR_API_KEY; + const checked = spawnSync("git", ["-C", project, "ls-files", "--error-unmatch", "--", ".affitor/.env"], { env, encoding: "utf8", timeout: 1500, windowsHide: true }); + return checked.status === 0 ? ["credential_tracked"] : []; +} + export function doctor(cwd: string, clients: AgentClient[]) { return clients.map(client => { try { @@ -209,7 +226,7 @@ export function doctor(cwd: string, clients: AgentClient[]) { const stat = lstatSync(keyPath); return stat.isFile() && !stat.isSymbolicLink() ? readFileSync(keyPath, "utf8") : null; }); - return { client, status: client === "codex" ? "manual" : plan.actions.some(a => a.operation === "create") ? "missing" : plan.actions.some(a => a.operation === "update") ? "stale" : "aligned", credential: credential ? "present_unverified" : "missing", liveSession: "not_checked", manual: plan.manual }; - } catch { return { client, status: "invalid", credential: "not_checked", liveSession: "not_checked", manual: [] }; } + return { client, warnings: credentialWarnings(plan.project), notes: plan.notes, status: client === "codex" ? "manual" : plan.actions.some(a => a.operation === "create") ? "missing" : plan.actions.some(a => a.operation === "update") ? "stale" : "aligned", credential: credential ? "present_unverified" : "missing", liveSession: "not_checked", manual: plan.manual }; + } catch { return { client, warnings: [], notes: [], status: "invalid", credential: "not_checked", liveSession: "not_checked", manual: [] }; } }); } diff --git a/packages/cli/tests/agent-setup-windows.test.ts b/packages/cli/tests/agent-setup-windows.test.ts index a12a6f4..fdf305d 100644 --- a/packages/cli/tests/agent-setup-windows.test.ts +++ b/packages/cli/tests/agent-setup-windows.test.ts @@ -6,30 +6,38 @@ import { spawnSync } from "node:child_process"; // Runs on the real Windows CI worker, rather than mocking process.platform. describe.skipIf(process.platform !== "win32")("Windows generated launcher smoke", () => { - it("starts npx.cmd through cmd.exe with a metacharacter project path and no money tools", () => { + it("ignores a cwd npx.cmd decoy and starts the PATH tool with a safe environment", () => { const fixture = realpathSync(mkdtempSync(join(tmpdir(), "affitor-windows-"))); const project = join(fixture, "project & (spaces) %NO_EXPAND%"); const bin = join(project, "bin"); mkdirSync(bin, { recursive: true }); - const env: NodeJS.ProcessEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !["path", "affitor_api_key", "affitor_api_url", "affitor_mcp_write", "claudecode", "codex", "codex_thread_id", "cursor_agent"].includes(key.toLowerCase()))); + const env: NodeJS.ProcessEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !["path", "affitor_api_key", "affitor_api_url", "affitor_mcp_write", "nodefaultcurrentdirectoryinexepath", "claudecode", "codex", "codex_thread_id", "cursor_agent"].includes(key.toLowerCase()))); env.PATH = bin; env.Affitor_Mcp_Write = "1"; env.affitor_api_url = "https://wrong.invalid"; env.NO_EXPAND = "wrong-path"; + env.NODE_OPTIONS = "--no-warnings"; + env.HTTPS_PROXY = "http://wrong.invalid"; + env.npm_config_registry = "https://wrong.invalid"; const cli = resolve("dist/cli.js"); try { const setup = spawnSync(process.execPath, [cli, "agent", "setup", "--client", "claude_code", "--yes", "--json"], { cwd: project, env, encoding: "utf8" }); expect(setup.status, setup.stderr + setup.stdout).toBe(0); writeFileSync(join(project, ".affitor/.env"), "AFFITOR_API_KEY=fake_windows_key\r\n"); - writeFileSync(join(bin, "npx-fixture.cjs"), 'process.stdout.write(JSON.stringify({args:process.argv.slice(2),cwd:process.cwd(),key:process.env.AFFITOR_API_KEY,write:process.env.AFFITOR_MCP_WRITE,overrides:Object.keys(process.env).filter(k=>k.toUpperCase()==="AFFITOR_API_URL"||k.toUpperCase()==="AFFITOR_MCP_WRITE")}));'); + writeFileSync(join(bin, "npx-fixture.cjs"), 'process.stdout.write(JSON.stringify({args:process.argv.slice(2),cwd:process.cwd(),key:process.env.AFFITOR_API_KEY,write:process.env.AFFITOR_MCP_WRITE,noCwd:process.env.NoDefaultCurrentDirectoryInExePath,unsafe:Object.keys(process.env).filter(k=>/^(https?_proxy|node_options|npm_config_registry)$/i.test(k)),overrides:Object.keys(process.env).filter(k=>k.toUpperCase()==="AFFITOR_API_URL"||k.toUpperCase()==="AFFITOR_MCP_WRITE")}));'); writeFileSync(join(bin, "npx.cmd"), `@"${process.execPath}" "%~dp0npx-fixture.cjs" %*\r\n`); + writeFileSync(join(project, "npx.cmd"), "@echo DECOY_CWD\r\n@exit /b 91\r\n"); // Reproduce r1 on the same real Windows worker and the same fixture. const baseline = spawnSync("npx.cmd", ["-y", "@affitor/mcp@0.2.2"], { cwd: project, env, shell: false, encoding: "utf8", timeout: 15000 }); expect(baseline.status).not.toBe(0); expect(baseline.error).toBeDefined(); + // The pre-hardening constant cmd command resolves the decoy from cwd. + const unsafeLookup = spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "npx.cmd -y @affitor/mcp@0.2.2"], { cwd: project, env, encoding: "utf8", timeout: 15000 }); + expect(unsafeLookup.status, unsafeLookup.stderr + unsafeLookup.stdout).toBe(91); + expect(unsafeLookup.stdout).toContain("DECOY_CWD"); const launcher = spawnSync(process.execPath, [join(project, ".affitor/agent-mcp.cjs")], { cwd: fixture, env, encoding: "utf8", timeout: 15000 }); expect(launcher.status, launcher.stderr + launcher.stdout).toBe(0); - expect(JSON.parse(launcher.stdout)).toEqual({ args: ["-y", "@affitor/mcp@0.2.2"], cwd: project, key: "fake_windows_key", write: "0", overrides: ["AFFITOR_MCP_WRITE"] }); + expect(JSON.parse(launcher.stdout)).toEqual({ args: ["--registry=https://registry.npmjs.org", "-y", "@affitor/mcp@0.2.2"], cwd: project, key: "fake_windows_key", write: "0", noCwd: "1", unsafe: [], overrides: ["AFFITOR_MCP_WRITE"] }); const doctor = spawnSync(process.execPath, [cli, "doctor", "--client", "claude_code", "--json"], { cwd: project, env, encoding: "utf8" }); expect(doctor.status, doctor.stderr + doctor.stdout).toBe(0); expect(JSON.parse(doctor.stdout).clients[0].credential).toBe("present_unverified"); diff --git a/packages/cli/tests/agent-setup.test.ts b/packages/cli/tests/agent-setup.test.ts index 770a427..d1ad969 100644 --- a/packages/cli/tests/agent-setup.test.ts +++ b/packages/cli/tests/agent-setup.test.ts @@ -3,6 +3,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSy import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; import { applySetup, doctor, planSetup, selectedClients } from "../src/lib/agent-setup.js"; import { AGENT_LAUNCHER, parseProgramCredential } from "../src/lib/agent-launcher.js"; @@ -77,6 +78,49 @@ describe("local transaction", () => { expect(readFileSync(join(dir, ".affitor/.env"), "utf8")).toBe("AFFITOR_API_KEY=fake_gitignore_key\n"); expect(planSetup(dir, ["claude_code"]).actions.every(a => a.operation === "unchanged")).toBe(true); }); + it("warns that generated MCP entries contain machine-specific absolute paths", () => { + const plan = planSetup(project(), ["claude_code"]); + expect(plan.notes).toContain("MCP entries contain this machine's absolute project path. Keep configs local or regenerate them on each teammate's machine."); + }); + it("protects the global login-token filename when a project is a home directory", () => { + const dir = project(); + expect(spawnSync("git", ["init", "-q", dir]).status).toBe(0); + put(dir, ".affitor/credentials.json", '{"token":"fake_login_token"}'); + applySetup(planSetup(dir, ["claude_code"])); + expect(spawnSync("git", ["-C", dir, "check-ignore", ".affitor/credentials.json"]).status).toBe(0); + expect(readFileSync(join(dir, ".affitor/credentials.json"), "utf8")).toBe('{"token":"fake_login_token"}'); + }); + it("keeps a secret-bearing temp private when the process exits before rename", () => { + const dir = project(); + expect(spawnSync("git", ["init", "-q", dir]).status).toBe(0); + const original = '{"mcpServers":{"other":{"env":{"TOKEN":"fake_private_config"}}}}'; + put(dir, ".mcp.json", original); + const module = pathToFileURL(resolve("dist/lib/agent-setup.js")).href; + const script = `const fs=require('node:fs');const rename=fs.renameSync;fs.renameSync=(from,to)=>{if(fs.readFileSync(from,'utf8').includes('fake_private_config')){process.stdout.write(JSON.stringify({temporary:from}));process.exit(99);}return rename(from,to);};require('node:module').syncBuiltinESMExports();import(${JSON.stringify(module)}).then(({applySetup,planSetup})=>applySetup(planSetup(process.cwd(),['claude_code'])));`; + const child = spawnSync(process.execPath, ["-e", script], { cwd: dir, env: cleanEnv, encoding: "utf8" }); + expect(child.status, child.stderr).toBe(99); + const temporary = JSON.parse(child.stdout).temporary; + expect(readFileSync(join(dir, ".mcp.json"), "utf8")).toBe(original); + expect(spawnSync("git", ["-C", dir, "check-ignore", temporary]).status).toBe(0); + expect(temporary.startsWith(join(dir, ".affitor/backups") + "/")).toBe(true); + expect(existsSync(join(dir, ".gitignore"))).toBe(false); + }); + it("doctor detects tracked credentials when Git root is above the project", () => { + const root = project(), dir = join(root, "nested"); + mkdirSync(dir); + expect(spawnSync("git", ["init", "-q", root]).status).toBe(0); + applySetup(planSetup(dir, ["claude_code"])); + put(dir, ".affitor/.env", "AFFITOR_API_KEY=fake_tracked_key\n"); + expect(spawnSync("git", ["-C", dir, "add", "-f", "--", ".affitor/.env"]).status).toBe(0); + const index = spawnSync("git", ["-C", root, "ls-files", "--stage"], { encoding: "utf8" }).stdout; + const checked = doctor(dir, ["claude_code"])[0]; + expect(checked.warnings).toContain("credential_tracked"); + const result = spawnSync(process.execPath, [resolve("dist/cli.js"), "doctor", "--client", "claude_code", "--json"], { cwd: dir, env: cleanEnv, encoding: "utf8" }); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout).status).toBe("needs_attention"); + expect(result.stdout).not.toContain("fake_tracked_key"); + expect(spawnSync("git", ["-C", root, "ls-files", "--stage"], { encoding: "utf8" }).stdout).toBe(index); + }); it("preserves unrelated entries, backs up original bytes privately, sets0600 and is idempotent", () => { const dir = project(), original = '{ "mcpServers": {"other":{"env":{"TOKEN":"fake-private-value"}}}, "keep":123 }'; put(dir, ".mcp.json", original); @@ -184,7 +228,7 @@ describe("real generated launcher without network", () => { } function install(dir: string) { put(dir, ".affitor/agent-mcp.cjs", AGENT_LAUNCHER); - put(dir, "bin/npx", `#!${process.execPath}\nprocess.stdout.write(JSON.stringify({args:process.argv.slice(2),cwd:process.cwd(),key:process.env.AFFITOR_API_KEY,write:process.env.AFFITOR_MCP_WRITE,url:process.env.AFFITOR_API_URL??null,aliases:Object.keys(process.env).filter(k=>k.toUpperCase()==="AFFITOR_API_URL"||k.toUpperCase()==="AFFITOR_MCP_WRITE")}));\n`); + put(dir, "bin/npx", `#!${process.execPath}\nprocess.stdout.write(JSON.stringify({args:process.argv.slice(2),cwd:process.cwd(),key:process.env.AFFITOR_API_KEY,write:process.env.AFFITOR_MCP_WRITE,url:process.env.AFFITOR_API_URL??null,unsafe:Object.keys(process.env).filter(k=>/^(https?_proxy|all_proxy|node_options|npm_config_registry|unrelated_secret)$/i.test(k)),noCwd:process.env.NoDefaultCurrentDirectoryInExePath??null,aliases:Object.keys(process.env).filter(k=>k.toUpperCase()==="AFFITOR_API_URL"||k.toUpperCase()==="AFFITOR_MCP_WRITE")}));\n`); chmodSync(join(dir, "bin/npx"), 0o700); } it("reads the project program key, pins MCP, fixes cwd and disables inherited money tools", () => { @@ -192,7 +236,7 @@ describe("real generated launcher without network", () => { put(dir, ".affitor/.env", "# fixture only\nexport AFFITOR_API_KEY='fake_program_key'\n"); const result = launch(dir); expect(result.status).toBe(0); - expect(JSON.parse(result.stdout)).toEqual({ args: ["-y", "@affitor/mcp@0.2.2"], cwd: dir, key: "fake_program_key", write: "0", url: null, aliases: ["AFFITOR_MCP_WRITE"] }); + expect(JSON.parse(result.stdout)).toEqual({ args: ["--registry=https://registry.npmjs.org", "-y", "@affitor/mcp@0.2.2"], cwd: dir, key: "fake_program_key", write: "0", url: null, unsafe: [], noCwd: "1", aliases: ["AFFITOR_MCP_WRITE"] }); }); it("removes mixed-case API overrides and write aliases before spawning MCP", () => { const dir = project(); install(dir); @@ -204,6 +248,16 @@ describe("real generated launcher without network", () => { expect(child.write).toBe("0"); expect(child.aliases).toEqual(["AFFITOR_MCP_WRITE"]); }); + it("scrubs proxy, Node options, npm registry and unrelated secrets from the actual child", () => { + const dir = project(); install(dir); + put(dir, ".affitor/.env", "AFFITOR_API_KEY=fake_file_key"); + const result = launch(dir, { HTTPS_PROXY: "http://wrong.invalid", ALL_PROXY: "http://wrong.invalid", NODE_OPTIONS: "--no-warnings", npm_config_registry: "https://wrong.invalid", UNRELATED_SECRET: "fake_unrelated_secret" }); + expect(result.status, result.stderr).toBe(0); + const child = JSON.parse(result.stdout); + expect(child.unsafe).toEqual([]); + expect(child.noCwd).toBe("1"); + expect(child.key).toBe("fake_file_key"); + }); it("prefers an explicitly inherited program key", () => { const dir = project(); install(dir); put(dir, ".affitor/.env", "AFFITOR_API_KEY=fake_file_key");