From 13c3925be1b2a3c4a3b74aa46ab8ef6dd373ab9b Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sat, 17 Oct 2026 23:30:05 -0700 Subject: [PATCH 1/3] feat: add local agent setup and static doctor --- packages/cli/README.md | 54 +++++++ packages/cli/src/cli.ts | 2 + packages/cli/src/commands/agent.ts | 82 ++++++++++ packages/cli/src/lib/agent-launcher.ts | 59 ++++++++ packages/cli/src/lib/agent-setup.ts | 199 +++++++++++++++++++++++++ packages/cli/tests/agent-setup.test.ts | 171 +++++++++++++++++++++ 6 files changed, 567 insertions(+) create mode 100644 packages/cli/src/commands/agent.ts create mode 100644 packages/cli/src/lib/agent-launcher.ts create mode 100644 packages/cli/src/lib/agent-setup.ts create mode 100644 packages/cli/tests/agent-setup.test.ts diff --git a/packages/cli/README.md b/packages/cli/README.md index dc5e382..a646d45 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -2,6 +2,60 @@ CLI-native affiliate tracking. Connect Stripe, track commissions, manage partners -- all from your terminal. +## AI agent setup + +From the project root, preview the local installation before applying it: + +```bash +affitor agent setup --client claude_code --dry-run --json +affitor agent setup --client claude_code --yes +affitor doctor --client claude_code --json +``` + +Choose `claude_code`, `cursor`, or `codex`; repeat `--client` for more than one. +Without a selection, an interactive terminal asks, with nothing selected by default. +Noninteractive runs require `--yes` and a selection. Inside an agent, setup can only +configure that agent. `--dry-run` writes nothing. Without confirmation, setup exits1. + +Claude Code uses project `.mcp.json`; Cursor uses `.cursor/mcp.json`. Existing +unrelated settings are preserved. Existing file bytes are backed up under +`.affitor/backups/` before replacement, with mode0600; generated `.gitignore` +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. +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. + +The generated `.affitor/agent-mcp.cjs` launcher starts pinned `@affitor/mcp@0.2.2` +from this project's absolute directory. No credential is embedded in an agent +config, launcher, or skill. The launcher reads inherited `AFFITOR_API_KEY`, then +this project's `.affitor/.env` (created by `affitor init`). It never reads the user +login token in `~/.affitor/credentials.json`. If `onboard` wrote a key to your root +`.env`, provide it privately as `AFFITOR_API_KEY` when starting the agent instead. +It uses the production API and disables sale/refund tools even when the parent +environment has `AFFITOR_MCP_WRITE=1`. Other tools still include tracking and +synthetic verification; approve those actions separately. + +A recovery skill is installed in `.claude/skills/affitor/` or `.cursor/skills/affitor/`. +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. + +**Installed is not verified.** Successful setup returns `needs_human` (exit0). +`doctor` is read-only and static: it does not start an agent, connect to the API, +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 +the program identity before integration. Only report the readiness checks that pass. + +This local installer uses an existing program key. Per-agent key issuance, +pairing, connection telemetry, and the dashboard Agents page are separate work; +this command does not claim to create or verify an agent connection. + ## Quick Start ```bash diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index d759100..d85cf43 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -13,6 +13,7 @@ import { registerSetupCommand } from "./commands/setup-stripe.js"; import { registerStatusCommand } from "./commands/status.js"; import { registerTestCommand } from "./commands/test.js"; import { registerProgramsCommand } from "./commands/programs.js"; +import { registerAgentCommands } from "./commands/agent.js"; // Read the version from package.json at runtime so `affitor --version` never // drifts from the published package version (dist/cli.js → ../package.json). @@ -72,5 +73,6 @@ registerSetupCommand(program); registerStatusCommand(program); registerTestCommand(program); registerProgramsCommand(program); +registerAgentCommands(program); program.parse(); diff --git a/packages/cli/src/commands/agent.ts b/packages/cli/src/commands/agent.ts new file mode 100644 index 0000000..9ff5d91 --- /dev/null +++ b/packages/cli/src/commands/agent.ts @@ -0,0 +1,82 @@ +import type { Command } from "commander"; +import { checkbox, confirm } from "@inquirer/prompts"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { CLIENTS, applySetup, callerClient, doctor, planSetup, selectedClients } from "../lib/agent-setup.js"; +import { getFlags } from "../lib/flags.js"; + +interface SetupOptions { client?: string[]; dryRun?: boolean; yes?: boolean } + +export function registerAgentCommands(program: Command) { + program.command("agent").description("Configure an AI coding agent for this project") + .command("setup") + .description("Preview and install project-scoped MCP configuration and an Affitor skill") + .option("--client ", "claude_code, cursor or codex (repeat to select)", (value: string, prior: string[]) => [...prior, value], []) + .option("--dry-run", "Show the plan without writing files") + .option("--yes", "Apply the selected client's plan") + .action(async (opts: SetupOptions, cmd: Command) => { + const flags = getFlags(cmd); + try { + let clients = selectedClients(opts.client ?? [], process.env); + const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY && !flags.noInteractive && !flags.json); + if (!clients.length && interactive && !opts.dryRun) { + clients = selectedClients(await checkbox({ + message: "Which agents should get Affitor in this project?", + choices: CLIENTS.map(value => ({ value, name: `${value}${existsSync(join(process.cwd(), value === "claude_code" ? ".claude" : value === "cursor" ? ".cursor" : ".agents")) ? " (project directory found)" : ""}`, checked: false })), + }), process.env); + } + const plan = planSetup(process.cwd(), clients); + // Never serialize plan.actions.content: existing configs can contain + // unrelated credentials that must stay local, including in a dry-run. + const preview = { + 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, + }; + let status = opts.dryRun ? "planned" : "needs_confirmation"; + if (!flags.json) process.stdout.write(JSON.stringify(preview, null, 2) + "\n"); + let approved = Boolean(opts.yes || flags.autoConfirm); + if (!opts.dryRun && clients.length && !approved && interactive) { + approved = await confirm({ message: "Apply this plan? Existing files are backed up first.", default: false }); + } + if (!opts.dryRun && approved && clients.length) { + applySetup(plan); + status = "needs_human"; + } + const next = !clients.length + ? "Select --client claude_code, cursor or codex. Detected agents are not selected automatically." + : status === "needs_confirmation" + ? "Review the plan, then run affitor agent setup --client --yes." + : "Installed is not verified. Configure the program key privately as AFFITOR_API_KEY or in .affitor/.env; restart the selected agent, then ask it to call affitor_readiness. For Codex, first run the printed manual command."; + if (flags.json) process.stdout.write(JSON.stringify({ status, ...preview, next }) + "\n"); + else process.stdout.write(`${status}\n${next}\n`); + process.exitCode = status === "needs_confirmation" || (!clients.length && !opts.dryRun) ? 1 : 0; + } catch (error) { + // Expected installer errors contain only fixed messages and relative + // client paths. Do not print arbitrary fs/JSON/credential exceptions. + const message = error instanceof Error && /^(Unknown client|An agent can only|\.mcp\.json |\.cursor\/mcp\.json |Setup failed|A setup file|Unsafe setup|Setup target)/.test(error.message) + ? error.message : "Agent setup could not finish. Check the project paths and run a fresh dry-run."; + process.stdout.write(JSON.stringify({ status: "error", message }) + "\n"); + process.exitCode = 1; + } + }); + + program.command("doctor").description("Read-only static check of local agent configuration; does not verify a running session") + .option("--client ", "Check one client (repeat to select)", (value: string, prior: string[]) => [...prior, value], []) + .action((opts: SetupOptions, cmd: Command) => { + try { + 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." }; + 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; + } catch { + process.stdout.write(JSON.stringify({ status: "error", message: "Doctor could not check the selected client. Use claude_code, cursor or codex." }) + "\n"); + process.exitCode = 1; + } + }); +} diff --git a/packages/cli/src/lib/agent-launcher.ts b/packages/cli/src/lib/agent-launcher.ts new file mode 100644 index 0000000..44c9cbe --- /dev/null +++ b/packages/cli/src/lib/agent-launcher.ts @@ -0,0 +1,59 @@ +// Kept as a standalone CommonJS file in the customer's project: a client can +// start it from any directory, without putting a credential in its MCP config. +export const MCP_VERSION = "0.2.2"; +export const AGENT_LAUNCHER = `// Generated by affitor agent setup. Contains no credentials. +const { readFileSync, lstatSync } = require('node:fs'); +const { join, resolve } = require('node:path'); +const { spawn } = require('node:child_process'); +const project = resolve(__dirname, '..'); +let key = process.env.AFFITOR_API_KEY; +if (!key) { + try { + const path = join(__dirname, '.env'); + if (!lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error(); + const lines = readFileSync(path, 'utf8').split(/\\r?\\n/); + const values = lines.filter(line => /^\\s*(?:export\\s+)?AFFITOR_API_KEY\\s*=/.test(line)); + if (values.length !== 1) throw new Error(); + key = values[0].replace(/^\\s*(?:export\\s+)?AFFITOR_API_KEY\\s*=\\s*/, '').trim(); + if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) key = key.slice(1, -1); + if (!/^[A-Za-z0-9_-]+$/.test(key)) throw new Error(); + } catch { + process.stderr.write('Affitor: set AFFITOR_API_KEY or configure this project with affitor init. No agent call was made.\\n'); + process.exit(1); + } +} +// Setup never opts into the sale/refund tools, including through inherited env. +const env = { ...process.env, AFFITOR_API_KEY: key, AFFITOR_MCP_WRITE: '0' }; +delete env.AFFITOR_API_URL; +const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['-y', '@affitor/mcp@${MCP_VERSION}'], { cwd: project, env, stdio: 'inherit', shell: false }); +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); }); +for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal)); +`; + +export const AGENT_SKILL = `--- +name: affitor +description: Check Affitor affiliate integration readiness and follow its integration runbook. +metadata: + version: "1" +--- + +# Affitor + +Connect only when this project needs Affitor. Follow https://affitor.com/docs/skill.md +and the founder's optional context. Detect the framework and payment provider first. +Never print, copy into a prompt, or commit credentials. Never treat a user login token +as a program key. Do not add a second sale writer when Stripe Connect may record sales. + +Installed, signed in, and verified are different states. After restarting the client, +call affitor_readiness and check the program identity before changing this project. +Only describe checks that actually passed. A static doctor cannot prove a live session. +Do not run sale/refund tools. Ask before running synthetic verification or other writes. + +| Problem | Next step | +| --- | --- | +| Missing or stale local files | Run affitor agent setup --dry-run --json, show the plan, then apply the selected client after approval. | +| Files aligned, tools absent | Restart the selected agent, then call affitor_readiness. | +| Credential missing or rejected | Configure AFFITOR_API_KEY privately for this program. Never paste the key into chat. | +| Readiness fails | Report the failed checks and follow the runbook; do not claim integration is verified. | +`; diff --git a/packages/cli/src/lib/agent-setup.ts b/packages/cli/src/lib/agent-setup.ts new file mode 100644 index 0000000..b0a85b3 --- /dev/null +++ b/packages/cli/src/lib/agent-setup.ts @@ -0,0 +1,199 @@ +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 } from "./agent-launcher.js"; + +export const CLIENTS = ["claude_code", "cursor", "codex"] as const; +export type AgentClient = typeof CLIENTS[number]; +type JsonObject = Record; +export interface FileAction { + path: string; + operation: "create" | "update" | "unchanged"; + backup: string | null; + // May include unrelated secrets from an existing config. Never serialize this field. + content: string; +} +export interface SetupPlan { + project: string; + clients: AgentClient[]; + mcpVersion: string; + entry: { command: string; args: string[] }; + actions: FileAction[]; + manual: string[]; +} +const snapshots = new WeakMap>(); + +export function object(value: unknown): value is JsonObject { + return !!value && typeof value === "object" && !Array.isArray(value); +} + +/** Refuse symlinks anywhere below the canonical project directory. */ +function safePath(project: string, path: string) { + const rel = relative(project, path); + if (!rel || rel.startsWith("..") || resolve(project, rel) !== path) throw new Error("Unsafe setup target."); + let current = project; + for (const part of rel.split(/[\\/]/)) { + current = join(current, part); + if (!existsSync(current)) { + // existsSync follows symlinks, including dangling ones. + try { if (lstatSync(current).isSymbolicLink()) throw new Error("Setup target is a symlink."); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } + continue; + } + const stat = lstatSync(current); + if (stat.isSymbolicLink() || (current === path ? !stat.isFile() || stat.nlink !== 1 : !stat.isDirectory())) { + throw new Error("Setup target must be a regular file with no symlink parents."); + } + } +} + +function readTarget(project: string, path: string): string | null { + safePath(project, path); + if (!existsSync(path)) return null; + const bytes = readFileSync(path); + const text = bytes.toString("utf8"); + if (!Buffer.from(text, "utf8").equals(bytes)) throw new Error("Setup target must contain valid UTF-8. Nothing was written."); + return text; +} + +function configFile(client: AgentClient) { + return client === "claude_code" ? ".mcp.json" : ".cursor/mcp.json"; +} + +export function callerClient(env: NodeJS.ProcessEnv): AgentClient | undefined { + if (env.CLAUDECODE) return "claude_code"; + if (env.CODEX || env.CODEX_THREAD_ID) return "codex"; + if (env.CURSOR_AGENT) return "cursor"; + return undefined; +} + +export function selectedClients(names: string[], env: NodeJS.ProcessEnv): AgentClient[] { + if (names.some(name => !CLIENTS.includes(name as AgentClient))) throw new Error("Unknown client. Choose claude_code, cursor or codex."); + const caller = callerClient(env); + if (caller && names.some(name => name !== caller)) throw new Error("An agent can only configure itself. Run setup in your own terminal for other clients."); + return [...new Set(names.length ? names as AgentClient[] : caller ? [caller] : [])]; +} + +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 before = new Map(); + const add = (rel: string, content: string, expectedOriginal?: string | null) => { + const path = join(project, rel); + const original = readTarget(project, path); + if (expectedOriginal !== undefined && original !== expectedOriginal) throw new Error("A setup file changed while planning. Run setup again."); + const backup = original !== null && original !== content ? join(project, ".affitor/backups", `${rel}.affitor.bak`) : null; + if (backup) { + safePath(project, backup); + // An earlier first snapshot stays intact; reject an unsafe backup, never overwrite it. + if (existsSync(backup)) readTarget(project, backup); + } + before.set(path, original); + plan.actions.push({ path, content, backup, operation: original === content ? "unchanged" : original === null ? "create" : "update" }); + }; + const editable = clients.filter(client => client !== "codex"); + for (const client of editable) { + const rel = configFile(client); + const path = join(project, rel); + const raw = readTarget(project, path); + let config: unknown; + try { config = raw === null ? {} : JSON.parse(raw); } + catch { throw new Error(`${rel} is not valid JSON. Nothing was written.`); } + if (!object(config) || (config.mcpServers !== undefined && !object(config.mcpServers))) { + throw new Error(`${rel} must contain an object with an mcpServers object. Nothing was written.`); + } + config.mcpServers = { ...(config.mcpServers as JsonObject | undefined), affitor: entry }; + add(rel, JSON.stringify(config, null, 2) + "\n", raw); + add(client === "claude_code" ? ".claude/skills/affitor/SKILL.md" : ".cursor/skills/affitor/SKILL.md", AGENT_SKILL); + } + if (clients.includes("codex")) { + plan.manual.push(`codex mcp add affitor -- node '${launcher.replaceAll("'", "'\"'\"'")}'`); + // Installing a shared skill and launcher needs the same explicit consent. + add(".agents/skills/affitor/SKILL.md", AGENT_SKILL); + } + if (clients.length) { + add(".affitor/agent-mcp.cjs", AGENT_LAUNCHER); + const path = join(project, ".gitignore"); + const raw = readTarget(project, path); + const prior = raw ?? ""; + const entries = ["/.affitor/.env", "/.affitor/backups/"]; + const missing = entries.filter(line => !prior.split(/\r?\n/).includes(line)); + add(".gitignore", missing.length ? prior + (prior && !prior.endsWith("\n") ? "\n" : "") + missing.join("\n") + "\n" : prior, raw); + } + if (plan.actions.some(action => action.backup)) { + const guard = join(project, ".affitor/backups/.gitignore"); + const raw = readTarget(project, guard); + if (raw !== null && !raw.split(/\r?\n/).includes("*")) throw new Error("Unsafe setup backup directory: its .gitignore must ignore all files."); + add(".affitor/backups/.gitignore", raw ?? "*\n", raw); + // Protect secret-containing backups before creating the first one. Keep this + // guard with backups on rollback even if the root .gitignore is restored. + plan.actions.unshift(plan.actions.pop()!); + } + snapshots.set(plan, before); + return plan; +} + +function atomicWrite(project: string, path: string, content: string) { + safePath(project, path); + mkdirSync(dirname(path), { recursive: true }); + const temporary = `${path}.affitor-${randomUUID()}.tmp`; + try { + writeFileSync(temporary, content, { mode: 0o600, flag: "wx" }); + safePath(project, path); + renameSync(temporary, path); + if (readFileSync(path, "utf8") !== content) throw new Error("Setup read-back failed."); + } finally { rmSync(temporary, { force: true }); } +} + +/** Local, synchronous transaction. It detects ordinary concurrent edits; it is not a local sandbox. */ +export function applySetup(plan: SetupPlan, beforeWrite?: (action: FileAction) => void) { + const before = snapshots.get(plan); + if (!before) throw new Error("Generate a fresh setup plan before applying it."); + const applied: FileAction[] = []; + let backupCreated = false; + try { + for (const action of plan.actions) { + if (readTarget(plan.project, action.path) !== before.get(action.path)) throw new Error("A setup file changed after planning. Run setup again."); + } + for (const action of plan.actions.filter(action => action.operation !== "unchanged")) { + beforeWrite?.(action); + if (readTarget(plan.project, action.path) !== before.get(action.path)) throw new Error("A setup file changed after planning. Run setup again."); + if (action.backup && !existsSync(action.backup)) { + safePath(plan.project, action.backup); + mkdirSync(dirname(action.backup), { recursive: true }); + backupCreated = true; + writeFileSync(action.backup, before.get(action.path)!, { flag: "wx", mode: 0o600 }); + } + applied.push(action); + atomicWrite(plan.project, action.path, action.content); + } + } catch { + let concurrent = false; + for (const action of applied.reverse()) { + // Never restore over a newer edit by somebody else. + try { + const original = before.get(action.path)!; + const current = readTarget(plan.project, action.path); + if (backupCreated && action.path === join(plan.project, ".affitor/backups/.gitignore") && original === null && current === action.content) continue; + if (current === original) continue; + if (current !== action.content) { concurrent = true; continue; } + if (original === null) rmSync(action.path); + else atomicWrite(plan.project, action.path, original); + } catch { concurrent = true; } + } + throw new Error(concurrent ? "Setup failed; a concurrent edit was preserved. Check the files and private backups before retrying." : "Setup failed. Written files were rolled back; private backups were kept. Run a fresh dry-run."); + } +} + +export function doctor(cwd: string, clients: AgentClient[]) { + return clients.map(client => { + try { + const plan = planSetup(cwd, [client]); + const keyPath = join(plan.project, ".affitor/.env"); + const credential = Boolean(process.env.AFFITOR_API_KEY) || (existsSync(keyPath) && !lstatSync(keyPath).isSymbolicLink() && lstatSync(keyPath).isFile() && /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*\S+/m.test(readFileSync(keyPath, "utf8"))); + 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: [] }; } + }); +} diff --git a/packages/cli/tests/agent-setup.test.ts b/packages/cli/tests/agent-setup.test.ts new file mode 100644 index 0000000..2cfbd5c --- /dev/null +++ b/packages/cli/tests/agent-setup.test.ts @@ -0,0 +1,171 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { spawnSync } from "node:child_process"; +import { applySetup, doctor, planSetup, selectedClients } from "../src/lib/agent-setup.js"; +import { AGENT_LAUNCHER } from "../src/lib/agent-launcher.js"; + +const fixtures: string[] = []; +function project() { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "affitor-agent-test-"))); + fixtures.push(dir); + return dir; +} +function put(dir: string, path: string, content: string) { + const file = join(dir, path); + mkdirSync(resolve(file, ".."), { recursive: true }); + writeFileSync(file, content); +} +const cleanEnv = { ...process.env, CLAUDECODE: "", CODEX: "", CODEX_THREAD_ID: "", CURSOR_AGENT: "", AFFITOR_API_KEY: "" }; +afterEach(() => { for (const dir of fixtures.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + +describe("selection and preflight", () => { + it("never selects detected clients without an explicit choice", () => { + expect(selectedClients([], {})).toEqual([]); + expect(selectedClients([], { CLAUDECODE: "1" })).toEqual(["claude_code"]); + expect(() => selectedClients(["cursor"], { CLAUDECODE: "1" })).toThrow("only configure itself"); + expect(() => selectedClients(["claude_code"], { CODEX_THREAD_ID: "fixture" })).toThrow("only configure itself"); + expect(() => selectedClients(["other"], {})).toThrow("Unknown client"); + }); + it.each(['{', '[]', '{"mcpServers":[]}', '{"mcpServers":null}'])("preflights every selected client before writing: %s", bad => { + const dir = project(); + put(dir, ".mcp.json", '{"keep":true}'); + put(dir, ".cursor/mcp.json", bad); + expect(() => planSetup(dir, ["claude_code", "cursor"])).toThrow(); + expect(readFileSync(join(dir, ".mcp.json"), "utf8")).toBe('{"keep":true}'); + expect(existsSync(join(dir, ".affitor"))).toBe(false); + }); + it.each([".mcp.json", ".cursor"])("rejects symlink targets and parents: %s", target => { + const dir = project(), external = project(); + put(external, "mcp.json", "{}"); + symlinkSync(target === ".cursor" ? external : join(external, "mcp.json"), join(dir, target)); + expect(() => planSetup(dir, [target === ".cursor" ? "cursor" : "claude_code"])).toThrow(); + expect(readFileSync(join(external, "mcp.json"), "utf8")).toBe("{}"); + }); + it("rejects a dangling symlink", () => { + const dir = project(); + symlinkSync(join(dir, "nonexistent"), join(dir, ".mcp.json")); + expect(() => planSetup(dir, ["claude_code"])).toThrow(); + }); + it("does not re-encode an invalid UTF-8 config", () => { + const dir = project(), bytes = Buffer.from([123, 34, 120, 34, 58, 34, 255, 34, 125]); + writeFileSync(join(dir, ".mcp.json"), bytes); + expect(() => planSetup(dir, ["claude_code"])).toThrow("UTF-8"); + expect(readFileSync(join(dir, ".mcp.json"))).toEqual(bytes); + }); +}); + +describe("local transaction", () => { + 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); + const plan = planSetup(dir, ["claude_code", "cursor"]); + applySetup(plan); + const config = JSON.parse(readFileSync(join(dir, ".mcp.json"), "utf8")); + expect(config.keep).toBe(123); + expect(config.mcpServers.other.env.TOKEN).toBe("fake-private-value"); + expect(config.mcpServers.affitor).toEqual({ command: "node", args: [join(dir, ".affitor/agent-mcp.cjs")] }); + const backup = join(dir, ".affitor/backups/.mcp.json.affitor.bak"); + expect(readFileSync(backup, "utf8")).toBe(original); + expect(statSync(backup).mode & 0o777).toBe(0o600); + expect(statSync(join(dir, ".mcp.json")).mode & 0o777).toBe(0o600); + expect(readFileSync(join(dir, ".gitignore"), "utf8")).toContain("/.affitor/backups/"); + expect(planSetup(dir, ["claude_code", "cursor"]).actions.every(a => a.operation === "unchanged")).toBe(true); + expect(doctor(dir, ["claude_code"])[0]).toMatchObject({ status: "aligned", liveSession: "not_checked" }); + }); + it("restores prior files when a later write fails", () => { + const dir = project(); + put(dir, ".mcp.json", '{"keep":true}'); + const plan = planSetup(dir, ["claude_code", "cursor"]); + expect(() => applySetup(plan, a => { if (a.path.endsWith(".cursor/mcp.json")) throw new Error("fixture failure"); })).toThrow("rolled back"); + expect(readFileSync(join(dir, ".mcp.json"), "utf8")).toBe('{"keep":true}'); + expect(existsSync(join(dir, ".claude/skills/affitor/SKILL.md"))).toBe(false); + expect(existsSync(join(dir, ".affitor/agent-mcp.cjs"))).toBe(false); + expect(readFileSync(join(dir, ".affitor/backups/.gitignore"), "utf8")).toBe("*\n"); + expect(spawnSync("git", ["init", "-q", dir]).status).toBe(0); + expect(spawnSync("git", ["-C", dir, "check-ignore", ".affitor/backups/.mcp.json.affitor.bak"]).status).toBe(0); + }); + it("preserves concurrent edits before apply", () => { + const dir = project(), plan = planSetup(dir, ["claude_code"]); + put(dir, ".mcp.json", '{"newer":true}'); + expect(() => applySetup(plan)).toThrow(); + expect(readFileSync(join(dir, ".mcp.json"), "utf8")).toBe('{"newer":true}'); + }); + it("preserves a concurrent edit to an earlier written file during rollback", () => { + const dir = project(), plan = planSetup(dir, ["claude_code"]); + expect(() => applySetup(plan, a => { + if (a.path.endsWith("SKILL.md")) { put(dir, ".mcp.json", '{"newer":true}'); throw new Error(); } + })).toThrow("concurrent edit was preserved"); + expect(readFileSync(join(dir, ".mcp.json"), "utf8")).toBe('{"newer":true}'); + }); + it("Codex stays manual and its shell command quotes unusual project paths", () => { + const dir = project(), special = join(dir, "a'b$(echo bad)"); + mkdirSync(special); + const plan = planSetup(special, ["codex"]); + applySetup(plan); + expect(plan.manual[0]).toContain("'\"'\"'"); + expect(existsSync(join(special, ".codex/config.toml"))).toBe(false); + expect(existsSync(join(special, ".agents/skills/affitor/SKILL.md"))).toBe(true); + expect(doctor(special, ["codex"])[0].status).toBe("manual"); + }); +}); + +describe("built command", () => { + const bin = resolve("dist/cli.js"); + const run = (dir: string, args: string[]) => spawnSync(process.execPath, [bin, ...args], { cwd: dir, env: { ...cleanEnv, HOME: dir }, encoding: "utf8" }); + it("dry-run and noninteractive no-consent do not write, JSON never contains existing secrets", () => { + const dir = project(); + put(dir, ".mcp.json", '{"mcpServers":{"other":{"env":{"TOKEN":"fake-private-value"}}}}'); + const dry = run(dir, ["agent", "setup", "--client", "claude_code", "--dry-run", "--json"]); + expect(dry.status).toBe(0); + expect(JSON.parse(dry.stdout).status).toBe("planned"); + expect(dry.stdout).not.toContain("fake-private-value"); + const no = run(dir, ["agent", "setup", "--client", "claude_code", "--json"]); + expect(no.status).toBe(1); + expect(JSON.parse(no.stdout).status).toBe("needs_confirmation"); + expect(existsSync(join(dir, ".affitor"))).toBe(false); + }); + it("real apply/doctor agree, with no global config and no connected claim", () => { + const dir = project(); + const applied = run(dir, ["agent", "setup", "--client", "claude_code", "--yes", "--json"]); + expect(applied.status).toBe(0); + expect(JSON.parse(applied.stdout).status).toBe("needs_human"); + expect(existsSync(join(dir, ".claude.json"))).toBe(false); + const result = run(dir, ["doctor", "--client", "claude_code", "--json"]); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ mode: "static", clients: [{ status: "aligned", credential: "missing", liveSession: "not_checked" }] }); + }); +}); + +describe("real generated launcher without network", () => { + function launch(dir: string, env: NodeJS.ProcessEnv = {}) { + return spawnSync(process.execPath, [join(dir, ".affitor/agent-mcp.cjs")], { cwd: tmpdir(), env: { ...cleanEnv, AFFITOR_MCP_WRITE: "1", AFFITOR_API_URL: "https://wrong.invalid", ...env, PATH: join(dir, "bin") }, encoding: "utf8" }); + } + 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}));\n`); + chmodSync(join(dir, "bin/npx"), 0o700); + } + it("reads the project program key, pins MCP, fixes cwd and disables inherited money tools", () => { + const dir = project(); install(dir); + 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 }); + }); + it("prefers an explicitly inherited program key", () => { + const dir = project(); install(dir); + put(dir, ".affitor/.env", "AFFITOR_API_KEY=fake_file_key"); + expect(JSON.parse(launch(dir, { AFFITOR_API_KEY: "fake_env_key" }).stdout).key).toBe("fake_env_key"); + }); + it.each(["", "AFFITOR_API_KEY=\"\"", "AFFITOR_API_KEY=one\nAFFITOR_API_KEY=two", 'AFFITOR_API_KEY=$(secret_command)'])("fails closed for missing/ambiguous key (%s)", content => { + const dir = project(); install(dir); + put(dir, ".affitor/.env", content); + put(dir, ".affitor/credentials.json", '{"token":"fake_user_login_token"}'); + const result = launch(dir); + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).not.toContain("fake_user_login_token"); + }); +}); From 694987909a595170de4ce44244b2d504f008ab6e Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sat, 17 Oct 2026 23:54:52 -0700 Subject: [PATCH 2/3] fix: align agent credential checks and support Windows launch --- .github/workflows/ci.yml | 20 ++++++++ packages/cli/README.md | 7 +++ packages/cli/src/lib/agent-launcher.ts | 46 +++++++++++++------ packages/cli/src/lib/agent-setup.ts | 11 +++-- .../cli/tests/agent-setup-windows.test.ts | 39 ++++++++++++++++ packages/cli/tests/agent-setup.test.ts | 32 ++++++++++++- 6 files changed, 135 insertions(+), 20 deletions(-) create mode 100644 packages/cli/tests/agent-setup-windows.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31ce555..103d6b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,3 +46,23 @@ jobs: - name: Unit tests run: npm run test --workspaces + + windows-agent-setup: + runs-on: windows-latest + timeout-minutes: 10 + steps: + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - name: Setup Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + cache: npm + - name: Install dependencies + run: npm ci --ignore-scripts + - name: Build + run: npm run build --workspaces + - name: Windows launcher smoke + run: npm exec --workspace packages/cli -- vitest run tests/agent-setup-windows.test.ts diff --git a/packages/cli/README.md b/packages/cli/README.md index a646d45..677689d 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -23,6 +23,7 @@ unrelated settings are preserved. Existing file bytes are backed up under 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. 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. @@ -52,6 +53,12 @@ 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 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. + This local installer uses an existing program key. Per-agent key issuance, pairing, connection telemetry, and the dashboard Agents page are separate work; this command does not claim to create or verify an agent connection. diff --git a/packages/cli/src/lib/agent-launcher.ts b/packages/cli/src/lib/agent-launcher.ts index 44c9cbe..3a2fdfd 100644 --- a/packages/cli/src/lib/agent-launcher.ts +++ b/packages/cli/src/lib/agent-launcher.ts @@ -1,31 +1,47 @@ // Kept as a standalone CommonJS file in the customer's project: a client can // start it from any directory, without putting a credential in its MCP config. export const MCP_VERSION = "0.2.2"; + +/** Shared by doctor and the generated launcher; never evaluates an env file. */ +export function parseProgramCredential(envKey: unknown, readText: () => string | null): string | null { + const valid = (value: string) => /^[A-Za-z0-9_-]+$/.test(value); + if (typeof envKey === "string" && envKey !== "") return valid(envKey) ? envKey : null; + try { + const text = readText(); + if (text === null) return null; + const assignments = text.split(/\r?\n/).filter(line => /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=/.test(line)); + if (assignments.length !== 1) return null; + let value = assignments[0].replace(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*/, "").trim(); + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1); + return valid(value) ? value : null; + } catch { return null; } +} + export const AGENT_LAUNCHER = `// Generated by affitor agent setup. Contains no credentials. const { readFileSync, lstatSync } = require('node:fs'); const { join, resolve } = require('node:path'); const { spawn } = require('node:child_process'); const project = resolve(__dirname, '..'); -let key = process.env.AFFITOR_API_KEY; +const parseProgramCredential = ${parseProgramCredential.toString()}; +const key = parseProgramCredential(process.env.AFFITOR_API_KEY, () => { + const path = join(__dirname, '.env'); + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) return null; + return readFileSync(path, 'utf8'); +}); if (!key) { - try { - const path = join(__dirname, '.env'); - if (!lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error(); - const lines = readFileSync(path, 'utf8').split(/\\r?\\n/); - const values = lines.filter(line => /^\\s*(?:export\\s+)?AFFITOR_API_KEY\\s*=/.test(line)); - if (values.length !== 1) throw new Error(); - key = values[0].replace(/^\\s*(?:export\\s+)?AFFITOR_API_KEY\\s*=\\s*/, '').trim(); - if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) key = key.slice(1, -1); - if (!/^[A-Za-z0-9_-]+$/.test(key)) throw new Error(); - } catch { - process.stderr.write('Affitor: set AFFITOR_API_KEY or configure this project with affitor init. No agent call was made.\\n'); - process.exit(1); - } + process.stderr.write('Affitor: set AFFITOR_API_KEY or configure this project with affitor init. No agent call was made.\\n'); + process.exit(1); } // Setup never opts into the sale/refund tools, including through inherited env. const env = { ...process.env, AFFITOR_API_KEY: key, AFFITOR_MCP_WRITE: '0' }; delete env.AFFITOR_API_URL; -const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['-y', '@affitor/mcp@${MCP_VERSION}'], { cwd: project, env, stdio: 'inherit', shell: false }); +// 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 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); }); for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal)); diff --git a/packages/cli/src/lib/agent-setup.ts b/packages/cli/src/lib/agent-setup.ts index b0a85b3..e7462fb 100644 --- a/packages/cli/src/lib/agent-setup.ts +++ b/packages/cli/src/lib/agent-setup.ts @@ -1,7 +1,7 @@ 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 } from "./agent-launcher.js"; +import { AGENT_LAUNCHER, AGENT_SKILL, MCP_VERSION, parseProgramCredential } from "./agent-launcher.js"; export const CLIENTS = ["claude_code", "cursor", "codex"] as const; export type AgentClient = typeof CLIENTS[number]; @@ -125,7 +125,7 @@ export function planSetup(cwd: string, clients: AgentClient[]): SetupPlan { if (plan.actions.some(action => action.backup)) { const guard = join(project, ".affitor/backups/.gitignore"); const raw = readTarget(project, guard); - if (raw !== null && !raw.split(/\r?\n/).includes("*")) throw new Error("Unsafe setup backup directory: its .gitignore must ignore all files."); + if (raw !== null && !["*", "*\n", "*\r\n"].includes(raw)) throw new Error("Unsafe setup backup directory: its .gitignore must contain only the '*' rule."); add(".affitor/backups/.gitignore", raw ?? "*\n", raw); // Protect secret-containing backups before creating the first one. Keep this // guard with backups on rollback even if the root .gitignore is restored. @@ -161,6 +161,8 @@ export function applySetup(plan: SetupPlan, beforeWrite?: (action: FileAction) = beforeWrite?.(action); if (readTarget(plan.project, action.path) !== before.get(action.path)) throw new Error("A setup file changed after planning. Run setup again."); if (action.backup && !existsSync(action.backup)) { + const guard = readTarget(plan.project, join(plan.project, ".affitor/backups/.gitignore")); + if (guard === null || !["*", "*\n", "*\r\n"].includes(guard)) throw new Error("Unsafe setup backup ignore guard."); safePath(plan.project, action.backup); mkdirSync(dirname(action.backup), { recursive: true }); backupCreated = true; @@ -192,7 +194,10 @@ export function doctor(cwd: string, clients: AgentClient[]) { try { const plan = planSetup(cwd, [client]); const keyPath = join(plan.project, ".affitor/.env"); - const credential = Boolean(process.env.AFFITOR_API_KEY) || (existsSync(keyPath) && !lstatSync(keyPath).isSymbolicLink() && lstatSync(keyPath).isFile() && /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*\S+/m.test(readFileSync(keyPath, "utf8"))); + const credential = parseProgramCredential(process.env.AFFITOR_API_KEY, () => { + 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: [] }; } }); diff --git a/packages/cli/tests/agent-setup-windows.test.ts b/packages/cli/tests/agent-setup-windows.test.ts new file mode 100644 index 0000000..84df19d --- /dev/null +++ b/packages/cli/tests/agent-setup-windows.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +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", () => { + 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", "claudecode", "codex", "codex_thread_id", "cursor_agent"].includes(key.toLowerCase()))); + env.PATH = bin; + env.AFFITOR_MCP_WRITE = "1"; + env.NO_EXPAND = "wrong-path"; + 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}));'); + writeFileSync(join(bin, "npx.cmd"), `@"${process.execPath}" "%~dp0npx-fixture.cjs" %*\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(); + 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" }); + 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"); + expect(existsSync(join(project, ".claude.json"))).toBe(false); + expect(readFileSync(join(project, ".mcp.json"), "utf8")).not.toContain("fake_windows_key"); + } finally { rmSync(fixture, { recursive: true, force: true }); } + }); +}); diff --git a/packages/cli/tests/agent-setup.test.ts b/packages/cli/tests/agent-setup.test.ts index 2cfbd5c..25db303 100644 --- a/packages/cli/tests/agent-setup.test.ts +++ b/packages/cli/tests/agent-setup.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { spawnSync } from "node:child_process"; import { applySetup, doctor, planSetup, selectedClients } from "../src/lib/agent-setup.js"; -import { AGENT_LAUNCHER } from "../src/lib/agent-launcher.js"; +import { AGENT_LAUNCHER, parseProgramCredential } from "../src/lib/agent-launcher.js"; const fixtures: string[] = []; function project() { @@ -57,6 +57,14 @@ describe("selection and preflight", () => { }); describe("local transaction", () => { + it.each(["*\n!*.bak\n", "*\n!.mcp.json.affitor.bak\n", "*\n!*/\n"])("rejects backup guards that can unignore secrets", guard => { + const dir = project(); + put(dir, ".mcp.json", '{"other":{"token":"fake_private"}}'); + put(dir, ".affitor/backups/.gitignore", guard); + expect(() => planSetup(dir, ["claude_code"])).toThrow("only the '*' rule"); + expect(existsSync(join(dir, ".affitor/backups/.mcp.json.affitor.bak"))).toBe(false); + expect(readFileSync(join(dir, ".mcp.json"), "utf8")).toBe('{"other":{"token":"fake_private"}}'); + }); 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); @@ -113,7 +121,18 @@ describe("local transaction", () => { describe("built command", () => { const bin = resolve("dist/cli.js"); - const run = (dir: string, args: string[]) => spawnSync(process.execPath, [bin, ...args], { cwd: dir, env: { ...cleanEnv, HOME: dir }, encoding: "utf8" }); + const run = (dir: string, args: string[], env: NodeJS.ProcessEnv = {}) => spawnSync(process.execPath, [bin, ...args], { cwd: dir, env: { ...cleanEnv, HOME: dir, ...env }, encoding: "utf8" }); + it.each(['AFFITOR_API_KEY=""', "AFFITOR_API_KEY=one\nAFFITOR_API_KEY=two", "AFFITOR_API_KEY=\nAFFITOR_API_KEY=two", "AFFITOR_API_KEY=", "AFFITOR_API_KEY=''"])("doctor rejects a credential the launcher cannot use: %s", text => { + const dir = project(); + expect(run(dir, ["agent", "setup", "--client", "claude_code", "--yes", "--json"]).status).toBe(0); + put(dir, ".affitor/.env", text); + const result = run(dir, ["doctor", "--client", "claude_code", "--json"]); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout).clients[0]).toMatchObject({ status: "aligned", credential: "missing" }); + const launcher = spawnSync(process.execPath, [join(dir, ".affitor/agent-mcp.cjs")], { env: cleanEnv, encoding: "utf8" }); + expect(launcher.status).toBe(1); + expect(launcher.stdout).toBe(""); + }); it("dry-run and noninteractive no-consent do not write, JSON never contains existing secrets", () => { const dir = project(); put(dir, ".mcp.json", '{"mcpServers":{"other":{"env":{"TOKEN":"fake-private-value"}}}}'); @@ -138,6 +157,15 @@ describe("built command", () => { }); }); +describe("shared credential parser", () => { + it("validates inherited credentials and preserves their priority without reading a file", () => { + const read = () => { throw new Error("should not read"); }; + expect(parseProgramCredential("fake_env_key", read)).toBe("fake_env_key"); + expect(parseProgramCredential(" ", () => "AFFITOR_API_KEY=fake_file_key")).toBe(null); + expect(parseProgramCredential("", () => "export AFFITOR_API_KEY='fake_file_key'\n")).toBe("fake_file_key"); + }); +}); + describe("real generated launcher without network", () => { function launch(dir: string, env: NodeJS.ProcessEnv = {}) { return spawnSync(process.execPath, [join(dir, ".affitor/agent-mcp.cjs")], { cwd: tmpdir(), env: { ...cleanEnv, AFFITOR_MCP_WRITE: "1", AFFITOR_API_URL: "https://wrong.invalid", ...env, PATH: join(dir, "bin") }, encoding: "utf8" }); From b271bf7b572f875f1c85dd9076ac073b6684e71d Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sun, 18 Oct 2026 00:13:10 -0700 Subject: [PATCH 3/3] fix: protect agent credentials and avoid unsafe Windows shell commands --- packages/cli/README.md | 11 +++++- packages/cli/src/commands/agent.ts | 2 +- packages/cli/src/lib/agent-launcher.ts | 6 ++- packages/cli/src/lib/agent-setup.ts | 25 ++++++++---- .../cli/tests/agent-setup-windows.test.ts | 38 +++++++++++++++++-- packages/cli/tests/agent-setup.test.ts | 26 ++++++++++++- 6 files changed, 90 insertions(+), 18 deletions(-) diff --git a/packages/cli/README.md b/packages/cli/README.md index 677689d..516385f 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -24,6 +24,9 @@ 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. +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. 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. @@ -34,7 +37,8 @@ config, launcher, or skill. The launcher reads inherited `AFFITOR_API_KEY`, then this project's `.affitor/.env` (created by `affitor init`). It never reads the user login token in `~/.affitor/credentials.json`. If `onboard` wrote a key to your root `.env`, provide it privately as `AFFITOR_API_KEY` when starting the agent instead. -It uses the production API and disables sale/refund tools even when the parent +It removes inherited API URL overrides regardless of their casing and uses the +production API. It disables sale/refund tools even when the parent environment has `AFFITOR_MCP_WRITE=1`. Other tools still include tracking and synthetic verification; approve those actions separately. @@ -42,7 +46,10 @@ 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. +command uses POSIX shell quoting on macOS/Linux. 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. **Installed is not verified.** Successful setup returns `needs_human` (exit0). `doctor` is read-only and static: it does not start an agent, connect to the API, diff --git a/packages/cli/src/commands/agent.ts b/packages/cli/src/commands/agent.ts index 9ff5d91..f070a07 100644 --- a/packages/cli/src/commands/agent.ts +++ b/packages/cli/src/commands/agent.ts @@ -48,7 +48,7 @@ export function registerAgentCommands(program: Command) { ? "Select --client claude_code, cursor or codex. Detected agents are not selected automatically." : status === "needs_confirmation" ? "Review the plan, then run affitor agent setup --client --yes." - : "Installed is not verified. Configure the program key privately as AFFITOR_API_KEY or in .affitor/.env; restart the selected agent, then ask it to call affitor_readiness. For Codex, first run the printed manual command."; + : "Installed is not verified. Configure the program key privately as AFFITOR_API_KEY or in .affitor/.env; restart the selected agent, then ask it to call affitor_readiness. For Codex, first follow the printed manual configuration instructions."; if (flags.json) process.stdout.write(JSON.stringify({ status, ...preview, next }) + "\n"); else process.stdout.write(`${status}\n${next}\n`); process.exitCode = status === "needs_confirmation" || (!clients.length && !opts.dryRun) ? 1 : 0; diff --git a/packages/cli/src/lib/agent-launcher.ts b/packages/cli/src/lib/agent-launcher.ts index 3a2fdfd..7784355 100644 --- a/packages/cli/src/lib/agent-launcher.ts +++ b/packages/cli/src/lib/agent-launcher.ts @@ -34,8 +34,10 @@ if (!key) { process.exit(1); } // Setup never opts into the sale/refund tools, including through inherited env. -const env = { ...process.env, AFFITOR_API_KEY: key, AFFITOR_MCP_WRITE: '0' }; -delete env.AFFITOR_API_URL; +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'; // 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'; diff --git a/packages/cli/src/lib/agent-setup.ts b/packages/cli/src/lib/agent-setup.ts index e7462fb..e421c0b 100644 --- a/packages/cli/src/lib/agent-setup.ts +++ b/packages/cli/src/lib/agent-setup.ts @@ -109,18 +109,29 @@ export function planSetup(cwd: string, clients: AgentClient[]): SetupPlan { add(client === "claude_code" ? ".claude/skills/affitor/SKILL.md" : ".cursor/skills/affitor/SKILL.md", AGENT_SKILL); } if (clients.includes("codex")) { - plan.manual.push(`codex mcp add affitor -- node '${launcher.replaceAll("'", "'\"'\"'")}'`); + if (process.platform === "win32") { + // A path may contain cmd.exe expansion/separator characters. Do not emit + // executable shell text when the invoking Windows shell is unknown. + plan.manual.push('Windows: add Affitor in Codex MCP settings using command "node" and the exact argument in entry.args. No shell command is generated.'); + } else { + plan.manual.push(`codex mcp add affitor -- node '${launcher.replaceAll("'", "'\"'\"'")}'`); + } // Installing a shared skill and launcher needs the same explicit consent. add(".agents/skills/affitor/SKILL.md", AGENT_SKILL); } if (clients.length) { add(".affitor/agent-mcp.cjs", AGENT_LAUNCHER); - const path = join(project, ".gitignore"); - const raw = readTarget(project, path); - const prior = raw ?? ""; - const entries = ["/.affitor/.env", "/.affitor/backups/"]; - const missing = entries.filter(line => !prior.split(/\r?\n/).includes(line)); - add(".gitignore", missing.length ? prior + (prior && !prior.endsWith("\n") ? "\n" : "") + missing.join("\n") + "\n" : prior, raw); + // 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/"]], + ] 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)) { const guard = join(project, ".affitor/backups/.gitignore"); diff --git a/packages/cli/tests/agent-setup-windows.test.ts b/packages/cli/tests/agent-setup-windows.test.ts index 84df19d..a12a6f4 100644 --- a/packages/cli/tests/agent-setup-windows.test.ts +++ b/packages/cli/tests/agent-setup-windows.test.ts @@ -11,16 +11,17 @@ describe.skipIf(process.platform !== "win32")("Windows generated launcher smoke" 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", "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", "claudecode", "codex", "codex_thread_id", "cursor_agent"].includes(key.toLowerCase()))); env.PATH = bin; - env.AFFITOR_MCP_WRITE = "1"; + env.Affitor_Mcp_Write = "1"; + env.affitor_api_url = "https://wrong.invalid"; env.NO_EXPAND = "wrong-path"; 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}));'); + 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.cmd"), `@"${process.execPath}" "%~dp0npx-fixture.cjs" %*\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 }); @@ -28,7 +29,7 @@ describe.skipIf(process.platform !== "win32")("Windows generated launcher smoke" expect(baseline.error).toBeDefined(); 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" }); + 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"] }); 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"); @@ -36,4 +37,33 @@ describe.skipIf(process.platform !== "win32")("Windows generated launcher smoke" expect(readFileSync(join(project, ".mcp.json"), "utf8")).not.toContain("fake_windows_key"); } finally { rmSync(fixture, { recursive: true, force: true }); } }); + it("refuses to print shell commands for Codex on Windows, including metacharacter paths", () => { + const fixture = realpathSync(mkdtempSync(join(tmpdir(), "affitor-windows-codex-"))); + const project = join(fixture, "project & echo INJECTED & rem (spaces) %NO_EXPAND% !EXPAND! 'quote'"); + mkdirSync(project); + const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !["claudecode", "codex", "codex_thread_id", "cursor_agent"].includes(key.toLowerCase()))); + try { + const setup = spawnSync(process.execPath, [resolve("dist/cli.js"), "agent", "setup", "--client", "codex", "--yes", "--json"], { cwd: project, env, encoding: "utf8" }); + expect(setup.status, setup.stderr + setup.stdout).toBe(0); + const plan = JSON.parse(setup.stdout); + // Negative control: the previous POSIX-only command executes a separator + // on real cmd.exe. The fixture stub never invokes an actual Codex client. + const stubBin = join(fixture, "bin"); + mkdirSync(stubBin); + writeFileSync(join(stubBin, "codex.cmd"), "@echo CODEX_STUB\r\n"); + const legacyCommand = `codex mcp add affitor -- node '${plan.entry.args[0].replaceAll("'", "'\"'\"'")}'`; + const baseline = spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", legacyCommand], { cwd: fixture, env: { ...env, PATH: stubBin }, encoding: "utf8", timeout: 15000 }); + expect(baseline.stdout).toContain("INJECTED"); + expect(plan.manual).toHaveLength(1); + expect(plan.manual[0]).toContain("No shell command is generated"); + expect(plan.manual[0]).not.toContain("codex mcp add"); + expect(plan.manual[0]).not.toContain(project); + expect(plan.entry).toEqual({ command: "node", args: [join(project, ".affitor/agent-mcp.cjs")] }); + expect(plan.next).toContain("manual configuration instructions"); + expect(existsSync(plan.entry.args[0])).toBe(true); + expect(existsSync(join(project, ".agents/skills/affitor/SKILL.md"))).toBe(true); + expect(existsSync(join(project, ".codex/config.toml"))).toBe(false); + } finally { rmSync(fixture, { recursive: true, force: true }); } + }); + }); diff --git a/packages/cli/tests/agent-setup.test.ts b/packages/cli/tests/agent-setup.test.ts index 25db303..770a427 100644 --- a/packages/cli/tests/agent-setup.test.ts +++ b/packages/cli/tests/agent-setup.test.ts @@ -65,6 +65,18 @@ describe("local transaction", () => { expect(existsSync(join(dir, ".affitor/backups/.mcp.json.affitor.bak"))).toBe(false); expect(readFileSync(join(dir, ".mcp.json"), "utf8")).toBe('{"other":{"token":"fake_private"}}'); }); + it.each([false, true])("keeps credentials ignored despite negations (child=%s)", child => { + const dir = project(); + expect(spawnSync("git", ["init", "-q", dir]).status).toBe(0); + put(dir, ".gitignore", "/.affitor/.env\n!/.affitor/.env\n"); + if (child) put(dir, ".affitor/.gitignore", "!/.env\n"); + put(dir, ".affitor/.env", "AFFITOR_API_KEY=fake_gitignore_key\n"); + expect(spawnSync("git", ["-C", dir, "check-ignore", ".affitor/.env"]).status).toBe(1); + applySetup(planSetup(dir, ["claude_code"])); + expect(spawnSync("git", ["-C", dir, "check-ignore", ".affitor/.env"]).status).toBe(0); + 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("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); @@ -172,7 +184,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}));\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,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", () => { @@ -180,7 +192,17 @@ 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 }); + 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"] }); + }); + it("removes mixed-case API overrides and write aliases before spawning MCP", () => { + const dir = project(); install(dir); + put(dir, ".affitor/.env", "AFFITOR_API_KEY=fake_file_key"); + const result = launch(dir, { affitor_api_url: "https://wrong.invalid", Affitor_Api_Url: "https://wrong2.invalid", affitor_mcp_write: "1" }); + expect(result.status, result.stderr).toBe(0); + const child = JSON.parse(result.stdout); + expect(child.url).toBe(null); + expect(child.write).toBe("0"); + expect(child.aliases).toEqual(["AFFITOR_MCP_WRITE"]); }); it("prefers an explicitly inherited program key", () => { const dir = project(); install(dir);