passport-bridge 0.18.0 → 0.19.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.
@@ -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;
@@ -0,0 +1,160 @@
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
+ import { createHash } from "node:crypto";
23
+ import { basename, splitCommands } from "./cliHookParse.js";
24
+ import { maskedFragments, redactCommand, redactWords } from "./cliHookRedact.js";
25
+ /** What the server accepts as a key; anything longer is hashed here. */
26
+ export const COMMAND_KEY_MAX = 400;
27
+ /** Filters that only read what the command before them prints, and the flags that keep them that way. */
28
+ const READ_FILTERS = {
29
+ head: { letters: "q", valued: ["-n", "-c", "--lines", "--bytes"], arguments: 0, count: true },
30
+ tail: { letters: "qfF", valued: ["-n", "-c", "--lines", "--bytes"], arguments: 0, count: true },
31
+ grep: {
32
+ letters: "ivEFwxcnoqshHlLG",
33
+ valued: ["-e", "-A", "-B", "-C", "-m", "--max-count"],
34
+ long: ["--color", "--line-buffered", "--ignore-case", "--invert-match"],
35
+ arguments: 1
36
+ },
37
+ egrep: { letters: "ivwxcnoqshH", valued: ["-e", "-A", "-B", "-C", "-m"], arguments: 1 },
38
+ fgrep: { letters: "ivwxcnoqshH", valued: ["-e", "-A", "-B", "-C", "-m"], arguments: 1 },
39
+ rg: {
40
+ letters: "ivFwxcnNoqS",
41
+ valued: ["-e", "-A", "-B", "-C", "-m", "--max-count"],
42
+ long: ["--color", "--no-heading", "--line-buffered"],
43
+ arguments: 1
44
+ },
45
+ jq: { letters: "rcejSMCa", valued: [], long: ["--raw-output", "--compact-output", "--sort-keys"], arguments: 1 },
46
+ wc: { letters: "lcwm", valued: [], arguments: 0 },
47
+ sort: { letters: "nruhVfbM", valued: ["-k", "-t", "--key", "--field-separator"], arguments: 0 },
48
+ uniq: { letters: "cdui", valued: [], arguments: 0 },
49
+ cat: { letters: "nAvbsTE", valued: [], arguments: 0 }
50
+ };
51
+ const NO_OP = new Set(["true", ":"]);
52
+ /** Whether a filter's words (after its name) use only harmless flags and arguments. */
53
+ function harmlessFilter(spec, words) {
54
+ let plain = 0;
55
+ for (let index = 0; index < words.length; index++) {
56
+ const word = words[index];
57
+ if (spec.count && /^-\d+$/.test(word))
58
+ continue;
59
+ const valued = spec.valued.find((flag) => word === flag || word.startsWith(flag.startsWith("--") ? `${flag}=` : flag));
60
+ if (valued) {
61
+ if (word === valued)
62
+ index++;
63
+ continue;
64
+ }
65
+ if (spec.long?.some((flag) => word === flag || word.startsWith(`${flag}=`)))
66
+ continue;
67
+ if (/^-[A-Za-z]+$/.test(word)) {
68
+ if ([...word.slice(1)].every((letter) => spec.letters.includes(letter)))
69
+ continue;
70
+ return false;
71
+ }
72
+ if (word.startsWith("-"))
73
+ return false;
74
+ plain++;
75
+ }
76
+ return plain <= spec.arguments;
77
+ }
78
+ /** `2>&1`, `>/dev/null`, `2>/dev/null`, `&>/dev/null`: where output goes, not what runs. */
79
+ function quiet(redirect) {
80
+ if (redirect.op === "2>&" && !redirect.target)
81
+ return true;
82
+ return /^(?:\d?>|&>|\d?>>)$/.test(redirect.op) && redirect.target?.text === "/dev/null";
83
+ }
84
+ function quotedWord(word) {
85
+ return /[\s"'\\|&;<>()$`]/.test(word) || word === "" ? JSON.stringify(word) : word;
86
+ }
87
+ function assignment(word) {
88
+ return /^[A-Za-z_][A-Za-z0-9_]*=/.test(word);
89
+ }
90
+ /** A pipe into a read-only filter that only reads: safe to leave out of the key. */
91
+ function droppableFilter(shape) {
92
+ const texts = shape.words.map((word) => word.text);
93
+ if (!texts.length || assignment(texts[0]))
94
+ return false;
95
+ const spec = READ_FILTERS[basename(texts[0])];
96
+ return Boolean(spec) && shape.redirects.every(quiet) && harmlessFilter(spec, texts.slice(1));
97
+ }
98
+ /** The governed parts, each redacted word by word, then the operators between them. */
99
+ function normalizedParts(shapes) {
100
+ const parts = [];
101
+ const plain = [];
102
+ for (let index = 0; index < shapes.length; index++) {
103
+ const shape = shapes[index];
104
+ const after = index > 0 ? shapes[index - 1].next : "";
105
+ const last = index === shapes.length - 1;
106
+ const filter = after === "|" && parts.length > 0 && droppableFilter(shape);
107
+ const trailingNoOp = after === "||" && last && shape.words.length === 1 && NO_OP.has(shape.words[0].text);
108
+ if (filter || trailingNoOp) {
109
+ // The operator after the dropped part now follows the part before it.
110
+ parts[parts.length - 1].next = shape.next;
111
+ continue;
112
+ }
113
+ const words = redactWords(shape.words.map((word) => word.text));
114
+ const redirects = shape.redirects
115
+ .filter((redirect) => !quiet(redirect))
116
+ .map((redirect) => {
117
+ const target = redirect.target ? redactWords([redirect.target.text])[0] : "";
118
+ return { op: redirect.op, target };
119
+ });
120
+ plain.push(...words, ...redirects.map((redirect) => redirect.target));
121
+ const text = [
122
+ ...words.map(quotedWord),
123
+ ...redirects.map((redirect) => `${redirect.op}${redirect.target ? quotedWord(redirect.target) : ""}`)
124
+ ].join(" ");
125
+ if (text)
126
+ parts.push({ text, next: shape.next });
127
+ }
128
+ return { plain, parts };
129
+ }
130
+ /** Within the server's limit, or a hash of the whole key. */
131
+ function bounded(key) {
132
+ return key.length <= COMMAND_KEY_MAX ? key : `sha256:${createHash("sha256").update(key).digest("hex")}`;
133
+ }
134
+ /** The normalized, redacted key, or undefined for an empty line. Never throws. */
135
+ export function commandKey(command) {
136
+ try {
137
+ const summary = () => {
138
+ const redacted = redactCommand(command);
139
+ return redacted ? bounded(redacted) : undefined;
140
+ };
141
+ const split = splitCommands(command);
142
+ if (split.nested.length || split.flags.heredoc || split.flags.processSubstitution)
143
+ return summary();
144
+ const { plain, parts } = normalizedParts(split.shapes);
145
+ if (!parts.length)
146
+ return undefined;
147
+ const key = parts
148
+ .map((part, index) => (index < parts.length - 1 && part.next !== "end" ? `${part.text} ${part.next}` : part.text))
149
+ .join(" ");
150
+ // Fail closed: anything the summary would hide must not show in the key.
151
+ const hidden = maskedFragments(command);
152
+ const words = plain.join(" ");
153
+ if (hidden.some((piece) => key.includes(piece) || words.includes(piece)))
154
+ return summary();
155
+ return bounded(key);
156
+ }
157
+ catch {
158
+ return undefined;
159
+ }
160
+ }
@@ -14,3 +14,16 @@ export declare const SUMMARY_MAX = 300;
14
14
  * heredoc bodies dropped, and the length bounded. Never throws.
15
15
  */
16
16
  export declare function redactCommand(command: string): string;
17
+ /**
18
+ * The same redaction over words a shell parser already unquoted (the command
19
+ * key's words, `cliHookKey.ts`): a secret flag hides the word after it, and
20
+ * every word is redacted on its own. One output word per input word.
21
+ */
22
+ export declare function redactWords(texts: readonly string[]): string[];
23
+ /**
24
+ * Every piece of a command line the summary's redaction would hide, on every
25
+ * line (not only the first): a check that nothing hidden there shows up in
26
+ * another rendering of the same command. Pieces under 4 characters are left
27
+ * out (too common to mean anything). Never throws.
28
+ */
29
+ export declare function maskedFragments(command: string): string[];
@@ -134,3 +134,63 @@ export function redactCommand(command) {
134
134
  return "";
135
135
  }
136
136
  }
137
+ /**
138
+ * The same redaction over words a shell parser already unquoted (the command
139
+ * key's words, `cliHookKey.ts`): a secret flag hides the word after it, and
140
+ * every word is redacted on its own. One output word per input word.
141
+ */
142
+ export function redactWords(texts) {
143
+ const out = [];
144
+ for (let index = 0; index < texts.length; index++) {
145
+ const word = texts[index];
146
+ out.push(redactWord(word).replace(KEY_PREFIX, HIDDEN));
147
+ if (secretFlag(word) && !word.includes("=") && index + 1 < texts.length) {
148
+ out.push(HIDDEN);
149
+ index++;
150
+ }
151
+ }
152
+ return out;
153
+ }
154
+ /** The raw text a redacted word hid: the gaps between what it kept. */
155
+ function hiddenGaps(raw, redacted) {
156
+ if (!redacted.includes(HIDDEN))
157
+ return [];
158
+ const kept = redacted.split(HIDDEN);
159
+ const gaps = [];
160
+ let at = raw.startsWith(kept[0]) ? kept[0].length : 0;
161
+ for (let index = 1; index < kept.length; index++) {
162
+ const part = kept[index];
163
+ const next = index === kept.length - 1 && part ? raw.lastIndexOf(part) : part ? raw.indexOf(part, at) : raw.length;
164
+ const end = next < at ? raw.length : next;
165
+ gaps.push(raw.slice(at, end));
166
+ at = end + part.length;
167
+ }
168
+ return gaps;
169
+ }
170
+ /**
171
+ * Every piece of a command line the summary's redaction would hide, on every
172
+ * line (not only the first): a check that nothing hidden there shows up in
173
+ * another rendering of the same command. Pieces under 4 characters are left
174
+ * out (too common to mean anything). Never throws.
175
+ */
176
+ export function maskedFragments(command) {
177
+ try {
178
+ const out = [];
179
+ for (const line of command.split("\n")) {
180
+ const tokens = words(line.replace(/[\u0000-\u001f\u007f]/g, " "));
181
+ for (let index = 0; index < tokens.length; index++) {
182
+ const token = tokens[index];
183
+ const bare = token.replace(/^['"]|['"]$/g, "");
184
+ if (secretFlag(bare) && !bare.includes("=") && index + 1 < tokens.length) {
185
+ out.push(tokens[++index].replace(/^['"]|['"]$/g, ""));
186
+ continue;
187
+ }
188
+ out.push(...hiddenGaps(token, redactWord(token).replace(KEY_PREFIX, HIDDEN)));
189
+ }
190
+ }
191
+ return out.map((piece) => piece.replace(/^['"]+|['"]+$/g, "")).filter((piece) => piece.length >= 4);
192
+ }
193
+ catch {
194
+ return [];
195
+ }
196
+ }
package/dist/cliMain.js CHANGED
@@ -531,6 +531,23 @@ async function dispatch(args, runtime) {
531
531
  return versionResult(args, runtime.env);
532
532
  }
533
533
  }
534
+ /** Commands an agent or script runs: never followed by a notice. */
535
+ const NO_NOTICE = new Set(["hook", "session", "completion", "version", "wait", "exec", "run", "doctor"]);
536
+ /** On a terminal, after a person's command: how to turn the guard's hold on, at most daily. */
537
+ async function holdNoticeAfter(args, runtime) {
538
+ try {
539
+ if (NO_NOTICE.has(args.command) || bool(args, "json") || bool(args, "quiet"))
540
+ return;
541
+ if (!runtime.stderr.isTTY)
542
+ return;
543
+ const notice = (await import("./holdNotice.js")).takeHoldNotice(VERSION, runtime.env);
544
+ if (notice)
545
+ runtime.stderr.write(`${notice}\n`);
546
+ }
547
+ catch {
548
+ /* A notice never changes a command's outcome. */
549
+ }
550
+ }
534
551
  export async function main(argv = process.argv.slice(2), env = process.env, io = {
535
552
  stdin: process.stdin,
536
553
  stdout: process.stdout,
@@ -554,6 +571,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, io =
554
571
  const result = await dispatch(args, runtime);
555
572
  if (args.command !== "session")
556
573
  emitResult(result, args, runtime);
574
+ await holdNoticeAfter(args, runtime);
557
575
  return result.exitCode ?? 0;
558
576
  }
559
577
  catch (error) {
package/dist/cliOutput.js CHANGED
@@ -39,7 +39,7 @@ const EXAMPLES = {
39
39
  ["passport status --json", "The same as one JSON object"]
40
40
  ],
41
41
  wait: [
42
- ["passport wait apr_123", "Wait up to 100 seconds for a decision"],
42
+ ["passport wait apr_123", "Wait for a decision on an approval"],
43
43
  ["passport wait apr_123 --timeout 300", "Wait up to five minutes"]
44
44
  ],
45
45
  rules: [
@@ -118,7 +118,7 @@ function helpText(verb) {
118
118
  profiles: "passport profiles\nLists saved profiles and marks the active profile. Works offline.",
119
119
  use: "passport use <name>\nSelects a saved profile as the default for subsequent commands. Works offline.",
120
120
  status: "passport status\nShows you, your workspace, and this computer; each agent's guard and its fix; Autopilot presets, team floors, and how old this computer's copy of your rules is; apps; keys Passport holds and when each was last used; this folder's environments; and the CLI version.\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}],autopilot?:{presets,floors,cache},computer,keys?,folder,cli}",
121
- wait: "passport wait <approval-id> [--timeout <sec>]\nWaits for a person to decide an approval request (default 100 seconds). While it is still waiting, prints the approval link; on a terminal, one live line counts down. Ctrl-C stops waiting and the request stays open (exit 4).\n Approved: prints who approved it; run the command again. Exit 0.\n Declined: prints the note for the agent. Exit 5.\n Expired: the agent can ask again. Exit 5.\n Still waiting at the timeout: exit 4; run it again.",
121
+ wait: "passport wait <approval-id> [--timeout <sec>]\nWaits for a person to decide an approval request, until they do or it expires. Agents run it as a background command. While it is still waiting, prints the approval link; on a terminal, one live line counts down. Ctrl-C stops waiting and the request stays open (exit 4).\n Approved: prints who approved it and for how long; run the command again. Exit 0.\n Declined: prints the person's note for the agent. Exit 5.\n Expired: run the command again to ask again. Exit 5.\n Still waiting at --timeout: exit 4; run it again.",
122
122
  rules: 'passport rules test "<command>" [--environment production|staging|development]\nShows what Autopilot decides for a command, why, and which environment it acts on. The command is read on this computer; only its app and verb are sent to Passport.',
123
123
  actions: "passport actions\npassport actions add <script> [args…] --environment production|staging|development --class read|change|delete|irreversible [--args <glob>]\npassport actions add --id <op_…> --environment <kind> --class <class>\npassport actions sync\nTells Passport what a project script does, so the guard checks it: its environment and action class. Your presets and exceptions still decide what runs; a project script never runs on its say-so alone. <script> is a file in the project, or make, npm, pnpm, or yarn with the target or script name. --args is a glob over its arguments (* is any). --id is the id a Session row shows under \"Tell Passport what this does\"; this computer resolves it, since the script's name never left it. sync proposes each entry of the project's .passport/actions.toml. You can say Production for a change, delete, or irreversible action; anything else waits for an admin in Rules › Environments › Project scripts. Sends the script's path in the repository, the repository's fingerprint and name, and a SHA-256 of what it runs, never its contents.\nJSON: {action} | {actions:[…]}",
124
124
  // copy-style-allow double-space: help columns line up