From 13eafb294087a7a75fce04f7d145c87507aec528 Mon Sep 17 00:00:00 2001 From: Keaton Hoskins Date: Sun, 29 Nov 2026 23:58:55 +0000 Subject: [PATCH] feat(T770): enroll explicitly reviewed native Codex hooks Task: T770 --- README.md | 18 ++ dist/cli.js | 20 ++ dist/codex-hook-trust.js | 462 ++++++++++++++++++++++++++++++++++ dist/doctor.js | 2 +- dist/setup.js | 7 +- src/cli.ts | 18 ++ src/codex-hook-trust.ts | 453 +++++++++++++++++++++++++++++++++ src/doctor.ts | 2 +- src/setup.ts | 8 +- test/codex-hook-trust.test.ts | 251 ++++++++++++++++++ 10 files changed, 1233 insertions(+), 8 deletions(-) create mode 100644 dist/codex-hook-trust.js create mode 100644 src/codex-hook-trust.ts create mode 100644 test/codex-hook-trust.test.ts diff --git a/README.md b/README.md index 153d6045..7eaebb73 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,24 @@ Kimi) with no mbx call for 10 minutes becomes claimable; a dedicated session is Restart your agent sessions and they have the `mbx_*` tools. `agentmbx setup --dry-run` previews, `--only codex` limits it, `--uninstall` undoes it. What it writes for each CLI (and how to do it by hand): [docs/INSTALL.md](docs/INSTALL.md). +### Review and enroll Codex hooks + +After setup, trust the hooks in Codex's native UI or use the explicit enrollment command with Codex 0.172.0. Setup and `setup --yes` leave native trust decisions to you. Run both commands from the same directory with the same `CODEX_HOME` (default `~/.codex`). + +```sh +(umask 077; agentmbx codex-hooks inspect > codex-hooks.review.json) +cat codex-hooks.review.json +shasum -a 256 codex-hooks.review.json +agentmbx codex-hooks enroll --manifest codex-hooks.review.json --sha256 "PASTE_REVIEWED_DIGEST_HERE" +``` + +Review the four commands, source, timeout, and native hashes before passing the printed 64-character digest. Inspection starts a short-lived Codex app-server and lists hook metadata without starting a thread. The manifest includes the Codex and AgentMBX versions and omits unrelated hook commands and config values. Native hashes cover hook definitions, including the command string. They do not attest to the executable bytes at that path. + +Enrollment requires the same definitions and a manifest inspected within 30 minutes for changes to trust. It uses the reviewed user config version to guard the write, then starts a fresh app-server to verify trust and check preservation. If the reviewed hooks are already trusted, enrollment returns a verified no-op even after unrelated config changes. `manualReviewRequired` flags outstanding review. Foreign hook trust stays as configured. If Codex would migrate existing hook state during the write, use its native UI. Avoid editing Codex config during enrollment. A report of concurrent drift means the fresh read differed from the expected config or other hook inventory. Enrollment verifies native hook trust only. Idle wake and delegated actions have separate requirements. + +Private receipts are stored in `$CODEX_HOME/agentmbx-hook-enrollment` with config and hook digests. If a write might have happened and verification could not finish, rerun the same enrollment command with the original manifest and digest. With `pending.json` present this is a read-only reconciliation, even if trust is still missing. The pending receipt stays in place to prevent automatic retries. After confirming the original process has stopped and reviewing the outcome, keep the receipt private and move it out of the way before starting a new review. For unsupported Codex versions, review hooks in the native UI. When native hooks are unavailable, use the MCP tools `mbx_whoami` and `mbx_catchup`. + + Pair a second machine: ```sh diff --git a/dist/cli.js b/dist/cli.js index b579da2c..43b5f117 100644 --- a/dist/cli.js +++ b/dist/cli.js @@ -72,6 +72,8 @@ import { isSlotName } from "./project-slot.js"; const HELP = `agentmbx (AgentMBX) — signed messages between AI coding agents, on this machine and across paired machines Start here + agentmbx codex-hooks inspect print a redacted native hook review manifest + agentmbx codex-hooks enroll --manifest --sha256 enroll four reviewed AgentMBX hooks agentmbx setup [--yes] [--dry-run] [--only claude,codex,opencode,kimi,hermes,grok,skill,daemon,owner] [--host ] [--no-owner] [--policy ask|collaborate|autonomous|yolo] [--uninstall] init this host, install the daemon, wire every detected agent CLI (MCP + hooks + skill), create the owner key agentmbx doctor [--fix] [--processes] checklist; --processes lists MCP/watch pid, ppid, birth, client liveness and RSS (read-only; excludes --fix) @@ -384,6 +386,24 @@ async function run(argv) { const [cmd, ...rest] = argv; if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") return console.log(HELP); + if (cmd === "codex-hooks") { + const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { + help: { type: "boolean", short: "h" }, manifest: { type: "string" }, sha256: { type: "string" }, + } }); + if (values.help) + return console.log(commandHelp(cmd)); + const { codexHooks } = await import("./codex-hook-trust.js"); + if (positionals.length === 1 && positionals[0] === "inspect" && !values.manifest && !values.sha256) + return console.log(JSON.stringify(await codexHooks({ inspect: true }), null, 2)); + if (positionals.length !== 1 || positionals[0] !== "enroll" || !values.manifest || !values.sha256) + return die("Use codex-hooks inspect or codex-hooks enroll --manifest --sha256 "); + const result = await codexHooks({ manifest: values.manifest, sha256: values.sha256 }); + console.log(JSON.stringify(result, null, 2)); + if ("status" in result && (result.status !== "verified" || + ("concurrentDrift" in result && result.concurrentDrift))) + process.exitCode = 1; + return; + } if (cmd === "claude") return launchClaude(rest); // every argument belongs to Claude Code: parse nothing here const { values: o, positionals: pos } = parseArgs({ args: rest, allowPositionals: true, strict: cmd !== "hook" && cmd !== "mcp", options: { diff --git a/dist/codex-hook-trust.js b/dist/codex-hook-trust.js new file mode 100644 index 00000000..42acf48d --- /dev/null +++ b/dist/codex-hook-trust.js @@ -0,0 +1,462 @@ +import { spawn } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { closeSync, constants, fsyncSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, writeFileSync, } from "node:fs"; +import { homedir } from "node:os"; +import { isAbsolute, join, resolve } from "node:path"; +import { StringDecoder } from "node:string_decoder"; +import { clearTimeout, setTimeout } from "node:timers"; +import { hookCommand, resolveCommand, SETUP_HOOK_TIMEOUT_SEC, STOP_EVENTS } from "./setup.js"; +import { version } from "./version.js"; +const CODEX_VERSION = "0.172.0"; +const MAX_FRAME = 8 * 1024 * 1024; +const MAX_MANIFEST = 64 * 1024; +const MAX_AGE = 30 * 60 * 1000; +const MANUAL = "Review hooks in Codex's native UI. Where native hooks are unavailable, use MCP mbx_whoami and mbx_catchup."; +const NATIVE_HASH = /^sha256:[a-f0-9]{64}$/; +const TRUST = ["managed", "untrusted", "trusted", "modified"]; +const object = (value) => !!value && typeof value === "object" && !Array.isArray(value); +const sha = (value) => createHash("sha256").update(value).digest("hex"); +const canonical = (value) => JSON.stringify(value, (_, item) => object(item) ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item); +const digest = (value) => sha(canonical(value)); +class NativeError extends Error { + conflict; + constructor(method, error) { + const conflict = error.code === -32600 && object(error.data) && + error.data.config_write_error_code === "configVersionConflict"; + const code = Number.isSafeInteger(error.code) ? String(error.code) : "unknown"; + super(`Codex ${method} rejected the request (RPC ${code}${conflict ? ", configVersionConflict" : ""}).${code === "-32601" ? ` ${MANUAL}` : ""}`); + this.conflict = conflict; + } +} +/** Requests are serial, with a byte limit, a deadline and bounded child cleanup. */ +async function withServer(options, use) { + const child = spawn(options.bin, ["app-server", "--listen", "stdio://"], { + cwd: options.cwd, env: { ...process.env, CODEX_HOME: options.home }, stdio: ["pipe", "pipe", "ignore"], + }); + const closed = new Promise(done => child.once("close", done)); + const decoder = new StringDecoder("utf8"); + let buffer = ""; + let nextId = 0; + let failure; + let pending; + const fail = (message) => { + failure ??= new Error(message); + pending?.reject(failure); + }; + child.on("error", () => fail("Could not launch Codex app-server.")); + child.stdin.on("error", () => fail("Codex app-server input closed.")); + child.stdout.on("error", () => fail("Codex app-server output failed.")); + child.stdout.on("end", () => { if (pending) + fail("Codex app-server closed before replying (EOF)."); }); + child.stdout.on("data", (chunk) => { + if (failure) + return; + buffer += decoder.write(chunk); + if (Buffer.byteLength(buffer) > MAX_FRAME) + return fail("Codex app-server response exceeded the size limit."); + let end; + while ((end = buffer.indexOf("\n")) !== -1) { + const line = buffer.slice(0, end); + buffer = buffer.slice(end + 1); + if (!line.trim()) + continue; + let message; + try { + message = JSON.parse(line); + } + catch { + return fail("Invalid JSON from Codex app-server."); + } + if (!object(message)) + return fail("Invalid Codex app-server message."); + if (typeof message.method === "string" && !("id" in message)) + continue; + if (!pending || message.id !== pending.id) + return fail("Unexpected Codex app-server message."); + const request = pending; + pending = undefined; + if (object(message.error) && Number.isSafeInteger(message.error.code) && !("result" in message)) + request.reject(new NativeError(request.method, message.error)); + else if (object(message.result) && !("error" in message)) + request.resolve(message.result); + else + request.reject(new Error("Malformed Codex app-server reply.")); + } + }); + const timeout = options.timeoutMs; + const rpc = async (method, params) => { + if (failure) + throw failure; + const id = ++nextId; + const timer = setTimeout(() => fail(`Codex ${method} timed out.`), timeout); + try { + return await new Promise((resolve, reject) => { + pending = { id, method, resolve, reject }; + child.stdin.write(JSON.stringify({ id, method, params }) + "\n"); + }); + } + finally { + clearTimeout(timer); + pending = undefined; + } + }; + try { + const init = await rpc("initialize", { + clientInfo: { name: "agentmbx", version: version() }, capabilities: { experimentalApi: true }, + }); + if (init.codexHome !== options.home || typeof init.userAgent !== "string" || + !init.userAgent.startsWith(`agentmbx/${CODEX_VERSION} `)) { + throw new Error(`Unsupported Codex version or Codex home mismatch. Native enrollment supports Codex ${CODEX_VERSION}. ${MANUAL}`); + } + child.stdin.write('{"method":"initialized"}\n'); + const result = await use(rpc); + if (failure) + throw failure; + child.stdin.end(); + const code = await new Promise(done => { + const timer = setTimeout(() => done(undefined), timeout); + void closed.then(code => { clearTimeout(timer); done(code); }); + }); + if (code !== 0 || failure) + throw new Error("Codex app-server did not close cleanly."); + return result; + } + finally { + if (child.exitCode === null && child.signalCode === null) + child.kill("SIGKILL"); + child.stdin.destroy(); + child.stdout.destroy(); + } +} +function definition(hook) { + const { trustStatus: _trustStatus, ...rest } = hook; + return rest; +} +async function inventory(rpc, options) { + const { home, cwd, command } = options; + const configPath = join(home, "config.toml"); + const sourcePath = join(home, "hooks.json"); + const config = await rpc("config/read", { cwd, includeLayers: true }); + const listed = await rpc("hooks/list", { cwds: [cwd] }); + if (!object(config.config) || !Array.isArray(config.layers) || !Array.isArray(listed.data) || listed.data.length !== 1) + throw new Error(`Unsupported Codex inventory response. ${MANUAL}`); + if (object(config.config.features) && config.config.features.hooks === false) + throw new Error(`Native hooks are disabled. ${MANUAL}`); + const entry = listed.data[0]; + if (!object(entry) || entry.cwd !== cwd || !Array.isArray(entry.hooks) || + !Array.isArray(entry.errors) || entry.errors.length || !Array.isArray(entry.warnings) || entry.warnings.length) + throw new Error(`Codex hook inventory is incomplete or reported diagnostics. ${MANUAL}`); + const layers = config.layers; + const validated = layers.map(layer => { + if (!object(layer) || !object(layer.name) || typeof layer.name.type !== "string" || + typeof layer.version !== "string" || !object(layer.config)) + throw new Error(`Unsupported Codex config layer. ${MANUAL}`); + return { name: layer.name, version: layer.version, disabledReason: layer.disabledReason, config: layer.config }; + }); + const userLayers = validated.filter(layer => layer.name.type === "user"); + const user = userLayers[0]; + if (userLayers.length !== 1 || user.name.file !== configPath || user.name.profile != null || + user.disabledReason != null || !NATIVE_HASH.test(user.version) || realpathSync(configPath) !== configPath || + realpathSync(sourcePath) !== sourcePath) + throw new Error(`Codex inventory is outside the base user config and hooks scope. ${MANUAL}`); + const keys = new Set(); + const rows = entry.hooks.map(row => { + if (!object(row) || typeof row.key !== "string" || keys.has(row.key) || + typeof row.currentHash !== "string" || !row.currentHash || + typeof row.trustStatus !== "string" || !TRUST.includes(row.trustStatus)) + throw new Error(`Malformed Codex hook metadata. ${MANUAL}`); + keys.add(row.key); + return { ...row, key: row.key, currentHash: row.currentHash, trustStatus: row.trustStatus }; + }); + const hooks = STOP_EVENTS.map(([event, subcommand]) => { + const eventName = event[0].toLowerCase() + event.slice(1); + const expected = hookCommand(command, subcommand, "codex"); + const matching = rows.filter(row => Reflect.get(row, "eventName") === eventName && Reflect.get(row, "command") === expected); + const row = matching[0]; + const nativeEvent = eventName.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`); + const prefix = `${sourcePath}:${nativeEvent}:`; + if (matching.length !== 1 || row.source !== "user" || row.sourcePath !== sourcePath || + !row.key.startsWith(prefix) || !/^\d+:\d+$/.test(row.key.slice(prefix.length)) || + row.handlerType !== "command" || row.matcher !== null || row.async !== false || row.enabled !== true || + row.isManaged !== false || row.pluginId !== null || row.environmentId !== null || + row.statusMessage !== null || row.additionalContextLimit !== null || + row.timeoutSec !== SETUP_HOOK_TIMEOUT_SEC || !NATIVE_HASH.test(row.currentHash) || row.trustStatus === "managed") + throw new Error(`Expected one unchanged AgentMBX ${event} definition in the Codex user hooks file. ${MANUAL}`); + return { + key: row.key, eventName, source: "user", sourcePath, handlerType: "command", command: expected, + timeoutSec: SETUP_HOOK_TIMEOUT_SEC, matcher: null, async: false, enabled: true, isManaged: false, + currentHash: row.currentHash, trustStatus: row.trustStatus, + }; + }); + const selected = new Set(hooks.map(hook => hook.key)); + const other = rows.filter(row => !selected.has(row.key)); + const otherHooksNeedingReview = other.filter(row => row.trustStatus === "untrusted" || row.trustStatus === "modified").length; + const edits = Object.fromEntries(hooks.map(hook => [hook.key, { trusted_hash: hook.currentHash }])); + const hookConfig = user.config.hooks ?? {}; + const state = object(hookConfig) ? hookConfig.state ?? {} : undefined; + if (!object(hookConfig) || !object(state)) + throw new Error("Unexpected shape for native hooks.state."); + const nextState = { ...state }; + for (const [key, value] of Object.entries(edits)) { + if (key in state && !object(state[key])) + throw new Error("Unexpected shape for a selected native hooks.state entry."); + nextState[key] = { ...(object(state[key]) ? state[key] : {}), ...value }; + } + const layerDigest = (next) => digest(validated.map(layer => layer === user + ? { ...layer, version: undefined, config: next ? { ...user.config, hooks: { ...hookConfig, state: nextState } } : user.config } + : layer)); + return { + hooks, configVersion: user.version, otherHooksNeedingReview, edits, + otherDigest: digest(other), configDigest: layerDigest(false), expectedConfigDigest: layerDigest(true), + trusted: hooks.every(hook => hook.trustStatus === "trusted"), + // Codex 0.172.0 splits legacy composite hashes anywhere in the table on write. + wouldMigrateHookState: Object.values(state).some(entry => object(entry) && typeof entry.trusted_hash === "string" && entry.trusted_hash.includes("/")), + persisted: hooks.every(hook => { + const entry = state[hook.key]; + return object(entry) && entry.trusted_hash === hook.currentHash; + }), + }; +} +function manifestFor(options, current) { + return { + schema: 1, reviewedProtocol: "codex-app-server-experimental", codexVersion: CODEX_VERSION, + agentmbxVersion: version(), codexHome: options.home, cwd: options.cwd, inspectedAt: new Date().toISOString(), + configVersion: current.configVersion, hooks: current.hooks, + manualReviewRequired: !current.trusted || current.otherHooksNeedingReview > 0, + otherHooksNeedingReview: current.otherHooksNeedingReview, + }; +} +function readJson(path, privateFile = false) { + const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | (privateFile ? constants.O_NOFOLLOW : 0)); + try { + const stat = fstatSync(fd); + if (!stat.isFile() || stat.size > MAX_MANIFEST || (privateFile && (stat.mode & 0o077 || stat.uid !== process.getuid?.()))) + throw new Error("Expected a regular, bounded manifest or private receipt file."); + const raw = Buffer.alloc(MAX_MANIFEST + 1); + let size = 0; + while (size < raw.length) { + const count = readSync(fd, raw, size, raw.length - size, null); + if (!count) + break; + size += count; + } + if (size > MAX_MANIFEST) + throw new Error("Manifest or receipt exceeded the size limit."); + const bytes = raw.subarray(0, size); + let value; + try { + value = JSON.parse(bytes.toString("utf8")); + } + catch { + throw new Error("Invalid manifest or receipt JSON."); + } + if (!object(value)) + throw new Error("Invalid manifest or receipt object."); + return { bytes, value }; + } + finally { + closeSync(fd); + } +} +function syncDir(path) { + const fd = openSync(path, "r"); + try { + fsyncSync(fd); + } + finally { + closeSync(fd); + } +} +function saveReceipt(dir, receipt, first = false) { + const pending = join(dir, "pending.json"); + const file = first ? pending : join(dir, `${randomUUID()}.tmp`); + const fd = openSync(file, "wx", 0o600); + try { + writeFileSync(fd, JSON.stringify(receipt, null, 2) + "\n"); + fsyncSync(fd); + } + finally { + closeSync(fd); + } + if (!first) + renameSync(file, pending); + syncDir(dir); +} +function finishReceipt(dir, receipt) { + saveReceipt(dir, receipt); + const path = join(dir, `${receipt.id}.json`); + renameSync(join(dir, "pending.json"), path); + syncDir(dir); + return path; +} +function priorReceipt(dir) { + try { + return readJson(join(dir, "pending.json"), true).value; + } + catch (error) { + if (error.code !== "ENOENT") + throw error; + } +} +function verifyPrivateDir(dir, create = false) { + if (create) { + try { + mkdirSync(dir, { mode: 0o700 }); + } + catch (error) { + if (error.code !== "EEXIST") + throw error; + } + } + const stat = lstatSync(dir, { throwIfNoEntry: false }); + if (stat && (!stat.isDirectory() || stat.mode & 0o077 || stat.uid !== process.getuid?.())) + throw new Error("Expected a private, user-owned Codex enrollment receipt directory."); +} +function matchesManifest(reviewed, current, options) { + const { schema, reviewedProtocol, codexVersion, agentmbxVersion, codexHome, cwd } = manifestFor(options, current); + if (reviewed.schema !== schema || reviewed.reviewedProtocol !== reviewedProtocol || + reviewed.codexVersion !== codexVersion || reviewed.agentmbxVersion !== agentmbxVersion || + reviewed.codexHome !== codexHome || reviewed.cwd !== cwd || + typeof reviewed.configVersion !== "string" || !NATIVE_HASH.test(reviewed.configVersion) || + typeof reviewed.inspectedAt !== "string" || !Number.isFinite(Date.parse(reviewed.inspectedAt)) || + !Array.isArray(reviewed.hooks) || reviewed.hooks.length !== current.hooks.length) + return false; + return current.hooks.every((hook, i) => { + const row = reviewed.hooks[i]; + if (!object(row) || typeof row.trustStatus !== "string" || !TRUST.includes(row.trustStatus) || row.trustStatus === "managed") + return false; + const { trustStatus: _trustStatus, ...rest } = row; + return digest(rest) === digest(definition(hook)); + }); +} +function readiness(current) { + return { + agentmbxHooksTrusted: current.trusted, + manualReviewRequired: !current.trusted || current.otherHooksNeedingReview > 0, + otherHooksNeedingReview: current.otherHooksNeedingReview, + }; +} +function preservation(current, expected, uncertain = false) { + return { + otherHooksChanged: current.otherDigest !== expected.otherDigest, + configChanged: (current.configDigest !== expected.expectedConfigDigest && + !(uncertain && current.configDigest === expected.configDigest)) || + (!uncertain && expected.nativeVersion !== undefined && expected.nativeVersion !== current.configVersion), + }; +} +/** Inspect or enroll exactly the four AgentMBX user hooks through native Codex RPC. */ +export async function codexHooks(action, overrides = {}) { + const reviewed = "manifest" in action ? readJson(action.manifest) : undefined; + const reviewedHash = reviewed && sha(reviewed.bytes); + if ("sha256" in action && (!/^[a-f0-9]{64}$/.test(action.sha256) || action.sha256 !== reviewedHash)) + throw new Error("Reviewed manifest SHA-256 does not match."); + const options = { + bin: "codex", home: process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), + cwd: process.cwd(), command: resolveCommand(), timeoutMs: 5000, ...overrides, + }; + if (!isAbsolute(options.home)) + throw new Error("CODEX_HOME must be absolute for native hook review."); + options.home = realpathSync(options.home); + options.cwd = realpathSync(resolve(options.cwd)); + const scan = () => withServer(options, rpc => inventory(rpc, options)); + const dir = join(options.home, "agentmbx-hook-enrollment"); + const pending = join(dir, "pending.json"); + if (!reviewed || !reviewedHash) + return manifestFor(options, await scan()); + verifyPrivateDir(dir); + let receipt; + let nativeRefusal; + try { + const result = await withServer(options, async (rpc) => { + const prior = priorReceipt(dir); + let current; + try { + current = await inventory(rpc, options); + } + catch (error) { + if (!prior) + throw error; + return { + status: "outcome-unknown", operation: "read-only-reconciliation", receipt: pending, + detail: `The pending receipt was retained because fresh inventory failed. ${error.message}`, + }; + } + if (prior) { + const sameReview = prior.manifestSha256 === reviewedHash && matchesManifest(reviewed.value, current, options); + const status = sameReview && current.trusted && current.persisted ? "verified" : "outcome-unknown"; + const changes = sameReview ? preservation(current, prior, status !== "verified") : undefined; + return { + status, operation: "read-only-reconciliation", receipt: pending, ...readiness(current), + ...changes, concurrentDrift: !!(changes?.otherHooksChanged || changes?.configChanged), + detail: "The pending receipt was retained. Review it before further enrollment.", + }; + } + if (!matchesManifest(reviewed.value, current, options)) + throw new Error("Reviewed manifest identity or exact hook definitions changed. Inspect and review again."); + if (current.trusted) + return { status: "verified", operation: "no-op", ...readiness(current) }; + if (current.wouldMigrateHookState) + throw new Error(`Codex would also migrate existing hook state during the write. ${MANUAL}`); + const age = Date.now() - Date.parse(String(reviewed.value.inspectedAt)); + if (age < 0 || age > MAX_AGE || current.configVersion !== reviewed.value.configVersion || + digest(current.hooks) !== digest(reviewed.value.hooks)) + throw new Error("Reviewed inventory is stale. Inspect and review again."); + verifyPrivateDir(dir, true); + syncDir(options.home); + const prepared = { + schema: 1, id: randomUUID(), state: "prepared", at: new Date().toISOString(), + manifestSha256: reviewedHash, configVersion: current.configVersion, + expectedConfigDigest: current.expectedConfigDigest, configDigest: current.configDigest, otherDigest: current.otherDigest, + }; + saveReceipt(dir, prepared, true); + receipt = prepared; + let native; + try { + native = await rpc("config/batchWrite", { + edits: [{ keyPath: "hooks.state", value: current.edits, mergeStrategy: "upsert" }], + filePath: null, expectedVersion: current.configVersion, reloadUserConfig: true, + }); + } + catch (error) { + if (error instanceof NativeError && error.conflict) + nativeRefusal = error; + throw error; + } + if ((native.status !== "ok" && native.status !== "okOverridden") || + native.filePath !== join(options.home, "config.toml") || + typeof native.version !== "string" || !NATIVE_HASH.test(native.version)) + throw new Error("Malformed Codex config/batchWrite acknowledgement."); + receipt = { ...receipt, state: "applied", nativeVersion: native.version }; + saveReceipt(dir, receipt); + }); + if (result) + return result; + if (!receipt) + throw new Error("Missing enrollment receipt."); + const fresh = await scan(); + if (!matchesManifest(reviewed.value, fresh, options) || !fresh.trusted || !fresh.persisted) + throw new Error("Fresh Codex inventory could not verify the reviewed hooks as trusted."); + const changes = preservation(fresh, { ...receipt }); + const concurrentDrift = changes.otherHooksChanged || changes.configChanged; + const path = finishReceipt(dir, { ...receipt, state: "verified", concurrentDrift }); + return { status: "verified", operation: "enrolled", receipt: path, ...readiness(fresh), ...changes, concurrentDrift }; + } + catch (error) { + if (!receipt) + throw error; + const reason = error instanceof Error ? error.message : "Unknown enrollment failure."; + if (nativeRefusal) { + const path = finishReceipt(dir, { ...receipt, state: "refused", error: nativeRefusal.message }); + return { status: "refused", receipt: path, detail: nativeRefusal.message }; + } + // A failed receipt update leaves the earlier durable receipt in place. + try { + saveReceipt(dir, { ...receipt, state: "outcome-unknown", error: reason }); + } + catch { /* preserve the durable prepared or applied receipt */ } + return { + status: "outcome-unknown", receipt: pending, + detail: `${reason} Run enrollment with the original reviewed manifest for read-only reconciliation.`, + }; + } +} diff --git a/dist/doctor.js b/dist/doctor.js index acf73d79..8a739302 100644 --- a/dist/doctor.js +++ b/dist/doctor.js @@ -666,7 +666,7 @@ export function codexHooksChecks(ctx) { const hooks = edits(ctx, "codex").find((e) => e.kind === "hooks"); if (!hooks || !wired(hooks)) return []; - const fix = "Review Codex's native hook settings and normal trust prompts; if hooks are unavailable, use MCP mbx_whoami then mbx_catchup"; + const fix = "Run agentmbx codex-hooks inspect or review Codex’s normal trust prompts. If hooks are unavailable, use MCP mbx_whoami then mbx_catchup"; let features; try { features = parseToml(readFileSync(join(ctx.home, ".codex", "config.toml"), "utf8")).features; diff --git a/dist/setup.js b/dist/setup.js index 560fbb96..fb778bf1 100644 --- a/dist/setup.js +++ b/dist/setup.js @@ -1168,7 +1168,8 @@ const parseObj = (cur) => { /** [CLI event, `agentmbx hook` subcommand]. PermissionRequest is YOLO (docs/POLICY.md §5): it answers only under an active policy. */ const HOOK_EVENTS = [["SessionStart", "session-start"], ["UserPromptSubmit", "prompt"], ["PermissionRequest", "permission"]]; /** Claude and Codex also take a Stop hook that can keep the turn going ({"decision":"block"}) when mail arrived mid-turn. */ -const STOP_EVENTS = [...HOOK_EVENTS, ["Stop", "stop"]]; +export const STOP_EVENTS = [...HOOK_EVENTS, ["Stop", "stop"]]; +export const SETUP_HOOK_TIMEOUT_SEC = 10; /** Hooks in the Claude/Codex shape: { hooks: { Event: [ { hooks: [ {type, command} ] } ] } }. Appends groups; never edits others. * `commandFor` overrides the command for an event (T342: PostToolUse runs the bundled sh fast * path when the skill script is installed; absent, the event keeps the direct `agentmbx hook`. */ @@ -1182,7 +1183,7 @@ function jsonHooks(events, cli, cmd, commandFor, home) { const groups = (hooks[ev] ??= []); const ours = groups.flatMap((g) => (g.hooks ?? []).filter((h) => isOurHook(h.command ?? "", sub, cli, cmd))); if (!ours.length) { - groups.push({ hooks: [{ type: "command", command: want, timeout: 10 }] }); + groups.push({ hooks: [{ type: "command", command: want, timeout: SETUP_HOOK_TIMEOUT_SEC }] }); changed = true; continue; } @@ -3150,7 +3151,7 @@ export function runSetup(ctx, o) { rows.push(row); } if (d.cli === "codex" && o.mode === "install" && rows.some((r) => r.cli === "codex" && r.item.startsWith("hooks") && r.action !== "unchanged")) - rows.push({ cli: "codex", item: "note", path: "-", action: "manual", note: "Codex may ask you to review/trust the new hooks on next start" }); + rows.push({ cli: "codex", item: "note", path: "-", action: "manual", note: "Review and trust hooks in Codex or use agentmbx codex-hooks inspect followed by explicit enrollment" }); // T460: Hermes registers shell hooks when it builds a session's agent, so a session that is already running keeps what it had. if (d.cli === "hermes" && o.mode === "install" && rows.some((r) => r.cli === "hermes" && r.item.startsWith("hooks") && (r.action === "added" || r.action === "updated"))) rows.push({ cli: "hermes", item: "note", path: "-", action: "manual", note: "Hermes reads hooks when a session starts: they apply to sessions started after this" }); diff --git a/src/cli.ts b/src/cli.ts index 936f74aa..cd310b12 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -74,6 +74,8 @@ import { isSlotName } from "./project-slot.ts"; const HELP = `agentmbx (AgentMBX) — signed messages between AI coding agents, on this machine and across paired machines Start here + agentmbx codex-hooks inspect print a redacted native hook review manifest + agentmbx codex-hooks enroll --manifest --sha256 enroll four reviewed AgentMBX hooks agentmbx setup [--yes] [--dry-run] [--only claude,codex,opencode,kimi,hermes,grok,skill,daemon,owner] [--host ] [--no-owner] [--policy ask|collaborate|autonomous|yolo] [--uninstall] init this host, install the daemon, wire every detected agent CLI (MCP + hooks + skill), create the owner key agentmbx doctor [--fix] [--processes] checklist; --processes lists MCP/watch pid, ppid, birth, client liveness and RSS (read-only; excludes --fix) @@ -347,6 +349,22 @@ async function relayServerCommand(pos: string[], o: Record, str async function run(argv: string[]) { const [cmd, ...rest] = argv; if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") return console.log(HELP); + if (cmd === "codex-hooks") { + const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { + help: { type: "boolean", short: "h" }, manifest: { type: "string" }, sha256: { type: "string" }, + } }); + if (values.help) return console.log(commandHelp(cmd)); + const { codexHooks } = await import("./codex-hook-trust.ts"); + if (positionals.length === 1 && positionals[0] === "inspect" && !values.manifest && !values.sha256) + return console.log(JSON.stringify(await codexHooks({ inspect: true }), null, 2)); + if (positionals.length !== 1 || positionals[0] !== "enroll" || !values.manifest || !values.sha256) + return die("Use codex-hooks inspect or codex-hooks enroll --manifest --sha256 "); + const result = await codexHooks({ manifest: values.manifest, sha256: values.sha256 }); + console.log(JSON.stringify(result, null, 2)); + if ("status" in result && (result.status !== "verified" || + ("concurrentDrift" in result && result.concurrentDrift))) process.exitCode = 1; + return; + } if (cmd === "claude") return launchClaude(rest); // every argument belongs to Claude Code: parse nothing here const { values: o, positionals: pos } = parseArgs({ args: rest, allowPositionals: true, strict: cmd !== "hook" && cmd !== "mcp", options: { help: { type: "boolean", short: "h" }, force: { type: "boolean" }, diff --git a/src/codex-hook-trust.ts b/src/codex-hook-trust.ts new file mode 100644 index 00000000..a4be8e45 --- /dev/null +++ b/src/codex-hook-trust.ts @@ -0,0 +1,453 @@ +import { spawn } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { + closeSync, constants, fsyncSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, + readSync, realpathSync, renameSync, writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { isAbsolute, join, resolve } from "node:path"; +import { StringDecoder } from "node:string_decoder"; +import { clearTimeout, setTimeout } from "node:timers"; +import { hookCommand, resolveCommand, SETUP_HOOK_TIMEOUT_SEC, STOP_EVENTS } from "./setup.ts"; +import { version } from "./version.ts"; + +const CODEX_VERSION = "0.172.0"; +const MAX_FRAME = 8 * 1024 * 1024; +const MAX_MANIFEST = 64 * 1024; +const MAX_AGE = 30 * 60 * 1000; +const MANUAL = "Review hooks in Codex's native UI. Where native hooks are unavailable, use MCP mbx_whoami and mbx_catchup."; +const NATIVE_HASH = /^sha256:[a-f0-9]{64}$/; +const TRUST = ["managed", "untrusted", "trusted", "modified"]; + +type RecordValue = Record; +const object = (value: unknown): value is RecordValue => !!value && typeof value === "object" && !Array.isArray(value); +const sha = (value: string | Buffer) => createHash("sha256").update(value).digest("hex"); +const canonical = (value: unknown): string => JSON.stringify(value, (_, item: unknown) => + object(item) ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item); +const digest = (value: unknown) => sha(canonical(value)); + +class NativeError extends Error { + readonly conflict: boolean; + constructor(method: string, error: RecordValue) { + const conflict = error.code === -32600 && object(error.data) && + error.data.config_write_error_code === "configVersionConflict"; + const code = Number.isSafeInteger(error.code) ? String(error.code) : "unknown"; + super(`Codex ${method} rejected the request (RPC ${code}${conflict ? ", configVersionConflict" : ""}).${code === "-32601" ? ` ${MANUAL}` : ""}`); + this.conflict = conflict; + } +} + +/** Requests are serial, with a byte limit, a deadline and bounded child cleanup. */ +async function withServer(options: Options, use: (rpc: Rpc) => Promise): Promise { + const child = spawn(options.bin, ["app-server", "--listen", "stdio://"], { + cwd: options.cwd, env: { ...process.env, CODEX_HOME: options.home }, stdio: ["pipe", "pipe", "ignore"], + }); + const closed = new Promise(done => child.once("close", done)); + const decoder = new StringDecoder("utf8"); + let buffer = ""; + let nextId = 0; + let failure: Error | undefined; + let pending: { id: number; method: string; resolve: (value: RecordValue) => void; reject: (error: Error) => void } | undefined; + const fail = (message: string) => { + failure ??= new Error(message); + pending?.reject(failure); + }; + child.on("error", () => fail("Could not launch Codex app-server.")); + child.stdin.on("error", () => fail("Codex app-server input closed.")); + child.stdout.on("error", () => fail("Codex app-server output failed.")); + child.stdout.on("end", () => { if (pending) fail("Codex app-server closed before replying (EOF)."); }); + child.stdout.on("data", (chunk: Buffer) => { + if (failure) return; + buffer += decoder.write(chunk); + if (Buffer.byteLength(buffer) > MAX_FRAME) return fail("Codex app-server response exceeded the size limit."); + let end: number; + while ((end = buffer.indexOf("\n")) !== -1) { + const line = buffer.slice(0, end); + buffer = buffer.slice(end + 1); + if (!line.trim()) continue; + let message: unknown; + try { message = JSON.parse(line); } + catch { return fail("Invalid JSON from Codex app-server."); } + if (!object(message)) return fail("Invalid Codex app-server message."); + if (typeof message.method === "string" && !("id" in message)) continue; + if (!pending || message.id !== pending.id) return fail("Unexpected Codex app-server message."); + const request = pending; + pending = undefined; + if (object(message.error) && Number.isSafeInteger(message.error.code) && !("result" in message)) + request.reject(new NativeError(request.method, message.error)); + else if (object(message.result) && !("error" in message)) request.resolve(message.result); + else request.reject(new Error("Malformed Codex app-server reply.")); + } + }); + + const timeout = options.timeoutMs; + const rpc: Rpc = async (method, params) => { + if (failure) throw failure; + const id = ++nextId; + const timer = setTimeout(() => fail(`Codex ${method} timed out.`), timeout); + try { + return await new Promise((resolve, reject) => { + pending = { id, method, resolve, reject }; + child.stdin.write(JSON.stringify({ id, method, params }) + "\n"); + }); + } finally { + clearTimeout(timer); + pending = undefined; + } + }; + + try { + const init = await rpc("initialize", { + clientInfo: { name: "agentmbx", version: version() }, capabilities: { experimentalApi: true }, + }); + if (init.codexHome !== options.home || typeof init.userAgent !== "string" || + !init.userAgent.startsWith(`agentmbx/${CODEX_VERSION} `)) { + throw new Error(`Unsupported Codex version or Codex home mismatch. Native enrollment supports Codex ${CODEX_VERSION}. ${MANUAL}`); + } + child.stdin.write('{"method":"initialized"}\n'); + const result = await use(rpc); + if (failure) throw failure; + child.stdin.end(); + const code = await new Promise(done => { + const timer = setTimeout(() => done(undefined), timeout); + void closed.then(code => { clearTimeout(timer); done(code); }); + }); + if (code !== 0 || failure) throw new Error("Codex app-server did not close cleanly."); + return result; + } finally { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + child.stdin.destroy(); + child.stdout.destroy(); + } +} + +type Rpc = (method: string, params: RecordValue) => Promise; +type Options = { bin: string; home: string; cwd: string; command: string[]; timeoutMs: number }; +type Hook = { + key: string; eventName: string; source: "user"; sourcePath: string; handlerType: "command"; + command: string; timeoutSec: number; matcher: null; async: false; enabled: true; isManaged: false; + currentHash: string; trustStatus: string; +}; +type Manifest = { + schema: 1; reviewedProtocol: "codex-app-server-experimental"; codexVersion: string; agentmbxVersion: string; + codexHome: string; cwd: string; inspectedAt: string; configVersion: string; hooks: Hook[]; + manualReviewRequired: boolean; otherHooksNeedingReview: number; +}; + +function definition(hook: Hook) { + const { trustStatus: _trustStatus, ...rest } = hook; + return rest; +} + +async function inventory(rpc: Rpc, options: Options) { + const { home, cwd, command } = options; + const configPath = join(home, "config.toml"); + const sourcePath = join(home, "hooks.json"); + const config = await rpc("config/read", { cwd, includeLayers: true }); + const listed = await rpc("hooks/list", { cwds: [cwd] }); + if (!object(config.config) || !Array.isArray(config.layers) || !Array.isArray(listed.data) || listed.data.length !== 1) + throw new Error(`Unsupported Codex inventory response. ${MANUAL}`); + if (object(config.config.features) && config.config.features.hooks === false) + throw new Error(`Native hooks are disabled. ${MANUAL}`); + const entry: unknown = listed.data[0]; + if (!object(entry) || entry.cwd !== cwd || !Array.isArray(entry.hooks) || + !Array.isArray(entry.errors) || entry.errors.length || !Array.isArray(entry.warnings) || entry.warnings.length) + throw new Error(`Codex hook inventory is incomplete or reported diagnostics. ${MANUAL}`); + + const layers: unknown[] = config.layers; + const validated = layers.map(layer => { + if (!object(layer) || !object(layer.name) || typeof layer.name.type !== "string" || + typeof layer.version !== "string" || !object(layer.config)) + throw new Error(`Unsupported Codex config layer. ${MANUAL}`); + return { name: layer.name, version: layer.version, disabledReason: layer.disabledReason, config: layer.config }; + }); + const userLayers = validated.filter(layer => layer.name.type === "user"); + const user = userLayers[0]; + if (userLayers.length !== 1 || user.name.file !== configPath || user.name.profile != null || + user.disabledReason != null || !NATIVE_HASH.test(user.version) || realpathSync(configPath) !== configPath || + realpathSync(sourcePath) !== sourcePath) + throw new Error(`Codex inventory is outside the base user config and hooks scope. ${MANUAL}`); + + const keys = new Set(); + const rows = (entry.hooks as unknown[]).map(row => { + if (!object(row) || typeof row.key !== "string" || keys.has(row.key) || + typeof row.currentHash !== "string" || !row.currentHash || + typeof row.trustStatus !== "string" || !TRUST.includes(row.trustStatus)) + throw new Error(`Malformed Codex hook metadata. ${MANUAL}`); + keys.add(row.key); + return { ...row, key: row.key, currentHash: row.currentHash, trustStatus: row.trustStatus }; + }); + const hooks: Hook[] = STOP_EVENTS.map(([event, subcommand]) => { + const eventName = event[0].toLowerCase() + event.slice(1); + const expected = hookCommand(command, subcommand, "codex"); + const matching = rows.filter(row => Reflect.get(row, "eventName") === eventName && Reflect.get(row, "command") === expected); + const row: RecordValue & { key: string; currentHash: string; trustStatus: string } = matching[0]; + const nativeEvent = eventName.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`); + const prefix = `${sourcePath}:${nativeEvent}:`; + if (matching.length !== 1 || row.source !== "user" || row.sourcePath !== sourcePath || + !row.key.startsWith(prefix) || !/^\d+:\d+$/.test(row.key.slice(prefix.length)) || + row.handlerType !== "command" || row.matcher !== null || row.async !== false || row.enabled !== true || + row.isManaged !== false || row.pluginId !== null || row.environmentId !== null || + row.statusMessage !== null || row.additionalContextLimit !== null || + row.timeoutSec !== SETUP_HOOK_TIMEOUT_SEC || !NATIVE_HASH.test(row.currentHash) || row.trustStatus === "managed") + throw new Error(`Expected one unchanged AgentMBX ${event} definition in the Codex user hooks file. ${MANUAL}`); + return { + key: row.key, eventName, source: "user", sourcePath, handlerType: "command", command: expected, + timeoutSec: SETUP_HOOK_TIMEOUT_SEC, matcher: null, async: false, enabled: true, isManaged: false, + currentHash: row.currentHash, trustStatus: row.trustStatus, + }; + }); + const selected = new Set(hooks.map(hook => hook.key)); + const other = rows.filter(row => !selected.has(row.key)); + const otherHooksNeedingReview = other.filter(row => row.trustStatus === "untrusted" || row.trustStatus === "modified").length; + const edits = Object.fromEntries(hooks.map(hook => [hook.key, { trusted_hash: hook.currentHash }])); + const hookConfig = user.config.hooks ?? {}; + const state = object(hookConfig) ? hookConfig.state ?? {} : undefined; + if (!object(hookConfig) || !object(state)) throw new Error("Unexpected shape for native hooks.state."); + const nextState = { ...state }; + for (const [key, value] of Object.entries(edits)) { + if (key in state && !object(state[key])) throw new Error("Unexpected shape for a selected native hooks.state entry."); + nextState[key] = { ...(object(state[key]) ? state[key] : {}), ...value }; + } + const layerDigest = (next: boolean) => digest(validated.map(layer => layer === user + ? { ...layer, version: undefined, config: next ? { ...user.config, hooks: { ...hookConfig, state: nextState } } : user.config } + : layer)); + return { + hooks, configVersion: user.version, otherHooksNeedingReview, edits, + otherDigest: digest(other), configDigest: layerDigest(false), expectedConfigDigest: layerDigest(true), + trusted: hooks.every(hook => hook.trustStatus === "trusted"), + // Codex 0.172.0 splits legacy composite hashes anywhere in the table on write. + wouldMigrateHookState: Object.values(state).some(entry => + object(entry) && typeof entry.trusted_hash === "string" && entry.trusted_hash.includes("/")), + persisted: hooks.every(hook => { + const entry = state[hook.key]; + return object(entry) && entry.trusted_hash === hook.currentHash; + }), + }; +} + +type Inventory = Awaited>; + +function manifestFor(options: Options, current: Inventory): Manifest { + return { + schema: 1, reviewedProtocol: "codex-app-server-experimental", codexVersion: CODEX_VERSION, + agentmbxVersion: version(), codexHome: options.home, cwd: options.cwd, inspectedAt: new Date().toISOString(), + configVersion: current.configVersion, hooks: current.hooks, + manualReviewRequired: !current.trusted || current.otherHooksNeedingReview > 0, + otherHooksNeedingReview: current.otherHooksNeedingReview, + }; +} + +function readJson(path: string, privateFile = false): { bytes: Buffer; value: RecordValue } { + const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | (privateFile ? constants.O_NOFOLLOW : 0)); + try { + const stat = fstatSync(fd); + if (!stat.isFile() || stat.size > MAX_MANIFEST || (privateFile && (stat.mode & 0o077 || stat.uid !== process.getuid?.()))) + throw new Error("Expected a regular, bounded manifest or private receipt file."); + const raw = Buffer.alloc(MAX_MANIFEST + 1); + let size = 0; + while (size < raw.length) { + const count = readSync(fd, raw, size, raw.length - size, null); + if (!count) break; + size += count; + } + if (size > MAX_MANIFEST) throw new Error("Manifest or receipt exceeded the size limit."); + const bytes = raw.subarray(0, size); + let value: unknown; + try { value = JSON.parse(bytes.toString("utf8")); } + catch { throw new Error("Invalid manifest or receipt JSON."); } + if (!object(value)) throw new Error("Invalid manifest or receipt object."); + return { bytes, value }; + } finally { closeSync(fd); } +} + +type Receipt = { + schema: 1; id: string; state: "prepared" | "applied" | "verified" | "refused" | "outcome-unknown"; + at: string; manifestSha256: string; configVersion: string; expectedConfigDigest: string; configDigest: string; otherDigest: string; + nativeVersion?: string; error?: string; concurrentDrift?: boolean; +}; + +function syncDir(path: string) { + const fd = openSync(path, "r"); + try { fsyncSync(fd); } finally { closeSync(fd); } +} + +function saveReceipt(dir: string, receipt: Receipt, first = false) { + const pending = join(dir, "pending.json"); + const file = first ? pending : join(dir, `${randomUUID()}.tmp`); + const fd = openSync(file, "wx", 0o600); + try { + writeFileSync(fd, JSON.stringify(receipt, null, 2) + "\n"); + fsyncSync(fd); + } finally { closeSync(fd); } + if (!first) renameSync(file, pending); + syncDir(dir); +} + +function finishReceipt(dir: string, receipt: Receipt) { + saveReceipt(dir, receipt); + const path = join(dir, `${receipt.id}.json`); + renameSync(join(dir, "pending.json"), path); + syncDir(dir); + return path; +} + +function priorReceipt(dir: string) { + try { return readJson(join(dir, "pending.json"), true).value; } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } +} + +function verifyPrivateDir(dir: string, create = false) { + if (create) { + try { mkdirSync(dir, { mode: 0o700 }); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } + } + const stat = lstatSync(dir, { throwIfNoEntry: false }); + if (stat && (!stat.isDirectory() || stat.mode & 0o077 || stat.uid !== process.getuid?.())) + throw new Error("Expected a private, user-owned Codex enrollment receipt directory."); +} + +function matchesManifest(reviewed: RecordValue, current: Inventory, options: Options) { + const { schema, reviewedProtocol, codexVersion, agentmbxVersion, codexHome, cwd } = manifestFor(options, current); + if (reviewed.schema !== schema || reviewed.reviewedProtocol !== reviewedProtocol || + reviewed.codexVersion !== codexVersion || reviewed.agentmbxVersion !== agentmbxVersion || + reviewed.codexHome !== codexHome || reviewed.cwd !== cwd || + typeof reviewed.configVersion !== "string" || !NATIVE_HASH.test(reviewed.configVersion) || + typeof reviewed.inspectedAt !== "string" || !Number.isFinite(Date.parse(reviewed.inspectedAt)) || + !Array.isArray(reviewed.hooks) || reviewed.hooks.length !== current.hooks.length) + return false; + return current.hooks.every((hook, i) => { + const row: unknown = (reviewed.hooks as unknown[])[i]; + if (!object(row) || typeof row.trustStatus !== "string" || !TRUST.includes(row.trustStatus) || row.trustStatus === "managed") + return false; + const { trustStatus: _trustStatus, ...rest } = row; + return digest(rest) === digest(definition(hook)); + }); +} + +function readiness(current: Inventory) { + return { + agentmbxHooksTrusted: current.trusted, + manualReviewRequired: !current.trusted || current.otherHooksNeedingReview > 0, + otherHooksNeedingReview: current.otherHooksNeedingReview, + }; +} + +function preservation(current: Inventory, expected: RecordValue, uncertain = false) { + return { + otherHooksChanged: current.otherDigest !== expected.otherDigest, + configChanged: (current.configDigest !== expected.expectedConfigDigest && + !(uncertain && current.configDigest === expected.configDigest)) || + (!uncertain && expected.nativeVersion !== undefined && expected.nativeVersion !== current.configVersion), + }; +} + +/** Inspect or enroll exactly the four AgentMBX user hooks through native Codex RPC. */ +export async function codexHooks( + action: { inspect: true } | { manifest: string; sha256: string }, + overrides: Partial = {}, +) { + const reviewed = "manifest" in action ? readJson(action.manifest) : undefined; + const reviewedHash = reviewed && sha(reviewed.bytes); + if ("sha256" in action && (!/^[a-f0-9]{64}$/.test(action.sha256) || action.sha256 !== reviewedHash)) + throw new Error("Reviewed manifest SHA-256 does not match."); + const options: Options = { + bin: "codex", home: process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), + cwd: process.cwd(), command: resolveCommand(), timeoutMs: 5000, ...overrides, + }; + if (!isAbsolute(options.home)) throw new Error("CODEX_HOME must be absolute for native hook review."); + options.home = realpathSync(options.home); + options.cwd = realpathSync(resolve(options.cwd)); + const scan = () => withServer(options, rpc => inventory(rpc, options)); + const dir = join(options.home, "agentmbx-hook-enrollment"); + const pending = join(dir, "pending.json"); + if (!reviewed || !reviewedHash) return manifestFor(options, await scan()); + + verifyPrivateDir(dir); + let receipt: Receipt | undefined; + let nativeRefusal: NativeError | undefined; + try { + const result = await withServer(options, async rpc => { + const prior = priorReceipt(dir); + let current: Inventory; + try { current = await inventory(rpc, options); } + catch (error) { + if (!prior) throw error; + return { + status: "outcome-unknown", operation: "read-only-reconciliation", receipt: pending, + detail: `The pending receipt was retained because fresh inventory failed. ${(error as Error).message}`, + } as const; + } + if (prior) { + const sameReview = prior.manifestSha256 === reviewedHash && matchesManifest(reviewed.value, current, options); + const status = sameReview && current.trusted && current.persisted ? "verified" : "outcome-unknown"; + const changes = sameReview ? preservation(current, prior, status !== "verified") : undefined; + return { + status, operation: "read-only-reconciliation", receipt: pending, ...readiness(current), + ...changes, concurrentDrift: !!(changes?.otherHooksChanged || changes?.configChanged), + detail: "The pending receipt was retained. Review it before further enrollment.", + } as const; + } + if (!matchesManifest(reviewed.value, current, options)) + throw new Error("Reviewed manifest identity or exact hook definitions changed. Inspect and review again."); + if (current.trusted) return { status: "verified", operation: "no-op", ...readiness(current) } as const; + if (current.wouldMigrateHookState) + throw new Error(`Codex would also migrate existing hook state during the write. ${MANUAL}`); + const age = Date.now() - Date.parse(String(reviewed.value.inspectedAt)); + if (age < 0 || age > MAX_AGE || current.configVersion !== reviewed.value.configVersion || + digest(current.hooks) !== digest(reviewed.value.hooks)) + throw new Error("Reviewed inventory is stale. Inspect and review again."); + + verifyPrivateDir(dir, true); + syncDir(options.home); + const prepared: Receipt = { + schema: 1, id: randomUUID(), state: "prepared", at: new Date().toISOString(), + manifestSha256: reviewedHash, configVersion: current.configVersion, + expectedConfigDigest: current.expectedConfigDigest, configDigest: current.configDigest, otherDigest: current.otherDigest, + }; + saveReceipt(dir, prepared, true); + receipt = prepared; + let native: RecordValue; + try { + native = await rpc("config/batchWrite", { + edits: [{ keyPath: "hooks.state", value: current.edits, mergeStrategy: "upsert" }], + filePath: null, expectedVersion: current.configVersion, reloadUserConfig: true, + }); + } catch (error) { + if (error instanceof NativeError && error.conflict) nativeRefusal = error; + throw error; + } + if ((native.status !== "ok" && native.status !== "okOverridden") || + native.filePath !== join(options.home, "config.toml") || + typeof native.version !== "string" || !NATIVE_HASH.test(native.version)) + throw new Error("Malformed Codex config/batchWrite acknowledgement."); + receipt = { ...receipt, state: "applied", nativeVersion: native.version }; + saveReceipt(dir, receipt); + }); + if (result) return result; + if (!receipt) throw new Error("Missing enrollment receipt."); + const fresh = await scan(); + if (!matchesManifest(reviewed.value, fresh, options) || !fresh.trusted || !fresh.persisted) + throw new Error("Fresh Codex inventory could not verify the reviewed hooks as trusted."); + const changes = preservation(fresh, { ...receipt }); + const concurrentDrift = changes.otherHooksChanged || changes.configChanged; + const path = finishReceipt(dir, { ...receipt, state: "verified", concurrentDrift }); + return { status: "verified", operation: "enrolled", receipt: path, ...readiness(fresh), ...changes, concurrentDrift } as const; + } catch (error) { + if (!receipt) throw error; + const reason = error instanceof Error ? error.message : "Unknown enrollment failure."; + if (nativeRefusal) { + const path = finishReceipt(dir, { ...receipt, state: "refused", error: nativeRefusal.message }); + return { status: "refused", receipt: path, detail: nativeRefusal.message } as const; + } + // A failed receipt update leaves the earlier durable receipt in place. + try { saveReceipt(dir, { ...receipt, state: "outcome-unknown", error: reason }); } + catch { /* preserve the durable prepared or applied receipt */ } + return { + status: "outcome-unknown", receipt: pending, + detail: `${reason} Run enrollment with the original reviewed manifest for read-only reconciliation.`, + } as const; + } +} diff --git a/src/doctor.ts b/src/doctor.ts index b7854a21..d8f5e8e4 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -570,7 +570,7 @@ export async function opencodePluginChecks(ctx: SetupCtx, node: MbxNode, options export function codexHooksChecks(ctx: SetupCtx): Check[] { const hooks = edits(ctx, "codex").find((e) => e.kind === "hooks"); if (!hooks || !wired(hooks)) return []; - const fix = "Review Codex's native hook settings and normal trust prompts; if hooks are unavailable, use MCP mbx_whoami then mbx_catchup"; + const fix = "Run agentmbx codex-hooks inspect or review Codex’s normal trust prompts. If hooks are unavailable, use MCP mbx_whoami then mbx_catchup"; let features: unknown; try { features = parseToml(readFileSync(join(ctx.home, ".codex", "config.toml"), "utf8")).features; } catch { diff --git a/src/setup.ts b/src/setup.ts index 11a9bb14..e93496f4 100644 --- a/src/setup.ts +++ b/src/setup.ts @@ -1022,7 +1022,9 @@ const parseObj = (cur: string | null): Record => { /** [CLI event, `agentmbx hook` subcommand]. PermissionRequest is YOLO (docs/POLICY.md §5): it answers only under an active policy. */ const HOOK_EVENTS: [string, string][] = [["SessionStart", "session-start"], ["UserPromptSubmit", "prompt"], ["PermissionRequest", "permission"]]; /** Claude and Codex also take a Stop hook that can keep the turn going ({"decision":"block"}) when mail arrived mid-turn. */ -const STOP_EVENTS: [string, string][] = [...HOOK_EVENTS, ["Stop", "stop"]]; +export const STOP_EVENTS: [string, string][] = [...HOOK_EVENTS, ["Stop", "stop"]]; + +export const SETUP_HOOK_TIMEOUT_SEC = 10; type HookGroup = { matcher?: string; hooks?: { type?: string; command?: string; timeout?: number }[] }; @@ -1037,7 +1039,7 @@ function jsonHooks(events: [string, string][], cli: string, cmd: string[], comma const want = commandFor?.(sub) ?? hookCommand(cmd, sub, cli); const groups = (hooks[ev] ??= []); const ours = groups.flatMap((g) => (g.hooks ?? []).filter((h) => isOurHook(h.command ?? "", sub, cli, cmd))); - if (!ours.length) { groups.push({ hooks: [{ type: "command", command: want, timeout: 10 }] }); changed = true; continue; } + if (!ours.length) { groups.push({ hooks: [{ type: "command", command: want, timeout: SETUP_HOOK_TIMEOUT_SEC }] }); changed = true; continue; } // T533/T654: [another node that meets the engines floor, this install's entry] is current, // including Claude's post-tool sh wrapper. Never rewritten to this shell's node path. if (ours[0].command !== want && !hookCommandCurrent(ours[0].command ?? "", sub, cli, home, cmd)) { ours[0].command = want; changed = true; } @@ -2721,7 +2723,7 @@ export function runSetup(ctx: SetupCtx, o: RunOpts): Row[] { rows.push(row); } if (d.cli === "codex" && o.mode === "install" && rows.some((r) => r.cli === "codex" && r.item.startsWith("hooks") && r.action !== "unchanged")) - rows.push({ cli: "codex", item: "note", path: "-", action: "manual", note: "Codex may ask you to review/trust the new hooks on next start" }); + rows.push({ cli: "codex", item: "note", path: "-", action: "manual", note: "Review and trust hooks in Codex or use agentmbx codex-hooks inspect followed by explicit enrollment" }); // T460: Hermes registers shell hooks when it builds a session's agent, so a session that is already running keeps what it had. if (d.cli === "hermes" && o.mode === "install" && rows.some((r) => r.cli === "hermes" && r.item.startsWith("hooks") && (r.action === "added" || r.action === "updated"))) rows.push({ cli: "hermes", item: "note", path: "-", action: "manual", note: "Hermes reads hooks when a session starts: they apply to sessions started after this" }); diff --git a/test/codex-hook-trust.test.ts b/test/codex-hook-trust.test.ts new file mode 100644 index 00000000..f0b258e0 --- /dev/null +++ b/test/codex-hook-trust.test.ts @@ -0,0 +1,251 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import type { TestContext } from "node:test"; +import { codexHooks } from "../src/codex-hook-trust.ts"; + +const sha = (s: string) => createHash("sha256").update(s).digest("hex"); +const nativeHash = (s: string) => `sha256:${sha(s)}`; +const events = [ + ["sessionStart", "session_start", "session-start"], ["userPromptSubmit", "user_prompt_submit", "prompt"], + ["permissionRequest", "permission_request", "permission"], ["stop", "stop", "stop"], +]; + +function fixture(t: TestContext) { + const home = mkdtempSync(join(tmpdir(), "mbx-hook-trust-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + const path = join(home, "hooks.json"); + const config = join(home, "config.toml"); + const manifest = join(home, "review.json"); + const dataPath = join(home, "fixture.json"); + const dir = join(home, "agentmbx-hook-enrollment"); + const pending = join(dir, "pending.json"); + const writes = join(home, "writes.jsonl"); + const bin = join(home, "codex"); + const command = ["/opt/agentmbx"]; + const hooks = events.map(([eventName, key, subcommand], displayOrder) => ({ + key: `${path}:${key}:0:0`, eventName, handlerType: "command", command: `${command[0]} hook ${subcommand} --cli codex`, + async: false, matcher: null, timeoutSec: 10, statusMessage: null, additionalContextLimit: null, + sourcePath: path, source: "user", pluginId: null, environmentId: null, displayOrder, + enabled: true, isManaged: false, currentHash: nativeHash(key), + })); + const foreign = { ...hooks[3], key: `${path}:stop:1:0`, command: "FOREIGN_SECRET", currentHash: nativeHash("foreign") }; + const baseline = { mcp_servers: { other: { token: "CONFIG_SECRET" } }, + hooks: { state: { [foreign.key]: { enabled: true, trusted_hash: nativeHash("previous foreign") } } } }; + const data = { config: baseline, hooks: [...hooks, foreign], mode: "normal", starts: 0 }; + writeFileSync(config, ""); + writeFileSync(path, "{}"); + writeFileSync(bin, `#!${process.execPath} +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const { createHash } = require("node:crypto"); +const { createInterface } = require("node:readline"); +const path = require("node:path"); +const home = process.env.CODEX_HOME; +const file = path.join(home, "fixture.json"); +const d = JSON.parse(fs.readFileSync(file)); +const save = () => fs.writeFileSync(file, JSON.stringify(d)); +const hash = x => "sha256:" + createHash("sha256").update(JSON.stringify(x)).digest("hex"); +const send = (id, result) => console.log(JSON.stringify({id, result})); +const configPath = path.join(home, "config.toml"); +let initialized = false; +assert.deepEqual(process.argv.slice(2), ["app-server", "--listen", "stdio://"]); +d.starts++; +save(); +const lines = createInterface({input:process.stdin}); +lines.on("close", () => { if (d.mode === "bad-close" && wrote) process.exitCode = 13; }); +let wrote = false; +lines.on("line", line => { + const {method, id, params} = JSON.parse(line); + if (method === "initialize") { + assert.equal(params.capabilities.experimentalApi, true); + if (d.mode === "hang") return; + if (d.mode === "exit") process.exit(12); + if (d.mode === "malformed") return console.log("{ bad JSON SECRET"); + return send(id, {codexHome:home, userAgent:"agentmbx/" + (d.mode === "version" ? "9.0.0" : "0.172.0") + " (fixture)"}); + } + if (method === "initialized") { initialized = true; return; } + assert.equal(initialized, true); + if (method === "config/read") { + assert.deepEqual(params, {cwd:home, includeLayers:true}); + return send(id, {config:d.config, origins:{}, layers:[ + {name:{type:"user",file:configPath}, version:hash(d.config), config:d.config}, + {name:{type:"system",file:"/etc/codex/config.toml"}, version:hash({}), config:{}} + ]}); + } + if (method === "hooks/list") { + assert.deepEqual(params, {cwds:[home]}); + const hooks = d.hooks.map(h => { + const trusted = d.config.hooks.state[h.key]?.trusted_hash; + return {...h,trustStatus:trusted === h.currentHash ? "trusted" : trusted ? "modified" : "untrusted"}; + }); + return send(id, {data:[{cwd:home,hooks,warnings:[],errors:[]}]}); + } + assert.equal(method, "config/batchWrite"); + assert.equal(params.expectedVersion, hash(d.config)); + assert.equal(params.filePath, null); + assert.equal(params.reloadUserConfig, true); + assert.equal(params.edits.length, 1); + const [edit] = params.edits; + assert.equal(edit.keyPath, "hooks.state"); + assert.equal(edit.mergeStrategy, "upsert"); + assert.deepEqual(edit.value,Object.fromEntries(d.hooks.slice(0,4).map(h => [h.key,{trusted_hash:h.currentHash}]))); + const receiptPath = path.join(home, "agentmbx-hook-enrollment", "pending.json"); + assert.equal(JSON.parse(fs.readFileSync(receiptPath)).state, "prepared"); + assert.equal(fs.statSync(receiptPath).mode & 511, 384); + fs.appendFileSync(path.join(home, "writes.jsonl"), JSON.stringify(params) + "\\n"); + if (d.mode === "conflict") + return console.log(JSON.stringify({id,error:{code:-32600,message:"SECRET",data:{config_write_error_code:"configVersionConflict"}}})); + if (d.mode === "abort-before-write") process.exit(4); + Object.assign(d.config.hooks.state, edit.value); + const version = hash(d.config); + if (d.mode === "drift") d.config.concurrent = true; + save(); + wrote = true; + if (d.mode === "abort-after-write") process.exit(5); + if (d.mode === "timeout-after-write") return; + if (d.mode === "malformed-ack") return send(id, {status:"unexpected"}); + send(id, {status:"ok",filePath:configPath,version}); +}); +`, { mode: 0o700 }); + const save = (next: typeof data) => writeFileSync(dataPath, JSON.stringify(next)); + const read = (): typeof data => JSON.parse(readFileSync(dataPath, "utf8")); + save(data); + const options = { bin, home, cwd: home, command, timeoutMs: 800 }; + const inspect = () => codexHooks({ inspect: true }, options); + const review = async () => { + const result = await inspect(); + const content = JSON.stringify(result, null, 2); + writeFileSync(manifest, content); + return { result, content, args: { manifest, sha256: sha(content) } }; + }; + const enroll = (args: { manifest: string; sha256: string }) => codexHooks(args, options); + const setMode = (mode: string) => save({ ...read(), mode }); + const attempts = () => existsSync(writes) ? readFileSync(writes, "utf8").trim().split("\n").length : 0; + return { baseline, dir, pending, inspect, review, enroll, read, save, setMode, attempts }; +} + +test("inventory redacts unrelated material and enrollment verifies four hashes in a fresh process", async t => { + const f = fixture(t); + const { result, content, args } = await f.review(); + assert.ok("hooks" in result); + assert.equal(result.hooks.length, 4); + assert.ok(result.hooks.every(h => h.trustStatus === "untrusted")); + assert.equal(result.otherHooksNeedingReview, 1); + assert.doesNotMatch(content, /FOREIGN_SECRET|CONFIG_SECRET/); + assert.ok(!existsSync(f.dir)); + await assert.rejects(f.enroll({ ...args, sha256: "0".repeat(64) }), /SHA-256/); + const applied = await f.enroll(args); + assert.ok("status" in applied && applied.status === "verified" && applied.operation === "enrolled"); + assert.equal(applied.manualReviewRequired, true); + assert.equal(applied.configChanged, false); + assert.equal(applied.otherHooksChanged, false); + assert.equal(f.read().starts, 3); + assert.equal(f.attempts(), 1); + assert.equal(f.read().config.mcp_servers.other.token, "CONFIG_SECRET"); + assert.ok(!existsSync(f.pending)); + const [archive] = readdirSync(f.dir); + const path = join(f.dir, archive); + assert.equal(statSync(path).mode & 0o777, 0o600); + assert.doesNotMatch(readFileSync(path, "utf8"), /FOREIGN_SECRET|CONFIG_SECRET/); + + const changed = f.read(); + changed.config.mcp_servers.other.token = "BENIGN_NEW_VALUE"; + f.save(changed); + const noOp = await f.enroll(args); + assert.ok("status" in noOp && noOp.status === "verified" && noOp.operation === "no-op"); + assert.equal(f.attempts(), 1); + assert.deepEqual(readdirSync(f.dir), [archive]); +}); + +test("modified, substituted, and out-of-scope AgentMBX definitions cannot be enrolled", async t => { + const f = fixture(t); + const { args } = await f.review(); + const original = f.read(); + for (const patch of [{ timeoutSec: 11 }, { command: "foreign" }, { source: "project" }]) { + const changed = structuredClone(original); + Object.assign(changed.hooks[0], patch); + f.save(changed); + await assert.rejects(f.enroll(args), /unchanged AgentMBX SessionStart definition/); + } + assert.equal(f.attempts(), 0); +}); + +test("foreign composite hashes are opaque and legacy state migration blocks a write", async t => { + const f = fixture(t); + const current = f.read(); + const foreign = current.hooks[4]; + foreign.currentHash += "/content"; + current.config.hooks.state[foreign.key].trusted_hash += "/old-content"; + f.save(current); + const { args } = await f.review(); + await assert.rejects(f.enroll(args), /migrate existing hook state/); + assert.equal(f.attempts(), 0); +}); + +test("a stale review fails locally and a native CAS refusal is retained without retry", async t => { + const f = fixture(t); + const { args, content } = await f.review(); + const expired = JSON.stringify({ ...JSON.parse(content), inspectedAt: new Date(0).toISOString() }); + writeFileSync(args.manifest, expired); + await assert.rejects(f.enroll({ ...args, sha256: sha(expired) }), /stale/); + writeFileSync(args.manifest, content); + const changed = f.read(); + changed.config.mcp_servers.other.token = "DIFFERENT"; + f.save(changed); + await assert.rejects(f.enroll(args), /stale/); + assert.equal(f.attempts(), 0); + const fresh = await f.review(); + f.setMode("conflict"); + const result = await f.enroll(fresh.args); + assert.ok("status" in result && result.status === "refused"); + assert.match(result.detail ?? "", /configVersionConflict/); + assert.doesNotMatch(result.detail ?? "", /SECRET/); + assert.equal(f.attempts(), 1); + assert.ok(!existsSync(f.pending)); +}); + +test("unsupported and malformed servers, timeouts, and EOF fail closed", async t => { + const f = fixture(t); + for (const [mode, reason] of [ + ["version", /Unsupported Codex version/], ["malformed", /Invalid JSON/], + ["hang", /timed out/], ["exit", /EOF/], + ] as const) { + f.setMode(mode); + await assert.rejects(f.inspect(), reason); + } + assert.equal(f.attempts(), 0); +}); + +test("post-send failures reconcile read-only and retain the pending receipt", async t => { + for (const mode of ["abort-before-write", "abort-after-write", "timeout-after-write", "malformed-ack", "bad-close"]) { + await t.test(mode, async t => { + const f = fixture(t); + const { args } = await f.review(); + f.setMode(mode); + const first = await f.enroll(args); + assert.ok("status" in first && first.status === "outcome-unknown"); + const saved = readFileSync(f.pending, "utf8"); + assert.equal(JSON.parse(saved).state, "outcome-unknown"); + const second = await f.enroll(args); + assert.ok("operation" in second && second.operation === "read-only-reconciliation"); + assert.equal(second.status, mode === "abort-before-write" ? "outcome-unknown" : "verified"); + assert.equal(readFileSync(f.pending, "utf8"), saved); + assert.equal(f.attempts(), 1); + }); + } +}); + +test("fresh verification reports concurrent config drift separately from selected trust", async t => { + const f = fixture(t); + const { args } = await f.review(); + f.setMode("drift"); + const result = await f.enroll(args); + assert.ok("operation" in result && result.operation === "enrolled"); + assert.equal(result.configChanged, true); + assert.equal(result.otherHooksChanged, false); + assert.equal(result.agentmbxHooksTrusted, true); +});