passport-bridge 0.16.10 → 0.16.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +16 -7
  2. package/dist/cli.js +6 -2
  3. package/dist/cliActions.js +20 -14
  4. package/dist/cliArgs.d.ts +3 -0
  5. package/dist/cliArgs.js +50 -6
  6. package/dist/cliAsk.d.ts +28 -0
  7. package/dist/cliAsk.js +49 -0
  8. package/dist/cliAutopilotPolicy.d.ts +15 -0
  9. package/dist/cliExec.d.ts +4 -0
  10. package/dist/cliExec.js +8 -1
  11. package/dist/cliGuardState.d.ts +20 -3
  12. package/dist/cliGuardState.js +24 -12
  13. package/dist/cliHook.js +4 -2
  14. package/dist/cliHookDecide.d.ts +16 -4
  15. package/dist/cliHookDecide.js +58 -14
  16. package/dist/cliHookDeliver.d.ts +17 -1
  17. package/dist/cliHookDeliver.js +70 -19
  18. package/dist/cliHookGuard.d.ts +9 -0
  19. package/dist/cliHookGuard.js +16 -2
  20. package/dist/cliHookInstall.d.ts +2 -0
  21. package/dist/cliHookInstall.js +2 -1
  22. package/dist/cliHookStatus.js +2 -4
  23. package/dist/cliKeys.d.ts +10 -3
  24. package/dist/cliKeys.js +60 -45
  25. package/dist/cliLogin.js +5 -2
  26. package/dist/cliMain.d.ts +7 -0
  27. package/dist/cliMain.js +502 -0
  28. package/dist/cliOutput.d.ts +3 -0
  29. package/dist/cliOutput.js +115 -8
  30. package/dist/cliPolicyV2.js +53 -2
  31. package/dist/cliSuggest.d.ts +19 -0
  32. package/dist/cliSuggest.js +57 -0
  33. package/dist/cliUndo.js +3 -8
  34. package/dist/compileCache.d.ts +8 -0
  35. package/dist/compileCache.js +60 -0
  36. package/dist/execNoKey.d.ts +9 -0
  37. package/dist/execNoKey.js +25 -0
  38. package/dist/hookMain.js +7 -11
  39. package/dist/hookOutbox.d.ts +15 -2
  40. package/dist/hookOutbox.js +143 -3
  41. package/dist/initKeysStep.d.ts +1 -1
  42. package/dist/initKeysStep.js +8 -7
  43. package/dist/initOutro.js +2 -1
  44. package/dist/initUi.d.ts +7 -2
  45. package/dist/initUi.js +22 -9
  46. package/dist/passport.d.ts +1 -7
  47. package/dist/passport.js +15 -499
  48. package/dist/pluginPin.d.ts +1 -1
  49. package/dist/pluginPin.js +1 -1
  50. package/dist/version.d.ts +1 -1
  51. package/dist/version.js +1 -1
  52. package/dist/webLinks.d.ts +2 -0
  53. package/dist/webLinks.js +7 -0
  54. package/npm-shrinkwrap.json +2 -2
  55. package/package.json +1 -1
@@ -18,8 +18,8 @@
18
18
  import { needsSecondPerson } from "./cliAutopilotPolicy.js";
19
19
  import { readBoundedJson } from "./boundedResponse.js";
20
20
  import { isEnvKind } from "./cliHookEnvironment.js";
21
- import { OFFLINE_NOTE, guardOutput, waitingMessage } from "./cliHookGuard.js";
22
- import { DEFAULT_OFFLINE, OFFLINE_CACHE_MAX_MS, offlineDecision } from "./cliGuardState.js";
21
+ import { askMessage, guardOutput, waitingMessage } from "./cliHookGuard.js";
22
+ import { OFFLINE_CACHE_MAX_MS, OFFLINE_DEFAULT, OFFLINE_NOTES, offlineDecision } from "./cliGuardState.js";
23
23
  import { redactCommand } from "./cliHookRedact.js";
24
24
  export const CLI_DECIDE_PATH = "/api/my/cli/decide";
25
25
  const MAX_RESPONSE_BYTES = 16 * 1024;
@@ -124,14 +124,33 @@ export async function decideOnServer(api, request, signal) {
124
124
  export function codexAskBlocked(report) {
125
125
  return report?.runtime === "codex" && report.decision === "ask" ? { ...report, decision: "deny" } : report;
126
126
  }
127
+ /**
128
+ * Whether an Ask came from something the person can't change on their own: a
129
+ * team floor (or the approver rule), a team or workspace rule, an approved
130
+ * exception, or a built-in rule such as sudo. Only the person's own preset or
131
+ * own rule may be loosened by their offline Run.
132
+ */
133
+ function requiredCause(cause, policy) {
134
+ if (!cause)
135
+ return true;
136
+ if (cause.kind === "preset")
137
+ return false;
138
+ if (cause.kind !== "rule")
139
+ return true;
140
+ const rule = policy?.version === 2 ? policy.autopilot.rules.find((entry) => entry.id === cause.id) : undefined;
141
+ return !(rule?.scope === "me" && !rule.exception);
142
+ }
127
143
  /**
128
144
  * When Passport can't be reached (Batch A): the person's setting for the
129
145
  * action's environment, from a policy synced in the last 7 days, else the
130
- * built-in defaults (Production asks, the rest run). Someone else's approval
131
- * is never possible offline, Run never covers an irreversible action, and
132
- * Codex can't ask, so Ask is a block there.
146
+ * built-in default (Ask everywhere). It only ever sees a local Ask that needed
147
+ * Passport; anything else stands as decided. Someone else's approval is never
148
+ * possible offline; Run never covers an irreversible action or anything the
149
+ * team requires; and an Ask nobody can answer (unattended, or Codex) blocks.
133
150
  */
134
- export function offlineVerdict(decision, policy, client, secondPerson, now) {
151
+ export function offlineVerdict(decision, policy, context, now) {
152
+ if (decision.verdict !== "ask")
153
+ return { verdict: decision.verdict, note: "decided" };
135
154
  const fresh = policy?.version === 2 && now - policy.fetchedAt <= OFFLINE_CACHE_MAX_MS ? policy : null;
136
155
  // An action Passport couldn't place counts as Production.
137
156
  const row = decision.environment === undefined
@@ -139,14 +158,38 @@ export function offlineVerdict(decision, policy, client, secondPerson, now) {
139
158
  : isEnvKind(decision.environment)
140
159
  ? decision.environment
141
160
  : "other";
142
- const setting = fresh?.autopilot.offline?.[row] ?? DEFAULT_OFFLINE[row];
143
- const verdict = offlineDecision({
161
+ const setting = fresh?.autopilot.offline?.[row] ?? OFFLINE_DEFAULT;
162
+ // Every command in the line that asked counts, not just the one named.
163
+ const asks = (decision.decided ?? []).filter((entry) => entry.decision === "ask");
164
+ const required = requiredCause(decision.cause, policy) || asks.some((entry) => requiredCause(entry.cause, policy));
165
+ const irreversible = decision.actionClass === "irreversible" || asks.some((entry) => entry.actionClass === "irreversible");
166
+ const { decision: verdict, note } = offlineDecision({
144
167
  setting,
145
- ...(decision.actionClass ? { actionClass: decision.actionClass } : {}),
146
- client,
147
- secondPerson
168
+ ...(irreversible
169
+ ? { actionClass: "irreversible" }
170
+ : decision.actionClass
171
+ ? { actionClass: decision.actionClass }
172
+ : {}),
173
+ client: context.client,
174
+ secondPerson: context.secondPerson,
175
+ attended: context.attended,
176
+ required
148
177
  });
149
- return verdict === "block" ? "deny" : verdict;
178
+ return { verdict: verdict === "block" ? "deny" : verdict, note };
179
+ }
180
+ /** What the agent reads when this computer decided offline. */
181
+ function offlineOutput(client, decision, offline) {
182
+ const note = OFFLINE_NOTES[offline.note];
183
+ // An explicit Run says it ran because of the setting, not the rule that asked.
184
+ if (offline.verdict === "allow") {
185
+ const cause = { kind: "default", label: note.replace(/\.$/, "") };
186
+ return guardOutput(client, { ...decision, verdict: "allow", cause });
187
+ }
188
+ if (offline.verdict !== "deny")
189
+ return guardOutput(client, { ...decision, verdict: offline.verdict }, { note });
190
+ // An Ask that became a block: say what it was, and why it's blocked now.
191
+ const asked = askMessage(decision).replace(/ Approve to run it\.$/, "");
192
+ return guardOutput(client, { ...decision, verdict: "deny" }, { waiting: `${asked} ${note}` });
150
193
  }
151
194
  /** Turn the server's answer into what the agent reads. */
152
195
  function serverOutput(client, decision, server) {
@@ -205,11 +248,12 @@ export async function planGuard(decision, policy, context) {
205
248
  : null;
206
249
  if (!server) {
207
250
  // Passport didn't answer in time: the environment's offline setting decides.
208
- const offline = offlineVerdict(decision, policy, context.client, secondPerson, context.now());
251
+ const offline = offlineVerdict(decision, policy, { client: context.client, secondPerson, attended: context.mode === "attended" }, context.now());
209
252
  return {
210
- output: guardOutput(context.client, { ...decision, verdict: offline }, { note: OFFLINE_NOTE }),
253
+ output: offlineOutput(context.client, decision, offline),
211
254
  server: null,
212
255
  offline: true,
256
+ verdict: offline.verdict,
213
257
  ...(api ? { api } : {})
214
258
  };
215
259
  }
@@ -133,8 +133,24 @@ export declare function profileAuth(args: ParsedArgs, env: Env): string | null;
133
133
  * couple of seconds. The hook itself never waits for it.
134
134
  */
135
135
  export declare function startFlushIfDue(profile: string, args: ParsedArgs, runtimeName: string, now: number): Promise<void>;
136
+ /** A detached flush is gone this long after its process started, whatever it
137
+ * is waiting on: the budget, then a second to write what it has. */
138
+ export declare const FLUSH_DEADLINE_MS: number;
139
+ /**
140
+ * Arm the hard deadline of a detached flush and return the exit it ends with.
141
+ * The abort budget is cooperative: it stops what listens to it, but a socket,
142
+ * a pool, or a slow start can keep a process alive past it, and an agent
143
+ * running hundreds of commands would then pile up flushes. So the process
144
+ * exits once its work is done, and in any case at the deadline (counted from
145
+ * process start, so a slow start counts too). Every file it writes is written
146
+ * synchronously and atomically, so exiting between two steps loses at most
147
+ * reports that would have been dropped anyway. The timer is deliberately not
148
+ * unref'd: it is the one thing guaranteed to end the process.
149
+ */
150
+ export declare function flushDeadline(release: () => void, exit?: (code: number) => void, startedMsAgo?: number): () => void;
136
151
  /** `passport hook flush`: what the hooks queued, sent within the budget by a
137
- * process nobody waits for. */
152
+ * process nobody waits for. Only one runs at a time per profile, and a
153
+ * detached one always exits by FLUSH_DEADLINE_MS. */
138
154
  export declare function runFlush(args: ParsedArgs, runtime: Runtime, deps: HookDependencies): Promise<void>;
139
155
  /** Leftover budget: Activity reports, a batch of answered counts and speed
140
156
  * numbers, and, at most hourly, a rules refresh (which keeps synced
@@ -4,6 +4,7 @@
4
4
  * `passport hook flush` (or a test's in-process run) waits on any of it; the
5
5
  * hooks themselves queue and return (`hookOutbox.ts`).
6
6
  */
7
+ import module from "node:module";
7
8
  import { value } from "./cliArgs.js";
8
9
  import { hasExpired, takeExpired } from "./cliHookPending.js";
9
10
  import { claimStaleRefresh, readCliPolicy, staleRefreshDue } from "./cliPolicy.js";
@@ -146,8 +147,43 @@ export async function startFlushIfDue(profile, args, runtimeName, now) {
146
147
  const named = value(args, "profile");
147
148
  outbox.startFlush(["--client", runtimeName, ...(named ? ["--profile", named] : [])]);
148
149
  }
150
+ /** A detached flush is gone this long after its process started, whatever it
151
+ * is waiting on: the budget, then a second to write what it has. */
152
+ export const FLUSH_DEADLINE_MS = HOOK_BUDGET_MS + 1_000;
153
+ /**
154
+ * Arm the hard deadline of a detached flush and return the exit it ends with.
155
+ * The abort budget is cooperative: it stops what listens to it, but a socket,
156
+ * a pool, or a slow start can keep a process alive past it, and an agent
157
+ * running hundreds of commands would then pile up flushes. So the process
158
+ * exits once its work is done, and in any case at the deadline (counted from
159
+ * process start, so a slow start counts too). Every file it writes is written
160
+ * synchronously and atomically, so exiting between two steps loses at most
161
+ * reports that would have been dropped anyway. The timer is deliberately not
162
+ * unref'd: it is the one thing guaranteed to end the process.
163
+ */
164
+ export function flushDeadline(release, exit = (code) => process.exit(code), startedMsAgo = performance.now()) {
165
+ let done = false;
166
+ const stop = () => {
167
+ if (done)
168
+ return;
169
+ done = true;
170
+ clearTimeout(timer);
171
+ release();
172
+ try {
173
+ // Written before exiting, not left to a teardown that may not finish.
174
+ module.flushCompileCache?.();
175
+ }
176
+ catch {
177
+ /* The next run compiles again. */
178
+ }
179
+ exit(0);
180
+ };
181
+ const timer = setTimeout(stop, Math.max(0, FLUSH_DEADLINE_MS - startedMsAgo));
182
+ return stop;
183
+ }
149
184
  /** `passport hook flush`: what the hooks queued, sent within the budget by a
150
- * process nobody waits for. */
185
+ * process nobody waits for. Only one runs at a time per profile, and a
186
+ * detached one always exits by FLUSH_DEADLINE_MS. */
151
187
  export async function runFlush(args, runtime, deps) {
152
188
  if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
153
189
  return;
@@ -156,24 +192,39 @@ export async function runFlush(args, runtime, deps) {
156
192
  if (!profile || auth !== profile)
157
193
  return;
158
194
  const clock = deps.now ?? Date.now;
159
- const policy = readCliPolicy(profile);
160
- const fast = await import("./hookFastPath.js");
161
- fast.drainFastPathSpool(profile, clock());
162
- const { takeQueued } = await import("./hookOutbox.js");
163
- const queued = takeQueued(profile, clock());
164
- const named = value(args, "client")?.trim().toLowerCase();
165
- const runtimeName = HOOK_RUNTIMES.includes(named ?? "") ? named : "other";
166
- await leftovers(queued, {
167
- profile,
168
- policy,
169
- local: policy?.version === 2 && policy.autopilot.localCommands === true,
170
- runtimeName,
171
- budget: budgetSignal(runtime),
172
- runtime,
173
- args,
174
- deps
175
- });
176
- fast.refreshFastPath(profile, readCliPolicy(profile), byDefault, clock());
195
+ const outbox = await import("./hookOutbox.js");
196
+ // Another flush is sending: it takes whatever is queued, so this one stops here.
197
+ const release = outbox.takeFlushLock(profile);
198
+ if (!release)
199
+ return;
200
+ // Started by `startFlush` (not a test's in-process run): ends at the deadline.
201
+ const stop = !deps.send && !deps.fetch ? flushDeadline(release) : null;
202
+ try {
203
+ const policy = readCliPolicy(profile);
204
+ const fast = await import("./hookFastPath.js");
205
+ fast.drainFastPathSpool(profile, clock());
206
+ const queued = outbox.takeQueued(profile, clock());
207
+ const named = value(args, "client")?.trim().toLowerCase();
208
+ const runtimeName = HOOK_RUNTIMES.includes(named ?? "") ? named : "other";
209
+ await leftovers(queued, {
210
+ profile,
211
+ policy,
212
+ local: policy?.version === 2 && policy.autopilot.localCommands === true,
213
+ runtimeName,
214
+ budget: budgetSignal(runtime),
215
+ runtime,
216
+ args,
217
+ deps
218
+ });
219
+ fast.refreshFastPath(profile, readCliPolicy(profile), byDefault, clock());
220
+ }
221
+ finally {
222
+ // Done: nothing it started (an aborted socket, a keep-alive pool) keeps it alive.
223
+ if (stop)
224
+ stop();
225
+ else
226
+ release();
227
+ }
177
228
  }
178
229
  /** Post the answered counts and speed numbers as one report. A server that
179
230
  * doesn't know `speed` (400) still gets the counts; its speed batch is
@@ -35,6 +35,13 @@ export type DecidedFinding = {
35
35
  target?: EnvTarget;
36
36
  /** What the server is told about that, when it reads placements. */
37
37
  placement?: Record<string, string>;
38
+ /** Blocked by the person's pass for the app this CLI acts on: what they read. */
39
+ access?: AppAccessBlock;
40
+ };
41
+ /** "You don't have access to Railway in Passport. Ask an admin." and the app's Access link. */
42
+ export type AppAccessBlock = {
43
+ message: string;
44
+ link?: string;
38
45
  };
39
46
  export type GuardDecision = {
40
47
  verdict: GuardVerdict;
@@ -55,6 +62,8 @@ export type GuardDecision = {
55
62
  deciding?: CliFinding;
56
63
  /** v2: where the deciding vendor command lands, and how Passport knows. */
57
64
  target?: EnvTarget;
65
+ /** The deciding command is blocked by the person's app access. */
66
+ access?: AppAccessBlock;
58
67
  };
59
68
  /** This machine, for reading folder links. Absent: flags and defaults only. */
60
69
  export type GuardMachine = {
@@ -231,17 +231,27 @@ export function decideFinding(finding, policy, machine) {
231
231
  : target;
232
232
  const verb = finding.verbKey ?? finding.verb;
233
233
  const actionClass = classOf(policy, finding, verb, hint.kind);
234
- const { decision, cause } = decideAction(policy.autopilot, {
234
+ const ruled = decideAction(policy.autopilot, {
235
235
  vendor: finding.vendor,
236
236
  verb,
237
237
  actionClass,
238
238
  environment: hint.kind
239
239
  });
240
+ // The person's pass for the app this CLI acts on comes first: No access
241
+ // blocks every command, Read-only runs only reads (the same as exec).
242
+ const pass = Object.hasOwn(policy.autopilot.appAccess ?? {}, finding.vendor)
243
+ ? policy.autopilot.appAccess[finding.vendor]
244
+ : undefined;
245
+ const limited = pass && (pass.pass === "none" || (pass.pass === "readonly" && actionClass !== "read"));
246
+ const { decision, cause } = limited
247
+ ? { decision: "block", cause: { kind: "block", label: pass.cause } }
248
+ : ruled;
240
249
  const reported = finding.pushEnvironment ?? reportedEnvironment(hint);
241
250
  return {
242
251
  finding,
243
252
  decision,
244
253
  cause,
254
+ ...(limited ? { access: { message: pass.message, ...(pass.link ? { link: pass.link } : {}) } } : {}),
245
255
  environment: hint.kind,
246
256
  environmentSource: hint.source,
247
257
  ...(reported ? { reported } : {}),
@@ -308,7 +318,8 @@ function decideV2(command, findings, policy, complete, machine) {
308
318
  actionClass: strictest.actionClass,
309
319
  decided,
310
320
  ...(strictest.finding.local || strictest.finding.pushEnvironment ? { deciding: strictest.finding } : {}),
311
- ...(strictest.target ? { target: strictest.target } : {})
321
+ ...(strictest.target ? { target: strictest.target } : {}),
322
+ ...(strictest.access ? { access: strictest.access } : {})
312
323
  };
313
324
  }
314
325
  /** The strictest verdict across every command in the line wins. */
@@ -394,6 +405,9 @@ export function askMessage(decision) {
394
405
  : `Passport: your Autopilot rules ask before ${decision.label}. Run it only if you meant to.`;
395
406
  }
396
407
  export function denyMessage(decision, owner) {
408
+ // The app's access, in the words exec uses, with where an admin changes it.
409
+ if (decision.access)
410
+ return decision.access.link ? `${decision.access.message} ${decision.access.link}` : decision.access.message;
397
411
  if (decision.cause) {
398
412
  const mine = decision.cause.label.startsWith("Your rule");
399
413
  const next = mine
@@ -51,6 +51,8 @@ export declare function registeredEntries(client: HookClient, env: Env): {
51
51
  guard: string | null;
52
52
  };
53
53
  export declare function displayPath(path: string): string;
54
+ /** What the guard does in Codex, in plain words (status, install, init). */
55
+ export declare const CODEX_BLOCK_ONLY = "Codex can't show Passport's questions, so Passport blocks a command your rules ask about and tells you how to approve it.";
54
56
  export type Change = {
55
57
  action: "add" | "update" | "remove";
56
58
  event: string;
@@ -324,7 +324,8 @@ export function displayPath(path) {
324
324
  const RECORDS_LINE = "It records the vendor, a coarse verb, and a risk class. Never the command line, its output, or your folder path.";
325
325
  const LIMITS_LINE = "It can't see inside scripts, aliases, or make targets.";
326
326
  const CODEX_TRUST_LINE = "Next: Open Codex → /hooks and trust Passport's hooks.";
327
- const CODEX_BLOCK_ONLY = "Codex can't ask from a hook, so commands set to ask are blocked and the approval comes to you.";
327
+ /** What the guard does in Codex, in plain words (status, install, init). */
328
+ export const CODEX_BLOCK_ONLY = "Codex can't show Passport's questions, so Passport blocks a command your rules ask about and tells you how to approve it.";
328
329
  function planLines(changes) {
329
330
  const width = Math.max(...changes.map((change) => change.event.length));
330
331
  return changes.map((change) => ` ${change.action.padEnd(6)} ${change.event.padEnd(width)} ${change.command}`);
@@ -6,7 +6,7 @@
6
6
  import { bool, value } from "./cliArgs.js";
7
7
  import { guardClientReports } from "./cliGuardHealth.js";
8
8
  import { GUARD_CLIENT_LABEL, GUARD_STATE_LABEL, fixLine, guardStateFix, localGuardState } from "./cliGuardState.js";
9
- import { HOOK_CLIENTS, agentHookStatus, displayPath } from "./cliHookInstall.js";
9
+ import { CODEX_BLOCK_ONLY, HOOK_CLIENTS, agentHookStatus, displayPath } from "./cliHookInstall.js";
10
10
  import { readCliPolicy } from "./cliPolicy.js";
11
11
  import { readCreds } from "./credentials.js";
12
12
  import { failure, selectStoredProfile } from "./cliSupport.js";
@@ -101,9 +101,7 @@ export async function hookStatus(args, runtime) {
101
101
  ].join(" ")),
102
102
  "",
103
103
  policy.line,
104
- ...(codexGuarded
105
- ? ["Codex can't ask from a hook, so commands set to ask are blocked and the approval comes to you."]
106
- : []),
104
+ ...(codexGuarded ? [CODEX_BLOCK_ONLY] : []),
107
105
  ...(disabled ? ["PASSPORT_HOOK_DISABLED=1 is set, so hooks do nothing in this shell."] : []),
108
106
  ...guardFixLines(guards)
109
107
  ];
package/dist/cliKeys.d.ts CHANGED
@@ -13,10 +13,15 @@ export type MoveIo = {
13
13
  confirm: (question: string) => Promise<boolean>;
14
14
  /**
15
15
  * Asks whether to replace a different key Passport already holds with this
16
- * computer's. Only when a person is there to answer: without it (--yes, no
17
- * terminal) Passport's key and this computer's sign-in both stay.
16
+ * computer's: a severe question, so the person types `name` (the CLI, like
17
+ * `railway`). Only when a person is at a terminal to answer: without it
18
+ * (--yes, no terminal) Passport's key and this computer's sign-in both
19
+ * stay. There is deliberately no flag for it: an agent's script must never
20
+ * swap a key Passport holds.
18
21
  */
19
- replace?: (question: string) => Promise<boolean>;
22
+ replace?: (question: string, name: string) => Promise<boolean>;
23
+ /** Only this CLI's key (`passport keys move railway`). */
24
+ only?: ExecVendor;
20
25
  /**
21
26
  * In a repository that deploys Passport with the Railway CLI: asks whether
22
27
  * to keep the Railway key here (`[Y/n]`, yes keeps it). Without it (--yes,
@@ -65,6 +70,8 @@ export declare function scanCounts(scan: ScanResult): {
65
70
  remaining: Record<string, number>;
66
71
  envFiles: string[];
67
72
  };
73
+ /** Without a person at a terminal, a key Passport holds is never replaced. */
74
+ export declare function replaceNeedsTerminal(vendor: ExecVendor): string;
68
75
  export declare function moveKeys(io: MoveIo): Promise<MoveSummary>;
69
76
  /** The lines after a move: what moved, what's left, where to rotate. */
70
77
  export declare function summaryLines(summary: MoveSummary): string[];
package/dist/cliKeys.js CHANGED
@@ -13,6 +13,7 @@
13
13
  import { execFileSync } from "node:child_process";
14
14
  import { hostname } from "node:os";
15
15
  import { bool } from "./cliArgs.js";
16
+ import { askYesNo, nameConfirmed, typeNamePrompt } from "./cliAsk.js";
16
17
  import { memberApi } from "./cliClient.js";
17
18
  import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, timeoutMs } from "./cliSupport.js";
18
19
  import { EXEC_TOKEN_PAGES, EXEC_VENDOR_NAMES, execVendorOf } from "./execVendors.js";
@@ -23,7 +24,10 @@ import { findLocalKeys, removeLocalCopy } from "./keysLocal.js";
23
24
  import { runScan } from "./scan.js";
24
25
  import { RELEASE_KEY_QUESTION, deploysPassportWithRailway } from "./releaseTooling.js";
25
26
  import { discardTypeAhead, listOf, processTerminal } from "./initUi.js";
27
+ import { unknownSubcommand } from "./cliSuggest.js";
28
+ import { table, termOf } from "./term.js";
26
29
  export const KEYS_PATH = "/api/my/keys";
30
+ const KEY_CLIS = "railway|gh|vercel|wrangler|supabase|stripe|aws|neonctl|flyctl";
27
31
  const MOVABLE_PROVIDERS = new Set(["Railway", "GitHub", "Vercel", "Cloudflare", "Supabase", "Stripe", "AWS"]);
28
32
  const ENV_FILE_LOCATION = /(?:^|\/)\.env[^/ ]*(?: \(|$)/;
29
33
  /** The computer's name people recognize: "Ramish's MacBook Pro", else its host. */
@@ -113,6 +117,18 @@ function oneEach(keys) {
113
117
  return true;
114
118
  });
115
119
  }
120
+ /** Replacing a key every agent uses is severe: only a person at a terminal,
121
+ * typing the CLI's name, says yes. No flag answers it. */
122
+ async function mayReplace(io, vendor) {
123
+ if (!io.replace)
124
+ return false;
125
+ const name = EXEC_VENDOR_NAMES[vendor];
126
+ return io.replace(`Passport already holds a different ${name} key. Replace it with this computer's? Every agent that uses it switches to this one.`, vendor);
127
+ }
128
+ /** Without a person at a terminal, a key Passport holds is never replaced. */
129
+ export function replaceNeedsTerminal(vendor) {
130
+ return `Replacing a key in Passport needs you at a terminal. Run passport keys move ${vendor} yourself.`;
131
+ }
116
132
  export async function moveKeys(io) {
117
133
  const summary = {
118
134
  moved: [],
@@ -128,7 +144,7 @@ export async function moveKeys(io) {
128
144
  ...(io.home ? { home: io.home } : {}),
129
145
  ...(io.platform ? { platform: io.platform } : {})
130
146
  };
131
- for (const key of oneEach(findLocalKeys(context))) {
147
+ for (const key of oneEach(findLocalKeys(context)).filter((found) => !io.only || found.vendor === io.only)) {
132
148
  const name = EXEC_VENDOR_NAMES[key.vendor];
133
149
  if (key.unholdable || !key.secret) {
134
150
  summary.unholdable.push(key.unholdable ?? `${key.label} can't move.`);
@@ -157,15 +173,12 @@ export async function moveKeys(io) {
157
173
  let replaced = false;
158
174
  if ("different" in stored) {
159
175
  // A different key is already in Passport. Replacing it changes what every
160
- // agent uses, so only a person answering here may say yes.
161
- const replace = io.replace
162
- ? await io.replace(`Replace the ${name} key in Passport with the one on this computer?`)
163
- : false;
164
- if (!replace) {
176
+ // agent uses: only a person at a terminal, typing the CLI's name.
177
+ if (!(await mayReplace(io, key.vendor))) {
165
178
  summary.kept.push({ vendor: key.vendor, label: key.label });
166
179
  io.result("skip", io.replace
167
180
  ? `${name}: Kept the key in Passport. This computer's ${name} CLI stays signed in.`
168
- : `${name}: A different key is already in Passport, so it stays, and this computer's ${name} CLI stays signed in. Run passport keys move to replace it.`);
181
+ : `${name}: ${replaceNeedsTerminal(key.vendor)}`);
169
182
  continue;
170
183
  }
171
184
  stored = await store(io, key, stored.different);
@@ -334,17 +347,26 @@ async function list(args, runtime, deps) {
334
347
  const keys = Array.isArray(view.keys) ? view.keys : [];
335
348
  const pruned = applyKeyList(profileOf(args, runtime), keys);
336
349
  const local = findLocalKeys({ env: runtime.env, ...(deps.home ? { home: deps.home } : {}) }).filter((key) => key.secret);
350
+ // One aligned row per key: what it is, how much agents used it, and how
351
+ // Passport hands it out when that isn't the stored key itself.
352
+ const rows = keys.map((key) => {
353
+ const label = ` ${String(key.label ?? "Key")}`;
354
+ if (key.status === "broken")
355
+ return [label, "! Not working", key.statusMessage ?? "Update it in Apps."];
356
+ const uses = Number(key.usesThisWeek ?? 0);
357
+ return [
358
+ label,
359
+ uses ? `Used ${uses} ${uses === 1 ? "time" : "times"} this week` : "Not used this week",
360
+ key.issuance && key.issuance !== "stored" ? (key.issuanceLabel ?? "") : ""
361
+ ];
362
+ });
363
+ const width = termOf((runtime.stdout ?? {}), runtime.env).width;
337
364
  const lines = keys.length
338
- ? keys.map((key) => {
339
- const label = String(key.label ?? "Key").padEnd(26);
340
- if (key.status === "broken")
341
- return `${label} ${key.statusMessage ?? "Stopped working. Update it in Apps."}`;
342
- const uses = Number(key.usesThisWeek ?? 0);
343
- return `${label} Stored in Passport · used ${uses} ${uses === 1 ? "time" : "times"} this week · ${key.issuanceLabel ?? ""}`;
344
- })
365
+ ? ["In Passport:", ...table(rows, width, { indent: " " })]
345
366
  : ["No keys in Passport yet."];
346
367
  if (local.length) {
347
- lines.push(`${local.length} ${local.length === 1 ? "key is" : "keys are"} still on this computer (${listOf([...new Set(local.map((key) => EXEC_VENDOR_NAMES[key.vendor]))])}). Run passport keys move.`);
368
+ const names = listOf([...new Set(local.map((key) => EXEC_VENDOR_NAMES[key.vendor]))]);
369
+ lines.push(`Still on this computer: ${names}. Run passport keys move to move ${local.length === 1 ? "it" : "them"}.`);
348
370
  }
349
371
  const shims = listShims(runtime.env);
350
372
  if (shims.length) {
@@ -366,6 +388,10 @@ async function list(args, runtime, deps) {
366
388
  async function move(args, runtime, deps) {
367
389
  const yes = bool(args, "yes");
368
390
  const json = bool(args, "json");
391
+ const named = args.positionals[1];
392
+ const only = named === undefined ? undefined : execVendorOf(named);
393
+ if (named !== undefined && !only)
394
+ return failure(`Use: passport keys move [${KEY_CLIS}]`, 6, "usage");
369
395
  const terminal = deps.terminal ?? processTerminal(runtime, process.platform, json);
370
396
  if (!yes && !terminal.interactive) {
371
397
  return failure("passport keys move asks before each key. Run it in a terminal, or add --yes to move them all.", 6, "usage");
@@ -377,42 +403,30 @@ async function move(args, runtime, deps) {
377
403
  if (!json)
378
404
  terminal.write(`${text}\n`);
379
405
  };
380
- const local = findLocalKeys({ env: runtime.env, ...(deps.home ? { home: deps.home } : {}) });
406
+ const local = findLocalKeys({ env: runtime.env, ...(deps.home ? { home: deps.home } : {}) }).filter((key) => !only || key.vendor === only);
381
407
  if (local.length) {
382
408
  write("Keys on this computer that Passport can hold:");
383
409
  for (const key of local)
384
410
  write(` ${key.label.padEnd(26)} ${key.location}`);
385
411
  write("");
386
412
  }
387
- // Signing a CLI out can't be taken back from here: no default, so a
388
- // stray Enter asks again instead of moving the key.
389
- const ask = async (question) => {
390
- for (;;) {
391
- const answer = (await terminal.question(`${question} [y/n] `, runtime.signal)).trim().toLowerCase();
392
- if (answer === "y" || answer === "yes")
393
- return true;
394
- if (answer === "n" || answer === "no")
395
- return false;
396
- write("Type y or n.");
397
- }
398
- };
413
+ const prompt = (text) => terminal.question(text, runtime.signal);
414
+ // Signing a CLI out can't be taken back from here: [y/N], Enter keeps it.
415
+ const ask = (question) => askYesNo(prompt, write, question, "destructive");
399
416
  // The safe answer is the default: Enter keeps things working.
400
- const askYes = async (question) => {
401
- for (;;) {
402
- const answer = (await terminal.question(`${question} [Y/n] `, runtime.signal)).trim().toLowerCase();
403
- if (answer === "" || answer === "y" || answer === "yes")
404
- return true;
405
- if (answer === "n" || answer === "no")
406
- return false;
407
- write("Type y or n.");
408
- }
417
+ const askYes = (question) => askYesNo(prompt, write, question, "safe");
418
+ // Replacing a key every agent uses: type the CLI's name.
419
+ const askName = async (question, name) => {
420
+ write(question);
421
+ return nameConfirmed(await prompt(`${typeNamePrompt(name)} `), name);
409
422
  };
410
423
  const summary = await moveKeys({
411
424
  api,
412
425
  confirm: ask,
413
- // Replacing a key Passport already holds is only ever a person's answer:
414
- // with --yes, both keys stay where they are.
415
- ...(terminal.interactive && !yes ? { replace: ask, keepHere: askYes } : {}),
426
+ // Replacing a key Passport already holds is only ever a person's answer
427
+ // at a terminal: with --yes, or without a terminal, both keys stay.
428
+ ...(terminal.interactive && !yes ? { replace: askName, keepHere: askYes } : {}),
429
+ ...(only ? { only } : {}),
416
430
  result: (kind, text) => write(` ${mark[kind]} ${text}`),
417
431
  line: write,
418
432
  env: runtime.env,
@@ -487,12 +501,12 @@ async function readSecret(runtime, prompt) {
487
501
  async function add(args, runtime, deps) {
488
502
  const vendor = execVendorOf(args.positionals[1] ?? "");
489
503
  if (!vendor)
490
- return failure("Use: passport keys add <railway|gh|vercel|wrangler|supabase|stripe|aws|neonctl|flyctl>", 6, "usage");
504
+ return failure(`Use: passport keys add <${KEY_CLIS}>`, 6, "usage");
491
505
  const api = apiFor(args, runtime, deps);
492
506
  const name = EXEC_VENDOR_NAMES[vendor];
493
507
  const prompt = vendor === "aws"
494
- ? "Paste the AWS access key id and secret, separated by a space: "
495
- : `Paste your ${name} token (it won't be shown): `;
508
+ ? "Paste the AWS access key id and secret, separated by a space (it won't be shown): "
509
+ : `Paste your ${name} key (it won't be shown): `;
496
510
  const raw = await (deps.readSecret ?? ((text) => readSecret(runtime, text)))(prompt);
497
511
  let secret;
498
512
  if (vendor === "aws") {
@@ -503,7 +517,7 @@ async function add(args, runtime, deps) {
503
517
  }
504
518
  else {
505
519
  if (!raw)
506
- return failure(`No ${name} token was given.`, 6, "usage");
520
+ return failure(`No ${name} key was given.`, 6, "usage");
507
521
  secret = { token: raw };
508
522
  }
509
523
  let response;
@@ -539,5 +553,6 @@ export async function keys(args, runtime, deps = {}) {
539
553
  return add(args, runtime, deps);
540
554
  if (action === "shim")
541
555
  return shim(args, runtime, deps, profileOf(args, runtime));
542
- return failure("Use passport keys, keys move, keys add <cli>, or keys shim [<cli>].", 6, "usage");
556
+ const unknown = unknownSubcommand("keys", action, ["list", "move", "add", "shim"]);
557
+ return failure(unknown.message, 6, "usage", unknown.next ? { next: unknown.next } : {});
543
558
  }
package/dist/cliLogin.js CHANGED
@@ -2,6 +2,7 @@ import { recordedEnrollment } from "./enrollment.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { workspaceOfToken } from "./tokenWorkspace.js";
4
4
  import { bool, value } from "./cliArgs.js";
5
+ import { answerOf, choices } from "./cliAsk.js";
5
6
  import { assertCredentialStoreMutationReady, credsPath, getProfile, getProfileStrict, readCreds, setActiveProfile, withProfileLock, writeProfile } from "./credentials.js";
6
7
  import { CliFailure, cloudOrigin, endpoint, failure, profileName, readBoundedJson, safeApiError, sameOriginWebUrl, selectStoredProfile, selfCommand, timedFetch, timeoutMs } from "./cliSupport.js";
7
8
  import { fetchLoginIdentity, identityPhrase, rememberLoginIdentity } from "./loginIdentity.js";
@@ -375,8 +376,10 @@ export async function login(args, runtime, hooks = {}) {
375
376
  const current = await currentSignIn(options.requestedProfile, args, runtime);
376
377
  if (current) {
377
378
  const who = identityPhrase(current);
378
- const answer = (await (hooks.ask ?? ((question) => askOnTerminal(runtime, question)))(`Already signed in as ${who}. Switch? [y/N] `)).toLowerCase();
379
- if (answer !== "y" && answer !== "yes") {
379
+ // Switching replaces the sign-in this computer uses: [y/N], and any
380
+ // answer but yes keeps it (cliAsk.ts).
381
+ const answer = await (hooks.ask ?? ((question) => askOnTerminal(runtime, question)))(`Already signed in as ${who}. Switch? ${choices("destructive")} `);
382
+ if (answerOf(answer, "destructive") !== true) {
380
383
  return {
381
384
  json: {
382
385
  profile: options.requestedProfile,
@@ -0,0 +1,7 @@
1
+ import { type Env, type Runtime } from "./cliSupport.js";
2
+ export { refusalOf } from "./cliResult.js";
3
+ export { callerFrom, sanitize } from "./cliSupport.js";
4
+ export declare function main(argv?: string[], env?: Env, io?: Pick<Runtime, "stdout" | "stderr"> & {
5
+ stdin?: Runtime["stdin"];
6
+ invokedAs?: Runtime["invokedAs"];
7
+ }): Promise<number>;