cve-lite-cli 1.39.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 (82) hide show
  1. package/README.md +28 -22
  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 +5 -3
  10. package/dist/cli/validate.js +23 -1
  11. package/dist/constants.js +15 -28
  12. package/dist/index.js +8 -3
  13. package/dist/osv/severity.js +1 -1
  14. package/dist/output/cyclonedx.js +24 -15
  15. package/dist/output/debug.js +68 -18
  16. package/dist/output/formatters.js +35 -7
  17. package/dist/output/html-reporter.js +68 -12
  18. package/dist/output/multi-folder-html-reporter.js +71 -11
  19. package/dist/output/output-dir.js +193 -7
  20. package/dist/output/override-findings-html.js +3 -6
  21. package/dist/output/override-findings-terminal.js +7 -12
  22. package/dist/output/override-fix-command.js +13 -0
  23. package/dist/output/printers.js +27 -12
  24. package/dist/output/sarif.js +168 -57
  25. package/dist/output/sbom-dependency-edges.js +16 -10
  26. package/dist/output/sbom-file.js +14 -6
  27. package/dist/output/scan-json.js +46 -3
  28. package/dist/output/spdx.js +61 -23
  29. package/dist/output/spinner.js +2 -1
  30. package/dist/output/write-outputs.js +143 -41
  31. package/dist/overrides/context-builder.js +23 -70
  32. package/dist/overrides/parsing/registry.js +1 -1
  33. package/dist/parsers/bun-lock.js +1 -2
  34. package/dist/parsers/index.js +22 -1
  35. package/dist/parsers/npm-lock-graph.js +39 -1
  36. package/dist/parsers/package-lock.js +25 -5
  37. package/dist/parsers/pnpm-lock.js +26 -12
  38. package/dist/parsers/utils.js +5 -3
  39. package/dist/parsers/yarn-lock-graph.js +5 -2
  40. package/dist/parsers/yarn-lock.js +1 -2
  41. package/dist/remediation/fix-commands.js +140 -50
  42. package/dist/remediation/npm-registry.js +56 -7
  43. package/dist/remediation/npm-transitive-graph.js +30 -72
  44. package/dist/remediation/npm-transitive-resolution.js +35 -107
  45. package/dist/remediation/parent-candidate-resolver.js +65 -0
  46. package/dist/remediation/parent-upgrade-blockers.js +51 -0
  47. package/dist/remediation/parent-upgrade.js +11 -116
  48. package/dist/remediation/registry-parent-ranges.js +21 -0
  49. package/dist/remediation/transitive-chain-resolver.js +3 -3
  50. package/dist/scan/completeness.js +17 -11
  51. package/dist/scan/multi-folder-scan.js +154 -59
  52. package/dist/scan/override-audit.js +11 -1
  53. package/dist/scan/single-scan.js +123 -67
  54. package/dist/scanner.js +288 -66
  55. package/dist/skills/content.js +12 -12
  56. package/dist/usage/scanner.js +19 -8
  57. package/dist/utils/array.js +11 -3
  58. package/dist/utils/contextual-signals.js +1 -1
  59. package/dist/utils/debug-bundle.js +118 -0
  60. package/dist/utils/debug-project.js +102 -0
  61. package/dist/utils/debug-redaction.js +117 -0
  62. package/dist/utils/effective-options.js +55 -0
  63. package/dist/utils/file.js +2 -1
  64. package/dist/utils/finding.js +1 -1
  65. package/dist/utils/fix-runner.js +98 -15
  66. package/dist/utils/import-type-queries.js +322 -0
  67. package/dist/utils/network.js +14 -10
  68. package/dist/utils/npm-lockfile.js +12 -0
  69. package/dist/utils/osv-fetch.js +70 -0
  70. package/dist/utils/package-identity.js +43 -0
  71. package/dist/utils/package-manager-source.js +24 -0
  72. package/dist/utils/purl.js +37 -0
  73. package/dist/utils/registry-config.js +129 -0
  74. package/dist/utils/severity.js +8 -0
  75. package/dist/utils/string.js +8 -0
  76. package/dist/utils/validate-url.js +4 -4
  77. package/dist/utils/version.js +47 -8
  78. package/dist/utils/versions/osv-range.js +191 -0
  79. package/dist/utils/versions/pep440.js +246 -0
  80. package/dist/utils/versions/scheme.js +10 -0
  81. package/dist/utils/vuln.js +75 -0
  82. package/package.json +3 -2
@@ -1,14 +1,32 @@
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";
14
+ /**
15
+ * Attribution leading the rule help, so an alert in Code Scanning is
16
+ * recognisably from this tool rather than from whichever scanner the reader
17
+ * assumed.
18
+ *
19
+ * ⚠ Deliberately a markdown link rather than the logo image the GitHub App
20
+ * puts on PR comments. This help text renders inside the ADOPTER's security
21
+ * dashboard, not ours, which makes an image the wrong shape twice over: it
22
+ * would be hot-linked from a moving branch, so renaming the asset later breaks
23
+ * the image in every historical alert they hold, and it would fetch 217KB from
24
+ * our repository every time one of their engineers opens an alert. A link
25
+ * carries the same attribution and costs them nothing.
26
+ */
27
+ const PROJECT_URL = "https://github.com/OWASP/cve-lite-cli";
28
+ const MARKDOWN_ATTRIBUTION = `Reported by [CVE Lite CLI](${PROJECT_URL})`;
29
+ const TEXT_ATTRIBUTION = `Reported by CVE Lite CLI - ${PROJECT_URL}`;
12
30
  const SARIF_SCHEMA = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json";
13
31
  const LOCKFILE_NAMES = {
14
32
  "package-lock": "package-lock.json",
@@ -44,7 +62,7 @@ function buildRuleHelp(vuln, depPath, action) {
44
62
  const rawCweIds = dbSpecific?.cwe_ids;
45
63
  const cweIds = Array.isArray(rawCweIds) ? rawCweIds : null;
46
64
  const range = extractAffectedRange(vuln);
47
- const textParts = [`Vulnerability: ${title}`];
65
+ const textParts = [TEXT_ATTRIBUTION, "", `Vulnerability: ${title}`];
48
66
  if (body)
49
67
  textParts.push("", body);
50
68
  if (cvssScore)
@@ -58,7 +76,7 @@ function buildRuleHelp(vuln, depPath, action) {
58
76
  if (depPath)
59
77
  textParts.push("", `Dependency path: ${depPath}`);
60
78
  textParts.push("", `Fix: ${action}`);
61
- const mdParts = [`## ${title}`];
79
+ const mdParts = [MARKDOWN_ATTRIBUTION, "", `## ${title}`];
62
80
  if (body)
63
81
  mdParts.push("", body);
64
82
  if (cvssScore)
@@ -75,9 +93,34 @@ function buildRuleHelp(vuln, depPath, action) {
75
93
  return { text: textParts.join("\n"), markdown: mdParts.join("\n") };
76
94
  }
77
95
  export function deriveLockfileUri(scanInput) {
78
- 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] === "..") {
79
117
  return path.basename(scanInput.filePath);
80
- 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("/");
81
124
  }
82
125
  function dedupeSkipped(skipped) {
83
126
  const seen = new Set();
@@ -91,16 +134,38 @@ function dedupeSkipped(skipped) {
91
134
  }
92
135
  return out;
93
136
  }
94
- export function buildSarifOutput(findings, lockfileUri, version, plan, overrideFindings, maintenanceFindings, licenseFindings,
95
- // NOTE: this parameter list is too long and wants an options object, tracked as #1244.
96
- // Kept positional here so #1222 does not also rewrite every call site. It is why the
97
- // new parameter sits last in both functions even though `writeSarifReport` already has
98
- // a defaulted `outputDir` ahead of it.
99
- overrideSkipped) {
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
+ }
153
+ export function buildSarifOutput(findings, lockfileUri, version, plan, options = {}) {
154
+ const { overrideFindings, maintenanceFindings, licenseFindings, overrideSkipped, completeness } = options;
155
+ // Accepted findings go through the SAME construction as actionable ones and differ only by
156
+ // carrying `suppressions`. Duplicating the loop instead is how the two would drift.
157
+ const taggedFindings = [
158
+ ...findings.map(finding => ({ finding, accepted: false })),
159
+ ...(options.acceptedFindings ?? []).map(finding => ({ finding, accepted: true })),
160
+ ];
100
161
  const ruleMap = new Map();
101
162
  const ruleIndexMap = new Map();
102
163
  const results = [];
103
- for (const finding of findings) {
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.";
168
+ for (const { finding, accepted } of taggedFindings) {
104
169
  const level = severityToSarifLevel(finding.severity);
105
170
  const action = getRecommendedAction(finding);
106
171
  // If the recommended fix for this finding lands on a version inside the
@@ -114,10 +179,20 @@ overrideSkipped) {
114
179
  region: { startLine: 1 },
115
180
  },
116
181
  };
117
- const ruleIds = finding.cveAliases.length > 0
182
+ const advisoryIds = finding.cveAliases.length > 0
118
183
  ? finding.cveAliases
119
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;
120
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
+ }
121
196
  if (!ruleMap.has(ruleId)) {
122
197
  // ruleMap.size before insertion = 0-based index of the new entry
123
198
  ruleIndexMap.set(ruleId, ruleMap.size);
@@ -136,34 +211,48 @@ overrideSkipped) {
136
211
  properties: { tags: ["security", "dependency"] },
137
212
  });
138
213
  }
214
+ // Fix metadata describes the resolved advisories, so it stays off the unavailable result.
139
215
  const resultProperties = {};
140
- if (cooldown)
141
- resultProperties.cooldownWarning = cooldown;
142
- if (finding.firstFixedVersion)
143
- resultProperties.advisoryFixVersion = finding.firstFixedVersion;
144
- const recommended = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
145
- if (recommended)
146
- resultProperties.recommendedFixVersion = recommended;
147
- if (finding.fixVersionPublishedAt)
148
- resultProperties.fixVersionPublishedAt = finding.fixVersionPublishedAt;
149
- if (finding.validatedTargetScannedVersions != null) {
150
- resultProperties.versionsScanned = finding.validatedTargetScannedVersions;
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;
151
236
  }
152
- if (finding.validatedTargetKnownVulnerableVersions != null) {
153
- resultProperties.versionsStillVulnerable = finding.validatedTargetKnownVulnerableVersions;
154
- }
155
- if (planTarget?.childPackage)
156
- resultProperties.childPackage = planTarget.childPackage;
157
- if (planTarget?.childTargetVersion)
158
- resultProperties.childTargetVersion = planTarget.childTargetVersion;
159
237
  results.push({
160
238
  ruleId,
161
239
  ruleIndex: ruleIndexMap.get(ruleId),
162
240
  kind: "open",
163
- level,
241
+ ...(accepted
242
+ ? {
243
+ suppressions: [{
244
+ kind: "external",
245
+ justification: "Accepted by the .cve-lite/baseline.json ratchet baseline.",
246
+ }],
247
+ }
248
+ : {}),
249
+ // Severity is unknown without the advisory details, so the alert is raised at warning.
250
+ level: detailUnavailable ? "warning" : level,
164
251
  message: {
165
- text: `${finding.pkg.name}@${finding.pkg.version} is vulnerable (${finding.severity}). ${action}`
166
- + (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)}` : ""),
167
256
  },
168
257
  locations: [location],
169
258
  partialFingerprints: {
@@ -196,6 +285,24 @@ overrideSkipped) {
196
285
  // One entry per (rule, reason), de-duplicated so the driver's notification
197
286
  // descriptors and the invocation's notifications cannot disagree.
198
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));
199
306
  return {
200
307
  $schema: SARIF_SCHEMA,
201
308
  version: "2.1.0",
@@ -210,11 +317,15 @@ overrideSkipped) {
210
317
  // Deduped by rule id, separately from the notification list. The notifications
211
318
  // are per (rule, reason) and one rule can be skipped for two reasons, but
212
319
  // reportingDescriptor.id must be unique within its array.
213
- ...(skippedNotifications.length > 0
320
+ ...(notificationDescriptorIds.length > 0
214
321
  ? {
215
- notifications: [...new Set(skippedNotifications.map((n) => n.ruleId))].map((id) => ({
322
+ notifications: notificationDescriptorIds.map((id) => ({
216
323
  id,
217
- 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
+ },
218
329
  })),
219
330
  }
220
331
  : {}),
@@ -226,21 +337,11 @@ overrideSkipped) {
226
337
  // toolExecutionNotifications rather than being silently omitted, so a machine
227
338
  // reading this file can tell an incomplete audit from a clean one.
228
339
  //
229
- // Emitted only when there is something to report, so a plain scan's SARIF is
230
- // unchanged by #1222. Each descriptor is declared on the driver above.
231
- ...(skippedNotifications.length > 0
232
- ? {
233
- invocations: [
234
- {
235
- executionSuccessful: true,
236
- toolExecutionNotifications: skippedNotifications.map((entry) => ({
237
- level: "warning",
238
- message: { text: `${entry.ruleId} did not run: ${entry.reason}` },
239
- descriptor: { id: entry.ruleId },
240
- })),
241
- },
242
- ],
243
- }
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 }] }
244
345
  : {}),
245
346
  artifacts: [
246
347
  { location: { uri: lockfileUri, uriBaseId: "%SRCROOT%" } },
@@ -249,17 +350,27 @@ overrideSkipped) {
249
350
  ],
250
351
  };
251
352
  }
252
- export function writeSarifReport(findings, lockfileUri, plan, overrideFindings, maintenanceFindings, licenseFindings, outputDir = process.cwd(), overrideSkipped) {
353
+ export function writeSarifReport(findings, lockfileUri, plan, 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
+ }
360
+ const outputDir = outputDirOption ?? process.cwd();
253
361
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
254
- const filename = `cve-lite-scan-${ts}.sarif`;
362
+ const filename = customFilename ?? `cve-lite-scan-${ts}.sarif`;
255
363
  const outputPath = path.join(outputDir, filename);
256
- const sarif = buildSarifOutput(findings, lockfileUri, getCliVersion(), plan, overrideFindings, maintenanceFindings, licenseFindings, overrideSkipped);
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);
257
367
  try {
258
- fs.writeFileSync(outputPath, JSON.stringify(sarif, null, 2));
368
+ fs.writeFileSync(tempPath, JSON.stringify(sarif, null, 2));
369
+ fs.renameSync(tempPath, outputPath);
259
370
  }
260
371
  catch (err) {
261
372
  try {
262
- fs.rmSync(outputPath, { force: true });
373
+ fs.rmSync(tempPath, { force: true });
263
374
  }
264
375
  catch { /* best-effort cleanup */ }
265
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,17 +1,32 @@
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";
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
+ }
6
13
  /**
7
14
  * Single-folder `--json` payload. HTML `report.json` reuses this so both
8
15
  * artifacts share one schema.
9
16
  */
10
17
  export function buildScanJson(input) {
11
18
  const payload = {
12
- projectPath: input.projectPath,
19
+ projectPath: artifactPathName(input.projectPath),
13
20
  mode: input.scanInput.mode,
14
21
  source: input.scanInput.source,
22
+ ...(input.registry
23
+ ? {
24
+ registry: {
25
+ registry: input.registry.registry,
26
+ sourceFile: input.registry.sourceFile ? artifactPathName(input.registry.sourceFile) : null,
27
+ },
28
+ }
29
+ : {}),
15
30
  packageCount: input.scanInput.packages.length,
16
31
  findingCount: input.findings.length,
17
32
  status: (input.completeness.complete ? "ok" : "partial"),
@@ -22,6 +37,12 @@ export function buildScanJson(input) {
22
37
  warnings: input.scanInput.warnings,
23
38
  skippedDependencies: input.scanInput.skippedDependencies,
24
39
  findings: input.findings.map(finding => serializeFinding(finding, input.suggestedFixCommands)),
40
+ ...(input.acceptedFindings && input.acceptedFindings.length > 0
41
+ ? {
42
+ acceptedFindingCount: input.acceptedFindings.length,
43
+ acceptedFindings: input.acceptedFindings.map(finding => serializeFinding(finding, input.suggestedFixCommands)),
44
+ }
45
+ : {}),
25
46
  };
26
47
  const overridePayload = overrideFindingsToJson(input.overrideFindings ?? [], input.overrideSkipped);
27
48
  const maintenancePayload = maintenanceFindingsToJson(input.maintenanceFindings ?? []);
@@ -31,7 +52,15 @@ export function buildScanJson(input) {
31
52
  ...(input.licenseLimitedToDirectOnly ? { licenseLimitedToDirectOnly: true } : {}),
32
53
  }
33
54
  : {};
34
- return { ...payload, ...overridePayload, ...maintenancePayload, ...licensePayload };
55
+ // Provenance is additive only: nothing existing changes shape (#1296).
56
+ const provenancePayload = input.provenance
57
+ ? {
58
+ cliVersion: input.provenance.cliVersion,
59
+ scannedAt: new Date().toISOString(),
60
+ effectiveOptions: summarizeEffectiveOptions(input.provenance.options),
61
+ }
62
+ : {};
63
+ return { ...payload, ...overridePayload, ...maintenancePayload, ...licensePayload, ...provenancePayload };
35
64
  }
36
65
  /**
37
66
  * Multi-folder `--json` payload. HTML `report.json` reuses this so both
@@ -40,9 +69,10 @@ export function buildScanJson(input) {
40
69
  export function buildMultiFolderScanJson(params) {
41
70
  const aggregatedCompleteness = aggregateMultiFolderCompleteness(params.results);
42
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 })));
43
73
  return {
44
74
  multiFolder: true,
45
- projectPath: params.projectPath,
75
+ projectPath: artifactPathName(params.projectPath),
46
76
  folders: params.results.map(r => r.subfolder),
47
77
  findingCount: findings.length,
48
78
  status: aggregatedCompleteness.complete ? "ok" : "partial",
@@ -50,6 +80,12 @@ export function buildMultiFolderScanJson(params) {
50
80
  diagnostics: aggregatedCompleteness.diagnostics,
51
81
  warnings: params.results.flatMap(r => r.scanInput.warnings),
52
82
  findings,
83
+ ...(acceptedFindings.length > 0
84
+ ? {
85
+ acceptedFindingCount: acceptedFindings.length,
86
+ acceptedFindings,
87
+ }
88
+ : {}),
53
89
  ...(params.includeOverrides
54
90
  ? {
55
91
  overrideFindings: params.results.flatMap(r => r.overrideFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
@@ -70,5 +106,12 @@ export function buildMultiFolderScanJson(params) {
70
106
  }
71
107
  : {}),
72
108
  scannedAt: new Date().toISOString(),
109
+ // Provenance is additive only: nothing existing changes shape (#1296).
110
+ ...(params.provenance
111
+ ? {
112
+ cliVersion: params.provenance.cliVersion,
113
+ effectiveOptions: summarizeEffectiveOptions(params.provenance.options),
114
+ }
115
+ : {}),
73
116
  };
74
117
  }