passcontrol 1.5.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,7 @@
6
6
  // Bearer token with no "use this API key?" prompt. The sidecar strips it and the
7
7
  // gateway injects the real key, so Claude Code never holds one.
8
8
  //
9
- // The settings file belongs to the user. Only these two keys, and with
9
+ // The settings file belongs to the user. The env keys and tool hook, and with
10
10
  // --statusline a `statusLine` running `passcontrol statusline`, are written or
11
11
  // removed, in one save; the previous file is backed up, a file that is not a JSON
12
12
  // object is refused rather than overwritten, a different gateway already
@@ -15,6 +15,7 @@
15
15
  import fs from "node:fs";
16
16
  import os from "node:os";
17
17
  import path from "node:path";
18
+ import { GATE_HOOK_TIMEOUT_S } from "./subscription-gate.mjs";
18
19
 
19
20
  /** Not a secret: the sidecar discards whatever arrives in this header. */
20
21
  export const CLAUDE_CODE_AUTH_PLACEHOLDER = "passcontrol-sidecar";
@@ -65,11 +66,37 @@ function save(target, value, exists) {
65
66
  return backupPath;
66
67
  }
67
68
 
69
+ /**
70
+ * `hooks` with API mode's note-only prompt hook for `port`, or without it when `port`
71
+ * is null. Every other hook, subscription mode's included, is left as it is.
72
+ */
73
+ function withNoteOnlyHook(hooks, port) {
74
+ const isNoteOnly = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_NOTE_ONLY_URL.test(h.url);
75
+ const base = isObject(hooks) ? hooks : null;
76
+ const groups = Array.isArray(base?.UserPromptSubmit) ? base.UserPromptSubmit : [];
77
+ const kept = [];
78
+ for (const group of groups) {
79
+ if (!isObject(group) || !Array.isArray(group.hooks) || !group.hooks.some(isNoteOnly)) kept.push(group);
80
+ else {
81
+ const rest = group.hooks.filter((h) => !isNoteOnly(h));
82
+ if (rest.length) kept.push({ ...group, hooks: rest });
83
+ }
84
+ }
85
+ const ours = { hooks: [{ type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?note=only`, timeout: GATE_HOOK_TIMEOUT_S }] };
86
+ if (port !== null && groups.length === kept.length + 1 && groups.some((g) => same(g, ours))) return hooks;
87
+ if (port !== null) kept.push(ours);
88
+ if (!base && !kept.length) return hooks;
89
+ const next = { ...(base ?? {}) };
90
+ if (kept.length) next.UserPromptSubmit = kept;
91
+ else delete next.UserPromptSubmit;
92
+ return next;
93
+ }
94
+
68
95
  /**
69
96
  * The env keys, and with `statusLineCommand` the status line too, in ONE save:
70
97
  * two saves would back up the first save's output and lose the user's original.
71
98
  */
72
- export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null }) {
99
+ export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null, noteHookPort = null, toolHookPort = null }) {
73
100
  const { exists, value } = readSettings(target);
74
101
  const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : {};
75
102
  const rawKeyFound = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
@@ -87,12 +114,20 @@ export function writeClaudeCodeSettings({ target, baseUrl, force = false, status
87
114
  next = line.value;
88
115
  statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
89
116
  }
90
- const changed = !envDone || Boolean(statusLine?.changed);
117
+ // configure passes the sidecar's port; URL.port is "" for :80, which would write a hook to nowhere.
118
+ const hooks = withApiTools(withNoteOnlyHook(value.hooks, noteHookPort), toolHookPort ?? (new URL(baseUrl).port || 80));
119
+ const hooksChanged = !same(hooks ?? null, value.hooks ?? null);
120
+ if (hooksChanged) {
121
+ next = { ...next };
122
+ if (hooks && Object.keys(hooks).length) next.hooks = hooks;
123
+ else delete next.hooks;
124
+ }
125
+ const changed = !envDone || Boolean(statusLine?.changed) || hooksChanged;
91
126
  const backupPath = changed ? save(target, next, exists) : null;
92
127
  return { changed, backupPath, rawKeyFound, ...(statusLine ? { statusLine } : {}) };
93
128
  }
94
129
 
95
- /** PassControl's two env keys and its status line, in one save. */
130
+ /** PassControl's env keys, tool hook, optional note and status line, in one save. */
96
131
  export function removeClaudeCodeSettings({ target }) {
97
132
  if (!fs.existsSync(target)) return { changed: false };
98
133
  const { value } = readSettings(target);
@@ -110,6 +145,14 @@ export function removeClaudeCodeSettings({ target }) {
110
145
  const { statusLine: _ours, ...rest } = next;
111
146
  next = rest;
112
147
  }
148
+ if (isObject(next.hooks)) {
149
+ const hooks = withApiTools(withNoteOnlyHook(next.hooks, null), null);
150
+ if (!same(hooks, next.hooks)) {
151
+ next = { ...next };
152
+ if (Object.keys(hooks).length) next.hooks = hooks;
153
+ else delete next.hooks;
154
+ }
155
+ }
113
156
  if (next === value) return { changed: false };
114
157
  save(target, next, true);
115
158
  return { changed: true };
@@ -176,9 +219,10 @@ export function removeClaudeCodeStatusLine({ target }) {
176
219
 
177
220
  const LOOPBACK_BASE = "http://127.0.0.1:";
178
221
  const OUR_LOGS_ENDPOINT = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/otlp\/v1\/logs$/;
179
- const OUR_HOOK_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook(\?t=\d{1,4})?$/;
222
+ const OUR_HOOK_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook(\?(t=\d{1,4}(&mode=api)?|note=1))?$/;
223
+ // API mode's own prompt hook, for the agent's note only (1.6.0): never a stop.
224
+ const OUR_NOTE_ONLY_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook\?note=only$/;
180
225
  const OUR_SIDECAR_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}$/;
181
- const GATED_EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolBatch"];
182
226
  // The log-export settings this mode owns, with the value it writes.
183
227
  const LOGS_ENV = {
184
228
  OTEL_LOGS_EXPORTER: "otlp",
@@ -196,8 +240,8 @@ export function subscriptionEnv(port) {
196
240
  };
197
241
  }
198
242
 
199
- function gateHook(port) {
200
- return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook`, timeout: 5 };
243
+ function gateHook(port, note = false) {
244
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook${note ? "?note=1" : ""}`, timeout: GATE_HOOK_TIMEOUT_S };
201
245
  }
202
246
 
203
247
  // PreToolUse may hold a tool while the owner is asked (Phase 2), and Claude Code lets
@@ -206,14 +250,45 @@ function gateHook(port) {
206
250
  // told, and a Phase 1 hook (no `t`, 5 s) refuses a tool that would need the owner
207
251
  // instead of letting it through on the timeout.
208
252
  export const TOOL_HOOK_TIMEOUT_S = 600;
209
- function toolHook(port) {
210
- return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}`, timeout: TOOL_HOOK_TIMEOUT_S };
253
+ function toolHook(port, api = false) {
254
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}${api ? "&mode=api" : ""}`, timeout: TOOL_HOOK_TIMEOUT_S };
255
+ }
256
+
257
+ /** API mode always asks the sidecar before a tool. */
258
+ export function apiToolHooks(port) {
259
+ return { PreToolUse: [{ matcher: "*", hooks: [toolHook(port, true)] }] };
260
+ }
261
+
262
+ const OUR_API_TOOL_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook\?t=\d{1,4}&mode=api$/;
263
+
264
+ // Writing: the same ownership matcher and merge as subscription mode, scoped to tools, so
265
+ // an API setup replaces subscription mode's tool hook instead of adding a second one.
266
+ // Removing (port null): only API mode's own hook. Subscription mode's stays, or a Pro/Max
267
+ // setup would keep its prompt and batch hooks and lose its tool rules.
268
+ function withApiTools(hooks, port) {
269
+ const base = isObject(hooks) ? hooks : {};
270
+ const tools = Object.hasOwn(base, "PreToolUse") ? { PreToolUse: base.PreToolUse } : {};
271
+ const next = { ...base };
272
+ delete next.PreToolUse;
273
+ if (port !== null) return { ...next, ...withOurHooks(tools, port, false, apiToolHooks(port)) };
274
+ if (!Array.isArray(tools.PreToolUse)) return isObject(hooks) ? { ...next, ...tools } : hooks;
275
+ const isApiTool = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_API_TOOL_URL.test(h.url);
276
+ const kept = [];
277
+ for (const group of tools.PreToolUse) {
278
+ if (!isObject(group) || !Array.isArray(group.hooks) || !group.hooks.some(isApiTool)) kept.push(group);
279
+ else {
280
+ const rest = group.hooks.filter((h) => !isApiTool(h));
281
+ if (rest.length) kept.push({ ...group, hooks: rest });
282
+ }
283
+ }
284
+ return kept.length ? { ...next, PreToolUse: kept } : next;
211
285
  }
212
286
 
213
- export function subscriptionHooks(port) {
287
+ /** `note`: the agent's opt-in note rides on the prompt hook (`--agent-note`). */
288
+ export function subscriptionHooks(port, { note = false } = {}) {
214
289
  const hook = gateHook(port);
215
290
  return {
216
- UserPromptSubmit: [{ hooks: [hook] }],
291
+ UserPromptSubmit: [{ hooks: [gateHook(port, note)] }],
217
292
  PreToolUse: [{ matcher: "*", hooks: [toolHook(port)] }],
218
293
  PostToolBatch: [{ hooks: [hook] }],
219
294
  };
@@ -247,11 +322,10 @@ function withoutOurHooks(hooks) {
247
322
  }
248
323
 
249
324
  /** `hooks` with exactly this port's gate hooks, leaving them where they are when already right. */
250
- function withOurHooks(hooks, port) {
251
- const ours = subscriptionHooks(port);
325
+ function withOurHooks(hooks, port, note = false, ours = subscriptionHooks(port, { note })) {
252
326
  const base = isObject(hooks) ? hooks : {};
253
327
  const next = withoutOurHooks(base);
254
- for (const event of GATED_EVENTS) {
328
+ for (const event of Object.keys(ours)) {
255
329
  const current = Array.isArray(base[event]) ? base[event] : [];
256
330
  const already = current.filter((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook));
257
331
  if (already.length === 1 && same(already[0], ours[event][0])) next[event] = current;
@@ -273,7 +347,7 @@ function urlAllowed(patterns, url) {
273
347
  * Subscription mode's settings, in one save. Throws, writing nothing, when the
274
348
  * user already exports Claude Code's logs somewhere else and `force` is not set.
275
349
  */
276
- export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false }) {
350
+ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false, note = false }) {
277
351
  const { exists, value } = readSettings(target);
278
352
  const env = isObject(value.env) ? value.env : {};
279
353
  const endpoint = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
@@ -286,7 +360,7 @@ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, f
286
360
  `${target} already exports Claude Code's logs (${theirs.join(", ")}). Subscription mode would send them to the sidecar instead. Re-run with --force to do that; nothing was written.`
287
361
  );
288
362
  }
289
- let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port) };
363
+ let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port, note) };
290
364
  let statusLine;
291
365
  if (statusLineCommand) {
292
366
  const line = withStatusLine(next, statusLineCommand);
@@ -300,7 +374,7 @@ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, f
300
374
  changed,
301
375
  backupPath,
302
376
  ...(statusLine ? { statusLine } : {}),
303
- hookUrlsBlocked: Boolean(allowlist && [gateHook(port), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
377
+ hookUrlsBlocked: Boolean(allowlist && [gateHook(port), gateHook(port, note), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
304
378
  routed: env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER && typeof env.ANTHROPIC_BASE_URL === "string",
305
379
  };
306
380
  }
@@ -40,6 +40,7 @@ const newKey = () => `evt_${randomBytes(16).toString("base64url")}`;
40
40
  /** One event from readClaudeCodeEvents, as the gateway takes it. Absent fields are left out. */
41
41
  function toWire(event, key) {
42
42
  if (event.kind === "tool_decision") return toolDecisionWire(event, key);
43
+ if (event.kind === "injection_finding") return injectionFindingWire(event, key);
43
44
  const wire = {
44
45
  key,
45
46
  kind: event.kind === "api_error" ? "model_error" : "model_call",
@@ -75,6 +76,27 @@ function toolDecisionWire(event, key) {
75
76
  return wire;
76
77
  }
77
78
 
79
+ // What the sidecar's scan of a tool's output found (cli/injection-sidecar.mjs): the
80
+ // gateway's fixed fields only (plans/injection-guard.md §2b), so nothing a caller adds,
81
+ // least of all text, is ever sent.
82
+ function injectionFindingWire(event, key) {
83
+ const wire = {
84
+ key,
85
+ kind: "injection_finding",
86
+ at: event.at,
87
+ source: event.source,
88
+ path: event.path,
89
+ tool: event.tool,
90
+ families: event.families,
91
+ severity: event.severity,
92
+ detector: event.detector,
93
+ normalization_version: event.normalization_version,
94
+ block_sha256: event.block_sha256,
95
+ };
96
+ for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
97
+ return wire;
98
+ }
99
+
78
100
  /**
79
101
  * @param {{
80
102
  * send: (events: object[]) => Promise<{ status: number, error?: string, retryAfterS?: number }>,
@@ -0,0 +1,282 @@
1
+ // Subscription mode for Codex (1.6.0, L5).
2
+ //
3
+ // A Codex session signed in with a ChatGPT plan talks to OpenAI directly, so the
4
+ // gateway cannot refuse its calls, as with a Claude Pro/Max login
5
+ // (cli/subscription-gate.mjs). The stops and tool rules still reach it through
6
+ // Codex's hooks: `passcontrol configure codex --subscription` adds three to
7
+ // `$CODEX_HOME/hooks.json`, each running `passcontrol codex-hook`, which hands
8
+ // Codex's input to the sidecar's hook endpoint (the one Claude Code calls) and
9
+ // answers in Codex's terms:
10
+ //
11
+ // UserPromptSubmit a stopped agent's prompt is blocked and the turn ends
12
+ // PreToolUse a stopped agent's tools, and the tool rules' denials, are refused
13
+ // PostToolUse tool output is scanned for injection tells; always neutral
14
+ //
15
+ // Codex has command hooks only (no http hook), hence the relay. Three differences
16
+ // from Claude Code are handled here, not in the sidecar:
17
+ // * hooks.json is SHARED (Peras writes into it), unlike the profile file
18
+ // cli/codex.mjs writes. Only entries whose command is PassControl's are added,
19
+ // replaced or removed (Peras's `ours()` rule), and the file is backed up the first
20
+ // time PassControl writes into one it did not create;
21
+ // * on PreToolUse, Codex takes `continue`, `stopReason`, `suppressOutput` and
22
+ // `permissionDecision: "ask"` as a FAILED hook and runs the tool. The sidecar's
23
+ // answers carry `continue: false` with every stop, so Codex's answer is rebuilt
24
+ // from an allow-list, and an "ask" rule becomes a refusal that says why;
25
+ // * Codex runs a hook only once the user has trusted it in `/hooks`, by its hash.
26
+ // The command is the same string on every run of configure, so a trusted hook
27
+ // stays trusted;
28
+ // * the command names node and the CLI by absolute path, like Peras's. A bare
29
+ // `passcontrol` failed both ways on the owner's Mac: "command not found" under a
30
+ // GUI app's minimal PATH, and "Unknown command" from an older CLI on PATH. Either
31
+ // is a failed hook, so configure runs the exact command once under a bare PATH
32
+ // before saying it is set up.
33
+ //
34
+ // Honest limits, said in the CLI too: Codex has no strict hook mode, so a hook that
35
+ // fails or is not trusted lets the action go ahead; the tool rules' path rules (Read,
36
+ // Write, Edit) and domain rules (WebFetch) name Claude Code's tools, which Codex does
37
+ // not have, so only command rules (Bash) and MCP tool rules can match; and a session
38
+ // cannot be stopped on its own, since its calls never pass the gateway.
39
+ import { spawnSync } from "node:child_process";
40
+ import fs from "node:fs";
41
+ import os from "node:os";
42
+ import path from "node:path";
43
+
44
+ import { GATE_HOOK_TIMEOUT_S, HOOK_PATH } from "./subscription-gate.mjs";
45
+
46
+ /** Codex's timeout for the tool hook: an "ask the owner" rule holds it while the owner answers. */
47
+ export const CODEX_TOOL_HOOK_TIMEOUT_S = 600;
48
+ const PROMPT_RELAY_MS = GATE_HOOK_TIMEOUT_S * 1000 - 500;
49
+ const TOOL_RELAY_MS = (CODEX_TOOL_HOOK_TIMEOUT_S - 10) * 1000;
50
+ const POST_TOOL_RELAY_MS = 1500;
51
+ const EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolUse"];
52
+ const BACKUP_SUFFIX = ".passcontrol-backup";
53
+
54
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
55
+ const text = (v) => (typeof v === "string" && v.length > 0 ? v : null);
56
+
57
+ export function codexHooksPath({ env = process.env } = {}) {
58
+ return path.join(env.CODEX_HOME || path.join(env.HOME || os.homedir(), ".codex"), "hooks.json");
59
+ }
60
+
61
+ /** PassControl's own entry: `passcontrol codex-hook …`, or `node ".../passcontrol.mjs" codex-hook …`. */
62
+ export function isPassControlCodexHook(hook) {
63
+ return isObject(hook) && hook.type === "command" && typeof hook.command === "string" && /(^|[\s"/])passcontrol(\.mjs)?"?\s+codex-hook(\s|$)/u.test(hook.command);
64
+ }
65
+
66
+ /**
67
+ * The command all hooks run: node and the CLI by absolute path, so PATH never
68
+ * decides whether it runs. Refuses a path a shell would read differently.
69
+ */
70
+ export function codexHookCommand({ port, node = process.execPath, entry }) {
71
+ for (const p of [node, entry]) {
72
+ if (typeof p !== "string" || !p || /["$`]/u.test(p)) {
73
+ throw new Error(`The path ${JSON.stringify(String(p))} cannot be quoted safely for Codex's hook command.`);
74
+ }
75
+ }
76
+ return `"${node}" "${entry}" codex-hook --port ${port}`;
77
+ }
78
+
79
+ /**
80
+ * Runs the exact command as Codex would, under a bare PATH, with an input it answers
81
+ * with nothing. Not on Windows, where Codex runs hooks through its own shell.
82
+ */
83
+ export function probeCodexHookCommand(command) {
84
+ if (process.platform === "win32") return { ok: true };
85
+ const run = spawnSync("/bin/sh", ["-c", command], {
86
+ input: JSON.stringify({ hook_event_name: "SessionStart" }),
87
+ env: { PATH: "/usr/bin:/bin", HOME: os.homedir(), PASSCONTROL_NO_UPDATE_CHECK: "1" },
88
+ encoding: "utf8",
89
+ timeout: 15_000,
90
+ });
91
+ if (run.status !== 0) return { ok: false, why: `it ended with exit ${run.status ?? "none"}${run.stderr ? `: ${run.stderr.trim().slice(0, 200)}` : ""}` };
92
+ if (run.stdout.trim()) return { ok: false, why: `it printed output it should not: ${run.stdout.trim().slice(0, 200)}` };
93
+ return { ok: true };
94
+ }
95
+
96
+ /** The three entries PassControl adds, as a hooks file of their own. */
97
+ export function codexHookEntries(command) {
98
+ return {
99
+ hooks: {
100
+ UserPromptSubmit: [{ hooks: [{ type: "command", command, timeout: GATE_HOOK_TIMEOUT_S }] }],
101
+ PreToolUse: [{ matcher: ".*", hooks: [{ type: "command", command, timeout: CODEX_TOOL_HOOK_TIMEOUT_S }] }],
102
+ PostToolUse: [{ matcher: ".*", hooks: [{ type: "command", command, timeout: GATE_HOOK_TIMEOUT_S }] }],
103
+ },
104
+ };
105
+ }
106
+
107
+ function readHooksFile(target) {
108
+ if (!fs.existsSync(target)) return { value: {}, exists: false };
109
+ let value;
110
+ try {
111
+ value = JSON.parse(fs.readFileSync(target, "utf8"));
112
+ } catch {
113
+ value = null;
114
+ }
115
+ if (!isObject(value) || (value.hooks !== undefined && !isObject(value.hooks))) {
116
+ throw new Error(`${target} is not a hooks object; nothing was written.`);
117
+ }
118
+ return { value, exists: true };
119
+ }
120
+
121
+ /** Each event's groups with PassControl's hooks taken out; a group left empty goes. */
122
+ function withoutOurs(hooks) {
123
+ const next = { ...hooks };
124
+ for (const event of Object.keys(next)) {
125
+ if (!Array.isArray(next[event])) continue;
126
+ next[event] = next[event].flatMap((group) => {
127
+ if (!isObject(group) || !Array.isArray(group.hooks)) return [group];
128
+ const rest = group.hooks.filter((h) => !isPassControlCodexHook(h));
129
+ if (rest.length === group.hooks.length) return [group];
130
+ return rest.length ? [{ ...group, hooks: rest }] : [];
131
+ });
132
+ if (next[event].length === 0) delete next[event];
133
+ }
134
+ return next;
135
+ }
136
+
137
+ const hasOurs = (hooks) =>
138
+ Object.values(hooks ?? {}).some((groups) => Array.isArray(groups) && groups.some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isPassControlCodexHook)));
139
+
140
+ function save(target, value) {
141
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
142
+ const temp = `${target}.${process.pid}.tmp`;
143
+ fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
144
+ fs.renameSync(temp, target);
145
+ }
146
+
147
+ /** Add PassControl's three hooks, replacing any earlier ones of its own and nobody else's. */
148
+ export function writeCodexHooks({ target, command }) {
149
+ const { value, exists } = readHooksFile(target);
150
+ const hooks = withoutOurs(value.hooks ?? {});
151
+ for (const [event, groups] of Object.entries(codexHookEntries(command).hooks)) {
152
+ // Codex keys trust by place (`<file>:<event>:<group>:<hook>`), so an entry of ours
153
+ // goes back where it stood: appended, it would swap with a hook added after it and
154
+ // both would quietly lose their trust. The groups before it held none of ours, so
155
+ // they are still the first `at`.
156
+ const before = Array.isArray(value.hooks?.[event]) ? value.hooks[event] : [];
157
+ const at = before.findIndex((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isPassControlCodexHook));
158
+ const rest = Array.isArray(hooks[event]) ? hooks[event] : [];
159
+ hooks[event] = at < 0 ? [...rest, ...groups] : [...rest.slice(0, at), ...groups, ...rest.slice(at)];
160
+ }
161
+ const next = { ...value, hooks };
162
+ if (JSON.stringify(next) === JSON.stringify(value)) return { changed: false, backupPath: null };
163
+ let backupPath = null;
164
+ if (exists && !hasOurs(value.hooks)) {
165
+ backupPath = `${target}${BACKUP_SUFFIX}`;
166
+ fs.copyFileSync(target, backupPath);
167
+ fs.chmodSync(backupPath, 0o600);
168
+ }
169
+ save(target, next);
170
+ return { changed: true, backupPath };
171
+ }
172
+
173
+ /** Take PassControl's hooks back out; everything else stays as it was. */
174
+ export function removeCodexHooks({ target }) {
175
+ if (!fs.existsSync(target)) return { changed: false };
176
+ const { value } = readHooksFile(target);
177
+ if (!hasOurs(value.hooks)) return { changed: false };
178
+ const hooks = withoutOurs(value.hooks);
179
+ const { hooks: _old, ...rest } = value;
180
+ save(target, Object.keys(hooks).length ? { ...rest, hooks } : rest);
181
+ return { changed: true };
182
+ }
183
+
184
+ const ASK_IN_CODEX =
185
+ " Codex cannot ask here, so PassControl refuses it: the user can run it themselves, or the agent's owner can change the rule on the agent's page.";
186
+
187
+ /**
188
+ * The sidecar's answer (Claude Code's hook output) as Codex must get it, built from
189
+ * an allow-list: on PreToolUse, a field Codex does not support there fails the hook,
190
+ * and a failed hook lets the tool run.
191
+ */
192
+ export function codexHookAnswer(event, out) {
193
+ if (event === "PostToolUse") return {}; // Telemetry must never alter Codex output.
194
+ const o = isObject(out) ? out : {};
195
+ const systemMessage = text(o.systemMessage);
196
+ const warning = systemMessage ? { systemMessage } : {};
197
+ if (event === "PreToolUse") {
198
+ const hso = isObject(o.hookSpecificOutput) ? o.hookSpecificOutput : {};
199
+ const stopped = o.continue === false || o.decision === "block";
200
+ const said = text(hso.permissionDecisionReason) ?? text(o.stopReason) ?? text(o.reason);
201
+ let reason = null;
202
+ if (hso.permissionDecision === "deny" || stopped) reason = said ?? "PassControl refused this tool call.";
203
+ else if (hso.permissionDecision === "ask") reason = `${said ?? "PassControl: the agent's tool rules ask the user to confirm this."}${ASK_IN_CODEX}`;
204
+ if (reason === null) return warning;
205
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason }, ...warning };
206
+ }
207
+ if (event === "UserPromptSubmit") {
208
+ const answer = {};
209
+ if (o.continue === false) answer.continue = false;
210
+ if (text(o.stopReason)) answer.stopReason = o.stopReason;
211
+ if (o.decision === "block") answer.decision = "block";
212
+ if (text(o.reason)) answer.reason = o.reason;
213
+ const context = isObject(o.hookSpecificOutput) ? text(o.hookSpecificOutput.additionalContext) : null;
214
+ if (context) answer.hookSpecificOutput = { hookEventName: "UserPromptSubmit", additionalContext: context };
215
+ return { ...answer, ...warning };
216
+ }
217
+ return {};
218
+ }
219
+
220
+ /**
221
+ * What `passcontrol codex-hook` prints for one hook run: Codex's input in, the
222
+ * sidecar's answer out, or nothing. Never throws, and never blocks on its own
223
+ * failure: a sidecar that is down or slow lets the action go ahead, with a warning
224
+ * for prompts/pre-tool events. Post-tool telemetry always prints nothing.
225
+ */
226
+ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeoutMs = PROMPT_RELAY_MS, toolTimeoutMs = TOOL_RELAY_MS, postToolTimeoutMs = POST_TOOL_RELAY_MS }) {
227
+ let parsed;
228
+ try {
229
+ parsed = JSON.parse(input);
230
+ } catch {
231
+ return "";
232
+ }
233
+ const event = isObject(parsed) ? parsed.hook_event_name : null;
234
+ if (!EVENTS.includes(event)) return "";
235
+ const tool = event === "PreToolUse";
236
+ const postTool = event === "PostToolUse";
237
+ // A post-tool hook is telemetry only. Bound the entire operation, including a
238
+ // stalled response body or a transport that does not honor AbortSignal.
239
+ if (postTool) {
240
+ const controller = new AbortController();
241
+ let timer;
242
+ try {
243
+ const timeout = new Promise((resolve) => {
244
+ timer = setTimeout(() => { controller.abort(); resolve(""); }, postToolTimeoutMs);
245
+ });
246
+ const relay = async () => {
247
+ await fetchImpl(`http://127.0.0.1:${port}${HOOK_PATH}`, {
248
+ method: "POST", headers: { "content-type": "application/json" }, body: input, signal: controller.signal,
249
+ });
250
+ return "";
251
+ };
252
+ return await Promise.race([relay(), timeout]);
253
+ } catch {
254
+ return "";
255
+ } finally {
256
+ clearTimeout(timer);
257
+ controller.abort();
258
+ }
259
+ }
260
+ const controller = new AbortController();
261
+ const timer = setTimeout(() => controller.abort(), tool ? toolTimeoutMs : promptTimeoutMs);
262
+ const warn = (why) => JSON.stringify({ systemMessage: `PassControl: ${why}, so this goes ahead unchecked.` });
263
+ try {
264
+ const url = `http://127.0.0.1:${port}${HOOK_PATH}${tool ? `?t=${CODEX_TOOL_HOOK_TIMEOUT_S}` : ""}`;
265
+ const response = await fetchImpl(url, {
266
+ method: "POST",
267
+ headers: { "content-type": "application/json" },
268
+ body: input,
269
+ signal: controller.signal,
270
+ });
271
+ if (!response.ok) return warn(`the sidecar on port ${port} refused the hook (HTTP ${response.status})`);
272
+ const out = await response.json().catch(() => null);
273
+ if (!isObject(out)) return warn(`the sidecar on port ${port} gave an answer that cannot be read`);
274
+ const answer = codexHookAnswer(event, out);
275
+ return Object.keys(answer).length ? JSON.stringify(answer) : "";
276
+ } catch {
277
+ if (controller.signal.aborted) return warn(`the sidecar on port ${port} did not answer in time`);
278
+ return warn(`no sidecar answered on port ${port} (start it: passcontrol sidecar --port ${port})`);
279
+ } finally {
280
+ clearTimeout(timer);
281
+ }
282
+ }
package/cli/config.mjs CHANGED
@@ -677,6 +677,9 @@ export function formatProxyError(status, body) {
677
677
  if (status === 402 && error === "blocked_budget_period") {
678
678
  return `${blocked}\n→ The agent's daily or monthly limit is spent; it resets at the next UTC day or month (see the retry-after header).\n→ Fix: wait for the reset, or raise the limit in the dashboard.`;
679
679
  }
680
+ if (status === 402 && error === "blocked_budget_pause") {
681
+ return `${blocked}\n→ The agent reached the pause line its owner set on its spending limit; the limit itself is not used up.\n→ Fix: let it go on for an hour from the agent's page in the dashboard, or raise the pause line.`;
682
+ }
680
683
  if (status === 402 && error === "blocked_budget_delegation") {
681
684
  return `${blocked}\n→ This worker's delegation (or one above it) used its spending cap.\n→ Fix: ask the agent that delegated to it for a new delegation with a larger cap.`;
682
685
  }
@@ -0,0 +1,7 @@
1
+ import type { ToolRuleVerdict } from "./tool-rules.mjs";
2
+
3
+ export type TaintVerdict = ToolRuleVerdict | { effect: "ask_owner"; reason: "injection_taint" };
4
+
5
+ export const INJECTION_HOLD_TOOLS: ReadonlySet<string>;
6
+ export function heldUnderTaint(toolName: unknown): boolean;
7
+ export function underTaint<V extends ToolRuleVerdict>(verdict: V, toolName: unknown): V | { effect: "ask_owner"; reason: "injection_taint" };
@@ -0,0 +1,30 @@
1
+ // Injection guard Phase 2, `hold`: which tools wait for the owner while an agent is
2
+ // tainted (owner, 2026-10-30; plans/injection-guard.md §4).
3
+ //
4
+ // Shared by the sidecar's tool gate and the gateway's re-check in
5
+ // POST /api/v1/tool-approvals, so what the sidecar holds is exactly what the gateway
6
+ // will put to the owner. Reading goes on: Read, Glob and Grep pass. Acting waits:
7
+ // running a command, writing a file, fetching a URL (a URL can carry data out) and any
8
+ // MCP tool. An explicit deny rule still wins, as everywhere in the rule language.
9
+ // `apply_patch` is Codex's file edit (its shell arrives as `Bash`; seen live, Codex
10
+ // 0.163, 2026-10-30).
11
+
12
+ export const INJECTION_HOLD_TOOLS = new Set(["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit", "WebFetch", "apply_patch"]);
13
+
14
+ /** True for a tool a tainted agent may not run without the owner. */
15
+ export function heldUnderTaint(toolName) {
16
+ if (typeof toolName !== "string") return false;
17
+ if (INJECTION_HOLD_TOOLS.has(toolName)) return true;
18
+ // `mcp__<server>__<tool>`: anything past the prefix.
19
+ return toolName.startsWith("mcp__") && toolName.length > "mcp__".length;
20
+ }
21
+
22
+ /**
23
+ * The verdict while tainted: a held tool is put to the owner unless a rule already
24
+ * denies it or already asks the owner. Any other verdict comes back unchanged.
25
+ */
26
+ export function underTaint(verdict, toolName) {
27
+ if (!heldUnderTaint(toolName)) return verdict;
28
+ if (verdict?.effect === "deny" || verdict?.effect === "ask_owner") return verdict;
29
+ return { effect: "ask_owner", reason: "injection_taint" };
30
+ }
@@ -0,0 +1,11 @@
1
+ export type InjectionFamily = "role_markup" | "instruction_override" | "exfil_directive" | "authority_claim" | "hidden_text";
2
+ export type InjectionSeverity = "high" | "low";
3
+ export interface InjectionHit {
4
+ family: InjectionFamily;
5
+ severity: InjectionSeverity;
6
+ }
7
+
8
+ export const INJECTION_DETECTOR: "pc-heuristic-1";
9
+ export const INJECTION_NORMALIZATION: 1;
10
+ export const INJECTION_FAMILIES: readonly InjectionFamily[];
11
+ export function scanText(raw: string): InjectionHit[];