cve-lite-cli 1.36.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.
@@ -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
  }
@@ -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
@@ -498,7 +498,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
498
498
  if (!offline) {
499
499
  const npmVersionCacheUpdated = await validateDirectFixTargets(findings, (finding) => {
500
500
  updateAnalysisProgress("validating fix target for", `${finding.pkg.name}@${finding.pkg.version}`);
501
- }, { cache, noCache: options.noCache, debugLog: log });
501
+ }, { cache, noCache: options.noCache, debugLog: log, advisorySource });
502
502
  if (npmVersionCacheUpdated) {
503
503
  saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
504
504
  }
@@ -640,6 +640,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
640
640
  cache,
641
641
  noCache: options.noCache,
642
642
  debugLog: log,
643
+ advisorySource,
643
644
  });
644
645
  if (npmVersionCacheUpdated) {
645
646
  saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
@@ -731,7 +732,9 @@ async function validateOneDirectFixTarget(finding, options) {
731
732
  verified: Boolean(finding.validatedFirstFixedVersion),
732
733
  });
733
734
  };
734
- 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 });
735
738
  const fixedVersionHint = finding.firstFixedVersion;
736
739
  const setPublishedDate = (resolution) => {
737
740
  const date = resolution.publishedAt;
@@ -856,49 +859,70 @@ function versionWithinAffectedWindow(version, introduced, fixed) {
856
859
  }
857
860
  return compareVersions(version, fixed) < 0;
858
861
  }
859
- export function findFirstFixedVersion(vulns, packageName, ecosystem, installedVersion) {
860
- const fixedVersions = [];
861
- // Fixes whose affected window actually contains the installed version. An
862
- // advisory that patches two release branches declares a fix per branch, and
863
- // the global minimum is the other branch's fix - a downgrade across a major
864
- // boundary rather than a remediation.
865
- const fixesOnInstalledBranch = [];
866
- for (const vuln of vulns) {
867
- for (const affected of vuln.affected ?? []) {
868
- // An advisory may list several packages with different fix versions.
869
- // Without this filter the global minimum across all of them was
870
- // returned, so a package inherited another package's (lower) fix and
871
- // the scan reported a version that does not fix it.
872
- if (!affectedEntryMatchesPackage(affected, packageName, ecosystem))
873
- continue;
874
- for (const range of affected.ranges ?? []) {
875
- // Events are ordered, and a single range can reintroduce a
876
- // vulnerability, so `introduced` is tracked as the walk proceeds and
877
- // reset once its matching `fixed` closes the window.
878
- let introduced = null;
879
- for (const event of range.events ?? []) {
880
- if (event.introduced) {
881
- introduced = event.introduced;
882
- continue;
883
- }
884
- const fixed = event.fixed;
885
- if (!fixed || !looksLikeVersion(fixed) || isPreReleaseVersion(fixed))
886
- continue;
887
- fixedVersions.push(fixed);
888
- if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed)) {
889
- fixesOnInstalledBranch.push(fixed);
890
- }
891
- 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;
892
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;
893
897
  }
894
898
  }
895
899
  }
896
- // Falling back to every known fix keeps a finding's remediation visible when
897
- // the installed version sits outside each declared window.
898
- const candidates = fixesOnInstalledBranch.length > 0 ? fixesOnInstalledBranch : fixedVersions;
899
- 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)
900
924
  return null;
901
- return candidates.sort(compareVersions)[0];
925
+ return everyKnownFix.sort(compareVersions)[0];
902
926
  }
903
927
  function buildCompletenessDiagnostics(params) {
904
928
  const diagnostics = [];
@@ -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.36.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": {