passport-bridge 0.11.2 → 0.13.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.
Files changed (58) hide show
  1. package/README.md +76 -10
  2. package/dist/cli.js +24 -0
  3. package/dist/cliArgs.d.ts +1 -1
  4. package/dist/cliArgs.js +14 -2
  5. package/dist/cliHook.d.ts +54 -11
  6. package/dist/cliHook.js +317 -75
  7. package/dist/cliHookClassify.d.ts +6 -0
  8. package/dist/cliHookClassify.js +23 -1
  9. package/dist/cliHookGuard.d.ts +39 -0
  10. package/dist/cliHookGuard.js +127 -0
  11. package/dist/cliHookInstall.d.ts +54 -21
  12. package/dist/cliHookInstall.js +397 -119
  13. package/dist/cliHookPending.d.ts +31 -0
  14. package/dist/cliHookPending.js +141 -0
  15. package/dist/cliInit.d.ts +74 -0
  16. package/dist/cliInit.js +477 -0
  17. package/dist/cliLogin.d.ts +15 -1
  18. package/dist/cliLogin.js +219 -41
  19. package/dist/cliOutput.js +10 -4
  20. package/dist/cliPolicy.d.ts +63 -0
  21. package/dist/cliPolicy.js +216 -0
  22. package/dist/cliScan.d.ts +21 -0
  23. package/dist/cliScan.js +220 -0
  24. package/dist/cliSetup.js +2 -0
  25. package/dist/cliSupport.d.ts +2 -0
  26. package/dist/completion.js +8 -3
  27. package/dist/discover.d.ts +9 -0
  28. package/dist/discover.js +18 -11
  29. package/dist/initAgents.d.ts +83 -0
  30. package/dist/initAgents.js +503 -0
  31. package/dist/initAppsStep.d.ts +22 -0
  32. package/dist/initAppsStep.js +346 -0
  33. package/dist/initInstall.d.ts +58 -0
  34. package/dist/initInstall.js +372 -0
  35. package/dist/initLocalSteps.d.ts +7 -0
  36. package/dist/initLocalSteps.js +313 -0
  37. package/dist/initState.d.ts +112 -0
  38. package/dist/initState.js +80 -0
  39. package/dist/initUi.d.ts +73 -0
  40. package/dist/initUi.js +273 -0
  41. package/dist/nodeVersion.d.ts +13 -0
  42. package/dist/nodeVersion.js +42 -0
  43. package/dist/passport.d.ts +1 -0
  44. package/dist/passport.js +21 -1
  45. package/dist/scan.d.ts +3 -0
  46. package/dist/scan.js +274 -0
  47. package/dist/scanCore.d.ts +139 -0
  48. package/dist/scanCore.js +386 -0
  49. package/dist/scanParse.d.ts +36 -0
  50. package/dist/scanParse.js +275 -0
  51. package/dist/scanRules.d.ts +246 -0
  52. package/dist/scanRules.js +402 -0
  53. package/dist/scanStores.d.ts +3 -0
  54. package/dist/scanStores.js +221 -0
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/npm-shrinkwrap.json +8 -8
  58. package/package.json +3 -3
@@ -1,22 +1,92 @@
1
1
  /**
2
- * Registering and removing the audit-only `passport hook` in an agent's own
3
- * settings. Every change is previewed unless `--apply` is supplied, the write
4
- * is atomic, and only Passport's own entry is ever added or taken away.
2
+ * Registering and removing Passport's shell hooks in an agent's own settings.
3
+ *
4
+ * Two entries per agent: the audit hook after each shell command, and, with
5
+ * `--guard`, the guard before it. Every change is previewed unless `--apply` is
6
+ * supplied, the write is atomic, and only Passport's own entries are ever added
7
+ * or taken away. Other hooks and settings are left as they were.
8
+ *
9
+ * | Agent | File | Before (guard) | After (audit) |
10
+ * | ----------- | ------------------------ | ---------------------- | --------------------- |
11
+ * | Claude Code | ~/.claude/settings.json | PreToolUse (Bash) | PostToolUse (Bash) |
12
+ * | Codex | ~/.codex/hooks.json | PreToolUse (Bash) | PostToolUse (Bash) |
13
+ * | Cursor | ~/.cursor/hooks.json | beforeShellExecution | afterShellExecution |
5
14
  */
6
15
  import { randomBytes } from "node:crypto";
7
- import { accessSync, closeSync, constants, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
16
+ import { accessSync, closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
8
17
  import { homedir } from "node:os";
9
18
  import { dirname, join } from "node:path";
10
19
  import { bool } from "./cliArgs.js";
11
- import { failure } from "./cliSupport.js";
12
- export const HOOK_CLIENTS = ["claude-code", "codex"];
20
+ import { readCliPolicy } from "./cliPolicy.js";
21
+ import { readCreds } from "./credentials.js";
22
+ import { failure, selectStoredProfile } from "./cliSupport.js";
23
+ export const HOOK_CLIENTS = ["claude-code", "codex", "cursor"];
13
24
  const SETTINGS_MAX_BYTES = 1024 * 1024;
14
25
  const HOOK_TIMEOUT_SECONDS = 5;
15
- const CODEX_NOT_AUTOMATED = "Codex hook registration is not automated yet. Add a PostToolUse hook that runs `passport hook`.";
16
- /** Recognise Passport's own entry however it was spelled: `passport hook`, or
17
- * an absolute path to the installed CLI followed by the same verb. */
26
+ export function claudeSettingsPath(env) {
27
+ const configured = env.CLAUDE_CONFIG_DIR?.trim();
28
+ return join(configured || join(homedir(), ".claude"), "settings.json");
29
+ }
30
+ export function codexHooksPath(env) {
31
+ const configured = env.CODEX_HOME?.trim();
32
+ return join(configured || join(homedir(), ".codex"), "hooks.json");
33
+ }
34
+ export function cursorHooksPath(env) {
35
+ // Cursor has no documented override for its home; tests and sandboxes use
36
+ // PASSPORT_CURSOR_HOME so a run never touches the real ~/.cursor.
37
+ const configured = env.PASSPORT_CURSOR_HOME?.trim();
38
+ return join(configured || join(homedir(), ".cursor"), "hooks.json");
39
+ }
40
+ const CLIENTS = {
41
+ "claude-code": {
42
+ id: "claude-code",
43
+ name: "Claude Code",
44
+ format: "groups",
45
+ pre: "PreToolUse",
46
+ post: "PostToolUse",
47
+ // Claude Code reports an interrupted or failed tool call here instead of
48
+ // PostToolUse, so an approved command that failed still counts as ran.
49
+ postFailure: "PostToolUseFailure",
50
+ path: claudeSettingsPath
51
+ },
52
+ codex: { id: "codex", name: "Codex", format: "groups", pre: "PreToolUse", post: "PostToolUse", path: codexHooksPath },
53
+ cursor: {
54
+ id: "cursor",
55
+ name: "Cursor",
56
+ format: "cursor",
57
+ pre: "beforeShellExecution",
58
+ post: "afterShellExecution",
59
+ path: cursorHooksPath
60
+ }
61
+ };
62
+ const PASSPORT_COMMAND = /passport[^\s"']*["']?\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?\s*$/i;
63
+ const VERB_TAIL = /^\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?\s*$/i;
64
+ /** "audit", "guard", or null. Recognises `passport hook`, an absolute path to
65
+ * the installed CLI followed by the same verb, and the exact `node <entry>`
66
+ * form this process registers when `passport` isn't on PATH, whatever
67
+ * folder that entry lives in. */
68
+ function passportEntryKind(command) {
69
+ if (typeof command !== "string")
70
+ return null;
71
+ const trimmed = command.trim();
72
+ let match = PASSPORT_COMMAND.exec(trimmed);
73
+ const own = ownInvocation();
74
+ if (!match && own && trimmed.startsWith(`${own} `))
75
+ match = VERB_TAIL.exec(trimmed.slice(own.length));
76
+ if (!match)
77
+ return null;
78
+ return match[1] ? "guard" : "audit";
79
+ }
80
+ /** Passport's audit entry, with or without `--client`. */
18
81
  export function isPassportHookCommand(command) {
19
- return typeof command === "string" && /passport[^\s"']*["']?\s+hook\s*$/i.test(command.trim());
82
+ return passportEntryKind(command) === "audit";
83
+ }
84
+ /** Passport's guard entry: `passport hook guard`, spelled the same ways. */
85
+ export function isPassportGuardCommand(command) {
86
+ return passportEntryKind(command) === "guard";
87
+ }
88
+ function isOurs(kind) {
89
+ return kind === "audit" ? isPassportHookCommand : isPassportGuardCommand;
20
90
  }
21
91
  function quoted(part) {
22
92
  return /[\s"']/.test(part) ? JSON.stringify(part) : part;
@@ -38,18 +108,35 @@ function executable(path) {
38
108
  return false;
39
109
  }
40
110
  }
41
- /** `passport hook` when the CLI is on PATH, otherwise this exact process. */
42
- export function hookCommand(env, exists = executable) {
43
- if (onPath("passport", env, exists))
44
- return "passport hook";
111
+ /** This exact process as a command prefix: `node <entry>`. */
112
+ function ownInvocation() {
45
113
  const entry = process.argv[1];
46
- if (!entry)
47
- return "passport hook";
48
- return `${quoted(process.execPath)} ${quoted(entry)} hook`;
114
+ return entry ? `${quoted(process.execPath)} ${quoted(entry)}` : null;
49
115
  }
50
- export function claudeSettingsPath(env) {
51
- const configured = env.CLAUDE_CONFIG_DIR?.trim();
52
- return join(configured || join(homedir(), ".claude"), "settings.json");
116
+ /** `passport` when the CLI is on PATH, otherwise this exact process. */
117
+ function passportInvocation(env, exists) {
118
+ if (onPath("passport", env, exists))
119
+ return "passport";
120
+ return ownInvocation() ?? "passport";
121
+ }
122
+ /** The registered audit command. Without a client it stays the historical
123
+ * `passport hook`, so older registrations still read as current. */
124
+ export function hookCommand(env, exists = executable, client, kind = "audit", invocation) {
125
+ const verb = kind === "guard" ? "hook guard" : "hook";
126
+ return `${invocation ?? passportInvocation(env, exists)} ${verb}${client ? ` --client ${client}` : ""}`;
127
+ }
128
+ /** A shell-safe `node <entry>` prefix for a hook command. */
129
+ export function nodeInvocation(node, entry) {
130
+ return `${quoted(node)} ${quoted(entry)}`;
131
+ }
132
+ /** Write through a symlinked settings file (dotfile managers) to its target. */
133
+ function writablePath(path) {
134
+ try {
135
+ return lstatSync(path).isSymbolicLink() ? realpathSync(path) : path;
136
+ }
137
+ catch {
138
+ return path;
139
+ }
53
140
  }
54
141
  function readSettings(path) {
55
142
  let raw;
@@ -58,29 +145,35 @@ function readSettings(path) {
58
145
  }
59
146
  catch (error) {
60
147
  if (error.code === "ENOENT")
61
- return { settings: {}, existed: false, raw: "" };
148
+ return { settings: {}, existed: false };
149
+ if (error.code === "EACCES") {
150
+ return failure(`Passport can't read ${displayPath(path)} (permission denied).`, 1, "settings");
151
+ }
62
152
  throw error;
63
153
  }
64
154
  if (Buffer.byteLength(raw) > SETTINGS_MAX_BYTES) {
65
155
  return failure("That agent's settings file is unexpectedly large; Passport did not change it.", 1, "settings");
66
156
  }
157
+ if (!raw.trim())
158
+ return { settings: {}, existed: true };
67
159
  let parsed;
68
160
  try {
69
161
  parsed = JSON.parse(raw);
70
162
  }
71
163
  catch {
72
- return failure("That agent's settings file is not valid JSON; fix it and run this again.", 1, "settings");
164
+ return failure(`${displayPath(path)} is not valid JSON, so Passport left it alone. Fix it and run this again.`, 1, "settings");
73
165
  }
74
166
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
75
167
  return failure("That agent's settings file must contain a JSON object.", 1, "settings");
76
168
  }
77
- return { settings: parsed, existed: true, raw };
169
+ return { settings: parsed, existed: true };
78
170
  }
79
171
  /** Same-directory temporary file, fsync, rename: the settings file is never
80
172
  * left half-written, even if the machine loses power mid-install. */
81
173
  function writeSettings(path, settings) {
82
- mkdirSync(dirname(path), { recursive: true });
83
- const temporary = join(dirname(path), `.passport-hook-${randomBytes(12).toString("hex")}.tmp`);
174
+ const target = writablePath(path);
175
+ mkdirSync(dirname(target), { recursive: true });
176
+ const temporary = join(dirname(target), `.passport-hook-${randomBytes(12).toString("hex")}.tmp`);
84
177
  let descriptor;
85
178
  try {
86
179
  descriptor = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
@@ -88,7 +181,7 @@ function writeSettings(path, settings) {
88
181
  fsyncSync(descriptor);
89
182
  closeSync(descriptor);
90
183
  descriptor = undefined;
91
- renameSync(temporary, path);
184
+ renameSync(temporary, target);
92
185
  }
93
186
  finally {
94
187
  if (descriptor !== undefined)
@@ -101,146 +194,331 @@ function writeSettings(path, settings) {
101
194
  }
102
195
  }
103
196
  }
104
- function postToolUseGroups(settings) {
197
+ function hooksOf(settings) {
105
198
  const hooks = settings.hooks;
106
- const groups = hooks && typeof hooks === "object" ? hooks.PostToolUse : undefined;
107
- return Array.isArray(groups) ? groups : [];
199
+ return hooks && typeof hooks === "object" && !Array.isArray(hooks) ? hooks : {};
200
+ }
201
+ function listOf(settings, event) {
202
+ const list = hooksOf(settings)[event];
203
+ return Array.isArray(list) ? list : [];
204
+ }
205
+ function commandsIn(spec, settings, event) {
206
+ const list = listOf(settings, event);
207
+ if (spec.format === "cursor")
208
+ return list.map((entry) => entry?.command);
209
+ return list.flatMap((group) => {
210
+ const hooks = group?.hooks;
211
+ return Array.isArray(hooks) ? hooks.map((entry) => entry?.command) : [];
212
+ });
108
213
  }
214
+ /** Every event an entry kind is registered on, primary first. */
215
+ function slotsOf(spec, kind) {
216
+ if (kind === "guard")
217
+ return [{ kind, event: spec.pre }];
218
+ return [{ kind, event: spec.post }, ...(spec.postFailure ? [{ kind, event: spec.postFailure }] : [])];
219
+ }
220
+ function registeredAt(spec, settings, slot) {
221
+ const found = commandsIn(spec, settings, slot.event).find(isOurs(slot.kind));
222
+ return typeof found === "string" ? found : null;
223
+ }
224
+ /** Whether a kind is on: its primary event holds Passport's entry. */
225
+ function registered(spec, settings, kind) {
226
+ return registeredAt(spec, settings, slotsOf(spec, kind)[0]);
227
+ }
228
+ /** The Passport audit command registered in Claude Code settings, if any. */
109
229
  export function registeredHookCommand(settings) {
110
- for (const group of postToolUseGroups(settings)) {
111
- for (const entry of Array.isArray(group.hooks) ? group.hooks : []) {
112
- if (isPassportHookCommand(entry.command))
113
- return entry.command;
114
- }
115
- }
116
- return null;
230
+ return registered(CLIENTS["claude-code"], settings, "audit");
117
231
  }
118
- /** Add Passport's entry to the Bash matcher without touching anything else. */
119
- export function withPassportHook(settings, command) {
120
- const hooks = { ...(settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {}) };
121
- const groups = [...postToolUseGroups(settings)];
232
+ function withEntry(spec, settings, slot, command) {
233
+ const { event } = slot;
234
+ const ours = isOurs(slot.kind);
235
+ const hooks = { ...hooksOf(settings) };
236
+ const list = [...listOf(settings, event)];
237
+ if (spec.format === "cursor") {
238
+ const kept = list.filter((entry) => !ours(entry?.command));
239
+ hooks[event] = [...kept, { command, timeout: HOOK_TIMEOUT_SECONDS }];
240
+ const version = typeof settings.version === "number" ? settings.version : 1;
241
+ return { ...settings, version, hooks };
242
+ }
122
243
  const entry = { type: "command", command, timeout: HOOK_TIMEOUT_SECONDS };
123
- const index = groups.findIndex((group) => group.matcher === "Bash");
244
+ const groups = list;
245
+ const index = groups.findIndex((group) => group && group.matcher === "Bash");
124
246
  if (index === -1)
125
247
  groups.push({ matcher: "Bash", hooks: [entry] });
126
248
  else {
127
249
  const existing = Array.isArray(groups[index].hooks) ? groups[index].hooks : [];
128
- groups[index] = {
129
- ...groups[index],
130
- hooks: [...existing.filter((candidate) => !isPassportHookCommand(candidate.command)), entry]
131
- };
250
+ groups[index] = { ...groups[index], hooks: [...existing.filter((candidate) => !ours(candidate?.command)), entry] };
132
251
  }
133
- return { ...settings, hooks: { ...hooks, PostToolUse: groups } };
252
+ hooks[event] = groups;
253
+ return { ...settings, hooks };
134
254
  }
135
- /** Remove only Passport's entry; a group we emptied goes with it. */
136
- export function withoutPassportHook(settings) {
137
- const groups = postToolUseGroups(settings)
138
- .map((group) => ({
139
- ...group,
140
- hooks: (Array.isArray(group.hooks) ? group.hooks : []).filter((entry) => !isPassportHookCommand(entry.command))
141
- }))
142
- .filter((group) => group.hooks.length > 0);
143
- const previous = settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {};
144
- const hooks = Object.fromEntries(Object.entries(previous).filter(([event]) => event !== "PostToolUse"));
145
- if (groups.length)
146
- hooks.PostToolUse = groups;
255
+ function withoutEntries(spec, settings, kinds) {
256
+ const previous = hooksOf(settings);
257
+ const hooks = { ...previous };
258
+ for (const { kind, event } of kinds.flatMap((kind) => slotsOf(spec, kind))) {
259
+ const ours = isOurs(kind);
260
+ if (!Array.isArray(previous[event]))
261
+ continue;
262
+ const list = previous[event];
263
+ const next = spec.format === "cursor"
264
+ ? list.filter((entry) => !ours(entry?.command))
265
+ : list
266
+ .map((group) => group && Array.isArray(group.hooks)
267
+ ? { ...group, hooks: group.hooks.filter((entry) => !ours(entry?.command)) }
268
+ : group)
269
+ .filter((group) => !(group && Array.isArray(group.hooks) && group.hooks.length === 0));
270
+ if (next.length)
271
+ hooks[event] = next;
272
+ else
273
+ delete hooks[event];
274
+ }
147
275
  const { hooks: _removed, ...rest } = settings;
148
276
  return Object.keys(hooks).length ? { ...rest, hooks } : rest;
149
277
  }
150
- function preview(action, path, change) {
278
+ /** Add Passport's audit entry to Claude Code's Bash matcher, touching nothing else. */
279
+ export function withPassportHook(settings, command) {
280
+ return withEntry(CLIENTS["claude-code"], settings, { kind: "audit", event: "PostToolUse" }, command);
281
+ }
282
+ /** Remove only Passport's audit entries; a group we emptied goes with it. */
283
+ export function withoutPassportHook(settings) {
284
+ return withoutEntries(CLIENTS["claude-code"], settings, ["audit"]);
285
+ }
286
+ /** Which Passport entries an agent's settings hold. Never throws. */
287
+ export function registeredEntries(client, env) {
288
+ const spec = CLIENTS[client];
289
+ try {
290
+ const { settings } = readSettings(spec.path(env));
291
+ return { audit: registered(spec, settings, "audit"), guard: registered(spec, settings, "guard") };
292
+ }
293
+ catch {
294
+ return { audit: null, guard: null };
295
+ }
296
+ }
297
+ export function displayPath(path) {
298
+ const home = homedir();
299
+ return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
300
+ }
301
+ const RECORDS_LINE = "It records the vendor, a coarse verb, and a risk class. Never the command line, its output, or your folder path.";
302
+ const LIMITS_LINE = "It can't see inside scripts, aliases, or make targets.";
303
+ const CODEX_TRUST_LINE = "Next: open Codex and trust the Passport hooks in /hooks.";
304
+ const CODEX_BLOCK_ONLY = "Codex can't ask first yet. Passport blocks only what your safety settings block.";
305
+ function planLines(changes) {
306
+ const width = Math.max(...changes.map((change) => change.event.length));
307
+ return changes.map((change) => ` ${change.action.padEnd(6)} ${change.event.padEnd(width)} ${change.command}`);
308
+ }
309
+ function previewResult(spec, action, path, changes, guard) {
310
+ return {
311
+ json: { preview: true, action, client: spec.id, path, guard, changes },
312
+ human: [
313
+ `Would change ${spec.name}:`,
314
+ ...planLines(changes),
315
+ ...(action === "uninstall" ? ["Other hooks stay as they are."] : []),
316
+ `File: ${displayPath(path)}`,
317
+ "Re-run with --apply to make this change."
318
+ ].join("\n")
319
+ };
320
+ }
321
+ function wantedEntries(spec, env, guard, invocation) {
322
+ // Claude Code is the historical default and is recognised from its input, so
323
+ // its commands stay unqualified and existing registrations stay current.
324
+ const named = spec.id === "claude-code" ? undefined : spec.id;
325
+ return (guard ? ["guard", "audit"] : ["audit"]).flatMap((kind) => slotsOf(spec, kind).map((slot) => ({ ...slot, command: hookCommand(env, undefined, named, kind, invocation) })));
326
+ }
327
+ function pendingChanges(spec, settings, wanted) {
328
+ const changes = [];
329
+ for (const entry of wanted) {
330
+ const current = registeredAt(spec, settings, entry);
331
+ if (current === entry.command)
332
+ continue;
333
+ changes.push({ action: current ? "update" : "add", event: entry.event, command: entry.command });
334
+ }
335
+ return changes;
336
+ }
337
+ /** Plan audit + guard for one agent, pointing at `invocation`. Throws a
338
+ * one-line CliFailure when the settings file is unreadable or malformed. */
339
+ export function planGuardInstall(client, env, invocation) {
340
+ const spec = CLIENTS[client];
341
+ const path = spec.path(env);
342
+ const { settings, existed } = readSettings(path);
151
343
  return {
152
- json: { preview: true, action, client: "claude-code", path, change },
153
- human: [`Would ${change}`, `File: ${path}`, "Re-run with --apply to make this local change."].join("\n")
344
+ client,
345
+ name: spec.name,
346
+ path,
347
+ existed,
348
+ changes: pendingChanges(spec, settings, wantedEntries(spec, env, true, invocation))
154
349
  };
155
350
  }
156
- function installClaudeCode(args, runtime) {
157
- const path = claudeSettingsPath(runtime.env);
351
+ /** Apply a plan. The file is read again, so an edit made since planning stays. */
352
+ export function applyGuardInstall(plan, env, invocation) {
353
+ const spec = CLIENTS[plan.client];
354
+ const { settings } = readSettings(plan.path);
355
+ let next = settings;
356
+ for (const entry of wantedEntries(spec, env, true, invocation))
357
+ next = withEntry(spec, next, entry, entry.command);
358
+ writeSettings(plan.path, next);
359
+ }
360
+ function installClient(spec, args, runtime) {
361
+ const path = spec.path(runtime.env);
158
362
  const { settings } = readSettings(path);
159
- const command = hookCommand(runtime.env);
160
- const current = registeredHookCommand(settings);
161
- if (current === command) {
363
+ const guard = bool(args, "guard");
364
+ const wanted = wantedEntries(spec, runtime.env, guard);
365
+ const changes = pendingChanges(spec, settings, wanted);
366
+ const guarded = guard || registered(spec, settings, "guard") !== null;
367
+ if (!changes.length) {
162
368
  return {
163
- json: { ok: true, action: "install", client: "claude-code", path, command, changed: false },
164
- human: `Claude Code already runs the Passport hook after each shell command.\nFile: ${path}`
369
+ json: { ok: true, action: "install", client: spec.id, path, guard: guarded, changed: false },
370
+ human: `${spec.name} already runs Passport ${guarded ? "audit + guard" : "audit"}.\nFile: ${displayPath(path)}`
165
371
  };
166
372
  }
167
- const change = current
168
- ? `update the Passport PostToolUse hook in Claude Code to run ${command}`
169
- : `register a Passport PostToolUse hook in Claude Code that runs ${command}`;
170
373
  if (!bool(args, "apply"))
171
- return preview("install", path, change);
172
- writeSettings(path, withPassportHook(settings, command));
374
+ return previewResult(spec, "install", path, changes, guard);
375
+ let next = settings;
376
+ for (const entry of wanted)
377
+ next = withEntry(spec, next, entry, entry.command);
378
+ writeSettings(path, next);
379
+ const lines = guard
380
+ ? [
381
+ `Guard on for ${spec.name}.`,
382
+ spec.id === "codex"
383
+ ? CODEX_BLOCK_ONLY
384
+ : "Passport asks before destructive commands it recognizes, like railway volume delete.",
385
+ LIMITS_LINE
386
+ ]
387
+ : [`${spec.name} now records the CLIs it runs in Passport Activity.`, RECORDS_LINE];
173
388
  return {
174
- json: { ok: true, action: "install", client: "claude-code", path, command, changed: true },
175
- human: [
176
- "Claude Code now records the CLIs it runs in Passport Activity.",
177
- "It records the vendor, a coarse verb, and a risk class. Never the command line, its output, or your folder path.",
178
- `File: ${path}`
179
- ].join("\n"),
389
+ json: { ok: true, action: "install", client: spec.id, path, guard: guarded, changed: true, changes },
390
+ human: [...lines, ...(spec.id === "codex" ? [CODEX_TRUST_LINE] : []), `File: ${displayPath(path)}`].join("\n"),
180
391
  essential: true
181
392
  };
182
393
  }
183
- function uninstallClaudeCode(args, runtime) {
184
- const path = claudeSettingsPath(runtime.env);
185
- const { settings, existed } = readSettings(path);
186
- const current = registeredHookCommand(settings);
187
- if (!existed || !current) {
394
+ function uninstallClient(spec, args, runtime) {
395
+ const path = spec.path(runtime.env);
396
+ const { settings } = readSettings(path);
397
+ const guardOnly = bool(args, "guard");
398
+ const kinds = guardOnly ? ["guard"] : ["guard", "audit"];
399
+ const changes = kinds
400
+ .flatMap((kind) => slotsOf(spec, kind))
401
+ .flatMap((slot) => {
402
+ const current = registeredAt(spec, settings, slot);
403
+ return current ? [{ action: "remove", event: slot.event, command: current }] : [];
404
+ });
405
+ if (!changes.length) {
188
406
  return {
189
- json: { ok: true, action: "uninstall", client: "claude-code", path, changed: false },
190
- human: `Claude Code does not run the Passport hook.\nFile: ${path}`
407
+ json: { ok: true, action: "uninstall", client: spec.id, path, changed: false },
408
+ human: `${spec.name} doesn't run ${guardOnly ? "the Passport guard" : "Passport hooks"}.\nFile: ${displayPath(path)}`
191
409
  };
192
410
  }
193
411
  if (!bool(args, "apply"))
194
- return preview("uninstall", path, "remove the Passport PostToolUse hook from Claude Code");
195
- writeSettings(path, withoutPassportHook(settings));
412
+ return previewResult(spec, "uninstall", path, changes, guardOnly);
413
+ writeSettings(path, withoutEntries(spec, settings, kinds));
414
+ const stillAudits = guardOnly && registered(spec, settings, "audit") !== null;
196
415
  return {
197
- json: { ok: true, action: "uninstall", client: "claude-code", path, changed: true },
198
- human: `Removed the Passport hook from Claude Code. Other hooks were left alone.\nFile: ${path}`,
416
+ json: { ok: true, action: "uninstall", client: spec.id, path, changed: true, changes },
417
+ human: [
418
+ guardOnly
419
+ ? `Guard off for ${spec.name}.${stillAudits ? " Passport still records the CLIs it runs." : ""}`
420
+ : `Removed Passport's hooks from ${spec.name}. Other hooks were left alone.`,
421
+ `File: ${displayPath(path)}`
422
+ ].join("\n"),
199
423
  essential: true
200
424
  };
201
425
  }
202
- function hookStatus(runtime) {
203
- const path = claudeSettingsPath(runtime.env);
204
- let command = null;
426
+ function clientStatus(spec, env) {
427
+ const path = spec.path(env);
428
+ let audit = null;
429
+ let guard = null;
430
+ let mode;
205
431
  try {
206
- command = registeredHookCommand(readSettings(path).settings);
432
+ const { settings } = readSettings(path);
433
+ audit = registered(spec, settings, "audit");
434
+ guard = registered(spec, settings, "guard");
435
+ mode = audit && guard ? "audit + guard" : audit ? "audit" : guard ? "guard" : "not installed";
207
436
  }
208
437
  catch {
209
- command = null;
438
+ mode = "unreadable";
210
439
  }
211
- const agents = [
212
- { client: "claude-code", registered: Boolean(command), command, path },
213
- { client: "codex", registered: false, command: null, path: null }
214
- ];
215
440
  return {
216
- json: { agents },
217
- human: [
218
- command
219
- ? `Claude Code · registered · ${command}`
220
- : "Claude Code · not registered · run: passport hook install --client claude-code --apply",
221
- "Codex · not registered · registration is not automated yet"
222
- ].join("\n"),
223
- essential: true
441
+ client: spec.id,
442
+ name: spec.name,
443
+ mode,
444
+ registered: audit !== null,
445
+ guard: guard !== null,
446
+ command: audit,
447
+ guardCommand: guard,
448
+ path,
449
+ agentPresent: existsSync(dirname(path))
224
450
  };
225
451
  }
452
+ function ageText(ms) {
453
+ const minutes = Math.floor(ms / 60_000);
454
+ if (minutes < 1)
455
+ return "just now";
456
+ if (minutes < 60)
457
+ return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
458
+ const hours = Math.floor(minutes / 60);
459
+ if (hours < 48)
460
+ return `${hours} hour${hours === 1 ? "" : "s"} ago`;
461
+ const days = Math.floor(hours / 24);
462
+ return `${days} days ago`;
463
+ }
464
+ function policyStatus(args, env, now) {
465
+ let profile;
466
+ try {
467
+ const creds = readCreds();
468
+ const selected = selectStoredProfile(args, env, creds, false).profile;
469
+ profile = selected && Object.hasOwn(creds, selected) ? selected : undefined;
470
+ }
471
+ catch {
472
+ profile = undefined;
473
+ }
474
+ const cached = profile ? readCliPolicy(profile) : null;
475
+ const ageMs = cached ? Math.max(0, now - cached.fetchedAt) : null;
476
+ const line = !profile
477
+ ? "Safety settings: built-in, asks before destructive commands (not signed in)."
478
+ : !cached
479
+ ? "Safety settings: built-in until synced. Run passport status to sync."
480
+ : `Safety settings: synced ${ageText(ageMs ?? 0)} for ${profile}.`;
481
+ return {
482
+ json: {
483
+ profile: profile ?? null,
484
+ source: cached ? "synced" : "built-in",
485
+ fetchedAt: cached?.fetchedAt ?? null,
486
+ ageMs,
487
+ safetyProfile: cached?.profile ?? null
488
+ },
489
+ line
490
+ };
491
+ }
492
+ function hookStatus(args, runtime) {
493
+ const agents = HOOK_CLIENTS.map((client) => clientStatus(CLIENTS[client], runtime.env));
494
+ const policy = policyStatus(args, runtime.env, Date.now());
495
+ const disabled = runtime.env.PASSPORT_HOOK_DISABLED === "1";
496
+ const nameWidth = Math.max(...agents.map((agent) => agent.name.length));
497
+ const modeWidth = Math.max(...agents.map((agent) => agent.mode.length));
498
+ const unguarded = agents.find((agent) => agent.agentPresent && !agent.guard && agent.mode !== "unreadable");
499
+ const codexGuarded = agents.some((agent) => agent.client === "codex" && agent.guard);
500
+ const lines = [
501
+ ...agents.map((agent) => `${agent.name.padEnd(nameWidth)} ${agent.mode.padEnd(modeWidth)} ${displayPath(agent.path)}`),
502
+ "",
503
+ policy.line,
504
+ ...(codexGuarded ? ["Codex can only block, not ask, so it skips commands set to ask first."] : []),
505
+ ...(disabled ? ["PASSPORT_HOOK_DISABLED=1 is set, so hooks do nothing in this shell."] : []),
506
+ ...(unguarded ? [`Turn on the guard: passport hook install --client ${unguarded.client} --guard --apply`] : [])
507
+ ];
508
+ return { json: { agents, policy: policy.json, disabled }, human: lines.join("\n"), essential: true };
509
+ }
226
510
  export function hookRegistration(action, client, args, runtime) {
227
511
  if (action === "status") {
228
512
  if (client)
229
513
  return failure("passport hook status takes no --client.", 6, "usage");
230
- return hookStatus(runtime);
514
+ if (bool(args, "guard"))
515
+ return failure("passport hook status takes no --guard.", 6, "usage");
516
+ return hookStatus(args, runtime);
231
517
  }
232
518
  const chosen = client ?? "claude-code";
233
519
  if (!HOOK_CLIENTS.includes(chosen)) {
234
- return failure("Choose --client claude-code or --client codex.", 6, "usage");
235
- }
236
- // The spike found no documented Codex file and schema for registering a
237
- // PostToolUse hook, so Passport refuses to guess at one.
238
- if (chosen === "codex") {
239
- return {
240
- json: { ok: true, action, client: "codex", automated: false },
241
- human: CODEX_NOT_AUTOMATED,
242
- essential: true
243
- };
520
+ return failure("Choose --client claude-code, --client codex, or --client cursor.", 6, "usage");
244
521
  }
245
- return action === "install" ? installClaudeCode(args, runtime) : uninstallClaudeCode(args, runtime);
522
+ const spec = CLIENTS[chosen];
523
+ return action === "install" ? installClient(spec, args, runtime) : uninstallClient(spec, args, runtime);
246
524
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Asks the guard is holding until it knows how they ended.
3
+ *
4
+ * When the guard asks before a command in Claude Code, the person either
5
+ * approves it, and the audit hook sees the same tool-use id after it runs, or
6
+ * declines it, and nothing follows: no agent fires a hook for a declined
7
+ * prompt. So the guard parks its report here instead of sending it. The audit
8
+ * hook takes it back and sends one row, "asked first, then ran". An ask nobody
9
+ * claimed within `PENDING_ASK_MS` is sent by the next hook run on this machine
10
+ * as "asked first, not run".
11
+ *
12
+ * A parked report holds exactly what would have been sent (vendor, coarse verb,
13
+ * risk, session and tool-use ids, folder name), never the command line. Files
14
+ * are owner-only, claimed by atomic rename so two hook processes never send the
15
+ * same ask, and bounded in count and age. Every function here never throws.
16
+ */
17
+ /** Longer than Claude Code's longest default Bash timeout plus a slow answer. */
18
+ export declare const PENDING_ASK_MS: number;
19
+ type Parked = {
20
+ createdAt: number;
21
+ report: Record<string, unknown>;
22
+ };
23
+ /** Park one ask. False when it couldn't, and the caller sends it now instead. */
24
+ export declare function holdAsk(runtime: string, sessionId: string | undefined, toolUseId: string, report: Record<string, unknown>, now?: number): boolean;
25
+ /** The audit hook takes back the ask for the command that just ran. */
26
+ export declare function takeAsk(runtime: string, sessionId: string | undefined, toolUseId: string): Parked | null;
27
+ /** Asks nobody claimed in time, oldest first, a few per hook run. */
28
+ export declare function takeExpired(now?: number): Parked[];
29
+ /** Whether any parked ask is old enough to send. Cheap: no reads. */
30
+ export declare function hasExpired(now?: number): boolean;
31
+ export {};