cve-lite-cli 1.39.0 → 1.40.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 (39) hide show
  1. package/README.md +11 -11
  2. package/dist/cli/help.js +1 -0
  3. package/dist/constants.js +4 -3
  4. package/dist/osv/severity.js +1 -1
  5. package/dist/output/cyclonedx.js +1 -1
  6. package/dist/output/formatters.js +2 -2
  7. package/dist/output/html-reporter.js +14 -8
  8. package/dist/output/multi-folder-html-reporter.js +12 -8
  9. package/dist/output/override-findings-html.js +3 -6
  10. package/dist/output/override-findings-terminal.js +7 -12
  11. package/dist/output/override-fix-command.js +13 -0
  12. package/dist/output/printers.js +11 -7
  13. package/dist/output/sarif.js +39 -11
  14. package/dist/output/scan-json.js +26 -1
  15. package/dist/output/write-outputs.js +13 -1
  16. package/dist/overrides/parsing/registry.js +1 -1
  17. package/dist/parsers/pnpm-lock.js +23 -10
  18. package/dist/remediation/fix-commands.js +36 -7
  19. package/dist/remediation/npm-registry.js +56 -7
  20. package/dist/remediation/npm-transitive-resolution.js +11 -30
  21. package/dist/remediation/parent-candidate-resolver.js +65 -0
  22. package/dist/remediation/parent-upgrade.js +6 -37
  23. package/dist/scan/completeness.js +7 -7
  24. package/dist/scan/multi-folder-scan.js +28 -8
  25. package/dist/scan/override-audit.js +11 -1
  26. package/dist/scan/single-scan.js +85 -45
  27. package/dist/scanner.js +32 -9
  28. package/dist/skills/content.js +12 -12
  29. package/dist/utils/contextual-signals.js +1 -1
  30. package/dist/utils/effective-options.js +55 -0
  31. package/dist/utils/finding.js +1 -1
  32. package/dist/utils/fix-runner.js +3 -2
  33. package/dist/utils/network.js +1 -1
  34. package/dist/utils/registry-config.js +144 -0
  35. package/dist/utils/severity.js +8 -0
  36. package/dist/utils/validate-url.js +3 -3
  37. package/dist/utils/version.js +17 -1
  38. package/dist/utils/vuln.js +75 -0
  39. package/package.json +1 -1
@@ -8,6 +8,7 @@ import { resolveDependencyEdges } from "./sbom-dependency-edges.js";
8
8
  import { resolveSbomFormat } from "../utils/sbom-format.js";
9
9
  import { buildScanJson } from "./scan-json.js";
10
10
  import { resolveOutputDir, displayOutputPath } from "./output-dir.js";
11
+ import { getCliVersion } from "../utils/version-info.js";
11
12
  function readProjectMeta(projectPath) {
12
13
  try {
13
14
  const pkgPath = path.join(projectPath, "package.json");
@@ -35,7 +36,9 @@ export async function writeOutputs(options, scanState, scanInput, projectPath) {
35
36
  const payload = buildScanJson({
36
37
  projectPath,
37
38
  scanInput,
39
+ registry: scanState.registry,
38
40
  findings: scanState.sorted,
41
+ acceptedFindings: scanState.acceptedFindings,
39
42
  suggestedFixCommands: scanState.suggestedFixCommands,
40
43
  coverage: scanState.coverage,
41
44
  completeness: scanState.completeness,
@@ -46,13 +49,22 @@ export async function writeOutputs(options, scanState, scanInput, projectPath) {
46
49
  maintenanceFindings: scanState.maintenanceFindings,
47
50
  licenseFindings: scanState.licenseFindings,
48
51
  licenseLimitedToDirectOnly: scanState.licenseLimitedToDirectOnly,
52
+ // Saved-artifact provenance for the --json payload (#1296).
53
+ provenance: { cliVersion: getCliVersion(), options },
49
54
  });
50
55
  fs.writeFileSync(jsonOutputPath, JSON.stringify(payload, null, 2));
51
56
  console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(displayOutputPath(jsonOutputPath))}`);
52
57
  }
53
58
  if (options.sarif) {
54
59
  const lockfileUri = deriveLockfileUri(scanInput);
55
- const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, scanState.overrideFindings, scanState.maintenanceFindings, scanState.licenseFindings, outputDir, scanState.overrideSkipped);
60
+ const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, {
61
+ acceptedFindings: scanState.acceptedFindings,
62
+ overrideFindings: scanState.overrideFindings,
63
+ maintenanceFindings: scanState.maintenanceFindings,
64
+ licenseFindings: scanState.licenseFindings,
65
+ overrideSkipped: scanState.overrideSkipped,
66
+ outputDir,
67
+ });
56
68
  console.log(`${chalk.gray("SARIF report written to")} ${chalk.cyan(sarifFilename)}`);
57
69
  }
58
70
  const sbomFormat = resolveSbomFormat(options);
@@ -174,7 +174,7 @@ export async function fetchVersionsBatch(pkgNames, opts = {}) {
174
174
  }
175
175
  /**
176
176
  * Encode a package name for the registry URL.
177
- * Scoped names like `@scope/pkg` need the slash kept literal — the registry
177
+ * Scoped names like `@scope/pkg` need the slash kept literal - the registry
178
178
  * doesn't accept `%2F` for the scope separator.
179
179
  */
180
180
  function encodeRegistryPath(pkgName) {
@@ -90,7 +90,9 @@ export function loadFromPnpmLock(filePath, prodOnly) {
90
90
  }
91
91
  function loadLegacy(parsed, prodOnly) {
92
92
  const packagesSection = parsed?.packages ?? {};
93
- const importers = parsed?.importers ?? {};
93
+ // A single-project v5/v6 lockfile has no `importers`; the root's dependency
94
+ // sections sit at the top level instead.
95
+ const importers = parsed?.importers ?? { ".": parsed ?? {} };
94
96
  const graph = new Map();
95
97
  const map = new Map();
96
98
  for (const [key, meta] of Object.entries(packagesSection)) {
@@ -285,13 +287,22 @@ function pathsEqual(left, right) {
285
287
  return false;
286
288
  return left.every((value, index) => value === right[index]);
287
289
  }
290
+ // Pre-v9 package keys come in two shapes. Lockfile v6 (pnpm 8) writes
291
+ // `/name@version` with peers in parentheses: `/react-dom@16.0.0(react@16.0.0)`.
292
+ // Lockfile v5 (pnpm 6 and 7) writes `/name/version` with peers after an
293
+ // underscore: `/react-dom/16.0.0_react@16.0.0`. Both are reduced to one
294
+ // canonical `/name/version` key so package entries and dependency refs meet.
288
295
  export function parsePnpmPackageKey(key) {
289
296
  const cleaned = key.replace(/^\//, "").split("(")[0];
290
- const match = cleaned.match(/^(@?[^/]+(?:\/[^/]+)?)\/([^/]+)$/);
297
+ const match = cleaned.match(/^(@[^/@]+\/[^/@]+|[^/@]+)@([^/]+)$/) ??
298
+ cleaned.match(/^(@?[^/]+(?:\/[^/]+)?)\/([^/]+)$/);
291
299
  if (!match)
292
300
  return null;
293
- const [, name, version] = match;
294
- return { key, name, version };
301
+ const name = match[1];
302
+ const version = match[2].replace(/_.*$/, "");
303
+ if (!version)
304
+ return null;
305
+ return { key: `/${name}/${version}`, name, version };
295
306
  }
296
307
  export function parsePnpmPackageKeyV9(key) {
297
308
  // strip leading slash (pnpm v9 can emit /@babel/core@7.20.0) then peer-dep suffix (pkg@1.0.0(peer@2.0.0))
@@ -310,12 +321,14 @@ export function normalizePnpmDepRef(depName, depRef) {
310
321
  const cleaned = depRef.replace(/^link:/, "").replace(/^workspace:/, "").split("(")[0];
311
322
  if (!cleaned || cleaned.startsWith(".") || cleaned.startsWith(".."))
312
323
  return null;
313
- if (cleaned.startsWith("/"))
314
- return cleaned;
315
- if (cleaned.includes("/"))
316
- return "/" + cleaned.replace(/^\//, "");
317
- if (looksLikeVersion(cleaned))
318
- return `/${depName}/${cleaned}`;
324
+ if (cleaned.includes("/")) {
325
+ const key = "/" + cleaned.replace(/^\//, "");
326
+ return parsePnpmPackageKey(key)?.key ?? null;
327
+ }
328
+ // Lockfile v5 appends resolved peers to the version: `16.0.0_react@16.0.0`.
329
+ const version = cleaned.replace(/_.*$/, "");
330
+ if (looksLikeVersion(version))
331
+ return `/${depName}/${version}`;
319
332
  }
320
333
  if (depRef && typeof depRef === "object") {
321
334
  const version = depRef.version ?? depRef.specifier;
@@ -87,7 +87,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
87
87
  const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
88
88
  // In offline mode validateDirectFixTargets never runs, so an unset
89
89
  // validatedFirstFixedVersion is "did not validate" rather than "validation
90
- // failed" — fall back to the advisory hint instead of dropping the target.
90
+ // failed" - fall back to the advisory hint instead of dropping the target.
91
91
  const validatedFieldOk = offline || !hasValidatedField || finding.validatedFirstFixedVersion !== null;
92
92
  // A confirmed fix version is a direct answer to "is there a safe upgrade",
93
93
  // where the counter comparison below is only an inference about one. When
@@ -145,6 +145,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
145
145
  version: finding.pkg.version,
146
146
  relationship: finding.relationship,
147
147
  reason: finding.fixVersionValidationNote,
148
+ advisoryHintUnavailable: finding.advisoryHintUnavailable ?? false,
148
149
  });
149
150
  }
150
151
  else if (finding.firstFixedVersion) {
@@ -184,7 +185,12 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
184
185
  currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
185
186
  childTargetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
186
187
  reason: finding.recommendedNpmTransitiveRemediation.reason,
187
- command: buildNpmUpdateCommand(finding.recommendedNpmTransitiveRemediation.package, finding.recommendedNpmTransitiveRemediation.workspaces),
188
+ // Name the package that actually moves. This remediation means the parent
189
+ // already allows a safe child version, so the parent stays where it is and
190
+ // the child is what has to be refreshed. Naming the parent achieves nothing
191
+ // when it is already at its newest allowed version, because npm has no
192
+ // reason to re-resolve its subtree.
193
+ command: buildNpmUpdateCommand(finding.pkg.name, finding.recommendedNpmTransitiveRemediation.workspaces),
188
194
  isDev: devLookup.get(`${finding.recommendedNpmTransitiveRemediation.package}@${finding.recommendedNpmTransitiveRemediation.currentVersion}`) ?? false,
189
195
  }));
190
196
  continue;
@@ -277,7 +283,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
277
283
  package: finding.pkg.name,
278
284
  currentVersion: finding.pkg.version,
279
285
  childTargetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
280
- reason: `${finding.pkg.name}@${finding.pkg.version} can be refreshed to ${finding.recommendedNpmTransitiveRemediation.targetChildVersion}+ — no parent upgrade needed.`,
286
+ reason: `${finding.pkg.name}@${finding.pkg.version} can be refreshed to ${finding.recommendedNpmTransitiveRemediation.targetChildVersion}+; no parent upgrade needed.`,
281
287
  command: lockfileRefreshCommand,
282
288
  }));
283
289
  continue;
@@ -474,12 +480,29 @@ export function findFixTargetForFinding(plan, finding) {
474
480
  compareVersions(item.targetVersion, finding.recommendedParentUpgrade.targetVersion) >= 0);
475
481
  }
476
482
  if (finding.chainResolution) {
477
- return (item.package === finding.chainResolution.directDep &&
478
- item.targetVersion === finding.chainResolution.targetVersion);
483
+ if (item.package !== finding.chainResolution.directDep)
484
+ return false;
485
+ if (item.targetVersion === finding.chainResolution.targetVersion)
486
+ return true;
487
+ // Mirrors the recommendedParentUpgrade branch above. When several children are
488
+ // cleared by the same parent, upsertTarget keeps the highest parent version, so a
489
+ // child whose chain was verified at a lower version failed an exact match and was
490
+ // left with no command, even though the command already in the plan covers it.
491
+ return (looksLikeVersion(item.targetVersion) &&
492
+ looksLikeVersion(finding.chainResolution.targetVersion) &&
493
+ compareVersions(item.targetVersion, finding.chainResolution.targetVersion) >= 0);
479
494
  }
480
495
  const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
481
496
  if (item.package !== finding.pkg.name)
482
497
  return false;
498
+ // A transitive finding is only fixed through a remediation, and each kind of
499
+ // remediation has its own branch above. Falling through to here for one means
500
+ // nothing was resolved for it, so matching it against a direct install of the same
501
+ // package name would claim that installing at the root moves a copy nested under a
502
+ // parent. npm does not guarantee that. A finding with no verified fix belongs in the
503
+ // skipped list with a reason, not holding somebody else's command.
504
+ if (finding.relationship !== "direct")
505
+ return false;
483
506
  if (item.targetVersion === directTarget)
484
507
  return true;
485
508
  // Mirrors the recommendedParentUpgrade branch above: a command targeting a
@@ -545,9 +568,15 @@ function packageManagerSourceLabel(scanInput) {
545
568
  // end up pinned onto the parent (`npm install axios@4.0.6`, where 4.0.6 is form-data's
546
569
  // version - #1007). Keep parent-update targets in their own keyspace, per child, so
547
570
  // they only ever merge with a refresh of the same child through the same package.
571
+ // The key carries the vulnerable package's INSTALLED version as well as its name. A tree
572
+ // routinely holds two majors of one package, and keying on the name alone merged them into
573
+ // a single target: the surviving row recorded one version pair, and the other finding was
574
+ // left with no target and no skipped entry, so it disappeared from the plan while having a
575
+ // known fix. The duplicate commands that now result collapse again downstream, because the
576
+ // emitted command list is de-duplicated.
548
577
  function targetKey(finding, target) {
549
578
  return target.kind === "parent-update"
550
- ? `parent-update:${target.package}>${finding.pkg.name}`
579
+ ? `parent-update:${target.package}>${finding.pkg.name}@${finding.pkg.version}`
551
580
  : `install:${target.package}`;
552
581
  }
553
582
  // Build a parent-update target whose targetVersion always belongs to `package`.
@@ -870,7 +899,7 @@ function buildCommandForTargets(targets, packageManager) {
870
899
  const updateCommands = explicitCommands.length > 0
871
900
  ? [...new Set(explicitCommands)]
872
901
  : packageManager === "npm"
873
- ? [`npm update ${parentUpdateTargets.map(target => target.package).join(" ")}`]
902
+ ? [`npm update ${parentUpdateTargets.map(target => target.childPackage ?? target.package).join(" ")}`]
874
903
  : [];
875
904
  commandParts.push(...updateCommands);
876
905
  }
@@ -1,4 +1,5 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
+ import { registryForPackage } from "../utils/registry-config.js";
2
3
  import { AsyncLocalStorage } from "node:async_hooks";
3
4
  const packumentCache = new Map();
4
5
  const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
@@ -46,8 +47,50 @@ export async function fetchPackument(packageName) {
46
47
  notifyPackumentObserver(result, packageName);
47
48
  return result.packument;
48
49
  }
50
+ let registryConfig = null;
51
+ /**
52
+ * Points package-metadata lookups at the registry the project installs from.
53
+ *
54
+ * Null restores the public registry, which is also the state when a project has no
55
+ * configuration, so an unconfigured scan behaves exactly as it did before.
56
+ *
57
+ * Only metadata lookups move. The npm advisory bulk endpoint deliberately stays on
58
+ * the public registry: a Nexus or Artifactory mirror proxies package metadata but
59
+ * generally does not implement `/-/npm/v1/security/advisories/bulk`, so redirecting
60
+ * it would turn a working advisory source into a 404 on every enterprise scan.
61
+ */
62
+ export function configureNpmRegistry(config) {
63
+ registryConfig = config;
64
+ }
65
+ /**
66
+ * Names the registry a lookup for this package actually went to, for use inside
67
+ * a sentence.
68
+ *
69
+ * A message that says npm when we asked a mirror is a false statement, and it is
70
+ * false in the direction that matters: the actionable fact is that the registry
71
+ * the project installs from is behind, not that public npm is missing something.
72
+ *
73
+ * Resolved per package with the same expression `doFetchPackument` uses, rather
74
+ * than from `registryConfig.registry`, because a scoped package can carry its own
75
+ * registry and the top-level value would then name the wrong one.
76
+ */
77
+ function registryLabelFor(packageName) {
78
+ const resolved = registryConfig
79
+ ? registryForPackage(registryConfig, packageName)
80
+ : DEFAULT_NPM_REGISTRY_URL;
81
+ // Trailing slashes are trimmed before comparing so that both spellings of the
82
+ // public registry are recognised: this module's own constant carries none,
83
+ // while the resolved configuration default carries one.
84
+ const trimmed = resolved.replace(/\/+$/, "");
85
+ if (trimmed === DEFAULT_NPM_REGISTRY_URL.replace(/\/+$/, ""))
86
+ return "npm";
87
+ return trimmed;
88
+ }
49
89
  async function doFetchPackument(packageName) {
50
- const url = `${DEFAULT_NPM_REGISTRY_URL}/${encodeURIComponent(packageName)
90
+ const base = registryConfig
91
+ ? registryForPackage(registryConfig, packageName)
92
+ : DEFAULT_NPM_REGISTRY_URL;
93
+ const url = `${base.replace(/\/+$/, "")}/${encodeURIComponent(packageName)
51
94
  .replace(/%40/g, "@")
52
95
  .replace(/%2F/g, "/")}`;
53
96
  const batchId = registryDebugLog ? nextRegistryBatchId() : "";
@@ -109,7 +152,7 @@ export async function resolvePublishedFixVersion(packageName, fixedVersionHint)
109
152
  if (!packument) {
110
153
  return {
111
154
  resolvedVersion: null,
112
- note: `Fixed-version hint ${fixedVersionHint} could not be verified against the npm registry for ${packageName}.`,
155
+ note: `Fixed-version hint ${fixedVersionHint} could not be verified for ${packageName} against ${registryLabelFor(packageName)}.`,
113
156
  verified: false,
114
157
  candidatesChecked: 0,
115
158
  candidatesKnownVulnerable: 0,
@@ -139,20 +182,26 @@ export async function resolvePublishedFixVersion(packageName, fixedVersionHint)
139
182
  resolvedVersion: nearestPublishedVersion,
140
183
  note: fixedVersionHintIsPreRelease
141
184
  ? `Advisory fixed-version hint ${fixedVersionHint} is a pre-release; using nearest published non-pre-release version ${nearestPublishedVersion}.`
142
- : `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}; using nearest published version ${nearestPublishedVersion}.`,
185
+ : `Advisory fixed-version hint ${fixedVersionHint} was not found for ${packageName} on ${registryLabelFor(packageName)}; using nearest published version ${nearestPublishedVersion}.`,
143
186
  verified: true,
144
187
  candidatesChecked: 0,
145
188
  candidatesKnownVulnerable: 0,
146
189
  candidatesUnknownCoverage: 0,
147
190
  publishedAt: packument.time?.[nearestPublishedVersion] ?? null,
191
+ // Set from the same test that picks the wording above, so the flag and the
192
+ // sentence can never disagree. A pre-release hint is deliberately excluded:
193
+ // that is reported as a pre-release problem rather than an availability one,
194
+ // and it belongs in a different section of the output.
195
+ advisoryHintUnavailable: !fixedVersionHintIsPreRelease,
148
196
  };
149
197
  }
150
198
  return {
151
199
  resolvedVersion: null,
152
200
  note: fixedVersionHintIsPreRelease
153
201
  ? `Advisory fixed-version hint ${fixedVersionHint} is a pre-release, and no published non-pre-release version >= ${fixedVersionHint} was found for ${packageName}.`
154
- : `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}, and no published version >= ${fixedVersionHint} was found.`,
202
+ : `Advisory fixed-version hint ${fixedVersionHint} was not found for ${packageName} on ${registryLabelFor(packageName)}, and no version >= ${fixedVersionHint} was found there either.`,
155
203
  verified: true,
204
+ advisoryHintUnavailable: !fixedVersionHintIsPreRelease,
156
205
  candidatesChecked: 0,
157
206
  candidatesKnownVulnerable: 0,
158
207
  candidatesUnknownCoverage: 0,
@@ -195,7 +244,7 @@ async function resolveFromAdvisoryRanges(packageName, installedVersion, vulnerab
195
244
  if (!packument) {
196
245
  return {
197
246
  resolvedVersion: null,
198
- note: `Published versions for ${packageName} could not be verified against the npm registry.`,
247
+ note: `Published versions for ${packageName} could not be verified against ${registryLabelFor(packageName)}.`,
199
248
  verified: false,
200
249
  candidatesChecked: 0,
201
250
  candidatesKnownVulnerable: 0,
@@ -211,7 +260,7 @@ async function resolveFromAdvisoryRanges(packageName, installedVersion, vulnerab
211
260
  if (candidates.length === 0) {
212
261
  return {
213
262
  resolvedVersion: null,
214
- note: `No published versions above ${installedVersion} were found for ${packageName}.`,
263
+ note: `No versions above ${installedVersion} were found for ${packageName} on ${registryLabelFor(packageName)}.`,
215
264
  verified: true,
216
265
  candidatesChecked: 0,
217
266
  candidatesKnownVulnerable: 0,
@@ -269,7 +318,7 @@ async function resolveFromAdvisoryRanges(packageName, installedVersion, vulnerab
269
318
  }
270
319
  return {
271
320
  resolvedVersion: null,
272
- note: `No known non-vulnerable published version was found above ${installedVersion} for ${packageName}.`,
321
+ note: `No known non-vulnerable version was found above ${installedVersion} for ${packageName} on ${registryLabelFor(packageName)}.`,
273
322
  verified: true,
274
323
  candidatesChecked,
275
324
  candidatesKnownVulnerable,
@@ -2,13 +2,18 @@ import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils
2
2
  import { fetchPackument } from "./npm-registry.js";
3
3
  import { findSafeVersionWithinParentRange } from "./npm-transitive-graph.js";
4
4
  import { findPackageAlongPath } from "./package-path-lookup.js";
5
+ import { resolveDirectParentContext } from "./parent-candidate-resolver.js";
5
6
  export async function resolveTransitiveRemediationViaRegistry(args) {
6
7
  if (args.finding.relationship !== "transitive")
7
8
  return null;
8
9
  const viaPath = getBestPath(args.finding);
9
10
  if (!viaPath || viaPath.length < 3)
10
11
  return null;
11
- const directParentContext = resolveDirectParentContext(viaPath, args.packages, args.directDependencyNames);
12
+ const directParentContext = resolveDirectParentContext({
13
+ viaPath,
14
+ packages: args.packages,
15
+ directDependencyNames: args.directDependencyNames,
16
+ });
12
17
  if (!directParentContext)
13
18
  return null;
14
19
  const { directParentName, immediateParentName, directParent } = directParentContext;
@@ -59,7 +64,11 @@ export async function resolveNpmTransitiveRemediation(args) {
59
64
  const viaPath = getBestPath(args.finding);
60
65
  if (!viaPath || viaPath.length < 3)
61
66
  return null;
62
- const directParentContext = resolveDirectParentContext(viaPath, args.packages, args.directDependencyNames);
67
+ const directParentContext = resolveDirectParentContext({
68
+ viaPath,
69
+ packages: args.packages,
70
+ directDependencyNames: args.directDependencyNames,
71
+ });
63
72
  if (!directParentContext)
64
73
  return null;
65
74
  const { directParentName, immediateParentName, directParent } = directParentContext;
@@ -154,34 +163,6 @@ function getBestPath(finding) {
154
163
  return null;
155
164
  return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
156
165
  }
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
166
  function buildOfflineSafeCandidates(installedVersion, fixedVersionHint) {
186
167
  if (!fixedVersionHint || !looksLikeVersion(fixedVersionHint))
187
168
  return [];
@@ -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
+ }
@@ -1,6 +1,7 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } 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
  }
@@ -9,20 +9,20 @@ export function getCompletenessImpact(completeness) {
9
9
  export function formatDiagnosticMessage(code, count, affectedPackageCount) {
10
10
  switch (code) {
11
11
  case "OSV_DETAIL_TRANSIENT_FAILURE":
12
- return `${count} advisory detail ${pluralize(count, "lookup")} failed with a transient error — re-run to retry.`;
12
+ return `${count} advisory detail ${pluralize(count, "lookup")} failed with a transient error: re-run to retry.`;
13
13
  case "OSV_DETAIL_OFFLINE_MISSING":
14
- return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} missing from the local advisory database — refresh to sync.`;
14
+ return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} missing from the local advisory database: refresh to sync.`;
15
15
  case "OSV_DETAIL_CONFIRMED_MISSING":
16
- return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} confirmed missing from the OSV API — affected findings lack detail data.`;
16
+ return `${count} advisory detail ${pluralize(count, "record")} ${pluralize(count, "is", "are")} confirmed missing from the OSV API: affected findings lack detail data.`;
17
17
  case "PACKUMENT_FETCH_FAILURE":
18
- return `${count} packument ${pluralize(count, "fetch", "fetches")} failed — remediation guidance may be incomplete.`;
18
+ return `${count} packument ${pluralize(count, "fetch", "fetches")} failed: remediation guidance may be incomplete.`;
19
19
  case "REMEDIATION_FAILURE":
20
20
  if (affectedPackageCount !== undefined) {
21
- return `${count} transitive remediation ${pluralize(count, "attempt")} failed across ${affectedPackageCount} ${pluralize(affectedPackageCount, "package")} — some fix recommendations may be missing.`;
21
+ return `${count} transitive remediation ${pluralize(count, "attempt")} failed across ${affectedPackageCount} ${pluralize(affectedPackageCount, "package")}: some fix recommendations may be missing.`;
22
22
  }
23
- return `${count} transitive remediation ${pluralize(count, "attempt")} failed — some fix recommendations may be missing.`;
23
+ return `${count} transitive remediation ${pluralize(count, "attempt")} failed: some fix recommendations may be missing.`;
24
24
  case "CHAIN_RESOLUTION_FAILURE":
25
- return `${count} chain resolution ${pluralize(count, "attempt")} failed — some validated upgrade chains may be missing.`;
25
+ return `${count} chain resolution ${pluralize(count, "attempt")} failed: some validated upgrade chains may be missing.`;
26
26
  default:
27
27
  return `${count} unknown diagnostic occurred.`;
28
28
  }