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
@@ -2,35 +2,44 @@ import { randomUUID } from "node:crypto";
2
2
  import { findFixTargetForFinding, findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
3
3
  import { getRecommendedAction } from "./formatters.js";
4
4
  import { getCliVersion } from "../utils/version-info.js";
5
- import { buildPurl } from "../utils/purl.js";
5
+ import { buildPurl, purlForSbom, sbomComponentRef } from "../utils/purl.js";
6
+ import { registryPackageName } from "../utils/package-identity.js";
6
7
  import { sbomTimestamp, writeSbomFile } from "./sbom-file.js";
7
8
  export { buildPurl };
8
9
  export function buildCycloneDxBom(allPackages, findings, projectMeta, version, plan = null) {
9
- const components = allPackages.map(pkg => {
10
- const purl = buildPurl(pkg.name, pkg.version);
11
- return {
10
+ const components = [];
11
+ for (const pkg of allPackages) {
12
+ const purl = purlForSbom(pkg);
13
+ if (!purl)
14
+ continue;
15
+ components.push({
12
16
  type: "library",
13
- "bom-ref": purl,
14
- name: pkg.name,
17
+ "bom-ref": sbomComponentRef(pkg, purl),
18
+ name: registryPackageName(pkg),
15
19
  version: pkg.version,
16
20
  purl,
17
- };
18
- });
19
- // Deduplicate vulnerabilities by CVE ID — one entry per CVE with multiple affects
21
+ ...(pkg.dev !== undefined
22
+ ? { scope: pkg.dev ? "excluded" : "required" }
23
+ : {}),
24
+ });
25
+ }
26
+ // Deduplicate vulnerabilities by CVE ID - one entry per CVE with multiple affects
20
27
  const vulnMap = new Map();
21
28
  for (const finding of findings) {
22
29
  const cveIds = finding.cveAliases.length > 0
23
30
  ? finding.cveAliases
24
31
  : finding.vulnerabilities.map(v => v.id);
25
- const purl = buildPurl(finding.pkg.name, finding.pkg.version);
32
+ const purl = purlForSbom(finding.pkg);
33
+ if (!purl)
34
+ continue;
26
35
  for (const cveId of cveIds) {
27
36
  const existing = vulnMap.get(cveId);
28
37
  if (existing) {
29
- existing.affects.push({ ref: purl });
38
+ existing.affects.push({ ref: sbomComponentRef(finding.pkg, purl) });
30
39
  }
31
40
  else {
32
41
  // severity from first finding wins when the same CVE affects multiple packages
33
- vulnMap.set(cveId, { finding, affects: [{ ref: purl }] });
42
+ vulnMap.set(cveId, { finding, affects: [{ ref: sbomComponentRef(finding.pkg, purl) }] });
34
43
  }
35
44
  }
36
45
  }
@@ -97,8 +106,8 @@ export function buildCycloneDxBom(allPackages, findings, projectMeta, version, p
97
106
  vulnerabilities,
98
107
  };
99
108
  }
100
- export function writeCycloneDxReport(allPackages, findings, plan, projectMeta, outputDir) {
101
- const filename = `cve-lite-scan-${sbomTimestamp()}.cdx.json`;
109
+ export function writeCycloneDxReport(allPackages, findings, plan, projectMeta, outputDir, filename) {
110
+ const finalFilename = filename ?? `cve-lite-scan-${sbomTimestamp()}.cdx.json`;
102
111
  const bom = buildCycloneDxBom(allPackages, findings, projectMeta, getCliVersion(), plan);
103
- return writeSbomFile(filename, bom, "CycloneDX report", outputDir);
112
+ return writeSbomFile(finalFilename, bom, "CycloneDX report", outputDir);
104
113
  }
@@ -1,31 +1,46 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { createDebugBundle } from "../utils/debug-bundle.js";
3
4
  export function createDebugLogger(enabled) {
4
- if (!enabled) {
5
- return {
6
- log: () => { },
7
- announcePath: () => { },
8
- close: () => { },
9
- };
10
- }
5
+ if (!enabled)
6
+ return { log: () => { }, announcePath: () => { }, close: () => { }, finalize: () => null };
11
7
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
12
8
  const filename = `cve-lite-debug-${ts}.log`;
13
9
  const outputPath = path.join(process.cwd(), filename);
14
- let announced = false;
10
+ const events = [];
11
+ let logWriteFailed = false;
12
+ let finalized = false;
13
+ let bundlePath = null;
15
14
  const log = (message, details) => {
16
15
  const time = new Date().toISOString();
17
- const payload = details === undefined
18
- ? ""
19
- : ` ${formatJson(details)}`;
20
- fs.appendFileSync(outputPath, `${time} [debug] ${message}${payload}\n`, "utf8");
21
- };
22
- const announcePath = () => {
23
- if (announced)
16
+ events.push({ timestamp: time, message, details });
17
+ // Retained locally for compatibility, not advertised as safe to attach.
18
+ if (logWriteFailed)
24
19
  return;
25
- announced = true;
26
- console.error(`[debug] Writing debug log to ./${filename}`);
20
+ try {
21
+ const payload = details === undefined ? "" : ` ${formatJson(details)}`;
22
+ fs.appendFileSync(outputPath, `${time} [debug] ${message}${payload}\n`, "utf8");
23
+ }
24
+ catch (error) {
25
+ logWriteFailed = true;
26
+ warnWriteFailure("the local debug log", filename, error, "continuing the scan.");
27
+ }
28
+ };
29
+ const finalize = (projectPath, options, scanJsonPath) => {
30
+ if (finalized)
31
+ return bundlePath;
32
+ finalized = true;
33
+ try {
34
+ bundlePath = createDebugBundle(events, options, projectPath, scanJsonPath);
35
+ const display = path.relative(process.cwd(), bundlePath) || bundlePath;
36
+ console.error(`[debug] Debug bundle written to ./${display} - attach this when reporting a problem.`);
37
+ }
38
+ catch (error) {
39
+ warnWriteFailure("the debug bundle", writeFailureName(error), error, "the scan result is unchanged.");
40
+ }
41
+ return bundlePath;
27
42
  };
28
- return { log, announcePath, close: () => { } };
43
+ return { log, announcePath: () => { }, close: () => { }, finalize };
29
44
  }
30
45
  function formatJson(details) {
31
46
  if (typeof details === "string")
@@ -37,3 +52,38 @@ function formatJson(details) {
37
52
  return String(details);
38
53
  }
39
54
  }
55
+ /** Shared by the legacy log and the bundle: name the file, then say why. */
56
+ function warnWriteFailure(subject, filename, error, followUp) {
57
+ const reason = failureReason(error) || "unknown error";
58
+ console.error(`[debug] Could not write ${subject} to ./${filename}: ${reason}; ${followUp}`);
59
+ }
60
+ function failureReason(error) {
61
+ // Read message and code off the object. `instanceof Error` is false for
62
+ // Node filesystem errors once this module is loaded in a different realm.
63
+ const record = error !== null && typeof error === "object" ? error : undefined;
64
+ const raw = typeof record?.message === "string" ? record.message : String(error);
65
+ const code = typeof record?.code === "string" ? record.code : "";
66
+ // Node ends filesystem errors with the absolute path. The relative name is
67
+ // already in the warning, and that path can itself contain a secret.
68
+ const detail = (code && raw.startsWith(`${code}:`) ? raw.slice(code.length + 1) : raw)
69
+ .replace(/,\s*[A-Za-z]+\s+'(?:\\'|[^'])*'$/, "")
70
+ .replace(/'(?:\\'|[^'])*'/g, "")
71
+ .replace(/(?:[A-Za-z]:[\\/]|\/)[^\s'"]+/g, "")
72
+ .replace(/[ \t]{2,}/g, " ")
73
+ .trim();
74
+ return code && raw.startsWith(`${code}:`) ? (detail ? `${code}: ${detail}` : code) : detail;
75
+ }
76
+ function writeFailureName(error) {
77
+ if (!error || typeof error !== "object")
78
+ return "cve-lite-debug";
79
+ const record = error;
80
+ const target = typeof record.path === "string" && record.path
81
+ ? record.path
82
+ : typeof record.writeTarget === "string" ? record.writeTarget : "";
83
+ if (!target)
84
+ return "cve-lite-debug";
85
+ const relative = path.relative(process.cwd(), target);
86
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative))
87
+ return relative;
88
+ return path.basename(target);
89
+ }
@@ -1,14 +1,17 @@
1
- import { findFixTargetForFinding, findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
1
+ import { findFixTargetForFinding, findSuggestedCommandForFinding, formatParentUpgradeBlockedReason } from "../remediation/fix-commands.js";
2
2
  import { chalk } from "../utils/chalk.js";
3
3
  import { severityOrder, MAL_PRIVATE_REGISTRY_MESSAGE, MAL_GIT_SOURCE_PINNED_MESSAGE, MAL_GIT_SOURCE_FLOATING_MESSAGE, } from "../constants.js";
4
4
  import { loadCache } from "../osv/cache.js";
5
5
  import { inferSeverity } from "../osv/severity.js";
6
6
  import { getPrimaryParent, getRootDependencies, isUnconfirmedFix } from "../utils/finding.js";
7
7
  import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
8
- import { pluralize } from "../utils/string.js";
8
+ import { pluralize, isOutputStdout } from "../utils/string.js";
9
9
  import { hasMaliciousAdvisory } from "../utils/vuln.js";
10
10
  import { computePrioritySignal } from "../utils/priority-signal.js";
11
11
  import { computeContextualSignals } from "../utils/contextual-signals.js";
12
+ export function formatPackageName(pkg) {
13
+ return pkg.registryName && pkg.registryName !== pkg.name ? `${pkg.name} (${pkg.registryName})` : pkg.name;
14
+ }
12
15
  export function formatRelationshipLabel(value) {
13
16
  if (value.startsWith("direct"))
14
17
  return chalk.green(value);
@@ -55,6 +58,9 @@ function transitiveRiskMessage(packageName, complete) {
55
58
  ? `Transitive issue. A specific parent upgrade target was found for ${packageName}.`
56
59
  : `Transitive issue. A path-specific parent upgrade target was found for ${packageName}; run it, rescan, and review remaining paths separately.`;
57
60
  }
61
+ function unreadablePyPiBoundaryAction(packageName) {
62
+ return `The advisory data for ${packageName} has an unreadable PyPI boundary, so the fix is inconclusive.`;
63
+ }
58
64
  export function getRecommendedAction(finding) {
59
65
  if (isMaliciousAdvisory(finding)) {
60
66
  if (finding.maliciousUnverifiable) {
@@ -64,8 +70,11 @@ export function getRecommendedAction(finding) {
64
70
  ? "This package has a malicious code advisory. Remove it from your dependencies."
65
71
  : "This package has a malicious code advisory. Upgrade or remove the parent package that pulls it in.";
66
72
  }
73
+ if (finding.advisoryBoundaryUnreadable) {
74
+ return unreadablePyPiBoundaryAction(finding.pkg.name);
75
+ }
67
76
  // Prefer the registry-validated target over the raw advisory hint when
68
- // available — they can disagree (the hint may not be published on npm or
77
+ // available - they can disagree (the hint may not be published on npm or
69
78
  // may itself be vulnerable), and the validated target is what the fix
70
79
  // command actually uses.
71
80
  const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
@@ -78,6 +87,9 @@ export function getRecommendedAction(finding) {
78
87
  if (finding.relationship === "direct") {
79
88
  return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
80
89
  }
90
+ if (finding.recommendedParentUpgrade && finding.parentUpgradeBlockers?.length) {
91
+ return formatParentUpgradeBlockedReason(finding);
92
+ }
81
93
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
82
94
  return `${finding.recommendedNpmTransitiveRemediation.package} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} - run \`npm install\` to pick it up.`;
83
95
  }
@@ -100,7 +112,7 @@ export function getRecommendedAction(finding) {
100
112
  // No parent identifiable: either dependencyPaths is empty, or the path is
101
113
  // a degenerate length-2 chain (project -> vulnerable, common when the
102
114
  // package is hoisted to top-level node_modules). The advice is the same
103
- // either way — inspect the lockfile or run `<pm> ls` to find the parent.
115
+ // either way - inspect the lockfile or run `<pm> ls` to find the parent.
104
116
  if (directTarget) {
105
117
  return `No parent dependency was identified for ${finding.pkg.name} in the lockfile. Run \`npm ls ${finding.pkg.name}\` (or your package manager equivalent) to find which package pulls it in, then upgrade toward ${directTarget}+.`;
106
118
  }
@@ -115,6 +127,9 @@ export function summarizeRisk(finding) {
115
127
  ? MAL_GIT_SOURCE_PINNED_MESSAGE
116
128
  : MAL_GIT_SOURCE_FLOATING_MESSAGE;
117
129
  }
130
+ if (finding.advisoryBoundaryUnreadable) {
131
+ return unreadablePyPiBoundaryAction(finding.pkg.name);
132
+ }
118
133
  let risk = "";
119
134
  if (finding.severity === "critical" && finding.relationship === "direct") {
120
135
  risk = "Critical direct dependency. Prioritize this first because the project controls it directly.";
@@ -125,6 +140,9 @@ export function summarizeRisk(finding) {
125
140
  else if (finding.relationship === "transitive" && finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
126
141
  risk = `Transitive issue. The current parent range can already absorb a safe ${finding.pkg.name} update via ${finding.recommendedNpmTransitiveRemediation.package}.`;
127
142
  }
143
+ else if (finding.relationship === "transitive" && finding.recommendedParentUpgrade && finding.parentUpgradeBlockers?.length) {
144
+ risk = `Transitive issue. ${formatParentUpgradeBlockedReason(finding)}`;
145
+ }
128
146
  else if (finding.relationship === "transitive" && finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version") {
129
147
  const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedNpmTransitiveRemediation.viaPath);
130
148
  risk = transitiveRiskMessage(finding.recommendedNpmTransitiveRemediation.package, coverage.coverage === "complete");
@@ -180,6 +198,9 @@ export function summarizeNextAction(finding) {
180
198
  ? "This package has a malicious code advisory. Remove it from your dependencies."
181
199
  : "This package has a malicious code advisory. Upgrade or remove the parent package that pulls it in.";
182
200
  }
201
+ if (finding.advisoryBoundaryUnreadable) {
202
+ return unreadablePyPiBoundaryAction(finding.pkg.name);
203
+ }
183
204
  if (isUnconfirmedFix(finding)) {
184
205
  return `Verify a safe version of ${finding.pkg.name} before upgrading.`;
185
206
  }
@@ -192,6 +213,9 @@ export function summarizeNextAction(finding) {
192
213
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
193
214
  return `Lockfile refresh - ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version.`;
194
215
  }
216
+ if (finding.recommendedParentUpgrade && finding.parentUpgradeBlockers?.length) {
217
+ return formatParentUpgradeBlockedReason(finding);
218
+ }
195
219
  if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
196
220
  finding.recommendedNpmTransitiveRemediation.targetVersion) {
197
221
  return `Upgrade ${finding.recommendedNpmTransitiveRemediation.package} ${finding.recommendedNpmTransitiveRemediation.currentVersion} -> ${finding.recommendedNpmTransitiveRemediation.targetVersion}.`;
@@ -231,6 +255,7 @@ export function formatFixCommandWithPublishDates(command, targets) {
231
255
  export function serializeFinding(finding, plan) {
232
256
  return {
233
257
  package: finding.pkg.name,
258
+ ...(finding.pkg.registryName ? { registryPackage: finding.pkg.registryName } : {}),
234
259
  version: finding.pkg.version,
235
260
  severity: finding.severity,
236
261
  relationship: finding.relationship,
@@ -247,7 +272,9 @@ export function serializeFinding(finding, plan) {
247
272
  primaryParent: getPrimaryParent(finding),
248
273
  rootDependencies: getRootDependencies(finding),
249
274
  recommendedParentUpgrade: finding.recommendedParentUpgrade,
275
+ parentUpgradeBlockers: finding.parentUpgradeBlockers ?? null,
250
276
  recommendedNpmTransitiveRemediation: finding.recommendedNpmTransitiveRemediation ?? null,
277
+ chainResolution: finding.chainResolution ?? null,
251
278
  cves: finding.cveAliases,
252
279
  epssScores: finding.epssScores ?? null,
253
280
  prioritySignal: computePrioritySignal(finding.severity, finding.epssScores) ?? null,
@@ -258,6 +285,7 @@ export function serializeFinding(finding, plan) {
258
285
  maliciousGitSource: finding.maliciousGitSource ?? false,
259
286
  maliciousGitSourcePinned: finding.maliciousGitSourcePinned ?? false,
260
287
  unresolvedAdvisoryIds: finding.unresolvedAdvisoryIds ?? [],
288
+ ...(finding.advisoryBoundaryUnreadable ? { advisoryBoundaryUnreadable: true } : {}),
261
289
  vulnerabilities: finding.vulnerabilities.map(v => ({
262
290
  id: v.id,
263
291
  aliases: v.aliases ?? [],
@@ -268,7 +296,7 @@ export function serializeFinding(finding, plan) {
268
296
  };
269
297
  }
270
298
  export function printCacheSummary(cacheDirOverride, options) {
271
- if (options?.json)
299
+ if (options?.json || isOutputStdout(options?.output))
272
300
  return;
273
301
  const cache = loadCache(cacheDirOverride);
274
302
  const advisoryCount = Object.values(cache.entries).filter(entry => entry.vuln).length;
@@ -283,12 +311,12 @@ export function printCacheSummary(cacheDirOverride, options) {
283
311
  : ""));
284
312
  }
285
313
  export function logInfo(message, options) {
286
- if (options?.json)
314
+ if (options?.json || isOutputStdout(options?.output))
287
315
  return;
288
316
  console.log(chalk.gray(message));
289
317
  }
290
318
  export function logWarn(message, options) {
291
- if (options?.json)
319
+ if (options?.json || isOutputStdout(options?.output))
292
320
  return;
293
321
  console.log(chalk.yellow(message));
294
322
  }
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { spawn } from "node:child_process";
4
5
  import { serializeFinding, summarizeNextAction, summarizeRisk, formatCooldownWarning } from "./formatters.js";
5
6
  import { loadLogoDataUri } from "./logos.js";
@@ -26,6 +27,7 @@ export function buildReportData(params) {
26
27
  return {
27
28
  projectPath: params.projectPath,
28
29
  scannedAt: new Date().toISOString(),
30
+ ...(params.registry ? { registry: params.registry } : {}),
29
31
  cliVersion: params.cliVersion,
30
32
  packageManager: params.packageManager,
31
33
  lockfileSource: params.lockfileSource,
@@ -246,6 +248,11 @@ function embedJson(value) {
246
248
  export function renderHtmlReport(data, jsonPayload) {
247
249
  const projectName = path.basename(data.projectPath);
248
250
  const scanDate = new Date(data.scannedAt).toLocaleString();
251
+ // Only when configured, matching the terminal, so nothing new appears for a project
252
+ // installing from public npm.
253
+ const registryMeta = data.registry?.sourceFile
254
+ ? ` &nbsp;·&nbsp; registry: ${escapeHtml(data.registry.registry)}`
255
+ : "";
249
256
  const counts = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0, none: 0 };
250
257
  for (const f of data.findings) {
251
258
  const sev = f.severity;
@@ -271,7 +278,7 @@ export function renderHtmlReport(data, jsonPayload) {
271
278
  <head>
272
279
  <meta charset="UTF-8">
273
280
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
274
- <title>CVE Lite — ${escapeHtml(projectName)}</title>
281
+ <title>CVE Lite - ${escapeHtml(projectName)}</title>
275
282
  <style>
276
283
  ${REPORT_STYLES}
277
284
  </style>
@@ -291,7 +298,7 @@ ${REPORT_STYLES}
291
298
  <div class="header-divider"></div>
292
299
  <div class="header-project">
293
300
  <span class="project-name">${escapeHtml(projectName)}</span>
294
- <span class="project-meta">${escapeHtml(data.packageManager)} &nbsp;·&nbsp; ${escapeHtml(data.lockfileSource)} &nbsp;·&nbsp; ${escapeHtml(scanDate)}</span>
301
+ <span class="project-meta">${escapeHtml(data.packageManager)} &nbsp;·&nbsp; ${escapeHtml(data.lockfileSource)} &nbsp;·&nbsp; ${escapeHtml(scanDate)}${registryMeta}</span>
295
302
  </div>
296
303
  </div>
297
304
  <div class="header-right">
@@ -371,7 +378,7 @@ ${findingRowsHtml}
371
378
  </table>
372
379
  ${renderPriorityLegendHtml(data.findings)}
373
380
  </div>
374
- ${renderOverrideFindingsHtml(data.overrideFindings, data.projectPath, data.skippedOverrideRules)}
381
+ ${renderOverrideFindingsHtml(data.overrideFindings, undefined, data.skippedOverrideRules)}
375
382
  ${renderMaintenanceFindingsHtml(data.maintenanceFindings)}
376
383
  ${renderLicenseFindingsHtml(data.licenseFindings, { limitedToDirectOnly: data.licenseLimitedToDirectOnly })}
377
384
  ${skippedDepsHtml}
@@ -618,18 +625,20 @@ export function renderFindingRow(finding, idx, skippedKeys) {
618
625
  const unconfirmed = isUnconfirmedFix(finding);
619
626
  const fixVersion = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
620
627
  const fixHtml = (isSkipped || unconfirmed) && fixVersion
621
- ? `<span class="fix-hint hint-only" title="Advisory hint only — a safe fix has not been confirmed.">${escapeHtml(fixVersion)} ⊘</span>`
628
+ ? `<span class="fix-hint hint-only" title="Advisory hint only: a safe fix has not been confirmed.">${escapeHtml(fixVersion)} ⊘</span>`
622
629
  : fixVersion
623
630
  ? `<span class="fix-hint">${escapeHtml(fixVersion)}</span>`
624
631
  : isMalicious && finding.maliciousUnverifiable
625
632
  ? `<span class="badge badge-warning" title="MAL- advisory found but package resolved from a private registry - may not apply to your artifact">Unverifiable (private source)</span>`
626
633
  : isMalicious && finding.maliciousGitSource && finding.maliciousGitSourcePinned
627
- ? `<span class="badge badge-git-source" title="MAL- advisory found but package resolves from a git source pinned to a commit SHA — verify the repository and org are trusted">${escapeHtml(MAL_GIT_SOURCE_PINNED_DISPLAY)}</span>`
634
+ ? `<span class="badge badge-git-source" title="MAL- advisory found but package resolves from a git source pinned to a commit SHA: verify the repository and org are trusted">${escapeHtml(MAL_GIT_SOURCE_PINNED_DISPLAY)}</span>`
628
635
  : isMalicious && finding.maliciousGitSource
629
- ? `<span class="badge badge-git-source" title="MAL- advisory found but package resolves from a git source with a floating reference — verify the repository, org, and ref are safe">${escapeHtml(MAL_GIT_SOURCE_FLOATING_DISPLAY)}</span>`
636
+ ? `<span class="badge badge-git-source" title="MAL- advisory found but package resolves from a git source with a floating reference: verify the repository, org, and ref are safe">${escapeHtml(MAL_GIT_SOURCE_FLOATING_DISPLAY)}</span>`
630
637
  : isMalicious
631
- ? `<span class="fix-hint none" title="Malicious code advisory — remove this package">⚠ Malicious</span>`
632
- : `<span class="fix-hint none" title="No known fix — consider replacing this package">⚠ No fix</span>`;
638
+ ? `<span class="fix-hint none" title="Malicious code advisory: remove this package">⚠ Malicious</span>`
639
+ : finding.advisoryBoundaryUnreadable
640
+ ? `<span class="fix-hint none" title="The advisory data has an unreadable PyPI boundary, so the fix is inconclusive.">unreadable advisory data</span>`
641
+ : `<span class="fix-hint none" title="No known fix: consider replacing this package">⚠ No fix</span>`;
633
642
  const depPaths = renderDependencyPathsHtml(finding);
634
643
  const description = finding.vulnerabilities[0]?.summary ?? "";
635
644
  const runnable = finding.runnableFixCommand ?? null;
@@ -705,9 +714,10 @@ export function renderFindingRow(finding, idx, skippedKeys) {
705
714
  </tr>`;
706
715
  }
707
716
  function renderTransitiveContextCol(finding) {
717
+ // A blocked parent upgrade names a step, not a fix (#1457).
708
718
  const hasFixAvailable = finding.runnableFixCommand != null ||
709
- finding.recommendedNpmTransitiveRemediation != null ||
710
- finding.recommendedParentUpgrade != null;
719
+ (!finding.parentUpgradeBlockers?.length &&
720
+ (finding.recommendedNpmTransitiveRemediation != null || finding.recommendedParentUpgrade != null));
711
721
  const rootNames = finding.rootDependencies.join(", ");
712
722
  if (hasFixAvailable) {
713
723
  const rootLine = rootNames
@@ -942,11 +952,57 @@ export async function writeHtmlReport(params) {
942
952
  }
943
953
  const indexPath = path.join(params.outputDir, "index.html");
944
954
  const jsonPath = path.join(params.outputDir, "report.json");
955
+ const tempJsonPath = path.join(params.outputDir, `.report.json.${randomUUID()}.tmp`);
956
+ const tempIndexPath = path.join(params.outputDir, `.index.html.${randomUUID()}.tmp`);
957
+ const backupJsonPath = path.join(params.outputDir, `.report.json.bak.${randomUUID()}.tmp`);
958
+ let jsonBackedUp = false;
959
+ let jsonReplaced = false;
945
960
  try {
946
- fs.writeFileSync(jsonPath, JSON.stringify(params.jsonPayload, null, 2), "utf8");
947
- fs.writeFileSync(indexPath, renderHtmlReport(params.data, params.jsonPayload), "utf8");
961
+ fs.writeFileSync(tempJsonPath, JSON.stringify(params.jsonPayload, null, 2), "utf8");
962
+ fs.writeFileSync(tempIndexPath, renderHtmlReport(params.data, params.jsonPayload), "utf8");
963
+ if (fs.existsSync(jsonPath)) {
964
+ fs.renameSync(jsonPath, backupJsonPath);
965
+ jsonBackedUp = true;
966
+ }
967
+ fs.renameSync(tempJsonPath, jsonPath);
968
+ jsonReplaced = true;
969
+ fs.renameSync(tempIndexPath, indexPath);
970
+ if (jsonBackedUp) {
971
+ try {
972
+ fs.rmSync(backupJsonPath, { force: true, recursive: true });
973
+ }
974
+ catch { /* best-effort cleanup */ }
975
+ }
948
976
  }
949
977
  catch (err) {
978
+ let backupJsonRestored = false;
979
+ if (jsonBackedUp) {
980
+ try {
981
+ fs.renameSync(backupJsonPath, jsonPath);
982
+ backupJsonRestored = true;
983
+ }
984
+ catch { /* best-effort restore */ }
985
+ }
986
+ else if (jsonReplaced) {
987
+ try {
988
+ fs.rmSync(jsonPath, { force: true, recursive: true });
989
+ }
990
+ catch { /* best-effort cleanup */ }
991
+ }
992
+ try {
993
+ fs.rmSync(tempJsonPath, { force: true, recursive: true });
994
+ }
995
+ catch { /* best-effort cleanup */ }
996
+ try {
997
+ fs.rmSync(tempIndexPath, { force: true, recursive: true });
998
+ }
999
+ catch { /* best-effort cleanup */ }
1000
+ if (!jsonBackedUp || backupJsonRestored) {
1001
+ try {
1002
+ fs.rmSync(backupJsonPath, { force: true, recursive: true });
1003
+ }
1004
+ catch { /* best-effort cleanup */ }
1005
+ }
950
1006
  if (!dirExisted) {
951
1007
  try {
952
1008
  fs.rmSync(params.outputDir, { recursive: true, force: true });
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { aggregateMultiFolderCompleteness } from "../scan/completeness.js";
4
5
  import { REPORT_STYLES, escapeHtml, openInBrowser, renderFindingRow, renderFixPlan, renderCompletenessBanner, serializeHtmlFinding, renderPriorityLegendHtml, } from "./html-reporter.js";
5
6
  import { renderOverrideFindingsHtml } from "./override-findings-html.js";
@@ -56,7 +57,7 @@ function renderFolderNotices(coverage, warnings) {
56
57
  <div class="scan-notes-body"><ul>${items}</ul></div>
57
58
  </div>`;
58
59
  }
59
- function renderFolderSection(result, folderIdx, idxOffset, serialized, projectRoot, includeOverrides, includeMaintenance, includeLicenses) {
60
+ function renderFolderSection(result, folderIdx, idxOffset, serialized, includeOverrides, includeMaintenance, includeLicenses) {
60
61
  const counts = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 };
61
62
  for (const f of result.sorted) {
62
63
  const sev = f.severity;
@@ -73,9 +74,8 @@ function renderFolderSection(result, folderIdx, idxOffset, serialized, projectRo
73
74
  const findingRowsHtml = serialized.map((f, i) => renderFindingRow(f, idxOffset + i)).join("\n");
74
75
  const fixPlanHtml = renderFixPlan(result.suggestedFixCommands);
75
76
  const noticesHtml = renderFolderNotices(result.coverage, result.scanInput.warnings);
76
- const folderAbs = path.join(projectRoot, result.subfolder);
77
77
  const overrideHtml = includeOverrides
78
- ? renderOverrideFindingsHtml(result.overrideFindings, folderAbs, result.overrideSkipped)
78
+ ? renderOverrideFindingsHtml(result.overrideFindings, result.subfolder, result.overrideSkipped)
79
79
  : "";
80
80
  const maintenanceHtml = includeMaintenance
81
81
  ? renderMaintenanceFindingsHtml(result.maintenanceFindings)
@@ -143,7 +143,13 @@ function renderFolderSection(result, folderIdx, idxOffset, serialized, projectRo
143
143
  </details>`;
144
144
  }
145
145
  export async function writeMultiFolderHtmlReport(params) {
146
- fs.mkdirSync(params.outputDir, { recursive: true });
146
+ const dirExisted = fs.existsSync(params.outputDir);
147
+ try {
148
+ fs.mkdirSync(params.outputDir, { recursive: true });
149
+ }
150
+ catch (err) {
151
+ throw new Error(`Failed to create report directory ${params.outputDir}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
152
+ }
147
153
  const projectName = path.basename(params.projectPath);
148
154
  const scanDate = new Date().toLocaleString();
149
155
  const counts = summaryCounts(params.results);
@@ -178,7 +184,7 @@ export async function writeMultiFolderHtmlReport(params) {
178
184
  let idxOffset = 0;
179
185
  const folderSectionsHtml = params.results
180
186
  .map((r, fi) => {
181
- const html = renderFolderSection(r, fi, idxOffset, allSerialized[fi], params.projectPath, params.includeOverrides, params.includeMaintenance, params.includeLicenses);
187
+ const html = renderFolderSection(r, fi, idxOffset, allSerialized[fi], params.includeOverrides, params.includeMaintenance, params.includeLicenses);
182
188
  idxOffset += r.sorted.length;
183
189
  return html;
184
190
  })
@@ -190,7 +196,7 @@ export async function writeMultiFolderHtmlReport(params) {
190
196
  <head>
191
197
  <meta charset="UTF-8">
192
198
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
193
- <title>CVE Lite — ${escapeHtml(projectName)}</title>
199
+ <title>CVE Lite - ${escapeHtml(projectName)}</title>
194
200
  <style>
195
201
  ${REPORT_STYLES}
196
202
  .folder-section{margin:0 32px 16px;background:#161b22;border:1px solid #30363d;border-radius:8px;overflow:hidden}
@@ -387,9 +393,9 @@ document.addEventListener('click', function(e) {
387
393
  </script>
388
394
  </body>
389
395
  </html>`;
390
- // Same --json multi-folder shape, plus cliVersion for saved-artifact provenance
391
- // (scannedAt is already on the multi-folder payload) and per-finding
392
- // riskSummary/nextAction from serializeHtmlFinding.
396
+ // Same --json multi-folder shape, plus per-finding riskSummary/nextAction
397
+ // from serializeHtmlFinding. Saved-artifact provenance (cliVersion,
398
+ // scannedAt, effectiveOptions) comes from the builder (#1296).
393
399
  const jsonPayload = {
394
400
  ...buildMultiFolderScanJson({
395
401
  results: params.results,
@@ -397,14 +403,68 @@ document.addEventListener('click', function(e) {
397
403
  includeOverrides: params.includeOverrides,
398
404
  includeMaintenance: params.includeMaintenance,
399
405
  includeLicenses: params.includeLicenses,
406
+ provenance: params.options
407
+ ? { cliVersion: params.cliVersion, options: params.options }
408
+ : undefined,
400
409
  }),
410
+ // cliVersion was always attached here; keep it unconditional and add
411
+ // effectiveOptions alongside when options are available (#1296).
401
412
  cliVersion: params.cliVersion,
402
413
  findings: reportData.findings,
403
414
  };
404
415
  const indexPath = path.join(params.outputDir, "index.html");
405
416
  const jsonPath = path.join(params.outputDir, "report.json");
406
- fs.writeFileSync(jsonPath, JSON.stringify(jsonPayload, null, 2), "utf8");
407
- fs.writeFileSync(indexPath, html, "utf8");
417
+ const tempJsonPath = path.join(params.outputDir, `.report.json.${randomUUID()}.tmp`);
418
+ const tempIndexPath = path.join(params.outputDir, `.index.html.${randomUUID()}.tmp`);
419
+ const backupJsonPath = path.join(params.outputDir, `.report.json.bak.${randomUUID()}.tmp`);
420
+ let jsonBackedUp = false;
421
+ let jsonReplaced = false;
422
+ try {
423
+ fs.writeFileSync(tempJsonPath, JSON.stringify(jsonPayload, null, 2), "utf8");
424
+ fs.writeFileSync(tempIndexPath, html, "utf8");
425
+ if (fs.existsSync(jsonPath)) {
426
+ fs.renameSync(jsonPath, backupJsonPath);
427
+ jsonBackedUp = true;
428
+ }
429
+ fs.renameSync(tempJsonPath, jsonPath);
430
+ jsonReplaced = true;
431
+ fs.renameSync(tempIndexPath, indexPath);
432
+ if (jsonBackedUp) {
433
+ try {
434
+ fs.rmSync(backupJsonPath, { force: true, recursive: true });
435
+ }
436
+ catch { /* best-effort cleanup */ }
437
+ }
438
+ }
439
+ catch (err) {
440
+ if (jsonBackedUp) {
441
+ try {
442
+ fs.renameSync(backupJsonPath, jsonPath);
443
+ }
444
+ catch { /* best-effort restore */ }
445
+ }
446
+ else if (jsonReplaced) {
447
+ try {
448
+ fs.rmSync(jsonPath, { force: true, recursive: true });
449
+ }
450
+ catch { /* best-effort cleanup */ }
451
+ }
452
+ try {
453
+ fs.rmSync(tempJsonPath, { force: true, recursive: true });
454
+ }
455
+ catch { /* best-effort cleanup */ }
456
+ try {
457
+ fs.rmSync(tempIndexPath, { force: true, recursive: true });
458
+ }
459
+ catch { /* best-effort cleanup */ }
460
+ if (!dirExisted) {
461
+ try {
462
+ fs.rmSync(params.outputDir, { recursive: true, force: true });
463
+ }
464
+ catch { /* best-effort cleanup */ }
465
+ }
466
+ throw new Error(`Failed to write HTML report to ${params.outputDir}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
467
+ }
408
468
  if (params.autoOpen)
409
469
  openInBrowser(indexPath);
410
470
  return { reportPath: indexPath };