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
package/dist/scanner.js CHANGED
@@ -1,8 +1,11 @@
1
+ import { findParentUpgradeBlockers } from "./remediation/parent-upgrade-blockers.js";
2
+ import { readWorkspaceMemberManifests } from "./utils/package-json.js";
1
3
  import { fetchEpssScores } from "./epss/client.js";
2
4
  import { chunk, runWithConcurrency } from "./utils/array.js";
3
5
  import { isPrivateRegistrySource, isGitSource, hasCommitShaPinning } from "./utils/advisory.js";
4
- import { extractCveAliases, hasMaliciousAdvisory } from "./utils/vuln.js";
5
- import { compareVersions, isPreReleaseVersion, normalizeAdvisoryVersion } from "./utils/version.js";
6
+ import { collapseAliasedDuplicates, extractCveAliases, hasMaliciousAdvisory } from "./utils/vuln.js";
7
+ import { compareVersions, isPep440Ecosystem, isPreReleaseVersion, looksLikeVersion, normalizeAdvisoryVersion } from "./utils/version.js";
8
+ import { pep440UnreadableApplies, readPep440Range, versionInPep440Window } from "./utils/versions/osv-range.js";
6
9
  import { loadCache, saveCache, isEntryStale } from "./osv/cache.js";
7
10
  import { maxSeverity } from "./osv/severity.js";
8
11
  import { createSpinner } from "./output/spinner.js";
@@ -12,18 +15,25 @@ import { queryNpmAdvisoryGaps } from "./advisory/npm-advisory-source.js";
12
15
  import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
13
16
  import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
14
17
  import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
15
- import { configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, runWithObserver, } from "./remediation/npm-registry.js";
18
+ import { configureNpmRegistry, configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, runWithObserver, } from "./remediation/npm-registry.js";
16
19
  import { countBySeverity } from "./utils/severity.js";
17
- import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry } from "./remediation/npm-transitive-resolution.js";
20
+ import { isNpmLockSource, packageManagerForSource } from "./utils/package-manager-source.js";
21
+ import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry, } from "./remediation/npm-transitive-resolution.js";
18
22
  import { resolveChainFix } from "./remediation/transitive-chain-resolver.js";
19
23
  import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js";
24
+ import { loadPnpmLockGraph } from "./parsers/pnpm-lock-graph.js";
25
+ import { loadYarnLockGraph } from "./parsers/yarn-lock-graph.js";
26
+ import { loadBunLockGraph } from "./parsers/bun-lock-graph.js";
20
27
  import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
21
28
  import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
22
29
  import { buildBunWorkspaceMap } from "./parsers/bun-lock.js";
23
30
  import { pluralize } from "./utils/string.js";
31
+ import path from "node:path";
32
+ import { resolveRegistryConfig } from "./utils/registry-config.js";
24
33
  import { extractErrorMessage } from "./utils/network.js";
25
34
  import { logWarn } from "./output/formatters.js";
26
35
  import { formatDiagnosticMessage } from "./scan/completeness.js";
36
+ import { packageInstanceKey, registryPackage, registryPackageName } from "./utils/package-identity.js";
27
37
  /**
28
38
  * Advisory id namespaces OSV does not serve. Ids with these prefixes come from
29
39
  * a different source, so OSV failing to resolve them is expected and must not
@@ -56,18 +66,7 @@ export function createAdvisorySource(options) {
56
66
  };
57
67
  }
58
68
  function getPackageCacheKey(pkg) {
59
- return `${pkg.ecosystem}:${pkg.name}@${pkg.version}`;
60
- }
61
- function inferPackageManagerForChain(source) {
62
- if (source === "package-lock" || source === "npm-shrinkwrap")
63
- return "npm";
64
- if (source === "pnpm-lock")
65
- return "pnpm";
66
- if (source === "yarn-lock")
67
- return "yarn";
68
- if (source === "bun-lock")
69
- return "bun";
70
- return null;
69
+ return `${pkg.ecosystem}:${registryPackageName(pkg)}@${pkg.version}`;
71
70
  }
72
71
  function isTransientFailure(error) {
73
72
  if (!(error instanceof Error))
@@ -80,16 +79,22 @@ function isTransientFailure(error) {
80
79
  function mergeResultsByPackage(results) {
81
80
  const map = new Map();
82
81
  for (const result of results) {
83
- const key = `${result.pkg.name}@${result.pkg.version}`;
82
+ const key = packageInstanceKey(result.pkg);
84
83
  const existing = map.get(key);
85
84
  if (existing) {
86
85
  for (const id of result.vulnIds) {
87
86
  if (!existing.vulnIds.includes(id))
88
87
  existing.vulnIds.push(id);
89
88
  }
89
+ if (result.unreadable)
90
+ existing.unreadable = true;
90
91
  }
91
92
  else {
92
- map.set(key, { pkg: result.pkg, vulnIds: [...result.vulnIds] });
93
+ map.set(key, {
94
+ pkg: result.pkg,
95
+ vulnIds: [...result.vulnIds],
96
+ ...(result.unreadable ? { unreadable: true } : {}),
97
+ });
93
98
  }
94
99
  }
95
100
  return [...map.values()];
@@ -112,9 +117,26 @@ export async function scanPackages(packages, batchSize, options, context, debugL
112
117
  if (!offline && options.debug) {
113
118
  configureNpmRegistryDebug(log);
114
119
  }
120
+ // Point metadata lookups at the registry this project installs from, so a fix
121
+ // version is validated against the registry the user would actually install it
122
+ // from rather than against public npm. Unconfigured projects resolve to the
123
+ // public registry, which is the previous behaviour.
124
+ const registryConfig = resolveRegistryConfig({
125
+ projectPath: context?.scanFilePath ? path.dirname(context.scanFilePath) : process.cwd(),
126
+ packageManager: packageManagerForSource(context?.scanSource),
127
+ });
128
+ configureNpmRegistry(registryConfig);
129
+ if (options.debug) {
130
+ log("Registry config", {
131
+ registry: registryConfig.registry,
132
+ scopes: Object.keys(registryConfig.scopes),
133
+ sourceFile: registryConfig.sourceFile,
134
+ });
135
+ }
115
136
  const cache = loadCache(cacheDirOverride, options.debug ? log : undefined);
116
137
  try {
117
138
  const results = [];
139
+ let unreadableBoundaryPackages = 0;
118
140
  const uncachedPackages = [];
119
141
  if (!offline) {
120
142
  const nowMs = Date.now();
@@ -144,8 +166,8 @@ export async function scanPackages(packages, batchSize, options, context, debugL
144
166
  const allAdvisoryResults = await runWithConcurrency(chunks, 5, c => {
145
167
  batchCounter += 1;
146
168
  const batchId = `b-${String(batchCounter).padStart(2, "0")}`;
147
- return advisorySource.queryBatch(c, { batchId });
148
- });
169
+ return advisorySource.queryBatch(c.map(registryPackage), { batchId });
170
+ }, { onError: "stop" });
149
171
  const cachedAt = new Date().toISOString();
150
172
  for (let i = 0; i < chunks.length; i++) {
151
173
  const chunkItems = chunks[i];
@@ -153,8 +175,8 @@ export async function scanPackages(packages, batchSize, options, context, debugL
153
175
  for (let j = 0; j < chunkItems.length; j++) {
154
176
  const pkg = chunkItems[j];
155
177
  const row = rows[j];
156
- if (row && (row.package !== pkg.name || row.version !== pkg.version)) {
157
- throw new Error(`OSV result identity mismatch at index ${j}: expected ${pkg.name}@${pkg.version}, got ${row.package}@${row.version}`);
178
+ if (row && (row.package !== registryPackageName(pkg) || row.version !== pkg.version)) {
179
+ throw new Error(`OSV result identity mismatch at index ${j}: expected ${registryPackageName(pkg)}@${pkg.version}, got ${row.package}@${row.version}`);
158
180
  }
159
181
  const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
160
182
  cache.queryEntries[getPackageCacheKey(pkg)] = { vulnIds, cachedAt };
@@ -178,14 +200,17 @@ export async function scanPackages(packages, batchSize, options, context, debugL
178
200
  }
179
201
  }
180
202
  else {
181
- const advisoryResult = await advisorySource.queryBatch(packages, { batchId: "offline" });
203
+ const advisoryResult = await advisorySource.queryBatch(packages.map(registryPackage), { batchId: "offline" });
182
204
  const rows = advisoryResult ?? [];
183
205
  for (let i = 0; i < packages.length; i++) {
184
206
  const pkg = packages[i];
185
207
  const row = rows[i];
186
208
  const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
209
+ const unreadable = row?.unreadableBoundary === true;
210
+ if (unreadable)
211
+ unreadableBoundaryPackages += 1;
187
212
  if (vulnIds.length > 0) {
188
- results.push({ pkg, vulnIds });
213
+ results.push({ pkg, vulnIds, ...(unreadable ? { unreadable: true } : {}) });
189
214
  }
190
215
  }
191
216
  spinner.succeed("Loaded package matches from the local advisory database");
@@ -227,13 +252,13 @@ export async function scanPackages(packages, batchSize, options, context, debugL
227
252
  }
228
253
  }
229
254
  if (uncachedForNpm.length > 0) {
230
- const npmResults = await queryNpmAdvisoryGaps(uncachedForNpm, {
255
+ const npmResults = await queryNpmAdvisoryGaps(uncachedForNpm.map(registryPackage), {
231
256
  fetchImpl,
232
257
  offline,
233
258
  debugLog: log,
234
259
  });
235
260
  for (const pkg of uncachedForNpm) {
236
- const found = npmResults.find(r => r.pkg.name === pkg.name && r.pkg.version === pkg.version);
261
+ const found = npmResults.find(r => r.pkg.name === registryPackageName(pkg) && r.pkg.version === pkg.version);
237
262
  const vulns = found?.vulns ?? [];
238
263
  // Store the full advisories in cache, not just their ids, so a later scan
239
264
  // can restore the detail rather than going looking for it in OSV, which
@@ -363,15 +388,17 @@ export async function scanPackages(packages, batchSize, options, context, debugL
363
388
  saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
364
389
  }
365
390
  const findings = mergeResultsByPackage(results).map(result => {
366
- const vulnerabilities = result.vulnIds
367
- .map(id => vulnMap.get(id))
368
- .filter((v) => Boolean(v));
391
+ // Collapse advisory records OSV marks as the same vulnerability before
392
+ // anything downstream counts them, so the terminal, JSON, SARIF, both SBOM
393
+ // formats and the HTML report all see one list.
394
+ const vulnerabilities = collapseAliasedDuplicates(result.vulnIds.map(id => vulnMap.get(id)).filter((v) => Boolean(v)));
369
395
  const unresolvedIds = result.vulnIds.filter(id => !vulnMap.has(id));
370
396
  const severity = maxSeverity(vulnerabilities);
371
397
  const cveAliases = extractCveAliases(vulnerabilities);
372
398
  const dependencyPaths = result.pkg.paths ?? [];
373
399
  const relationship = classifyRelationship(dependencyPaths, result.pkg.name, context?.directDependencyNames);
374
- const firstFixedVersion = findFirstFixedVersion(vulnerabilities, result.pkg.name, result.pkg.ecosystem, result.pkg.version);
400
+ const selectedFix = selectFixedVersion(vulnerabilities, registryPackageName(result.pkg), result.pkg.ecosystem, result.pkg.version);
401
+ const advisoryBoundaryUnreadable = selectedFix.unreadable || result.unreadable === true;
375
402
  return {
376
403
  pkg: result.pkg,
377
404
  vulnerabilities,
@@ -379,7 +406,8 @@ export async function scanPackages(packages, batchSize, options, context, debugL
379
406
  cveAliases,
380
407
  dependencyPaths,
381
408
  relationship,
382
- firstFixedVersion,
409
+ firstFixedVersion: advisoryBoundaryUnreadable ? null : selectedFix.version,
410
+ ...(advisoryBoundaryUnreadable ? { advisoryBoundaryUnreadable: true } : {}),
383
411
  validatedFirstFixedVersion: null,
384
412
  fixVersionValidationNote: null,
385
413
  fixVersionPublishedAt: null,
@@ -390,6 +418,12 @@ export async function scanPackages(packages, batchSize, options, context, debugL
390
418
  ...(unresolvedIds.length > 0 ? { unresolvedAdvisoryIds: unresolvedIds } : {}),
391
419
  };
392
420
  });
421
+ // Parent resolvers interpret path segments as registry names. Until they
422
+ // support aliases, do not let them recommend a different package that
423
+ // happens to be published under an installed alias's name.
424
+ const aliasNames = new Set(packages.filter(pkg => pkg.registryName).map(pkg => pkg.name));
425
+ const aliasRemediationFindings = new Set(findings.filter(finding => finding.relationship === "transitive"
426
+ && finding.dependencyPaths.some(dependencyPath => dependencyPath.some(name => aliasNames.has(name)))));
393
427
  const unresolvedDetailIds = idSet.size > 0
394
428
  ? [...idSet].filter(id => !vulnMap.has(id))
395
429
  : [];
@@ -400,10 +434,10 @@ export async function scanPackages(packages, batchSize, options, context, debugL
400
434
  const otherCount = unresolvedDetailIds.length - transientCount - offlineCount - confirmedCount;
401
435
  const parts = [];
402
436
  if (transientCount > 0) {
403
- parts.push(`${transientCount} from transient failures — re-run to retry`);
437
+ parts.push(`${transientCount} from transient failures: re-run to retry`);
404
438
  }
405
439
  if (offlineCount > 0) {
406
- parts.push(`${offlineCount} missing from local advisory database — refresh to sync`);
440
+ parts.push(`${offlineCount} missing from local advisory database: refresh to sync`);
407
441
  }
408
442
  if (confirmedCount > 0) {
409
443
  parts.push(`${confirmedCount} confirmed missing from the OSV API`);
@@ -411,7 +445,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
411
445
  if (otherCount > 0) {
412
446
  parts.push(`${otherCount} could not be resolved`);
413
447
  }
414
- logWarn(`⚠ ${unresolvedDetailIds.length} advisory detail ${pluralize(unresolvedDetailIds.length, "lookup")} missing from findings. ${parts.join("; ")}.`, { json: options.json });
448
+ logWarn(`⚠ ${unresolvedDetailIds.length} advisory detail ${pluralize(unresolvedDetailIds.length, "lookup")} missing from findings. ${parts.join("; ")}.`, { json: options.json, output: options.output });
415
449
  }
416
450
  for (const finding of findings) {
417
451
  if (hasMaliciousAdvisory(finding.vulnerabilities)) {
@@ -424,12 +458,14 @@ export async function scanPackages(packages, batchSize, options, context, debugL
424
458
  }
425
459
  }
426
460
  }
427
- const npmTransitiveGraph = context?.scanSource === "package-lock" && context.scanFilePath
461
+ const npmTransitiveGraph = isNpmLockSource(context?.scanSource) && context?.scanFilePath
428
462
  ? createNpmTransitiveGraphFromLockfile(context.scanFilePath, log, packages.length)
429
463
  : null;
464
+ const lockParentGraph = loadLockParentGraph(context?.scanSource, context?.scanFilePath, log);
465
+ const workspaceMemberNames = readWorkspaceMemberNames(context?.scanFilePath);
430
466
  const npmWorkspaceMap = (() => {
431
467
  try {
432
- return context?.scanSource === "package-lock" && context.scanFilePath
468
+ return isNpmLockSource(context?.scanSource) && context?.scanFilePath
433
469
  ? buildNpmWorkspaceMap(context.scanFilePath) : null;
434
470
  }
435
471
  catch (error) {
@@ -442,7 +478,10 @@ export async function scanPackages(packages, batchSize, options, context, debugL
442
478
  }
443
479
  })();
444
480
  if (npmWorkspaceMap) {
445
- log("Workspace map", { type: "npm", workspaces: npmWorkspaceMap.size });
481
+ log("Workspace map", {
482
+ type: "npm",
483
+ dependencyCount: npmWorkspaceMap.size,
484
+ });
446
485
  }
447
486
  const pnpmWorkspaceMap = (() => {
448
487
  try {
@@ -459,7 +498,10 @@ export async function scanPackages(packages, batchSize, options, context, debugL
459
498
  }
460
499
  })();
461
500
  if (pnpmWorkspaceMap) {
462
- log("Workspace map", { type: "pnpm", workspaces: pnpmWorkspaceMap.size });
501
+ log("Workspace map", {
502
+ type: "pnpm",
503
+ dependencyCount: pnpmWorkspaceMap.size,
504
+ });
463
505
  }
464
506
  const bunWorkspaceMap = (() => {
465
507
  try {
@@ -476,7 +518,10 @@ export async function scanPackages(packages, batchSize, options, context, debugL
476
518
  }
477
519
  })();
478
520
  if (bunWorkspaceMap) {
479
- log("Workspace map", { type: "bun", workspaces: bunWorkspaceMap.size });
521
+ log("Workspace map", {
522
+ type: "bun",
523
+ dependencyCount: bunWorkspaceMap.size,
524
+ });
480
525
  }
481
526
  const lockfileWorkspaceMap = pnpmWorkspaceMap ?? bunWorkspaceMap ?? null;
482
527
  const packumentFailures = new Set();
@@ -522,6 +567,9 @@ export async function scanPackages(packages, batchSize, options, context, debugL
522
567
  for (const finding of findings) {
523
568
  if (finding.relationship !== "transitive")
524
569
  continue;
570
+ if (aliasRemediationFindings.has(finding)) {
571
+ continue;
572
+ }
525
573
  packumentsToPrewarm.add(finding.pkg.name);
526
574
  const paths = finding.dependencyPaths;
527
575
  if (paths.length > 0 && paths[0].length >= 2) {
@@ -538,6 +586,11 @@ export async function scanPackages(packages, batchSize, options, context, debugL
538
586
  if (finding.relationship !== "transitive")
539
587
  continue;
540
588
  updateAnalysisProgress("resolving remediation for", `${finding.pkg.name}@${finding.pkg.version}`);
589
+ if (aliasRemediationFindings.has(finding)) {
590
+ const aliasNote = `Automatic parent remediation is unavailable for paths containing an npm alias. Run \`npm ls ${finding.pkg.name}\` to inspect the declaring dependency, then rescan after updating it.`;
591
+ finding.fixVersionValidationNote = [finding.fixVersionValidationNote, aliasNote].filter(Boolean).join(" ");
592
+ continue;
593
+ }
541
594
  const remediationCacheKey = JSON.stringify({
542
595
  package: finding.pkg.name,
543
596
  version: finding.pkg.version,
@@ -572,6 +625,11 @@ export async function scanPackages(packages, batchSize, options, context, debugL
572
625
  confidence: "verified",
573
626
  reason: finding.recommendedNpmTransitiveRemediation.reason,
574
627
  };
628
+ finding.parentUpgradeBlockers = await blockersForParentUpgrade(finding, {
629
+ packages,
630
+ workspaceMemberNames,
631
+ npmGraph: npmTransitiveGraph,
632
+ });
575
633
  continue;
576
634
  }
577
635
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
@@ -590,6 +648,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
590
648
  packages,
591
649
  directDependencyNames: context?.directDependencyNames,
592
650
  workspaceMap: lockfileWorkspaceMap,
651
+ parentGraph: lockParentGraph,
593
652
  });
594
653
  npmRemediationCache.set(remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null);
595
654
  }
@@ -605,6 +664,12 @@ export async function scanPackages(packages, batchSize, options, context, debugL
605
664
  finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade(finding, packages, context?.directDependencyNames, { offline });
606
665
  parentUpgradeCache.set(remediationCacheKey, finding.recommendedParentUpgrade ?? null);
607
666
  }
667
+ finding.parentUpgradeBlockers = await blockersForParentUpgrade(finding, {
668
+ packages,
669
+ workspaceMemberNames,
670
+ npmGraph: npmTransitiveGraph,
671
+ lockParentGraph,
672
+ });
608
673
  }
609
674
  catch (error) {
610
675
  const packageName = finding.pkg.name;
@@ -620,11 +685,11 @@ export async function scanPackages(packages, batchSize, options, context, debugL
620
685
  }
621
686
  analysisSpinner.succeed("Analyzed vulnerability findings");
622
687
  // Chain fix resolution: pre-compute validated chain for transitive findings
623
- const chainPm = inferPackageManagerForChain(context?.scanSource);
688
+ const chainPm = packageManagerForSource(context?.scanSource);
624
689
  if (chainPm) {
625
690
  const installedVersions = new Map(packages.map(p => [p.name, p.version]));
626
691
  await Promise.all(findings
627
- .filter(f => f.relationship === "transitive" && f.dependencyPaths?.length)
692
+ .filter(f => f.relationship === "transitive" && f.dependencyPaths?.length && !aliasRemediationFindings.has(f))
628
693
  .map(async (finding) => {
629
694
  try {
630
695
  finding.chainResolution = await resolveChainFix(finding, installedVersions, chainPm, { offline });
@@ -676,6 +741,8 @@ export async function scanPackages(packages, batchSize, options, context, debugL
676
741
  packumentFailures,
677
742
  remediationFailures,
678
743
  chainResolutionFailureCount,
744
+ unreadableBoundaryPackages,
745
+ unreadableFixPackages: findings.filter(finding => finding.advisoryBoundaryUnreadable).length,
679
746
  });
680
747
  const completeness = {
681
748
  complete: diagnostics.length === 0,
@@ -694,6 +761,35 @@ export async function scanPackages(packages, batchSize, options, context, debugL
694
761
  sourceContext.cleanup();
695
762
  }
696
763
  }
764
+ // Direct dependencies that keep the vulnerable copy installed after the
765
+ // recommended parent upgrade, judged against the first safe version (#1457).
766
+ async function blockersForParentUpgrade(finding, graphs) {
767
+ const upgrade = finding.recommendedParentUpgrade;
768
+ // Without a known fixed version, test the child version the upgrade moves to.
769
+ const safeVersion = finding.validatedFirstFixedVersion
770
+ ?? finding.firstFixedVersion
771
+ ?? finding.recommendedNpmTransitiveRemediation?.targetChildVersion;
772
+ if (!upgrade || !safeVersion)
773
+ return undefined;
774
+ const blockers = await findParentUpgradeBlockers({
775
+ childName: finding.pkg.name,
776
+ childVersion: finding.pkg.version,
777
+ targetChildVersion: safeVersion,
778
+ upgradedParent: upgrade.package,
779
+ packages: graphs.packages,
780
+ workspaceMemberNames: graphs.workspaceMemberNames,
781
+ npmGraph: graphs.npmGraph,
782
+ lockParentGraph: graphs.lockParentGraph,
783
+ });
784
+ return blockers.length > 0 ? blockers : undefined;
785
+ }
786
+ function readWorkspaceMemberNames(scanFilePath) {
787
+ if (!scanFilePath)
788
+ return new Set();
789
+ return new Set(readWorkspaceMemberManifests(path.dirname(scanFilePath))
790
+ .map(member => member.manifest.name)
791
+ .filter((name) => typeof name === "string"));
792
+ }
697
793
  function createNpmTransitiveGraphFromLockfile(filePath, log, packageCount) {
698
794
  try {
699
795
  const lockGraph = loadNpmLockGraph(filePath, { includePaths: false });
@@ -714,6 +810,12 @@ function createNpmTransitiveGraphFromLockfile(filePath, log, packageCount) {
714
810
  rangeFor(parentNodeId, childName) {
715
811
  return lockGraph.rangeFor(parentNodeId, childName);
716
812
  },
813
+ parentsFor(nodeId) {
814
+ return lockGraph.parentsFor(nodeId);
815
+ },
816
+ peerRangesFor(nodeId) {
817
+ return lockGraph.peerRangesFor?.(nodeId) ?? [];
818
+ },
717
819
  };
718
820
  }
719
821
  catch (error) {
@@ -724,6 +826,25 @@ function createNpmTransitiveGraphFromLockfile(filePath, log, packageCount) {
724
826
  return null;
725
827
  }
726
828
  }
829
+ // Every parent of each package, for the lockfiles whose remediation goes through
830
+ // the registry. A within-range update has to suit all of them (#1291). Without
831
+ // it the route falls back to the one parent the recorded path names.
832
+ function loadLockParentGraph(source, filePath, log) {
833
+ if (!filePath)
834
+ return null;
835
+ try {
836
+ if (source === "pnpm-lock")
837
+ return loadPnpmLockGraph(filePath);
838
+ if (source === "yarn-lock")
839
+ return loadYarnLockGraph(filePath);
840
+ if (source === "bun-lock")
841
+ return loadBunLockGraph(filePath);
842
+ }
843
+ catch (error) {
844
+ log("lock parent graph", { status: "failed", error: extractErrorMessage(error) });
845
+ }
846
+ return null;
847
+ }
727
848
  async function validateDirectFixTargets(findings, onFinding, options) {
728
849
  const directCandidates = findings.filter(finding => finding.vulnerabilities.length > 0);
729
850
  const results = await runWithConcurrency(directCandidates, 8, async (finding) => {
@@ -733,6 +854,8 @@ async function validateDirectFixTargets(findings, onFinding, options) {
733
854
  return results.some(Boolean);
734
855
  }
735
856
  async function validateOneDirectFixTarget(finding, options) {
857
+ if (finding.advisoryBoundaryUnreadable)
858
+ return false;
736
859
  let npmVersionCacheUpdated = false;
737
860
  const debugLog = options?.debugLog;
738
861
  const logFixValidation = () => {
@@ -745,14 +868,14 @@ async function validateOneDirectFixTarget(finding, options) {
745
868
  };
746
869
  // The advisory source re-checks the proposed version for advisories
747
870
  // introduced above the installed one, which never matched this finding.
748
- const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities, { advisorySource: options?.advisorySource, proposedVersion: finding.firstFixedVersion });
871
+ const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(registryPackageName(finding.pkg), finding.pkg.version, finding.vulnerabilities, { advisorySource: options?.advisorySource, proposedVersion: finding.firstFixedVersion });
749
872
  const fixedVersionHint = finding.firstFixedVersion;
750
873
  const setPublishedDate = (resolution) => {
751
874
  const date = resolution.publishedAt;
752
875
  finding.fixVersionPublishedAt = date;
753
876
  if (!date || !options?.cache)
754
877
  return;
755
- const cacheKey = `${finding.pkg.name}@${finding.validatedFirstFixedVersion}`;
878
+ const cacheKey = `${registryPackageName(finding.pkg)}@${finding.validatedFirstFixedVersion}`;
756
879
  const existing = options.cache.npmVersionEntries?.[cacheKey];
757
880
  if (!options.noCache && existing?.publishedAt === date)
758
881
  return;
@@ -773,10 +896,11 @@ async function validateOneDirectFixTarget(finding, options) {
773
896
  logFixValidation();
774
897
  return npmVersionCacheUpdated;
775
898
  }
776
- const hintResolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
899
+ const hintResolution = await resolvePublishedFixVersion(registryPackageName(finding.pkg), fixedVersionHint);
777
900
  if (hintResolution.resolvedVersion === lowestKnownResolution.resolvedVersion &&
778
901
  hintResolution.note) {
779
902
  finding.fixVersionValidationNote = hintResolution.note;
903
+ finding.advisoryHintUnavailable = hintResolution.advisoryHintUnavailable ?? false;
780
904
  // date is for the validated version, not the hint
781
905
  setPublishedDate(lowestKnownResolution);
782
906
  logFixValidation();
@@ -797,13 +921,16 @@ async function validateOneDirectFixTarget(finding, options) {
797
921
  logFixValidation();
798
922
  return npmVersionCacheUpdated;
799
923
  }
800
- const resolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
924
+ const resolution = await resolvePublishedFixVersion(registryPackageName(finding.pkg), fixedVersionHint);
801
925
  // Publication confirms availability, not that every advisory is fixed.
802
926
  finding.validatedFirstFixedVersion = null;
803
927
  finding.fixVersionValidationNote = [
804
928
  lowestKnownResolution.note ?? `A non-vulnerable version could not be confirmed for ${finding.pkg.name}.`,
805
929
  resolution.note,
806
930
  ].filter(Boolean).join(" ");
931
+ // The note above is two notes joined, so the only honest way to know whether
932
+ // the hint was missing from the registry is to carry the resolver's own answer.
933
+ finding.advisoryHintUnavailable = resolution.advisoryHintUnavailable ?? false;
807
934
  finding.validatedTargetScannedVersions = null;
808
935
  finding.validatedTargetKnownVulnerableVersions = null;
809
936
  finding.fixVersionPublishedAt = null;
@@ -824,11 +951,11 @@ function classifyRelationship(paths, packageName, directDependencyNames) {
824
951
  if (packageName && directDependencyNames?.has(packageName)) {
825
952
  // The package name is declared as a direct dependency. But when multiple versions
826
953
  // of the same package are installed (one direct, one transitive), the name alone
827
- // is not enough — we need to verify this specific installed version is the direct
954
+ // is not enough - we need to verify this specific installed version is the direct
828
955
  // one. A direct install always has at least one path of length 2 (["project", name]).
829
956
  // If all paths are longer, this is a different (transitive) version of the package.
830
957
  if (paths.length === 0)
831
- return "direct"; // no path data — trust the name
958
+ return "direct"; // no path data - trust the name
832
959
  const hasDirectPath = paths.some(p => p.length <= 2);
833
960
  return hasDirectPath ? "direct" : "transitive";
834
961
  }
@@ -865,18 +992,18 @@ function affectedEntryMatchesPackage(affected, packageName, ecosystem) {
865
992
  * `introduced` of "0" (or absent) means the window has no lower bound, which is
866
993
  * how OSV expresses "every version before the fix".
867
994
  */
868
- function versionWithinAffectedWindow(version, introduced, fixed) {
995
+ function versionWithinAffectedWindow(version, introduced, fixed, ecosystem) {
869
996
  if (introduced && introduced !== "0") {
870
- // Advisories write boundaries with fewer than three components, so `2` means
871
- // 2.0.0. Normalizing rather than rejecting keeps the window usable, and a
872
- // value that is not a version at all still returns null and bails (#1192).
873
- const normalizedIntroduced = normalizeAdvisoryVersion(introduced);
997
+ // Advisories write boundaries with fewer than three components. Semver pads
998
+ // `2` to 2.0.0. PEP 440 keeps `2`, which compares equal to 2.0.0. A value
999
+ // that is not a version at all still returns null and the window is skipped.
1000
+ const normalizedIntroduced = normalizeAdvisoryVersion(introduced, ecosystem);
874
1001
  if (!normalizedIntroduced)
875
1002
  return false;
876
- if (compareVersions(version, normalizedIntroduced) < 0)
1003
+ if (compareVersions(version, normalizedIntroduced, ecosystem) < 0)
877
1004
  return false;
878
1005
  }
879
- return compareVersions(version, fixed) < 0;
1006
+ return compareVersions(version, fixed, ecosystem) < 0;
880
1007
  }
881
1008
  /**
882
1009
  * Every usable fixed version one advisory declares for this package, split into
@@ -905,16 +1032,18 @@ function collectAdvisoryFixes(vuln, packageName, ecosystem, installedVersion) {
905
1032
  introduced = event.introduced;
906
1033
  continue;
907
1034
  }
908
- // `fixed: "1.22"` is 1.22.0. Requiring a strict X.Y.Z here discarded the
909
- // event, and a finding whose every candidate was discarded reported "no
910
- // fix available", which tells a developer to stop looking for a fix that
911
- // exists (#1192). A value that cannot be read in full is still dropped,
912
- // so a commit hash from a GIT range never becomes a fix version.
913
- const fixed = normalizeAdvisoryVersion(event.fixed);
914
- if (!fixed || isPreReleaseVersion(fixed))
1035
+ // `fixed: "1.22"` is 1.22.0 for npm. PEP 440 keeps `1.22`, which compares
1036
+ // equal to 1.22.0, and a post-release such as `2026.3.post1` stays a fix.
1037
+ // Requiring a strict X.Y.Z here discarded the event, and a finding whose
1038
+ // every candidate was discarded reported "no fix available", which tells
1039
+ // a developer to stop looking for a fix that exists (#1192). A value that
1040
+ // cannot be read in full is still dropped, so a commit hash from a GIT
1041
+ // range never becomes a fix version.
1042
+ const fixed = normalizeAdvisoryVersion(event.fixed, ecosystem);
1043
+ if (!fixed || isPreReleaseVersion(fixed, ecosystem))
915
1044
  continue;
916
1045
  all.push(fixed);
917
- if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed)) {
1046
+ if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed, ecosystem)) {
918
1047
  onInstalledBranch.push(fixed);
919
1048
  }
920
1049
  introduced = null;
@@ -924,29 +1053,120 @@ function collectAdvisoryFixes(vuln, packageName, ecosystem, installedVersion) {
924
1053
  return { all, onInstalledBranch };
925
1054
  }
926
1055
  export function findFirstFixedVersion(vulns, packageName, ecosystem, installedVersion) {
1056
+ return selectFixedVersion(vulns, packageName, ecosystem, installedVersion).version;
1057
+ }
1058
+ /**
1059
+ * The fix to recommend, and whether a PyPI boundary that might contain the
1060
+ * installed version could not be read. An unreadable boundary leaves the
1061
+ * version null and does not stop the scan. npm never sets `unreadable`.
1062
+ */
1063
+ export function selectFixedVersion(vulns, packageName, ecosystem, installedVersion) {
1064
+ if (isPep440Ecosystem(ecosystem)) {
1065
+ return selectPep440FixedVersion(vulns, packageName, ecosystem, installedVersion);
1066
+ }
1067
+ return {
1068
+ version: selectNpmFixedVersion(vulns, packageName, ecosystem, installedVersion),
1069
+ unreadable: false,
1070
+ };
1071
+ }
1072
+ function selectNpmFixedVersion(vulns, packageName, ecosystem, installedVersion) {
927
1073
  const everyKnownFix = [];
928
1074
  // One entry per advisory: the earliest version clearing THAT advisory on the
929
1075
  // branch the install sits on.
930
1076
  const perAdvisoryFixes = [];
1077
+ const byVersion = (left, right) => compareVersions(left, right, ecosystem);
931
1078
  for (const vuln of vulns) {
932
1079
  const { all, onInstalledBranch } = collectAdvisoryFixes(vuln, packageName, ecosystem, installedVersion);
933
1080
  everyKnownFix.push(...all);
934
1081
  if (onInstalledBranch.length > 0) {
935
1082
  // Lowest WITHIN one advisory: the branch fix, not the other branch's.
936
- perAdvisoryFixes.push(onInstalledBranch.sort(compareVersions)[0]);
1083
+ perAdvisoryFixes.push(onInstalledBranch.sort(byVersion)[0]);
937
1084
  }
938
1085
  }
939
1086
  // Highest ACROSS advisories: the caller needs a version clear of all of them,
940
1087
  // and stopping at the lowest leaves every advisory fixed above it still live.
941
1088
  if (perAdvisoryFixes.length > 0) {
942
- return perAdvisoryFixes.sort(compareVersions)[perAdvisoryFixes.length - 1];
1089
+ return perAdvisoryFixes.sort(byVersion)[perAdvisoryFixes.length - 1];
943
1090
  }
944
1091
  // No declared window contains the installed version, so there is no branch to
945
1092
  // scope to. Falling back to every known fix keeps a finding's remediation
946
1093
  // visible rather than reporting none.
947
1094
  if (everyKnownFix.length === 0)
948
1095
  return null;
949
- return everyKnownFix.sort(compareVersions)[0];
1096
+ return everyKnownFix.sort(byVersion)[0];
1097
+ }
1098
+ function selectPep440FixedVersion(vulns, packageName, ecosystem, installedVersion) {
1099
+ if (installedVersion && !looksLikeVersion(installedVersion, ecosystem)) {
1100
+ return { version: null, unreadable: true };
1101
+ }
1102
+ const everyKnownFix = [];
1103
+ const perAdvisoryFixes = [];
1104
+ let unreadable = false;
1105
+ let blocked = false;
1106
+ const byVersion = (left, right) => compareVersions(left, right, ecosystem);
1107
+ for (const vuln of vulns) {
1108
+ const branchFixes = [];
1109
+ let advisoryUnreadable = false;
1110
+ let heldWithoutFix = false;
1111
+ for (const affected of vuln.affected ?? []) {
1112
+ if (!affectedEntryMatchesPackage(affected, packageName, ecosystem))
1113
+ continue;
1114
+ for (const range of affected.ranges ?? []) {
1115
+ const rangeType = range.type;
1116
+ if (rangeType === "GIT")
1117
+ continue;
1118
+ if (rangeType && rangeType !== "ECOSYSTEM" && rangeType !== "SEMVER")
1119
+ continue;
1120
+ const read = readPep440Range(range.events ?? []);
1121
+ if (!installedVersion) {
1122
+ if (read.unreadable.length > 0)
1123
+ advisoryUnreadable = true;
1124
+ }
1125
+ else if (read.unreadable.some(boundary => pep440UnreadableApplies(installedVersion, boundary))) {
1126
+ advisoryUnreadable = true;
1127
+ }
1128
+ for (const fix of read.fixes) {
1129
+ if (!isPreReleaseVersion(fix, ecosystem))
1130
+ everyKnownFix.push(fix);
1131
+ }
1132
+ if (!installedVersion)
1133
+ continue;
1134
+ for (const window of read.windows) {
1135
+ if (!versionInPep440Window(installedVersion, window))
1136
+ continue;
1137
+ if (window.fixed && !isPreReleaseVersion(window.fixed, ecosystem))
1138
+ branchFixes.push(window.fixed);
1139
+ else
1140
+ heldWithoutFix = true;
1141
+ }
1142
+ }
1143
+ }
1144
+ if (advisoryUnreadable) {
1145
+ unreadable = true;
1146
+ continue;
1147
+ }
1148
+ if (heldWithoutFix)
1149
+ blocked = true;
1150
+ else if (branchFixes.length > 0)
1151
+ perAdvisoryFixes.push(branchFixes.sort(byVersion)[0]);
1152
+ }
1153
+ if (unreadable)
1154
+ return { version: null, unreadable: true };
1155
+ if (blocked)
1156
+ return { version: null, unreadable: false };
1157
+ if (perAdvisoryFixes.length > 0) {
1158
+ return { version: perAdvisoryFixes.sort(byVersion)[perAdvisoryFixes.length - 1], unreadable: false };
1159
+ }
1160
+ // No window contains the installed version. A fix it has already reached can
1161
+ // still be named (a patched 2.x build still names the 1.x fix). A later fix
1162
+ // it has not reached belongs to another window, and recommending it would
1163
+ // treat an unaffected version as vulnerable.
1164
+ if (everyKnownFix.length === 0)
1165
+ return { version: null, unreadable: false };
1166
+ if (installedVersion && everyKnownFix.every(fix => byVersion(installedVersion, fix) < 0)) {
1167
+ return { version: null, unreadable: false };
1168
+ }
1169
+ return { version: everyKnownFix.sort(byVersion)[0], unreadable: false };
950
1170
  }
951
1171
  function buildCompletenessDiagnostics(params) {
952
1172
  const diagnostics = [];
@@ -956,7 +1176,7 @@ function buildCompletenessDiagnostics(params) {
956
1176
  diagnostics.push({
957
1177
  code,
958
1178
  severity: "warning",
959
- message: formatDiagnosticMessage(code, count, affectedPackageCount),
1179
+ message: formatDiagnosticMessage(code, count, affectedPackageCount, impact),
960
1180
  impact,
961
1181
  count,
962
1182
  ...(affectedPackageCount === undefined ? {} : { affectedPackageCount }),
@@ -969,6 +1189,8 @@ function buildCompletenessDiagnostics(params) {
969
1189
  addDiagnostic("PACKUMENT_FETCH_FAILURE", params.packumentFailures.size, "remediation");
970
1190
  addDiagnostic("REMEDIATION_FAILURE", remediationTotal, "remediation", params.remediationFailures.size);
971
1191
  addDiagnostic("CHAIN_RESOLUTION_FAILURE", params.chainResolutionFailureCount, "remediation");
1192
+ addDiagnostic("UNREADABLE_PYPI_BOUNDARY", params.unreadableBoundaryPackages, "detection");
1193
+ addDiagnostic("UNREADABLE_PYPI_BOUNDARY", params.unreadableFixPackages, "remediation");
972
1194
  return diagnostics;
973
1195
  }
974
1196
  async function enrichWithEpssScores(findings, fetchImpl) {