passport-bridge 0.16.0 → 0.16.2

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.
@@ -2,6 +2,15 @@ import { type ParsedArgs } from "./cliArgs.js";
2
2
  import { CliFailure, type CommandResult, type Runtime } from "./cliSupport.js";
3
3
  export declare function helpResult(args: ParsedArgs): CommandResult;
4
4
  export declare function emitResult(result: CommandResult, args: ParsedArgs, runtime: Runtime): void;
5
- export declare function asFailure(error: unknown): CliFailure;
5
+ /**
6
+ * Passport didn't answer: no connection, a dropped one, or Passport said it
7
+ * was unavailable (a 5xx or 429) while trading the sign-in for a token.
8
+ * Never true for an answer Passport gave on purpose, like a refused sign-in.
9
+ */
10
+ export declare function passportUnreachable(error: unknown): boolean;
11
+ /** The one line a command prints when Passport can't be reached. */
12
+ export declare function unreachableMessage(origin?: string): string;
13
+ /** `origin` names the Passport the command tried, when it's known. */
14
+ export declare function asFailure(error: unknown, origin?: string): CliFailure;
6
15
  export declare function emitFailure(error: CliFailure, json: boolean, quiet: boolean, runtime: Runtime): void;
7
16
  export declare function failurePayload(error: CliFailure): Record<string, unknown>;
package/dist/cliOutput.js CHANGED
@@ -4,7 +4,7 @@ import { CliFailure, sanitize } from "./cliSupport.js";
4
4
  import { VERSION } from "./version.js";
5
5
  function helpText(verb) {
6
6
  const details = {
7
- init: 'passport init [--yes] [--no-open] [--cloud <origin>] [--skip-apps] [--skip-agents] [--skip-guard] [--verbose] [--json]\nnpx passport-bridge@latest init [same options]\nSets up Passport in one pass: scans for keys your agents can reach, signs you in (or up), connects the apps it found, shows the environments Passport placed, adds Passport to your agents, turns on the guard for shell commands, and sets how much agents can do on their own (Autopilot). Each step asks first and can be skipped. Run it again any time: finished steps are left as they are.\n --yes accept every default without asking (needed without a terminal)\n --no-open print links instead of opening a browser\n --cloud <url> a self-hosted Passport\n --skip-apps, --skip-agents, --skip-guard leave that step out\n --verbose show the full scan\n --json with --yes: one JSON summary with each step\'s status\nUndo: passport hook uninstall --client <agent> --apply, then remove the "passport" entry from each agent.',
7
+ init: 'passport init [--yes] [--move-keys] [--no-open] [--cloud <origin>] [--skip-apps] [--skip-agents] [--skip-guard] [--verbose] [--json]\nnpx passport-bridge@latest init [same options]\nSets up Passport in one pass: scans for keys your agents can reach, signs you in (or up), connects the apps it found, shows the environments Passport placed, adds Passport to your agents, turns on the guard for shell commands, and sets how much agents can do on their own (Autopilot). Each step asks first and can be skipped. Run it again any time: finished steps are left as they are.\n --yes accept every default without asking (needed without a terminal); CLI keys stay on this computer\n --move-keys with --yes, also move CLI keys into Passport and sign those CLIs out\n --no-open print links instead of opening a browser\n --cloud <url> a self-hosted Passport\n --skip-apps, --skip-agents, --skip-guard leave that step out\n --verbose show the full scan\n --json with --yes: one JSON summary with each step\'s status\nUndo: passport hook uninstall --client <agent> --apply, then remove the "passport" entry from each agent.',
8
8
  login: "passport login [--workspace <id>] [--cloud <origin>] [--client <id>] [--profile <name>] [--no-open]\nSigns in, stores a cli-surface rotating credential, and makes that profile active. Without --workspace, login reuses the workspace and cloud of the saved profile it refreshes, or the one workspace all saved profiles share; it never chooses between several. With no saved workspace, it opens the browser to sign in or sign up and pick or create a workspace. Passport Cloud is the default; self-hosted servers take --cloud.",
9
9
  logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
10
10
  profiles: "passport profiles\nLists saved profiles and marks the active profile. Works offline.",
@@ -100,7 +100,61 @@ export function emitResult(result, args, runtime) {
100
100
  else
101
101
  runtime.stdout.write(result.raw ? result.human : `${result.human}${result.human.endsWith("\n") ? "" : "\n"}`);
102
102
  }
103
- export function asFailure(error) {
103
+ /** Connection failures: nothing answered, or the connection dropped. */
104
+ const UNREACHABLE_CODES = new Set([
105
+ "ECONNREFUSED",
106
+ "ECONNRESET",
107
+ "ENOTFOUND",
108
+ "EAI_AGAIN",
109
+ "EHOSTUNREACH",
110
+ "ENETUNREACH",
111
+ "ENETDOWN",
112
+ "ETIMEDOUT",
113
+ "EPIPE",
114
+ "UND_ERR_SOCKET",
115
+ "UND_ERR_CONNECT_TIMEOUT"
116
+ ]);
117
+ /**
118
+ * Passport didn't answer: no connection, a dropped one, or Passport said it
119
+ * was unavailable (a 5xx or 429) while trading the sign-in for a token.
120
+ * Never true for an answer Passport gave on purpose, like a refused sign-in.
121
+ */
122
+ export function passportUnreachable(error) {
123
+ let current = error;
124
+ for (let depth = 0; depth < 4 && current && typeof current === "object"; depth += 1) {
125
+ const { message, code, errors } = current;
126
+ if (typeof code === "string" && UNREACHABLE_CODES.has(code))
127
+ return true;
128
+ if (typeof message === "string" && /^fetch failed$|token exchange failed \((?:5\d\d|429)\)/i.test(message)) {
129
+ return true;
130
+ }
131
+ if (Array.isArray(errors) &&
132
+ errors.length > 0 &&
133
+ errors.every((attempt) => UNREACHABLE_CODES.has(String(attempt?.code)))) {
134
+ return true;
135
+ }
136
+ current = current.cause;
137
+ }
138
+ return false;
139
+ }
140
+ /** `passportmcp.com` from `https://passportmcp.com`, or nothing. */
141
+ function hostOf(origin) {
142
+ if (!origin)
143
+ return "";
144
+ try {
145
+ return new URL(origin).host;
146
+ }
147
+ catch {
148
+ return "";
149
+ }
150
+ }
151
+ /** The one line a command prints when Passport can't be reached. */
152
+ export function unreachableMessage(origin) {
153
+ const host = hostOf(origin);
154
+ return `Passport couldn't be reached${host ? ` at ${host}` : ""}. Check your connection and try again.`;
155
+ }
156
+ /** `origin` names the Passport the command tried, when it's known. */
157
+ export function asFailure(error, origin) {
104
158
  if (error instanceof CliFailure)
105
159
  return error;
106
160
  if (error instanceof ArgError)
@@ -110,13 +164,16 @@ export function asFailure(error) {
110
164
  if (message === SERVER_TOO_OLD || message.includes("CLI-compatible server")) {
111
165
  return new CliFailure(SERVER_TOO_OLD, 1, "server_too_old");
112
166
  }
167
+ if (passportUnreachable(error))
168
+ return new CliFailure(unreachableMessage(origin), 1, "network_or_server");
113
169
  if (/token exchange failed|invalid_or_revoked|unauthori[sz]ed|\b401\b/i.test(message)) {
114
170
  return new CliFailure("Passport authentication expired or was revoked.", 2, "auth", {
115
171
  hint: "Run: passport login"
116
172
  });
117
173
  }
118
174
  if (/timeout|timed out|aborted|aborterror|requesttimeout/i.test(message)) {
119
- return new CliFailure("The Passport request timed out; it was not retried.", 1, "timeout");
175
+ const host = hostOf(origin);
176
+ return new CliFailure(`Passport${host ? ` at ${host}` : ""} didn't answer in time, and the request was not retried. Check your connection and try again.`, 1, "timeout");
120
177
  }
121
178
  return new CliFailure(message || "Passport request failed.", 1, "network_or_server");
122
179
  }
@@ -98,6 +98,15 @@ export declare function cloudOrigin(raw: string): string;
98
98
  */
99
99
  export declare function selectStoredProfile(args: ParsedArgs | undefined, env: Env, creds?: Record<string, Profile>, persistDetected?: boolean): StoredProfileSelection;
100
100
  export declare function sameOriginWebUrl(raw: string, trustedOrigin: string, label: string): string;
101
+ /** The Passport a command talks to, for the one line when it can't. */
102
+ export declare function passportOrigin(args: ParsedArgs, env: Env): string | undefined;
103
+ /**
104
+ * For one command: Ctrl-C and SIGTERM call `cancel`, and the process stays up
105
+ * until the command settles. Retry timers are unref'd so a finished command
106
+ * never waits on one; without this hold, a command waiting to retry Passport
107
+ * could exit 0 with nothing printed. Returns the release.
108
+ */
109
+ export declare function holdForCommand(cancel: () => void): () => void;
101
110
  export declare function resolveCliAuth(args: ParsedArgs, env: Env): CliAuth;
102
111
  export declare function callerFrom(args: ParsedArgs, env: Env): string | undefined;
103
112
  export declare function sanitize(message: string): string;
@@ -115,6 +115,31 @@ export function sameOriginWebUrl(raw, trustedOrigin, label) {
115
115
  }
116
116
  return normalized;
117
117
  }
118
+ /** The Passport a command talks to, for the one line when it can't. */
119
+ export function passportOrigin(args, env) {
120
+ try {
121
+ return new URL(resolveCliAuth(args, env).endpoint).origin;
122
+ }
123
+ catch {
124
+ return undefined;
125
+ }
126
+ }
127
+ /**
128
+ * For one command: Ctrl-C and SIGTERM call `cancel`, and the process stays up
129
+ * until the command settles. Retry timers are unref'd so a finished command
130
+ * never waits on one; without this hold, a command waiting to retry Passport
131
+ * could exit 0 with nothing printed. Returns the release.
132
+ */
133
+ export function holdForCommand(cancel) {
134
+ process.once("SIGINT", cancel);
135
+ process.once("SIGTERM", cancel);
136
+ const alive = setInterval(() => undefined, 60_000);
137
+ return () => {
138
+ clearInterval(alive);
139
+ process.removeListener("SIGINT", cancel);
140
+ process.removeListener("SIGTERM", cancel);
141
+ };
142
+ }
118
143
  export function resolveCliAuth(args, env) {
119
144
  const explicitProfile = value(args, "profile");
120
145
  const agentKey = env.PASSPORT_AGENT_KEY ?? "";
@@ -34,7 +34,7 @@ const DESCRIPTIONS = {
34
34
  };
35
35
  const GLOBAL = ["--profile", "--json", "--timeout", "--quiet", "--caller", "--help"];
36
36
  const COMMAND_FLAGS = {
37
- init: ["--yes", "--no-open", "--cloud", "--skip-apps", "--skip-agents", "--skip-guard", "--verbose"],
37
+ init: ["--yes", "--no-open", "--cloud", "--skip-apps", "--skip-agents", "--skip-guard", "--move-keys", "--verbose"],
38
38
  login: ["--cloud", "--workspace", "--client", "--no-open"],
39
39
  search: ["--app"],
40
40
  scan: ["--path", "--verbose", "--check"],
@@ -2,11 +2,13 @@
2
2
  * `passport init`: the Keys step, after Apps. For each CLI sign-in on this
3
3
  * computer it asks to store the key in Passport and sign that CLI out here,
4
4
  * the same as `passport keys move`. Quiet when there's nothing to move.
5
+ * With --yes it moves nothing unless --move-keys is passed too.
5
6
  *
6
7
  * Keys 2 CLI keys can move to Passport: Railway and GitHub
7
- * Store your Railway account token in Passport and sign the Railway CLI out on this computer? [Y/n]
8
+ * Store your Railway account token in Passport and sign the Railway CLI out on this computer? [y/n]
8
9
  * ✓ Railway: stored in Passport, removed from this computer
9
10
  */
11
+ import { bool } from "./cliArgs.js";
10
12
  import { EXEC_VENDOR_NAMES } from "./execVendors.js";
11
13
  import { computerName, moveKeys, summaryLines, KEYS_PATH } from "./cliKeys.js";
12
14
  import { noteExecVendor } from "./execMarker.js";
@@ -35,10 +37,23 @@ export async function keysStep(s) {
35
37
  }
36
38
  const names = [...new Set(local.map((key) => EXEC_VENDOR_NAMES[key.vendor]))];
37
39
  s.screen.step("Keys", `${local.length} CLI ${local.length === 1 ? "key" : "keys"} can move to Passport: ${listOf(names)}`);
40
+ // --yes never signs a CLI out: `setup --org --yes` and scripts run with
41
+ // nobody watching. Moving keys unasked takes --move-keys as well.
42
+ if (s.yes && !bool(s.args, "move-keys")) {
43
+ s.screen.result("skip", "Keys stayed on this computer. Run passport keys move to move them.");
44
+ s.summary.next.push({ argv: ["passport", "keys", "move"], description: "Move CLI keys into Passport." });
45
+ s.record("keys", "skipped", {
46
+ moved: [],
47
+ left: 0,
48
+ kept: [...new Set(local.map((key) => key.vendor))]
49
+ });
50
+ return;
51
+ }
38
52
  const cwd = s.deps.cwd ?? process.cwd();
39
53
  const summary = await moveKeys({
40
54
  api: (path, init) => s.api(path, init),
41
- confirm: (question) => s.screen.confirm(question, s.signal),
55
+ // Signs a CLI out on this computer: `[y/n]` with no default.
56
+ confirm: (question) => s.screen.confirm(question, s.signal, undefined, { destructive: true }),
42
57
  result: (mark, text) => s.screen.result(mark, text),
43
58
  line: (text) => s.screen.line(text),
44
59
  env: s.env,
package/dist/initUi.d.ts CHANGED
@@ -25,6 +25,17 @@ export type InitTerminal = {
25
25
  stop(): void;
26
26
  };
27
27
  };
28
+ export type TerminalInput = NodeJS.ReadableStream & {
29
+ isTTY?: boolean;
30
+ setRawMode?: (on: boolean) => unknown;
31
+ };
32
+ /**
33
+ * Read and drop whatever was typed before a prompt appears, so an Enter pressed
34
+ * during a pause can't answer the next question. Only on a terminal: piped
35
+ * input is a script, and every line of it is an answer. Resolves true when a
36
+ * Ctrl-C was among the dropped keys.
37
+ */
38
+ export declare function discardTypeAhead(stdin: TerminalInput, ms?: number): Promise<boolean>;
28
39
  export declare function supportsUnicode(env: Env, platform: NodeJS.Platform): boolean;
29
40
  /** The real terminal behind a Runtime. */
30
41
  export declare function processTerminal(runtime: Runtime, platform: NodeJS.Platform, json: boolean): InitTerminal;
@@ -33,11 +44,21 @@ export declare function visibleLength(text: string): number;
33
44
  export declare function wrapText(text: string, width: number): string[];
34
45
  /** "Railway", "Railway and GitHub", "Railway, GitHub, and Stripe". */
35
46
  export declare function listOf(items: string[]): string;
47
+ /** A wait longer than this shows what setup is doing. */
48
+ export declare const QUIET_MS = 300;
36
49
  export declare class InitScreen {
37
50
  readonly terminal: InitTerminal;
38
51
  private readonly yes;
39
52
  private liveShown;
40
53
  private labelled;
54
+ /** What setup is doing now, shown after QUIET_MS with nothing new on screen. */
55
+ private activity?;
56
+ private quietSince;
57
+ private ticker?;
58
+ /** A prompt is open: nothing may draw over it. */
59
+ private asking;
60
+ /** A step is drawing its own live line (the app sign-in wait). */
61
+ private ownLive;
41
62
  constructor(terminal: InitTerminal, yes: boolean);
42
63
  paint(code: string, text: string): string;
43
64
  symbol(mark: Mark): string;
@@ -45,6 +66,20 @@ export declare class InitScreen {
45
66
  text(value: string): string;
46
67
  header(): void;
47
68
  private emit;
69
+ /** Something new is on screen; the activity clock starts again. */
70
+ private quiet;
71
+ /**
72
+ * What setup is doing now. When nothing new reaches the screen for about
73
+ * 300 ms it shows as a live row (`Sign in Checking your sign-in…`) until
74
+ * the next line replaces it. Terminals only; elsewhere it prints nothing.
75
+ * `now` draws it at once, for work that holds the event loop (the scan).
76
+ */
77
+ working(text: string, label?: string, now?: boolean): void;
78
+ /** Nothing is in progress. */
79
+ idle(): void;
80
+ private tick;
81
+ /** Ask through the terminal with nothing drawn over the prompt. */
82
+ private question;
48
83
  /** Start a step's row. */
49
84
  step(label: string, text: string): void;
50
85
  /** A further line under the current step. */
@@ -62,8 +97,14 @@ export declare class InitScreen {
62
97
  /** A blank line and free text outside the step table. A line holding a
63
98
  * command to paste is never wrapped. */
64
99
  outro(lines: string[]): void;
65
- /** `[Y/n]`. Defaults to yes. With --yes, answers itself. */
66
- confirm(question: string, signal: AbortSignal, label?: string): Promise<boolean>;
100
+ /**
101
+ * `[Y/n]`, defaulting to yes. A destructive question (it signs a CLI out or
102
+ * removes a key from this computer) shows `[y/n]` and has no default: an
103
+ * empty answer asks again. With --yes, answers itself and shows it did.
104
+ */
105
+ confirm(question: string, signal: AbortSignal, label?: string, options?: {
106
+ destructive?: boolean;
107
+ }): Promise<boolean>;
67
108
  /** A numbered choice. Returns an index, or undefined when there is no answer. */
68
109
  choose(question: string, options: string[], signal: AbortSignal, label?: string): Promise<number | undefined>;
69
110
  /** Free text input; empty means skip. */
package/dist/initUi.js CHANGED
@@ -18,6 +18,47 @@ export class InitPaused extends Error {
18
18
  super("Setup paused.");
19
19
  }
20
20
  }
21
+ /** How long a prompt listens for keys typed before it appeared. Keys already
22
+ * waiting in the terminal arrive on the first read, well inside this. */
23
+ const TYPE_AHEAD_MS = 40;
24
+ /**
25
+ * Read and drop whatever was typed before a prompt appears, so an Enter pressed
26
+ * during a pause can't answer the next question. Only on a terminal: piped
27
+ * input is a script, and every line of it is an answer. Resolves true when a
28
+ * Ctrl-C was among the dropped keys.
29
+ */
30
+ export function discardTypeAhead(stdin, ms = TYPE_AHEAD_MS) {
31
+ if (!stdin.isTTY || !stdin.setRawMode)
32
+ return Promise.resolve(false);
33
+ return new Promise((resolve) => {
34
+ let interrupted = false;
35
+ const onData = (chunk) => {
36
+ if (String(chunk).includes("\u0003"))
37
+ interrupted = true;
38
+ };
39
+ try {
40
+ // Raw, so a half-typed line without Enter is read and dropped too.
41
+ stdin.setRawMode?.(true);
42
+ }
43
+ catch {
44
+ resolve(false);
45
+ return;
46
+ }
47
+ stdin.on("data", onData);
48
+ stdin.resume();
49
+ setTimeout(() => {
50
+ stdin.removeListener("data", onData);
51
+ stdin.pause();
52
+ try {
53
+ stdin.setRawMode?.(false);
54
+ }
55
+ catch {
56
+ /* the terminal went away */
57
+ }
58
+ resolve(interrupted);
59
+ }, ms);
60
+ });
61
+ }
21
62
  export function supportsUnicode(env, platform) {
22
63
  if (env.TERM === "dumb" || env.TERM === "linux")
23
64
  return false;
@@ -52,30 +93,38 @@ export function processTerminal(runtime, platform, json) {
52
93
  color: !json && colorOn(runtime.env, stdout),
53
94
  unicode: supportsUnicode(runtime.env, platform),
54
95
  width: Math.max(60, Math.min(columns, 100)),
55
- question: (prompt, signal) => new Promise((resolve, reject) => {
96
+ question: async (prompt, signal) => {
56
97
  if (signal.aborted)
57
- return reject(new InitPaused());
58
- const reader = createInterface({ input: stdin, output: stdout, terminal: true });
59
- let settled = false;
60
- const finish = (fn) => {
61
- if (settled)
62
- return;
63
- settled = true;
64
- signal.removeEventListener("abort", onAbort);
65
- reader.close();
66
- fn();
67
- };
68
- const onAbort = () => finish(() => reject(new InitPaused()));
69
- reader.on("SIGINT", () => finish(() => reject(new InitPaused())));
70
- reader.on("close", () => finish(() => reject(new InitPaused())));
71
- signal.addEventListener("abort", onAbort, { once: true });
72
- reader.question(prompt, (answer) => finish(() => resolve(answer)));
73
- }),
98
+ throw new InitPaused();
99
+ if (await discardTypeAhead(stdin))
100
+ throw new InitPaused();
101
+ return new Promise((resolve, reject) => {
102
+ if (signal.aborted)
103
+ return reject(new InitPaused());
104
+ const reader = createInterface({ input: stdin, output: stdout, terminal: true });
105
+ let settled = false;
106
+ const finish = (fn) => {
107
+ if (settled)
108
+ return;
109
+ settled = true;
110
+ signal.removeEventListener("abort", onAbort);
111
+ reader.close();
112
+ fn();
113
+ };
114
+ const onAbort = () => finish(() => reject(new InitPaused()));
115
+ reader.on("SIGINT", () => finish(() => reject(new InitPaused())));
116
+ reader.on("close", () => finish(() => reject(new InitPaused())));
117
+ signal.addEventListener("abort", onAbort, { once: true });
118
+ reader.question(prompt, (answer) => finish(() => resolve(answer)));
119
+ });
120
+ },
74
121
  enter: (signal, onPause) => {
75
122
  let stop = () => { };
76
123
  const done = new Promise((resolve) => {
77
124
  if (!interactive || !stdin.setRawMode)
78
125
  return;
126
+ let stopped = false;
127
+ let listening = false;
79
128
  const onData = (chunk) => {
80
129
  const text = String(chunk);
81
130
  if (text.includes("\u0003")) {
@@ -89,8 +138,12 @@ export function processTerminal(runtime, platform, json) {
89
138
  }
90
139
  };
91
140
  const cleanup = () => {
92
- stdin.removeListener("data", onData);
141
+ stopped = true;
93
142
  signal.removeEventListener("abort", cleanup);
143
+ if (!listening)
144
+ return;
145
+ listening = false;
146
+ stdin.removeListener("data", onData);
94
147
  try {
95
148
  stdin.setRawMode?.(false);
96
149
  }
@@ -100,10 +153,21 @@ export function processTerminal(runtime, platform, json) {
100
153
  stdin.pause();
101
154
  };
102
155
  stop = cleanup;
103
- stdin.setRawMode(true);
104
- stdin.resume();
105
- stdin.on("data", onData);
106
156
  signal.addEventListener("abort", cleanup, { once: true });
157
+ // An Enter pressed before "Press Enter to stop waiting" appeared doesn't count.
158
+ void discardTypeAhead(stdin).then((interrupted) => {
159
+ if (stopped || signal.aborted)
160
+ return;
161
+ if (interrupted) {
162
+ cleanup();
163
+ onPause();
164
+ return;
165
+ }
166
+ listening = true;
167
+ stdin.setRawMode?.(true);
168
+ stdin.resume();
169
+ stdin.on("data", onData);
170
+ });
107
171
  });
108
172
  return { done, stop: () => stop() };
109
173
  }
@@ -140,11 +204,21 @@ export function listOf(items) {
140
204
  return `${items[0]} and ${items[1]}`;
141
205
  return `${items.slice(0, -1).join(", ")}, and ${items.at(-1)}`;
142
206
  }
207
+ /** A wait longer than this shows what setup is doing. */
208
+ export const QUIET_MS = 300;
143
209
  export class InitScreen {
144
210
  terminal;
145
211
  yes;
146
212
  liveShown = false;
147
213
  labelled = false;
214
+ /** What setup is doing now, shown after QUIET_MS with nothing new on screen. */
215
+ activity;
216
+ quietSince = Date.now();
217
+ ticker;
218
+ /** A prompt is open: nothing may draw over it. */
219
+ asking = false;
220
+ /** A step is drawing its own live line (the app sign-in wait). */
221
+ ownLive = false;
148
222
  constructor(terminal, yes) {
149
223
  this.terminal = terminal;
150
224
  this.yes = yes;
@@ -186,6 +260,67 @@ export class InitScreen {
186
260
  const lead = index === 0 && label !== undefined ? `${INDENT}${label.padEnd(LABEL_WIDTH)}` : CONTINUATION;
187
261
  this.terminal.write(`${lead}${line}\n`);
188
262
  });
263
+ this.quiet();
264
+ }
265
+ /** Something new is on screen; the activity clock starts again. */
266
+ quiet() {
267
+ this.quietSince = Date.now();
268
+ this.ownLive = false;
269
+ }
270
+ /**
271
+ * What setup is doing now. When nothing new reaches the screen for about
272
+ * 300 ms it shows as a live row (`Sign in Checking your sign-in…`) until
273
+ * the next line replaces it. Terminals only; elsewhere it prints nothing.
274
+ * `now` draws it at once, for work that holds the event loop (the scan).
275
+ */
276
+ working(text, label, now = false) {
277
+ this.activity = { text, ...(label !== undefined ? { label } : {}) };
278
+ if (this.liveShown && !this.ownLive)
279
+ this.clearLive();
280
+ if (!this.terminal.live)
281
+ return;
282
+ if (now) {
283
+ this.quietSince = 0;
284
+ this.tick();
285
+ }
286
+ if (this.ticker)
287
+ return;
288
+ this.ticker = setInterval(() => this.tick(), 50);
289
+ this.ticker.unref?.();
290
+ }
291
+ /** Nothing is in progress. */
292
+ idle() {
293
+ this.activity = undefined;
294
+ if (this.ticker)
295
+ clearInterval(this.ticker);
296
+ this.ticker = undefined;
297
+ if (!this.ownLive)
298
+ this.clearLive();
299
+ }
300
+ tick() {
301
+ const activity = this.activity;
302
+ if (!activity || this.asking || this.ownLive || this.liveShown)
303
+ return;
304
+ if (Date.now() - this.quietSince < QUIET_MS)
305
+ return;
306
+ const label = !this.labelled ? activity.label : undefined;
307
+ const lead = label === undefined
308
+ ? CONTINUATION
309
+ : `${INDENT}${label.length >= LABEL_WIDTH ? `${label} ` : label.padEnd(LABEL_WIDTH)}`;
310
+ this.terminal.write(`\r\u001b[2K${lead}${this.paint("2", this.text(activity.text))}`);
311
+ this.liveShown = true;
312
+ }
313
+ /** Ask through the terminal with nothing drawn over the prompt. */
314
+ async question(prompt, signal) {
315
+ this.clearLive();
316
+ this.asking = true;
317
+ try {
318
+ return await this.terminal.question(prompt, signal);
319
+ }
320
+ finally {
321
+ this.asking = false;
322
+ this.quiet();
323
+ }
189
324
  }
190
325
  /** Start a step's row. */
191
326
  step(label, text) {
@@ -215,6 +350,7 @@ export class InitScreen {
215
350
  return;
216
351
  this.terminal.write(`\r\u001b[2K${CONTINUATION}${this.text(text)}`);
217
352
  this.liveShown = true;
353
+ this.ownLive = true;
218
354
  }
219
355
  clearLive() {
220
356
  if (!this.liveShown)
@@ -230,21 +366,27 @@ export class InitScreen {
230
366
  const wrapped = lines.flatMap((line) => /: (?:echo|fish_add_path|passport|npx) /.test(line) ? [this.text(line)] : wrapText(this.text(line), width));
231
367
  this.terminal.write(`\n${wrapped.join("\n")}\n`);
232
368
  }
233
- /** `[Y/n]`. Defaults to yes. With --yes, answers itself. */
234
- async confirm(question, signal, label) {
235
- const prompt = `${question} [Y/n] `;
369
+ /**
370
+ * `[Y/n]`, defaulting to yes. A destructive question (it signs a CLI out or
371
+ * removes a key from this computer) shows `[y/n]` and has no default: an
372
+ * empty answer asks again. With --yes, answers itself and shows it did.
373
+ */
374
+ async confirm(question, signal, label, options = {}) {
375
+ const destructive = options.destructive === true;
376
+ const prompt = `${question} ${destructive ? "[y/n]" : "[Y/n]"} `;
236
377
  if (this.yes || !this.terminal.interactive) {
237
- this.line(`${prompt}${this.paint("2", "yes")}`, label);
238
- return true;
378
+ // Without --yes and a person to ask, a destructive change doesn't happen.
379
+ const yes = this.yes || !destructive;
380
+ this.line(`${prompt}${this.paint("2", yes ? "yes" : "no")}`, label);
381
+ return yes;
239
382
  }
240
383
  const fresh = label !== undefined && !this.labelled;
241
384
  const lead = fresh ? `${INDENT}${label.padEnd(LABEL_WIDTH)}` : CONTINUATION;
242
385
  if (fresh)
243
386
  this.labelled = true;
244
- this.clearLive();
245
387
  for (;;) {
246
- const answer = (await this.terminal.question(`${lead}${this.text(prompt)}`, signal)).trim().toLowerCase();
247
- if (answer === "" || answer === "y" || answer === "yes")
388
+ const answer = (await this.question(`${lead}${this.text(prompt)}`, signal)).trim().toLowerCase();
389
+ if ((answer === "" && !destructive) || answer === "y" || answer === "yes")
248
390
  return true;
249
391
  if (answer === "n" || answer === "no")
250
392
  return false;
@@ -258,7 +400,7 @@ export class InitScreen {
258
400
  if (!this.terminal.interactive)
259
401
  return undefined;
260
402
  for (;;) {
261
- const answer = (await this.terminal.question(`${CONTINUATION}${this.text("Choose a number: ")}`, signal)).trim();
403
+ const answer = (await this.question(`${CONTINUATION}${this.text("Choose a number: ")}`, signal)).trim();
262
404
  const picked = Number(answer);
263
405
  if (Number.isInteger(picked) && picked >= 1 && picked <= options.length)
264
406
  return picked - 1;
@@ -269,7 +411,7 @@ export class InitScreen {
269
411
  async ask(prompt, signal) {
270
412
  if (!this.terminal.interactive)
271
413
  return "";
272
- return (await this.terminal.question(`${CONTINUATION}${this.text(prompt)}`, signal)).trim();
414
+ return (await this.question(`${CONTINUATION}${this.text(prompt)}`, signal)).trim();
273
415
  }
274
416
  /** The next step starts a fresh row. */
275
417
  endStep() {
@@ -0,0 +1,14 @@
1
+ export type KeychainItem = {
2
+ service: string;
3
+ account: string;
4
+ };
5
+ export type Keychain = {
6
+ label: string;
7
+ items: KeychainItem[];
8
+ };
9
+ type Runner = (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<number>;
10
+ export declare function stripeKeychain(profile: string): Keychain;
11
+ export declare function supabaseKeychain(env: NodeJS.ProcessEnv): Keychain;
12
+ /** Delete each item; undefined when done, else one line saying what stays. */
13
+ export declare function removeKeychainItems(keychain: Keychain, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, runner: Runner): Promise<string | undefined>;
14
+ export {};
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Keychain copies a vendor CLI keeps beside its config file, removed after a
3
+ * key move so "removed from this computer" stays true. Only the exact items
4
+ * named here are deleted (one service and account each), never a sweep:
5
+ *
6
+ * - Stripe CLI: service `StripeCLI`, account `<profile>.live_mode_api_key`
7
+ * (stripe-cli `pkg/config`: `KeyManagementService`, `deleteLivemodeKey`).
8
+ * - Supabase CLI: service `Supabase CLI`, accounts `access-token` (legacy) and
9
+ * the profile name, `supabase` by default (supabase/cli
10
+ * `internal/utils/access_token.go`). Project database passwords live under
11
+ * the same service with the project ref as account and are never touched.
12
+ *
13
+ * macOS uses `security delete-generic-password -s <service> -a <account>`;
14
+ * Linux uses `secret-tool clear service <service> username <account>`, the
15
+ * attributes go-keyring writes. Elsewhere the item stays, with one line.
16
+ */
17
+ import { findOnPath } from "./initInstall.js";
18
+ /** `security` exits 44 when no item matches: already gone. */
19
+ const SECURITY_NOT_FOUND = 44;
20
+ export function stripeKeychain(profile) {
21
+ return {
22
+ label: "The Stripe CLI's live key in the system keychain",
23
+ items: [{ service: "StripeCLI", account: `${profile}.live_mode_api_key` }]
24
+ };
25
+ }
26
+ export function supabaseKeychain(env) {
27
+ const profile = env.SUPABASE_PROFILE?.trim();
28
+ const accounts = new Set(["access-token", profile && /^[A-Za-z0-9._-]{1,64}$/.test(profile) ? profile : "supabase"]);
29
+ return {
30
+ label: "The Supabase CLI's access token in the system keychain",
31
+ items: [...accounts].map((account) => ({ service: "Supabase CLI", account }))
32
+ };
33
+ }
34
+ /** Delete each item; undefined when done, else one line saying what stays. */
35
+ export async function removeKeychainItems(keychain, env, platform, runner) {
36
+ const tool = platform === "darwin" ? "security" : platform === "linux" ? "secret-tool" : undefined;
37
+ if (!tool)
38
+ return `${keychain.label}, if there is one, stays: Passport can't remove it on this system.`;
39
+ const binary = findOnPath(tool, env, platform);
40
+ if (!binary)
41
+ return `${keychain.label}, if there is one, stays: ${tool} isn't on your PATH.`;
42
+ let failed = false;
43
+ for (const { service, account } of keychain.items) {
44
+ const args = tool === "security"
45
+ ? ["delete-generic-password", "-s", service, "-a", account]
46
+ : ["clear", "service", service, "username", account];
47
+ const code = await runner(binary, args, env);
48
+ if (code !== 0 && !(tool === "security" && code === SECURITY_NOT_FOUND))
49
+ failed = true;
50
+ }
51
+ return failed ? `${keychain.label} may still be there: ${tool} didn't finish.` : undefined;
52
+ }