passport-bridge 0.16.2 → 0.16.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cliHook.js CHANGED
@@ -22,11 +22,12 @@ import { decideGuard, guardMachineOf } from "./cliHookGuard.js";
22
22
  import { detectMode } from "./cliHookMode.js";
23
23
  import { readInput } from "./cliHookInput.js";
24
24
  import { hookViaPlugin } from "./hookPlugin.js";
25
- import { INTERPRETERS } from "./cliHookParse.js";
25
+ import { opaqueParts } from "./cliHookOpaque.js";
26
+ export { opaqueKind, opaqueProgram } from "./cliHookOpaque.js";
26
27
  import { hasExpired, holdAsk, takeAsk, takeExpired } from "./cliHookPending.js";
27
28
  import { claimStaleRefresh, readCliPolicy } from "./cliPolicy.js";
28
29
  import { readCreds } from "./credentials.js";
29
- import { resolveCliAuth, selectStoredProfile } from "./cliSupport.js";
30
+ import { endpoint, resolveCliAuth, selectStoredProfile } from "./cliSupport.js";
30
31
  /** Claude Code, Codex, and Cursor fail open on a slow hook, so the budget is ours. */
31
32
  export const HOOK_BUDGET_MS = 1_500;
32
33
  const MAX_FINDINGS = 8;
@@ -70,19 +71,6 @@ export function safeVerb(raw) {
70
71
  .slice(0, 4);
71
72
  return tokens.join(" ").slice(0, 80).trim() || "invoke";
72
73
  }
73
- /** Why a command could not be read. Never what it was. */
74
- export function opaqueKind(finding) {
75
- const via = finding.via[finding.via.length - 1] ?? "";
76
- if (finding.vendor === "psql")
77
- return "sql";
78
- if (via === "make" || via === "just" || via === "task")
79
- return "task-runner";
80
- if (via === "source" || via.endsWith("<script>") || INTERPRETERS.has(via))
81
- return "script";
82
- if (via === "npx" || via === "bunx")
83
- return "package-runner";
84
- return "unknown";
85
- }
86
74
  function isCursorEvent(input) {
87
75
  return input.hook_event_name === "beforeShellExecution" || input.hook_event_name === "afterShellExecution";
88
76
  }
@@ -172,13 +160,14 @@ export function buildReport(input, findings, env, declared, decided = [], local
172
160
  const governed = reportable(summary.governed, decided, local);
173
161
  if (!governed.length && !summary.opaque)
174
162
  return null;
175
- const kinds = [...new Set(summary.unknown.map(opaqueKind))].slice(0, MAX_OPAQUE_KINDS);
163
+ const { kinds, programs } = opaqueParts(summary.unknown, MAX_OPAQUE_KINDS);
176
164
  return {
177
165
  ...context(input, env, declared),
178
166
  ...outcomeOfInput(input),
179
167
  findings: governed,
180
168
  opaque: summary.opaque,
181
- ...(summary.opaque && kinds.length ? { opaqueKinds: kinds } : {})
169
+ ...(summary.opaque && kinds.length ? { opaqueKinds: kinds } : {}),
170
+ ...(summary.opaque && programs.length ? { opaquePrograms: programs } : {})
182
171
  };
183
172
  }
184
173
  /** What the guard answered, and for which findings. The audit row that
@@ -239,16 +228,16 @@ function localProfile(args, env) {
239
228
  return undefined;
240
229
  }
241
230
  }
242
- /** One authenticated call surface for everything after the decision. The
243
- * exchange never rotates the refresh token (see `postReport`). */
231
+ /** One authenticated call surface for everything after the decision: a
232
+ * still-valid access token cached by an earlier run, or one exchange that
233
+ * never rotates the refresh token (see `reportSender`). */
244
234
  async function profileApi(profile, signal, fetcher) {
245
235
  const saved = readCreds()[profile];
246
236
  if (!saved)
247
237
  return null;
248
- const origin = new URL(saved.endpoint).origin;
249
- const { TokenManager } = await import("./bridgeExchange.js");
250
- const manager = new TokenManager(saved.endpoint, saved.refreshToken, undefined, undefined, HOOK_BUDGET_MS, signal, fetcher);
251
- return (path, init) => manager.authedFetch(`${origin}${path}`, init);
238
+ const { cachedAccessApi } = await import("./accessTokenCache.js");
239
+ const credential = { endpoint: endpoint(saved.endpoint), refreshToken: saved.refreshToken };
240
+ return cachedAccessApi(profile, credential, signal, fetcher, HOOK_BUDGET_MS);
252
241
  }
253
242
  /** The report an older server accepts: no Autopilot fields, ask or deny only. */
254
243
  export function legacyReport(report) {
@@ -281,17 +270,17 @@ async function postWith(api, report, signal) {
281
270
  * command under a 1.5 s budget, and a rotation cut short by that budget would
282
271
  * lose the only copy of the new token, which later revokes the whole family.
283
272
  * With nothing to rotate there is nothing to serialize either, so the hook
284
- * never takes the profile lease or queues behind a serving bridge. */
273
+ * never takes the profile lease or queues behind a serving bridge. The
274
+ * access token it gets is cached for the next run (`accessTokenCache.ts`), so
275
+ * most runs send one request, not an exchange and then the report. */
285
276
  async function reportSender(args, runtime, signal, deps) {
286
277
  if (deps.send)
287
278
  return (report) => deps.send(report, signal, runtime, args);
288
279
  const auth = resolveCliAuth(args, runtime.env);
289
280
  if (auth.kind !== "profile")
290
281
  return null;
291
- const { TokenManager } = await import("./bridgeExchange.js");
292
- const manager = new TokenManager(auth.endpoint, auth.refreshToken, undefined, undefined, HOOK_BUDGET_MS, signal, deps.fetch ?? fetch);
293
- const origin = new URL(auth.endpoint).origin;
294
- return (report) => postWith((path, init) => manager.authedFetch(`${origin}${path}`, init), report, signal);
282
+ const api = await profileApi(auth.profile, signal, deps.fetch ?? fetch);
283
+ return api ? (report) => postWith(api, report, signal) : null;
295
284
  }
296
285
  /** Parked asks nobody claimed in time: the prompt was declined, or nothing ran. */
297
286
  function expiredAsks(now) {
@@ -32,6 +32,13 @@ export declare function isPassportGuardCommand(command: unknown): boolean;
32
32
  export declare function hookCommand(env: Env, exists?: (path: string) => boolean, client?: HookClient, kind?: Kind, invocation?: string): string;
33
33
  /** A shell-safe `node <entry>` prefix for a hook command. */
34
34
  export declare function nodeInvocation(node: string, entry: string): string;
35
+ /** What hooks run for a stable install: its version-independent launcher, so
36
+ * an upgrade moves every hook; a global npm install by its own path. */
37
+ export declare function stableInvocation(stable: {
38
+ node: string;
39
+ entry: string;
40
+ launcher?: string;
41
+ }): string;
35
42
  /** The Passport audit command registered in Claude Code settings, if any. */
36
43
  export declare function registeredHookCommand(settings: Settings): string | null;
37
44
  /** Add Passport's audit entry to Claude Code's Bash matcher, touching nothing else. */
@@ -21,6 +21,8 @@ import { readCliPolicy } from "./cliPolicy.js";
21
21
  import { coveredByPlugin, pluginInstalled } from "./hookPlugin.js";
22
22
  import { syncNative } from "./nativeSync.js";
23
23
  import { readCreds } from "./credentials.js";
24
+ import { credentialDir } from "./credentialStorage.js";
25
+ import { launcherPath } from "./initInstall.js";
24
26
  import { failure, selectStoredProfile } from "./cliSupport.js";
25
27
  export const HOOK_CLIENTS = ["claude-code", "codex", "cursor"];
26
28
  const SETTINGS_MAX_BYTES = 1024 * 1024;
@@ -115,8 +117,17 @@ function ownInvocation() {
115
117
  const entry = process.argv[1];
116
118
  return entry ? `${quoted(process.execPath)} ${quoted(entry)}` : null;
117
119
  }
118
- /** `passport` when the CLI is on PATH, otherwise this exact process. */
120
+ /** Passport's own launcher (`passport init` writes it), when it is there. */
121
+ function installedLauncher(exists) {
122
+ const launcher = launcherPath(join(credentialDir(), "cli", "bin"), process.platform);
123
+ return exists(launcher) ? launcher : null;
124
+ }
125
+ /** The launcher `passport init` installed, else `passport` when the CLI is on
126
+ * PATH, otherwise this exact process. */
119
127
  function passportInvocation(env, exists) {
128
+ const launcher = installedLauncher(exists);
129
+ if (launcher)
130
+ return quoted(launcher);
120
131
  if (onPath("passport", env, exists))
121
132
  return "passport";
122
133
  return ownInvocation() ?? "passport";
@@ -131,6 +142,11 @@ export function hookCommand(env, exists = executable, client, kind = "audit", in
131
142
  export function nodeInvocation(node, entry) {
132
143
  return `${quoted(node)} ${quoted(entry)}`;
133
144
  }
145
+ /** What hooks run for a stable install: its version-independent launcher, so
146
+ * an upgrade moves every hook; a global npm install by its own path. */
147
+ export function stableInvocation(stable) {
148
+ return stable.launcher ? quoted(stable.launcher) : nodeInvocation(stable.node, stable.entry);
149
+ }
134
150
  /** Write through a symlinked settings file (dotfile managers) to its target. */
135
151
  function writablePath(path) {
136
152
  try {
@@ -237,19 +253,26 @@ function withEntry(spec, settings, slot, command) {
237
253
  const hooks = { ...hooksOf(settings) };
238
254
  const list = [...listOf(settings, event)];
239
255
  if (spec.format === "cursor") {
256
+ const at = list.findIndex((entry) => ours(entry?.command));
240
257
  const kept = list.filter((entry) => !ours(entry?.command));
241
- hooks[event] = [...kept, { command, timeout: HOOK_TIMEOUT_SECONDS }];
258
+ const fresh = { command, timeout: HOOK_TIMEOUT_SECONDS };
259
+ hooks[event] = at === -1 ? [...kept, fresh] : [...kept.slice(0, at), fresh, ...kept.slice(at)];
242
260
  const version = typeof settings.version === "number" ? settings.version : 1;
243
261
  return { ...settings, version, hooks };
244
262
  }
245
263
  const entry = { type: "command", command, timeout: HOOK_TIMEOUT_SECONDS };
246
264
  const groups = list;
247
- const index = groups.findIndex((group) => group && group.matcher === "Bash");
265
+ // An older Passport entry (another version's path) is replaced where it stands.
266
+ const owner = groups.findIndex((group) => group && Array.isArray(group.hooks) && group.hooks.some((candidate) => ours(candidate?.command)));
267
+ const index = owner !== -1 ? owner : groups.findIndex((group) => group && group.matcher === "Bash");
248
268
  if (index === -1)
249
269
  groups.push({ matcher: "Bash", hooks: [entry] });
250
270
  else {
251
271
  const existing = Array.isArray(groups[index].hooks) ? groups[index].hooks : [];
252
- groups[index] = { ...groups[index], hooks: [...existing.filter((candidate) => !ours(candidate?.command)), entry] };
272
+ const at = existing.findIndex((candidate) => ours(candidate?.command));
273
+ const kept = existing.filter((candidate) => !ours(candidate?.command));
274
+ const hooks = at === -1 ? [...kept, entry] : [...kept.slice(0, at), entry, ...kept.slice(at)];
275
+ groups[index] = { ...groups[index], hooks };
253
276
  }
254
277
  hooks[event] = groups;
255
278
  return { ...settings, hooks };
@@ -36,6 +36,9 @@ export type LocalMachine = {
36
36
  temp: string[];
37
37
  /** Extra folders whose contents are keys or agent settings. */
38
38
  sensitive: string[];
39
+ /** Folders where agents keep their own checkouts of a project (Codex and
40
+ * Cursor worktrees). A project inside one is a project, not agent settings. */
41
+ worktrees?: string[];
39
42
  fs: LocalFs;
40
43
  };
41
44
  export declare const NODE_FS: LocalFs;
@@ -18,6 +18,7 @@ import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
18
18
  import { homedir, tmpdir } from "node:os";
19
19
  import { posix } from "node:path";
20
20
  import { classifyArgv, classifyNestedText } from "./cliHookClassify.js";
21
+ import { heredocBodies, projectCode } from "./cliHookLocalCode.js";
21
22
  import { splitCommands } from "./cliHookParse.js";
22
23
  import { VENDORS } from "./cliHookVendors.js";
23
24
  import { databasePrefix } from "./envDatabase.js";
@@ -192,11 +193,27 @@ export function localMachine(cwd, env = process.env, fs = NODE_FS) {
192
193
  else if (!tooBroad(working, home))
193
194
  projectRoot = working;
194
195
  }
195
- return { cwd: working, projectRoot, home, temp, sensitive, fs };
196
+ const worktrees = [
197
+ posix.join(home, ".codex", "worktrees"),
198
+ posix.join(home, ".cursor", "worktrees"),
199
+ ...[env.CODEX_HOME, env.PASSPORT_CURSOR_HOME]
200
+ .filter((value) => typeof value === "string" && value.startsWith("/"))
201
+ .map((value) => posix.join(canonical(value, fs), "worktrees"))
202
+ ];
203
+ return { cwd: working, projectRoot, home, temp, sensitive, worktrees, fs };
204
+ }
205
+ /** A git checkout an agent made for itself (`~/.codex/worktrees/<id>/<repo>`):
206
+ * its own files are the project, even though the folder above holds settings. */
207
+ function agentWorktree(projectRoot, machine) {
208
+ if (!projectRoot)
209
+ return false;
210
+ return (machine.worktrees ?? []).some((folder) => projectRoot !== folder && within(projectRoot, folder));
196
211
  }
197
212
  /** Where a resolved, canonical path lands. */
198
213
  export function placeOfPath(path, machine) {
199
214
  const { home, projectRoot } = machine;
215
+ if (agentWorktree(projectRoot, machine) && within(path, projectRoot))
216
+ return projectPlace(path, projectRoot);
200
217
  if (SENSITIVE_ABSOLUTE.some((folder) => within(path, folder)))
201
218
  return "sensitive";
202
219
  if (machine.sensitive.some((folder) => within(path, folder)))
@@ -207,13 +224,8 @@ export function placeOfPath(path, machine) {
207
224
  return "root";
208
225
  if (within(home, path))
209
226
  return "home";
210
- if (projectRoot && within(path, projectRoot)) {
211
- if (SENSITIVE_IN_PROJECT.some((entry) => within(path, posix.join(projectRoot, entry))))
212
- return "sensitive";
213
- if (path === projectRoot || path === posix.join(projectRoot, ".git"))
214
- return "project-root";
215
- return "project";
216
- }
227
+ if (projectRoot && within(path, projectRoot))
228
+ return projectPlace(path, projectRoot);
217
229
  // Home is personal even when it sits in a temporary folder (sandboxes).
218
230
  if (within(path, home))
219
231
  return "outside";
@@ -225,6 +237,13 @@ export function placeOfPath(path, machine) {
225
237
  return "system";
226
238
  return "outside";
227
239
  }
240
+ function projectPlace(path, projectRoot) {
241
+ if (SENSITIVE_IN_PROJECT.some((entry) => within(path, posix.join(projectRoot, entry))))
242
+ return "sensitive";
243
+ if (path === projectRoot || path === posix.join(projectRoot, ".git"))
244
+ return "project-root";
245
+ return "project";
246
+ }
228
247
  const EVERYTHING = new Set(["*", "**", ".*", "*.*", ".??*", ".[!.]*"]);
229
248
  /** The path a word names, relative to `cwd`; null when it can't be known. */
230
249
  export function resolveWord(word, cwd, machine) {
@@ -392,6 +411,24 @@ function vendorFindings(shape, outcome, walk, depth, cwd) {
392
411
  if (!plain)
393
412
  walk.complete = false;
394
413
  }
414
+ /** The project's own code (`cliHookLocalCode.ts`): a script, a shell's quoted
415
+ * line, a patch. True when it was placed; the vendor map then has nothing to add. */
416
+ function ownCode(shape, at, machine, walk) {
417
+ const code = projectCode(shape.words, contextAt(at.cwd, machine), at.heredocs);
418
+ if (!code)
419
+ return false;
420
+ if ("line" in code) {
421
+ const inner = classifyLine(code.line, { ...machine, cwd: at.cwd }, at.depth + 1);
422
+ walk.findings.push(...inner.findings);
423
+ if (!inner.complete)
424
+ walk.complete = false;
425
+ return true;
426
+ }
427
+ walk.findings.push(...code.actions.map(localFinding));
428
+ if (!code.complete)
429
+ walk.complete = false;
430
+ return true;
431
+ }
395
432
  /**
396
433
  * Classify a whole command line run in `machine.cwd`. Vendor commands get the
397
434
  * vendor map's findings; everyday commands get local findings; anything else
@@ -402,6 +439,7 @@ export function classifyLine(command, machine, depth = 0) {
402
439
  if (depth > 4)
403
440
  return { findings: [], complete: false };
404
441
  const { shapes, nested, flags } = splitCommands(command);
442
+ const heredocs = heredocBodies(nested);
405
443
  if (flags.braces || flags.processSubstitution || flags.heredoc || nested.length)
406
444
  walk.complete = false;
407
445
  const cwdAt = [machine.cwd];
@@ -440,6 +478,8 @@ export function classifyLine(command, machine, depth = 0) {
440
478
  cwdAt[shape.depth] = nextDirectory(outcome.target, cwd, machine);
441
479
  continue;
442
480
  }
481
+ if (outcome.kind === "unknown" && ownCode(shape, { cwd, depth, heredocs }, machine, walk))
482
+ continue;
443
483
  vendorFindings(shape, outcome, walk, depth, cwd);
444
484
  }
445
485
  for (const sub of nested) {
@@ -0,0 +1,36 @@
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 { type CommandContext, type LocalAction, type ShellWord } from "./localCommands.js";
20
+ export type CodeFindings = {
21
+ actions: LocalAction[];
22
+ complete: boolean;
23
+ } | {
24
+ line: string;
25
+ } | null;
26
+ /**
27
+ * What a command the everyday table didn't recognize does, when it runs the
28
+ * project's own code. `heredocs` are the bodies this line feeds, by program.
29
+ */
30
+ export declare function projectCode(words: ShellWord[], ctx: CommandContext, heredocs: Map<string, string>): CodeFindings;
31
+ /** Bodies of the heredocs a line feeds, keyed by the program that reads them. */
32
+ export declare function heredocBodies(nested: Array<{
33
+ kind: string;
34
+ text: string;
35
+ target?: string;
36
+ }>): Map<string, string>;
@@ -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
+ }
@@ -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) {
@@ -1,7 +1,9 @@
1
1
  import { activeProfilePath } from "./activeProfile.js";
2
2
  /**
3
3
  * Local credential store for the bridge: ~/.passport/credentials.json.
4
- * PASSPORT_HOME overrides the directory for tests and sandboxes.
4
+ * PASSPORT_HOME overrides the directory for tests and sandboxes. Every write
5
+ * that replaces or removes a profile's credential also drops the hook's
6
+ * cached access token for it (`accessTokenCache.ts`).
5
7
  */
6
8
  export type Profile = {
7
9
  refreshToken: string;