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
@@ -120,6 +120,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
120
120
  usage: finding.usage ?? null,
121
121
  workspaces: pkgWorkspaces.length > 0 ? pkgWorkspaces : undefined,
122
122
  isDev: finding.pkg.dev ?? false,
123
+ fixVersionPublishedAt: finding.fixVersionPublishedAt ?? null,
123
124
  });
124
125
  }
125
126
  else if (finding.fixVersionValidationNote) {
@@ -166,7 +167,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
166
167
  package: finding.recommendedNpmTransitiveRemediation.package,
167
168
  currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
168
169
  targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
169
- displayTargetVersion: "lockfile refresh",
170
+ displayTargetVersion: "npm install",
170
171
  scannedVersions: null,
171
172
  knownVulnerableVersions: null,
172
173
  kind: "parent-update",
@@ -187,6 +188,9 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
187
188
  finding.recommendedNpmTransitiveRemediation.targetVersion &&
188
189
  isUpgradeTarget(finding.recommendedNpmTransitiveRemediation.currentVersion, finding.recommendedNpmTransitiveRemediation.targetVersion)) {
189
190
  const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedNpmTransitiveRemediation.viaPath);
191
+ const chainForNpmRemediation = finding.chainResolution?.directDep === finding.recommendedNpmTransitiveRemediation.package
192
+ ? finding.chainResolution
193
+ : null;
190
194
  upsertTarget(targetsByPackage, {
191
195
  package: finding.recommendedNpmTransitiveRemediation.package,
192
196
  currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
@@ -204,6 +208,9 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
204
208
  remainingPaths: coverage.remainingPaths,
205
209
  usage: finding.usage ?? null,
206
210
  isDev: devLookup.get(`${finding.recommendedNpmTransitiveRemediation.package}@${finding.recommendedNpmTransitiveRemediation.currentVersion}`) ?? false,
211
+ chainProof: chainForNpmRemediation?.chain,
212
+ chainSafeVersion: chainForNpmRemediation?.safeVersion,
213
+ chainVulnerablePackage: chainForNpmRemediation ? finding.pkg.name : undefined,
207
214
  });
208
215
  continue;
209
216
  }
@@ -211,6 +218,9 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
211
218
  finding.recommendedParentUpgrade &&
212
219
  isUpgradeTarget(finding.recommendedParentUpgrade.currentVersion, finding.recommendedParentUpgrade.targetVersion)) {
213
220
  const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedParentUpgrade.viaPath);
221
+ const chainForParentUpgrade = finding.chainResolution?.directDep === finding.recommendedParentUpgrade.package
222
+ ? finding.chainResolution
223
+ : null;
214
224
  upsertTarget(targetsByPackage, {
215
225
  package: finding.recommendedParentUpgrade.package,
216
226
  currentVersion: finding.recommendedParentUpgrade.currentVersion,
@@ -228,6 +238,9 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
228
238
  remainingPaths: coverage.remainingPaths,
229
239
  usage: finding.usage ?? null,
230
240
  isDev: devLookup.get(`${finding.recommendedParentUpgrade.package}@${finding.recommendedParentUpgrade.currentVersion}`) ?? false,
241
+ chainProof: chainForParentUpgrade?.chain,
242
+ chainSafeVersion: chainForParentUpgrade?.safeVersion,
243
+ chainVulnerablePackage: chainForParentUpgrade ? finding.pkg.name : undefined,
231
244
  });
232
245
  continue;
233
246
  }
@@ -252,7 +265,6 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
252
265
  package: finding.pkg.name,
253
266
  currentVersion: finding.pkg.version,
254
267
  targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
255
- displayTargetVersion: "lockfile refresh",
256
268
  scannedVersions: null,
257
269
  knownVulnerableVersions: null,
258
270
  kind: "parent-update",
@@ -268,9 +280,31 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
268
280
  }
269
281
  const primaryParent = getPrimaryParent(finding);
270
282
  if (finding.relationship === "transitive" && primaryParent) {
283
+ if (finding.chainResolution) {
284
+ const isDev = devLookup.get(`${finding.chainResolution.directDep}@${finding.chainResolution.directDepCurrentVersion}`) ?? false;
285
+ const coverage = calculatePathCoverage(finding.dependencyPaths, [finding.chainResolution.directDep]);
286
+ upsertTarget(targetsByPackage, {
287
+ package: finding.chainResolution.directDep,
288
+ currentVersion: finding.chainResolution.directDepCurrentVersion,
289
+ targetVersion: finding.chainResolution.targetVersion,
290
+ kind: "parent-upgrade",
291
+ urgent,
292
+ severity: finding.severity,
293
+ adjusted: false,
294
+ adjustmentNote: null,
295
+ reason: buildParentUpgradeReason(finding, coverage),
296
+ command: finding.chainResolution.command,
297
+ chainProof: finding.chainResolution.chain,
298
+ chainSafeVersion: finding.chainResolution.safeVersion,
299
+ chainVulnerablePackage: finding.pkg.name,
300
+ usage: finding.usage ?? null,
301
+ isDev,
302
+ });
303
+ continue;
304
+ }
271
305
  const fixHint = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
272
306
  const fixClause = fixHint
273
- ? ` — check for a release that resolves ${finding.pkg.name} to ${fixHint}+`
307
+ ? ` - check for a release that resolves ${finding.pkg.name} to ${fixHint}+`
274
308
  : "";
275
309
  skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
276
310
  package: finding.pkg.name,
@@ -359,7 +393,7 @@ function buildPnpmLockfileRefreshCommand(pkg, workspaces) {
359
393
  }
360
394
  return `pnpm -C ${workspace} update --no-save ${pkg}`;
361
395
  }
362
- function commandPrefix(packageManager) {
396
+ export function commandPrefix(packageManager) {
363
397
  if (packageManager === "npm")
364
398
  return "npm install";
365
399
  if (packageManager === "pnpm")
@@ -388,6 +422,10 @@ export function findSuggestedCommandForFinding(plan, finding) {
388
422
  looksLikeVersion(finding.recommendedParentUpgrade.targetVersion) &&
389
423
  compareVersions(item.targetVersion, finding.recommendedParentUpgrade.targetVersion) >= 0);
390
424
  }
425
+ if (finding.chainResolution) {
426
+ return (item.package === finding.chainResolution.directDep &&
427
+ item.targetVersion === finding.chainResolution.targetVersion);
428
+ }
391
429
  const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
392
430
  return item.package === finding.pkg.name && item.targetVersion === directTarget;
393
431
  });
@@ -444,6 +482,9 @@ function upsertTarget(targetsByPackage, next) {
444
482
  coveredPaths: mergePathArrays(existing.coveredPaths ?? [], next.coveredPaths ?? []),
445
483
  remainingPaths: mergePathArrays(existing.remainingPaths ?? [], next.remainingPaths ?? []),
446
484
  usage: existing.usage || next.usage,
485
+ chainProof: existing.chainProof ?? next.chainProof,
486
+ chainSafeVersion: existing.chainSafeVersion ?? next.chainSafeVersion,
487
+ chainVulnerablePackage: existing.chainVulnerablePackage ?? next.chainVulnerablePackage,
447
488
  };
448
489
  if (looksLikeVersion(existing.targetVersion) && looksLikeVersion(next.targetVersion)) {
449
490
  if (compareVersions(next.targetVersion, existing.targetVersion) > 0) {
@@ -456,6 +497,7 @@ function upsertTarget(targetsByPackage, next) {
456
497
  }
457
498
  merged.scannedVersions = next.scannedVersions ?? merged.scannedVersions ?? null;
458
499
  merged.knownVulnerableVersions = next.knownVulnerableVersions ?? merged.knownVulnerableVersions ?? null;
500
+ merged.fixVersionPublishedAt = next.fixVersionPublishedAt ?? merged.fixVersionPublishedAt ?? null;
459
501
  }
460
502
  targetsByPackage.set(next.package, merged);
461
503
  return;
@@ -467,6 +509,7 @@ function upsertTarget(targetsByPackage, next) {
467
509
  merged.adjustmentNote = next.adjustmentNote ?? merged.adjustmentNote;
468
510
  merged.scannedVersions = next.scannedVersions ?? merged.scannedVersions ?? null;
469
511
  merged.knownVulnerableVersions = next.knownVulnerableVersions ?? merged.knownVulnerableVersions ?? null;
512
+ merged.fixVersionPublishedAt = next.fixVersionPublishedAt ?? merged.fixVersionPublishedAt ?? null;
470
513
  }
471
514
  targetsByPackage.set(next.package, merged);
472
515
  }
@@ -525,6 +568,11 @@ function buildSections(targets, packageManager) {
525
568
  { kind: "parent-update", severity: "medium" },
526
569
  { kind: "parent-update", severity: "low" },
527
570
  { kind: "parent-update", severity: "unknown" },
571
+ { kind: "validated-chain-upgrade", severity: "critical" },
572
+ { kind: "validated-chain-upgrade", severity: "high" },
573
+ { kind: "validated-chain-upgrade", severity: "medium" },
574
+ { kind: "validated-chain-upgrade", severity: "low" },
575
+ { kind: "validated-chain-upgrade", severity: "unknown" },
528
576
  { kind: "parent-upgrade", severity: "medium" },
529
577
  { kind: "parent-upgrade", severity: "low" },
530
578
  { kind: "parent-upgrade", severity: "unknown" },
@@ -533,7 +581,10 @@ function buildSections(targets, packageManager) {
533
581
  const sectionTargets = targets.filter(target => {
534
582
  const targetKind = target.kind === "parent-update"
535
583
  ? "parent-update"
536
- : target.urgent ? "urgent" : target.adjusted ? "direct-adjusted" : target.kind;
584
+ : target.urgent ? "urgent"
585
+ : target.adjusted ? "direct-adjusted"
586
+ : target.chainProof !== undefined ? "validated-chain-upgrade"
587
+ : target.kind;
537
588
  return targetKind === entry.kind && target.severity === entry.severity;
538
589
  });
539
590
  if (sectionTargets.length === 0)
@@ -567,6 +618,9 @@ function buildSectionTitle(kind, severity) {
567
618
  if (kind === "parent-update") {
568
619
  return `${severityTitle} parent updates within range`;
569
620
  }
621
+ if (kind === "validated-chain-upgrade") {
622
+ return `${severityTitle} validated chain upgrades`;
623
+ }
570
624
  return `${severityTitle} parent upgrades`;
571
625
  }
572
626
  function groupByWorkspaceKey(targets) {
@@ -1,4 +1,7 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
+ function getNpmVersionCacheKey(packageName, version) {
3
+ return `${packageName}@${version}`;
4
+ }
2
5
  const packumentCache = new Map();
3
6
  const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
4
7
  let registryDebugLog;
@@ -75,6 +78,33 @@ export async function packageVersionExists(packageName, version) {
75
78
  return null;
76
79
  return Boolean(packument.versions && version in packument.versions);
77
80
  }
81
+ export async function resolveVersionPublishDate(packageName, version, options) {
82
+ const cacheKey = getNpmVersionCacheKey(packageName, version);
83
+ if (options?.cache && !options.noCache) {
84
+ const cached = options.cache.npmVersionEntries?.[cacheKey];
85
+ if (cached) {
86
+ return { publishedAt: cached.publishedAt, cacheWritten: false };
87
+ }
88
+ }
89
+ const packument = await fetchPackument(packageName);
90
+ if (!packument)
91
+ return { publishedAt: null, cacheWritten: false };
92
+ const publishedAt = packument.time?.[version];
93
+ if (!publishedAt)
94
+ return { publishedAt: null, cacheWritten: false };
95
+ let cacheWritten = false;
96
+ if (options?.cache) {
97
+ if (!options.cache.npmVersionEntries) {
98
+ options.cache.npmVersionEntries = {};
99
+ }
100
+ options.cache.npmVersionEntries[cacheKey] = {
101
+ publishedAt,
102
+ cachedAt: new Date().toISOString(),
103
+ };
104
+ cacheWritten = true;
105
+ }
106
+ return { publishedAt, cacheWritten };
107
+ }
78
108
  export async function resolvePublishedFixVersion(packageName, fixedVersionHint) {
79
109
  const packument = await fetchPackument(packageName);
80
110
  if (!packument) {
@@ -228,11 +228,11 @@ function resolveParentNodeId(args) {
228
228
  }
229
229
  return candidateNodeIds[0] ?? null;
230
230
  }
231
- function highestVersionSatisfyingRange(candidates, rawRange) {
231
+ export function highestVersionSatisfyingRange(candidates, rawRange) {
232
232
  const matches = candidates.filter(candidate => versionSatisfiesRange(candidate, rawRange)).sort(compareVersions);
233
233
  return matches.at(-1) ?? null;
234
234
  }
235
- function versionSatisfiesRange(version, rawRange) {
235
+ export function versionSatisfiesRange(version, rawRange) {
236
236
  const range = rawRange.trim();
237
237
  if (!range)
238
238
  return false;
@@ -0,0 +1,100 @@
1
+ import { commandPrefix } from "./fix-commands.js";
2
+ import { fetchPackument } from "./npm-registry.js";
3
+ import { compareVersions, looksLikeVersion, isPreReleaseVersion } from "../utils/version.js";
4
+ import { versionSatisfiesRange, highestVersionSatisfyingRange } from "./npm-transitive-resolution.js";
5
+ export async function resolveChainFix(finding, installedVersions, packageManager, options) {
6
+ if (options.offline)
7
+ return null;
8
+ if (finding.relationship !== "transitive")
9
+ return null;
10
+ const fixedVersion = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
11
+ if (!fixedVersion)
12
+ return null;
13
+ const uniqueDirectDeps = [...new Set(finding.dependencyPaths
14
+ .filter(path => path.length >= 3)
15
+ .map(path => path[1]))];
16
+ for (const directDepName of uniqueDirectDeps) {
17
+ const directDepCurrentVersion = installedVersions.get(directDepName);
18
+ if (!directDepCurrentVersion)
19
+ continue;
20
+ const packument = await fetchPackument(directDepName);
21
+ if (!packument?.versions)
22
+ continue;
23
+ const candidateVersions = Object.keys(packument.versions)
24
+ .filter(looksLikeVersion)
25
+ .filter(v => !isPreReleaseVersion(v))
26
+ .filter(v => compareVersions(v, directDepCurrentVersion) > 0)
27
+ .sort(compareVersions);
28
+ const pathsForDep = finding.dependencyPaths.filter(p => p[1] === directDepName);
29
+ for (const candidateVersion of candidateVersions) {
30
+ const candidateDeps = packument.versions[candidateVersion]?.dependencies ?? {};
31
+ // hops = everything after the direct dep and before (and including) the vulnerable package
32
+ // For path ["root", "express", "send", "mime-types"]:
33
+ // directDep = path[1] = "express"
34
+ // hops = path.slice(2) = ["send", "mime-types"]
35
+ const hops = pathsForDep[0].slice(2);
36
+ const traced = await traceChain(candidateDeps, hops, finding.pkg.version, fixedVersion);
37
+ if (!traced)
38
+ continue;
39
+ return {
40
+ directDep: directDepName,
41
+ directDepCurrentVersion,
42
+ targetVersion: candidateVersion,
43
+ chain: traced.chain,
44
+ safeVersion: traced.safeVersion,
45
+ command: `${commandPrefix(packageManager)} ${directDepName}@${candidateVersion}`,
46
+ coveredPaths: 1,
47
+ totalPaths: finding.dependencyPaths.length,
48
+ };
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+ async function traceChain(deps, remainingPath, vulnerableInstalledVersion, fixedVersion) {
54
+ if (remainingPath.length === 0)
55
+ return null;
56
+ const nextName = remainingPath[0];
57
+ const range = deps[nextName];
58
+ if (!range)
59
+ return null;
60
+ if (remainingPath.length === 1) {
61
+ // Bottom of chain: nextName IS the vulnerable package.
62
+ // The range from the parent must exclude the vulnerable installed version.
63
+ if (versionSatisfiesRange(vulnerableInstalledVersion, range)) {
64
+ // Range still allows the vulnerable version - this candidate does not fix it.
65
+ return null;
66
+ }
67
+ // Range excludes the vulnerable version - find the highest safe published version.
68
+ const packument = await fetchPackument(nextName);
69
+ if (!packument?.versions)
70
+ return null;
71
+ const candidates = Object.keys(packument.versions)
72
+ .filter(looksLikeVersion)
73
+ .filter(v => !isPreReleaseVersion(v))
74
+ .filter(v => compareVersions(v, fixedVersion) >= 0)
75
+ .sort(compareVersions);
76
+ const safeVersion = highestVersionSatisfyingRange(candidates, range);
77
+ if (!safeVersion)
78
+ return null;
79
+ return { chain: [], safeVersion };
80
+ }
81
+ // Intermediate hop: resolve the highest version of nextName within range, then recurse.
82
+ const packument = await fetchPackument(nextName);
83
+ if (!packument?.versions)
84
+ return null;
85
+ const candidates = Object.keys(packument.versions)
86
+ .filter(looksLikeVersion)
87
+ .filter(v => !isPreReleaseVersion(v))
88
+ .sort(compareVersions);
89
+ const resolvedVersion = highestVersionSatisfyingRange(candidates, range);
90
+ if (!resolvedVersion)
91
+ return null;
92
+ const nextDeps = packument.versions[resolvedVersion]?.dependencies ?? {};
93
+ const result = await traceChain(nextDeps, remainingPath.slice(1), vulnerableInstalledVersion, fixedVersion);
94
+ if (!result)
95
+ return null;
96
+ return {
97
+ chain: [{ name: nextName, version: resolvedVersion }, ...result.chain],
98
+ safeVersion: result.safeVersion,
99
+ };
100
+ }
@@ -12,6 +12,8 @@ import { printMultiFolderResults } from "../output/multi-folder-printer.js";
12
12
  import { writeMultiFolderHtmlReport } from "../output/multi-folder-html-reporter.js";
13
13
  import { chalk } from "../utils/chalk.js";
14
14
  import { getCliVersion } from "../utils/version-info.js";
15
+ import { buildOverrideContext, audit } from "../overrides/index.js";
16
+ import { NULL_AUDIT_LOG } from "../audit-log/index.js";
15
17
  export async function runMultiFolderScan(params) {
16
18
  const searchDepth = Math.max(0, Number(params.options.searchDepth || DEFAULT_SEARCH_DEPTH));
17
19
  const folders = loadMultiplePackages(params.projectRoot, !!params.options.prodOnly, searchDepth);
@@ -35,6 +37,17 @@ export async function runMultiFolderScan(params) {
35
37
  const minSeverity = normalizeSeverity(params.options.minSeverity || "medium");
36
38
  const tableFindings = params.options.all ? sorted : selectFindingsForTable(sorted, minSeverity);
37
39
  const suggestedFixCommands = buildSuggestedFixCommandPlan(sorted, scanInput, { offline, subfolder });
40
+ // Override hygiene per folder, mirroring the single-folder --check-overrides path.
41
+ let overrideFindings = [];
42
+ if (params.options.checkOverrides) {
43
+ const overrideCtx = buildOverrideContext(subfolderAbs, {
44
+ auditLog: NULL_AUDIT_LOG,
45
+ logger: { info: () => { }, warn: () => { }, error: () => { }, debug: () => { } },
46
+ checkNetwork: !!params.options.checkNetwork,
47
+ });
48
+ const overrideAudit = await audit(overrideCtx, { checkNetwork: !!params.options.checkNetwork });
49
+ overrideFindings = overrideAudit.findings;
50
+ }
38
51
  results.push({
39
52
  subfolder,
40
53
  scanInput,
@@ -44,6 +57,7 @@ export async function runMultiFolderScan(params) {
44
57
  minSeverity,
45
58
  tableFindings,
46
59
  allPackages: scanInput.packages,
60
+ overrideFindings,
47
61
  });
48
62
  }
49
63
  return results;
@@ -72,11 +86,23 @@ export async function handleMultiFolderScan(params) {
72
86
  multiFolder: true,
73
87
  folders: results.map(r => r.subfolder),
74
88
  findings: allFindings,
89
+ ...(params.options.checkOverrides
90
+ ? {
91
+ overrideFindings: results.flatMap(r => r.overrideFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
92
+ }
93
+ : {}),
75
94
  scannedAt: new Date().toISOString(),
76
95
  }, null, 2));
77
96
  }
78
97
  else {
79
98
  printMultiFolderResults(results, params.options);
99
+ if (params.options.checkOverrides) {
100
+ const { renderOverrideFindings } = await import("../output/formatters.js");
101
+ for (const r of results) {
102
+ process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray("override hygiene")}\n`);
103
+ console.log(renderOverrideFindings(r.overrideFindings));
104
+ }
105
+ }
80
106
  }
81
107
  if (params.options.report) {
82
108
  const outputDir = path.resolve(typeof params.options.report === "string" ? params.options.report : "./cve-report");
package/dist/scanner.js CHANGED
@@ -9,9 +9,10 @@ import { LocalAdvisorySource } from "./advisory/local-advisory-source.js";
9
9
  import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
10
10
  import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
11
11
  import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
12
- import { configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, } from "./remediation/npm-registry.js";
12
+ import { configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, resolveVersionPublishDate, } from "./remediation/npm-registry.js";
13
13
  import { countBySeverity } from "./utils/severity.js";
14
14
  import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry } from "./remediation/npm-transitive-resolution.js";
15
+ import { resolveChainFix } from "./remediation/transitive-chain-resolver.js";
15
16
  import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js";
16
17
  import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
17
18
  import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
@@ -45,6 +46,17 @@ export function createAdvisorySource(options) {
45
46
  function getPackageCacheKey(pkg) {
46
47
  return `${pkg.ecosystem}:${pkg.name}@${pkg.version}`;
47
48
  }
49
+ function inferPackageManagerForChain(source) {
50
+ if (source === "package-lock" || source === "npm-shrinkwrap")
51
+ return "npm";
52
+ if (source === "pnpm-lock")
53
+ return "pnpm";
54
+ if (source === "yarn-lock")
55
+ return "yarn";
56
+ if (source === "bun-lock")
57
+ return "bun";
58
+ return null;
59
+ }
48
60
  export async function scanPackages(packages, batchSize, options, context, debugLog) {
49
61
  const log = debugLog ?? (() => { });
50
62
  const sourceContext = createAdvisorySource({
@@ -222,6 +234,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
222
234
  firstFixedVersion,
223
235
  validatedFirstFixedVersion: null,
224
236
  fixVersionValidationNote: null,
237
+ fixVersionPublishedAt: null,
225
238
  validatedTargetScannedVersions: null,
226
239
  validatedTargetKnownVulnerableVersions: null,
227
240
  recommendedParentUpgrade: undefined,
@@ -308,9 +321,12 @@ export async function scanPackages(packages, batchSize, options, context, debugL
308
321
  };
309
322
  try {
310
323
  if (!offline) {
311
- await validateDirectFixTargets(findings, (finding) => {
324
+ const npmVersionCacheUpdated = await validateDirectFixTargets(findings, (finding) => {
312
325
  updateAnalysisProgress("validating fix target for", `${finding.pkg.name}@${finding.pkg.version}`);
313
- }, log);
326
+ }, { cache, noCache: options.noCache, debugLog: log });
327
+ if (npmVersionCacheUpdated) {
328
+ saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
329
+ }
314
330
  }
315
331
  // Pre-warm packument cache for all packages needed in the remediation loop.
316
332
  // This converts N sequential registry round-trips into one concurrent burst,
@@ -413,6 +429,21 @@ export async function scanPackages(packages, batchSize, options, context, debugL
413
429
  }
414
430
  }
415
431
  analysisSpinner.succeed("Analyzed vulnerability findings");
432
+ // Chain fix resolution: pre-compute validated chain for transitive findings
433
+ const chainPm = inferPackageManagerForChain(context?.scanSource);
434
+ if (chainPm) {
435
+ const installedVersions = new Map(packages.map(p => [p.name, p.version]));
436
+ await Promise.all(findings
437
+ .filter(f => f.relationship === "transitive" && f.dependencyPaths?.length)
438
+ .map(async (finding) => {
439
+ try {
440
+ finding.chainResolution = await resolveChainFix(finding, installedVersions, chainPm, { offline });
441
+ }
442
+ catch {
443
+ finding.chainResolution = null;
444
+ }
445
+ }));
446
+ }
416
447
  }
417
448
  catch (error) {
418
449
  analysisSpinner.fail("Failed while analyzing vulnerability findings");
@@ -420,7 +451,14 @@ export async function scanPackages(packages, batchSize, options, context, debugL
420
451
  }
421
452
  }
422
453
  else if (!offline) {
423
- await validateDirectFixTargets(findings, undefined, log);
454
+ const npmVersionCacheUpdated = await validateDirectFixTargets(findings, undefined, {
455
+ cache,
456
+ noCache: options.noCache,
457
+ debugLog: log,
458
+ });
459
+ if (npmVersionCacheUpdated) {
460
+ saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
461
+ }
424
462
  }
425
463
  const severityCounts = countBySeverity(findings);
426
464
  log("Findings classified", {
@@ -473,8 +511,10 @@ function createNpmTransitiveGraphFromLockfile(filePath, log, packageCount) {
473
511
  return null;
474
512
  }
475
513
  }
476
- async function validateDirectFixTargets(findings, onFinding, debugLog) {
514
+ async function validateDirectFixTargets(findings, onFinding, options) {
477
515
  const directCandidates = findings.filter(finding => finding.vulnerabilities.length > 0);
516
+ let npmVersionCacheUpdated = false;
517
+ const debugLog = options?.debugLog;
478
518
  for (const finding of directCandidates) {
479
519
  onFinding?.(finding);
480
520
  const logFixValidation = () => {
@@ -493,6 +533,7 @@ async function validateDirectFixTargets(findings, onFinding, debugLog) {
493
533
  finding.validatedTargetKnownVulnerableVersions = lowestKnownResolution.candidatesKnownVulnerable;
494
534
  if (!fixedVersionHint || fixedVersionHint === lowestKnownResolution.resolvedVersion) {
495
535
  finding.fixVersionValidationNote = null;
536
+ npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
496
537
  logFixValidation();
497
538
  continue;
498
539
  }
@@ -500,11 +541,13 @@ async function validateDirectFixTargets(findings, onFinding, debugLog) {
500
541
  if (hintResolution.resolvedVersion === lowestKnownResolution.resolvedVersion &&
501
542
  hintResolution.note) {
502
543
  finding.fixVersionValidationNote = hintResolution.note;
544
+ npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
503
545
  logFixValidation();
504
546
  continue;
505
547
  }
506
548
  finding.fixVersionValidationNote =
507
549
  `Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package ${pluralize(lowestKnownResolution.candidatesChecked, "version")} above current version (${lowestKnownResolution.candidatesKnownVulnerable} still known vulnerable); using lowest known non-vulnerable version ${lowestKnownResolution.resolvedVersion}.`;
550
+ npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
508
551
  logFixValidation();
509
552
  continue;
510
553
  }
@@ -513,6 +556,7 @@ async function validateDirectFixTargets(findings, onFinding, debugLog) {
513
556
  finding.fixVersionValidationNote = lowestKnownResolution.note;
514
557
  finding.validatedTargetScannedVersions = null;
515
558
  finding.validatedTargetKnownVulnerableVersions = null;
559
+ finding.fixVersionPublishedAt = null;
516
560
  logFixValidation();
517
561
  continue;
518
562
  }
@@ -521,8 +565,20 @@ async function validateDirectFixTargets(findings, onFinding, debugLog) {
521
565
  finding.fixVersionValidationNote = resolution.note ?? lowestKnownResolution.note;
522
566
  finding.validatedTargetScannedVersions = null;
523
567
  finding.validatedTargetKnownVulnerableVersions = null;
568
+ npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
524
569
  logFixValidation();
525
570
  }
571
+ return npmVersionCacheUpdated;
572
+ }
573
+ async function attachFixVersionPublishDate(finding, options) {
574
+ const version = finding.validatedFirstFixedVersion;
575
+ if (!version) {
576
+ finding.fixVersionPublishedAt = null;
577
+ return false;
578
+ }
579
+ const { publishedAt, cacheWritten } = await resolveVersionPublishDate(finding.pkg.name, version, options);
580
+ finding.fixVersionPublishedAt = publishedAt;
581
+ return cacheWritten;
526
582
  }
527
583
  function isAdvisoryDbStale(metadata) {
528
584
  if (!metadata.lastSyncAt) {
package/dist/types.js CHANGED
@@ -1 +1,13 @@
1
- export {};
1
+ /**
2
+ * Exit codes used by the CLI.
3
+ *
4
+ * 0 - no findings above --fail-on threshold
5
+ * 1 - findings present (CVE or override) above threshold
6
+ * 2 - --fix applied but verify() detected the fix did not take
7
+ * (operationally distinct from 1: "fix ran but did not work")
8
+ * 3 - tool error (unhandled exception, unreadable lockfile, etc.)
9
+ */
10
+ export const EXIT_OK = 0;
11
+ export const EXIT_FINDINGS = 1;
12
+ export const EXIT_VERIFY_FAILED = 2;
13
+ export const EXIT_ERROR = 3;
@@ -32,6 +32,22 @@ export function writeBaseline(projectRoot, findings) {
32
32
  };
33
33
  fs.writeFileSync(baselinePath(projectRoot), JSON.stringify(baseline, null, 2) + "\n", "utf8");
34
34
  }
35
+ /**
36
+ * Decide what `--ratchet` should do for this scan.
37
+ *
38
+ * - No baseline yet -> "save": record the current findings as the baseline.
39
+ * - Baseline exists -> "gate": never overwrite; report findings not already in
40
+ * the baseline so the caller can fail on them. This is the "if baseline exists,
41
+ * only fail on new findings" half of --ratchet. Re-saving here would let a newly
42
+ * introduced vulnerability be silently absorbed into a fresh baseline, so a
43
+ * ratcheted CI job could never fail on a regression.
44
+ */
45
+ export function ratchetOutcome(baseline, findings) {
46
+ if (!baseline)
47
+ return { action: "save" };
48
+ const { newFindings, suppressedCount } = filterNewFindings(findings, baseline);
49
+ return { action: "gate", newFindings, suppressedCount };
50
+ }
35
51
  export function filterNewFindings(findings, baseline) {
36
52
  const baselineMap = new Map();
37
53
  for (const entry of baseline.findings) {
@@ -22,11 +22,17 @@ export function defaultFixBranchName(date = new Date()) {
22
22
  const day = String(date.getUTCDate()).padStart(2, "0");
23
23
  return `cve-lite/fix-${year}-${month}-${day}`;
24
24
  }
25
- export function buildPullRequestTitle(appliedCount, packageNames) {
25
+ export function buildPullRequestTitle(appliedCount, packageNames, overrideFixCount = 0) {
26
+ if (appliedCount === 0 && overrideFixCount > 0) {
27
+ return `[CVE-Lite-CLI] chore: ${overrideFixCount} override hygiene ${pluralize(overrideFixCount, "fix", "fixes")}`;
28
+ }
26
29
  const pkgList = packageNames.length <= 3
27
30
  ? packageNames.join(", ")
28
31
  : `${packageNames.slice(0, 2).join(", ")} +${packageNames.length - 2} more`;
29
- return `[CVE-Lite-CLI] fix: upgrade ${pkgList} (${appliedCount} ${pluralize(appliedCount, "vulnerability", "vulnerabilities")} resolved)`;
32
+ const base = `[CVE-Lite-CLI] fix: upgrade ${pkgList} (${appliedCount} ${pluralize(appliedCount, "vulnerability", "vulnerabilities")} resolved)`;
33
+ return overrideFixCount > 0
34
+ ? `${base} + ${overrideFixCount} override hygiene ${pluralize(overrideFixCount, "fix", "fixes")}`
35
+ : base;
30
36
  }
31
37
  export function collectAdvisoryIdsForPackage(findings, packageName) {
32
38
  const ids = new Set();
@@ -45,6 +51,7 @@ export function collectAdvisoryIdsForPackage(findings, packageName) {
45
51
  return [...ids].sort();
46
52
  }
47
53
  export function buildPullRequestBody(params) {
54
+ const overrideFixCount = params.overrideFixCount ?? 0;
48
55
  const lines = [
49
56
  "## Summary",
50
57
  "",
@@ -53,12 +60,18 @@ export function buildPullRequestBody(params) {
53
60
  "## Fixed packages",
54
61
  "",
55
62
  ];
63
+ if (params.fixResult.applied.length === 0) {
64
+ lines.push("- _No direct CVE fixes in this PR._");
65
+ }
56
66
  for (const item of params.fixResult.applied) {
57
67
  const advisoryIds = collectAdvisoryIdsForPackage(params.findingsBeforeFix, item.package);
58
68
  const advisoryText = advisoryIds.length > 0 ? advisoryIds.join(", ") : "n/a";
59
69
  lines.push(`- **${item.package}**: \`${item.from}\` → \`${item.to}\``);
60
70
  lines.push(` - Advisories: ${advisoryText}`);
61
71
  }
72
+ if (overrideFixCount > 0) {
73
+ lines.push("", "## Override hygiene", "", `- Applied **${overrideFixCount}** override hygiene ${pluralize(overrideFixCount, "fix", "fixes")} to \`package.json\` (e.g. removing orphaned or ineffective overrides). Each change is constrained to existing overrides; no new override key is ever introduced.`);
74
+ }
62
75
  lines.push("", "## Scan results", "", `- Findings before fix: **${params.findingsBeforeFix.length}**`, `- Findings after fix: **${params.findingsAfterFix.length}**`, "", "## Notes", "", "- Only validated **direct** dependency upgrades are included in this PR.", "- Transitive vulnerabilities may still require parent package upgrades or upstream releases.");
63
76
  return lines.join("\n");
64
77
  }
@@ -151,7 +164,8 @@ function extractPullRequestUrl(output) {
151
164
  }
152
165
  export async function createPullRequestForFixes(params) {
153
166
  const baseBranchName = defaultFixBranchName();
154
- if (params.fixResult.appliedFixCount === 0) {
167
+ const overrideFixCount = params.overrideFixCount ?? 0;
168
+ if (params.fixResult.appliedFixCount === 0 && overrideFixCount === 0) {
155
169
  return {
156
170
  branchName: baseBranchName,
157
171
  prUrl: null,
@@ -170,11 +184,12 @@ export async function createPullRequestForFixes(params) {
170
184
  };
171
185
  }
172
186
  const packageNames = params.fixResult.applied.map(a => a.package);
173
- const title = buildPullRequestTitle(params.fixResult.appliedFixCount, packageNames);
187
+ const title = buildPullRequestTitle(params.fixResult.appliedFixCount, packageNames, overrideFixCount);
174
188
  const body = buildPullRequestBody({
175
189
  fixResult: params.fixResult,
176
190
  findingsBeforeFix: params.findingsBeforeFix,
177
191
  findingsAfterFix: params.findingsAfterFix,
192
+ overrideFixCount,
178
193
  });
179
194
  await stageDependencyFilesOnly(params.projectPath);
180
195
  if (!(await hasStagedDependencyChanges(params.projectPath))) {