passport-bridge 0.16.10 → 0.16.12

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.
package/README.md CHANGED
@@ -139,10 +139,10 @@ Eight steps, each reusing the command that owns it:
139
139
  1. **Scan**: the same local scan as `passport scan`, as one summary line (`--verbose` prints the table).
140
140
  2. **Sign in**: reuses the active or only CLI profile, asks which one when there are several, or runs the browser sign-in from `passport login`.
141
141
  3. **Apps**: Railway, Vercel, Supabase, Cloudflare, GitHub, and Stripe, when the scan found a key or its CLI is on PATH. Missing apps are added through the same catalog rules as the web (an app your workspace reviews first says `! Stripe needs approval from your admin.`), then one sign-in page covers the rest. In a terminal init waits until they connect (Enter stops waiting); with `--yes` or without a terminal it prints the page, adds `passport connect --wait 300` to `next`, and moves on.
142
- 4. **Keys**: the recommended setup keeps them; the plan says `Your Railway and GitHub keys stay on this computer. Move them any time: passport keys move`. Step by step asks the same question as `passport keys move` for each: `Store your Railway account token in Passport and sign the Railway CLI out on this computer? [y/n]`. It has no default: Enter asks again (`Type y or n.`). Add `--move-keys` to move every key it finds without asking; the closing list then says which (`Moved your Railway key into Passport and signed that CLI out here`) and, once per moved key, where to rotate the old one (`Rotate the old Railway key, since copies may exist elsewhere: https://railway.com/account/tokens`). When Passport already holds a different key for that CLI, an interactive run asks `Replace the Railway key in Passport with the one on this computer? [y/n]` (no default): yes replaces it and signs the CLI out, keeping links; no prints `Kept the key in Passport. This computer's Railway CLI stays signed in.` `--yes` never replaces a key. Quiet when there's nothing to move.
142
+ 4. **Keys**: the recommended setup keeps them; the plan says `Your Railway and GitHub keys stay on this computer. Move them any time: passport keys move`. Step by step asks the same question as `passport keys move` for each: `Store your Railway account token in Passport and sign the Railway CLI out on this computer? [y/N]`. Enter keeps the key here; an answer that isn't y or n asks again (`Type y or n.`). Add `--move-keys` to move every key it finds without asking; the closing list then says which (`Moved your Railway key into Passport and signed that CLI out here`) and, once per moved key, where to rotate the old one (`Rotate the old Railway key, since copies may exist elsewhere: https://railway.com/account/tokens`). When Passport already holds a different key for that CLI, an interactive run asks `Passport already holds a different Railway key. Replace it with this computer's? Every agent that uses it switches to this one.` then `Type railway to confirm, or press Enter to cancel:`: only the name replaces it and signs the CLI out, keeping links; anything else prints `Kept the key in Passport. This computer's Railway CLI stays signed in.` `--yes` never replaces a key. Quiet when there's nothing to move.
143
143
  5. **Environments**: the environments Passport has placed for your apps, grouped by kind (`Production production (Railway), production (Vercel)`), one row per resource. Anything Passport can't place counts as Production and is listed once: `Treated as Production until placed: blue (Railway). Change it in Rules.` A resource named for its kind (`production` in Production) is never called assumed. This folder's links follow (`This folder: Railway production · linked · Production`). With no app connected yet it says they appear once one is.
144
144
  6. **Agents**: Passport's one MCP URL with this workspace as its hint (`https://passportmcp.com/mcp?ws=<workspace>`), with each agent's own browser sign-in; a server that doesn't serve `/mcp` yet (read from its OAuth protected-resource metadata) gets the workspace's own URL (`https://<host>/w/<workspace>/mcp`). An existing entry at either URL for this workspace counts as set up, so no token lands in a config file. Claude Code and Codex through their own CLIs (`claude mcp add --transport http --scope user`, `codex mcp add --url`), Cursor through `~/.cursor/mcp.json`, VS Code through `code --add-mcp` or its user `mcp.json`. Claude Desktop connects through Settings → Connectors: on a terminal init copies the URL and says `Claude Desktop: Settings → Connectors → Add custom connector → paste the URL (copied)`; without one it names the URL.
145
- 7. **Guard**: (step by step asks `Check each shell command in <agents> before it runs? [Y/n]`) runs `passport hook install --guard` for Claude Code, Codex, and Cursor (Codex: blocks only), pointing at the launcher `$PASSPORT_HOME/cli/bin/passport` (`passport.cmd` on Windows), which runs a stable copy of the CLI in `$PASSPORT_HOME/cli/<version>/` (never npm's cache), or at a global `passport-bridge` of the same version or newer. An upgrade rewrites the launcher and the `cli/current` link in one rename each, so hooks follow without being edited; the launcher runs the recorded node, or the node on PATH once that one is removed. A hook from an older init that names a version folder is replaced where it stands, next to your other hooks. Once the new copy is in place, older copies are deleted unless a hook still runs them.
145
+ 7. **Guard**: (step by step asks `Check each shell command in <agents> before it runs? [Y/n]`) runs `passport hook install --guard` for Claude Code, Codex, and Cursor (in Codex, a command your rules ask about is blocked with how to approve it, since Codex can't show Passport's questions), pointing at the launcher `$PASSPORT_HOME/cli/bin/passport` (`passport.cmd` on Windows), which runs a stable copy of the CLI in `$PASSPORT_HOME/cli/<version>/` (never npm's cache), or at a global `passport-bridge` of the same version or newer. An upgrade rewrites the launcher and the `cli/current` link in one rename each, so hooks follow without being edited; the launcher runs the recorded node, or the node on PATH once that one is removed. A hook from an older init that names a version folder is replaced where it stands, next to your other hooks. Once the new copy is in place, older copies are deleted unless a hook still runs them.
146
146
  8. **Autopilot**: how much agents can do on their own, per environment:
147
147
 
148
148
  ```
@@ -289,7 +289,8 @@ passport actions sync # propose this repository's .passport/actions.toml
289
289
  ### Keys and passport exec
290
290
 
291
291
  ```sh
292
- passport keys move # confirm each key [y/n], store it in Passport, sign that CLI out here
292
+ passport keys move # confirm each key [y/N], store it in Passport, sign that CLI out here
293
+ passport keys move railway # only the Railway key
293
294
  passport keys # what Passport holds, and what's still on this computer
294
295
  passport keys add railway # store a key you paste (stdin, never echoed)
295
296
  passport exec -- railway up -e staging
@@ -301,9 +302,9 @@ passport keys shim # the CLIs that run through Passport when you type
301
302
  - Releases: Passport's own release computer keeps its Railway sign-in, so releases never depend on Passport. In a repository with `scripts/lib/local-release-controller.mjs`, `keys move` and `init` ask `This computer deploys Passport with the Railway CLI. Moving the key will stop releases. Keep it here? [Y/n]` (Enter, `--yes`, and no terminal keep it). Release attestation checks the exact Railway CLI binary on PATH with a throwaway HOME, so a shim in front of it fails closed. See `docs/DEPLOY.md`.
302
303
 
303
304
  - After a move, `keys move` remembers where each removed key was in `$PASSPORT_HOME/keys-moved.json` (vendor, `~/…` location, file, field names, size, modified time; never a value or hash). With the daily guard report, files that changed are read again; a key that's back is reported as `reappeared: [vendor]` on `POST /api/my/keys/report`, so the key reads "Back on <computer>" in Apps with the fix `passport keys move`. Kept keys are never listed. The report's computer is the CLI's own sign-in (its Device); the name it sends stays for older servers.
304
- - `keys move` finds CLI sign-ins (Railway, GitHub CLI, Vercel, Wrangler API tokens, Supabase, Stripe test keys, the AWS `default` profile) and tokens in Claude Code's settings `env`. For each it asks `[y/n]` with no default (an empty answer asks again; `--yes` moves them all), stores the key in Passport (`POST /api/my/keys`), then signs that CLI out by removing only the credential: the token fields of `~/.railway/config.json` (project links stay), `token` in Vercel's `auth.json` (not revoked; the current team stays), Wrangler's sign-in keys in `default.toml`, the Supabase `access-token` file and its keychain token (saved database passwords stay), the Stripe profile's API keys and its live key in the keychain (account, color, and other profiles stay), the AWS profile's key lines, or the one settings entry. Files are written atomically with their mode kept. Vendor sign-outs don't run because they do more (`railway logout` unlinks every project, `vercel logout` revokes the token Passport just stored); only the GitHub CLI's `gh auth logout --hostname github.com` runs, adding `--user <active>` when several accounts are signed in, so other hosts and accounts stay. Keychain items are deleted by exact service and account (`security delete-generic-password` on macOS, `secret-tool clear` on Linux); where that isn't possible the row says which keychain copy may stay. Wrangler OAuth tokens are removed locally, not revoked. A sign-out that fails leaves the key in Passport and says what's left on disk. `.env` files are never touched: "Used by your app, so Passport leaves it." Browser-session sign-ins (Railway, Vercel, Wrangler OAuth) can't move; the line says how to make a token instead. A different key than the one already in Passport is replaced only when the person answers yes to `Replace the <CLI> key in Passport with the one on this computer? [y/n]`; the CLI then names the key it replaces (`replace: <keyId>` on `POST /api/my/keys`). The server alerts the owner and admins with an Undo, records it in the audit trail, and keeps the old value encrypted for seven days (`POST /api/my/keys/:id/restore` from the browser, or the alert). Without a person (`--yes`, no terminal), both keys stay. The scan report sent afterwards carries provider counts only.
305
+ - `keys move` finds CLI sign-ins (Railway, GitHub CLI, Vercel, Wrangler API tokens, Supabase, Stripe test keys, the AWS `default` profile) and tokens in Claude Code's settings `env`. For each it asks `[y/N]` (Enter keeps it; `--yes` moves them all; `keys move <cli>` only that CLI's), stores the key in Passport (`POST /api/my/keys`), then signs that CLI out by removing only the credential: the token fields of `~/.railway/config.json` (project links stay), `token` in Vercel's `auth.json` (not revoked; the current team stays), Wrangler's sign-in keys in `default.toml`, the Supabase `access-token` file and its keychain token (saved database passwords stay), the Stripe profile's API keys and its live key in the keychain (account, color, and other profiles stay), the AWS profile's key lines, or the one settings entry. Files are written atomically with their mode kept. Vendor sign-outs don't run because they do more (`railway logout` unlinks every project, `vercel logout` revokes the token Passport just stored); only the GitHub CLI's `gh auth logout --hostname github.com` runs, adding `--user <active>` when several accounts are signed in, so other hosts and accounts stay. Keychain items are deleted by exact service and account (`security delete-generic-password` on macOS, `secret-tool clear` on Linux); where that isn't possible the row says which keychain copy may stay. Wrangler OAuth tokens are removed locally, not revoked. A sign-out that fails leaves the key in Passport and says what's left on disk. `.env` files are never touched: "Used by your app, so Passport leaves it." Browser-session sign-ins (Railway, Vercel, Wrangler OAuth) can't move; the line says how to make a token instead. A different key than the one already in Passport is replaced only when the person types the CLI's name at a terminal (`Type railway to confirm, or press Enter to cancel:`); no flag does it, so an agent's script can never swap a key. The CLI then names the key it replaces (`replace: <keyId>` on `POST /api/my/keys`). The server alerts the owner and admins with an Undo, records it in the audit trail, and keeps the old value encrypted for seven days (`POST /api/my/keys/:id/restore` from the browser, or the alert). Without a person at a terminal (`--yes`, no terminal), both keys stay, and the line says `Replacing a key in Passport needs you at a terminal. Run passport keys move railway yourself.` The scan report sent afterwards carries provider counts only.
305
306
  - `exec -- <cli> …` runs railway, gh, vercel, wrangler, supabase, stripe, aws, neonctl, or flyctl from PATH. It classifies the command here, asks `POST /api/my/exec/authorize`, and on allow sets only that vendor's variables (`GH_TOKEN`, `RAILWAY_API_TOKEN`, `VERCEL_TOKEN`, `CLOUDFLARE_API_TOKEN`, `SUPABASE_ACCESS_TOKEN`, `STRIPE_API_KEY`, `AWS_*`, `NEON_API_KEY`, `FLY_API_TOKEN`) in the child's environment, removing Passport's own and any stray vendor tokens. Output and exit code pass through. Afterwards it reports the exit code and duration (`POST /api/my/exec/result`, best effort, two seconds at most) so the session row reads Ran or Failed. It refuses paths, shells, `env`, and subcommands that would print the key, sign in again, mint longer-lived tokens, or run another program with the key (`railway run`, `gh auth`, gh extensions, `aws configure`, `vercel dev`, `fly tokens`).
306
- - Asks wait for your approval in Passport (web or push) when you're at the keyboard or with `--wait <sec>`; otherwise exit 4 with the approval id: run `passport wait <id>`, then the command again. While it waits, the approval link prints at once and, on a terminal, one live line counts down (`Waiting for Erin · 1:32 left`); piped, it prints the waiting line and `Open in Passport: <url>`. Ctrl-C exits 4: `The request is still open. Run passport wait <id> to keep waiting, then run the command again.` An approval is used once. Blocked or declined: exit 5. A decline answers the same command for ten minutes, said with who and when: `Declined 2 minutes ago by Erin: Not during the freeze.` and `Run with --ask-again to request again.`; `--ask-again` opens a new request. No key, or it stopped working: exit 3 ("Your Railway key in Passport stopped working. Update it in Apps."). Offline: exit 1, nothing runs, and exec never uses a key on this computer instead. A team that requires the guard refuses exec for an agent whose computer hasn't reported its guard On in 48 hours: exit 5 with `Blocked by Passport: guard required…` and the fix.
307
+ - Asks wait for your approval in Passport (web or push) when you're at the keyboard or with `--wait <sec>`; otherwise exit 4 with the approval id: run `passport wait <id>`, then the command again. While it waits, the approval link prints at once and, on a terminal, one live line counts down (`Waiting for Erin · 1:32 left`); piped, it prints the waiting line and `Open in Passport: <url>`. Ctrl-C exits 4: `The request is still open. Run passport wait <id> to keep waiting, then run the command again.` An approval is used once. Blocked or declined: exit 5. A decline answers the same command for ten minutes, said with who and when: `Declined 2 minutes ago by Erin: Not during the freeze.` and `Run with --ask-again to request again.`; `--ask-again` opens a new request. No key, or it stopped working: exit 3 (`No Railway key in Passport yet. Add a Railway key in Passport → Apps.`, or `Your Railway key in Passport stopped working. Update it in Apps.`). When this computer still has the Railway CLI's own sign-in, the no-key line is `No Railway key in Passport yet, but this computer has one. Run passport keys move railway` instead (read here; Passport never sees this computer's files). Offline: exit 1, nothing runs, and exec never uses a key on this computer instead. A team that requires the guard refuses exec for an agent whose computer hasn't reported its guard On in 48 hours: exit 5 with `Blocked by Passport: guard required…` and the fix.
307
308
  - In Claude Code, the guard rewrites a plain vendor command whose key is in Passport to `passport exec` (PreToolUse `updatedInput` with allow; a block stays a deny). When the rules ask, or someone is at the keyboard, the rewrite adds `--wait 120`, so the agent holds while the person approves: "Approve it on your phone or in Passport." Codex and Cursor get no rewrite: use `passport exec` there.
308
309
  - Cloud agents (Agents → Cloud agents) run exec and MCP with `PASSPORT_AGENT_KEY` and `PASSPORT_ENDPOINT`: the owner's rules decide, the owner's keys are used, and approvals go to the owner.
309
310
  - Backups: for `gh issue close`, `gh pr close`, `gh api -X DELETE` of a branch, `vercel env rm`, `vercel rollback`, and `vercel promote`, exec also sends the ids Passport needs to take a backup first (repo and number or branch; the linked Vercel project and variable name from `.vercel/project.json`), never a value. After the run it prints `Backup taken. Undo within 7 days: passport undo <action-id>`, or `No backup: <reason>` for a delete it couldn't back up.
@@ -421,6 +422,10 @@ const actions = await client.actions(); // or client.actions(delegationId)
421
422
 
422
423
  With `--json`, stdout is exactly one JSON value; hints and warnings go to stderr. JSON shapes only gain fields.
423
424
 
425
+ A mistyped command, option, subcommand, or `help <command>` exits 6 with the closest match, stated rather than asked (`Unknown command "stauts". Did you mean: passport status`, `Unknown option "--jsn". Did you mean: --json`); with `--json` the match is in `next`. With nothing close it says where to look (`Run passport help to see every command.`). `help <unknown>` never prints the general help. Help pages lead with examples, and `passport help` ends with the exit codes below.
426
+
427
+ Questions follow one convention (`src/cliAsk.ts`), only on a terminal: `[Y/n]` for a safe step (Enter is yes); `[y/N]` for a destructive one, such as signing a CLI out, switching who you're signed in as, or an undo (Enter is no); and for a severe one you type its name (`Type railway to confirm, or press Enter to cancel:`). `--yes` never answers a severe question. A severe step a script may take gets `--confirm=<name>`; replacing a key Passport holds, today's only severe step, deliberately has no flag, so it only ever happens on a person's answer at a terminal.
428
+
424
429
  On a terminal, human output comes from one renderer (`src/term.ts`): it wraps to the window's width (at least 40 columns, at most 100) without breaking a URL or a `passport` command, hangs wrapped lines under their label or mark, stacks a table one row at a time when its columns don't fit, and clips a live line (a countdown, a "Checking…" row) to one row so it's always replaced cleanly. Marks always sit next to words (`✓ On`, `! Not trusted`, `– skipped`), with `+`, `!`, `-` where the terminal can't show them. Piped output never wraps, has no color, and draws no live lines. `NO_COLOR` and `TERM=dumb` turn color off.
425
430
 
426
431
  | Command | JSON value |
@@ -459,7 +464,7 @@ Errors: `{"error":"...","cause":"blocked","exitCode":5,"app":"github"}`, optiona
459
464
  | 3 | App needs member sign-in |
460
465
  | 4 | Approval pending (including `wait` still waiting at its timeout) |
461
466
  | 5 | Policy, guardrail, selection, or approval denial (including a declined or expired approval in `wait`) |
462
- | 6 | Invalid usage or unknown tool/app |
467
+ | 6 | Usage mistake: an unknown command, option, tool, or app (with the closest match when there is one) |
463
468
 
464
469
  ## MCP stdio bridge
465
470
 
@@ -482,6 +487,8 @@ passport-bridge serve --profile cursor@ws_example
482
487
 
483
488
  ## Maintainers
484
489
 
490
+ Startup: `dist/passport.js` (the npm bin, the launcher `$PASSPORT_HOME/cli/bin/passport`, and `passport.cmd` on Windows) and the hooks' `dist/hookMain.js` are tiny entries that turn on Node's compile cache (`module.enableCompileCache`, `src/compileCache.ts`) before loading the CLI (`src/cliMain.ts`), so the second and later runs skip compiling it. The cache is `$PASSPORT_HOME/cli/compile-cache` (`~/.passport/cli/compile-cache`), created 0700 and used only while it's owned by this user and nobody else can write it: never the repository or the system's temp folder. `NODE_COMPILE_CACHE` and `NODE_DISABLE_COMPILE_CACHE` keep Node's meaning. `npm run bench:guard` times the guard and `version`, `--help`, and `status` (piped, Passport refusing connections) through the launcher; `PASSPORT_BENCH_NO_CACHE=1` times the same build without the cache. The hook path never loads the renderer or prompt code (`src/termImports.test.ts`).
491
+
485
492
  Tests never reach production Passport: `scripts/no-production-guard.mjs` is preloaded by the unit tests and, through `NODE_OPTIONS`, by every process `cli-e2e.ts` starts, and any request to passportmcp.com fails the run. Harnesses use a local server with `--cloud http://127.0.0.1:<port>` (or `PASSPORT_CLOUD`) and `PASSPORT_NO_OPEN=1`.
486
493
 
487
494
  `npm run pack:verified` builds the npm tarball, checks required files, and writes a `.sha256` checksum file (verify with `sha256sum -c passport-bridge-<version>.tgz.sha256`). Releases publish only through the repository's npm trusted-publisher workflow.
package/dist/cli.js CHANGED
@@ -38,7 +38,7 @@ async function passportOneLiner() {
38
38
  return;
39
39
  }
40
40
  ensureOneLinerRuntime();
41
- const { main: passport } = await import("./passport.js");
41
+ const { main: passport } = await import("./cliMain.js");
42
42
  process.exitCode = await passport(process.argv.slice(2), process.env, {
43
43
  stdin: process.stdin,
44
44
  stdout: process.stdout,
@@ -62,7 +62,11 @@ async function main() {
62
62
  return logout();
63
63
  if (command === "status")
64
64
  return status();
65
- process.stderr.write(`Unknown command: ${command}\nRun \`passport-bridge --help\` for usage.\n`);
65
+ const { closest } = await import("./cliSuggest.js");
66
+ const guess = closest(command, ["serve", "login", "logout", "status", "help", "version", ...PASSPORT_ONE_LINERS]);
67
+ process.stderr.write(guess
68
+ ? `Unknown command "${command}". Did you mean: passport-bridge ${guess}\n`
69
+ : `Unknown command "${command}". Run passport-bridge --help to see every command.\n`);
66
70
  process.exit(1);
67
71
  }
68
72
  function help() {
@@ -23,6 +23,8 @@ import { memberApi } from "./cliClient.js";
23
23
  import { localMachine, NODE_FS } from "./cliHookLocal.js";
24
24
  import { lookupOpaqueId, normalizeRemote, originUrl, remoteFingerprint, sha256 } from "./cliScriptRead.js";
25
25
  import { linesDigestInput, makeLines, packageLines, parseRepoActions } from "./cliScriptText.js";
26
+ import { unknownSubcommand } from "./cliSuggest.js";
27
+ import { table, termOf } from "./term.js";
26
28
  import { callerFrom, failure, resolveCliAuth, safeApiError, timeoutMs } from "./cliSupport.js";
27
29
  const ENVIRONMENTS = new Set(["production", "staging", "development"]);
28
30
  const CLASSES = new Set(["read", "change", "delete", "irreversible"]);
@@ -196,19 +198,22 @@ async function list(args, runtime, deps) {
196
198
  return failure(await safeApiError(response, "Passport couldn't list them."), 1, "server");
197
199
  const body = (await readBoundedJson(response).catch(() => ({})));
198
200
  const actions = body.projectActions ?? [];
199
- const human = actions.length
200
- ? actions
201
- .map((action) => {
202
- const where = action.environment ? (ENV_WORD[action.environment] ?? action.environment) : "";
203
- const notes = [
204
- action.repoName ?? "Any repository",
205
- ...(action.setByName ? [`Set by ${action.setByName}`] : []),
206
- ...(action.status === "proposed" ? ["Proposed"] : []),
207
- ...(action.changedAt ? ["Changed since set"] : [])
208
- ];
209
- return `${action.label ?? "script"} ${where} · ${action.actionClass ?? ""} ${notes.join(" · ")}`;
210
- })
211
- .join("\n")
201
+ // One aligned row per script (script, environment, class, repository,
202
+ // notes); on a narrow terminal each row stacks.
203
+ const rows = actions.map((action) => [
204
+ action.label ?? "script",
205
+ action.environment ? (ENV_WORD[action.environment] ?? action.environment) : "",
206
+ action.actionClass ?? "",
207
+ action.repoName ?? "Any repository",
208
+ [
209
+ ...(action.setByName ? [`Set by ${action.setByName}`] : []),
210
+ ...(action.status === "proposed" ? ["Proposed"] : []),
211
+ ...(action.changedAt ? ["Changed since set"] : [])
212
+ ].join(" · ")
213
+ ]);
214
+ const width = termOf((runtime.stdout ?? {}), runtime.env).width;
215
+ const human = rows.length
216
+ ? table(rows, width).join("\n")
212
217
  : "No project scripts yet. Add one: passport actions add <script> --environment <kind> --class <class>";
213
218
  return { json: { actions }, human };
214
219
  }
@@ -220,5 +225,6 @@ export async function actions(args, runtime, deps = {}) {
220
225
  return add(args, runtime, deps);
221
226
  if (action === "sync")
222
227
  return sync(args, runtime, deps);
223
- return failure("Use passport actions, actions add, or actions sync.", 6, "usage");
228
+ const unknown = unknownSubcommand("actions", action, ["list", "add", "sync"]);
229
+ return failure(unknown.message, 6, "usage", unknown.next ? { next: unknown.next } : {});
224
230
  }
package/dist/cliArgs.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  export declare const COMMANDS: readonly ["init", "login", "logout", "profiles", "use", "status", "doctor", "ready", "search", "describe", "run", "connect", "resources", "prompts", "discover", "scan", "hook", "wait", "rules", "actions", "sessions", "env", "sync", "exec", "undo", "keys", "setup", "session", "access", "completion", "help", "version"];
2
2
  export type Command = (typeof COMMANDS)[number];
3
+ /** A usage mistake. `suggestion` is the command the person most likely meant. */
3
4
  export declare class ArgError extends Error {
5
+ readonly suggestion?: string[] | undefined;
6
+ constructor(message: string, suggestion?: string[] | undefined);
4
7
  }
5
8
  export type ParsedArgs = {
6
9
  command: Command;
package/dist/cliArgs.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { closest } from "./cliSuggest.js";
1
2
  export const COMMANDS = [
2
3
  "init",
3
4
  "login",
@@ -91,7 +92,34 @@ const FLAGS = {
91
92
  const FLAG_ALIASES = { agent: "client", agents: "clients" };
92
93
  const shownFlag = (name) => Object.keys(FLAG_ALIASES).find((alias) => FLAG_ALIASES[alias] === name) ?? name;
93
94
  const passedTwice = (name) => shownFlag(name) === name ? `--${name} may only be passed once.` : `Pass --${shownFlag(name)} or --${name} once.`;
95
+ /** A usage mistake. `suggestion` is the command the person most likely meant. */
94
96
  export class ArgError extends Error {
97
+ suggestion;
98
+ constructor(message, suggestion) {
99
+ super(message);
100
+ this.suggestion = suggestion;
101
+ }
102
+ }
103
+ /** Every option name a command takes, as typed (`--agent`, not `--client`). */
104
+ function optionsFor(command) {
105
+ const names = Object.keys(FLAGS)
106
+ .filter((name) => !command || !FLAGS[name].commands || FLAGS[name].commands.includes(command))
107
+ .map(shownFlag);
108
+ return [...new Set(names)];
109
+ }
110
+ function unknownCommand(raw, help = false) {
111
+ const guess = closest(raw, COMMANDS);
112
+ const argv = guess ? ["passport", ...(help ? ["help"] : []), guess] : undefined;
113
+ return new ArgError(`Unknown command "${raw}". ${argv ? `Did you mean: ${argv.join(" ")}` : "Run passport help to see every command."}`, argv);
114
+ }
115
+ function unknownOption(raw, command) {
116
+ const given = raw.startsWith("--") ? flagParts(raw).name : raw.replace(/^-+/, "");
117
+ const guess = closest(given, optionsFor(command));
118
+ if (guess) {
119
+ return new ArgError(`Unknown option "${raw}". Did you mean: --${guess}`, command ? ["passport", command, `--${guess}`] : undefined);
120
+ }
121
+ const where = command && command !== "help" ? `passport help ${command}` : "passport help";
122
+ return new ArgError(`Unknown option "${raw}". Run ${where} to see the options.`);
95
123
  }
96
124
  function knownCommand(value) {
97
125
  return COMMANDS.includes(value);
@@ -109,6 +137,9 @@ export function parseArgs(argv) {
109
137
  const repeats = {};
110
138
  const booleans = new Set();
111
139
  let positionalOnly = false;
140
+ // An unknown option is reported once the command is known, so the
141
+ // suggestion comes from that command's own options.
142
+ let unknown;
112
143
  for (let i = 0; i < argv.length; i++) {
113
144
  let raw = argv[i];
114
145
  if (!positionalOnly && raw === "--") {
@@ -128,8 +159,10 @@ export function parseArgs(argv) {
128
159
  const { name: given, inline } = flagParts(raw);
129
160
  const name = FLAG_ALIASES[given] ?? given;
130
161
  const spec = FLAGS[name];
131
- if (!spec)
132
- throw new ArgError(`Unknown option: --${given}`);
162
+ if (!spec) {
163
+ unknown ??= raw;
164
+ continue;
165
+ }
133
166
  if (spec.kind === "boolean") {
134
167
  if (inline !== undefined)
135
168
  throw new ArgError(`--${name} does not take a value.`);
@@ -151,11 +184,13 @@ export function parseArgs(argv) {
151
184
  }
152
185
  continue;
153
186
  }
154
- if (!positionalOnly && raw.startsWith("-") && raw !== "-")
155
- throw new ArgError(`Unknown option: ${raw}`);
187
+ if (!positionalOnly && raw.startsWith("-") && raw !== "-") {
188
+ unknown ??= raw;
189
+ continue;
190
+ }
156
191
  if (!command) {
157
192
  if (!knownCommand(raw))
158
- throw new ArgError(`Unknown command: ${raw}`);
193
+ throw unknownCommand(raw);
159
194
  command = raw;
160
195
  }
161
196
  else {
@@ -166,7 +201,14 @@ export function parseArgs(argv) {
166
201
  positionalOnly = true;
167
202
  }
168
203
  }
169
- command ??= "help";
204
+ if (unknown !== undefined)
205
+ throw unknownOption(unknown, command);
206
+ return settle({ command: command ?? "help", positionals, values, repeats, booleans });
207
+ }
208
+ /** `--help` becomes `help <command>`; then every option must fit the command. */
209
+ function settle(args) {
210
+ let { command } = args;
211
+ const { positionals, values, repeats, booleans } = args;
170
212
  if (booleans.has("help") && command !== "help") {
171
213
  positionals.splice(0, positionals.length, command);
172
214
  command = "help";
@@ -177,6 +219,8 @@ export function parseArgs(argv) {
177
219
  if (allowed && !allowed.includes(command))
178
220
  throw new ArgError(`--${shownFlag(name)} is not valid with ${command}.`);
179
221
  }
222
+ if (command === "help" && positionals[0] !== undefined && !knownCommand(positionals[0]))
223
+ throw unknownCommand(positionals[0], true);
180
224
  validateShape(command, positionals);
181
225
  validateNumbers(values);
182
226
  return { command, positionals, values, repeats, booleans };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The one question convention for every prompt the CLI shows (init, keys,
3
+ * undo, login):
4
+ *
5
+ * [Y/n] a safe step. Enter says yes.
6
+ * [y/N] a destructive step: it signs a CLI out, removes something
7
+ * from this computer, switches who you're signed in as, or
8
+ * undoes an action. Enter says no.
9
+ * type the name a severe step: it replaces a key every agent uses. Only the
10
+ * exact name says yes; Enter or anything else says no. A
11
+ * severe step a script may take gets --confirm=<name>; replacing
12
+ * a key Passport holds deliberately has none, so an agent's
13
+ * script can never swap one.
14
+ *
15
+ * A prompt only ever appears on a terminal. --yes answers safe and destructive
16
+ * questions, never a severe one.
17
+ */
18
+ export type Stakes = "safe" | "destructive";
19
+ export declare function choices(stakes: Stakes): "[Y/n]" | "[y/N]";
20
+ /** true or false, or undefined when the answer is neither. */
21
+ export declare function answerOf(answer: string, stakes: Stakes): boolean | undefined;
22
+ export declare const ASK_AGAIN = "Type y or n.";
23
+ /** Asks until the answer is yes, no, or Enter (the default). */
24
+ export declare function askYesNo(ask: (prompt: string) => Promise<string>, say: (text: string) => void, question: string, stakes: Stakes): Promise<boolean>;
25
+ /** The second line of a severe question. */
26
+ export declare function typeNamePrompt(name: string): string;
27
+ /** Only the exact name confirms. */
28
+ export declare function nameConfirmed(answer: string, name: string): boolean;
package/dist/cliAsk.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The one question convention for every prompt the CLI shows (init, keys,
3
+ * undo, login):
4
+ *
5
+ * [Y/n] a safe step. Enter says yes.
6
+ * [y/N] a destructive step: it signs a CLI out, removes something
7
+ * from this computer, switches who you're signed in as, or
8
+ * undoes an action. Enter says no.
9
+ * type the name a severe step: it replaces a key every agent uses. Only the
10
+ * exact name says yes; Enter or anything else says no. A
11
+ * severe step a script may take gets --confirm=<name>; replacing
12
+ * a key Passport holds deliberately has none, so an agent's
13
+ * script can never swap one.
14
+ *
15
+ * A prompt only ever appears on a terminal. --yes answers safe and destructive
16
+ * questions, never a severe one.
17
+ */
18
+ export function choices(stakes) {
19
+ return stakes === "safe" ? "[Y/n]" : "[y/N]";
20
+ }
21
+ /** true or false, or undefined when the answer is neither. */
22
+ export function answerOf(answer, stakes) {
23
+ const typed = answer.trim().toLowerCase();
24
+ if (typed === "y" || typed === "yes")
25
+ return true;
26
+ if (typed === "n" || typed === "no")
27
+ return false;
28
+ if (typed === "")
29
+ return stakes === "safe";
30
+ return undefined;
31
+ }
32
+ export const ASK_AGAIN = "Type y or n.";
33
+ /** Asks until the answer is yes, no, or Enter (the default). */
34
+ export async function askYesNo(ask, say, question, stakes) {
35
+ for (;;) {
36
+ const answer = answerOf(await ask(`${question} ${choices(stakes)} `), stakes);
37
+ if (answer !== undefined)
38
+ return answer;
39
+ say(ASK_AGAIN);
40
+ }
41
+ }
42
+ /** The second line of a severe question. */
43
+ export function typeNamePrompt(name) {
44
+ return `Type ${name} to confirm, or press Enter to cancel:`;
45
+ }
46
+ /** Only the exact name confirms. */
47
+ export function nameConfirmed(answer, name) {
48
+ return answer.trim() === name;
49
+ }
package/dist/cliExec.d.ts CHANGED
@@ -37,6 +37,8 @@ export type ExecDependencies = {
37
37
  cwd?: string;
38
38
  interactive?: boolean;
39
39
  now?: () => number;
40
+ /** Where to look for this computer's own CLI sign-ins (tests). */
41
+ home?: string;
40
42
  };
41
43
  type Authorized = {
42
44
  decision?: unknown;
package/dist/cliExec.js CHANGED
@@ -466,6 +466,9 @@ export async function exec(args, runtime, deps = {}) {
466
466
  if (removed.length && !bool(args, "quiet")) {
467
467
  runtime.stderr.write(`Removed Passport's ${removed.join(" and ")} shim, so ${binary} runs on its own again.\n`);
468
468
  }
469
+ if (auth.kind === "profile") {
470
+ throw (await import("./execNoKey.js")).keyHereFailure(error, vendor, runtime, deps.home);
471
+ }
469
472
  }
470
473
  throw error;
471
474
  }
@@ -133,8 +133,24 @@ export declare function profileAuth(args: ParsedArgs, env: Env): string | null;
133
133
  * couple of seconds. The hook itself never waits for it.
134
134
  */
135
135
  export declare function startFlushIfDue(profile: string, args: ParsedArgs, runtimeName: string, now: number): Promise<void>;
136
+ /** A detached flush is gone this long after its process started, whatever it
137
+ * is waiting on: the budget, then a second to write what it has. */
138
+ export declare const FLUSH_DEADLINE_MS: number;
139
+ /**
140
+ * Arm the hard deadline of a detached flush and return the exit it ends with.
141
+ * The abort budget is cooperative: it stops what listens to it, but a socket,
142
+ * a pool, or a slow start can keep a process alive past it, and an agent
143
+ * running hundreds of commands would then pile up flushes. So the process
144
+ * exits once its work is done, and in any case at the deadline (counted from
145
+ * process start, so a slow start counts too). Every file it writes is written
146
+ * synchronously and atomically, so exiting between two steps loses at most
147
+ * reports that would have been dropped anyway. The timer is deliberately not
148
+ * unref'd: it is the one thing guaranteed to end the process.
149
+ */
150
+ export declare function flushDeadline(release: () => void, exit?: (code: number) => void, startedMsAgo?: number): () => void;
136
151
  /** `passport hook flush`: what the hooks queued, sent within the budget by a
137
- * process nobody waits for. */
152
+ * process nobody waits for. Only one runs at a time per profile, and a
153
+ * detached one always exits by FLUSH_DEADLINE_MS. */
138
154
  export declare function runFlush(args: ParsedArgs, runtime: Runtime, deps: HookDependencies): Promise<void>;
139
155
  /** Leftover budget: Activity reports, a batch of answered counts and speed
140
156
  * numbers, and, at most hourly, a rules refresh (which keeps synced
@@ -4,6 +4,7 @@
4
4
  * `passport hook flush` (or a test's in-process run) waits on any of it; the
5
5
  * hooks themselves queue and return (`hookOutbox.ts`).
6
6
  */
7
+ import module from "node:module";
7
8
  import { value } from "./cliArgs.js";
8
9
  import { hasExpired, takeExpired } from "./cliHookPending.js";
9
10
  import { claimStaleRefresh, readCliPolicy, staleRefreshDue } from "./cliPolicy.js";
@@ -146,8 +147,43 @@ export async function startFlushIfDue(profile, args, runtimeName, now) {
146
147
  const named = value(args, "profile");
147
148
  outbox.startFlush(["--client", runtimeName, ...(named ? ["--profile", named] : [])]);
148
149
  }
150
+ /** A detached flush is gone this long after its process started, whatever it
151
+ * is waiting on: the budget, then a second to write what it has. */
152
+ export const FLUSH_DEADLINE_MS = HOOK_BUDGET_MS + 1_000;
153
+ /**
154
+ * Arm the hard deadline of a detached flush and return the exit it ends with.
155
+ * The abort budget is cooperative: it stops what listens to it, but a socket,
156
+ * a pool, or a slow start can keep a process alive past it, and an agent
157
+ * running hundreds of commands would then pile up flushes. So the process
158
+ * exits once its work is done, and in any case at the deadline (counted from
159
+ * process start, so a slow start counts too). Every file it writes is written
160
+ * synchronously and atomically, so exiting between two steps loses at most
161
+ * reports that would have been dropped anyway. The timer is deliberately not
162
+ * unref'd: it is the one thing guaranteed to end the process.
163
+ */
164
+ export function flushDeadline(release, exit = (code) => process.exit(code), startedMsAgo = performance.now()) {
165
+ let done = false;
166
+ const stop = () => {
167
+ if (done)
168
+ return;
169
+ done = true;
170
+ clearTimeout(timer);
171
+ release();
172
+ try {
173
+ // Written before exiting, not left to a teardown that may not finish.
174
+ module.flushCompileCache?.();
175
+ }
176
+ catch {
177
+ /* The next run compiles again. */
178
+ }
179
+ exit(0);
180
+ };
181
+ const timer = setTimeout(stop, Math.max(0, FLUSH_DEADLINE_MS - startedMsAgo));
182
+ return stop;
183
+ }
149
184
  /** `passport hook flush`: what the hooks queued, sent within the budget by a
150
- * process nobody waits for. */
185
+ * process nobody waits for. Only one runs at a time per profile, and a
186
+ * detached one always exits by FLUSH_DEADLINE_MS. */
151
187
  export async function runFlush(args, runtime, deps) {
152
188
  if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
153
189
  return;
@@ -156,24 +192,39 @@ export async function runFlush(args, runtime, deps) {
156
192
  if (!profile || auth !== profile)
157
193
  return;
158
194
  const clock = deps.now ?? Date.now;
159
- const policy = readCliPolicy(profile);
160
- const fast = await import("./hookFastPath.js");
161
- fast.drainFastPathSpool(profile, clock());
162
- const { takeQueued } = await import("./hookOutbox.js");
163
- const queued = takeQueued(profile, clock());
164
- const named = value(args, "client")?.trim().toLowerCase();
165
- const runtimeName = HOOK_RUNTIMES.includes(named ?? "") ? named : "other";
166
- await leftovers(queued, {
167
- profile,
168
- policy,
169
- local: policy?.version === 2 && policy.autopilot.localCommands === true,
170
- runtimeName,
171
- budget: budgetSignal(runtime),
172
- runtime,
173
- args,
174
- deps
175
- });
176
- fast.refreshFastPath(profile, readCliPolicy(profile), byDefault, clock());
195
+ const outbox = await import("./hookOutbox.js");
196
+ // Another flush is sending: it takes whatever is queued, so this one stops here.
197
+ const release = outbox.takeFlushLock(profile);
198
+ if (!release)
199
+ return;
200
+ // Started by `startFlush` (not a test's in-process run): ends at the deadline.
201
+ const stop = !deps.send && !deps.fetch ? flushDeadline(release) : null;
202
+ try {
203
+ const policy = readCliPolicy(profile);
204
+ const fast = await import("./hookFastPath.js");
205
+ fast.drainFastPathSpool(profile, clock());
206
+ const queued = outbox.takeQueued(profile, clock());
207
+ const named = value(args, "client")?.trim().toLowerCase();
208
+ const runtimeName = HOOK_RUNTIMES.includes(named ?? "") ? named : "other";
209
+ await leftovers(queued, {
210
+ profile,
211
+ policy,
212
+ local: policy?.version === 2 && policy.autopilot.localCommands === true,
213
+ runtimeName,
214
+ budget: budgetSignal(runtime),
215
+ runtime,
216
+ args,
217
+ deps
218
+ });
219
+ fast.refreshFastPath(profile, readCliPolicy(profile), byDefault, clock());
220
+ }
221
+ finally {
222
+ // Done: nothing it started (an aborted socket, a keep-alive pool) keeps it alive.
223
+ if (stop)
224
+ stop();
225
+ else
226
+ release();
227
+ }
177
228
  }
178
229
  /** Post the answered counts and speed numbers as one report. A server that
179
230
  * doesn't know `speed` (400) still gets the counts; its speed batch is
@@ -51,6 +51,8 @@ export declare function registeredEntries(client: HookClient, env: Env): {
51
51
  guard: string | null;
52
52
  };
53
53
  export declare function displayPath(path: string): string;
54
+ /** What the guard does in Codex, in plain words (status, install, init). */
55
+ export declare const CODEX_BLOCK_ONLY = "Codex can't show Passport's questions, so Passport blocks a command your rules ask about and tells you how to approve it.";
54
56
  export type Change = {
55
57
  action: "add" | "update" | "remove";
56
58
  event: string;
@@ -324,7 +324,8 @@ export function displayPath(path) {
324
324
  const RECORDS_LINE = "It records the vendor, a coarse verb, and a risk class. Never the command line, its output, or your folder path.";
325
325
  const LIMITS_LINE = "It can't see inside scripts, aliases, or make targets.";
326
326
  const CODEX_TRUST_LINE = "Next: Open Codex → /hooks and trust Passport's hooks.";
327
- const CODEX_BLOCK_ONLY = "Codex can't ask from a hook, so commands set to ask are blocked and the approval comes to you.";
327
+ /** What the guard does in Codex, in plain words (status, install, init). */
328
+ export const CODEX_BLOCK_ONLY = "Codex can't show Passport's questions, so Passport blocks a command your rules ask about and tells you how to approve it.";
328
329
  function planLines(changes) {
329
330
  const width = Math.max(...changes.map((change) => change.event.length));
330
331
  return changes.map((change) => ` ${change.action.padEnd(6)} ${change.event.padEnd(width)} ${change.command}`);
@@ -6,7 +6,7 @@
6
6
  import { bool, value } from "./cliArgs.js";
7
7
  import { guardClientReports } from "./cliGuardHealth.js";
8
8
  import { GUARD_CLIENT_LABEL, GUARD_STATE_LABEL, fixLine, guardStateFix, localGuardState } from "./cliGuardState.js";
9
- import { HOOK_CLIENTS, agentHookStatus, displayPath } from "./cliHookInstall.js";
9
+ import { CODEX_BLOCK_ONLY, HOOK_CLIENTS, agentHookStatus, displayPath } from "./cliHookInstall.js";
10
10
  import { readCliPolicy } from "./cliPolicy.js";
11
11
  import { readCreds } from "./credentials.js";
12
12
  import { failure, selectStoredProfile } from "./cliSupport.js";
@@ -101,9 +101,7 @@ export async function hookStatus(args, runtime) {
101
101
  ].join(" ")),
102
102
  "",
103
103
  policy.line,
104
- ...(codexGuarded
105
- ? ["Codex can't ask from a hook, so commands set to ask are blocked and the approval comes to you."]
106
- : []),
104
+ ...(codexGuarded ? [CODEX_BLOCK_ONLY] : []),
107
105
  ...(disabled ? ["PASSPORT_HOOK_DISABLED=1 is set, so hooks do nothing in this shell."] : []),
108
106
  ...guardFixLines(guards)
109
107
  ];
package/dist/cliKeys.d.ts CHANGED
@@ -13,10 +13,15 @@ export type MoveIo = {
13
13
  confirm: (question: string) => Promise<boolean>;
14
14
  /**
15
15
  * Asks whether to replace a different key Passport already holds with this
16
- * computer's. Only when a person is there to answer: without it (--yes, no
17
- * terminal) Passport's key and this computer's sign-in both stay.
16
+ * computer's: a severe question, so the person types `name` (the CLI, like
17
+ * `railway`). Only when a person is at a terminal to answer: without it
18
+ * (--yes, no terminal) Passport's key and this computer's sign-in both
19
+ * stay. There is deliberately no flag for it: an agent's script must never
20
+ * swap a key Passport holds.
18
21
  */
19
- replace?: (question: string) => Promise<boolean>;
22
+ replace?: (question: string, name: string) => Promise<boolean>;
23
+ /** Only this CLI's key (`passport keys move railway`). */
24
+ only?: ExecVendor;
20
25
  /**
21
26
  * In a repository that deploys Passport with the Railway CLI: asks whether
22
27
  * to keep the Railway key here (`[Y/n]`, yes keeps it). Without it (--yes,
@@ -65,6 +70,8 @@ export declare function scanCounts(scan: ScanResult): {
65
70
  remaining: Record<string, number>;
66
71
  envFiles: string[];
67
72
  };
73
+ /** Without a person at a terminal, a key Passport holds is never replaced. */
74
+ export declare function replaceNeedsTerminal(vendor: ExecVendor): string;
68
75
  export declare function moveKeys(io: MoveIo): Promise<MoveSummary>;
69
76
  /** The lines after a move: what moved, what's left, where to rotate. */
70
77
  export declare function summaryLines(summary: MoveSummary): string[];