passport-bridge 0.16.3 → 0.16.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -8
- package/dist/accessTokenCache.d.ts +54 -0
- package/dist/accessTokenCache.js +163 -0
- package/dist/bridgeExchange.d.ts +6 -0
- package/dist/bridgeExchange.js +5 -0
- package/dist/cliAnswered.d.ts +5 -0
- package/dist/cliAnswered.js +27 -2
- package/dist/cliAutopilot.d.ts +10 -2
- package/dist/cliAutopilot.js +12 -32
- package/dist/cliAutopilotPolicy.d.ts +7 -0
- package/dist/cliCodexTrust.d.ts +42 -0
- package/dist/cliCodexTrust.js +145 -0
- package/dist/cliEnv.d.ts +9 -2
- package/dist/cliEnv.js +30 -20
- package/dist/cliExec.d.ts +2 -8
- package/dist/cliExec.js +12 -22
- package/dist/cliExecGuard.d.ts +10 -0
- package/dist/cliExecGuard.js +36 -0
- package/dist/cliGuardHealth.d.ts +40 -0
- package/dist/cliGuardHealth.js +191 -0
- package/dist/cliGuardState.d.ts +60 -0
- package/dist/cliGuardState.js +121 -0
- package/dist/cliHook.d.ts +3 -58
- package/dist/cliHook.js +107 -145
- package/dist/cliHookDecide.d.ts +13 -0
- package/dist/cliHookDecide.js +35 -2
- package/dist/cliHookDeliver.d.ts +137 -0
- package/dist/cliHookDeliver.js +271 -0
- package/dist/cliHookExtras.d.ts +26 -0
- package/dist/cliHookExtras.js +34 -0
- package/dist/cliHookGuard.d.ts +6 -3
- package/dist/cliHookGuard.js +15 -3
- package/dist/cliHookInstall.d.ts +14 -0
- package/dist/cliHookInstall.js +9 -69
- package/dist/cliHookRewrite.js +1 -1
- package/dist/cliHookStatus.d.ts +18 -0
- package/dist/cliHookStatus.js +111 -0
- package/dist/cliInit.d.ts +3 -0
- package/dist/cliInit.js +17 -5
- package/dist/cliKeys.d.ts +8 -0
- package/dist/cliKeys.js +71 -20
- package/dist/cliKeysBack.d.ts +41 -0
- package/dist/cliKeysBack.js +124 -0
- package/dist/cliPolicy.d.ts +3 -0
- package/dist/cliPolicy.js +17 -0
- package/dist/cliPolicyV2.js +24 -3
- package/dist/cliSeen.d.ts +40 -0
- package/dist/cliSeen.js +203 -0
- package/dist/cliSpeed.d.ts +104 -0
- package/dist/cliSpeed.js +320 -0
- package/dist/cliStatusGuard.d.ts +28 -0
- package/dist/cliStatusGuard.js +77 -0
- package/dist/credentials.d.ts +3 -1
- package/dist/credentials.js +14 -0
- package/dist/envResolve.d.ts +9 -5
- package/dist/envResolve.js +27 -8
- package/dist/execTarget.d.ts +8 -0
- package/dist/execTarget.js +28 -0
- package/dist/fastPathFlag.d.ts +38 -0
- package/dist/fastPathFlag.js +90 -0
- package/dist/hookFastPath.d.ts +44 -0
- package/dist/hookFastPath.js +239 -0
- package/dist/hookMain.d.ts +2 -0
- package/dist/hookMain.js +53 -0
- package/dist/hookOutbox.d.ts +27 -0
- package/dist/hookOutbox.js +176 -0
- package/dist/initAutopilotStep.js +6 -8
- package/dist/initInstall.d.ts +6 -3
- package/dist/initInstall.js +44 -5
- package/dist/initKeysStep.js +5 -0
- package/dist/initUi.d.ts +10 -0
- package/dist/initUi.js +27 -0
- package/dist/launcherFastPath.d.ts +52 -0
- package/dist/launcherFastPath.js +350 -0
- package/dist/pluginPin.d.ts +1 -1
- package/dist/pluginPin.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +6 -6
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -134,7 +134,7 @@ Eight steps, each reusing the command that owns it:
|
|
|
134
134
|
1. **Scan**: the same local scan as `passport scan`, as one summary line (`--verbose` prints the table).
|
|
135
135
|
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`.
|
|
136
136
|
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); without one it prints the page and `Next: passport connect --wait 300` and moves on.
|
|
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.
|
|
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.`) and which old keys to rotate (`Rotate the old Railway key once your agents don't need it.`, only when a key moved in that run). 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.
|
|
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
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.
|
|
@@ -212,6 +212,8 @@ 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
|
+
**Speed.** Hooks must never slow agents down. The launcher `$PASSPORT_HOME/cli/bin/passport` (written by `src/initInstall.ts`) answers plain reads and local dev commands in POSIX sh without starting Node (`src/launcherFastPath.ts`): `ls`, `cat`, `rg`, `git status`, `npm test`, `cargo check`, and the rest of a fixed list, joined only by single pipes, with relative paths that stay in the folder and pass through no symlink or hidden file. It answers only while `cli-policy/fastpath.ok` is armed: a full guard run arms it for five minutes when the cached rules give those commands exactly the launcher's answer (`src/hookFastPath.ts`), and a policy or profile change removes it. Each answer appends one line (agent, session id, program names, never an argument) to `cli-policy/fastpath.spool`, which the next full run counts. Anything else, or any doubt, starts Node with the same input, through `dist/hookMain.js`, which loads only the guard. `src/launcherFastPath.test.ts` holds the launcher to the full guard's exact answer across both corpora and generated variants. `PASSPORT_HOOK_FAST=0` turns it off. The after-hook and the guard's own report never wait on the network: they queue to `$PASSPORT_HOME/hook-outbox/` and a detached `passport hook flush` sends them within the budget (`src/hookOutbox.ts`). Each guard run records its timings (numbers only, `src/cliSpeed.ts`), sent every five minutes with the answered counts. `npm run bench:guard` times it all on the compiled CLI.
|
|
216
|
+
|
|
215
217
|
**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
218
|
|
|
217
219
|
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.`
|
|
@@ -231,14 +233,20 @@ Codex has no field for `codex exec`; its prompt-free modes count as unattended,
|
|
|
231
233
|
|
|
232
234
|
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
235
|
|
|
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.
|
|
236
|
+
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. After answering it never waits on the network: its report, the batches, and, at most every ten minutes, a refresh of a policy cache older than an hour go through the detached `passport hook flush`. 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
237
|
|
|
236
238
|
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
239
|
|
|
238
240
|
- 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 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
|
|
241
|
+
- 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 (an ask fails the hook open, and its allow rewrites commands), so an ask is a deny there that says why (`Codex can't ask from a hook, so Passport blocked it. Approve it in Passport or run it yourself.`), recorded as a block. With a member profile and Autopilot, it goes to Passport like an unattended ask: an approval request, then the waiting line. Trust the hooks in Codex's `/hooks`.
|
|
240
242
|
- 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
243
|
|
|
244
|
+
**Guard health** (`src/cliGuardHealth.ts`, states and fixes in `src/cliGuardState.ts`, a checked copy of `shared/guardContract.ts`). `passport hook status` and `passport status` show each agent's guard in the web's words, **On**, **Off**, **Outdated**, **Not trusted**, or **Locked**, and each problem's fix: `passport hook install --client <agent> --guard --apply`, `npx passport-bridge@latest init`, or `Open Codex → /hooks and trust Passport's hooks.` At most once a day (`$PASSPORT_HOME/guard/.<profile>.heartbeat`) the CLI sends `POST /api/my/guard-health` with `{cliVersion, launcherTarget?, clients: [{client, present, mode, guard, plugin, codexTrust?, locked?, disabledEnv?}]}`: flags only, never a command, path, or value. It goes from a guard run with at least 300 ms of its budget left (a hook's first one waits a day), from `passport exec`, and from `passport status`. Codex trust (`src/cliCodexTrust.ts`) compares `trusted_hash` in `~/.codex/config.toml` `[hooks.state."<hooks.json>:pre_tool_use:<group>:<handler>"]` with Codex's own hash of Passport's guard entry: SHA-256 of the sorted-key JSON of `{event_name, matcher?, hooks: [{type, command, timeout (600 when unset), async, statusMessage?, additionalContextLimit? (when not 2500)}]}`, as in openai/codex `hook_hash`/`version_for_toml`, checked against codex-cli 0.146.0's `hooks/list`. Missing is **Not trusted**, a different hash is **Not trusted** (modified), `enabled = false` is **Off**. **Locked** means managed settings hold Passport's guard: `/Library/Application Support/ClaudeCode/managed-settings.json` (and `managed-settings.d/`), `/etc/claude-code/…`, `/etc/codex/requirements.toml`, `/Library/Application Support/Cursor/hooks.json`, or `/etc/cursor/hooks.json` (`PASSPORT_MANAGED_ROOT` points tests elsewhere).
|
|
245
|
+
|
|
246
|
+
**Coverage** (`src/cliSeen.ts`). The guard counts every command it saw, per agent per day, one character per command in `$PASSPORT_HOME/seen/<profile>.<agent>.<day>.log` (an app's action, not checked, or neither), and Cursor's imported copy of Claude Code's hook doesn't count twice. Counts go in their own batches, at most every five minutes, as `seen: {batch, day, count, governed, opaque}` on `POST /api/my/cli-activity`, never inside a report that can expire. `passport status` prints `Checked: 94% of commands Passport saw this week`.
|
|
247
|
+
|
|
248
|
+
**When Passport can't be reached.** When the guard needs Passport (an unattended ask, Codex, or a Production action someone else approves) and it doesn't answer within the budget, the environment's `offline` setting from cli-policy v2 decides: ask, block, or allow (Production asks, the rest run, by default). Allow never covers an irreversible action, a second-person action is always blocked, Codex's ask is a block, and a policy synced more than 7 days ago uses the defaults. The reason ends with `Passport couldn't be reached, so this computer decided.`
|
|
249
|
+
|
|
242
250
|
`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.
|
|
243
251
|
|
|
244
252
|
The Passport plugin (`rsyed94/passport-plugins`) runs the same two hooks from the agent's plugin folder, with `PASSPORT_HOOK_VIA=plugin`. `passport hook status` shows those agents as `via plugin`, and `hook install`, `init`, and `setup --org` skip them (`Claude Code: already covered by the Passport plugin.`) so nothing is recorded twice. The plugin pins the CLI version in `src/pluginPin.ts`.
|
|
@@ -254,13 +262,13 @@ passport sync # or: passport sync --remove
|
|
|
254
262
|
passport env # or: passport env set railway qa staging
|
|
255
263
|
```
|
|
256
264
|
|
|
257
|
-
- `env` lists where commands in this folder land, read the way each vendor's own CLI reads it (`src/envResolve.ts`; order: flag, the folder's link, the vendor's default, the workspace's saved mapping, the whole-word naming rule, else Production). Link readers: `src/envLinksHosting.ts` (Railway `~/.railway/config.json`, Vercel `.vercel/project.json` / `repo.json`, Supabase `supabase/.temp/project-ref`, Wrangler config, Netlify `.netlify/state.json`, Firebase `.firebaserc` + configstore, Convex `CONVEX_DEPLOYMENT`, Neon `.neon`), `src/envLinksCloud.ts` (Fly, Heroku git remotes, kubeconfig, AWS profile, gcloud configuration, Terraform workspace, Stripe key mode), and `src/envDatabase.ts` (database URLs: only `DATABASE_URL`, `DIRECT_URL`, `POSTGRES_URL*`, `DATABASE_URL_UNPOOLED`, reduced to a host-derived key; the URL, user, and password never leave the function). Files are read fresh for every command, size-capped, and a link file symlinked out of the project is ignored (`src/envLinkFs.ts`). A name in a link file never loosens anything: an unplaced id is
|
|
265
|
+
- `env` lists where commands in this folder land, read the way each vendor's own CLI reads it (`src/envResolve.ts`; order: flag, the folder's link, the vendor's default, the workspace's saved mapping, the whole-word naming rule, else Production). Link readers: `src/envLinksHosting.ts` (Railway `~/.railway/config.json`, Vercel `.vercel/project.json` / `repo.json`, Supabase `supabase/.temp/project-ref`, Wrangler config, Netlify `.netlify/state.json`, Firebase `.firebaserc` + configstore, Convex `CONVEX_DEPLOYMENT`, Neon `.neon`), `src/envLinksCloud.ts` (Fly, Heroku git remotes, kubeconfig, AWS profile, gcloud configuration, Terraform workspace, Stripe key mode), and `src/envDatabase.ts` (database URLs: only `DATABASE_URL`, `DIRECT_URL`, `POSTGRES_URL*`, `DATABASE_URL_UNPOOLED`, reduced to a host-derived key; the URL, user, and password never leave the function). Files are read fresh for every command, size-capped, and a link file symlinked out of the project is ignored (`src/envLinkFs.ts`). For a placed id its mapping decides, and a different name in the link file is treated as a rename (sent as the new label, which the server stores). A name in a link file never loosens anything: an unplaced id is named only by a label the server confirmed through the connected app (`resources[].confirmed`), which the naming rule then reads (`source: "name"`, shown as `Staging (from its name)`); without one, or when it says nothing, it is assumed Production. The table keeps its columns when every row fits the terminal and stacks each row otherwise. Findings to a server that sends `resources` in cli-policy v2 carry `{kind, source, resourceKey?, label?, platform?, flag?, via}`. `env set` calls `PUT /api/my/environments/:platform/:key`; members may only say Production.
|
|
258
266
|
|
|
259
267
|
- `rules test` classifies the command here and sends only its app and verb (and the environment kind) to `POST /api/my/rules/test`, never the command line. An everyday command goes as a finding (`{finding: {vendor, verb, risk, environment}}`), because only this computer can place its paths. It prints the decision, its cause, the environment, and the class. Without a server answer it decides from this computer's copy and says how old it is. `--environment` picks one when the flags don't say.
|
|
260
268
|
- `wait` long-polls `GET /api/my/approvals/<id>/wait`. Approved: `Approved by Ramish. Run the command again.` (exit 0). Declined: the note for the agent, `Declined by Ramish: <note>` (exit 5, cause `approval_denied`). Expired: `Expired. The agent can ask again.` (exit 5, cause `approval_expired`). Still waiting at `--timeout` (default 100 seconds, under an agent's 2-minute command limit): exit 4 with the same command as `next`.
|
|
261
269
|
- `sessions` lists recent sessions (`GET /api/my/agent-sessions`): status, agent, folder, start, `42 ran · 2 asked · 1 blocked`, environments touched, and `Waiting for you` when approvals are pending.
|
|
262
270
|
- `sync` writes the allows Passport is sure of into each agent's own permission settings, so those prompts disappear offline and in Codex (`src/nativeSync.ts`). Only reads, test runners, builds and type checks, linters that only check, `git status`, `git add`, and `git commit`, checked against the person's rules. Formatters, fixing linters, `mv`/`cp`, and package scripts stay with the hook, which sees what they touch; deletes, installs, pushes, and Production never sync. Claude Code: `Bash(npm test *)` in `permissions.allow` of `~/.claude/settings.json`. Codex: `prefix_rule(pattern = ["npm", "test"], decision = "allow")` in `~/.codex/rules/passport.rules`, a file Passport owns. Cursor CLI: `Shell(npm:test*)` in `permissions.allow` of `~/.cursor/cli-config.json`. Cursor: `npm test` in `terminalAllowlist` of `~/.cursor/permissions.json`, only when that list already exists there (defining it replaces Cursor's in-app list). Entries Passport added are listed in `$PASSPORT_HOME/native-sync.json`; an entry you had before is never claimed or removed, and a file Passport can't parse exactly (JSONC) is left alone. Sync runs on `init`, `setup --org`, every rules refresh, and `passport sync`; `hook uninstall`, `sync --remove`, and signing out of the last profile take the entries out.
|
|
263
|
-
- `status` adds `Answered for you: N prompts today` (allows the hook gave in Claude Code and Cursor, and Codex commands Passport synced, counted only when the agent would have prompted) and which agents' allowlists are synced. Under the presets, one line per exception that lets something run your presets would ask about, in the web's words: `! 1 exception: deletes run in Production without asking, even without a backup.` Counts are appended locally (`$PASSPORT_HOME/answered/`) and sent in batches at most every five minutes as `answered: {batch, count}` on `POST /api/my/cli-activity`.
|
|
271
|
+
- `status` adds each agent's guard (`Guard: Claude Code On · Codex Not trusted`), the coverage line, and each fix, and sends the daily guard report when due. It also adds today's speed line, `Passport added 0.3 s and asked you twice today. 412 actions ran on their own.` (across your computers when the server keeps speed numbers, else `(this computer)`), and `Answered for you: N prompts today` (allows the hook gave in Claude Code and Cursor, and Codex commands Passport synced, counted only when the agent would have prompted) and which agents' allowlists are synced. Under the presets, one line per exception that lets something run your presets would ask about, in the web's words: `! 1 exception: deletes run in Production without asking, even without a backup.` Counts are appended locally (`$PASSPORT_HOME/answered/`) and sent in batches at most every five minutes as `answered: {batch, count}` on `POST /api/my/cli-activity`.
|
|
264
272
|
- `rules test`, `sessions`, and `sync` need a member profile. `wait` also works for a cloud agent's key, on the approval its own `passport exec` opened.
|
|
265
273
|
|
|
266
274
|
### Keys and passport exec
|
|
@@ -272,9 +280,10 @@ passport keys add railway # store a key you paste (stdin, never echoed)
|
|
|
272
280
|
passport exec -- railway up -e staging
|
|
273
281
|
```
|
|
274
282
|
|
|
275
|
-
-
|
|
283
|
+
- 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.
|
|
284
|
+
- `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.
|
|
276
285
|
- `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`).
|
|
277
|
-
- 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. An approval is used once. Blocked or declined: exit 5. 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.
|
|
286
|
+
- 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. An approval is used once. Blocked or declined: exit 5. 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.
|
|
278
287
|
- 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.
|
|
279
288
|
- 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.
|
|
280
289
|
- 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.
|
|
@@ -314,7 +323,7 @@ passport completion fish > ~/.config/fish/completions/passport.fish
|
|
|
314
323
|
|
|
315
324
|
## Profiles
|
|
316
325
|
|
|
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.
|
|
326
|
+
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
327
|
|
|
319
328
|
Resolution order:
|
|
320
329
|
|
|
@@ -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
|
+
}
|
package/dist/bridgeExchange.d.ts
CHANGED
|
@@ -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;
|
package/dist/bridgeExchange.js
CHANGED
|
@@ -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/cliAnswered.d.ts
CHANGED
|
@@ -19,6 +19,11 @@ export declare function localDay(now: number): string;
|
|
|
19
19
|
export declare function noteAnswered(profile: string, now?: number): void;
|
|
20
20
|
/** Prompts answered on this computer today. */
|
|
21
21
|
export declare function answeredToday(profile: string, now?: number): number;
|
|
22
|
+
/** Whether a batch report is due, without claiming it. Never throws. */
|
|
23
|
+
export declare function reportIntervalDue(profile: string, now?: number): boolean;
|
|
24
|
+
/** At most one batch report (answered counts and speed numbers) per interval
|
|
25
|
+
* per profile, claimed before any network. Never throws. */
|
|
26
|
+
export declare function claimReportInterval(profile: string, now?: number): boolean;
|
|
22
27
|
/** The next batch to report, or null. A batch that wasn't confirmed is sent again as is. */
|
|
23
28
|
export declare function claimAnsweredBatch(profile: string, now?: number, force?: boolean): {
|
|
24
29
|
batch: string;
|
package/dist/cliAnswered.js
CHANGED
|
@@ -123,9 +123,32 @@ function readState(profile) {
|
|
|
123
123
|
function writeState(profile, state) {
|
|
124
124
|
writePrivateAtomic(statePath(profile), ".answered", `${JSON.stringify(state)}\n`, "answered counts");
|
|
125
125
|
}
|
|
126
|
-
|
|
126
|
+
function intervalMarker(profile) {
|
|
127
|
+
assertProfileName(profile);
|
|
128
|
+
return join(directory(), `.${profile}.report`);
|
|
129
|
+
}
|
|
130
|
+
/** Whether a batch report is due, without claiming it. Never throws. */
|
|
131
|
+
export function reportIntervalDue(profile, now = Date.now()) {
|
|
132
|
+
try {
|
|
133
|
+
const last = statSync(intervalMarker(profile)).mtimeMs;
|
|
134
|
+
return now - last >= ANSWERED_REPORT_MS || last > now;
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
return error.code === "ENOENT";
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** At most one batch report (answered counts and speed numbers) per interval
|
|
141
|
+
* per profile, claimed before any network. Never throws. */
|
|
142
|
+
export function claimReportInterval(profile, now = Date.now()) {
|
|
143
|
+
try {
|
|
144
|
+
return claimInterval(profile, now);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
127
150
|
function claimInterval(profile, now) {
|
|
128
|
-
const marker =
|
|
151
|
+
const marker = intervalMarker(profile);
|
|
129
152
|
try {
|
|
130
153
|
const last = statSync(marker).mtimeMs;
|
|
131
154
|
if (now - last < ANSWERED_REPORT_MS && last <= now)
|
|
@@ -136,6 +159,8 @@ function claimInterval(profile, now) {
|
|
|
136
159
|
return false;
|
|
137
160
|
}
|
|
138
161
|
try {
|
|
162
|
+
ensurePrivateDirectory(true);
|
|
163
|
+
mkdirSync(directory(), { recursive: true, mode: 0o700 });
|
|
139
164
|
const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
|
|
140
165
|
closeSync(openSync(marker, constants.O_WRONLY | constants.O_CREAT | noFollow, 0o600));
|
|
141
166
|
utimesSync(marker, now / 1000, now / 1000);
|
package/dist/cliAutopilot.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* `rules test` classifies the command on this machine and sends only the
|
|
11
11
|
* vendor and verb (and the environment kind), never the command line.
|
|
12
12
|
*/
|
|
13
|
+
import { type GuardStatus } from "./cliStatusGuard.js";
|
|
13
14
|
import { type ParsedArgs } from "./cliArgs.js";
|
|
14
15
|
import { type Preset, type PresetRow } from "./cliAutopilotPolicy.js";
|
|
15
16
|
import { type MemberApi } from "./cliClient.js";
|
|
@@ -70,15 +71,22 @@ export type AutopilotStatus = {
|
|
|
70
71
|
today: number;
|
|
71
72
|
source: "workspace" | "this-computer";
|
|
72
73
|
};
|
|
74
|
+
/** "Passport added 0.3 s and asked you twice today. …": across your
|
|
75
|
+
* computers when Passport keeps the numbers, else this computer's own. */
|
|
76
|
+
speed?: {
|
|
77
|
+
line: string;
|
|
78
|
+
source: "workspace" | "this-computer";
|
|
79
|
+
};
|
|
73
80
|
/** Agents whose own allowlist Passport keeps in sync, with how many entries. */
|
|
74
81
|
allowlists?: Array<{
|
|
75
82
|
agent: string;
|
|
76
83
|
name: string;
|
|
77
84
|
entries: number;
|
|
78
85
|
}>;
|
|
86
|
+
/** Batch A: each agent's guard here, coverage this week, and fixes. */
|
|
87
|
+
guard?: GuardStatus;
|
|
79
88
|
};
|
|
80
|
-
|
|
81
|
-
export declare function localMidnight(now: number): number;
|
|
89
|
+
export { localMidnight } from "./cliSpeed.js";
|
|
82
90
|
/** Read presets and floors for `passport status`. Never throws. */
|
|
83
91
|
export declare function autopilotStatus(fetchApi: (path: string, init: RequestInit) => Promise<Response>, profile: string | undefined, signal: AbortSignal, now?: number): Promise<AutopilotStatus>;
|
|
84
92
|
export declare function autopilotLines(status: AutopilotStatus): string[];
|
package/dist/cliAutopilot.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* `rules test` classifies the command on this machine and sends only the
|
|
11
11
|
* vendor and verb (and the environment kind), never the command line.
|
|
12
12
|
*/
|
|
13
|
+
import { guardLines, guardStatus } from "./cliStatusGuard.js";
|
|
13
14
|
import { bool, value } from "./cliArgs.js";
|
|
14
15
|
import { OTHER_APPS, PRESET_LABEL, PRESET_ROWS, rowLabel } from "./cliAutopilotPolicy.js";
|
|
15
16
|
import { memberApi } from "./cliClient.js";
|
|
@@ -75,7 +76,7 @@ function waitOutcome(id, body) {
|
|
|
75
76
|
const lead = message ?? `Approved${by ? ` by ${by}` : ""}.`;
|
|
76
77
|
const next = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
|
|
77
78
|
// Once, when this approval reaches the threshold: "Tip: You've approved
|
|
78
|
-
// railway redeploy in Staging
|
|
79
|
+
// railway redeploy in Staging 3 times. ... Make it a rule: <link>".
|
|
79
80
|
const suggestion = text(body.suggestion, 400);
|
|
80
81
|
const human = suggestion ? `${next}\n${suggestion}` : next;
|
|
81
82
|
return {
|
|
@@ -398,36 +399,7 @@ function presetMap(raw) {
|
|
|
398
399
|
out[OTHER_APPS] = body[OTHER_APPS];
|
|
399
400
|
return out;
|
|
400
401
|
}
|
|
401
|
-
|
|
402
|
-
export function localMidnight(now) {
|
|
403
|
-
const date = new Date(now);
|
|
404
|
-
date.setHours(0, 0, 0, 0);
|
|
405
|
-
return date.getTime();
|
|
406
|
-
}
|
|
407
|
-
async function answeredStatus(fetchApi, profile, signal, now) {
|
|
408
|
-
const { answeredToday } = await import("./cliAnswered.js");
|
|
409
|
-
const local = profile ? answeredToday(profile, now) : 0;
|
|
410
|
-
try {
|
|
411
|
-
const response = await fetchApi(`/api/my/stats?range=24h&todayStart=${localMidnight(now)}`, {
|
|
412
|
-
method: "GET",
|
|
413
|
-
headers: { accept: "application/json" },
|
|
414
|
-
signal
|
|
415
|
-
});
|
|
416
|
-
if (response.ok) {
|
|
417
|
-
const body = await readBoundedJson(response);
|
|
418
|
-
const today = body.answered?.today;
|
|
419
|
-
// Batches reach Passport every few minutes; never show less than this computer counted.
|
|
420
|
-
if (typeof today === "number" && Number.isFinite(today))
|
|
421
|
-
return { today: Math.max(today, local), source: "workspace" };
|
|
422
|
-
}
|
|
423
|
-
else
|
|
424
|
-
await response.body?.cancel().catch(() => undefined);
|
|
425
|
-
}
|
|
426
|
-
catch {
|
|
427
|
-
/* This computer's own count. */
|
|
428
|
-
}
|
|
429
|
-
return { today: local, source: "this-computer" };
|
|
430
|
-
}
|
|
402
|
+
export { localMidnight } from "./cliSpeed.js";
|
|
431
403
|
async function allowlistStatus() {
|
|
432
404
|
try {
|
|
433
405
|
const { readManifest } = await import("./nativeSync.js");
|
|
@@ -476,8 +448,9 @@ export async function autopilotStatus(fetchApi, profile, signal, now = Date.now(
|
|
|
476
448
|
}
|
|
477
449
|
const reason = text(body.floors?.reason, 120);
|
|
478
450
|
const exceptions = looseningLines(body);
|
|
479
|
-
const answered = await
|
|
451
|
+
const { answered, speed } = await (await import("./cliSpeed.js")).todayStatus(fetchApi, profile, signal, now);
|
|
480
452
|
const allowlists = await allowlistStatus();
|
|
453
|
+
const guard = await guardStatus(fetchApi, profile, signal, now);
|
|
481
454
|
return {
|
|
482
455
|
presets: presetMap(body.presets),
|
|
483
456
|
floors,
|
|
@@ -485,6 +458,8 @@ export async function autopilotStatus(fetchApi, profile, signal, now = Date.now(
|
|
|
485
458
|
...(exceptions.length ? { exceptions } : {}),
|
|
486
459
|
cache,
|
|
487
460
|
...(answered ? { answered } : {}),
|
|
461
|
+
...(speed ? { speed } : {}),
|
|
462
|
+
...(guard ? { guard } : {}),
|
|
488
463
|
...(allowlists ? { allowlists } : {})
|
|
489
464
|
};
|
|
490
465
|
}
|
|
@@ -507,6 +482,11 @@ export function autopilotLines(status) {
|
|
|
507
482
|
lines.push(cache.fetchedAt === null
|
|
508
483
|
? "Rules on this computer: not synced yet"
|
|
509
484
|
: `Rules on this computer: synced ${ageText(cache.ageMs ?? 0)}${cache.version === 1 ? " (older server: asks before destructive commands only)" : ""}`);
|
|
485
|
+
if (status.speed) {
|
|
486
|
+
lines.push(`${status.speed.line}${status.speed.source === "this-computer" ? " (this computer)" : ""}`);
|
|
487
|
+
}
|
|
488
|
+
// The guard state sits next to the speed line: both say how the guard is doing here.
|
|
489
|
+
lines.push(...guardLines(status.guard));
|
|
510
490
|
if (status.answered) {
|
|
511
491
|
const count = status.answered.today;
|
|
512
492
|
lines.push(`Answered for you: ${count.toLocaleString("en-US")} ${count === 1 ? "prompt" : "prompts"} today${status.answered.source === "this-computer" ? " on this computer" : ""}`);
|
|
@@ -87,12 +87,17 @@ export type AutopilotPolicy = {
|
|
|
87
87
|
/** The server decides everyday commands too (Phase 1.5): reports and
|
|
88
88
|
* decide requests may carry them. */
|
|
89
89
|
localCommands?: boolean;
|
|
90
|
+
/** The server keeps the hook's speed numbers (cli-policy v2 `speed`). */
|
|
91
|
+
reportsSpeed?: boolean;
|
|
90
92
|
/** Production classes someone else must approve: never run here, and never
|
|
91
93
|
* approved in the agent's own prompt. "Maya or Sam" names who approves. */
|
|
92
94
|
secondPerson?: {
|
|
93
95
|
classes: ActionClass[];
|
|
94
96
|
approvers: string;
|
|
95
97
|
};
|
|
98
|
+
/** What the guard does per environment when Passport can't be reached
|
|
99
|
+
* (Batch A). Absent from older servers: built-in defaults apply. */
|
|
100
|
+
offline?: Record<ActionEnv, "ask" | "block" | "allow">;
|
|
96
101
|
/** Resources the workspace placed, by id (Phase 4.5). Present only when the
|
|
97
102
|
* server reads where a finding lands, so findings may carry it. */
|
|
98
103
|
resources?: Array<{
|
|
@@ -101,6 +106,8 @@ export type AutopilotPolicy = {
|
|
|
101
106
|
label: string;
|
|
102
107
|
kind: EnvKind;
|
|
103
108
|
source: "detected" | "set" | "assumed";
|
|
109
|
+
/** The label came from the connected app, not from a link file. */
|
|
110
|
+
confirmed?: boolean;
|
|
104
111
|
}>;
|
|
105
112
|
};
|
|
106
113
|
/** The platform a vendor CLI acts on, so its rules and environments line up
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether Codex trusts Passport's guard hook (Batch A, "Not trusted").
|
|
3
|
+
*
|
|
4
|
+
* Codex runs a hook from `~/.codex/hooks.json` only after the person trusts
|
|
5
|
+
* it in `/hooks`. It then stores, in `~/.codex/config.toml`,
|
|
6
|
+
*
|
|
7
|
+
* [hooks.state."<hooks.json path>:pre_tool_use:<group>:<handler>"]
|
|
8
|
+
* trusted_hash = "sha256:<hex>"
|
|
9
|
+
*
|
|
10
|
+
* and runs the hook only while that hash matches the hook as written now. The
|
|
11
|
+
* hash input, confirmed in openai/codex (codex-rs/hooks/src/engine/discovery.rs
|
|
12
|
+
* `hook_hash`, codex-rs/config/src/fingerprint.rs `version_for_toml`) and
|
|
13
|
+
* against codex-cli 0.146.0's `hooks/list`, is the normalized identity
|
|
14
|
+
* `{ event_name, matcher?, hooks: [handler] }`, where the handler is
|
|
15
|
+
* `{ type: "command", command, timeout (default 600), async (default false),
|
|
16
|
+
* statusMessage?, additionalContextLimit? (when not 2500) }`, serialized as
|
|
17
|
+
* JSON with every object's keys sorted, no whitespace, then SHA-256.
|
|
18
|
+
*
|
|
19
|
+
* Read-only: Passport never writes Codex's trust; only the person can.
|
|
20
|
+
*/
|
|
21
|
+
import type { CodexTrust } from "./cliGuardState.js";
|
|
22
|
+
type Handler = Record<string, unknown>;
|
|
23
|
+
/** Codex's trust hash for one PreToolUse command handler. */
|
|
24
|
+
export declare function codexHookHash(matcher: string | undefined, handler: Handler): string;
|
|
25
|
+
/** Where Passport's guard sits in hooks.json: its group and handler index. */
|
|
26
|
+
export declare function findGuardEntry(settings: unknown, isGuard: (command: unknown) => boolean): {
|
|
27
|
+
group: number;
|
|
28
|
+
handler: number;
|
|
29
|
+
matcher?: string;
|
|
30
|
+
entry: Handler;
|
|
31
|
+
} | null;
|
|
32
|
+
/** `[hooks.state."<key>"]` tables in config.toml: each key's trusted hash and enabled flag. */
|
|
33
|
+
export declare function codexHookStates(toml: string): Map<string, {
|
|
34
|
+
trustedHash?: string;
|
|
35
|
+
enabled?: boolean;
|
|
36
|
+
}>;
|
|
37
|
+
/**
|
|
38
|
+
* Codex's trust in Passport's guard entry in `hooksPath`, or undefined when
|
|
39
|
+
* the file holds no guard entry (nothing to trust).
|
|
40
|
+
*/
|
|
41
|
+
export declare function codexGuardTrust(hooksPath: string, isGuard: (command: unknown) => boolean): CodexTrust | undefined;
|
|
42
|
+
export {};
|