passport-bridge 0.11.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +76 -10
  2. package/dist/cli.js +24 -0
  3. package/dist/cliArgs.d.ts +1 -1
  4. package/dist/cliArgs.js +14 -2
  5. package/dist/cliHook.d.ts +54 -11
  6. package/dist/cliHook.js +317 -75
  7. package/dist/cliHookClassify.d.ts +6 -0
  8. package/dist/cliHookClassify.js +23 -1
  9. package/dist/cliHookGuard.d.ts +39 -0
  10. package/dist/cliHookGuard.js +127 -0
  11. package/dist/cliHookInstall.d.ts +54 -21
  12. package/dist/cliHookInstall.js +397 -119
  13. package/dist/cliHookPending.d.ts +31 -0
  14. package/dist/cliHookPending.js +141 -0
  15. package/dist/cliInit.d.ts +74 -0
  16. package/dist/cliInit.js +477 -0
  17. package/dist/cliLogin.d.ts +15 -1
  18. package/dist/cliLogin.js +219 -41
  19. package/dist/cliOutput.js +10 -4
  20. package/dist/cliPolicy.d.ts +63 -0
  21. package/dist/cliPolicy.js +216 -0
  22. package/dist/cliScan.d.ts +21 -0
  23. package/dist/cliScan.js +220 -0
  24. package/dist/cliSetup.js +2 -0
  25. package/dist/cliSupport.d.ts +2 -0
  26. package/dist/completion.js +8 -3
  27. package/dist/discover.d.ts +9 -0
  28. package/dist/discover.js +18 -11
  29. package/dist/initAgents.d.ts +83 -0
  30. package/dist/initAgents.js +503 -0
  31. package/dist/initAppsStep.d.ts +22 -0
  32. package/dist/initAppsStep.js +346 -0
  33. package/dist/initInstall.d.ts +58 -0
  34. package/dist/initInstall.js +372 -0
  35. package/dist/initLocalSteps.d.ts +7 -0
  36. package/dist/initLocalSteps.js +313 -0
  37. package/dist/initState.d.ts +112 -0
  38. package/dist/initState.js +80 -0
  39. package/dist/initUi.d.ts +73 -0
  40. package/dist/initUi.js +273 -0
  41. package/dist/nodeVersion.d.ts +13 -0
  42. package/dist/nodeVersion.js +42 -0
  43. package/dist/passport.d.ts +1 -0
  44. package/dist/passport.js +21 -1
  45. package/dist/scan.d.ts +3 -0
  46. package/dist/scan.js +274 -0
  47. package/dist/scanCore.d.ts +139 -0
  48. package/dist/scanCore.js +386 -0
  49. package/dist/scanParse.d.ts +36 -0
  50. package/dist/scanParse.js +275 -0
  51. package/dist/scanRules.d.ts +246 -0
  52. package/dist/scanRules.js +402 -0
  53. package/dist/scanStores.d.ts +3 -0
  54. package/dist/scanStores.js +221 -0
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/npm-shrinkwrap.json +8 -8
  58. package/package.json +3 -3
package/dist/cliLogin.js CHANGED
@@ -77,18 +77,26 @@ function ambiguousWorkspace(candidates, complete) {
77
77
  }))
78
78
  });
79
79
  }
80
- function loginOptions(args, runtime) {
80
+ /** --profile and PASSPORT_PROFILE always win. Otherwise --workspace names the
81
+ * CLI profile to refresh; without it, login refreshes the profile other
82
+ * commands would use (active, then the sole CLI profile, then the sole
83
+ * profile). `passport init` asks for a fresh browser sign-in instead. */
84
+ function savedSelection(args, runtime, hooks) {
85
+ if (hooks.browserOnly) {
86
+ const profile = value(args, "profile");
87
+ return { creds: {}, selection: { profile, source: profile ? "explicit" : "none" } };
88
+ }
89
+ const creds = readCreds();
90
+ return { creds, selection: selectStoredProfile(args, runtime.env, creds) };
91
+ }
92
+ function loginOptions(args, runtime, hooks = {}) {
81
93
  const workspaceOption = value(args, "workspace");
82
94
  const explicitWorkspace = workspaceOption !== undefined;
83
95
  const workspaceFromOption = workspaceOption?.trim() ?? "";
84
96
  if (explicitWorkspace && !/^[A-Za-z0-9_-]{1,80}$/.test(workspaceFromOption)) {
85
97
  return failure("--workspace must be a valid workspace id.", 6, "usage");
86
98
  }
87
- const creds = readCreds();
88
- // --profile and PASSPORT_PROFILE always win. Otherwise --workspace names the
89
- // CLI profile to refresh; without it, login refreshes the profile other
90
- // commands would use (active, then the sole CLI profile, then the sole profile).
91
- const selection = selectStoredProfile(args, runtime.env, creds);
99
+ const { creds, selection } = savedSelection(args, runtime, hooks);
92
100
  const namedBySelector = selection.source === "explicit" || selection.source === "environment";
93
101
  const requestedProfile = explicitWorkspace && !namedBySelector ? `cli@${workspaceFromOption}` : (selection.profile ?? "");
94
102
  const existing = requestedProfile ? getProfile(requestedProfile) : undefined;
@@ -112,9 +120,15 @@ function loginOptions(args, runtime) {
112
120
  else if (candidates.length) {
113
121
  return ambiguousWorkspace(candidates, complete);
114
122
  }
123
+ else if (!complete && !requestedCloud) {
124
+ // Only unreadable legacy profiles: their server is unknown, so never
125
+ // guess Passport Cloud for someone who may be self-hosted.
126
+ return missingWorkspace("");
127
+ }
115
128
  }
129
+ // Nothing names a workspace: the browser finds or creates one.
116
130
  if (!cloud)
117
- return missingWorkspace("");
131
+ cloud = PASSPORT_CLOUD;
118
132
  const clientOption = value(args, "client");
119
133
  const client = clientOption === undefined ? existing?.client || "cli" : clientOption.trim();
120
134
  if (!/^[A-Za-z0-9._-]{1,40}$/.test(client)) {
@@ -122,8 +136,52 @@ function loginOptions(args, runtime) {
122
136
  }
123
137
  return { requestedProfile, cloud: cloudOrigin(cloud), workspace, client };
124
138
  }
139
+ /** Status codes an older or self-hosted server gives for a route it lacks. */
140
+ const BROWSER_SIGN_IN_UNSUPPORTED = new Set([401, 403, 404, 405]);
141
+ const SIGN_IN_WINDOW_MS = 10 * 60 * 1000;
142
+ const MAX_TRANSIENT_POLL_FAILURES = 5;
143
+ const EXPIRED = "This sign-in code expired. Run passport login again.";
144
+ const DENIED = "Sign-in was denied in the browser. Nothing was saved.";
145
+ const CANCELLED = "Sign-in cancelled. Nothing was saved.";
146
+ /** Printable text from the server: no terminal controls, bounded. */
147
+ function displayText(raw, max = 80) {
148
+ if (typeof raw !== "string")
149
+ return "";
150
+ return raw
151
+ .replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, "")
152
+ .trim()
153
+ .slice(0, max);
154
+ }
155
+ function printPrompt(runtime, opts, hooks) {
156
+ const { verifyUrl, userCode, shouldOpen, workspace } = opts;
157
+ if (hooks.onPrompt) {
158
+ hooks.onPrompt({ verifyUrl, userCode, opened: shouldOpen && openUrl(verifyUrl) });
159
+ return;
160
+ }
161
+ const lines = [
162
+ `Sign in to Passport${workspace ? ` (workspace ${workspace})` : ""}`,
163
+ shouldOpen ? `Opening your browser... (or open ${verifyUrl})` : `Open this link to continue: ${verifyUrl}`,
164
+ `Confirm this code in the browser: ${userCode}`,
165
+ "Waiting... (Ctrl-C to cancel)"
166
+ ];
167
+ runtime.stderr.write(`${lines.join("\n")}\n`);
168
+ if (shouldOpen && !openUrl(verifyUrl)) {
169
+ runtime.stderr.write("Couldn't open a browser. Open the link above to continue.\n");
170
+ }
171
+ }
172
+ /** Ctrl-C while waiting is a choice, not an error. */
173
+ async function cancellable(runtime, wait) {
174
+ try {
175
+ return await wait();
176
+ }
177
+ catch (error) {
178
+ if (runtime.signal.aborted)
179
+ return failure(CANCELLED, 1, "cancelled");
180
+ throw error;
181
+ }
182
+ }
125
183
  async function waitForDeviceApproval(cloud, code, args, runtime) {
126
- const deadlineAt = Date.now() + 10 * 60 * 1000;
184
+ const deadlineAt = Date.now() + SIGN_IN_WINDOW_MS;
127
185
  while (Date.now() < deadlineAt) {
128
186
  await sleep(1_500, runtime.signal);
129
187
  const poll = await timedFetch(`${cloud}/api/auth/device/poll`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code }) }, timeoutMs(args), runtime.signal);
@@ -132,23 +190,18 @@ async function waitForDeviceApproval(cloud, code, args, runtime) {
132
190
  const result = await readBoundedJson(poll);
133
191
  if (result.status === "approved" && typeof result.token === "string")
134
192
  return result.token;
135
- if (result.status === "denied" || result.status === "expired") {
136
- return failure(`Sign-in ${result.status}.`, 2, "auth");
137
- }
193
+ if (result.status === "denied")
194
+ return failure(DENIED, 2, "auth");
195
+ if (result.status === "expired")
196
+ return failure(EXPIRED, 2, "auth");
138
197
  }
139
- return failure("Timed out waiting for sign-in approval.", 2, "auth");
198
+ return failure(EXPIRED, 2, "auth");
140
199
  }
141
- export async function login(args, runtime) {
142
- if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
143
- return failure("Unset PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT before interactive login.", 6, "usage");
144
- }
145
- assertCredentialStoreMutationReady();
146
- const { requestedProfile, cloud, workspace, client } = loginOptions(args, runtime);
147
- const workspaceQuery = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
148
- const start = await timedFetch(`${cloud}/api/auth/device/start${workspaceQuery}`, { method: "POST" }, timeoutMs(args), runtime.signal);
200
+ /** Today's tenant device flow, for a known workspace. Unchanged on the wire. */
201
+ async function workspaceSignIn(options, args, runtime, hooks) {
202
+ const { cloud, workspace } = options;
203
+ const start = await timedFetch(`${cloud}/api/auth/device/start?ws=${encodeURIComponent(workspace)}`, { method: "POST" }, timeoutMs(args), runtime.signal);
149
204
  if (start.status === 404) {
150
- if (!workspace)
151
- return missingWorkspace(cloud);
152
205
  return failure("Passport could not find that workspace. Ask your admin for its workspace id.", 2, "auth", {
153
206
  hint: `Then run: ${loginArgv("<ws_id>", cloud).join(" ")}`
154
207
  });
@@ -162,20 +215,125 @@ export async function login(args, runtime) {
162
215
  return failure("Passport returned an invalid device sign-in response.", 1, "invalid_server_response");
163
216
  }
164
217
  const verifyUrl = sameOriginWebUrl(started.verifyUrl, cloud, "a sign-in URL");
165
- const shouldOpen = !bool(args, "no-open") && !runtime.env.PASSPORT_NO_OPEN;
166
- runtime.stderr.write(`Sign in to Passport${workspace ? ` workspace ${workspace}` : ""}\n${shouldOpen ? "Opening your browser..." : "Browser opening is disabled."}\nOpen: ${verifyUrl}\nConfirm code: ${started.userCode}\nWaiting for approval (up to 10 minutes; press Ctrl-C to cancel)...\n`);
167
- if (shouldOpen && !openUrl(verifyUrl)) {
168
- runtime.stderr.write("Could not open a browser automatically. Open the URL above to continue.\n");
169
- }
170
- const sessionToken = await waitForDeviceApproval(cloud, started.code, args, runtime);
171
- runtime.stderr.write("Sign-in approved. Creating your CLI credential...\n");
218
+ printPrompt(runtime, {
219
+ verifyUrl,
220
+ userCode: displayText(started.userCode, 16),
221
+ shouldOpen: !bool(args, "no-open") && !runtime.env.PASSPORT_NO_OPEN,
222
+ workspace
223
+ }, hooks);
224
+ const sessionToken = await cancellable(runtime, () => waitForDeviceApproval(cloud, started.code, args, runtime));
172
225
  const approvedWorkspace = workspaceOfToken(sessionToken);
173
- if (workspace && approvedWorkspace && approvedWorkspace !== workspace) {
226
+ if (approvedWorkspace && approvedWorkspace !== workspace) {
174
227
  return failure("Passport approved a different workspace than the one requested; no credential was saved.", 2, "auth");
175
228
  }
176
- const tokenWorkspace = workspace || approvedWorkspace || "workspace";
177
- const profile = profileName(requestedProfile || `cli@${tokenWorkspace}`);
178
- const storedInstanceId = getProfileStrict(profile)?.instanceId;
229
+ return { sessionToken, workspace };
230
+ }
231
+ async function waitForBrowserApproval(cloud, code, intervalMs, args, runtime) {
232
+ // The server's window plus a little slack, so its own "expired" wins.
233
+ const deadlineAt = Date.now() + SIGN_IN_WINDOW_MS + 15_000;
234
+ let transient = 0;
235
+ const lostContact = (status) => failure(status
236
+ ? `Could not check sign-in (${status}). Run passport login again.`
237
+ : "Lost contact with Passport while waiting. Check your connection and run passport login again.", 1, "network_or_server");
238
+ while (Date.now() < deadlineAt) {
239
+ await sleep(intervalMs, runtime.signal);
240
+ let poll;
241
+ try {
242
+ poll = await timedFetch(`${cloud}/api/auth/cli/poll`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code }) }, timeoutMs(args), runtime.signal);
243
+ }
244
+ catch (error) {
245
+ if (runtime.signal.aborted)
246
+ throw error;
247
+ // A dropped connection or a slow replica mid-wait is not fatal; the
248
+ // browser may still be finishing.
249
+ if (++transient >= MAX_TRANSIENT_POLL_FAILURES)
250
+ return lostContact();
251
+ continue;
252
+ }
253
+ if (poll.status === 429 || poll.status >= 500) {
254
+ await poll.body?.cancel().catch(() => undefined);
255
+ if (++transient >= MAX_TRANSIENT_POLL_FAILURES)
256
+ return lostContact(poll.status);
257
+ continue;
258
+ }
259
+ if (!poll.ok)
260
+ return lostContact(poll.status);
261
+ transient = 0;
262
+ const result = await readBoundedJson(poll);
263
+ if (result.status === "pending")
264
+ continue;
265
+ if (result.status === "denied")
266
+ return failure(DENIED, 2, "auth");
267
+ if (result.status === "approved") {
268
+ const sessionToken = typeof result.token === "string" ? result.token : "";
269
+ const workspace = workspaceOfToken(sessionToken);
270
+ const claimed = typeof result.workspaceId === "string" ? result.workspaceId : "";
271
+ if (!sessionToken || !workspace || (claimed && claimed !== workspace)) {
272
+ return failure("Passport returned an invalid sign-in response.", 1, "invalid_server_response");
273
+ }
274
+ return { sessionToken, workspace, workspaceName: displayText(result.workspaceName) || undefined };
275
+ }
276
+ return failure(EXPIRED, 2, "auth");
277
+ }
278
+ return failure(EXPIRED, 2, "auth");
279
+ }
280
+ /** No workspace known: the browser signs in or signs up, then picks one. */
281
+ async function browserSignIn(options, args, runtime, hooks) {
282
+ const { cloud } = options;
283
+ const start = await timedFetch(`${cloud}/api/auth/cli/start`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }, timeoutMs(args), runtime.signal);
284
+ if (BROWSER_SIGN_IN_UNSUPPORTED.has(start.status)) {
285
+ // An older or self-hosted server without browser sign-in: today's rule.
286
+ await start.body?.cancel().catch(() => undefined);
287
+ return missingWorkspace(cloud === PASSPORT_CLOUD ? "" : cloud);
288
+ }
289
+ if (start.status === 429) {
290
+ return failure("Too many sign-in attempts from this network. Wait a few minutes and try again.", 1, "rate_limited");
291
+ }
292
+ if (!start.ok)
293
+ return failure(`Could not start sign-in (${start.status}).`, 1, "server");
294
+ const started = await readBoundedJson(start);
295
+ if (typeof started.code !== "string" ||
296
+ typeof started.userCode !== "string" ||
297
+ typeof started.verifyUrl !== "string") {
298
+ return failure("Passport returned an invalid sign-in response.", 1, "invalid_server_response");
299
+ }
300
+ const verifyUrl = sameOriginWebUrl(started.verifyUrl, cloud, "a sign-in URL");
301
+ // Everything printed to the terminal is validated first, so a hostile
302
+ // server can't smuggle escape sequences into it.
303
+ if (!/^cli_[A-Za-z0-9_-]{43}$/.test(started.code) || !/^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(started.userCode)) {
304
+ return failure("Passport returned an invalid sign-in response.", 1, "invalid_server_response");
305
+ }
306
+ const interval = typeof started.interval === "number" && Number.isFinite(started.interval) ? started.interval : 2;
307
+ printPrompt(runtime, {
308
+ verifyUrl,
309
+ userCode: started.userCode,
310
+ shouldOpen: !bool(args, "no-open") && !runtime.env.PASSPORT_NO_OPEN
311
+ }, hooks);
312
+ return cancellable(runtime, () => waitForBrowserApproval(cloud, started.code, Math.min(10_000, Math.max(1_000, interval * 1000)), args, runtime));
313
+ }
314
+ export async function login(args, runtime, hooks = {}) {
315
+ if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
316
+ return failure("Unset PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT before interactive login.", 6, "usage");
317
+ }
318
+ assertCredentialStoreMutationReady();
319
+ const options = loginOptions(args, runtime, hooks);
320
+ const { requestedProfile, cloud, client } = options;
321
+ const approval = options.workspace
322
+ ? await workspaceSignIn(options, args, runtime, hooks)
323
+ : await browserSignIn(options, args, runtime, hooks);
324
+ const { sessionToken, workspace } = approval;
325
+ if (!bool(args, "json") && !hooks.onPrompt)
326
+ runtime.stderr.write("\n");
327
+ const profile = profileName(requestedProfile || `cli@${workspace || "workspace"}`);
328
+ const stored = getProfileStrict(profile);
329
+ if (!options.workspace && stored) {
330
+ // A profile named for one workspace never silently becomes another's.
331
+ const storedWorkspace = workspaceOfProfile(stored);
332
+ if (storedWorkspace && storedWorkspace !== workspace) {
333
+ return failure(`Profile "${profile}" belongs to another workspace and will not be overwritten. Choose a new --profile name.`, 6, "usage");
334
+ }
335
+ }
336
+ const storedInstanceId = stored?.instanceId;
179
337
  const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
180
338
  const credential = await timedFetch(`${cloud}/api/my/bridge-credential`, {
181
339
  method: "POST",
@@ -214,15 +372,35 @@ export async function login(args, runtime) {
214
372
  // when other client/workspace profiles already exist.
215
373
  setActiveProfile(profile);
216
374
  });
375
+ // Give the hook guard this member's safety settings now, not an hour from
376
+ // now. It reuses the sign-in session, so no extra token exchange; bounded,
377
+ // and a failure or an older server changes nothing.
378
+ const { refreshCliPolicy } = await import("./cliPolicy.js");
379
+ const origin = new URL(credentialEndpoint).origin;
380
+ await refreshCliPolicy(profile, AbortSignal.any([runtime.signal, AbortSignal.timeout(5_000)]), {
381
+ api: (path, init) => fetch(`${origin}${path}`, {
382
+ ...init,
383
+ redirect: "error",
384
+ headers: { ...init.headers, authorization: `Bearer ${sessionToken}` }
385
+ })
386
+ });
387
+ const next = [{ argv: ["passport", "status", "--json"], description: "Verify the active profile and connections." }];
388
+ const json = {
389
+ profile,
390
+ endpoint: credentialEndpoint,
391
+ client,
392
+ surface: "cli",
393
+ active: true,
394
+ ...(workspace ? { workspaceId: workspace } : {}),
395
+ ...(approval.workspaceName ? { workspaceName: approval.workspaceName } : {}),
396
+ next
397
+ };
398
+ if (!options.workspace) {
399
+ const where = approval.workspaceName ?? `workspace ${workspace}`;
400
+ return { json, human: `Signed in to ${where}.\nNext: passport status` };
401
+ }
217
402
  return {
218
- json: {
219
- profile,
220
- endpoint: credentialEndpoint,
221
- client,
222
- surface: "cli",
223
- active: true,
224
- next: [{ argv: ["passport", "status", "--json"], description: "Verify the active profile and connections." }]
225
- },
403
+ json,
226
404
  human: `Signed in as profile "${profile}".\nActive profile: "${profile}".\nCredential saved to ${credsPath()}.\nNext: passport status`
227
405
  };
228
406
  }
package/dist/cliOutput.js CHANGED
@@ -4,7 +4,8 @@ import { CliFailure, sanitize } from "./cliSupport.js";
4
4
  import { VERSION } from "./version.js";
5
5
  function helpText(verb) {
6
6
  const details = {
7
- login: "passport login [--workspace <id>] [--cloud <origin>] [--client <id>] [--profile <name>] [--no-open]\nStarts device sign-in, stores a cli-surface rotating credential, and makes that profile active. Passport Cloud is used when --workspace is provided without --cloud. Without --workspace, login reuses the workspace and cloud of the saved profile it refreshes, or the one workspace all saved profiles share; it never chooses between several.",
7
+ init: 'passport init [--yes] [--no-open] [--cloud <origin>] [--skip-apps] [--skip-agents] [--skip-guard] [--verbose] [--json]\nnpx passport-bridge init [same options]\nSets up Passport in one pass: scans for keys your agents can reach, signs you in (or up), connects the apps it found, adds Passport to your agents, turns on the guard for shell commands, and makes destructive actions ask first. Each step asks first and can be skipped. Run it again any time: finished steps are left as they are.\n --yes accept every default without asking (needed without a terminal)\n --no-open print links instead of opening a browser\n --cloud <url> a self-hosted Passport\n --skip-apps, --skip-agents, --skip-guard leave that step out\n --verbose show the full scan\n --json with --yes: one JSON summary with each step\'s status\nUndo: passport hook uninstall --client <agent> --apply, then remove the "passport" entry from each agent.',
8
+ login: "passport login [--workspace <id>] [--cloud <origin>] [--client <id>] [--profile <name>] [--no-open]\nSigns in, stores a cli-surface rotating credential, and makes that profile active. Without --workspace, login reuses the workspace and cloud of the saved profile it refreshes, or the one workspace all saved profiles share; it never chooses between several. With no saved workspace, it opens the browser to sign in or sign up and pick or create a workspace. Passport Cloud is the default; self-hosted servers take --cloud.",
8
9
  logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
9
10
  profiles: "passport profiles\nLists saved profiles and marks the active profile. Works offline.",
10
11
  use: "passport use <name>\nSelects a saved profile as the default for subsequent commands. Works offline.",
@@ -17,8 +18,9 @@ function helpText(verb) {
17
18
  connect: "passport connect [app...] [--alias <name>] [--open] [--wait <sec>]\nShows member-bound connection links and can wait for sign-in to finish. JSON is the manage_connections payload.",
18
19
  resources: "passport resources [uri] [--out <file>]\nLists or reads workspace MCP resources. Binary content requires --out or --json.",
19
20
  prompts: "passport prompts [name] [--set key=value] [--out <file>]\nLists or gets workspace MCP prompts. Binary content requires --out or --json.",
21
+ scan: "passport scan [--path <folder>] [--verbose] [--check] [--json]\nnpx passport-bridge scan [same options]\nFinds keys your agents can reach: agent configs, CLI sign-ins, your shell\nenvironment, and this project's .env files. Runs locally with no account.\nNothing leaves this machine, and no part of a key is ever printed.\n --path <folder> scan this project instead of the current folder\n --verbose show every place a key was found and files it couldn't read\n --check files only, no shell environment; exit 5 on a high or\n medium key (CI, pre-commit)\n --json one JSON document: {version,findings,agents,unreadable,checked}",
20
22
  discover: "passport discover\nScans supported local MCP configuration, submits privacy-minimized inventory, and exits 5 when a managed policy reports a violation.",
21
- hook: "passport hook\npassport hook install [--client claude-code|codex] [--apply]\npassport hook uninstall [--client claude-code|codex] [--apply]\npassport hook status\nWith no subcommand this is the hook itself: it reads one agent PostToolUse event on stdin, classifies the shell command locally, and records the vendor, a coarse verb, and a risk class in Activity. It never blocks, never answers a permission question, and never sends the command line, its output, your folder path, or your environment. Registration is previewed unless --apply is supplied.",
23
+ hook: "passport hook install [--client claude-code|codex|cursor] [--guard] [--apply]\npassport hook uninstall [--client claude-code|codex|cursor] [--guard] [--apply]\npassport hook status\nThe audit hook runs after each shell command an agent runs and records the vendor, a coarse verb, and a risk class in Activity. With --guard, Passport also checks each command before it runs: it asks before destructive commands it recognizes, or blocks them when your safety settings say so. It never allows anything your agent would otherwise ask about. Neither hook sends the command line, its output, your folder path, or your environment. It can't see inside scripts, aliases, or make targets. Changes are previewed unless --apply is supplied. uninstall --guard removes only the guard.",
22
24
  setup: "passport setup list\npassport setup installed\npassport setup install <setup-id> <workflow-key> --client <codex|claude-code> [--apply]\npassport setup remove <skill-name> [--apply]\npassport setup rollback <skill-name> [--apply]\nLists assigned workflows and safely manages their local skill files. Changes are previewed unless --apply is supplied. Personal edits are preserved. Installed inventory, removal, and rollback work offline.",
23
25
  session: 'passport session\nReads newline-delimited {"id"?:string|number,"argv":string[]} requests from stdin and emits one JSON response per line. Reuses one authenticated MCP session. Supported request commands: status, search, describe, run, connect, resources, prompts, discover.',
24
26
  access: "passport access <keygen|actions|run|invoke|status|cancel>\nkeygen writes a new owner-only private key and separate public JWK. Other commands use PASSPORT_ENDPOINT, PASSPORT_CLIENT_ID, and PASSPORT_PRIVATE_KEY_FILE.\n access actions [--delegation-id <id>]\n access run --input <json-file>\n access invoke --input <json-file> --caller <stable-id>\n access status <invocation-id>\n access cancel <run-id>",
@@ -26,13 +28,17 @@ function helpText(verb) {
26
28
  help: "passport help [verb]",
27
29
  version: "passport version\nWorks without a profile or network."
28
30
  };
31
+ if ((verb === "scan" || verb === "init") && details[verb])
32
+ return details[verb];
29
33
  if (verb && details[verb])
30
34
  return `${details[verb]}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
31
35
  return `Passport CLI ${VERSION}
32
36
 
33
37
  Usage: passport <command> [options]
34
38
 
35
- login Sign in with the device flow
39
+ scan Find keys your agents can reach. Local, no account
40
+ init Set up Passport for your agents, step by step
41
+ login Sign in or sign up in the browser
36
42
  logout Revoke and remove a profile
37
43
  profiles List saved profiles and the active selection
38
44
  use Select a saved profile for subsequent commands
@@ -46,7 +52,7 @@ Usage: passport <command> [options]
46
52
  resources List or read MCP resources
47
53
  prompts List or get MCP prompts
48
54
  discover Scan this computer for direct MCP configuration
49
- hook Record the CLIs your agents run, for the audit log
55
+ hook Record the CLIs your agents run, and ask before destructive ones
50
56
  setup Install and maintain assigned team workflows
51
57
  session Reuse one authenticated MCP session for NDJSON commands
52
58
  access Use the signed managed access gateway
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The member's CLI policy, cached on this machine for `passport hook guard`.
3
+ *
4
+ * The server derives it from the same choices that gate MCP tool calls, so a
5
+ * command and a tool with the same effect get the same answer. The guard reads
6
+ * only this local copy: it must decide before a shell command runs, inside a
7
+ * 1.5 s budget, with no network. `passport login` and `passport status` refresh
8
+ * it, and the hook refreshes a stale copy after it has already answered.
9
+ *
10
+ * Reading never throws: a missing, corrupt, oversized, or foreign-owned cache
11
+ * is treated as absent, and the guard falls back to its built-in default.
12
+ * Refreshing never rejects: a 404 (an older server) or any failure keeps the
13
+ * previous copy untouched.
14
+ */
15
+ export declare const CLI_POLICY_PATH = "/api/my/cli-policy";
16
+ /** Older than this, the hook refreshes the cache after it has answered. */
17
+ export declare const CLI_POLICY_STALE_MS: number;
18
+ /** The hook tries at most this often, so an offline laptop pays nothing. */
19
+ export declare const CLI_POLICY_RETRY_MS: number;
20
+ export declare const CLI_DECISIONS: readonly ["allow", "ask", "never"];
21
+ export type CliDecision = (typeof CLI_DECISIONS)[number];
22
+ export declare const SAFETY_PROFILES: readonly ["off", "ask", "block"];
23
+ export type SafetyProfile = (typeof SAFETY_PROFILES)[number];
24
+ export type CliPolicy = {
25
+ version: 1;
26
+ profile: SafetyProfile;
27
+ updatedAt: number;
28
+ /** Only verbs whose decision differs from `default`. Null-prototype maps. */
29
+ vendors: Record<string, Record<string, CliDecision>>;
30
+ default: {
31
+ destructive: CliDecision;
32
+ };
33
+ };
34
+ /** What the cache holds: the server's policy plus when this machine got it. */
35
+ export type CachedCliPolicy = CliPolicy & {
36
+ fetchedAt: number;
37
+ };
38
+ export type CliPolicyRefresh = "updated" | "unavailable" | "failed";
39
+ export type CliPolicyRefreshDependencies = {
40
+ /** An authenticated same-origin API call the caller already holds, such as
41
+ * the one `passport status` opened. Without it the saved profile is used. */
42
+ api?: (path: string, init: RequestInit) => Promise<Response>;
43
+ /** Network seam for the default credential exchange. */
44
+ fetch?: typeof fetch;
45
+ now?: () => number;
46
+ };
47
+ /** Validate a policy document. Unknown fields are ignored so a newer server
48
+ * can add to the contract; anything malformed rejects the whole document. */
49
+ export declare function parseCliPolicy(value: unknown): CliPolicy | null;
50
+ export declare function cliPolicyPath(profile: string): string;
51
+ /** Sync, bounded, validated, and it never throws. */
52
+ export declare function readCliPolicy(profile: string): CachedCliPolicy | null;
53
+ export declare function writeCliPolicy(profile: string, policy: CliPolicy, fetchedAt: number): void;
54
+ /** Signing out forgets what that profile's policy said. Never throws. */
55
+ export declare function removeCliPolicy(profile: string): void;
56
+ /**
57
+ * Claim the hook's once-per-interval refresh. True when the cache is missing or
58
+ * stale and no other hook tried in the last ten minutes; the claim is recorded
59
+ * before any network so parallel shell commands don't all try at once.
60
+ */
61
+ export declare function claimStaleRefresh(profile: string, cached: CachedCliPolicy | null, now?: number): boolean;
62
+ /** Fetch, validate, and atomically replace the cache. Never rejects. */
63
+ export declare function refreshCliPolicy(profile: string, signal: AbortSignal, deps?: CliPolicyRefreshDependencies): Promise<CliPolicyRefresh>;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * The member's CLI policy, cached on this machine for `passport hook guard`.
3
+ *
4
+ * The server derives it from the same choices that gate MCP tool calls, so a
5
+ * command and a tool with the same effect get the same answer. The guard reads
6
+ * only this local copy: it must decide before a shell command runs, inside a
7
+ * 1.5 s budget, with no network. `passport login` and `passport status` refresh
8
+ * it, and the hook refreshes a stale copy after it has already answered.
9
+ *
10
+ * Reading never throws: a missing, corrupt, oversized, or foreign-owned cache
11
+ * is treated as absent, and the guard falls back to its built-in default.
12
+ * Refreshing never rejects: a 404 (an older server) or any failure keeps the
13
+ * previous copy untouched.
14
+ */
15
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, rmSync, statSync, utimesSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { readBoundedUtf8File } from "./boundedFile.js";
18
+ import { readBoundedJson } from "./boundedResponse.js";
19
+ import { credentialDir, enforceOwner, ensurePrivateDirectory, writePrivateAtomic } from "./credentialStorage.js";
20
+ import { assertProfileName, getProfile } from "./credentials.js";
21
+ export const CLI_POLICY_PATH = "/api/my/cli-policy";
22
+ /** Older than this, the hook refreshes the cache after it has answered. */
23
+ export const CLI_POLICY_STALE_MS = 60 * 60 * 1000;
24
+ /** The hook tries at most this often, so an offline laptop pays nothing. */
25
+ export const CLI_POLICY_RETRY_MS = 10 * 60 * 1000;
26
+ const CACHE_DIRECTORY = "cli-policy";
27
+ const MAX_BYTES = 256 * 1024;
28
+ const MAX_VENDORS = 128;
29
+ const MAX_VERBS_PER_VENDOR = 256;
30
+ const VENDOR_KEY = /^[a-z0-9._-]{1,40}$/;
31
+ const VERB_KEY = /^[^\u0000-\u001f\u007f]{1,80}$/;
32
+ const UNSAFE_KEYS = new Set(["__proto__", "prototype", "constructor"]);
33
+ export const CLI_DECISIONS = ["allow", "ask", "never"];
34
+ export const SAFETY_PROFILES = ["off", "ask", "block"];
35
+ function isDecision(value) {
36
+ return typeof value === "string" && CLI_DECISIONS.includes(value);
37
+ }
38
+ function plainObject(value) {
39
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
40
+ }
41
+ /** Validate a policy document. Unknown fields are ignored so a newer server
42
+ * can add to the contract; anything malformed rejects the whole document. */
43
+ export function parseCliPolicy(value) {
44
+ const body = plainObject(value);
45
+ if (!body || body.version !== 1)
46
+ return null;
47
+ if (typeof body.profile !== "string" || !SAFETY_PROFILES.includes(body.profile))
48
+ return null;
49
+ if (typeof body.updatedAt !== "number" || !Number.isFinite(body.updatedAt) || body.updatedAt < 0)
50
+ return null;
51
+ const fallback = plainObject(body.default);
52
+ if (!fallback || !isDecision(fallback.destructive))
53
+ return null;
54
+ const rawVendors = plainObject(body.vendors ?? {});
55
+ if (!rawVendors)
56
+ return null;
57
+ const vendorEntries = Object.entries(rawVendors);
58
+ if (vendorEntries.length > MAX_VENDORS)
59
+ return null;
60
+ const vendors = Object.create(null);
61
+ for (const [vendor, rawVerbs] of vendorEntries) {
62
+ if (!VENDOR_KEY.test(vendor) || UNSAFE_KEYS.has(vendor))
63
+ return null;
64
+ const verbs = plainObject(rawVerbs);
65
+ if (!verbs)
66
+ return null;
67
+ const verbEntries = Object.entries(verbs);
68
+ if (verbEntries.length > MAX_VERBS_PER_VENDOR)
69
+ return null;
70
+ const mapped = Object.create(null);
71
+ for (const [verb, decision] of verbEntries) {
72
+ if (!VERB_KEY.test(verb) || UNSAFE_KEYS.has(verb) || !isDecision(decision))
73
+ return null;
74
+ mapped[verb] = decision;
75
+ }
76
+ vendors[vendor] = mapped;
77
+ }
78
+ return {
79
+ version: 1,
80
+ profile: body.profile,
81
+ updatedAt: body.updatedAt,
82
+ vendors,
83
+ default: { destructive: fallback.destructive }
84
+ };
85
+ }
86
+ function directory() {
87
+ return join(credentialDir(), CACHE_DIRECTORY);
88
+ }
89
+ export function cliPolicyPath(profile) {
90
+ assertProfileName(profile);
91
+ return join(directory(), `${profile}.json`);
92
+ }
93
+ function attemptPath(profile) {
94
+ assertProfileName(profile);
95
+ return join(directory(), `.${profile}.attempt`);
96
+ }
97
+ /** Sync, bounded, validated, and it never throws. */
98
+ export function readCliPolicy(profile) {
99
+ try {
100
+ const path = cliPolicyPath(profile);
101
+ enforceOwner(lstatSync(path), "CLI policy cache");
102
+ const raw = JSON.parse(readBoundedUtf8File(path, MAX_BYTES));
103
+ const document = plainObject(raw);
104
+ if (!document)
105
+ return null;
106
+ const fetchedAt = document.fetchedAt;
107
+ if (typeof fetchedAt !== "number" || !Number.isFinite(fetchedAt) || fetchedAt < 0)
108
+ return null;
109
+ const policy = parseCliPolicy(document.policy);
110
+ return policy ? { ...policy, fetchedAt } : null;
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ /** The cache lives in a private subdirectory of the credential directory. */
117
+ function ensureCacheDirectory() {
118
+ ensurePrivateDirectory(true);
119
+ const path = directory();
120
+ try {
121
+ mkdirSync(path, { mode: 0o700 });
122
+ }
123
+ catch (error) {
124
+ if (error.code !== "EEXIST")
125
+ throw error;
126
+ }
127
+ const stat = lstatSync(path);
128
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
129
+ throw new Error("Passport CLI policy directory must be a regular directory, not a symlink.");
130
+ }
131
+ enforceOwner(stat, "CLI policy directory");
132
+ }
133
+ export function writeCliPolicy(profile, policy, fetchedAt) {
134
+ const target = cliPolicyPath(profile);
135
+ ensureCacheDirectory();
136
+ writePrivateAtomic(target, ".cli-policy", `${JSON.stringify({ fetchedAt, policy })}\n`, "CLI policy cache");
137
+ }
138
+ /** Signing out forgets what that profile's policy said. Never throws. */
139
+ export function removeCliPolicy(profile) {
140
+ try {
141
+ rmSync(cliPolicyPath(profile), { force: true });
142
+ rmSync(attemptPath(profile), { force: true });
143
+ }
144
+ catch {
145
+ /* A leftover cache is harmless: it only ever adds friction. */
146
+ }
147
+ }
148
+ /**
149
+ * Claim the hook's once-per-interval refresh. True when the cache is missing or
150
+ * stale and no other hook tried in the last ten minutes; the claim is recorded
151
+ * before any network so parallel shell commands don't all try at once.
152
+ */
153
+ export function claimStaleRefresh(profile, cached, now = Date.now()) {
154
+ if (cached && now - cached.fetchedAt < CLI_POLICY_STALE_MS && cached.fetchedAt <= now)
155
+ return false;
156
+ try {
157
+ const marker = attemptPath(profile);
158
+ try {
159
+ const last = statSync(marker).mtimeMs;
160
+ if (now - last < CLI_POLICY_RETRY_MS && last <= now)
161
+ return false;
162
+ }
163
+ catch (error) {
164
+ if (error.code !== "ENOENT")
165
+ return false;
166
+ }
167
+ ensureCacheDirectory();
168
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
169
+ closeSync(openSync(marker, constants.O_WRONLY | constants.O_CREAT | noFollow, 0o600));
170
+ const seconds = now / 1000;
171
+ utimesSync(marker, seconds, seconds);
172
+ return true;
173
+ }
174
+ catch {
175
+ return false;
176
+ }
177
+ }
178
+ async function defaultApi(profile, signal, fetcher) {
179
+ const saved = getProfile(profile);
180
+ if (!saved)
181
+ return null;
182
+ const origin = new URL(saved.endpoint).origin;
183
+ const { TokenManager } = await import("./bridgeExchange.js");
184
+ // Never rotate: a refresh cut short by a caller's deadline must not lose the
185
+ // only copy of a new refresh token. The same reasoning as `passport hook`.
186
+ const manager = new TokenManager(saved.endpoint, saved.refreshToken, undefined, undefined, undefined, signal, fetcher);
187
+ return (path, init) => manager.authedFetch(`${origin}${path}`, init);
188
+ }
189
+ /** Fetch, validate, and atomically replace the cache. Never rejects. */
190
+ export async function refreshCliPolicy(profile, signal, deps = {}) {
191
+ try {
192
+ assertProfileName(profile);
193
+ const api = deps.api ?? (await defaultApi(profile, signal, deps.fetch ?? fetch));
194
+ if (!api)
195
+ return "unavailable";
196
+ const response = await api(CLI_POLICY_PATH, {
197
+ method: "GET",
198
+ headers: { accept: "application/json", "x-passport-surface": "cli" },
199
+ signal
200
+ });
201
+ if (!response.ok) {
202
+ await response.body?.cancel().catch(() => undefined);
203
+ return response.status === 404 ? "unavailable" : "failed";
204
+ }
205
+ const policy = parseCliPolicy(await readBoundedJson(response, MAX_BYTES));
206
+ if (!policy)
207
+ return "failed";
208
+ if (signal.aborted)
209
+ return "failed";
210
+ writeCliPolicy(profile, policy, (deps.now ?? Date.now)());
211
+ return "updated";
212
+ }
213
+ catch {
214
+ return "failed";
215
+ }
216
+ }