cve-lite-cli 1.37.0 → 1.39.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 (47) hide show
  1. package/README.md +20 -1
  2. package/dist/cli/args.js +121 -104
  3. package/dist/cli/flags.js +39 -0
  4. package/dist/cli/help.js +6 -3
  5. package/dist/cli/overrides.js +25 -19
  6. package/dist/cli/validate.js +31 -9
  7. package/dist/index.js +6 -1
  8. package/dist/output/compact-truncation.js +35 -0
  9. package/dist/output/formatters.js +10 -2
  10. package/dist/output/html-reporter.js +24 -12
  11. package/dist/output/multi-folder-html-reporter.js +26 -7
  12. package/dist/output/override-findings-html.js +24 -3
  13. package/dist/output/override-findings-json.js +5 -2
  14. package/dist/output/override-findings-sarif.js +1 -0
  15. package/dist/output/override-findings-terminal.js +21 -1
  16. package/dist/output/printers.js +34 -21
  17. package/dist/output/sarif.js +54 -3
  18. package/dist/output/scan-json.js +74 -0
  19. package/dist/output/skipped-override-rules.js +41 -0
  20. package/dist/output/write-outputs.js +16 -28
  21. package/dist/overrides/admitted-scan.js +12 -1
  22. package/dist/overrides/api.js +75 -21
  23. package/dist/overrides/context-builder.js +49 -6
  24. package/dist/overrides/detectors/index.js +2 -0
  25. package/dist/overrides/detectors/oa005-nested-ineffective.js +50 -2
  26. package/dist/overrides/detectors/oa008-materialized.js +72 -13
  27. package/dist/overrides/detectors/oa009-stale-floor.js +12 -15
  28. package/dist/overrides/detectors/oa010-vulnerable-floor.js +5 -1
  29. package/dist/overrides/detectors/oa011-exceeds-range.js +128 -0
  30. package/dist/overrides/detectors/pd001-override-only-phantom.js +5 -4
  31. package/dist/overrides/detectors/pd002-transitive-only-phantom.js +5 -4
  32. package/dist/overrides/detectors/phantom-utils.js +29 -0
  33. package/dist/overrides/parsing/registry.js +79 -10
  34. package/dist/scan/multi-folder-scan.js +65 -51
  35. package/dist/scan/override-audit.js +49 -0
  36. package/dist/scan/single-scan.js +109 -33
  37. package/dist/scanner.js +8 -4
  38. package/dist/skills/content.js +4 -2
  39. package/dist/usage/scanner.js +219 -28
  40. package/dist/utils/contextual-signals.js +193 -0
  41. package/dist/utils/finding.js +5 -0
  42. package/dist/utils/node-builtins.js +32 -0
  43. package/dist/utils/package-json.js +66 -14
  44. package/dist/utils/severity.js +22 -0
  45. package/dist/utils/update-check.js +2 -1
  46. package/dist/utils/version.js +37 -19
  47. package/package.json +1 -1
@@ -9,7 +9,9 @@ import { severityOrder } from "../constants.js";
9
9
  import { pluralize } from "../utils/string.js";
10
10
  import { hasMaliciousAdvisory } from "../utils/vuln.js";
11
11
  import { selectFindingsForCompact } from "./finding-display.js";
12
+ import { COMPACT_COMMAND_GROUP_LIMIT, COMPACT_FINDING_BLOCK_LIMIT, formatCompactCommandGroupTruncationNotice, formatCompactFindingTruncationNotice, } from "./compact-truncation.js";
12
13
  import { computePrioritySignal, PRIORITY_SIGNAL_LABELS, PRIORITY_SIGNAL_TABLE_LABELS, PRIORITY_SIGNAL_DESCRIPTIONS } from "../utils/priority-signal.js";
14
+ import { computeContextualSignals, formatContextualSignalValues, formatContextualSignalsLine } from "../utils/contextual-signals.js";
13
15
  import { renderLicenseFindings } from "./license-terminal.js";
14
16
  import { getCompletenessImpact } from "../scan/completeness.js";
15
17
  import { MAL_PRIVATE_REGISTRY_COMPACT_MESSAGE, MAL_PRIVATE_REGISTRY_LEGEND_MESSAGE, MAL_GIT_SOURCE_PINNED_MESSAGE, MAL_GIT_SOURCE_FLOATING_MESSAGE, MAL_GIT_SOURCE_COMPACT_MESSAGE, MAL_GIT_SOURCE_LEGEND_MESSAGE, MAL_GIT_SOURCE_PINNED_DISPLAY, MAL_GIT_SOURCE_FLOATING_DISPLAY, OVERRIDES_COMMAND, } from "../constants.js";
@@ -228,6 +230,8 @@ const TABLE_COLUMNS = [
228
230
  cell: row => {
229
231
  if (!row.usage)
230
232
  return { value: "n/a", decorated: chalk.gray("n/a") };
233
+ if (row.usage.imported === null)
234
+ return { value: "unknown", decorated: chalk.gray("unknown") };
231
235
  const value = row.usage.imported ? `${row.usage.files.length} file(s)` : "unused";
232
236
  return { value, decorated: row.usage.imported ? chalk.red(value) : chalk.green(value) };
233
237
  },
@@ -280,11 +284,6 @@ const TABLE_COLUMNS = [
280
284
  decorated: formatPrioritySignal(row.signal ?? null),
281
285
  }),
282
286
  },
283
- {
284
- name: "ids",
285
- header: "IDs",
286
- cell: row => ({ value: row.ids ? formatAdvisoryIdFoothold(row.ids) : "-" }),
287
- },
288
287
  {
289
288
  name: "context",
290
289
  header: "Context",
@@ -304,7 +303,7 @@ const TABLE_COLUMNS = [
304
303
  const FINDINGS_TABLE_COLUMNS = [
305
304
  "package", "version", "severity", "type", "root", "usage",
306
305
  "advisory", "target", "scanned", "stillVulnerable", "breaking",
307
- "epss", "epssPriority", "ids",
306
+ "epss", "epssPriority",
308
307
  ];
309
308
  // Both remediation tables draw the same columns. A direct upgrade and a parent
310
309
  // upgrade are different rows, but showing them in differently shaped tables made
@@ -391,7 +390,7 @@ function findingToTableRow(finding, plan, skippedKeys) {
391
390
  package: finding.pkg.name,
392
391
  version: finding.pkg.version,
393
392
  severity: finding.severity,
394
- relationship: formatRelLabel(finding).replace(" · dev", "\n· dev"),
393
+ relationship: formatRelLabel(finding),
395
394
  root: shortenRootSummary(formatRootDependencySummary(finding)),
396
395
  usage: finding.usage ?? null,
397
396
  advisoryVersion: finding.firstFixedVersion ?? null,
@@ -407,7 +406,6 @@ function findingToTableRow(finding, plan, skippedKeys) {
407
406
  signal: finding.epssScores && finding.epssScores.length > 0
408
407
  ? computePrioritySignal(finding.severity, finding.epssScores)
409
408
  : null,
410
- ids: finding.vulnerabilities.map(v => v.id),
411
409
  };
412
410
  }
413
411
  function formatTargetDisplay(finding, fixVersion, isSkipped) {
@@ -454,7 +452,6 @@ function fixTargetToTableRow(target, context) {
454
452
  breaking: !!target.currentVersion && isBreakingUpgrade(target.currentVersion, target.targetVersion),
455
453
  epss: context?.epss ?? null,
456
454
  signal: context?.prioritySignal ?? null,
457
- ids: context?.ids,
458
455
  context: fixTargetContext(target),
459
456
  };
460
457
  }
@@ -483,6 +480,15 @@ export function printTable(findings, threshold, skippedKeys, plan) {
483
480
  console.log(chalk.gray("Use --all to show every finding."));
484
481
  }
485
482
  printColumnTable(columns, rows, columnWidths(columns, rows));
483
+ if (findings.length > 0) {
484
+ console.log("");
485
+ console.log(chalk.bold("Prioritization signals (heuristic)"));
486
+ console.log(chalk.gray("Triage hints only — not exploitability or runtime reachability proofs."));
487
+ for (const finding of findings) {
488
+ const values = formatContextualSignalValues(computeContextualSignals(finding));
489
+ console.log(chalk.gray(` ${finding.pkg.name}@${finding.pkg.version} ${values}`));
490
+ }
491
+ }
486
492
  const maliciousFindings = findings.filter(f => hasMaliciousAdvisory(f.vulnerabilities));
487
493
  if (maliciousFindings.length > 0) {
488
494
  console.log("");
@@ -584,13 +590,6 @@ export function printOverrideHint() {
584
590
  // --json, --sarif and the HTML report, where it is not competing for terminal
585
591
  // width and each ID is a link. Joined into the table it ran to 628 characters on
586
592
  // a real project, and truncated it left a single usable ID followed by a stump.
587
- function formatAdvisoryIdFoothold(ids) {
588
- if (ids.length === 0)
589
- return "-";
590
- if (ids.length === 1)
591
- return ids[0];
592
- return `${ids[0]} ${chalk.gray(`+${ids.length - 1}`)}`;
593
- }
594
593
  function renderRow(cells, widths) {
595
594
  const columnLines = cells.map(cell => String(cell).split("\n"));
596
595
  const height = Math.max(1, ...columnLines.map(lines => lines.length));
@@ -679,7 +678,7 @@ export function printCompactOutput(findings, scanInput, options) {
679
678
  console.log("────────────────────────────────\n");
680
679
  // Reuse shared display selection logic so compact mode does not silently
681
680
  // drop direct unknown-severity findings.
682
- const urgentFindings = selectFindingsForCompact(findings, { urgentLimit: 3 });
681
+ const urgentFindings = selectFindingsForCompact(findings, { urgentLimit: COMPACT_FINDING_BLOCK_LIMIT });
683
682
  for (const finding of urgentFindings) {
684
683
  const sevLabel = finding.severity.toUpperCase().padEnd(8);
685
684
  const typeLabel = finding.relationship === "direct"
@@ -689,7 +688,10 @@ export function printCompactOutput(findings, scanInput, options) {
689
688
  : "Unknown dependency";
690
689
  let usageContext = "";
691
690
  if (finding.usage) {
692
- if (finding.usage.imported) {
691
+ if (finding.usage.imported === null) {
692
+ usageContext = chalk.gray(` (import status unknown - usage scan hit the file cap)`);
693
+ }
694
+ else if (finding.usage.imported) {
693
695
  usageContext = chalk.red(` (imported in ${finding.usage.files.length} ${pluralize(finding.usage.files.length, "file")})`);
694
696
  }
695
697
  else {
@@ -698,6 +700,7 @@ export function printCompactOutput(findings, scanInput, options) {
698
700
  }
699
701
  console.log(`${formatSeverityLabel(sevLabel)} ${chalk.whiteBright(finding.pkg.name)}@${finding.pkg.version}`);
700
702
  console.log(` ${typeLabel}${usageContext}`);
703
+ console.log(` ${chalk.gray(formatContextualSignalsLine(computeContextualSignals(finding)))}`);
701
704
  if (finding.epssScores && finding.epssScores.length > 0) {
702
705
  const best = finding.epssScores.slice().sort((a, b) => b.percentile - a.percentile)[0];
703
706
  const pct = (best.epss * 100).toFixed(1);
@@ -760,6 +763,11 @@ export function printCompactOutput(findings, scanInput, options) {
760
763
  }
761
764
  console.log("");
762
765
  }
766
+ const findingTruncationNotice = formatCompactFindingTruncationNotice(urgentFindings.length, findings.length);
767
+ if (findingTruncationNotice && !options?.all) {
768
+ console.log(chalk.gray(findingTruncationNotice));
769
+ console.log("");
770
+ }
763
771
  const plan = scanInput ? buildSuggestedFixCommandPlan(findings, scanInput, options) : null;
764
772
  if (plan) {
765
773
  if (plan?.sections.length) {
@@ -773,7 +781,8 @@ export function printCompactOutput(findings, scanInput, options) {
773
781
  console.log(chalk.gray(`Validation: scanned ${compactValidationSummary.checked} package ${pluralize(compactValidationSummary.checked, "version")}; ${compactValidationSummary.vulnerable} ${pluralize(compactValidationSummary.vulnerable, "is", "are")} still known vulnerable.`));
774
782
  }
775
783
  console.log("");
776
- for (const section of plan.sections.slice(0, 3)) {
784
+ const shownSections = plan.sections.slice(0, COMPACT_COMMAND_GROUP_LIMIT);
785
+ for (const section of shownSections) {
777
786
  console.log(`${section.title}`);
778
787
  for (const target of section.targets) {
779
788
  if (section.kind === "direct-adjusted" && target.adjustmentNote) {
@@ -784,6 +793,11 @@ export function printCompactOutput(findings, scanInput, options) {
784
793
  console.log(renderCommandCallout(section.command, section.targets));
785
794
  console.log("");
786
795
  }
796
+ const commandGroupTruncationNotice = formatCompactCommandGroupTruncationNotice(plan.sections.slice(COMPACT_COMMAND_GROUP_LIMIT));
797
+ if (commandGroupTruncationNotice) {
798
+ console.log(chalk.gray(commandGroupTruncationNotice));
799
+ console.log("");
800
+ }
787
801
  }
788
802
  }
789
803
  if (options?.licenseFindings) {
@@ -981,7 +995,7 @@ function buildFixRowContexts(findings) {
981
995
  }
982
996
  const contexts = new Map();
983
997
  for (const [name, group] of byPackage) {
984
- // The package's own finding describes Type, Root and IDs; fall back to the
998
+ // The package's own finding describes Type and Root; fall back to the
985
999
  // first of the group when the package only appears as somebody else's parent.
986
1000
  const own = group.find(f => f.relationship === "direct") ?? group[0];
987
1001
  const worst = group.reduce((a, b) => (severityOrder[b.severity] > severityOrder[a.severity] ? b : a));
@@ -1002,7 +1016,6 @@ function buildFixRowContexts(findings) {
1002
1016
  root: shortenRootSummary(formatRootDependencySummary(own)),
1003
1017
  epss: bestEpss,
1004
1018
  prioritySignal: bestSignal,
1005
- ids: own.vulnerabilities.map(v => v.id),
1006
1019
  advisoryVersion: own.firstFixedVersion ?? null,
1007
1020
  scanned: own.validatedTargetScannedVersions ?? null,
1008
1021
  stillVulnerable: own.validatedTargetKnownVulnerableVersions ?? null,
@@ -79,7 +79,24 @@ export function deriveLockfileUri(scanInput) {
79
79
  return path.basename(scanInput.filePath);
80
80
  return LOCKFILE_NAMES[scanInput.source] ?? "lockfile";
81
81
  }
82
- export function buildSarifOutput(findings, lockfileUri, version, plan, overrideFindings, maintenanceFindings, licenseFindings) {
82
+ function dedupeSkipped(skipped) {
83
+ const seen = new Set();
84
+ const out = [];
85
+ for (const entry of skipped) {
86
+ const key = `${entry.ruleId}\u0000${entry.reason}`;
87
+ if (seen.has(key))
88
+ continue;
89
+ seen.add(key);
90
+ out.push(entry);
91
+ }
92
+ return out;
93
+ }
94
+ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideFindings, maintenanceFindings, licenseFindings,
95
+ // NOTE: this parameter list is too long and wants an options object, tracked as #1244.
96
+ // Kept positional here so #1222 does not also rewrite every call site. It is why the
97
+ // new parameter sits last in both functions even though `writeSarifReport` already has
98
+ // a defaulted `outputDir` ahead of it.
99
+ overrideSkipped) {
83
100
  const ruleMap = new Map();
84
101
  const ruleIndexMap = new Map();
85
102
  const results = [];
@@ -176,6 +193,9 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
176
193
  ? buildLicenseSarifResults(licenseFindings, lockfileUri, licenseExtensionIndex)
177
194
  : []),
178
195
  ];
196
+ // One entry per (rule, reason), de-duplicated so the driver's notification
197
+ // descriptors and the invocation's notifications cannot disagree.
198
+ const skippedNotifications = dedupeSkipped(overrideSkipped ?? []);
179
199
  return {
180
200
  $schema: SARIF_SCHEMA,
181
201
  version: "2.1.0",
@@ -187,10 +207,41 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
187
207
  version,
188
208
  informationUri: "https://owasp.org/cve-lite-cli/",
189
209
  rules: Array.from(ruleMap.values()),
210
+ // Deduped by rule id, separately from the notification list. The notifications
211
+ // are per (rule, reason) and one rule can be skipped for two reasons, but
212
+ // reportingDescriptor.id must be unique within its array.
213
+ ...(skippedNotifications.length > 0
214
+ ? {
215
+ notifications: [...new Set(skippedNotifications.map((n) => n.ruleId))].map((id) => ({
216
+ id,
217
+ shortDescription: { text: `${id} did not run during this scan` },
218
+ })),
219
+ }
220
+ : {}),
190
221
  },
191
222
  ...(extensions.length > 0 ? { extensions } : {}),
192
223
  },
193
224
  results: allResults,
225
+ // SARIF 2.1.0 §3.20.21: a rule that could not run belongs in
226
+ // toolExecutionNotifications rather than being silently omitted, so a machine
227
+ // reading this file can tell an incomplete audit from a clean one.
228
+ //
229
+ // Emitted only when there is something to report, so a plain scan's SARIF is
230
+ // unchanged by #1222. Each descriptor is declared on the driver above.
231
+ ...(skippedNotifications.length > 0
232
+ ? {
233
+ invocations: [
234
+ {
235
+ executionSuccessful: true,
236
+ toolExecutionNotifications: skippedNotifications.map((entry) => ({
237
+ level: "warning",
238
+ message: { text: `${entry.ruleId} did not run: ${entry.reason}` },
239
+ descriptor: { id: entry.ruleId },
240
+ })),
241
+ },
242
+ ],
243
+ }
244
+ : {}),
194
245
  artifacts: [
195
246
  { location: { uri: lockfileUri, uriBaseId: "%SRCROOT%" } },
196
247
  ],
@@ -198,11 +249,11 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
198
249
  ],
199
250
  };
200
251
  }
201
- export function writeSarifReport(findings, lockfileUri, plan, overrideFindings, maintenanceFindings, licenseFindings, outputDir = process.cwd()) {
252
+ export function writeSarifReport(findings, lockfileUri, plan, overrideFindings, maintenanceFindings, licenseFindings, outputDir = process.cwd(), overrideSkipped) {
202
253
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
203
254
  const filename = `cve-lite-scan-${ts}.sarif`;
204
255
  const outputPath = path.join(outputDir, filename);
205
- const sarif = buildSarifOutput(findings, lockfileUri, getCliVersion(), plan, overrideFindings, maintenanceFindings, licenseFindings);
256
+ const sarif = buildSarifOutput(findings, lockfileUri, getCliVersion(), plan, overrideFindings, maintenanceFindings, licenseFindings, overrideSkipped);
206
257
  try {
207
258
  fs.writeFileSync(outputPath, JSON.stringify(sarif, null, 2));
208
259
  }
@@ -0,0 +1,74 @@
1
+ import { serializeFinding } from "./formatters.js";
2
+ import { overrideFindingsToJson } from "./override-findings-json.js";
3
+ import { maintenanceFindingsToJson } from "./maintenance-findings-json.js";
4
+ import { serializeLicenseFindings } from "./license-findings-json.js";
5
+ import { aggregateMultiFolderCompleteness } from "../scan/completeness.js";
6
+ /**
7
+ * Single-folder `--json` payload. HTML `report.json` reuses this so both
8
+ * artifacts share one schema.
9
+ */
10
+ export function buildScanJson(input) {
11
+ const payload = {
12
+ projectPath: input.projectPath,
13
+ mode: input.scanInput.mode,
14
+ source: input.scanInput.source,
15
+ packageCount: input.scanInput.packages.length,
16
+ findingCount: input.findings.length,
17
+ status: (input.completeness.complete ? "ok" : "partial"),
18
+ complete: input.completeness.complete,
19
+ diagnostics: input.completeness.diagnostics,
20
+ suggestedFixCommands: input.suggestedFixCommands,
21
+ notes: [...input.scanInput.notes, ...input.coverage],
22
+ warnings: input.scanInput.warnings,
23
+ skippedDependencies: input.scanInput.skippedDependencies,
24
+ findings: input.findings.map(finding => serializeFinding(finding, input.suggestedFixCommands)),
25
+ };
26
+ const overridePayload = overrideFindingsToJson(input.overrideFindings ?? [], input.overrideSkipped);
27
+ const maintenancePayload = maintenanceFindingsToJson(input.maintenanceFindings ?? []);
28
+ const licensePayload = input.licenseFindings && input.licenseFindings.length > 0
29
+ ? {
30
+ licenseFindings: serializeLicenseFindings(input.licenseFindings),
31
+ ...(input.licenseLimitedToDirectOnly ? { licenseLimitedToDirectOnly: true } : {}),
32
+ }
33
+ : {};
34
+ return { ...payload, ...overridePayload, ...maintenancePayload, ...licensePayload };
35
+ }
36
+ /**
37
+ * Multi-folder `--json` payload. HTML `report.json` reuses this so both
38
+ * artifacts share one schema.
39
+ */
40
+ export function buildMultiFolderScanJson(params) {
41
+ const aggregatedCompleteness = aggregateMultiFolderCompleteness(params.results);
42
+ const findings = params.results.flatMap(r => r.sorted.map(f => ({ ...serializeFinding(f, r.suggestedFixCommands), subfolder: r.subfolder })));
43
+ return {
44
+ multiFolder: true,
45
+ projectPath: params.projectPath,
46
+ folders: params.results.map(r => r.subfolder),
47
+ findingCount: findings.length,
48
+ status: aggregatedCompleteness.complete ? "ok" : "partial",
49
+ complete: aggregatedCompleteness.complete,
50
+ diagnostics: aggregatedCompleteness.diagnostics,
51
+ warnings: params.results.flatMap(r => r.scanInput.warnings),
52
+ findings,
53
+ ...(params.includeOverrides
54
+ ? {
55
+ overrideFindings: params.results.flatMap(r => r.overrideFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
56
+ // CI and the GitHub App read this file, so a skipped rule has to reach it. Tagged
57
+ // per folder the same way findings are, since one folder can skip a rule while
58
+ // another runs it.
59
+ skippedOverrideRules: params.results.flatMap(r => (r.overrideSkipped ?? []).map(sk => ({ ...sk, subfolder: r.subfolder }))),
60
+ }
61
+ : {}),
62
+ ...(params.includeMaintenance
63
+ ? {
64
+ maintenanceFindings: params.results.flatMap(r => r.maintenanceFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
65
+ }
66
+ : {}),
67
+ ...(params.includeLicenses
68
+ ? {
69
+ licenseFindings: params.results.flatMap(r => r.licenseFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
70
+ }
71
+ : {}),
72
+ scannedAt: new Date().toISOString(),
73
+ };
74
+ }
@@ -0,0 +1,41 @@
1
+ // Shared shape for reporting override rules that could not run. The terminal renderer
2
+ // and the HTML report both need the same grouping and the same sentence, and when this
3
+ // lived in both files they had already drifted to two different pluralisations.
4
+ import { pluralize } from "../utils/string.js";
5
+ /** Distinct rules skipped. Not the entry count: one rule can be recorded more than
6
+ * once with different reasons. */
7
+ export function skippedRuleCount(skipped) {
8
+ return new Set(skipped.map((entry) => entry.ruleId)).size;
9
+ }
10
+ /** The sentence both surfaces lead with, kept in one place so they cannot diverge. */
11
+ export function skippedHeadline(ruleCount) {
12
+ return `${ruleCount} override ${pluralize(ruleCount, "rule")} did not run, so this is not a complete override audit:`;
13
+ }
14
+ /**
15
+ * The reason text for a total registry failure. Shared because OA007 and OA010 record it
16
+ * from two different modules, and the sentence plus its pluralisation had already been
17
+ * written out twice, which is the same drift this module exists to stop.
18
+ */
19
+ export function registryFailureReason(count, noun) {
20
+ return `registry lookups failed for all ${count} ${noun} ${pluralize(count, "package")}`;
21
+ }
22
+ /**
23
+ * Rule ids grouped by the reason they were skipped, de-duplicated and sorted.
24
+ *
25
+ * Grouped by reason rather than keyed on specific rule ids, so it covers the lockfile
26
+ * and node_modules skips recorded in context-builder as well as the network-backed ones
27
+ * recorded in audit().
28
+ */
29
+ export function groupSkippedByReason(skipped) {
30
+ const byReason = new Map();
31
+ for (const entry of skipped) {
32
+ const ids = byReason.get(entry.reason) ?? [];
33
+ if (!ids.includes(entry.ruleId))
34
+ ids.push(entry.ruleId);
35
+ byReason.set(entry.reason, ids);
36
+ }
37
+ return [...byReason.entries()].map(([reason, ruleIds]) => ({
38
+ reason,
39
+ ruleIds: [...ruleIds].sort(),
40
+ }));
41
+ }
@@ -1,15 +1,12 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { chalk } from "../utils/chalk.js";
4
- import { serializeLicenseFindings } from "./license-findings-json.js";
5
- import { serializeFinding } from "./formatters.js";
6
4
  import { writeSarifReport, deriveLockfileUri } from "./sarif.js";
7
5
  import { writeCycloneDxReport } from "./cyclonedx.js";
8
6
  import { writeSpdxReport } from "./spdx.js";
9
7
  import { resolveDependencyEdges } from "./sbom-dependency-edges.js";
10
8
  import { resolveSbomFormat } from "../utils/sbom-format.js";
11
- import { overrideFindingsToJson } from "./override-findings-json.js";
12
- import { maintenanceFindingsToJson } from "./maintenance-findings-json.js";
9
+ import { buildScanJson } from "./scan-json.js";
13
10
  import { resolveOutputDir, displayOutputPath } from "./output-dir.js";
14
11
  function readProjectMeta(projectPath) {
15
12
  try {
@@ -35,36 +32,27 @@ export async function writeOutputs(options, scanState, scanInput, projectPath) {
35
32
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
36
33
  const jsonFilename = `cve-lite-scan-${ts}.json`;
37
34
  const jsonOutputPath = path.join(outputDir, jsonFilename);
38
- const payload = {
35
+ const payload = buildScanJson({
39
36
  projectPath,
40
- mode: scanInput.mode,
41
- source: scanInput.source,
42
- packageCount: scanInput.packages.length,
43
- findingCount: scanState.sorted.length,
44
- status: scanState.completeness.complete ? "ok" : "partial",
45
- complete: scanState.completeness.complete,
46
- diagnostics: scanState.completeness.diagnostics,
37
+ scanInput,
38
+ findings: scanState.sorted,
47
39
  suggestedFixCommands: scanState.suggestedFixCommands,
48
- notes: [...scanInput.notes, ...scanState.coverage],
49
- warnings: scanInput.warnings,
50
- skippedDependencies: scanInput.skippedDependencies,
51
- findings: scanState.sorted.map(finding => serializeFinding(finding, scanState.suggestedFixCommands)),
52
- };
53
- const overridePayload = overrideFindingsToJson(scanState.overrideFindings ?? []);
54
- const maintenancePayload = maintenanceFindingsToJson(scanState.maintenanceFindings ?? []);
55
- const licensePayload = scanState.licenseFindings && scanState.licenseFindings.length > 0
56
- ? {
57
- licenseFindings: serializeLicenseFindings(scanState.licenseFindings),
58
- ...(scanState.licenseLimitedToDirectOnly ? { licenseLimitedToDirectOnly: true } : {}),
59
- }
60
- : {};
61
- const combined = { ...payload, ...overridePayload, ...maintenancePayload, ...licensePayload };
62
- fs.writeFileSync(jsonOutputPath, JSON.stringify(combined, null, 2));
40
+ coverage: scanState.coverage,
41
+ completeness: scanState.completeness,
42
+ overrideFindings: scanState.overrideFindings,
43
+ // Only passed when override checking ran, so `[]` means "ran, nothing skipped" and
44
+ // absent means "never audited". An unconditional `[]` collapses those two.
45
+ overrideSkipped: scanState.overrideSkipped,
46
+ maintenanceFindings: scanState.maintenanceFindings,
47
+ licenseFindings: scanState.licenseFindings,
48
+ licenseLimitedToDirectOnly: scanState.licenseLimitedToDirectOnly,
49
+ });
50
+ fs.writeFileSync(jsonOutputPath, JSON.stringify(payload, null, 2));
63
51
  console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(displayOutputPath(jsonOutputPath))}`);
64
52
  }
65
53
  if (options.sarif) {
66
54
  const lockfileUri = deriveLockfileUri(scanInput);
67
- const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, scanState.overrideFindings, scanState.maintenanceFindings, scanState.licenseFindings, outputDir);
55
+ const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, scanState.overrideFindings, scanState.maintenanceFindings, scanState.licenseFindings, outputDir, scanState.overrideSkipped);
68
56
  console.log(`${chalk.gray("SARIF report written to")} ${chalk.cyan(sarifFilename)}`);
69
57
  }
70
58
  const sbomFormat = resolveSbomFormat(options);
@@ -1,5 +1,6 @@
1
1
  import { admittedKey } from "./context.js";
2
2
  import { fetchVersionsBatch } from "./parsing/registry.js";
3
+ import { registryFailureReason } from "../output/skipped-override-rules.js";
3
4
  import { looksLikeVersion, satisfiesRange, compareVersions } from "../utils/version.js";
4
5
  import { inferSeverity } from "../osv/severity.js";
5
6
  import { chunk } from "../utils/array.js";
@@ -49,7 +50,17 @@ export async function populateAdmittedVersions(ctx, opts) {
49
50
  const entries = rangeEntries(ctx);
50
51
  if (entries.length === 0)
51
52
  return;
52
- const versionsByName = await fetchVersionsBatch(entries.map((e) => e.name), opts.registry ?? {});
53
+ const { results: versionsByName, failed: versionFetchFailures } = await fetchVersionsBatch(entries.map((e) => e.name), opts.registry ?? {});
54
+ // Same reasoning as OA007 in api.ts: a total registry failure leaves this map empty and
55
+ // every entry below would `continue` past in silence, so OA010 would report nothing and
56
+ // look clean. Only a total failure is recorded, since a skip entry suppresses the rule.
57
+ if (versionsByName.size === 0 && versionFetchFailures.length > 0) {
58
+ ctx.skippedDetectors.push({
59
+ ruleId: "OA010",
60
+ reason: registryFailureReason(versionFetchFailures.length, "floored"),
61
+ });
62
+ return;
63
+ }
53
64
  const refs = [];
54
65
  // A (name, version) pair can be admitted by more than one override range, so
55
66
  // track which keys each pair belongs to and query the pair only once.
@@ -1,32 +1,85 @@
1
1
  import { populateAdmittedVersions } from "./admitted-scan.js";
2
2
  import { ALL_DETECTORS, VERIFY_DETECTORS } from "./detectors/index.js";
3
3
  import { applyComposite } from "./composite.js";
4
+ import { FLAG_CHECK_NETWORK } from "../cli/flags.js";
5
+ import { registryFailureReason } from "../output/skipped-override-rules.js";
4
6
  import { fetchDistTagsBatch } from "./parsing/registry.js";
7
+ /**
8
+ * Records the rules that cannot run under the given options, before any detector runs.
9
+ * Detectors self-suppress by matching their own id against this list, so these entries
10
+ * are load-bearing rather than cosmetic.
11
+ *
12
+ * Nothing is recorded when the manifest declares no overrides. There is no audit to be
13
+ * incomplete, so warning about it would be both noisy and untrue, and it would fire on
14
+ * every plain `--check-overrides` run. Same guard the lockfile and node_modules skips in
15
+ * context-builder already use.
16
+ */
17
+ function recordNetworkSkips(ctx, opts) {
18
+ if (ctx.overrideEntries.length === 0)
19
+ return;
20
+ const record = (ruleId, reason) => {
21
+ // audit() can be called more than once against one context; do not stack duplicates.
22
+ if (ctx.skippedDetectors.some((s) => s.ruleId === ruleId && s.reason === reason))
23
+ return;
24
+ ctx.skippedDetectors.push({ ruleId, reason });
25
+ };
26
+ if (!opts.checkNetwork) {
27
+ // Neither network-backed rule can run without the opt-in. Recorded rather than left
28
+ // to no-op on empty data: a scan that cannot run a rule has to say so instead of
29
+ // reporting a clean bill of health (#1222).
30
+ record("OA007", `requires ${FLAG_CHECK_NETWORK}`);
31
+ record("OA010", `requires ${FLAG_CHECK_NETWORK}`);
32
+ return;
33
+ }
34
+ if (!opts.advisorySource) {
35
+ // Distinct from the flag being absent: the caller opted in but wired no advisory
36
+ // source, which is ours to fix rather than the user's.
37
+ record("OA010", "no advisory source was available");
38
+ }
39
+ }
40
+ /**
41
+ * OA007's registry work, in its own function the way OA010's lives in
42
+ * populateAdmittedVersions. Never throws: a failure is recorded and the audit continues.
43
+ */
44
+ async function populateRegistryDistTags(ctx, opts) {
45
+ if (!opts.checkNetwork)
46
+ return;
47
+ const stringOverrideNames = ctx.overrideEntries
48
+ .filter((e) => typeof e.value === "string")
49
+ .map((e) => e.packageName);
50
+ if (stringOverrideNames.length === 0)
51
+ return;
52
+ try {
53
+ const { results, failed } = await fetchDistTagsBatch(stringOverrideNames, opts.registry ?? {});
54
+ for (const [name, tags] of results) {
55
+ ctx.registryDistTags.set(name, tags);
56
+ }
57
+ // Every lookup failed, so OA007 has no data at all. Without this the rule returns no
58
+ // findings and the scan reports a clean bill of health, which is exactly what happens
59
+ // behind a TLS proxy. Recorded only on a TOTAL failure, because a skip entry makes the
60
+ // detector suppress itself and a partial result is still worth reporting. The partial
61
+ // case is a known gap tracked separately.
62
+ if (results.size === 0 && failed.length > 0) {
63
+ ctx.skippedDetectors.push({
64
+ ruleId: "OA007",
65
+ reason: registryFailureReason(failed.length, "overridden"),
66
+ });
67
+ }
68
+ }
69
+ catch (err) {
70
+ ctx.skippedDetectors.push({
71
+ ruleId: "OA007",
72
+ reason: `registry calls failed: ${err instanceof Error ? err.message : String(err)}`,
73
+ });
74
+ }
75
+ }
5
76
  /**
6
77
  * Full audit: run all 8 detectors over the project, apply composite passes,
7
78
  * emit oa.detected per finding.
8
79
  */
9
80
  export async function audit(ctx, opts) {
10
- // OA007 network fetch - only when opted in.
11
- if (opts.checkNetwork) {
12
- const stringOverrideNames = ctx.overrideEntries
13
- .filter((e) => typeof e.value === "string")
14
- .map((e) => e.packageName);
15
- if (stringOverrideNames.length > 0) {
16
- try {
17
- const fetched = await fetchDistTagsBatch(stringOverrideNames, opts.registry ?? {});
18
- for (const [name, tags] of fetched) {
19
- ctx.registryDistTags.set(name, tags);
20
- }
21
- }
22
- catch (err) {
23
- ctx.skippedDetectors.push({
24
- ruleId: "OA007",
25
- reason: `registry calls failed: ${err instanceof Error ? err.message : String(err)}`,
26
- });
27
- }
28
- }
29
- }
81
+ recordNetworkSkips(ctx, opts);
82
+ await populateRegistryDistTags(ctx, opts);
30
83
  // OA010 network fetch - needs both the opt-in and an injected advisory source.
31
84
  if (opts.checkNetwork && opts.advisorySource) {
32
85
  try {
@@ -59,7 +112,8 @@ export async function audit(ctx, opts) {
59
112
  location: { file: f.location.file, jsonPath: f.location.jsonPath },
60
113
  });
61
114
  }
62
- return { findings };
115
+ // Copied, so a caller holding the result cannot mutate the context.
116
+ return { findings, skippedDetectors: [...ctx.skippedDetectors] };
63
117
  }
64
118
  /**
65
119
  * Post-fix verification: run OA001 and OA008 only, scoped to the just-touched