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,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: () => { },
@@ -1,13 +1,15 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { chalk } from "../utils/chalk.js";
4
5
  import { writeSarifReport, deriveLockfileUri } from "./sarif.js";
5
6
  import { writeCycloneDxReport } from "./cyclonedx.js";
6
7
  import { writeSpdxReport } from "./spdx.js";
7
- import { resolveDependencyEdges } from "./sbom-dependency-edges.js";
8
+ import { resolveDependencyEdgesResult } from "./sbom-dependency-edges.js";
8
9
  import { resolveSbomFormat } from "../utils/sbom-format.js";
9
10
  import { buildScanJson } from "./scan-json.js";
10
- import { resolveOutputDir, displayOutputPath } from "./output-dir.js";
11
+ import { resolveOutputTarget, displayOutputPath, checkFormatExtensionMismatch, drainStdout } from "./output-dir.js";
12
+ import { getCliVersion } from "../utils/version-info.js";
11
13
  function readProjectMeta(projectPath) {
12
14
  try {
13
15
  const pkgPath = path.join(projectPath, "package.json");
@@ -26,50 +28,150 @@ function readProjectMeta(projectPath) {
26
28
  return null;
27
29
  }
28
30
  }
29
- export async function writeOutputs(options, scanState, scanInput, projectPath) {
30
- const outputDir = resolveOutputDir(options.output);
31
- if (options.json) {
32
- const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
33
- const jsonFilename = `cve-lite-scan-${ts}.json`;
34
- const jsonOutputPath = path.join(outputDir, jsonFilename);
35
- const payload = buildScanJson({
36
- projectPath,
37
- scanInput,
38
- findings: scanState.sorted,
39
- suggestedFixCommands: scanState.suggestedFixCommands,
40
- coverage: scanState.coverage,
41
- completeness: scanState.completeness,
42
- overrideFindings: scanState.overrideFindings,
43
- // Only passed when override checking ran, so `[]` means "ran, nothing skipped" and
44
- // absent means "never audited". An unconditional `[]` collapses those two.
45
- overrideSkipped: scanState.overrideSkipped,
46
- maintenanceFindings: scanState.maintenanceFindings,
47
- licenseFindings: scanState.licenseFindings,
48
- licenseLimitedToDirectOnly: scanState.licenseLimitedToDirectOnly,
31
+ function stageOrWrite(outputDir, customFilename, logLabel, writeFn, stagedOutputs, note, isStdout) {
32
+ if (isStdout) {
33
+ writeFn();
34
+ return;
35
+ }
36
+ if (customFilename) {
37
+ const tempFilename = `.${customFilename}.${randomUUID()}.tmp`;
38
+ const tempPath = path.join(outputDir, tempFilename);
39
+ const destinationPath = path.join(outputDir, customFilename);
40
+ stagedOutputs.push({
41
+ tempPath,
42
+ destinationPath,
43
+ logMessage: `${chalk.gray(logLabel)} ${chalk.cyan(displayOutputPath(destinationPath))}`,
44
+ note,
49
45
  });
50
- fs.writeFileSync(jsonOutputPath, JSON.stringify(payload, null, 2));
51
- console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(displayOutputPath(jsonOutputPath))}`);
46
+ writeFn(tempFilename);
52
47
  }
53
- if (options.sarif) {
54
- const lockfileUri = deriveLockfileUri(scanInput);
55
- const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, scanState.overrideFindings, scanState.maintenanceFindings, scanState.licenseFindings, outputDir, scanState.overrideSkipped);
56
- console.log(`${chalk.gray("SARIF report written to")} ${chalk.cyan(sarifFilename)}`);
48
+ else {
49
+ const writtenPath = writeFn();
50
+ if (writtenPath) {
51
+ console.log(`${chalk.gray(logLabel)} ${chalk.cyan(writtenPath)}`);
52
+ }
53
+ if (note) {
54
+ console.log(note);
55
+ }
57
56
  }
57
+ }
58
+ function warnOnFormatMismatch(customFilename, format) {
59
+ const warning = checkFormatExtensionMismatch(customFilename, format);
60
+ if (warning) {
61
+ console.warn(chalk.yellow(`Warning: ${warning}`));
62
+ }
63
+ }
64
+ export const SPDX_NOASSERTION_LOCKFILE_NOTE = "Note: Package licenses are marked NOASSERTION (not determined) because pnpm, Yarn and Bun lockfiles do not record licenses.";
65
+ function stageJsonOutput(options, scanState, scanInput, projectPath, outputDir, customFilename, stagedOutputs, isStdout) {
66
+ if (!options.json)
67
+ return undefined;
68
+ warnOnFormatMismatch(customFilename, "json");
69
+ const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
70
+ const jsonFilename = customFilename ?? `cve-lite-scan-${ts}.json`;
71
+ const jsonOutputPath = isStdout ? undefined : path.join(outputDir, jsonFilename);
72
+ const payload = buildScanJson({
73
+ projectPath,
74
+ scanInput,
75
+ registry: scanState.registry,
76
+ findings: scanState.sorted,
77
+ acceptedFindings: scanState.acceptedFindings,
78
+ suggestedFixCommands: scanState.suggestedFixCommands,
79
+ coverage: scanState.coverage,
80
+ completeness: scanState.completeness,
81
+ overrideFindings: scanState.overrideFindings,
82
+ // Only passed when override checking ran, so `[]` means "ran, nothing skipped" and
83
+ // absent means "never audited". An unconditional `[]` collapses those two.
84
+ overrideSkipped: scanState.overrideSkipped,
85
+ maintenanceFindings: scanState.maintenanceFindings,
86
+ licenseFindings: scanState.licenseFindings,
87
+ licenseLimitedToDirectOnly: scanState.licenseLimitedToDirectOnly,
88
+ // Saved-artifact provenance for the --json payload (#1296).
89
+ provenance: { cliVersion: getCliVersion(), options },
90
+ });
91
+ const jsonContent = JSON.stringify(payload, null, 2);
92
+ stageOrWrite(outputDir, customFilename, "JSON saved to", (tempFilename) => {
93
+ if (isStdout) {
94
+ process.stdout.write(jsonContent + "\n");
95
+ return undefined;
96
+ }
97
+ const targetPath = tempFilename ? path.join(outputDir, tempFilename) : jsonOutputPath;
98
+ fs.writeFileSync(targetPath, jsonContent);
99
+ return displayOutputPath(jsonOutputPath);
100
+ }, stagedOutputs, undefined, isStdout);
101
+ return jsonOutputPath;
102
+ }
103
+ function stageSbomOutput(options, scanState, scanInput, projectPath, outputDir, customFilename, stagedOutputs, isStdout) {
58
104
  const sbomFormat = resolveSbomFormat(options);
59
- if (sbomFormat) {
60
- const projectMeta = readProjectMeta(projectPath);
61
- if (sbomFormat === "spdx") {
62
- const spdxFilename = writeSpdxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta, {
63
- inventoryOnly: options.sbomInventoryOnly,
64
- // Resolved from the lockfile graph where available. Empty for pnpm,
65
- // Yarn and Bun, which falls back to path-derived edges.
66
- dependencyEdges: resolveDependencyEdges(scanInput, scanState.allPackages),
67
- }, outputDir);
68
- console.log(`${chalk.gray("SPDX SBOM written to")} ${chalk.cyan(spdxFilename)}`);
105
+ if (!sbomFormat)
106
+ return;
107
+ warnOnFormatMismatch(customFilename, sbomFormat);
108
+ const projectMeta = readProjectMeta(projectPath);
109
+ if (sbomFormat === "spdx") {
110
+ const { edges: dependencyEdges, graphLoaded } = resolveDependencyEdgesResult(scanInput, scanState.allPackages);
111
+ const spdxNote = scanInput.source === "pnpm-lock" ||
112
+ scanInput.source === "yarn-lock" ||
113
+ scanInput.source === "bun-lock"
114
+ ? chalk.gray(SPDX_NOASSERTION_LOCKFILE_NOTE)
115
+ : undefined;
116
+ stageOrWrite(outputDir, customFilename, "SPDX SBOM written to", (tempFilename) => writeSpdxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta, {
117
+ inventoryOnly: options.sbomInventoryOnly,
118
+ dependencyEdges,
119
+ graphFailed: !graphLoaded,
120
+ ...(tempFilename ? { filename: tempFilename } : isStdout ? { filename: "-" } : {}),
121
+ }, outputDir), stagedOutputs, spdxNote, isStdout);
122
+ }
123
+ else {
124
+ stageOrWrite(outputDir, customFilename, "CycloneDX BOM written to", (tempFilename) => writeCycloneDxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta, outputDir, tempFilename ?? (isStdout ? "-" : undefined)), stagedOutputs, undefined, isStdout);
125
+ }
126
+ }
127
+ function stageSarifOutput(options, scanState, scanInput, outputDir, customFilename, stagedOutputs, isStdout) {
128
+ if (!options.sarif)
129
+ return;
130
+ warnOnFormatMismatch(customFilename, "sarif");
131
+ const lockfileUri = deriveLockfileUri(scanInput);
132
+ stageOrWrite(outputDir, customFilename, "SARIF report written to", (tempFilename) => writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, {
133
+ acceptedFindings: scanState.acceptedFindings,
134
+ overrideFindings: scanState.overrideFindings,
135
+ maintenanceFindings: scanState.maintenanceFindings,
136
+ licenseFindings: scanState.licenseFindings,
137
+ overrideSkipped: scanState.overrideSkipped,
138
+ completeness: scanState.completeness,
139
+ outputDir,
140
+ ...(tempFilename ? { filename: tempFilename } : isStdout ? { filename: "-" } : {}),
141
+ }), stagedOutputs, undefined, isStdout);
142
+ }
143
+ export async function writeOutputs(options, scanState, scanInput, projectPath) {
144
+ const target = resolveOutputTarget(options.output);
145
+ const isStdout = target.isStdout === true;
146
+ const outputDir = target.dir;
147
+ const customFilename = target.isFile ? target.filename : undefined;
148
+ let jsonOutputPath;
149
+ const stagedOutputs = [];
150
+ try {
151
+ jsonOutputPath = stageJsonOutput(options, scanState, scanInput, projectPath, outputDir, customFilename, stagedOutputs, isStdout);
152
+ stageSarifOutput(options, scanState, scanInput, outputDir, customFilename, stagedOutputs, isStdout);
153
+ stageSbomOutput(options, scanState, scanInput, projectPath, outputDir, customFilename, stagedOutputs, isStdout);
154
+ for (const item of stagedOutputs) {
155
+ fs.renameSync(item.tempPath, item.destinationPath);
156
+ console.log(item.logMessage);
157
+ if (item.note) {
158
+ console.log(item.note);
159
+ }
69
160
  }
70
- else {
71
- const cdxFilename = writeCycloneDxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta, outputDir);
72
- console.log(`${chalk.gray("CycloneDX BOM written to")} ${chalk.cyan(cdxFilename)}`);
161
+ if (isStdout) {
162
+ await drainStdout();
163
+ }
164
+ }
165
+ catch (err) {
166
+ for (const item of stagedOutputs) {
167
+ try {
168
+ fs.rmSync(item.tempPath, { force: true });
169
+ }
170
+ catch {
171
+ /* best-effort cleanup of temp file */
172
+ }
73
173
  }
174
+ throw err;
74
175
  }
176
+ return jsonOutputPath;
75
177
  }
@@ -1,11 +1,8 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { basename, join } from "node:path";
3
3
  import { extractOverrideEntries } from "./parsing/package-json.js";
4
4
  import { walkInstalledTree } from "./parsing/installed-tree.js";
5
- import { loadFromPackageLock } from "../parsers/package-lock.js";
6
- import { loadFromPnpmLock } from "../parsers/pnpm-lock.js";
7
- import { loadFromYarnLock } from "../parsers/yarn-lock.js";
8
- import { loadFromBunLock } from "../parsers/bun-lock.js";
5
+ import { readSelectedLockfile, selectRootLockfile } from "../parsers/index.js";
9
6
  import { scanAllImports, usageScanTruncationWarning } from "../usage/scanner.js";
10
7
  import { readWorkspaceMemberManifests } from "../utils/package-json.js";
11
8
  import { isNodeBuiltinSpecifier } from "../utils/node-builtins.js";
@@ -18,8 +15,11 @@ export function buildOverrideContext(projectPath, opts) {
18
15
  const raw = readFileSync(pkgJsonPath, "utf8");
19
16
  const parsed = JSON.parse(raw);
20
17
  const overrideEntries = extractOverrideEntries(parsed);
21
- const packageManager = detectPackageManager(projectPath);
22
- const readResult = readLockfileNames(projectPath, packageManager);
18
+ // The same root lockfile the scan reads, so the override rules see the tree
19
+ // the findings came from (#1497).
20
+ const lockfile = selectRootLockfile(projectPath);
21
+ const packageManager = lockfile ? PACKAGE_MANAGER_BY_LOCKFILE[lockfile.name] : "unknown";
22
+ const readResult = readLockfileNames(lockfile);
23
23
  const lockfilePackageNames = readResult.kind === "ok" ? readResult.names : new Set();
24
24
  const lockfileVersions = readResult.kind === "ok" ? readResult.versions : new Map();
25
25
  const nodeModulesExists = existsSync(join(projectPath, "node_modules"));
@@ -104,17 +104,13 @@ export function buildOverrideContext(projectPath, opts) {
104
104
  logger: opts.logger,
105
105
  };
106
106
  }
107
- function detectPackageManager(projectPath) {
108
- if (existsSync(join(projectPath, "pnpm-lock.yaml")))
109
- return "pnpm";
110
- if (existsSync(join(projectPath, "yarn.lock")))
111
- return "yarn";
112
- if (existsSync(join(projectPath, "bun.lock")))
113
- return "bun";
114
- if (existsSync(join(projectPath, "package-lock.json")))
115
- return "npm";
116
- return "unknown";
117
- }
107
+ const PACKAGE_MANAGER_BY_LOCKFILE = {
108
+ "package-lock.json": "npm",
109
+ "npm-shrinkwrap.json": "npm",
110
+ "pnpm-lock.yaml": "pnpm",
111
+ "yarn.lock": "yarn",
112
+ "bun.lock": "bun",
113
+ };
118
114
  /**
119
115
  * Groups resolved lockfile versions by package name. A package can appear at
120
116
  * several versions in one tree, so every one is kept: an override selector only
@@ -136,60 +132,17 @@ function versionsByName(refs) {
136
132
  }
137
133
  return byName;
138
134
  }
139
- function readLockfileNames(projectPath, pm) {
140
- if (pm === "npm") {
141
- const lockPath = join(projectPath, "package-lock.json");
142
- if (!existsSync(lockPath))
143
- return { kind: "absent" };
144
- try {
145
- const refs = loadFromPackageLock(lockPath, false);
146
- return { kind: "ok", names: new Set(refs.map((r) => r.name)), versions: versionsByName(refs) };
147
- }
148
- catch (e) {
149
- const message = e instanceof Error ? e.message : String(e);
150
- return { kind: "error", message: `package-lock.json: ${message}` };
151
- }
152
- }
153
- if (pm === "pnpm") {
154
- const lockPath = join(projectPath, "pnpm-lock.yaml");
155
- if (!existsSync(lockPath))
156
- return { kind: "absent" };
157
- try {
158
- const refs = loadFromPnpmLock(lockPath, false);
159
- return { kind: "ok", names: new Set(refs.map((r) => r.name)), versions: versionsByName(refs) };
160
- }
161
- catch (e) {
162
- const message = e instanceof Error ? e.message : String(e);
163
- return { kind: "error", message: `pnpm-lock.yaml: ${message}` };
164
- }
165
- }
166
- if (pm === "yarn") {
167
- const lockPath = join(projectPath, "yarn.lock");
168
- if (!existsSync(lockPath))
169
- return { kind: "absent" };
170
- try {
171
- const refs = loadFromYarnLock(lockPath);
172
- return { kind: "ok", names: new Set(refs.map((r) => r.name)), versions: versionsByName(refs) };
173
- }
174
- catch (e) {
175
- const message = e instanceof Error ? e.message : String(e);
176
- return { kind: "error", message: `yarn.lock: ${message}` };
177
- }
135
+ function readLockfileNames(lockfile) {
136
+ if (lockfile === null)
137
+ return { kind: "absent" };
138
+ try {
139
+ const refs = readSelectedLockfile(lockfile);
140
+ return { kind: "ok", names: new Set(refs.map((r) => r.name)), versions: versionsByName(refs) };
178
141
  }
179
- if (pm === "bun") {
180
- const lockPath = join(projectPath, "bun.lock");
181
- if (!existsSync(lockPath))
182
- return { kind: "absent" };
183
- try {
184
- const refs = loadFromBunLock(lockPath, false);
185
- return { kind: "ok", names: new Set(refs.map((r) => r.name)), versions: versionsByName(refs) };
186
- }
187
- catch (e) {
188
- const message = e instanceof Error ? e.message : String(e);
189
- return { kind: "error", message: `bun.lock: ${message}` };
190
- }
142
+ catch (e) {
143
+ const message = e instanceof Error ? e.message : String(e);
144
+ return { kind: "error", message: `${basename(lockfile.filePath)}: ${message}` };
191
145
  }
192
- return { kind: "absent" };
193
146
  }
194
147
  function seedRootDeclarations(pkg, parentDeclarations) {
195
148
  const rootName = typeof pkg.name === "string" ? pkg.name : "<root>";
@@ -174,7 +174,7 @@ export async function fetchVersionsBatch(pkgNames, opts = {}) {
174
174
  }
175
175
  /**
176
176
  * Encode a package name for the registry URL.
177
- * Scoped names like `@scope/pkg` need the slash kept literal — the registry
177
+ * Scoped names like `@scope/pkg` need the slash kept literal - the registry
178
178
  * doesn't accept `%2F` for the scope separator.
179
179
  */
180
180
  function encodeRegistryPath(pkgName) {
@@ -1,7 +1,6 @@
1
1
  import { uniquePathArrays } from "../utils/array.js";
2
- import { upsertPackage } from "./utils.js";
2
+ import { upsertPackage, MAX_PATHS_PER_PACKAGE } from "./utils.js";
3
3
  import { buildBunChildKeyGraph, buildBunKeyIndex, collectReachableKeys, readAndParseBunLock, resolveBunChildKey, } from "./bun-lock-graph.js";
4
- const MAX_PATHS_PER_PACKAGE = 5;
5
4
  const MAX_PATH_DEPTH = 10;
6
5
  const DEPENDENCY_SECTIONS = ["dependencies", "optionalDependencies", "devDependencies"];
7
6
  /**
@@ -90,7 +90,13 @@ function findRootLockfile(projectRoot) {
90
90
  if (present.length === 0)
91
91
  return null;
92
92
  const declared = readDeclaredPackageManager(projectRoot);
93
- const declaredLockfile = declared ? PACKAGE_MANAGER_LOCKFILES[declared] : undefined;
93
+ // npm treats npm-shrinkwrap.json as authoritative over package-lock.json.
94
+ // Keep that rule even when package.json declares npm, while preserving the
95
+ // packageManager override for other ecosystems (for example, pnpm beside a
96
+ // stale package-lock.json).
97
+ const declaredLockfile = declared === "npm" && present.includes("npm-shrinkwrap.json")
98
+ ? "npm-shrinkwrap.json"
99
+ : declared ? PACKAGE_MANAGER_LOCKFILES[declared] : undefined;
94
100
  const chosen = declaredLockfile && present.includes(declaredLockfile) ? declaredLockfile : present[0];
95
101
  return {
96
102
  filePath: path.join(projectRoot, chosen),
@@ -132,6 +138,21 @@ function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
132
138
  skippedDependencies: [],
133
139
  };
134
140
  }
141
+ /**
142
+ * The lockfile a scan of `projectRoot` reads at that folder's root, by the same
143
+ * rules `loadPackages` uses. Anything that has to agree with the scan about
144
+ * which tree it is looking at, such as the override rules, takes its lockfile
145
+ * from here rather than choosing one by its own order (#1497). A nested
146
+ * lockfile is deliberately not returned: it belongs to a different manifest.
147
+ */
148
+ export function selectRootLockfile(projectRoot) {
149
+ const root = findRootLockfile(projectRoot);
150
+ return root === null ? null : { filePath: root.filePath, name: root.name };
151
+ }
152
+ /** Reads every resolved package from a selected lockfile, dev dependencies included. */
153
+ export function readSelectedLockfile(lockfile) {
154
+ return LOCKFILE_HANDLERS[lockfile.name].load(lockfile.filePath, false);
155
+ }
135
156
  export function loadPackages(projectRoot, prodOnly, maxDepth) {
136
157
  const rootLockfile = findRootLockfile(projectRoot);
137
158
  if (rootLockfile !== null) {