cve-lite-cli 1.40.0 → 1.41.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 (68) hide show
  1. package/README.md +17 -11
  2. package/dist/advisory/local-advisory-source.js +9 -5
  3. package/dist/advisory/local-db.js +91 -13
  4. package/dist/advisory/osv-sync.js +187 -56
  5. package/dist/advisory/staging-directory.js +112 -0
  6. package/dist/cli/advisories-sync.js +16 -2
  7. package/dist/cli/args.js +46 -35
  8. package/dist/cli/config.js +4 -1
  9. package/dist/cli/help.js +4 -3
  10. package/dist/cli/validate.js +23 -1
  11. package/dist/constants.js +11 -25
  12. package/dist/index.js +8 -3
  13. package/dist/output/cyclonedx.js +23 -14
  14. package/dist/output/debug.js +68 -18
  15. package/dist/output/formatters.js +33 -5
  16. package/dist/output/html-reporter.js +55 -5
  17. package/dist/output/multi-folder-html-reporter.js +59 -3
  18. package/dist/output/output-dir.js +193 -7
  19. package/dist/output/printers.js +16 -5
  20. package/dist/output/sarif.js +131 -48
  21. package/dist/output/sbom-dependency-edges.js +16 -10
  22. package/dist/output/sbom-file.js +14 -6
  23. package/dist/output/scan-json.js +21 -3
  24. package/dist/output/spdx.js +61 -23
  25. package/dist/output/spinner.js +2 -1
  26. package/dist/output/write-outputs.js +142 -52
  27. package/dist/overrides/context-builder.js +23 -70
  28. package/dist/parsers/bun-lock.js +1 -2
  29. package/dist/parsers/index.js +22 -1
  30. package/dist/parsers/npm-lock-graph.js +39 -1
  31. package/dist/parsers/package-lock.js +25 -5
  32. package/dist/parsers/pnpm-lock.js +3 -2
  33. package/dist/parsers/utils.js +5 -3
  34. package/dist/parsers/yarn-lock-graph.js +5 -2
  35. package/dist/parsers/yarn-lock.js +1 -2
  36. package/dist/remediation/fix-commands.js +105 -44
  37. package/dist/remediation/npm-transitive-graph.js +30 -72
  38. package/dist/remediation/npm-transitive-resolution.js +24 -77
  39. package/dist/remediation/parent-upgrade-blockers.js +51 -0
  40. package/dist/remediation/parent-upgrade.js +5 -79
  41. package/dist/remediation/registry-parent-ranges.js +21 -0
  42. package/dist/remediation/transitive-chain-resolver.js +3 -3
  43. package/dist/scan/completeness.js +10 -4
  44. package/dist/scan/multi-folder-scan.js +133 -58
  45. package/dist/scan/single-scan.js +41 -25
  46. package/dist/scanner.js +257 -58
  47. package/dist/usage/scanner.js +19 -8
  48. package/dist/utils/array.js +11 -3
  49. package/dist/utils/debug-bundle.js +118 -0
  50. package/dist/utils/debug-project.js +102 -0
  51. package/dist/utils/debug-redaction.js +117 -0
  52. package/dist/utils/file.js +2 -1
  53. package/dist/utils/fix-runner.js +95 -13
  54. package/dist/utils/import-type-queries.js +322 -0
  55. package/dist/utils/network.js +13 -9
  56. package/dist/utils/npm-lockfile.js +12 -0
  57. package/dist/utils/osv-fetch.js +70 -0
  58. package/dist/utils/package-identity.js +43 -0
  59. package/dist/utils/package-manager-source.js +24 -0
  60. package/dist/utils/purl.js +37 -0
  61. package/dist/utils/registry-config.js +1 -16
  62. package/dist/utils/string.js +8 -0
  63. package/dist/utils/validate-url.js +1 -1
  64. package/dist/utils/version.js +30 -7
  65. package/dist/utils/versions/osv-range.js +191 -0
  66. package/dist/utils/versions/pep440.js +246 -0
  67. package/dist/utils/versions/scheme.js +10 -0
  68. package/package.json +3 -2
@@ -1,11 +1,13 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { getCompletenessImpact } from "../scan/completeness.js";
3
5
  import { findFixTargetForFinding } from "../remediation/fix-commands.js";
4
6
  import { getRecommendedAction, formatCooldownWarning } from "./formatters.js";
5
7
  import { getCliVersion } from "../utils/version-info.js";
6
8
  import { severityToSarifLevel } from "../utils/severity.js";
7
9
  import { sarifFingerprintHash } from "../utils/sarif.js";
8
- import { displayOutputPath } from "./output-dir.js";
10
+ import { displayOutputPath, isOutputStdout } from "./output-dir.js";
9
11
  import { buildOverrideSarifComponent, buildOverrideSarifResults } from "./override-findings-sarif.js";
10
12
  import { buildMaintenanceSarifComponent, buildMaintenanceSarifResults } from "./maintenance-findings-sarif.js";
11
13
  import { buildLicenseSarifComponent, buildLicenseSarifResults } from "./license-findings-sarif.js";
@@ -91,9 +93,34 @@ function buildRuleHelp(vuln, depPath, action) {
91
93
  return { text: textParts.join("\n"), markdown: mdParts.join("\n") };
92
94
  }
93
95
  export function deriveLockfileUri(scanInput) {
94
- if (scanInput.filePath)
96
+ if (!scanInput.filePath)
97
+ return LOCKFILE_NAMES[scanInput.source] ?? "lockfile";
98
+ // Every location in this document is emitted with uriBaseId "%SRCROOT%", so the value has to be
99
+ // the lockfile measured from the source root or the declaration is a lie. It used to be the
100
+ // basename, which made a scan of a subdirectory report its findings against a lockfile at the
101
+ // repository root (#1380).
102
+ //
103
+ // The launch directory is the right base because it IS the checkout root on every path that
104
+ // uploads to Code Scanning: our own action pins working-directory to the workspace in all seven
105
+ // scan steps and passes the target directory as an argument. A scan of the root therefore still
106
+ // yields the bare filename it has always emitted, which is why this is not a blanket change.
107
+ //
108
+ // Note this is deliberately NOT the base the HTML report uses. That artefact is read wherever
109
+ // somebody pastes it, so it measures from the scanned project (#1271). Each artefact measures
110
+ // from wherever it is read, and the two answers differ because the readers differ.
111
+ const relative = path.relative(process.cwd(), path.resolve(scanInput.filePath));
112
+ // A path that climbs above the launch directory cannot be source-root-relative by definition,
113
+ // and Code Scanning rejects one that tries. Nor can one on another Windows drive, where the
114
+ // "relative" path comes back absolute. Fall back to the basename, which is no worse than what
115
+ // shipped, rather than emit a URI that is invalid.
116
+ if (relative === "" || path.isAbsolute(relative) || relative.split(path.sep)[0] === "..") {
95
117
  return path.basename(scanInput.filePath);
96
- return LOCKFILE_NAMES[scanInput.source] ?? "lockfile";
118
+ }
119
+ // A SARIF location is a URI, so each directory name is percent-encoded: unencoded, a "#" would
120
+ // start a fragment and cut the path short, and a literal "%41" would decode to another name. The
121
+ // lockfile basenames the old code emitted never needed this; directory names can. Splitting on
122
+ // path.sep also turns Windows backslashes into the forward slashes a URI requires.
123
+ return relative.split(path.sep).map(encodeURIComponent).join("/");
97
124
  }
98
125
  function dedupeSkipped(skipped) {
99
126
  const seen = new Set();
@@ -107,8 +134,24 @@ function dedupeSkipped(skipped) {
107
134
  }
108
135
  return out;
109
136
  }
137
+ /** Rule for a finding whose advisory details could not be retrieved. Without it such a finding
138
+ * has no advisory id to report under and drops out of the log, and an empty upload is how Code
139
+ * Scanning learns that open alerts are fixed (#1362). */
140
+ export const ADVISORY_DETAIL_UNAVAILABLE_RULE_ID = "CVE-LITE-ADVISORY-DETAIL-UNAVAILABLE";
141
+ function buildAdvisoryDetailUnavailableRule() {
142
+ return {
143
+ id: ADVISORY_DETAIL_UNAVAILABLE_RULE_ID,
144
+ name: "Advisory details could not be retrieved",
145
+ shortDescription: { text: "Advisory details could not be retrieved" },
146
+ fullDescription: {
147
+ text: "This package matched a known advisory, but the advisory's details could not be retrieved during the scan, so it cannot be reported under its advisory id. Re-run the scan to retry.",
148
+ },
149
+ helpUri: "https://owasp.org/cve-lite-cli/",
150
+ properties: { tags: ["security", "dependency"] },
151
+ };
152
+ }
110
153
  export function buildSarifOutput(findings, lockfileUri, version, plan, options = {}) {
111
- const { overrideFindings, maintenanceFindings, licenseFindings, overrideSkipped } = options;
154
+ const { overrideFindings, maintenanceFindings, licenseFindings, overrideSkipped, completeness } = options;
112
155
  // Accepted findings go through the SAME construction as actionable ones and differ only by
113
156
  // carrying `suppressions`. Duplicating the loop instead is how the two would drift.
114
157
  const taggedFindings = [
@@ -118,6 +161,10 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
118
161
  const ruleMap = new Map();
119
162
  const ruleIndexMap = new Map();
120
163
  const results = [];
164
+ // Re-running an offline scan re-reads the same local database, so it has to be refreshed first.
165
+ const detailRetryStep = completeness?.diagnostics.some((d) => d.code === "OSV_DETAIL_OFFLINE_MISSING")
166
+ ? "Run cve-lite advisories sync, then re-run the scan."
167
+ : "Re-run the scan to retry.";
121
168
  for (const { finding, accepted } of taggedFindings) {
122
169
  const level = severityToSarifLevel(finding.severity);
123
170
  const action = getRecommendedAction(finding);
@@ -132,10 +179,20 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
132
179
  region: { startLine: 1 },
133
180
  },
134
181
  };
135
- const ruleIds = finding.cveAliases.length > 0
182
+ const advisoryIds = finding.cveAliases.length > 0
136
183
  ? finding.cveAliases
137
184
  : finding.vulnerabilities.map(v => v.id);
185
+ // Advisories whose details failed to load are reported too, whether or not others resolved.
186
+ const unresolvedIds = finding.unresolvedAdvisoryIds ?? [];
187
+ const ruleIds = advisoryIds.length === 0 || unresolvedIds.length > 0
188
+ ? [...advisoryIds, ADVISORY_DETAIL_UNAVAILABLE_RULE_ID]
189
+ : advisoryIds;
138
190
  for (const ruleId of ruleIds) {
191
+ const detailUnavailable = ruleId === ADVISORY_DETAIL_UNAVAILABLE_RULE_ID;
192
+ if (!ruleMap.has(ruleId) && detailUnavailable) {
193
+ ruleIndexMap.set(ruleId, ruleMap.size);
194
+ ruleMap.set(ruleId, buildAdvisoryDetailUnavailableRule());
195
+ }
139
196
  if (!ruleMap.has(ruleId)) {
140
197
  // ruleMap.size before insertion = 0-based index of the new entry
141
198
  ruleIndexMap.set(ruleId, ruleMap.size);
@@ -154,26 +211,29 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
154
211
  properties: { tags: ["security", "dependency"] },
155
212
  });
156
213
  }
214
+ // Fix metadata describes the resolved advisories, so it stays off the unavailable result.
157
215
  const resultProperties = {};
158
- if (cooldown)
159
- resultProperties.cooldownWarning = cooldown;
160
- if (finding.firstFixedVersion)
161
- resultProperties.advisoryFixVersion = finding.firstFixedVersion;
162
- const recommended = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
163
- if (recommended)
164
- resultProperties.recommendedFixVersion = recommended;
165
- if (finding.fixVersionPublishedAt)
166
- resultProperties.fixVersionPublishedAt = finding.fixVersionPublishedAt;
167
- if (finding.validatedTargetScannedVersions != null) {
168
- resultProperties.versionsScanned = finding.validatedTargetScannedVersions;
169
- }
170
- if (finding.validatedTargetKnownVulnerableVersions != null) {
171
- resultProperties.versionsStillVulnerable = finding.validatedTargetKnownVulnerableVersions;
216
+ if (!detailUnavailable) {
217
+ if (cooldown)
218
+ resultProperties.cooldownWarning = cooldown;
219
+ if (finding.firstFixedVersion)
220
+ resultProperties.advisoryFixVersion = finding.firstFixedVersion;
221
+ const recommended = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
222
+ if (recommended)
223
+ resultProperties.recommendedFixVersion = recommended;
224
+ if (finding.fixVersionPublishedAt)
225
+ resultProperties.fixVersionPublishedAt = finding.fixVersionPublishedAt;
226
+ if (finding.validatedTargetScannedVersions != null) {
227
+ resultProperties.versionsScanned = finding.validatedTargetScannedVersions;
228
+ }
229
+ if (finding.validatedTargetKnownVulnerableVersions != null) {
230
+ resultProperties.versionsStillVulnerable = finding.validatedTargetKnownVulnerableVersions;
231
+ }
232
+ if (planTarget?.childPackage)
233
+ resultProperties.childPackage = planTarget.childPackage;
234
+ if (planTarget?.childTargetVersion)
235
+ resultProperties.childTargetVersion = planTarget.childTargetVersion;
172
236
  }
173
- if (planTarget?.childPackage)
174
- resultProperties.childPackage = planTarget.childPackage;
175
- if (planTarget?.childTargetVersion)
176
- resultProperties.childTargetVersion = planTarget.childTargetVersion;
177
237
  results.push({
178
238
  ruleId,
179
239
  ruleIndex: ruleIndexMap.get(ruleId),
@@ -186,10 +246,13 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
186
246
  }],
187
247
  }
188
248
  : {}),
189
- level,
249
+ // Severity is unknown without the advisory details, so the alert is raised at warning.
250
+ level: detailUnavailable ? "warning" : level,
190
251
  message: {
191
- text: `${finding.pkg.name}@${finding.pkg.version} is vulnerable (${finding.severity}). ${action}`
192
- + (cooldown ? ` Release cooldown: ${formatCooldownWarning(cooldown)}` : ""),
252
+ text: detailUnavailable
253
+ ? `${finding.pkg.name}@${finding.pkg.version} matched ${unresolvedIds.length > 0 ? unresolvedIds.join(", ") : "a known advisory"}, but the details could not be retrieved during this scan. ${detailRetryStep}`
254
+ : `${finding.pkg.name}@${finding.pkg.version} is vulnerable (${finding.severity}). ${action}`
255
+ + (cooldown ? ` Release cooldown: ${formatCooldownWarning(cooldown)}` : ""),
193
256
  },
194
257
  locations: [location],
195
258
  partialFingerprints: {
@@ -222,6 +285,24 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
222
285
  // One entry per (rule, reason), de-duplicated so the driver's notification
223
286
  // descriptors and the invocation's notifications cannot disagree.
224
287
  const skippedNotifications = dedupeSkipped(overrideSkipped ?? []);
288
+ const diagnostics = completeness?.diagnostics ?? [];
289
+ const executionSuccessful = !getCompletenessImpact(completeness).hasDetectionGap;
290
+ const notificationDescriptorIds = [
291
+ ...new Set([...skippedNotifications.map((n) => n.ruleId), ...diagnostics.map((d) => d.code)]),
292
+ ];
293
+ const toolExecutionNotifications = [
294
+ ...diagnostics.map((diagnostic) => ({
295
+ level: diagnostic.severity,
296
+ message: { text: diagnostic.message },
297
+ descriptor: { id: diagnostic.code },
298
+ })),
299
+ ...skippedNotifications.map((entry) => ({
300
+ level: "warning",
301
+ message: { text: `${entry.ruleId} did not run: ${entry.reason}` },
302
+ descriptor: { id: entry.ruleId },
303
+ })),
304
+ ];
305
+ const diagnosticCodes = new Set(diagnostics.map((d) => d.code));
225
306
  return {
226
307
  $schema: SARIF_SCHEMA,
227
308
  version: "2.1.0",
@@ -236,11 +317,15 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
236
317
  // Deduped by rule id, separately from the notification list. The notifications
237
318
  // are per (rule, reason) and one rule can be skipped for two reasons, but
238
319
  // reportingDescriptor.id must be unique within its array.
239
- ...(skippedNotifications.length > 0
320
+ ...(notificationDescriptorIds.length > 0
240
321
  ? {
241
- notifications: [...new Set(skippedNotifications.map((n) => n.ruleId))].map((id) => ({
322
+ notifications: notificationDescriptorIds.map((id) => ({
242
323
  id,
243
- shortDescription: { text: `${id} did not run during this scan` },
324
+ shortDescription: {
325
+ text: diagnosticCodes.has(id)
326
+ ? `${id}: the scan could not complete this step`
327
+ : `${id} did not run during this scan`,
328
+ },
244
329
  })),
245
330
  }
246
331
  : {}),
@@ -252,21 +337,11 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
252
337
  // toolExecutionNotifications rather than being silently omitted, so a machine
253
338
  // reading this file can tell an incomplete audit from a clean one.
254
339
  //
255
- // Emitted only when there is something to report, so a plain scan's SARIF is
256
- // unchanged by #1222. Each descriptor is declared on the driver above.
257
- ...(skippedNotifications.length > 0
258
- ? {
259
- invocations: [
260
- {
261
- executionSuccessful: true,
262
- toolExecutionNotifications: skippedNotifications.map((entry) => ({
263
- level: "warning",
264
- message: { text: `${entry.ruleId} did not run: ${entry.reason}` },
265
- descriptor: { id: entry.ruleId },
266
- })),
267
- },
268
- ],
269
- }
340
+ // Completeness diagnostics travel the same way (#1362), and a detection gap marks the
341
+ // run unsuccessful. Emitted only when there is something to report, so a plain scan's
342
+ // SARIF is unchanged. Each descriptor is declared on the driver above.
343
+ ...(toolExecutionNotifications.length > 0
344
+ ? { invocations: [{ executionSuccessful, toolExecutionNotifications }] }
270
345
  : {}),
271
346
  artifacts: [
272
347
  { location: { uri: lockfileUri, uriBaseId: "%SRCROOT%" } },
@@ -276,18 +351,26 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, options =
276
351
  };
277
352
  }
278
353
  export function writeSarifReport(findings, lockfileUri, plan, options = {}) {
279
- const { outputDir: outputDirOption, ...sarifOptions } = options;
354
+ const { outputDir: outputDirOption, filename: customFilename, ...sarifOptions } = options;
355
+ if (isOutputStdout(customFilename) || isOutputStdout(outputDirOption)) {
356
+ const sarif = buildSarifOutput(findings, lockfileUri, getCliVersion(), plan, sarifOptions);
357
+ process.stdout.write(JSON.stringify(sarif, null, 2) + "\n");
358
+ return "-";
359
+ }
280
360
  const outputDir = outputDirOption ?? process.cwd();
281
361
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
282
- const filename = `cve-lite-scan-${ts}.sarif`;
362
+ const filename = customFilename ?? `cve-lite-scan-${ts}.sarif`;
283
363
  const outputPath = path.join(outputDir, filename);
284
364
  const sarif = buildSarifOutput(findings, lockfileUri, getCliVersion(), plan, sarifOptions);
365
+ const tempFilename = `.${path.basename(filename)}.${randomUUID()}.tmp`;
366
+ const tempPath = path.join(outputDir, path.dirname(filename), tempFilename);
285
367
  try {
286
- fs.writeFileSync(outputPath, JSON.stringify(sarif, null, 2));
368
+ fs.writeFileSync(tempPath, JSON.stringify(sarif, null, 2));
369
+ fs.renameSync(tempPath, outputPath);
287
370
  }
288
371
  catch (err) {
289
372
  try {
290
- fs.rmSync(outputPath, { force: true });
373
+ fs.rmSync(tempPath, { force: true });
291
374
  }
292
375
  catch { /* best-effort cleanup */ }
293
376
  throw new Error(`Failed to write SARIF report to ${outputPath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
@@ -2,9 +2,8 @@ import { loadBunLockGraph } from "../parsers/bun-lock-graph.js";
2
2
  import { loadNpmLockGraph } from "../parsers/npm-lock-graph.js";
3
3
  import { loadPnpmLockGraph } from "../parsers/pnpm-lock-graph.js";
4
4
  import { loadYarnLockGraph } from "../parsers/yarn-lock-graph.js";
5
- function packageKey(name, version) {
6
- return `${name}@${version}`;
7
- }
5
+ import { isNpmLockSource } from "../utils/package-manager-source.js";
6
+ import { packageInstanceKey, registryPackageName } from "../utils/package-identity.js";
8
7
  /** Several graph nodes collapse to one name@version, so edges are deduplicated. */
9
8
  function addEdge(edges, seen, child, parent) {
10
9
  const key = `${child} ${parent ?? ""}`;
@@ -22,7 +21,7 @@ function loadEdgeGraph(scanInput) {
22
21
  if (!scanInput.filePath)
23
22
  return null;
24
23
  try {
25
- if (scanInput.source === "package-lock") {
24
+ if (isNpmLockSource(scanInput.source)) {
26
25
  return loadNpmLockGraph(scanInput.filePath, { includePaths: false });
27
26
  }
28
27
  if (scanInput.source === "pnpm-lock") {
@@ -41,20 +40,24 @@ function loadEdgeGraph(scanInput) {
41
40
  }
42
41
  return null;
43
42
  }
44
- export function resolveDependencyEdges(scanInput, allPackages) {
43
+ export function resolveDependencyEdgesResult(scanInput, allPackages) {
45
44
  const graph = loadEdgeGraph(scanInput);
46
45
  if (!graph)
47
- return [];
46
+ return { edges: [], graphLoaded: false };
48
47
  // Only packages present in the document can be referenced. `--prod-only` and
49
48
  // similar filters shrink this set without shrinking the graph, and an edge to
50
49
  // 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)));
50
+ const included = new Set(allPackages.map(packageInstanceKey));
52
51
  const edges = [];
53
52
  const seen = new Set();
54
53
  for (const pkg of allPackages) {
55
- const childKey = packageKey(pkg.name, pkg.version);
54
+ const childKey = packageInstanceKey(pkg);
56
55
  let anchored = false;
57
56
  for (const nodeId of graph.nodeIdsFor(pkg.name, pkg.version)) {
57
+ const node = graph.getNode(nodeId);
58
+ if (!node || registryPackageName(node) !== registryPackageName(pkg)) {
59
+ continue;
60
+ }
58
61
  for (const parentNodeId of graph.parentsFor(nodeId)) {
59
62
  const parentNode = graph.getNode(parentNodeId);
60
63
  // Workspace members are symlinked rather than installed, so the graph
@@ -62,7 +65,7 @@ export function resolveDependencyEdges(scanInput, allPackages) {
62
65
  // package set. They cannot be referenced as SPDX packages.
63
66
  if (!parentNode?.version)
64
67
  continue;
65
- const parentKey = packageKey(parentNode.name, parentNode.version);
68
+ const parentKey = packageInstanceKey({ ...parentNode, version: parentNode.version });
66
69
  if (parentKey === childKey)
67
70
  continue;
68
71
  // Referencing a package absent from the document would be a dangling
@@ -82,5 +85,8 @@ export function resolveDependencyEdges(scanInput, allPackages) {
82
85
  if (!anchored)
83
86
  addEdge(edges, seen, childKey, null);
84
87
  }
85
- return edges;
88
+ return { edges, graphLoaded: true };
89
+ }
90
+ export function resolveDependencyEdges(scanInput, allPackages) {
91
+ return resolveDependencyEdgesResult(scanInput, allPackages).edges;
86
92
  }
@@ -1,22 +1,30 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { displayOutputPath } from "./output-dir.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { displayOutputPath, isOutputStdout } from "./output-dir.js";
4
5
  /**
5
6
  * Writes an SBOM document to a timestamped file in the output directory,
6
7
  * which defaults to the working directory.
7
8
  *
8
- * A partial file left behind by a failed write would look like a valid SBOM to
9
- * whatever consumes it next, so the partial output is removed before the error
10
- * propagates.
9
+ * Writes via a temporary file and atomically renames to the destination,
10
+ * so pre-existing reports at the destination are never truncated or removed
11
+ * on write failure.
11
12
  */
12
13
  export function writeSbomFile(filename, document, label, outputDir = process.cwd()) {
14
+ if (isOutputStdout(filename) || isOutputStdout(outputDir)) {
15
+ process.stdout.write(JSON.stringify(document, null, 2) + "\n");
16
+ return "-";
17
+ }
13
18
  const outputPath = path.join(outputDir, filename);
19
+ const tempFilename = `.${path.basename(filename)}.${randomUUID()}.tmp`;
20
+ const tempPath = path.join(outputDir, path.dirname(filename), tempFilename);
14
21
  try {
15
- fs.writeFileSync(outputPath, JSON.stringify(document, null, 2));
22
+ fs.writeFileSync(tempPath, JSON.stringify(document, null, 2));
23
+ fs.renameSync(tempPath, outputPath);
16
24
  }
17
25
  catch (err) {
18
26
  try {
19
- fs.rmSync(outputPath, { force: true });
27
+ fs.rmSync(tempPath, { force: true });
20
28
  }
21
29
  catch { /* best-effort cleanup */ }
22
30
  throw new Error(`Failed to write ${label} to ${outputPath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
@@ -1,20 +1,31 @@
1
+ import path from "node:path";
1
2
  import { serializeFinding } from "./formatters.js";
2
3
  import { overrideFindingsToJson } from "./override-findings-json.js";
3
4
  import { maintenanceFindingsToJson } from "./maintenance-findings-json.js";
4
5
  import { serializeLicenseFindings } from "./license-findings-json.js";
5
6
  import { aggregateMultiFolderCompleteness } from "../scan/completeness.js";
6
7
  import { summarizeEffectiveOptions } from "../utils/effective-options.js";
8
+ /** A shared artefact must identify a project without exposing its host path. */
9
+ function artifactPathName(value) {
10
+ const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
11
+ return normalized === "" ? "." : path.posix.basename(normalized);
12
+ }
7
13
  /**
8
14
  * Single-folder `--json` payload. HTML `report.json` reuses this so both
9
15
  * artifacts share one schema.
10
16
  */
11
17
  export function buildScanJson(input) {
12
18
  const payload = {
13
- projectPath: input.projectPath,
19
+ projectPath: artifactPathName(input.projectPath),
14
20
  mode: input.scanInput.mode,
15
21
  source: input.scanInput.source,
16
22
  ...(input.registry
17
- ? { registry: { registry: input.registry.registry, sourceFile: input.registry.sourceFile } }
23
+ ? {
24
+ registry: {
25
+ registry: input.registry.registry,
26
+ sourceFile: input.registry.sourceFile ? artifactPathName(input.registry.sourceFile) : null,
27
+ },
28
+ }
18
29
  : {}),
19
30
  packageCount: input.scanInput.packages.length,
20
31
  findingCount: input.findings.length,
@@ -58,9 +69,10 @@ export function buildScanJson(input) {
58
69
  export function buildMultiFolderScanJson(params) {
59
70
  const aggregatedCompleteness = aggregateMultiFolderCompleteness(params.results);
60
71
  const findings = params.results.flatMap(r => r.sorted.map(f => ({ ...serializeFinding(f, r.suggestedFixCommands), subfolder: r.subfolder })));
72
+ const acceptedFindings = params.results.flatMap(r => (r.acceptedFindings ?? []).map(f => ({ ...serializeFinding(f, r.suggestedFixCommands), subfolder: r.subfolder })));
61
73
  return {
62
74
  multiFolder: true,
63
- projectPath: params.projectPath,
75
+ projectPath: artifactPathName(params.projectPath),
64
76
  folders: params.results.map(r => r.subfolder),
65
77
  findingCount: findings.length,
66
78
  status: aggregatedCompleteness.complete ? "ok" : "partial",
@@ -68,6 +80,12 @@ export function buildMultiFolderScanJson(params) {
68
80
  diagnostics: aggregatedCompleteness.diagnostics,
69
81
  warnings: params.results.flatMap(r => r.scanInput.warnings),
70
82
  findings,
83
+ ...(acceptedFindings.length > 0
84
+ ? {
85
+ acceptedFindingCount: acceptedFindings.length,
86
+ acceptedFindings,
87
+ }
88
+ : {}),
71
89
  ...(params.includeOverrides
72
90
  ? {
73
91
  overrideFindings: params.results.flatMap(r => r.overrideFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
@@ -1,11 +1,24 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { chalk } from "../utils/chalk.js";
2
3
  import { findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
3
4
  import { getRecommendedAction } from "./formatters.js";
4
- import { buildPurl } from "../utils/purl.js";
5
+ import { purlForSbom } from "../utils/purl.js";
6
+ import { MAX_PATHS_PER_PACKAGE } from "../parsers/utils.js";
5
7
  import { getCliVersion } from "../utils/version-info.js";
6
8
  import { sbomTimestamp, writeSbomFile } from "./sbom-file.js";
9
+ import { packageInstanceKey, registryPackageName } from "../utils/package-identity.js";
7
10
  /**
8
- * SPDX's explicit marker for "we looked and cannot say". Preferred over
11
+ * Emitted when dependency edges are reconstructed from PackageRef.paths
12
+ * which were subject to the per-package path cap.
13
+ */
14
+ export const SBOM_FALLBACK_CAP_WARNING = "⚠ SPDX SBOM: dependency relationships were rebuilt from recorded paths, which are capped at five per package, so some may be missing.";
15
+ /**
16
+ * Document-level comment added to the SPDX document when the fallback edge
17
+ * builder was used and dependency paths were capped.
18
+ */
19
+ export const SBOM_FALLBACK_CAP_DOCUMENT_NOTE = "Dependency relationships were rebuilt from recorded paths, which are capped at five per package, so some may be missing.";
20
+ /**
21
+ * SPDX's explicit marker for "not determined" or "no assertion made". Preferred over
9
22
  * omitting a field, because omission reads as "not considered".
10
23
  */
11
24
  const NOASSERTION = "NOASSERTION";
@@ -35,10 +48,9 @@ function makeSpdxId(name, version, used) {
35
48
  used.set(base, seen + 1);
36
49
  return `${base}-${seen + 1}`;
37
50
  }
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
- */
51
+ function findingPackageKey(pkg) {
52
+ return `${pkg.ecosystem}\0${packageInstanceKey(pkg)}`;
53
+ }
42
54
  function groupFindingsByPackage(findings) {
43
55
  const byPackage = new Map();
44
56
  for (const finding of findings) {
@@ -47,7 +59,7 @@ function groupFindingsByPackage(findings) {
47
59
  // and annotating it contradicts the real fix, so it is dropped here.
48
60
  if (finding.vulnerabilities.length === 0)
49
61
  continue;
50
- const key = `${finding.pkg.name}@${finding.pkg.version}`;
62
+ const key = findingPackageKey(finding.pkg);
51
63
  const existing = byPackage.get(key);
52
64
  if (existing)
53
65
  existing.push(finding);
@@ -126,10 +138,10 @@ function buildAdvisoryRefs(pkgFindings) {
126
138
  }
127
139
  return refs;
128
140
  }
129
- function buildPackageEntry(pkg, pkgFindings, usedIds, plan, annotator, timestamp) {
141
+ function buildPackageEntry(pkg, pkgFindings, usedIds, plan, annotator, timestamp, purl) {
130
142
  return {
131
143
  SPDXID: makeSpdxId(pkg.name, pkg.version, usedIds),
132
- name: pkg.name,
144
+ name: registryPackageName(pkg),
133
145
  downloadLocation: pkg.resolvedUrl ?? NOASSERTION,
134
146
  // NTIA lists supplier as a minimum element. A lockfile does not record who
135
147
  // published a package, so we assert nothing rather than guess from the name.
@@ -146,7 +158,7 @@ function buildPackageEntry(pkg, pkgFindings, usedIds, plan, annotator, timestamp
146
158
  {
147
159
  referenceCategory: "PACKAGE-MANAGER",
148
160
  referenceType: "purl",
149
- referenceLocator: buildPurl(pkg.name, pkg.version),
161
+ referenceLocator: purl,
150
162
  },
151
163
  ...buildAdvisoryRefs(pkgFindings),
152
164
  ],
@@ -179,12 +191,12 @@ function indexPackagesByPath(entries, rootId) {
179
191
  return index;
180
192
  }
181
193
  /**
182
- * Derives DEPENDENCY_OF relationships from the dependency paths.
194
+ * Derives DEPENDENCY_OF or DEV_DEPENDENCY_OF relationships from the dependency paths.
183
195
  *
184
196
  * NTIA lists dependency relationships among the minimum elements of an SBOM, so
185
197
  * a flat package list is not sufficient for the compliance use case SPDX serves.
186
198
  */
187
- function buildDependencyEdges(entries, index) {
199
+ function buildDependencyEdges(entries, index, rootId) {
188
200
  const edges = [];
189
201
  const seen = new Set();
190
202
  for (const { ref, id } of entries) {
@@ -199,10 +211,11 @@ function buildDependencyEdges(entries, index) {
199
211
  if (seen.has(key))
200
212
  continue;
201
213
  seen.add(key);
214
+ const isDirectDev = Boolean(ref.dev) && rootId !== null && parentId === rootId;
202
215
  edges.push({
203
216
  spdxElementId: id,
204
217
  relatedSpdxElement: parentId,
205
- relationshipType: "DEPENDENCY_OF",
218
+ relationshipType: isDirectDev ? "DEV_DEPENDENCY_OF" : "DEPENDENCY_OF",
206
219
  });
207
220
  }
208
221
  }
@@ -217,10 +230,13 @@ function buildDependencyEdges(entries, index) {
217
230
  */
218
231
  function buildEdgesFromResolved(resolved, entries, rootId) {
219
232
  const idByPackage = new Map();
233
+ const devByPackage = new Map();
220
234
  for (const { ref, id } of entries) {
221
- const key = `${ref.name}@${ref.version}`;
222
- if (!idByPackage.has(key))
235
+ const key = packageInstanceKey(ref);
236
+ if (!idByPackage.has(key)) {
223
237
  idByPackage.set(key, id);
238
+ devByPackage.set(key, ref.dev === true);
239
+ }
224
240
  }
225
241
  const edges = [];
226
242
  const seen = new Set();
@@ -235,10 +251,11 @@ function buildEdgesFromResolved(resolved, entries, rootId) {
235
251
  if (seen.has(key))
236
252
  continue;
237
253
  seen.add(key);
254
+ const isDirectDev = Boolean(devByPackage.get(child)) && (parent === null || (rootId !== null && parentId === rootId));
238
255
  edges.push({
239
256
  spdxElementId: childId,
240
257
  relatedSpdxElement: parentId,
241
- relationshipType: "DEPENDENCY_OF",
258
+ relationshipType: isDirectDev ? "DEV_DEPENDENCY_OF" : "DEPENDENCY_OF",
242
259
  });
243
260
  }
244
261
  return edges;
@@ -260,24 +277,34 @@ export function buildSpdxDocument(allPackages, findings, projectMeta, version, p
260
277
  }
261
278
  const indexed = [];
262
279
  for (const pkg of allPackages) {
263
- const pkgFindings = findingsByPackage.get(`${pkg.name}@${pkg.version}`) ?? [];
264
- const entry = buildPackageEntry(pkg, pkgFindings, usedIds, plan, annotator, timestamp);
280
+ const purl = purlForSbom(pkg);
281
+ if (!purl)
282
+ continue;
283
+ const pkgFindings = findingsByPackage.get(findingPackageKey(pkg)) ?? [];
284
+ const entry = buildPackageEntry(pkg, pkgFindings, usedIds, plan, annotator, timestamp, purl);
265
285
  packages.push(entry);
266
286
  indexed.push({ ref: pkg, id: entry.SPDXID });
267
287
  }
268
288
  // The graph describes the tree, not the findings, so it is inventory data and
269
289
  // 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.
290
+ // Checked by length, not truthiness: an empty array is truthy.
291
+ const isFallback = !options.dependencyEdges || options.dependencyEdges.length === 0;
292
+ const graphFailed = options.graphFailed ?? isFallback;
293
+ const pathCapApplies = allPackages.some(pkg => (pkg.paths?.length ?? 0) >= MAX_PATHS_PER_PACKAGE);
294
+ const shouldWarnFallback = isFallback && graphFailed && pathCapApplies;
295
+ if (shouldWarnFallback) {
296
+ options.onWarning?.(SBOM_FALLBACK_CAP_WARNING);
297
+ }
272
298
  relationships.push(...(options.dependencyEdges?.length
273
299
  ? buildEdgesFromResolved(options.dependencyEdges, indexed, root?.pkg.SPDXID ?? null)
274
- : buildDependencyEdges(indexed, indexPackagesByPath(indexed, root?.pkg.SPDXID ?? null))));
300
+ : buildDependencyEdges(indexed, indexPackagesByPath(indexed, root?.pkg.SPDXID ?? null), root?.pkg.SPDXID ?? null)));
275
301
  return {
276
302
  spdxVersion: "SPDX-2.3",
277
303
  SPDXID: "SPDXRef-DOCUMENT",
278
304
  name,
279
305
  dataLicense: "CC0-1.0",
280
306
  documentNamespace: `https://owasp.org/cve-lite-cli/spdxdocs/${encodeURIComponent(name)}-${randomUUID()}`,
307
+ ...(shouldWarnFallback ? { comment: SBOM_FALLBACK_CAP_DOCUMENT_NOTE } : {}),
281
308
  creationInfo: {
282
309
  created: timestamp,
283
310
  creators: [annotator],
@@ -287,7 +314,18 @@ export function buildSpdxDocument(allPackages, findings, projectMeta, version, p
287
314
  };
288
315
  }
289
316
  export function writeSpdxReport(allPackages, findings, plan, projectMeta, options = {}, outputDir) {
290
- const filename = `cve-lite-scan-${sbomTimestamp()}.spdx.json`;
291
- const doc = buildSpdxDocument(allPackages, findings, projectMeta, getCliVersion(), plan, options);
317
+ const filename = options.filename ?? `cve-lite-scan-${sbomTimestamp()}.spdx.json`;
318
+ const effectiveOptions = {
319
+ ...options,
320
+ onWarning: (msg) => {
321
+ if (options.onWarning) {
322
+ options.onWarning(msg);
323
+ }
324
+ else {
325
+ console.warn(chalk.yellow(msg));
326
+ }
327
+ },
328
+ };
329
+ const doc = buildSpdxDocument(allPackages, findings, projectMeta, getCliVersion(), plan, effectiveOptions);
292
330
  return writeSbomFile(filename, doc, "SPDX SBOM", outputDir);
293
331
  }
@@ -1,7 +1,8 @@
1
1
  import process from "node:process";
2
2
  import { chalk } from "../utils/chalk.js";
3
+ import { isOutputStdout } from "./output-dir.js";
3
4
  export function createSpinner(initialMessage, options) {
4
- const enabled = Boolean(process.stdout.isTTY) && !options?.json;
5
+ const enabled = Boolean(process.stdout.isTTY) && !options?.json && !isOutputStdout(options?.output);
5
6
  if (!enabled) {
6
7
  return {
7
8
  update: () => { },