cve-lite-cli 1.33.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.
package/README.md CHANGED
@@ -1,4 +1,3 @@
1
-
2
1
  *Most tools tell you what's wrong. CVE Lite CLI tells you what to run.*
3
2
 
4
3
  [![OWASP Lab Project](https://img.shields.io/badge/OWASP-Lab%20Project-48A646?logo=owasp)](https://owasp.org/cve-lite-cli)
@@ -95,6 +94,7 @@ cve-lite /path/to/project --fix # apply validated direct fixes and r
95
94
  cve-lite /path/to/project --fail-on high # exit non-zero on high severity and above
96
95
  cve-lite /path/to/project --json # JSON output
97
96
  cve-lite /path/to/project --sarif # SARIF output for GitHub Code Scanning
97
+ cve-lite /path/to/project --sbom spdx # SPDX 2.3 SBOM (also: --sbom cyclonedx)
98
98
  cve-lite /path/to/project --report # interactive HTML dashboard
99
99
  cve-lite /path/to/project --check-overrides # audit override hygiene alongside the CVE scan
100
100
  cve-lite /path/to/project --check-maintenance # flag CVE-blocking version drag and npm-deprecated direct deps
@@ -210,7 +210,7 @@ The closer a security tool is to a developer's natural workflow, the more likely
210
210
 
211
211
  ## How it compares
212
212
 
213
- No other free tool combines all of the following: lockfile scanning across npm, pnpm, Yarn, and Bun; parent-aware transitive remediation that tells you which package to upgrade (not just which one is vulnerable); fix version validation before suggesting an upgrade; a fully offline advisory DB for restricted environments; CVE + license compliance scanning in a single pass; and an EPSS priority signal that combines CVSS severity with exploitation likelihood into four actionable tiers.
213
+ No other free tool combines all of the following: lockfile scanning across npm, pnpm, Yarn, and Bun; parent-aware transitive remediation that tells you which package to upgrade (not just which one is vulnerable); fix version validation before suggesting an upgrade; a fully offline advisory DB for restricted environments; CVE + license compliance scanning in a single pass; SBOM output in both CycloneDX and SPDX with the vulnerability findings attached rather than as a separate inventory step; and an EPSS priority signal that combines CVSS severity with exploitation likelihood into four actionable tiers.
214
214
 
215
215
  | Capability | CVE Lite CLI | npm audit | OSV-Scanner | Snyk CLI | Socket CLI |
216
216
  |---|:---:|:---:|:---:|:---:|:---:|
@@ -228,6 +228,7 @@ No other free tool combines all of the following: lockfile scanning across npm,
228
228
  | [Interactive HTML report](https://owasp.org/cve-lite-cli/docs/html-report) | ✅ | ❌ | ❌ | ✅ | ❌ |
229
229
  | [SARIF / GitHub Code Scanning output](https://owasp.org/cve-lite-cli/docs/sarif) | ✅ | ❌ | ✅ | ✅ | ❌ |
230
230
  | [JSON output](https://owasp.org/cve-lite-cli/docs/cli-reference#output-options) | ✅ | ✅ | ✅ | ✅ | ✅ |
231
+ | [SBOM output with findings attached (CycloneDX + SPDX)](https://owasp.org/cve-lite-cli/docs/spdx) | ✅ | ❌ | ❌ | ⚠️ | ⚠️ |
231
232
  | [Offline/local advisory DB](https://owasp.org/cve-lite-cli/docs/offline-advisory-db) | ✅ | ❌ | ⚠️ | ❌ | ❌ |
232
233
  | [Override hygiene auditing](https://owasp.org/cve-lite-cli/docs/override-hygiene) | ✅ | ❌ | ❌ | ❌ | ❌ |
233
234
  | [Maintenance-risk detection (CVE-fix drag)](https://owasp.org/cve-lite-cli/docs/maintenance-risk) | ✅ | ❌ | ❌ | ❌ | ❌ |
@@ -363,6 +364,8 @@ This is intentional. Because CVE Lite CLI is a security-oriented tool, runtime d
363
364
  - [Parser Coverage guide](https://owasp.org/cve-lite-cli/docs/parser-coverage) - supported lockfile formats, selection priority, `package.json` fallback, monorepos, private registries
364
365
  - [Remediation Strategy guide](https://owasp.org/cve-lite-cli/docs/remediation-strategy) - how CVE Lite CLI chooses upgrade targets and parent update paths
365
366
  - [Release Cooldown Awareness guide](https://owasp.org/cve-lite-cli/docs/release-cooldown) - how CVE Lite CLI reads your package manager's cooldown and warns on fix versions newer than the window you trust
367
+ - [SPDX SBOM guide](https://owasp.org/cve-lite-cli/docs/spdx) - SPDX 2.3 output, how findings are attached, NTIA minimum elements, and inventory-only mode
368
+ - [CycloneDX SBOM guide](https://owasp.org/cve-lite-cli/docs/cyclonedx) - CycloneDX 1.6 output and Dependency-Track integration
366
369
 
367
370
  ## Security and verification
368
371
 
@@ -437,4 +440,4 @@ Thank you to those who sponsor CVE Lite CLI and help keep it maintained:
437
440
 
438
441
  ## License
439
442
 
440
- MIT - built in public and maintained as an OWASP Foundation Project by Sonu Kapoor.
443
+ MIT - built in public and maintained as an OWASP Foundation Project by Sonu Kapoor.
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import Database from "better-sqlite3";
4
- import { compareVersions, looksLikeVersion } from "../utils/version.js";
4
+ import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
5
5
  const SCHEMA_SQL = `
6
6
  CREATE TABLE IF NOT EXISTS advisories (
7
7
  id TEXT PRIMARY KEY,
@@ -177,11 +177,40 @@ export class LocalAdvisoryDatabase {
177
177
  return [...ids];
178
178
  }
179
179
  }
180
+ /**
181
+ * The release core of a version, with any pre-release and build metadata
182
+ * stripped: `1.2.0-beta.1+exp` becomes `1.2.0`.
183
+ */
184
+ function releaseCore(version) {
185
+ return version.split("+")[0].split("-")[0];
186
+ }
187
+ /**
188
+ * Whether `version` is at or above an advisory's `introduced` bound.
189
+ *
190
+ * Plain semver precedence puts a pre-release below its release, so
191
+ * `1.2.0-beta.1` sorts below an `introduced` of `1.2.0` and would fall outside
192
+ * the range the advisory declared. In practice a `1.2.0-beta.1` build is a
193
+ * pre-release *of* `1.2.0` and carries whatever was introduced there, so
194
+ * excluding it is a false negative.
195
+ *
196
+ * The relaxation cannot widen a pre-release lower bound, which matters because
197
+ * OSV declares plenty of them: 64 of 352 sampled `introduced` events, with
198
+ * Next.js using values like `15.0.1-canary.0` routinely. Those are deliberate
199
+ * canary boundaries and must keep comparing exactly, or we would pull in
200
+ * earlier canaries the advisory explicitly excluded and trade this false
201
+ * negative for a false positive. No guard is needed for that: a release core
202
+ * never contains "-", so it can never equal a pre-release `introduced`.
203
+ */
204
+ function versionAtOrAboveIntroduced(version, introduced) {
205
+ if (compareVersions(version, introduced) >= 0)
206
+ return true;
207
+ return isPreReleaseVersion(version) && releaseCore(version) === introduced;
208
+ }
180
209
  function versionMatchesRange(version, row) {
181
210
  const introduced = row.introduced;
182
211
  const fixed = row.fixed;
183
212
  const lastAffected = row.last_affected;
184
- if (introduced && introduced !== "0" && compareVersions(version, introduced) < 0) {
213
+ if (introduced && introduced !== "0" && !versionAtOrAboveIntroduced(version, introduced)) {
185
214
  return false;
186
215
  }
187
216
  if (fixed && compareVersions(version, fixed) >= 0) {
@@ -62,6 +62,9 @@ export class OsvAdvisorySource {
62
62
  if (!Array.isArray(data?.results)) {
63
63
  throw new Error('OSV batch query returned a 200 response with no "results" array');
64
64
  }
65
+ if (data.results.length !== packages.length) {
66
+ throw new Error(`OSV batch query returned ${data.results.length} result(s) for ${packages.length} quer(ies) - response length mismatch`);
67
+ }
65
68
  return data.results.map((r, i) => ({
66
69
  package: packages[i].name,
67
70
  version: packages[i].version,
package/dist/cli/args.js CHANGED
@@ -1,4 +1,25 @@
1
1
  import { ConfigAction, ConfigKey } from "./config.js";
2
+ /**
3
+ * Accepted `--sbom` values. `spdx2.3` is an explicit alias for the version we
4
+ * emit today, so a future `spdx3` can be added without changing what a plain
5
+ * `spdx` means for anyone already using it in CI.
6
+ */
7
+ const SBOM_FORMAT_ALIASES = {
8
+ cyclonedx: "cyclonedx",
9
+ spdx: "spdx",
10
+ "spdx2.3": "spdx",
11
+ };
12
+ function parseSbomFormat(value) {
13
+ const valid = Object.keys(SBOM_FORMAT_ALIASES).join(", ");
14
+ if (value === undefined || value.startsWith("-")) {
15
+ throw new Error(`--sbom requires a format. Valid formats: ${valid}.`);
16
+ }
17
+ const format = SBOM_FORMAT_ALIASES[value.toLowerCase()];
18
+ if (!format) {
19
+ throw new Error(`Unknown --sbom format "${value}". Valid formats: ${valid}.`);
20
+ }
21
+ return format;
22
+ }
2
23
  export function parseArgs(argv) {
3
24
  // Normalize "cve-lite <path> overrides [flags]" to "cve-lite overrides <path> [flags]"
4
25
  // so both orderings work. Only reorder when "overrides" is a bare positional (not argv[0]).
@@ -351,7 +372,21 @@ export function parseArgs(argv) {
351
372
  continue;
352
373
  }
353
374
  if (arg === "--cdx") {
375
+ // Permanent alias. --cdx shipped before --sbom existed and stays supported.
354
376
  options.cdx = true;
377
+ options.sbom = "cyclonedx";
378
+ continue;
379
+ }
380
+ if (arg === "--sbom") {
381
+ options.sbom = parseSbomFormat(argv[++i]);
382
+ continue;
383
+ }
384
+ if (arg.startsWith("--sbom=")) {
385
+ options.sbom = parseSbomFormat(arg.slice("--sbom=".length));
386
+ continue;
387
+ }
388
+ if (arg === "--sbom-inventory-only") {
389
+ options.sbomInventoryOnly = true;
355
390
  continue;
356
391
  }
357
392
  if (arg === "--audit-log") {
@@ -399,8 +434,12 @@ export function parseArgs(argv) {
399
434
  }
400
435
  throw new Error(`Unexpected argument: ${arg}`);
401
436
  }
402
- if (options.cdx && options.report) {
403
- throw new Error("cannot combine --cdx and --report");
437
+ if (options.sbom && options.report) {
438
+ const flag = options.cdx ? "--cdx" : "--sbom";
439
+ throw new Error(`cannot combine ${flag} and --report`);
440
+ }
441
+ if (options.sbomInventoryOnly && !options.sbom) {
442
+ throw new Error("--sbom-inventory-only only applies to SBOM output. Add --sbom <format>, or drop --sbom-inventory-only.");
404
443
  }
405
444
  return { command: "scan", options, projectArg };
406
445
  }
package/dist/cli/help.js CHANGED
@@ -34,7 +34,9 @@ export function printHelp() {
34
34
  " --json Save scan results to a timestamped JSON file",
35
35
  " --report [dir] Generate an HTML report in [dir] (default: ./cve-report)",
36
36
  " --sarif Write SARIF 2.1.0 output to a timestamped .sarif file",
37
- " --cdx Write CycloneDX 1.4 SBOM to a timestamped .cdx.json file",
37
+ " --sbom <format> Write an SBOM: cyclonedx (1.6) or spdx (2.3), to a timestamped file",
38
+ " --sbom-inventory-only Omit the vulnerability overlay from --sbom, leaving a pure inventory",
39
+ " --cdx Alias for --sbom cyclonedx",
38
40
  " --no-open Don't auto-open the report in the browser",
39
41
  " --fix Apply validated direct dependency fixes and rescan",
40
42
  " --ratchet Save current findings as baseline or, if baseline exists, only fail on new findings",
@@ -1,5 +1,6 @@
1
1
  import { validateCaCertFile } from "./config.js";
2
2
  import { validateOsvUrl } from "../utils/validate-url.js";
3
+ import { resolveSbomFormat } from "../utils/sbom-format.js";
3
4
  export async function validateOptions(options) {
4
5
  if (options.allowPrivateOsvUrl && !options.osvUrl) {
5
6
  throw new Error("--allow-private-osv-url requires --osv-url. Provide a custom OSV endpoint with --osv-url, or remove --allow-private-osv-url.");
@@ -30,8 +31,11 @@ export async function validateOptions(options) {
30
31
  if (options.fix && options.sarif) {
31
32
  throw new Error("--fix cannot be used with --sarif. Use --fix to apply validated fixes and rescan, or --sarif to save scan results as SARIF, not both.");
32
33
  }
33
- if (options.fix && options.cdx) {
34
- throw new Error("--fix cannot be used with --cdx. Use --fix to apply validated fixes and rescan, or --cdx to save a CycloneDX SBOM, not both.");
34
+ if (options.fix && resolveSbomFormat(options)) {
35
+ // Name the flag the user actually typed: --cdx is an alias for --sbom cyclonedx.
36
+ const flag = options.cdx ? "--cdx" : "--sbom";
37
+ const what = options.cdx ? "a CycloneDX SBOM" : "an SBOM";
38
+ throw new Error(`--fix cannot be used with ${flag}. Use --fix to apply validated fixes and rescan, or ${flag} to save ${what}, not both.`);
35
39
  }
36
40
  if (options.createPr && !options.fix) {
37
41
  throw new Error("--create-pr requires --fix. Add --fix to apply validated fixes before opening a pull request, or remove --create-pr.");
package/dist/index.js CHANGED
@@ -646,7 +646,7 @@ if (parsedArgs) {
646
646
  licenseFindings,
647
647
  licenseLimitedToDirectOnly,
648
648
  }, scanInput, projectPath);
649
- if (!(options.json || options.sarif || options.cdx) || options.verbose) {
649
+ if (!(options.json || options.sarif || options.sbom) || options.verbose) {
650
650
  const offline = !!options.offline || !!options.offlineDb;
651
651
  const showOverrideHint = !options.checkOverrides && !options.ratchet && hasOverrideEntries(projectPath);
652
652
  if (options.verbose) {
@@ -1,13 +1,10 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
1
  import { randomUUID } from "node:crypto";
4
2
  import { findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
5
3
  import { getRecommendedAction } from "./formatters.js";
6
4
  import { getCliVersion } from "../utils/version-info.js";
7
- export function buildPurl(name, version) {
8
- const encodedName = name.startsWith("@") ? `%40${name.slice(1)}` : name;
9
- return `pkg:npm/${encodedName}@${version}`;
10
- }
5
+ import { buildPurl } from "../utils/purl.js";
6
+ import { sbomTimestamp, writeSbomFile } from "./sbom-file.js";
7
+ export { buildPurl };
11
8
  export function buildCycloneDxBom(allPackages, findings, projectMeta, version, plan = null) {
12
9
  const components = allPackages.map(pkg => {
13
10
  const purl = buildPurl(pkg.name, pkg.version);
@@ -54,9 +51,16 @@ export function buildCycloneDxBom(allPackages, findings, projectMeta, version, p
54
51
  }
55
52
  const metadata = {
56
53
  timestamp: new Date().toISOString(),
57
- tools: [
58
- { vendor: "OWASP", name: "CVE Lite CLI", version },
59
- ],
54
+ tools: {
55
+ components: [
56
+ {
57
+ type: "application",
58
+ name: "CVE Lite CLI",
59
+ version,
60
+ publisher: "OWASP",
61
+ },
62
+ ],
63
+ },
60
64
  };
61
65
  if (projectMeta && projectMeta.name) {
62
66
  const metaComponent = {
@@ -70,7 +74,7 @@ export function buildCycloneDxBom(allPackages, findings, projectMeta, version, p
70
74
  }
71
75
  return {
72
76
  bomFormat: "CycloneDX",
73
- specVersion: "1.4",
77
+ specVersion: "1.6",
74
78
  version: 1,
75
79
  serialNumber: `urn:uuid:${randomUUID()}`,
76
80
  metadata,
@@ -79,19 +83,7 @@ export function buildCycloneDxBom(allPackages, findings, projectMeta, version, p
79
83
  };
80
84
  }
81
85
  export function writeCycloneDxReport(allPackages, findings, plan, projectMeta) {
82
- const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
83
- const filename = `cve-lite-scan-${ts}.cdx.json`;
84
- const outputPath = path.join(process.cwd(), filename);
86
+ const filename = `cve-lite-scan-${sbomTimestamp()}.cdx.json`;
85
87
  const bom = buildCycloneDxBom(allPackages, findings, projectMeta, getCliVersion(), plan);
86
- try {
87
- fs.writeFileSync(outputPath, JSON.stringify(bom, null, 2));
88
- }
89
- catch (err) {
90
- try {
91
- fs.rmSync(outputPath, { force: true });
92
- }
93
- catch { /* best-effort cleanup */ }
94
- throw new Error(`Failed to write CycloneDX report to ${outputPath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
95
- }
96
- return filename;
88
+ return writeSbomFile(filename, bom, "CycloneDX report");
97
89
  }
@@ -303,3 +303,16 @@ export function sortFindingsForOutput(findings) {
303
303
  export function countUniqueAdvisories(findings) {
304
304
  return new Set(findings.flatMap(f => f.vulnerabilities.map(v => v.id))).size;
305
305
  }
306
+ export function countProdFindings(findings) {
307
+ const devFlagAvailable = findings.some(f => f.pkg.dev !== undefined);
308
+ if (!devFlagAvailable)
309
+ return null;
310
+ const devTotal = findings.filter(f => f.pkg.dev === true).length;
311
+ if (devTotal === 0)
312
+ return null;
313
+ return {
314
+ prodTotal: findings.length - devTotal,
315
+ devTotal,
316
+ total: findings.length,
317
+ };
318
+ }
@@ -220,10 +220,11 @@ button.header-link:hover{color:var(--link);border-color:var(--link)}
220
220
  .priority-none{font-size:11px;color:var(--text-3)}
221
221
  .epss-val{font-size:11px;color:var(--text-2);font-family:monospace;white-space:nowrap;cursor:help;border-bottom:1px dotted var(--text-3)}
222
222
  .epss-val.hot{color:#a371f7;border-bottom-color:#a371f7}
223
- .priority-legend{background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:14px 18px;margin:0 32px 24px}
223
+ .priority-legend{background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:14px 18px;margin:16px 0 24px}
224
224
  .priority-legend h4{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.4px;color:var(--text-2);margin-bottom:12px}
225
225
  .priority-legend-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px}
226
- .priority-legend-item{display:flex;align-items:flex-start;gap:10px;font-size:12px;color:var(--text-2);line-height:1.5}`;
226
+ .priority-legend-item{display:flex;align-items:flex-start;gap:10px;font-size:12px;color:var(--text-2);line-height:1.5}
227
+ .sev-dev-note{text-align:center;font-size:12px;color:var(--text-2);margin:-12px 0 16px;padding:0 32px}`;
227
228
  export function renderHtmlReport(data) {
228
229
  const projectName = path.basename(data.projectPath);
229
230
  const scanDate = new Date(data.scannedAt).toLocaleString();
@@ -234,6 +235,10 @@ export function renderHtmlReport(data) {
234
235
  counts[sev]++;
235
236
  }
236
237
  const totalCVEs = new Set(data.findings.flatMap(f => f.vulnerabilities.map(v => v.id))).size;
238
+ const devTotal = data.findings.filter(f => f.dev === true).length;
239
+ const devNoteHtml = devTotal > 0
240
+ ? `<div class="sev-dev-note">${data.findings.length - devTotal} of ${data.findings.length} findings in prod dependencies</div>`
241
+ : "";
237
242
  const noticesHtml = renderNotices(data.notes, data.warnings);
238
243
  const completenessBannerHtml = renderCompletenessBanner(data.completeness);
239
244
  const fixPlanHtml = renderFixPlan(data.suggestedFixCommands);
@@ -307,6 +312,7 @@ ${REPORT_STYLES}
307
312
  <div class="sev-card total"><span class="count">${data.findings.length}</span><span class="label">Packages</span></div>
308
313
  <div class="sev-card total"><span class="count">${totalCVEs}</span><span class="label">CVEs</span></div>
309
314
  </div>
315
+ ${devNoteHtml}
310
316
 
311
317
  ${completenessBannerHtml}
312
318
  ${fixPlanHtml}
@@ -336,7 +342,7 @@ ${duplicatePackagesHtml}
336
342
  <th onclick="sortBy('severity')" class="sorted">Severity <span class="sort-arrow" style="color:var(--link)">↓</span></th>
337
343
  <th title="Exploit Prediction Scoring System - likelihood of exploitation in the next 30 days, relative to all CVEs (FIRST.org)">EPSS</th>
338
344
  <th>EPSS Priority</th>
339
- <th onclick="sortBy('relationship')">Type <span class="sort-arrow">↕</span></th>
345
+ <th onclick="sortBy('relationship')" style="min-width:130px">Type <span class="sort-arrow">↕</span></th>
340
346
  <th>Root</th>
341
347
  <th>CVE / Advisory</th>
342
348
  </tr>
@@ -2,7 +2,7 @@ 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";
@@ -34,6 +34,10 @@ export function printSummary(findings, packageCount, scanInput) {
34
34
  };
35
35
  console.log(chalk.redBright(`✗ Found ${uniquePkgCount} ${pkgLabel} (${totalCVEs} ${cveLabel}) with known OSV matches from ${scanInput.source}`));
36
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
+ }
37
41
  }
38
42
  export function printActionSummary(findings, overrideCount = 0, packageManager) {
39
43
  if (findings.length === 0 && overrideCount === 0)
@@ -590,6 +594,10 @@ export function printCompactOutput(findings, scanInput, options) {
590
594
  console.log(`${chalk.cyan(String(direct))} ${chalk.white("direct")}` +
591
595
  `${chalk.gray(" · ")}` +
592
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
+ }
593
601
  if (options?.licenseFindings && options.licenseFindings.length > 0) {
594
602
  const lHigh = options.licenseFindings.filter(f => f.severity === "high").length;
595
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
  }
package/dist/scanner.js CHANGED
@@ -71,6 +71,23 @@ function isTransientFailure(error) {
71
71
  return false;
72
72
  return true;
73
73
  }
74
+ function mergeResultsByPackage(results) {
75
+ const map = new Map();
76
+ for (const result of results) {
77
+ const key = `${result.pkg.name}@${result.pkg.version}`;
78
+ const existing = map.get(key);
79
+ if (existing) {
80
+ for (const id of result.vulnIds) {
81
+ if (!existing.vulnIds.includes(id))
82
+ existing.vulnIds.push(id);
83
+ }
84
+ }
85
+ else {
86
+ map.set(key, { pkg: result.pkg, vulnIds: [...result.vulnIds] });
87
+ }
88
+ }
89
+ return [...map.values()];
90
+ }
74
91
  export async function scanPackages(packages, batchSize, options, context, debugLog, fetchImpl) {
75
92
  const log = debugLog ?? (() => { });
76
93
  const sourceContext = createAdvisorySource({
@@ -130,6 +147,9 @@ export async function scanPackages(packages, batchSize, options, context, debugL
130
147
  for (let j = 0; j < chunkItems.length; j++) {
131
148
  const pkg = chunkItems[j];
132
149
  const row = rows[j];
150
+ if (row && (row.package !== pkg.name || row.version !== pkg.version)) {
151
+ throw new Error(`OSV result identity mismatch at index ${j}: expected ${pkg.name}@${pkg.version}, got ${row.package}@${row.version}`);
152
+ }
133
153
  const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
134
154
  cache.queryEntries[getPackageCacheKey(pkg)] = { vulnIds, cachedAt };
135
155
  if (vulnIds.length > 0) {
@@ -310,7 +330,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
310
330
  if (!offline && (idSet.size > 0 || wroteNpmAdvisoryEntries)) {
311
331
  saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
312
332
  }
313
- const findings = results.map(result => {
333
+ const findings = mergeResultsByPackage(results).map(result => {
314
334
  const vulnerabilities = result.vulnIds
315
335
  .map(id => vulnMap.get(id))
316
336
  .filter((v) => Boolean(v));
@@ -319,7 +339,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
319
339
  const cveAliases = extractCveAliases(vulnerabilities);
320
340
  const dependencyPaths = result.pkg.paths ?? [];
321
341
  const relationship = classifyRelationship(dependencyPaths, result.pkg.name, context?.directDependencyNames);
322
- const firstFixedVersion = findFirstFixedVersion(vulnerabilities, result.pkg.name, result.pkg.ecosystem);
342
+ const firstFixedVersion = findFirstFixedVersion(vulnerabilities, result.pkg.name, result.pkg.ecosystem, result.pkg.version);
323
343
  return {
324
344
  pkg: result.pkg,
325
345
  vulnerabilities,
@@ -800,8 +820,28 @@ function affectedEntryMatchesPackage(affected, packageName, ecosystem) {
800
820
  return false;
801
821
  return true;
802
822
  }
803
- export function findFirstFixedVersion(vulns, packageName, ecosystem) {
823
+ /**
824
+ * True when `version` sits inside the half-open window `[introduced, fixed)`.
825
+ *
826
+ * `introduced` of "0" (or absent) means the window has no lower bound, which is
827
+ * how OSV expresses "every version before the fix".
828
+ */
829
+ function versionWithinAffectedWindow(version, introduced, fixed) {
830
+ if (introduced && introduced !== "0") {
831
+ if (!looksLikeVersion(introduced))
832
+ return false;
833
+ if (compareVersions(version, introduced) < 0)
834
+ return false;
835
+ }
836
+ return compareVersions(version, fixed) < 0;
837
+ }
838
+ export function findFirstFixedVersion(vulns, packageName, ecosystem, installedVersion) {
804
839
  const fixedVersions = [];
840
+ // Fixes whose affected window actually contains the installed version. An
841
+ // advisory that patches two release branches declares a fix per branch, and
842
+ // the global minimum is the other branch's fix - a downgrade across a major
843
+ // boundary rather than a remediation.
844
+ const fixesOnInstalledBranch = [];
805
845
  for (const vuln of vulns) {
806
846
  for (const affected of vuln.affected ?? []) {
807
847
  // An advisory may list several packages with different fix versions.
@@ -811,18 +851,33 @@ export function findFirstFixedVersion(vulns, packageName, ecosystem) {
811
851
  if (!affectedEntryMatchesPackage(affected, packageName, ecosystem))
812
852
  continue;
813
853
  for (const range of affected.ranges ?? []) {
854
+ // Events are ordered, and a single range can reintroduce a
855
+ // vulnerability, so `introduced` is tracked as the walk proceeds and
856
+ // reset once its matching `fixed` closes the window.
857
+ let introduced = null;
814
858
  for (const event of range.events ?? []) {
859
+ if (event.introduced) {
860
+ introduced = event.introduced;
861
+ continue;
862
+ }
815
863
  const fixed = event.fixed;
816
- if (fixed && looksLikeVersion(fixed) && !isPreReleaseVersion(fixed)) {
817
- fixedVersions.push(fixed);
864
+ if (!fixed || !looksLikeVersion(fixed) || isPreReleaseVersion(fixed))
865
+ continue;
866
+ fixedVersions.push(fixed);
867
+ if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed)) {
868
+ fixesOnInstalledBranch.push(fixed);
818
869
  }
870
+ introduced = null;
819
871
  }
820
872
  }
821
873
  }
822
874
  }
823
- if (fixedVersions.length === 0)
875
+ // Falling back to every known fix keeps a finding's remediation visible when
876
+ // the installed version sits outside each declared window.
877
+ const candidates = fixesOnInstalledBranch.length > 0 ? fixesOnInstalledBranch : fixedVersions;
878
+ if (candidates.length === 0)
824
879
  return null;
825
- return fixedVersions.sort(compareVersions)[0];
880
+ return candidates.sort(compareVersions)[0];
826
881
  }
827
882
  function buildCompletenessDiagnostics(params) {
828
883
  const diagnostics = [];
package/dist/types.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * 1 - findings present (CVE or override) above threshold
6
6
  * 2 - --fix applied but verify() detected the fix did not take
7
7
  * (operationally distinct from 1: "fix ran but did not work")
8
- * 3 - tool error (unhandled exception, unreadable lockfile, etc.)
8
+ * 3 - tool error (unhandled exception, unreadable lockfile, etc.) or incomplete scan (--incomplete-policy=error)
9
9
  */
10
10
  export const EXIT_OK = 0;
11
11
  export const EXIT_FINDINGS = 1;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Builds a Package URL (purl) for an npm package.
3
+ *
4
+ * Scoped names carry a leading `@` which is not legal unencoded in the purl
5
+ * name component, so it is percent-encoded.
6
+ */
7
+ export function buildPurl(name, version) {
8
+ const encodedName = name.startsWith("@") ? `%40${name.slice(1)}` : name;
9
+ return `pkg:npm/${encodedName}@${version}`;
10
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Resolves which SBOM format a run should emit, if any.
3
+ *
4
+ * `--cdx` predates `--sbom` and remains supported, so it is honoured here as
5
+ * well as in argument parsing. Keeping the alias in one place means callers
6
+ * that build options programmatically behave the same as the CLI.
7
+ */
8
+ export function resolveSbomFormat(options) {
9
+ if (options.sbom)
10
+ return options.sbom;
11
+ return options.cdx ? "cyclonedx" : undefined;
12
+ }
@@ -1,27 +1,45 @@
1
1
  export function looksLikeVersion(value) {
2
2
  return /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][^/]+)?$/.test(value);
3
3
  }
4
+ // Matches a well-formed X.Y.Z version, capturing an optional dot-separated
5
+ // pre-release identifier list and discarding build metadata (semver §11.3/11.4).
6
+ // The pre-release character class matches looksLikeVersion's admission gate
7
+ // above (anything but '/' or '+') rather than a narrower ASCII set, so a
8
+ // pre-release looksLikeVersion accepts can never fail this match and fall
9
+ // through to the flat-token fallback, which would reintroduce the exact
10
+ // precedence bug this file fixes.
11
+ const VERSION_SHAPE = /^(\d+)\.(\d+)\.(\d+)(?:-([^/+]+))?(?:\+.*)?$/;
4
12
  // module-level; safe to grow unbounded — a single scan sees at most
5
13
  // a few hundred unique version strings, and the cache is discarded when the process exits.
6
14
  const parsedVersionCache = new Map();
7
15
  export function getVersionCacheSize() {
8
16
  return parsedVersionCache.size;
9
17
  }
10
- function parseVersionTuple(v) {
18
+ function parseVersion(v) {
11
19
  const cached = parsedVersionCache.get(v);
12
- if (cached)
20
+ if (cached !== undefined)
13
21
  return cached;
14
- const parsed = v.split(/[.+-]/).map(n => {
15
- const num = Number(n);
16
- return Number.isFinite(num) ? num : n;
17
- });
18
- Object.freeze(parsed);
22
+ const match = VERSION_SHAPE.exec(v);
23
+ const parsed = match
24
+ ? {
25
+ release: [Number(match[1]), Number(match[2]), Number(match[3])],
26
+ prerelease: match[4] ? match[4].split(".") : null,
27
+ }
28
+ : null;
19
29
  parsedVersionCache.set(v, parsed);
20
30
  return parsed;
21
31
  }
22
- export function compareVersions(a, b) {
23
- const pa = parseVersionTuple(a);
24
- const pb = parseVersionTuple(b);
32
+ // Legacy flat-tuple comparison, used only when at least one operand doesn't
33
+ // match VERSION_SHAPE, so a malformed input on either side degrades to prior
34
+ // (non-throwing) behavior instead of comparing a semver-parsed shape against
35
+ // an unparsed one (KTD3).
36
+ function compareFallback(a, b) {
37
+ const toTuple = (v) => v.split(/[.+-]/).map(n => {
38
+ const num = Number(n);
39
+ return Number.isFinite(num) ? num : n;
40
+ });
41
+ const pa = toTuple(a);
42
+ const pb = toTuple(b);
25
43
  const len = Math.max(pa.length, pb.length);
26
44
  for (let i = 0; i < len; i++) {
27
45
  const av = pa[i] ?? 0;
@@ -39,6 +57,52 @@ export function compareVersions(a, b) {
39
57
  }
40
58
  return 0;
41
59
  }
60
+ const NUMERIC_IDENTIFIER = /^\d+$/;
61
+ // Compares two dot-separated pre-release identifier lists per semver §11.4:
62
+ // numeric identifiers compare numerically, alphanumeric ones lexically, a
63
+ // numeric identifier always has lower precedence than an alphanumeric one,
64
+ // and (when the shared prefix is equal) a longer list outranks a shorter one.
65
+ function compareIdentifiers(a, b) {
66
+ const aIsNumeric = NUMERIC_IDENTIFIER.test(a);
67
+ const bIsNumeric = NUMERIC_IDENTIFIER.test(b);
68
+ if (aIsNumeric && bIsNumeric)
69
+ return Number(a) - Number(b);
70
+ if (aIsNumeric !== bIsNumeric)
71
+ return aIsNumeric ? -1 : 1;
72
+ return a < b ? -1 : a > b ? 1 : 0;
73
+ }
74
+ // A version with no pre-release outranks one with a pre-release at the same
75
+ // release; between two pre-releases, compare identifiers left to right.
76
+ function comparePrerelease(a, b) {
77
+ if (a === null && b === null)
78
+ return 0;
79
+ if (a === null)
80
+ return 1;
81
+ if (b === null)
82
+ return -1;
83
+ const len = Math.max(a.length, b.length);
84
+ for (let i = 0; i < len; i++) {
85
+ if (i >= a.length)
86
+ return -1;
87
+ if (i >= b.length)
88
+ return 1;
89
+ const cmp = compareIdentifiers(a[i], b[i]);
90
+ if (cmp !== 0)
91
+ return cmp;
92
+ }
93
+ return 0;
94
+ }
95
+ export function compareVersions(a, b) {
96
+ const pa = parseVersion(a);
97
+ const pb = parseVersion(b);
98
+ if (!pa || !pb)
99
+ return compareFallback(a, b);
100
+ for (let i = 0; i < 3; i++) {
101
+ if (pa.release[i] !== pb.release[i])
102
+ return pa.release[i] - pb.release[i];
103
+ }
104
+ return comparePrerelease(pa.prerelease, pb.prerelease);
105
+ }
42
106
  export function parseExactManifestVersion(spec) {
43
107
  const cleaned = spec.trim().replace(/^npm:/, "");
44
108
  if (looksLikeVersion(cleaned))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.33.0",
3
+ "version": "1.34.0",
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": {
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "better-sqlite3": "^12.8.0",
23
- "fflate": "^0.8.2",
23
+ "fflate": "^0.8.3",
24
24
  "yaml": "^2.7.1",
25
25
  "yarn-lockfile": "^1.1.0"
26
26
  },