passport-bridge 0.46.0 → 0.47.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 (59) hide show
  1. package/dist/cliGitCredential.d.ts +2 -0
  2. package/dist/cliGitCredential.js +15 -7
  3. package/dist/cliGuardHealth.d.ts +5 -0
  4. package/dist/cliGuardHealth.js +6 -1
  5. package/dist/cliHook.d.ts +3 -13
  6. package/dist/cliHook.js +68 -43
  7. package/dist/cliHookClients.d.ts +3 -0
  8. package/dist/cliHookClients.js +4 -0
  9. package/dist/cliHookDecide.d.ts +11 -3
  10. package/dist/cliHookDecide.js +100 -9
  11. package/dist/cliHookDeliver.js +5 -2
  12. package/dist/cliHookInput.d.ts +2 -0
  13. package/dist/cliHookInput.js +10 -0
  14. package/dist/cliHookInstall.d.ts +6 -1
  15. package/dist/cliHookInstall.js +36 -9
  16. package/dist/cliHookStatus.d.ts +13 -0
  17. package/dist/cliHookStatus.js +54 -5
  18. package/dist/cliSetupLock.d.ts +1 -1
  19. package/dist/cliSetupLock.js +4 -3
  20. package/dist/cliSigningKeys.d.ts +10 -0
  21. package/dist/cliSigningKeys.js +10 -0
  22. package/dist/cliStatus.d.ts +5 -0
  23. package/dist/cliStatus.js +15 -5
  24. package/dist/controlPlane.generated.d.ts +12 -27
  25. package/dist/controlPlane.generated.js +11 -2
  26. package/dist/controlPlaneCli.js +5 -2
  27. package/dist/controlPlaneGuard.js +9 -5
  28. package/dist/controlPlaneModel.generated.js +3 -0
  29. package/dist/controlPlaneOffline.d.ts +67 -0
  30. package/dist/controlPlaneOffline.js +213 -0
  31. package/dist/controlPlanePeople.generated.d.ts +9 -0
  32. package/dist/controlPlaneRailwayGuard.d.ts +7 -0
  33. package/dist/controlPlaneRailwayGuard.js +15 -2
  34. package/dist/controlPlaneRoutes.generated.d.ts +63 -0
  35. package/dist/controlPlaneRoutes.generated.js +111 -0
  36. package/dist/controlPlaneSupabase.d.ts +7 -0
  37. package/dist/controlPlaneSupabase.js +16 -3
  38. package/dist/cpCli.d.ts +20 -0
  39. package/dist/cpCli.js +102 -1
  40. package/dist/cpRefusal.d.ts +8 -0
  41. package/dist/cpRefusal.js +13 -0
  42. package/dist/gitCredentialRetire.d.ts +25 -0
  43. package/dist/gitCredentialRetire.js +143 -0
  44. package/dist/hookAdapters.d.ts +44 -0
  45. package/dist/hookAdapters.js +106 -0
  46. package/dist/lockedHooks.d.ts +13 -11
  47. package/dist/lockedHooks.js +19 -16
  48. package/dist/managedHooks.d.ts +2 -0
  49. package/dist/managedHooks.js +24 -3
  50. package/dist/pluginPin.d.ts +1 -1
  51. package/dist/pluginPin.js +1 -1
  52. package/dist/testHookEnv.d.ts +2 -0
  53. package/dist/testHookEnv.js +26 -0
  54. package/dist/testSigning.d.ts +5 -0
  55. package/dist/testSigning.js +19 -0
  56. package/dist/version.d.ts +1 -1
  57. package/dist/version.js +1 -1
  58. package/npm-shrinkwrap.json +2 -2
  59. package/package.json +1 -1
@@ -20,6 +20,8 @@ export type GitCredentialDependencies = CredentialsSwitch & {
20
20
  fallback?: (helper: string, operation: string, input: string, env: Runtime["env"]) => Promise<string>;
21
21
  run?: RunGit;
22
22
  command?: readonly string[];
23
+ /** The person's own helpers' answer once Passport's entry is gone (tests). */
24
+ fillFromOwnHelpers?: (input: string, env: Runtime["env"]) => Promise<string>;
23
25
  /** What a helper line answers (tests); the default runs it as git would. */
24
26
  probe?: (line: string, env: Runtime["env"]) => string | null;
25
27
  mintTimeoutMs?: number;
@@ -48,6 +48,7 @@ import { beginShadowLine, shadowAfterDecision, shadowAlongside, shadowGithubLine
48
48
  import { takePushDecisions } from "./gitPushDecisions.js";
49
49
  import { helperLine, helperProgram, installGitCredential, probeHelper, readGitCredentialState, removeGitCredential } from "./gitCredentialSetup.js";
50
50
  import { GIT_OFF, issuesCredentials, offResult } from "./offInV1.js";
51
+ import { fillFromOwnHelpers, retireGitCredential } from "./gitCredentialRetire.js";
51
52
  export const GIT_CREDENTIAL_PATH = "/api/my/github/git-credential";
52
53
  export const TOKEN_USERNAME = "x-access-token";
53
54
  const REPO_PATH = /^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100}?)(?:\.git)?\/?$/;
@@ -119,8 +120,7 @@ const runFallback = (helper, operation, input, env) => new Promise((resolve) =>
119
120
  });
120
121
  /** Ask the helpers git used before setup, in order, as git would; the first that answers wins. `quit`: whether
121
122
  * a helper's quit stops there (in v1 it doesn't: the next helper is asked). */
122
- async function delegate(operation, input, runtime, deps, quit = true) {
123
- const helpers = readGitCredentialState()?.fallback ?? [];
123
+ async function delegate(operation, input, runtime, deps, quit = true, helpers = readGitCredentialState()?.fallback ?? []) {
124
124
  const run = deps.fallback ?? runFallback;
125
125
  // The path is there for Passport (useHttpPath); the earlier helpers stored their
126
126
  // passwords per host, so they get the request as git sent it before setup.
@@ -476,15 +476,23 @@ export async function gitCredential(args, runtime, deps = {}) {
476
476
  const input = await readInput(runtime);
477
477
  let out = "";
478
478
  try {
479
- // Off in v1: no token from Passport. The helpers git used before setup answer, else nothing, so git
480
- // asks the next helper or the person. Never quit=1: Passport doesn't stop git here.
481
- if (operation === "get" && !on)
482
- out = withoutQuit(await delegate("get", input, runtime, deps, false));
479
+ // Off in v1: no token from Passport, and this helper is retired: it takes its own entries out of the
480
+ // global config, then the helpers git used before setup answer, else the person's own helpers, so git
481
+ // is never left with an empty answer. Never quit=1: Passport doesn't stop git here.
482
+ // The recorded helpers are read before the retire step deletes the record.
483
+ const recorded = on ? null : readGitCredentialState();
484
+ if (!on)
485
+ retireGitCredential(runtime, recorded, deps.run);
486
+ if (operation === "get" && !on) {
487
+ out = withoutQuit(await delegate("get", input, runtime, deps, false, recorded?.fallback ?? []));
488
+ if (!/^password=/m.test(out))
489
+ out = await (deps.fillFromOwnHelpers ?? fillFromOwnHelpers)(input, runtime.env);
490
+ }
483
491
  else if (operation === "get")
484
492
  out = await get(args, runtime, deps, input);
485
493
  // A token Passport issued is never stored: git would offer an expired one next time.
486
494
  else if (parseCredentialRequest(input).get("username") !== TOKEN_USERNAME) {
487
- out = await delegate(operation, input, runtime, deps);
495
+ out = await delegate(operation, input, runtime, deps, true, recorded?.fallback);
488
496
  }
489
497
  }
490
498
  catch (error) {
@@ -12,6 +12,7 @@ import { type CodexTrust } from "./cliCodexTrust.js";
12
12
  import type { Env } from "./cliSupport.js";
13
13
  export declare const GUARD_CLIENTS: readonly ["claude-code", "codex", "cursor"];
14
14
  export type GuardClient = (typeof GUARD_CLIENTS)[number];
15
+ export declare const isGuardClient: (value: unknown) => value is GuardClient;
15
16
  export declare const GUARD_CLIENT_LABEL: Readonly<Record<GuardClient, string>>;
16
17
  export type { CodexTrust };
17
18
  export type GuardMode = "audit+guard" | "audit" | "guard" | "plugin" | "none" | "unreadable";
@@ -23,10 +24,14 @@ export type GuardClientReport = {
23
24
  plugin: boolean;
24
25
  codexTrust?: CodexTrust;
25
26
  locked?: boolean;
27
+ /** The guard that runs fails closed (the agent refuses the command when the hook can't run). Codex can't. */
28
+ failClosed?: boolean;
26
29
  disabledEnv?: boolean;
27
30
  /** Hook events Passport's entry should be on but isn't. */
28
31
  missing?: string[];
29
32
  };
33
+ /** Agents with a setting that makes a hook fail closed (Claude Code `onFailure`, Cursor `failClosed`). */
34
+ export declare const CAN_FAIL_CLOSED: ReadonlySet<GuardClient>;
30
35
  export type GuardHealthReport = {
31
36
  cliVersion: string;
32
37
  launcherTarget?: string;
@@ -12,17 +12,20 @@ import { closeSync, constants, mkdirSync, openSync, readFileSync, statSync, utim
12
12
  import { join } from "node:path";
13
13
  import { readBoundedJson } from "./boundedResponse.js";
14
14
  import { codexGuardTrust } from "./cliCodexTrust.js";
15
- import { managedPassportHook } from "./managedHooks.js";
15
+ import { managedFailClosed, managedPassportHook } from "./managedHooks.js";
16
16
  import { credentialDir, ensurePrivateDirectory } from "./credentialStorage.js";
17
17
  import { assertProfileName } from "./credentials.js";
18
18
  import { VERSION } from "./version.js";
19
19
  /* ---- Guard states and their fixes, in the web's words: On · Off · Outdated · Not trusted · Locked ---- */
20
20
  export const GUARD_CLIENTS = ["claude-code", "codex", "cursor"];
21
+ export const isGuardClient = (value) => typeof value === "string" && GUARD_CLIENTS.includes(value);
21
22
  export const GUARD_CLIENT_LABEL = {
22
23
  "claude-code": "Claude Code",
23
24
  codex: "Codex",
24
25
  cursor: "Cursor"
25
26
  };
27
+ /** Agents with a setting that makes a hook fail closed (Claude Code `onFailure`, Cursor `failClosed`). */
28
+ export const CAN_FAIL_CLOSED = new Set(["claude-code", "cursor"]);
26
29
  export const GUARD_STATE_LABEL = {
27
30
  on: "On",
28
31
  locked: "Locked",
@@ -146,6 +149,7 @@ export async function guardClientReports(env) {
146
149
  return GUARD_CLIENTS.map((client) => {
147
150
  const status = agentHookStatus(client, env);
148
151
  const locked = managedGuard(client, env);
152
+ const failClosed = locked ? managedFailClosed(client, env) === true : status.failClosed === true;
149
153
  const codexTrust = client === "codex" && status.guardCommand && !status.plugin
150
154
  ? codexGuardTrust(codexHooksPath(env), isPassportGuardCommand)
151
155
  : undefined;
@@ -157,6 +161,7 @@ export async function guardClientReports(env) {
157
161
  plugin: status.plugin,
158
162
  ...(codexTrust ? { codexTrust } : {}),
159
163
  ...(locked ? { locked: true } : {}),
164
+ ...(failClosed ? { failClosed: true } : {}),
160
165
  ...(env.PASSPORT_HOOK_DISABLED === "1" ? { disabledEnv: true } : {}),
161
166
  // Slots an older install never got: the agent reads as Partly set up.
162
167
  ...(status.missing.length && !locked ? { missing: status.missing } : {})
package/dist/cliHook.d.ts CHANGED
@@ -12,27 +12,19 @@
12
12
  *
13
13
  * Both work inside `HOOK_BUDGET_MS`, and neither ever sends the command line,
14
14
  * its arguments, the output, the full working directory, or the environment.
15
- * A failure of any kind is silent and fails open: the agent must never notice
16
- * this hook going wrong.
15
+ * The guard refuses a payload it can't read (exit 2, `hookAdapters.ts`); any
16
+ * other failure is silent: the agent must never notice this hook going wrong.
17
17
  */
18
18
  import { type ParsedArgs } from "./cliArgs.js";
19
19
  import { type CliFinding } from "./cliHookClassify.js";
20
20
  import { type GuardClient } from "./cliHookGuard.js";
21
21
  import { type HookInput } from "./cliHookInput.js";
22
+ export { shellEvent } from "./hookAdapters.js";
22
23
  import { type ApiCall, type CliHookReport, type HookDependencies, type HookRuntime } from "./cliHookDeliver.js";
23
24
  export { HOOK_BUDGET_MS, HOOK_RUNTIMES, type CliHookReport, type HookDependencies, type HookRuntime, type ReportedFinding } from "./cliHookDeliver.js";
24
25
  export { outcomeOf } from "./cliHookOutcome.js";
25
26
  import type { CommandResult, Env, Runtime } from "./cliSupport.js";
26
27
  export type { HookInput };
27
- /** One shell command, whichever agent format it arrived in. */
28
- type ShellEvent = {
29
- phase: "pre" | "post";
30
- command: string;
31
- /** Cursor's own beforeShellExecution / afterShellExecution. */
32
- cursorNative: boolean;
33
- /** Cursor running a hook it imported from Claude Code settings. */
34
- cursorImported: boolean;
35
- };
36
28
  /** Keep the shape of the verb, never its arguments: anything that could carry a
37
29
  * path, an endpoint, or a value is dropped rather than truncated. */
38
30
  export declare function safeVerb(raw: string | null): string;
@@ -45,8 +37,6 @@ export declare function safeVerb(raw: string | null): string;
45
37
  export declare function detectRuntime(input: HookInput, env: Env, declared?: string): HookRuntime;
46
38
  /** One row for a line that ran vendor commands; null for any other line. */
47
39
  export declare function buildReport(input: HookInput, findings: CliFinding[], env: Env, declared?: string): CliHookReport | null;
48
- /** Normalise one stdin event into the command and when it runs. */
49
- export declare function shellEvent(input: HookInput): ShellEvent | null;
50
40
  /** `passport exec` records its own action, with its decision and credential. */
51
41
  export declare function isPassportExec(command: string): boolean;
52
42
  /** Calls that name the agent (`x-passport-caller`): its kind only. */
package/dist/cliHook.js CHANGED
@@ -12,8 +12,8 @@
12
12
  *
13
13
  * Both work inside `HOOK_BUDGET_MS`, and neither ever sends the command line,
14
14
  * its arguments, the output, the full working directory, or the environment.
15
- * A failure of any kind is silent and fails open: the agent must never notice
16
- * this hook going wrong.
15
+ * The guard refuses a payload it can't read (exit 2, `hookAdapters.ts`); any
16
+ * other failure is silent: the agent must never notice this hook going wrong.
17
17
  */
18
18
  import { value } from "./cliArgs.js";
19
19
  import { summarize, unknownVerb, UNRECOGNIZED_VERB } from "./cliHookClassify.js";
@@ -23,15 +23,17 @@ import { localRefusal, planGuard } from "./cliHookDecide.js";
23
23
  import { denyOutput } from "./cliHookGuard.js";
24
24
  import { localIrreversibleVerbs } from "./localIrreversible.js";
25
25
  import { permissionModeOf } from "./cliHookMode.js";
26
- import { commandText, readInput, record, subagentOf } from "./cliHookInput.js";
26
+ import { readInput, readRaw, record, subagentOf } from "./cliHookInput.js";
27
+ import { parsePayload, shellEvent, unreadableMessage } from "./hookAdapters.js";
28
+ export { shellEvent } from "./hookAdapters.js";
27
29
  import { budgetSignal, HOOK_BUDGET_MS, HOOK_RUNTIMES, leftovers, localProfile, localSelection, agentKeyApi, profileApi, queueAfterCommand, reportSender, runFlush, startFlushIfDue } from "./cliHookDeliver.js";
28
30
  export { HOOK_BUDGET_MS, HOOK_RUNTIMES } from "./cliHookDeliver.js";
29
31
  import { readCpCli } from "./cpCli.js";
30
32
  import { standDownForManaged } from "./managedHooks.js";
31
33
  import { isCursorEvent, outcomeOfInput } from "./cliHookOutcome.js";
34
+ import { isGuardClient } from "./cliGuardHealth.js";
32
35
  export { outcomeOf } from "./cliHookOutcome.js";
33
36
  const MAX_FINDINGS = 8;
34
- const SHELL_TOOLS = new Set(["Bash", "bash", "shell", "Shell"]);
35
37
  const VERB_TOKEN = /^-{0,2}[A-Za-z0-9][A-Za-z0-9._:+-]{0,39}$/;
36
38
  const VENDOR_NAME = /^[a-z0-9._-]{1,40}$/;
37
39
  function text(candidate, max) {
@@ -122,32 +124,6 @@ export function buildReport(input, findings, env, declared) {
122
124
  opaque: summary.opaque
123
125
  };
124
126
  }
125
- /** Normalise one stdin event into the command and when it runs. */
126
- export function shellEvent(input) {
127
- if (isCursorEvent(input)) {
128
- if (typeof input.command !== "string")
129
- return null;
130
- return {
131
- phase: input.hook_event_name === "beforeShellExecution" ? "pre" : "post",
132
- command: input.command,
133
- cursorNative: true,
134
- cursorImported: false
135
- };
136
- }
137
- if (typeof input.tool_name !== "string" || !SHELL_TOOLS.has(input.tool_name))
138
- return null;
139
- const command = commandText(record(input.tool_input).command);
140
- if (command === null)
141
- return null;
142
- const phase = input.hook_event_name === "PreToolUse"
143
- ? "pre"
144
- : input.hook_event_name === "PostToolUse" || input.hook_event_name === "PostToolUseFailure"
145
- ? "post"
146
- : null;
147
- if (!phase)
148
- return null;
149
- return { phase, command, cursorNative: false, cursorImported: typeof input.cursor_version === "string" };
150
- }
151
127
  /** Cursor imports Claude Code's hooks by default. When Passport's own Cursor
152
128
  * entry is registered too, the imported copy stays quiet so nothing is
153
129
  * recorded twice. */
@@ -202,8 +178,12 @@ async function runAudit(args, runtime, deps) {
202
178
  const profile = localProfile(args, runtime.env);
203
179
  const now = (deps.now ?? Date.now)();
204
180
  // It ran: a decision the guard couldn't wait for may still have been recorded as a block (controlPlaneLateHold).
205
- if (profile)
206
- await (await import("./controlPlaneLateHold.js")).releaseLate(profile, sessionOfInput(input), text(input.tool_use_id, 128), now);
181
+ if (profile) {
182
+ const [sessionId, toolUseId] = [sessionOfInput(input), text(input.tool_use_id, 128)];
183
+ await (await import("./controlPlaneLateHold.js")).releaseLate(profile, sessionId, toolUseId, now);
184
+ // Ran while Passport couldn't be reached and no rules were known: Passport is told what it was.
185
+ await (await import("./controlPlaneOffline.js")).releaseOffline(profile, sessionId, toolUseId, now);
186
+ }
207
187
  const declared = value(args, "client");
208
188
  const runtimeName = detectRuntime(input, runtime.env, declared);
209
189
  const after = await import("./cliHookAfter.js");
@@ -242,21 +222,32 @@ function outputClient(event, runtime) {
242
222
  }
243
223
  /** Leave room after the server call to print and exit inside the budget. */
244
224
  const PRINT_RESERVE_MS = 200;
225
+ /** The guard refuses a payload it can't read (any of the three agents reads exit 2 as deny), unless managed
226
+ * settings run the guard for this agent too: that copy decides. */
227
+ function refuseUnreadable(args, runtime) {
228
+ const declared = (value(args, "client") ?? runtime.env.PASSPORT_HOOK_RUNTIME)?.trim().toLowerCase();
229
+ const client = isGuardClient(declared) ? declared : undefined;
230
+ if (client && standDownForManaged(client, runtime.env))
231
+ return undefined;
232
+ runtime.stderr.write(`${unreadableMessage(client)}\n`);
233
+ return 2;
234
+ }
245
235
  async function runGuard(args, runtime, deps) {
246
236
  if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
247
- return;
237
+ return undefined;
248
238
  const clock = deps.now ?? Date.now;
249
239
  const startedAt = clock();
250
240
  const budget = budgetSignal(runtime, deps);
251
- const input = await readInput(runtime, budget);
252
- if (!input)
253
- return;
241
+ const parsed = parsePayload(await readRaw(runtime, budget));
242
+ if (!parsed.ok)
243
+ return refuseUnreadable(args, runtime);
244
+ const input = parsed.input;
254
245
  const event = hookEvent(input, "pre", args, runtime);
255
246
  if (!event)
256
- return;
247
+ return undefined;
257
248
  // Cursor runs the hook it imported from Claude Code too: with Passport's own Cursor entry there, that one decides.
258
249
  if (event.cursorImported && (await cursorHasOwnEntry(runtime, "guard")))
259
- return;
250
+ return undefined;
260
251
  const machine = localMachine(workingFolder(input), runtime.env);
261
252
  const line = classifyLine(event.command, machine);
262
253
  const declared = value(args, "client");
@@ -269,8 +260,35 @@ async function runGuard(args, runtime, deps) {
269
260
  if (local[0])
270
261
  runtime.stdout.write(`${JSON.stringify(denyOutput(client, localRefusal(local[0], "unreachable")))}\n`);
271
262
  };
272
- if (budget.aborted)
273
- return refuseLocal();
263
+ // Passport never asked (out of time, or a failure before the answer): what a cached Block rule covers is refused.
264
+ const unasked = async () => {
265
+ const { profile } = localSelection(args, runtime.env);
266
+ const cp = profile ? readCpCli(profile) : null;
267
+ const offline = await (await import("./cliHookDecide.js")).planUnreachable({
268
+ client,
269
+ canAsk: Boolean(profile),
270
+ cp,
271
+ ...(profile ? { profile } : {}),
272
+ openApi: async () => null,
273
+ report: context(input, runtime.env, declared),
274
+ command: event.command,
275
+ findings: line.findings,
276
+ cwd: machine.cwd,
277
+ env: runtime.env,
278
+ budget,
279
+ deadline: 0,
280
+ now: clock
281
+ });
282
+ if (offline)
283
+ runtime.stdout.write(`${JSON.stringify(offline)}\n`);
284
+ };
285
+ if (budget.aborted) {
286
+ if (local[0])
287
+ return void refuseLocal();
288
+ await unasked().catch(() => undefined);
289
+ return undefined;
290
+ }
291
+ let answered = false;
274
292
  try {
275
293
  await guardLine({
276
294
  args,
@@ -287,10 +305,15 @@ async function runGuard(args, runtime, deps) {
287
305
  budget,
288
306
  startedAt
289
307
  });
308
+ answered = true;
290
309
  }
291
310
  catch {
292
- refuseLocal();
311
+ if (local[0])
312
+ refuseLocal();
313
+ else if (!answered)
314
+ await unasked().catch(() => undefined);
293
315
  }
316
+ return undefined;
294
317
  }
295
318
  /** Calls that name the agent (`x-passport-caller`): its kind only. */
296
319
  export function asCaller(api, client) {
@@ -332,6 +355,7 @@ async function guardLine(at) {
332
355
  client,
333
356
  canAsk: canReport || agentApi !== null,
334
357
  cp,
358
+ ...(profile ? { profile } : {}),
335
359
  openApi,
336
360
  report: context(input, runtime.env, declared),
337
361
  command: event.command,
@@ -388,9 +412,10 @@ export async function hook(args, runtime, deps = {}) {
388
412
  const unknown = unknownSubcommand("hook", action, ["install", "uninstall", "status"]);
389
413
  return failure(unknown.message, 6, "usage", unknown.next ? { next: unknown.next } : {});
390
414
  }
415
+ let exitCode;
391
416
  try {
392
417
  if (action === "guard")
393
- await runGuard(args, runtime, deps);
418
+ exitCode = await runGuard(args, runtime, deps);
394
419
  else if (action === "flush")
395
420
  await runFlush(args, runtime, deps);
396
421
  else
@@ -399,5 +424,5 @@ export async function hook(args, runtime, deps = {}) {
399
424
  catch {
400
425
  /* Best effort. The agent must never notice this hook failing. */
401
426
  }
402
- return { json: { ok: true }, silent: true };
427
+ return { json: { ok: true }, silent: true, ...(exitCode ? { exitCode } : {}) };
403
428
  }
@@ -17,6 +17,9 @@ export type ClientSpec = {
17
17
  * end, and for Claude Code each prompt (an entry older versions installed;
18
18
  * a prompt now ends at once, `hookPromptFast.ts`). */
19
19
  lifecycle?: string[];
20
+ /** What makes the guard entry fail closed (the agent refuses the command when the hook can't run or times out);
21
+ * absent where the agent has no such setting (Codex: a failed hook lets the command continue). */
22
+ failClosed?: Readonly<Record<string, unknown>>;
20
23
  path(env: Env): string;
21
24
  };
22
25
  export declare function claudeSettingsPath(env: Env): string;
@@ -30,6 +30,8 @@ export const CLIENTS = {
30
30
  // PostToolUse, so an approved command that failed still counts as ran.
31
31
  postFailure: "PostToolUseFailure",
32
32
  lifecycle: ["SessionStart", "SessionEnd", "UserPromptSubmit"],
33
+ // code.claude.com/docs/en/hooks: with "block", a failure does what exit code 2 does (Claude Code 2.1.295+).
34
+ failClosed: { onFailure: "block" },
33
35
  path: claudeSettingsPath
34
36
  },
35
37
  codex: {
@@ -47,6 +49,8 @@ export const CLIENTS = {
47
49
  format: "cursor",
48
50
  pre: "beforeShellExecution",
49
51
  post: "afterShellExecution",
52
+ // cursor.com/docs/agent/hooks: `failClosed` is off by default.
53
+ failClosed: { failClosed: true },
50
54
  path: cursorHooksPath
51
55
  }
52
56
  };
@@ -11,9 +11,10 @@
11
11
  * "local", whether or not any platform is connected.
12
12
  *
13
13
  * Any block refuses the command at once with Passport's own words; nothing waits for a person. Unanswered in time,
14
- * the command runs as it would without Passport, and once it ran Passport is told so (`controlPlaneLate.ts`); a
15
- * command that can't be undone is the exception: unless Passport allowed it, it is refused here (not signed in,
16
- * unreachable, or no answer in time). Anything else gets no answer at all.
14
+ * the command runs as it would without Passport, and once it ran Passport is told so (`controlPlaneLate.ts`); two
15
+ * exceptions: a command that can't be undone runs only on Passport's allow, and an action a Block rule covers, by
16
+ * this computer's copy of the rules from the last 7 days, is refused (`controlPlaneOffline.ts`). With no such copy,
17
+ * what ran is recorded as "decided offline, no rules known". Anything else gets no answer at all.
17
18
  */
18
19
  import type { CliFinding } from "./cliHookClassify.js";
19
20
  import { type GuardClient } from "./cliHookGuard.js";
@@ -29,6 +30,8 @@ export type GuardContext = {
29
30
  /** Signed in with a member profile that may ask Passport. */
30
31
  canAsk: boolean;
31
32
  cp: CachedCpCli | null;
33
+ /** The signed-in profile whose copy `cp` is (the workspace its signed rules must name). */
34
+ profile?: string | null;
32
35
  openApi: () => Promise<ApiCall | null>;
33
36
  report: {
34
37
  runtime?: string;
@@ -55,4 +58,9 @@ export declare function vendorVerbs(findings: readonly CliFinding[], vendors: re
55
58
  export declare function localRefusal(verb: LocalIrreversibleVerb, why: "signed-out" | "unreachable"): string;
56
59
  /** What the guard answers: a block's refusal, or nothing. */
57
60
  export declare function planGuard(context: GuardContext): Promise<GuardPlan>;
61
+ /** The guard never got to ask (its budget ran out first, or something failed before it answered): every platform the
62
+ * line would have asked about counts as unreachable, so a covered action is refused and the rest is recorded. */
63
+ export declare function planUnreachable(context: GuardContext): Promise<Record<string, unknown> | null>;
64
+ /** What the agent reads when the guard couldn't even classify a line Passport didn't answer for. */
65
+ export declare const UNCHECKED_REFUSAL = "Passport couldn't be reached or check this command, so it didn't run.";
58
66
  export {};
@@ -11,9 +11,10 @@
11
11
  * "local", whether or not any platform is connected.
12
12
  *
13
13
  * Any block refuses the command at once with Passport's own words; nothing waits for a person. Unanswered in time,
14
- * the command runs as it would without Passport, and once it ran Passport is told so (`controlPlaneLate.ts`); a
15
- * command that can't be undone is the exception: unless Passport allowed it, it is refused here (not signed in,
16
- * unreachable, or no answer in time). Anything else gets no answer at all.
14
+ * the command runs as it would without Passport, and once it ran Passport is told so (`controlPlaneLate.ts`); two
15
+ * exceptions: a command that can't be undone runs only on Passport's allow, and an action a Block rule covers, by
16
+ * this computer's copy of the rules from the last 7 days, is refused (`controlPlaneOffline.ts`). With no such copy,
17
+ * what ran is recorded as "decided offline, no rules known". Anything else gets no answer at all.
17
18
  */
18
19
  import { homedir } from "node:os";
19
20
  import { denyOutput } from "./cliHookGuard.js";
@@ -89,8 +90,11 @@ export async function planGuard(context) {
89
90
  return local[0] ? refuse(local[0], "signed-out") : { output: null };
90
91
  const { github, railway, supabase, verbs } = asking(context, local);
91
92
  const left = context.deadline - context.now();
92
- if (left <= 0)
93
- return local[0] ? refuse(local[0], "unreachable") : { output: null };
93
+ if (left <= 0) {
94
+ if (local[0])
95
+ return refuse(local[0], "unreachable");
96
+ return { output: await whenUnreachable(context, { github, railway, supabase }, []) };
97
+ }
94
98
  if (!github && !railway && !supabase && !verbs.length)
95
99
  return { output: null };
96
100
  // The kit's shadow run (`kitShadow.ts`) stops before the guard's deadline.
@@ -99,11 +103,17 @@ export async function planGuard(context) {
99
103
  const open = async () => (api ??= (await context.openApi()) ?? undefined) ?? null;
100
104
  const signal = AbortSignal.any([context.budget, AbortSignal.timeout(left)]);
101
105
  const extra = context.report?.sessionId ? { sessionId: context.report.sessionId } : {};
102
- // A step that fails is no answer from its platform; it never drops another's block or a local refusal.
106
+ // A step that fails is no answer from its platform (it counts as unreachable for the offline rules below); it never
107
+ // drops another's block or a local refusal.
108
+ const threw = { github: false, railway: false, supabase: false };
109
+ const failed = (platform) => () => {
110
+ threw[platform] = true;
111
+ return null;
112
+ };
103
113
  const [githubLine, railwayAnswer, supabaseAnswer, verbAnswers] = await Promise.all([
104
- github ? githubLinePlan(context, open, extra, signal).catch(() => null) : null,
105
- railway ? railwayLine(context, open, extra, signal).catch(() => null) : null,
106
- supabase ? supabaseLine(context, open, extra, signal).catch(() => null) : null,
114
+ github ? githubLinePlan(context, open, extra, signal).catch(failed("github")) : null,
115
+ railway ? railwayLine(context, open, extra, signal).catch(failed("railway")) : null,
116
+ supabase ? supabaseLine(context, open, extra, signal).catch(failed("supabase")) : null,
107
117
  askVerbs(verbs, open, extra, signal).catch(() => [])
108
118
  ]);
109
119
  // Decided: the kit's shadow run reads what was asked about, off the decision's path.
@@ -113,6 +123,11 @@ export async function planGuard(context) {
113
123
  const blocked = answers.find((answer) => answer?.kind === "block");
114
124
  if (blocked)
115
125
  return withApi(denyOutput(context.client, blocked.message));
126
+ const late = answers.flatMap((answer) => (answer?.kind === "unreachable" ? (answer.late ?? []) : []));
127
+ const missed = missedPlatforms({ github, railway, supabase }, threw, githubLine, railwayAnswer?.answer, supabaseAnswer?.answer);
128
+ const offline = await whenUnreachable(context, missed, late);
129
+ if (offline)
130
+ return withApi(offline);
116
131
  // A command that can't be undone runs only on Passport's allow.
117
132
  const localAnswers = verbAnswers.length === verbs.length ? verbAnswers.slice(verbs.length - local.length) : [];
118
133
  const unanswered = local.find((_verb, at) => localAnswers[at]?.kind !== "allow");
@@ -164,3 +179,79 @@ async function leaveDecisions(github, railway, context, others) {
164
179
  await railway.leave();
165
180
  await holdLate([github?.answer, railway?.answer, ...others], context.report, context.now());
166
181
  }
182
+ /** The platforms asked and not answered: Passport couldn't be reached for them. Every non-answer counts: no response,
183
+ * a 401, 403, 404, 429 or 5xx, a timeout, a 200 that isn't Passport's JSON (each reads as unreachable), or a step
184
+ * that threw. An `undecided` from Passport itself is an answer. */
185
+ function missedPlatforms(asked, threw, github, railway, supabase) {
186
+ // A real `undecided` (Passport answered, and doesn't decide this) keeps today's behavior: it isn't offline.
187
+ const missed = (answer) => !answer || answer.kind === "unreachable";
188
+ return {
189
+ github: asked.github && (threw.github || (Boolean(github?.label) && missed(github?.decided?.answer))),
190
+ railway: asked.railway && (threw.railway || missed(railway)),
191
+ supabase: asked.supabase && (threw.supabase || missed(supabase))
192
+ };
193
+ }
194
+ /** What the line does on each platform Passport didn't answer for, classified on this computer. */
195
+ async function foundOffline(context, missed) {
196
+ const found = [];
197
+ if (missed.github) {
198
+ const cp = await import("./controlPlaneGuard.js");
199
+ const where = context.cwd ? { cwd: context.cwd } : undefined;
200
+ for (const entry of cp.classifyCommands(context.command, cp.gitPlace(context.cwd), where)) {
201
+ for (const one of entry.classifications) {
202
+ found.push({ platform: "github", nodeId: one.nodeId, actionKey: one.actionKey, summary: one.summary });
203
+ }
204
+ }
205
+ }
206
+ if (missed.railway) {
207
+ const where = { cwd: context.cwd, env: context.env ?? process.env, home: homedir() };
208
+ found.push(...(await (await import("./controlPlaneRailwayGuard.js")).railwayFound(context.command, where)));
209
+ }
210
+ if (missed.supabase) {
211
+ const where = { cwd: context.cwd ?? null, env: context.env ?? process.env };
212
+ found.push(...(await import("./controlPlaneSupabase.js")).supabaseFound(context.command, where));
213
+ }
214
+ return found;
215
+ }
216
+ /** The guard never got to ask (its budget ran out first, or something failed before it answered): every platform the
217
+ * line would have asked about counts as unreachable, so a covered action is refused and the rest is recorded. */
218
+ export async function planUnreachable(context) {
219
+ const { github, railway, supabase } = asking(context, []);
220
+ return whenUnreachable(context, { github, railway, supabase }, []);
221
+ }
222
+ /** What the agent reads when the guard couldn't even classify a line Passport didn't answer for. */
223
+ export const UNCHECKED_REFUSAL = "Passport couldn't be reached or check this command, so it didn't run.";
224
+ /**
225
+ * Passport couldn't be reached for part of the line (`controlPlaneOffline.ts`). The line is classified on this
226
+ * computer, and every outcome is recorded as decided offline: with rules from the last 7 days, an action a Block rule
227
+ * covers is refused (recorded at once: it won't run), anything else runs (recorded once it ran); with none, it runs
228
+ * (recorded as no rules known). Anything that throws here refuses: a covered action is never allowed by an error.
229
+ */
230
+ async function whenUnreachable(context, missed, late) {
231
+ if (!missed.github && !missed.railway && !missed.supabase)
232
+ return null;
233
+ try {
234
+ const found = await foundOffline(context, missed);
235
+ if (!found.length)
236
+ return null;
237
+ const offline = await import("./controlPlaneOffline.js");
238
+ const now = context.now();
239
+ const report = { sessionId: context.report?.sessionId, toolUseId: context.report?.toolUseId };
240
+ const blocks = offline.usableBlocks(context.cp, context.profile ?? null, now);
241
+ if (!blocks) {
242
+ offline.holdOffline(report.sessionId, report.toolUseId, found, late, "no_rules", now);
243
+ return null;
244
+ }
245
+ const covered = offline.coveredOffline(found, blocks)[0];
246
+ if (!covered) {
247
+ offline.holdOffline(report.sessionId, report.toolUseId, found, late, "allowed", now);
248
+ return null;
249
+ }
250
+ if (context.profile)
251
+ offline.queueOffline(context.profile, report.sessionId, found, late, "blocked", now);
252
+ return denyOutput(context.client, offline.offlineRefusal(covered));
253
+ }
254
+ catch {
255
+ return denyOutput(context.client, UNCHECKED_REFUSAL);
256
+ }
257
+ }
@@ -289,11 +289,13 @@ export async function leftovers(queued, context) {
289
289
  const { profile, budget, deps } = context;
290
290
  const now = (deps.now ?? Date.now)();
291
291
  const late = await import("./controlPlaneLate.js");
292
- const { late: lateIds, reports } = late.splitLate(queued);
292
+ const offlineNotices = await import("./controlPlaneOffline.js");
293
+ const { offline, rest } = offlineNotices.splitOffline(queued);
294
+ const { late: lateIds, reports } = late.splitLate(rest);
293
295
  const refresh = claimStaleRefresh(profile, readCpCli(profile), now);
294
296
  const extras = await import("./cliHookExtras.js");
295
297
  const heartbeat = await extras.heartbeatDue(profile, now);
296
- if (!reports.length && !lateIds.length && !refresh && !heartbeat)
298
+ if (!reports.length && !lateIds.length && !offline.length && !refresh && !heartbeat)
297
299
  return;
298
300
  const api = context.api ?? (await profileApi(profile, budget, deps.fetch ?? fetch));
299
301
  if (!api)
@@ -304,6 +306,7 @@ export async function leftovers(queued, context) {
304
306
  await Promise.allSettled([
305
307
  ...reports.map((entry) => send(entry)),
306
308
  lateIds.length ? late.tellLate(api, lateIds, budget) : null,
309
+ offline.length ? offlineNotices.tellOffline(api, offline, budget) : null,
307
310
  heartbeat ? extras.heartbeat(api, profile, context.runtime.env, budget, now) : null,
308
311
  refresh ? refreshCpCli(profile, budget, { api, ...(deps.now ? { now: deps.now } : {}) }) : null
309
312
  ]);
@@ -48,6 +48,8 @@ export declare function subagentOf(input: Pick<HookInput, "agent_id">): {
48
48
  /** A shell string as-is, or an argv array (`["bash", "-lc", "…"]`) re-quoted
49
49
  * so the classifier reads the same words the shell will. */
50
50
  export declare function commandText(candidate: unknown): string | null;
51
+ /** What the agent sent, as text; null when nothing arrived in the budget or it was more than the hook reads. */
52
+ export declare function readRaw(runtime: Runtime, signal: AbortSignal): Promise<string | null>;
51
53
  export declare function readInput(runtime: Runtime, signal: AbortSignal): Promise<HookInput | null>;
52
54
  /** An object's fields, or none for anything else. */
53
55
  export declare function record(candidate: unknown): Record<string, unknown>;
@@ -55,6 +55,16 @@ export function commandText(candidate) {
55
55
  .map((part) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(part) ? part : `'${part.replaceAll("'", `'\\''`)}'`))
56
56
  .join(" ");
57
57
  }
58
+ /** What the agent sent, as text; null when nothing arrived in the budget or it was more than the hook reads. */
59
+ export async function readRaw(runtime, signal) {
60
+ try {
61
+ const text = await readStdin(runtime, signal);
62
+ return text ? text : null;
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
58
68
  export async function readInput(runtime, signal) {
59
69
  try {
60
70
  const parsed = JSON.parse(await readStdin(runtime, signal));
@@ -43,7 +43,8 @@ export declare function stableInvocation(stable: {
43
43
  * Add Passport's entry to every slot a registered kind is missing, with the
44
44
  * command it already runs, touching nothing else. Idempotent; never adds a
45
45
  * kind that isn't there (the guard someone turned off stays off), and leaves
46
- * an agent the plugin covers alone. Returns the events added. Throws a
46
+ * an agent the plugin covers alone. A guard entry from before fail-closed is
47
+ * upgraded in place (not counted). Returns the events added. Throws a
47
48
  * CliFailure when the file can't be read.
48
49
  */
49
50
  export declare function repairHookSlots(client: HookClient, env: Env): string[];
@@ -60,6 +61,8 @@ export declare function registeredEntries(client: HookClient, env: Env): {
60
61
  };
61
62
  /** What the guard does in Codex, in plain words (status, install, init). */
62
63
  export declare const CODEX_BLOCK_ONLY = "In Codex, Passport refuses what your rules block and says why.";
64
+ /** Where the guard fails closed (Claude Code, Cursor): removing Passport first would block every shell command. */
65
+ export declare const FAIL_CLOSED_WARNING = "The guard fails closed: before removing Passport, run passport hook uninstall, or this agent's shell commands are refused.";
63
66
  export type Change = {
64
67
  action: "add" | "update" | "remove";
65
68
  event: string;
@@ -93,6 +96,8 @@ export declare function agentHookStatus(client: HookClient, env: Env): {
93
96
  plugin: boolean;
94
97
  /** Hook events Passport's entry should be on but isn't. */
95
98
  missing: string[];
99
+ /** The guard entry fails closed; null where the agent can't (Codex). The plugin's hooks fail open. */
100
+ failClosed: boolean | null;
96
101
  command: string | null;
97
102
  guardCommand: string | null;
98
103
  path: string;