Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -57,14 +61,24 @@ 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
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;
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/commands/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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;
Expand Down
22 changes: 17 additions & 5 deletions packages/cli/src/lib/agent-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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); });
Expand Down
33 changes: 25 additions & 8 deletions packages/cli/src/lib/agent-setup.ts
Original file line number Diff line number Diff line change
@@ -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];
Expand All @@ -20,6 +21,7 @@ export interface SetupPlan {
entry: { command: string; args: string[] };
actions: FileAction[];
manual: string[];
notes: string[];
}
const snapshots = new WeakMap<SetupPlan, Map<string, string | null>>();

Expand Down Expand Up @@ -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<string, string | null>();
const add = (rel: string, content: string, expectedOriginal?: string | null) => {
const path = join(project, rel);
Expand Down Expand Up @@ -124,16 +126,16 @@ 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 ?? "";
const suffix = entries.join("\n") + "\n";
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.");
Expand All @@ -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);
Expand Down Expand Up @@ -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 {
Expand All @@ -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: [] }; }
});
}
16 changes: 12 additions & 4 deletions packages/cli/tests/agent-setup-windows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Loading
Loading