cve-lite-cli 1.32.0 → 1.34.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.
@@ -2,11 +2,12 @@ import { chalk, stripAnsi } from "../utils/chalk.js";
2
2
  import { buildSuggestedFixCommandPlan, UNVERIFIED_PARENT_UPGRADE_NOTE } from "../remediation/fix-commands.js";
3
3
  import { isBreakingUpgrade } from "../utils/version.js";
4
4
  import { getPrimaryParent } from "../utils/finding.js";
5
- import { countUniqueAdvisories, formatRelationshipLabel, formatRelLabel, formatRootDependencySummary, formatFixCommandWithPublishDates, formatCooldownWarning, } from "./formatters.js";
5
+ import { countUniqueAdvisories, countProdFindings, formatRelationshipLabel, formatRelLabel, formatRootDependencySummary, formatFixCommandWithPublishDates, formatCooldownWarning, } from "./formatters.js";
6
6
  import { formatSeverityLabel } from "../utils/severity.js";
7
7
  import { pluralize } from "../utils/string.js";
8
8
  import { hasMaliciousAdvisory } from "../utils/vuln.js";
9
9
  import { selectFindingsForCompact } from "./finding-display.js";
10
+ import { computePrioritySignal, PRIORITY_SIGNAL_LABELS, PRIORITY_SIGNAL_TABLE_LABELS, PRIORITY_SIGNAL_DESCRIPTIONS } from "../utils/priority-signal.js";
10
11
  import { renderLicenseFindings } from "./license-terminal.js";
11
12
  import { getCompletenessImpact } from "../scan/completeness.js";
12
13
  import { MAL_PRIVATE_REGISTRY_COMPACT_MESSAGE, MAL_PRIVATE_REGISTRY_LEGEND_MESSAGE, MAL_GIT_SOURCE_PINNED_MESSAGE, MAL_GIT_SOURCE_FLOATING_MESSAGE, MAL_GIT_SOURCE_COMPACT_MESSAGE, MAL_GIT_SOURCE_LEGEND_MESSAGE, MAL_GIT_SOURCE_PINNED_DISPLAY, MAL_GIT_SOURCE_FLOATING_DISPLAY, OVERRIDES_COMMAND, } from "../constants.js";
@@ -21,7 +22,8 @@ export function printSummary(findings, packageCount, scanInput) {
21
22
  return;
22
23
  }
23
24
  const totalCVEs = countUniqueAdvisories(findings);
24
- const pkgLabel = findings.length === 1 ? "package" : "packages";
25
+ const uniquePkgCount = new Set(findings.map(f => `${f.pkg.name}@${f.pkg.version}`)).size;
26
+ const pkgLabel = uniquePkgCount === 1 ? "package" : "packages";
25
27
  const cveLabel = totalCVEs === 1 ? "CVE" : "CVEs";
26
28
  const counts = {
27
29
  critical: findings.filter(f => f.severity === "critical").length,
@@ -30,8 +32,12 @@ export function printSummary(findings, packageCount, scanInput) {
30
32
  low: findings.filter(f => f.severity === "low").length,
31
33
  unknown: findings.filter(f => f.severity === "unknown").length
32
34
  };
33
- console.log(chalk.redBright(`✗ Found ${findings.length} ${pkgLabel} (${totalCVEs} ${cveLabel}) with known OSV matches from ${scanInput.source}`));
35
+ console.log(chalk.redBright(`✗ Found ${uniquePkgCount} ${pkgLabel} (${totalCVEs} ${cveLabel}) with known OSV matches from ${scanInput.source}`));
34
36
  console.log(renderSeverityTable(counts));
37
+ const prodSplit = countProdFindings(findings);
38
+ if (prodSplit !== null) {
39
+ console.log(chalk.gray(` └ ${prodSplit.prodTotal} of ${prodSplit.total} findings in prod dependencies`));
40
+ }
35
41
  }
36
42
  export function printActionSummary(findings, overrideCount = 0, packageManager) {
37
43
  if (findings.length === 0 && overrideCount === 0)
@@ -193,8 +199,21 @@ export function printSkippedDependencies(skipped) {
193
199
  console.log(`${chalk.yellow("•")} ...and ${skipped.length - 10} more`);
194
200
  }
195
201
  }
202
+ function formatPrioritySignal(signal) {
203
+ if (!signal)
204
+ return chalk.gray("-");
205
+ const label = PRIORITY_SIGNAL_TABLE_LABELS[signal];
206
+ if (signal === "fix_now")
207
+ return chalk.red(label);
208
+ if (signal === "fix_soon")
209
+ return chalk.yellow(label);
210
+ if (signal === "monitor")
211
+ return chalk.blue(label);
212
+ return chalk.gray(label);
213
+ }
196
214
  export function printTable(findings, threshold, skippedKeys) {
197
- const headers = ["Package", "Version", "Severity", "Type", "Root", "Usage", "Fixed", "EPSS", "IDs"];
215
+ const headers = ["Package", "Version", "Severity", "Type", "Root", "Usage", "Fixed", "EPSS", "EPSS Priority", "IDs"];
216
+ const rowSignals = [];
198
217
  const rawRows = findings.map(f => {
199
218
  let usageText = "n/a";
200
219
  if (f.usage) {
@@ -222,10 +241,14 @@ export function printTable(findings, threshold, skippedKeys) {
222
241
  fixedDisplay = chalk.yellow("⚠ no fix");
223
242
  }
224
243
  let epssDisplay = "-";
244
+ let signal = null;
225
245
  if (f.epssScores && f.epssScores.length > 0) {
226
- const best = f.epssScores.slice().sort((a, b) => b.epss - a.epss)[0];
246
+ const best = f.epssScores.slice().sort((a, b) => b.percentile - a.percentile)[0];
227
247
  epssDisplay = `${(best.epss * 100).toFixed(1)}%`;
248
+ signal = computePrioritySignal(f.severity, f.epssScores);
228
249
  }
250
+ rowSignals.push(signal);
251
+ const priorityDisplay = signal ? PRIORITY_SIGNAL_TABLE_LABELS[signal] : "-";
229
252
  return [
230
253
  f.pkg.name,
231
254
  f.pkg.version,
@@ -235,6 +258,7 @@ export function printTable(findings, threshold, skippedKeys) {
235
258
  usageText,
236
259
  fixedDisplay,
237
260
  epssDisplay,
261
+ priorityDisplay,
238
262
  f.vulnerabilities.map(v => v.id).join(", ")
239
263
  ];
240
264
  });
@@ -247,7 +271,7 @@ export function printTable(findings, threshold, skippedKeys) {
247
271
  console.log(line("┌", "┬", "┐"));
248
272
  console.log(renderRow(headers, widths));
249
273
  console.log(line("├", "┼", "┤"));
250
- for (const row of rawRows) {
274
+ rawRows.forEach((row, idx) => {
251
275
  let usageDecorated = String(row[5]);
252
276
  if (usageDecorated.includes("file(s)"))
253
277
  usageDecorated = chalk.red(usageDecorated);
@@ -264,10 +288,11 @@ export function printTable(findings, threshold, skippedKeys) {
264
288
  usageDecorated,
265
289
  row[6],
266
290
  chalk.gray(String(row[7])),
267
- row[8]
291
+ formatPrioritySignal(rowSignals[idx] ?? null),
292
+ row[9],
268
293
  ];
269
294
  console.log(renderRow(decorated, widths));
270
- }
295
+ });
271
296
  console.log(line("└", "┴", "┘"));
272
297
  const maliciousFindings = findings.filter(f => hasMaliciousAdvisory(f.vulnerabilities));
273
298
  if (maliciousFindings.length > 0) {
@@ -442,11 +467,15 @@ export function printCompactOutput(findings, scanInput, options) {
442
467
  console.log(`${formatSeverityLabel(sevLabel)} ${chalk.whiteBright(finding.pkg.name)}@${finding.pkg.version}`);
443
468
  console.log(` ${typeLabel}${usageContext}`);
444
469
  if (finding.epssScores && finding.epssScores.length > 0) {
445
- const best = finding.epssScores.slice().sort((a, b) => b.epss - a.epss)[0];
470
+ const best = finding.epssScores.slice().sort((a, b) => b.percentile - a.percentile)[0];
446
471
  const pct = (best.epss * 100).toFixed(1);
447
472
  const top = ((1 - best.percentile) * 100);
448
473
  const topStr = top < 0.01 ? "<0.01" : top < 1 ? top.toFixed(2) : top.toFixed(1);
449
474
  console.log(` ${chalk.gray(`EPSS: ${pct}% exploitation probability - ${best.cve} (top ${topStr}% of all CVEs)`)}`);
475
+ const priority = computePrioritySignal(finding.severity, finding.epssScores);
476
+ if (priority === "fix_now") {
477
+ console.log(` ${chalk.red(PRIORITY_SIGNAL_LABELS.fix_now)} - ${PRIORITY_SIGNAL_DESCRIPTIONS[priority]}`);
478
+ }
450
479
  }
451
480
  const isMalicious = hasMaliciousAdvisory(finding.vulnerabilities);
452
481
  if (isMalicious) {
@@ -565,6 +594,10 @@ export function printCompactOutput(findings, scanInput, options) {
565
594
  console.log(`${chalk.cyan(String(direct))} ${chalk.white("direct")}` +
566
595
  `${chalk.gray(" · ")}` +
567
596
  `${chalk.cyan(String(transitive))} ${chalk.white("transitive")}`);
597
+ const compactProdSplit = countProdFindings(findings);
598
+ if (compactProdSplit !== null) {
599
+ console.log(chalk.gray(` └ ${compactProdSplit.prodTotal} of ${compactProdSplit.total} findings in prod dependencies`));
600
+ }
568
601
  if (options?.licenseFindings && options.licenseFindings.length > 0) {
569
602
  const lHigh = options.licenseFindings.filter(f => f.severity === "high").length;
570
603
  const lMed = options.licenseFindings.filter(f => f.severity === "medium").length;
@@ -0,0 +1,76 @@
1
+ import { loadNpmLockGraph } from "../parsers/npm-lock-graph.js";
2
+ function packageKey(name, version) {
3
+ return `${name}@${version}`;
4
+ }
5
+ /** Several graph nodes collapse to one name@version, so edges are deduplicated. */
6
+ function addEdge(edges, seen, child, parent) {
7
+ const key = `${child} ${parent ?? ""}`;
8
+ if (seen.has(key))
9
+ return;
10
+ seen.add(key);
11
+ edges.push({ child, parent });
12
+ }
13
+ /**
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.
25
+ */
26
+ export function resolveDependencyEdges(scanInput, allPackages) {
27
+ if (scanInput.source !== "package-lock" || !scanInput.filePath)
28
+ return [];
29
+ let graph;
30
+ try {
31
+ graph = loadNpmLockGraph(scanInput.filePath, { includePaths: false });
32
+ }
33
+ 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 [];
37
+ }
38
+ // Only packages present in the document can be referenced. `--prod-only` and
39
+ // similar filters shrink this set without shrinking the graph, and an edge to
40
+ // a package absent from the document would be a dangling SPDX reference.
41
+ const included = new Set(allPackages.map(p => packageKey(p.name, p.version)));
42
+ const edges = [];
43
+ const seen = new Set();
44
+ for (const pkg of allPackages) {
45
+ const childKey = packageKey(pkg.name, pkg.version);
46
+ let anchored = false;
47
+ for (const nodeId of graph.nodeIdsFor(pkg.name, pkg.version)) {
48
+ for (const parentNodeId of graph.parentsFor(nodeId)) {
49
+ const parentNode = graph.getNode(parentNodeId);
50
+ // Workspace members are symlinked rather than installed, so the graph
51
+ // records them without a version and they never appear in the scanned
52
+ // package set. They cannot be referenced as SPDX packages.
53
+ if (!parentNode?.version)
54
+ continue;
55
+ const parentKey = packageKey(parentNode.name, parentNode.version);
56
+ if (parentKey === childKey)
57
+ continue;
58
+ // Referencing a package absent from the document would be a dangling
59
+ // SPDX reference. `--prod-only` and similar filters shrink the package
60
+ // set without shrinking the graph.
61
+ if (!included.has(parentKey))
62
+ continue;
63
+ addEdge(edges, seen, childKey, parentKey);
64
+ anchored = true;
65
+ }
66
+ }
67
+ // Either nothing depends on it, or every parent was a workspace member or
68
+ // filtered out of the document. Anchoring to the root keeps the package in
69
+ // the graph: it is genuinely part of the tree, and the root is the only
70
+ // anchor the document can offer. Orphaning it would silently drop a
71
+ // dependency relationship, which is an NTIA minimum element.
72
+ if (!anchored)
73
+ addEdge(edges, seen, childKey, null);
74
+ }
75
+ return edges;
76
+ }
@@ -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
  }
@@ -24,6 +24,15 @@ export function buildNpmWorkspaceMap(filePath) {
24
24
  }
25
25
  return map;
26
26
  }
27
+ /**
28
+ * npm records a package's declared license in package-lock.json v2/v3, so we
29
+ * get it without touching the registry. Very old manifests used the object
30
+ * form `{ type, url }`; only the modern SPDX expression string is usable as-is,
31
+ * so anything else is treated as absent rather than stringified into nonsense.
32
+ */
33
+ function readLockfileLicense(value) {
34
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
35
+ }
27
36
  export function loadFromPackageLock(filePath, prodOnly) {
28
37
  const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
29
38
  const map = new Map();
@@ -45,7 +54,8 @@ export function loadFromPackageLock(filePath, prodOnly) {
45
54
  const graphPaths = nodeIds.flatMap(id => graph.pathsFor(id));
46
55
  const paths = graphPaths.length > 0 ? graphPaths : [normalizeNodeModulesPath(pkgPath)];
47
56
  const resolvedUrl = meta?.resolved;
48
- upsertPackage(map, { name, version, ecosystem: "npm", dev, paths, resolvedUrl });
57
+ const license = readLockfileLicense(meta?.license);
58
+ upsertPackage(map, { name, version, ecosystem: "npm", dev, paths, resolvedUrl, license });
49
59
  }
50
60
  }
51
61
  if (map.size === 0 && raw.dependencies && typeof raw.dependencies === "object") {
@@ -8,6 +8,9 @@ export function upsertPackage(map, candidate) {
8
8
  }
9
9
  existing.dev = existing.dev && candidate.dev;
10
10
  existing.paths = uniquePathArrays([...(existing.paths ?? []), ...(candidate.paths ?? [])]).slice(0, 5);
11
+ // The same name@version can appear at several lockfile paths; keep the first
12
+ // license we see rather than losing it if a later entry omits the field.
13
+ existing.license ??= candidate.license;
11
14
  }
12
15
  export function normalizeNodeModulesPath(pkgPath) {
13
16
  const parts = pkgPath.split("/").filter(Boolean);
@@ -119,7 +119,9 @@ export async function resolvePublishedFixVersion(packageName, fixedVersionHint)
119
119
  }
120
120
  const publishedVersions = Object.keys(packument.versions ?? {})
121
121
  .filter(looksLikeVersion)
122
+ .filter(version => !isPreReleaseVersion(version))
122
123
  .sort(compareVersions);
124
+ const fixedVersionHintIsPreRelease = isPreReleaseVersion(fixedVersionHint);
123
125
  if (publishedVersions.includes(fixedVersionHint)) {
124
126
  return {
125
127
  resolvedVersion: fixedVersionHint,
@@ -135,7 +137,9 @@ export async function resolvePublishedFixVersion(packageName, fixedVersionHint)
135
137
  if (nearestPublishedVersion) {
136
138
  return {
137
139
  resolvedVersion: nearestPublishedVersion,
138
- note: `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}; using nearest published version ${nearestPublishedVersion}.`,
140
+ note: fixedVersionHintIsPreRelease
141
+ ? `Advisory fixed-version hint ${fixedVersionHint} is a pre-release; using nearest published non-pre-release version ${nearestPublishedVersion}.`
142
+ : `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}; using nearest published version ${nearestPublishedVersion}.`,
139
143
  verified: true,
140
144
  candidatesChecked: 0,
141
145
  candidatesKnownVulnerable: 0,
@@ -145,7 +149,9 @@ export async function resolvePublishedFixVersion(packageName, fixedVersionHint)
145
149
  }
146
150
  return {
147
151
  resolvedVersion: null,
148
- note: `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}, and no published version >= ${fixedVersionHint} was found.`,
152
+ note: fixedVersionHintIsPreRelease
153
+ ? `Advisory fixed-version hint ${fixedVersionHint} is a pre-release, and no published non-pre-release version >= ${fixedVersionHint} was found for ${packageName}.`
154
+ : `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}, and no published version >= ${fixedVersionHint} was found.`,
149
155
  verified: true,
150
156
  candidatesChecked: 0,
151
157
  candidatesKnownVulnerable: 0,
@@ -48,6 +48,7 @@ export function aggregateMultiFolderCompleteness(results) {
48
48
  return { complete: deduped.size === 0, diagnostics: [...deduped.values()] };
49
49
  }
50
50
  export function shouldFailForIncompleteScan(completeness, policy) {
51
+ // --incomplete-policy=warn has the same effect as not passing the flag at all
51
52
  if (policy !== "error") {
52
53
  return false;
53
54
  }