cve-lite-cli 1.33.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 (53) hide show
  1. package/README.md +6 -3
  2. package/dist/advisory/local-db.js +31 -2
  3. package/dist/advisory/osv-advisory-source.js +3 -0
  4. package/dist/cli/advisories-init.js +13 -0
  5. package/dist/cli/advisories-sync.js +30 -0
  6. package/dist/cli/args.js +41 -2
  7. package/dist/cli/config-command.js +15 -0
  8. package/dist/cli/config.js +29 -0
  9. package/dist/cli/help.js +7 -5
  10. package/dist/cli/overrides.js +10 -1
  11. package/dist/cli/validate.js +6 -2
  12. package/dist/constants.js +52 -0
  13. package/dist/index.js +25 -719
  14. package/dist/output/cyclonedx.js +28 -24
  15. package/dist/output/formatters.js +13 -0
  16. package/dist/output/html-reporter.js +81 -40
  17. package/dist/output/multi-folder-html-reporter.js +16 -10
  18. package/dist/output/multi-folder-printer.js +1 -1
  19. package/dist/output/override-findings-sarif.js +1 -0
  20. package/dist/output/printers.js +436 -271
  21. package/dist/output/sarif.js +17 -1
  22. package/dist/output/sbom-dependency-edges.js +86 -0
  23. package/dist/output/sbom-file.js +27 -0
  24. package/dist/output/spdx.js +293 -0
  25. package/dist/output/write-outputs.js +18 -3
  26. package/dist/overrides/admitted-scan.js +158 -0
  27. package/dist/overrides/api.js +16 -0
  28. package/dist/overrides/context-builder.js +4 -0
  29. package/dist/overrides/context.js +8 -1
  30. package/dist/overrides/detectors/index.js +2 -0
  31. package/dist/overrides/detectors/oa010-vulnerable-floor.js +123 -0
  32. package/dist/overrides/parsing/registry.js +53 -0
  33. package/dist/parsers/bun-lock-graph.js +182 -0
  34. package/dist/parsers/bun-lock.js +93 -132
  35. package/dist/parsers/index.js +75 -149
  36. package/dist/parsers/multi-package.js +5 -6
  37. package/dist/parsers/package-lock.js +11 -1
  38. package/dist/parsers/pnpm-lock-graph.js +94 -0
  39. package/dist/parsers/pnpm-lock.js +5 -5
  40. package/dist/parsers/utils.js +3 -0
  41. package/dist/parsers/yarn-lock-graph.js +148 -0
  42. package/dist/parsers/yarn-lock.js +3 -3
  43. package/dist/remediation/fix-commands.js +48 -7
  44. package/dist/remediation/npm-registry.js +8 -2
  45. package/dist/scan/completeness.js +1 -0
  46. package/dist/scan/single-scan.js +643 -0
  47. package/dist/scanner.js +62 -7
  48. package/dist/types.js +1 -1
  49. package/dist/utils/file.js +11 -14
  50. package/dist/utils/purl.js +10 -0
  51. package/dist/utils/sbom-format.js +12 -0
  52. package/dist/utils/version.js +84 -10
  53. package/package.json +2 -2
@@ -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
  }
@@ -0,0 +1,86 @@
1
+ import { loadBunLockGraph } from "../parsers/bun-lock-graph.js";
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";
5
+ function packageKey(name, version) {
6
+ return `${name}@${version}`;
7
+ }
8
+ /** Several graph nodes collapse to one name@version, so edges are deduplicated. */
9
+ function addEdge(edges, seen, child, parent) {
10
+ const key = `${child} ${parent ?? ""}`;
11
+ if (seen.has(key))
12
+ return;
13
+ seen.add(key);
14
+ edges.push({ child, parent });
15
+ }
16
+ /**
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.
20
+ */
21
+ function loadEdgeGraph(scanInput) {
22
+ if (!scanInput.filePath)
23
+ return null;
24
+ try {
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
+ }
37
+ }
38
+ catch {
39
+ // A lockfile we cannot read is not worth failing an SBOM over.
40
+ return null;
41
+ }
42
+ return null;
43
+ }
44
+ export function resolveDependencyEdges(scanInput, allPackages) {
45
+ const graph = loadEdgeGraph(scanInput);
46
+ if (!graph)
47
+ return [];
48
+ // Only packages present in the document can be referenced. `--prod-only` and
49
+ // similar filters shrink this set without shrinking the graph, and an edge to
50
+ // a package absent from the document would be a dangling SPDX reference.
51
+ const included = new Set(allPackages.map(p => packageKey(p.name, p.version)));
52
+ const edges = [];
53
+ const seen = new Set();
54
+ for (const pkg of allPackages) {
55
+ const childKey = packageKey(pkg.name, pkg.version);
56
+ let anchored = false;
57
+ for (const nodeId of graph.nodeIdsFor(pkg.name, pkg.version)) {
58
+ for (const parentNodeId of graph.parentsFor(nodeId)) {
59
+ const parentNode = graph.getNode(parentNodeId);
60
+ // Workspace members are symlinked rather than installed, so the graph
61
+ // records them without a version and they never appear in the scanned
62
+ // package set. They cannot be referenced as SPDX packages.
63
+ if (!parentNode?.version)
64
+ continue;
65
+ const parentKey = packageKey(parentNode.name, parentNode.version);
66
+ if (parentKey === childKey)
67
+ continue;
68
+ // Referencing a package absent from the document would be a dangling
69
+ // SPDX reference. `--prod-only` and similar filters shrink the package
70
+ // set without shrinking the graph.
71
+ if (!included.has(parentKey))
72
+ continue;
73
+ addEdge(edges, seen, childKey, parentKey);
74
+ anchored = true;
75
+ }
76
+ }
77
+ // Either nothing depends on it, or every parent was a workspace member or
78
+ // filtered out of the document. Anchoring to the root keeps the package in
79
+ // the graph: it is genuinely part of the tree, and the root is the only
80
+ // anchor the document can offer. Orphaning it would silently drop a
81
+ // dependency relationship, which is an NTIA minimum element.
82
+ if (!anchored)
83
+ addEdge(edges, seen, childKey, null);
84
+ }
85
+ return edges;
86
+ }
@@ -0,0 +1,27 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ /**
4
+ * Writes an SBOM document to a timestamped file in the working directory.
5
+ *
6
+ * A partial file left behind by a failed write would look like a valid SBOM to
7
+ * whatever consumes it next, so the partial output is removed before the error
8
+ * propagates.
9
+ */
10
+ export function writeSbomFile(filename, document, label) {
11
+ const outputPath = path.join(process.cwd(), filename);
12
+ try {
13
+ fs.writeFileSync(outputPath, JSON.stringify(document, null, 2));
14
+ }
15
+ catch (err) {
16
+ try {
17
+ fs.rmSync(outputPath, { force: true });
18
+ }
19
+ catch { /* best-effort cleanup */ }
20
+ throw new Error(`Failed to write ${label} to ${outputPath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
21
+ }
22
+ return filename;
23
+ }
24
+ /** Filesystem-safe UTC stamp shared by every SBOM filename. */
25
+ export function sbomTimestamp() {
26
+ return new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
27
+ }
@@ -0,0 +1,293 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
3
+ import { getRecommendedAction } from "./formatters.js";
4
+ import { buildPurl } from "../utils/purl.js";
5
+ import { getCliVersion } from "../utils/version-info.js";
6
+ import { sbomTimestamp, writeSbomFile } from "./sbom-file.js";
7
+ /**
8
+ * SPDX's explicit marker for "we looked and cannot say". Preferred over
9
+ * omitting a field, because omission reads as "not considered".
10
+ */
11
+ const NOASSERTION = "NOASSERTION";
12
+ /**
13
+ * SPDX requires a second-precision UTC timestamp (YYYY-MM-DDThh:mm:ssZ), not
14
+ * the millisecond form `toISOString()` produces.
15
+ */
16
+ function spdxTimestamp() {
17
+ return new Date().toISOString().slice(0, 19) + "Z";
18
+ }
19
+ /**
20
+ * Mints an SPDXID for a package.
21
+ *
22
+ * The spec restricts identifiers to letters, digits, `.` and `-`, which rules
23
+ * out the `@` and `/` in scoped npm names. Sanitising can make two distinct
24
+ * packages collide (`@scope/pkg` and `scope-pkg` both reduce to `scope-pkg`),
25
+ * so a counter disambiguates rather than silently emitting a duplicate ID that
26
+ * would make external references ambiguous.
27
+ */
28
+ function makeSpdxId(name, version, used) {
29
+ const base = `SPDXRef-${`${name}-${version}`.replace(/[^A-Za-z0-9.-]/g, "-").replace(/^-+/, "")}`;
30
+ const seen = used.get(base);
31
+ if (seen === undefined) {
32
+ used.set(base, 1);
33
+ return base;
34
+ }
35
+ used.set(base, seen + 1);
36
+ return `${base}-${seen + 1}`;
37
+ }
38
+ /**
39
+ * Groups findings by `name@version` so each package can be decorated in one
40
+ * pass without rescanning the finding list per package.
41
+ */
42
+ function groupFindingsByPackage(findings) {
43
+ const byPackage = new Map();
44
+ for (const finding of findings) {
45
+ // A supplemental advisory pass can produce an empty finding alongside a real
46
+ // one for the same package. It has nothing to reference and no remediation,
47
+ // and annotating it contradicts the real fix, so it is dropped here.
48
+ if (finding.vulnerabilities.length === 0)
49
+ continue;
50
+ const key = `${finding.pkg.name}@${finding.pkg.version}`;
51
+ const existing = byPackage.get(key);
52
+ if (existing)
53
+ existing.push(finding);
54
+ else
55
+ byPackage.set(key, [finding]);
56
+ }
57
+ return byPackage;
58
+ }
59
+ /**
60
+ * Summarises a package's findings for an SPDX annotation.
61
+ *
62
+ * Severity and runnable fix commands have no home in SPDX 2.3: the format has
63
+ * no vulnerability model, and `referenceLocator` must be a URI, so a shell
64
+ * command cannot go there. A free-text annotation is the spec-legal place for
65
+ * both, and keeps the output actionable.
66
+ */
67
+ function buildFindingAnnotation(findings, plan, annotator, timestamp) {
68
+ // The advisory IDs are already enumerated as SECURITY externalRefs, so the
69
+ // annotation carries only what SPDX has no field for: severity and the fix.
70
+ const parts = findings.map(finding => {
71
+ const fix = (plan ? findSuggestedCommandForFinding(plan, finding) : null) ?? getRecommendedAction(finding);
72
+ return `severity=${finding.severity}; advisories=${finding.vulnerabilities.length}; fix=${fix}`;
73
+ });
74
+ return {
75
+ annotationDate: timestamp,
76
+ annotationType: "OTHER",
77
+ annotator,
78
+ comment: parts.join(" | "),
79
+ };
80
+ }
81
+ /**
82
+ * Builds the SPDX package entry describing the scanned project itself, plus the
83
+ * DESCRIBES relationship tying the document to it. Returns null when the
84
+ * project has no name to describe.
85
+ */
86
+ function buildRootPackage(projectMeta, usedIds) {
87
+ if (!projectMeta?.name)
88
+ return null;
89
+ const rootId = makeSpdxId(projectMeta.name, projectMeta.version ?? "", usedIds);
90
+ return {
91
+ pkg: {
92
+ SPDXID: rootId,
93
+ name: projectMeta.name,
94
+ downloadLocation: NOASSERTION,
95
+ supplier: NOASSERTION,
96
+ filesAnalyzed: false,
97
+ ...(projectMeta.version ? { versionInfo: projectMeta.version } : {}),
98
+ licenseDeclared: NOASSERTION,
99
+ licenseConcluded: NOASSERTION,
100
+ externalRefs: [],
101
+ },
102
+ relationship: {
103
+ spdxElementId: "SPDXRef-DOCUMENT",
104
+ relatedSpdxElement: rootId,
105
+ relationshipType: "DESCRIBES",
106
+ },
107
+ };
108
+ }
109
+ /** Advisory references for one package, with duplicate IDs collapsed. */
110
+ function buildAdvisoryRefs(pkgFindings) {
111
+ // Two advisory sources can report the same ID for one package; a duplicated
112
+ // externalRef would overstate how many distinct advisories were found.
113
+ const seen = new Set();
114
+ const refs = [];
115
+ for (const finding of pkgFindings) {
116
+ for (const vuln of finding.vulnerabilities) {
117
+ if (seen.has(vuln.id))
118
+ continue;
119
+ seen.add(vuln.id);
120
+ refs.push({
121
+ referenceCategory: "SECURITY",
122
+ referenceType: "advisory",
123
+ referenceLocator: `https://osv.dev/vulnerability/${vuln.id}`,
124
+ });
125
+ }
126
+ }
127
+ return refs;
128
+ }
129
+ function buildPackageEntry(pkg, pkgFindings, usedIds, plan, annotator, timestamp) {
130
+ return {
131
+ SPDXID: makeSpdxId(pkg.name, pkg.version, usedIds),
132
+ name: pkg.name,
133
+ downloadLocation: pkg.resolvedUrl ?? NOASSERTION,
134
+ // NTIA lists supplier as a minimum element. A lockfile does not record who
135
+ // published a package, so we assert nothing rather than guess from the name.
136
+ supplier: NOASSERTION,
137
+ // We read lockfile metadata, never package contents. Omitting this would
138
+ // default it to true and claim otherwise.
139
+ filesAnalyzed: false,
140
+ versionInfo: pkg.version,
141
+ licenseDeclared: pkg.license ?? NOASSERTION,
142
+ // We only ever observe what a package declares. Concluding a license is a
143
+ // human legal judgement, so it stays NOASSERTION.
144
+ licenseConcluded: NOASSERTION,
145
+ externalRefs: [
146
+ {
147
+ referenceCategory: "PACKAGE-MANAGER",
148
+ referenceType: "purl",
149
+ referenceLocator: buildPurl(pkg.name, pkg.version),
150
+ },
151
+ ...buildAdvisoryRefs(pkgFindings),
152
+ ],
153
+ ...(pkgFindings.length > 0
154
+ ? { annotations: [buildFindingAnnotation(pkgFindings, plan, annotator, timestamp)] }
155
+ : {}),
156
+ };
157
+ }
158
+ /**
159
+ * Indexes packages by their dependency path so a parent can be resolved by path
160
+ * prefix rather than by name.
161
+ *
162
+ * Name lookup would be ambiguous whenever one package name is installed at two
163
+ * versions, which is exactly the case a dependency graph most needs to get
164
+ * right. A path identifies a single node in the tree, so it never collides.
165
+ */
166
+ function indexPackagesByPath(entries, rootId) {
167
+ const index = new Map();
168
+ for (const { ref, id } of entries) {
169
+ for (const path of ref.paths ?? []) {
170
+ if (rootId && path.length > 0) {
171
+ // The first path segment is the project itself, whatever it is labelled.
172
+ index.set(JSON.stringify([path[0]]), rootId);
173
+ }
174
+ const key = JSON.stringify(path);
175
+ if (!index.has(key))
176
+ index.set(key, id);
177
+ }
178
+ }
179
+ return index;
180
+ }
181
+ /**
182
+ * Derives DEPENDENCY_OF relationships from the dependency paths.
183
+ *
184
+ * NTIA lists dependency relationships among the minimum elements of an SBOM, so
185
+ * a flat package list is not sufficient for the compliance use case SPDX serves.
186
+ */
187
+ function buildDependencyEdges(entries, index) {
188
+ const edges = [];
189
+ const seen = new Set();
190
+ for (const { ref, id } of entries) {
191
+ for (const path of ref.paths ?? []) {
192
+ if (path.length < 2)
193
+ continue;
194
+ const parentId = index.get(JSON.stringify(path.slice(0, -1)));
195
+ // A self-edge would appear if a package somehow contained itself.
196
+ if (!parentId || parentId === id)
197
+ continue;
198
+ const key = `${id}\u0000${parentId}`;
199
+ if (seen.has(key))
200
+ continue;
201
+ seen.add(key);
202
+ edges.push({
203
+ spdxElementId: id,
204
+ relatedSpdxElement: parentId,
205
+ relationshipType: "DEPENDENCY_OF",
206
+ });
207
+ }
208
+ }
209
+ return edges;
210
+ }
211
+ /**
212
+ * Maps edges already resolved from the lockfile graph onto SPDX ids.
213
+ *
214
+ * A null parent means the root project depends on the package directly, so it
215
+ * anchors to the root element. An edge naming a package absent from the
216
+ * document is dropped rather than emitted as a dangling reference.
217
+ */
218
+ function buildEdgesFromResolved(resolved, entries, rootId) {
219
+ const idByPackage = new Map();
220
+ for (const { ref, id } of entries) {
221
+ const key = `${ref.name}@${ref.version}`;
222
+ if (!idByPackage.has(key))
223
+ idByPackage.set(key, id);
224
+ }
225
+ const edges = [];
226
+ const seen = new Set();
227
+ for (const { child, parent } of resolved) {
228
+ const childId = idByPackage.get(child);
229
+ if (!childId)
230
+ continue;
231
+ const parentId = parent === null ? rootId : idByPackage.get(parent);
232
+ if (!parentId || parentId === childId)
233
+ continue;
234
+ const key = `${childId} ${parentId}`;
235
+ if (seen.has(key))
236
+ continue;
237
+ seen.add(key);
238
+ edges.push({
239
+ spdxElementId: childId,
240
+ relatedSpdxElement: parentId,
241
+ relationshipType: "DEPENDENCY_OF",
242
+ });
243
+ }
244
+ return edges;
245
+ }
246
+ export function buildSpdxDocument(allPackages, findings, projectMeta, version, plan = null, options = {}) {
247
+ const name = projectMeta?.name ?? "cve-lite-scan";
248
+ const annotator = `Tool: CVE Lite CLI-${version}`;
249
+ const timestamp = spdxTimestamp();
250
+ const findingsByPackage = options.inventoryOnly
251
+ ? new Map()
252
+ : groupFindingsByPackage(findings);
253
+ const usedIds = new Map();
254
+ const packages = [];
255
+ const relationships = [];
256
+ const root = buildRootPackage(projectMeta, usedIds);
257
+ if (root) {
258
+ packages.push(root.pkg);
259
+ relationships.push(root.relationship);
260
+ }
261
+ const indexed = [];
262
+ for (const pkg of allPackages) {
263
+ const pkgFindings = findingsByPackage.get(`${pkg.name}@${pkg.version}`) ?? [];
264
+ const entry = buildPackageEntry(pkg, pkgFindings, usedIds, plan, annotator, timestamp);
265
+ packages.push(entry);
266
+ indexed.push({ ref: pkg, id: entry.SPDXID });
267
+ }
268
+ // The graph describes the tree, not the findings, so it is inventory data and
269
+ // stays even in inventory-only mode.
270
+ // Checked by length, not truthiness: resolveDependencyEdges returns an empty
271
+ // array for pnpm, Yarn and Bun, and an empty array is truthy.
272
+ relationships.push(...(options.dependencyEdges?.length
273
+ ? buildEdgesFromResolved(options.dependencyEdges, indexed, root?.pkg.SPDXID ?? null)
274
+ : buildDependencyEdges(indexed, indexPackagesByPath(indexed, root?.pkg.SPDXID ?? null))));
275
+ return {
276
+ spdxVersion: "SPDX-2.3",
277
+ SPDXID: "SPDXRef-DOCUMENT",
278
+ name,
279
+ dataLicense: "CC0-1.0",
280
+ documentNamespace: `https://owasp.org/cve-lite-cli/spdxdocs/${encodeURIComponent(name)}-${randomUUID()}`,
281
+ creationInfo: {
282
+ created: timestamp,
283
+ creators: [annotator],
284
+ },
285
+ packages,
286
+ relationships,
287
+ };
288
+ }
289
+ export function writeSpdxReport(allPackages, findings, plan, projectMeta, options = {}) {
290
+ const filename = `cve-lite-scan-${sbomTimestamp()}.spdx.json`;
291
+ const doc = buildSpdxDocument(allPackages, findings, projectMeta, getCliVersion(), plan, options);
292
+ return writeSbomFile(filename, doc, "SPDX SBOM");
293
+ }
@@ -5,6 +5,9 @@ import { serializeLicenseFindings } from "./license-findings-json.js";
5
5
  import { serializeFinding } from "./formatters.js";
6
6
  import { writeSarifReport, deriveLockfileUri } from "./sarif.js";
7
7
  import { writeCycloneDxReport } from "./cyclonedx.js";
8
+ import { writeSpdxReport } from "./spdx.js";
9
+ import { resolveDependencyEdges } from "./sbom-dependency-edges.js";
10
+ import { resolveSbomFormat } from "../utils/sbom-format.js";
8
11
  import { overrideFindingsToJson } from "./override-findings-json.js";
9
12
  import { maintenanceFindingsToJson } from "./maintenance-findings-json.js";
10
13
  function readProjectMeta(projectPath) {
@@ -62,9 +65,21 @@ export async function writeOutputs(options, scanState, scanInput, projectPath) {
62
65
  const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, scanState.overrideFindings, scanState.maintenanceFindings, scanState.licenseFindings);
63
66
  console.log(`${chalk.gray("SARIF report written to")} ${chalk.cyan(sarifFilename)}`);
64
67
  }
65
- if (options.cdx) {
68
+ const sbomFormat = resolveSbomFormat(options);
69
+ if (sbomFormat) {
66
70
  const projectMeta = readProjectMeta(projectPath);
67
- const cdxFilename = writeCycloneDxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta);
68
- console.log(`${chalk.gray("CycloneDX BOM written to")} ${chalk.cyan(cdxFilename)}`);
71
+ if (sbomFormat === "spdx") {
72
+ const spdxFilename = writeSpdxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta, {
73
+ inventoryOnly: options.sbomInventoryOnly,
74
+ // Resolved from the lockfile graph where available. Empty for pnpm,
75
+ // Yarn and Bun, which falls back to path-derived edges.
76
+ dependencyEdges: resolveDependencyEdges(scanInput, scanState.allPackages),
77
+ });
78
+ console.log(`${chalk.gray("SPDX SBOM written to")} ${chalk.cyan(spdxFilename)}`);
79
+ }
80
+ else {
81
+ const cdxFilename = writeCycloneDxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta);
82
+ console.log(`${chalk.gray("CycloneDX BOM written to")} ${chalk.cyan(cdxFilename)}`);
83
+ }
69
84
  }
70
85
  }
@@ -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,