cve-lite-cli 1.39.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 (39) hide show
  1. package/README.md +11 -11
  2. package/dist/cli/help.js +1 -0
  3. package/dist/constants.js +4 -3
  4. package/dist/osv/severity.js +1 -1
  5. package/dist/output/cyclonedx.js +1 -1
  6. package/dist/output/formatters.js +2 -2
  7. package/dist/output/html-reporter.js +14 -8
  8. package/dist/output/multi-folder-html-reporter.js +12 -8
  9. package/dist/output/override-findings-html.js +3 -6
  10. package/dist/output/override-findings-terminal.js +7 -12
  11. package/dist/output/override-fix-command.js +13 -0
  12. package/dist/output/printers.js +11 -7
  13. package/dist/output/sarif.js +39 -11
  14. package/dist/output/scan-json.js +26 -1
  15. package/dist/output/write-outputs.js +13 -1
  16. package/dist/overrides/parsing/registry.js +1 -1
  17. package/dist/parsers/pnpm-lock.js +23 -10
  18. package/dist/remediation/fix-commands.js +36 -7
  19. package/dist/remediation/npm-registry.js +56 -7
  20. package/dist/remediation/npm-transitive-resolution.js +11 -30
  21. package/dist/remediation/parent-candidate-resolver.js +65 -0
  22. package/dist/remediation/parent-upgrade.js +6 -37
  23. package/dist/scan/completeness.js +7 -7
  24. package/dist/scan/multi-folder-scan.js +28 -8
  25. package/dist/scan/override-audit.js +11 -1
  26. package/dist/scan/single-scan.js +85 -45
  27. package/dist/scanner.js +32 -9
  28. package/dist/skills/content.js +12 -12
  29. package/dist/utils/contextual-signals.js +1 -1
  30. package/dist/utils/effective-options.js +55 -0
  31. package/dist/utils/finding.js +1 -1
  32. package/dist/utils/fix-runner.js +3 -2
  33. package/dist/utils/network.js +1 -1
  34. package/dist/utils/registry-config.js +144 -0
  35. package/dist/utils/severity.js +8 -0
  36. package/dist/utils/validate-url.js +3 -3
  37. package/dist/utils/version.js +17 -1
  38. package/dist/utils/vuln.js +75 -0
  39. package/package.json +1 -1
@@ -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/
546
- // lockfileSource for a 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,9 @@ 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,
567
607
  lockfileSource: reportData.lockfileSource,
568
608
  findings: reportData.findings,
569
609
  };
@@ -595,9 +635,9 @@ export async function handleSingleFolderScan(params) {
595
635
  // The gate and the line that explains it come from one call, so the exit code
596
636
  // and the printed reason cannot drift apart.
597
637
  const gateLine = failingGateSummary([
598
- { label: "vulnerability", findings: scanState.sorted },
599
- { label: "override hygiene", findings: overrideFindings },
600
- { 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 },
601
641
  ], options.failOn);
602
642
  const shouldFail = gateLine !== null;
603
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 = [
@@ -0,0 +1,55 @@
1
+ import { DEFAULT_BATCH_SIZE, DEFAULT_SEARCH_DEPTH } from "../constants.js";
2
+ export function summarizeEffectiveOptions(options) {
3
+ const summary = {
4
+ json: options.json ?? false,
5
+ debug: options.debug ?? false,
6
+ verbose: options.verbose ?? false,
7
+ fix: options.fix ?? false,
8
+ ratchet: options.ratchet ?? false,
9
+ createPr: options.createPr ?? false,
10
+ prodOnly: options.prodOnly ?? false,
11
+ offline: options.offline ?? false,
12
+ all: options.all ?? false,
13
+ onlyUsed: options.onlyUsed ?? false,
14
+ noOpen: options.noOpen ?? false,
15
+ noCache: options.noCache ?? false,
16
+ sarif: options.sarif ?? false,
17
+ cdx: options.cdx ?? false,
18
+ sbomInventoryOnly: options.sbomInventoryOnly ?? false,
19
+ checkOverrides: options.checkOverrides ?? false,
20
+ checkMaintenance: options.checkMaintenance ?? false,
21
+ checkLicenses: options.checkLicenses ?? false,
22
+ checkNetwork: options.checkNetwork ?? false,
23
+ allowPrivateOsvUrl: options.allowPrivateOsvUrl ?? false,
24
+ usage: options.usage ?? false,
25
+ failOn: options.failOn,
26
+ incompletePolicy: options.incompletePolicy,
27
+ // Same normalization as the CLI entrypoint (src/index.ts).
28
+ batchSize: Number(options.batchSize || DEFAULT_BATCH_SIZE),
29
+ searchDepth: Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH)),
30
+ };
31
+ if (options.minSeverity !== undefined)
32
+ summary.minSeverity = options.minSeverity;
33
+ if (options.sbom !== undefined)
34
+ summary.sbom = options.sbom;
35
+ if (options.rule !== undefined)
36
+ summary.rule = options.rule;
37
+ if (options.prBase !== undefined)
38
+ summary.prBase = options.prBase;
39
+ // Path/URL options: record only that they were set, never the value.
40
+ if (options.offlineDb)
41
+ summary.offlineDb = true;
42
+ if (options.cacheDir)
43
+ summary.cacheDir = true;
44
+ if (options.osvUrl)
45
+ summary.osvUrl = true;
46
+ if (options.output)
47
+ summary.output = true;
48
+ if (options.caCert)
49
+ summary.caCert = true;
50
+ if (options.auditLog)
51
+ summary.auditLog = true;
52
+ if (options.report)
53
+ summary.report = true;
54
+ return summary;
55
+ }
@@ -12,7 +12,7 @@ export function getPrimaryParent(finding) {
12
12
  /**
13
13
  * Unique root (top-level) dependencies that pull in this package, derived from
14
14
  * every known dependencyPaths chain. Paths of length < 3 (direct dependencies,
15
- * where the package itself is path[1]) are excluded — there is no meaningful
15
+ * where the package itself is path[1]) are excluded - there is no meaningful
16
16
  * root distinct from the package.
17
17
  *
18
18
  * Gated on relationship === "transitive": a package can be a direct dependency
@@ -111,8 +111,9 @@ export async function applyFixesIfRequested(params) {
111
111
  const spinner = createSpinner(`Applying safe package fixes with ${commandLabel}... 0/${total}`, params.options);
112
112
  const fixHint = `\nHint: Check that \`${params.plan.packageManager}\` is available and you have write access to node_modules.\nIf running in CI, ensure the install step has already run before cve-lite --fix.`;
113
113
  // parent-update is keyed per child, so two children behind one parent produce
114
- // two targets with the same `npm update <parent>` command. Spawn each command
115
- // once; the displayed plan already dedupes the same way.
114
+ // two targets. npm update names the child, so those commands differ. Two
115
+ // parents that refresh the same child can still share `npm update <child>`.
116
+ // Spawn each command once; the displayed plan already dedupes the same way.
116
117
  const seenCommands = new Set();
117
118
  for (let i = 0; i < applyTargets.length; i++) {
118
119
  const target = applyTargets[i];
@@ -11,7 +11,7 @@ export function extractErrorMessage(error) {
11
11
  }
12
12
  export function sslCertificateErrorHint() {
13
13
  return [
14
- "Hint: SSL certificate error — your network may be using a corporate proxy that intercepts HTTPS traffic.",
14
+ "Hint: SSL certificate error. Your network may be using a corporate proxy that intercepts HTTPS traffic.",
15
15
  "Fix (recommended): save your corporate CA certificate path once:",
16
16
  " cve-lite config set ca-cert /path/to/corporate-ca.crt",
17
17
  "Or pass it per-invocation:",