cve-lite-cli 1.35.0 → 1.36.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.
package/README.md CHANGED
@@ -39,6 +39,40 @@
39
39
 
40
40
  <br/>
41
41
 
42
+ <p>
43
+ 🏆 <strong>Ranked #5</strong> in <a href="https://www.helpnetsecurity.com/2026/07/08/20-latest-open-source-cybersecurity-tools/">Help Net Security's 20 open-source security tools</a> &nbsp;·&nbsp;
44
+ <strong><a href="https://www.bestpractices.dev/projects/12731">OpenSSF Best Practices</a></strong>
45
+ </p>
46
+
47
+ <p>
48
+ Covered by
49
+ <a href="https://www.theregister.com/security/2026/06/23/sniff-out-stale-ai-override-advice-with-this-open-source-cli/5259853"><strong>The Register</strong></a> ·
50
+ <a href="https://www.csoonline.com/article/4176701/as-ai-speeds-coding-cve-lite-cli-keeps-security-deliberately-ai-free.html"><strong>CSO Online</strong></a> ·
51
+ <a href="https://www.securityweek.com/owasp-incubator-project-helps-developers-find-and-fix-vulnerable-dependencies-in-seconds/"><strong>SecurityWeek</strong></a> ·
52
+ <a href="https://sdtimes.com/security/shift-left-how-cve-lite-cli-is-transforming-developer-security/"><strong>SD Times</strong></a> ·
53
+ <a href="https://devops.com/owasp-adopts-cve-lite-cli-to-boost-dependency-scanning/"><strong>DevOps.com</strong></a> ·
54
+ <a href="https://www.reversinglabs.com/blog/cve-lite-cli"><strong>ReversingLabs</strong></a>
55
+ </p>
56
+
57
+ <p>
58
+ <sub>Running in CI at
59
+ <a href="https://github.com/solidjs/solid/blob/main/.github/workflows/cve-lite.yml"><strong>SolidJS</strong></a>,
60
+ <a href="https://github.com/bcgov/nr-waste-plus/blob/main/.github/workflows/analysis.yml"><strong>the Government of British Columbia</strong></a> as a required merge gate,
61
+ <a href="https://github.com/etalab-ia/parcours-rag/blob/main/package.json">French government digital services (<strong>DINUM</strong>)</a>, and
62
+ <a href="https://github.com/fabian-hiller/valibot"><strong>Valibot</strong></a>.<br/>
63
+ In production use in France, Canada, Germany, Thailand and China.</sub>
64
+ </p>
65
+
66
+ <br/>
67
+
68
+ <p>
69
+ ⚡ <strong>One command. No account, no API key, nothing leaves your machine.</strong>
70
+ &nbsp;<code>npx cve-lite-cli .</code>&nbsp;
71
+ <a href="#quick-start"><strong>→ Quick Start</strong></a>
72
+ </p>
73
+
74
+ <br/>
75
+
42
76
  <p>
43
77
  <a href="#quick-start">Quick Start</a> •
44
78
  <a href="#usage">Usage</a> •
@@ -1,3 +1,4 @@
1
+ import { satisfiesRange } from "../utils/version.js";
1
2
  const NPM_ADVISORY_URL = "https://registry.npmjs.org/-/npm/v1/security/advisories/bulk";
2
3
  function isValidAdvisory(a) {
3
4
  return (typeof a === "object" &&
@@ -6,8 +7,58 @@ function isValidAdvisory(a) {
6
7
  typeof a.title === "string" &&
7
8
  typeof a.vulnerable_versions === "string");
8
9
  }
10
+ /**
11
+ * The bulk endpoint does not send `ghsa_id`. It sends the advisory's GitHub URL,
12
+ * and the GHSA is the last segment of it.
13
+ *
14
+ * This matters more than a tidier identifier: the scanner drops an npm advisory
15
+ * whose id OSV already surfaced, so without the real GHSA every advisory arrived
16
+ * under a private `NPM-` id, matched nothing, and was counted twice.
17
+ */
18
+ function advisoryId(advisory) {
19
+ if (typeof advisory.ghsa_id === "string" && advisory.ghsa_id.length > 0)
20
+ return advisory.ghsa_id;
21
+ const fromUrl = advisory.url?.match(/GHSA-([a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})/i);
22
+ // Casing has to match OSV exactly or the id match that drives dedup misses.
23
+ // OSV writes the prefix uppercase and the segments lowercase.
24
+ if (fromUrl)
25
+ return `GHSA-${fromUrl[1].toLowerCase()}`;
26
+ return `NPM-${advisory.id}`;
27
+ }
28
+ /**
29
+ * Turn npm's `vulnerable_versions` range into OSV events.
30
+ *
31
+ * `patched_versions` is what this used to read, and the bulk endpoint does not
32
+ * send that either, so every advisory carried `introduced: 0` and no upper bound.
33
+ * A range with no `fixed` cannot be evaluated, which is what made the fix-version
34
+ * validator report unknown coverage and give up.
35
+ *
36
+ * `<=` becomes `last_affected` rather than `fixed`, because `<=2.0.9` says 2.0.9
37
+ * is still vulnerable and `fixed: 2.0.9` would say the opposite.
38
+ */
39
+ function rangeEvents(advisory) {
40
+ let introduced = "0";
41
+ let upper = null;
42
+ for (const token of (advisory.vulnerable_versions ?? "").trim().split(/\s+/).filter(Boolean)) {
43
+ const value = token.replace(/^[<>]=?|^=/, "").trim();
44
+ if (!value || value === "*")
45
+ continue;
46
+ if (token.startsWith(">=") || token.startsWith(">"))
47
+ introduced = value;
48
+ else if (token.startsWith("<="))
49
+ upper = { last_affected: value };
50
+ else if (token.startsWith("<"))
51
+ upper = { fixed: value };
52
+ }
53
+ // Some npm surfaces do send patched_versions. Honour it when the vulnerable
54
+ // range left the window open.
55
+ if (!upper && advisory.patched_versions) {
56
+ upper = { fixed: advisory.patched_versions.replace(/^>=/, "").trim() };
57
+ }
58
+ return upper ? [{ introduced }, upper] : [{ introduced }];
59
+ }
9
60
  function normalizeAdvisory(advisory, pkgName) {
10
- const id = advisory.ghsa_id ?? `NPM-${advisory.id}`;
61
+ const id = advisoryId(advisory);
11
62
  return {
12
63
  id,
13
64
  aliases: advisory.cve_ids ?? [],
@@ -16,17 +67,7 @@ function normalizeAdvisory(advisory, pkgName) {
16
67
  affected: [
17
68
  {
18
69
  package: { ecosystem: "npm", name: pkgName },
19
- ranges: [
20
- {
21
- type: "ECOSYSTEM",
22
- events: [
23
- { introduced: "0" },
24
- ...(advisory.patched_versions
25
- ? [{ fixed: advisory.patched_versions.replace(/^>=/, "") }]
26
- : []),
27
- ],
28
- },
29
- ],
70
+ ranges: [{ type: "ECOSYSTEM", events: rangeEvents(advisory) }],
30
71
  },
31
72
  ],
32
73
  severity: [],
@@ -35,13 +76,25 @@ function normalizeAdvisory(advisory, pkgName) {
35
76
  },
36
77
  };
37
78
  }
79
+ /** Whether this advisory's declared range covers the version we are asking about. */
80
+ function coversVersion(advisory, version) {
81
+ const range = advisory.vulnerable_versions?.trim();
82
+ if (!range || range === "*")
83
+ return true;
84
+ return satisfiesRange(version, range);
85
+ }
38
86
  export async function queryNpmAdvisoryGaps(packages, options = {}) {
39
87
  if (options.offline || packages.length === 0)
40
88
  return [];
41
89
  const fetchImpl = options.fetchImpl ?? fetch;
90
+ // Every version, not one. Assigning rather than appending meant a tree holding
91
+ // six copies of a package asked about whichever came last, and the single
92
+ // answer was then handed to all six.
42
93
  const body = {};
43
94
  for (const pkg of packages) {
44
- body[pkg.name] = [pkg.version];
95
+ const versions = (body[pkg.name] ??= []);
96
+ if (!versions.includes(pkg.version))
97
+ versions.push(pkg.version);
45
98
  }
46
99
  let data;
47
100
  try {
@@ -68,6 +121,10 @@ export async function queryNpmAdvisoryGaps(packages, options = {}) {
68
121
  for (const raw of advisories) {
69
122
  if (!isValidAdvisory(raw))
70
123
  continue;
124
+ // The reply is per package and says nothing about which version each
125
+ // advisory belongs to, so the range has to decide.
126
+ if (!coversVersion(raw, pkg.version))
127
+ continue;
71
128
  vulns.push(normalizeAdvisory(raw, pkg.name));
72
129
  }
73
130
  if (vulns.length > 0)
@@ -1,26 +1,37 @@
1
+ import { DEFAULT_BATCH_SIZE } from "../constants.js";
2
+ import { chunk } from "../utils/array.js";
1
3
  const EPSS_API_URL = "https://api.first.org/data/v1/epss";
2
- export async function fetchEpssScores(cveIds, fetchImpl = fetch) {
3
- const unique = [...new Set(cveIds.map(id => id.toUpperCase()).filter(id => id.startsWith("CVE-")))];
4
- if (unique.length === 0)
5
- return new Map();
4
+ async function fetchBatch(cveIds, fetchImpl) {
6
5
  try {
7
- const url = `${EPSS_API_URL}?cve=${unique.join(",")}`;
6
+ const url = `${EPSS_API_URL}?cve=${cveIds.join(",")}`;
8
7
  const response = await fetchImpl(url);
9
8
  if (!response.ok)
10
- return new Map();
9
+ return [];
11
10
  const json = await response.json();
12
- const result = new Map();
11
+ const scores = [];
13
12
  for (const item of json.data ?? []) {
14
13
  const epss = parseFloat(item.epss);
15
14
  const percentile = parseFloat(item.percentile);
16
15
  if (!isNaN(epss) && !isNaN(percentile)) {
17
16
  const cve = item.cve.toUpperCase();
18
- result.set(cve, { cve, epss, percentile });
17
+ scores.push({ cve, epss, percentile });
19
18
  }
20
19
  }
21
- return result;
20
+ return scores;
22
21
  }
23
22
  catch {
23
+ return [];
24
+ }
25
+ }
26
+ export async function fetchEpssScores(cveIds, fetchImpl = fetch) {
27
+ const unique = [...new Set(cveIds.map(id => id.toUpperCase()).filter(id => id.startsWith("CVE-")))];
28
+ if (unique.length === 0)
24
29
  return new Map();
30
+ const batches = chunk(unique, DEFAULT_BATCH_SIZE);
31
+ const scores = (await Promise.all(batches.map(batch => fetchBatch(batch, fetchImpl)))).flat();
32
+ const result = new Map();
33
+ for (const score of scores) {
34
+ result.set(score.cve, score);
25
35
  }
36
+ return result;
26
37
  }
package/dist/osv/cache.js CHANGED
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import os from "node:os";
4
4
  import { CACHE_TTL_MS } from "../constants.js";
5
5
  function createEmptyCache() {
6
- return { version: 5, createdAt: new Date().toISOString(), entries: {}, queryEntries: {}, npmVersionEntries: {}, npmAdvisoryEntries: {} };
6
+ return { version: 6, createdAt: new Date().toISOString(), entries: {}, queryEntries: {}, npmVersionEntries: {}, npmAdvisoryEntries: {} };
7
7
  }
8
8
  // v4 stores detail records as { vuln, cachedAt }. v1-v3 stored the OsvVuln (or
9
9
  // null for a known-empty lookup) directly, with no timestamp. Legacy records are
@@ -53,12 +53,15 @@ export function loadCache(cacheDirOverride, debugLog) {
53
53
  debugLog?.("Cache load failed", { path: filePath, reason: "invalid root object" });
54
54
  return createEmptyCache();
55
55
  }
56
- const version = parsed.version;
56
+ // Compare cumulatively rather than listing each version. An explicit list has to
57
+ // be extended at every bump, and missing one silently discards that whole section
58
+ // of the cache instead of failing.
59
+ const version = typeof parsed.version === "number" ? parsed.version : 0;
57
60
  const rawEntries = parsed.entries;
58
- // Detail records: v4 and v5 already carry { vuln, cachedAt }; v1-v3 stored the record
61
+ // Detail records: v4 onward already carry { vuln, cachedAt }; v1-v3 stored the record
59
62
  // directly and are wrapped (and backdated) so the TTL applies uniformly.
60
- const entries = version === 4 || version === 5 ? readDetailEntries(rawEntries) : wrapLegacyDetailEntries(rawEntries);
61
- // Query records: v2 stored string[]; v3, v4, and v5 store { vulnIds, cachedAt }; v1/unknown had none.
63
+ const entries = version >= 4 ? readDetailEntries(rawEntries) : wrapLegacyDetailEntries(rawEntries);
64
+ // Query records: v2 stored string[]; v3 onward store { vulnIds, cachedAt }; v1/unknown had none.
62
65
  const queryEntries = {};
63
66
  if (version === 2) {
64
67
  const rawQuery = parsed.queryEntries;
@@ -67,7 +70,7 @@ export function loadCache(cacheDirOverride, debugLog) {
67
70
  queryEntries[key] = { vulnIds: Array.isArray(vulnIds) ? vulnIds : [], cachedAt: epoch };
68
71
  }
69
72
  }
70
- else if (version === 3 || version === 4 || version === 5) {
73
+ else if (version >= 3) {
71
74
  const rawQuery = parsed.queryEntries;
72
75
  for (const [key, value] of Object.entries(rawQuery ?? {})) {
73
76
  if (value && typeof value === "object" && "vulnIds" in value && "cachedAt" in value) {
@@ -77,7 +80,7 @@ export function loadCache(cacheDirOverride, debugLog) {
77
80
  }
78
81
  // npm publish-date records exist from v3 onward.
79
82
  const npmVersionEntries = {};
80
- if (version === 3 || version === 4 || version === 5) {
83
+ if (version >= 3) {
81
84
  const rawNpmVersions = parsed.npmVersionEntries;
82
85
  for (const [key, value] of Object.entries(rawNpmVersions ?? {})) {
83
86
  if (value && typeof value === "object" && "publishedAt" in value && "cachedAt" in value) {
@@ -85,18 +88,22 @@ export function loadCache(cacheDirOverride, debugLog) {
85
88
  }
86
89
  }
87
90
  }
88
- // npm advisory entries exist from v5 onward.
91
+ // npm advisory entries exist from v5 onward, but v5 stored ids only. Those
92
+ // records cannot be reused: the advisory detail they refer to lives in the npm
93
+ // registry namespace, so a later scan reading a v5 record had ids it could not
94
+ // resolve and silently dropped them from the findings. v6 stores the advisories
95
+ // themselves; v5 records are discarded so the next scan refetches them.
89
96
  const npmAdvisoryEntries = {};
90
- if (version === 5) {
97
+ if (version >= 6) {
91
98
  const raw = parsed.npmAdvisoryEntries;
92
99
  for (const [key, value] of Object.entries(raw ?? {})) {
93
- if (value && typeof value === "object" && "vulnIds" in value && "cachedAt" in value) {
100
+ if (value && typeof value === "object" && "vulns" in value && "cachedAt" in value) {
94
101
  npmAdvisoryEntries[key] = value;
95
102
  }
96
103
  }
97
104
  }
98
105
  const loaded = {
99
- version: 5,
106
+ version: 6,
100
107
  createdAt: String(parsed.createdAt ?? new Date().toISOString()),
101
108
  entries,
102
109
  queryEntries,
@@ -107,7 +114,7 @@ export function loadCache(cacheDirOverride, debugLog) {
107
114
  path: filePath,
108
115
  queryEntries: Object.keys(loaded.queryEntries).length,
109
116
  detailEntries: Object.keys(loaded.entries).length,
110
- ...(version === 5 ? {} : { migratedFrom: version ?? "unknown" }),
117
+ ...(version === 6 ? {} : { migratedFrom: version || "unknown" }),
111
118
  });
112
119
  return loaded;
113
120
  }
@@ -497,6 +497,26 @@ export function printTable(findings, threshold, skippedKeys, plan) {
497
497
  console.log(chalk.gray("Tip: use --all to include low findings, or --min-severity high to focus only on urgent issues."));
498
498
  }
499
499
  }
500
+ /**
501
+ * Builds the one-sentence verdict both output modes close with.
502
+ *
503
+ * Compact and verbose used to construct this separately, 350 lines apart, and had
504
+ * drifted: compact reported critical+high while verbose reported every finding, so
505
+ * the same scan closed with "7 urgent issues" or "11 vulnerabilities" depending on
506
+ * the flag. Verbose's noun was wrong too - findings are vulnerable packages, and
507
+ * that scan carried 94 advisories across its 11 packages (#1168).
508
+ */
509
+ function buildScanVerdict(findingCount, critical, high) {
510
+ const urgentCount = critical + high;
511
+ const packages = `${findingCount} vulnerable ${pluralize(findingCount, "package")}`;
512
+ // Only name the severities actually present. "(0 critical, 1 high)" reads as noise.
513
+ const breakdown = [
514
+ critical > 0 ? `${critical} critical` : null,
515
+ high > 0 ? `${high} high` : null,
516
+ ].filter(Boolean).join(", ");
517
+ const urgentNote = urgentCount > 0 ? `, ${urgentCount} urgent (${breakdown})` : "";
518
+ return { text: `${packages}${urgentNote}`, urgent: urgentCount > 0 };
519
+ }
500
520
  export function printFinalStatus(findings, overrideCount = 0, completeness) {
501
521
  console.log("");
502
522
  console.log(chalk.gray("────────────────────────────────"));
@@ -521,19 +541,17 @@ export function printFinalStatus(findings, overrideCount = 0, completeness) {
521
541
  else {
522
542
  const criticalCount = findings.filter(f => f.severity === "critical").length;
523
543
  const highCount = findings.filter(f => f.severity === "high").length;
524
- const urgent = criticalCount > 0 || highCount > 0;
525
- const label = `${findings.length} ${pluralize(findings.length, "vulnerability", "vulnerabilities")}`;
544
+ const verdict = buildScanVerdict(findings.length, criticalCount, highCount);
545
+ const action = verdict.urgent ? "Start with the priority fixes above." : "Review the suggested fix plan above.";
546
+ const renderStatus = verdict.urgent ? chalk.redBright : chalk.yellow;
526
547
  if (hasDetectionGap) {
527
- const severityNote = urgent ? ` (${criticalCount} critical, ${highCount} high)` : "";
528
- const action = urgent ? "Start with the priority fixes above." : "Review the suggested fix plan above.";
529
- const renderStatus = urgent ? chalk.redBright : chalk.yellow;
530
- console.log(renderStatus(`⚠ Partial scan: ${label} found${overrideSuffix}${severityNote}. Vulnerability findings may be incomplete. ${action}`));
548
+ console.log(renderStatus(`⚠ Partial scan: ${verdict.text}${overrideSuffix}. Vulnerability findings may be incomplete. ${action}`));
531
549
  }
532
- else if (urgent) {
533
- console.log(chalk.redBright(`✖ Scan complete. ${label}${overrideSuffix} found (${criticalCount} critical, ${highCount} high). Start with the priority fixes above.`));
550
+ else if (verdict.urgent) {
551
+ console.log(chalk.redBright(`✖ Scan complete. ${verdict.text}${overrideSuffix}. ${action}`));
534
552
  }
535
553
  else {
536
- console.log(chalk.yellow(`▲ Scan complete. ${label}${overrideSuffix} found. Review the suggested fix plan above.`));
554
+ console.log(chalk.yellow(`▲ Scan complete. ${verdict.text}${overrideSuffix}. ${action}`));
537
555
  }
538
556
  }
539
557
  if (hasRemediationGap) {
@@ -833,19 +851,16 @@ export function printCompactOutput(findings, scanInput, options) {
833
851
  console.log("");
834
852
  }
835
853
  // Footer
836
- const urgentCount = counts.critical + counts.high;
854
+ const verdict = buildScanVerdict(findings.length, counts.critical, counts.high);
855
+ const renderStatus = verdict.urgent ? chalk.redBright : chalk.yellow;
837
856
  if (hasDetectionGap) {
838
- const label = urgentCount > 0
839
- ? `${urgentCount} urgent ${pluralize(urgentCount, "issue")} found`
840
- : `${findings.length} ${pluralize(findings.length, "issue")} found`;
841
- const renderStatus = urgentCount > 0 ? chalk.redBright : chalk.yellow;
842
- console.log(renderStatus(`⚠ Partial scan: ${label}. Vulnerability findings may be incomplete.`));
857
+ console.log(renderStatus(`⚠ Partial scan: ${verdict.text}. Vulnerability findings may be incomplete.`));
843
858
  }
844
- else if (urgentCount > 0) {
845
- console.log(chalk.redBright(`✖ Scan complete. ${urgentCount} urgent ${pluralize(urgentCount, "issue")} found.`));
859
+ else if (verdict.urgent) {
860
+ console.log(chalk.redBright(`✖ Scan complete. ${verdict.text}.`));
846
861
  }
847
862
  else {
848
- console.log(chalk.yellow(`▲ Scan complete. ${findings.length} ${pluralize(findings.length, "issue")} found.`));
863
+ console.log(chalk.yellow(`▲ Scan complete. ${verdict.text}.`));
849
864
  }
850
865
  printIncompleteDiagnostics(options?.completeness);
851
866
  if (hasRemediationGap) {
@@ -47,15 +47,74 @@ function toLockfileName(filePath) {
47
47
  const name = path.basename(filePath);
48
48
  return LOCKFILE_NAMES.find(candidate => candidate === name) ?? null;
49
49
  }
50
- /** First lockfile present at the repo root, in precedence order. */
50
+ /** The lockfile each package manager writes, for reading `packageManager`. */
51
+ const PACKAGE_MANAGER_LOCKFILES = {
52
+ npm: "package-lock.json",
53
+ pnpm: "pnpm-lock.yaml",
54
+ yarn: "yarn.lock",
55
+ bun: "bun.lock",
56
+ };
57
+ /**
58
+ * The package manager a project declares for itself, from the `packageManager`
59
+ * field npm and Corepack already standardise on. Returns the bare name, so
60
+ * "pnpm@10.14.0" gives "pnpm".
61
+ */
62
+ function readDeclaredPackageManager(projectRoot) {
63
+ const manifest = safeReadText(path.join(projectRoot, "package.json"));
64
+ if (manifest === null)
65
+ return null;
66
+ try {
67
+ const declared = JSON.parse(manifest).packageManager;
68
+ if (typeof declared !== "string")
69
+ return null;
70
+ const name = declared.split("@")[0]?.trim().toLowerCase();
71
+ return name && name in PACKAGE_MANAGER_LOCKFILES ? name : null;
72
+ }
73
+ catch {
74
+ // A manifest we cannot parse tells us nothing about the package manager.
75
+ // Lockfile selection falls back to precedence rather than failing here.
76
+ return null;
77
+ }
78
+ }
79
+ /**
80
+ * Picks the lockfile at the repo root.
81
+ *
82
+ * A project that declares `packageManager` has already answered this, so that
83
+ * wins. Filename precedence is only a guess for when it has not, and guessing
84
+ * went badly: a stale `package-lock.json` left behind by a migration outranked
85
+ * the `pnpm-lock.yaml` actually describing the project, so a 504-package tree
86
+ * scanned as one package and reported no known vulnerabilities (#1159).
87
+ */
51
88
  function findRootLockfile(projectRoot) {
52
- for (const name of LOCKFILE_PRIORITY_ROOT) {
53
- const filePath = path.join(projectRoot, name);
54
- if (fs.existsSync(filePath)) {
55
- return { filePath, name };
56
- }
89
+ const present = LOCKFILE_PRIORITY_ROOT.filter(name => fs.existsSync(path.join(projectRoot, name)));
90
+ if (present.length === 0)
91
+ return null;
92
+ const declared = readDeclaredPackageManager(projectRoot);
93
+ const declaredLockfile = declared ? PACKAGE_MANAGER_LOCKFILES[declared] : undefined;
94
+ const chosen = declaredLockfile && present.includes(declaredLockfile) ? declaredLockfile : present[0];
95
+ return {
96
+ filePath: path.join(projectRoot, chosen),
97
+ name: chosen,
98
+ skipped: present.filter(name => name !== chosen),
99
+ declaredBy: chosen === declaredLockfile ? declared : undefined,
100
+ };
101
+ }
102
+ /** Says which lockfile was used and why, whenever the root held more than one. */
103
+ function describeLockfileChoice(found) {
104
+ if (found.skipped.length === 0)
105
+ return [];
106
+ const others = found.skipped.join(", ");
107
+ return found.declaredBy
108
+ ? [`Root also contains ${others}. Used ${found.name} because package.json declares packageManager "${found.declaredBy}".`]
109
+ : [`Root also contains ${others}. Used ${found.name} by precedence; no packageManager field declared.`];
110
+ }
111
+ function readInput(filePath, load) {
112
+ try {
113
+ return load();
114
+ }
115
+ catch (err) {
116
+ throw new Error(`Failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
57
117
  }
58
- return null;
59
118
  }
60
119
  function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
61
120
  const handler = LOCKFILE_HANDLERS[name];
@@ -63,7 +122,7 @@ function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
63
122
  mode: "resolved-lockfile",
64
123
  source: handler.source,
65
124
  filePath,
66
- packages: handler.load(filePath, prodOnly),
125
+ packages: readInput(filePath, () => handler.load(filePath, prodOnly)),
67
126
  notes: [
68
127
  `Scanned resolved dependency versions from ${label}.`,
69
128
  handler.pathNote,
@@ -76,7 +135,7 @@ function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
76
135
  export function loadPackages(projectRoot, prodOnly, maxDepth) {
77
136
  const rootLockfile = findRootLockfile(projectRoot);
78
137
  if (rootLockfile !== null) {
79
- return buildLockfileScan(rootLockfile.filePath, rootLockfile.name, prodOnly, rootLockfile.name, []);
138
+ return buildLockfileScan(rootLockfile.filePath, rootLockfile.name, prodOnly, rootLockfile.name, describeLockfileChoice(rootLockfile));
80
139
  }
81
140
  const discoveredLockfiles = findFiles(projectRoot, [...LOCKFILE_NAMES], maxDepth);
82
141
  if (discoveredLockfiles.length > 0) {
@@ -88,7 +147,7 @@ export function loadPackages(projectRoot, prodOnly, maxDepth) {
88
147
  }
89
148
  const packageJsonPath = findNearestPackageJson(projectRoot, maxDepth);
90
149
  if (packageJsonPath) {
91
- const manifestResult = loadFromPackageJson(packageJsonPath, prodOnly);
150
+ const manifestResult = readInput(packageJsonPath, () => loadFromPackageJson(packageJsonPath, prodOnly));
92
151
  const warnings = [
93
152
  "No supported lockfile was found, so the scanner fell back to package.json.",
94
153
  "Manifest fallback can only check direct dependencies pinned to exact versions."
@@ -59,7 +59,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
59
59
  return relDelta;
60
60
  return a.pkg.name.localeCompare(b.pkg.name);
61
61
  });
62
- const targetsByPackage = new Map();
62
+ const targetsByKey = new Map();
63
63
  const skippedByKey = new Map();
64
64
  const orderedFindings = [
65
65
  ...prioritizedFindings,
@@ -106,7 +106,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
106
106
  isUpgradeTarget(finding.pkg.version, directTarget) &&
107
107
  validatedFieldOk) {
108
108
  const pkgWorkspaces = workspaceMap.get(finding.pkg.name)?.filter(w => w !== ".") ?? [];
109
- upsertTarget(targetsByPackage, {
109
+ upsertTarget(targetsByKey, finding, {
110
110
  package: finding.pkg.name,
111
111
  currentVersion: finding.pkg.version,
112
112
  targetVersion: directTarget,
@@ -171,7 +171,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
171
171
  if (packageManager === "npm" &&
172
172
  finding.relationship === "transitive" &&
173
173
  finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
174
- upsertTarget(targetsByPackage, {
174
+ upsertTarget(targetsByKey, finding, {
175
175
  package: finding.recommendedNpmTransitiveRemediation.package,
176
176
  currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
177
177
  targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
@@ -199,7 +199,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
199
199
  ? finding.chainResolution
200
200
  : null;
201
201
  const npmParentUpgradeWorkspaces = workspaceMap.get(finding.recommendedNpmTransitiveRemediation.package)?.filter(w => w !== ".") ?? [];
202
- upsertTarget(targetsByPackage, {
202
+ upsertTarget(targetsByKey, finding, {
203
203
  package: finding.recommendedNpmTransitiveRemediation.package,
204
204
  currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
205
205
  targetVersion: finding.recommendedNpmTransitiveRemediation.targetVersion,
@@ -231,7 +231,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
231
231
  ? finding.chainResolution
232
232
  : null;
233
233
  const parentUpgradeWorkspaces = workspaceMap.get(finding.recommendedParentUpgrade.package)?.filter(w => w !== ".") ?? [];
234
- upsertTarget(targetsByPackage, {
234
+ upsertTarget(targetsByKey, finding, {
235
235
  package: finding.recommendedParentUpgrade.package,
236
236
  currentVersion: finding.recommendedParentUpgrade.currentVersion,
237
237
  targetVersion: finding.recommendedParentUpgrade.targetVersion,
@@ -273,7 +273,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
273
273
  : packageManager === "yarn"
274
274
  ? `yarn upgrade ${finding.pkg.name}`
275
275
  : `bun update ${finding.pkg.name}`;
276
- upsertTarget(targetsByPackage, {
276
+ upsertTarget(targetsByKey, finding, {
277
277
  package: finding.pkg.name,
278
278
  currentVersion: finding.pkg.version,
279
279
  targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
@@ -296,7 +296,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
296
296
  const isDev = devLookup.get(`${finding.chainResolution.directDep}@${finding.chainResolution.directDepCurrentVersion}`) ?? false;
297
297
  const coverage = calculatePathCoverage(finding.dependencyPaths, [finding.chainResolution.directDep]);
298
298
  const chainWorkspaces = workspaceMap.get(finding.chainResolution.directDep)?.filter(w => w !== ".") ?? [];
299
- upsertTarget(targetsByPackage, {
299
+ upsertTarget(targetsByKey, finding, {
300
300
  package: finding.chainResolution.directDep,
301
301
  currentVersion: finding.chainResolution.directDepCurrentVersion,
302
302
  targetVersion: finding.chainResolution.targetVersion,
@@ -337,7 +337,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
337
337
  : "No confident automatic fix command could be generated for this issue.",
338
338
  });
339
339
  }
340
- const targets = [...targetsByPackage.values()].sort((a, b) => {
340
+ const targets = [...targetsByKey.values()].sort((a, b) => {
341
341
  const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
342
342
  if (sevDelta !== 0)
343
343
  return sevDelta;
@@ -532,10 +532,25 @@ function packageManagerSourceLabel(scanInput) {
532
532
  return "bun.lock";
533
533
  return scanInput.source;
534
534
  }
535
- function upsertTarget(targetsByPackage, next) {
536
- const existing = targetsByPackage.get(next.package);
535
+ // Install targets (direct / parent-upgrade) all mean "install <package>@<targetVersion>",
536
+ // so findings that land on the same package merge into one target and the higher
537
+ // version wins. A parent-update target means something else: "refresh <vulnerable
538
+ // child> within <package>'s declared range", and its targetVersion is the CHILD's
539
+ // version, not <package>'s. Merging it with an install target for the same package
540
+ // compares versions of two different packages, and the child's version can end up
541
+ // pinned onto the parent (`npm install axios@4.0.6`, where 4.0.6 is form-data's
542
+ // version - #1007). Keep parent-update targets in their own keyspace, per child, so
543
+ // they only ever merge with a refresh of the same child through the same package.
544
+ function targetKey(finding, target) {
545
+ return target.kind === "parent-update"
546
+ ? `parent-update:${target.package}>${finding.pkg.name}`
547
+ : `install:${target.package}`;
548
+ }
549
+ function upsertTarget(targetsByKey, finding, next) {
550
+ const key = targetKey(finding, next);
551
+ const existing = targetsByKey.get(key);
537
552
  if (!existing) {
538
- targetsByPackage.set(next.package, next);
553
+ targetsByKey.set(key, next);
539
554
  return;
540
555
  }
541
556
  const merged = {
@@ -600,7 +615,7 @@ function upsertTarget(targetsByPackage, next) {
600
615
  merged.adjustmentNote = existing.adjustmentNote ?? null;
601
616
  merged.advisoryVersion = existing.advisoryVersion ?? next.advisoryVersion ?? null;
602
617
  }
603
- targetsByPackage.set(next.package, merged);
618
+ targetsByKey.set(key, merged);
604
619
  return;
605
620
  }
606
621
  if (next.kind === "direct" && existing.kind !== "direct") {
@@ -612,7 +627,7 @@ function upsertTarget(targetsByPackage, next) {
612
627
  merged.knownVulnerableVersions = next.knownVulnerableVersions ?? merged.knownVulnerableVersions ?? null;
613
628
  merged.fixVersionPublishedAt = next.fixVersionPublishedAt ?? merged.fixVersionPublishedAt ?? null;
614
629
  }
615
- targetsByPackage.set(next.package, merged);
630
+ targetsByKey.set(key, merged);
616
631
  }
617
632
  function buildParentUpgradeReason(finding, coverage) {
618
633
  const coveredPath = coverage.coveredPaths[0];
@@ -159,7 +159,16 @@ export async function resolvePublishedFixVersion(packageName, fixedVersionHint)
159
159
  publishedAt: null,
160
160
  };
161
161
  }
162
- export async function resolveLowestKnownNonVulnerableVersion(packageName, installedVersion, vulnerabilities) {
162
+ /**
163
+ * Resolve a fix version from advisory range metadata alone.
164
+ *
165
+ * Correct for the advisories it is handed, and that is the limitation: the
166
+ * caller passes the set that matched the INSTALLED version, so an advisory
167
+ * introduced at or above the fix version is not in it and nothing here can
168
+ * reject a candidate that advisory covers. `confirmAgainstAdvisorySource`
169
+ * closes that gap.
170
+ */
171
+ async function resolveFromAdvisoryRanges(packageName, installedVersion, vulnerabilities) {
163
172
  if (!looksLikeVersion(installedVersion)) {
164
173
  return {
165
174
  resolvedVersion: null,
@@ -268,6 +277,96 @@ export async function resolveLowestKnownNonVulnerableVersion(packageName, instal
268
277
  publishedAt: null,
269
278
  };
270
279
  }
280
+ /** Candidates queried above the range answer before giving up and saying so. */
281
+ const CONFIRMATION_CANDIDATE_LIMIT = 25;
282
+ /**
283
+ * Re-ask the advisory source about the version we are about to recommend.
284
+ *
285
+ * The question is asked per version rather than by evaluating ranges, the same
286
+ * choice `populateAdmittedVersions` makes for OA010 and for the same reason:
287
+ * advisory ranges arrive in shapes that are not valid semver and one id can
288
+ * carry different ranges per ecosystem, so parsing them fails silently in the
289
+ * unsafe direction. A version-scoped query cannot.
290
+ *
291
+ * Starts at the range answer rather than at the installed version, so the usual
292
+ * case is a single query that confirms it.
293
+ */
294
+ /** Keep the version we were going to recommend, but say it is not confirmed. */
295
+ function markUnconfirmed(resolution, packageName, proposed, reason) {
296
+ return {
297
+ ...resolution,
298
+ verified: false,
299
+ note: `${packageName}@${proposed} could not be confirmed free of later advisories (${reason}).`,
300
+ };
301
+ }
302
+ /** Published stable versions from the proposed one upward, capped. */
303
+ function confirmationCandidates(packument, proposed) {
304
+ return Object.keys(packument?.versions ?? {})
305
+ .filter(looksLikeVersion)
306
+ .filter(v => !isPreReleaseVersion(v))
307
+ .filter(v => compareVersions(v, proposed) >= 0)
308
+ .sort(compareVersions)
309
+ .slice(0, CONFIRMATION_CANDIDATE_LIMIT);
310
+ }
311
+ async function confirmAgainstAdvisorySource(packageName, resolution, advisorySource, proposedVersion) {
312
+ // The range pass returns null whenever any advisory lacks usable ranges, which
313
+ // one sparse duplicate record is enough to cause (#1196). The caller's hint is
314
+ // then what gets recommended, so that is what has to be confirmed.
315
+ const proposed = resolution.resolvedVersion ?? proposedVersion;
316
+ if (!proposed)
317
+ return resolution;
318
+ const packument = await fetchPackument(packageName);
319
+ const candidates = confirmationCandidates(packument, proposed);
320
+ if (candidates.length === 0)
321
+ return resolution;
322
+ const unconfirmed = (reason) => markUnconfirmed(resolution, packageName, proposed, reason);
323
+ let results;
324
+ try {
325
+ results = await advisorySource.queryBatch(candidates.map(version => ({ name: packageName, version, ecosystem: "npm" })), { batchId: "fix-version-confirmation" });
326
+ }
327
+ catch {
328
+ return unconfirmed("the advisory source was unavailable");
329
+ }
330
+ // An advisory source is an external boundary: it can resolve to undefined or a
331
+ // non-array, and one malformed response must not take the whole scan down the
332
+ // way an unguarded advisory record used to (#917).
333
+ if (!Array.isArray(results))
334
+ return unconfirmed("the advisory source returned no usable result");
335
+ const vulnerableVersions = new Set(results
336
+ .filter((r) => typeof r === "object" && r !== null && typeof r.version === "string")
337
+ .filter(r => (r.vulnerabilities ?? []).length > 0)
338
+ .map(r => r.version));
339
+ const confirmed = candidates.find(v => !vulnerableVersions.has(v));
340
+ if (!confirmed)
341
+ return unconfirmed(`the ${candidates.length} versions above it are also affected`);
342
+ // A version-scoped query returning nothing is a stronger statement than range
343
+ // arithmetic, so it confirms the answer even when the range pass could not.
344
+ if (confirmed === proposed && resolution.resolvedVersion)
345
+ return resolution;
346
+ return {
347
+ ...resolution,
348
+ resolvedVersion: confirmed,
349
+ verified: true,
350
+ note: null,
351
+ candidatesKnownVulnerable: resolution.candidatesKnownVulnerable + candidates.indexOf(confirmed),
352
+ publishedAt: packument?.time?.[confirmed] ?? null,
353
+ };
354
+ }
355
+ /**
356
+ * The lowest published version above `installedVersion` with no known advisory.
357
+ *
358
+ * Two passes. The first reads the advisory ranges we already hold, which is fast
359
+ * and offline-capable. The second asks the advisory source about the version
360
+ * that produced, because an advisory introduced at or above it was never matched
361
+ * to this finding and is therefore invisible to the first pass.
362
+ */
363
+ export async function resolveLowestKnownNonVulnerableVersion(packageName, installedVersion, vulnerabilities, options) {
364
+ const resolution = await resolveFromAdvisoryRanges(packageName, installedVersion, vulnerabilities);
365
+ const advisorySource = options?.advisorySource;
366
+ if (!advisorySource)
367
+ return resolution;
368
+ return confirmAgainstAdvisorySource(packageName, resolution, advisorySource, options?.proposedVersion);
369
+ }
271
370
  function isVersionAffectedByVulnerability(packageName, version, vuln) {
272
371
  const affectedEntries = vuln.affected ?? [];
273
372
  if (affectedEntries.length === 0)
package/dist/scanner.js CHANGED
@@ -24,6 +24,12 @@ import { pluralize } from "./utils/string.js";
24
24
  import { extractErrorMessage } from "./utils/network.js";
25
25
  import { logWarn } from "./output/formatters.js";
26
26
  import { formatDiagnosticMessage } from "./scan/completeness.js";
27
+ /**
28
+ * Advisory id namespaces OSV does not serve. Ids with these prefixes come from
29
+ * a different source, so OSV failing to resolve them is expected and must not
30
+ * be reported as missing detail.
31
+ */
32
+ const OSV_FOREIGN_ID_PREFIXES = ["NPM-"];
27
33
  export function createAdvisorySource(options) {
28
34
  const offline = !!options?.offline || !!options?.offlineDb;
29
35
  if (offline) {
@@ -197,9 +203,17 @@ export async function scanPackages(packages, batchSize, options, context, debugL
197
203
  const key = getPackageCacheKey(pkg);
198
204
  const cached = cache.npmAdvisoryEntries[key];
199
205
  if (cached && !isEntryStale(cached, nowMs)) {
200
- const newCachedVulnIds = cached.vulnIds.filter(id => !existingVulnIds.has(id));
201
- if (newCachedVulnIds.length > 0) {
202
- results.push({ pkg, vulnIds: newCachedVulnIds });
206
+ const newCachedVulns = cached.vulns.filter(v => !existingVulnIds.has(v.id));
207
+ if (newCachedVulns.length > 0) {
208
+ results.push({ pkg, vulnIds: newCachedVulns.map(v => v.id) });
209
+ // Seed the detail map from the cache. These advisories come from the npm
210
+ // registry namespace, so nothing downstream can resolve them: OSV returns
211
+ // 404 for an NPM-prefixed id by definition. Restoring only the ids left
212
+ // them unresolvable, which dropped them from the CVE tally on every scan
213
+ // after the first and reported them as detail confirmed missing.
214
+ for (const vuln of newCachedVulns) {
215
+ vulnMap.set(vuln.id, vuln);
216
+ }
203
217
  }
204
218
  }
205
219
  else {
@@ -215,10 +229,11 @@ export async function scanPackages(packages, batchSize, options, context, debugL
215
229
  for (const pkg of uncachedForNpm) {
216
230
  const found = npmResults.find(r => r.pkg.name === pkg.name && r.pkg.version === pkg.version);
217
231
  const vulns = found?.vulns ?? [];
218
- const vulnIds = vulns.map(v => v.id);
219
- // Store the full list in cache (for cache correctness on future scans),
220
- // but only add genuinely new vulns to results - ones OSV did not already surface
221
- cache.npmAdvisoryEntries[getPackageCacheKey(pkg)] = { vulnIds, cachedAt };
232
+ // Store the full advisories in cache, not just their ids, so a later scan
233
+ // can restore the detail rather than going looking for it in OSV, which
234
+ // does not hold this namespace. Only genuinely new vulns go into results -
235
+ // ones OSV did not already surface.
236
+ cache.npmAdvisoryEntries[getPackageCacheKey(pkg)] = { vulns, cachedAt };
222
237
  const newVulns = vulns.filter(v => !existingVulnIds.has(v.id));
223
238
  const newVulnIds = newVulns.map(v => v.id);
224
239
  if (newVulns.length > 0) {
@@ -238,7 +253,13 @@ export async function scanPackages(packages, batchSize, options, context, debugL
238
253
  const offlineMissingDetailIds = new Set();
239
254
  const confirmedMissingDetailIds = new Set();
240
255
  if (idSet.size > 0 && !offline) {
241
- const ids = [...idSet];
256
+ // Only ask OSV for ids OSV can own. The npm registry advisory source
257
+ // (#1056) contributes NPM-prefixed ids from its own namespace, and
258
+ // api.osv.dev/v1/vulns/NPM-... is a 404 by definition. Sending them
259
+ // anyway made every online scan of a project carrying npm-sourced
260
+ // advisories report `partial` with "findings may be incomplete", when
261
+ // nothing was missing: the detail was looked for in the wrong database.
262
+ const ids = [...idSet].filter((id) => !OSV_FOREIGN_ID_PREFIXES.some((prefix) => id.startsWith(prefix)));
242
263
  const detailSpinner = createSpinner("Fetching vulnerability details...", options);
243
264
  try {
244
265
  const nowMs = Date.now();
@@ -477,7 +498,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
477
498
  if (!offline) {
478
499
  const npmVersionCacheUpdated = await validateDirectFixTargets(findings, (finding) => {
479
500
  updateAnalysisProgress("validating fix target for", `${finding.pkg.name}@${finding.pkg.version}`);
480
- }, { cache, noCache: options.noCache, debugLog: log });
501
+ }, { cache, noCache: options.noCache, debugLog: log, advisorySource });
481
502
  if (npmVersionCacheUpdated) {
482
503
  saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
483
504
  }
@@ -619,6 +640,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
619
640
  cache,
620
641
  noCache: options.noCache,
621
642
  debugLog: log,
643
+ advisorySource,
622
644
  });
623
645
  if (npmVersionCacheUpdated) {
624
646
  saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
@@ -710,7 +732,9 @@ async function validateOneDirectFixTarget(finding, options) {
710
732
  verified: Boolean(finding.validatedFirstFixedVersion),
711
733
  });
712
734
  };
713
- const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities);
735
+ // The advisory source re-checks the proposed version for advisories
736
+ // introduced above the installed one, which never matched this finding.
737
+ const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities, { advisorySource: options?.advisorySource, proposedVersion: finding.firstFixedVersion });
714
738
  const fixedVersionHint = finding.firstFixedVersion;
715
739
  const setPublishedDate = (resolution) => {
716
740
  const date = resolution.publishedAt;
@@ -835,49 +859,70 @@ function versionWithinAffectedWindow(version, introduced, fixed) {
835
859
  }
836
860
  return compareVersions(version, fixed) < 0;
837
861
  }
838
- export function findFirstFixedVersion(vulns, packageName, ecosystem, installedVersion) {
839
- const fixedVersions = [];
840
- // Fixes whose affected window actually contains the installed version. An
841
- // advisory that patches two release branches declares a fix per branch, and
842
- // the global minimum is the other branch's fix - a downgrade across a major
843
- // boundary rather than a remediation.
844
- const fixesOnInstalledBranch = [];
845
- for (const vuln of vulns) {
846
- for (const affected of vuln.affected ?? []) {
847
- // An advisory may list several packages with different fix versions.
848
- // Without this filter the global minimum across all of them was
849
- // returned, so a package inherited another package's (lower) fix and
850
- // the scan reported a version that does not fix it.
851
- if (!affectedEntryMatchesPackage(affected, packageName, ecosystem))
852
- continue;
853
- for (const range of affected.ranges ?? []) {
854
- // Events are ordered, and a single range can reintroduce a
855
- // vulnerability, so `introduced` is tracked as the walk proceeds and
856
- // reset once its matching `fixed` closes the window.
857
- let introduced = null;
858
- for (const event of range.events ?? []) {
859
- if (event.introduced) {
860
- introduced = event.introduced;
861
- continue;
862
- }
863
- const fixed = event.fixed;
864
- if (!fixed || !looksLikeVersion(fixed) || isPreReleaseVersion(fixed))
865
- continue;
866
- fixedVersions.push(fixed);
867
- if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed)) {
868
- fixesOnInstalledBranch.push(fixed);
869
- }
870
- introduced = null;
862
+ /**
863
+ * Every usable fixed version one advisory declares for this package, split into
864
+ * all of them and those whose affected window contains the installed version.
865
+ */
866
+ function collectAdvisoryFixes(vuln, packageName, ecosystem, installedVersion) {
867
+ const all = [];
868
+ // An advisory that patches two release branches declares a fix per branch, and
869
+ // the other branch's fix is a downgrade across a major boundary rather than a
870
+ // remediation.
871
+ const onInstalledBranch = [];
872
+ for (const affected of vuln.affected ?? []) {
873
+ // An advisory may list several packages with different fix versions.
874
+ // Without this filter the minimum across all of them was returned, so a
875
+ // package inherited another package's (lower) fix and the scan reported a
876
+ // version that does not fix it.
877
+ if (!affectedEntryMatchesPackage(affected, packageName, ecosystem))
878
+ continue;
879
+ for (const range of affected.ranges ?? []) {
880
+ // Events are ordered, and a single range can reintroduce a vulnerability,
881
+ // so `introduced` is tracked as the walk proceeds and reset once its
882
+ // matching `fixed` closes the window.
883
+ let introduced = null;
884
+ for (const event of range.events ?? []) {
885
+ if (event.introduced) {
886
+ introduced = event.introduced;
887
+ continue;
871
888
  }
889
+ const fixed = event.fixed;
890
+ if (!fixed || !looksLikeVersion(fixed) || isPreReleaseVersion(fixed))
891
+ continue;
892
+ all.push(fixed);
893
+ if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed)) {
894
+ onInstalledBranch.push(fixed);
895
+ }
896
+ introduced = null;
872
897
  }
873
898
  }
874
899
  }
875
- // Falling back to every known fix keeps a finding's remediation visible when
876
- // the installed version sits outside each declared window.
877
- const candidates = fixesOnInstalledBranch.length > 0 ? fixesOnInstalledBranch : fixedVersions;
878
- if (candidates.length === 0)
900
+ return { all, onInstalledBranch };
901
+ }
902
+ export function findFirstFixedVersion(vulns, packageName, ecosystem, installedVersion) {
903
+ const everyKnownFix = [];
904
+ // One entry per advisory: the earliest version clearing THAT advisory on the
905
+ // branch the install sits on.
906
+ const perAdvisoryFixes = [];
907
+ for (const vuln of vulns) {
908
+ const { all, onInstalledBranch } = collectAdvisoryFixes(vuln, packageName, ecosystem, installedVersion);
909
+ everyKnownFix.push(...all);
910
+ if (onInstalledBranch.length > 0) {
911
+ // Lowest WITHIN one advisory: the branch fix, not the other branch's.
912
+ perAdvisoryFixes.push(onInstalledBranch.sort(compareVersions)[0]);
913
+ }
914
+ }
915
+ // Highest ACROSS advisories: the caller needs a version clear of all of them,
916
+ // and stopping at the lowest leaves every advisory fixed above it still live.
917
+ if (perAdvisoryFixes.length > 0) {
918
+ return perAdvisoryFixes.sort(compareVersions)[perAdvisoryFixes.length - 1];
919
+ }
920
+ // No declared window contains the installed version, so there is no branch to
921
+ // scope to. Falling back to every known fix keeps a finding's remediation
922
+ // visible rather than reporting none.
923
+ if (everyKnownFix.length === 0)
879
924
  return null;
880
- return candidates.sort(compareVersions)[0];
925
+ return everyKnownFix.sort(compareVersions)[0];
881
926
  }
882
927
  function buildCompletenessDiagnostics(params) {
883
928
  const diagnostics = [];
@@ -152,6 +152,10 @@ export function getNetworkErrorHint(error, errorMessage) {
152
152
  return serverAdvisoryRequestHint();
153
153
  if (isLikelyBlockedAdvisoryRequestError(errorMessage))
154
154
  return blockedAdvisoryRequestHint();
155
+ // Local read/parse failures are stamped with this prefix by readInput() in
156
+ // src/parsers/index.ts. They are not network failures, so no CA hint.
157
+ if (errorMessage.startsWith("Failed to read "))
158
+ return [];
155
159
  return fetchErrorCaCertHint();
156
160
  }
157
161
  export function createCertAwareFetch(caCertPath) {
@@ -218,18 +218,27 @@ export function satisfiesRange(version, range) {
218
218
  const target = coerceVersion(trimmedRange.slice(1));
219
219
  return target !== null && compareVersions(v, target) === 0;
220
220
  }
221
- // `^` caret: same major, >= specified, < next major
221
+ // `^` caret: >= floor, ceiling at the leftmost non-zero component of the
222
+ // target (npm: ^1.2.0 -> <2.0.0; ^0.2.3 -> <0.3.0; ^0.0.3 -> <0.0.4).
223
+ // Partial ranges keep their component count: ^0 admits all 0.x, ^0.0 admits 0.0.x.
222
224
  if (trimmedRange.startsWith("^")) {
223
225
  const target = coerceVersion(trimmedRange.slice(1));
224
226
  if (!target)
225
227
  return false;
226
228
  if (compareVersions(v, target) < 0)
227
229
  return false;
228
- const tMajor = majorVersion(target);
229
- const vMajor = majorVersion(v);
230
- if (tMajor === null || vMajor === null)
231
- return false;
232
- return vMajor === tMajor;
230
+ const [vMaj, vMin, vPatch] = v.split(".").map(Number);
231
+ const [tMaj, tMin, tPatch] = target.split(".").map(Number);
232
+ const parts = trimmedRange.slice(1).split("-")[0].split(".");
233
+ if (tMaj > 0)
234
+ return vMaj === tMaj; // ^1, ^1.2, ^1.2.3
235
+ if (tMin > 0)
236
+ return vMaj === tMaj && vMin === tMin; // ^0.1, ^0.1.x
237
+ if (parts.length >= 3)
238
+ return vMaj === tMaj && vMin === tMin && vPatch === tPatch; // ^0.0.3 exact
239
+ if (parts.length === 2)
240
+ return vMaj === tMaj && vMin === tMin; // ^0.0 -> 0.0.x
241
+ return vMaj === tMaj; // ^0 -> all 0.x
233
242
  }
234
243
  // `~` tilde: same major.minor, >= specified
235
244
  if (trimmedRange.startsWith("~")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.35.0",
3
+ "version": "1.36.1",
4
4
  "description": "Developer-friendly CLI for scanning JS/TS projects for dependency vulnerabilities using local lockfiles and OSV",
5
5
  "type": "module",
6
6
  "bin": {
@@ -59,6 +59,7 @@
59
59
  "homepage": "https://github.com/OWASP/cve-lite-cli#readme",
60
60
  "files": [
61
61
  "dist",
62
+ "scripts/pr-scan-delta.mjs",
62
63
  "README.md",
63
64
  "LICENSE",
64
65
  "assets/logo-with-title-removebg-preview.png",
@@ -0,0 +1,315 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Turn two scan JSON files (base and head of a PR) into a PR comment describing
4
+ * only what THIS PR changed.
5
+ *
6
+ * The scoping is the whole point. A comment that republishes every pre-existing
7
+ * finding on an unrelated PR is the reason people disable tools like this, so
8
+ * this reports the delta and stays silent when the finding set did not move.
9
+ *
10
+ * node scripts/pr-scan-delta.mjs base.json head.json
11
+ *
12
+ * Prints the comment body, or nothing at all when there is no delta.
13
+ */
14
+
15
+ const MARKER = "<!-- cve-lite-cli:pr-delta -->";
16
+
17
+ /**
18
+ * The wordmark on its own line, linked to the repository.
19
+ *
20
+ * Inline it cannot win: at a legible width the image is taller than the line
21
+ * box, so it either overhangs or has to shrink to about 24px. On its own line
22
+ * there is nothing to align against.
23
+ *
24
+ * The link is not decoration. Without an explicit href GitHub wraps the image
25
+ * in a link to the raw PNG, so clicking the logo opens a 217KB file, which is
26
+ * worse than no link at all.
27
+ */
28
+ const LOGO_URL =
29
+ "https://raw.githubusercontent.com/OWASP/cve-lite-cli/main/assets/logo-with-title-transparent.png";
30
+ const PROJECT_URL = "https://github.com/OWASP/cve-lite-cli";
31
+ const TITLE =
32
+ `<a href="${PROJECT_URL}"><img src="${LOGO_URL}" width="120" alt="CVE Lite CLI"></a>`;
33
+
34
+ /**
35
+ * Collapsed by default, so it costs one line until someone opens it. The badge
36
+ * is fenced rather than inlined: an inline badge renders as an image, and the
37
+ * point is to give people something they can copy into a README.
38
+ */
39
+ const SHARE = [
40
+ "<details>",
41
+ "<summary>\u2764\ufe0f Share</summary>",
42
+ "",
43
+ "If this caught something before it merged, a mention helps other maintainers find it.",
44
+ "",
45
+ `- [Post on X](https://twitter.com/intent/tweet?text=CVE%20Lite%20CLI%20caught%20a%20vulnerable%20transitive%20dependency%20in%20my%20PR%20before%20it%20merged.&url=${PROJECT_URL})`,
46
+ `- [Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=${PROJECT_URL})`,
47
+ "- Add the badge to your README:",
48
+ "",
49
+ " ```markdown",
50
+ ` [![Protected by CVE Lite CLI](https://img.shields.io/badge/Protected_by-CVE_Lite_CLI-brightgreen)](${PROJECT_URL})`,
51
+ " ```",
52
+ "",
53
+ "</details>",
54
+ ];
55
+
56
+ const SEVERITY_RANK = { critical: 4, high: 3, medium: 2, low: 1, unknown: 0, none: 0 };
57
+
58
+ /**
59
+ * Every string in the comment originates in a lockfile the PR author controls,
60
+ * and with fork PRs supported that author is untrusted. GitHub strips raw HTML
61
+ * in comments so this is not an XSS surface, but a crafted package name can
62
+ * still inject links, headings, or prose that reads as if a maintainer wrote it.
63
+ *
64
+ * Allowlist rather than escape: these fields have known, narrow shapes, so
65
+ * anything outside them is dropped rather than encoded. npm names allow
66
+ * `@scope/name`, semver allows dots, hyphens and plus, advisory ids are
67
+ * alphanumeric with separators.
68
+ */
69
+ const SAFE_CHARS = /[^A-Za-z0-9._@/+-]/g;
70
+ const MAX_FIELD = 120;
71
+
72
+ /**
73
+ * Commands are rendered inside a fenced block, so spaces must survive while
74
+ * anything that could close the fence or start a new directive must not.
75
+ */
76
+ function safeCommand(value) {
77
+ const raw = String(value ?? "");
78
+ return raw.replace(/[^A-Za-z0-9._@/+ -]/g, "").trim().slice(0, 200);
79
+ }
80
+
81
+ /**
82
+ * Post a command only when sanitising it changes nothing.
83
+ *
84
+ * safeCommand's allowlist is a trust boundary, not cosmetics: stage 1 built this
85
+ * JSON on a machine the PR author controls (see pr-delta-scan.yml), so the string
86
+ * is attacker-influenced. But the allowlist also rewrites legitimate commands. It
87
+ * excludes `&`, and runnableFixCommand genuinely contains `&&` because
88
+ * fix-commands.ts chains with " && " in three places, so a real
89
+ * `pnpm add a@1 && pnpm add -D b@2` was being posted as
90
+ * `pnpm add a@1 pnpm add -D b@2`, which does not work.
91
+ *
92
+ * Rather than loosen the boundary or rebuild the command here (a second
93
+ * implementation of the CLI's own logic, which is what mergeCommands was and why
94
+ * it corrupted pnpm workspace filters), only show commands that survive
95
+ * sanitisation byte for byte. Anything else degrades to no command, which is
96
+ * honest, rather than a wrong one, which is not.
97
+ *
98
+ * Returns the command, or null when one exists but cannot be shown safely, or
99
+ * undefined when the finding carries none (#1172).
100
+ */
101
+ function acceptCommand(value) {
102
+ if (!value) return undefined;
103
+ const raw = String(value);
104
+ return safeCommand(raw) === raw ? raw : null;
105
+ }
106
+
107
+ function safe(value) {
108
+ const raw = String(value ?? "");
109
+ const cleaned = raw.replace(SAFE_CHARS, "").slice(0, MAX_FIELD);
110
+ return cleaned.length > 0 ? cleaned : "(unnamed)";
111
+ }
112
+
113
+ function findingsOf(scan) {
114
+ if (!scan || typeof scan !== "object") return [];
115
+ return Array.isArray(scan.findings) ? scan.findings : [];
116
+ }
117
+
118
+ /**
119
+ * One row per (package, version), carrying every advisory id on it. A single
120
+ * finding routinely covers several ids (js-yaml 3.15.1 carries both
121
+ * GHSA-2883-xcg3-v3hh and NPM-1193726) and listing them as separate rows reads
122
+ * as two problems rather than one.
123
+ */
124
+ function index(scan) {
125
+ const rows = new Map();
126
+ for (const f of findingsOf(scan)) {
127
+ const pkg = f.package ?? f.pkg?.name;
128
+ const version = f.version ?? f.pkg?.version;
129
+ if (!pkg || !version) continue;
130
+
131
+ const key = `${pkg}@${version}`;
132
+ const row = rows.get(key) ?? {
133
+ package: safe(pkg),
134
+ version: safe(version),
135
+ severity: safe(f.severity ?? "unknown"),
136
+ relationship: safe(f.relationship ?? ""),
137
+ fixVersion: f.validatedFirstFixedVersion ?? f.firstFixedVersion
138
+ ? safe(f.validatedFirstFixedVersion ?? f.firstFixedVersion)
139
+ : undefined,
140
+ advisories: [],
141
+ cves: [],
142
+ fixCommand: acceptCommand(f.runnableFixCommand),
143
+ };
144
+ for (const v of f.vulnerabilities ?? []) {
145
+ if (v?.id && !row.advisories.includes(safe(v.id))) row.advisories.push(safe(v.id));
146
+ }
147
+ // Advisories whose detail could not be fetched still count as findings, and
148
+ // dropping them silently would understate the delta.
149
+ for (const id of f.unresolvedAdvisoryIds ?? []) {
150
+ if (id && !row.advisories.includes(safe(id))) row.advisories.push(safe(id));
151
+ }
152
+ // A CVE number is what a reader recognises; the GHSA id is what we key on.
153
+ for (const c of f.cves ?? []) {
154
+ if (c && !row.cves.includes(safe(c))) row.cves.push(safe(c));
155
+ }
156
+ rows.set(key, row);
157
+ }
158
+ return rows;
159
+ }
160
+
161
+ export function buildDelta(baseScan, headScan) {
162
+ const base = index(baseScan);
163
+ const head = index(headScan);
164
+
165
+ const bySeverity = (a, b) =>
166
+ (SEVERITY_RANK[b.severity] ?? 0) - (SEVERITY_RANK[a.severity] ?? 0) ||
167
+ a.package.localeCompare(b.package);
168
+
169
+ const introduced = [...head.entries()]
170
+ .filter(([k]) => !base.has(k))
171
+ .map(([, v]) => v)
172
+ .sort(bySeverity);
173
+ const resolved = [...base.entries()]
174
+ .filter(([k]) => !head.has(k))
175
+ .map(([, v]) => v)
176
+ .sort(bySeverity);
177
+
178
+ return { introduced, resolved, hasChanges: introduced.length > 0 || resolved.length > 0 };
179
+ }
180
+
181
+ /**
182
+ * "1 new high finding" when they are all one severity, otherwise
183
+ * "6 new findings (2 critical, 4 high)". Naming only the worst severity across
184
+ * a mixed set reads as though every finding were that severe, which is a
185
+ * material overstatement on a security comment.
186
+ */
187
+ function countPhrase(rows, { adjective } = {}) {
188
+ const n = rows.length;
189
+ const counts = new Map();
190
+ for (const r of rows) counts.set(r.severity, (counts.get(r.severity) ?? 0) + 1);
191
+
192
+ const parts = [String(n)];
193
+ if (adjective) parts.push(adjective);
194
+
195
+ if (counts.size === 1) {
196
+ const only = [...counts.keys()][0];
197
+ if (only !== "unknown") parts.push(only);
198
+ parts.push(`finding${n === 1 ? "" : "s"}`);
199
+ return parts.join(" ");
200
+ }
201
+
202
+ parts.push(`finding${n === 1 ? "" : "s"}`);
203
+ const breakdown = [...counts.entries()]
204
+ .sort((a, b) => (SEVERITY_RANK[b[0]] ?? 0) - (SEVERITY_RANK[a[0]] ?? 0))
205
+ .map(([sev, c]) => `${c} ${sev}`)
206
+ .join(", ");
207
+ return `${parts.join(" ")} (${breakdown})`;
208
+ }
209
+
210
+ /**
211
+ * "GHSA-xxx (CVE-2026-84375)", capped. A single package can carry dozens of
212
+ * advisories (tar@6.1.0 has 36), and listing them all produces a line nobody
213
+ * can read. CVEs are shown in preference to GHSA ids because they are what a
214
+ * reviewer recognises.
215
+ */
216
+ const MAX_IDS = 3;
217
+
218
+ function advisoryLabel(r) {
219
+ const cves = r.cves ?? [];
220
+ const primary = cves.length > 0 ? cves : r.advisories;
221
+ const shown = primary.slice(0, MAX_IDS).join(", ");
222
+ const hidden = primary.length - Math.min(primary.length, MAX_IDS);
223
+ return hidden > 0 ? `${shown} and ${hidden} more` : shown;
224
+ }
225
+
226
+
227
+ export function renderComment(delta) {
228
+ if (!delta.hasChanges) return null;
229
+
230
+ const lines = [MARKER, ""];
231
+ const { introduced, resolved } = delta;
232
+
233
+ if (introduced.length > 0) {
234
+ lines.push(TITLE);
235
+ lines.push("");
236
+ lines.push(`${countPhrase(introduced, { adjective: "new" })} introduced by this PR`);
237
+ lines.push("");
238
+ for (const r of introduced) {
239
+ const via = r.relationship === "transitive" ? " (transitive)" : "";
240
+ lines.push(`- \`${r.package}@${r.version}\`${via} · ${advisoryLabel(r)} · **${r.severity}**`);
241
+ if (r.fixVersion) lines.push(` Fixed in \`${r.fixVersion}\``);
242
+ }
243
+ // Verbatim and complete, or nothing. A partial set reads as the whole fix,
244
+ // and the CLI has already merged these into its plan, so re-merging them here
245
+ // is what corrupted pnpm workspace filters (#1172).
246
+ const raw = introduced.map((r) => r.fixCommand).filter((c) => c !== undefined);
247
+ const withheld = raw.some((c) => c === null);
248
+ const commands = [...new Set(raw.filter(Boolean))];
249
+ if (!withheld && commands.length > 0) {
250
+ lines.push("");
251
+ lines.push("```bash");
252
+ lines.push(...commands);
253
+ lines.push("```");
254
+ } else if (withheld) {
255
+ lines.push("");
256
+ lines.push("Run `cve-lite .` for the fix commands.");
257
+ }
258
+
259
+ if (resolved.length > 0) {
260
+ lines.push("");
261
+ lines.push(`Also resolves ${resolved.length} existing finding${resolved.length === 1 ? "" : "s"}.`);
262
+ }
263
+ } else {
264
+ lines.push(TITLE);
265
+ lines.push("");
266
+ lines.push(`${countPhrase(resolved)} resolved by this PR`);
267
+ lines.push("");
268
+ for (const r of resolved) {
269
+ lines.push(`- \`${r.package}@${r.version}\` · ${advisoryLabel(r)}`);
270
+ }
271
+ }
272
+
273
+ lines.push("");
274
+ lines.push("<sub>Only findings this PR changed are listed. Nothing is posted when the set is unchanged.</sub>");
275
+ lines.push("");
276
+ lines.push(
277
+ `<sub>Scanned by <a href="${PROJECT_URL}">CVE Lite CLI</a>, a free and open source OWASP project.</sub>`,
278
+ );
279
+ lines.push("");
280
+ lines.push(...SHARE);
281
+ return lines.join("\n");
282
+ }
283
+
284
+ export { MARKER };
285
+
286
+ // CLI entrypoint. Kept side-effect free on import so the tests can call the
287
+ // functions directly.
288
+ if (process.argv[1] && import.meta.url.endsWith(process.argv[1].split("/").pop())) {
289
+ const [basePath, headPath] = process.argv.slice(2);
290
+ if (!basePath || !headPath) {
291
+ console.error("usage: pr-scan-delta.mjs <base.json> <head.json>");
292
+ process.exit(2);
293
+ }
294
+ const { readFileSync } = await import("node:fs");
295
+ // Fail loudly. Treating an unreadable scan as "no findings" would print
296
+ // nothing, which is indistinguishable from "this PR changed nothing" and
297
+ // would quietly stop the check from ever reporting.
298
+ const read = (p) => {
299
+ let raw;
300
+ try {
301
+ raw = readFileSync(p, "utf8");
302
+ } catch (err) {
303
+ console.error(`pr-scan-delta: cannot read ${p}: ${err.message}`);
304
+ process.exit(1);
305
+ }
306
+ try {
307
+ return JSON.parse(raw);
308
+ } catch (err) {
309
+ console.error(`pr-scan-delta: ${p} is not valid JSON: ${err.message}`);
310
+ process.exit(1);
311
+ }
312
+ };
313
+ const body = renderComment(buildDelta(read(basePath), read(headPath)));
314
+ if (body) console.log(body);
315
+ }