passport-bridge 0.16.3 → 0.16.6

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 (80) hide show
  1. package/README.md +17 -8
  2. package/dist/accessTokenCache.d.ts +54 -0
  3. package/dist/accessTokenCache.js +163 -0
  4. package/dist/bridgeExchange.d.ts +6 -0
  5. package/dist/bridgeExchange.js +5 -0
  6. package/dist/cliAnswered.d.ts +5 -0
  7. package/dist/cliAnswered.js +27 -2
  8. package/dist/cliAutopilot.d.ts +10 -2
  9. package/dist/cliAutopilot.js +12 -32
  10. package/dist/cliAutopilotPolicy.d.ts +7 -0
  11. package/dist/cliCodexTrust.d.ts +42 -0
  12. package/dist/cliCodexTrust.js +145 -0
  13. package/dist/cliEnv.d.ts +9 -2
  14. package/dist/cliEnv.js +30 -20
  15. package/dist/cliExec.d.ts +2 -8
  16. package/dist/cliExec.js +12 -22
  17. package/dist/cliExecGuard.d.ts +10 -0
  18. package/dist/cliExecGuard.js +36 -0
  19. package/dist/cliGuardHealth.d.ts +40 -0
  20. package/dist/cliGuardHealth.js +191 -0
  21. package/dist/cliGuardState.d.ts +60 -0
  22. package/dist/cliGuardState.js +121 -0
  23. package/dist/cliHook.d.ts +3 -58
  24. package/dist/cliHook.js +107 -145
  25. package/dist/cliHookDecide.d.ts +13 -0
  26. package/dist/cliHookDecide.js +35 -2
  27. package/dist/cliHookDeliver.d.ts +137 -0
  28. package/dist/cliHookDeliver.js +271 -0
  29. package/dist/cliHookExtras.d.ts +26 -0
  30. package/dist/cliHookExtras.js +34 -0
  31. package/dist/cliHookGuard.d.ts +6 -3
  32. package/dist/cliHookGuard.js +15 -3
  33. package/dist/cliHookInstall.d.ts +14 -0
  34. package/dist/cliHookInstall.js +9 -69
  35. package/dist/cliHookRewrite.js +1 -1
  36. package/dist/cliHookStatus.d.ts +18 -0
  37. package/dist/cliHookStatus.js +111 -0
  38. package/dist/cliInit.d.ts +3 -0
  39. package/dist/cliInit.js +17 -5
  40. package/dist/cliKeys.d.ts +8 -0
  41. package/dist/cliKeys.js +71 -20
  42. package/dist/cliKeysBack.d.ts +41 -0
  43. package/dist/cliKeysBack.js +124 -0
  44. package/dist/cliPolicy.d.ts +3 -0
  45. package/dist/cliPolicy.js +17 -0
  46. package/dist/cliPolicyV2.js +24 -3
  47. package/dist/cliSeen.d.ts +40 -0
  48. package/dist/cliSeen.js +203 -0
  49. package/dist/cliSpeed.d.ts +104 -0
  50. package/dist/cliSpeed.js +320 -0
  51. package/dist/cliStatusGuard.d.ts +28 -0
  52. package/dist/cliStatusGuard.js +77 -0
  53. package/dist/credentials.d.ts +3 -1
  54. package/dist/credentials.js +14 -0
  55. package/dist/envResolve.d.ts +9 -5
  56. package/dist/envResolve.js +27 -8
  57. package/dist/execTarget.d.ts +8 -0
  58. package/dist/execTarget.js +28 -0
  59. package/dist/fastPathFlag.d.ts +38 -0
  60. package/dist/fastPathFlag.js +90 -0
  61. package/dist/hookFastPath.d.ts +44 -0
  62. package/dist/hookFastPath.js +239 -0
  63. package/dist/hookMain.d.ts +2 -0
  64. package/dist/hookMain.js +53 -0
  65. package/dist/hookOutbox.d.ts +27 -0
  66. package/dist/hookOutbox.js +176 -0
  67. package/dist/initAutopilotStep.js +6 -8
  68. package/dist/initInstall.d.ts +6 -3
  69. package/dist/initInstall.js +44 -5
  70. package/dist/initKeysStep.js +5 -0
  71. package/dist/initUi.d.ts +10 -0
  72. package/dist/initUi.js +27 -0
  73. package/dist/launcherFastPath.d.ts +52 -0
  74. package/dist/launcherFastPath.js +350 -0
  75. package/dist/pluginPin.d.ts +1 -1
  76. package/dist/pluginPin.js +1 -1
  77. package/dist/version.d.ts +1 -1
  78. package/dist/version.js +1 -1
  79. package/npm-shrinkwrap.json +6 -6
  80. package/package.json +4 -3
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Whether Codex trusts Passport's guard hook (Batch A, "Not trusted").
3
+ *
4
+ * Codex runs a hook from `~/.codex/hooks.json` only after the person trusts
5
+ * it in `/hooks`. It then stores, in `~/.codex/config.toml`,
6
+ *
7
+ * [hooks.state."<hooks.json path>:pre_tool_use:<group>:<handler>"]
8
+ * trusted_hash = "sha256:<hex>"
9
+ *
10
+ * and runs the hook only while that hash matches the hook as written now. The
11
+ * hash input, confirmed in openai/codex (codex-rs/hooks/src/engine/discovery.rs
12
+ * `hook_hash`, codex-rs/config/src/fingerprint.rs `version_for_toml`) and
13
+ * against codex-cli 0.146.0's `hooks/list`, is the normalized identity
14
+ * `{ event_name, matcher?, hooks: [handler] }`, where the handler is
15
+ * `{ type: "command", command, timeout (default 600), async (default false),
16
+ * statusMessage?, additionalContextLimit? (when not 2500) }`, serialized as
17
+ * JSON with every object's keys sorted, no whitespace, then SHA-256.
18
+ *
19
+ * Read-only: Passport never writes Codex's trust; only the person can.
20
+ */
21
+ import { createHash } from "node:crypto";
22
+ import { readFileSync } from "node:fs";
23
+ import { dirname, join, resolve } from "node:path";
24
+ const MAX_BYTES = 1024 * 1024;
25
+ const DEFAULT_TIMEOUT_SEC = 600;
26
+ const DEFAULT_CONTEXT_LIMIT = 2500;
27
+ function sortDeep(value) {
28
+ if (Array.isArray(value))
29
+ return value.map(sortDeep);
30
+ if (value && typeof value === "object") {
31
+ return Object.fromEntries(Object.keys(value)
32
+ .sort()
33
+ .map((key) => [key, sortDeep(value[key])]));
34
+ }
35
+ return value;
36
+ }
37
+ /** Codex's trust hash for one PreToolUse command handler. */
38
+ export function codexHookHash(matcher, handler) {
39
+ const timeout = typeof handler.timeout === "number" && Number.isFinite(handler.timeout)
40
+ ? Math.max(1, Math.floor(handler.timeout))
41
+ : DEFAULT_TIMEOUT_SEC;
42
+ const normalized = {
43
+ type: "command",
44
+ command: handler.command,
45
+ timeout,
46
+ async: handler.async === true
47
+ };
48
+ if (typeof handler.statusMessage === "string")
49
+ normalized.statusMessage = handler.statusMessage;
50
+ if (typeof handler.additionalContextLimit === "number" && handler.additionalContextLimit !== DEFAULT_CONTEXT_LIMIT) {
51
+ normalized.additionalContextLimit = handler.additionalContextLimit;
52
+ }
53
+ const identity = { event_name: "pre_tool_use", hooks: [normalized] };
54
+ if (typeof matcher === "string")
55
+ identity.matcher = matcher;
56
+ return `sha256:${createHash("sha256")
57
+ .update(JSON.stringify(sortDeep(identity)))
58
+ .digest("hex")}`;
59
+ }
60
+ function readBounded(path) {
61
+ try {
62
+ const raw = readFileSync(path, "utf8");
63
+ return Buffer.byteLength(raw) > MAX_BYTES ? null : raw;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /** Where Passport's guard sits in hooks.json: its group and handler index. */
70
+ export function findGuardEntry(settings, isGuard) {
71
+ const hooks = settings?.hooks;
72
+ const groups = hooks && Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse : [];
73
+ for (let group = 0; group < groups.length; group++) {
74
+ const value = groups[group];
75
+ const handlers = value && Array.isArray(value.hooks) ? value.hooks : [];
76
+ for (let handler = 0; handler < handlers.length; handler++) {
77
+ const entry = handlers[handler];
78
+ if (entry && (entry.type === undefined || entry.type === "command") && isGuard(entry.command)) {
79
+ return {
80
+ group,
81
+ handler,
82
+ ...(typeof value?.matcher === "string" ? { matcher: value.matcher } : {}),
83
+ entry
84
+ };
85
+ }
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ /** A TOML basic string's contents, unescaped (the forms Codex writes). */
91
+ function unquote(body) {
92
+ return body.replace(/\\(["\\/bfnrt])/g, (_match, char) => char === "b" ? "\b" : char === "f" ? "\f" : char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? "\t" : char);
93
+ }
94
+ /** `[hooks.state."<key>"]` tables in config.toml: each key's trusted hash and enabled flag. */
95
+ export function codexHookStates(toml) {
96
+ const states = new Map();
97
+ let current = null;
98
+ for (const raw of toml.split(/\r?\n/)) {
99
+ const line = raw.trim();
100
+ if (line.startsWith("[")) {
101
+ const header = /^\[\s*hooks\s*\.\s*state\s*\.\s*"((?:[^"\\]|\\.)*)"\s*\]$/.exec(line);
102
+ current = header ? { ...(states.get(unquote(header[1])) ?? {}) } : null;
103
+ if (header)
104
+ states.set(unquote(header[1]), current);
105
+ continue;
106
+ }
107
+ if (!current)
108
+ continue;
109
+ const hash = /^trusted_hash\s*=\s*"((?:[^"\\]|\\.)*)"/.exec(line);
110
+ if (hash)
111
+ current.trustedHash = unquote(hash[1]);
112
+ const enabled = /^enabled\s*=\s*(true|false)\b/.exec(line);
113
+ if (enabled)
114
+ current.enabled = enabled[1] === "true";
115
+ }
116
+ return states;
117
+ }
118
+ /**
119
+ * Codex's trust in Passport's guard entry in `hooksPath`, or undefined when
120
+ * the file holds no guard entry (nothing to trust).
121
+ */
122
+ export function codexGuardTrust(hooksPath, isGuard) {
123
+ const raw = readBounded(hooksPath);
124
+ if (raw === null)
125
+ return undefined;
126
+ let settings;
127
+ try {
128
+ settings = JSON.parse(raw);
129
+ }
130
+ catch {
131
+ return undefined;
132
+ }
133
+ const found = findGuardEntry(settings, isGuard);
134
+ if (!found)
135
+ return undefined;
136
+ const absolute = resolve(hooksPath);
137
+ const key = `${absolute}:pre_tool_use:${found.group}:${found.handler}`;
138
+ const states = codexHookStates(readBounded(join(dirname(absolute), "config.toml")) ?? "");
139
+ const state = states.get(key);
140
+ if (state?.enabled === false)
141
+ return "disabled";
142
+ if (!state?.trustedHash)
143
+ return "untrusted";
144
+ return state.trustedHash === codexHookHash(found.matcher, found.entry) ? "trusted" : "modified";
145
+ }
package/dist/cliEnv.d.ts CHANGED
@@ -28,6 +28,8 @@ export type EnvRow = {
28
28
  how: string;
29
29
  kind: string;
30
30
  assumed: boolean;
31
+ /** Placed by the naming rule: `staging` is Staging. */
32
+ named?: boolean;
31
33
  note?: string;
32
34
  };
33
35
  /** One row per linked vendor, as the table and `--json` show it. */
@@ -35,6 +37,11 @@ export declare function envRows(links: DetectedLink[]): EnvRow[];
35
37
  /** The links in this folder, placed with this computer's copy of the rules. */
36
38
  export declare function linksHere(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): DetectedLink[];
37
39
  export declare const ENV_EMPTY = "No linked apps in this folder.";
38
- /** The Environments table `init` shows for this project. */
39
- export declare function envTableLines(rows: EnvRow[]): string[];
40
+ /**
41
+ * The Environments table `passport env` and `init` show, one string per line.
42
+ * Columns line up when every row fits in `width`; otherwise each row is
43
+ * stacked (app and resource, then how and environment) so nothing wraps into
44
+ * the next column.
45
+ */
46
+ export declare function envTableLines(rows: EnvRow[], width?: number): string[];
40
47
  export declare function env(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): Promise<CommandResult>;
package/dist/cliEnv.js CHANGED
@@ -19,13 +19,15 @@ import { readCliPolicy } from "./cliPolicy.js";
19
19
  import { NODE_LINK_FS } from "./envLinkFs.js";
20
20
  import { detectLinks } from "./envResolve.js";
21
21
  import { vendorName } from "./envTarget.js";
22
+ import { columns, wrapText } from "./initUi.js";
22
23
  import { callerFrom, failure, resolveCliAuth, safeApiError, timeoutMs } from "./cliSupport.js";
23
24
  const HOW = {
24
25
  flag: "flag",
25
26
  linked: "linked",
26
27
  "vendor-default": "default",
27
28
  mapping: "placed",
28
- name: "name",
29
+ // Found through the folder's link, then placed by its name.
30
+ name: "linked",
29
31
  assumed: "linked"
30
32
  };
31
33
  /** One row per linked vendor, as the table and `--json` show it. */
@@ -38,6 +40,7 @@ export function envRows(links) {
38
40
  how: target.problem ? "unreadable" : HOW[target.source],
39
41
  kind: target.kind,
40
42
  assumed,
43
+ ...(target.source === "name" ? { named: true } : {}),
41
44
  ...(target.problem
42
45
  ? { note: target.problem }
43
46
  : assumed
@@ -46,20 +49,16 @@ export function envRows(links) {
46
49
  };
47
50
  });
48
51
  }
49
- function table(rows) {
50
- const cells = rows.map((row) => [
51
- row.vendor,
52
- row.resource,
53
- row.how,
54
- `${ENV_LABEL[row.kind] ?? row.kind}${row.assumed ? " (assumed)" : ""}`
55
- ]);
56
- const header = ["App", "Resource", "How", "Environment"];
57
- const widths = header.map((title, index) => Math.max(title.length, ...cells.map((cell) => cell[index].length)));
58
- const line = (cell) => cell
59
- .map((part, index) => part.padEnd(widths[index]))
60
- .join(" ")
61
- .trimEnd();
62
- return [line(header), ...cells.map(line)].join("\n");
52
+ /** "Staging (from its name)", "Production (assumed)". */
53
+ function environmentCell(row) {
54
+ const label = ENV_LABEL[row.kind] ?? row.kind;
55
+ return `${label}${row.assumed ? " (assumed)" : row.named ? " (from its name)" : ""}`;
56
+ }
57
+ const HEADER = ["App", "Resource", "How", "Environment"];
58
+ /** A row too wide for the table: the app and resource, then how and where. */
59
+ function stacked(row, width) {
60
+ const detail = wrapText(`${row.how}, ${environmentCell(row)}`, Math.max(20, width - 2)).map((line) => ` ${line}`);
61
+ return [...wrapText(`${row.vendor} ${row.resource}`, width), ...detail];
63
62
  }
64
63
  function whereHere(runtime, deps) {
65
64
  const cwd = deps.cwd ?? process.cwd();
@@ -93,12 +92,21 @@ export function linksHere(args, runtime, deps = {}) {
93
92
  });
94
93
  }
95
94
  export const ENV_EMPTY = "No linked apps in this folder.";
96
- /** The Environments table `init` shows for this project. */
97
- export function envTableLines(rows) {
95
+ /**
96
+ * The Environments table `passport env` and `init` show, one string per line.
97
+ * Columns line up when every row fits in `width`; otherwise each row is
98
+ * stacked (app and resource, then how and environment) so nothing wraps into
99
+ * the next column.
100
+ */
101
+ export function envTableLines(rows, width = Number.POSITIVE_INFINITY) {
98
102
  if (!rows.length)
99
103
  return [ENV_EMPTY];
100
- const notes = rows.filter((row) => row.note).map((row) => `${row.vendor} ${row.resource}: ${row.note}`);
101
- return [table(rows), ...notes];
104
+ const cells = rows.map((row) => [row.vendor, row.resource, row.how, environmentCell(row)]);
105
+ const body = columns([HEADER, ...cells], width) ?? rows.flatMap((row) => stacked(row, width));
106
+ const notes = rows
107
+ .filter((row) => row.note)
108
+ .flatMap((row) => wrapText(`${row.vendor} ${row.resource}: ${row.note}`, width));
109
+ return [...body, ...notes];
102
110
  }
103
111
  async function setEnvironment(args, runtime, deps) {
104
112
  const [, vendor, resource, kind] = args.positionals;
@@ -150,8 +158,10 @@ export async function env(args, runtime, deps = {}) {
150
158
  if (action !== undefined)
151
159
  return failure("Use: passport env, or passport env set <vendor> <resource> <kind>.", 6, "usage");
152
160
  const rows = envRows(linksHere(args, runtime, deps));
161
+ const columnsHere = runtime.stdout?.columns;
162
+ const width = typeof columnsHere === "number" && columnsHere >= 40 ? columnsHere : undefined;
153
163
  return {
154
164
  json: { environments: rows, ...(value(args, "profile") ? { profile: value(args, "profile") } : {}) },
155
- human: envTableLines(rows).join("\n")
165
+ human: envTableLines(rows, width).join("\n")
156
166
  };
157
167
  }
package/dist/cliExec.d.ts CHANGED
@@ -24,6 +24,7 @@ import type { WhereContext } from "./envTarget.js";
24
24
  import { readCliPolicy } from "./cliPolicy.js";
25
25
  import { type CommandResult, type Runtime } from "./cliSupport.js";
26
26
  import { type ExecVendor } from "./execVendors.js";
27
+ import { execTarget } from "./execTarget.js";
27
28
  export declare const EXEC_AUTHORIZE_PATH = "/api/my/exec/authorize";
28
29
  export declare const EXEC_RESULT_PATH = "/api/my/exec/result";
29
30
  export declare const EXEC_WAIT_DEFAULT_SECONDS = 100;
@@ -54,13 +55,7 @@ type Authorized = {
54
55
  backup?: unknown;
55
56
  backupNote?: unknown;
56
57
  };
57
- /** Which vendor, or one line saying why exec won't run it. */
58
- export declare function execTarget(argv: readonly string[]): {
59
- vendor: ExecVendor;
60
- binary: string;
61
- } | {
62
- refused: string;
63
- };
58
+ export { execTarget };
64
59
  /** The classified finding the server decides on: vendor, verb, risk, environment. */
65
60
  export declare function execFinding(vendor: ExecVendor, binary: string, args: readonly string[], policy: ReturnType<typeof readCliPolicy>, where?: WhereContext): {
66
61
  vendor: string;
@@ -80,4 +75,3 @@ export declare function waitingLine(message: string, seconds: number): string;
80
75
  export declare function exec(args: ParsedArgs, runtime: Runtime, deps?: ExecDependencies): Promise<CommandResult>;
81
76
  /** One line after the run on the backup Passport took first, or couldn't. */
82
77
  export declare function backupLine(decided: Authorized, exitCode: number): string | undefined;
83
- export {};
package/dist/cliExec.js CHANGED
@@ -33,7 +33,8 @@ import { execBackupTarget } from "./execBackupTarget.js";
33
33
  import { readCliPolicy } from "./cliPolicy.js";
34
34
  import { noteExecVendor } from "./execMarker.js";
35
35
  import { CliFailure, callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, sleep, timeoutMs } from "./cliSupport.js";
36
- import { EXEC_ENV_NAMES, EXEC_PASSPORT_ENV, EXEC_SHADOWED_ENV, EXEC_VENDORS, EXEC_VENDOR_NAMES, EXEC_WRAPPERS, execVendorOf, refusedReason } from "./execVendors.js";
36
+ import { EXEC_ENV_NAMES, EXEC_PASSPORT_ENV, EXEC_SHADOWED_ENV, EXEC_VENDOR_NAMES, execVendorOf } from "./execVendors.js";
37
+ import { execTarget } from "./execTarget.js";
37
38
  import { findOnPath } from "./initInstall.js";
38
39
  export const EXEC_AUTHORIZE_PATH = "/api/my/exec/authorize";
39
40
  export const EXEC_RESULT_PATH = "/api/my/exec/result";
@@ -42,27 +43,7 @@ const WAIT_POLL_SECONDS = 30;
42
43
  const SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
43
44
  const RUNTIME = /^[a-z0-9-]{1,24}$/;
44
45
  const REPO = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
45
- const LIST = `${EXEC_VENDORS.filter((vendor) => vendor !== "flyctl").join(", ")}, and flyctl`;
46
- /** Which vendor, or one line saying why exec won't run it. */
47
- export function execTarget(argv) {
48
- const program = argv[0];
49
- if (!program)
50
- return { refused: "Use: passport exec -- <cli> [args…], for example passport exec -- railway up." };
51
- // A path could be any program; exec runs only the vendor CLI found on PATH.
52
- if (program.includes("/") || program.includes("\\")) {
53
- return { refused: `passport exec runs ${LIST} from your PATH, not a path like ${basename(program)}.` };
54
- }
55
- if (EXEC_WRAPPERS.has(program)) {
56
- return {
57
- refused: `passport exec runs ${LIST}. It won't run ${program}, which could run anything or print the key.`
58
- };
59
- }
60
- const vendor = execVendorOf(program);
61
- if (!vendor)
62
- return { refused: `passport exec runs ${LIST}. It won't run ${program}.` };
63
- const refused = refusedReason(vendor, argv.slice(1));
64
- return refused ? { refused } : { vendor, binary: program };
65
- }
46
+ export { execTarget };
66
47
  function quote(part) {
67
48
  return /^[A-Za-z0-9_@%+=:,./-]+$/.test(part) ? part : `'${part.replaceAll("'", `'\\''`)}'`;
68
49
  }
@@ -196,6 +177,11 @@ async function post(client, body, runtime, ms, binary) {
196
177
  }
197
178
  return offline(binary);
198
179
  }
180
+ if (response.status === 403) {
181
+ const refused = await (await import("./cliExecGuard.js")).guardRequiredFailure(response.clone());
182
+ if (refused)
183
+ return refused;
184
+ }
199
185
  if (response.status === 401 || response.status === 403) {
200
186
  return failure(await safeApiError(response, "Passport refused this sign-in. Nothing ran."), 2, "auth", {
201
187
  hint: "Run: passport login"
@@ -387,6 +373,10 @@ export async function exec(args, runtime, deps = {}) {
387
373
  throw error;
388
374
  }
389
375
  };
376
+ // Batch A: the daily guard report, so a team's Guard required sees this computer.
377
+ if (auth.kind === "profile" && !deps.api) {
378
+ await (await import("./cliExecGuard.js")).execHeartbeat(client.fetchApi, auth.profile, runtime.signal);
379
+ }
390
380
  const decided = await decide(ask, client, prepared, args, runtime, deps);
391
381
  if (decided.decision === "block") {
392
382
  const message = typeof decided.message === "string" ? decided.message : "Blocked by Passport.";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `passport exec` and Batch A. A team that requires the guard refuses exec
3
+ * for an agent whose guard isn't On (403 `guard_required`): the CLI prints the
4
+ * server's line and the same fix the web shows, and exits 5 like any block.
5
+ * Exec also sends this computer's daily guard report when one is due.
6
+ */
7
+ /** A guard-required refusal as a CLI failure, or null for any other 403. */
8
+ export declare function guardRequiredFailure(response: Response): Promise<never | null>;
9
+ /** The daily guard report from exec, best effort and bounded. */
10
+ export declare function execHeartbeat(api: (path: string, init: RequestInit) => Promise<Response>, profile: string | undefined, signal: AbortSignal): Promise<void>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `passport exec` and Batch A. A team that requires the guard refuses exec
3
+ * for an agent whose guard isn't On (403 `guard_required`): the CLI prints the
4
+ * server's line and the same fix the web shows, and exits 5 like any block.
5
+ * Exec also sends this computer's daily guard report when one is due.
6
+ */
7
+ import { readBoundedJson } from "./boundedResponse.js";
8
+ import { fixLine } from "./cliGuardState.js";
9
+ import { failure, sanitize } from "./cliSupport.js";
10
+ /** A guard-required refusal as a CLI failure, or null for any other 403. */
11
+ export async function guardRequiredFailure(response) {
12
+ let body;
13
+ try {
14
+ body = await readBoundedJson(response);
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ if (body.code !== "guard_required")
20
+ return null;
21
+ const fix = body.fix;
22
+ const message = typeof body.error === "string" ? sanitize(body.error) : "Blocked by Passport: guard required. Nothing ran.";
23
+ return failure(message, 5, "guard_required", {
24
+ ...(fix && typeof fix.text === "string" ? { hint: sanitize(fixLine(fix)) } : {}),
25
+ ...(fix && typeof fix.command === "string"
26
+ ? { next: [{ argv: fix.command.split(" "), description: sanitize(fix.text) }] }
27
+ : {})
28
+ });
29
+ }
30
+ /** The daily guard report from exec, best effort and bounded. */
31
+ export async function execHeartbeat(api, profile, signal) {
32
+ if (!profile)
33
+ return;
34
+ const { guardHeartbeat } = await import("./cliGuardHealth.js");
35
+ await guardHeartbeat(api, profile, process.env, AbortSignal.any([signal, AbortSignal.timeout(1_500)])).catch(() => undefined);
36
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Guard health (Batch A): what this computer's Passport CLI can see about each
3
+ * agent's guard, reported to Passport at most once a day so the Agent rows,
4
+ * Home, and the bell show it. Self-reported, read-only, and counts and flags
5
+ * only: never a command, a path, or a setting's value.
6
+ *
7
+ * Sent from a guard run that has 300 ms of its budget left, from
8
+ * `passport exec`, and from `passport status`.
9
+ */
10
+ import { type GuardClient, type GuardClientReport, type GuardHealthReport, type ProblemFix } from "./cliGuardState.js";
11
+ import type { Env } from "./cliSupport.js";
12
+ export declare const GUARD_HEALTH_PATH = "/api/my/guard-health";
13
+ type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
14
+ /** Managed settings hold Passport's guard for this agent. */
15
+ export declare function managedGuard(client: GuardClient, env: Env): boolean;
16
+ /** Each agent on this computer, as the report sends it. */
17
+ export declare function guardClientReports(env: Env): Promise<GuardClientReport[]>;
18
+ export declare function guardHealthReport(env: Env): Promise<GuardHealthReport>;
19
+ /**
20
+ * Whether a daily report is due, without claiming it. Never throws. A guard
21
+ * run (`firstWaits`) never sends the very first report: it starts the clock,
22
+ * and `passport status`, `exec`, and `init` send one right away.
23
+ */
24
+ export declare function guardHeartbeatDue(profile: string, now?: number, firstWaits?: boolean): boolean;
25
+ /** Claim today's report before any network, so parallel runs send one. */
26
+ export declare function claimGuardHeartbeat(profile: string, now?: number): boolean;
27
+ export type ReportedAgent = {
28
+ client: string;
29
+ state: string;
30
+ label: string;
31
+ fix?: ProblemFix;
32
+ };
33
+ /**
34
+ * Send this computer's guard report. Returns what Passport made of it (each
35
+ * agent's state and fix) or null when it couldn't be sent.
36
+ */
37
+ export declare function sendGuardHealth(api: ApiCall, profile: string, env: Env, signal: AbortSignal): Promise<ReportedAgent[] | null>;
38
+ /** The daily report, if due: claim, then send. */
39
+ export declare function guardHeartbeat(api: ApiCall, profile: string, env: Env, signal: AbortSignal, now?: number): Promise<ReportedAgent[] | null>;
40
+ export {};
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Guard health (Batch A): what this computer's Passport CLI can see about each
3
+ * agent's guard, reported to Passport at most once a day so the Agent rows,
4
+ * Home, and the bell show it. Self-reported, read-only, and counts and flags
5
+ * only: never a command, a path, or a setting's value.
6
+ *
7
+ * Sent from a guard run that has 300 ms of its budget left, from
8
+ * `passport exec`, and from `passport status`.
9
+ */
10
+ import { closeSync, constants, mkdirSync, openSync, readdirSync, readFileSync, statSync, utimesSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { readBoundedJson } from "./boundedResponse.js";
13
+ import { codexGuardTrust } from "./cliCodexTrust.js";
14
+ import { GUARD_CLIENTS, GUARD_HEARTBEAT_MS } from "./cliGuardState.js";
15
+ import { credentialDir, ensurePrivateDirectory } from "./credentialStorage.js";
16
+ import { assertProfileName } from "./credentials.js";
17
+ import { VERSION } from "./version.js";
18
+ export const GUARD_HEALTH_PATH = "/api/my/guard-health";
19
+ const MANAGED_MAX_BYTES = 1024 * 1024;
20
+ const PASSPORT_GUARD = /passport[^\s"']*["']?\s+hook\s+guard\b/i;
21
+ /** Managed settings the person can't turn off, per agent. Tests point
22
+ * PASSPORT_MANAGED_ROOT at a sandbox; otherwise they are the system's own. */
23
+ function managedPaths(client, env) {
24
+ const root = env.PASSPORT_MANAGED_ROOT?.trim() || "/";
25
+ const at = (...parts) => join(root, ...parts);
26
+ if (client === "claude-code") {
27
+ const dirs = [at("Library", "Application Support", "ClaudeCode"), at("etc", "claude-code")];
28
+ return dirs.flatMap((dir) => [join(dir, "managed-settings.json"), ...listJson(join(dir, "managed-settings.d"))]);
29
+ }
30
+ if (client === "codex") {
31
+ return [
32
+ at("etc", "codex", "requirements.toml"),
33
+ at("Library", "Application Support", "Codex", "requirements.toml")
34
+ ];
35
+ }
36
+ return [at("Library", "Application Support", "Cursor", "hooks.json"), at("etc", "cursor", "hooks.json")];
37
+ }
38
+ function listJson(dir) {
39
+ try {
40
+ return readdirSync(dir)
41
+ .filter((name) => name.endsWith(".json"))
42
+ .slice(0, 20)
43
+ .map((name) => join(dir, name));
44
+ }
45
+ catch {
46
+ return [];
47
+ }
48
+ }
49
+ /** Managed settings hold Passport's guard for this agent. */
50
+ export function managedGuard(client, env) {
51
+ for (const path of managedPaths(client, env)) {
52
+ try {
53
+ const raw = readFileSync(path, "utf8");
54
+ if (Buffer.byteLength(raw) <= MANAGED_MAX_BYTES && PASSPORT_GUARD.test(raw))
55
+ return true;
56
+ }
57
+ catch {
58
+ /* Not there, or not readable: not locked by this file. */
59
+ }
60
+ }
61
+ return false;
62
+ }
63
+ const MODES = {
64
+ "audit + guard": "audit+guard",
65
+ audit: "audit",
66
+ guard: "guard",
67
+ "via plugin": "plugin",
68
+ "not installed": "none",
69
+ unreadable: "unreadable"
70
+ };
71
+ /** Each agent on this computer, as the report sends it. */
72
+ export async function guardClientReports(env) {
73
+ const { agentHookStatus, codexHooksPath, isPassportGuardCommand } = await import("./cliHookInstall.js");
74
+ return GUARD_CLIENTS.map((client) => {
75
+ const status = agentHookStatus(client, env);
76
+ const locked = managedGuard(client, env);
77
+ const codexTrust = client === "codex" && status.guardCommand && !status.plugin
78
+ ? codexGuardTrust(codexHooksPath(env), isPassportGuardCommand)
79
+ : undefined;
80
+ return {
81
+ client,
82
+ present: status.agentPresent || locked,
83
+ mode: MODES[status.mode] ?? "none",
84
+ guard: status.guard || locked,
85
+ plugin: status.plugin,
86
+ ...(codexTrust ? { codexTrust } : {}),
87
+ ...(locked ? { locked: true } : {}),
88
+ ...(env.PASSPORT_HOOK_DISABLED === "1" ? { disabledEnv: true } : {})
89
+ };
90
+ });
91
+ }
92
+ /** The version the stable launcher runs, when it isn't this one. */
93
+ function launcherTarget() {
94
+ try {
95
+ const current = readFileSync(join(credentialDir(), "cli", "current", "package.json"), "utf8");
96
+ const version = JSON.parse(current).version;
97
+ return typeof version === "string" && version !== VERSION && /^\d+\.\d+\.\d+/.test(version) ? version : undefined;
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ }
103
+ export async function guardHealthReport(env) {
104
+ const target = launcherTarget();
105
+ return { cliVersion: VERSION, ...(target ? { launcherTarget: target } : {}), clients: await guardClientReports(env) };
106
+ }
107
+ function markerPath(profile) {
108
+ assertProfileName(profile);
109
+ return join(credentialDir(), "guard", `.${profile}.heartbeat`);
110
+ }
111
+ /**
112
+ * Whether a daily report is due, without claiming it. Never throws. A guard
113
+ * run (`firstWaits`) never sends the very first report: it starts the clock,
114
+ * and `passport status`, `exec`, and `init` send one right away.
115
+ */
116
+ export function guardHeartbeatDue(profile, now = Date.now(), firstWaits = false) {
117
+ try {
118
+ const last = statSync(markerPath(profile)).mtimeMs;
119
+ return now - last >= GUARD_HEARTBEAT_MS || last > now;
120
+ }
121
+ catch (error) {
122
+ if (error.code !== "ENOENT")
123
+ return false;
124
+ if (firstWaits)
125
+ stampHeartbeat(profile, now);
126
+ return !firstWaits;
127
+ }
128
+ }
129
+ function stampHeartbeat(profile, now) {
130
+ try {
131
+ ensurePrivateDirectory(true);
132
+ mkdirSync(join(credentialDir(), "guard"), { recursive: true, mode: 0o700 });
133
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
134
+ closeSync(openSync(markerPath(profile), constants.O_WRONLY | constants.O_CREAT | noFollow, 0o600));
135
+ utimesSync(markerPath(profile), now / 1000, now / 1000);
136
+ return true;
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ }
142
+ /** Claim today's report before any network, so parallel runs send one. */
143
+ export function claimGuardHeartbeat(profile, now = Date.now()) {
144
+ return guardHeartbeatDue(profile, now) && stampHeartbeat(profile, now);
145
+ }
146
+ /** A failed send leaves the day unclaimed, so the next run tries again. */
147
+ function releaseGuardHeartbeat(profile) {
148
+ try {
149
+ utimesSync(markerPath(profile), 0, 0);
150
+ }
151
+ catch {
152
+ /* The next day's run tries again. */
153
+ }
154
+ }
155
+ /**
156
+ * Send this computer's guard report. Returns what Passport made of it (each
157
+ * agent's state and fix) or null when it couldn't be sent.
158
+ */
159
+ export async function sendGuardHealth(api, profile, env, signal) {
160
+ try {
161
+ const report = await guardHealthReport(env);
162
+ const response = await api(GUARD_HEALTH_PATH, {
163
+ method: "POST",
164
+ headers: { "content-type": "application/json", accept: "application/json", "x-passport-surface": "cli" },
165
+ body: JSON.stringify(report),
166
+ signal
167
+ });
168
+ if (!response.ok) {
169
+ await response.body?.cancel().catch(() => undefined);
170
+ // An older server without the route: try again tomorrow, not every command.
171
+ if (response.status !== 404)
172
+ releaseGuardHeartbeat(profile);
173
+ return null;
174
+ }
175
+ const body = await readBoundedJson(response).catch(() => null);
176
+ return Array.isArray(body?.agents) ? body.agents : [];
177
+ }
178
+ catch {
179
+ releaseGuardHeartbeat(profile);
180
+ return null;
181
+ }
182
+ }
183
+ /** The daily report, if due: claim, then send. */
184
+ export async function guardHeartbeat(api, profile, env, signal, now = Date.now()) {
185
+ if (!claimGuardHeartbeat(profile, now))
186
+ return null;
187
+ const sent = await sendGuardHealth(api, profile, env, signal);
188
+ // Once a day too: has a key `passport keys move` removed come back?
189
+ await (await import("./cliKeysBack.js")).checkKeysBack(api, signal).catch(() => undefined);
190
+ return sent;
191
+ }