cve-lite-cli 1.37.0 → 1.38.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 (45) hide show
  1. package/README.md +20 -1
  2. package/dist/cli/args.js +120 -103
  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 +17 -2
  24. package/dist/overrides/detectors/index.js +2 -0
  25. package/dist/overrides/detectors/oa008-materialized.js +72 -13
  26. package/dist/overrides/detectors/oa009-stale-floor.js +12 -15
  27. package/dist/overrides/detectors/oa010-vulnerable-floor.js +5 -1
  28. package/dist/overrides/detectors/oa011-exceeds-range.js +128 -0
  29. package/dist/overrides/detectors/pd001-override-only-phantom.js +5 -4
  30. package/dist/overrides/detectors/pd002-transitive-only-phantom.js +5 -4
  31. package/dist/overrides/detectors/phantom-utils.js +29 -0
  32. package/dist/overrides/parsing/registry.js +79 -10
  33. package/dist/scan/multi-folder-scan.js +65 -51
  34. package/dist/scan/override-audit.js +49 -0
  35. package/dist/scan/single-scan.js +108 -33
  36. package/dist/scanner.js +8 -4
  37. package/dist/skills/content.js +4 -2
  38. package/dist/usage/scanner.js +219 -28
  39. package/dist/utils/contextual-signals.js +193 -0
  40. package/dist/utils/finding.js +5 -0
  41. package/dist/utils/package-json.js +66 -14
  42. package/dist/utils/severity.js +22 -0
  43. package/dist/utils/update-check.js +2 -1
  44. package/dist/utils/version.js +33 -19
  45. package/package.json +1 -1
@@ -4,28 +4,29 @@ import process from "node:process";
4
4
  import { EXIT_OK, EXIT_FINDINGS, EXIT_ERROR } from "../types.js";
5
5
  import { loadMultiplePackages } from "../parsers/multi-package.js";
6
6
  import { scanPackages, buildCoverageNotes } from "../scanner.js";
7
- import { sortFindingsForOutput, serializeFinding, logInfo } from "../output/formatters.js";
7
+ import { sortFindingsForOutput, logInfo } from "../output/formatters.js";
8
+ import { buildMultiFolderScanJson } from "../output/scan-json.js";
8
9
  import { resolveOutputDir, displayOutputPath } from "../output/output-dir.js";
9
10
  import { normalizeSeverity } from "../osv/severity.js";
10
11
  import { selectFindingsForTable } from "../output/finding-display.js";
11
12
  import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
12
13
  import { readDirectDependencyNames, hasOverrideEntries } from "../utils/package-json.js";
13
- import { DEFAULT_SEARCH_DEPTH, severityOrder, OVERRIDES_COMMAND } from "../constants.js";
14
+ import { DEFAULT_SEARCH_DEPTH, OVERRIDES_COMMAND } from "../constants.js";
14
15
  import { printMultiFolderResults } from "../output/multi-folder-printer.js";
15
16
  import { printOverrideHint } from "../output/printers.js";
16
17
  import { writeMultiFolderHtmlReport } from "../output/multi-folder-html-reporter.js";
17
18
  import { chalk } from "../utils/chalk.js";
18
19
  import { getCliVersion } from "../utils/version-info.js";
19
- import { buildOverrideContext, audit } from "../overrides/index.js";
20
+ import { runOverrideAudit } from "./override-audit.js";
20
21
  import { NULL_AUDIT_LOG } from "../audit-log/index.js";
21
22
  import { detectDM001 } from "../maintenance/dm001-maintenance-risk.js";
22
23
  import { detectLicenseIssues } from "../licenses/license-check.js";
23
24
  import { renderLicenseFindings } from "../output/license-terminal.js";
24
- import { reachesFailOn } from "../utils/severity.js";
25
+ import { failingGateSummary } from "../utils/severity.js";
25
26
  import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "../utils/baseline.js";
26
27
  import { pluralize } from "../utils/string.js";
27
28
  import { aggregateMultiFolderCompleteness, formatDiagnosticMessage, getCompletenessImpact, shouldFailForIncompleteScan, } from "./completeness.js";
28
- import { scanProjectForPackageUsage } from "../usage/scanner.js";
29
+ import { scanProjectForPackageUsage, usageScanTruncationWarning } from "../usage/scanner.js";
29
30
  export async function runMultiFolderScan(params) {
30
31
  const searchDepth = Math.max(0, Number(params.options.searchDepth || DEFAULT_SEARCH_DEPTH));
31
32
  const folders = loadMultiplePackages(params.projectRoot, !!params.options.prodOnly, searchDepth);
@@ -45,22 +46,37 @@ export async function runMultiFolderScan(params) {
45
46
  scanFilePath: scanInput.filePath,
46
47
  }, undefined, params.fetchImpl);
47
48
  // Mirror single-folder scanProject: annotate / filter by source imports per subfolder.
49
+ let usageTruncated = false;
48
50
  if (params.options.usage) {
49
51
  logInfo(`Scanning ${subfolder}/ source for usage hints...`, params.options);
50
52
  const pkgNames = new Set(findings.map(f => f.pkg.name));
51
- const usageData = scanProjectForPackageUsage(subfolderAbs, pkgNames);
53
+ const usageResult = scanProjectForPackageUsage(subfolderAbs, pkgNames);
54
+ const usageData = usageResult.usage;
55
+ usageTruncated = usageResult.truncated;
52
56
  for (const finding of findings) {
53
57
  const files = usageData[finding.pkg.name];
54
- if (files) {
55
- finding.usage = {
56
- imported: files.length > 0,
57
- files,
58
- };
58
+ if (!files)
59
+ continue;
60
+ if (files.length > 0) {
61
+ finding.usage = { imported: true, files };
62
+ }
63
+ else if (usageTruncated) {
64
+ // A truncated scan cannot prove a package is unused: unknown, not false.
65
+ finding.usage = { imported: null, files };
59
66
  }
67
+ else {
68
+ finding.usage = { imported: false, files };
69
+ }
70
+ }
71
+ if (usageResult.truncated) {
72
+ // Push into the folder's scan warnings so --json and the HTML report
73
+ // disclose it; printMultiFolderResults prints the same array in terminal mode.
74
+ scanInput.warnings.push(usageScanTruncationWarning({ subfolder, onlyUsed: !!params.options.onlyUsed }));
60
75
  }
61
76
  }
62
77
  let finalFindings = findings;
63
- if (params.options.onlyUsed) {
78
+ if (params.options.onlyUsed && !usageTruncated) {
79
+ // Truncated: "not scanned" is not "not imported", so don't narrow the gate.
64
80
  finalFindings = finalFindings.filter(f => f.usage?.imported);
65
81
  }
66
82
  let sorted = sortFindingsForOutput(finalFindings);
@@ -83,14 +99,21 @@ export async function runMultiFolderScan(params) {
83
99
  // Override hygiene is independent of the CVE ratchet/baseline. A --ratchet
84
100
  // run skips the override audit entirely (same boundary as single-folder).
85
101
  let overrideFindings = [];
102
+ let overrideSkipped = [];
86
103
  if (params.options.checkOverrides && !params.options.ratchet) {
87
- const overrideCtx = buildOverrideContext(subfolderAbs, {
104
+ // Per folder, through the same helper the single-folder path uses. Building the
105
+ // advisory source here is what lets OA010 run at all; passing only checkNetwork
106
+ // left it recording "no advisory source was available" for every folder.
107
+ const outcome = await runOverrideAudit({
108
+ projectPath: subfolderAbs,
109
+ checkNetwork: !!params.options.checkNetwork,
110
+ osvUrl: params.options.osvUrl,
88
111
  auditLog: params.auditLog ?? NULL_AUDIT_LOG,
89
112
  logger: { info: () => { }, warn: () => { }, error: () => { }, debug: () => { } },
90
- checkNetwork: !!params.options.checkNetwork,
113
+ fetchImpl: params.fetchImpl,
91
114
  });
92
- const overrideAudit = await audit(overrideCtx, { checkNetwork: !!params.options.checkNetwork });
93
- overrideFindings = overrideAudit.findings;
115
+ overrideFindings = outcome.findings;
116
+ overrideSkipped = outcome.skipped;
94
117
  }
95
118
  // Maintenance from the baseline-filtered set. Skipped under --ratchet because
96
119
  // that path always early-exits on CVE save/gate (same as single-folder).
@@ -124,6 +147,7 @@ export async function runMultiFolderScan(params) {
124
147
  allPackages: scanInput.packages,
125
148
  completeness,
126
149
  overrideFindings,
150
+ overrideSkipped,
127
151
  maintenanceFindings,
128
152
  licenseFindings,
129
153
  licenseLimitedToDirectOnly,
@@ -141,6 +165,9 @@ function handleMultiFolderRatchet(results, projectRoot, options) {
141
165
  let anyNewFindings = false;
142
166
  let hasDetectionGaps = false;
143
167
  for (const r of results) {
168
+ for (const warning of r.scanInput.warnings) {
169
+ console.log(chalk.yellow(warning));
170
+ }
144
171
  const { hasDetectionGap } = getCompletenessImpact(r.completeness);
145
172
  if (hasDetectionGap) {
146
173
  hasDetectionGaps = true;
@@ -252,33 +279,13 @@ export async function handleMultiFolderScan(params) {
252
279
  if (params.options.json) {
253
280
  // Match single-folder writeOutputs: timestamped file in cwd, not stdout dump.
254
281
  // Help text and CI both treat --json as "save a JSON file".
255
- const allFindings = results.flatMap(r => r.sorted.map(f => ({ ...serializeFinding(f, r.suggestedFixCommands), subfolder: r.subfolder })));
256
- const payload = {
257
- multiFolder: true,
282
+ const payload = buildMultiFolderScanJson({
283
+ results,
258
284
  projectPath: params.projectRoot,
259
- folders: results.map(r => r.subfolder),
260
- findingCount: allFindings.length,
261
- status: aggregatedCompleteness.complete ? "ok" : "partial",
262
- complete: aggregatedCompleteness.complete,
263
- diagnostics: aggregatedCompleteness.diagnostics,
264
- findings: allFindings,
265
- ...(params.options.checkOverrides
266
- ? {
267
- overrideFindings: results.flatMap(r => r.overrideFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
268
- }
269
- : {}),
270
- ...(params.options.checkMaintenance
271
- ? {
272
- maintenanceFindings: results.flatMap(r => r.maintenanceFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
273
- }
274
- : {}),
275
- ...(params.options.checkLicenses
276
- ? {
277
- licenseFindings: results.flatMap(r => r.licenseFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
278
- }
279
- : {}),
280
- scannedAt: new Date().toISOString(),
281
- };
285
+ includeOverrides: !!params.options.checkOverrides,
286
+ includeMaintenance: !!params.options.checkMaintenance,
287
+ includeLicenses: !!params.options.checkLicenses,
288
+ });
282
289
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
283
290
  const jsonFilename = `cve-lite-scan-${ts}.json`;
284
291
  const jsonOutputPath = path.join(resolveOutputDir(params.options.output), jsonFilename);
@@ -288,10 +295,13 @@ export async function handleMultiFolderScan(params) {
288
295
  else {
289
296
  printMultiFolderResults(results, params.options);
290
297
  if (params.options.checkOverrides) {
291
- const { renderOverrideFindings } = await import("../output/override-findings-terminal.js");
298
+ const { renderOverrideFindings, renderSkippedOverrideRules } = await import("../output/override-findings-terminal.js");
292
299
  for (const r of results) {
293
300
  process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray("override hygiene")}\n`);
294
- console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose, projectPath: path.join(params.projectRoot, r.subfolder) }));
301
+ console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose, projectPath: path.join(params.projectRoot, r.subfolder), rulesSkipped: r.overrideSkipped.length > 0 }));
302
+ if (r.overrideSkipped.length > 0) {
303
+ console.log(renderSkippedOverrideRules(r.overrideSkipped));
304
+ }
295
305
  }
296
306
  }
297
307
  if (params.options.checkMaintenance) {
@@ -334,22 +344,26 @@ export async function handleMultiFolderScan(params) {
334
344
  });
335
345
  console.log(`${chalk.gray("Report:")} ${chalk.cyan(reportPath)}`);
336
346
  }
337
- const failLevel = normalizeSeverity(params.options.failOn);
338
347
  const allSorted = results.flatMap(r => r.sorted);
339
348
  const allOverrideFindings = results.flatMap(r => r.overrideFindings);
340
349
  const allMaintenanceFindings = results.flatMap(r => r.maintenanceFindings);
341
- // Mirror single-folder exit policy in src/index.ts: CVE + override + maintenance
342
- // all count toward --fail-on. Without overrides here, multi-folder CI using
343
- // --check-overrides --fail-on high would exit 0 despite high OA findings.
344
- const shouldFail = allSorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]) ||
345
- reachesFailOn(allOverrideFindings, params.options.failOn) ||
346
- reachesFailOn(allMaintenanceFindings, params.options.failOn);
350
+ // Mirror single-folder exit policy in src/scan/single-scan.ts: CVE + override +
351
+ // maintenance all count toward --fail-on. Without overrides here, multi-folder CI
352
+ // using --check-overrides --fail-on high would exit 0 despite high OA findings.
353
+ const gateLine = failingGateSummary([
354
+ { label: "vulnerability", findings: allSorted },
355
+ { label: "override hygiene", findings: allOverrideFindings },
356
+ { label: "maintenance risk", findings: allMaintenanceFindings },
357
+ ], params.options.failOn);
358
+ const shouldFail = gateLine !== null;
347
359
  const incompleteFailure = shouldFailForIncompleteScan(aggregatedCompleteness, params.options.incompletePolicy);
348
360
  const exitCode = incompleteFailure
349
361
  ? EXIT_ERROR
350
362
  : shouldFail
351
363
  ? EXIT_FINDINGS
352
364
  : EXIT_OK;
365
+ if (gateLine && !params.options.json)
366
+ console.log(chalk.red(gateLine));
353
367
  auditLog.emit({
354
368
  ts: new Date(scanFinishedAt).toISOString(),
355
369
  type: "scan.finished",
@@ -0,0 +1,49 @@
1
+ // One place that runs the override-hygiene audit, so the three entry points cannot drift
2
+ // in what they wire up: a single-folder scan, a multi-folder scan, and the `overrides`
3
+ // subcommand. That drift is what #1222 was: the scan path threaded the network opt-in
4
+ // through but never built the advisory source OA010 needs, so the rule silently no-opped
5
+ // while the flag looked wired up.
6
+ import { audit, buildOverrideContext } from "../overrides/index.js";
7
+ import { createAdvisorySource } from "../scanner.js";
8
+ export async function runOverrideAudit(params) {
9
+ const ctx = buildOverrideContext(params.projectPath, {
10
+ auditLog: params.auditLog,
11
+ logger: params.logger,
12
+ checkNetwork: params.checkNetwork,
13
+ });
14
+ // OA010 needs an advisory source on top of the network opt-in. Built here rather than
15
+ // inside audit() so the overrides module stays free of a scanner import, and closed in
16
+ // the finally so an offline database handle never leaks.
17
+ //
18
+ // Always an online source. On the scan paths that is because validate.ts rejects both
19
+ // offline flags alongside `--check-network`. On the `overrides` subcommand it is because
20
+ // that subcommand dispatches BEFORE validateOptions runs and its parser has a tight flag
21
+ // allowlist that rejects `--offline` as unknown. Two different mechanisms, same result,
22
+ // so do not remove either believing the other covers it.
23
+ //
24
+ // A consequence: createAdvisorySource only returns a real `cleanup` on its offline
25
+ // branch, so the call below is a no-op on every reachable path today. Kept as insurance
26
+ // in case an offline route ever becomes legal here.
27
+ const advisory = params.checkNetwork
28
+ ? createAdvisorySource({
29
+ osvUrl: params.osvUrl,
30
+ debugLog: params.debugLog,
31
+ fetchImpl: params.fetchImpl,
32
+ })
33
+ : null;
34
+ try {
35
+ const result = await audit(ctx, {
36
+ checkNetwork: params.checkNetwork,
37
+ advisorySource: advisory?.advisorySource,
38
+ // The registry calls behind OA007 and OA010 must use the same fetch the scan uses,
39
+ // or a corporate CA certificate configured through `config set ca-cert` never
40
+ // reaches them. NODE_EXTRA_CA_CERTS is read only at process start, which is why a
41
+ // cert-aware fetch is threaded explicitly.
42
+ registry: { fetchImpl: params.fetchImpl },
43
+ });
44
+ return { findings: result.findings, skipped: result.skippedDetectors };
45
+ }
46
+ finally {
47
+ advisory?.cleanup();
48
+ }
49
+ }
@@ -5,25 +5,26 @@ import { normalizeSeverity } from "../osv/severity.js";
5
5
  import { OVERRIDES_COMMAND } from "../constants.js";
6
6
  import { chalk } from "../utils/chalk.js";
7
7
  import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
8
- import { scanProjectForPackageUsage } from "../usage/scanner.js";
8
+ import { scanProjectForPackageUsage, usageScanTruncationWarning } from "../usage/scanner.js";
9
9
  import { offlineDbSyncHint } from "../utils/network.js";
10
10
  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, reachesFailOn } from "../utils/severity.js";
14
+ import { countBySeverity, failingGateSummary } from "../utils/severity.js";
15
15
  import { buildReportData, writeHtmlReport } from "../output/html-reporter.js";
16
+ import { buildScanJson } from "../output/scan-json.js";
16
17
  import { writeOutputs } from "../output/write-outputs.js";
17
18
  import { selectFindingsForTable } from "../output/finding-display.js";
18
19
  import { printActionSummary, printCompactOutput, printCoverage, printFinalStatus, printOverrideHint, printSkippedDependencies, printSuggestedFixCommands, printSuggestedFixCommandSkips, printSummary, printTable, } from "../output/printers.js";
19
- import { renderOverrideFindings } from "../output/override-findings-terminal.js";
20
+ import { renderOverrideFindings, renderSkippedOverrideRules } from "../output/override-findings-terminal.js";
20
21
  import { detectDM001 } from "../maintenance/dm001-maintenance-risk.js";
21
22
  import { renderMaintenanceFindings } from "../output/maintenance-terminal.js";
22
23
  import { detectLicenseIssues } from "../licenses/license-check.js";
23
24
  import { renderLicenseFindings } from "../output/license-terminal.js";
24
25
  import { readDirectDependencyNames, hasOverrideEntries } from "../utils/package-json.js";
25
26
  import { applyFixesIfRequested, printFixModeSummary, writeFixResultJson, } from "../utils/fix-runner.js";
26
- import { audit, buildOverrideContext } from "../overrides/index.js";
27
+ import { runOverrideAudit } from "./override-audit.js";
27
28
  import { buildFixResultAppliedEntries, createPullRequestForFixes, } from "../utils/create-pr.js";
28
29
  import { buildCveFixAppliedEvent } from "../audit-log/events.js";
29
30
  import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "../utils/baseline.js";
@@ -151,8 +152,12 @@ export async function handleSingleFolderScan(params) {
151
152
  // --ratchet run skips the override audit entirely - override findings are never
152
153
  // baselined or suppressed.
153
154
  let overrideFindings = [];
155
+ let overrideSkipped = [];
154
156
  if (options.checkOverrides && !options.ratchet) {
155
- const overrideCtx = buildOverrideContext(projectPath, {
157
+ const outcome = await runOverrideAudit({
158
+ projectPath,
159
+ checkNetwork: !!options.checkNetwork,
160
+ osvUrl: options.osvUrl,
156
161
  auditLog,
157
162
  logger: {
158
163
  info: (msg) => debugLog("oa.info", { message: msg }),
@@ -160,10 +165,11 @@ export async function handleSingleFolderScan(params) {
160
165
  error: (msg) => debugLog("oa.error", { message: msg }),
161
166
  debug: (msg) => debugLog("oa.debug", { message: msg }),
162
167
  },
163
- checkNetwork: !!options.checkNetwork,
168
+ debugLog,
169
+ fetchImpl,
164
170
  });
165
- const auditResult = await audit(overrideCtx, { checkNetwork: !!options.checkNetwork });
166
- overrideFindings = auditResult.findings;
171
+ overrideFindings = outcome.findings;
172
+ overrideSkipped = outcome.skipped;
167
173
  }
168
174
  let maintenanceFindings = [];
169
175
  let licenseFindings = [];
@@ -439,6 +445,9 @@ export async function handleSingleFolderScan(params) {
439
445
  tableFindings: scanState.tableFindings,
440
446
  completeness: scanState.completeness,
441
447
  overrideFindings,
448
+ // undefined when override checking was not requested, so an absent field in the
449
+ // JSON means "never audited" rather than "audited and nothing skipped".
450
+ overrideSkipped: options.checkOverrides ? overrideSkipped : undefined,
442
451
  maintenanceFindings,
443
452
  licenseFindings,
444
453
  licenseLimitedToDirectOnly,
@@ -468,7 +477,10 @@ export async function handleSingleFolderScan(params) {
468
477
  }
469
478
  }
470
479
  if (options.checkOverrides && overrideFindings.length > 0) {
471
- console.log("\n" + renderOverrideFindings(overrideFindings, { verbose: true, projectPath }));
480
+ console.log("\n" + renderOverrideFindings(overrideFindings, { verbose: true, projectPath, rulesSkipped: overrideSkipped.length > 0 }));
481
+ }
482
+ if (options.checkOverrides && overrideSkipped.length > 0) {
483
+ console.log("\n" + renderSkippedOverrideRules(overrideSkipped));
472
484
  }
473
485
  if (options.checkMaintenance && maintenanceFindings.length > 0) {
474
486
  console.log("\n" + renderMaintenanceFindings(maintenanceFindings, { verbose: true }));
@@ -494,7 +506,10 @@ export async function handleSingleFolderScan(params) {
494
506
  licenseLimitedToDirectOnly: options.checkLicenses ? licenseLimitedToDirectOnly : undefined,
495
507
  });
496
508
  if (options.checkOverrides) {
497
- console.log("\n" + renderOverrideFindings(overrideFindings, { verbose: false, projectPath }));
509
+ console.log("\n" + renderOverrideFindings(overrideFindings, { verbose: false, projectPath, rulesSkipped: overrideSkipped.length > 0 }));
510
+ }
511
+ if (options.checkOverrides && overrideSkipped.length > 0) {
512
+ console.log("\n" + renderSkippedOverrideRules(overrideSkipped));
498
513
  }
499
514
  if (options.checkMaintenance && maintenanceFindings.length > 0) {
500
515
  console.log("\n" + renderMaintenanceFindings(maintenanceFindings, { verbose: false }));
@@ -520,15 +535,41 @@ export async function handleSingleFolderScan(params) {
520
535
  // undefined (not []) when override checking was not requested, so the HTML
521
536
  // report omits the Override hygiene panel entirely on a plain scan.
522
537
  overrideFindings: options.checkOverrides ? overrideFindings : undefined,
538
+ skippedOverrideRules: options.checkOverrides ? overrideSkipped : undefined,
523
539
  // Same undefined-vs-[] convention as overrideFindings above.
524
540
  maintenanceFindings: options.checkMaintenance ? maintenanceFindings : undefined,
525
541
  licenseFindings: options.checkLicenses ? licenseFindings : undefined,
526
542
  licenseLimitedToDirectOnly: options.checkLicenses ? licenseLimitedToDirectOnly : undefined,
527
543
  completeness: scanState.completeness,
528
544
  });
545
+ // report.json follows the --json schema, plus scannedAt/cliVersion for a
546
+ // saved artifact and per-finding riskSummary/nextAction (stdout --json
547
+ // stays unchanged via buildScanJson alone).
548
+ const jsonPayload = {
549
+ ...buildScanJson({
550
+ projectPath,
551
+ scanInput,
552
+ findings: scanState.sorted,
553
+ suggestedFixCommands: scanState.suggestedFixCommands,
554
+ coverage: scanState.coverage,
555
+ completeness: scanState.completeness,
556
+ overrideFindings,
557
+ // Gated on the flag deliberately, unlike overrideFindings above. An absent
558
+ // skippedOverrideRules means override checking never ran; an empty array means it
559
+ // ran and every rule ran. Passing this unconditionally would collapse the two.
560
+ overrideSkipped: options.checkOverrides ? overrideSkipped : undefined,
561
+ maintenanceFindings,
562
+ licenseFindings,
563
+ licenseLimitedToDirectOnly,
564
+ }),
565
+ scannedAt: reportData.scannedAt,
566
+ cliVersion: reportData.cliVersion,
567
+ findings: reportData.findings,
568
+ };
529
569
  const { reportPath } = await writeHtmlReport({
530
570
  outputDir,
531
571
  data: reportData,
572
+ jsonPayload,
532
573
  autoOpen: !options.noOpen,
533
574
  });
534
575
  console.log(`${chalk.gray("Report:")} ${chalk.cyan(reportPath)}`);
@@ -546,15 +587,20 @@ export async function handleSingleFolderScan(params) {
546
587
  console.log(chalk.yellow(`${scanState.sorted.length} new ${scanState.sorted.length === 1 ? "finding" : "findings"} above baseline - ${suppressedCount} existing ${suppressedCount === 1 ? "finding" : "findings"} suppressed`));
547
588
  }
548
589
  }
549
- // Override hygiene findings count toward --fail-on too, using the shared
550
- // reachesFailOn helper from src/utils/severity.ts, the same logic used by
551
- // the standalone `overrides` command. Without this, a CI run
590
+ // Override hygiene findings count toward --fail-on too. Without this, a CI run
552
591
  // of `cve-lite . --check-overrides --fail-on high` would exit 0 despite high-severity
553
592
  // override findings, giving a false sense of protection. overrideFindings is empty
554
593
  // unless --check-overrides (and non-ratchet), so this is a no-op otherwise.
555
- const shouldFail = reachesFailOn(scanState.sorted, options.failOn) ||
556
- reachesFailOn(overrideFindings, options.failOn) ||
557
- reachesFailOn(maintenanceFindings, options.failOn);
594
+ // The gate and the line that explains it come from one call, so the exit code
595
+ // and the printed reason cannot drift apart.
596
+ const gateLine = failingGateSummary([
597
+ { label: "vulnerability", findings: scanState.sorted },
598
+ { label: "override hygiene", findings: overrideFindings },
599
+ { label: "maintenance risk", findings: maintenanceFindings },
600
+ ], options.failOn);
601
+ const shouldFail = gateLine !== null;
602
+ if (gateLine && !options.json && !options.fix)
603
+ console.log(chalk.red(gateLine));
558
604
  // In fix mode, remaining transitive findings cannot be auto-fixed.
559
605
  // Exiting non-zero would prevent the Action PR step from running.
560
606
  const incompleteFailure = shouldFailForIncompleteScan(scanState.completeness, options.incompletePolicy);
@@ -581,42 +627,71 @@ export async function scanProject(params) {
581
627
  scanSource: params.scanInput.source,
582
628
  scanFilePath: params.scanInput.filePath,
583
629
  }, params.debugLog, params.fetchImpl);
630
+ let usageTruncated = false;
584
631
  if (params.options.usage) {
585
632
  logInfo(`Scanning project source for usage hints...`, params.options);
586
633
  const usageStartedAt = Date.now();
587
634
  const pkgNames = new Set(findings.map(f => f.pkg.name));
588
- const usageData = scanProjectForPackageUsage(params.projectPath, pkgNames);
635
+ const usageResult = scanProjectForPackageUsage(params.projectPath, pkgNames);
636
+ const usageData = usageResult.usage;
637
+ usageTruncated = usageResult.truncated;
589
638
  let matchedPackages = 0;
590
639
  for (const finding of findings) {
591
640
  const files = usageData[finding.pkg.name];
592
- if (files) {
593
- if (files.length > 0) {
594
- matchedPackages += 1;
595
- }
596
- finding.usage = {
597
- imported: files.length > 0,
598
- files,
599
- };
641
+ if (!files)
642
+ continue;
643
+ if (files.length > 0) {
644
+ matchedPackages += 1;
645
+ finding.usage = { imported: true, files };
646
+ }
647
+ else if (usageTruncated) {
648
+ // Absence during a truncated walk is not proof of non-use: unknown, not false.
649
+ finding.usage = { imported: null, files };
650
+ }
651
+ else {
652
+ // Only a complete scan can conclude a package is genuinely unused.
653
+ finding.usage = { imported: false, files };
600
654
  }
601
655
  }
656
+ if (usageResult.truncated) {
657
+ // Push into the scan warnings so machine consumers (--json, HTML report)
658
+ // see the same disclosure the terminal prints.
659
+ const warning = usageScanTruncationWarning({ onlyUsed: !!params.options.onlyUsed });
660
+ params.scanInput.warnings.push(warning);
661
+ logWarn(warning, params.options);
662
+ }
602
663
  if (params.options.debug) {
603
664
  params.debugLog("Usage scan", {
604
665
  durationMs: Date.now() - usageStartedAt,
605
666
  packagesChecked: pkgNames.size,
606
667
  matchedPackages,
668
+ truncated: usageResult.truncated,
669
+ scannedFiles: usageResult.scannedFiles,
607
670
  });
608
671
  }
609
672
  }
610
673
  let finalFindings = findings;
611
674
  if (params.options.onlyUsed) {
612
- const beforeCount = finalFindings.length;
613
- finalFindings = finalFindings.filter(f => f.usage?.imported);
614
- if (params.options.debug) {
615
- params.debugLog("Findings filtered", {
616
- reason: "only-used",
617
- before: beforeCount,
618
- after: finalFindings.length,
619
- });
675
+ if (usageTruncated) {
676
+ // Truncated: absence is not proof of unused; keep findings so --fail-on isn't narrowed.
677
+ if (params.options.debug) {
678
+ params.debugLog("Findings filtered", {
679
+ reason: "only-used-skipped-truncated-usage-scan",
680
+ before: findings.length,
681
+ after: findings.length,
682
+ });
683
+ }
684
+ }
685
+ else {
686
+ const beforeCount = finalFindings.length;
687
+ finalFindings = finalFindings.filter(f => f.usage?.imported);
688
+ if (params.options.debug) {
689
+ params.debugLog("Findings filtered", {
690
+ reason: "only-used",
691
+ before: beforeCount,
692
+ after: finalFindings.length,
693
+ });
694
+ }
620
695
  }
621
696
  }
622
697
  const offline = !!params.options.offline || !!params.options.offlineDb;
package/dist/scanner.js CHANGED
@@ -763,7 +763,7 @@ async function validateOneDirectFixTarget(finding, options) {
763
763
  };
764
764
  npmVersionCacheUpdated = true;
765
765
  };
766
- if (lowestKnownResolution.resolvedVersion) {
766
+ if (lowestKnownResolution.resolvedVersion && lowestKnownResolution.verified) {
767
767
  finding.validatedFirstFixedVersion = lowestKnownResolution.resolvedVersion;
768
768
  finding.validatedTargetScannedVersions = lowestKnownResolution.candidatesChecked;
769
769
  finding.validatedTargetKnownVulnerableVersions = lowestKnownResolution.candidatesKnownVulnerable;
@@ -798,11 +798,15 @@ async function validateOneDirectFixTarget(finding, options) {
798
798
  return npmVersionCacheUpdated;
799
799
  }
800
800
  const resolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
801
- finding.validatedFirstFixedVersion = resolution.resolvedVersion;
802
- finding.fixVersionValidationNote = resolution.note ?? lowestKnownResolution.note;
801
+ // Publication confirms availability, not that every advisory is fixed.
802
+ finding.validatedFirstFixedVersion = null;
803
+ finding.fixVersionValidationNote = [
804
+ lowestKnownResolution.note ?? `A non-vulnerable version could not be confirmed for ${finding.pkg.name}.`,
805
+ resolution.note,
806
+ ].filter(Boolean).join(" ");
803
807
  finding.validatedTargetScannedVersions = null;
804
808
  finding.validatedTargetKnownVulnerableVersions = null;
805
- setPublishedDate(resolution);
809
+ finding.fixVersionPublishedAt = null;
806
810
  logFixValidation();
807
811
  return npmVersionCacheUpdated;
808
812
  }
@@ -12,7 +12,8 @@ Key fields in each finding:
12
12
  - \`recommendedAction\` — human-readable fix guidance
13
13
  - \`cves\` — CVE IDs
14
14
  - \`dependencyPaths\` — chains showing how the package is pulled in
15
- - \`usage.imported\` — whether the package is actually imported in source files
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
16
17
 
17
18
  Top-level \`suggestedFixCommands\` contains grouped, copy-ready fix commands.
18
19
 
@@ -22,10 +23,11 @@ Top-level \`suggestedFixCommands\` contains grouped, copy-ready fix commands.
22
23
  2. Direct dependencies before transitive
23
24
  3. If \`usage.imported === false\`, flag as lower practical risk but do not dismiss
24
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
27
 
26
28
  ### Codebase analysis
27
29
 
28
- - Cross-reference vulnerable packages against source file imports to confirm reachability
30
+ - Cross-reference vulnerable packages against source file imports as a heuristic only; an import match is not proof of runtime reachability
29
31
  - Check \`package.json\` version constraints for direct dependency findings
30
32
  - Use \`dependencyPaths\` to trace transitive chains and identify which parent package to upgrade
31
33
  - Look for patterns: a single parent responsible for multiple transitive findings (fixing the parent clears all of them)