passport-bridge 0.18.0 → 0.20.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 (43) hide show
  1. package/README.md +5 -3
  2. package/dist/approvalLines.d.ts +17 -0
  3. package/dist/approvalLines.js +40 -0
  4. package/dist/approvalNote.d.ts +20 -0
  5. package/dist/approvalNote.js +33 -0
  6. package/dist/cliArgs.js +1 -0
  7. package/dist/cliAutopilotPolicy.d.ts +34 -9
  8. package/dist/cliAutopilotPolicy.js +32 -1
  9. package/dist/cliHook.js +32 -11
  10. package/dist/cliHookDecide.d.ts +14 -0
  11. package/dist/cliHookDecide.js +62 -4
  12. package/dist/cliHookDeliver.d.ts +8 -1
  13. package/dist/cliHookDeliver.js +3 -3
  14. package/dist/cliHookGuard.d.ts +12 -5
  15. package/dist/cliHookGuard.js +26 -35
  16. package/dist/cliHookHold.d.ts +91 -0
  17. package/dist/cliHookHold.js +168 -0
  18. package/dist/cliHookInstall.d.ts +8 -1
  19. package/dist/cliHookInstall.js +58 -12
  20. package/dist/cliHookKey.d.ts +25 -0
  21. package/dist/cliHookKey.js +160 -0
  22. package/dist/cliHookRedact.d.ts +13 -0
  23. package/dist/cliHookRedact.js +60 -0
  24. package/dist/cliHookVendors.d.ts +3 -0
  25. package/dist/cliHookVendors.js +7 -0
  26. package/dist/cliHookVendorsMore.d.ts +3 -4
  27. package/dist/cliHookVendorsMore.js +3 -9
  28. package/dist/cliKeysShim.d.ts +1 -1
  29. package/dist/cliMain.js +18 -0
  30. package/dist/cliOutput.js +2 -2
  31. package/dist/cliPolicyV2.js +61 -19
  32. package/dist/cliWait.d.ts +7 -8
  33. package/dist/cliWait.js +50 -19
  34. package/dist/doctor.js +14 -0
  35. package/dist/holdNotice.d.ts +23 -0
  36. package/dist/holdNotice.js +73 -0
  37. package/dist/launcherFastPath.js +11 -4
  38. package/dist/pluginPin.d.ts +1 -1
  39. package/dist/pluginPin.js +1 -1
  40. package/dist/version.d.ts +1 -1
  41. package/dist/version.js +1 -1
  42. package/npm-shrinkwrap.json +2 -2
  43. package/package.json +3 -2
@@ -107,8 +107,8 @@ export function expiredAsks(now) {
107
107
  .filter((report) => report.decision === "ask")
108
108
  .map((report) => ({ ...report, ran: false }));
109
109
  }
110
- export function budgetSignal(runtime) {
111
- return AbortSignal.any([runtime.signal, AbortSignal.timeout(HOOK_BUDGET_MS)]);
110
+ export function budgetSignal(runtime, deps = {}) {
111
+ return AbortSignal.any([runtime.signal, deps.budget?.signal ?? AbortSignal.timeout(HOOK_BUDGET_MS)]);
112
112
  }
113
113
  /** Never wait on the network after a command: queue the report, and a
114
114
  * detached flush sends it. */
@@ -211,7 +211,7 @@ export async function runFlush(args, runtime, deps) {
211
211
  policy,
212
212
  local: policy?.version === 2 && policy.autopilot.localCommands === true,
213
213
  runtimeName,
214
- budget: budgetSignal(runtime),
214
+ budget: budgetSignal(runtime, deps),
215
215
  runtime,
216
216
  args,
217
217
  deps
@@ -13,7 +13,7 @@
13
13
  * With a v1 policy (an older server) or none at all, the guard keeps its old
14
14
  * shape: ask or deny, never allow.
15
15
  */
16
- import { type ActionClass, type ActionEnv, type Cause, type Decision } from "./cliAutopilotPolicy.js";
16
+ import { type AccessBlock, type ActionClass, type ActionEnv, type Cause, type Decision } from "./cliAutopilotPolicy.js";
17
17
  import type { CliFinding } from "./cliHookClassify.js";
18
18
  import { type EnvSource } from "./cliHookEnvironment.js";
19
19
  import { type LinkFs } from "./envLinkFs.js";
@@ -39,10 +39,7 @@ export type DecidedFinding = {
39
39
  access?: AppAccessBlock;
40
40
  };
41
41
  /** "You don't have access to Railway in Passport. Ask an admin." and the app's Access link. */
42
- export type AppAccessBlock = {
43
- message: string;
44
- link?: string;
45
- };
42
+ export type AppAccessBlock = AccessBlock;
46
43
  export type GuardDecision = {
47
44
  verdict: GuardVerdict;
48
45
  /** The finding that set the verdict, e.g. `railway volume delete`. */
@@ -83,6 +80,16 @@ export declare function guardMachineOf(machine: {
83
80
  }, rawCwd: unknown, env: Record<string, string | undefined>): GuardMachine;
84
81
  /** The words a person needs to recognise the command, never its arguments. */
85
82
  export declare function guardLabel(finding: CliFinding): string;
83
+ /**
84
+ * Read, Change, Delete, or Irreversible: the server's `cliActionClass`, from
85
+ * the tables it serves. A read is a read, whatever lists it. A write is a
86
+ * Change unless a safety pack raises it (`deletes`); anything else is raised.
87
+ * A raised verb is Irreversible where `irreversible` lists it, or
88
+ * `irreversibleInProduction` does and it runs in Production; otherwise a Delete.
89
+ */
90
+ export declare function classOf(policy: CachedCliPolicyV2, finding: CliFinding & {
91
+ vendor: string;
92
+ }, verb: string, environment: ActionEnv): ActionClass;
86
93
  /** One recognized command's decision, or null when Autopilot has no opinion. */
87
94
  export declare function decideFinding(finding: CliFinding, policy: CachedCliPolicyV2, machine?: GuardMachine): DecidedFinding | null;
88
95
  /**
@@ -18,8 +18,7 @@ import { reportedEnvironment } from "./cliHookEnvironment.js";
18
18
  import { placementOf, resolveTarget, targetNote } from "./envResolve.js";
19
19
  import { NODE_LINK_FS } from "./envLinkFs.js";
20
20
  import { normalizeArgv, splitCommands } from "./cliHookParse.js";
21
- import { VENDORS } from "./cliHookVendors.js";
22
- import { IRREVERSIBLE_IN_PRODUCTION } from "./cliHookVendorsMore.js";
21
+ import { VENDORS, vendorKeys } from "./cliHookVendors.js";
23
22
  /** This machine for folder links: the command's folder (canonical, and as
24
23
  * the agent named it), the project, home, and the agent's shell. */
25
24
  export function guardMachineOf(machine, rawCwd, env) {
@@ -49,16 +48,8 @@ const RANK = { allow: 0, ask: 1, deny: 2 };
49
48
  const LABEL_TOKEN = /^-{0,2}[A-Za-z0-9][A-Za-z0-9._:+-]{0,39}$/;
50
49
  /** Shell features that hide what will run. Any of them: no allow. */
51
50
  const OPAQUE_SHELL = /[<>`$\\\n]|\$\(/;
52
- /** Built in, whatever the server sends: these can't be taken back. */
53
- const BUILT_IN_IRREVERSIBLE = { gh: ["repo delete"] };
54
51
  /** Classes the guard decides; anything else (http, api, sql, local) is no decision. */
55
52
  const CLASS_OF_RISK = CLASS_OF_HOOK_RISK;
56
- /** `fly` and `flyctl` share one map; the server may key either spelling. */
57
- function vendorKeys(vendor) {
58
- const spec = Object.hasOwn(VENDORS, vendor) ? VENDORS[vendor] : undefined;
59
- const aliases = spec ? Object.keys(VENDORS).filter((key) => VENDORS[key] === spec && key !== vendor) : [];
60
- return [vendor, ...aliases];
61
- }
62
53
  function policyDecision(policy, vendor, verb) {
63
54
  for (const key of vendorKeys(vendor)) {
64
55
  const verbs = Object.hasOwn(policy.vendors, key) ? policy.vendors[key] : undefined;
@@ -107,6 +98,8 @@ function verdictV1(finding, policy) {
107
98
  return null;
108
99
  const explicit = policy ? policyDecision(policy, finding.vendor, finding.verbKey ?? finding.verb) : undefined;
109
100
  // Built-in default when no policy was ever synced: ask before destructive.
101
+ // Every irreversible verb (the server's irreversible tables) is destructive
102
+ // too, so this covers them without a list of its own.
110
103
  const decision = explicit ?? (finding.risk === "destructive" ? (policy?.default.destructive ?? "ask") : undefined);
111
104
  if (decision === "never")
112
105
  return "deny";
@@ -140,25 +133,25 @@ function listed(map, vendor, verb) {
140
133
  return false;
141
134
  return vendorKeys(vendor).some((key) => Object.hasOwn(map, key) && map[key].includes(verb));
142
135
  }
143
- /** Read, Change, Delete, or Irreversible, as the server's packs define them. */
144
- function classOf(policy, finding, verb, environment) {
136
+ /**
137
+ * Read, Change, Delete, or Irreversible: the server's `cliActionClass`, from
138
+ * the tables it serves. A read is a read, whatever lists it. A write is a
139
+ * Change unless a safety pack raises it (`deletes`); anything else is raised.
140
+ * A raised verb is Irreversible where `irreversible` lists it, or
141
+ * `irreversibleInProduction` does and it runs in Production; otherwise a Delete.
142
+ */
143
+ export function classOf(policy, finding, verb, environment) {
145
144
  const { autopilot } = policy;
146
- // The server's `cliActionClass`: a read is a read, whatever lists it.
147
145
  if (finding.risk === "read")
148
146
  return "read";
149
- if (listed(autopilot.irreversible, finding.vendor, verb) || listed(BUILT_IN_IRREVERSIBLE, finding.vendor, verb)) {
147
+ if (finding.risk === "write" && !listed(autopilot.deletes, finding.vendor, verb))
148
+ return "change";
149
+ if (listed(autopilot.irreversible, finding.vendor, verb))
150
150
  return "irreversible";
151
- }
152
- const productionOnly = listed(autopilot.irreversibleInProduction, finding.vendor, verb) ||
153
- listed(IRREVERSIBLE_IN_PRODUCTION, finding.vendor, verb);
154
- if (environment === "production" && productionOnly) {
151
+ if (environment === "production" && listed(autopilot.irreversibleInProduction, finding.vendor, verb)) {
155
152
  return "irreversible";
156
153
  }
157
- // Force-pushing the default branch rewrites history others already have.
158
- if (finding.vendor === "git" && verb === "push --force" && environment === "production")
159
- return "irreversible";
160
- const base = CLASS_OF_RISK[finding.risk] ?? "delete";
161
- return base === "change" && listed(autopilot.deletes, finding.vendor, verb) ? "delete" : base;
154
+ return "delete";
162
155
  }
163
156
  /** Commands run as administrator never run silently. */
164
157
  const SUDO_CAUSE = { kind: "default", label: "Commands run with sudo always ask" };
@@ -176,6 +169,7 @@ function decideLocal(finding, policy) {
176
169
  finding,
177
170
  decision: sudo ? "ask" : decided.decision,
178
171
  cause: sudo ? SUDO_CAUSE : decided.cause,
172
+ ...(decided.access ? { access: decided.access } : {}),
179
173
  environment: facts.environment,
180
174
  environmentSource: "flag",
181
175
  reported: facts.environment,
@@ -187,7 +181,7 @@ function decideLocal(finding, policy) {
187
181
  * repository's own `.passport/actions.toml` may only ask or block. */
188
182
  function decideProject(finding, policy) {
189
183
  const facts = finding.project;
190
- const { decision, cause } = decideAction(policy.autopilot, {
184
+ const { decision, cause, access } = decideAction(policy.autopilot, {
191
185
  vendor: "project",
192
186
  verb: finding.verb,
193
187
  actionClass: facts.actionClass,
@@ -199,6 +193,7 @@ function decideProject(finding, policy) {
199
193
  finding,
200
194
  decision,
201
195
  cause,
196
+ ...(access ? { access } : {}),
202
197
  environment: facts.environment,
203
198
  environmentSource: "mapping",
204
199
  reported: facts.environment,
@@ -231,27 +226,20 @@ export function decideFinding(finding, policy, machine) {
231
226
  : target;
232
227
  const verb = finding.verbKey ?? finding.verb;
233
228
  const actionClass = classOf(policy, finding, verb, hint.kind);
234
- const ruled = decideAction(policy.autopilot, {
229
+ // The access ceiling comes first inside the engine: No access blocks every
230
+ // command, Read-only runs only reads (the same as exec).
231
+ const { decision, cause, access } = decideAction(policy.autopilot, {
235
232
  vendor: finding.vendor,
236
233
  verb,
237
234
  actionClass,
238
235
  environment: hint.kind
239
236
  });
240
- // The person's pass for the app this CLI acts on comes first: No access
241
- // blocks every command, Read-only runs only reads (the same as exec).
242
- const pass = Object.hasOwn(policy.autopilot.appAccess ?? {}, finding.vendor)
243
- ? policy.autopilot.appAccess[finding.vendor]
244
- : undefined;
245
- const limited = pass && (pass.pass === "none" || (pass.pass === "readonly" && actionClass !== "read"));
246
- const { decision, cause } = limited
247
- ? { decision: "block", cause: { kind: "block", label: pass.cause } }
248
- : ruled;
249
237
  const reported = finding.pushEnvironment ?? reportedEnvironment(hint);
250
238
  return {
251
239
  finding,
252
240
  decision,
253
241
  cause,
254
- ...(limited ? { access: { message: pass.message, ...(pass.link ? { link: pass.link } : {}) } } : {}),
242
+ ...(access ? { access } : {}),
255
243
  environment: hint.kind,
256
244
  environmentSource: hint.source,
257
245
  ...(reported ? { reported } : {}),
@@ -402,6 +390,9 @@ export function denyMessage(decision, owner) {
402
390
  // The app's access, in the words exec uses, with where an admin changes it.
403
391
  if (decision.access)
404
392
  return decision.access.link ? `${decision.access.message} ${decision.access.link}` : decision.access.message;
393
+ // The server's access block without its message: no rule or exception lifts it.
394
+ if (decision.cause?.kind === "access")
395
+ return `${decision.cause.label}. Ask an admin for access.`;
405
396
  if (decision.cause) {
406
397
  const mine = decision.cause.label.startsWith("Your rule");
407
398
  const next = mine
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The hold: after Passport opens an approval request for an unattended ask,
3
+ * the guard waits a little while for a person to answer on their phone. When
4
+ * they approve in time, the agent's original command runs with no retry.
5
+ *
6
+ * Fail closed, always. The only way out that runs the command is a fresh
7
+ * `allow` from `POST /api/my/cli/decide`, asked again with the same request
8
+ * after the approval says allowed: that call consumes the approval once and
9
+ * re-checks every rule on fresh state. A timeout, an error, an abort, an
10
+ * answer that doesn't parse, or a slow second decide leaves the command
11
+ * declined with the pending line, and the approval waits for `passport wait`.
12
+ *
13
+ * The hold must end before the agent kills the hook: Claude Code runs the
14
+ * command anyway when a hook outlives its `timeout`. So its length travels in
15
+ * the installed command (`passport hook guard --hold 25`), written in the same
16
+ * entry as `timeout: hold + 15`. An entry without `--hold` doesn't hold.
17
+ * `PASSPORT_HOOK_HOLD` may shorten the hold, never lengthen it.
18
+ */
19
+ /** The longest hold an install writes; with its margin, under a minute. */
20
+ export declare const HOLD_MAX_SECONDS = 45;
21
+ /** What `hook install` and `init` write for agents that can run a held command. */
22
+ export declare const HOLD_DEFAULT_SECONDS = 25;
23
+ /** The hook's `timeout` is the hold plus this, so the agent never kills it first. */
24
+ export declare const HOLD_TIMEOUT_MARGIN_SECONDS = 15;
25
+ /** Kept at the end of the hold for the second decide and printing. */
26
+ export declare const HOLD_SETTLE_MS = 3000;
27
+ type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
28
+ /** The hold an installed guard command carries (`--hold <s>` anywhere), or 0. */
29
+ export declare function holdOfCommand(command: string): number;
30
+ /**
31
+ * The hold this run may use, checked against the timeout the agent will
32
+ * actually enforce: the guard's entry in Claude Code's settings. A hand-edited
33
+ * shorter timeout shortens the hold; an entry this run can't find (another
34
+ * settings file, a plugin, managed settings) means no hold, so a hold can
35
+ * never outlive the hook. Only Claude Code holds.
36
+ */
37
+ export declare function cappedHold(seconds: number, entry: {
38
+ command: string;
39
+ timeout?: unknown;
40
+ } | null): number;
41
+ /** Seconds as a hold, or null when it isn't a whole number in range. */
42
+ export declare function parseHold(raw: string | undefined): number | null;
43
+ /**
44
+ * This run's hold: what the installed command says (`--hold`), shortened by
45
+ * `PASSPORT_HOOK_HOLD` when that is smaller. No flag, or a bad one, is no hold.
46
+ */
47
+ export declare function holdSeconds(flag: string | undefined, env: Record<string, string | undefined>): number;
48
+ /** The parts of a decide answer the hold reads. */
49
+ export type DecideAnswer = {
50
+ decision: string;
51
+ message?: string;
52
+ approvalId?: string;
53
+ waitingFor?: string;
54
+ expiresAt?: number;
55
+ };
56
+ export type HoldOutcome<D extends DecideAnswer = DecideAnswer> =
57
+ /** Approved, and the second decide allowed it: the command runs now. */
58
+ {
59
+ kind: "approved";
60
+ server: D;
61
+ }
62
+ /** Declined, or blocked on the second decide: the line says by whom and why. */
63
+ | {
64
+ kind: "declined";
65
+ message: string;
66
+ server?: D;
67
+ } | {
68
+ kind: "expired";
69
+ }
70
+ /** Still waiting when the hold ended, or anything went wrong. */
71
+ | {
72
+ kind: "pending";
73
+ waitingFor?: string;
74
+ expiresAt?: number;
75
+ /** A new request the second decide opened (the first was used elsewhere). */
76
+ approvalId?: string;
77
+ };
78
+ /**
79
+ * Hold for a decision on one approval, within `seconds`. Never throws, and
80
+ * never answers "approved" without a fresh allow from the server.
81
+ */
82
+ export declare function holdForDecision<D extends DecideAnswer>(api: ApiCall, approvalId: string,
83
+ /** Decide again with the original request (`decideOnServer`), or null. */
84
+ decideAgain: (signal: AbortSignal) => Promise<D | null>, options: {
85
+ seconds: number;
86
+ signal: AbortSignal;
87
+ now: () => number;
88
+ /** For tests: how the guard sleeps between gentle polls. */
89
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
90
+ }): Promise<HoldOutcome<D>>;
91
+ export { EXPIRED_MESSAGE, expiryTime, pendingMessage } from "./approvalLines.js";
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The hold: after Passport opens an approval request for an unattended ask,
3
+ * the guard waits a little while for a person to answer on their phone. When
4
+ * they approve in time, the agent's original command runs with no retry.
5
+ *
6
+ * Fail closed, always. The only way out that runs the command is a fresh
7
+ * `allow` from `POST /api/my/cli/decide`, asked again with the same request
8
+ * after the approval says allowed: that call consumes the approval once and
9
+ * re-checks every rule on fresh state. A timeout, an error, an abort, an
10
+ * answer that doesn't parse, or a slow second decide leaves the command
11
+ * declined with the pending line, and the approval waits for `passport wait`.
12
+ *
13
+ * The hold must end before the agent kills the hook: Claude Code runs the
14
+ * command anyway when a hook outlives its `timeout`. So its length travels in
15
+ * the installed command (`passport hook guard --hold 25`), written in the same
16
+ * entry as `timeout: hold + 15`. An entry without `--hold` doesn't hold.
17
+ * `PASSPORT_HOOK_HOLD` may shorten the hold, never lengthen it.
18
+ */
19
+ import { readBoundedJson } from "./boundedResponse.js";
20
+ import { declinedFrom } from "./approvalLines.js";
21
+ /** The longest hold an install writes; with its margin, under a minute. */
22
+ export const HOLD_MAX_SECONDS = 45;
23
+ /** What `hook install` and `init` write for agents that can run a held command. */
24
+ export const HOLD_DEFAULT_SECONDS = 25;
25
+ /** The hook's `timeout` is the hold plus this, so the agent never kills it first. */
26
+ export const HOLD_TIMEOUT_MARGIN_SECONDS = 15;
27
+ /** Kept at the end of the hold for the second decide and printing. */
28
+ export const HOLD_SETTLE_MS = 3_000;
29
+ const WAIT_POLL_SECONDS = 30;
30
+ const MAX_RESPONSE_BYTES = 16 * 1024;
31
+ /** The hold an installed guard command carries (`--hold <s>` anywhere), or 0. */
32
+ export function holdOfCommand(command) {
33
+ const found = /(?:^|\s)--hold(?:\s+|=)(\d{1,2})(?=\s|$)/.exec(command);
34
+ return found ? (parseHold(found[1]) ?? 0) : 0;
35
+ }
36
+ /** Claude Code's own default when an entry sets no timeout. */
37
+ const CLAUDE_DEFAULT_TIMEOUT_SECONDS = 60;
38
+ /** Kept under the configured timeout for the guard's own work around the hold. */
39
+ const HOLD_RUNTIME_RESERVE_SECONDS = 8;
40
+ /**
41
+ * The hold this run may use, checked against the timeout the agent will
42
+ * actually enforce: the guard's entry in Claude Code's settings. A hand-edited
43
+ * shorter timeout shortens the hold; an entry this run can't find (another
44
+ * settings file, a plugin, managed settings) means no hold, so a hold can
45
+ * never outlive the hook. Only Claude Code holds.
46
+ */
47
+ export function cappedHold(seconds, entry) {
48
+ if (seconds <= 0 || !entry || holdOfCommand(entry.command) <= 0)
49
+ return 0;
50
+ const timeout = typeof entry.timeout === "number" && Number.isFinite(entry.timeout)
51
+ ? entry.timeout
52
+ : entry.timeout === undefined
53
+ ? CLAUDE_DEFAULT_TIMEOUT_SECONDS
54
+ : 0;
55
+ return Math.max(0, Math.min(seconds, Math.floor(timeout - HOLD_RUNTIME_RESERVE_SECONDS)));
56
+ }
57
+ /** Seconds as a hold, or null when it isn't a whole number in range. */
58
+ export function parseHold(raw) {
59
+ if (raw === undefined || !/^\d{1,2}$/.test(raw.trim()))
60
+ return null;
61
+ const seconds = Number(raw.trim());
62
+ return seconds <= HOLD_MAX_SECONDS ? seconds : null;
63
+ }
64
+ /**
65
+ * This run's hold: what the installed command says (`--hold`), shortened by
66
+ * `PASSPORT_HOOK_HOLD` when that is smaller. No flag, or a bad one, is no hold.
67
+ */
68
+ export function holdSeconds(flag, env) {
69
+ const installed = parseHold(flag);
70
+ if (installed === null)
71
+ return 0;
72
+ const shorter = parseHold(env.PASSPORT_HOOK_HOLD);
73
+ return shorter === null ? installed : Math.min(installed, shorter);
74
+ }
75
+ function line(raw, max) {
76
+ if (typeof raw !== "string")
77
+ return undefined;
78
+ const cleaned = raw
79
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
80
+ .replace(/\s+/g, " ")
81
+ .trim();
82
+ return cleaned ? cleaned.slice(0, max) : undefined;
83
+ }
84
+ /**
85
+ * Hold for a decision on one approval, within `seconds`. Never throws, and
86
+ * never answers "approved" without a fresh allow from the server.
87
+ */
88
+ export async function holdForDecision(api, approvalId,
89
+ /** Decide again with the original request (`decideOnServer`), or null. */
90
+ decideAgain, options) {
91
+ const { now } = options;
92
+ const end = now() + options.seconds * 1000;
93
+ const pollUntil = end - HOLD_SETTLE_MS;
94
+ const sleep = options.sleep ?? defaultSleep;
95
+ let pending = { kind: "pending" };
96
+ try {
97
+ while (!options.signal.aborted) {
98
+ const left = Math.floor((pollUntil - now()) / 1000);
99
+ if (left < 1)
100
+ return pending;
101
+ const poll = Math.min(WAIT_POLL_SECONDS, left);
102
+ const response = await api(`/api/my/approvals/${encodeURIComponent(approvalId)}/wait?timeout=${poll}`, {
103
+ method: "GET",
104
+ headers: { accept: "application/json", "x-passport-surface": "cli" },
105
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(Math.max(1, pollUntil - now()))])
106
+ });
107
+ if (!response.ok) {
108
+ await response.body?.cancel().catch(() => undefined);
109
+ return pending;
110
+ }
111
+ const body = await readBoundedJson(response, MAX_RESPONSE_BYTES);
112
+ if (body.status === "pending") {
113
+ pending = {
114
+ kind: "pending",
115
+ ...(line(body.waitingFor, 80) ? { waitingFor: line(body.waitingFor, 80) } : {}),
116
+ ...(typeof body.expiresAt === "number" && Number.isFinite(body.expiresAt)
117
+ ? { expiresAt: body.expiresAt }
118
+ : {})
119
+ };
120
+ // A server that answers at once instead of holding is polled gently.
121
+ if (response.headers.get("x-passport-long-poll") === "0")
122
+ await sleep(1_000, options.signal);
123
+ continue;
124
+ }
125
+ if (body.status === "denied")
126
+ return { kind: "declined", message: declinedFrom(body.message) };
127
+ if (body.status === "expired")
128
+ return { kind: "expired" };
129
+ if (body.status !== "allowed")
130
+ return pending;
131
+ // Approved: ask again, so the approval is consumed once and every rule
132
+ // is checked on fresh state. Only that allow runs the command.
133
+ const leftMs = end - now() - 250;
134
+ if (leftMs < 100)
135
+ return pending;
136
+ const server = await decideAgain(AbortSignal.any([options.signal, AbortSignal.timeout(leftMs)]));
137
+ if (server?.decision === "allow")
138
+ return { kind: "approved", server };
139
+ // A new request instead (the approval was used by another run): name it.
140
+ if (server?.decision === "ask" && server.approvalId) {
141
+ return {
142
+ kind: "pending",
143
+ approvalId: server.approvalId,
144
+ ...(server.waitingFor ? { waitingFor: server.waitingFor } : {}),
145
+ ...(server.expiresAt !== undefined ? { expiresAt: server.expiresAt } : {})
146
+ };
147
+ }
148
+ if (server?.decision === "block") {
149
+ return { kind: "declined", message: server.message ?? "Blocked by Passport.", server };
150
+ }
151
+ return pending;
152
+ }
153
+ }
154
+ catch {
155
+ /* Fail closed: still pending. */
156
+ }
157
+ return pending;
158
+ }
159
+ function defaultSleep(ms, signal) {
160
+ return new Promise((resolve) => {
161
+ const timer = setTimeout(resolve, ms);
162
+ signal.addEventListener("abort", () => {
163
+ clearTimeout(timer);
164
+ resolve();
165
+ }, { once: true });
166
+ });
167
+ }
168
+ export { EXPIRED_MESSAGE, expiryTime, pendingMessage } from "./approvalLines.js";
@@ -29,7 +29,9 @@ export declare function isPassportHookCommand(command: unknown): boolean;
29
29
  export declare function isPassportGuardCommand(command: unknown): boolean;
30
30
  /** The registered audit command. Without a client it stays the historical
31
31
  * `passport hook`, so older registrations still read as current. */
32
- export declare function hookCommand(env: Env, exists?: (path: string) => boolean, client?: HookClient, kind?: Kind, invocation?: string): string;
32
+ export declare function hookCommand(env: Env, exists?: (path: string) => boolean, client?: HookClient, kind?: Kind, invocation?: string,
33
+ /** The guard's hold, in seconds (`cliHookHold.ts`); 0 writes no flag. */
34
+ hold?: number): string;
33
35
  /** A shell-safe `node <entry>` prefix for a hook command. */
34
36
  export declare function nodeInvocation(node: string, entry: string): string;
35
37
  /** What hooks run for a stable install: its version-independent launcher, so
@@ -89,5 +91,10 @@ export declare function agentHookStatus(client: HookClient, env: Env): {
89
91
  path: string;
90
92
  agentPresent: boolean;
91
93
  };
94
+ /** One agent's guard entry, its command and timeout; null when off or unreadable. Never throws. */
95
+ export declare function guardEntryOf(client: HookClient, env: Env): {
96
+ command: string;
97
+ timeout?: unknown;
98
+ } | null;
92
99
  export declare function hookRegistration(action: "install" | "uninstall" | "status", client: string | undefined, args: ParsedArgs, runtime: Runtime): CommandResult;
93
100
  export {};
@@ -16,7 +16,8 @@ import { randomBytes } from "node:crypto";
16
16
  import { accessSync, closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
17
17
  import { homedir } from "node:os";
18
18
  import { dirname, join } from "node:path";
19
- import { bool } from "./cliArgs.js";
19
+ import { bool, value } from "./cliArgs.js";
20
+ import { HOLD_DEFAULT_SECONDS, HOLD_MAX_SECONDS, HOLD_TIMEOUT_MARGIN_SECONDS, holdOfCommand, parseHold } from "./cliHookHold.js";
20
21
  import { coveredByPlugin, pluginInstalled } from "./hookPlugin.js";
21
22
  import { syncNative } from "./nativeSync.js";
22
23
  import { credentialDir } from "./credentialStorage.js";
@@ -62,8 +63,8 @@ const CLIENTS = {
62
63
  path: cursorHooksPath
63
64
  }
64
65
  };
65
- const PASSPORT_COMMAND = /passport[^\s"']*["']?\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?\s*$/i;
66
- const VERB_TAIL = /^\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?\s*$/i;
66
+ const PASSPORT_COMMAND = /passport[^\s"']*["']?\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?(?:\s+--hold(?:\s+|=)\d{1,2})?\s*$/i;
67
+ const VERB_TAIL = /^\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?(?:\s+--hold(?:\s+|=)\d{1,2})?\s*$/i;
67
68
  /** "audit", "guard", or null. Recognises `passport hook`, an absolute path to
68
69
  * the installed CLI followed by the same verb, and the exact `node <entry>`
69
70
  * form this process registers when `passport` isn't on PATH, whatever
@@ -133,9 +134,21 @@ function passportInvocation(env, exists) {
133
134
  }
134
135
  /** The registered audit command. Without a client it stays the historical
135
136
  * `passport hook`, so older registrations still read as current. */
136
- export function hookCommand(env, exists = executable, client, kind = "audit", invocation) {
137
+ export function hookCommand(env, exists = executable, client, kind = "audit", invocation,
138
+ /** The guard's hold, in seconds (`cliHookHold.ts`); 0 writes no flag. */
139
+ hold = 0) {
137
140
  const verb = kind === "guard" ? "hook guard" : "hook";
138
- return `${invocation ?? passportInvocation(env, exists)} ${verb}${client ? ` --client ${client}` : ""}`;
141
+ const held = kind === "guard" && hold > 0 ? ` --hold ${hold}` : "";
142
+ return `${invocation ?? passportInvocation(env, exists)} ${verb}${client ? ` --client ${client}` : ""}${held}`;
143
+ }
144
+ /** Agents whose hook can answer allow, so a held command can run when approved. */
145
+ function holdsFor(spec, hold) {
146
+ return spec.id === "claude-code" ? hold : 0; // Codex can't run it; Cursor's timeout behaviour is undocumented.
147
+ }
148
+ /** The entry's timeout: long enough that the agent never kills a hold first. */
149
+ function timeoutFor(command) {
150
+ const hold = holdOfCommand(command);
151
+ return hold > 0 ? hold + HOLD_TIMEOUT_MARGIN_SECONDS : HOOK_TIMEOUT_SECONDS;
139
152
  }
140
153
  /** A shell-safe `node <entry>` prefix for a hook command. */
141
154
  export function nodeInvocation(node, entry) {
@@ -238,6 +251,14 @@ function registeredAt(spec, settings, slot) {
238
251
  const found = commandsIn(spec, settings, slot.event).find(isOurs(slot.kind));
239
252
  return typeof found === "string" ? found : null;
240
253
  }
254
+ /** Passport's entry on one event, with its timeout. */
255
+ function entryAt(spec, settings, event, kind) {
256
+ const list = listOf(settings, event);
257
+ const entries = spec.format === "cursor"
258
+ ? list
259
+ : list.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []));
260
+ return entries.find((entry) => isOurs(kind)(entry?.command)) ?? null;
261
+ }
241
262
  /** Whether a kind is on: its primary event holds Passport's entry. */
242
263
  function registered(spec, settings, kind) {
243
264
  return registeredAt(spec, settings, slotsOf(spec, kind)[0]);
@@ -254,12 +275,12 @@ function withEntry(spec, settings, slot, command) {
254
275
  if (spec.format === "cursor") {
255
276
  const at = list.findIndex((entry) => ours(entry?.command));
256
277
  const kept = list.filter((entry) => !ours(entry?.command));
257
- const fresh = { command, timeout: HOOK_TIMEOUT_SECONDS };
278
+ const fresh = { command, timeout: timeoutFor(command) };
258
279
  hooks[event] = at === -1 ? [...kept, fresh] : [...kept.slice(0, at), fresh, ...kept.slice(at)];
259
280
  const version = typeof settings.version === "number" ? settings.version : 1;
260
281
  return { ...settings, version, hooks };
261
282
  }
262
- const entry = { type: "command", command, timeout: HOOK_TIMEOUT_SECONDS };
283
+ const entry = { type: "command", command, timeout: timeoutFor(command) };
263
284
  const groups = list;
264
285
  // An older Passport entry (another version's path) is replaced where it stands.
265
286
  const owner = groups.findIndex((group) => group && Array.isArray(group.hooks) && group.hooks.some((candidate) => ours(candidate?.command)));
@@ -352,17 +373,23 @@ function previewResult(spec, action, path, changes, guard, verbose = false) {
352
373
  ].join("\n")
353
374
  };
354
375
  }
355
- function wantedEntries(spec, env, guard, invocation) {
376
+ function wantedEntries(spec, env, guard, invocation, hold = HOLD_DEFAULT_SECONDS) {
356
377
  // Claude Code is the historical default and is recognised from its input, so
357
378
  // its commands stay unqualified and existing registrations stay current.
358
379
  const named = spec.id === "claude-code" ? undefined : spec.id;
359
- return (guard ? ["guard", "audit"] : ["audit"]).flatMap((kind) => slotsOf(spec, kind).map((slot) => ({ ...slot, command: hookCommand(env, undefined, named, kind, invocation) })));
380
+ return (guard ? ["guard", "audit"] : ["audit"]).flatMap((kind) => slotsOf(spec, kind).map((slot) => ({
381
+ ...slot,
382
+ command: hookCommand(env, undefined, named, kind, invocation, holdsFor(spec, hold))
383
+ })));
360
384
  }
361
385
  function pendingChanges(spec, settings, wanted) {
362
386
  const changes = [];
363
387
  for (const entry of wanted) {
364
388
  const current = registeredAt(spec, settings, entry);
365
- if (current === entry.command)
389
+ // A timeout shorter than the entry needs (hand-edited) is fixed too.
390
+ const timeout = entryAt(spec, settings, entry.event, entry.kind)?.timeout;
391
+ const short = typeof timeout === "number" && timeout < timeoutFor(entry.command);
392
+ if (current === entry.command && !short)
366
393
  continue;
367
394
  changes.push({ action: current ? "update" : "add", event: entry.event, command: entry.command });
368
395
  }
@@ -402,8 +429,14 @@ function installClient(spec, args, runtime) {
402
429
  };
403
430
  }
404
431
  const { settings } = readSettings(path);
405
- const guard = bool(args, "guard");
406
- const wanted = wantedEntries(spec, runtime.env, guard);
432
+ // A guard already on is kept current too (its hold), with or without --guard.
433
+ const guard = bool(args, "guard") || registered(spec, settings, "guard") !== null;
434
+ const holdFlag = value(args, "hold");
435
+ const hold = holdFlag === undefined ? HOLD_DEFAULT_SECONDS : parseHold(holdFlag);
436
+ if (hold === null) {
437
+ return failure(`--hold takes whole seconds from 0 to ${HOLD_MAX_SECONDS}.`, 6, "usage");
438
+ }
439
+ const wanted = wantedEntries(spec, runtime.env, guard, undefined, hold);
407
440
  const changes = pendingChanges(spec, settings, wanted);
408
441
  const guarded = guard || registered(spec, settings, "guard") !== null;
409
442
  if (!changes.length) {
@@ -515,6 +548,19 @@ function clientStatus(spec, env) {
515
548
  agentPresent: existsSync(dirname(path))
516
549
  };
517
550
  }
551
+ /** One agent's guard entry, its command and timeout; null when off or unreadable. Never throws. */
552
+ export function guardEntryOf(client, env) {
553
+ try {
554
+ const spec = CLIENTS[client];
555
+ if (pluginInstalled(client, env))
556
+ return null;
557
+ const found = entryAt(spec, readSettings(spec.path(env)).settings, spec.pre, "guard");
558
+ return found && typeof found.command === "string" ? { command: found.command, timeout: found.timeout } : null;
559
+ }
560
+ catch {
561
+ return null;
562
+ }
563
+ }
518
564
  export function hookRegistration(action, client, args, runtime) {
519
565
  if (action === "status") {
520
566
  // `hook status` lives in cliHookStatus.ts (cliHook.ts sends it there).
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The command key an approval binds to: the governed part of a command line,
3
+ * normalized so an agent's equivalent retry finds the same approval.
4
+ *
5
+ * Quoting is read by the shell parser, so `'release/old'` and `release/old`
6
+ * are one word. Dropped, because they never change what the command does: a
7
+ * pipe into a read-only filter whose every flag is on that filter's harmless
8
+ * list (`| tail -5`, `| grep -v hint`), `2>&1`, output sent to /dev/null, and
9
+ * a trailing `|| true`. Everything else stays: `cd`, flag order, every
10
+ * argument, env assignments, and any filter with a flag that could write a
11
+ * file or run a program (`| sort -o out`, `| rg --pre ./prog`).
12
+ *
13
+ * Secrets go first: every word and redirect target is redacted on its own,
14
+ * exactly as the summary redacts (`cliHookRedact.ts`), before anything is
15
+ * quoted or joined. Then a fail-closed check: if any piece the summary would
16
+ * hide still shows in the key, the key is the redacted summary instead. A
17
+ * line the parser can't read flatly (substitutions, a heredoc) keys on its
18
+ * redacted summary too. A key longer than the server takes is sent as a
19
+ * SHA-256 of the whole key, so nothing past a cut is lost. The server hashes
20
+ * the key again; it is never shown or stored as text.
21
+ */
22
+ /** What the server accepts as a key; anything longer is hashed here. */
23
+ export declare const COMMAND_KEY_MAX = 400;
24
+ /** The normalized, redacted key, or undefined for an empty line. Never throws. */
25
+ export declare function commandKey(command: string): string | undefined;