cve-lite-cli 1.39.0 → 1.41.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.
Files changed (82) hide show
  1. package/README.md +28 -22
  2. package/dist/advisory/local-advisory-source.js +9 -5
  3. package/dist/advisory/local-db.js +91 -13
  4. package/dist/advisory/osv-sync.js +187 -56
  5. package/dist/advisory/staging-directory.js +112 -0
  6. package/dist/cli/advisories-sync.js +16 -2
  7. package/dist/cli/args.js +46 -35
  8. package/dist/cli/config.js +4 -1
  9. package/dist/cli/help.js +5 -3
  10. package/dist/cli/validate.js +23 -1
  11. package/dist/constants.js +15 -28
  12. package/dist/index.js +8 -3
  13. package/dist/osv/severity.js +1 -1
  14. package/dist/output/cyclonedx.js +24 -15
  15. package/dist/output/debug.js +68 -18
  16. package/dist/output/formatters.js +35 -7
  17. package/dist/output/html-reporter.js +68 -12
  18. package/dist/output/multi-folder-html-reporter.js +71 -11
  19. package/dist/output/output-dir.js +193 -7
  20. package/dist/output/override-findings-html.js +3 -6
  21. package/dist/output/override-findings-terminal.js +7 -12
  22. package/dist/output/override-fix-command.js +13 -0
  23. package/dist/output/printers.js +27 -12
  24. package/dist/output/sarif.js +168 -57
  25. package/dist/output/sbom-dependency-edges.js +16 -10
  26. package/dist/output/sbom-file.js +14 -6
  27. package/dist/output/scan-json.js +46 -3
  28. package/dist/output/spdx.js +61 -23
  29. package/dist/output/spinner.js +2 -1
  30. package/dist/output/write-outputs.js +143 -41
  31. package/dist/overrides/context-builder.js +23 -70
  32. package/dist/overrides/parsing/registry.js +1 -1
  33. package/dist/parsers/bun-lock.js +1 -2
  34. package/dist/parsers/index.js +22 -1
  35. package/dist/parsers/npm-lock-graph.js +39 -1
  36. package/dist/parsers/package-lock.js +25 -5
  37. package/dist/parsers/pnpm-lock.js +26 -12
  38. package/dist/parsers/utils.js +5 -3
  39. package/dist/parsers/yarn-lock-graph.js +5 -2
  40. package/dist/parsers/yarn-lock.js +1 -2
  41. package/dist/remediation/fix-commands.js +140 -50
  42. package/dist/remediation/npm-registry.js +56 -7
  43. package/dist/remediation/npm-transitive-graph.js +30 -72
  44. package/dist/remediation/npm-transitive-resolution.js +35 -107
  45. package/dist/remediation/parent-candidate-resolver.js +65 -0
  46. package/dist/remediation/parent-upgrade-blockers.js +51 -0
  47. package/dist/remediation/parent-upgrade.js +11 -116
  48. package/dist/remediation/registry-parent-ranges.js +21 -0
  49. package/dist/remediation/transitive-chain-resolver.js +3 -3
  50. package/dist/scan/completeness.js +17 -11
  51. package/dist/scan/multi-folder-scan.js +154 -59
  52. package/dist/scan/override-audit.js +11 -1
  53. package/dist/scan/single-scan.js +123 -67
  54. package/dist/scanner.js +288 -66
  55. package/dist/skills/content.js +12 -12
  56. package/dist/usage/scanner.js +19 -8
  57. package/dist/utils/array.js +11 -3
  58. package/dist/utils/contextual-signals.js +1 -1
  59. package/dist/utils/debug-bundle.js +118 -0
  60. package/dist/utils/debug-project.js +102 -0
  61. package/dist/utils/debug-redaction.js +117 -0
  62. package/dist/utils/effective-options.js +55 -0
  63. package/dist/utils/file.js +2 -1
  64. package/dist/utils/finding.js +1 -1
  65. package/dist/utils/fix-runner.js +98 -15
  66. package/dist/utils/import-type-queries.js +322 -0
  67. package/dist/utils/network.js +14 -10
  68. package/dist/utils/npm-lockfile.js +12 -0
  69. package/dist/utils/osv-fetch.js +70 -0
  70. package/dist/utils/package-identity.js +43 -0
  71. package/dist/utils/package-manager-source.js +24 -0
  72. package/dist/utils/purl.js +37 -0
  73. package/dist/utils/registry-config.js +129 -0
  74. package/dist/utils/severity.js +8 -0
  75. package/dist/utils/string.js +8 -0
  76. package/dist/utils/validate-url.js +4 -4
  77. package/dist/utils/version.js +47 -8
  78. package/dist/utils/versions/osv-range.js +191 -0
  79. package/dist/utils/versions/pep440.js +246 -0
  80. package/dist/utils/versions/scheme.js +10 -0
  81. package/dist/utils/vuln.js +75 -0
  82. package/package.json +3 -2
@@ -1,7 +1,7 @@
1
1
  import { commandPrefix } from "./fix-commands.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
- import { compareVersions, looksLikeVersion, isPreReleaseVersion } from "../utils/version.js";
4
- import { versionSatisfiesRange, highestVersionSatisfyingRange } from "./npm-transitive-resolution.js";
3
+ import { compareVersions, looksLikeVersion, isPreReleaseVersion, satisfiesRange } from "../utils/version.js";
4
+ import { highestVersionSatisfyingRange } from "./npm-transitive-resolution.js";
5
5
  export async function resolveChainFix(finding, installedVersions, packageManager, options) {
6
6
  if (options.offline)
7
7
  return null;
@@ -60,7 +60,7 @@ async function traceChain(deps, remainingPath, vulnerableInstalledVersion, fixed
60
60
  if (remainingPath.length === 1) {
61
61
  // Bottom of chain: nextName IS the vulnerable package.
62
62
  // The range from the parent must exclude the vulnerable installed version.
63
- if (versionSatisfiesRange(vulnerableInstalledVersion, range)) {
63
+ if (satisfiesRange(vulnerableInstalledVersion, range)) {
64
64
  // Range still allows the vulnerable version - this candidate does not fix it.
65
65
  return null;
66
66
  }
@@ -6,23 +6,28 @@ export function getCompletenessImpact(completeness) {
6
6
  hasRemediationGap: diagnostics.some(diagnostic => diagnostic.impact === "remediation"),
7
7
  };
8
8
  }
9
- export function formatDiagnosticMessage(code, count, affectedPackageCount) {
9
+ export function formatDiagnosticMessage(code, count, affectedPackageCount, impact) {
10
10
  switch (code) {
11
11
  case "OSV_DETAIL_TRANSIENT_FAILURE":
12
- return `${count} advisory detail ${pluralize(count, "lookup")} failed with a transient error — re-run to retry.`;
12
+ return `${count} advisory detail ${pluralize(count, "lookup")} failed with a transient error: re-run to retry.`;
13
13
  case "OSV_DETAIL_OFFLINE_MISSING":
14
- return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} missing from the local advisory database — refresh to sync.`;
14
+ return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} missing from the local advisory database: refresh to sync.`;
15
15
  case "OSV_DETAIL_CONFIRMED_MISSING":
16
- return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} confirmed missing from the OSV API — affected findings lack detail data.`;
16
+ return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} confirmed missing from the OSV API: affected findings lack detail data.`;
17
17
  case "PACKUMENT_FETCH_FAILURE":
18
- return `${count} packument ${pluralize(count, "fetch", "fetches")} failed — remediation guidance may be incomplete.`;
18
+ return `${count} packument ${pluralize(count, "fetch", "fetches")} failed: remediation guidance may be incomplete.`;
19
19
  case "REMEDIATION_FAILURE":
20
20
  if (affectedPackageCount !== undefined) {
21
- return `${count} transitive remediation ${pluralize(count, "attempt")} failed across ${affectedPackageCount} ${pluralize(affectedPackageCount, "package")} — some fix recommendations may be missing.`;
21
+ return `${count} transitive remediation ${pluralize(count, "attempt")} failed across ${affectedPackageCount} ${pluralize(affectedPackageCount, "package")}: some fix recommendations may be missing.`;
22
22
  }
23
- return `${count} transitive remediation ${pluralize(count, "attempt")} failed — some fix recommendations may be missing.`;
23
+ return `${count} transitive remediation ${pluralize(count, "attempt")} failed: some fix recommendations may be missing.`;
24
24
  case "CHAIN_RESOLUTION_FAILURE":
25
- return `${count} chain resolution ${pluralize(count, "attempt")} failed — some validated upgrade chains may be missing.`;
25
+ return `${count} chain resolution ${pluralize(count, "attempt")} failed: some validated upgrade chains may be missing.`;
26
+ case "UNREADABLE_PYPI_BOUNDARY":
27
+ if (impact === "remediation") {
28
+ return `${count} ${pluralize(count, "package")} ${pluralize(count, "has", "have")} an unreadable PyPI advisory boundary, so the fix is inconclusive.`;
29
+ }
30
+ return `${count} ${pluralize(count, "package")} ${pluralize(count, "has", "have")} an unreadable PyPI version or advisory boundary, so vulnerability status could not be determined.`;
26
31
  default:
27
32
  return `${count} unknown diagnostic occurred.`;
28
33
  }
@@ -31,17 +36,18 @@ export function aggregateMultiFolderCompleteness(results) {
31
36
  const deduped = new Map();
32
37
  for (const result of results) {
33
38
  for (const diagnostic of result.completeness.diagnostics) {
34
- const existing = deduped.get(diagnostic.code);
39
+ const key = `${diagnostic.code}:${diagnostic.impact}`;
40
+ const existing = deduped.get(key);
35
41
  if (existing) {
36
42
  existing.count += diagnostic.count;
37
43
  if (diagnostic.affectedPackageCount !== undefined) {
38
44
  existing.affectedPackageCount =
39
45
  (existing.affectedPackageCount ?? 0) + diagnostic.affectedPackageCount;
40
46
  }
41
- existing.message = formatDiagnosticMessage(diagnostic.code, existing.count, existing.affectedPackageCount);
47
+ existing.message = formatDiagnosticMessage(diagnostic.code, existing.count, existing.affectedPackageCount, existing.impact);
42
48
  }
43
49
  else {
44
- deduped.set(diagnostic.code, { ...diagnostic });
50
+ deduped.set(key, { ...diagnostic });
45
51
  }
46
52
  }
47
53
  }
@@ -1,17 +1,18 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import process from "node:process";
4
+ import { randomUUID } from "node:crypto";
4
5
  import { EXIT_OK, EXIT_FINDINGS, EXIT_ERROR } from "../types.js";
5
6
  import { loadMultiplePackages } from "../parsers/multi-package.js";
6
7
  import { scanPackages, buildCoverageNotes } from "../scanner.js";
7
8
  import { sortFindingsForOutput, logInfo } from "../output/formatters.js";
8
9
  import { buildMultiFolderScanJson } from "../output/scan-json.js";
9
- import { resolveOutputDir, displayOutputPath } from "../output/output-dir.js";
10
+ import { resolveOutputTarget, displayOutputPath, checkFormatExtensionMismatch, isOutputStdout, drainStdout } from "../output/output-dir.js";
10
11
  import { normalizeSeverity } from "../osv/severity.js";
11
12
  import { selectFindingsForTable } from "../output/finding-display.js";
12
13
  import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
13
14
  import { readDirectDependencyNames, hasOverrideEntries } from "../utils/package-json.js";
14
- import { DEFAULT_SEARCH_DEPTH, OVERRIDES_COMMAND } from "../constants.js";
15
+ import { DEFAULT_SEARCH_DEPTH, OVERRIDES_COMMAND, RATCHET_BASELINE_COMMIT_HINT } from "../constants.js";
15
16
  import { printMultiFolderResults } from "../output/multi-folder-printer.js";
16
17
  import { printOverrideHint } from "../output/printers.js";
17
18
  import { writeMultiFolderHtmlReport } from "../output/multi-folder-html-reporter.js";
@@ -22,11 +23,12 @@ import { NULL_AUDIT_LOG } from "../audit-log/index.js";
22
23
  import { detectDM001 } from "../maintenance/dm001-maintenance-risk.js";
23
24
  import { detectLicenseIssues } from "../licenses/license-check.js";
24
25
  import { renderLicenseFindings } from "../output/license-terminal.js";
25
- import { failingGateSummary } from "../utils/severity.js";
26
+ import { GATE_CLASS_LABELS, failingGateSummary } from "../utils/severity.js";
26
27
  import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "../utils/baseline.js";
27
28
  import { pluralize } from "../utils/string.js";
28
29
  import { aggregateMultiFolderCompleteness, formatDiagnosticMessage, getCompletenessImpact, shouldFailForIncompleteScan, } from "./completeness.js";
29
30
  import { scanProjectForPackageUsage, usageScanTruncationWarning } from "../usage/scanner.js";
31
+ import { isNpmLockSource } from "../utils/package-manager-source.js";
30
32
  export async function runMultiFolderScan(params) {
31
33
  const searchDepth = Math.max(0, Number(params.options.searchDepth || DEFAULT_SEARCH_DEPTH));
32
34
  const folders = loadMultiplePackages(params.projectRoot, !!params.options.prodOnly, searchDepth);
@@ -35,7 +37,7 @@ export async function runMultiFolderScan(params) {
35
37
  for (const { scanInput, subfolder } of folders) {
36
38
  if (scanInput.packages.length === 0)
37
39
  continue;
38
- if (!params.options.json && !params.options.ratchet) {
40
+ if (!params.options.json && !params.options.ratchet && !isOutputStdout(params.options.output)) {
39
41
  process.stdout.write(`\n${chalk.bold.cyan(`📁 ${subfolder}/`)}\n`);
40
42
  }
41
43
  const subfolderAbs = path.join(params.projectRoot, subfolder);
@@ -44,7 +46,7 @@ export async function runMultiFolderScan(params) {
44
46
  directDependencyNames,
45
47
  scanSource: scanInput.source,
46
48
  scanFilePath: scanInput.filePath,
47
- }, undefined, params.fetchImpl);
49
+ }, params.debugLog, params.fetchImpl);
48
50
  // Mirror single-folder scanProject: annotate / filter by source imports per subfolder.
49
51
  let usageTruncated = false;
50
52
  if (params.options.usage) {
@@ -106,6 +108,7 @@ export async function runMultiFolderScan(params) {
106
108
  // left it recording "no advisory source was available" for every folder.
107
109
  const outcome = await runOverrideAudit({
108
110
  projectPath: subfolderAbs,
111
+ scanSource: scanInput?.source ?? null,
109
112
  checkNetwork: !!params.options.checkNetwork,
110
113
  osvUrl: params.options.osvUrl,
111
114
  auditLog: params.auditLog ?? NULL_AUDIT_LOG,
@@ -114,6 +117,8 @@ export async function runMultiFolderScan(params) {
114
117
  });
115
118
  overrideFindings = outcome.findings;
116
119
  overrideSkipped = outcome.skipped;
120
+ if (overrideSkipped.length > 0)
121
+ params.debugLog?.("Rules skipped", { projectPath: subfolderAbs, rules: overrideSkipped });
117
122
  }
118
123
  // Maintenance from the baseline-filtered set. Skipped under --ratchet because
119
124
  // that path always early-exits on CVE save/gate (same as single-folder).
@@ -126,7 +131,7 @@ export async function runMultiFolderScan(params) {
126
131
  let licenseLimitedToDirectOnly = false;
127
132
  if (params.options.checkLicenses && !params.options.ratchet) {
128
133
  const directDeps = scanInput.packages.filter(p => directDependencyNames?.has(p.name));
129
- const isNpm = scanInput.source === "package-lock" || scanInput.source === "npm-shrinkwrap";
134
+ const isNpm = isNpmLockSource(scanInput.source);
130
135
  const licenseResult = await detectLicenseIssues({
131
136
  lockfilePath: scanInput.filePath,
132
137
  directDeps,
@@ -158,24 +163,32 @@ export async function runMultiFolderScan(params) {
158
163
  }
159
164
  /**
160
165
  * Per-subfolder --ratchet: each folder gets its own `.cve-lite/baseline.json`.
161
- * Folders without a baseline are saved; folders with a baseline are gated.
162
- * Exit 1 if any gated folder has findings above its baseline.
166
+ * Folders without a baseline are saved and gated by --fail-on.
167
+ * Folders with a baseline fail only on findings above that baseline.
163
168
  */
164
169
  function handleMultiFolderRatchet(results, projectRoot, options) {
165
170
  let anyNewFindings = false;
171
+ let anyFirstRunGateFailure = false;
166
172
  let hasDetectionGaps = false;
173
+ const baselinesToCommit = [];
174
+ const isStdout = isOutputStdout(options.output);
167
175
  for (const r of results) {
168
- for (const warning of r.scanInput.warnings) {
169
- console.log(chalk.yellow(warning));
176
+ if (!isStdout) {
177
+ for (const warning of r.scanInput.warnings) {
178
+ console.log(chalk.yellow(warning));
179
+ }
170
180
  }
171
181
  const { hasDetectionGap } = getCompletenessImpact(r.completeness);
172
182
  if (hasDetectionGap) {
173
183
  hasDetectionGaps = true;
174
- console.log(chalk.red(`${r.subfolder}/: Scan data is incomplete. Refusing to create or evaluate a baseline from partial detection data.`));
175
- for (const diagnostic of r.completeness.diagnostics) {
176
- if (diagnostic.impact !== "detection")
177
- continue;
178
- console.log(chalk.red(` ${formatDiagnosticMessage(diagnostic.code, diagnostic.count, diagnostic.affectedPackageCount)}`));
184
+ r.acceptedFindings = [];
185
+ if (!isStdout) {
186
+ console.log(chalk.red(`${r.subfolder}/: Scan data is incomplete. Refusing to create or evaluate a baseline from partial detection data.`));
187
+ for (const diagnostic of r.completeness.diagnostics) {
188
+ if (diagnostic.impact !== "detection")
189
+ continue;
190
+ console.log(chalk.red(` ${formatDiagnosticMessage(diagnostic.code, diagnostic.count, diagnostic.affectedPackageCount)}`));
191
+ }
179
192
  }
180
193
  continue;
181
194
  }
@@ -184,40 +197,121 @@ function handleMultiFolderRatchet(results, projectRoot, options) {
184
197
  const outcome = ratchetOutcome(baseline, r.sorted);
185
198
  if (outcome.action === "save") {
186
199
  writeBaseline(subfolderAbs, r.sorted);
200
+ r.acceptedFindings = [];
187
201
  const count = r.sorted.length;
188
- console.log(chalk.green(`✓ ${r.subfolder}/: Baseline saved to .cve-lite/baseline.json with ${count} ${pluralize(count, "finding")}. Future scans will only report findings above this baseline.`));
202
+ if (!isStdout) {
203
+ console.log(chalk.green(`✓ ${r.subfolder}/: Baseline saved to .cve-lite/baseline.json with ${count} ${pluralize(count, "finding")}. Future scans will only report findings above this baseline.`));
204
+ }
205
+ const gateLine = failingGateSummary([{ label: GATE_CLASS_LABELS.vulnerability, findings: r.sorted }], options.failOn);
206
+ if (gateLine) {
207
+ anyFirstRunGateFailure = true;
208
+ if (!options.json && !isStdout) {
209
+ console.log(chalk.red(`${r.subfolder}/: ${gateLine}`));
210
+ }
211
+ }
212
+ if (count > 0) {
213
+ baselinesToCommit.push(`${r.subfolder}/.cve-lite/baseline.json`);
214
+ }
189
215
  continue;
190
216
  }
191
217
  const { newFindings, suppressedCount } = outcome;
192
218
  const suppressedLabel = `${suppressedCount} existing ${pluralize(suppressedCount, "finding")} suppressed`;
219
+ r.acceptedFindings = r.sorted.filter(f => !newFindings.includes(f));
220
+ r.sorted = newFindings;
221
+ r.suppressedCount = suppressedCount;
193
222
  if (newFindings.length === 0) {
194
- console.log(chalk.green(`✓ ${r.subfolder}/: No new findings above baseline - ${suppressedLabel}`));
223
+ if (!isStdout) {
224
+ console.log(chalk.green(`✓ ${r.subfolder}/: No new findings above baseline - ${suppressedLabel}`));
225
+ }
195
226
  continue;
196
227
  }
197
228
  anyNewFindings = true;
198
- console.log(chalk.red(`${r.subfolder}/: ${newFindings.length} new ${pluralize(newFindings.length, "finding")} above baseline - ${suppressedLabel}`));
199
- for (const f of newFindings) {
200
- const ids = f.vulnerabilities.map(v => v.id).join(", ");
201
- console.log(` ${chalk.yellow(f.severity)} ${f.pkg.name}@${f.pkg.version}${ids ? ` (${ids})` : ""}`);
229
+ if (!isStdout) {
230
+ console.log(chalk.red(`${r.subfolder}/: ${newFindings.length} new ${pluralize(newFindings.length, "finding")} above baseline - ${suppressedLabel}`));
231
+ for (const f of newFindings) {
232
+ const ids = f.vulnerabilities.map(v => v.id).join(", ");
233
+ console.log(` ${chalk.yellow(f.severity)} ${f.pkg.name}@${f.pkg.version}${ids ? ` (${ids})` : ""}`);
234
+ }
202
235
  }
203
236
  }
237
+ // One hint for every saved baseline that carries debt, rather than one per folder.
238
+ if (baselinesToCommit.length > 0 && !options.json && !isStdout) {
239
+ console.log(chalk.gray(`Commit ${baselinesToCommit.join(", ")} ${RATCHET_BASELINE_COMMIT_HINT}`));
240
+ }
204
241
  if (hasDetectionGaps) {
205
242
  return EXIT_ERROR;
206
243
  }
207
- if (options.checkOverrides) {
244
+ if (options.checkOverrides && !isStdout) {
208
245
  console.log(chalk.gray(`Note: override hygiene (--check-overrides) is not part of the ratchet baseline; run \`${OVERRIDES_COMMAND}\` to audit overrides.`));
209
246
  }
210
247
  if (anyNewFindings) {
211
- console.log(chalk.gray("To accept these, re-baseline intentionally by deleting the folder's .cve-lite/baseline.json and re-running --ratchet."));
248
+ if (!isStdout) {
249
+ console.log(chalk.gray("To accept these, re-baseline intentionally by deleting the folder's .cve-lite/baseline.json and re-running --ratchet."));
250
+ }
212
251
  return EXIT_FINDINGS;
213
252
  }
214
- return EXIT_OK;
253
+ return anyFirstRunGateFailure ? EXIT_FINDINGS : EXIT_OK;
254
+ }
255
+ async function writeMultiFolderJson(results, projectRoot, options, onScanJsonPath) {
256
+ // Match single-folder writeOutputs: timestamped file in cwd, not stdout dump.
257
+ // Help text and CI both treat --json as "save a JSON file".
258
+ const payload = buildMultiFolderScanJson({
259
+ results,
260
+ projectPath: projectRoot,
261
+ includeOverrides: !!options.checkOverrides,
262
+ includeMaintenance: !!options.checkMaintenance,
263
+ includeLicenses: !!options.checkLicenses,
264
+ // Saved-artifact provenance for the --json payload (#1296).
265
+ provenance: { cliVersion: getCliVersion(), options },
266
+ });
267
+ const target = resolveOutputTarget(options.output);
268
+ const jsonContent = JSON.stringify(payload, null, 2);
269
+ if (target.isStdout) {
270
+ process.stdout.write(jsonContent + "\n");
271
+ await drainStdout();
272
+ }
273
+ else {
274
+ const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
275
+ const jsonFilename = target.isFile && target.filename ? target.filename : `cve-lite-scan-${ts}.json`;
276
+ const jsonOutputPath = path.join(target.dir, jsonFilename);
277
+ if (target.isFile && target.filename) {
278
+ const warning = checkFormatExtensionMismatch(target.filename, "json");
279
+ if (warning) {
280
+ console.warn(chalk.yellow(`Warning: ${warning}`));
281
+ }
282
+ const tempFilename = `.${target.filename}.${randomUUID()}.tmp`;
283
+ const tempPath = path.join(target.dir, tempFilename);
284
+ try {
285
+ fs.writeFileSync(tempPath, jsonContent);
286
+ fs.renameSync(tempPath, jsonOutputPath);
287
+ }
288
+ catch (err) {
289
+ try {
290
+ fs.rmSync(tempPath, { force: true });
291
+ }
292
+ catch { /* best-effort cleanup */ }
293
+ throw err;
294
+ }
295
+ }
296
+ else {
297
+ fs.writeFileSync(jsonOutputPath, jsonContent);
298
+ }
299
+ onScanJsonPath?.(jsonOutputPath);
300
+ console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(displayOutputPath(jsonOutputPath))}`);
301
+ }
215
302
  }
216
303
  export async function handleMultiFolderScan(params) {
217
304
  const auditLog = params.auditLog ?? NULL_AUDIT_LOG;
218
305
  const scanStartedAt = Date.now();
219
306
  const results = await runMultiFolderScan(params);
220
307
  const scanFinishedAt = Date.now();
308
+ params.debugLog?.("Scan finished", {
309
+ packages: results.reduce((sum, result) => sum + result.allPackages.length, 0),
310
+ });
311
+ params.debugLog?.("Findings classified", {
312
+ direct: results.reduce((sum, result) => sum + result.sorted.filter(f => f.relationship === "direct").length, 0),
313
+ transitive: results.reduce((sum, result) => sum + result.sorted.filter(f => f.relationship === "transitive").length, 0),
314
+ });
221
315
  const first = results[0];
222
316
  auditLog.emit({
223
317
  ts: new Date(scanStartedAt).toISOString(),
@@ -237,7 +331,12 @@ export async function handleMultiFolderScan(params) {
237
331
  },
238
332
  });
239
333
  if (results.length === 0) {
240
- console.log(chalk.yellow("No scannable packages found in any subfolder."));
334
+ if (params.options.json) {
335
+ await writeMultiFolderJson(results, params.projectRoot, params.options, params.onScanJsonPath);
336
+ }
337
+ else if (!isOutputStdout(params.options.output)) {
338
+ console.log(chalk.yellow("No scannable packages found in any subfolder."));
339
+ }
241
340
  auditLog.emit({
242
341
  ts: new Date(scanFinishedAt).toISOString(),
243
342
  type: "scan.finished",
@@ -260,8 +359,8 @@ export async function handleMultiFolderScan(params) {
260
359
  });
261
360
  return EXIT_ERROR;
262
361
  }
263
- if (params.options.sarif || params.options.cdx) {
264
- console.error(chalk.yellow("--sarif and --cdx are not yet supported in multi-folder mode."));
362
+ if (params.options.sarif || params.options.cdx || params.options.sbom) {
363
+ console.error(chalk.yellow("--sarif, --cdx and --sbom are not yet supported in multi-folder mode. Run cve-lite . from each subfolder individually, or drop the flag to scan all folders."));
265
364
  auditLog.emit({
266
365
  ts: new Date().toISOString(),
267
366
  type: "scan.finished",
@@ -272,32 +371,20 @@ export async function handleMultiFolderScan(params) {
272
371
  });
273
372
  return EXIT_ERROR;
274
373
  }
374
+ let ratchetExitCode;
275
375
  if (params.options.ratchet) {
276
- return handleMultiFolderRatchet(results, params.projectRoot, params.options);
376
+ ratchetExitCode = handleMultiFolderRatchet(results, params.projectRoot, params.options);
277
377
  }
278
378
  const aggregatedCompleteness = aggregateMultiFolderCompleteness(results);
279
379
  if (params.options.json) {
280
- // Match single-folder writeOutputs: timestamped file in cwd, not stdout dump.
281
- // Help text and CI both treat --json as "save a JSON file".
282
- const payload = buildMultiFolderScanJson({
283
- results,
284
- projectPath: params.projectRoot,
285
- includeOverrides: !!params.options.checkOverrides,
286
- includeMaintenance: !!params.options.checkMaintenance,
287
- includeLicenses: !!params.options.checkLicenses,
288
- });
289
- const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
290
- const jsonFilename = `cve-lite-scan-${ts}.json`;
291
- const jsonOutputPath = path.join(resolveOutputDir(params.options.output), jsonFilename);
292
- fs.writeFileSync(jsonOutputPath, JSON.stringify(payload, null, 2));
293
- console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(displayOutputPath(jsonOutputPath))}`);
380
+ await writeMultiFolderJson(results, params.projectRoot, params.options, params.onScanJsonPath);
294
381
  }
295
- else {
382
+ else if (!params.options.ratchet && !isOutputStdout(params.options.output)) {
296
383
  printMultiFolderResults(results, params.options);
297
384
  if (params.options.checkOverrides) {
298
385
  const { renderOverrideFindings, renderSkippedOverrideRules } = await import("../output/override-findings-terminal.js");
299
386
  for (const r of results) {
300
- process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray("override hygiene")}\n`);
387
+ process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray(GATE_CLASS_LABELS.overrideHygiene)}\n`);
301
388
  console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose, projectPath: path.join(params.projectRoot, r.subfolder), rulesSkipped: r.overrideSkipped.length > 0 }));
302
389
  if (r.overrideSkipped.length > 0) {
303
390
  console.log(renderSkippedOverrideRules(r.overrideSkipped));
@@ -307,7 +394,7 @@ export async function handleMultiFolderScan(params) {
307
394
  if (params.options.checkMaintenance) {
308
395
  const { renderMaintenanceFindings } = await import("../output/maintenance-terminal.js");
309
396
  for (const r of results) {
310
- process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray("maintenance risk")}\n`);
397
+ process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray(GATE_CLASS_LABELS.maintenanceRisk)}\n`);
311
398
  console.log(renderMaintenanceFindings(r.maintenanceFindings, { verbose: !!params.options.verbose }));
312
399
  }
313
400
  }
@@ -336,6 +423,7 @@ export async function handleMultiFolderScan(params) {
336
423
  projectPath: params.projectRoot,
337
424
  cliVersion,
338
425
  autoOpen: !params.options.noOpen,
426
+ options: params.options,
339
427
  // Same undefined-vs-[] contract as single-folder buildReportData: pass the
340
428
  // flag so empty panels render when the check ran with no hits.
341
429
  includeOverrides: !!params.options.checkOverrides,
@@ -350,20 +438,27 @@ export async function handleMultiFolderScan(params) {
350
438
  // Mirror single-folder exit policy in src/scan/single-scan.ts: CVE + override +
351
439
  // maintenance all count toward --fail-on. Without overrides here, multi-folder CI
352
440
  // using --check-overrides --fail-on high would exit 0 despite high OA findings.
353
- const gateLine = failingGateSummary([
354
- { label: "vulnerability", findings: allSorted },
355
- { label: "override hygiene", findings: allOverrideFindings },
356
- { label: "maintenance risk", findings: allMaintenanceFindings },
357
- ], params.options.failOn);
358
- const shouldFail = gateLine !== null;
359
- const incompleteFailure = shouldFailForIncompleteScan(aggregatedCompleteness, params.options.incompletePolicy);
360
- const exitCode = incompleteFailure
361
- ? EXIT_ERROR
362
- : shouldFail
363
- ? EXIT_FINDINGS
364
- : EXIT_OK;
365
- if (gateLine && !params.options.json)
366
- console.log(chalk.red(gateLine));
441
+ let exitCode;
442
+ if (params.options.ratchet) {
443
+ exitCode = ratchetExitCode;
444
+ }
445
+ else {
446
+ const gateLine = failingGateSummary([
447
+ { label: GATE_CLASS_LABELS.vulnerability, findings: allSorted },
448
+ { label: GATE_CLASS_LABELS.overrideHygiene, findings: allOverrideFindings },
449
+ { label: GATE_CLASS_LABELS.maintenanceRisk, findings: allMaintenanceFindings },
450
+ ], params.options.failOn);
451
+ const shouldFail = gateLine !== null;
452
+ const incompleteFailure = shouldFailForIncompleteScan(aggregatedCompleteness, params.options.incompletePolicy);
453
+ exitCode = incompleteFailure
454
+ ? EXIT_ERROR
455
+ : shouldFail
456
+ ? EXIT_FINDINGS
457
+ : EXIT_OK;
458
+ if (gateLine && !params.options.json && !isOutputStdout(params.options.output)) {
459
+ console.log(chalk.red(gateLine));
460
+ }
461
+ }
367
462
  auditLog.emit({
368
463
  ts: new Date(scanFinishedAt).toISOString(),
369
464
  type: "scan.finished",
@@ -5,6 +5,7 @@
5
5
  // while the flag looked wired up.
6
6
  import { audit, buildOverrideContext } from "../overrides/index.js";
7
7
  import { createAdvisorySource } from "../scanner.js";
8
+ import { packageManagerForSource, resolveRegistryConfig } from "../utils/registry-config.js";
8
9
  export async function runOverrideAudit(params) {
9
10
  const ctx = buildOverrideContext(params.projectPath, {
10
11
  auditLog: params.auditLog,
@@ -39,7 +40,16 @@ export async function runOverrideAudit(params) {
39
40
  // or a corporate CA certificate configured through `config set ca-cert` never
40
41
  // reaches them. NODE_EXTRA_CA_CERTS is read only at process start, which is why a
41
42
  // cert-aware fetch is threaded explicitly.
42
- registry: { fetchImpl: params.fetchImpl },
43
+ // OA007 and OA010 ask the registry about versions and advisories, so they have to
44
+ // ask the registry this project installs from. Resolved here rather than taken from
45
+ // the scanner's module state, because the audit runs before the scan configures it.
46
+ registry: {
47
+ fetchImpl: params.fetchImpl,
48
+ baseUrl: resolveRegistryConfig({
49
+ projectPath: params.projectPath,
50
+ packageManager: packageManagerForSource(params.scanSource),
51
+ }).registry,
52
+ },
43
53
  });
44
54
  return { findings: result.findings, skipped: result.skippedDetectors };
45
55
  }