passport-bridge 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -246,7 +246,7 @@ Two hooks per agent. `passport hook` runs after each shell command and records t
246
246
 
247
247
  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.`
248
248
 
249
- **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:
249
+ **Attended or unattended** (`src/cliHookMode.ts`). With a person at the keyboard, an ask is the agent's own prompt with Passport's reason, except an irreversible command: it is approved only in Passport, with a passkey check, so the guard files the request and holds as below, and blocks with `Passport can't be reached. Irreversible commands need approval in Passport.` if Passport doesn't answer. 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:
250
250
 
251
251
  | Signal | Means |
252
252
  | ------------------------------------------------------------------------------------------------- | --------------------------------------- |
@@ -261,7 +261,7 @@ Codex has no field for `codex exec`; its prompt-free modes count as unattended,
261
261
 
262
262
  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.
263
263
 
264
- 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.
264
+ The guard decides from local data inside `HOOK_BUDGET_MS` (1.5 s) and prints first; only an unattended ask (or an irreversible one) waits for the server, within the same budget. The one exception is End session (`src/cliHookSessionEnd.ts`): before a command it would let run on its own (an allow, or nothing to decide), a signed-in guard asks `GET /api/my/cli/session` (agent and session id only) whether a person ended that session, at most every 15 s per session and for at most 300 ms; an ended session is cached and refused with the server's line from then on, and no answer means the command proceeds. It is a guardrail, not a security boundary: the launcher's fast-path reads and a guard running with `PASSPORT_AGENT_KEY` don't check. 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.
265
265
 
266
266
  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.
267
267
 
@@ -53,7 +53,9 @@ function repository(cwd, runtime, fs) {
53
53
  return {
54
54
  root,
55
55
  cwd: machine.cwd,
56
- ...(remote ? { repo: remoteFingerprint(remote), repoName: remote.split("/").pop() } : {})
56
+ ...(remote
57
+ ? { repo: remoteFingerprint(remote), repoName: remote.split("/").pop(), repoHost: remote.split("/")[0] }
58
+ : {})
57
59
  };
58
60
  }
59
61
  /** What `<script> [args…]` names, with the hash of what it runs today. */
@@ -64,7 +66,7 @@ function describeScript(words, explicitArgs, repo, fs) {
64
66
  const cwd = repo.cwd ?? repo.root;
65
67
  if (!cwd)
66
68
  return "Run this inside the project.";
67
- const ids = { ...(repo.repo ? { repo: repo.repo, repoName: repo.repoName } : {}) };
69
+ const ids = repo.repo ? { repo: repo.repo, repoName: repo.repoName, repoHost: repo.repoHost } : {};
68
70
  if (RUNNERS.has(first)) {
69
71
  // `make deploy`, `npm run deploy`: what the target or package script runs.
70
72
  const target = first === "make" ? rest.join(" ") : `run ${rest.filter((word) => word !== "run").join(" ")}`;
@@ -115,8 +117,15 @@ async function post(client, body, args, runtime) {
115
117
  body: JSON.stringify(body),
116
118
  signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
117
119
  });
118
- if (!response.ok)
119
- return { error: await safeApiError(response, "Passport couldn't save it."), status: response.status };
120
+ if (!response.ok) {
121
+ const error = await safeApiError(response, "Passport couldn't save it.");
122
+ // A server from before repository hosts refuses the field: send it without.
123
+ if (response.status === 400 && body.repoHost && error.includes('"repoHost"')) {
124
+ const { repoHost: _host, ...older } = body;
125
+ return post(client, older, args, runtime);
126
+ }
127
+ return { error, status: response.status };
128
+ }
120
129
  const parsed = (await readBoundedJson(response).catch(() => ({})));
121
130
  return { action: parsed.action ?? {} };
122
131
  }
@@ -125,7 +134,7 @@ function line(action, fallback) {
125
134
  const where = action.environment ? (ENV_WORD[action.environment] ?? action.environment) : "";
126
135
  const what = classWord(action.actionClass);
127
136
  return action.status === "proposed"
128
- ? `${label}: proposed (${what} in ${where}). An admin approves it in Passport Rules › Environments.`
137
+ ? `${label}: proposed (${what} in ${where}). An admin approves it on the app's page in Passport.`
129
138
  : `${label}: ${what} in ${where}. Passport checks it from now on.`;
130
139
  }
131
140
  function classified(args) {
@@ -147,6 +147,9 @@ export type AutopilotPolicy = {
147
147
  /** The workspace keeps the agent's own step descriptions (cli-policy v2
148
148
  * `descriptions`, "Show what agents say they're doing"). Off when absent. */
149
149
  reportsSteps?: boolean;
150
+ /** The server answers an attended ask with its reason line and short link
151
+ * (cli-policy v2 `asks`), so the guard asks it before the agent's prompt. */
152
+ askLines?: boolean;
150
153
  /** Production classes someone else must approve: never run here, and never
151
154
  * approved in the agent's own prompt. "Maya or Sam" names who approves. */
152
155
  secondPerson?: {
@@ -17,7 +17,7 @@ import { failure, timeoutMs } from "./cliSupport.js";
17
17
  import { appName, clientName, count, list, oneOf, record, text, time, windowOf } from "./cliSessionsJson.js";
18
18
  import { countOf } from "./plural.js";
19
19
  import { joinParts, mark, visibleLength, wrap, termOf } from "./term.js";
20
- import { hashLink } from "./webLinks.js";
20
+ import { APPS_LINK, hashLink } from "./webLinks.js";
21
21
  const DATE = /^\d{4}-\d{2}-\d{2}$/;
22
22
  const RANGES = ["1h", "6h", "24h", "7d", "30d", "today"];
23
23
  const DEFAULT_SINCE = "7d";
@@ -344,7 +344,7 @@ export async function changes(args, runtime, deps = {}) {
344
344
  return {
345
345
  json: page,
346
346
  human: renderChanges(page, term, now, since, {
347
- environments: hashLink(client.origin, "#rules?section=environments"),
347
+ environments: hashLink(client.origin, APPS_LINK),
348
348
  more: hashLink(client.origin, `#sessions${web}`)
349
349
  })
350
350
  };
@@ -87,7 +87,7 @@ export function problemFix(kind, client) {
87
87
  return {
88
88
  text: "Move it back into Passport.",
89
89
  command: "passport keys move",
90
- link: "#settings/keys",
90
+ link: "#apps",
91
91
  docs: `${DOCS_BASE}/member/cli-hook#keys-in-passport`
92
92
  };
93
93
  }
package/dist/cliHook.js CHANGED
@@ -505,9 +505,9 @@ async function runGuard(args, runtime, deps) {
505
505
  const plan = await planGuard(decision, policy, {
506
506
  client,
507
507
  mode,
508
- canAsk: Boolean(profile) && canReport && !event.cursorImported,
508
+ canAsk: canReport && !event.cursorImported,
509
509
  openApi: () => profileApi(profile, budget, deps.fetch ?? fetch).catch(() => null),
510
- report: base,
510
+ report: base ?? context(input, runtime.env, declared),
511
511
  local,
512
512
  command: event.command,
513
513
  budget,
@@ -51,6 +51,8 @@ export type ServerDecision = {
51
51
  /** A pending approval: when it expires, and who decides. */
52
52
  expiresAt?: number;
53
53
  waitingFor?: string;
54
+ /** An attended ask's reason line, ending with its short link (≤ 240). */
55
+ askLine?: string;
54
56
  };
55
57
  type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
56
58
  /** Validate what the server said. Anything unexpected is no answer at all. */
@@ -61,7 +63,10 @@ export declare function decideRequest(decision: GuardDecision, context: {
61
63
  toolUseId?: string;
62
64
  folder?: string;
63
65
  project?: string;
64
- }, command: string, local?: boolean): CliDecideRequest & {
66
+ }, command: string, local?: boolean,
67
+ /** Someone is at the keyboard: the agent's own prompt answers, and Passport
68
+ * only supplies its reason line (cli-policy `asks`). */
69
+ interactive?: boolean): CliDecideRequest & {
65
70
  project?: string;
66
71
  };
67
72
  /** Ask the server, or null when it couldn't answer in time. Never throws. */
@@ -99,13 +104,20 @@ export declare function offlineVerdict(decision: GuardDecision, policy: CachedCl
99
104
  secondPerson: boolean;
100
105
  attended: boolean;
101
106
  }, now: number): OfflineVerdict;
107
+ /** What an attended irreversible ask says when Passport can't be reached. */
108
+ export declare const IRREVERSIBLE_UNREACHABLE = "Passport can't be reached. Irreversible commands need approval in Passport.";
109
+ /** What an irreversible ask tells the agent while it waits in Passport. */
110
+ export declare const IRREVERSIBLE_IN_PASSPORT = "Approve this in Passport. Irreversible actions need a passkey check.";
102
111
  /**
103
112
  * Attended, or no v2 policy: the local decision, printed at once. Unattended
104
113
  * ask: the server decides within the budget, and an approval request replaces
105
114
  * the prompt nobody would answer; a server that can't answer in time leaves
106
115
  * the local decision with one line saying so.
107
116
  */
108
- export declare function planGuard(decision: GuardDecision | null, policy: CachedCliPolicy | null, context: {
117
+ export declare function planGuard(...args: Parameters<typeof decidePlan>): Promise<GuardPlan & {
118
+ api?: ApiCall;
119
+ }>;
120
+ declare function decidePlan(decision: GuardDecision | null, policy: CachedCliPolicy | null, context: {
109
121
  client: GuardClient;
110
122
  mode: HookMode;
111
123
  /** Signed in with a member profile that may report. */
@@ -23,6 +23,7 @@ import { OFFLINE_CACHE_MAX_MS, OFFLINE_DEFAULT, OFFLINE_NOTES, offlineDecision }
23
23
  import { commandKey } from "./cliHookKey.js";
24
24
  import { unknownVerb, UNRECOGNIZED_VERB } from "./cliHookClassify.js";
25
25
  import { redactCommand } from "./cliHookRedact.js";
26
+ import { endedSessionLine, rememberEnded } from "./cliHookSessionEnd.js";
26
27
  export const CLI_DECIDE_PATH = "/api/my/cli/decide";
27
28
  const MAX_RESPONSE_BYTES = 16 * 1024;
28
29
  const MAX_FINDINGS = 8;
@@ -59,6 +60,7 @@ export function parseServerDecision(raw) {
59
60
  const explanation = line(body.explanation, 240);
60
61
  const message = line(body.message, 400);
61
62
  const waitingFor = line(body.waitingFor, 80);
63
+ const askLine = line(body.askLine, 240);
62
64
  const expiresAt = typeof body.expiresAt === "number" && Number.isSafeInteger(body.expiresAt) && body.expiresAt > 0
63
65
  ? body.expiresAt
64
66
  : undefined;
@@ -73,7 +75,8 @@ export function parseServerDecision(raw) {
73
75
  ...(approvalId ? { approvalId } : {}),
74
76
  ...(message ? { message } : {}),
75
77
  ...(expiresAt !== undefined ? { expiresAt } : {}),
76
- ...(waitingFor ? { waitingFor } : {})
78
+ ...(waitingFor ? { waitingFor } : {}),
79
+ ...(askLine ? { askLine } : {})
77
80
  };
78
81
  }
79
82
  const VERB_TOKEN = /^-{0,2}[A-Za-z0-9][A-Za-z0-9._:+-]{0,39}$/;
@@ -85,7 +88,10 @@ function safeVerbOf(raw) {
85
88
  .slice(0, 4);
86
89
  return tokens.join(" ").slice(0, 80).trim() || UNRECOGNIZED_VERB;
87
90
  }
88
- export function decideRequest(decision, context, command, local = false) {
91
+ export function decideRequest(decision, context, command, local = false,
92
+ /** Someone is at the keyboard: the agent's own prompt answers, and Passport
93
+ * only supplies its reason line (cli-policy `asks`). */
94
+ interactive = false) {
89
95
  const findings = (decision.decided ?? [])
90
96
  .filter((entry) => entry.finding.vendor)
91
97
  // Everyday commands go only to a server that places them.
@@ -109,7 +115,7 @@ export function decideRequest(decision, context, command, local = false) {
109
115
  ...(context.folder ? { folder: context.folder } : {}),
110
116
  // The repository's name, for code that reaches its default branch.
111
117
  ...(context.project ? { project: context.project } : {}),
112
- interactive: false,
118
+ interactive,
113
119
  findings,
114
120
  ...(summary ? { commandSummary: summary } : {}),
115
121
  ...(key ? { commandKey: key } : {})
@@ -128,7 +134,11 @@ export async function decideOnServer(api, request, signal) {
128
134
  await response.body?.cancel().catch(() => undefined);
129
135
  return null;
130
136
  }
131
- return parseServerDecision(await readBoundedJson(response, MAX_RESPONSE_BYTES));
137
+ const decided = parseServerDecision(await readBoundedJson(response, MAX_RESPONSE_BYTES));
138
+ // Passport refused because a person ended this session: remember it here.
139
+ if (decided?.decision === "block")
140
+ rememberEnded(request, decided.message);
141
+ return decided;
132
142
  }
133
143
  catch {
134
144
  return null;
@@ -223,13 +233,48 @@ function serverOutput(client, decision, server) {
223
233
  : {};
224
234
  return guardOutput(client, decided, options);
225
235
  }
236
+ /** What an attended irreversible ask says when Passport can't be reached. */
237
+ export const IRREVERSIBLE_UNREACHABLE = "Passport can't be reached. Irreversible commands need approval in Passport.";
238
+ /** What an irreversible ask tells the agent while it waits in Passport. */
239
+ export const IRREVERSIBLE_IN_PASSPORT = "Approve this in Passport. Irreversible actions need a passkey check.";
240
+ /** Whether any command in the line that asked is irreversible. */
241
+ function irreversibleAsk(decision) {
242
+ return (decision.actionClass === "irreversible" ||
243
+ (decision.decided ?? []).some((entry) => entry.decision === "ask" && entry.actionClass === "irreversible"));
244
+ }
245
+ function attendedIrreversible(decision, mode) {
246
+ return mode !== "unattended" && irreversibleAsk(decision);
247
+ }
248
+ /** An attended ask the agent's own prompt answers (Codex can't ask from a hook). */
249
+ function staysLocal(context, toPassport) {
250
+ return context.mode !== "unattended" && !toPassport && context.client !== "codex";
251
+ }
252
+ function unreachableIrreversible(client, decision, api) {
253
+ const output = guardOutput(client, { ...decision, verdict: "deny" }, { waiting: IRREVERSIBLE_UNREACHABLE });
254
+ return { output, server: null, offline: true, verdict: "deny", ...(api ? { api } : {}) };
255
+ }
256
+ /** A person ended this session in Passport: nothing more runs in it, even a
257
+ * command this computer would let run (`cliHookSessionEnd.ts`). */
258
+ async function endedPlan(decision, context) {
259
+ // Only what would run without anyone deciding: an ask is a person's call.
260
+ if (!context.canAsk || (decision && decision.verdict !== "allow"))
261
+ return null;
262
+ const ended = await endedSessionLine(context.report, context.openApi, context);
263
+ if (!ended)
264
+ return null;
265
+ const refused = decision ?? { verdict: "deny", label: "command", findings: [], destructive: false };
266
+ return { output: guardOutput(context.client, refused, { waiting: ended }), server: null, offline: false };
267
+ }
226
268
  /**
227
269
  * Attended, or no v2 policy: the local decision, printed at once. Unattended
228
270
  * ask: the server decides within the budget, and an approval request replaces
229
271
  * the prompt nobody would answer; a server that can't answer in time leaves
230
272
  * the local decision with one line saying so.
231
273
  */
232
- export async function planGuard(decision, policy, context) {
274
+ export async function planGuard(...args) {
275
+ return (await endedPlan(args[0], args[2])) ?? decidePlan(...args);
276
+ }
277
+ async function decidePlan(decision, policy, context) {
233
278
  const local = { output: decision ? guardOutput(context.client, decision) : null, server: null, offline: false };
234
279
  // A Production action someone else must approve goes to Passport even when
235
280
  // someone is at the keyboard: the agent's own prompt would let them approve it.
@@ -240,10 +285,13 @@ export async function planGuard(decision, policy, context) {
240
285
  Boolean(policy.autopilot.secondPerson?.classes.includes(decision.actionClass)));
241
286
  if (!decision || decision.verdict !== "ask" || policy?.version !== 2)
242
287
  return local;
288
+ // An irreversible action is approved only in Passport, with a passkey check:
289
+ // the one attended ask that waits on the network (docs/DECISIONS.md).
290
+ const irreversible = attendedIrreversible(decision, context.mode);
243
291
  // Codex can't ask from a hook: like an unattended run, the ask goes to
244
292
  // Passport as an approval request instead of a prompt nobody would see.
245
- if (context.mode !== "unattended" && !secondPerson && context.client !== "codex")
246
- return local;
293
+ if (staysLocal(context, secondPerson || irreversible))
294
+ return attendedPlan(decision, policy, context, local);
247
295
  if (!context.canAsk)
248
296
  return local;
249
297
  const request = decideRequest(decision, {
@@ -262,6 +310,9 @@ export async function planGuard(decision, policy, context) {
262
310
  const server = api && left > 50
263
311
  ? await decideOnServer(api, request, AbortSignal.any([context.budget, AbortSignal.timeout(left)]))
264
312
  : null;
313
+ // Never the agent's own Approve prompt, even with Passport out of reach.
314
+ if (!server && irreversible)
315
+ return unreachableIrreversible(context.client, decision, api);
265
316
  if (!server) {
266
317
  // Passport didn't answer in time: the environment's offline setting decides.
267
318
  const offline = offlineVerdict(decision, policy, { client: context.client, secondPerson, attended: context.mode === "attended" }, context.now());
@@ -277,6 +328,41 @@ export async function planGuard(decision, policy, context) {
277
328
  ? heldPlan(decision, server, request, api, context)
278
329
  : { output: serverOutput(context.client, decision, server), server, offline: false };
279
330
  }
331
+ /**
332
+ * An attended ask the agent's own prompt answers. Passport, when it answers in
333
+ * time, supplies the reason line (the ask, ending with its short link to every
334
+ * other choice) and anything it knows better: an answer already given there
335
+ * ("It’s Staging, always run", Run for this task) runs, a stop refuses. Out
336
+ * of time, or no answer: the local prompt, unchanged.
337
+ */
338
+ async function attendedPlan(decision, policy, context, local) {
339
+ // Only a server that sends ask lines (cli-policy `asks`) is asked, and only signed in.
340
+ if (policy.version !== 2 || !policy.autopilot.askLines || !context.canAsk)
341
+ return local;
342
+ const request = decideRequest(decision, {
343
+ runtime: context.report?.runtime ?? "other",
344
+ ...(context.report?.sessionId ? { sessionId: context.report.sessionId } : {}),
345
+ ...(context.report?.toolUseId ? { toolUseId: context.report.toolUseId } : {}),
346
+ ...(context.report?.cwdName ? { folder: context.report.cwdName } : {}),
347
+ ...(context.report?.project && policy.autopilot.repos ? { project: context.report.project } : {})
348
+ }, context.command, context.local === true, true);
349
+ if (!request.findings.length)
350
+ return local;
351
+ const api = await context.openApi();
352
+ const left = context.deadline - context.now();
353
+ const server = api && left > 50
354
+ ? await decideOnServer(api, request, AbortSignal.any([context.budget, AbortSignal.timeout(left)]))
355
+ : null;
356
+ if (!server || server.decision === "none")
357
+ return local;
358
+ if (server.decision === "ask" && !server.approvalId) {
359
+ const output = guardOutput(context.client, decision, server.askLine ? { askReason: server.askLine } : {});
360
+ return { output, server, offline: false, ...(api ? { api } : {}) };
361
+ }
362
+ return api
363
+ ? heldPlan(decision, server, request, api, context)
364
+ : { output: serverOutput(context.client, decision, server), server, offline: false };
365
+ }
280
366
  /**
281
367
  * The server's answer as a plan. A request a person can answer: hold for them (Claude Code and Cursor run
282
368
  * the original command when they approve in time); otherwise, or when the
@@ -288,7 +374,9 @@ async function heldPlan(decision, server, request, api, context) {
288
374
  return { output: serverOutput(context.client, decision, server), server, offline: false, api };
289
375
  const hold = await import("./cliHookHold.js");
290
376
  const pending = (who, expiresAt, approvalId) => guardOutput(context.client, { ...decision, verdict: "deny" }, {
291
- waiting: hold.pendingMessage(approvalId ?? waiting.approvalId, who ?? waiting.waitingFor, expiresAt ?? waiting.expiresAt, context.now())
377
+ // An irreversible action says first that it's approved in Passport.
378
+ waiting: (irreversibleAsk(decision) ? `${IRREVERSIBLE_IN_PASSPORT} ` : "") +
379
+ hold.pendingMessage(approvalId ?? waiting.approvalId, who ?? waiting.waitingFor, expiresAt ?? waiting.expiresAt, context.now())
292
380
  });
293
381
  // Only Claude Code holds: Codex can't run an approved command from a hook,
294
382
  // and Cursor's behaviour past a hook's timeout isn't documented.
@@ -133,6 +133,9 @@ export declare const CODEX_ASK_NOTE = "Codex can't ask from a hook, so Passport
133
133
  export type GuardOutputOptions = {
134
134
  /** Replaces the reason entirely: an approval request is waiting. */
135
135
  waiting?: string;
136
+ /** An ask's reason line from Passport (its short link to every other
137
+ * choice at the end), in place of the local one. */
138
+ askReason?: string;
136
139
  /** One line added to the reason, e.g. OFFLINE_NOTE. */
137
140
  note?: string;
138
141
  /** Who to ask, for a block. */
@@ -469,7 +469,7 @@ export function guardOutput(client, decision, options = {}) {
469
469
  return { permission: "allow" };
470
470
  return verdict === "deny"
471
471
  ? { permission: "deny", user_message: deny, agent_message: agentDeny }
472
- : { permission: "ask", user_message: withNote(askMessage(decision), options.note) };
472
+ : { permission: "ask", user_message: withNote(options.askReason ?? askMessage(decision), options.note) };
473
473
  }
474
474
  if (client === "codex") {
475
475
  if (verdict === "ask") {
@@ -518,7 +518,7 @@ export function guardOutput(client, decision, options = {}) {
518
518
  hookSpecificOutput: {
519
519
  hookEventName: "PreToolUse",
520
520
  permissionDecision: "ask",
521
- permissionDecisionReason: withNote(askMessage(decision), options.note)
521
+ permissionDecisionReason: withNote(options.askReason ?? askMessage(decision), options.note)
522
522
  }
523
523
  };
524
524
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * End session, on this computer. When a person ends an agent's session in
3
+ * Passport, the server refuses everything that reaches it under that session.
4
+ * The guard decides most commands here, so before a command it would let run
5
+ * on its own (an allow, or nothing to decide; an ask is a person's call) it
6
+ * asks Passport whether the session was ended (`GET /api/my/cli/session`),
7
+ * and refuses with the server's own line when it was.
8
+ *
9
+ * It costs little: a session checked in the last 15 seconds isn't asked
10
+ * again, a session known to be ended is never asked again, and the question
11
+ * never waits more than 300 ms. On a timeout or any error the command
12
+ * proceeds as it would have: the guard is a guardrail, not a security
13
+ * boundary. A refusal from the decide fast path teaches it too.
14
+ *
15
+ * State lives in owner-only files named by a digest of the agent and session
16
+ * id, holding only when it was checked and, once ended, the server's line.
17
+ * Bounded in count and age. Never throws.
18
+ */
19
+ export declare const CLI_SESSION_PATH = "/api/my/cli/session";
20
+ /** A session checked this recently isn't asked about again. */
21
+ export declare const SESSION_FRESH_MS = 15000;
22
+ /** The longest a command the guard would let run waits on the question. */
23
+ export declare const SESSION_CHECK_MS = 300;
24
+ /** The server's line, exactly: "Session ended by Maya at 14:05 UTC. Start a new session to continue." */
25
+ export declare const ENDED_LINE: RegExp;
26
+ type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
27
+ export type SessionRef = {
28
+ runtime: string;
29
+ sessionId?: string;
30
+ } | null;
31
+ /** A refusal Passport sent for this session (decide): remember it, so the
32
+ * guard refuses the rest here without asking. */
33
+ export declare function rememberEnded(session: SessionRef, message: string | undefined, now?: number): void;
34
+ /** Validate what Passport said: the line when the session ended, "" when it
35
+ * runs, null for anything unexpected. */
36
+ export declare function parseSessionState(raw: unknown): string | null;
37
+ /**
38
+ * The line to refuse with when a person ended this session, else undefined.
39
+ * Known ended: no network. Checked in the last 15 s: no network. Otherwise one
40
+ * question, bounded by 300 ms (and the hook's own budget); no answer in time
41
+ * means the command proceeds, and the session is asked again after 15 s.
42
+ */
43
+ export declare function endedSessionLine(session: SessionRef, openApi: () => Promise<ApiCall | null>, options: {
44
+ now: () => number;
45
+ budget: AbortSignal;
46
+ timeoutMs?: number;
47
+ }): Promise<string | undefined>;
48
+ export {};
@@ -0,0 +1,162 @@
1
+ /**
2
+ * End session, on this computer. When a person ends an agent's session in
3
+ * Passport, the server refuses everything that reaches it under that session.
4
+ * The guard decides most commands here, so before a command it would let run
5
+ * on its own (an allow, or nothing to decide; an ask is a person's call) it
6
+ * asks Passport whether the session was ended (`GET /api/my/cli/session`),
7
+ * and refuses with the server's own line when it was.
8
+ *
9
+ * It costs little: a session checked in the last 15 seconds isn't asked
10
+ * again, a session known to be ended is never asked again, and the question
11
+ * never waits more than 300 ms. On a timeout or any error the command
12
+ * proceeds as it would have: the guard is a guardrail, not a security
13
+ * boundary. A refusal from the decide fast path teaches it too.
14
+ *
15
+ * State lives in owner-only files named by a digest of the agent and session
16
+ * id, holding only when it was checked and, once ended, the server's line.
17
+ * Bounded in count and age. Never throws.
18
+ */
19
+ import { createHash } from "node:crypto";
20
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
21
+ import { basename, join } from "node:path";
22
+ import { readBoundedJson } from "./boundedResponse.js";
23
+ import { credentialDir, enforceOwner, ensurePrivateDirectory, writePrivateAtomic } from "./credentialStorage.js";
24
+ export const CLI_SESSION_PATH = "/api/my/cli/session";
25
+ /** A session checked this recently isn't asked about again. */
26
+ export const SESSION_FRESH_MS = 15_000;
27
+ /** The longest a command the guard would let run waits on the question. */
28
+ export const SESSION_CHECK_MS = 300;
29
+ const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
30
+ const MAX_FILES = 500;
31
+ const MAX_RESPONSE_BYTES = 4 * 1024;
32
+ const DIRECTORY = "hook-sessions";
33
+ const SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
34
+ const RUNTIMES = new Set(["claude-code", "codex", "copilot", "cursor", "other"]);
35
+ /** The server's line, exactly: "Session ended by Maya at 14:05 UTC. Start a new session to continue." */
36
+ export const ENDED_LINE = /^Session ended by [^\n]{1,80} at \d\d:\d\d UTC\. Start a new session to continue\.$/;
37
+ function directory() {
38
+ return join(credentialDir(), DIRECTORY);
39
+ }
40
+ function usable(session) {
41
+ return Boolean(session?.sessionId && SESSION.test(session.sessionId) && RUNTIMES.has(session.runtime));
42
+ }
43
+ function statePath(runtime, sessionId) {
44
+ const key = createHash("sha256").update(`${runtime}\u0000${sessionId}`).digest("hex").slice(0, 40);
45
+ return join(directory(), `${key}.json`);
46
+ }
47
+ function readState(runtime, sessionId) {
48
+ try {
49
+ const path = statePath(runtime, sessionId);
50
+ if (statSync(path).size > MAX_RESPONSE_BYTES)
51
+ return null;
52
+ const raw = JSON.parse(readFileSync(path, "utf8"));
53
+ if (typeof raw.checkedAt !== "number")
54
+ return null;
55
+ const ended = typeof raw.ended === "string" && ENDED_LINE.test(raw.ended) ? raw.ended : undefined;
56
+ return { checkedAt: raw.checkedAt, ...(ended ? { ended } : {}) };
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ function writeState(runtime, sessionId, state, now) {
63
+ try {
64
+ ensurePrivateDirectory(true);
65
+ try {
66
+ mkdirSync(directory(), { mode: 0o700 });
67
+ }
68
+ catch (error) {
69
+ if (error.code !== "EEXIST")
70
+ throw error;
71
+ }
72
+ const stat = lstatSync(directory());
73
+ if (stat.isSymbolicLink() || !stat.isDirectory())
74
+ return;
75
+ enforceOwner(stat, "hook sessions directory");
76
+ const path = statePath(runtime, sessionId);
77
+ let names = readdirSync(directory()).filter((name) => /^[0-9a-f]{40}\.json$/.test(name));
78
+ if (names.length >= MAX_FILES && !names.includes(basename(path))) {
79
+ for (const name of names) {
80
+ const file = join(directory(), name);
81
+ if (now - statSync(file).mtimeMs > MAX_AGE_MS)
82
+ rmSync(file, { force: true });
83
+ }
84
+ names = readdirSync(directory()).filter((name) => /^[0-9a-f]{40}\.json$/.test(name));
85
+ if (names.length >= MAX_FILES)
86
+ return;
87
+ }
88
+ writePrivateAtomic(path, ".hook-session", JSON.stringify(state), "hook session");
89
+ }
90
+ catch {
91
+ /* Asked again next time: harmless. */
92
+ }
93
+ }
94
+ /** A refusal Passport sent for this session (decide): remember it, so the
95
+ * guard refuses the rest here without asking. */
96
+ export function rememberEnded(session, message, now = Date.now()) {
97
+ if (!usable(session) || !message || !ENDED_LINE.test(message))
98
+ return;
99
+ writeState(session.runtime, session.sessionId, { checkedAt: now, ended: message }, now);
100
+ }
101
+ /** Validate what Passport said: the line when the session ended, "" when it
102
+ * runs, null for anything unexpected. */
103
+ export function parseSessionState(raw) {
104
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
105
+ return null;
106
+ const body = raw;
107
+ if (body.ended === false)
108
+ return "";
109
+ return body.ended === true && typeof body.message === "string" && ENDED_LINE.test(body.message) ? body.message : null;
110
+ }
111
+ async function askPassport(openApi, session, signal) {
112
+ try {
113
+ const api = await openApi();
114
+ if (!api || signal.aborted)
115
+ return null;
116
+ const query = new URLSearchParams({ runtime: session.runtime, sessionId: session.sessionId });
117
+ const response = await api(`${CLI_SESSION_PATH}?${query.toString()}`, {
118
+ method: "GET",
119
+ headers: { accept: "application/json", "x-passport-surface": "cli" },
120
+ signal
121
+ });
122
+ if (!response.ok) {
123
+ await response.body?.cancel().catch(() => undefined);
124
+ return null;
125
+ }
126
+ return parseSessionState(await readBoundedJson(response, MAX_RESPONSE_BYTES));
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
132
+ /**
133
+ * The line to refuse with when a person ended this session, else undefined.
134
+ * Known ended: no network. Checked in the last 15 s: no network. Otherwise one
135
+ * question, bounded by 300 ms (and the hook's own budget); no answer in time
136
+ * means the command proceeds, and the session is asked again after 15 s.
137
+ */
138
+ export async function endedSessionLine(session, openApi, options) {
139
+ if (!usable(session))
140
+ return undefined;
141
+ const state = readState(session.runtime, session.sessionId);
142
+ if (state?.ended)
143
+ return state.ended;
144
+ const now = options.now();
145
+ if (state && now - state.checkedAt >= 0 && now - state.checkedAt < SESSION_FRESH_MS)
146
+ return undefined;
147
+ // A timer of our own (AbortSignal.timeout's doesn't keep the process up),
148
+ // and openApi may refresh a sign-in: the bound covers it too.
149
+ const bound = new AbortController();
150
+ const timer = setTimeout(() => bound.abort(), options.timeoutMs ?? SESSION_CHECK_MS);
151
+ const signal = AbortSignal.any([options.budget, bound.signal]);
152
+ const answer = await Promise.race([
153
+ askPassport(openApi, session, signal),
154
+ new Promise((resolve) => {
155
+ if (signal.aborted)
156
+ resolve(null);
157
+ signal.addEventListener("abort", () => resolve(null), { once: true });
158
+ })
159
+ ]).finally(() => clearTimeout(timer));
160
+ writeState(session.runtime, session.sessionId, { checkedAt: options.now(), ...(answer ? { ended: answer } : {}) }, options.now());
161
+ return answer || undefined;
162
+ }
package/dist/cliOutput.js CHANGED
@@ -144,7 +144,7 @@ function helpText(verb) {
144
144
  status: "passport status\nShows you, your workspace, and this computer; each agent's guard and its fix; Autopilot presets, team floors, and how old this computer's copy of your rules is; apps; keys Passport holds and when each was last used; this folder's environments; and the CLI version.\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}],autopilot?:{presets,floors,cache},computer,keys?,folder,cli}",
145
145
  wait: "passport wait <approval-id> [--timeout <sec>]\nWaits for a person to decide an approval request, until they do or it expires. Agents run it as a background command. While it is still waiting, prints the approval link; on a terminal, one live line counts down. Ctrl-C stops waiting and the request stays open (exit 4).\n Approved: prints who approved it and for how long; run the command again. Exit 0.\n Declined: prints the person's note for the agent. Exit 5.\n Expired: run the command again to ask again. Exit 5.\n Still waiting at --timeout: exit 4; run it again.",
146
146
  rules: 'passport rules test "<command>" [--environment production|staging|development]\nShows what Autopilot decides for a command, why, and which environment it acts on. The command is read on this computer; only its app and verb are sent to Passport.',
147
- actions: "passport actions\npassport actions add <script> [args…] --environment production|staging|development --class read|change|delete|irreversible [--args <glob>]\npassport actions add --id <op_…> --environment <kind> --class <class>\npassport actions sync\nTells Passport what a project script does, so the guard checks it: its environment and action class. Your presets and exceptions still decide what runs; a project script never runs on its say-so alone. <script> is a file in the project, or make, npm, pnpm, or yarn with the target or script name. --args is a glob over its arguments (* is any). --id is the id a Session row shows under \"Tell Passport what this does\"; this computer resolves it, since the script's name never left it. sync proposes each entry of the project's .passport/actions.toml. You can say Production for a change, delete, or irreversible action; anything else waits for an admin in Rules › Environments › Project scripts. Sends the script's path in the repository, the repository's fingerprint and name, and a SHA-256 of what it runs, never its contents.\nJSON: {action} | {actions:[…]}",
147
+ actions: "passport actions\npassport actions add <script> [args…] --environment production|staging|development --class read|change|delete|irreversible [--args <glob>]\npassport actions add --id <op_…> --environment <kind> --class <class>\npassport actions sync\nTells Passport what a project script does, so the guard checks it: its environment and action class. Your presets and exceptions still decide what runs; a project script never runs on its say-so alone. <script> is a file in the project, or make, npm, pnpm, or yarn with the target or script name. --args is a glob over its arguments (* is any). --id is the id a Session row shows under \"Tell Passport what this does\"; this computer resolves it, since the script's name never left it. sync proposes each entry of the project's .passport/actions.toml. You can say Production for a change, delete, or irreversible action; anything else waits for an admin in the app's Project scripts in Passport. Sends the script's path in the repository, the repository's fingerprint, name, and host, and a SHA-256 of what it runs, never its contents.\nJSON: {action} | {actions:[…]}",
148
148
  // copy-style-allow double-space: help columns line up
149
149
  sync: "passport sync [--remove]\nAdds what your Autopilot rules run without asking (reads, and changes inside the project: tests, builds, formatters, git add, git commit) to each agent's own allowlist, so those prompts stop even offline and in Codex. Claude Code: permissions.allow in ~/.claude/settings.json. Codex: ~/.codex/rules/passport.rules. Cursor CLI: permissions.allow in ~/.cursor/cli-config.json; Cursor: terminalAllowlist in ~/.cursor/permissions.json when you keep one there. Deletes, installs, and Production never sync. Your own entries are never changed. Runs again on its own when your rules change.\n --remove take Passport's entries out and stop syncing\nJSON: {action,agents:[{agent,name,path,added,removed,skipped?}]}",
150
150
  // copy-style-allow double-space: help columns line up
@@ -464,6 +464,7 @@ export function serializeCliPolicyV2(policy) {
464
464
  ...(autopilot.reportsSpeed ? { speed: true } : {}),
465
465
  ...(autopilot.reportsUsage ? { usage: true } : {}),
466
466
  ...(autopilot.reportsSteps ? { descriptions: true } : {}),
467
+ ...(autopilot.askLines ? { asks: true } : {}),
467
468
  ...(autopilot.repos ? { repos: autopilot.repos } : {}),
468
469
  ...(autopilot.project
469
470
  ? {
@@ -481,7 +482,8 @@ function keptReports(body) {
481
482
  return {
482
483
  ...(body.speed === true ? { reportsSpeed: true } : {}),
483
484
  ...(body.usage === true ? { reportsUsage: true } : {}),
484
- ...(body.descriptions === true ? { reportsSteps: true } : {})
485
+ ...(body.descriptions === true ? { reportsSteps: true } : {}),
486
+ ...(body.asks === true ? { askLines: true } : {})
485
487
  };
486
488
  }
487
489
  export function parseCliPolicyV2(value) {
@@ -22,7 +22,7 @@ import { bool, value } from "./cliArgs.js";
22
22
  import { api, json } from "./cliAutopilot.js";
23
23
  import { failure, timeoutMs } from "./cliSupport.js";
24
24
  import { termOf } from "./term.js";
25
- import { hashLink } from "./webLinks.js";
25
+ import { APPS_LINK, hashLink } from "./webLinks.js";
26
26
  import { count, ID, ledgerOf, list, mergeGroups, record, sessionOf, text, windowOf, workCountsOf, workGroupOf } from "./cliSessionsJson.js";
27
27
  import { renderLedger, renderSession, renderWork } from "./cliSessionsRender.js";
28
28
  import { projectOf, renderProject } from "./cliProjectSummary.js";
@@ -134,7 +134,7 @@ export async function sessions(args, runtime, deps = {}) {
134
134
  }
135
135
  if (views[0] === "production-changes") {
136
136
  const ledger = ledgerOf(await read(client, `/api/my/production-ledger${query(filters)}`, args, runtime, "This Passport server doesn't have the Production changes ledger yet."));
137
- const link = hashLink(client.origin, "#rules?section=environments");
137
+ const link = hashLink(client.origin, APPS_LINK);
138
138
  return { json: ledger, human: renderLedger(ledger, term, now, value(args, "since"), link) };
139
139
  }
140
140
  const view = views[0] === "all" ? "all" : views[0] === "running" ? "running" : "notable";
@@ -4,4 +4,4 @@
4
4
  * the version, then runs `npm run set-version -- <version>` in the plugin repo
5
5
  * and pushes (docs/RELEASING.md). `pluginPin.test.ts` fails when it drifts.
6
6
  */
7
- export declare const PLUGIN_PIN = "0.27.0";
7
+ export declare const PLUGIN_PIN = "0.29.0";
package/dist/pluginPin.js CHANGED
@@ -4,4 +4,4 @@
4
4
  * the version, then runs `npm run set-version -- <version>` in the plugin repo
5
5
  * and pushes (docs/RELEASING.md). `pluginPin.test.ts` fails when it drifts.
6
6
  */
7
- export const PLUGIN_PIN = "0.27.0";
7
+ export const PLUGIN_PIN = "0.29.0";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.27.0";
1
+ export declare const VERSION = "0.29.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Keep in lockstep with bridge/package.json.
2
- export const VERSION = "0.27.0";
2
+ export const VERSION = "0.29.0";
@@ -5,3 +5,6 @@ export declare function approvalLink(origin: string | undefined, approvalId: str
5
5
  /** A page the server named by its hash (`#apps/railway/access`), or null. */
6
6
  export declare function hashLink(origin: string | undefined, hash: unknown): string | null;
7
7
  export declare function ruleLink(origin: string | undefined, ruleId?: string): string | null;
8
+ /** Apps: each app's page holds its environments, keys, and project scripts
9
+ * (shared/appPageLinks.ts APPS_LINK; the CLI can't import shared/). */
10
+ export declare const APPS_LINK = "#apps";
package/dist/webLinks.js CHANGED
@@ -54,3 +54,6 @@ export function ruleLink(origin, ruleId) {
54
54
  return `${base}/#rules`;
55
55
  return usable(ruleId) ? `${base}/#rules?${new URLSearchParams({ rule: ruleId }).toString()}` : null;
56
56
  }
57
+ /** Apps: each app's page holds its environments, keys, and project scripts
58
+ * (shared/appPageLinks.ts APPS_LINK; the CLI can't import shared/). */
59
+ export const APPS_LINK = "#apps";
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "passport-bridge",
3
- "version": "0.27.0",
3
+ "version": "0.29.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "passport-bridge",
9
- "version": "0.27.0",
9
+ "version": "0.29.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "1.32.1"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passport-bridge",
3
- "version": "0.27.0",
3
+ "version": "0.29.0",
4
4
  "description": "Passport CLI for governed terminal and CI agents, plus the local stdio-to-cloud MCP bridge.",
5
5
  "license": "MIT",
6
6
  "repository": {