cve-lite-cli 1.34.0 → 1.35.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 (37) hide show
  1. package/dist/cli/advisories-init.js +13 -0
  2. package/dist/cli/advisories-sync.js +30 -0
  3. package/dist/cli/config-command.js +15 -0
  4. package/dist/cli/config.js +29 -0
  5. package/dist/cli/help.js +4 -4
  6. package/dist/cli/overrides.js +10 -1
  7. package/dist/constants.js +52 -0
  8. package/dist/index.js +25 -719
  9. package/dist/output/cyclonedx.js +12 -0
  10. package/dist/output/html-reporter.js +73 -38
  11. package/dist/output/multi-folder-html-reporter.js +16 -10
  12. package/dist/output/multi-folder-printer.js +1 -1
  13. package/dist/output/override-findings-sarif.js +1 -0
  14. package/dist/output/printers.js +427 -270
  15. package/dist/output/sarif.js +17 -1
  16. package/dist/output/sbom-dependency-edges.js +29 -19
  17. package/dist/overrides/admitted-scan.js +158 -0
  18. package/dist/overrides/api.js +16 -0
  19. package/dist/overrides/context-builder.js +4 -0
  20. package/dist/overrides/context.js +8 -1
  21. package/dist/overrides/detectors/index.js +2 -0
  22. package/dist/overrides/detectors/oa010-vulnerable-floor.js +123 -0
  23. package/dist/overrides/parsing/registry.js +53 -0
  24. package/dist/parsers/bun-lock-graph.js +182 -0
  25. package/dist/parsers/bun-lock.js +93 -132
  26. package/dist/parsers/index.js +75 -149
  27. package/dist/parsers/multi-package.js +5 -6
  28. package/dist/parsers/pnpm-lock-graph.js +94 -0
  29. package/dist/parsers/pnpm-lock.js +5 -5
  30. package/dist/parsers/yarn-lock-graph.js +148 -0
  31. package/dist/parsers/yarn-lock.js +3 -3
  32. package/dist/remediation/fix-commands.js +48 -7
  33. package/dist/scan/completeness.js +1 -1
  34. package/dist/scan/single-scan.js +643 -0
  35. package/dist/utils/file.js +11 -14
  36. package/dist/utils/version.js +10 -0
  37. package/package.json +1 -1
@@ -117,6 +117,22 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
117
117
  properties: { tags: ["security", "dependency"] },
118
118
  });
119
119
  }
120
+ const resultProperties = {};
121
+ if (cooldown)
122
+ resultProperties.cooldownWarning = cooldown;
123
+ if (finding.firstFixedVersion)
124
+ resultProperties.advisoryFixVersion = finding.firstFixedVersion;
125
+ const recommended = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
126
+ if (recommended)
127
+ resultProperties.recommendedFixVersion = recommended;
128
+ if (finding.fixVersionPublishedAt)
129
+ resultProperties.fixVersionPublishedAt = finding.fixVersionPublishedAt;
130
+ if (finding.validatedTargetScannedVersions != null) {
131
+ resultProperties.versionsScanned = finding.validatedTargetScannedVersions;
132
+ }
133
+ if (finding.validatedTargetKnownVulnerableVersions != null) {
134
+ resultProperties.versionsStillVulnerable = finding.validatedTargetKnownVulnerableVersions;
135
+ }
120
136
  results.push({
121
137
  ruleId,
122
138
  ruleIndex: ruleIndexMap.get(ruleId),
@@ -130,7 +146,7 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
130
146
  partialFingerprints: {
131
147
  primaryLocationLineHash: sarifFingerprintHash(`${ruleId}:${finding.pkg.name}@${finding.pkg.version}`),
132
148
  },
133
- ...(cooldown ? { properties: { cooldownWarning: cooldown } } : {}),
149
+ ...(Object.keys(resultProperties).length > 0 ? { properties: resultProperties } : {}),
134
150
  });
135
151
  }
136
152
  }
@@ -1,4 +1,7 @@
1
+ import { loadBunLockGraph } from "../parsers/bun-lock-graph.js";
1
2
  import { loadNpmLockGraph } from "../parsers/npm-lock-graph.js";
3
+ import { loadPnpmLockGraph } from "../parsers/pnpm-lock-graph.js";
4
+ import { loadYarnLockGraph } from "../parsers/yarn-lock-graph.js";
2
5
  function packageKey(name, version) {
3
6
  return `${name}@${version}`;
4
7
  }
@@ -11,30 +14,37 @@ function addEdge(edges, seen, child, parent) {
11
14
  edges.push({ child, parent });
12
15
  }
13
16
  /**
14
- * Resolves dependency edges from the npm lock graph.
15
- *
16
- * The graph keeps a complete child-to-parents map (`parentsFor`) that is not
17
- * subject to the five-path cap applied to `PackageRef.paths`. Reconstructing
18
- * edges from those truncated paths loses roughly a quarter of the routes on a
19
- * large tree, and a package whose surviving routes all traverse filtered-out
20
- * packages ends up with no parent at all.
21
- *
22
- * Returns an empty list for anything other than an npm lockfile, so pnpm, Yarn
23
- * and Bun fall back to the caller's path-derived behaviour rather than silently
24
- * losing every edge.
17
+ * Returns the lock graph for lockfiles that have one, or null for everything
18
+ * else so the caller falls back to path-derived edges rather than emitting an
19
+ * SBOM with no dependency relationships at all.
25
20
  */
26
- export function resolveDependencyEdges(scanInput, allPackages) {
27
- if (scanInput.source !== "package-lock" || !scanInput.filePath)
28
- return [];
29
- let graph;
21
+ function loadEdgeGraph(scanInput) {
22
+ if (!scanInput.filePath)
23
+ return null;
30
24
  try {
31
- graph = loadNpmLockGraph(scanInput.filePath, { includePaths: false });
25
+ if (scanInput.source === "package-lock") {
26
+ return loadNpmLockGraph(scanInput.filePath, { includePaths: false });
27
+ }
28
+ if (scanInput.source === "pnpm-lock") {
29
+ return loadPnpmLockGraph(scanInput.filePath);
30
+ }
31
+ if (scanInput.source === "bun-lock") {
32
+ return loadBunLockGraph(scanInput.filePath);
33
+ }
34
+ if (scanInput.source === "yarn-lock") {
35
+ return loadYarnLockGraph(scanInput.filePath);
36
+ }
32
37
  }
33
38
  catch {
34
- // A lockfile we cannot read is not worth failing an SBOM over. The caller
35
- // falls back to path-derived edges.
36
- return [];
39
+ // A lockfile we cannot read is not worth failing an SBOM over.
40
+ return null;
37
41
  }
42
+ return null;
43
+ }
44
+ export function resolveDependencyEdges(scanInput, allPackages) {
45
+ const graph = loadEdgeGraph(scanInput);
46
+ if (!graph)
47
+ return [];
38
48
  // Only packages present in the document can be referenced. `--prod-only` and
39
49
  // similar filters shrink this set without shrinking the graph, and an edge to
40
50
  // a package absent from the document would be a dangling SPDX reference.
@@ -0,0 +1,158 @@
1
+ import { admittedKey } from "./context.js";
2
+ import { fetchVersionsBatch } from "./parsing/registry.js";
3
+ import { looksLikeVersion, satisfiesRange, compareVersions } from "../utils/version.js";
4
+ import { inferSeverity } from "../osv/severity.js";
5
+ import { chunk } from "../utils/array.js";
6
+ import { DEFAULT_BATCH_SIZE } from "../constants.js";
7
+ /**
8
+ * Cap on how many (name, version) pairs we will ask the advisory source about in
9
+ * one audit. A project with many wide floors could otherwise enumerate thousands
10
+ * of versions; OA010 is a hygiene check, not a reason to hammer OSV.
11
+ */
12
+ const MAX_ADMITTED_QUERIES = 2000;
13
+ /** Override entries whose value is a range rather than an exact pin. */
14
+ function rangeEntries(ctx) {
15
+ const out = [];
16
+ const seen = new Set();
17
+ for (const entry of ctx.overrideEntries) {
18
+ if (typeof entry.value !== "string")
19
+ continue;
20
+ const range = entry.value.trim();
21
+ if (looksLikeVersion(range))
22
+ continue;
23
+ const key = `${entry.packageName}@${range}`;
24
+ if (seen.has(key))
25
+ continue;
26
+ seen.add(key);
27
+ out.push({ name: entry.packageName, range });
28
+ }
29
+ return out;
30
+ }
31
+ /**
32
+ * Populate ctx.admittedVersions and ctx.admittedVulnerable so OA010 can run.
33
+ *
34
+ * The question OA010 answers is "does this range permit a vulnerable version",
35
+ * which is deliberately asked by *enumerating* the admitted versions and letting
36
+ * the advisory source judge each one, rather than by parsing advisory range
37
+ * strings ourselves. That choice matters: advisory ranges arrive in shapes that
38
+ * are not valid semver (GitHub emits `">= 5.9.3, < 5.10.1"` with a comma), and a
39
+ * single advisory can cover several ecosystems with different ranges under the
40
+ * same id. Both of those mis-parse silently and in the unsafe direction, telling
41
+ * you a floor is clean when it is not. Querying per version sidesteps both,
42
+ * because the advisory source is already ecosystem-scoped and version-scoped.
43
+ *
44
+ * Never throws. A registry or advisory failure records a skippedDetectors entry
45
+ * and leaves the maps empty, so OA010 sits out rather than reporting a clean
46
+ * bill of health it has not earned.
47
+ */
48
+ export async function populateAdmittedVersions(ctx, opts) {
49
+ const entries = rangeEntries(ctx);
50
+ if (entries.length === 0)
51
+ return;
52
+ const versionsByName = await fetchVersionsBatch(entries.map((e) => e.name), opts.registry ?? {});
53
+ const refs = [];
54
+ // A (name, version) pair can be admitted by more than one override range, so
55
+ // track which keys each pair belongs to and query the pair only once.
56
+ const keysByPair = new Map();
57
+ for (const { name, range } of entries) {
58
+ const published = versionsByName.get(name);
59
+ if (!published)
60
+ continue;
61
+ const admitted = published.filter((v) => satisfiesRange(v, range));
62
+ if (admitted.length === 0)
63
+ continue;
64
+ const key = admittedKey(name, range);
65
+ ctx.admittedVersions.set(key, admitted);
66
+ for (const version of admitted) {
67
+ const pair = `${name}@${version}`;
68
+ const existing = keysByPair.get(pair);
69
+ if (existing) {
70
+ existing.push(key);
71
+ continue;
72
+ }
73
+ keysByPair.set(pair, [key]);
74
+ refs.push({ name, version, ecosystem: "npm" });
75
+ }
76
+ }
77
+ if (refs.length === 0)
78
+ return;
79
+ if (refs.length > MAX_ADMITTED_QUERIES) {
80
+ ctx.skippedDetectors.push({
81
+ ruleId: "OA010",
82
+ reason: `override ranges admit ${refs.length} versions, above the ` +
83
+ `${MAX_ADMITTED_QUERIES} query cap`,
84
+ });
85
+ return;
86
+ }
87
+ // OSV rejects oversized batches with a 400, and queryBatch does not chunk -
88
+ // the caller owns that, the same way scanPackages does. Sending all admitted
89
+ // versions in one request fails the whole rule closed.
90
+ const results = [];
91
+ const batches = chunk(refs, DEFAULT_BATCH_SIZE);
92
+ for (let i = 0; i < batches.length; i++) {
93
+ try {
94
+ results.push(...await opts.advisorySource.queryBatch(batches[i], { batchId: `oa010-${i}` }));
95
+ }
96
+ catch (err) {
97
+ ctx.skippedDetectors.push({
98
+ ruleId: "OA010",
99
+ reason: `advisory batch ${i + 1}/${batches.length} failed: ${err instanceof Error ? err.message : String(err)}`,
100
+ });
101
+ ctx.admittedVulnerable.clear();
102
+ return;
103
+ }
104
+ }
105
+ // The batch endpoint answers with { id, modified } only - no severity and no
106
+ // affected ranges - so severity would be "unknown" on every finding and
107
+ // firstPatched would never resolve. Pull the detail record per unique id, the
108
+ // same second phase scanPackages runs.
109
+ const ids = [...new Set(results.flatMap((r) => (r.vulnerabilities ?? []).map((v) => v.id)))];
110
+ const details = new Map();
111
+ for (const id of ids) {
112
+ try {
113
+ details.set(id, await opts.advisorySource.getVuln(id));
114
+ }
115
+ catch {
116
+ // Leave it out: severity falls back to unknown for this one advisory
117
+ // rather than dropping the finding, which would hide a real hit.
118
+ }
119
+ }
120
+ for (const result of results) {
121
+ const vulns = (result.vulnerabilities ?? []);
122
+ if (vulns.length === 0)
123
+ continue;
124
+ const hits = vulns.map((vuln) => {
125
+ const detail = details.get(vuln.id);
126
+ return {
127
+ version: result.version,
128
+ advisoryId: vuln.id,
129
+ severity: detail ? inferSeverity(detail) : "unknown",
130
+ firstPatched: detail ? firstPatchedFor(detail, result.package) : undefined,
131
+ };
132
+ });
133
+ for (const key of keysByPair.get(`${result.package}@${result.version}`) ?? []) {
134
+ const existing = ctx.admittedVulnerable.get(key) ?? [];
135
+ ctx.admittedVulnerable.set(key, [...existing, ...hits].sort((a, b) => compareVersions(a.version, b.version)));
136
+ }
137
+ }
138
+ }
139
+ /**
140
+ * Pull the `fixed` event for `pkgName` out of an OSV advisory, when it states one.
141
+ * Only npm entries are considered: the same advisory id routinely carries
142
+ * different ranges for pip or Maven, and borrowing those produces a wrong floor.
143
+ */
144
+ function firstPatchedFor(vuln, pkgName) {
145
+ for (const affected of vuln.affected ?? []) {
146
+ if (affected.package?.ecosystem !== "npm")
147
+ continue;
148
+ if (affected.package?.name !== pkgName)
149
+ continue;
150
+ for (const range of affected.ranges ?? []) {
151
+ for (const event of range.events ?? []) {
152
+ if (event.fixed)
153
+ return event.fixed;
154
+ }
155
+ }
156
+ }
157
+ return undefined;
158
+ }
@@ -1,3 +1,4 @@
1
+ import { populateAdmittedVersions } from "./admitted-scan.js";
1
2
  import { ALL_DETECTORS, VERIFY_DETECTORS } from "./detectors/index.js";
2
3
  import { applyComposite } from "./composite.js";
3
4
  import { fetchDistTagsBatch } from "./parsing/registry.js";
@@ -26,6 +27,21 @@ export async function audit(ctx, opts) {
26
27
  }
27
28
  }
28
29
  }
30
+ // OA010 network fetch - needs both the opt-in and an injected advisory source.
31
+ if (opts.checkNetwork && opts.advisorySource) {
32
+ try {
33
+ await populateAdmittedVersions(ctx, {
34
+ registry: opts.registry,
35
+ advisorySource: opts.advisorySource,
36
+ });
37
+ }
38
+ catch (err) {
39
+ ctx.skippedDetectors.push({
40
+ ruleId: "OA010",
41
+ reason: `admitted-version scan failed: ${err instanceof Error ? err.message : String(err)}`,
42
+ });
43
+ }
44
+ }
29
45
  const raw = [];
30
46
  for (const { detect } of ALL_DETECTORS) {
31
47
  raw.push(...detect(ctx));
@@ -60,6 +60,8 @@ export function buildOverrideContext(projectPath, opts) {
60
60
  seedRootDeclarations(parsed, tree.parentDeclarations);
61
61
  // OA007 registry: only when --check-network. Empty otherwise.
62
62
  const registryDistTags = new Map();
63
+ const admittedVersions = new Map();
64
+ const admittedVulnerable = new Map();
63
65
  const importedPackageNames = scanAllImports(projectPath);
64
66
  return {
65
67
  projectPath,
@@ -72,6 +74,8 @@ export function buildOverrideContext(projectPath, opts) {
72
74
  installedCopies: tree.installedCopies,
73
75
  parentDeclarations: tree.parentDeclarations,
74
76
  registryDistTags,
77
+ admittedVersions,
78
+ admittedVulnerable,
75
79
  skippedDetectors: skipped,
76
80
  importedPackageNames,
77
81
  auditLog: opts.auditLog,
@@ -1,3 +1,10 @@
1
1
  // Single context object built once per scan/audit and consumed by every
2
2
  // detector. Filled by buildOverrideContext() from cve-lite's parser outputs.
3
- export {};
3
+ /**
4
+ * Key for the admitted-version maps. Name alone is not unique: pnpm lets the
5
+ * same package carry several overrides under different selectors, each with its
6
+ * own range.
7
+ */
8
+ export function admittedKey(name, range) {
9
+ return `${name}@${range.trim()}`;
10
+ }
@@ -7,6 +7,7 @@ import { detect as detectOA006 } from "./oa006-coupled-platform-binary.js";
7
7
  import { detect as detectOA007 } from "./oa007-frozen-latest.js";
8
8
  import { detect as detectOA008 } from "./oa008-materialized.js";
9
9
  import { detect as detectOA009 } from "./oa009-stale-floor.js";
10
+ import { detect as detectOA010 } from "./oa010-vulnerable-floor.js";
10
11
  import { detect as detectPD001 } from "./pd001-override-only-phantom.js";
11
12
  import { detect as detectPD002 } from "./pd002-transitive-only-phantom.js";
12
13
  export const ALL_DETECTORS = [
@@ -19,6 +20,7 @@ export const ALL_DETECTORS = [
19
20
  { ruleId: "OA007", detect: detectOA007 },
20
21
  { ruleId: "OA008", detect: detectOA008 },
21
22
  { ruleId: "OA009", detect: detectOA009 },
23
+ { ruleId: "OA010", detect: detectOA010 },
22
24
  { ruleId: "PD001", detect: detectPD001 },
23
25
  { ruleId: "PD002", detect: detectPD002 },
24
26
  ];
@@ -0,0 +1,123 @@
1
+ import { admittedKey } from "../context.js";
2
+ import { jsonPointer } from "../parsing/json-pointer.js";
3
+ import { looksLikeVersion, compareVersions, majorVersion } from "../../utils/version.js";
4
+ import { OVERRIDES_COMMAND } from "../../constants.js";
5
+ const RULE_ID = "OA010";
6
+ /**
7
+ * Severity ordering for picking the worst advisory in an admitted set. "unknown"
8
+ * and "none" sort below everything so a graded advisory always wins.
9
+ */
10
+ const SEVERITY_RANK = {
11
+ none: 0,
12
+ unknown: 0,
13
+ low: 1,
14
+ medium: 2,
15
+ high: 3,
16
+ critical: 4,
17
+ };
18
+ function worstSeverity(hits) {
19
+ let worst = "unknown";
20
+ for (const hit of hits) {
21
+ if (SEVERITY_RANK[hit.severity] > SEVERITY_RANK[worst])
22
+ worst = hit.severity;
23
+ }
24
+ return worst;
25
+ }
26
+ /**
27
+ * Rewrite the floor of an override range, preserving whatever ceiling it already
28
+ * carries. `>=5.7.0 <6` with a 5.10.1 floor becomes `>=5.10.1 <6`; a bare `^5.7.0`
29
+ * becomes `>=5.10.1 <6.0.0` because a caret cannot express a raised floor.
30
+ * Returns null when the shape is not one we can safely rewrite.
31
+ */
32
+ function raiseFloor(pin, newFloor) {
33
+ const tokens = pin.trim().split(/\s+/).filter(Boolean);
34
+ if (tokens.length > 0 && tokens.every((t) => t.startsWith(">=") || t.startsWith("<"))) {
35
+ return tokens.map((t) => (t.startsWith(">=") ? `>=${newFloor}` : t)).join(" ");
36
+ }
37
+ if (tokens.length === 1 && tokens[0].startsWith("^")) {
38
+ const major = majorVersion(newFloor);
39
+ return major === null ? null : `>=${newFloor} <${major + 1}.0.0`;
40
+ }
41
+ return null;
42
+ }
43
+ /**
44
+ * OA010: the range an override floor admits contains a known-vulnerable version.
45
+ *
46
+ * OA009 asks whether a floor is redundant. This asks whether it is safe. A floor
47
+ * is a range, so `>=X` admits every published version above X, and a later
48
+ * advisory can land inside that window without touching the installed version.
49
+ * The scan answers "what fixes the version you have"; nothing was asking "is
50
+ * everything this range permits clean".
51
+ *
52
+ * Pure consumer of ctx.admittedVersions / ctx.admittedVulnerable, both populated
53
+ * by audit() only under --check-network. Makes no network calls itself and
54
+ * no-ops when those maps are empty, the same contract as OA007.
55
+ */
56
+ export function detect(ctx) {
57
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
58
+ return [];
59
+ if (ctx.admittedVulnerable.size === 0)
60
+ return [];
61
+ const findings = [];
62
+ for (const entry of ctx.overrideEntries) {
63
+ if (typeof entry.value !== "string")
64
+ continue;
65
+ const pin = entry.value.trim();
66
+ // An exact pin admits exactly one version, which is OA008's question, not ours.
67
+ if (looksLikeVersion(pin))
68
+ continue;
69
+ // Keyed by name AND range: the same package can be floored more than once
70
+ // under different selectors, and each range admits a different set.
71
+ const key = admittedKey(entry.packageName, pin);
72
+ const hits = ctx.admittedVulnerable.get(key) ?? [];
73
+ if (hits.length === 0)
74
+ continue;
75
+ const admitted = ctx.admittedVersions.get(key) ?? [];
76
+ const vulnerableVersions = new Set(hits.map((h) => h.version));
77
+ const highestVulnerable = hits
78
+ .map((h) => h.version)
79
+ .reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b));
80
+ // The replacement floor must clear every vulnerable version the range admits,
81
+ // not merely the lowest one, so search above the highest of them.
82
+ const newFloor = admitted
83
+ .filter((v) => !vulnerableVersions.has(v) && compareVersions(v, highestVulnerable) > 0)
84
+ .sort(compareVersions)[0];
85
+ const advisoryIds = [...new Set(hits.map((h) => h.advisoryId))];
86
+ const severity = worstSeverity(hits);
87
+ const versionList = hits.map((h) => h.version).sort(compareVersions).join(", ");
88
+ const base = {
89
+ ruleId: RULE_ID,
90
+ severity,
91
+ package: { name: entry.packageName },
92
+ location: { file: "package.json", jsonPath: jsonPointer(entry.path) },
93
+ references: [
94
+ "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA010.md",
95
+ ],
96
+ };
97
+ const rewritten = newFloor ? raiseFloor(pin, newFloor) : null;
98
+ if (!newFloor || !rewritten) {
99
+ findings.push({
100
+ ...base,
101
+ message: "Override floor admits a known-vulnerable version",
102
+ details: `${entry.packageName} is floored to ${pin}, which admits ${versionList} ` +
103
+ `(${advisoryIds.join(", ")}). There is no clean version above them inside ` +
104
+ `the current range, so the floor cannot be raised without widening the ceiling.`,
105
+ });
106
+ continue;
107
+ }
108
+ findings.push({
109
+ ...base,
110
+ message: "Override floor admits a known-vulnerable version",
111
+ details: `${entry.packageName} is floored to ${pin}, which admits ${versionList} ` +
112
+ `(${advisoryIds.join(", ")}). The installed version may be clean today, but ` +
113
+ `any resolution inside this range is permitted to pick a vulnerable one. ` +
114
+ `Raise the floor to ${newFloor}.`,
115
+ fix: {
116
+ type: "rfc6902",
117
+ patch: [{ op: "replace", path: jsonPointer(entry.path), value: rewritten }],
118
+ runnableCommand: `${OVERRIDES_COMMAND} --fix --rule ${RULE_ID}`,
119
+ },
120
+ });
121
+ }
122
+ return findings;
123
+ }
@@ -1,3 +1,4 @@
1
+ import { compareVersions, isPreReleaseVersion } from '../../utils/version.js';
1
2
  /**
2
3
  * Fetch the `dist-tags` map for `pkgName` from the npm registry.
3
4
  *
@@ -50,6 +51,58 @@ export async function fetchDistTagsBatch(pkgNames, opts = {}) {
50
51
  }));
51
52
  return out;
52
53
  }
54
+ /**
55
+ * Fetch every published version of `pkgName`, ascending, excluding prereleases.
56
+ *
57
+ * Uses the same abbreviated packument as `fetchDistTags`, which already carries
58
+ * the full `versions` map, so this costs no extra round trip shape-wise.
59
+ * Returns null on any failure, matching `fetchDistTags`.
60
+ */
61
+ export async function fetchVersions(pkgName, opts = {}) {
62
+ const baseUrl = opts.baseUrl ?? 'https://registry.npmjs.org';
63
+ const timeoutMs = opts.timeoutMs ?? 5000;
64
+ const fetchImpl = opts.fetchImpl ?? fetch;
65
+ const url = `${baseUrl}/${encodeRegistryPath(pkgName)}`;
66
+ const controller = new AbortController();
67
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
68
+ try {
69
+ const res = await fetchImpl(url, {
70
+ signal: controller.signal,
71
+ headers: {
72
+ Accept: 'application/vnd.npm.install-v1+json',
73
+ 'User-Agent': 'override-audit-cli',
74
+ },
75
+ });
76
+ if (!res.ok)
77
+ return null;
78
+ const body = await res.json();
79
+ if (!body.versions)
80
+ return null;
81
+ return Object.keys(body.versions)
82
+ .filter((v) => !isPreReleaseVersion(v))
83
+ .sort(compareVersions);
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ finally {
89
+ clearTimeout(timer);
90
+ }
91
+ }
92
+ /**
93
+ * Fetch version lists for many packages concurrently. Per-package failures
94
+ * collapse to an absent entry rather than failing the batch.
95
+ */
96
+ export async function fetchVersionsBatch(pkgNames, opts = {}) {
97
+ const out = new Map();
98
+ const unique = Array.from(new Set(pkgNames));
99
+ await Promise.all(unique.map(async (name) => {
100
+ const versions = await fetchVersions(name, opts);
101
+ if (versions)
102
+ out.set(name, versions);
103
+ }));
104
+ return out;
105
+ }
53
106
  /**
54
107
  * Encode a package name for the registry URL.
55
108
  * Scoped names like `@scope/pkg` need the slash kept literal — the registry