cve-lite-cli 1.24.0 → 1.25.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 (55) hide show
  1. package/README.md +56 -0
  2. package/dist/audit-log/events.js +3 -0
  3. package/dist/audit-log/handle.js +20 -0
  4. package/dist/audit-log/index.js +16 -0
  5. package/dist/audit-log/ndjson-writer.js +28 -0
  6. package/dist/cli/args.js +71 -0
  7. package/dist/cli/fix-overrides-hook.js +64 -0
  8. package/dist/cli/help.js +22 -0
  9. package/dist/cli/overrides.js +67 -0
  10. package/dist/index.js +270 -12
  11. package/dist/osv/cache.js +23 -3
  12. package/dist/output/formatters.js +23 -4
  13. package/dist/output/html-reporter.js +34 -4
  14. package/dist/output/override-findings-html.js +57 -0
  15. package/dist/output/override-findings-json.js +3 -0
  16. package/dist/output/override-findings-sarif.js +52 -0
  17. package/dist/output/override-findings-terminal.js +37 -0
  18. package/dist/output/printers.js +25 -8
  19. package/dist/output/sarif.js +77 -8
  20. package/dist/output/write-outputs.js +7 -3
  21. package/dist/overrides/api.js +79 -0
  22. package/dist/overrides/composite.js +23 -0
  23. package/dist/overrides/context-builder.js +150 -0
  24. package/dist/overrides/context.js +3 -0
  25. package/dist/overrides/detectors/index.js +23 -0
  26. package/dist/overrides/detectors/oa001-orphaned-target.js +36 -0
  27. package/dist/overrides/detectors/oa002-floating-tag.js +40 -0
  28. package/dist/overrides/detectors/oa003-wrong-section.js +48 -0
  29. package/dist/overrides/detectors/oa004-surpassed-pin.js +49 -0
  30. package/dist/overrides/detectors/oa005-nested-ineffective.js +128 -0
  31. package/dist/overrides/detectors/oa006-coupled-platform-binary.js +170 -0
  32. package/dist/overrides/detectors/oa007-frozen-latest.js +69 -0
  33. package/dist/overrides/detectors/oa008-materialized.js +75 -0
  34. package/dist/overrides/detectors/platform-binary.js +37 -0
  35. package/dist/overrides/fixer.js +199 -0
  36. package/dist/overrides/index.js +5 -0
  37. package/dist/overrides/parsing/installed-tree.js +164 -0
  38. package/dist/overrides/parsing/json-pointer.js +8 -0
  39. package/dist/overrides/parsing/node-modules.js +19 -0
  40. package/dist/overrides/parsing/package-json.js +139 -0
  41. package/dist/overrides/parsing/registry.js +66 -0
  42. package/dist/overrides/types.js +2 -0
  43. package/dist/parsers/yarn-lock.js +2 -2
  44. package/dist/remediation/fix-commands.js +59 -5
  45. package/dist/remediation/npm-registry.js +30 -0
  46. package/dist/remediation/npm-transitive-resolution.js +2 -2
  47. package/dist/remediation/transitive-chain-resolver.js +100 -0
  48. package/dist/scan/multi-folder-scan.js +26 -0
  49. package/dist/scanner.js +61 -5
  50. package/dist/types.js +13 -1
  51. package/dist/utils/baseline.js +16 -0
  52. package/dist/utils/create-pr.js +19 -4
  53. package/dist/utils/string.js +34 -0
  54. package/dist/utils/version.js +115 -0
  55. package/package.json +3 -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
28
  import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } 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
33
  import { readDirectDependencyNames } from "./utils/package-json.js";
31
34
  import { applyFixesIfRequested, printFixModeSummary, } 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
39
  import { createPullRequestForFixes, } from "./utils/create-pr.js";
35
- import { readBaseline, writeBaseline, filterNewFindings } from "./utils/baseline.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,6 +160,23 @@ if (parsedArgs) {
136
160
  process.exit(0);
137
161
  return;
138
162
  }
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
+ }
139
180
  validateOptions(options);
140
181
  // Multi-folder mode: if no root lockfile and 2+ nested lockfiles exist,
141
182
  // route to dedicated multi-folder handler instead of single-lockfile scan
@@ -204,6 +245,23 @@ if (parsedArgs) {
204
245
  count: packages.length,
205
246
  source: scanInput.source,
206
247
  });
248
+ // Emit scan.started event after loading packages
249
+ const scanStartTime = Date.now();
250
+ auditLogHandle.emit({
251
+ ts: new Date().toISOString(),
252
+ type: "scan.started",
253
+ schemaVersion: 1,
254
+ projectPath,
255
+ mode: scanInput.mode,
256
+ source: scanInput.source,
257
+ flags: {
258
+ fix: options.fix === true,
259
+ json: options.json === true,
260
+ prodOnly: options.prodOnly === true,
261
+ offline: options.offline === true,
262
+ checkOverrides: options.checkOverrides === true,
263
+ },
264
+ });
207
265
  if (!options.ratchet) {
208
266
  logInfo(`Parsed ${packages.length} ${pluralize(packages.length, "package")} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
209
267
  printCacheSummary(options.cacheDir, options);
@@ -216,6 +274,15 @@ if (parsedArgs) {
216
274
  if (packages.length === 0) {
217
275
  debugLog("Scan skipped", { reason: "no packages found", projectPath });
218
276
  logWarn(buildNoPackagesMessage(projectPath), options);
277
+ auditLogHandle.emit({
278
+ ts: new Date().toISOString(),
279
+ type: "scan.finished",
280
+ schemaVersion: 1,
281
+ durationMs: Date.now() - scanStartTime,
282
+ findingsCount: 0,
283
+ exitCode: 0,
284
+ });
285
+ auditLogHandle.close();
219
286
  process.exit(0);
220
287
  return;
221
288
  }
@@ -233,6 +300,38 @@ if (parsedArgs) {
233
300
  let fixResult = null;
234
301
  let baseline = readBaseline(projectArg ?? ".");
235
302
  let suppressedCount = 0;
303
+ // Collect override findings if --check-overrides is set.
304
+ // Boundary: override hygiene is independent of the CVE ratchet/baseline. The
305
+ // baseline only ever records CVE findings (see src/utils/baseline.ts), so a
306
+ // --ratchet run skips the override audit entirely - override findings are never
307
+ // baselined or suppressed.
308
+ let overrideFindings = [];
309
+ if (options.checkOverrides && !options.ratchet) {
310
+ const overrideCtx = buildOverrideContext(projectPath, {
311
+ auditLog: auditLogHandle,
312
+ logger: {
313
+ info: (msg) => debugLog("oa.info", { message: msg }),
314
+ warn: (msg) => debugLog("oa.warn", { message: msg }),
315
+ error: (msg) => debugLog("oa.error", { message: msg }),
316
+ debug: (msg) => debugLog("oa.debug", { message: msg }),
317
+ },
318
+ checkNetwork: !!options.checkNetwork,
319
+ });
320
+ const auditResult = await audit(overrideCtx, { checkNetwork: !!options.checkNetwork });
321
+ overrideFindings = auditResult.findings;
322
+ }
323
+ // Emit cve.detected for each CVE finding
324
+ for (const f of scanState.sorted) {
325
+ auditLogHandle.emit({
326
+ ts: new Date().toISOString(),
327
+ type: "cve.detected",
328
+ schemaVersion: 1,
329
+ package: { name: f.pkg.name, version: f.pkg.version },
330
+ severity: f.severity,
331
+ cveAliases: f.cveAliases,
332
+ vulnerabilityIds: f.vulnerabilities.map((v) => v.id),
333
+ });
334
+ }
236
335
  if (options.fix) {
237
336
  fixResult = await applyFixesIfRequested({
238
337
  plan: scanState.suggestedFixCommands,
@@ -248,6 +347,15 @@ if (parsedArgs) {
248
347
  if (packages.length === 0) {
249
348
  debugLog("Scan skipped", { reason: "no packages found after fix rescan", projectPath });
250
349
  logWarn(buildNoPackagesMessage(projectPath), options);
350
+ auditLogHandle.emit({
351
+ ts: new Date().toISOString(),
352
+ type: "scan.finished",
353
+ schemaVersion: 1,
354
+ durationMs: Date.now() - scanStartTime,
355
+ findingsCount: 0,
356
+ exitCode: 0,
357
+ });
358
+ auditLogHandle.close();
251
359
  process.exit(0);
252
360
  return;
253
361
  }
@@ -260,6 +368,64 @@ if (parsedArgs) {
260
368
  });
261
369
  }
262
370
  }
371
+ let overridesFixHookResult = null;
372
+ // Override hygiene is opt-in. Only run the fix hook (which can patch
373
+ // package.json) when --check-overrides was requested, so `cve-lite . --fix`
374
+ // stays a pure CVE operation and never touches overrides unasked.
375
+ if (options.fix && fixResult && options.checkOverrides) {
376
+ const { runOverridesFixHook } = await import("./cli/fix-overrides-hook.js");
377
+ const projectPathResolved = path.resolve(projectArg ?? ".");
378
+ // Collect CVE-touched targets from cve-lite's fix result.
379
+ const cveFixTargets = fixResult.applied.map((entry) => ({
380
+ name: entry.package,
381
+ version: entry.to,
382
+ }));
383
+ // Create a simple logger adapter if needed
384
+ const hookLogger = {
385
+ info: (msg) => debugLog("hook.info", { message: msg }),
386
+ warn: (msg) => debugLog("hook.warn", { message: msg }),
387
+ error: (msg) => debugLog("hook.error", { message: msg }),
388
+ debug: (msg) => debugLog("hook.debug", { message: msg }),
389
+ };
390
+ overridesFixHookResult = await runOverridesFixHook({
391
+ projectPath: projectPathResolved,
392
+ auditLog: auditLogHandle,
393
+ logger: hookLogger,
394
+ cveFixTargets,
395
+ });
396
+ if (!overridesFixHookResult.verifyOk) {
397
+ debugLog("overrides-fix-hook verify failed", {
398
+ failures: overridesFixHookResult.verifyFailures,
399
+ });
400
+ console.log(chalk.red(`Overrides fix verify failed:\n${overridesFixHookResult.verifyFailures
401
+ .map((v) => ` ${v.ruleId} ${v.package}: ${v.reason}`)
402
+ .join("\n")}`));
403
+ auditLogHandle.emit({
404
+ ts: new Date().toISOString(),
405
+ type: "scan.finished",
406
+ schemaVersion: 1,
407
+ durationMs: Date.now() - scanStartTime,
408
+ findingsCount: scanState.sorted.length + overrideFindings.length,
409
+ exitCode: 2,
410
+ });
411
+ auditLogHandle.close();
412
+ process.exit(2);
413
+ }
414
+ }
415
+ // Emit cve.fix.applied for each target in the fix plan
416
+ if (scanState.suggestedFixCommands?.targets) {
417
+ for (const target of scanState.suggestedFixCommands.targets) {
418
+ auditLogHandle.emit({
419
+ ts: new Date().toISOString(),
420
+ type: "cve.fix.applied",
421
+ schemaVersion: 1,
422
+ package: target.package,
423
+ fromVersion: target.currentVersion ?? "unknown",
424
+ toVersion: target.targetVersion,
425
+ mechanism: target.kind,
426
+ });
427
+ }
428
+ }
263
429
  if (options.fix) {
264
430
  printFixModeSummary({
265
431
  fixResult,
@@ -268,7 +434,10 @@ if (parsedArgs) {
268
434
  remainingBySeverity: countBySeverity(scanState.sorted),
269
435
  });
270
436
  if (options.createPr && fixResult) {
271
- if (fixResult.appliedFixCount === 0) {
437
+ // Override hygiene fixes also land in package.json (staged by create-pr), so
438
+ // a PR is warranted when either CVE fixes or override fixes were applied.
439
+ const overrideFixCount = overridesFixHookResult?.applied ?? 0;
440
+ if (fixResult.appliedFixCount === 0 && overrideFixCount === 0) {
272
441
  logWarn("Skipping pull request creation: no direct fixes were applied.", options);
273
442
  }
274
443
  else {
@@ -280,6 +449,7 @@ if (parsedArgs) {
280
449
  fixResult,
281
450
  findingsBeforeFix: findingsBeforeFixList,
282
451
  findingsAfterFix: scanState.sorted,
452
+ overrideFixCount,
283
453
  });
284
454
  if (prResult.skipped) {
285
455
  logWarn(prResult.skipReason ?? "Pull request was not created.", options);
@@ -295,12 +465,63 @@ if (parsedArgs) {
295
465
  }
296
466
  }
297
467
  else {
298
- // --ratchet: save baseline and exit 0
468
+ // --ratchet: with no baseline yet, save the current findings. With an
469
+ // existing baseline, GATE instead of re-saving - fail on findings not in the
470
+ // baseline. Re-saving here would silently absorb a new vulnerability into a
471
+ // fresh baseline, so a ratcheted CI job could never fail on a regression.
299
472
  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);
473
+ const outcome = ratchetOutcome(baseline, scanState.sorted);
474
+ if (outcome.action === "save") {
475
+ writeBaseline(projectArg ?? ".", scanState.sorted);
476
+ const count = scanState.sorted.length;
477
+ 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.`));
478
+ if (options.checkOverrides) {
479
+ console.log(chalk.gray("Note: override hygiene (--check-overrides) is not part of the ratchet baseline; run `cve-lite overrides` to audit overrides."));
480
+ }
481
+ auditLogHandle.emit({
482
+ ts: new Date().toISOString(),
483
+ type: "scan.finished",
484
+ schemaVersion: 1,
485
+ durationMs: Date.now() - scanStartTime,
486
+ findingsCount: scanState.sorted.length,
487
+ exitCode: 0,
488
+ });
489
+ auditLogHandle.close();
490
+ process.exit(0);
491
+ return;
492
+ }
493
+ const { newFindings, suppressedCount } = outcome;
494
+ const suppressedLabel = `${suppressedCount} existing ${suppressedCount === 1 ? "finding" : "findings"} suppressed`;
495
+ if (newFindings.length === 0) {
496
+ console.log(chalk.green(`No new findings above baseline - ${suppressedLabel}`));
497
+ auditLogHandle.emit({
498
+ ts: new Date().toISOString(),
499
+ type: "scan.finished",
500
+ schemaVersion: 1,
501
+ durationMs: Date.now() - scanStartTime,
502
+ findingsCount: scanState.sorted.length,
503
+ exitCode: 0,
504
+ });
505
+ auditLogHandle.close();
506
+ process.exit(0);
507
+ return;
508
+ }
509
+ console.log(chalk.red(`${newFindings.length} new ${newFindings.length === 1 ? "finding" : "findings"} above baseline - ${suppressedLabel}`));
510
+ for (const f of newFindings) {
511
+ const ids = f.vulnerabilities.map(v => v.id).join(", ");
512
+ console.log(` ${chalk.yellow(f.severity)} ${f.pkg.name}@${f.pkg.version}${ids ? ` (${ids})` : ""}`);
513
+ }
514
+ console.log(chalk.gray("To accept these, re-baseline intentionally by deleting .cve-lite/baseline.json and re-running --ratchet."));
515
+ auditLogHandle.emit({
516
+ ts: new Date().toISOString(),
517
+ type: "scan.finished",
518
+ schemaVersion: 1,
519
+ durationMs: Date.now() - scanStartTime,
520
+ findingsCount: newFindings.length,
521
+ exitCode: 1,
522
+ });
523
+ auditLogHandle.close();
524
+ process.exit(1);
304
525
  return;
305
526
  }
306
527
  // auto-apply baseline if it exists - filter before output
@@ -317,6 +538,7 @@ if (parsedArgs) {
317
538
  coverage: scanState.coverage,
318
539
  minSeverity: scanState.minSeverity,
319
540
  tableFindings: scanState.tableFindings,
541
+ overrideFindings,
320
542
  }, scanInput, projectPath);
321
543
  if (!(options.json || options.sarif || options.cdx) || options.verbose) {
322
544
  const offline = !!options.offline || !!options.offlineDb;
@@ -343,6 +565,12 @@ if (parsedArgs) {
343
565
  else {
344
566
  printCompactOutput(scanState.sorted, scanInput, { offline, all: !!options.all });
345
567
  }
568
+ // Override hygiene section: --check-overrides collects these and threads
569
+ // them to JSON/SARIF/HTML; render them in the terminal too so the feature
570
+ // is visible in a plain scan, not only in machine output (#35).
571
+ if (options.checkOverrides) {
572
+ console.log(renderOverrideFindings(overrideFindings));
573
+ }
346
574
  }
347
575
  }
348
576
  if (options.report) {
@@ -357,6 +585,9 @@ if (parsedArgs) {
357
585
  suggestedFixCommands: scanState.suggestedFixCommands,
358
586
  notes: [...scanInput.notes, ...scanState.coverage],
359
587
  warnings: scanInput.warnings,
588
+ // undefined (not []) when override checking was not requested, so the HTML
589
+ // report omits the Override hygiene panel entirely on a plain scan.
590
+ overrideFindings: options.checkOverrides ? overrideFindings : undefined,
360
591
  });
361
592
  const { reportPath } = await writeHtmlReport({
362
593
  outputDir,
@@ -379,8 +610,25 @@ if (parsedArgs) {
379
610
  }
380
611
  }
381
612
  const failLevel = normalizeSeverity(options.failOn);
382
- const shouldFail = scanState.sorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
383
- process.exit(shouldFail ? 1 : 0);
613
+ // Override hygiene findings count toward --fail-on too, mirroring the standalone
614
+ // `overrides` command (src/cli/overrides.ts reachedFailOn). Without this, a CI run
615
+ // of `cve-lite . --check-overrides --fail-on high` would exit 0 despite high-severity
616
+ // override findings, giving a false sense of protection. overrideFindings is empty
617
+ // unless --check-overrides (and non-ratchet), so this is a no-op otherwise.
618
+ const reachesFailOn = (f) => severityOrder[f.severity] >= severityOrder[failLevel];
619
+ const shouldFail = scanState.sorted.some(reachesFailOn) || overrideFindings.some(reachesFailOn);
620
+ const exitCode = shouldFail ? 1 : 0;
621
+ // Emit scan.finished event and close audit-log
622
+ auditLogHandle.emit({
623
+ ts: new Date().toISOString(),
624
+ type: "scan.finished",
625
+ schemaVersion: 1,
626
+ durationMs: Date.now() - scanStartTime,
627
+ findingsCount: scanState.sorted.length + overrideFindings.length,
628
+ exitCode,
629
+ });
630
+ auditLogHandle.close();
631
+ process.exit(exitCode);
384
632
  return;
385
633
  }
386
634
  main().catch((error) => {
@@ -389,6 +637,16 @@ if (parsedArgs) {
389
637
  if (options.debug && error instanceof Error && error.stack) {
390
638
  debugLog("Unhandled error", { message: error.message, stack: error.stack });
391
639
  }
640
+ // Emit error event to audit-log
641
+ auditLogHandle.emit({
642
+ ts: new Date().toISOString(),
643
+ type: "error",
644
+ schemaVersion: 1,
645
+ phase: "scan",
646
+ message: errorMessage,
647
+ stack: error instanceof Error ? error.stack : undefined,
648
+ });
649
+ auditLogHandle.close();
392
650
  if (isSslCertificateError(error)) {
393
651
  const [hint, ...rest] = sslCertificateErrorHint();
394
652
  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,
@@ -63,7 +63,7 @@ export function getRecommendedAction(finding) {
63
63
  return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
64
64
  }
65
65
  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.`;
66
+ return `${finding.recommendedNpmTransitiveRemediation.package} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} - run \`npm install\` to pick it up.`;
67
67
  }
68
68
  if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
69
69
  finding.recommendedNpmTransitiveRemediation.targetVersion) {
@@ -76,7 +76,7 @@ export function getRecommendedAction(finding) {
76
76
  }
77
77
  const parent = getPrimaryParent(finding);
78
78
  if (parent && directTarget) {
79
- return `Upgrade ${parent} — no safe version was identified automatically. Check for a release that resolves ${finding.pkg.name} to ${directTarget}+.`;
79
+ return `Upgrade ${parent} - no safe version was identified automatically. Check for a release that resolves ${finding.pkg.name} to ${directTarget}+.`;
80
80
  }
81
81
  if (parent) {
82
82
  return `Review ${parent}; it currently pulls in vulnerable ${finding.pkg.name}.`;
@@ -175,7 +175,7 @@ export function summarizeNextAction(finding) {
175
175
  return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
176
176
  }
177
177
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
178
- return `Lockfile refresh — ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version.`;
178
+ return `Lockfile refresh - ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version.`;
179
179
  }
180
180
  if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
181
181
  finding.recommendedNpmTransitiveRemediation.targetVersion) {
@@ -186,13 +186,30 @@ export function summarizeNextAction(finding) {
186
186
  }
187
187
  const parent = getPrimaryParent(finding);
188
188
  if (parent && directTarget) {
189
- return `Upgrade ${parent} — no safe version identified. Find a release resolving ${finding.pkg.name} to ${directTarget}+.`;
189
+ return `Upgrade ${parent} - no safe version identified. Find a release resolving ${finding.pkg.name} to ${directTarget}+.`;
190
190
  }
191
191
  if (directTarget) {
192
192
  return `No parent identified in the lockfile. Run \`npm ls ${finding.pkg.name}\` to find the parent, then upgrade toward ${directTarget}+.`;
193
193
  }
194
194
  return `Inspect the parent dependency chain for ${finding.pkg.name} and choose the safest available upgrade.`;
195
195
  }
196
+ export function formatFixVersionPublishDate(iso) {
197
+ return iso.slice(0, 10);
198
+ }
199
+ export function formatFixCommandPublishSuffix(targets) {
200
+ const dated = targets.filter(target => target.kind === "direct" && target.fixVersionPublishedAt);
201
+ if (dated.length === 0)
202
+ return "";
203
+ if (dated.length === 1) {
204
+ return ` (published ${formatFixVersionPublishDate(dated[0].fixVersionPublishedAt)})`;
205
+ }
206
+ const parts = dated.map(target => `${target.package} published ${formatFixVersionPublishDate(target.fixVersionPublishedAt)}`);
207
+ return ` (${parts.join(", ")})`;
208
+ }
209
+ export function formatFixCommandWithPublishDates(command, targets) {
210
+ const suffix = formatFixCommandPublishSuffix(targets);
211
+ return suffix ? `${command}${suffix}` : command;
212
+ }
196
213
  export function serializeFinding(finding, plan) {
197
214
  return {
198
215
  package: finding.pkg.name,
@@ -203,6 +220,7 @@ export function serializeFinding(finding, plan) {
203
220
  firstFixedVersion: finding.firstFixedVersion,
204
221
  validatedFirstFixedVersion: finding.validatedFirstFixedVersion ?? null,
205
222
  fixVersionValidationNote: finding.fixVersionValidationNote ?? null,
223
+ fixVersionPublishedAt: finding.fixVersionPublishedAt ?? null,
206
224
  validatedTargetScannedVersions: finding.validatedTargetScannedVersions ?? null,
207
225
  validatedTargetKnownVulnerableVersions: finding.validatedTargetKnownVulnerableVersions ?? null,
208
226
  recommendedAction: getRecommendedAction(finding),
@@ -268,3 +286,4 @@ export function sortFindingsForOutput(findings) {
268
286
  export function countUniqueAdvisories(findings) {
269
287
  return new Set(findings.flatMap(f => f.vulnerabilities.map(v => v.id))).size;
270
288
  }
289
+ export { renderOverrideFindings } from "./override-findings-terminal.js";
@@ -1,12 +1,13 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { spawn } from "node:child_process";
4
- import { serializeFinding, summarizeNextAction, summarizeRisk } from "./formatters.js";
4
+ import { serializeFinding, summarizeNextAction, summarizeRisk, formatFixCommandWithPublishDates } from "./formatters.js";
5
5
  import { LOGO_BASE64 } from "./logo-base64.js";
6
6
  import { OWASP_LOGO_BASE64 } from "./owasp-logo-base64.js";
7
7
  import { isMajorVersionBump } from "../utils/version.js";
8
8
  import { pluralize } from "../utils/string.js";
9
9
  import { MAL_GIT_SOURCE_PINNED_DISPLAY, MAL_GIT_SOURCE_FLOATING_DISPLAY } from "../constants.js";
10
+ import { renderOverrideFindingsHtml } from "./override-findings-html.js";
10
11
  export function serializeHtmlFinding(finding, plan) {
11
12
  return {
12
13
  ...serializeFinding(finding, plan),
@@ -26,6 +27,7 @@ export function buildReportData(params) {
26
27
  suggestedFixCommands: params.suggestedFixCommands,
27
28
  notes: params.notes,
28
29
  warnings: params.warnings,
30
+ overrideFindings: params.overrideFindings,
29
31
  };
30
32
  }
31
33
  export const REPORT_STYLES = `*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
@@ -153,10 +155,26 @@ button.header-link:hover{color:#58a6ff;border-color:#58a6ff}
153
155
  .fix-target-stats{color:#6b7280;font-size:10px}
154
156
  .fix-target-note{color:#6b7280;font-style:italic;font-size:10px}
155
157
  .fix-target-coverage{flex-basis:100%;color:#6b7280;font-size:10px;line-height:1.45}
158
+ .chain-proof{font-size:0.78rem;color:#8b949e;margin-left:6px;font-family:monospace}
156
159
  .break-badge{font-size:10px;font-weight:700;background:#fb850022;color:#fb8500;border:1px solid #fb850066;border-radius:4px;padding:1px 5px}
157
160
  .tier-ok{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#3fb95022;color:#3fb950;border:1px solid #3fb95033;margin-bottom:6px}
158
161
  .tier-warn{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#e3b34122;color:#e3b341;border:1px solid #e3b34133;margin-bottom:6px}
159
- .tier-err{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#ff000011;color:#ff7b72;border:1px solid #ff7b7222;margin-bottom:6px}`;
162
+ .tier-err{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#ff000011;color:#ff7b72;border:1px solid #ff7b7222;margin-bottom:6px}
163
+ .override-hygiene{margin:0 32px 32px}
164
+ .override-hygiene h2{font-size:13px;font-weight:600;color:#e6edf3;margin-bottom:12px}
165
+ .override-hygiene p{font-size:13px;color:#8b949e}
166
+ .override-hygiene table{width:100%;border-collapse:collapse;background:#161b22;border:1px solid #30363d;border-radius:8px;overflow:hidden}
167
+ .override-hygiene table thead th{text-align:left;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.4px;color:#8b949e;padding:10px 14px;border-bottom:1px solid #21262d;background:#1c2128}
168
+ .override-hygiene table tbody tr{border-bottom:1px solid #21262d}
169
+ .override-hygiene table tbody tr:last-child{border-bottom:none}
170
+ .override-hygiene table tbody tr.severity-group{background:#1c2128}
171
+ .override-hygiene table tbody tr.severity-group th{font-weight:600;color:#e6edf3;padding:10px 14px}
172
+ .override-hygiene table tbody tr.finding td{padding:11px 14px;font-size:12px;color:#e6edf3;vertical-align:middle}
173
+ .override-hygiene table tbody tr.finding.critical{border-left:3px solid #f85149}
174
+ .override-hygiene table tbody tr.finding.high{border-left:3px solid #fb8500}
175
+ .override-hygiene table tbody tr.finding.medium{border-left:3px solid #e3b341}
176
+ .override-hygiene table tbody tr.finding.low{border-left:3px solid #388bfd}
177
+ .override-hygiene table tbody tr.finding.info{border-left:3px solid #8b949e}`;
160
178
  export function renderHtmlReport(data) {
161
179
  const projectName = path.basename(data.projectPath);
162
180
  const scanDate = new Date(data.scannedAt).toLocaleString();
@@ -269,6 +287,8 @@ ${findingRowsHtml}
269
287
  </div>
270
288
  ${noticesHtml}
271
289
 
290
+ ${renderOverrideFindingsHtml(data.overrideFindings)}
291
+
272
292
  <div class="report-footer">
273
293
  <span>Generated by <strong>cve-lite v${escapeHtml(data.cliVersion)}</strong></span>
274
294
  <span>${escapeHtml(data.lockfileSource)} &nbsp;·&nbsp; ${data.findings.length} findings &nbsp;·&nbsp; ${data.packageCount} packages</span>
@@ -562,14 +582,24 @@ export function renderFixPlan(plan) {
562
582
  const coverageHtml = t.coverage === "partial"
563
583
  ? ` <span class="fix-target-coverage">Path-specific remediation. Run this command, then rescan; ${t.remainingPaths?.length ?? 0} other known ${pluralize(t.remainingPaths?.length ?? 0, "path")} may still need separate parent upgrades.</span>`
564
584
  : "";
565
- return `<div class="fix-target-row">${versionHtml}${breakBadge}${statsHtml}${noteHtml}${coverageHtml}</div>`;
585
+ const chainProofHtml = t.chainProof && t.chainSafeVersion
586
+ ? (() => {
587
+ const hops = t.chainProof.map(h => `${escapeHtml(h.name)}@${escapeHtml(h.version)}`);
588
+ const safe = escapeHtml(t.chainSafeVersion);
589
+ const proofText = hops.length > 0
590
+ ? `resolves via ${hops.join(" -&gt; ")} -&gt; ${safe} (safe)`
591
+ : `resolves to ${safe} (safe)`;
592
+ return ` <span class="chain-proof">${proofText}</span>`;
593
+ })()
594
+ : "";
595
+ return `<div class="fix-target-row">${versionHtml}${breakBadge}${statsHtml}${noteHtml}${coverageHtml}${chainProofHtml}</div>`;
566
596
  }).join("\n");
567
597
  const targetsHtml = section.targets.length > 0
568
598
  ? `<div class="fix-targets-list">${targetRows}</div>`
569
599
  : "";
570
600
  return `
571
601
  <div class="fix-cmd">
572
- <span class="cmd-text">${escapeHtml(section.command)}</span>
602
+ <span class="cmd-text">${escapeHtml(formatFixCommandWithPublishDates(section.command, section.targets))}</span>
573
603
  <span class="cmd-meta">${escapeHtml(section.title)}</span>
574
604
  <button class="copy-btn" data-cmd="${escapeHtml(section.command)}">Copy</button>
575
605
  </div>${targetsHtml}`;