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,9 +1,10 @@
1
- import { compareVersions, looksLikeVersion } from "../utils/version.js";
1
+ import { compareVersions, looksLikeVersion, satisfiesRange } from "../utils/version.js";
2
2
  export function createNpmTransitiveGraph(args) {
3
3
  const nodesById = new Map();
4
4
  const nodeIdsByPackageKey = new Map();
5
5
  const childNodeIdsByParentNodeId = new Map();
6
6
  const rangeByParentNodeId = new Map();
7
+ const parentNodeIdsByChildNodeId = new Map();
7
8
  for (const node of args.nodes) {
8
9
  nodesById.set(node.id, { ...node });
9
10
  nodeIdsByPackageKey.set(buildPackageKey(node.name, node.version), [
@@ -16,6 +17,10 @@ export function createNpmTransitiveGraph(args) {
16
17
  ...(childNodeIdsByParentNodeId.get(edge.parentNodeId) ?? []),
17
18
  edge.childNodeId,
18
19
  ]);
20
+ parentNodeIdsByChildNodeId.set(edge.childNodeId, [
21
+ ...(parentNodeIdsByChildNodeId.get(edge.childNodeId) ?? []),
22
+ edge.parentNodeId,
23
+ ]);
19
24
  const ranges = rangeByParentNodeId.get(edge.parentNodeId) ?? new Map();
20
25
  ranges.set(edge.childName, edge.range);
21
26
  rangeByParentNodeId.set(edge.parentNodeId, ranges);
@@ -34,90 +39,43 @@ export function createNpmTransitiveGraph(args) {
34
39
  rangeFor(parentNodeId, childName) {
35
40
  return rangeByParentNodeId.get(parentNodeId)?.get(childName) ?? null;
36
41
  },
42
+ parentsFor(nodeId) {
43
+ return Object.freeze([...(parentNodeIdsByChildNodeId.get(nodeId) ?? [])]);
44
+ },
37
45
  };
38
46
  }
39
47
  function buildPackageKey(name, version) {
40
48
  return `${name}@${version ?? "null"}`;
41
49
  }
50
+ // A within-range update re-resolves the installed copy of the child, so the
51
+ // target has to satisfy every parent holding that copy, not only the parent the
52
+ // path led to (#1291). When `childVersion` is given, every parent's declared
53
+ // range is applied as well as the chosen parent's.
42
54
  export function findSafeVersionWithinParentRange(args) {
43
55
  const allowedRange = args.graph.rangeFor(args.parentNodeId, args.childName);
44
56
  if (!allowedRange)
45
57
  return null;
58
+ const ranges = [
59
+ allowedRange,
60
+ ...(args.childVersion ? rangesFromEveryParent(args.graph, args.childName, args.childVersion) : []),
61
+ ];
46
62
  const matchingCandidates = args.candidates
47
63
  .filter(looksLikeVersion)
48
- .filter(candidate => versionSatisfiesRange(candidate, allowedRange))
64
+ .filter(candidate => ranges.every(range => satisfiesRange(candidate, range)))
49
65
  .sort(compareVersions);
50
66
  return matchingCandidates.at(-1) ?? null;
51
67
  }
52
- function versionSatisfiesRange(version, rawRange) {
53
- const range = rawRange.trim();
54
- if (!range)
55
- return false;
56
- if (range === "*" || range === "latest")
57
- return true;
58
- const orParts = range.split("||").map(part => part.trim()).filter(Boolean);
59
- return orParts.some(part => satisfiesAndRange(version, part));
60
- }
61
- function satisfiesAndRange(version, range) {
62
- const normalized = normalizeRange(range);
63
- if (!normalized)
64
- return false;
65
- const tokens = normalized.split(/\s+/).filter(Boolean);
66
- return tokens.every(token => satisfiesComparator(version, token));
67
- }
68
- function normalizeRange(range) {
69
- const trimmed = range.trim();
70
- if (!trimmed)
71
- return null;
72
- if (looksLikeVersion(trimmed)) {
73
- return `=${trimmed}`;
74
- }
75
- if (trimmed.startsWith("^")) {
76
- const base = trimmed.slice(1);
77
- if (!looksLikeVersion(base))
78
- return null;
79
- const [major, minor, patch] = parseCoreVersion(base);
80
- if (major > 0)
81
- return `>=${base} <${major + 1}.0.0`;
82
- if (minor > 0)
83
- return `>=${base} <0.${minor + 1}.0`;
84
- return `>=${base} <0.0.${patch + 1}`;
85
- }
86
- if (trimmed.startsWith("~")) {
87
- const base = trimmed.slice(1);
88
- if (!looksLikeVersion(base))
89
- return null;
90
- const [major, minor] = parseCoreVersion(base);
91
- return `>=${base} <${major}.${minor + 1}.0`;
92
- }
93
- return trimmed;
94
- }
95
- function satisfiesComparator(version, comparator) {
96
- const token = comparator.trim();
97
- if (!token)
98
- return true;
99
- const match = token.match(/^(<=|>=|<|>|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[-+][^\s]+)?)$/);
100
- if (!match)
101
- return false;
102
- const operator = match[1] ?? "=";
103
- const target = match[2];
104
- const cmp = compareVersions(version, target);
105
- switch (operator) {
106
- case "<":
107
- return cmp < 0;
108
- case "<=":
109
- return cmp <= 0;
110
- case ">":
111
- return cmp > 0;
112
- case ">=":
113
- return cmp >= 0;
114
- case "=":
115
- return cmp === 0;
116
- default:
117
- return false;
68
+ function rangesFromEveryParent(graph, childName, childVersion) {
69
+ if (!graph.parentsFor)
70
+ return [];
71
+ const ranges = [];
72
+ for (const childNodeId of graph.nodeIdsFor(childName, childVersion)) {
73
+ for (const parentNodeId of graph.parentsFor(childNodeId)) {
74
+ const range = graph.rangeFor(parentNodeId, childName);
75
+ if (range)
76
+ ranges.push(range);
77
+ }
78
+ ranges.push(...(graph.peerRangesFor?.(childNodeId) ?? []));
118
79
  }
119
- }
120
- function parseCoreVersion(version) {
121
- const [major = "0", minor = "0", patch = "0"] = version.split(/[+-]/)[0].split(".");
122
- return [Number(major), Number(minor), Number(patch)];
80
+ return ranges;
123
81
  }
@@ -1,14 +1,20 @@
1
- import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
1
+ import { compareVersions, isPreReleaseVersion, looksLikeVersion, satisfiesRange } from "../utils/version.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
3
  import { findSafeVersionWithinParentRange } from "./npm-transitive-graph.js";
4
+ import { registryParentRanges } from "./registry-parent-ranges.js";
4
5
  import { findPackageAlongPath } from "./package-path-lookup.js";
6
+ import { resolveDirectParentContext } from "./parent-candidate-resolver.js";
5
7
  export async function resolveTransitiveRemediationViaRegistry(args) {
6
8
  if (args.finding.relationship !== "transitive")
7
9
  return null;
8
10
  const viaPath = getBestPath(args.finding);
9
11
  if (!viaPath || viaPath.length < 3)
10
12
  return null;
11
- const directParentContext = resolveDirectParentContext(viaPath, args.packages, args.directDependencyNames);
13
+ const directParentContext = resolveDirectParentContext({
14
+ viaPath,
15
+ packages: args.packages,
16
+ directDependencyNames: args.directDependencyNames,
17
+ });
12
18
  if (!directParentContext)
13
19
  return null;
14
20
  const { directParentName, immediateParentName, directParent } = directParentContext;
@@ -23,6 +29,7 @@ export async function resolveTransitiveRemediationViaRegistry(args) {
23
29
  viaPath,
24
30
  packages: args.packages,
25
31
  workspaceMap: args.workspaceMap,
32
+ parentGraph: args.parentGraph,
26
33
  });
27
34
  }
28
35
  if (!looksLikeVersion(directParent.version))
@@ -36,9 +43,13 @@ export async function resolveTransitiveRemediationViaRegistry(args) {
36
43
  parentManifest?.optionalDependencies?.[vulnerableName];
37
44
  if (!depRange)
38
45
  return null;
46
+ const ranges = [
47
+ depRange,
48
+ ...(await registryRangesFromEveryParent(args.parentGraph, vulnerableName, args.finding.pkg.version)),
49
+ ];
39
50
  const inRangeTarget = [...safeCandidates]
40
51
  .sort(compareVersions)
41
- .filter(v => versionSatisfiesRange(v, depRange))
52
+ .filter(v => ranges.every(range => satisfiesRange(v, range)))
42
53
  .at(-1);
43
54
  if (!inRangeTarget)
44
55
  return null;
@@ -59,7 +70,11 @@ export async function resolveNpmTransitiveRemediation(args) {
59
70
  const viaPath = getBestPath(args.finding);
60
71
  if (!viaPath || viaPath.length < 3)
61
72
  return null;
62
- const directParentContext = resolveDirectParentContext(viaPath, args.packages, args.directDependencyNames);
73
+ const directParentContext = resolveDirectParentContext({
74
+ viaPath,
75
+ packages: args.packages,
76
+ directDependencyNames: args.directDependencyNames,
77
+ });
63
78
  if (!directParentContext)
64
79
  return null;
65
80
  const { directParentName, immediateParentName, directParent } = directParentContext;
@@ -99,6 +114,7 @@ export async function resolveNpmTransitiveRemediation(args) {
99
114
  parentNodeId,
100
115
  childName: vulnerableName,
101
116
  candidates: safeCandidates,
117
+ childVersion: args.finding.pkg.version,
102
118
  });
103
119
  if (inRangeTarget) {
104
120
  const workspaces = collectWorkspacesFromAllPaths(args.finding.dependencyPaths ?? [], args.workspaceMap);
@@ -132,7 +148,7 @@ export async function resolveNpmTransitiveRemediation(args) {
132
148
  const targetChildVersion = highestVersionSatisfyingRange(safeCandidates, depRange);
133
149
  if (!targetChildVersion)
134
150
  continue;
135
- const stillAllowsInstalled = versionSatisfiesRange(args.finding.pkg.version, depRange);
151
+ const stillAllowsInstalled = satisfiesRange(args.finding.pkg.version, depRange);
136
152
  if (stillAllowsInstalled && compareVersions(targetChildVersion, args.finding.pkg.version) <= 0) {
137
153
  continue;
138
154
  }
@@ -154,34 +170,6 @@ function getBestPath(finding) {
154
170
  return null;
155
171
  return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
156
172
  }
157
- function findDirectDependency(packages, name, directDependencyNames) {
158
- for (const pkg of packages) {
159
- if (pkg.name !== name)
160
- continue;
161
- if (directDependencyNames?.has(name)) {
162
- return pkg;
163
- }
164
- const paths = pkg.paths ?? [];
165
- if (paths.some(path => path.at(-1) === name && path.length >= 2)) {
166
- return pkg;
167
- }
168
- }
169
- return null;
170
- }
171
- function resolveDirectParentContext(viaPath, packages, directDependencyNames) {
172
- const immediateParentName = viaPath[viaPath.length - 2];
173
- const candidateSegments = viaPath.slice(1, -1);
174
- const directParentCandidates = directDependencyNames
175
- ? candidateSegments.filter(segment => directDependencyNames.has(segment))
176
- : [viaPath[1]].filter(Boolean);
177
- const directParentName = directParentCandidates[0];
178
- if (!directParentName)
179
- return null;
180
- const directParent = findDirectDependency(packages, directParentName, directDependencyNames);
181
- if (!directParent)
182
- return null;
183
- return { directParentName, immediateParentName, directParent };
184
- }
185
173
  function buildOfflineSafeCandidates(installedVersion, fixedVersionHint) {
186
174
  if (!fixedVersionHint || !looksLikeVersion(fixedVersionHint))
187
175
  return [];
@@ -226,81 +214,9 @@ function resolveParentNodeId(args) {
226
214
  return candidateNodeIds[0] ?? null;
227
215
  }
228
216
  export function highestVersionSatisfyingRange(candidates, rawRange) {
229
- const matches = candidates.filter(candidate => versionSatisfiesRange(candidate, rawRange)).sort(compareVersions);
217
+ const matches = candidates.filter(candidate => satisfiesRange(candidate, rawRange)).sort(compareVersions);
230
218
  return matches.at(-1) ?? null;
231
219
  }
232
- export function versionSatisfiesRange(version, rawRange) {
233
- const range = rawRange.trim();
234
- if (!range)
235
- return false;
236
- if (range === "*" || range === "latest")
237
- return true;
238
- const orParts = range.split("||").map(part => part.trim()).filter(Boolean);
239
- return orParts.some(part => satisfiesAndRange(version, part));
240
- }
241
- function satisfiesAndRange(version, range) {
242
- const normalized = normalizeRange(range);
243
- if (!normalized)
244
- return false;
245
- const tokens = normalized.split(/\s+/).filter(Boolean);
246
- return tokens.every(token => satisfiesComparator(version, token));
247
- }
248
- function normalizeRange(range) {
249
- const trimmed = range.trim();
250
- if (!trimmed)
251
- return null;
252
- if (looksLikeVersion(trimmed)) {
253
- return `=${trimmed}`;
254
- }
255
- if (trimmed.startsWith("^")) {
256
- const base = trimmed.slice(1);
257
- if (!looksLikeVersion(base))
258
- return null;
259
- const [major, minor, patch] = parseCoreVersion(base);
260
- if (major > 0)
261
- return `>=${base} <${major + 1}.0.0`;
262
- if (minor > 0)
263
- return `>=${base} <0.${minor + 1}.0`;
264
- return `>=${base} <0.0.${patch + 1}`;
265
- }
266
- if (trimmed.startsWith("~")) {
267
- const base = trimmed.slice(1);
268
- if (!looksLikeVersion(base))
269
- return null;
270
- const [major, minor] = parseCoreVersion(base);
271
- return `>=${base} <${major}.${minor + 1}.0`;
272
- }
273
- return trimmed;
274
- }
275
- function satisfiesComparator(version, comparator) {
276
- const token = comparator.trim();
277
- if (!token)
278
- return true;
279
- const match = token.match(/^(<=|>=|<|>|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[-+][^\s]+)?)$/);
280
- if (!match)
281
- return false;
282
- const operator = match[1] ?? "=";
283
- const target = match[2];
284
- const cmp = compareVersions(version, target);
285
- switch (operator) {
286
- case "<":
287
- return cmp < 0;
288
- case "<=":
289
- return cmp <= 0;
290
- case ">":
291
- return cmp > 0;
292
- case ">=":
293
- return cmp >= 0;
294
- case "=":
295
- return cmp === 0;
296
- default:
297
- return false;
298
- }
299
- }
300
- function parseCoreVersion(version) {
301
- const [major = "0", minor = "0", patch = "0"] = version.split(/[+-]/)[0].split(".");
302
- return [Number(major), Number(minor), Number(patch)];
303
- }
304
220
  async function resolveWithinRangeForDeepChainViaRegistry(args) {
305
221
  const immediateParentPathPrefix = args.viaPath.slice(0, -1);
306
222
  const immediateParent = findPackageAlongPath(args.packages, args.immediateParentName, immediateParentPathPrefix);
@@ -315,9 +231,13 @@ async function resolveWithinRangeForDeepChainViaRegistry(args) {
315
231
  parentManifest?.optionalDependencies?.[args.vulnerableName];
316
232
  if (!depRange)
317
233
  return null;
234
+ const ranges = [
235
+ depRange,
236
+ ...(await registryRangesFromEveryParent(args.parentGraph, args.vulnerableName, args.installedVersion)),
237
+ ];
318
238
  const inRangeTarget = [...safeCandidates]
319
239
  .sort(compareVersions)
320
- .filter(version => versionSatisfiesRange(version, depRange))
240
+ .filter(version => ranges.every(range => satisfiesRange(version, range)))
321
241
  .at(-1);
322
242
  if (!inRangeTarget)
323
243
  return null;
@@ -351,6 +271,7 @@ async function resolveWithinRangeForDeepChain(args) {
351
271
  parentNodeId: nodeId,
352
272
  childName: args.vulnerableName,
353
273
  candidates: safeCandidates,
274
+ childVersion: args.installedVersion,
354
275
  });
355
276
  if (inRangeTarget) {
356
277
  return {
@@ -365,6 +286,13 @@ async function resolveWithinRangeForDeepChain(args) {
365
286
  }
366
287
  return null;
367
288
  }
289
+ // The range each parent of the installed copy declares for it, read from that
290
+ // parent's published manifest. A parent the registry cannot describe, such as a
291
+ // workspace member, is skipped, which leaves the chosen parent's range in force.
292
+ async function registryRangesFromEveryParent(graph, childName, childVersion) {
293
+ const parents = await registryParentRanges(graph, childName, childVersion);
294
+ return parents.map(parent => parent.range).filter((range) => range !== null);
295
+ }
368
296
  function collectWorkspacesFromAllPaths(dependencyPaths, workspaceMap) {
369
297
  if (!workspaceMap)
370
298
  return undefined;
@@ -0,0 +1,65 @@
1
+ import { isLocalProtocolVersion } from "../utils/version.js";
2
+ import { findPackageAlongPath } from "./package-path-lookup.js";
3
+ // Chooses which declared direct dependency to treat as the upgrade target for a
4
+ // transitive finding, and resolves it to the installed copy that actually sits on this
5
+ // finding's dependency path.
6
+ //
7
+ // It lives in its own module because both remediation paths need it and they do not
8
+ // import each other. Which path runs is decided by whether a resolved npm transitive
9
+ // graph exists, NOT by package manager: parent-upgrade.ts drives the graph-free route,
10
+ // while npm-transitive-resolution.ts serves npm through the graph AND every other
11
+ // package manager through its registry route, since scanner.ts falls back to that
12
+ // whenever the graph is absent and the scan is online. Two copies of this logic drifted
13
+ // apart once already and the copy npm used had lost the path lookup below, which is what
14
+ // #1352 records.
15
+ export function resolveDirectParentContext(args) {
16
+ const { viaPath, packages, directDependencyNames } = args;
17
+ const immediateParentName = viaPath[viaPath.length - 2];
18
+ const candidateSegments = viaPath.slice(1, -1);
19
+ const directParentCandidates = directDependencyNames
20
+ ? candidateSegments.filter(segment => directDependencyNames.has(segment))
21
+ : [viaPath[1]].filter(Boolean);
22
+ // Try each candidate rather than only the leftmost. A workspace member is a
23
+ // declared dependency name, and depending on the package manager it either
24
+ // never resolves to a PackageRef (npm's link stub) or resolves to one whose
25
+ // version is a `workspace:` path (Bun, Yarn). Neither is an upgrade target. Stopping at the
26
+ // first candidate therefore abandoned remediation on every workspace path and
27
+ // reported an available fix as unavailable.
28
+ for (const directParentName of directParentCandidates) {
29
+ // Resolve along the dependency path. Taking any copy that merely shares the name
30
+ // makes the recorded parent version wrong, and because the fix version is then
31
+ // validated against that copy's declared range, the recommendation can be a version
32
+ // the real parent cannot accept. Measured on examples/vscode: the vulnerable
33
+ // brace-expansion sits under minimatch@3.1.5, which declares ^1.1.7, while a
34
+ // name-only lookup selected minimatch@9.0.9, which declares ^2.0.2. We therefore
35
+ // recommended upgrading to 2.1.7, outside the real parent's range, when 1.1.21 was
36
+ // published, within range, and what the advisory itself named. Those two are
37
+ // recommended targets rather than versions present in that lockfile.
38
+ const directParentIdx = viaPath.indexOf(directParentName);
39
+ const directParentPathPrefix = viaPath.slice(0, directParentIdx + 1);
40
+ // Path lookup only, with no name-based fallback. A fallback cannot tell which installed
41
+ // copy belongs to this finding's path, and the chosen version is not merely a comparison
42
+ // baseline: it selects which manifest gets fetched, and the child's fix is validated
43
+ // against THAT copy's declared range. So guessing here reproduces the defect this module
44
+ // exists to prevent, which is how we recommended brace-expansion@2.1.7 against a parent
45
+ // declaring ^1.1.7. Taking the highest copy avoids offering a downgrade but does nothing
46
+ // about the wrong-identity half, which was the gap in the first version of this change.
47
+ //
48
+ // The honest failure mode is to report no remediation rather than one the real parent
49
+ // cannot accept, and it is what the first-party branch below already does for the same
50
+ // reason. Unreached on eight example trees across all four package managers, since the
51
+ // path lookup resolves first every time, but reachable because recorded paths are capped
52
+ // at five per package and ten deep.
53
+ const directParent = findPackageAlongPath(packages, directParentName, directParentPathPrefix);
54
+ // A local protocol version means the path's own parent is first-party, so this
55
+ // candidate is not an upgrade target and the next candidate name is tried. We do
56
+ // deliberately NOT fall back to another installed copy of this same name here: a
57
+ // copy living elsewhere in the tree is not the parent of this finding, and offering
58
+ // it is the wrong-copy mistake this module exists to prevent. The npm route could
59
+ // previously do exactly that.
60
+ if (directParent && !isLocalProtocolVersion(directParent.version)) {
61
+ return { directParentName, immediateParentName, directParent };
62
+ }
63
+ }
64
+ return null;
65
+ }
@@ -0,0 +1,51 @@
1
+ import { isValidRange, looksLikeVersion, satisfiesRange } from "../utils/version.js";
2
+ import { registryParentRanges } from "./registry-parent-ranges.js";
3
+ // Only the project's own copies count: a package declared by the root or by a
4
+ // workspace member. Nothing else moves them, so the copy they hold stays put. A
5
+ // transitive holder, even one sharing a direct dependency's name, is often
6
+ // re-resolved along with the upgraded parent, so naming it would claim a block
7
+ // that may not exist (#1457).
8
+ export async function findParentUpgradeBlockers(args) {
9
+ if (!looksLikeVersion(args.targetChildVersion))
10
+ return [];
11
+ const holders = args.npmGraph
12
+ ? npmHolders(args.npmGraph, args.childName, args.childVersion)
13
+ : await registryParentRanges(args.lockParentGraph, args.childName, args.childVersion);
14
+ const isProjectCopy = projectCopyMatcher(args.packages, args.workspaceMemberNames);
15
+ const blockers = new Map();
16
+ for (const holder of holders) {
17
+ if (holder.name === args.upgradedParent || !holder.range || !isValidRange(holder.range))
18
+ continue;
19
+ if (!isProjectCopy(holder.name, holder.version))
20
+ continue;
21
+ if (satisfiesRange(args.targetChildVersion, holder.range))
22
+ continue;
23
+ blockers.set(`${holder.name}@${holder.version}`, { package: holder.name, version: holder.version, range: holder.range });
24
+ }
25
+ return [...blockers.values()].sort((a, b) => a.package.localeCompare(b.package));
26
+ }
27
+ function npmHolders(graph, childName, childVersion) {
28
+ if (!graph.parentsFor)
29
+ return [];
30
+ const holders = [];
31
+ for (const childNodeId of graph.nodeIdsFor(childName, childVersion)) {
32
+ for (const parentNodeId of graph.parentsFor(childNodeId)) {
33
+ const parent = graph.getNode(parentNodeId);
34
+ if (parent?.version)
35
+ holders.push({ name: parent.name, version: parent.version, range: graph.rangeFor(parentNodeId, childName) });
36
+ }
37
+ }
38
+ return holders;
39
+ }
40
+ // A copy is the project's own when a recorded path reaches it straight from the
41
+ // project, or from a workspace member one step below it.
42
+ function projectCopyMatcher(packages, workspaceMemberNames) {
43
+ const projectCopies = new Set();
44
+ for (const pkg of packages) {
45
+ const direct = (pkg.paths ?? []).some(p => p[p.length - 1] === pkg.name &&
46
+ (p.length === 2 || (p.length === 3 && workspaceMemberNames.has(p[1]))));
47
+ if (direct)
48
+ projectCopies.add(`${pkg.name}@${pkg.version}`);
49
+ }
50
+ return (name, version) => projectCopies.has(`${name}@${version}`);
51
+ }
@@ -1,6 +1,7 @@
1
- import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
1
+ import { compareVersions, isPreReleaseVersion, looksLikeVersion, satisfiesRange } from "../utils/version.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
3
  import { findPackageAlongPath } from "./package-path-lookup.js";
4
+ import { resolveDirectParentContext } from "./parent-candidate-resolver.js";
4
5
  export function isVerifiedUpgrade(confidence) {
5
6
  return confidence === "verified";
6
7
  }
@@ -14,8 +15,11 @@ export async function resolveRecommendedParentUpgrade(finding, packages, directD
14
15
  const viaPath = getBestPath(finding);
15
16
  if (!viaPath || viaPath.length < 3)
16
17
  return null;
17
- const packagesByName = new Map(packages.map(p => [p.name, p]));
18
- const directParentContext = resolveDirectParentContext(viaPath, packages, directDependencyNames, packagesByName);
18
+ const directParentContext = resolveDirectParentContext({
19
+ viaPath,
20
+ packages,
21
+ directDependencyNames,
22
+ });
19
23
  if (!directParentContext)
20
24
  return null;
21
25
  const { directParentName, immediateParentName, directParent } = directParentContext;
@@ -56,41 +60,6 @@ function getBestPath(finding) {
56
60
  return null;
57
61
  return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
58
62
  }
59
- function findDirectDependency(packages, name, directDependencyNames, packagesByName) {
60
- if (directDependencyNames?.has(name)) {
61
- return packagesByName.get(name) ?? null;
62
- }
63
- for (const pkg of packages) {
64
- if (pkg.name !== name)
65
- continue;
66
- const paths = pkg.paths ?? [];
67
- if (paths.some(path => path.at(-1) === name && path.length >= 2)) {
68
- return pkg;
69
- }
70
- }
71
- return null;
72
- }
73
- function resolveDirectParentContext(viaPath, packages, directDependencyNames, packagesByName) {
74
- const immediateParentName = viaPath[viaPath.length - 2];
75
- const candidateSegments = viaPath.slice(1, -1);
76
- const directParentCandidates = directDependencyNames
77
- ? candidateSegments.filter(segment => directDependencyNames.has(segment))
78
- : [viaPath[1]].filter(Boolean);
79
- const directParentName = directParentCandidates[0];
80
- if (!directParentName)
81
- return null;
82
- // Path-based lookup disambiguates when the same package name is installed at
83
- // multiple versions (e.g. eslint@9.36.0 at root AND eslint@6.14.0 nested).
84
- // A name-keyed Map (last-write-wins) would return an arbitrary version, making
85
- // directParentVersion wrong and potentially producing downgrade suggestions.
86
- const directParentIdx = viaPath.indexOf(directParentName);
87
- const directParentPathPrefix = viaPath.slice(0, directParentIdx + 1);
88
- const directParent = findPackageAlongPath(packages, directParentName, directParentPathPrefix) ??
89
- findDirectDependency(packages, directParentName, directDependencyNames, packagesByName);
90
- if (!directParent)
91
- return null;
92
- return { directParentName, immediateParentName, directParent };
93
- }
94
63
  function findPackageVersion(packages, name, pathPrefix) {
95
64
  return findPackageAlongPath(packages, name, pathPrefix)?.version ?? null;
96
65
  }
@@ -103,7 +72,7 @@ export async function resolveHighestSatisfying(name, range) {
103
72
  const versions = Object.keys(packument?.versions ?? {})
104
73
  .filter(looksLikeVersion)
105
74
  .filter(v => !isPreReleaseVersion(v))
106
- .filter(version => versionSatisfiesRange(version, range))
75
+ .filter(version => satisfiesRange(version, range))
107
76
  .sort(compareVersions);
108
77
  return versions.at(-1) ?? null;
109
78
  }
@@ -149,9 +118,9 @@ async function findUpgradeForExactDirectChild(args) {
149
118
  manifest?.optionalDependencies?.[args.vulnerableName];
150
119
  if (!depRange)
151
120
  continue;
152
- const stillAllowsInstalled = versionSatisfiesRange(args.vulnerableInstalledVersion, depRange);
121
+ const stillAllowsInstalled = satisfiesRange(args.vulnerableInstalledVersion, depRange);
153
122
  const allowsFixed = args.vulnerableFixedVersion
154
- ? versionSatisfiesRange(args.vulnerableFixedVersion, depRange)
123
+ ? satisfiesRange(args.vulnerableFixedVersion, depRange)
155
124
  : true;
156
125
  if (!stillAllowsInstalled && allowsFixed) {
157
126
  return {
@@ -229,7 +198,7 @@ async function findUpgradeForImmediateIntermediate(args) {
229
198
  if (!heuristicFallback) {
230
199
  const depRange = manifest.dependencies?.[args.immediateChildName] ??
231
200
  manifest.optionalDependencies?.[args.immediateChildName];
232
- if (depRange && !versionSatisfiesRange(args.immediateChildInstalledVersion, depRange)) {
201
+ if (depRange && !satisfiesRange(args.immediateChildInstalledVersion, depRange)) {
233
202
  heuristicFallback = {
234
203
  package: args.directParentName,
235
204
  currentVersion: args.directParentVersion,
@@ -247,77 +216,3 @@ async function findUpgradeForImmediateIntermediate(args) {
247
216
  }
248
217
  return null;
249
218
  }
250
- function versionSatisfiesRange(version, rawRange) {
251
- const range = rawRange.trim();
252
- if (!range)
253
- return false;
254
- if (range === "*" || range === "latest")
255
- return true;
256
- const orParts = range.split("||").map(part => part.trim()).filter(Boolean);
257
- return orParts.some(part => satisfiesAndRange(version, part));
258
- }
259
- function satisfiesAndRange(version, range) {
260
- const normalized = normalizeRange(range);
261
- if (!normalized)
262
- return false;
263
- const tokens = normalized.split(/\s+/).filter(Boolean);
264
- return tokens.every(token => satisfiesComparator(version, token));
265
- }
266
- function normalizeRange(range) {
267
- const trimmed = range.trim();
268
- if (!trimmed)
269
- return null;
270
- if (looksLikeVersion(trimmed)) {
271
- return `=${trimmed}`;
272
- }
273
- if (trimmed.startsWith("^")) {
274
- const base = trimmed.slice(1);
275
- if (!looksLikeVersion(base))
276
- return null;
277
- const [major, minor, patch] = parseCoreVersion(base);
278
- if (major > 0)
279
- return `>=${base} <${major + 1}.0.0`;
280
- if (minor > 0)
281
- return `>=${base} <0.${minor + 1}.0`;
282
- return `>=${base} <0.0.${patch + 1}`;
283
- }
284
- if (trimmed.startsWith("~")) {
285
- const base = trimmed.slice(1);
286
- if (!looksLikeVersion(base))
287
- return null;
288
- const [major, minor] = parseCoreVersion(base);
289
- return `>=${base} <${major}.${minor + 1}.0`;
290
- }
291
- return trimmed;
292
- }
293
- function satisfiesComparator(version, comparator) {
294
- const token = comparator.trim();
295
- if (!token)
296
- return true;
297
- const match = token.match(/^(<=|>=|<|>|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[-+][^\s]+)?)$/);
298
- if (!match)
299
- return false;
300
- const operator = match[1] ?? "=";
301
- const target = match[2];
302
- const cmp = compareVersions(version, target);
303
- switch (operator) {
304
- case "<":
305
- return cmp < 0;
306
- case "<=":
307
- return cmp <= 0;
308
- case ">":
309
- return cmp > 0;
310
- case ">=":
311
- return cmp >= 0;
312
- case "=":
313
- return cmp === 0;
314
- default:
315
- return false;
316
- }
317
- }
318
- function parseCoreVersion(version) {
319
- const [major, minor, patch] = version
320
- .split(".")
321
- .map(part => Number(part.replace(/[^0-9].*$/, "")));
322
- return [major || 0, minor || 0, patch || 0];
323
- }
@@ -0,0 +1,21 @@
1
+ import { looksLikeVersion } from "../utils/version.js";
2
+ import { fetchPackument } from "./npm-registry.js";
3
+ // Every parent of the installed copy with the range its published manifest declares
4
+ // for the child, or null where the manifest does not say.
5
+ export async function registryParentRanges(graph, childName, childVersion) {
6
+ if (!graph)
7
+ return [];
8
+ const parents = new Map();
9
+ for (const childNodeId of graph.nodeIdsFor(childName, childVersion)) {
10
+ for (const parentNodeId of graph.parentsFor(childNodeId)) {
11
+ const parent = graph.getNode(parentNodeId);
12
+ if (parent && looksLikeVersion(parent.version))
13
+ parents.set(`${parent.name}@${parent.version}`, parent);
14
+ }
15
+ }
16
+ return Promise.all([...parents.values()].map(async (parent) => {
17
+ const manifest = (await fetchPackument(parent.name))?.versions?.[parent.version];
18
+ const range = manifest?.dependencies?.[childName] ?? manifest?.optionalDependencies?.[childName] ?? null;
19
+ return { name: parent.name, version: parent.version, range };
20
+ }));
21
+ }