cve-lite-cli 1.10.0 → 1.11.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.
package/dist/index.js CHANGED
@@ -270,7 +270,11 @@ function formatAdvisorySourceLine(sourceLabel) {
270
270
  }
271
271
  async function scanProject(params) {
272
272
  const directDependencyNames = readDirectDependencyNames(params.projectPath, !!params.options.prodOnly);
273
- const findings = await scanPackages(params.scanInput.packages, params.batchSize, params.options, { directDependencyNames });
273
+ const findings = await scanPackages(params.scanInput.packages, params.batchSize, params.options, {
274
+ directDependencyNames,
275
+ scanSource: params.scanInput.source,
276
+ scanFilePath: params.scanInput.filePath,
277
+ });
274
278
  if (params.options.usage) {
275
279
  console.log(chalk.gray(`Scanning project source for usage hints...`));
276
280
  const pkgNames = new Set(findings.map(f => f.pkg.name));
@@ -446,21 +450,18 @@ function readDirectDependencyNames(projectPath, prodOnly) {
446
450
  return null;
447
451
  }
448
452
  try {
449
- const raw = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
450
453
  const directNames = new Set();
451
- const sections = [
452
- raw?.dependencies,
453
- raw?.optionalDependencies,
454
- ];
455
- if (!prodOnly) {
456
- sections.push(raw?.devDependencies);
454
+ const rootManifest = readPackageJsonObject(packageJsonPath);
455
+ if (!rootManifest) {
456
+ return null;
457
457
  }
458
- for (const section of sections) {
459
- if (!section || typeof section !== "object")
458
+ addDependencyNamesFromManifest(directNames, rootManifest, prodOnly);
459
+ const workspacePatterns = readWorkspacePatterns(rootManifest);
460
+ for (const workspacePackageJsonPath of resolveWorkspacePackageJsonPaths(projectPath, workspacePatterns)) {
461
+ const workspaceManifest = readPackageJsonObject(workspacePackageJsonPath);
462
+ if (!workspaceManifest)
460
463
  continue;
461
- for (const name of Object.keys(section)) {
462
- directNames.add(name);
463
- }
464
+ addDependencyNamesFromManifest(directNames, workspaceManifest, prodOnly);
464
465
  }
465
466
  return directNames;
466
467
  }
@@ -468,6 +469,89 @@ function readDirectDependencyNames(projectPath, prodOnly) {
468
469
  return null;
469
470
  }
470
471
  }
472
+ function readPackageJsonObject(filePath) {
473
+ try {
474
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
475
+ return raw && typeof raw === "object" ? raw : null;
476
+ }
477
+ catch {
478
+ return null;
479
+ }
480
+ }
481
+ function addDependencyNamesFromManifest(target, manifest, prodOnly) {
482
+ const sections = [
483
+ isRecord(manifest.dependencies) ? manifest.dependencies : undefined,
484
+ isRecord(manifest.optionalDependencies) ? manifest.optionalDependencies : undefined,
485
+ ];
486
+ if (!prodOnly) {
487
+ sections.push(isRecord(manifest.devDependencies) ? manifest.devDependencies : undefined);
488
+ }
489
+ for (const section of sections) {
490
+ if (!section)
491
+ continue;
492
+ for (const name of Object.keys(section)) {
493
+ target.add(name);
494
+ }
495
+ }
496
+ }
497
+ function readWorkspacePatterns(manifest) {
498
+ const workspaces = manifest.workspaces;
499
+ if (Array.isArray(workspaces)) {
500
+ return workspaces.filter((value) => typeof value === "string");
501
+ }
502
+ if (isRecord(workspaces) && Array.isArray(workspaces.packages)) {
503
+ return workspaces.packages.filter((value) => typeof value === "string");
504
+ }
505
+ return [];
506
+ }
507
+ function resolveWorkspacePackageJsonPaths(projectPath, patterns) {
508
+ const matches = new Set();
509
+ for (const pattern of patterns) {
510
+ const normalized = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
511
+ if (!normalized)
512
+ continue;
513
+ for (const relativeDir of expandWorkspacePattern(projectPath, normalized.split("/").filter(Boolean), "")) {
514
+ const packageJsonPath = path.join(projectPath, relativeDir, "package.json");
515
+ if (fs.existsSync(packageJsonPath)) {
516
+ matches.add(packageJsonPath);
517
+ }
518
+ }
519
+ }
520
+ return [...matches];
521
+ }
522
+ function expandWorkspacePattern(projectPath, segments, currentRelativePath) {
523
+ if (segments.length === 0) {
524
+ return currentRelativePath ? [currentRelativePath] : [];
525
+ }
526
+ const [segment, ...rest] = segments;
527
+ if (segment === "*") {
528
+ const baseDir = currentRelativePath ? path.join(projectPath, currentRelativePath) : projectPath;
529
+ let entries = [];
530
+ try {
531
+ entries = fs.readdirSync(baseDir, { withFileTypes: true });
532
+ }
533
+ catch {
534
+ return [];
535
+ }
536
+ return entries
537
+ .filter(entry => entry.isDirectory())
538
+ .flatMap(entry => {
539
+ const nextRelativePath = currentRelativePath
540
+ ? path.join(currentRelativePath, entry.name)
541
+ : entry.name;
542
+ return expandWorkspacePattern(projectPath, rest, nextRelativePath);
543
+ });
544
+ }
545
+ const nextRelativePath = currentRelativePath ? path.join(currentRelativePath, segment) : segment;
546
+ const nextAbsolutePath = path.join(projectPath, nextRelativePath);
547
+ if (!fs.existsSync(nextAbsolutePath) || !fs.statSync(nextAbsolutePath).isDirectory()) {
548
+ return [];
549
+ }
550
+ return expandWorkspacePattern(projectPath, rest, nextRelativePath);
551
+ }
552
+ function isRecord(value) {
553
+ return !!value && typeof value === "object" && !Array.isArray(value);
554
+ }
471
555
  function formatAdvisoryDbFreshness(lastSyncAt) {
472
556
  if (!lastSyncAt) {
473
557
  return chalk.yellow("unknown");
@@ -31,6 +31,13 @@ export function getRecommendedAction(finding) {
31
31
  if (finding.relationship === "direct") {
32
32
  return `Review and upgrade ${finding.pkg.name} directly in this project.`;
33
33
  }
34
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
35
+ return `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range to pull in vulnerable ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion}.`;
36
+ }
37
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
38
+ finding.recommendedNpmTransitiveRemediation.targetVersion) {
39
+ return `Upgrade ${finding.recommendedNpmTransitiveRemediation.package} from ${finding.recommendedNpmTransitiveRemediation.currentVersion} to ${finding.recommendedNpmTransitiveRemediation.targetVersion} to stop pulling in vulnerable ${finding.pkg.name}.`;
40
+ }
34
41
  if (finding.recommendedParentUpgrade) {
35
42
  return `Upgrade ${finding.recommendedParentUpgrade.package} from ${finding.recommendedParentUpgrade.currentVersion} to ${finding.recommendedParentUpgrade.targetVersion} to stop pulling in vulnerable ${finding.pkg.name}.`;
36
43
  }
@@ -54,6 +61,12 @@ export function summarizeRisk(finding) {
54
61
  else if (finding.severity === "high" && finding.relationship === "direct") {
55
62
  risk = "High-severity direct dependency. A direct upgrade is likely the fastest path.";
56
63
  }
64
+ else if (finding.relationship === "transitive" && finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
65
+ risk = `Transitive issue. The current parent range can already absorb a safe ${finding.pkg.name} update via ${finding.recommendedNpmTransitiveRemediation.package}.`;
66
+ }
67
+ else if (finding.relationship === "transitive" && finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version") {
68
+ risk = `Transitive issue. A specific parent upgrade target was found for ${finding.recommendedNpmTransitiveRemediation.package}.`;
69
+ }
57
70
  else if (finding.relationship === "transitive" && finding.recommendedParentUpgrade) {
58
71
  risk = `Transitive issue. A specific parent upgrade target was found for ${finding.recommendedParentUpgrade.package}.`;
59
72
  }
@@ -86,6 +99,13 @@ export function summarizeNextAction(finding) {
86
99
  if (finding.relationship === "direct") {
87
100
  return `Review and upgrade ${finding.pkg.name} directly in this project.`;
88
101
  }
102
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
103
+ return `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range.`;
104
+ }
105
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
106
+ finding.recommendedNpmTransitiveRemediation.targetVersion) {
107
+ return `Upgrade ${finding.recommendedNpmTransitiveRemediation.package} ${finding.recommendedNpmTransitiveRemediation.currentVersion} -> ${finding.recommendedNpmTransitiveRemediation.targetVersion}.`;
108
+ }
89
109
  if (finding.recommendedParentUpgrade) {
90
110
  return `Upgrade ${finding.recommendedParentUpgrade.package} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}.`;
91
111
  }
@@ -112,6 +132,7 @@ export function serializeFinding(finding) {
112
132
  recommendedAction: getRecommendedAction(finding),
113
133
  primaryParent: getPrimaryParent(finding),
114
134
  recommendedParentUpgrade: finding.recommendedParentUpgrade,
135
+ recommendedNpmTransitiveRemediation: finding.recommendedNpmTransitiveRemediation ?? null,
115
136
  cves: finding.cveAliases,
116
137
  dependencyPaths: finding.dependencyPaths,
117
138
  usage: finding.usage ?? null,
@@ -499,11 +499,11 @@ export async function writeHtmlReport(params) {
499
499
  fs.writeFileSync(jsonPath, JSON.stringify(params.data, null, 2), "utf8");
500
500
  fs.writeFileSync(indexPath, renderHtmlReport(params.data), "utf8");
501
501
  if (params.autoOpen) {
502
- await openInBrowser(indexPath);
502
+ openInBrowser(indexPath);
503
503
  }
504
504
  return { reportPath: indexPath };
505
505
  }
506
- async function openInBrowser(filePath) {
506
+ function openInBrowser(filePath) {
507
507
  if (!path.isAbsolute(filePath))
508
508
  return;
509
509
  const cmd = process.platform === "darwin"
@@ -514,11 +514,11 @@ async function openInBrowser(filePath) {
514
514
  const args = process.platform === "win32"
515
515
  ? ["/c", "start", "", filePath]
516
516
  : [filePath];
517
- return new Promise(resolve => {
517
+ try {
518
518
  const child = spawn(cmd, args, { stdio: "ignore", detached: true, shell: false });
519
519
  child.unref();
520
- const timer = setTimeout(resolve, 1500);
521
- child.on("error", () => { clearTimeout(timer); resolve(); });
522
- child.on("close", () => { clearTimeout(timer); resolve(); });
523
- });
520
+ }
521
+ catch {
522
+ // Best-effort only: report creation should not fail if the OS open command is unavailable.
523
+ }
524
524
  }
@@ -71,7 +71,10 @@ export function printPriorityFixes(findings) {
71
71
  const parent = getPrimaryParent(finding);
72
72
  if (parent)
73
73
  console.log(` Parent: ${parent}`);
74
- if (finding.recommendedParentUpgrade) {
74
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
75
+ console.log(` Target: npm update ${finding.recommendedNpmTransitiveRemediation.package} (pulls in ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} within range)`);
76
+ }
77
+ else if (finding.recommendedParentUpgrade) {
75
78
  console.log(` Target: ${finding.recommendedParentUpgrade.package} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}`);
76
79
  }
77
80
  console.log(` Next: ${summarizeNextAction(finding)}`);
@@ -146,7 +149,7 @@ export function printSuggestedFixCommands(findings, scanInput) {
146
149
  }
147
150
  else if (section.kind === "urgent") {
148
151
  const directTargets = section.targets.filter(t => t.kind === "direct");
149
- const parentUpgradeTargets = section.targets.filter(t => t.kind === "parent-upgrade");
152
+ const parentUpgradeTargets = section.targets.filter(t => t.kind === "parent-upgrade" || t.kind === "parent-update");
150
153
  if (directTargets.length > 0) {
151
154
  const validationSummary = summarizeAdjustedValidation(directTargets);
152
155
  const remainingNotes = [];
@@ -288,7 +291,10 @@ export function printPathHints(findings) {
288
291
  for (const example of examples) {
289
292
  console.log(` ${chalk.gray(example)}`);
290
293
  }
291
- if (finding.recommendedParentUpgrade) {
294
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
295
+ console.log(` Recommended parent update: ${chalk.bold.cyan(`npm update ${finding.recommendedNpmTransitiveRemediation.package}`)}`);
296
+ }
297
+ else if (finding.recommendedParentUpgrade) {
292
298
  console.log(` Recommended parent upgrade: ${chalk.bold.cyan(finding.recommendedParentUpgrade.package)} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}`);
293
299
  }
294
300
  }
@@ -355,7 +361,10 @@ export function printCompactOutput(findings, scanInput) {
355
361
  }
356
362
  console.log(`${formatSeverityLabel(sevLabel)} ${chalk.whiteBright(finding.pkg.name)}@${finding.pkg.version}`);
357
363
  console.log(` ${typeLabel}${usageContext}`);
358
- if (finding.recommendedParentUpgrade) {
364
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
365
+ console.log(` ${chalk.gray(`Fix: update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range`)}`);
366
+ }
367
+ else if (finding.recommendedParentUpgrade) {
359
368
  console.log(` ${chalk.gray(`Fix: upgrade ${finding.recommendedParentUpgrade.package} to ${finding.recommendedParentUpgrade.targetVersion}`)}`);
360
369
  }
361
370
  else if (finding.firstFixedVersion) {
@@ -425,6 +434,9 @@ export function printCompactOutput(findings, scanInput) {
425
434
  else if (topFinding.relationship === "direct") {
426
435
  console.log(`Upgrade ${chalk.whiteBright(topFinding.pkg.name)} to latest safe version`);
427
436
  }
437
+ else if (topFinding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
438
+ console.log(`Update ${chalk.whiteBright(topFinding.recommendedNpmTransitiveRemediation.package)} within current range`);
439
+ }
428
440
  else if (topFinding.recommendedParentUpgrade) {
429
441
  console.log(`Upgrade ${chalk.whiteBright(topFinding.recommendedParentUpgrade.package)} ${topFinding.recommendedParentUpgrade.currentVersion} → ${topFinding.recommendedParentUpgrade.targetVersion}`);
430
442
  }
@@ -523,6 +535,11 @@ function renderCommandCallout(command) {
523
535
  }
524
536
  function findSuggestedCommandForFinding(plan, finding) {
525
537
  const target = plan.targets.find(item => {
538
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
539
+ return (item.kind === "parent-update" &&
540
+ item.package === finding.recommendedNpmTransitiveRemediation.package &&
541
+ item.targetVersion === finding.recommendedNpmTransitiveRemediation.targetChildVersion);
542
+ }
526
543
  if (finding.recommendedParentUpgrade) {
527
544
  return (item.package === finding.recommendedParentUpgrade.package &&
528
545
  item.targetVersion === finding.recommendedParentUpgrade.targetVersion);
@@ -532,6 +549,8 @@ function findSuggestedCommandForFinding(plan, finding) {
532
549
  });
533
550
  if (!target)
534
551
  return null;
552
+ if (target.command)
553
+ return target.command;
535
554
  return `${packageManagerCommandPrefix(plan.packageManager)} ${target.package}@${target.targetVersion}`;
536
555
  }
537
556
  function packageManagerCommandPrefix(packageManager) {
@@ -622,7 +641,7 @@ function printParentUpgradeTargetsTable(targets, widthsOverride) {
622
641
  return [
623
642
  target.package,
624
643
  target.currentVersion ?? "-",
625
- chalk.cyan(target.targetVersion),
644
+ chalk.cyan(target.displayTargetVersion ?? target.targetVersion),
626
645
  usageText,
627
646
  chalk.gray(target.reason),
628
647
  ];
@@ -675,7 +694,7 @@ function computeSharedDirectTableWidths(sections) {
675
694
  return computeTableWidths(headers, rows);
676
695
  }
677
696
  function shouldRenderParentUpgradeTable(targets) {
678
- return targets.length > 0 && targets.every(target => target.kind === "parent-upgrade");
697
+ return targets.length > 0 && targets.every(target => target.kind === "parent-upgrade" || target.kind === "parent-update");
679
698
  }
680
699
  function computeSharedParentUpgradeTableWidths(sections) {
681
700
  const parentSections = sections.filter(section => shouldRenderParentUpgradeTable(section.targets));
@@ -692,7 +711,7 @@ function computeSharedParentUpgradeTableWidths(sections) {
692
711
  rows.push([
693
712
  target.package,
694
713
  target.currentVersion ?? "-",
695
- target.targetVersion,
714
+ target.displayTargetVersion ?? target.targetVersion,
696
715
  usageText,
697
716
  target.reason,
698
717
  ]);
@@ -0,0 +1,231 @@
1
+ import fs from "node:fs";
2
+ import { unique, uniquePathArrays } from "../utils/array.js";
3
+ export function loadNpmLockGraph(filePath, options) {
4
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
5
+ const packages = raw?.packages;
6
+ const rawPackages = isRecord(packages) ? packages : {};
7
+ const nodesById = new Map();
8
+ const nodeIdsByPackageKey = new Map();
9
+ const nodeIdByPackagePath = new Map();
10
+ const dependencyRangesByNodeId = new Map();
11
+ const resolutionBasePathsByNodeId = new Map();
12
+ const parentNodeIdsByChildNodeId = new Map();
13
+ const childNodeIdsByParentNodeId = new Map();
14
+ const rangeByParentNodeId = new Map();
15
+ const pathSetByNodeId = new Map();
16
+ if (!packages || typeof packages !== "object") {
17
+ return createGraph({
18
+ entryPackages: [],
19
+ nodesById,
20
+ nodeIdsByPackageKey,
21
+ parentNodeIdsByChildNodeId,
22
+ childNodeIdsByParentNodeId,
23
+ rangeByParentNodeId,
24
+ pathSetByNodeId,
25
+ });
26
+ }
27
+ for (const [packagePath, meta] of Object.entries(rawPackages)) {
28
+ if (!packagePath || packagePath === "")
29
+ continue;
30
+ if (!packagePath.includes("node_modules/"))
31
+ continue;
32
+ const name = packageNameFromPath(packagePath) ?? meta?.name;
33
+ const version = meta?.version;
34
+ const isLinkNode = !!meta?.link;
35
+ if (!name || (!version && !isLinkNode))
36
+ continue;
37
+ const id = packagePath;
38
+ const normalizedVersion = version ?? null;
39
+ const packageKey = buildPackageKey(name, normalizedVersion);
40
+ nodesById.set(id, {
41
+ id,
42
+ packageKey,
43
+ name,
44
+ version: normalizedVersion,
45
+ packagePath,
46
+ dev: !!meta?.dev,
47
+ });
48
+ nodeIdByPackagePath.set(packagePath, id);
49
+ nodeIdsByPackageKey.set(packageKey, [...(nodeIdsByPackageKey.get(packageKey) ?? []), id]);
50
+ dependencyRangesByNodeId.set(id, collectDependencyRanges(resolveDependencySource(meta, rawPackages)));
51
+ resolutionBasePathsByNodeId.set(id, resolveBasePaths(packagePath, meta));
52
+ }
53
+ const rootMeta = isRecord(rawPackages[""]) ? rawPackages[""] : null;
54
+ const entryPackages = resolveEdgesForParent("", collectRootDependencyRanges(rootMeta), [""], nodeIdByPackagePath, childNodeIdsByParentNodeId, parentNodeIdsByChildNodeId, rangeByParentNodeId);
55
+ for (const node of nodesById.values()) {
56
+ resolveEdgesForParent(node.packagePath, dependencyRangesByNodeId.get(node.id) ?? {}, resolutionBasePathsByNodeId.get(node.id) ?? [node.packagePath], nodeIdByPackagePath, childNodeIdsByParentNodeId, parentNodeIdsByChildNodeId, rangeByParentNodeId);
57
+ }
58
+ if (options?.includePaths !== false) {
59
+ const queue = entryPackages.map((entryNodeId) => ({
60
+ nodeId: entryNodeId,
61
+ path: ["project", nodesById.get(entryNodeId)?.name ?? entryNodeId],
62
+ }));
63
+ while (queue.length > 0) {
64
+ const current = queue.shift();
65
+ if (!current)
66
+ continue;
67
+ rememberPath(pathSetByNodeId, current.nodeId, current.path);
68
+ for (const childNodeId of childNodeIdsByParentNodeId.get(current.nodeId) ?? []) {
69
+ const childNode = nodesById.get(childNodeId);
70
+ if (!childNode)
71
+ continue;
72
+ const nextPath = [...current.path, childNode.name];
73
+ const beforeSize = pathSetByNodeId.get(childNodeId)?.size ?? 0;
74
+ rememberPath(pathSetByNodeId, childNodeId, nextPath);
75
+ const afterSize = pathSetByNodeId.get(childNodeId)?.size ?? 0;
76
+ if (afterSize > beforeSize) {
77
+ queue.push({ nodeId: childNodeId, path: nextPath });
78
+ }
79
+ }
80
+ }
81
+ }
82
+ return createGraph({
83
+ entryPackages,
84
+ nodesById,
85
+ nodeIdsByPackageKey,
86
+ parentNodeIdsByChildNodeId,
87
+ childNodeIdsByParentNodeId,
88
+ rangeByParentNodeId,
89
+ pathSetByNodeId,
90
+ });
91
+ }
92
+ function createGraph(args) {
93
+ const entryPackages = Object.freeze([...unique(args.entryPackages)]);
94
+ return {
95
+ entryPackages,
96
+ nodeIdsFor(name, version) {
97
+ return Object.freeze([...(args.nodeIdsByPackageKey.get(buildPackageKey(name, version)) ?? [])]);
98
+ },
99
+ getNode(nodeId) {
100
+ const node = args.nodesById.get(nodeId);
101
+ return node ? Object.freeze({ ...node }) : null;
102
+ },
103
+ parentsFor(nodeId) {
104
+ return Object.freeze([...(args.parentNodeIdsByChildNodeId.get(nodeId) ?? [])]);
105
+ },
106
+ childrenFor(nodeId) {
107
+ return Object.freeze([...(args.childNodeIdsByParentNodeId.get(nodeId) ?? [])]);
108
+ },
109
+ rangeFor(parentNodeId, childName) {
110
+ return args.rangeByParentNodeId.get(parentNodeId)?.get(childName) ?? null;
111
+ },
112
+ pathsFor(nodeId) {
113
+ const serializedPaths = [...(args.pathSetByNodeId.get(nodeId) ?? new Set())]
114
+ .map((item) => item.split(">"));
115
+ return uniquePathArrays(serializedPaths);
116
+ },
117
+ };
118
+ }
119
+ function resolveEdgesForParent(parentPackagePath, dependencyRanges, resolutionBasePaths, nodeIdByPackagePath, childNodeIdsByParentNodeId, parentNodeIdsByChildNodeId, rangeByParentNodeId) {
120
+ const resolvedChildNodeIds = [];
121
+ for (const [dependencyName, range] of Object.entries(dependencyRanges)) {
122
+ const childPackagePath = resolveDependencyPackagePath(resolutionBasePaths, dependencyName, nodeIdByPackagePath);
123
+ if (!childPackagePath)
124
+ continue;
125
+ const childNodeId = nodeIdByPackagePath.get(childPackagePath);
126
+ if (!childNodeId)
127
+ continue;
128
+ resolvedChildNodeIds.push(childNodeId);
129
+ const parentNodeId = parentPackagePath ? nodeIdByPackagePath.get(parentPackagePath) : null;
130
+ if (!parentNodeId)
131
+ continue;
132
+ childNodeIdsByParentNodeId.set(parentNodeId, unique([...(childNodeIdsByParentNodeId.get(parentNodeId) ?? []), childNodeId]));
133
+ parentNodeIdsByChildNodeId.set(childNodeId, unique([...(parentNodeIdsByChildNodeId.get(childNodeId) ?? []), parentNodeId]));
134
+ const rangesForParent = rangeByParentNodeId.get(parentNodeId) ?? new Map();
135
+ rangesForParent.set(dependencyName, range);
136
+ rangeByParentNodeId.set(parentNodeId, rangesForParent);
137
+ }
138
+ return unique(resolvedChildNodeIds);
139
+ }
140
+ function collectDependencyRanges(meta) {
141
+ if (!meta)
142
+ return {};
143
+ const ranges = {};
144
+ for (const source of [
145
+ meta.dependencies,
146
+ meta.optionalDependencies,
147
+ ]) {
148
+ if (!source || typeof source !== "object")
149
+ continue;
150
+ for (const [name, range] of Object.entries(source)) {
151
+ if (typeof range !== "string" || !range)
152
+ continue;
153
+ ranges[name] = range;
154
+ }
155
+ }
156
+ return ranges;
157
+ }
158
+ function collectRootDependencyRanges(meta) {
159
+ if (!meta)
160
+ return {};
161
+ const ranges = collectDependencyRanges(meta);
162
+ if (meta.devDependencies && typeof meta.devDependencies === "object") {
163
+ for (const [name, range] of Object.entries(meta.devDependencies)) {
164
+ if (typeof range !== "string" || !range)
165
+ continue;
166
+ ranges[name] = range;
167
+ }
168
+ }
169
+ return ranges;
170
+ }
171
+ function resolveDependencyPackagePath(basePaths, dependencyName, nodeIdByPackagePath) {
172
+ for (const basePath of basePaths) {
173
+ let currentPath = basePath;
174
+ while (currentPath !== null) {
175
+ const candidatePath = currentPath
176
+ ? `${currentPath}/node_modules/${dependencyName}`
177
+ : `node_modules/${dependencyName}`;
178
+ if (nodeIdByPackagePath.has(candidatePath)) {
179
+ return candidatePath;
180
+ }
181
+ currentPath = nextAncestorPackagePath(currentPath);
182
+ }
183
+ }
184
+ return null;
185
+ }
186
+ function nextAncestorPackagePath(packagePath) {
187
+ if (!packagePath)
188
+ return null;
189
+ const nestedIndex = packagePath.lastIndexOf("/node_modules/");
190
+ if (nestedIndex >= 0) {
191
+ return packagePath.slice(0, nestedIndex);
192
+ }
193
+ if (packagePath.startsWith("node_modules/")) {
194
+ return "";
195
+ }
196
+ return null;
197
+ }
198
+ function packageNameFromPath(packagePath) {
199
+ const marker = "node_modules/";
200
+ const markerIndex = packagePath.lastIndexOf(marker);
201
+ if (markerIndex === -1)
202
+ return null;
203
+ const name = packagePath.slice(markerIndex + marker.length);
204
+ return name || null;
205
+ }
206
+ function rememberPath(pathSetByNodeId, nodeId, pathParts) {
207
+ const serialized = pathParts.join(">");
208
+ const existing = pathSetByNodeId.get(nodeId) ?? new Set();
209
+ existing.add(serialized);
210
+ pathSetByNodeId.set(nodeId, existing);
211
+ }
212
+ function isRecord(value) {
213
+ return !!value && typeof value === "object";
214
+ }
215
+ function buildPackageKey(name, version) {
216
+ return `${name}@${version ?? "<link>"}`;
217
+ }
218
+ function resolveDependencySource(meta, rawPackages) {
219
+ if (!meta)
220
+ return null;
221
+ if (!meta.link || !meta.resolved)
222
+ return meta;
223
+ const linkedTarget = rawPackages[meta.resolved];
224
+ return linkedTarget ?? meta;
225
+ }
226
+ function resolveBasePaths(packagePath, meta) {
227
+ if (!meta?.link || !meta.resolved) {
228
+ return [packagePath];
229
+ }
230
+ return unique([meta.resolved, packagePath]);
231
+ }
@@ -12,7 +12,11 @@ export function upsertPackage(map, candidate) {
12
12
  export function normalizeNodeModulesPath(pkgPath) {
13
13
  const parts = pkgPath.split("/").filter(Boolean);
14
14
  const names = ["project"];
15
- for (let i = 0; i < parts.length; i++) {
15
+ const firstNodeModulesIndex = parts.indexOf("node_modules");
16
+ if (firstNodeModulesIndex > 0) {
17
+ names.push(...parts.slice(0, firstNodeModulesIndex));
18
+ }
19
+ for (let i = Math.max(firstNodeModulesIndex, 0); i < parts.length; i++) {
16
20
  if (parts[i] !== "node_modules")
17
21
  continue;
18
22
  const next = parts[i + 1];
@@ -99,6 +99,48 @@ export function buildSuggestedFixCommandPlan(findings, scanInput) {
99
99
  }
100
100
  continue;
101
101
  }
102
+ if (packageManager === "npm" &&
103
+ finding.relationship === "transitive" &&
104
+ finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
105
+ upsertTarget(targetsByPackage, {
106
+ package: finding.recommendedNpmTransitiveRemediation.package,
107
+ currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
108
+ targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
109
+ displayTargetVersion: "within current range",
110
+ scannedVersions: null,
111
+ knownVulnerableVersions: null,
112
+ kind: "parent-update",
113
+ urgent,
114
+ severity: finding.severity,
115
+ adjusted: false,
116
+ adjustmentNote: null,
117
+ reason: `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range to pick up ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion}.`,
118
+ command: `npm update ${finding.recommendedNpmTransitiveRemediation.package}`,
119
+ usage: finding.usage ?? null,
120
+ });
121
+ continue;
122
+ }
123
+ if (packageManager === "npm" &&
124
+ finding.relationship === "transitive" &&
125
+ finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
126
+ finding.recommendedNpmTransitiveRemediation.targetVersion &&
127
+ isUpgradeTarget(finding.recommendedNpmTransitiveRemediation.currentVersion, finding.recommendedNpmTransitiveRemediation.targetVersion)) {
128
+ upsertTarget(targetsByPackage, {
129
+ package: finding.recommendedNpmTransitiveRemediation.package,
130
+ currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
131
+ targetVersion: finding.recommendedNpmTransitiveRemediation.targetVersion,
132
+ scannedVersions: null,
133
+ knownVulnerableVersions: null,
134
+ kind: "parent-upgrade",
135
+ urgent,
136
+ severity: finding.severity,
137
+ adjusted: false,
138
+ adjustmentNote: null,
139
+ reason: `Parent upgrade for vulnerable ${finding.pkg.name}@${finding.pkg.version}`,
140
+ usage: finding.usage ?? null,
141
+ });
142
+ continue;
143
+ }
102
144
  if (finding.relationship === "transitive" &&
103
145
  finding.recommendedParentUpgrade &&
104
146
  isUpgradeTarget(finding.recommendedParentUpgrade.currentVersion, finding.recommendedParentUpgrade.targetVersion)) {
@@ -127,6 +169,18 @@ export function buildSuggestedFixCommandPlan(findings, scanInput) {
127
169
  });
128
170
  continue;
129
171
  }
172
+ if (packageManager !== "npm" &&
173
+ finding.relationship === "transitive" &&
174
+ finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
175
+ const primaryParent = getPrimaryParent(finding);
176
+ skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
177
+ package: finding.pkg.name,
178
+ version: finding.pkg.version,
179
+ relationship: finding.relationship,
180
+ reason: `${finding.pkg.name}@${finding.pkg.version} is pulled in by ${primaryParent ?? finding.recommendedNpmTransitiveRemediation.package}. No safe upgrade version for ${finding.recommendedNpmTransitiveRemediation.package} was identified automatically — npm can update it within the current range, but this fix path is npm-specific.`,
181
+ });
182
+ continue;
183
+ }
130
184
  const primaryParent = getPrimaryParent(finding);
131
185
  if (finding.relationship === "transitive" && primaryParent) {
132
186
  const fixClause = finding.firstFixedVersion
@@ -165,7 +219,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput) {
165
219
  const skipped = [...skippedByKey.values()].sort((a, b) => a.package.localeCompare(b.package));
166
220
  const sections = buildSections(targets, packageManager);
167
221
  const command = targets.length > 0
168
- ? `${commandPrefix(packageManager)} ${targets.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`
222
+ ? buildCommandForTargets(targets, packageManager)
169
223
  : null;
170
224
  return {
171
225
  packageManager,
@@ -222,7 +276,13 @@ function upsertTarget(targetsByPackage, next) {
222
276
  severity: severityOrder[next.severity] > severityOrder[existing.severity] ? next.severity : existing.severity,
223
277
  adjusted: existing.adjusted || next.adjusted,
224
278
  adjustmentNote: existing.adjustmentNote ?? next.adjustmentNote ?? null,
225
- kind: existing.kind === "direct" || next.kind === "direct" ? "direct" : "parent-upgrade",
279
+ kind: existing.kind === "direct" || next.kind === "direct"
280
+ ? "direct"
281
+ : existing.kind === "parent-update" || next.kind === "parent-update"
282
+ ? "parent-update"
283
+ : "parent-upgrade",
284
+ displayTargetVersion: existing.displayTargetVersion ?? next.displayTargetVersion,
285
+ command: existing.command ?? next.command,
226
286
  usage: existing.usage || next.usage,
227
287
  };
228
288
  if (looksLikeVersion(existing.targetVersion) && looksLikeVersion(next.targetVersion)) {
@@ -256,7 +316,6 @@ function isUpgradeTarget(currentVersion, targetVersion) {
256
316
  }
257
317
  function buildSections(targets, packageManager) {
258
318
  const groups = [];
259
- const commandForTargets = (items) => `${commandPrefix(packageManager)} ${items.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`;
260
319
  const sectionOrder = [
261
320
  { kind: "urgent", severity: "critical" },
262
321
  { kind: "urgent", severity: "high" },
@@ -266,6 +325,9 @@ function buildSections(targets, packageManager) {
266
325
  { kind: "direct-adjusted", severity: "medium" },
267
326
  { kind: "direct-adjusted", severity: "low" },
268
327
  { kind: "direct-adjusted", severity: "unknown" },
328
+ { kind: "parent-update", severity: "medium" },
329
+ { kind: "parent-update", severity: "low" },
330
+ { kind: "parent-update", severity: "unknown" },
269
331
  { kind: "parent-upgrade", severity: "medium" },
270
332
  { kind: "parent-upgrade", severity: "low" },
271
333
  { kind: "parent-upgrade", severity: "unknown" },
@@ -282,7 +344,7 @@ function buildSections(targets, packageManager) {
282
344
  kind: entry.kind,
283
345
  severity: entry.severity,
284
346
  title: buildSectionTitle(entry.kind, entry.severity),
285
- command: commandForTargets(sectionTargets),
347
+ command: buildCommandForTargets(sectionTargets, packageManager),
286
348
  targets: sectionTargets,
287
349
  });
288
350
  }
@@ -303,8 +365,31 @@ function buildSectionTitle(kind, severity) {
303
365
  if (kind === "direct-adjusted") {
304
366
  return `${severityTitle} direct fixes (registry-adjusted)`;
305
367
  }
368
+ if (kind === "parent-update") {
369
+ return `${severityTitle} parent updates within range`;
370
+ }
306
371
  return `${severityTitle} parent upgrades`;
307
372
  }
373
+ function buildCommandForTargets(targets, packageManager) {
374
+ const explicitCommands = targets
375
+ .map(target => target.command)
376
+ .filter((value) => Boolean(value));
377
+ const commandParts = [];
378
+ const parentUpdateTargets = targets.filter(target => target.kind === "parent-update");
379
+ const installTargets = targets.filter(target => target.kind !== "parent-update");
380
+ if (parentUpdateTargets.length > 0) {
381
+ const updateCommands = explicitCommands.length > 0
382
+ ? [...new Set(explicitCommands)]
383
+ : packageManager === "npm"
384
+ ? [`npm update ${parentUpdateTargets.map(target => target.package).join(" ")}`]
385
+ : [];
386
+ commandParts.push(...updateCommands);
387
+ }
388
+ if (installTargets.length > 0) {
389
+ commandParts.push(`${commandPrefix(packageManager)} ${installTargets.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`);
390
+ }
391
+ return commandParts.join(" && ");
392
+ }
308
393
  function capitalize(value) {
309
394
  return value.charAt(0).toUpperCase() + value.slice(1);
310
395
  }
@@ -0,0 +1,123 @@
1
+ import { compareVersions, looksLikeVersion } from "../utils/version.js";
2
+ export function createNpmTransitiveGraph(args) {
3
+ const nodesById = new Map();
4
+ const nodeIdsByPackageKey = new Map();
5
+ const childNodeIdsByParentNodeId = new Map();
6
+ const rangeByParentNodeId = new Map();
7
+ for (const node of args.nodes) {
8
+ nodesById.set(node.id, { ...node });
9
+ nodeIdsByPackageKey.set(buildPackageKey(node.name, node.version), [
10
+ ...(nodeIdsByPackageKey.get(buildPackageKey(node.name, node.version)) ?? []),
11
+ node.id,
12
+ ]);
13
+ }
14
+ for (const edge of args.edges) {
15
+ childNodeIdsByParentNodeId.set(edge.parentNodeId, [
16
+ ...(childNodeIdsByParentNodeId.get(edge.parentNodeId) ?? []),
17
+ edge.childNodeId,
18
+ ]);
19
+ const ranges = rangeByParentNodeId.get(edge.parentNodeId) ?? new Map();
20
+ ranges.set(edge.childName, edge.range);
21
+ rangeByParentNodeId.set(edge.parentNodeId, ranges);
22
+ }
23
+ return {
24
+ nodeIdsFor(name, version) {
25
+ return Object.freeze([...(nodeIdsByPackageKey.get(buildPackageKey(name, version)) ?? [])]);
26
+ },
27
+ getNode(nodeId) {
28
+ const node = nodesById.get(nodeId);
29
+ return node ? Object.freeze({ ...node }) : null;
30
+ },
31
+ childrenFor(nodeId) {
32
+ return Object.freeze([...(childNodeIdsByParentNodeId.get(nodeId) ?? [])]);
33
+ },
34
+ rangeFor(parentNodeId, childName) {
35
+ return rangeByParentNodeId.get(parentNodeId)?.get(childName) ?? null;
36
+ },
37
+ };
38
+ }
39
+ function buildPackageKey(name, version) {
40
+ return `${name}@${version ?? "null"}`;
41
+ }
42
+ export function findSafeVersionWithinParentRange(args) {
43
+ const allowedRange = args.graph.rangeFor(args.parentNodeId, args.childName);
44
+ if (!allowedRange)
45
+ return null;
46
+ const matchingCandidates = args.candidates
47
+ .filter(looksLikeVersion)
48
+ .filter(candidate => versionSatisfiesRange(candidate, allowedRange))
49
+ .sort(compareVersions);
50
+ return matchingCandidates.at(-1) ?? null;
51
+ }
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;
118
+ }
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)];
123
+ }
@@ -0,0 +1,221 @@
1
+ import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
+ import { fetchPackument } from "./npm-registry.js";
3
+ import { findSafeVersionWithinParentRange } from "./npm-transitive-graph.js";
4
+ export async function resolveNpmTransitiveRemediation(args) {
5
+ if (args.finding.relationship !== "transitive")
6
+ return null;
7
+ const viaPath = getBestPath(args.finding);
8
+ if (!viaPath || viaPath.length < 3)
9
+ return null;
10
+ const directParentContext = resolveDirectParentContext(viaPath, args.packages, args.directDependencyNames);
11
+ if (!directParentContext)
12
+ return null;
13
+ const { directParentName, immediateParentName, directParent } = directParentContext;
14
+ const vulnerableName = args.finding.pkg.name;
15
+ // Task 3 keeps the graph-aware resolution focused on exact direct-child npm paths.
16
+ if (directParentName !== immediateParentName) {
17
+ return null;
18
+ }
19
+ const parentNodeId = resolveParentNodeId({
20
+ graph: args.graph,
21
+ parentName: directParentName,
22
+ parentVersion: directParent.version,
23
+ childName: vulnerableName,
24
+ childVersion: args.finding.pkg.version,
25
+ });
26
+ if (!parentNodeId)
27
+ return null;
28
+ const safeCandidates = await findSafeChildCandidates(vulnerableName, args.finding.pkg.version, args.finding.validatedFirstFixedVersion ?? args.finding.firstFixedVersion);
29
+ if (safeCandidates.length === 0)
30
+ return null;
31
+ const inRangeTarget = findSafeVersionWithinParentRange({
32
+ graph: args.graph,
33
+ parentNodeId,
34
+ childName: vulnerableName,
35
+ candidates: safeCandidates,
36
+ });
37
+ if (inRangeTarget) {
38
+ return {
39
+ kind: "update-parent-within-range",
40
+ package: directParentName,
41
+ currentVersion: directParent.version,
42
+ targetChildVersion: inRangeTarget,
43
+ viaPath,
44
+ reason: `${directParentName}@${directParent.version} already allows ${vulnerableName}@${inRangeTarget} within the current dependency range`,
45
+ };
46
+ }
47
+ const parentPackument = await fetchPackument(directParentName);
48
+ const parentVersions = Object.keys(parentPackument?.versions ?? {})
49
+ .filter(looksLikeVersion)
50
+ .filter(version => !isPreReleaseVersion(version))
51
+ .filter(version => compareVersions(version, directParent.version) > 0)
52
+ .sort(compareVersions);
53
+ for (const version of parentVersions) {
54
+ const manifest = parentPackument?.versions?.[version];
55
+ const depRange = manifest?.dependencies?.[vulnerableName] ??
56
+ manifest?.optionalDependencies?.[vulnerableName];
57
+ if (!depRange)
58
+ continue;
59
+ const targetChildVersion = highestVersionSatisfyingRange(safeCandidates, depRange);
60
+ if (!targetChildVersion)
61
+ continue;
62
+ const stillAllowsInstalled = versionSatisfiesRange(args.finding.pkg.version, depRange);
63
+ if (stillAllowsInstalled && compareVersions(targetChildVersion, args.finding.pkg.version) <= 0) {
64
+ continue;
65
+ }
66
+ return {
67
+ kind: "upgrade-parent-to-version",
68
+ package: directParentName,
69
+ currentVersion: directParent.version,
70
+ targetVersion: version,
71
+ targetChildVersion,
72
+ viaPath,
73
+ reason: `${directParentName}@${version} no longer allows ${vulnerableName}@${args.finding.pkg.version} and allows ${targetChildVersion}+`,
74
+ };
75
+ }
76
+ return null;
77
+ }
78
+ function getBestPath(finding) {
79
+ const paths = finding.dependencyPaths ?? [];
80
+ if (paths.length === 0)
81
+ return null;
82
+ return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
83
+ }
84
+ function findDirectDependency(packages, name, directDependencyNames) {
85
+ for (const pkg of packages) {
86
+ if (pkg.name !== name)
87
+ continue;
88
+ if (directDependencyNames?.has(name)) {
89
+ return pkg;
90
+ }
91
+ const paths = pkg.paths ?? [];
92
+ if (paths.some(path => path.at(-1) === name && path.length >= 2)) {
93
+ return pkg;
94
+ }
95
+ }
96
+ return null;
97
+ }
98
+ function resolveDirectParentContext(viaPath, packages, directDependencyNames) {
99
+ const immediateParentName = viaPath[viaPath.length - 2];
100
+ const candidateSegments = viaPath.slice(1, -1);
101
+ const directParentCandidates = directDependencyNames
102
+ ? candidateSegments.filter(segment => directDependencyNames.has(segment))
103
+ : [viaPath[1]].filter(Boolean);
104
+ const directParentName = directParentCandidates[0];
105
+ if (!directParentName)
106
+ return null;
107
+ const directParent = findDirectDependency(packages, directParentName, directDependencyNames);
108
+ if (!directParent)
109
+ return null;
110
+ return { directParentName, immediateParentName, directParent };
111
+ }
112
+ async function findSafeChildCandidates(packageName, installedVersion, fixedVersionHint) {
113
+ const packument = await fetchPackument(packageName);
114
+ if (!packument)
115
+ return [];
116
+ return Object.keys(packument.versions ?? {})
117
+ .filter(looksLikeVersion)
118
+ .filter(version => !isPreReleaseVersion(version))
119
+ .filter(version => compareVersions(version, installedVersion) > 0)
120
+ .filter(version => !fixedVersionHint || compareVersions(version, fixedVersionHint) >= 0)
121
+ .sort(compareVersions);
122
+ }
123
+ function resolveParentNodeId(args) {
124
+ const candidateNodeIds = args.graph.nodeIdsFor(args.parentName, args.parentVersion);
125
+ if (candidateNodeIds.length === 0)
126
+ return null;
127
+ for (const nodeId of candidateNodeIds) {
128
+ const childNodeIds = args.graph.childrenFor(nodeId);
129
+ const hasMatchingChild = childNodeIds.some((childNodeId) => {
130
+ const childNode = args.graph.getNode(childNodeId);
131
+ return childNode?.name === args.childName && childNode.version === args.childVersion;
132
+ });
133
+ if (!hasMatchingChild)
134
+ continue;
135
+ if (!args.graph.rangeFor(nodeId, args.childName))
136
+ continue;
137
+ return nodeId;
138
+ }
139
+ for (const nodeId of candidateNodeIds) {
140
+ if (args.graph.rangeFor(nodeId, args.childName)) {
141
+ return nodeId;
142
+ }
143
+ }
144
+ return candidateNodeIds[0] ?? null;
145
+ }
146
+ function highestVersionSatisfyingRange(candidates, rawRange) {
147
+ const matches = candidates.filter(candidate => versionSatisfiesRange(candidate, rawRange)).sort(compareVersions);
148
+ return matches.at(-1) ?? null;
149
+ }
150
+ function versionSatisfiesRange(version, rawRange) {
151
+ const range = rawRange.trim();
152
+ if (!range)
153
+ return false;
154
+ if (range === "*" || range === "latest")
155
+ return true;
156
+ const orParts = range.split("||").map(part => part.trim()).filter(Boolean);
157
+ return orParts.some(part => satisfiesAndRange(version, part));
158
+ }
159
+ function satisfiesAndRange(version, range) {
160
+ const normalized = normalizeRange(range);
161
+ if (!normalized)
162
+ return false;
163
+ const tokens = normalized.split(/\s+/).filter(Boolean);
164
+ return tokens.every(token => satisfiesComparator(version, token));
165
+ }
166
+ function normalizeRange(range) {
167
+ const trimmed = range.trim();
168
+ if (!trimmed)
169
+ return null;
170
+ if (looksLikeVersion(trimmed)) {
171
+ return `=${trimmed}`;
172
+ }
173
+ if (trimmed.startsWith("^")) {
174
+ const base = trimmed.slice(1);
175
+ if (!looksLikeVersion(base))
176
+ return null;
177
+ const [major, minor, patch] = parseCoreVersion(base);
178
+ if (major > 0)
179
+ return `>=${base} <${major + 1}.0.0`;
180
+ if (minor > 0)
181
+ return `>=${base} <0.${minor + 1}.0`;
182
+ return `>=${base} <0.0.${patch + 1}`;
183
+ }
184
+ if (trimmed.startsWith("~")) {
185
+ const base = trimmed.slice(1);
186
+ if (!looksLikeVersion(base))
187
+ return null;
188
+ const [major, minor] = parseCoreVersion(base);
189
+ return `>=${base} <${major}.${minor + 1}.0`;
190
+ }
191
+ return trimmed;
192
+ }
193
+ function satisfiesComparator(version, comparator) {
194
+ const token = comparator.trim();
195
+ if (!token)
196
+ return true;
197
+ const match = token.match(/^(<=|>=|<|>|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[-+][^\s]+)?)$/);
198
+ if (!match)
199
+ return false;
200
+ const operator = match[1] ?? "=";
201
+ const target = match[2];
202
+ const cmp = compareVersions(version, target);
203
+ switch (operator) {
204
+ case "<":
205
+ return cmp < 0;
206
+ case "<=":
207
+ return cmp <= 0;
208
+ case ">":
209
+ return cmp > 0;
210
+ case ">=":
211
+ return cmp >= 0;
212
+ case "=":
213
+ return cmp === 0;
214
+ default:
215
+ return false;
216
+ }
217
+ }
218
+ function parseCoreVersion(version) {
219
+ const [major = "0", minor = "0", patch = "0"] = version.split(/[+-]/)[0].split(".");
220
+ return [Number(major), Number(minor), Number(patch)];
221
+ }
@@ -1,20 +1,19 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
- export async function resolveRecommendedParentUpgrade(finding, packages) {
3
+ export async function resolveRecommendedParentUpgrade(finding, packages, directDependencyNames) {
4
4
  if (finding.relationship !== "transitive")
5
5
  return null;
6
6
  const viaPath = getBestPath(finding);
7
7
  if (!viaPath || viaPath.length < 3)
8
8
  return null;
9
- const directParentName = viaPath[1];
10
- const immediateParentName = viaPath[viaPath.length - 2];
11
- const vulnerableName = finding.pkg.name;
12
- const directParent = findDirectDependency(packages, directParentName);
13
- if (!directParent)
9
+ const directParentContext = resolveDirectParentContext(viaPath, packages, directDependencyNames);
10
+ if (!directParentContext)
14
11
  return null;
12
+ const { directParentName, immediateParentName, directParent } = directParentContext;
13
+ const vulnerableName = finding.pkg.name;
15
14
  // Common reliable case:
16
15
  // project -> sanitize-html -> lodash
17
- if (viaPath.length === 3) {
16
+ if (directParentName === immediateParentName) {
18
17
  return findUpgradeForExactDirectChild({
19
18
  directParentName,
20
19
  directParentVersion: directParent.version,
@@ -40,17 +39,34 @@ function getBestPath(finding) {
40
39
  return null;
41
40
  return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
42
41
  }
43
- function findDirectDependency(packages, name) {
42
+ function findDirectDependency(packages, name, directDependencyNames) {
44
43
  for (const pkg of packages) {
45
44
  if (pkg.name !== name)
46
45
  continue;
46
+ if (directDependencyNames?.has(name)) {
47
+ return pkg;
48
+ }
47
49
  const paths = pkg.paths ?? [];
48
- if (paths.some(path => path.length === 2 && path[1] === name)) {
50
+ if (paths.some(path => path.at(-1) === name && path.length >= 2)) {
49
51
  return pkg;
50
52
  }
51
53
  }
52
54
  return null;
53
55
  }
56
+ function resolveDirectParentContext(viaPath, packages, directDependencyNames) {
57
+ const immediateParentName = viaPath[viaPath.length - 2];
58
+ const candidateSegments = viaPath.slice(1, -1);
59
+ const directParentCandidates = directDependencyNames
60
+ ? candidateSegments.filter(segment => directDependencyNames.has(segment))
61
+ : [viaPath[1]].filter(Boolean);
62
+ const directParentName = directParentCandidates[0];
63
+ if (!directParentName)
64
+ return null;
65
+ const directParent = findDirectDependency(packages, directParentName, directDependencyNames);
66
+ if (!directParent)
67
+ return null;
68
+ return { directParentName, immediateParentName, directParent };
69
+ }
54
70
  function findPackageVersion(packages, name, pathPrefix) {
55
71
  for (const pkg of packages) {
56
72
  if (pkg.name !== name)
package/dist/scanner.js CHANGED
@@ -9,6 +9,8 @@ import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
9
9
  import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
10
10
  import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
11
11
  import { resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion } from "./remediation/npm-registry.js";
12
+ import { resolveNpmTransitiveRemediation } from "./remediation/npm-transitive-resolution.js";
13
+ import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js";
12
14
  export function createAdvisorySource(options) {
13
15
  const offline = !!options?.offline || !!options?.offlineDb;
14
16
  if (offline) {
@@ -180,21 +182,98 @@ export async function scanPackages(packages, batchSize, options, context) {
180
182
  validatedTargetScannedVersions: null,
181
183
  validatedTargetKnownVulnerableVersions: null,
182
184
  recommendedParentUpgrade: undefined,
185
+ recommendedNpmTransitiveRemediation: undefined,
183
186
  };
184
187
  });
185
- if (!offline) {
186
- await validateDirectFixTargets(findings);
187
- }
188
- for (const finding of findings) {
189
- if (finding.relationship !== "transitive" || offline)
190
- continue;
188
+ const npmTransitiveGraph = !offline && context?.scanSource === "package-lock" && context.scanFilePath
189
+ ? createNpmTransitiveGraphFromLockfile(context.scanFilePath)
190
+ : null;
191
+ const npmRemediationCache = new Map();
192
+ const parentUpgradeCache = new Map();
193
+ const directValidationCount = offline ? 0 : findings.length;
194
+ const transitiveRemediationCount = offline
195
+ ? 0
196
+ : findings.filter(finding => finding.relationship === "transitive").length;
197
+ const analysisStepCount = directValidationCount + transitiveRemediationCount;
198
+ if (analysisStepCount > 0) {
199
+ const analysisSpinner = createSpinner("Analyzing vulnerability findings...", options);
200
+ let completedSteps = 0;
201
+ const updateAnalysisProgress = (phase, subject) => {
202
+ completedSteps += 1;
203
+ analysisSpinner.update(`Analyzing vulnerability findings ${completedSteps}/${analysisStepCount}: ${phase} ${subject}...`);
204
+ };
191
205
  try {
192
- finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade(finding, packages);
206
+ if (!offline) {
207
+ await validateDirectFixTargets(findings, (finding) => {
208
+ updateAnalysisProgress("validating fix target for", `${finding.pkg.name}@${finding.pkg.version}`);
209
+ });
210
+ }
211
+ for (const finding of findings) {
212
+ if (finding.relationship !== "transitive" || offline)
213
+ continue;
214
+ updateAnalysisProgress("resolving remediation for", `${finding.pkg.name}@${finding.pkg.version}`);
215
+ const remediationCacheKey = JSON.stringify({
216
+ package: finding.pkg.name,
217
+ version: finding.pkg.version,
218
+ dependencyPaths: finding.dependencyPaths,
219
+ firstFixedVersion: finding.firstFixedVersion,
220
+ validatedFirstFixedVersion: finding.validatedFirstFixedVersion ?? null,
221
+ });
222
+ try {
223
+ if (npmTransitiveGraph) {
224
+ if (npmRemediationCache.has(remediationCacheKey)) {
225
+ finding.recommendedNpmTransitiveRemediation =
226
+ npmRemediationCache.get(remediationCacheKey) ?? undefined;
227
+ }
228
+ else {
229
+ finding.recommendedNpmTransitiveRemediation = await resolveNpmTransitiveRemediation({
230
+ finding,
231
+ graph: npmTransitiveGraph,
232
+ packages,
233
+ directDependencyNames: context?.directDependencyNames,
234
+ });
235
+ npmRemediationCache.set(remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null);
236
+ }
237
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version") {
238
+ finding.recommendedParentUpgrade = {
239
+ package: finding.recommendedNpmTransitiveRemediation.package,
240
+ currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
241
+ targetVersion: finding.recommendedNpmTransitiveRemediation.targetVersion ?? "",
242
+ viaPath: finding.recommendedNpmTransitiveRemediation.viaPath,
243
+ vulnerablePackage: finding.pkg.name,
244
+ confidence: "exact-direct-child",
245
+ reason: finding.recommendedNpmTransitiveRemediation.reason,
246
+ };
247
+ continue;
248
+ }
249
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
250
+ finding.recommendedParentUpgrade = undefined;
251
+ continue;
252
+ }
253
+ }
254
+ if (parentUpgradeCache.has(remediationCacheKey)) {
255
+ finding.recommendedParentUpgrade = parentUpgradeCache.get(remediationCacheKey) ?? undefined;
256
+ }
257
+ else {
258
+ finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade(finding, packages, context?.directDependencyNames);
259
+ parentUpgradeCache.set(remediationCacheKey, finding.recommendedParentUpgrade ?? null);
260
+ }
261
+ }
262
+ catch {
263
+ finding.recommendedNpmTransitiveRemediation = undefined;
264
+ finding.recommendedParentUpgrade = undefined;
265
+ }
266
+ }
267
+ analysisSpinner.succeed("Analyzed vulnerability findings");
193
268
  }
194
- catch {
195
- finding.recommendedParentUpgrade = undefined;
269
+ catch (error) {
270
+ analysisSpinner.fail("Failed while analyzing vulnerability findings");
271
+ throw error;
196
272
  }
197
273
  }
274
+ else if (!offline) {
275
+ await validateDirectFixTargets(findings);
276
+ }
198
277
  return findings;
199
278
  }
200
279
  catch (error) {
@@ -205,9 +284,35 @@ export async function scanPackages(packages, batchSize, options, context) {
205
284
  sourceContext.cleanup();
206
285
  }
207
286
  }
208
- async function validateDirectFixTargets(findings) {
287
+ function createNpmTransitiveGraphFromLockfile(filePath) {
288
+ try {
289
+ const lockGraph = loadNpmLockGraph(filePath, { includePaths: false });
290
+ return {
291
+ nodeIdsFor(name, version) {
292
+ return lockGraph.nodeIdsFor(name, version);
293
+ },
294
+ getNode(nodeId) {
295
+ const node = lockGraph.getNode(nodeId);
296
+ return node
297
+ ? { id: node.id, name: node.name, version: node.version, packagePath: node.packagePath }
298
+ : null;
299
+ },
300
+ childrenFor(nodeId) {
301
+ return lockGraph.childrenFor(nodeId);
302
+ },
303
+ rangeFor(parentNodeId, childName) {
304
+ return lockGraph.rangeFor(parentNodeId, childName);
305
+ },
306
+ };
307
+ }
308
+ catch {
309
+ return null;
310
+ }
311
+ }
312
+ async function validateDirectFixTargets(findings, onFinding) {
209
313
  const directCandidates = findings.filter(finding => finding.vulnerabilities.length > 0);
210
314
  for (const finding of directCandidates) {
315
+ onFinding?.(finding);
211
316
  const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities);
212
317
  const fixedVersionHint = finding.firstFixedVersion;
213
318
  if (lowestKnownResolution.resolvedVersion) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "Developer-friendly CLI for scanning JS/TS projects for dependency vulnerabilities using local lockfiles and OSV",
5
5
  "type": "module",
6
6
  "bin": {