cve-lite-cli 1.24.0 → 1.26.0-beta.1

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 (77) hide show
  1. package/README.md +83 -2
  2. package/assets/OWASP_Logo_Black_TM.png +0 -0
  3. package/assets/logo-with-title-removebg-preview.png +0 -0
  4. package/dist/advisory/local-db.js +7 -1
  5. package/dist/advisory/osv-advisory-source.js +2 -1
  6. package/dist/audit-log/events.js +3 -0
  7. package/dist/audit-log/handle.js +20 -0
  8. package/dist/audit-log/index.js +16 -0
  9. package/dist/audit-log/ndjson-writer.js +28 -0
  10. package/dist/cli/args.js +75 -0
  11. package/dist/cli/fix-overrides-hook.js +64 -0
  12. package/dist/cli/help.js +24 -1
  13. package/dist/cli/overrides.js +67 -0
  14. package/dist/cli/validate.js +9 -1
  15. package/dist/index.js +310 -21
  16. package/dist/osv/cache.js +28 -4
  17. package/dist/output/formatters.js +22 -18
  18. package/dist/output/html-reporter.js +37 -8
  19. package/dist/output/logos.js +18 -0
  20. package/dist/output/multi-folder-html-reporter.js +3 -4
  21. package/dist/output/override-findings-html.js +63 -0
  22. package/dist/output/override-findings-json.js +3 -0
  23. package/dist/output/override-findings-sarif.js +52 -0
  24. package/dist/output/override-findings-terminal.js +106 -0
  25. package/dist/output/printers.js +66 -23
  26. package/dist/output/sarif.js +77 -8
  27. package/dist/output/write-outputs.js +7 -3
  28. package/dist/overrides/api.js +79 -0
  29. package/dist/overrides/composite.js +23 -0
  30. package/dist/overrides/context-builder.js +150 -0
  31. package/dist/overrides/context.js +3 -0
  32. package/dist/overrides/detectors/index.js +23 -0
  33. package/dist/overrides/detectors/oa001-orphaned-target.js +36 -0
  34. package/dist/overrides/detectors/oa002-floating-tag.js +40 -0
  35. package/dist/overrides/detectors/oa003-wrong-section.js +48 -0
  36. package/dist/overrides/detectors/oa004-surpassed-pin.js +49 -0
  37. package/dist/overrides/detectors/oa005-nested-ineffective.js +128 -0
  38. package/dist/overrides/detectors/oa006-coupled-platform-binary.js +170 -0
  39. package/dist/overrides/detectors/oa007-frozen-latest.js +69 -0
  40. package/dist/overrides/detectors/oa008-materialized.js +75 -0
  41. package/dist/overrides/detectors/platform-binary.js +37 -0
  42. package/dist/overrides/fixer.js +199 -0
  43. package/dist/overrides/index.js +5 -0
  44. package/dist/overrides/parsing/installed-tree.js +164 -0
  45. package/dist/overrides/parsing/json-pointer.js +8 -0
  46. package/dist/overrides/parsing/node-modules.js +19 -0
  47. package/dist/overrides/parsing/package-json.js +139 -0
  48. package/dist/overrides/parsing/registry.js +66 -0
  49. package/dist/overrides/types.js +2 -0
  50. package/dist/parsers/pnpm-lock.js +46 -3
  51. package/dist/parsers/yarn-lock.js +2 -2
  52. package/dist/remediation/fix-commands.js +59 -5
  53. package/dist/remediation/npm-registry.js +55 -43
  54. package/dist/remediation/npm-transitive-resolution.js +2 -2
  55. package/dist/remediation/transitive-chain-resolver.js +100 -0
  56. package/dist/scan/multi-folder-scan.js +37 -1
  57. package/dist/scanner.js +122 -46
  58. package/dist/types.js +13 -1
  59. package/dist/utils/baseline.js +16 -0
  60. package/dist/utils/create-pr.js +19 -4
  61. package/dist/utils/fix-runner.js +6 -0
  62. package/dist/utils/package-json.js +21 -0
  63. package/dist/utils/severity.js +16 -0
  64. package/dist/utils/string.js +34 -0
  65. package/dist/utils/validate-url.js +223 -0
  66. package/dist/utils/version.js +135 -2
  67. package/package.json +8 -2
  68. package/dist/learn/keypress.js +0 -50
  69. package/dist/learn/runner.js +0 -96
  70. package/dist/learn/scenario.js +0 -47
  71. package/dist/learn/session.js +0 -36
  72. package/dist/learn/types.js +0 -1
  73. package/dist/llm/client.js +0 -40
  74. package/dist/llm/config.js +0 -48
  75. package/dist/llm/explainer.js +0 -31
  76. package/dist/output/logo-base64.js +0 -1
  77. package/dist/output/owasp-logo-base64.js +0 -1
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import path from "node:path";
3
3
  import process from "node:process";
4
+ import { existsSync } from "node:fs";
4
5
  import { parseArgs } from "./cli/args.js";
5
- import { printBanner, printHelp } from "./cli/help.js";
6
+ import { printBanner, printHelp, printOverridesHelp } from "./cli/help.js";
6
7
  import { validateOptions } from "./cli/validate.js";
7
8
  import { loadPackages, buildNoPackagesMessage } from "./parsers/index.js";
8
9
  import { scanPackages, buildCoverageNotes, createAdvisorySource } from "./scanner.js";
@@ -17,22 +18,26 @@ import { scanProjectForPackageUsage } from "./usage/scanner.js";
17
18
  import { getCliVersion } from "./utils/version-info.js";
18
19
  import { blockedAdvisoryRequestHint, fetchErrorCaCertHint, isLikelyBlockedAdvisoryRequestError, isRateLimitError, isServerError, isSslCertificateError, offlineDbSyncHint, rateLimitAdvisoryRequestHint, serverAdvisoryRequestHint, sslCertificateErrorHint, } from "./utils/network.js";
19
20
  import { formatAdvisoryDbFreshness } from "./utils/time.js";
20
- import { pluralize } from "./utils/string.js";
21
+ import { pluralize, nearestCommand } from "./utils/string.js";
22
+ import { EXIT_ERROR } from "./types.js";
21
23
  import { formatAdvisorySourceLine, logInfo, logWarn, printCacheSummary, sortFindingsForOutput } from "./output/formatters.js";
22
24
  import { countBySeverity } from "./utils/severity.js";
23
25
  import { buildReportData, writeHtmlReport } from "./output/html-reporter.js";
24
26
  import { writeOutputs } from "./output/write-outputs.js";
25
27
  import { selectFindingsForTable } from "./output/finding-display.js";
26
- import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } from "./output/printers.js";
28
+ import { printActionSummary, printCompactOutput, printCoverage, printFinalStatus, printOverrideHint, printSkippedDependencies, printSuggestedFixCommands, printSuggestedFixCommandSkips, printSummary, printTable, } from "./output/printers.js";
29
+ import { renderOverrideFindings } from "./output/override-findings-terminal.js";
27
30
  import { installSkill } from "./skills/install.js";
28
31
  import { readConfig, validateCaCertFile } from "./cli/config.js";
29
32
  import { runConfigCommand } from "./cli/config-command.js";
30
- import { readDirectDependencyNames } from "./utils/package-json.js";
31
- import { applyFixesIfRequested, printFixModeSummary, } from "./utils/fix-runner.js";
33
+ import { readDirectDependencyNames, hasOverrideEntries } from "./utils/package-json.js";
34
+ import { applyFixesIfRequested, printFixModeSummary, writeFixResultJson, } from "./utils/fix-runner.js";
35
+ import { createAuditLog } from "./audit-log/index.js";
36
+ import { audit, buildOverrideContext } from "./overrides/index.js";
32
37
  import { hasRootLockfile, findNestedLockfiles } from "./parsers/multi-package.js";
33
38
  import { handleMultiFolderScan } from "./scan/multi-folder-scan.js";
34
- import { createPullRequestForFixes, } from "./utils/create-pr.js";
35
- import { readBaseline, writeBaseline, filterNewFindings } from "./utils/baseline.js";
39
+ import { collectAdvisoryIdsForPackage, createPullRequestForFixes, } from "./utils/create-pr.js";
40
+ import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "./utils/baseline.js";
36
41
  let parsedArgs = null;
37
42
  try {
38
43
  parsedArgs = parseArgs(process.argv.slice(2));
@@ -47,7 +52,12 @@ if (parsedArgs) {
47
52
  const { command, options, projectArg } = parsedArgs;
48
53
  const cliVersion = getCliVersion();
49
54
  if (options.help) {
50
- printHelp();
55
+ if (command === "overrides") {
56
+ printOverridesHelp();
57
+ }
58
+ else {
59
+ printHelp();
60
+ }
51
61
  process.exit(0);
52
62
  }
53
63
  else if (options.version) {
@@ -56,11 +66,25 @@ if (parsedArgs) {
56
66
  }
57
67
  else {
58
68
  const projectPath = path.resolve(projectArg || ".");
69
+ // A known command would have been dispatched before this branch, so an explicit
70
+ // first argument that does not resolve to an existing path is almost certainly a
71
+ // mistyped command (e.g. `cve-lite frobnicate`). Error instead of silently
72
+ // scanning a nonexistent path and reporting "0 packages, exit 0" - a clean exit
73
+ // on a typo'd command is a foot-gun for a security tool. Existing directories
74
+ // still scan unchanged; the guard only fires on nonexistent paths.
75
+ if (command === "scan" && projectArg && !existsSync(projectPath)) {
76
+ const near = nearestCommand(projectArg);
77
+ console.error(chalk.red(`Error: '${projectArg}' is not an existing path or a known command.` +
78
+ (near ? ` Did you mean '${near}'?` : "")));
79
+ console.error(chalk.gray("Run 'cve-lite --help' for usage."));
80
+ process.exit(EXIT_ERROR);
81
+ }
59
82
  const batchSize = Number(options.batchSize || DEFAULT_BATCH_SIZE);
60
83
  const searchDepth = Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH));
61
84
  const debugSession = createDebugLogger(!!options.debug);
62
85
  const debugLog = debugSession.log;
63
86
  const scanStartedAt = Date.now();
87
+ const auditLogHandle = createAuditLog(options.auditLog ?? process.env.CVE_LITE_AUDIT_LOG);
64
88
  async function main() {
65
89
  printBanner(options);
66
90
  debugSession.announcePath();
@@ -136,7 +160,26 @@ if (parsedArgs) {
136
160
  process.exit(0);
137
161
  return;
138
162
  }
139
- validateOptions(options);
163
+ if (command === "overrides") {
164
+ const { runOverrides } = await import("./cli/overrides.js");
165
+ const logger = {
166
+ info: (msg) => console.log(msg),
167
+ warn: (msg) => console.warn(msg),
168
+ error: (msg) => console.error(msg),
169
+ debug: (msg) => console.debug(msg),
170
+ };
171
+ const exitCode = await runOverrides({
172
+ projectArg,
173
+ options,
174
+ logger,
175
+ auditLog: auditLogHandle,
176
+ });
177
+ auditLogHandle.close();
178
+ process.exit(exitCode);
179
+ }
180
+ const validationWarning = await validateOptions(options);
181
+ if (validationWarning)
182
+ logWarn(validationWarning, options);
140
183
  // Multi-folder mode: if no root lockfile and 2+ nested lockfiles exist,
141
184
  // route to dedicated multi-folder handler instead of single-lockfile scan
142
185
  const nestedLockfiles = findNestedLockfiles(projectPath, searchDepth);
@@ -204,6 +247,23 @@ if (parsedArgs) {
204
247
  count: packages.length,
205
248
  source: scanInput.source,
206
249
  });
250
+ // Emit scan.started event after loading packages
251
+ const scanStartTime = Date.now();
252
+ auditLogHandle.emit({
253
+ ts: new Date().toISOString(),
254
+ type: "scan.started",
255
+ schemaVersion: 1,
256
+ projectPath,
257
+ mode: scanInput.mode,
258
+ source: scanInput.source,
259
+ flags: {
260
+ fix: options.fix === true,
261
+ json: options.json === true,
262
+ prodOnly: options.prodOnly === true,
263
+ offline: options.offline === true,
264
+ checkOverrides: options.checkOverrides === true,
265
+ },
266
+ });
207
267
  if (!options.ratchet) {
208
268
  logInfo(`Parsed ${packages.length} ${pluralize(packages.length, "package")} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
209
269
  printCacheSummary(options.cacheDir, options);
@@ -216,6 +276,15 @@ if (parsedArgs) {
216
276
  if (packages.length === 0) {
217
277
  debugLog("Scan skipped", { reason: "no packages found", projectPath });
218
278
  logWarn(buildNoPackagesMessage(projectPath), options);
279
+ auditLogHandle.emit({
280
+ ts: new Date().toISOString(),
281
+ type: "scan.finished",
282
+ schemaVersion: 1,
283
+ durationMs: Date.now() - scanStartTime,
284
+ findingsCount: 0,
285
+ exitCode: 0,
286
+ });
287
+ auditLogHandle.close();
219
288
  process.exit(0);
220
289
  return;
221
290
  }
@@ -233,6 +302,38 @@ if (parsedArgs) {
233
302
  let fixResult = null;
234
303
  let baseline = readBaseline(projectArg ?? ".");
235
304
  let suppressedCount = 0;
305
+ // Collect override findings if --check-overrides is set.
306
+ // Boundary: override hygiene is independent of the CVE ratchet/baseline. The
307
+ // baseline only ever records CVE findings (see src/utils/baseline.ts), so a
308
+ // --ratchet run skips the override audit entirely - override findings are never
309
+ // baselined or suppressed.
310
+ let overrideFindings = [];
311
+ if (options.checkOverrides && !options.ratchet) {
312
+ const overrideCtx = buildOverrideContext(projectPath, {
313
+ auditLog: auditLogHandle,
314
+ logger: {
315
+ info: (msg) => debugLog("oa.info", { message: msg }),
316
+ warn: (msg) => debugLog("oa.warn", { message: msg }),
317
+ error: (msg) => debugLog("oa.error", { message: msg }),
318
+ debug: (msg) => debugLog("oa.debug", { message: msg }),
319
+ },
320
+ checkNetwork: !!options.checkNetwork,
321
+ });
322
+ const auditResult = await audit(overrideCtx, { checkNetwork: !!options.checkNetwork });
323
+ overrideFindings = auditResult.findings;
324
+ }
325
+ // Emit cve.detected for each CVE finding
326
+ for (const f of scanState.sorted) {
327
+ auditLogHandle.emit({
328
+ ts: new Date().toISOString(),
329
+ type: "cve.detected",
330
+ schemaVersion: 1,
331
+ package: { name: f.pkg.name, version: f.pkg.version },
332
+ severity: f.severity,
333
+ cveAliases: f.cveAliases,
334
+ vulnerabilityIds: f.vulnerabilities.map((v) => v.id),
335
+ });
336
+ }
236
337
  if (options.fix) {
237
338
  fixResult = await applyFixesIfRequested({
238
339
  plan: scanState.suggestedFixCommands,
@@ -248,6 +349,15 @@ if (parsedArgs) {
248
349
  if (packages.length === 0) {
249
350
  debugLog("Scan skipped", { reason: "no packages found after fix rescan", projectPath });
250
351
  logWarn(buildNoPackagesMessage(projectPath), options);
352
+ auditLogHandle.emit({
353
+ ts: new Date().toISOString(),
354
+ type: "scan.finished",
355
+ schemaVersion: 1,
356
+ durationMs: Date.now() - scanStartTime,
357
+ findingsCount: 0,
358
+ exitCode: 0,
359
+ });
360
+ auditLogHandle.close();
251
361
  process.exit(0);
252
362
  return;
253
363
  }
@@ -260,6 +370,64 @@ if (parsedArgs) {
260
370
  });
261
371
  }
262
372
  }
373
+ let overridesFixHookResult = null;
374
+ // Override hygiene is opt-in. Only run the fix hook (which can patch
375
+ // package.json) when --check-overrides was requested, so `cve-lite . --fix`
376
+ // stays a pure CVE operation and never touches overrides unasked.
377
+ if (options.fix && fixResult && options.checkOverrides) {
378
+ const { runOverridesFixHook } = await import("./cli/fix-overrides-hook.js");
379
+ const projectPathResolved = path.resolve(projectArg ?? ".");
380
+ // Collect CVE-touched targets from cve-lite's fix result.
381
+ const cveFixTargets = fixResult.applied.map((entry) => ({
382
+ name: entry.package,
383
+ version: entry.to,
384
+ }));
385
+ // Create a simple logger adapter if needed
386
+ const hookLogger = {
387
+ info: (msg) => debugLog("hook.info", { message: msg }),
388
+ warn: (msg) => debugLog("hook.warn", { message: msg }),
389
+ error: (msg) => debugLog("hook.error", { message: msg }),
390
+ debug: (msg) => debugLog("hook.debug", { message: msg }),
391
+ };
392
+ overridesFixHookResult = await runOverridesFixHook({
393
+ projectPath: projectPathResolved,
394
+ auditLog: auditLogHandle,
395
+ logger: hookLogger,
396
+ cveFixTargets,
397
+ });
398
+ if (!overridesFixHookResult.verifyOk) {
399
+ debugLog("overrides-fix-hook verify failed", {
400
+ failures: overridesFixHookResult.verifyFailures,
401
+ });
402
+ console.log(chalk.red(`Overrides fix verify failed:\n${overridesFixHookResult.verifyFailures
403
+ .map((v) => ` ${v.ruleId} ${v.package}: ${v.reason}`)
404
+ .join("\n")}`));
405
+ auditLogHandle.emit({
406
+ ts: new Date().toISOString(),
407
+ type: "scan.finished",
408
+ schemaVersion: 1,
409
+ durationMs: Date.now() - scanStartTime,
410
+ findingsCount: scanState.sorted.length + overrideFindings.length,
411
+ exitCode: 2,
412
+ });
413
+ auditLogHandle.close();
414
+ process.exit(2);
415
+ }
416
+ }
417
+ // Emit cve.fix.applied for each target in the fix plan
418
+ if (scanState.suggestedFixCommands?.targets) {
419
+ for (const target of scanState.suggestedFixCommands.targets) {
420
+ auditLogHandle.emit({
421
+ ts: new Date().toISOString(),
422
+ type: "cve.fix.applied",
423
+ schemaVersion: 1,
424
+ package: target.package,
425
+ fromVersion: target.currentVersion ?? "unknown",
426
+ toVersion: target.targetVersion,
427
+ mechanism: target.kind,
428
+ });
429
+ }
430
+ }
263
431
  if (options.fix) {
264
432
  printFixModeSummary({
265
433
  fixResult,
@@ -267,8 +435,26 @@ if (parsedArgs) {
267
435
  findingsAfterFix: scanState.sorted.length,
268
436
  remainingBySeverity: countBySeverity(scanState.sorted),
269
437
  });
438
+ // Write fix result JSON for Action-level PR creation.
439
+ // Written even when appliedFixCount is 0 so the Action can detect
440
+ // the nothing-to-fix case without parsing stdout.
441
+ const fixResultJson = {
442
+ appliedFixCount: fixResult?.appliedFixCount ?? 0,
443
+ findingsBeforeFix,
444
+ findingsAfterFix: scanState.sorted.length,
445
+ applied: (fixResult?.applied ?? []).map(entry => ({
446
+ package: entry.package,
447
+ from: entry.from,
448
+ to: entry.to,
449
+ advisories: collectAdvisoryIdsForPackage(findingsBeforeFixList, entry.package),
450
+ })),
451
+ };
452
+ writeFixResultJson(fixResultJson, projectPath);
270
453
  if (options.createPr && fixResult) {
271
- if (fixResult.appliedFixCount === 0) {
454
+ // Override hygiene fixes also land in package.json (staged by create-pr), so
455
+ // a PR is warranted when either CVE fixes or override fixes were applied.
456
+ const overrideFixCount = overridesFixHookResult?.applied ?? 0;
457
+ if (fixResult.appliedFixCount === 0 && overrideFixCount === 0) {
272
458
  logWarn("Skipping pull request creation: no direct fixes were applied.", options);
273
459
  }
274
460
  else {
@@ -280,6 +466,7 @@ if (parsedArgs) {
280
466
  fixResult,
281
467
  findingsBeforeFix: findingsBeforeFixList,
282
468
  findingsAfterFix: scanState.sorted,
469
+ overrideFixCount,
283
470
  });
284
471
  if (prResult.skipped) {
285
472
  logWarn(prResult.skipReason ?? "Pull request was not created.", options);
@@ -295,12 +482,63 @@ if (parsedArgs) {
295
482
  }
296
483
  }
297
484
  else {
298
- // --ratchet: save baseline and exit 0
485
+ // --ratchet: with no baseline yet, save the current findings. With an
486
+ // existing baseline, GATE instead of re-saving - fail on findings not in the
487
+ // baseline. Re-saving here would silently absorb a new vulnerability into a
488
+ // fresh baseline, so a ratcheted CI job could never fail on a regression.
299
489
  if (options.ratchet) {
300
- writeBaseline(projectArg ?? ".", scanState.sorted);
301
- const count = scanState.sorted.length;
302
- console.log(chalk.green(`✓ Baseline saved to .cve-lite/baseline.json with ${count} ${count === 1 ? "finding" : "findings"}. Future scans will only report findings above this baseline.`));
303
- process.exit(0);
490
+ const outcome = ratchetOutcome(baseline, scanState.sorted);
491
+ if (outcome.action === "save") {
492
+ writeBaseline(projectArg ?? ".", scanState.sorted);
493
+ const count = scanState.sorted.length;
494
+ console.log(chalk.green(`✓ Baseline saved to .cve-lite/baseline.json with ${count} ${count === 1 ? "finding" : "findings"}. Future scans will only report findings above this baseline.`));
495
+ if (options.checkOverrides) {
496
+ console.log(chalk.gray("Note: override hygiene (--check-overrides) is not part of the ratchet baseline; run `cve-lite overrides` to audit overrides."));
497
+ }
498
+ auditLogHandle.emit({
499
+ ts: new Date().toISOString(),
500
+ type: "scan.finished",
501
+ schemaVersion: 1,
502
+ durationMs: Date.now() - scanStartTime,
503
+ findingsCount: scanState.sorted.length,
504
+ exitCode: 0,
505
+ });
506
+ auditLogHandle.close();
507
+ process.exit(0);
508
+ return;
509
+ }
510
+ const { newFindings, suppressedCount } = outcome;
511
+ const suppressedLabel = `${suppressedCount} existing ${suppressedCount === 1 ? "finding" : "findings"} suppressed`;
512
+ if (newFindings.length === 0) {
513
+ console.log(chalk.green(`No new findings above baseline - ${suppressedLabel}`));
514
+ auditLogHandle.emit({
515
+ ts: new Date().toISOString(),
516
+ type: "scan.finished",
517
+ schemaVersion: 1,
518
+ durationMs: Date.now() - scanStartTime,
519
+ findingsCount: scanState.sorted.length,
520
+ exitCode: 0,
521
+ });
522
+ auditLogHandle.close();
523
+ process.exit(0);
524
+ return;
525
+ }
526
+ console.log(chalk.red(`${newFindings.length} new ${newFindings.length === 1 ? "finding" : "findings"} above baseline - ${suppressedLabel}`));
527
+ for (const f of newFindings) {
528
+ const ids = f.vulnerabilities.map(v => v.id).join(", ");
529
+ console.log(` ${chalk.yellow(f.severity)} ${f.pkg.name}@${f.pkg.version}${ids ? ` (${ids})` : ""}`);
530
+ }
531
+ console.log(chalk.gray("To accept these, re-baseline intentionally by deleting .cve-lite/baseline.json and re-running --ratchet."));
532
+ auditLogHandle.emit({
533
+ ts: new Date().toISOString(),
534
+ type: "scan.finished",
535
+ schemaVersion: 1,
536
+ durationMs: Date.now() - scanStartTime,
537
+ findingsCount: newFindings.length,
538
+ exitCode: 1,
539
+ });
540
+ auditLogHandle.close();
541
+ process.exit(1);
304
542
  return;
305
543
  }
306
544
  // auto-apply baseline if it exists - filter before output
@@ -317,13 +555,19 @@ if (parsedArgs) {
317
555
  coverage: scanState.coverage,
318
556
  minSeverity: scanState.minSeverity,
319
557
  tableFindings: scanState.tableFindings,
558
+ overrideFindings,
320
559
  }, scanInput, projectPath);
321
560
  if (!(options.json || options.sarif || options.cdx) || options.verbose) {
322
561
  const offline = !!options.offline || !!options.offlineDb;
562
+ const showOverrideHint = !options.checkOverrides && !options.ratchet && hasOverrideEntries(projectPath);
323
563
  if (options.verbose) {
564
+ const overrideCount = options.checkOverrides ? overrideFindings.length : 0;
324
565
  printSummary(scanState.sorted, packages.length, scanInput);
325
- printActionSummary(scanState.sorted);
326
- printSuggestedFixCommands(scanState.sorted, scanInput, { offline });
566
+ const pmLabel = scanState.suggestedFixCommands
567
+ ? `${chalk.cyan(scanState.suggestedFixCommands.packageManager)} ${chalk.gray(`(${scanState.suggestedFixCommands.sourceLabel})`)}`
568
+ : undefined;
569
+ printActionSummary(scanState.sorted, overrideCount, pmLabel);
570
+ printSuggestedFixCommands(scanState.sorted, scanInput, { offline, overrideCount });
327
571
  printSuggestedFixCommandSkips(scanState.sorted, scanInput, { offline });
328
572
  if (scanInput.skippedDependencies.length > 0) {
329
573
  printSkippedDependencies(scanInput.skippedDependencies);
@@ -337,11 +581,24 @@ if (parsedArgs) {
337
581
  logInfo(`No findings met the table threshold of ${scanState.minSeverity}. Re-run with --all to show everything.`, options);
338
582
  }
339
583
  }
584
+ if (options.checkOverrides && overrideFindings.length > 0) {
585
+ console.log(renderOverrideFindings(overrideFindings, { verbose: true }));
586
+ }
340
587
  printCoverage([...scanInput.notes, ...scanState.coverage]);
341
- printFinalStatus(scanState.sorted);
588
+ printFinalStatus(scanState.sorted, overrideCount);
589
+ if (showOverrideHint)
590
+ printOverrideHint();
342
591
  }
343
592
  else {
344
- printCompactOutput(scanState.sorted, scanInput, { offline, all: !!options.all });
593
+ const compactPmLabel = scanState.suggestedFixCommands
594
+ ? `${chalk.cyan(scanState.suggestedFixCommands.packageManager)} ${chalk.gray(`(${scanState.suggestedFixCommands.sourceLabel})`)}`
595
+ : undefined;
596
+ printCompactOutput(scanState.sorted, scanInput, { offline, all: !!options.all, packageManager: compactPmLabel });
597
+ if (options.checkOverrides) {
598
+ console.log(renderOverrideFindings(overrideFindings, { verbose: false }));
599
+ }
600
+ if (showOverrideHint)
601
+ printOverrideHint();
345
602
  }
346
603
  }
347
604
  }
@@ -357,6 +614,9 @@ if (parsedArgs) {
357
614
  suggestedFixCommands: scanState.suggestedFixCommands,
358
615
  notes: [...scanInput.notes, ...scanState.coverage],
359
616
  warnings: scanInput.warnings,
617
+ // undefined (not []) when override checking was not requested, so the HTML
618
+ // report omits the Override hygiene panel entirely on a plain scan.
619
+ overrideFindings: options.checkOverrides ? overrideFindings : undefined,
360
620
  });
361
621
  const { reportPath } = await writeHtmlReport({
362
622
  outputDir,
@@ -379,8 +639,27 @@ if (parsedArgs) {
379
639
  }
380
640
  }
381
641
  const failLevel = normalizeSeverity(options.failOn);
382
- const shouldFail = scanState.sorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
383
- process.exit(shouldFail ? 1 : 0);
642
+ // Override hygiene findings count toward --fail-on too, mirroring the standalone
643
+ // `overrides` command (src/cli/overrides.ts reachedFailOn). Without this, a CI run
644
+ // of `cve-lite . --check-overrides --fail-on high` would exit 0 despite high-severity
645
+ // override findings, giving a false sense of protection. overrideFindings is empty
646
+ // unless --check-overrides (and non-ratchet), so this is a no-op otherwise.
647
+ const reachesFailOn = (f) => severityOrder[f.severity] >= severityOrder[failLevel];
648
+ const shouldFail = scanState.sorted.some(reachesFailOn) || overrideFindings.some(reachesFailOn);
649
+ // In fix mode, remaining transitive findings cannot be auto-fixed.
650
+ // Exiting non-zero would prevent the Action PR step from running.
651
+ const exitCode = shouldFail && !options.fix ? 1 : 0;
652
+ // Emit scan.finished event and close audit-log
653
+ auditLogHandle.emit({
654
+ ts: new Date().toISOString(),
655
+ type: "scan.finished",
656
+ schemaVersion: 1,
657
+ durationMs: Date.now() - scanStartTime,
658
+ findingsCount: scanState.sorted.length + overrideFindings.length,
659
+ exitCode,
660
+ });
661
+ auditLogHandle.close();
662
+ process.exit(exitCode);
384
663
  return;
385
664
  }
386
665
  main().catch((error) => {
@@ -389,6 +668,16 @@ if (parsedArgs) {
389
668
  if (options.debug && error instanceof Error && error.stack) {
390
669
  debugLog("Unhandled error", { message: error.message, stack: error.stack });
391
670
  }
671
+ // Emit error event to audit-log
672
+ auditLogHandle.emit({
673
+ ts: new Date().toISOString(),
674
+ type: "error",
675
+ schemaVersion: 1,
676
+ phase: "scan",
677
+ message: errorMessage,
678
+ stack: error instanceof Error ? error.stack : undefined,
679
+ });
680
+ auditLogHandle.close();
392
681
  if (isSslCertificateError(error)) {
393
682
  const [hint, ...rest] = sslCertificateErrorHint();
394
683
  console.error(chalk.yellow(hint));
package/dist/osv/cache.js CHANGED
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
4
  function createEmptyCache() {
5
- return { version: 3, createdAt: new Date().toISOString(), entries: {}, queryEntries: {} };
5
+ return { version: 3, createdAt: new Date().toISOString(), entries: {}, queryEntries: {}, npmVersionEntries: {} };
6
6
  }
7
7
  export function getCacheFilePath(cacheDirOverride) {
8
8
  const baseDir = cacheDirOverride
@@ -41,7 +41,13 @@ export function loadCache(cacheDirOverride, debugLog) {
41
41
  for (const [key, vulnIds] of Object.entries(rawQuery ?? {})) {
42
42
  queryEntries[key] = { vulnIds: Array.isArray(vulnIds) ? vulnIds : [], cachedAt: new Date(0).toISOString() };
43
43
  }
44
- const migrated = { version: 3, createdAt: String(parsed.createdAt ?? new Date().toISOString()), entries, queryEntries };
44
+ const migrated = {
45
+ version: 3,
46
+ createdAt: String(parsed.createdAt ?? new Date().toISOString()),
47
+ entries,
48
+ queryEntries,
49
+ npmVersionEntries: {},
50
+ };
45
51
  debugLog?.("Cache loaded", {
46
52
  path: filePath,
47
53
  queryEntries: Object.keys(migrated.queryEntries).length,
@@ -52,7 +58,13 @@ export function loadCache(cacheDirOverride, debugLog) {
52
58
  }
53
59
  // v1 or unknown: no queryEntries
54
60
  if (parsed.version !== 3) {
55
- const upgraded = { version: 3, createdAt: new Date().toISOString(), entries, queryEntries: {} };
61
+ const upgraded = {
62
+ version: 3,
63
+ createdAt: new Date().toISOString(),
64
+ entries,
65
+ queryEntries: {},
66
+ npmVersionEntries: {},
67
+ };
56
68
  debugLog?.("Cache loaded", {
57
69
  path: filePath,
58
70
  queryEntries: 0,
@@ -68,11 +80,19 @@ export function loadCache(cacheDirOverride, debugLog) {
68
80
  queryEntries[key] = value;
69
81
  }
70
82
  }
83
+ const rawNpmVersions = parsed.npmVersionEntries;
84
+ const npmVersionEntries = {};
85
+ for (const [key, value] of Object.entries(rawNpmVersions ?? {})) {
86
+ if (value && typeof value === "object" && "publishedAt" in value && "cachedAt" in value) {
87
+ npmVersionEntries[key] = value;
88
+ }
89
+ }
71
90
  const loaded = {
72
91
  version: 3,
73
92
  createdAt: String(parsed.createdAt ?? new Date().toISOString()),
74
93
  entries,
75
94
  queryEntries,
95
+ npmVersionEntries,
76
96
  };
77
97
  debugLog?.("Cache loaded", {
78
98
  path: filePath,
@@ -92,7 +112,11 @@ export function loadCache(cacheDirOverride, debugLog) {
92
112
  export function saveCache(cache, cacheDirOverride, debugLog) {
93
113
  const filePath = getCacheFilePath(cacheDirOverride);
94
114
  cache.createdAt = new Date().toISOString();
95
- fs.writeFileSync(filePath, JSON.stringify(cache, null, 2), "utf8");
115
+ // Compact JSON: indentation roughly doubles the on-disk cache size and adds
116
+ // significant serialization time for large caches (10K+ entries). `loadCache`
117
+ // reads via `JSON.parse` which handles both compact and pretty formats, so
118
+ // existing pretty-printed caches migrate transparently on the next save.
119
+ fs.writeFileSync(filePath, JSON.stringify(cache), "utf8");
96
120
  if (debugLog) {
97
121
  debugLog("Cache saved", {
98
122
  path: filePath,
@@ -6,20 +6,6 @@ import { inferSeverity } from "../osv/severity.js";
6
6
  import { getPrimaryParent } from "../utils/finding.js";
7
7
  import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
8
8
  import { pluralize } from "../utils/string.js";
9
- export function formatSeverityLabel(severity) {
10
- const lower = severity.toLowerCase();
11
- if (lower === "critical")
12
- return chalk.redBright(severity);
13
- if (lower === "high")
14
- return chalk.red(severity);
15
- if (lower === "medium")
16
- return chalk.yellow(severity);
17
- if (lower === "low")
18
- return chalk.blueBright(severity);
19
- if (lower === "unknown")
20
- return chalk.magenta(severity);
21
- return severity;
22
- }
23
9
  export function formatRelationshipLabel(value) {
24
10
  if (value.startsWith("direct"))
25
11
  return chalk.green(value);
@@ -63,7 +49,7 @@ export function getRecommendedAction(finding) {
63
49
  return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
64
50
  }
65
51
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
66
- return `${finding.recommendedNpmTransitiveRemediation.package} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} — run the lockfile refresh command to pick it up.`;
52
+ return `${finding.recommendedNpmTransitiveRemediation.package} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} - run \`npm install\` to pick it up.`;
67
53
  }
68
54
  if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
69
55
  finding.recommendedNpmTransitiveRemediation.targetVersion) {
@@ -76,7 +62,7 @@ export function getRecommendedAction(finding) {
76
62
  }
77
63
  const parent = getPrimaryParent(finding);
78
64
  if (parent && directTarget) {
79
- return `Upgrade ${parent} — no safe version was identified automatically. Check for a release that resolves ${finding.pkg.name} to ${directTarget}+.`;
65
+ return `Upgrade ${parent} - no safe version was identified automatically. Check for a release that resolves ${finding.pkg.name} to ${directTarget}+.`;
80
66
  }
81
67
  if (parent) {
82
68
  return `Review ${parent}; it currently pulls in vulnerable ${finding.pkg.name}.`;
@@ -175,7 +161,7 @@ export function summarizeNextAction(finding) {
175
161
  return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
176
162
  }
177
163
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
178
- return `Lockfile refresh — ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version.`;
164
+ return `Lockfile refresh - ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version.`;
179
165
  }
180
166
  if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
181
167
  finding.recommendedNpmTransitiveRemediation.targetVersion) {
@@ -186,13 +172,30 @@ export function summarizeNextAction(finding) {
186
172
  }
187
173
  const parent = getPrimaryParent(finding);
188
174
  if (parent && directTarget) {
189
- return `Upgrade ${parent} — no safe version identified. Find a release resolving ${finding.pkg.name} to ${directTarget}+.`;
175
+ return `Upgrade ${parent} - no safe version identified. Find a release resolving ${finding.pkg.name} to ${directTarget}+.`;
190
176
  }
191
177
  if (directTarget) {
192
178
  return `No parent identified in the lockfile. Run \`npm ls ${finding.pkg.name}\` to find the parent, then upgrade toward ${directTarget}+.`;
193
179
  }
194
180
  return `Inspect the parent dependency chain for ${finding.pkg.name} and choose the safest available upgrade.`;
195
181
  }
182
+ export function formatFixVersionPublishDate(iso) {
183
+ return iso.slice(0, 10);
184
+ }
185
+ export function formatFixCommandPublishSuffix(targets) {
186
+ const dated = targets.filter(target => target.kind === "direct" && target.fixVersionPublishedAt);
187
+ if (dated.length === 0)
188
+ return "";
189
+ if (dated.length === 1) {
190
+ return ` (published ${formatFixVersionPublishDate(dated[0].fixVersionPublishedAt)})`;
191
+ }
192
+ const parts = dated.map(target => `${target.package} published ${formatFixVersionPublishDate(target.fixVersionPublishedAt)}`);
193
+ return ` (${parts.join(", ")})`;
194
+ }
195
+ export function formatFixCommandWithPublishDates(command, targets) {
196
+ const suffix = formatFixCommandPublishSuffix(targets);
197
+ return suffix ? `${command}${suffix}` : command;
198
+ }
196
199
  export function serializeFinding(finding, plan) {
197
200
  return {
198
201
  package: finding.pkg.name,
@@ -203,6 +206,7 @@ export function serializeFinding(finding, plan) {
203
206
  firstFixedVersion: finding.firstFixedVersion,
204
207
  validatedFirstFixedVersion: finding.validatedFirstFixedVersion ?? null,
205
208
  fixVersionValidationNote: finding.fixVersionValidationNote ?? null,
209
+ fixVersionPublishedAt: finding.fixVersionPublishedAt ?? null,
206
210
  validatedTargetScannedVersions: finding.validatedTargetScannedVersions ?? null,
207
211
  validatedTargetKnownVulnerableVersions: finding.validatedTargetKnownVulnerableVersions ?? null,
208
212
  recommendedAction: getRecommendedAction(finding),