@vaultcompass/conductor 0.4.7 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -7,16 +7,16 @@
7
7
  // decisions be tested without a subprocess.
8
8
  import { Command, CommanderError } from 'commander';
9
9
  import { execFileSync } from 'node:child_process';
10
- import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
10
+ import { readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
11
11
  import path from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
13
  import { EXIT_BLOCKED, EXIT_COULD_NOT_RUN, EXIT_OK } from './exit-codes.js';
14
14
  import { applyInit, planInit, renderInitHuman, renderRevertHuman, revertInit, } from './init.js';
15
15
  import { renderSarif } from './output-sarif.js';
16
- import { renderText } from './output-text.js';
16
+ import { jobLogSummary, renderText } from './output-text.js';
17
17
  import { GATE_ROLES, GATE_STAGES, POLICY_FILE_NAME, PolicyError, applyCliOverrides, loadPolicy, parsePolicy, } from './policy.js';
18
18
  import { refusedTrustBase, runAll } from './run.js';
19
- import { policyDiffers, readPolicyAtRef, refuseTrustBaseRef } from './trust-base.js';
19
+ import { headTreeEqualsBase, policyDiffers, readPolicyAtRef, refuseTrustBaseForPullRequest, refuseTrustBaseRef, } from './trust-base.js';
20
20
  const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
21
21
  const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
22
22
  /**
@@ -39,6 +39,30 @@ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
39
39
  * one line on stderr with no stack and the could-not-run exit code, so
40
40
  * nothing here has to know about either.
41
41
  */
42
+ /**
43
+ * True when `cwd` is itself a `.git` directory (or another directory git
44
+ * manages as one, such as a worktree's own git dir), rather than a working
45
+ * tree with no repository at all.
46
+ *
47
+ * Only consulted once `--show-toplevel` has already failed, so the extra
48
+ * spawn is on an error path already about to fail the whole command, never
49
+ * on the path every ordinary run takes. Both failure shapes exit non-zero,
50
+ * so this is what tells "point conductor at a .git directory" apart from
51
+ * "point conductor at a plain, ungoverned directory" without guessing from
52
+ * the path's spelling.
53
+ */
54
+ function isGitDirectory(cwd) {
55
+ try {
56
+ return (execFileSync('git', ['rev-parse', '--is-inside-git-dir'], {
57
+ cwd,
58
+ encoding: 'utf8',
59
+ stdio: ['ignore', 'pipe', 'ignore'],
60
+ }).trim() === 'true');
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ }
42
66
  function repoRoot(cwd) {
43
67
  try {
44
68
  return execFileSync('git', ['rev-parse', '--show-toplevel'], {
@@ -56,6 +80,10 @@ function repoRoot(cwd) {
56
80
  // git ran and refused. The directory is named because it is the one
57
81
  // thing the reader has to check, and it is the directory they typed
58
82
  // the command in rather than anything internal to this tool.
83
+ if (isGitDirectory(cwd)) {
84
+ throw new Error(`${cwd} is a git directory, not a working tree. Point conductor at the repository's ` +
85
+ 'working tree instead of at its .git directory.');
86
+ }
59
87
  throw new Error(`not a git repository: ${cwd}. conductor anchors every gate at the working-tree ` +
60
88
  'root, so run it inside a checkout.');
61
89
  }
@@ -65,6 +93,54 @@ function repoRoot(cwd) {
65
93
  throw new Error(`git could not be run to find the repository root: ${err.message}`);
66
94
  }
67
95
  }
96
+ /**
97
+ * The repository root for one command, from --project when it was given and
98
+ * from the working directory otherwise (issue #55).
99
+ *
100
+ * --project changes WHERE the repository is, never WHAT is trusted: once
101
+ * resolved, the root it names goes through the exact same discovery as the
102
+ * working directory always has, `repoRoot`'s own `git rev-parse
103
+ * --show-toplevel`, so a subdirectory of a repository resolves to that
104
+ * repository's top level exactly as a bare `conductor init` or `conductor
105
+ * run` from that subdirectory already does. Nothing downstream of this
106
+ * function -- the trust-base checks, the node_modules/.bin skip on a
107
+ * pull-request run, the program-vetting rules -- reads the working directory
108
+ * again; every one of them takes this root explicitly.
109
+ *
110
+ * A relative value resolves against the working directory, never against
111
+ * anything already discovered, so this has to run before any git call. A
112
+ * path that does not exist, is not a directory, or is not inside a git
113
+ * repository is a usage error naming the path, never a silent fall back to
114
+ * the working directory: guessing which repository a scripted caller meant
115
+ * is how a CI job ends up gating the wrong tree while reporting a clean run
116
+ * of nothing.
117
+ */
118
+ function resolveProjectRoot(cwd, project) {
119
+ if (project === undefined) {
120
+ return repoRoot(cwd);
121
+ }
122
+ const resolved = path.resolve(cwd, project);
123
+ let stat;
124
+ try {
125
+ stat = statSync(resolved);
126
+ }
127
+ catch {
128
+ throw new Error(`--project ${project}: no such directory (resolved to ${resolved}).`);
129
+ }
130
+ if (!stat.isDirectory()) {
131
+ throw new Error(`--project ${project}: not a directory (resolved to ${resolved}).`);
132
+ }
133
+ // repoRoot names `resolved` in its own "not a git repository" sentence,
134
+ // which is what makes that refusal name the path here too, without a
135
+ // second, separately-worded check that could drift from the one bare `cwd`
136
+ // already goes through.
137
+ return repoRoot(resolved);
138
+ }
139
+ const PROJECT_OPTION_HELP = 'run against this directory instead of the current one, resolved to its repository root ' +
140
+ 'the same way the current directory already is: a subdirectory resolves to the top of that ' +
141
+ 'repository. Relative values resolve against the current directory. A path that does not ' +
142
+ 'exist, is not a directory, or is not inside a git repository is a usage error (exit 2) ' +
143
+ 'naming the path, never a silent fall back to the current directory.';
68
144
  /**
69
145
  * The process exit code for a run, with --advisory applied.
70
146
  *
@@ -127,11 +203,22 @@ function inventoryFromHead(root, overrides) {
127
203
  return { version: 1, gates: {}, report: { format: 'text' } };
128
204
  }
129
205
  }
130
- function policyForRun(root, trustBase, overrides) {
206
+ function policyForRun(root, trustBase, overrides, githubBaseRef) {
131
207
  if (trustBase === undefined) {
132
208
  return { kind: 'policy', policy: applyCliOverrides(loadPolicy(root), overrides) };
133
209
  }
134
- const refusal = refuseTrustBaseRef(root, trustBase);
210
+ // DEFENCE IN DEPTH, ISSUE #58. action.yml's validate step already refuses
211
+ // an explicit trust-base input outright on a pull_request event; this is
212
+ // the same rule for anyone invoking the CLI directly in CI, bypassing that
213
+ // step. Checked BEFORE refuseTrustBaseRef and deliberately narrower than
214
+ // it: it says nothing about HEAD or about tree equality, only about
215
+ // whether the given ref agrees with origin/<GITHUB_BASE_REF>, which is
216
+ // exactly what the composite action itself always passes. So on an
217
+ // ordinary pull-request run this returns null immediately and
218
+ // refuseTrustBaseRef runs its own checks unchanged, the equal-tree
219
+ // first-parent exception (issue #69/#73) included.
220
+ const pullRequestRefusal = refuseTrustBaseForPullRequest(root, trustBase, githubBaseRef);
221
+ const refusal = pullRequestRefusal ?? refuseTrustBaseRef(root, trustBase);
135
222
  if (refusal !== null) {
136
223
  return {
137
224
  kind: 'refused',
@@ -191,6 +278,12 @@ function policyForRun(root, trustBase, overrides) {
191
278
  ref: trustBase,
192
279
  policyChanged: policyDiffers(baseText, headText),
193
280
  refusal: null,
281
+ // Computed AFTER refuseTrustBaseRef has already returned null, on the
282
+ // one shape that check accepts despite an identical tree: a merge
283
+ // commit whose first parent is this ref (issue #69). runAll reads this
284
+ // to run only the gates whose profile says readsHistory and to report
285
+ // every other enabled gate as tree-unchanged instead of spawning it.
286
+ treeUnchanged: headTreeEqualsBase(root, trustBase),
194
287
  },
195
288
  };
196
289
  }
@@ -244,55 +337,94 @@ export function buildProgram() {
244
337
  .exitOverride();
245
338
  program
246
339
  .command('init')
247
- .description('Write the policy file and one pre-commit hook that runs the commit-stage gates.')
340
+ .description('Write the policy file. Add --hook for a pre-commit hook running the commit-stage gates.')
248
341
  .option('--dry-run', 'print every file that would be written or changed, and write nothing')
249
- .option('--adopt', "replace a gate's own pre-commit hook with the umbrella hook")
342
+ .option('--hook', 'also write a pre-commit hook running the commit-stage gates. Without it, only the policy ' +
343
+ 'file and the manifest are written. .git/hooks is never part of a clone, so a second ' +
344
+ 'clone needs its own "conductor init --hook".')
345
+ .option('--adopt', "replace a gate's own pre-commit hook with the umbrella hook (needs --hook)")
250
346
  .option('--revert', 'remove exactly what a previous init wrote')
251
- .option('--force', 'act on a file that has changed since init wrote it: replace a managed hook somebody has edited, or with --revert remove one and restore any adopted hook')
347
+ .option('--force', 'act on a file that has changed since init wrote it: replace a managed hook somebody has ' +
348
+ 'edited (needs --hook), or with --revert remove one and restore any adopted hook')
252
349
  .option('--json', 'print the result as JSON')
350
+ .option('--project <dir>', PROJECT_OPTION_HELP)
253
351
  .exitOverride()
254
352
  .action((options) => {
255
- const cwd = process.cwd();
256
- const shared = { cwd, pathValue: process.env.PATH ?? '' };
257
- if (options.revert) {
258
- const result = revertInit({
353
+ try {
354
+ // options.project === undefined takes the EXACT path main always
355
+ // did: process.cwd() straight through, with no resolveProjectRoot
356
+ // call at all. planInit and revertInit already do their own
357
+ // repoRootOf(options.cwd) and report a non-repository as a
358
+ // structured conflict (not-a-git-repository, JSON under --json,
359
+ // exit 2 through the ordinary result.ok branch below) rather than
360
+ // throwing, and planInit checks flag-requires-hook (--adopt or
361
+ // --force without --hook) BEFORE it ever asks whether it is in a
362
+ // repository at all. Calling resolveProjectRoot unconditionally
363
+ // here used to short-circuit both of those: it threw its own
364
+ // differently-worded, JSON-less error before planInit ever ran, so
365
+ // a plain "conductor init" outside a repository stopped matching
366
+ // main, and "--adopt" without "--hook" outside a repository
367
+ // reported the wrong conflict. Only an EXPLICIT --project goes
368
+ // through resolveProjectRoot, whose own usage errors (a path that
369
+ // does not exist, is not a directory, or is not inside a git
370
+ // repository) are new behaviour this flag introduces on purpose.
371
+ const cwd = options.project === undefined
372
+ ? process.cwd()
373
+ : resolveProjectRoot(process.cwd(), options.project);
374
+ const shared = { cwd, pathValue: process.env.PATH ?? '' };
375
+ if (options.revert) {
376
+ const result = revertInit({
377
+ ...shared,
378
+ force: Boolean(options.force),
379
+ dryRun: Boolean(options.dryRun),
380
+ });
381
+ const rendered = `${renderRevertHuman(result)}\n`;
382
+ if (options.json) {
383
+ process.stdout.write(`${JSON.stringify(result)}\n`);
384
+ }
385
+ else if (result.ok) {
386
+ process.stdout.write(rendered);
387
+ }
388
+ else {
389
+ // A partial revert left something behind, so it is not success
390
+ // output. Writing it to stdout would let a script pipe it past a
391
+ // reader who needed to see it.
392
+ process.stderr.write(rendered);
393
+ }
394
+ process.exitCode = result.ok ? 0 : EXIT_COULD_NOT_RUN;
395
+ return;
396
+ }
397
+ const initOptions = {
259
398
  ...shared,
260
- force: Boolean(options.force),
261
- dryRun: Boolean(options.dryRun),
262
- });
263
- const rendered = `${renderRevertHuman(result)}\n`;
399
+ ...(options.dryRun === undefined ? {} : { dryRun: options.dryRun }),
400
+ ...(options.hook === undefined ? {} : { hook: options.hook }),
401
+ ...(options.adopt === undefined ? {} : { adopt: options.adopt }),
402
+ ...(options.force === undefined ? {} : { force: options.force }),
403
+ };
404
+ const result = applyInit(planInit(initOptions), initOptions);
264
405
  if (options.json) {
265
406
  process.stdout.write(`${JSON.stringify(result)}\n`);
266
407
  }
267
408
  else if (result.ok) {
268
- process.stdout.write(rendered);
409
+ process.stdout.write(`${renderInitHuman(result)}\n`);
269
410
  }
270
411
  else {
271
- // A partial revert left something behind, so it is not success
272
- // output. Writing it to stdout would let a script pipe it past a
273
- // reader who needed to see it.
274
- process.stderr.write(rendered);
412
+ process.stderr.write(`${renderInitHuman(result)}\n`);
275
413
  }
276
414
  process.exitCode = result.ok ? 0 : EXIT_COULD_NOT_RUN;
277
- return;
278
415
  }
279
- const initOptions = {
280
- ...shared,
281
- ...(options.dryRun === undefined ? {} : { dryRun: options.dryRun }),
282
- ...(options.adopt === undefined ? {} : { adopt: options.adopt }),
283
- ...(options.force === undefined ? {} : { force: options.force }),
284
- };
285
- const result = applyInit(planInit(initOptions), initOptions);
286
- if (options.json) {
287
- process.stdout.write(`${JSON.stringify(result)}\n`);
288
- }
289
- else if (result.ok) {
290
- process.stdout.write(`${renderInitHuman(result)}\n`);
291
- }
292
- else {
293
- process.stderr.write(`${renderInitHuman(result)}\n`);
416
+ catch (err) {
417
+ // planInit, applyInit and revertInit report every ordinary
418
+ // conflict as a structured result rather than throwing, exactly as
419
+ // they did before this flag existed, so in practice only an
420
+ // explicit --project's own usage error reaches here. But this is
421
+ // not narrowed to that: any throw from this block lands here and
422
+ // gets the same one-line, no-stack treatment main's own outer catch
423
+ // gives an uncaught error, which is what this local catch replaces
424
+ // for the init command, the same shape "run"'s own catch below
425
+ // uses for the same kind of failure.
426
+ process.exitCode = fail(`conductor: ${err instanceof Error ? err.message : String(err)}`);
294
427
  }
295
- process.exitCode = result.ok ? 0 : EXIT_COULD_NOT_RUN;
296
428
  });
297
429
  program
298
430
  .command('run')
@@ -308,21 +440,23 @@ export function buildProgram() {
308
440
  .option('--compact-on-refusal', 'when the trust base was refused and no gate ran, print a short body instead of the full refusal report: the version, the verdict, and the refusal reason (with its remedy, when one applies), never the full per-gate report. Built for the pull-request-comment step; every other run is unaffected, whatever --verbose says. Text output only; SARIF is unaffected.')
309
441
  .option('--gate <role>', 'restrict the run to this role; repeatable', (value, previous = []) => [...previous, value])
310
442
  .option('--advisory', 'maps exit 1 (every enabled gate ran and at least one blocked) to exit 0, so a blocking finding never fails this run. A gate that could not run is unaffected and still exits 2: advisory changes what a FINDING does, never what a broken gate does. The report is unchanged and a blocking finding still prints as BLOCKING; only the process exit code and the verdict line, which says findings were advisory, are different.')
443
+ .option('--project <dir>', PROJECT_OPTION_HELP)
311
444
  .exitOverride()
312
445
  .action((options) => {
313
446
  const cwd = process.cwd();
314
447
  try {
315
- // Inside the try, because repoRoot now reports rather than guesses,
316
- // and the catch below is what turns any of its three sentences into
317
- // one line on stderr and the could-not-run exit code.
318
- const root = repoRoot(cwd);
448
+ // Inside the try, because resolveProjectRoot (like repoRoot before
449
+ // it) reports rather than guesses, and the catch below is what turns
450
+ // any of its sentences into one line on stderr and the could-not-run
451
+ // exit code.
452
+ const root = resolveProjectRoot(cwd, options.project);
319
453
  const overrides = {
320
454
  ...(parseRoles(options.gate) === undefined
321
455
  ? {}
322
456
  : { gates: parseRoles(options.gate) }),
323
457
  };
324
458
  const stage = parseStage(options.stage);
325
- const source = policyForRun(root, options.trustBase, overrides);
459
+ const source = policyForRun(root, options.trustBase, overrides, process.env.GITHUB_BASE_REF);
326
460
  const policy = source.kind === 'policy' ? source.policy : source.inventory;
327
461
  const format = parseFormat(options.format ?? policy.report.format);
328
462
  const result = source.kind === 'refused'
@@ -363,9 +497,14 @@ export function buildProgram() {
363
497
  // fail on a missing file with no explanation here.
364
498
  writeFileSync(options.output, rendered);
365
499
  // One line, so a CI job whose only product is an uploaded artifact
366
- // does not read as a job that did nothing.
367
- process.stdout.write(`conductor run: ${result.gates.length} gate(s), ${result.findings.length} finding(s); ` +
368
- `${format} report written to ${options.output}\n`);
500
+ // does not read as a job that did nothing. jobLogSummary carries
501
+ // its own "N gate(s), N finding(s)" on an ordinary run, unchanged,
502
+ // and a refusal sentence instead on a refused run: refusedTrustBase
503
+ // fills result.gates and result.findings with one couldNotRun
504
+ // outcome per enabled gate, so the plain count used to read as
505
+ // "N gate(s), N finding(s)" on a run where nothing ran and nothing
506
+ // was found (issue #46).
507
+ process.stdout.write(`conductor run: ${jobLogSummary(result)}; ${format} report written to ${options.output}\n`);
369
508
  }
370
509
  process.exitCode = applyAdvisory(result.exitCode, advisory);
371
510
  }
package/dist/envelope.js CHANGED
@@ -2,7 +2,7 @@
2
2
  //
3
3
  // This shape is NOT published. SARIF is the family's published finding
4
4
  // format, and every field here exists to make one SARIF mapping decision
5
- // possible without the mapping having to know which of the three gates it
5
+ // possible without the mapping having to know which of the five gates it
6
6
  // is looking at. Keeping it internal is what lets it change when a gate
7
7
  // changes, without anybody's pipeline breaking.
8
8
  //
@@ -5,7 +5,11 @@
5
5
  // third code, 2, for "could not run the checks at all"; the other two have
6
6
  // only 0 and 1, and both use 1 for a rejected config as well as for a real
7
7
  // finding. Taking a maximum would flatten dep-guard's distinction away and
8
- // would call a broken config a policy violation.
8
+ // would call a broken config a policy violation. The two external gates
9
+ // have their own numbers again (gitleaks is handed --exit-code 3 for a
10
+ // leak, osv-scanner uses 128 for nothing to scan); the gate runner reads
11
+ // each child's exit through that product's profile (src/products.ts) before
12
+ // anything reaches this file.
9
13
  //
10
14
  // 2 an enabled gate could not run: its binary is missing, it exited 2,
11
15
  // it was rejected its own config, or its output could not be parsed.
@@ -0,0 +1,54 @@
1
+ import type { ProductProfile } from './products.js';
2
+ export interface MaterializedIgnore {
3
+ /** A directory holding the base's ignore file (or an empty one). */
4
+ dir: string;
5
+ proposal: string | null;
6
+ }
7
+ export interface MaterializedConfig {
8
+ path: string;
9
+ proposal: string | null;
10
+ source: 'base' | 'neutral';
11
+ /** The tool's ignore file, for a tool that auto-loads one; null otherwise. */
12
+ ignore: MaterializedIgnore | null;
13
+ /**
14
+ * The directory to run the tool from. Every relative path the base config
15
+ * names ([extend] path, a baseline) was materialised here from the base
16
+ * ref, so it resolves here and never in the head tree.
17
+ */
18
+ cwd: string;
19
+ /** Head-side differences in those materialised files, one line each. */
20
+ extendProposals: string[];
21
+ }
22
+ /** The base ref's config cannot be materialised; the gate cannot run safely. */
23
+ export declare class ExternalConfigError extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /**
27
+ * The `[extend] path` a gitleaks config names, or null when it names none.
28
+ *
29
+ * A deliberately small reader rather than a TOML parser: it looks for the
30
+ * `path` key inside an `[extend]` table, or a top-level `extend.path`, and
31
+ * accepts a basic or literal string. A config that names an extend path in
32
+ * any other spelling is refused rather than guessed at, because a missed
33
+ * extend is exactly a file read from the head.
34
+ */
35
+ export declare function extendPath(config: string): string | null;
36
+ /**
37
+ * Proposals for config files in subdirectories that differ from the base.
38
+ *
39
+ * osv-scanner loads an osv-scanner.toml from each lockfile's own directory
40
+ * when no --config is given. On a pull request --config is always given, so
41
+ * a nested file added or edited by the pull request has no effect on the run
42
+ * (measured against 2.6.0: a nested file ignoring lodash passes without
43
+ * --config and blocks with it). It is still a change to how the tool behaves
44
+ * once merged, so it is reported the way the root config is.
45
+ */
46
+ export declare function nestedConfigProposals(repoRoot: string, trustBase: string, trackedFiles: readonly string[], configFile: string): string[];
47
+ export declare function materializeExternalConfig(args: {
48
+ repoRoot: string;
49
+ trustBase: string;
50
+ profile: ProductProfile;
51
+ tempRoot: string;
52
+ /** Further relative files the tool will read from its working directory, such as a baseline. */
53
+ extraFiles?: readonly string[];
54
+ }): MaterializedConfig | null;
@@ -0,0 +1,171 @@
1
+ // An external tool's config, read from the base ref on a pull request.
2
+ //
3
+ // Both external tools auto-load a config file out of the tree they scan:
4
+ // gitleaks reads .gitleaks.toml (and .gitleaksignore), osv-scanner reads
5
+ // osv-scanner.toml. On a pull request that tree is the head, so without this
6
+ // a pull request could add an allowlist entry for exactly the secret or the
7
+ // advisory it introduces, and the gate would read that entry and pass. The
8
+ // umbrella's own policy is read from the base ref for the same reason
9
+ // (src/trust-base.ts); this does the same for the files the external tools
10
+ // would otherwise pick up themselves.
11
+ //
12
+ // The umbrella ALWAYS hands over a path on a pull request. When the base has
13
+ // no config, the tool gets a neutral one (gitleaks' defaults, an empty
14
+ // osv-scanner config), because handing it nothing would let it find the
15
+ // head's file on its own. A head-side difference is not an error: it is
16
+ // reported as a proposal, which takes effect once it merges and the base
17
+ // carries it.
18
+ import { spawnSync } from 'node:child_process';
19
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
20
+ import path from 'node:path';
21
+ /** The base ref's config cannot be materialised; the gate cannot run safely. */
22
+ export class ExternalConfigError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = 'ExternalConfigError';
26
+ }
27
+ }
28
+ /**
29
+ * The `[extend] path` a gitleaks config names, or null when it names none.
30
+ *
31
+ * A deliberately small reader rather than a TOML parser: it looks for the
32
+ * `path` key inside an `[extend]` table, or a top-level `extend.path`, and
33
+ * accepts a basic or literal string. A config that names an extend path in
34
+ * any other spelling is refused rather than guessed at, because a missed
35
+ * extend is exactly a file read from the head.
36
+ */
37
+ export function extendPath(config) {
38
+ let inExtend = false;
39
+ let beforeAnyTable = true;
40
+ for (const raw of config.split(/\r?\n/)) {
41
+ const line = raw.replace(/^\s+/, '');
42
+ if (line.startsWith('#') || line === '') {
43
+ continue;
44
+ }
45
+ if (line.startsWith('[')) {
46
+ beforeAnyTable = false;
47
+ inExtend = /^\[\s*extend\s*\]\s*(#.*)?$/.test(line);
48
+ continue;
49
+ }
50
+ const key = inExtend ? /^path\s*=/ : beforeAnyTable ? /^extend\.path\s*=/ : null;
51
+ if (key === null || !key.test(line)) {
52
+ continue;
53
+ }
54
+ const value = /=\s*(?:"([^"\\]*)"|'([^']*)')\s*(#.*)?$/.exec(line);
55
+ if (value === null) {
56
+ throw new ExternalConfigError(`the base ref's config names an [extend] path in a form conductor does not read (${line.trim()}); ` +
57
+ 'write it as a plain quoted string.');
58
+ }
59
+ return value[1] ?? value[2] ?? null;
60
+ }
61
+ return null;
62
+ }
63
+ /** A file's contents at a ref, or null when the ref does not have it. */
64
+ function showAtRef(repoRoot, ref, file) {
65
+ const child = spawnSync('git', ['show', `${ref}:${file}`], { cwd: repoRoot, encoding: 'utf8' });
66
+ return child.status === 0 && typeof child.stdout === 'string' ? child.stdout : null;
67
+ }
68
+ function headCopy(repoRoot, file) {
69
+ const full = path.join(repoRoot, file);
70
+ return existsSync(full) ? readFileSync(full, 'utf8') : null;
71
+ }
72
+ function differs(file, base, head) {
73
+ if (head === null || head === base) {
74
+ return null;
75
+ }
76
+ return `${file} differs from the base ref; the base's copy was used and this change takes effect after merge.`;
77
+ }
78
+ /**
79
+ * Copies one relative file from the base ref into the run directory, at the
80
+ * same relative path, and returns its base contents. Refuses a path that is
81
+ * absolute or climbs out of the run directory, and a file the base ref does
82
+ * not have: either way the tool would read something no ref approved.
83
+ */
84
+ function materializeRelative(repoRoot, trustBase, cwd, file, what) {
85
+ const target = path.resolve(cwd, file);
86
+ if (path.isAbsolute(file) || !target.startsWith(`${cwd}${path.sep}`)) {
87
+ throw new ExternalConfigError(`${what} ${file} is not a path inside the repository, so conductor cannot read it from ` +
88
+ 'the base ref; name it relative to the repository root.');
89
+ }
90
+ const base = showAtRef(repoRoot, trustBase, path.relative(cwd, target).split(path.sep).join('/'));
91
+ if (base === null) {
92
+ throw new ExternalConfigError(`${what} ${file} does not exist on the base ref ${trustBase}, so there is no approved copy ` +
93
+ 'to read; commit it to the base branch or remove the reference.');
94
+ }
95
+ mkdirSync(path.dirname(target), { recursive: true });
96
+ writeFileSync(target, base);
97
+ return base;
98
+ }
99
+ /**
100
+ * Proposals for config files in subdirectories that differ from the base.
101
+ *
102
+ * osv-scanner loads an osv-scanner.toml from each lockfile's own directory
103
+ * when no --config is given. On a pull request --config is always given, so
104
+ * a nested file added or edited by the pull request has no effect on the run
105
+ * (measured against 2.6.0: a nested file ignoring lodash passes without
106
+ * --config and blocks with it). It is still a change to how the tool behaves
107
+ * once merged, so it is reported the way the root config is.
108
+ */
109
+ export function nestedConfigProposals(repoRoot, trustBase, trackedFiles, configFile) {
110
+ return trackedFiles
111
+ .filter((file) => file !== configFile && path.posix.basename(file) === configFile)
112
+ .map((file) => differs(file, showAtRef(repoRoot, trustBase, file), headCopy(repoRoot, file)))
113
+ .filter((proposal) => proposal !== null);
114
+ }
115
+ export function materializeExternalConfig(args) {
116
+ const { repoRoot, trustBase, profile, tempRoot } = args;
117
+ if (profile.configFile === null) {
118
+ return null;
119
+ }
120
+ const base = showAtRef(repoRoot, trustBase, profile.configFile);
121
+ const ext = path.extname(profile.configFile) || '.toml';
122
+ const out = path.join(tempRoot, `${profile.product}-config${ext}`);
123
+ writeFileSync(out, base ?? profile.neutralConfig ?? '');
124
+ // The run directory. gitleaks resolves a relative [extend] path against
125
+ // its working directory, which would otherwise be the head tree: a base
126
+ // config extending gl-extra.toml would read the pull request's copy of it.
127
+ const cwd = path.join(tempRoot, 'cwd');
128
+ mkdirSync(cwd, { recursive: true });
129
+ const extendProposals = [];
130
+ const recordDifference = (file, baseCopy) => {
131
+ const proposal = differs(file, baseCopy, headCopy(repoRoot, file));
132
+ if (proposal !== null) {
133
+ extendProposals.push(proposal);
134
+ }
135
+ };
136
+ if (profile.followsConfigExtend && base !== null) {
137
+ // An extended file may extend again. Followed to a small fixed depth,
138
+ // each hop from the base ref; a longer chain is refused, not truncated.
139
+ let next = extendPath(base);
140
+ for (let depth = 0; next !== null; depth += 1) {
141
+ if (depth >= 4) {
142
+ throw new ExternalConfigError('the base config [extend] chain is longer than four files.');
143
+ }
144
+ const copy = materializeRelative(repoRoot, trustBase, cwd, next, 'the [extend] path');
145
+ recordDifference(next, copy);
146
+ next = extendPath(copy);
147
+ }
148
+ }
149
+ for (const file of args.extraFiles ?? []) {
150
+ recordDifference(file, materializeRelative(repoRoot, trustBase, cwd, file, 'the file'));
151
+ }
152
+ let ignore = null;
153
+ if (profile.ignoreFile !== null) {
154
+ const name = profile.ignoreFile.name;
155
+ const baseIgnore = showAtRef(repoRoot, trustBase, name);
156
+ const dir = path.join(tempRoot, `${profile.product}-ignore`);
157
+ mkdirSync(dir, { recursive: true });
158
+ // An empty file when the base has none, for the reason the neutral
159
+ // config exists: pointing the tool anywhere else lets it find the head's.
160
+ writeFileSync(path.join(dir, name), baseIgnore ?? '');
161
+ ignore = { dir, proposal: differs(name, baseIgnore, headCopy(repoRoot, name)) };
162
+ }
163
+ return {
164
+ path: out,
165
+ proposal: differs(profile.configFile, base, headCopy(repoRoot, profile.configFile)),
166
+ source: base === null ? 'neutral' : 'base',
167
+ ignore,
168
+ cwd,
169
+ extendProposals,
170
+ };
171
+ }
@@ -24,7 +24,19 @@ export type CouldNotRunReason = 'binary-missing' | 'configured-command-missing'
24
24
  * places: one is a packaging problem with the installed gate, and this one
25
25
  * is a pull request choosing the program that judges it.
26
26
  */
27
- | 'gate-program-refused';
27
+ | 'gate-program-refused'
28
+ /**
29
+ * The installed build is older than the oldest version whose command line
30
+ * the umbrella speaks (`minVersion` in src/products.ts). Only the external
31
+ * tools have a floor; nothing was run beyond the version probe.
32
+ */
33
+ | 'gate-version-unsupported'
34
+ /**
35
+ * The gate exited with a verdict but the report file it writes that
36
+ * verdict to is not there. Only a tool whose output is a report file can
37
+ * land here.
38
+ */
39
+ | 'report-missing';
28
40
  export interface CouldNotRun {
29
41
  reason: CouldNotRunReason;
30
42
  detail: string;
@@ -32,7 +44,7 @@ export interface CouldNotRun {
32
44
  /**
33
45
  * The first version of each gate that understands `--trust-base`.
34
46
  *
35
- * A TABLE rather than a boolean, because the three gates get pull-request
47
+ * A TABLE rather than a boolean, because the three family gates got pull-request
36
48
  * mode in three separate releases and the umbrella has to keep working
37
49
  * against every combination in the meantime. A product missing from this
38
50
  * table has no pull-request mode yet and is never handed the flag; a product
@@ -178,6 +190,13 @@ export interface RunGateOptions {
178
190
  * Offered to every child; `decideTrustBase` says which ones can take it.
179
191
  */
180
192
  trustBase?: string;
193
+ /**
194
+ * The directory under which this gate's own working directory is made, for
195
+ * an external tool's report file and materialised config. The runner
196
+ * removes what it made. Defaults to the system temporary directory; tests
197
+ * inject one so they can see that nothing is left behind.
198
+ */
199
+ tempRoot?: string;
181
200
  }
182
201
  /**
183
202
  * A gate that never got as far as being spawned.
@@ -220,6 +239,25 @@ export declare function refuseHeadControlledBinary(repoRoot: string, trustBase:
220
239
  * and keep the run green.
221
240
  */
222
241
  export declare function gateProgramRefused(gate: GatePolicy, trustBase: string, refusal: string, binary: ResolvedBinary): GateOutcome;
242
+ /**
243
+ * Files the runner owns on an external tool's behalf: where gitleaks writes
244
+ * its report, and the config materialised from the base ref on a pull
245
+ * request (src/external-config.ts).
246
+ */
247
+ export interface ExternalArgs {
248
+ reportPath?: string;
249
+ configPath?: string;
250
+ /** Where the tool's ignore file was materialised (gitleaks only). */
251
+ ignorePath?: string;
252
+ /**
253
+ * What gitleaks scans, when not the working tree. On a pull request it is
254
+ * the repository's git directory: the same history, with no head-written
255
+ * .gitleaksignore at its root for gitleaks to load on its own.
256
+ */
257
+ scanRoot?: string;
258
+ /** The tracked lockfiles osv-scanner is handed, repository-relative. */
259
+ lockfiles?: readonly string[];
260
+ }
223
261
  /**
224
262
  * The arguments the umbrella adds, per product.
225
263
  *
@@ -241,7 +279,9 @@ export declare function gateArgs(gate: GatePolicy, staged: boolean, intent: Inte
241
279
  * `decideTrustBase`; nothing here re-decides it, so a gate that cannot take
242
280
  * the flag is never handed one by a second opinion written in this switch.
243
281
  */
244
- trustBase?: string): string[];
282
+ trustBase?: string,
283
+ /** Paths the runner owns for an external tool; the npm gates ignore them. */
284
+ external?: ExternalArgs): string[];
245
285
  /**
246
286
  * Runs one gate. TOTAL: this never throws.
247
287
  *