cve-lite-cli 1.38.0 → 1.40.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 (43) hide show
  1. package/README.md +11 -11
  2. package/dist/cli/args.js +1 -1
  3. package/dist/cli/help.js +1 -0
  4. package/dist/constants.js +4 -3
  5. package/dist/osv/severity.js +1 -1
  6. package/dist/output/cyclonedx.js +1 -1
  7. package/dist/output/formatters.js +2 -2
  8. package/dist/output/html-reporter.js +14 -8
  9. package/dist/output/multi-folder-html-reporter.js +12 -8
  10. package/dist/output/override-findings-html.js +3 -6
  11. package/dist/output/override-findings-terminal.js +7 -12
  12. package/dist/output/override-fix-command.js +13 -0
  13. package/dist/output/printers.js +11 -7
  14. package/dist/output/sarif.js +39 -11
  15. package/dist/output/scan-json.js +26 -1
  16. package/dist/output/write-outputs.js +13 -1
  17. package/dist/overrides/context-builder.js +33 -5
  18. package/dist/overrides/detectors/oa005-nested-ineffective.js +50 -2
  19. package/dist/overrides/parsing/registry.js +1 -1
  20. package/dist/parsers/pnpm-lock.js +23 -10
  21. package/dist/remediation/fix-commands.js +36 -7
  22. package/dist/remediation/npm-registry.js +56 -7
  23. package/dist/remediation/npm-transitive-resolution.js +11 -30
  24. package/dist/remediation/parent-candidate-resolver.js +65 -0
  25. package/dist/remediation/parent-upgrade.js +6 -37
  26. package/dist/scan/completeness.js +7 -7
  27. package/dist/scan/multi-folder-scan.js +28 -8
  28. package/dist/scan/override-audit.js +11 -1
  29. package/dist/scan/single-scan.js +86 -45
  30. package/dist/scanner.js +32 -9
  31. package/dist/skills/content.js +12 -12
  32. package/dist/utils/contextual-signals.js +1 -1
  33. package/dist/utils/effective-options.js +55 -0
  34. package/dist/utils/finding.js +1 -1
  35. package/dist/utils/fix-runner.js +3 -2
  36. package/dist/utils/network.js +1 -1
  37. package/dist/utils/node-builtins.js +32 -0
  38. package/dist/utils/registry-config.js +144 -0
  39. package/dist/utils/severity.js +8 -0
  40. package/dist/utils/validate-url.js +3 -3
  41. package/dist/utils/version.js +21 -1
  42. package/dist/utils/vuln.js +75 -0
  43. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
3
  import { findPackageAlongPath } from "./package-path-lookup.js";
4
+ import { resolveDirectParentContext } from "./parent-candidate-resolver.js";
4
5
  export function isVerifiedUpgrade(confidence) {
5
6
  return confidence === "verified";
6
7
  }
@@ -14,8 +15,11 @@ export async function resolveRecommendedParentUpgrade(finding, packages, directD
14
15
  const viaPath = getBestPath(finding);
15
16
  if (!viaPath || viaPath.length < 3)
16
17
  return null;
17
- const packagesByName = new Map(packages.map(p => [p.name, p]));
18
- const directParentContext = resolveDirectParentContext(viaPath, packages, directDependencyNames, packagesByName);
18
+ const directParentContext = resolveDirectParentContext({
19
+ viaPath,
20
+ packages,
21
+ directDependencyNames,
22
+ });
19
23
  if (!directParentContext)
20
24
  return null;
21
25
  const { directParentName, immediateParentName, directParent } = directParentContext;
@@ -56,41 +60,6 @@ function getBestPath(finding) {
56
60
  return null;
57
61
  return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
58
62
  }
59
- function findDirectDependency(packages, name, directDependencyNames, packagesByName) {
60
- if (directDependencyNames?.has(name)) {
61
- return packagesByName.get(name) ?? null;
62
- }
63
- for (const pkg of packages) {
64
- if (pkg.name !== name)
65
- continue;
66
- const paths = pkg.paths ?? [];
67
- if (paths.some(path => path.at(-1) === name && path.length >= 2)) {
68
- return pkg;
69
- }
70
- }
71
- return null;
72
- }
73
- function resolveDirectParentContext(viaPath, packages, directDependencyNames, packagesByName) {
74
- const immediateParentName = viaPath[viaPath.length - 2];
75
- const candidateSegments = viaPath.slice(1, -1);
76
- const directParentCandidates = directDependencyNames
77
- ? candidateSegments.filter(segment => directDependencyNames.has(segment))
78
- : [viaPath[1]].filter(Boolean);
79
- const directParentName = directParentCandidates[0];
80
- if (!directParentName)
81
- return null;
82
- // Path-based lookup disambiguates when the same package name is installed at
83
- // multiple versions (e.g. eslint@9.36.0 at root AND eslint@6.14.0 nested).
84
- // A name-keyed Map (last-write-wins) would return an arbitrary version, making
85
- // directParentVersion wrong and potentially producing downgrade suggestions.
86
- const directParentIdx = viaPath.indexOf(directParentName);
87
- const directParentPathPrefix = viaPath.slice(0, directParentIdx + 1);
88
- const directParent = findPackageAlongPath(packages, directParentName, directParentPathPrefix) ??
89
- findDirectDependency(packages, directParentName, directDependencyNames, packagesByName);
90
- if (!directParent)
91
- return null;
92
- return { directParentName, immediateParentName, directParent };
93
- }
94
63
  function findPackageVersion(packages, name, pathPrefix) {
95
64
  return findPackageAlongPath(packages, name, pathPrefix)?.version ?? null;
96
65
  }
@@ -9,20 +9,20 @@ export function getCompletenessImpact(completeness) {
9
9
  export function formatDiagnosticMessage(code, count, affectedPackageCount) {
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
26
  default:
27
27
  return `${count} unknown diagnostic occurred.`;
28
28
  }
@@ -11,7 +11,7 @@ import { normalizeSeverity } from "../osv/severity.js";
11
11
  import { selectFindingsForTable } from "../output/finding-display.js";
12
12
  import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
13
13
  import { readDirectDependencyNames, hasOverrideEntries } from "../utils/package-json.js";
14
- import { DEFAULT_SEARCH_DEPTH, OVERRIDES_COMMAND } from "../constants.js";
14
+ import { DEFAULT_SEARCH_DEPTH, OVERRIDES_COMMAND, RATCHET_BASELINE_COMMIT_HINT } from "../constants.js";
15
15
  import { printMultiFolderResults } from "../output/multi-folder-printer.js";
16
16
  import { printOverrideHint } from "../output/printers.js";
17
17
  import { writeMultiFolderHtmlReport } from "../output/multi-folder-html-reporter.js";
@@ -22,7 +22,7 @@ import { NULL_AUDIT_LOG } from "../audit-log/index.js";
22
22
  import { detectDM001 } from "../maintenance/dm001-maintenance-risk.js";
23
23
  import { detectLicenseIssues } from "../licenses/license-check.js";
24
24
  import { renderLicenseFindings } from "../output/license-terminal.js";
25
- import { failingGateSummary } from "../utils/severity.js";
25
+ import { GATE_CLASS_LABELS, failingGateSummary } from "../utils/severity.js";
26
26
  import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "../utils/baseline.js";
27
27
  import { pluralize } from "../utils/string.js";
28
28
  import { aggregateMultiFolderCompleteness, formatDiagnosticMessage, getCompletenessImpact, shouldFailForIncompleteScan, } from "./completeness.js";
@@ -106,6 +106,7 @@ export async function runMultiFolderScan(params) {
106
106
  // left it recording "no advisory source was available" for every folder.
107
107
  const outcome = await runOverrideAudit({
108
108
  projectPath: subfolderAbs,
109
+ scanSource: scanInput?.source ?? null,
109
110
  checkNetwork: !!params.options.checkNetwork,
110
111
  osvUrl: params.options.osvUrl,
111
112
  auditLog: params.auditLog ?? NULL_AUDIT_LOG,
@@ -158,12 +159,14 @@ export async function runMultiFolderScan(params) {
158
159
  }
159
160
  /**
160
161
  * 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.
162
+ * Folders without a baseline are saved and gated by --fail-on.
163
+ * Folders with a baseline fail only on findings above that baseline.
163
164
  */
164
165
  function handleMultiFolderRatchet(results, projectRoot, options) {
165
166
  let anyNewFindings = false;
167
+ let anyFirstRunGateFailure = false;
166
168
  let hasDetectionGaps = false;
169
+ const baselinesToCommit = [];
167
170
  for (const r of results) {
168
171
  for (const warning of r.scanInput.warnings) {
169
172
  console.log(chalk.yellow(warning));
@@ -186,6 +189,16 @@ function handleMultiFolderRatchet(results, projectRoot, options) {
186
189
  writeBaseline(subfolderAbs, r.sorted);
187
190
  const count = r.sorted.length;
188
191
  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.`));
192
+ const gateLine = failingGateSummary([{ label: GATE_CLASS_LABELS.vulnerability, findings: r.sorted }], options.failOn);
193
+ if (gateLine) {
194
+ anyFirstRunGateFailure = true;
195
+ if (!options.json) {
196
+ console.log(chalk.red(`${r.subfolder}/: ${gateLine}`));
197
+ }
198
+ }
199
+ if (count > 0) {
200
+ baselinesToCommit.push(`${r.subfolder}/.cve-lite/baseline.json`);
201
+ }
189
202
  continue;
190
203
  }
191
204
  const { newFindings, suppressedCount } = outcome;
@@ -201,6 +214,10 @@ function handleMultiFolderRatchet(results, projectRoot, options) {
201
214
  console.log(` ${chalk.yellow(f.severity)} ${f.pkg.name}@${f.pkg.version}${ids ? ` (${ids})` : ""}`);
202
215
  }
203
216
  }
217
+ // One hint for every saved baseline that carries debt, rather than one per folder.
218
+ if (baselinesToCommit.length > 0 && !options.json) {
219
+ console.log(chalk.gray(`Commit ${baselinesToCommit.join(", ")} ${RATCHET_BASELINE_COMMIT_HINT}`));
220
+ }
204
221
  if (hasDetectionGaps) {
205
222
  return EXIT_ERROR;
206
223
  }
@@ -211,7 +228,7 @@ function handleMultiFolderRatchet(results, projectRoot, options) {
211
228
  console.log(chalk.gray("To accept these, re-baseline intentionally by deleting the folder's .cve-lite/baseline.json and re-running --ratchet."));
212
229
  return EXIT_FINDINGS;
213
230
  }
214
- return EXIT_OK;
231
+ return anyFirstRunGateFailure ? EXIT_FINDINGS : EXIT_OK;
215
232
  }
216
233
  export async function handleMultiFolderScan(params) {
217
234
  const auditLog = params.auditLog ?? NULL_AUDIT_LOG;
@@ -285,6 +302,8 @@ export async function handleMultiFolderScan(params) {
285
302
  includeOverrides: !!params.options.checkOverrides,
286
303
  includeMaintenance: !!params.options.checkMaintenance,
287
304
  includeLicenses: !!params.options.checkLicenses,
305
+ // Saved-artifact provenance for the --json payload (#1296).
306
+ provenance: { cliVersion: getCliVersion(), options: params.options },
288
307
  });
289
308
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
290
309
  const jsonFilename = `cve-lite-scan-${ts}.json`;
@@ -336,6 +355,7 @@ export async function handleMultiFolderScan(params) {
336
355
  projectPath: params.projectRoot,
337
356
  cliVersion,
338
357
  autoOpen: !params.options.noOpen,
358
+ options: params.options,
339
359
  // Same undefined-vs-[] contract as single-folder buildReportData: pass the
340
360
  // flag so empty panels render when the check ran with no hits.
341
361
  includeOverrides: !!params.options.checkOverrides,
@@ -351,9 +371,9 @@ export async function handleMultiFolderScan(params) {
351
371
  // maintenance all count toward --fail-on. Without overrides here, multi-folder CI
352
372
  // using --check-overrides --fail-on high would exit 0 despite high OA findings.
353
373
  const gateLine = failingGateSummary([
354
- { label: "vulnerability", findings: allSorted },
355
- { label: "override hygiene", findings: allOverrideFindings },
356
- { label: "maintenance risk", findings: allMaintenanceFindings },
374
+ { label: GATE_CLASS_LABELS.vulnerability, findings: allSorted },
375
+ { label: GATE_CLASS_LABELS.overrideHygiene, findings: allOverrideFindings },
376
+ { label: GATE_CLASS_LABELS.maintenanceRisk, findings: allMaintenanceFindings },
357
377
  ], params.options.failOn);
358
378
  const shouldFail = gateLine !== null;
359
379
  const incompleteFailure = shouldFailForIncompleteScan(aggregatedCompleteness, params.options.incompletePolicy);
@@ -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
  }
@@ -2,7 +2,7 @@ import path from "node:path";
2
2
  import { loadPackages, buildNoPackagesMessage } from "../parsers/index.js";
3
3
  import { scanPackages, buildCoverageNotes, createAdvisorySource } from "../scanner.js";
4
4
  import { normalizeSeverity } from "../osv/severity.js";
5
- import { OVERRIDES_COMMAND } from "../constants.js";
5
+ import { OVERRIDES_COMMAND, RATCHET_BASELINE_COMMIT_HINT } from "../constants.js";
6
6
  import { chalk } from "../utils/chalk.js";
7
7
  import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
8
8
  import { scanProjectForPackageUsage, usageScanTruncationWarning } from "../usage/scanner.js";
@@ -11,7 +11,7 @@ import { formatAdvisoryDbFreshness } from "../utils/time.js";
11
11
  import { pluralize } from "../utils/string.js";
12
12
  import { EXIT_ERROR } from "../types.js";
13
13
  import { formatAdvisorySourceLine, logInfo, logWarn, printCacheSummary, sortFindingsForOutput, } from "../output/formatters.js";
14
- import { countBySeverity, failingGateSummary } from "../utils/severity.js";
14
+ import { GATE_CLASS_LABELS, countBySeverity, failingGateSummary } from "../utils/severity.js";
15
15
  import { buildReportData, writeHtmlReport } from "../output/html-reporter.js";
16
16
  import { buildScanJson } from "../output/scan-json.js";
17
17
  import { writeOutputs } from "../output/write-outputs.js";
@@ -29,6 +29,7 @@ import { buildFixResultAppliedEntries, createPullRequestForFixes, } from "../uti
29
29
  import { buildCveFixAppliedEvent } from "../audit-log/events.js";
30
30
  import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "../utils/baseline.js";
31
31
  import { formatDiagnosticMessage, getCompletenessImpact, shouldFailForIncompleteScan } from "./completeness.js";
32
+ import { packageManagerForSource, resolveRegistryConfig } from "../utils/registry-config.js";
32
33
  export async function handleSingleFolderScan(params) {
33
34
  const { projectPath, projectArg, batchSize, searchDepth, options, debugLog, fetchImpl, auditLog, scanStartedAt, cliVersion, } = params;
34
35
  let advisorySourceLine = "";
@@ -82,6 +83,15 @@ export async function handleSingleFolderScan(params) {
82
83
  }
83
84
  let scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
84
85
  let packages = scanInput.packages;
86
+ // Reported only when the project configured one, so an unconfigured scan says nothing
87
+ // new. An adopter whose results differ from public npm can then see why without asking.
88
+ const reportedRegistry = resolveRegistryConfig({
89
+ projectPath,
90
+ packageManager: packageManagerForSource(scanInput.source),
91
+ });
92
+ if (reportedRegistry.sourceFile && !options.json && !options.ratchet) {
93
+ console.log(`${chalk.gray("Package registry:")} ${reportedRegistry.registry} ${chalk.gray(`(from ${reportedRegistry.sourceFile})`)}`);
94
+ }
85
95
  if (scanInput.filePath) {
86
96
  debugLog("Lockfile selected", {
87
97
  source: scanInput.source,
@@ -156,6 +166,7 @@ export async function handleSingleFolderScan(params) {
156
166
  if (options.checkOverrides && !options.ratchet) {
157
167
  const outcome = await runOverrideAudit({
158
168
  projectPath,
169
+ scanSource: scanInput.source,
159
170
  checkNetwork: !!options.checkNetwork,
160
171
  osvUrl: options.osvUrl,
161
172
  auditLog,
@@ -337,6 +348,44 @@ export async function handleSingleFolderScan(params) {
337
348
  // existing baseline, GATE instead of re-saving - fail on findings not in the
338
349
  // baseline. Re-saving here would silently absorb a new vulnerability into a
339
350
  // fresh baseline, so a ratcheted CI job could never fail on a regression.
351
+ // Every --ratchet exit used to return before the single writeOutputs call below, so a
352
+ // ratchet run wrote no --json and no --sarif file on ANY path: first run, fully suppressed,
353
+ // new-findings-above-baseline, and the incomplete-detection refusal alike. Nobody combining --ratchet with either flag has
354
+ // ever received an artefact. #1314 did not cause that; it made the first-run path exit 1,
355
+ // which turned a silent gap into a red build with nothing to attach (#1332, #1315).
356
+ //
357
+ // This writes from inside the ratchet block rather than falling through, deliberately:
358
+ // the code between here and that call re-applies the baseline filter for non-ratchet runs,
359
+ // so falling through would filter an already-filtered set.
360
+ const finishRatchetRun = async (reported, accepted, exitCode) => {
361
+ await writeOutputs(options, {
362
+ registry: reportedRegistry,
363
+ sorted: reported,
364
+ acceptedFindings: accepted,
365
+ allPackages: scanState.allPackages,
366
+ suggestedFixCommands: scanState.suggestedFixCommands,
367
+ coverage: scanState.coverage,
368
+ minSeverity: scanState.minSeverity,
369
+ tableFindings: scanState.tableFindings,
370
+ completeness: scanState.completeness,
371
+ // A ratchet run does not audit overrides, so these stay absent rather than empty:
372
+ // absent means "never audited", which is the distinction #1222 established.
373
+ overrideFindings: [],
374
+ overrideSkipped: undefined,
375
+ maintenanceFindings: [],
376
+ licenseFindings: [],
377
+ licenseLimitedToDirectOnly: false,
378
+ }, scanInput, projectPath);
379
+ auditLog.emit({
380
+ ts: new Date().toISOString(),
381
+ type: "scan.finished",
382
+ schemaVersion: 1,
383
+ durationMs: Date.now() - scanStartTime,
384
+ findingsCount: reported.length,
385
+ exitCode,
386
+ });
387
+ return exitCode;
388
+ };
340
389
  if (options.ratchet) {
341
390
  const { hasDetectionGap } = getCompletenessImpact(scanState.completeness);
342
391
  if (hasDetectionGap) {
@@ -346,15 +395,11 @@ export async function handleSingleFolderScan(params) {
346
395
  continue;
347
396
  console.log(chalk.red(` ${formatDiagnosticMessage(diagnostic.code, diagnostic.count, diagnostic.affectedPackageCount)}`));
348
397
  }
349
- auditLog.emit({
350
- ts: new Date().toISOString(),
351
- type: "scan.finished",
352
- schemaVersion: 1,
353
- durationMs: Date.now() - scanStartTime,
354
- findingsCount: scanState.sorted.length,
355
- exitCode: EXIT_ERROR,
356
- });
357
- return EXIT_ERROR;
398
+ // Writes the requested artefact too, and accepts nothing: the baseline was never
399
+ // evaluated, so claiming anything is accepted would be a lie. This is the path where
400
+ // an artefact matters most, since the build goes red and the diagnostics are the only
401
+ // thing that explains why. A non-ratchet scan with the same gap already writes one.
402
+ return finishRatchetRun(scanState.sorted, [], EXIT_ERROR);
358
403
  }
359
404
  const outcome = ratchetOutcome(baseline, scanState.sorted);
360
405
  if (outcome.action === "save") {
@@ -364,29 +409,25 @@ export async function handleSingleFolderScan(params) {
364
409
  if (options.checkOverrides) {
365
410
  console.log(chalk.gray(`Note: override hygiene (--check-overrides) is not part of the ratchet baseline; run \`${OVERRIDES_COMMAND}\` to audit overrides.`));
366
411
  }
367
- auditLog.emit({
368
- ts: new Date().toISOString(),
369
- type: "scan.finished",
370
- schemaVersion: 1,
371
- durationMs: Date.now() - scanStartTime,
372
- findingsCount: scanState.sorted.length,
373
- exitCode: 0,
374
- });
375
- return 0;
412
+ // A missing baseline accepts no debt, including on fresh CI checkouts.
413
+ const gateLine = failingGateSummary([{ label: GATE_CLASS_LABELS.vulnerability, findings: scanState.sorted }], options.failOn);
414
+ if (gateLine && !options.json && !options.fix) {
415
+ console.log(chalk.red(gateLine));
416
+ }
417
+ if (count > 0 && !options.json) {
418
+ console.log(chalk.gray(`Commit .cve-lite/baseline.json ${RATCHET_BASELINE_COMMIT_HINT}`));
419
+ }
420
+ const exitCode = gateLine && !options.fix ? 1 : 0;
421
+ // A first run accepts nothing, so every finding is reported and none is accepted.
422
+ return finishRatchetRun(scanState.sorted, [], exitCode);
376
423
  }
377
424
  const { newFindings, suppressedCount: sc } = outcome;
378
425
  const suppressedLabel = `${sc} existing ${sc === 1 ? "finding" : "findings"} suppressed`;
379
426
  if (newFindings.length === 0) {
380
427
  console.log(chalk.green(`No new findings above baseline - ${suppressedLabel}`));
381
- auditLog.emit({
382
- ts: new Date().toISOString(),
383
- type: "scan.finished",
384
- schemaVersion: 1,
385
- durationMs: Date.now() - scanStartTime,
386
- findingsCount: scanState.sorted.length,
387
- exitCode: 0,
388
- });
389
- return 0;
428
+ // Nothing actionable, so the artefact carries an empty finding set and records what the
429
+ // baseline is holding. Writing no file at all is what made accepted debt look resolved.
430
+ return finishRatchetRun([], scanState.sorted, 0);
390
431
  }
391
432
  console.log(chalk.red(`${newFindings.length} new ${newFindings.length === 1 ? "finding" : "findings"} above baseline - ${suppressedLabel}`));
392
433
  for (const f of newFindings) {
@@ -394,15 +435,10 @@ export async function handleSingleFolderScan(params) {
394
435
  console.log(` ${chalk.yellow(f.severity)} ${f.pkg.name}@${f.pkg.version}${ids ? ` (${ids})` : ""}`);
395
436
  }
396
437
  console.log(chalk.gray("To accept these, re-baseline intentionally by deleting .cve-lite/baseline.json and re-running --ratchet."));
397
- auditLog.emit({
398
- ts: new Date().toISOString(),
399
- type: "scan.finished",
400
- schemaVersion: 1,
401
- durationMs: Date.now() - scanStartTime,
402
- findingsCount: newFindings.length,
403
- exitCode: 1,
404
- });
405
- return 1;
438
+ // The build fails here because something new appeared, which is exactly the run where a
439
+ // machine-readable artefact matters most, and it produced none.
440
+ const acceptedHere = scanState.sorted.filter(f => !newFindings.includes(f));
441
+ return finishRatchetRun(newFindings, acceptedHere, 1);
406
442
  }
407
443
  // auto-apply baseline if it exists - filter before output
408
444
  if (baseline) {
@@ -437,6 +473,7 @@ export async function handleSingleFolderScan(params) {
437
473
  licenseLimitedToDirectOnly = licenseResult.limitedToDirectOnly;
438
474
  }
439
475
  await writeOutputs(options, {
476
+ registry: reportedRegistry,
440
477
  sorted: scanState.sorted,
441
478
  allPackages: scanState.allPackages,
442
479
  suggestedFixCommands: scanState.suggestedFixCommands,
@@ -522,6 +559,7 @@ export async function handleSingleFolderScan(params) {
522
559
  if (options.report) {
523
560
  const outputDir = path.resolve(typeof options.report === "string" ? options.report : "./cve-report");
524
561
  const reportData = buildReportData({
562
+ registry: { registry: reportedRegistry.registry, sourceFile: reportedRegistry.sourceFile },
525
563
  projectPath,
526
564
  cliVersion,
527
565
  packageManager: scanInput.source,
@@ -542,13 +580,15 @@ export async function handleSingleFolderScan(params) {
542
580
  licenseLimitedToDirectOnly: options.checkLicenses ? licenseLimitedToDirectOnly : undefined,
543
581
  completeness: scanState.completeness,
544
582
  });
545
- // report.json follows the --json schema, plus scannedAt/cliVersion for a
546
- // saved artifact and per-finding riskSummary/nextAction (stdout --json
583
+ // report.json follows the --json schema, plus saved-artifact provenance
584
+ // (cliVersion/scannedAt/effectiveOptions via the builders, #1296),
585
+ // lockfileSource, and per-finding riskSummary/nextAction (stdout --json
547
586
  // stays unchanged via buildScanJson alone).
548
587
  const jsonPayload = {
549
588
  ...buildScanJson({
550
589
  projectPath,
551
590
  scanInput,
591
+ registry: reportedRegistry,
552
592
  findings: scanState.sorted,
553
593
  suggestedFixCommands: scanState.suggestedFixCommands,
554
594
  coverage: scanState.coverage,
@@ -561,9 +601,10 @@ export async function handleSingleFolderScan(params) {
561
601
  maintenanceFindings,
562
602
  licenseFindings,
563
603
  licenseLimitedToDirectOnly,
604
+ // Saved-artifact provenance for report.json (#1296).
605
+ provenance: { cliVersion, options },
564
606
  }),
565
- scannedAt: reportData.scannedAt,
566
- cliVersion: reportData.cliVersion,
607
+ lockfileSource: reportData.lockfileSource,
567
608
  findings: reportData.findings,
568
609
  };
569
610
  const { reportPath } = await writeHtmlReport({
@@ -594,9 +635,9 @@ export async function handleSingleFolderScan(params) {
594
635
  // The gate and the line that explains it come from one call, so the exit code
595
636
  // and the printed reason cannot drift apart.
596
637
  const gateLine = failingGateSummary([
597
- { label: "vulnerability", findings: scanState.sorted },
598
- { label: "override hygiene", findings: overrideFindings },
599
- { label: "maintenance risk", findings: maintenanceFindings },
638
+ { label: GATE_CLASS_LABELS.vulnerability, findings: scanState.sorted },
639
+ { label: GATE_CLASS_LABELS.overrideHygiene, findings: overrideFindings },
640
+ { label: GATE_CLASS_LABELS.maintenanceRisk, findings: maintenanceFindings },
600
641
  ], options.failOn);
601
642
  const shouldFail = gateLine !== null;
602
643
  if (gateLine && !options.json && !options.fix)
package/dist/scanner.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { fetchEpssScores } from "./epss/client.js";
2
2
  import { chunk, runWithConcurrency } from "./utils/array.js";
3
3
  import { isPrivateRegistrySource, isGitSource, hasCommitShaPinning } from "./utils/advisory.js";
4
- import { extractCveAliases, hasMaliciousAdvisory } from "./utils/vuln.js";
4
+ import { collapseAliasedDuplicates, extractCveAliases, hasMaliciousAdvisory } from "./utils/vuln.js";
5
5
  import { compareVersions, isPreReleaseVersion, normalizeAdvisoryVersion } from "./utils/version.js";
6
6
  import { loadCache, saveCache, isEntryStale } from "./osv/cache.js";
7
7
  import { maxSeverity } from "./osv/severity.js";
@@ -12,7 +12,7 @@ import { queryNpmAdvisoryGaps } from "./advisory/npm-advisory-source.js";
12
12
  import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
13
13
  import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
14
14
  import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
15
- import { configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, runWithObserver, } from "./remediation/npm-registry.js";
15
+ import { configureNpmRegistry, configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, runWithObserver, } from "./remediation/npm-registry.js";
16
16
  import { countBySeverity } from "./utils/severity.js";
17
17
  import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry } from "./remediation/npm-transitive-resolution.js";
18
18
  import { resolveChainFix } from "./remediation/transitive-chain-resolver.js";
@@ -21,6 +21,8 @@ import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
21
21
  import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
22
22
  import { buildBunWorkspaceMap } from "./parsers/bun-lock.js";
23
23
  import { pluralize } from "./utils/string.js";
24
+ import path from "node:path";
25
+ import { resolveRegistryConfig } from "./utils/registry-config.js";
24
26
  import { extractErrorMessage } from "./utils/network.js";
25
27
  import { logWarn } from "./output/formatters.js";
26
28
  import { formatDiagnosticMessage } from "./scan/completeness.js";
@@ -112,6 +114,22 @@ export async function scanPackages(packages, batchSize, options, context, debugL
112
114
  if (!offline && options.debug) {
113
115
  configureNpmRegistryDebug(log);
114
116
  }
117
+ // Point metadata lookups at the registry this project installs from, so a fix
118
+ // version is validated against the registry the user would actually install it
119
+ // from rather than against public npm. Unconfigured projects resolve to the
120
+ // public registry, which is the previous behaviour.
121
+ const registryConfig = resolveRegistryConfig({
122
+ projectPath: context?.scanFilePath ? path.dirname(context.scanFilePath) : process.cwd(),
123
+ packageManager: inferPackageManagerForChain(context?.scanSource),
124
+ });
125
+ configureNpmRegistry(registryConfig);
126
+ if (options.debug) {
127
+ log("Registry config", {
128
+ registry: registryConfig.registry,
129
+ scopes: Object.keys(registryConfig.scopes),
130
+ sourceFile: registryConfig.sourceFile,
131
+ });
132
+ }
115
133
  const cache = loadCache(cacheDirOverride, options.debug ? log : undefined);
116
134
  try {
117
135
  const results = [];
@@ -363,9 +381,10 @@ export async function scanPackages(packages, batchSize, options, context, debugL
363
381
  saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
364
382
  }
365
383
  const findings = mergeResultsByPackage(results).map(result => {
366
- const vulnerabilities = result.vulnIds
367
- .map(id => vulnMap.get(id))
368
- .filter((v) => Boolean(v));
384
+ // Collapse advisory records OSV marks as the same vulnerability before
385
+ // anything downstream counts them, so the terminal, JSON, SARIF, both SBOM
386
+ // formats and the HTML report all see one list.
387
+ const vulnerabilities = collapseAliasedDuplicates(result.vulnIds.map(id => vulnMap.get(id)).filter((v) => Boolean(v)));
369
388
  const unresolvedIds = result.vulnIds.filter(id => !vulnMap.has(id));
370
389
  const severity = maxSeverity(vulnerabilities);
371
390
  const cveAliases = extractCveAliases(vulnerabilities);
@@ -400,10 +419,10 @@ export async function scanPackages(packages, batchSize, options, context, debugL
400
419
  const otherCount = unresolvedDetailIds.length - transientCount - offlineCount - confirmedCount;
401
420
  const parts = [];
402
421
  if (transientCount > 0) {
403
- parts.push(`${transientCount} from transient failures — re-run to retry`);
422
+ parts.push(`${transientCount} from transient failures: re-run to retry`);
404
423
  }
405
424
  if (offlineCount > 0) {
406
- parts.push(`${offlineCount} missing from local advisory database — refresh to sync`);
425
+ parts.push(`${offlineCount} missing from local advisory database: refresh to sync`);
407
426
  }
408
427
  if (confirmedCount > 0) {
409
428
  parts.push(`${confirmedCount} confirmed missing from the OSV API`);
@@ -777,6 +796,7 @@ async function validateOneDirectFixTarget(finding, options) {
777
796
  if (hintResolution.resolvedVersion === lowestKnownResolution.resolvedVersion &&
778
797
  hintResolution.note) {
779
798
  finding.fixVersionValidationNote = hintResolution.note;
799
+ finding.advisoryHintUnavailable = hintResolution.advisoryHintUnavailable ?? false;
780
800
  // date is for the validated version, not the hint
781
801
  setPublishedDate(lowestKnownResolution);
782
802
  logFixValidation();
@@ -804,6 +824,9 @@ async function validateOneDirectFixTarget(finding, options) {
804
824
  lowestKnownResolution.note ?? `A non-vulnerable version could not be confirmed for ${finding.pkg.name}.`,
805
825
  resolution.note,
806
826
  ].filter(Boolean).join(" ");
827
+ // The note above is two notes joined, so the only honest way to know whether
828
+ // the hint was missing from the registry is to carry the resolver's own answer.
829
+ finding.advisoryHintUnavailable = resolution.advisoryHintUnavailable ?? false;
807
830
  finding.validatedTargetScannedVersions = null;
808
831
  finding.validatedTargetKnownVulnerableVersions = null;
809
832
  finding.fixVersionPublishedAt = null;
@@ -824,11 +847,11 @@ function classifyRelationship(paths, packageName, directDependencyNames) {
824
847
  if (packageName && directDependencyNames?.has(packageName)) {
825
848
  // The package name is declared as a direct dependency. But when multiple versions
826
849
  // of the same package are installed (one direct, one transitive), the name alone
827
- // is not enough — we need to verify this specific installed version is the direct
850
+ // is not enough - we need to verify this specific installed version is the direct
828
851
  // one. A direct install always has at least one path of length 2 (["project", name]).
829
852
  // If all paths are longer, this is a different (transitive) version of the package.
830
853
  if (paths.length === 0)
831
- return "direct"; // no path data — trust the name
854
+ return "direct"; // no path data - trust the name
832
855
  const hasDirectPath = paths.some(p => p.length <= 2);
833
856
  return hasDirectPath ? "direct" : "transitive";
834
857
  }
@@ -4,16 +4,16 @@ export const SKILL_CONTENT = `Run \`cve-lite . --json\` in the project root. The
4
4
 
5
5
  Key fields in each finding:
6
6
 
7
- - \`package\`, \`version\` — the vulnerable package
8
- - \`severity\` — \`critical | high | medium | low | unknown\`
9
- - \`relationship\` — \`direct | transitive\`
10
- - \`firstFixedVersion\` — minimum safe version, if known
11
- - \`runnableFixCommand\` — exact install command to run, if available
12
- - \`recommendedAction\` — human-readable fix guidance
13
- - \`cves\` — CVE IDs
14
- - \`dependencyPaths\` — chains showing how the package is pulled in
15
- - \`usage.imported\` — whether the package is imported in source files; \`null\` when the usage scan hit its file cap (import status unknown), and \`usage\` itself is \`null\` when \`--usage\` was not run
16
- - \`contextualSignals\` — heuristic prioritization hints (\`usage\`, \`reachabilityHint\`, \`exposure\`). Not exploitability verdicts; \`not_imported\` / \`not_indicated\` does not mean safe or unreachable
7
+ - \`package\`, \`version\`: the vulnerable package
8
+ - \`severity\`: \`critical | high | medium | low | unknown\`
9
+ - \`relationship\`: \`direct | transitive\`
10
+ - \`firstFixedVersion\`: minimum safe version, if known
11
+ - \`runnableFixCommand\`: exact install command to run, if available
12
+ - \`recommendedAction\`: human-readable fix guidance
13
+ - \`cves\`: CVE IDs
14
+ - \`dependencyPaths\`: chains showing how the package is pulled in
15
+ - \`usage.imported\`: whether the package is imported in source files; \`null\` when the usage scan hit its file cap (import status unknown), and \`usage\` itself is \`null\` when \`--usage\` was not run
16
+ - \`contextualSignals\`: heuristic prioritization hints (\`usage\`, \`reachabilityHint\`, \`exposure\`). Not exploitability verdicts; \`not_imported\` / \`not_indicated\` does not mean safe or unreachable
17
17
 
18
18
  Top-level \`suggestedFixCommands\` contains grouped, copy-ready fix commands.
19
19
 
@@ -22,8 +22,8 @@ Top-level \`suggestedFixCommands\` contains grouped, copy-ready fix commands.
22
22
  1. Critical before high before medium before low
23
23
  2. Direct dependencies before transitive
24
24
  3. If \`usage.imported === false\`, flag as lower practical risk but do not dismiss
25
- 4. If \`runnableFixCommand\` is present, that is the exact command to run — prefer it over manual guidance
26
- 5. Treat \`contextualSignals\` as triage context only — never as exploitability or runtime reachability
25
+ 4. If \`runnableFixCommand\` is present, that is the exact command to run: prefer it over manual guidance
26
+ 5. Treat \`contextualSignals\` as triage context only: never as exploitability or runtime reachability
27
27
 
28
28
  ### Codebase analysis
29
29
 
@@ -5,7 +5,7 @@
5
5
  * a network probe, a runtime check, or an exploitability verdict.
6
6
  *
7
7
  * Short/generic names (`http`, `next`, `router`, …) match the exact package or
8
- * a scoped prefix such as `@next/` — never hyphenated lookalikes. Distinctive
8
+ * a scoped prefix such as `@next/` - never hyphenated lookalikes. Distinctive
9
9
  * stacks (`express`, `fastify`, `@nestjs/`, …) still allow hyphen/token forms.
10
10
  */
11
11
  export const REQUEST_FACING_MARKERS = [