passport-bridge 0.16.1 → 0.16.3

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.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The project's own code, run directly: the everyday commands a coding agent
3
+ * runs instead of `npm run` (Codex does this most).
4
+ *
5
+ * - `bash -lc '…'` and `sh -c '…'`: the quoted line, classified like any other.
6
+ * - `node scripts/check.mjs`, `npx tsx scripts/x.ts`, `bash scripts/ci.sh`,
7
+ * `./scripts/ci.sh`: a script file inside the project. Development work, the
8
+ * same as `npm run <script>`. Passport can't see what the script does, so the
9
+ * line stays incomplete: the guard never allows it, the agent's own prompt
10
+ * applies. It is not "opaque" in Activity either: it is the project's work.
11
+ * - `make test`, `just lint`: a target from the project's own task file, the
12
+ * same way.
13
+ * - `./node_modules/.bin/eslint .`: the tool itself.
14
+ * - `apply_patch <<'PATCH'` (Codex's patch format through the shell): a change
15
+ * to the files the patch names, placed like any other write.
16
+ *
17
+ * Anything else returns null and the caller's rules apply unchanged.
18
+ */
19
+ import { posix } from "node:path";
20
+ import { classifyLocalCommand, unwrap } from "./localCommands.js";
21
+ const SCRIPT_RUNNERS = new Set([
22
+ "node",
23
+ "tsx",
24
+ "ts-node",
25
+ "bun",
26
+ "deno",
27
+ "python",
28
+ "python3",
29
+ "ruby",
30
+ "perl",
31
+ "bash",
32
+ "sh",
33
+ "zsh",
34
+ "dash"
35
+ ]);
36
+ const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh"]);
37
+ /** Interpreter flags that take a value: the script is the word after it. */
38
+ const VALUE_FLAGS = new Set([
39
+ "-r",
40
+ "--require",
41
+ "--import",
42
+ "--loader",
43
+ "--experimental-loader",
44
+ "-C",
45
+ "--conditions",
46
+ "--env-file",
47
+ "--tsconfig",
48
+ "-W",
49
+ "-X",
50
+ "-o"
51
+ ]);
52
+ /** Interpreter flags whose code is inline: not a project file. */
53
+ const INLINE = /^(-e|-p|--eval|--print|-c|-m|-|-i|--interactive)$/;
54
+ const PACKAGE_RUNNER_FLAGS = /^(-y|--yes|-q|--quiet|--no-install|--prefer-offline|--silent|-s)$/;
55
+ const PATCH_PROGRAMS = new Set(["apply_patch", "applypatch"]);
56
+ const TASK_RUNNERS = new Set(["make", "just", "task"]);
57
+ function plain(word) {
58
+ return Boolean(word && word.text && !word.expands && !word.glob);
59
+ }
60
+ /** `npx tsx x.ts`, `pnpm exec tsx x.ts`, `npm exec -- tsx x.ts` → `tsx x.ts`. */
61
+ function withoutPackageRunner(words) {
62
+ const program = words[0]?.text;
63
+ let rest = null;
64
+ if (program === "npx" || program === "bunx" || program === "pnpx")
65
+ rest = words.slice(1);
66
+ else if ((program === "pnpm" || program === "yarn") && words[1]?.text === "exec")
67
+ rest = words.slice(2);
68
+ else if (program === "npm" && (words[1]?.text === "exec" || words[1]?.text === "x"))
69
+ rest = words.slice(2);
70
+ if (!rest)
71
+ return words;
72
+ const start = rest.findIndex((word) => !PACKAGE_RUNNER_FLAGS.test(word.text) && word.text !== "--");
73
+ return start === -1 ? [] : rest.slice(start);
74
+ }
75
+ /** `bash -lc 'line'`: the line, when nothing else follows it. */
76
+ function shellLine(words) {
77
+ if (!SHELLS.has(words[0]?.text ?? ""))
78
+ return null;
79
+ for (let index = 1; index < words.length; index++) {
80
+ const text = words[index].text;
81
+ if (!text.startsWith("-"))
82
+ return null;
83
+ if (text === "-o" || text === "+o") {
84
+ index++;
85
+ continue;
86
+ }
87
+ if (!/^-[a-zA-Z]*c[a-zA-Z]*$/.test(text))
88
+ continue;
89
+ const line = words[index + 1];
90
+ return plain(line) && index + 2 === words.length ? line.text : null;
91
+ }
92
+ return null;
93
+ }
94
+ /** The script a runner was given, when it's a plain word. */
95
+ function scriptOperand(words) {
96
+ for (let index = 1; index < words.length; index++) {
97
+ const word = words[index];
98
+ if (INLINE.test(word.text))
99
+ return null;
100
+ if (word.text === "run" && (words[0].text === "deno" || words[0].text === "bun"))
101
+ continue;
102
+ if (word.text.startsWith("-")) {
103
+ if (VALUE_FLAGS.has(word.text))
104
+ index++;
105
+ continue;
106
+ }
107
+ return plain(word) ? word : null;
108
+ }
109
+ return null;
110
+ }
111
+ function runScript(program) {
112
+ return {
113
+ vendor: program,
114
+ verb: "run script",
115
+ actionClass: "change",
116
+ environment: "development",
117
+ touches: "this project"
118
+ };
119
+ }
120
+ /** The files a patch adds, updates, moves to, or deletes. */
121
+ function patchedFiles(body) {
122
+ const written = [];
123
+ const deleted = [];
124
+ for (const line of body.split("\n")) {
125
+ const match = /^\*\*\* (Add File|Update File|Delete File|Move to): (.+)$/.exec(line.trim());
126
+ if (!match)
127
+ continue;
128
+ const file = { text: match[2].trim() };
129
+ (match[1] === "Delete File" ? deleted : written).push(file);
130
+ }
131
+ return written.length || deleted.length ? { written, deleted } : null;
132
+ }
133
+ function patch(body, ctx) {
134
+ const files = body === undefined ? null : patchedFiles(body);
135
+ if (!files)
136
+ return null;
137
+ const actions = [];
138
+ for (const [program, words] of [
139
+ ["tee", files.written],
140
+ ["rm", files.deleted]
141
+ ]) {
142
+ if (!words.length)
143
+ continue;
144
+ const outcome = classifyLocalCommand([{ text: program }, ...words], ctx);
145
+ if (outcome.kind !== "local")
146
+ return null;
147
+ actions.push(...outcome.actions.map((action) => ({
148
+ ...action,
149
+ vendor: "apply_patch",
150
+ verb: program === "rm" ? "delete" : "patch"
151
+ })));
152
+ }
153
+ return { actions, complete: false };
154
+ }
155
+ /**
156
+ * What a command the everyday table didn't recognize does, when it runs the
157
+ * project's own code. `heredocs` are the bodies this line feeds, by program.
158
+ */
159
+ export function projectCode(words, ctx, heredocs) {
160
+ const unwrapped = unwrap(words);
161
+ if (unwrapped.reason || unwrapped.sudo || !unwrapped.words.length)
162
+ return null;
163
+ const argv = withoutPackageRunner(unwrapped.words);
164
+ const head = argv[0];
165
+ if (!plain(head))
166
+ return null;
167
+ if (PATCH_PROGRAMS.has(head.text))
168
+ return patch(heredocs.get(head.text), ctx);
169
+ const line = shellLine(argv);
170
+ if (line !== null)
171
+ return { line };
172
+ if (head.text.includes("/")) {
173
+ const place = ctx.place(head);
174
+ if (place !== "project")
175
+ return null;
176
+ const segments = head.text.split("/");
177
+ const name = segments[segments.length - 1];
178
+ // A tool the project installed: `./node_modules/.bin/eslint .` is `eslint .`.
179
+ if (segments.length >= 3 &&
180
+ segments[segments.length - 2] === ".bin" &&
181
+ segments[segments.length - 3] === "node_modules") {
182
+ const outcome = classifyLocalCommand([{ text: name }, ...argv.slice(1)], ctx);
183
+ return outcome.kind === "local" ? { actions: outcome.actions, complete: true } : null;
184
+ }
185
+ if (ctx.isVendor(name))
186
+ return null;
187
+ return { actions: [runScript("script")], complete: false };
188
+ }
189
+ // `make test` in the project: a target from its own Makefile.
190
+ if (TASK_RUNNERS.has(head.text)) {
191
+ const elsewhere = argv.some((word) => /^(-C|-f|--directory|--file|--makefile|--justfile|--taskfile|-d|--dir)(=|$)/.test(word.text));
192
+ return !elsewhere && (ctx.here === "project" || ctx.here === "project-root")
193
+ ? { actions: [{ ...runScript(head.text), verb: "run target" }], complete: false }
194
+ : null;
195
+ }
196
+ if (!SCRIPT_RUNNERS.has(head.text))
197
+ return null;
198
+ const script = scriptOperand(argv);
199
+ if (!script || ctx.place(script) !== "project")
200
+ return null;
201
+ return { actions: [runScript(head.text)], complete: false };
202
+ }
203
+ /** Bodies of the heredocs a line feeds, keyed by the program that reads them. */
204
+ export function heredocBodies(nested) {
205
+ const bodies = new Map();
206
+ for (const sub of nested) {
207
+ if (sub.kind === "heredoc" && sub.target)
208
+ bodies.set(posix.basename(sub.target), sub.text);
209
+ }
210
+ return bodies;
211
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What a hook report says about the parts of a command Passport couldn't
3
+ * check: why (its kind) and the program that ran it (its first word). Never
4
+ * a script name, an argument, or anything else the command said.
5
+ */
6
+ import type { CliFinding } from "./cliHookClassify.js";
7
+ /** Why a command could not be read. Never what it was. */
8
+ export declare function opaqueKind(finding: CliFinding): string;
9
+ /** The program an opaque part ran, as its first word: `python` for
10
+ * `python deploy.py`, `bash` for `bash ./x.sh`. Null when it isn't a plain name. */
11
+ export declare function opaqueProgram(finding: CliFinding): string | null;
12
+ /** The distinct kinds and programs of a command's opaque parts, up to `max` each. */
13
+ export declare function opaqueParts(unknown: readonly CliFinding[], max: number): {
14
+ kinds: string[];
15
+ programs: string[];
16
+ };
@@ -0,0 +1,29 @@
1
+ import { INTERPRETERS } from "./cliHookParse.js";
2
+ const PROGRAM_NAME = /^[a-z0-9._-]{1,40}$/;
3
+ /** Why a command could not be read. Never what it was. */
4
+ export function opaqueKind(finding) {
5
+ const via = finding.via[finding.via.length - 1] ?? "";
6
+ if (finding.vendor === "psql")
7
+ return "sql";
8
+ if (via === "make" || via === "just" || via === "task")
9
+ return "task-runner";
10
+ if (via === "source" || via.endsWith("<script>") || INTERPRETERS.has(via))
11
+ return "script";
12
+ if (via === "npx" || via === "bunx")
13
+ return "package-runner";
14
+ return "unknown";
15
+ }
16
+ /** The program an opaque part ran, as its first word: `python` for
17
+ * `python deploy.py`, `bash` for `bash ./x.sh`. Null when it isn't a plain name. */
18
+ export function opaqueProgram(finding) {
19
+ const program = (finding.via[finding.via.length - 1] ?? "").split(" ")[0]?.toLowerCase() ?? "";
20
+ return PROGRAM_NAME.test(program) ? program : null;
21
+ }
22
+ /** The distinct kinds and programs of a command's opaque parts, up to `max` each. */
23
+ export function opaqueParts(unknown, max) {
24
+ const programs = unknown.map(opaqueProgram).filter((program) => Boolean(program));
25
+ return {
26
+ kinds: [...new Set(unknown.map(opaqueKind))].slice(0, max),
27
+ programs: [...new Set(programs)].slice(0, max)
28
+ };
29
+ }
package/dist/cliKeys.js CHANGED
@@ -130,8 +130,14 @@ export async function moveKeys(io) {
130
130
  }
131
131
  const removed = await removeLocalCopy(key, context, io.runner);
132
132
  summary.moved.push({ vendor: key.vendor, label: key.label, keyId: stored.id, localCopy: removed.localCopy });
133
- if (removed.localCopy === "removed")
133
+ if (removed.localCopy === "removed" && removed.note) {
134
+ // The file copy is gone; say plainly that a keychain copy may not be.
135
+ summary.left.push(removed.note);
136
+ io.result("warn", `${name}: stored in Passport, removed from ${key.location}. ${removed.note}`);
137
+ }
138
+ else if (removed.localCopy === "removed") {
134
139
  io.result("done", `${name}: stored in Passport, removed from this computer`);
140
+ }
135
141
  else {
136
142
  summary.left.push(removed.left ?? `${key.location} still holds it.`);
137
143
  io.result("warn", `${name}: stored in Passport. ${removed.left ?? ""}`.trim());
@@ -17,7 +17,7 @@ import { syncNative } from "./nativeSync.js";
17
17
  import { homedir } from "node:os";
18
18
  import { dirname, join } from "node:path";
19
19
  import { value } from "./cliArgs.js";
20
- import { HOOK_CLIENTS, applyGuardInstall, registeredEntries, nodeInvocation, planGuardInstall } from "./cliHookInstall.js";
20
+ import { HOOK_CLIENTS, applyGuardInstall, registeredEntries, stableInvocation, planGuardInstall } from "./cliHookInstall.js";
21
21
  import { CliFailure, cloudOrigin, failure } from "./cliSupport.js";
22
22
  import { AGENT_NAMES, AGENT_ORDER, applyAgent, backupOnce, claudeCodeConfigPath, claudeDesktopConfigPath, codexConfigFile, cursorConfigPath, detectAgents, needsWork, planAgent, vscodeConfigPath } from "./initAgents.js";
23
23
  import { copyVersionsIn, ensureStableCommand, pruneCopies } from "./initInstall.js";
@@ -129,7 +129,7 @@ function addHooks(line, context, stable, installProblem) {
129
129
  line.message ??= installProblem;
130
130
  return;
131
131
  }
132
- const invocation = nodeInvocation(stable.node, stable.entry);
132
+ const invocation = stableInvocation(stable);
133
133
  try {
134
134
  const plan = planGuardInstall(line.agent, env, invocation);
135
135
  if (!plan.changes.length) {
@@ -7,6 +7,9 @@ export type StableCommand = {
7
7
  source: "global" | "installed";
8
8
  /** Folder holding the `passport` shim, when this is Passport's own copy. */
9
9
  binDir?: string;
10
+ /** The version-independent launcher in `binDir` that hooks run. Upgrades
11
+ * rewrite it in place, so hooks follow without being edited. */
12
+ launcher?: string;
10
13
  /** Whether `passport` already resolves on PATH (outside npm's cache). */
11
14
  onPath: boolean;
12
15
  };
@@ -37,6 +40,15 @@ export declare function resolveStableNode(context: InstallContext): string | und
37
40
  * only where two versions conflict.
38
41
  */
39
42
  export declare function copyPackageClosure(packageRoot: string, target: string): number;
43
+ /**
44
+ * One launcher's text. It runs the recorded node when that still exists, else
45
+ * whichever node the shell finds, so removing an nvm version doesn't break
46
+ * hooks. The last line keeps the exact `exec '<node>' '<entry>' "$@"` (or
47
+ * `"<node>" "<entry>" %*`) form the Passport plugin reads.
48
+ */
49
+ export declare function launcherText(node: string, entry: string, platform: NodeJS.Platform): string;
50
+ /** The launcher hooks run: `passport` (or `passport.cmd`) in `binDir`. */
51
+ export declare function launcherPath(binDir: string, platform: NodeJS.Platform): string;
40
52
  export declare class StableInstallError extends Error {
41
53
  }
42
54
  /**
@@ -4,20 +4,25 @@
4
4
  * `npx passport-bridge@latest init` runs from npm's cache, which npm may clear at
5
5
  * any time. A hook that points there breaks silently. So init copies the running
6
6
  * package once into `$PASSPORT_HOME/cli/<version>/` (with its dependencies) and
7
- * registers `"<node>" "<that copy>/dist/passport.js"`, both absolute, so hooks
8
- * do not depend on the agent's PATH. A global `passport` from npm
9
- * that is the same version or newer is used instead of a copy.
7
+ * registers the launcher `$PASSPORT_HOME/cli/bin/passport` (`passport.cmd` on
8
+ * Windows), an absolute path, so hooks do not depend on the agent's PATH. The
9
+ * launcher names the version, so an upgrade rewrites it (and the `cli/current`
10
+ * link) and every hook follows without being edited. It runs the recorded node,
11
+ * or the node on PATH once that one is gone. A global `passport` from npm that
12
+ * is the same version or newer is used instead of a copy.
10
13
  *
11
14
  * Every write is atomic: the copy is built in a temporary folder and renamed
12
15
  * into place, so Ctrl-C never leaves a half-installed version behind.
13
16
  */
14
17
  import { randomBytes } from "node:crypto";
15
- import { accessSync, chmodSync, constants, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
18
+ import { accessSync, chmodSync, constants, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
16
19
  import { spawnSync } from "node:child_process";
17
20
  import { basename, delimiter, dirname, join, relative, resolve, sep } from "node:path";
18
21
  import { credentialDir, ensurePrivateDirectory } from "./credentialStorage.js";
19
22
  import { ONE_LINER_MIN_NODE } from "./nodeVersion.js";
20
23
  const INSTALL_MARKER = ".passport-install.json";
24
+ /** `cli/current`: a link to the installed version (POSIX), read by the plugin. */
25
+ const CURRENT = "current";
21
26
  /** npm's cache and the one-off folders npx and pnpm dlx run from. */
22
27
  export function isEphemeralPath(path) {
23
28
  const normalized = path.split(sep).join("/");
@@ -236,7 +241,42 @@ export function copyPackageClosure(packageRoot, target) {
236
241
  function quoteSh(value) {
237
242
  return `'${value.replace(/'/g, `'\\''`)}'`;
238
243
  }
239
- /** Version-independent `passport` and `passport-bridge` launchers for PATH. */
244
+ /**
245
+ * One launcher's text. It runs the recorded node when that still exists, else
246
+ * whichever node the shell finds, so removing an nvm version doesn't break
247
+ * hooks. The last line keeps the exact `exec '<node>' '<entry>' "$@"` (or
248
+ * `"<node>" "<entry>" %*`) form the Passport plugin reads.
249
+ */
250
+ export function launcherText(node, entry, platform) {
251
+ if (platform === "win32") {
252
+ return [
253
+ "@echo off",
254
+ `if not exist "${node}" goto fallback`,
255
+ `"${node}" "${entry}" %*`,
256
+ "exit /b %ERRORLEVEL%",
257
+ ":fallback",
258
+ `node "${entry}" %*`,
259
+ ""
260
+ ].join("\r\n");
261
+ }
262
+ return [
263
+ "#!/bin/sh",
264
+ "# Passport CLI launcher. Upgrades rewrite this file; agent hooks run it.",
265
+ `if [ ! -x ${quoteSh(node)} ]; then`,
266
+ ` for candidate in "$(command -v node 2>/dev/null)" /opt/homebrew/bin/node /usr/local/bin/node; do`,
267
+ ` if [ -n "$candidate" ] && [ -x "$candidate" ]; then exec "$candidate" ${quoteSh(entry)} "$@"; fi`,
268
+ " done",
269
+ "fi",
270
+ `exec ${quoteSh(node)} ${quoteSh(entry)} "$@"`,
271
+ ""
272
+ ].join("\n");
273
+ }
274
+ /** The launcher hooks run: `passport` (or `passport.cmd`) in `binDir`. */
275
+ export function launcherPath(binDir, platform) {
276
+ return join(binDir, platform === "win32" ? "passport.cmd" : "passport");
277
+ }
278
+ /** Version-independent `passport` and `passport-bridge` launchers. Each is
279
+ * replaced with one rename, so a hook never runs a half-written file. */
240
280
  function writeShims(binDir, node, versionDir, platform) {
241
281
  mkdirSync(binDir, { recursive: true, mode: 0o700 });
242
282
  const shims = [
@@ -245,9 +285,7 @@ function writeShims(binDir, node, versionDir, platform) {
245
285
  ];
246
286
  for (const [name, entry] of shims) {
247
287
  const file = join(binDir, platform === "win32" ? `${name}.cmd` : name);
248
- const body = platform === "win32"
249
- ? `@echo off\r\n"${node}" "${entry}" %*\r\n`
250
- : `#!/bin/sh\nexec ${quoteSh(node)} ${quoteSh(entry)} "$@"\n`;
288
+ const body = launcherText(node, entry, platform);
251
289
  try {
252
290
  if (readFileSync(file, "utf8") === body)
253
291
  continue;
@@ -261,6 +299,37 @@ function writeShims(binDir, node, versionDir, platform) {
261
299
  renameSync(temporary, file);
262
300
  }
263
301
  }
302
+ /** `cli/current` → the installed version, swapped with one rename. POSIX only:
303
+ * Windows has the launcher alone. Best effort; the launcher is what hooks run. */
304
+ function pointCurrent(root, version, platform) {
305
+ if (platform === "win32")
306
+ return;
307
+ const link = join(root, CURRENT);
308
+ try {
309
+ if (lstatSync(link).isSymbolicLink() && readlinkSync(link) === version)
310
+ return;
311
+ }
312
+ catch {
313
+ /* not there yet */
314
+ }
315
+ const temporary = join(root, `.current-${randomBytes(6).toString("hex")}.tmp`);
316
+ try {
317
+ symlinkSync(version, temporary);
318
+ renameSync(temporary, link);
319
+ }
320
+ catch {
321
+ rmSync(temporary, { force: true });
322
+ }
323
+ }
324
+ /** The version `cli/current` points at, if any. */
325
+ function currentVersion() {
326
+ try {
327
+ return readlinkSync(join(cliRoot(), CURRENT));
328
+ }
329
+ catch {
330
+ return undefined;
331
+ }
332
+ }
264
333
  export class StableInstallError extends Error {
265
334
  }
266
335
  /**
@@ -301,7 +370,16 @@ export function ensureStableCommand(context) {
301
370
  }
302
371
  const binDir = join(root, "bin");
303
372
  writeShims(binDir, node, versionDir, context.platform);
304
- return { node, entry: join(versionDir, "dist", "passport.js"), version, source: "installed", binDir, onPath };
373
+ pointCurrent(root, version, context.platform);
374
+ return {
375
+ node,
376
+ entry: join(versionDir, "dist", "passport.js"),
377
+ version,
378
+ source: "installed",
379
+ binDir,
380
+ launcher: launcherPath(binDir, context.platform),
381
+ onPath
382
+ };
305
383
  }
306
384
  /** The versions of Passport's own copies that these commands run. */
307
385
  export function copyVersionsIn(commands) {
@@ -326,6 +404,9 @@ export function copyVersionsIn(commands) {
326
404
  */
327
405
  export function pruneCopies(keep) {
328
406
  const kept = new Set(keep);
407
+ const linked = currentVersion();
408
+ if (linked)
409
+ kept.add(linked);
329
410
  const removed = [];
330
411
  let entries;
331
412
  try {
@@ -335,7 +416,7 @@ export function pruneCopies(keep) {
335
416
  return removed;
336
417
  }
337
418
  for (const entry of entries) {
338
- if (entry === "bin" || entry.startsWith(".") || kept.has(entry))
419
+ if (entry === "bin" || entry === CURRENT || entry.startsWith(".") || kept.has(entry))
339
420
  continue;
340
421
  const directory = join(cliRoot(), entry);
341
422
  if (!existsSync(join(directory, INSTALL_MARKER)))
@@ -357,7 +438,7 @@ export function isOtherPassportInstall(path, version) {
357
438
  if (rel.startsWith("..") || rel === "")
358
439
  return false;
359
440
  const [installed] = rel.split(sep);
360
- return installed !== version && installed !== "bin";
441
+ return installed !== version && installed !== "bin" && installed !== CURRENT;
361
442
  }
362
443
  /** One line a person can paste to put `passport` on PATH. Printed, never run. */
363
444
  export function pathLine(binDir, env, home, platform) {
@@ -4,7 +4,7 @@
4
4
  * destructive production actions ask first.
5
5
  */
6
6
  import { bool } from "./cliArgs.js";
7
- import { HOOK_CLIENTS, applyGuardInstall, nodeInvocation, planGuardInstall, registeredEntries } from "./cliHookInstall.js";
7
+ import { HOOK_CLIENTS, applyGuardInstall, stableInvocation, planGuardInstall, registeredEntries } from "./cliHookInstall.js";
8
8
  import { CliFailure, readBoundedJson, safeApiError } from "./cliSupport.js";
9
9
  import { AGENT_NAMES, applyAgent, backupOnce, detectAgents, displayHome, editsExistingFile, needsWork, planAgent } from "./initAgents.js";
10
10
  import { copyVersionsIn, ensureStableCommand, pruneCopies } from "./initInstall.js";
@@ -209,7 +209,7 @@ async function guardSetup(s) {
209
209
  return;
210
210
  }
211
211
  s.stable = stable;
212
- const invocation = nodeInvocation(stable.node, stable.entry);
212
+ const invocation = stableInvocation(stable);
213
213
  const plans = [];
214
214
  const problems = [];
215
215
  for (const client of clients) {
@@ -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
+ }
@@ -1,4 +1,6 @@
1
1
  import { type ExecVendor } from "./execVendors.js";
2
+ import { type Keychain } from "./keysKeychain.js";
3
+ export { withoutAwsProfileKeys, withoutJsonFields, withoutTomlKeys } from "./keysLocalEdit.js";
2
4
  export type LocalSecret = {
3
5
  token: string;
4
6
  } | {
@@ -10,6 +12,25 @@ export type Removal = {
10
12
  kind: "logout";
11
13
  command: string;
12
14
  args: string[];
15
+ }
16
+ /** Delete these fields of the object at `object` (a path of keys) in a JSON file. */
17
+ | {
18
+ kind: "json-fields";
19
+ path: string;
20
+ object: string[];
21
+ fields: string[];
22
+ }
23
+ /** Delete these keys of one table (`[]` is the root) in a TOML file. */
24
+ | {
25
+ kind: "toml-keys";
26
+ path: string;
27
+ table: string[];
28
+ keys: string[];
29
+ }
30
+ /** A file that holds only the credential. */
31
+ | {
32
+ kind: "credential-file";
33
+ path: string;
13
34
  } | {
14
35
  kind: "settings-env";
15
36
  path: string;
@@ -19,6 +40,12 @@ export type Removal = {
19
40
  path: string;
20
41
  profile: string;
21
42
  };
43
+ /** Railway's sign-in fields on `user` (railwayapp/cli `RailwayUser`); `id` and everything else stay. */
44
+ export declare const RAILWAY_CREDENTIAL_FIELDS: string[];
45
+ /** Wrangler's sign-in keys in `config/default.toml` (workers-auth `readStoredAuthState`). */
46
+ export declare const WRANGLER_CREDENTIAL_KEYS: string[];
47
+ /** One Stripe profile's API keys (stripe-cli `profile.go`); account, device, color, and other profiles stay. */
48
+ export declare const STRIPE_CREDENTIAL_KEYS: string[];
22
49
  export type LocalKey = {
23
50
  vendor: ExecVendor;
24
51
  kind: string;
@@ -32,21 +59,29 @@ export type LocalKey = {
32
59
  removal?: Removal;
33
60
  /** What the sign-out does, in the confirmation question. */
34
61
  removalWords: string;
62
+ /** Keychain copies the CLI keeps beside the file, removed with it. */
63
+ keychain?: Keychain;
35
64
  };
36
65
  export type LocalContext = {
37
66
  env: NodeJS.ProcessEnv;
38
67
  home?: string;
39
68
  platform?: NodeJS.Platform;
40
69
  };
70
+ /** The host-level (active) `oauth_token` and `user` of one host in gh's hosts.yml. */
71
+ export declare function ghActiveAccount(text: string, host: string): {
72
+ token?: string;
73
+ user?: string;
74
+ multiAccount: boolean;
75
+ };
41
76
  export declare function claudeSettingsFile(env: NodeJS.ProcessEnv, home: string): string;
42
77
  /** Every key this computer holds that Passport could take, CLI sign-ins first. */
43
78
  export declare function findLocalKeys(context: LocalContext): LocalKey[];
44
- /** Drop only the key lines of one profile; everything else stays byte for byte. */
45
- export declare function withoutAwsProfileKeys(text: string, profile: string): string;
46
79
  export type RemovalRunner = (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<number>;
80
+ /** `note`: the file copy is gone but a keychain copy may remain. */
47
81
  export type RemovalResult = {
48
82
  localCopy: "removed" | "logout_failed";
49
83
  left?: string;
84
+ note?: string;
50
85
  };
51
86
  /**
52
87
  * Remove this computer's copy after it is safely in Passport. A sign-out that