passport-bridge 0.11.3 → 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 (57) 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/cliSupport.d.ts +2 -0
  25. package/dist/completion.js +8 -3
  26. package/dist/discover.d.ts +9 -0
  27. package/dist/discover.js +18 -11
  28. package/dist/initAgents.d.ts +83 -0
  29. package/dist/initAgents.js +503 -0
  30. package/dist/initAppsStep.d.ts +22 -0
  31. package/dist/initAppsStep.js +346 -0
  32. package/dist/initInstall.d.ts +58 -0
  33. package/dist/initInstall.js +372 -0
  34. package/dist/initLocalSteps.d.ts +7 -0
  35. package/dist/initLocalSteps.js +313 -0
  36. package/dist/initState.d.ts +112 -0
  37. package/dist/initState.js +80 -0
  38. package/dist/initUi.d.ts +73 -0
  39. package/dist/initUi.js +273 -0
  40. package/dist/nodeVersion.d.ts +13 -0
  41. package/dist/nodeVersion.js +42 -0
  42. package/dist/passport.d.ts +1 -0
  43. package/dist/passport.js +21 -1
  44. package/dist/scan.d.ts +3 -0
  45. package/dist/scan.js +274 -0
  46. package/dist/scanCore.d.ts +139 -0
  47. package/dist/scanCore.js +386 -0
  48. package/dist/scanParse.d.ts +36 -0
  49. package/dist/scanParse.js +275 -0
  50. package/dist/scanRules.d.ts +246 -0
  51. package/dist/scanRules.js +402 -0
  52. package/dist/scanStores.d.ts +3 -0
  53. package/dist/scanStores.js +221 -0
  54. package/dist/version.d.ts +1 -1
  55. package/dist/version.js +1 -1
  56. package/npm-shrinkwrap.json +8 -8
  57. package/package.json +3 -3
package/dist/cliHook.js CHANGED
@@ -1,25 +1,35 @@
1
1
  /**
2
- * `passport hook` — the audit-only shell hook an agent runs after each command.
2
+ * `passport hook`: the shell hooks an agent runs around each command.
3
3
  *
4
- * It classifies the command locally, keeps the vendor, a coarse verb and a risk
5
- * class, and records that as one Activity row per governed invocation. It never
6
- * blocks, never returns a permission decision, and never sends the command
7
- * line, its arguments, the output, the full working directory, or the
8
- * environment. A failure of any kind is silent: an audit trail is never worth
9
- * disturbing the agent for.
4
+ * - `passport hook` (audit) runs after a command. It classifies the command
5
+ * locally, keeps the vendor, a coarse verb and a risk class, and records that
6
+ * as one Activity row per governed invocation.
7
+ * - `passport hook guard` runs before a command. For a destructive verb it
8
+ * recognises, it asks the person to confirm, or blocks when their safety
9
+ * settings say so. Otherwise it says nothing and the agent's own permission
10
+ * rules apply. It never answers "allow".
11
+ *
12
+ * Both decide from local data only, inside `HOOK_BUDGET_MS`, and neither ever
13
+ * sends the command line, its arguments, the output, the full working
14
+ * directory, or the environment. A failure of any kind is silent and fails
15
+ * open: the agent must never notice this hook going wrong.
10
16
  */
11
17
  import { value } from "./cliArgs.js";
12
18
  import { classifyCommand, summarize } from "./cliHookClassify.js";
19
+ import { decideGuard, guardOutput } from "./cliHookGuard.js";
13
20
  import { INTERPRETERS } from "./cliHookParse.js";
14
- import { resolveCliAuth } from "./cliSupport.js";
15
- /** Claude Code and Copilot fail open on a slow hook, so the budget is ours. */
21
+ import { hasExpired, holdAsk, takeAsk, takeExpired } from "./cliHookPending.js";
22
+ import { claimStaleRefresh, readCliPolicy, refreshCliPolicy } from "./cliPolicy.js";
23
+ import { readCreds } from "./credentials.js";
24
+ import { resolveCliAuth, selectStoredProfile } from "./cliSupport.js";
25
+ /** Claude Code, Codex, and Cursor fail open on a slow hook, so the budget is ours. */
16
26
  export const HOOK_BUDGET_MS = 1_500;
17
27
  const STDIN_MAX_BYTES = 1024 * 1024;
18
28
  const MAX_FINDINGS = 8;
19
29
  const MAX_OPAQUE_KINDS = 6;
20
30
  const CLI_ACTIVITY_PATH = "/api/my/cli-activity";
21
31
  export const HOOK_RUNTIMES = ["claude-code", "codex", "copilot", "cursor", "other"];
22
- const SHELL_TOOLS = new Set(["Bash", "bash", "shell"]);
32
+ const SHELL_TOOLS = new Set(["Bash", "bash", "shell", "Shell"]);
23
33
  const VERB_TOKEN = /^-{0,2}[A-Za-z0-9][A-Za-z0-9._:+-]{0,39}$/;
24
34
  const VENDOR_NAME = /^[a-z0-9._-]{1,40}$/;
25
35
  function text(candidate, max) {
@@ -69,10 +79,21 @@ export function opaqueKind(finding) {
69
79
  return "package-runner";
70
80
  return "unknown";
71
81
  }
72
- export function detectRuntime(input, env) {
73
- const declared = env.PASSPORT_HOOK_RUNTIME?.trim().toLowerCase();
74
- if (declared === "codex" || declared === "copilot" || declared === "cursor")
75
- return declared;
82
+ function isCursorEvent(input) {
83
+ return input.hook_event_name === "beforeShellExecution" || input.hook_event_name === "afterShellExecution";
84
+ }
85
+ /**
86
+ * Which agent sent this. An installed hook names its client with `--client`;
87
+ * Cursor is also recognised by its own event names and version field, which
88
+ * wins even over `--client claude-code` because Cursor imports Claude Code's
89
+ * hooks by default.
90
+ */
91
+ export function detectRuntime(input, env, declared) {
92
+ if (isCursorEvent(input) || typeof input.cursor_version === "string")
93
+ return "cursor";
94
+ const named = (declared ?? env.PASSPORT_HOOK_RUNTIME)?.trim().toLowerCase();
95
+ if (named && HOOK_RUNTIMES.includes(named) && named !== "other")
96
+ return named;
76
97
  const claudeCode = typeof input.hook_event_name === "string" &&
77
98
  typeof input.session_id === "string" &&
78
99
  typeof input.tool_use_id === "string";
@@ -95,45 +116,178 @@ export function outcomeOf(response) {
95
116
  ...(duration !== undefined && duration >= 0 ? { durationMs: duration } : {})
96
117
  };
97
118
  }
98
- export function buildReport(input, findings, env) {
99
- const summary = summarize(findings);
100
- if (!summary.governed.length && !summary.opaque)
101
- return null;
102
- const reportable = summary.governed
119
+ function outcomeOfInput(input) {
120
+ if (input.hook_event_name === "PostToolUseFailure") {
121
+ // The call failed or was interrupted: it ran, and it did not succeed.
122
+ const reported = outcomeOf(input.tool_response);
123
+ const exitCode = reported.exitCode ?? (input.is_interrupt === true ? 130 : 1);
124
+ return { ...reported, exitCode: exitCode === 0 ? 1 : exitCode };
125
+ }
126
+ if (!isCursorEvent(input))
127
+ return outcomeOf(input.tool_response);
128
+ const duration = integer(input.duration);
129
+ return duration !== undefined && duration >= 0 ? { durationMs: duration } : {};
130
+ }
131
+ function context(input, env, declared) {
132
+ const sessionId = text(input.session_id, 128) ?? text(input.conversation_id, 128);
133
+ const toolUseId = text(input.tool_use_id, 128);
134
+ const roots = Array.isArray(input.workspace_roots) ? input.workspace_roots : [];
135
+ const cwdName = directoryName(input.cwd) ?? directoryName(roots[0]);
136
+ return {
137
+ runtime: detectRuntime(input, env, declared),
138
+ ...(sessionId ? { sessionId } : {}),
139
+ ...(toolUseId ? { toolUseId } : {}),
140
+ ...(cwdName ? { cwdName } : {})
141
+ };
142
+ }
143
+ function reportable(findings) {
144
+ return findings
103
145
  .filter((finding) => Boolean(finding.vendor))
104
146
  .filter((finding) => VENDOR_NAME.test(finding.vendor))
105
147
  .slice(0, MAX_FINDINGS)
106
148
  .map((finding) => ({ vendor: finding.vendor, verb: safeVerb(finding.verb), risk: finding.risk }));
107
- if (!reportable.length && !summary.opaque)
149
+ }
150
+ export function buildReport(input, findings, env, declared) {
151
+ const summary = summarize(findings);
152
+ if (!summary.governed.length && !summary.opaque)
153
+ return null;
154
+ const governed = reportable(summary.governed);
155
+ if (!governed.length && !summary.opaque)
108
156
  return null;
109
157
  const kinds = [...new Set(summary.unknown.map(opaqueKind))].slice(0, MAX_OPAQUE_KINDS);
110
158
  return {
111
- runtime: detectRuntime(input, env),
112
- ...(text(input.session_id, 128) ? { sessionId: text(input.session_id, 128) } : {}),
113
- ...(text(input.tool_use_id, 128) ? { toolUseId: text(input.tool_use_id, 128) } : {}),
114
- ...(directoryName(input.cwd) ? { cwdName: directoryName(input.cwd) } : {}),
115
- ...outcomeOf(input.tool_response),
116
- findings: reportable,
159
+ ...context(input, env, declared),
160
+ ...outcomeOfInput(input),
161
+ findings: governed,
117
162
  opaque: summary.opaque,
118
163
  ...(summary.opaque && kinds.length ? { opaqueKinds: kinds } : {})
119
164
  };
120
165
  }
121
- async function readStdin(runtime) {
166
+ /** What the guard answered, and for which findings. The audit row that
167
+ * follows a command that ran carries its outcome and any opaque parts. */
168
+ export function buildDecisionReport(input, decision, env, declared) {
169
+ const findings = reportable(decision.findings);
170
+ if (!findings.length)
171
+ return null;
172
+ return { ...context(input, env, declared), findings, opaque: false, decision: decision.verdict };
173
+ }
174
+ /** A shell string as-is, or an argv array (`["bash", "-lc", "…"]`) re-quoted
175
+ * so the classifier reads the same words the shell will. */
176
+ function commandText(candidate) {
177
+ if (typeof candidate === "string")
178
+ return candidate;
179
+ if (!Array.isArray(candidate) || !candidate.length || candidate.length > 256)
180
+ return null;
181
+ if (!candidate.every((part) => typeof part === "string"))
182
+ return null;
183
+ return candidate
184
+ .map((part) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(part) ? part : `'${part.replaceAll("'", `'\\''`)}'`))
185
+ .join(" ");
186
+ }
187
+ /** Normalise one stdin event into the command and when it runs. */
188
+ export function shellEvent(input) {
189
+ if (isCursorEvent(input)) {
190
+ if (typeof input.command !== "string")
191
+ return null;
192
+ return {
193
+ phase: input.hook_event_name === "beforeShellExecution" ? "pre" : "post",
194
+ command: input.command,
195
+ cursorNative: true,
196
+ cursorImported: false
197
+ };
198
+ }
199
+ if (typeof input.tool_name !== "string" || !SHELL_TOOLS.has(input.tool_name))
200
+ return null;
201
+ const command = commandText(record(input.tool_input).command);
202
+ if (command === null)
203
+ return null;
204
+ const phase = input.hook_event_name === "PreToolUse"
205
+ ? "pre"
206
+ : input.hook_event_name === "PostToolUse" || input.hook_event_name === "PostToolUseFailure"
207
+ ? "post"
208
+ : null;
209
+ if (!phase)
210
+ return null;
211
+ return { phase, command, cursorNative: false, cursorImported: typeof input.cursor_version === "string" };
212
+ }
213
+ /** Read stdin within the budget. An agent that never closes it gets silence. */
214
+ async function readStdin(runtime, signal) {
122
215
  const source = runtime.stdin;
123
216
  if (!source)
124
217
  return "";
125
- const chunks = [];
126
- let bytes = 0;
127
- for await (const chunk of source) {
128
- const buffer = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
129
- bytes += buffer.byteLength;
130
- if (bytes > STDIN_MAX_BYTES)
131
- return "";
132
- chunks.push(buffer);
133
- }
134
- return Buffer.concat(chunks).toString("utf8");
135
- }
136
- /** Post one report with the same credential `passport discover` uses. Agent
218
+ const read = (async () => {
219
+ const chunks = [];
220
+ let bytes = 0;
221
+ for await (const chunk of source) {
222
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
223
+ bytes += buffer.byteLength;
224
+ if (bytes > STDIN_MAX_BYTES)
225
+ return "";
226
+ chunks.push(buffer);
227
+ }
228
+ return Buffer.concat(chunks).toString("utf8");
229
+ })();
230
+ if (signal.aborted)
231
+ return "";
232
+ let onAbort;
233
+ const aborted = new Promise((resolve) => {
234
+ onAbort = () => {
235
+ const destroy = source.destroy;
236
+ if (typeof destroy === "function")
237
+ destroy.call(source);
238
+ resolve("");
239
+ };
240
+ signal.addEventListener("abort", onAbort, { once: true });
241
+ });
242
+ try {
243
+ return await Promise.race([read, aborted]);
244
+ }
245
+ finally {
246
+ if (onAbort)
247
+ signal.removeEventListener("abort", onAbort);
248
+ }
249
+ }
250
+ async function readInput(runtime, signal) {
251
+ try {
252
+ const parsed = JSON.parse(await readStdin(runtime, signal));
253
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
254
+ }
255
+ catch {
256
+ return null;
257
+ }
258
+ }
259
+ /** The saved profile this shell would use, chosen without writing anything. */
260
+ function localProfile(args, env) {
261
+ try {
262
+ const creds = readCreds();
263
+ const selected = selectStoredProfile(args, env, creds, false).profile;
264
+ return selected && Object.hasOwn(creds, selected) ? selected : undefined;
265
+ }
266
+ catch {
267
+ return undefined;
268
+ }
269
+ }
270
+ /** One authenticated call surface for everything after the decision. The
271
+ * exchange never rotates the refresh token (see `postReport`). */
272
+ async function profileApi(profile, signal, fetcher) {
273
+ const saved = readCreds()[profile];
274
+ if (!saved)
275
+ return null;
276
+ const origin = new URL(saved.endpoint).origin;
277
+ const { TokenManager } = await import("./bridgeExchange.js");
278
+ const manager = new TokenManager(saved.endpoint, saved.refreshToken, undefined, undefined, HOOK_BUDGET_MS, signal, fetcher);
279
+ return (path, init) => manager.authedFetch(`${origin}${path}`, init);
280
+ }
281
+ async function postWith(api, report, signal) {
282
+ const response = await api(CLI_ACTIVITY_PATH, {
283
+ method: "POST",
284
+ headers: { "content-type": "application/json", "x-passport-surface": "cli" },
285
+ body: JSON.stringify(report),
286
+ signal
287
+ });
288
+ await response.body?.cancel().catch(() => undefined);
289
+ }
290
+ /** Deliver reports with the same credential `passport discover` uses. Agent
137
291
  * keys are deliberately unsupported: a hook reports a person's own shell.
138
292
  *
139
293
  * The exchange never rotates the refresh token. The hook runs once per shell
@@ -141,49 +295,134 @@ async function readStdin(runtime) {
141
295
  * lose the only copy of the new token, which later revokes the whole family.
142
296
  * With nothing to rotate there is nothing to serialize either, so the hook
143
297
  * never takes the profile lease or queues behind a serving bridge. */
144
- async function postReport(report, signal, args, env, fetcher) {
145
- const auth = resolveCliAuth(args, env);
298
+ async function reportSender(args, runtime, signal, deps) {
299
+ if (deps.send)
300
+ return (report) => deps.send(report, signal, runtime, args);
301
+ const auth = resolveCliAuth(args, runtime.env);
146
302
  if (auth.kind !== "profile")
147
- return;
148
- const { TokenManager } = await import("./bridge.js");
149
- const manager = new TokenManager(auth.endpoint, auth.refreshToken, undefined, undefined, HOOK_BUDGET_MS, signal, fetcher);
150
- const response = await manager.authedFetch(`${new URL(auth.endpoint).origin}${CLI_ACTIVITY_PATH}`, {
151
- method: "POST",
152
- headers: { "content-type": "application/json", "x-passport-surface": "cli" },
153
- body: JSON.stringify(report),
154
- signal
155
- });
156
- await response.body?.cancel().catch(() => undefined);
303
+ return null;
304
+ const { TokenManager } = await import("./bridgeExchange.js");
305
+ const manager = new TokenManager(auth.endpoint, auth.refreshToken, undefined, undefined, HOOK_BUDGET_MS, signal, deps.fetch ?? fetch);
306
+ const origin = new URL(auth.endpoint).origin;
307
+ return (report) => postWith((path, init) => manager.authedFetch(`${origin}${path}`, init), report, signal);
157
308
  }
158
- async function runHook(args, runtime, deps) {
159
- if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
160
- return;
161
- let input;
309
+ /** Parked asks nobody claimed in time: the prompt was declined, or nothing ran. */
310
+ function expiredAsks(now) {
311
+ if (!hasExpired(now))
312
+ return [];
313
+ return takeExpired(now).map((parked) => ({ ...parked.report, ran: false }));
314
+ }
315
+ /** Only hold an ask when the audit hook will be there to claim it. */
316
+ async function claudeAuditRegistered(runtime) {
162
317
  try {
163
- const parsed = JSON.parse(await readStdin(runtime));
164
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
165
- return;
166
- input = parsed;
318
+ const { registeredEntries } = await import("./cliHookInstall.js");
319
+ return registeredEntries("claude-code", runtime.env).audit !== null;
167
320
  }
168
321
  catch {
322
+ return false;
323
+ }
324
+ }
325
+ /** Cursor imports Claude Code's hooks by default. When Passport's own Cursor
326
+ * entry is registered too, the imported copy stays quiet so nothing is
327
+ * recorded twice. */
328
+ async function cursorHasOwnEntry(runtime, kind) {
329
+ try {
330
+ const { registeredEntries } = await import("./cliHookInstall.js");
331
+ return registeredEntries("cursor", runtime.env)[kind] !== null;
332
+ }
333
+ catch {
334
+ return false;
335
+ }
336
+ }
337
+ function budgetSignal(runtime) {
338
+ return AbortSignal.any([runtime.signal, AbortSignal.timeout(HOOK_BUDGET_MS)]);
339
+ }
340
+ async function runAudit(args, runtime, deps) {
341
+ if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
342
+ return;
343
+ const budget = budgetSignal(runtime);
344
+ const input = await readInput(runtime, budget);
345
+ if (!input)
346
+ return;
347
+ const event = shellEvent(input);
348
+ // A PreToolUse event gets no opinion from the audit hook: that is the guard's job.
349
+ if (!event || event.phase !== "post")
169
350
  return;
351
+ if (event.cursorImported && (await cursorHasOwnEntry(runtime, "audit")))
352
+ return;
353
+ let report = buildReport(input, classifyCommand(event.command), runtime.env, value(args, "client"));
354
+ // The guard asked before this exact command and parked its report: send one
355
+ // row for both, "asked first, then ran".
356
+ const toolUseId = text(input.tool_use_id, 128);
357
+ if (report && toolUseId && !event.cursorImported && takeAsk(report.runtime, report.sessionId, toolUseId)) {
358
+ report = { ...report, decision: "ask", ran: true };
170
359
  }
171
- if (typeof input.tool_name !== "string" || !SHELL_TOOLS.has(input.tool_name))
360
+ const now = (deps.now ?? Date.now)();
361
+ if (!report && !hasExpired(now))
362
+ return;
363
+ const send = await reportSender(args, runtime, budget, deps);
364
+ // Claim expired asks only once there is a way to send them.
365
+ if (!send)
366
+ return;
367
+ const reports = [...(report ? [report] : []), ...expiredAsks(now)];
368
+ await Promise.allSettled(reports.map((entry) => send(entry)));
369
+ }
370
+ function outputClient(event, runtime) {
371
+ if (event.cursorNative)
372
+ return "cursor";
373
+ // Cursor accepts Claude Code's response shape for the hooks it imports.
374
+ if (event.cursorImported)
375
+ return "claude-code";
376
+ return runtime === "codex" ? "codex" : "claude-code";
377
+ }
378
+ async function runGuard(args, runtime, deps) {
379
+ if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
172
380
  return;
173
- const command = record(input.tool_input).command;
174
- if (typeof command !== "string")
381
+ const budget = budgetSignal(runtime);
382
+ const input = await readInput(runtime, budget);
383
+ if (!input || budget.aborted)
175
384
  return;
176
- // PreToolUse gets no opinion at all: silence is the normal permission flow.
177
- if (input.hook_event_name !== "PostToolUse")
385
+ const event = shellEvent(input);
386
+ if (!event || event.phase !== "pre")
178
387
  return;
179
- const report = buildReport(input, classifyCommand(command), runtime.env);
180
- if (!report)
388
+ // Decide from local data only, and answer before anything touches the network.
389
+ const profile = localProfile(args, runtime.env);
390
+ const policy = profile ? readCliPolicy(profile) : null;
391
+ const decision = decideGuard(classifyCommand(event.command), policy);
392
+ const declared = value(args, "client");
393
+ const output = decision
394
+ ? guardOutput(outputClient(event, detectRuntime(input, runtime.env, declared)), decision)
395
+ : null;
396
+ if (output)
397
+ runtime.stdout.write(`${JSON.stringify(output)}\n`);
398
+ // Leftover budget: one Activity report and, at most hourly, a policy refresh.
399
+ // Cursor does not enforce "ask" on hooks it imports, so an imported copy
400
+ // records nothing; Passport's own Cursor entry does.
401
+ if (!profile || runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT)
181
402
  return;
182
- const budget = AbortSignal.any([runtime.signal, AbortSignal.timeout(HOOK_BUDGET_MS)]);
183
- if (deps.send)
184
- await deps.send(report, budget, runtime, args);
185
- else
186
- await postReport(report, budget, args, runtime.env, deps.fetch ?? fetch);
403
+ const now = (deps.now ?? Date.now)();
404
+ const report = decision && output && !event.cursorImported ? buildDecisionReport(input, decision, runtime.env, declared) : null;
405
+ // Claude Code gives the same tool-use id before and after a command, so an
406
+ // ask is parked until the audit hook says it ran, and sent as one row.
407
+ const held = report?.decision === "ask" &&
408
+ report.runtime === "claude-code" &&
409
+ report.toolUseId !== undefined &&
410
+ (await claudeAuditRegistered(runtime)) &&
411
+ holdAsk(report.runtime, report.sessionId, report.toolUseId, report, now);
412
+ const reports = [...(report && !held ? [report] : []), ...expiredAsks(now)];
413
+ const refresh = claimStaleRefresh(profile, policy, now);
414
+ if (!reports.length && !refresh)
415
+ return;
416
+ const api = await profileApi(profile, budget, deps.fetch ?? fetch);
417
+ if (!api)
418
+ return;
419
+ const send = deps.send
420
+ ? (entry) => deps.send(entry, budget, runtime, args)
421
+ : (entry) => postWith(api, entry, budget);
422
+ await Promise.allSettled([
423
+ ...reports.map((entry) => send(entry)),
424
+ refresh ? refreshCliPolicy(profile, budget, { api, ...(deps.now ? { now: deps.now } : {}) }) : undefined
425
+ ]);
187
426
  }
188
427
  export async function hook(args, runtime, deps = {}) {
189
428
  const action = args.positionals[0];
@@ -191,15 +430,18 @@ export async function hook(args, runtime, deps = {}) {
191
430
  const { hookRegistration } = await import("./cliHookInstall.js");
192
431
  return hookRegistration(action, value(args, "client"), args, runtime);
193
432
  }
194
- if (action !== undefined) {
433
+ if (action !== undefined && action !== "guard") {
195
434
  const { failure } = await import("./cliSupport.js");
196
- return failure("Use passport hook, hook install, hook uninstall, or hook status.", 6, "usage");
435
+ return failure("Use passport hook, hook guard, hook install, hook uninstall, or hook status.", 6, "usage");
197
436
  }
198
437
  try {
199
- await runHook(args, runtime, deps);
438
+ if (action === "guard")
439
+ await runGuard(args, runtime, deps);
440
+ else
441
+ await runAudit(args, runtime, deps);
200
442
  }
201
443
  catch {
202
- /* Audit is best effort. The agent must never notice this hook failing. */
444
+ /* Best effort. The agent must never notice this hook failing. */
203
445
  }
204
446
  return { json: { ok: true }, silent: true };
205
447
  }
@@ -18,6 +18,12 @@ export type CliFinding = {
18
18
  via: string[];
19
19
  note?: string;
20
20
  envInjected?: string[];
21
+ /** The exact vendor-map verb when it is more specific than `verb`, such as
22
+ * `push --force` for a destructive git push. Local only; never reported. */
23
+ verbKey?: string;
24
+ /** `--help` or `--dry-run`: the invocation describes the action instead of
25
+ * taking it, so the guard has no opinion. Local only; never reported. */
26
+ inert?: true;
21
27
  };
22
28
  export type CliSummary = {
23
29
  governed: CliFinding[];
@@ -190,7 +190,27 @@ function longestVerbMatch(spec, positional, args) {
190
190
  }
191
191
  return null;
192
192
  }
193
+ /** Flags that make any vendor verb describe itself instead of acting. */
194
+ function isInert(flags) {
195
+ return flags.some((flag) => flag === "--help" || flag === "--dry-run" || flag.startsWith("--dry-run="));
196
+ }
197
+ /** Which destructive push this is, as the vendor map spells it. */
198
+ function pushKey(flags, positional) {
199
+ if (flags.includes("--mirror"))
200
+ return "push --mirror";
201
+ if (flags.includes("--delete") || flags.includes("-d") || positional.some((word) => word.startsWith(":"))) {
202
+ return "push --delete";
203
+ }
204
+ if (flags.some((flag) => flag === "-f" || flag === "--force" || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(flag))) {
205
+ return "push --force";
206
+ }
207
+ return undefined;
208
+ }
193
209
  function classifyVendor(vendor, args, via, envInjected) {
210
+ const found = classifyVendorVerb(vendor, args, via, envInjected);
211
+ return isInert(args.filter((arg) => arg.startsWith("-"))) ? { ...found, inert: true } : found;
212
+ }
213
+ function classifyVendorVerb(vendor, args, via, envInjected) {
194
214
  const spec = VENDORS[vendor];
195
215
  const positional = args.filter((arg) => !arg.startsWith("-"));
196
216
  const flags = args.filter((arg) => arg.startsWith("-"));
@@ -200,7 +220,9 @@ function classifyVendor(vendor, args, via, envInjected) {
200
220
  const gitRisk = classifyGit(spec, positional, flags);
201
221
  if (gitRisk) {
202
222
  const verb = positional[0] === "push" ? "push" : positional[0] || null;
203
- return finding(vendor, verb, gitRisk, via, "high", envInjected);
223
+ const found = finding(vendor, verb, gitRisk, via, "high", envInjected);
224
+ const key = gitRisk === "destructive" ? pushKey(flags, positional) : undefined;
225
+ return key ? { ...found, verbKey: key } : found;
204
226
  }
205
227
  }
206
228
  const resourceRisk = riskOf(spec.resourceVerbRisk, positional[1] ?? "");
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The guard's decision and the one line each agent shows for it.
3
+ *
4
+ * Passport can only add friction here, never remove it: the guard answers
5
+ * "ask" or "deny", or says nothing at all so the agent's own permission rules
6
+ * apply. It never answers "allow", whatever the policy says, because an allow
7
+ * from a hook skips the agent's prompt, and a guard that misreads a command must
8
+ * never be the reason something ran unasked.
9
+ */
10
+ import type { CliFinding } from "./cliHookClassify.js";
11
+ import type { CachedCliPolicy } from "./cliPolicy.js";
12
+ export type GuardVerdict = "ask" | "deny";
13
+ export type GuardClient = "claude-code" | "codex" | "cursor";
14
+ export type GuardDecision = {
15
+ verdict: GuardVerdict;
16
+ /** The finding that set the verdict, e.g. `railway volume delete`. */
17
+ label: string;
18
+ /** Every finding that carried a verdict of its own, strictest first. */
19
+ findings: CliFinding[];
20
+ /** Whether the deciding finding is destructive by Passport's own map. */
21
+ destructive: boolean;
22
+ };
23
+ /** The words a person needs to recognise the command, never its arguments. */
24
+ export declare function guardLabel(finding: CliFinding): string;
25
+ /** The strictest verdict across every command in the line wins. */
26
+ export declare function decideGuard(findings: CliFinding[], policy: CachedCliPolicy | null): GuardDecision | null;
27
+ export declare function askMessage(decision: GuardDecision): string;
28
+ export declare function denyMessage(decision: GuardDecision): string;
29
+ export declare const DENY_AGENT_MESSAGE = "Blocked by Passport safety settings. Ask the user to run this command themselves.";
30
+ /**
31
+ * The exact stdout each agent reads, or null for nothing at all.
32
+ *
33
+ * - Claude Code shows an ask reason in its permission prompt; a deny reason
34
+ * goes to the model, so the person gets the deny line as a system message.
35
+ * - Codex parses "ask" but does not support it yet, so the guard stays silent
36
+ * and Codex's own approval policy applies. Deny is supported.
37
+ * - Cursor's beforeShellExecution takes a flat, snake_case response.
38
+ */
39
+ export declare function guardOutput(client: GuardClient, decision: GuardDecision): Record<string, unknown> | null;