passport-bridge 0.16.2 → 0.16.4

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
@@ -46,34 +46,34 @@ passport run github_search_issues '{"query":"SSO"}'
46
46
 
47
47
  ## Commands
48
48
 
49
- | Command | Purpose |
50
- | --- | --- |
51
- | `init [--yes] [--move-keys] [--no-open] [--cloud <origin>] [--skip-apps\|--skip-agents\|--skip-guard] [--verbose] [--json]` | Set up Passport for this computer's agents in one pass. Every step asks first, can be skipped, and is safe to run again. |
52
- | `login` | Browser sign-in or sign-up (or device sign-in with `--workspace`); saves a rotating CLI credential and makes the profile active. |
53
- | `logout` | Revoke the credential and always remove the local profile (warns if revocation fails). |
54
- | `profiles` / `use <name>` | List stored profiles / select the active one. Offline. |
55
- | `status` | Workspace, member, agent, and app connection states, plus Autopilot presets, team floors, and how old this computer's copy of your rules is. |
56
- | `doctor` | Check Node, credential-file safety, HTTPS policy, `/healthz`, auth, serverInfo, and CLI protocol. Exit 1 on a failed check, with the full report. |
57
- | `ready` | Readiness preflight for automation; gate on its `ready` field and exit code. |
58
- | `search [query] [--app <key>]` | Search permitted tools. Empty query lists the full catalog. |
59
- | `describe <tool>` | One exact definition with its full parameter schema. |
60
- | `run <tool> [json]` | Run a tool through Passport governance. |
61
- | `connect [app...] [--alias <name>] [--open] [--wait <s>]` | Show member sign-in links and optionally wait for completion. |
62
- | `resources [uri] [--out <file>]` | List or read MCP resources. |
63
- | `prompts [name] [--set k=v] [--out <file>]` | List or get MCP prompts. |
64
- | `scan [--path <dir>] [--verbose] [--check]` | Find keys your agents can reach on this computer and what each can do. Local only, no account. `--check` scans files only (not the shell environment) and exits 5 on a high or medium key. |
65
- | `discover` | Scan local MCP configuration and submit a privacy-minimized fleet report. Exit 5 on a managed-policy violation. |
66
- | `hook` | Records the CLIs agents run and, with `--guard`, decides each one before it runs from your Autopilot rules (`install`, `uninstall`, `status`). |
67
- | `wait <approval-id> [--timeout <s>]` | Wait for a person to decide an approval request (default 100 seconds). |
68
- | `rules test "<command>" [--environment <kind>]` | What Autopilot decides for a command, why, and which environment it acts on. |
69
- | `sessions [--status running\|idle\|ended]` | Your agents' recent sessions with what Passport decided. |
70
- | `undo <action-id>\|--last [--option <id>] [--yes]` | Undo an action Passport took a backup before, within 7 days. See [Undo](#undo). |
71
- | `setup --org <pek_key> [--yes] [--clients <list>]` | Set up every agent on this computer for your company without asking anything (MDM and scripts). See [Company rollout](#company-rollout). |
72
- | `setup` | Install and maintain assigned team workflows as managed skills. |
73
- | `session` | Run NDJSON commands over one authenticated MCP session. |
74
- | `access` | Signed managed access: `keygen`, `actions`, `run`, `invoke`, `status`, `cancel`. |
75
- | `completion <bash\|zsh\|fish>` | Print a completion script. Offline. |
76
- | `help [command]`, `version` | Help; package version and local profile context. |
49
+ | Command | Purpose |
50
+ | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
51
+ | `init [--yes] [--move-keys] [--no-open] [--cloud <origin>] [--skip-apps\|--skip-agents\|--skip-guard] [--verbose] [--json]` | Set up Passport for this computer's agents in one pass. Every step asks first, can be skipped, and is safe to run again. |
52
+ | `login` | Browser sign-in or sign-up (or device sign-in with `--workspace`); saves a rotating CLI credential and makes the profile active. |
53
+ | `logout` | Revoke the credential and always remove the local profile (warns if revocation fails). |
54
+ | `profiles` / `use <name>` | List stored profiles / select the active one. Offline. |
55
+ | `status` | Workspace, member, agent, and app connection states, plus Autopilot presets, team floors, and how old this computer's copy of your rules is. |
56
+ | `doctor` | Check Node, credential-file safety, HTTPS policy, `/healthz`, auth, serverInfo, and CLI protocol. Exit 1 on a failed check, with the full report. |
57
+ | `ready` | Readiness preflight for automation; gate on its `ready` field and exit code. |
58
+ | `search [query] [--app <key>]` | Search permitted tools. Empty query lists the full catalog. |
59
+ | `describe <tool>` | One exact definition with its full parameter schema. |
60
+ | `run <tool> [json]` | Run a tool through Passport governance. |
61
+ | `connect [app...] [--alias <name>] [--open] [--wait <s>]` | Show member sign-in links and optionally wait for completion. |
62
+ | `resources [uri] [--out <file>]` | List or read MCP resources. |
63
+ | `prompts [name] [--set k=v] [--out <file>]` | List or get MCP prompts. |
64
+ | `scan [--path <dir>] [--verbose] [--check]` | Find keys your agents can reach on this computer and what each can do. Local only, no account. `--check` scans files only (not the shell environment) and exits 5 on a high or medium key. |
65
+ | `discover` | Scan local MCP configuration and submit a privacy-minimized fleet report. Exit 5 on a managed-policy violation. |
66
+ | `hook` | Records the CLIs agents run and, with `--guard`, decides each one before it runs from your Autopilot rules (`install`, `uninstall`, `status`). |
67
+ | `wait <approval-id> [--timeout <s>]` | Wait for a person to decide an approval request (default 100 seconds). |
68
+ | `rules test "<command>" [--environment <kind>]` | What Autopilot decides for a command, why, and which environment it acts on. |
69
+ | `sessions [--status running\|idle\|ended]` | Your agents' recent sessions with what Passport decided. |
70
+ | `undo <action-id>\|--last [--option <id>] [--yes]` | Undo an action Passport took a backup before, within 7 days. See [Undo](#undo). |
71
+ | `setup --org <pek_key> [--yes] [--clients <list>]` | Set up every agent on this computer for your company without asking anything (MDM and scripts). See [Company rollout](#company-rollout). |
72
+ | `setup` | Install and maintain assigned team workflows as managed skills. |
73
+ | `session` | Run NDJSON commands over one authenticated MCP session. |
74
+ | `access` | Signed managed access: `keygen`, `actions`, `run`, `invoke`, `status`, `cancel`. |
75
+ | `completion <bash\|zsh\|fish>` | Print a completion script. Offline. |
76
+ | `help [command]`, `version` | Help; package version and local profile context. |
77
77
 
78
78
  Global options: `--profile <name>`, `--json`, `--timeout <seconds>` (default 30), `--quiet`, `--caller <id>`.
79
79
 
@@ -137,7 +137,7 @@ Eight steps, each reusing the command that owns it:
137
137
  4. **Keys**: for each CLI sign-in on this computer, the same question as `passport keys move`: `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.`). `--yes` never moves a key: the step prints `Keys stayed on this computer. Run passport keys move to move them.` Add `--move-keys` to move every key it finds unasked; the closing summary then says which (`Moved your Railway key into Passport and signed that CLI out on this computer.`). Quiet when there's nothing to move.
138
138
  5. **Environments**: the environments Passport has placed for your apps, each with its kind: `Found 3 environments: production (Railway), preview (Vercel), qa (Railway)`. Anything Passport can't place counts as Production; change it any time in Rules. With no app connected yet it says `Environments appear once an app is connected.`
139
139
  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, so init prints that step.
140
- 7. **Guard**: asks `Apply your Autopilot rules before each shell command in <agents>? [Y/n]`, then runs `passport hook install --guard` for Claude Code, Codex, and Cursor (Codex: blocks only), pointing at 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. Once the new copy is in place, older copies are deleted unless a hook still runs them.
140
+ 7. **Guard**: asks `Apply your Autopilot rules before each shell command in <agents>? [Y/n]`, then 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.
141
141
  8. **Autopilot**: how much agents can do on their own, per environment:
142
142
 
143
143
  ```
@@ -152,15 +152,15 @@ Eight steps, each reusing the command that owns it:
152
152
 
153
153
  What changes on disk, and how to undo it:
154
154
 
155
- | Where | What | Undo |
156
- | --- | --- | --- |
157
- | `~/.passport/credentials.json` | A `cli@<workspace>` profile, as `passport login` writes | `passport logout` |
158
- | `~/.passport/cli/` | A copy of this CLI and `bin/passport` launchers | Delete the folder (after removing the hooks) |
159
- | `~/.claude.json` | A `passport` MCP server entry, via `claude mcp add` | `claude mcp remove --scope user passport` |
160
- | `~/.codex/config.toml` | `[mcp_servers.passport]`, via `codex mcp add` | `codex mcp remove passport` |
161
- | `~/.cursor/mcp.json` | `mcpServers.passport` | Delete that entry |
162
- | VS Code user `mcp.json` | `servers.passport` | `MCP: List Servers`, then remove it |
163
- | `~/.claude/settings.json`, `~/.codex/hooks.json`, `~/.cursor/hooks.json` | Passport's audit and guard hooks | `passport hook uninstall --client <agent> --apply` |
155
+ | Where | What | Undo |
156
+ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | -------------------------------------------------- |
157
+ | `~/.passport/credentials.json` | A `cli@<workspace>` profile, as `passport login` writes | `passport logout` |
158
+ | `~/.passport/cli/` | A copy of this CLI, the `bin/passport` launchers hooks run, and a `current` link | Delete the folder (after removing the hooks) |
159
+ | `~/.claude.json` | A `passport` MCP server entry, via `claude mcp add` | `claude mcp remove --scope user passport` |
160
+ | `~/.codex/config.toml` | `[mcp_servers.passport]`, via `codex mcp add` | `codex mcp remove passport` |
161
+ | `~/.cursor/mcp.json` | `mcpServers.passport` | Delete that entry |
162
+ | VS Code user `mcp.json` | `servers.passport` | `MCP: List Servers`, then remove it |
163
+ | `~/.claude/settings.json`, `~/.codex/hooks.json`, `~/.cursor/hooks.json` | Passport's audit and guard hooks | `passport hook uninstall --client <agent> --apply` |
164
164
 
165
165
  Before editing a file it didn't create, init says which file and keeps one copy of the original as `<file>.passport-backup`. It changes only Passport's own entries, writes atomically, refuses a malformed file with one line, and leaves an existing Passport entry alone unless it points at npm's cache or a file that's gone. Ctrl-C at any point stops cleanly; run init again to pick up where it left off. A question only takes keys typed after it appears, so an Enter pressed during a pause never answers it. Any wait longer than a moment shows what it's for in the step's row (`Sign in Checking your sign-in…`); off a terminal nothing extra prints. If Passport can't be reached, init says `Couldn't reach Passport at <origin>. Check your connection, then run passport init again.` and exits 1. Without a terminal, `init` needs `--yes` (exit 6 otherwise), and `--json` needs `--yes`. It never edits your shell profile: it prints the one `PATH` line to add if you want `passport` everywhere.
166
166
 
@@ -212,31 +212,31 @@ Two hooks per agent. `passport hook` runs after each shell command and records t
212
212
  - **Ask** or **deny** when any recognized command needs it. The strictest part of a compound command wins and names itself. `--help` and `--dry-run` never ask.
213
213
  - Each reason names its cause in one line: `Passport: railway redeploy changes Production. Approve to run it.`, or `Blocked by Passport: Team rule, no deletes in Production. Ask an admin to run it, or request an exception in Passport.`
214
214
 
215
- **Everyday commands** (`src/cliHookLocal.ts`, tables in `src/localCommands.ts`, `localTools.ts`, `localFiles.ts`, `localGit.ts`, `localNetwork.ts`). Local commands are placed by what they touch on this computer. The project folder (the git root, else the agent's folder; never `/` or the home folder) is Development: reads such as `ls`, `rg`, `git status`, test runners, linters, builds, and type checks are Reads; `git commit`, formatters with `--write`, package scripts, and `mv`/`cp` are Changes; `rm`, `git clean -fd`, and `git reset --hard` are Deletes. Package installs (`npm install`, `pip install`, `brew install`) are Changes in Other apps. `git push` to the default branch (origin's HEAD, else `main`/`master`) is a Change in Production, to any other branch a Change in Development; deleting a remote branch (`--delete`, `:branch`) is a Delete in Other apps because teammates share it. Temporary folders (`/tmp`, `$TMPDIR`) count as Development; deleting one whole is Irreversible. Outside the project: deleting the home folder, `/`, system paths, or the whole project is Irreversible; other writes are Changes and deletes are Deletes in Other apps; writes to keys, shell startup files, or an agent's own settings are Deletes, and reads of them are no decision. `curl`/`wget` GETs are Reads and anything that sends data is a Change, in Other apps (Development for localhost). docker `ps`/`logs` read, `run`/`build`/`compose up` change, `rm`/`prune` delete. `sudo` never runs silently. Symlinks are resolved before deciding, `cd` is followed through `&&`, `;`, and subshells, and redirects are writes where they land. The server keeps a generated copy of the tables (`node scripts/generate-local-commands.mjs`) for `rules test` on the web. Allowed project work and reads are counted on the machine ("Answered for you") rather than recorded one by one; installs, pushes, and anything that asks or blocks are recorded like vendor commands, with the environment kind and never a path.
215
+ **Everyday commands** (`src/cliHookLocal.ts`, tables in `src/localCommands.ts`, `localTools.ts`, `localFiles.ts`, `localGit.ts`, `localNetwork.ts`). Local commands are placed by what they touch on this computer. The project folder (the git root, else the agent's folder; never `/` or the home folder) is Development: reads such as `ls`, `rg`, `git status`, test runners, linters, builds, and type checks are Reads; `git commit`, formatters with `--write`, package scripts, and `mv`/`cp` are Changes; `rm`, `git clean -fd`, and `git reset --hard` are Deletes. Package installs (`npm install`, `pip install`, `brew install`) are Changes in Other apps. `git push` to the default branch (origin's HEAD, else `main`/`master`) is a Change in Production, to any other branch a Change in Development; deleting a remote branch (`--delete`, `:branch`) is a Delete in Other apps because teammates share it. Temporary folders (`/tmp`, `$TMPDIR`) count as Development; deleting one whole is Irreversible. Outside the project: deleting the home folder, `/`, system paths, or the whole project is Irreversible; other writes are Changes and deletes are Deletes in Other apps; writes to keys, shell startup files, or an agent's own settings are Deletes, and reads of them are no decision. `curl`/`wget` GETs are Reads and anything that sends data is a Change, in Other apps (Development for localhost). docker `ps`/`logs` read, `run`/`build`/`compose up` change, `rm`/`prune` delete. `sudo` never runs silently. The project's own code run directly (`node scripts/check.mjs`, `npx tsx scripts/x.ts`, `bash scripts/ci.sh`, `./scripts/ci.sh`, `make test`) is a Change in Development, like a package script; Passport can't read inside it, so it is never allowed and never recorded as opaque. `tsx --test` and `./node_modules/.bin/<tool>` are their tools, `bash -lc '…'` and `sh -c '…'` are read as the line inside, and Codex's `apply_patch <<'PATCH'` is a change to the files the patch names. A checkout an agent keeps for itself (`~/.codex/worktrees/…`, `~/.cursor/worktrees/…`) is the project, not the agent's settings. Symlinks are resolved before deciding, `cd` is followed through `&&`, `;`, and subshells, and redirects are writes where they land. The server keeps a generated copy of the tables (`node scripts/generate-local-commands.mjs`) for `rules test` on the web. Allowed project work and reads are counted on the machine ("Answered for you") rather than recorded one by one; installs, pushes, and anything that asks or blocks are recorded like vendor commands, with the environment kind and never a path.
216
216
 
217
217
  The environment comes from each vendor's own flags (`src/cliHookEnvironment.ts`): Railway `-e/--environment`, Wrangler and Sentry `-e/--env`, Vercel `--prod`/`--target` (a deploy without either is a preview), Supabase `--local`/`--linked`/`--project-ref` (`db reset` is local unless `--linked`), Stripe `--live` (test mode otherwise), `git push <remote> <branch>`, `psql` hosts (`localhost` is Development), fly and Heroku `-a/--app`, kubectl `--context`/`-n`, helm `--kube-context`/`-n`, AWS `--profile`, gcloud `--project`, plus any flags the server adds. Names follow Passport's rules (`prod|production|live|main` → Production, `stag|qa|uat|preview` → Staging, `dev|local|test|sandbox|feature|branch` → Development), and the workspace's own placement of a name wins. Anything else, or no flag at all (a linked project the hook can't see), counts as Production, and the reason says `Environment unknown, treated as Production.`
218
218
 
219
- **Attended or unattended** (`src/cliHookMode.ts`). With a person at the keyboard, an ask is the agent's own prompt with Passport's reason. With nobody there, the guard asks Passport instead (`POST /api/my/cli/decide`, inside the hook's budget): the server knows grants already given this session, every rule, and the workspace's environments. An allow from it runs the command (for example, a retry after approval); an ask becomes an approval request on the web and the person's phone, and the agent reads `` Waiting for approval from Ramish. Run `passport wait <id>` to wait, or continue with other work. `` If Passport can't answer in time, the local decision stands and the reason adds `Passport couldn't be reached, so this computer decided.` Signals, strongest first:
219
+ **Attended or unattended** (`src/cliHookMode.ts`). With a person at the keyboard, an ask is the agent's own prompt with Passport's reason. With nobody there, the guard asks Passport instead (`POST /api/my/cli/decide`, inside the hook's budget): the server knows grants already given this session, every rule, and the workspace's environments. An allow from it runs the command (for example, a retry after approval); an ask becomes an approval request on the web and the person's phone, and the agent reads ``Waiting for approval from Ramish. Run `passport wait <id>` to wait, or continue with other work.`` If Passport can't answer in time, the local decision stands and the reason adds `Passport couldn't be reached, so this computer decided.` Signals, strongest first:
220
220
 
221
- | Signal | Means |
222
- | --- | --- |
223
- | `PASSPORT_HOOK_MODE=attended\|unattended` | Override |
224
- | Claude Code `CLAUDE_CODE_SESSION_ATTENDED` (`1`/`0`), passed to every hook | Attended / unattended |
225
- | Hook input `permission_mode` `dontAsk` or `bypassPermissions` (Claude Code, Codex) | Unattended: prompts are suppressed |
226
- | Cursor `is_background_agent: true` | Unattended: background and cloud agents |
227
- | `CLAUDE_CODE_ENTRYPOINT` `sdk-cli` (`claude -p`), `sdk-ts`, `sdk-py`, `claude-code-github-action` | Unattended (older Claude Code builds) |
228
- | `CI`, `GITHUB_ACTIONS`, `GITLAB_CI`, `BUILDKITE`, `CIRCLECI`, `JENKINS_URL`, `TF_BUILD` | Unattended |
221
+ | Signal | Means |
222
+ | ------------------------------------------------------------------------------------------------- | --------------------------------------- |
223
+ | `PASSPORT_HOOK_MODE=attended\|unattended` | Override |
224
+ | Claude Code `CLAUDE_CODE_SESSION_ATTENDED` (`1`/`0`), passed to every hook | Attended / unattended |
225
+ | Hook input `permission_mode` `dontAsk` or `bypassPermissions` (Claude Code, Codex) | Unattended: prompts are suppressed |
226
+ | Cursor `is_background_agent: true` | Unattended: background and cloud agents |
227
+ | `CLAUDE_CODE_ENTRYPOINT` `sdk-cli` (`claude -p`), `sdk-ts`, `sdk-py`, `claude-code-github-action` | Unattended (older Claude Code builds) |
228
+ | `CI`, `GITHUB_ACTIONS`, `GITLAB_CI`, `BUILDKITE`, `CIRCLECI`, `JENKINS_URL`, `TF_BUILD` | Unattended |
229
229
 
230
230
  Codex has no field for `codex exec`; its prompt-free modes count as unattended, where an ask blocks for now with the waiting line.
231
231
 
232
232
  The approval request carries a command summary with secrets removed on this computer (`src/cliHookRedact.ts`, using `passport scan`'s key formats plus secret-named flags, variables, JSON fields, URL credentials, and long opaque values; heredoc bodies are dropped). It is the only part of a command line that ever leaves the machine, and only approvers see it.
233
233
 
234
- The guard decides from local data inside `HOOK_BUDGET_MS` (1.5 s) and prints first; only an unattended ask waits for the server, within the same budget. With the budget left, it reports its decision and, at most every ten minutes, refreshes a policy cache older than an hour. Any failure is silent and fails open. Neither hook sends the raw command line, output, folder path, or environment.
234
+ The guard decides from local data inside `HOOK_BUDGET_MS` (1.5 s) and prints first; only an unattended ask waits for the server, within the same budget. With the budget left, it reports its decision and, at most every ten minutes, refreshes a policy cache older than an hour. Any failure is silent and fails open. Neither hook sends the raw command line, output, folder path, or environment. Both hooks exchange the profile's refresh credential without rotating it and keep the short-lived access token in `$PASSPORT_HOME/.<profile>.access.json` (`src/accessTokenCache.ts`, mode 600, atomic replace), so most runs send one request instead of an exchange and then the request. A cached token is used only with more than a minute left; a 401 on it drops it, exchanges once, and retries once.
235
235
 
236
236
  An ask becomes one Activity row. In Claude Code, with the audit hook registered, the guard parks its report in `$PASSPORT_HOME/hook-pending/` (`src/cliHookPending.ts`, mode 600, claimed by atomic rename). The audit hook for the same tool-use id sends the run with `decision: "ask", ran: true` ("asked first, then ran"). An ask nobody claims within 30 minutes (no agent fires a hook for a declined prompt) is sent by the next hook run as `ran: false` ("asked first, not run"). An allow the server gave is parked the same way, so the run's row says `Approved earlier this session`. Cursor has no tool-use id to match, so its asks are sent at once as their own "asked first" row. Denies are always sent at once; asks and blocks the server decided are recorded by the server.
237
237
 
238
238
  - Claude Code: `PreToolUse`, plus `PostToolUse` and `PostToolUseFailure` (failed or interrupted calls, recorded as ran with a non-zero exit), in `~/.claude/settings.json` (`CLAUDE_CONFIG_DIR` honored).
239
- - Codex: the same events in `~/.codex/hooks.json` (`CODEX_HOME` honored). Codex supports deny only (ask fails the hook, and its allow rewrites commands), so the guard only blocks there. Trust the hooks in Codex's `/hooks`.
239
+ - Codex: the same events in `~/.codex/hooks.json` (`CODEX_HOME` honored). Codex sends every shell command as `tool_name: "Bash"` with the model's raw command string in `tool_input.command` (never shell-wrapped), so it is read exactly like Claude Code's; its `apply_patch` tool is a file edit, not a shell command, and isn't recorded. Codex supports deny only (ask fails the hook, and its allow rewrites commands), so the guard only blocks there. Trust the hooks in Codex's `/hooks`.
240
240
  - Cursor: `beforeShellExecution`/`afterShellExecution` in `~/.cursor/hooks.json`. Cursor also imports Claude Code's hooks by default; that imported copy records nothing when Passport's own Cursor entry exists, so rows aren't doubled.
241
241
 
242
242
  `src/cliPolicy.ts` caches the member's CLI policy (`GET /api/my/cli-policy`) at `$PASSPORT_HOME/cli-policy/<profile>.json` (mode 600). Servers with Autopilot send version 2 (`src/cliPolicyV2.ts`: presets, floors, CLI rules, irreversible and delete verbs, environment flags, placed environments); older servers send version 1, and then the guard keeps its earlier shape: ask or deny before destructive verbs, never allow, no server call, and reports without the Autopilot fields. `passport login` and `passport status` refresh it and `passport logout` removes it. A 404 or error keeps the previous copy; with no copy the guard asks before every destructive verb. `PASSPORT_HOOK_DISABLED=1` turns both hooks off.
@@ -314,7 +314,7 @@ passport completion fish > ~/.config/fish/completions/passport.fish
314
314
 
315
315
  ## Profiles
316
316
 
317
- Credentials live in `~/.passport/credentials.json` (mode `0600`, atomic updates); `PASSPORT_HOME` changes the directory. The store is shared with `passport-bridge`, and refreshes are coordinated across processes.
317
+ Credentials live in `~/.passport/credentials.json` (mode `0600`, atomic updates); `PASSPORT_HOME` changes the directory. The store is shared with `passport-bridge`, and refreshes are coordinated across processes. The hooks cache each profile's current access token next to it in `.<profile>.access.json` (mode `0600`): the token, its expiry, the endpoint, and a sha256 fingerprint of the refresh credential (never the credential itself), so a re-login, rotation, or endpoint change can't reuse it. Logging out, signing in again, or rotating a profile deletes its cached token.
318
318
 
319
319
  Resolution order:
320
320
 
@@ -392,43 +392,43 @@ const actions = await client.actions(); // or client.actions(delegationId)
392
392
 
393
393
  With `--json`, stdout is exactly one JSON value; hints and warnings go to stderr.
394
394
 
395
- | Command | JSON value |
396
- | --- | --- |
397
- | `login` | `{profile,endpoint,client,surface,active,workspaceId,workspaceName?,next}` (`workspaceName` after browser sign-in) |
398
- | `profiles` | `{profiles:[{name,active,client?}],active?}` |
399
- | `use` | `{profile,active:true}` |
400
- | `logout` | `{profile,removed,revoked}` |
401
- | `status` | `{workspace,member,endpoint,auth,profile?,client,mcps,autopilot?:{presets,floors,floorReason?,exceptions?,cache:{version,fetchedAt,ageMs}},next?}` |
402
- | `wait` | `{approvalId,status:"approved",scope?,message}`; declined, expired, and still-waiting are errors with `approvalId` |
403
- | `rules` | `{command,decision,cause?,explanation?,environment?,environmentAssumed?,actionClass?,source}` |
404
- | `sessions` | `{sessions:[{id,client,folder,status,startedAt,lastActivityAt,counts,environments,waiting}],nextCursor}` |
405
- | `undo` | `{actionId,status,message,steps:[{label,ok,detail?}],option,undoActionId?}`; without `--yes` off a terminal, `{actionId,status:"preview",preview,next}`; pending, blocked, and declined are errors |
406
- | `doctor` | `{version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}`, also on failure |
407
- | `ready` | `{ready,version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}` |
408
- | `search` | Gateway payload with `results` or `catalog`, and `note` |
409
- | `describe` | Tool definition (`tool`, `parameters`) plus `name`/`inputSchema` aliases |
410
- | `run` | Full governed MCP tool result, including `structuredContent` |
411
- | `connect` | Gateway payload with `connections` and optional `connectAllUrl` |
412
- | `resources`, `prompts` | MCP list, read, or get result |
413
- | `discover` | `{snapshot,report,compliant}` |
414
- | `scan` | `{version:1,findings:[{id,provider,kind,label,severity,location,locations,blastRadius}],agents,unreadable,checked}` |
415
- | `session` | NDJSON `{id?,ok,exitCode,result?}` or `{id?,ok:false,error,cause,exitCode,...}` |
416
- | `access` | `keygen`: algorithm, paths, public JWK; `actions`: `{actions}`; `run`/`cancel`: `{run}`; `invoke`: governed result; `status`: `{receipt}` |
417
- | `completion` | `{shell,script}` |
418
- | `help` | `{command,help}` |
419
- | `version` | `{version,profileCount,profileSelected,selectionSource,next,endpoint?,profile?}` |
395
+ | Command | JSON value |
396
+ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
397
+ | `login` | `{profile,endpoint,client,surface,active,workspaceId,workspaceName?,next}` (`workspaceName` after browser sign-in) |
398
+ | `profiles` | `{profiles:[{name,active,client?}],active?}` |
399
+ | `use` | `{profile,active:true}` |
400
+ | `logout` | `{profile,removed,revoked}` |
401
+ | `status` | `{workspace,member,endpoint,auth,profile?,client,mcps,autopilot?:{presets,floors,floorReason?,exceptions?,cache:{version,fetchedAt,ageMs}},next?}` |
402
+ | `wait` | `{approvalId,status:"approved",scope?,message}`; declined, expired, and still-waiting are errors with `approvalId` |
403
+ | `rules` | `{command,decision,cause?,explanation?,environment?,environmentAssumed?,actionClass?,source}` |
404
+ | `sessions` | `{sessions:[{id,client,folder,status,startedAt,lastActivityAt,counts,environments,waiting}],nextCursor}` |
405
+ | `undo` | `{actionId,status,message,steps:[{label,ok,detail?}],option,undoActionId?}`; without `--yes` off a terminal, `{actionId,status:"preview",preview,next}`; pending, blocked, and declined are errors |
406
+ | `doctor` | `{version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}`, also on failure |
407
+ | `ready` | `{ready,version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}` |
408
+ | `search` | Gateway payload with `results` or `catalog`, and `note` |
409
+ | `describe` | Tool definition (`tool`, `parameters`) plus `name`/`inputSchema` aliases |
410
+ | `run` | Full governed MCP tool result, including `structuredContent` |
411
+ | `connect` | Gateway payload with `connections` and optional `connectAllUrl` |
412
+ | `resources`, `prompts` | MCP list, read, or get result |
413
+ | `discover` | `{snapshot,report,compliant}` |
414
+ | `scan` | `{version:1,findings:[{id,provider,kind,label,severity,location,locations,blastRadius}],agents,unreadable,checked}` |
415
+ | `session` | NDJSON `{id?,ok,exitCode,result?}` or `{id?,ok:false,error,cause,exitCode,...}` |
416
+ | `access` | `keygen`: algorithm, paths, public JWK; `actions`: `{actions}`; `run`/`cancel`: `{run}`; `invoke`: governed result; `status`: `{receipt}` |
417
+ | `completion` | `{shell,script}` |
418
+ | `help` | `{command,help}` |
419
+ | `version` | `{version,profileCount,profileSelected,selectionSource,next,endpoint?,profile?}` |
420
420
 
421
421
  Errors: `{"error":"...","cause":"blocked","exitCode":5,"app":"github"}`, optionally with `approvalId`, `hint`, `profiles`, `next` (`argv` plus description), `remediation`, `retry`, `requiredInput`, or `connectUrl`.
422
422
 
423
- | Exit | Meaning |
424
- | ---: | --- |
425
- | 0 | Success |
426
- | 1 | Network, timeout, server, or unsupported-content error. When Passport can't be reached: `Passport couldn't be reached at <host>. Check your connection and try again.` |
427
- | 2 | Missing, expired, or revoked authentication |
428
- | 3 | App needs member sign-in |
429
- | 4 | Approval pending (including `wait` still waiting at its timeout) |
430
- | 5 | Policy, guardrail, selection, or approval denial (including a declined or expired approval in `wait`) |
431
- | 6 | Invalid usage or unknown tool/app |
423
+ | Exit | Meaning |
424
+ | ---: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
425
+ | 0 | Success |
426
+ | 1 | Network, timeout, server, or unsupported-content error. When Passport can't be reached: `Passport couldn't be reached at <host>. Check your connection and try again.` |
427
+ | 2 | Missing, expired, or revoked authentication |
428
+ | 3 | App needs member sign-in |
429
+ | 4 | Approval pending (including `wait` still waiting at its timeout) |
430
+ | 5 | Policy, guardrail, selection, or approval denial (including a declined or expired approval in `wait`) |
431
+ | 6 | Invalid usage or unknown tool/app |
432
432
 
433
433
  ## MCP stdio bridge
434
434
 
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The CLI hook's access-token cache: `$PASSPORT_HOME/.<profile>.access.json`,
3
+ * next to the credential store.
4
+ *
5
+ * A hook process lives for one shell command under a 1.5 s budget, and a
6
+ * token exchange alone can take most of it. So the short-lived access token
7
+ * one hook run mints is kept for the next run, and the common path is one
8
+ * request instead of two.
9
+ *
10
+ * Each entry is bound to the profile's endpoint and to a fingerprint of its
11
+ * refresh token (a sha256 prefix, never the token), so a re-login, a rotation,
12
+ * a logout, or an endpoint change can never reuse it. The file is owner-only
13
+ * and replaced atomically; concurrent hook runs race harmlessly (last writer
14
+ * wins). Reading never throws: a missing, corrupt, foreign-owned, mismatched,
15
+ * or nearly expired entry is simply absent and the hook exchanges as before.
16
+ */
17
+ /** Use a cached token only with at least this long left. */
18
+ export declare const ACCESS_REUSE_MARGIN_MS = 60000;
19
+ export type AccessBinding = {
20
+ endpoint: string;
21
+ refresh: string;
22
+ };
23
+ export type HeldAccess = {
24
+ token: string;
25
+ expiresAt: number;
26
+ };
27
+ type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
28
+ export declare function accessCachePath(profile: string): string;
29
+ /** Identifies the refresh token an entry was minted from without storing it. */
30
+ export declare function refreshFingerprint(refreshToken: string): string;
31
+ /** The cached access token for this exact binding, if it has more than a
32
+ * minute left. */
33
+ export declare function readCachedAccess(profile: string, binding: AccessBinding, now: number): string | undefined;
34
+ /** Replace the entry atomically (temp file, then rename), mode 0600. Throws;
35
+ * the hook treats a failed write as nothing cached. */
36
+ export declare function writeCachedAccess(profile: string, binding: AccessBinding, held: HeldAccess): void;
37
+ /** Remove the entry. With `only`, remove it only while it still holds that
38
+ * token, so a run that saw a 401 does not delete a sibling's fresh entry.
39
+ * Never throws. */
40
+ export declare function dropCachedAccess(profile: string, only?: string): void;
41
+ /**
42
+ * One authenticated call surface for a hook run. A cached token goes out
43
+ * first with no exchange. A 401 on it drops the entry, exchanges once (shared
44
+ * by every call in the run), and retries once. A fresh token is cached for
45
+ * the next run, best effort.
46
+ *
47
+ * The exchange never rotates the refresh token: a rotation cut short by the
48
+ * hook's budget would lose the only copy of the new one.
49
+ */
50
+ export declare function cachedAccessApi(profile: string, saved: {
51
+ endpoint: string;
52
+ refreshToken: string;
53
+ }, signal: AbortSignal, fetcher: typeof fetch, exchangeTimeoutMs: number): Promise<ApiCall>;
54
+ export {};
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The CLI hook's access-token cache: `$PASSPORT_HOME/.<profile>.access.json`,
3
+ * next to the credential store.
4
+ *
5
+ * A hook process lives for one shell command under a 1.5 s budget, and a
6
+ * token exchange alone can take most of it. So the short-lived access token
7
+ * one hook run mints is kept for the next run, and the common path is one
8
+ * request instead of two.
9
+ *
10
+ * Each entry is bound to the profile's endpoint and to a fingerprint of its
11
+ * refresh token (a sha256 prefix, never the token), so a re-login, a rotation,
12
+ * a logout, or an endpoint change can never reuse it. The file is owner-only
13
+ * and replaced atomically; concurrent hook runs race harmlessly (last writer
14
+ * wins). Reading never throws: a missing, corrupt, foreign-owned, mismatched,
15
+ * or nearly expired entry is simply absent and the hook exchanges as before.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import { lstatSync, unlinkSync } from "node:fs";
19
+ import { join } from "node:path";
20
+ import { readBoundedUtf8File } from "./boundedFile.js";
21
+ import { credentialDir, enforceOwner, writePrivateAtomic } from "./credentialStorage.js";
22
+ const VERSION = 1;
23
+ const MAX_BYTES = 16 * 1024;
24
+ const MAX_TOKEN_LENGTH = 4096;
25
+ /** Use a cached token only with at least this long left. */
26
+ export const ACCESS_REUSE_MARGIN_MS = 60_000;
27
+ /** Passport's access tokens last an hour. Anything claiming far longer was
28
+ * written under a wrong clock, so it is ignored rather than trusted. */
29
+ const MAX_REMAINING_MS = 24 * 60 * 60 * 1000;
30
+ /** Mirrors the credential store's profile-name rule. Kept local so this file
31
+ * does not import `credentials.ts`, which imports it. */
32
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,79}$/;
33
+ const UNSAFE_PROFILE_KEYS = new Set(["__proto__", "prototype", "constructor"]);
34
+ export function accessCachePath(profile) {
35
+ if (!PROFILE_NAME.test(profile) || UNSAFE_PROFILE_KEYS.has(profile)) {
36
+ throw new Error("Invalid Passport profile name.");
37
+ }
38
+ return join(credentialDir(), `.${profile}.access.json`);
39
+ }
40
+ /** Identifies the refresh token an entry was minted from without storing it. */
41
+ export function refreshFingerprint(refreshToken) {
42
+ return createHash("sha256").update(refreshToken, "utf8").digest("hex").slice(0, 32);
43
+ }
44
+ function readEntry(profile) {
45
+ try {
46
+ const path = accessCachePath(profile);
47
+ enforceOwner(lstatSync(path), "access-token cache");
48
+ const parsed = JSON.parse(readBoundedUtf8File(path, MAX_BYTES));
49
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ /** The cached access token for this exact binding, if it has more than a
56
+ * minute left. */
57
+ export function readCachedAccess(profile, binding, now) {
58
+ const entry = readEntry(profile);
59
+ if (!entry || entry.version !== VERSION)
60
+ return undefined;
61
+ if (entry.endpoint !== binding.endpoint || entry.refresh !== binding.refresh)
62
+ return undefined;
63
+ const { accessToken, expiresAt } = entry;
64
+ if (typeof accessToken !== "string" || !accessToken || accessToken.length > MAX_TOKEN_LENGTH)
65
+ return undefined;
66
+ if (/[\u0000- \u007f]/.test(accessToken))
67
+ return undefined;
68
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
69
+ return undefined;
70
+ const remaining = expiresAt - now;
71
+ if (remaining <= ACCESS_REUSE_MARGIN_MS || remaining > MAX_REMAINING_MS)
72
+ return undefined;
73
+ return accessToken;
74
+ }
75
+ /** Replace the entry atomically (temp file, then rename), mode 0600. Throws;
76
+ * the hook treats a failed write as nothing cached. */
77
+ export function writeCachedAccess(profile, binding, held) {
78
+ const document = {
79
+ version: VERSION,
80
+ endpoint: binding.endpoint,
81
+ refresh: binding.refresh,
82
+ accessToken: held.token,
83
+ expiresAt: held.expiresAt
84
+ };
85
+ writePrivateAtomic(accessCachePath(profile), `.${profile}.access`, JSON.stringify(document), "access-token cache");
86
+ }
87
+ /** Remove the entry. With `only`, remove it only while it still holds that
88
+ * token, so a run that saw a 401 does not delete a sibling's fresh entry.
89
+ * Never throws. */
90
+ export function dropCachedAccess(profile, only) {
91
+ try {
92
+ if (only !== undefined && readEntry(profile)?.accessToken !== only)
93
+ return;
94
+ unlinkSync(accessCachePath(profile));
95
+ }
96
+ catch {
97
+ /* Missing already, or the binding check keeps a leftover from being used. */
98
+ }
99
+ }
100
+ /**
101
+ * One authenticated call surface for a hook run. A cached token goes out
102
+ * first with no exchange. A 401 on it drops the entry, exchanges once (shared
103
+ * by every call in the run), and retries once. A fresh token is cached for
104
+ * the next run, best effort.
105
+ *
106
+ * The exchange never rotates the refresh token: a rotation cut short by the
107
+ * hook's budget would lose the only copy of the new one.
108
+ */
109
+ export async function cachedAccessApi(profile, saved, signal, fetcher, exchangeTimeoutMs) {
110
+ const origin = new URL(saved.endpoint).origin;
111
+ const binding = { endpoint: saved.endpoint, refresh: refreshFingerprint(saved.refreshToken) };
112
+ const initial = readCachedAccess(profile, binding, Date.now());
113
+ let cached = initial;
114
+ const { BridgeCredentialError, TokenManager } = await import("./bridgeExchange.js");
115
+ const manager = new TokenManager(saved.endpoint, saved.refreshToken, undefined, undefined, exchangeTimeoutMs, signal, fetcher);
116
+ let kept;
117
+ const keep = () => {
118
+ const held = manager.heldAccessToken();
119
+ if (!held || held.token === kept)
120
+ return;
121
+ kept = held.token;
122
+ try {
123
+ writeCachedAccess(profile, binding, held);
124
+ }
125
+ catch {
126
+ /* Best effort: the next run exchanges instead. */
127
+ }
128
+ };
129
+ const send = (path, init, token) => {
130
+ const headers = new Headers(init.headers);
131
+ headers.set("authorization", `Bearer ${token}`);
132
+ const pending = fetcher(`${origin}${path}`, { ...init, headers, redirect: "error" });
133
+ // Written while the request is in flight, never ahead of it.
134
+ if (token !== initial)
135
+ keep();
136
+ return pending;
137
+ };
138
+ // A refused token never stays cached, whether it came from disk or was
139
+ // just minted.
140
+ const refused = (token) => {
141
+ if (token === cached)
142
+ cached = undefined;
143
+ dropCachedAccess(profile, token);
144
+ };
145
+ return async (path, init) => {
146
+ const presented = cached ?? (await manager.accessToken());
147
+ const response = await send(path, init, presented);
148
+ if (response.status !== 401)
149
+ return response;
150
+ await response.body?.cancel().catch(() => undefined);
151
+ refused(presented);
152
+ // A refused cached token needs this run's one exchange (shared with any
153
+ // concurrent call); a refused fresh one forces another, as before.
154
+ const next = await manager.accessToken(presented !== initial);
155
+ const retried = await send(path, init, next);
156
+ if (retried.status === 401) {
157
+ await retried.body?.cancel().catch(() => undefined);
158
+ refused(next);
159
+ throw new BridgeCredentialError(401);
160
+ }
161
+ return retried;
162
+ };
163
+ }
@@ -87,6 +87,12 @@ export declare class TokenManager {
87
87
  * only: never log it. Recovery correlates with it and self-heal compares
88
88
  * the on-disk token against it. */
89
89
  currentRefreshToken(): string;
90
+ /** The access token this process holds and when it expires, for the CLI
91
+ * hook's cross-process cache. In-process only: never log it. */
92
+ heldAccessToken(): {
93
+ token: string;
94
+ expiresAt: number;
95
+ } | undefined;
90
96
  /** The exchange in flight, if any, so shutdown can let it persist. */
91
97
  inflightExchange(): Promise<unknown> | undefined;
92
98
  private assertHomeWorkspace;
@@ -161,6 +161,11 @@ export class TokenManager {
161
161
  currentRefreshToken() {
162
162
  return this.refreshToken;
163
163
  }
164
+ /** The access token this process holds and when it expires, for the CLI
165
+ * hook's cross-process cache. In-process only: never log it. */
166
+ heldAccessToken() {
167
+ return this.access ? { token: this.access, expiresAt: this.expiresAt } : undefined;
168
+ }
164
169
  /** The exchange in flight, if any, so shutdown can let it persist. */
165
170
  inflightExchange() {
166
171
  return this.inflight;
package/dist/cliHook.d.ts CHANGED
@@ -18,6 +18,7 @@ import { type ParsedArgs } from "./cliArgs.js";
18
18
  import { type CliFinding } from "./cliHookClassify.js";
19
19
  import { type DecidedFinding, type GuardDecision } from "./cliHookGuard.js";
20
20
  import { type HookInput } from "./cliHookInput.js";
21
+ export { opaqueKind, opaqueProgram } from "./cliHookOpaque.js";
21
22
  import { type CommandResult, type Env, type Runtime } from "./cliSupport.js";
22
23
  /** Claude Code, Codex, and Cursor fail open on a slow hook, so the budget is ours. */
23
24
  export declare const HOOK_BUDGET_MS = 1500;
@@ -33,6 +34,9 @@ export type CliHookReport = {
33
34
  findings: ReportedFinding[];
34
35
  opaque: boolean;
35
36
  opaqueKinds?: string[];
37
+ /** The program of each part Passport couldn't check: its first word only
38
+ * (`python`, `make`, `npx`), never a script name or an argument. */
39
+ opaquePrograms?: string[];
36
40
  /** What the guard answered before the command ran. "allow" only with a v2
37
41
  * (Autopilot) policy; the server works out the cause and class itself. */
38
42
  decision?: "allow" | "ask" | "deny";
@@ -84,8 +88,6 @@ type ShellEvent = {
84
88
  /** Keep the shape of the verb, never its arguments: anything that could carry a
85
89
  * path, an endpoint, or a value is dropped rather than truncated. */
86
90
  export declare function safeVerb(raw: string | null): string;
87
- /** Why a command could not be read. Never what it was. */
88
- export declare function opaqueKind(finding: CliFinding): string;
89
91
  /**
90
92
  * Which agent sent this. An installed hook names its client with `--client`;
91
93
  * Cursor is also recognised by its own event names and version field, which