cve-lite-cli 1.18.0 → 1.18.2

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 (38) hide show
  1. package/README.md +15 -0
  2. package/dist/advisory/local-advisory-source.js +1 -1
  3. package/dist/advisory/osv-advisory-source.js +83 -13
  4. package/dist/advisory/osv-sync.js +3 -2
  5. package/dist/cli/args.js +52 -0
  6. package/dist/cli/config-command.js +40 -0
  7. package/dist/cli/config.js +66 -0
  8. package/dist/cli/help.js +7 -0
  9. package/dist/cli/validate.js +9 -0
  10. package/dist/index.js +112 -130
  11. package/dist/learn/keypress.js +50 -0
  12. package/dist/learn/runner.js +96 -0
  13. package/dist/learn/scenario.js +47 -0
  14. package/dist/learn/session.js +36 -0
  15. package/dist/learn/types.js +1 -0
  16. package/dist/osv/cache.js +46 -7
  17. package/dist/output/debug.js +38 -0
  18. package/dist/output/finding-display.js +30 -0
  19. package/dist/output/formatters.js +4 -3
  20. package/dist/output/html-reporter.js +3 -2
  21. package/dist/output/multi-folder-html-reporter.js +323 -0
  22. package/dist/output/multi-folder-printer.js +46 -0
  23. package/dist/output/printers.js +16 -15
  24. package/dist/output/sarif.js +3 -9
  25. package/dist/output/spinner.js +1 -1
  26. package/dist/parsers/multi-package.js +58 -0
  27. package/dist/parsers/pnpm-lock.js +4 -0
  28. package/dist/parsers/yarn-lock.js +60 -0
  29. package/dist/remediation/fix-commands.js +127 -6
  30. package/dist/remediation/npm-registry.js +44 -1
  31. package/dist/remediation/parent-upgrade.js +14 -8
  32. package/dist/scan/multi-folder-scan.js +97 -0
  33. package/dist/scanner.js +100 -21
  34. package/dist/utils/fix-runner.js +131 -0
  35. package/dist/utils/network.js +18 -4
  36. package/dist/utils/string.js +3 -0
  37. package/dist/utils/time.js +4 -3
  38. package/package.json +1 -1
@@ -3,6 +3,8 @@ import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
3
3
  import { isMajorVersionBump } from "../utils/version.js";
4
4
  import { getPrimaryParent } from "../utils/finding.js";
5
5
  import { countUniqueAdvisories, formatSeverityLabel, formatRelationshipLabel } from "./formatters.js";
6
+ import { pluralize } from "../utils/string.js";
7
+ import { selectFindingsForCompact } from "./finding-display.js";
6
8
  export function printSummary(findings, packageCount, scanInput) {
7
9
  if (findings.length === 0) {
8
10
  if (scanInput.mode === "manifest-fallback") {
@@ -36,13 +38,13 @@ export function printActionSummary(findings) {
36
38
  const fixable = findings.filter(f => Boolean(f.firstFixedVersion)).length;
37
39
  console.log("");
38
40
  console.log(chalk.bold.cyan("Quick take"));
39
- console.log(`- ${chalk.green(String(direct))} vulnerable package${direct === 1 ? "" : "s"} look directly fixable in this project.`);
40
- console.log(`- ${chalk.yellow(String(transitive))} issue${transitive === 1 ? "" : "s"} come through other dependencies.`);
41
+ console.log(`- ${chalk.green(String(direct))} vulnerable ${pluralize(direct, "package")} look directly fixable in this project.`);
42
+ console.log(`- ${chalk.yellow(String(transitive))} ${pluralize(transitive, "issue")} come through other dependencies.`);
41
43
  if (unknown > 0) {
42
- console.log(`- ${chalk.magenta(String(unknown))} package${unknown === 1 ? "" : "s"} could not be clearly classified as direct or transitive.`);
44
+ console.log(`- ${chalk.magenta(String(unknown))} ${pluralize(unknown, "package")} could not be clearly classified as direct or transitive.`);
43
45
  }
44
- console.log(`- ${chalk.blueBright(String(uniqueAdvisories))} CVE${uniqueAdvisories === 1 ? "" : "s"} matched overall.`);
45
- console.log(`- ${chalk.blue(String(fixable))} package${fixable === 1 ? "" : "s"} include a fixed-version hint from OSV.`);
46
+ console.log(`- ${chalk.blueBright(String(uniqueAdvisories))} ${pluralize(uniqueAdvisories, "CVE")} matched overall.`);
47
+ console.log(`- ${chalk.blue(String(fixable))} ${pluralize(fixable, "package")} include a fixed-version hint from OSV.`);
46
48
  }
47
49
  export function printSuggestedFixCommands(findings, scanInput, options) {
48
50
  const plan = buildSuggestedFixCommandPlan(findings, scanInput, options);
@@ -218,10 +220,10 @@ export function printFinalStatus(findings) {
218
220
  const criticalCount = findings.filter(f => f.severity === "critical").length;
219
221
  const highCount = findings.filter(f => f.severity === "high").length;
220
222
  if (criticalCount > 0 || highCount > 0) {
221
- console.log(chalk.redBright(`✖ Scan complete. ${findings.length} issue${findings.length === 1 ? "" : "s"} found (${criticalCount} critical, ${highCount} high). Start with the priority fixes above.`));
223
+ console.log(chalk.redBright(`✖ Scan complete. ${findings.length} ${pluralize(findings.length, "issue")} found (${criticalCount} critical, ${highCount} high). Start with the priority fixes above.`));
222
224
  return;
223
225
  }
224
- console.log(chalk.yellow(`▲ Scan complete. ${findings.length} issue${findings.length === 1 ? "" : "s"} found. Review the suggested fix plan above.`));
226
+ console.log(chalk.yellow(`▲ Scan complete. ${findings.length} ${pluralize(findings.length, "issue")} found. Review the suggested fix plan above.`));
225
227
  }
226
228
  function renderRow(cells, widths) {
227
229
  const formatted = cells.map((cell, i) => {
@@ -282,10 +284,9 @@ export function printCompactOutput(findings, scanInput, options) {
282
284
  console.log("────────────────────────────────");
283
285
  console.log(chalk.bold("📦 Vulnerabilities found"));
284
286
  console.log("────────────────────────────────\n");
285
- // Get top 3 critical/high issues plus all unknown (malicious) findings
286
- const urgentFindings = findings
287
- .filter(f => f.severity === "critical" || f.severity === "high" || f.severity === "unknown")
288
- .slice(0, 3);
287
+ // Reuse shared display selection logic so compact mode does not silently
288
+ // drop direct unknown-severity findings.
289
+ const urgentFindings = selectFindingsForCompact(findings, { urgentLimit: 3 });
289
290
  for (const finding of urgentFindings) {
290
291
  const sevLabel = finding.severity.toUpperCase().padEnd(8);
291
292
  const typeLabel = finding.relationship === "direct"
@@ -296,7 +297,7 @@ export function printCompactOutput(findings, scanInput, options) {
296
297
  let usageContext = "";
297
298
  if (finding.usage) {
298
299
  if (finding.usage.imported) {
299
- usageContext = chalk.red(` (imported in ${finding.usage.files.length} file${finding.usage.files.length === 1 ? "" : "s"})`);
300
+ usageContext = chalk.red(` (imported in ${finding.usage.files.length} ${pluralize(finding.usage.files.length, "file")})`);
300
301
  }
301
302
  else {
302
303
  usageContext = chalk.green(` (no direct import found)`);
@@ -356,7 +357,7 @@ export function printCompactOutput(findings, scanInput, options) {
356
357
  console.log(formatFixCommandSummary(plan));
357
358
  const compactValidationSummary = summarizeAdjustedValidation(plan.targets);
358
359
  if (compactValidationSummary.checked > 0) {
359
- console.log(chalk.gray(`Validation: scanned ${compactValidationSummary.checked} package version${compactValidationSummary.checked === 1 ? "" : "s"}; ${compactValidationSummary.vulnerable} ${compactValidationSummary.vulnerable === 1 ? "is" : "are"} still known vulnerable.`));
360
+ console.log(chalk.gray(`Validation: scanned ${compactValidationSummary.checked} package ${pluralize(compactValidationSummary.checked, "version")}; ${compactValidationSummary.vulnerable} ${pluralize(compactValidationSummary.vulnerable, "is", "are")} still known vulnerable.`));
360
361
  }
361
362
  console.log("");
362
363
  for (const section of plan.sections.slice(0, 3)) {
@@ -427,10 +428,10 @@ export function printCompactOutput(findings, scanInput, options) {
427
428
  // Footer
428
429
  const urgentCount = counts.critical + counts.high;
429
430
  if (urgentCount > 0) {
430
- console.log(chalk.redBright(`✖ Scan complete. ${urgentCount} urgent issue${urgentCount === 1 ? "" : "s"} found.`));
431
+ console.log(chalk.redBright(`✖ Scan complete. ${urgentCount} urgent ${pluralize(urgentCount, "issue")} found.`));
431
432
  }
432
433
  else {
433
- console.log(chalk.yellow(`▲ Scan complete. ${findings.length} issue${findings.length === 1 ? "" : "s"} found.`));
434
+ console.log(chalk.yellow(`▲ Scan complete. ${findings.length} ${pluralize(findings.length, "issue")} found.`));
434
435
  }
435
436
  if (!options?.all) {
436
437
  console.log(chalk.gray(`Run with ${chalk.whiteBright("--verbose")} for fix plan, paths, and full table.`));
@@ -1,6 +1,5 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
4
3
  import { getRecommendedAction } from "./formatters.js";
5
4
  import { getCliVersion } from "../utils/version-info.js";
6
5
  import { severityToSarifLevel } from "../utils/severity.js";
@@ -19,13 +18,12 @@ export function deriveLockfileUri(scanInput) {
19
18
  return path.basename(scanInput.filePath);
20
19
  return LOCKFILE_NAMES[scanInput.source] ?? "lockfile";
21
20
  }
22
- export function buildSarifOutput(findings, lockfileUri, version, plan) {
21
+ export function buildSarifOutput(findings, lockfileUri, version, _plan) {
23
22
  const ruleMap = new Map();
24
23
  const results = [];
25
24
  for (const finding of findings) {
26
25
  const level = severityToSarifLevel(finding.severity);
27
26
  const action = getRecommendedAction(finding);
28
- const runnableFixCommand = plan ? findSuggestedCommandForFinding(plan, finding) : null;
29
27
  const location = {
30
28
  physicalLocation: {
31
29
  artifactLocation: { uri: lockfileUri, uriBaseId: "%SRCROOT%" },
@@ -47,18 +45,14 @@ export function buildSarifOutput(findings, lockfileUri, version, plan) {
47
45
  properties: { tags: ["security", "dependency"] },
48
46
  });
49
47
  }
50
- const result = {
48
+ results.push({
51
49
  ruleId,
52
50
  level,
53
51
  message: {
54
52
  text: `${finding.pkg.name}@${finding.pkg.version} is vulnerable (${finding.severity}). ${action}`,
55
53
  },
56
54
  locations: [location],
57
- };
58
- if (runnableFixCommand) {
59
- result.fixes = [{ description: { text: runnableFixCommand }, artifactChanges: [] }];
60
- }
61
- results.push(result);
55
+ });
62
56
  }
63
57
  }
64
58
  return {
@@ -1,7 +1,7 @@
1
1
  import process from "node:process";
2
2
  import { chalk } from "../utils/chalk.js";
3
3
  export function createSpinner(initialMessage, options) {
4
- const enabled = Boolean(process.stdout.isTTY);
4
+ const enabled = Boolean(process.stdout.isTTY) && !options?.json;
5
5
  if (!enabled) {
6
6
  return {
7
7
  update: () => { },
@@ -0,0 +1,58 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { EXCLUDED_DIRS } from "../constants.js";
4
+ import { loadPackages } from "./index.js";
5
+ const LOCKFILE_NAMES = ["bun.lock", "npm-shrinkwrap.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"];
6
+ export function hasRootLockfile(projectRoot) {
7
+ return LOCKFILE_NAMES.some(name => fs.existsSync(path.join(projectRoot, name)));
8
+ }
9
+ export function findNestedLockfiles(projectRoot, maxDepth) {
10
+ const results = [];
11
+ function walk(dir, depth) {
12
+ if (depth > maxDepth)
13
+ return;
14
+ let entries = [];
15
+ try {
16
+ entries = fs.readdirSync(dir, { withFileTypes: true });
17
+ }
18
+ catch {
19
+ return;
20
+ }
21
+ const lockfile = entries.find(e => e.isFile() && LOCKFILE_NAMES.includes(e.name));
22
+ if (lockfile) {
23
+ results.push(path.join(dir, lockfile.name));
24
+ return; // stop recursing — this lockfile covers its subtree
25
+ }
26
+ for (const entry of entries) {
27
+ if (!entry.isDirectory())
28
+ continue;
29
+ if (EXCLUDED_DIRS.has(entry.name))
30
+ continue;
31
+ walk(path.join(dir, entry.name), depth + 1);
32
+ }
33
+ }
34
+ let rootEntries = [];
35
+ try {
36
+ rootEntries = fs.readdirSync(projectRoot, { withFileTypes: true });
37
+ }
38
+ catch {
39
+ return results;
40
+ }
41
+ for (const entry of rootEntries) {
42
+ if (!entry.isDirectory())
43
+ continue;
44
+ if (EXCLUDED_DIRS.has(entry.name))
45
+ continue;
46
+ walk(path.join(projectRoot, entry.name), 1);
47
+ }
48
+ return results;
49
+ }
50
+ export function loadMultiplePackages(projectRoot, prodOnly, maxDepth) {
51
+ const lockfiles = findNestedLockfiles(projectRoot, maxDepth);
52
+ return lockfiles.map(lockfilePath => {
53
+ const subfolderAbs = path.dirname(lockfilePath);
54
+ const subfolder = path.relative(projectRoot, subfolderAbs);
55
+ const scanInput = loadPackages(subfolderAbs, prodOnly, maxDepth);
56
+ return { scanInput, subfolder };
57
+ });
58
+ }
@@ -219,6 +219,10 @@ function normalizePnpmDepRefV9(depName, depRef) {
219
219
  return null;
220
220
  if (looksLikeVersion(cleaned))
221
221
  return `${depName}@${cleaned}`;
222
+ // Handle aliased deps where the ref is a full "pkgName@version" key (e.g. '@remix-run/dev': '@vercel/remix-run-dev@1.16.1')
223
+ const atIdx = cleaned.lastIndexOf("@");
224
+ if (atIdx > 0 && looksLikeVersion(cleaned.slice(atIdx + 1)))
225
+ return cleaned;
222
226
  }
223
227
  if (depRef && typeof depRef === "object") {
224
228
  const version = depRef.version ?? depRef.specifier;
@@ -1,6 +1,66 @@
1
1
  import fs from "node:fs";
2
+ import path from "node:path";
2
3
  import { parse as parseYarnLock } from "yarn-lockfile";
3
4
  import { upsertPackage } from "./utils.js";
5
+ export function buildYarnWorkspaceMap(filePath) {
6
+ const dir = path.dirname(filePath);
7
+ const map = new Map();
8
+ let rootPkg;
9
+ try {
10
+ rootPkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
11
+ }
12
+ catch {
13
+ return map;
14
+ }
15
+ const patterns = Array.isArray(rootPkg.workspaces)
16
+ ? rootPkg.workspaces
17
+ : rootPkg.workspaces?.packages ?? [];
18
+ if (!patterns.length)
19
+ return map;
20
+ for (const pattern of patterns) {
21
+ const parts = pattern.split("/");
22
+ const lastPart = parts[parts.length - 1];
23
+ const baseParts = parts.slice(0, -1);
24
+ let wsDirs;
25
+ if (lastPart === "*") {
26
+ const baseDir = path.join(dir, ...baseParts);
27
+ try {
28
+ wsDirs = fs.readdirSync(baseDir, { withFileTypes: true })
29
+ .filter(d => d.isDirectory())
30
+ .map(d => [...baseParts, d.name].join("/"));
31
+ }
32
+ catch {
33
+ continue;
34
+ }
35
+ }
36
+ else {
37
+ wsDirs = [pattern];
38
+ }
39
+ for (const wsDir of wsDirs) {
40
+ let wsPkg;
41
+ try {
42
+ wsPkg = JSON.parse(fs.readFileSync(path.join(dir, wsDir, "package.json"), "utf8"));
43
+ }
44
+ catch {
45
+ continue;
46
+ }
47
+ const wsName = wsPkg.name;
48
+ if (!wsName)
49
+ continue;
50
+ for (const depSection of ["dependencies", "optionalDependencies", "devDependencies"]) {
51
+ const deps = wsPkg[depSection];
52
+ if (!deps || typeof deps !== "object")
53
+ continue;
54
+ for (const depName of Object.keys(deps)) {
55
+ const existing = map.get(depName) ?? [];
56
+ if (!existing.includes(wsName))
57
+ map.set(depName, [...existing, wsName]);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ return map;
63
+ }
4
64
  function isYarnBerry(content) {
5
65
  return content.startsWith('__metadata:') || content.includes('\n__metadata:');
6
66
  }
@@ -2,11 +2,36 @@ import { severityOrder } from "../constants.js";
2
2
  import { compareVersions, looksLikeVersion } from "../utils/version.js";
3
3
  import { getPrimaryParent } from "../utils/finding.js";
4
4
  import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
5
+ import { pluralize } from "../utils/string.js";
6
+ import { buildNpmWorkspaceMap } from "../parsers/package-lock.js";
7
+ import { buildPnpmWorkspaceMap } from "../parsers/pnpm-lock.js";
8
+ import { buildYarnWorkspaceMap } from "../parsers/yarn-lock.js";
9
+ import { buildBunWorkspaceMap } from "../parsers/bun-lock.js";
5
10
  export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
6
11
  const packageManager = inferPackageManager(scanInput);
7
12
  if (!packageManager)
8
13
  return null;
9
14
  const offline = !!options?.offline;
15
+ let workspaceMap = new Map();
16
+ if (scanInput.filePath) {
17
+ try {
18
+ if (packageManager === "npm" && (scanInput.source === "package-lock" || scanInput.source === "npm-shrinkwrap")) {
19
+ workspaceMap = buildNpmWorkspaceMap(scanInput.filePath);
20
+ }
21
+ else if (packageManager === "pnpm" && scanInput.source === "pnpm-lock") {
22
+ workspaceMap = buildPnpmWorkspaceMap(scanInput.filePath);
23
+ }
24
+ else if (packageManager === "yarn" && scanInput.source === "yarn-lock") {
25
+ workspaceMap = buildYarnWorkspaceMap(scanInput.filePath);
26
+ }
27
+ else if (packageManager === "bun" && scanInput.source === "bun-lock") {
28
+ workspaceMap = buildBunWorkspaceMap(scanInput.filePath);
29
+ }
30
+ }
31
+ catch {
32
+ // workspace map is best-effort
33
+ }
34
+ }
10
35
  const prioritizedFindings = [...findings]
11
36
  .filter(f => f.severity === "critical" || f.severity === "high")
12
37
  .sort((a, b) => {
@@ -46,16 +71,30 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
46
71
  ];
47
72
  for (const finding of orderedFindings) {
48
73
  const urgent = finding.severity === "critical" || finding.severity === "high";
49
- if (finding.relationship === "direct" || finding.relationship === "unknown") {
74
+ if (finding.relationship === "direct") {
50
75
  const hasValidatedField = Object.prototype.hasOwnProperty.call(finding, "validatedFirstFixedVersion");
51
76
  const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
52
77
  // In offline mode validateDirectFixTargets never runs, so an unset
53
78
  // validatedFirstFixedVersion is "did not validate" rather than "validation
54
79
  // failed" — fall back to the advisory hint instead of dropping the target.
55
80
  const validatedFieldOk = offline || !hasValidatedField || finding.validatedFirstFixedVersion !== null;
81
+ const allVersionsVulnerable = finding.validatedTargetScannedVersions != null &&
82
+ finding.validatedTargetKnownVulnerableVersions != null &&
83
+ finding.validatedTargetScannedVersions > 0 &&
84
+ finding.validatedTargetKnownVulnerableVersions >= finding.validatedTargetScannedVersions;
85
+ if (directTarget && allVersionsVulnerable) {
86
+ skippedByKey.set(`direct:${finding.pkg.name}@${finding.pkg.version}`, {
87
+ package: finding.pkg.name,
88
+ version: finding.pkg.version,
89
+ relationship: finding.relationship,
90
+ reason: `No safe upgrade: all ${finding.validatedTargetScannedVersions} scanned ${pluralize(finding.validatedTargetScannedVersions ?? 0, "version")} are still known-vulnerable. This package may be unmaintained.`,
91
+ });
92
+ continue;
93
+ }
56
94
  if (directTarget &&
57
95
  isUpgradeTarget(finding.pkg.version, directTarget) &&
58
96
  validatedFieldOk) {
97
+ const pkgWorkspaces = workspaceMap.get(finding.pkg.name)?.filter(w => w !== ".") ?? [];
59
98
  upsertTarget(targetsByPackage, {
60
99
  package: finding.pkg.name,
61
100
  currentVersion: finding.pkg.version,
@@ -75,6 +114,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
75
114
  : null,
76
115
  reason: `Direct upgrade target for ${finding.pkg.name}@${finding.pkg.version}`,
77
116
  usage: finding.usage ?? null,
117
+ workspaces: pkgWorkspaces.length > 0 ? pkgWorkspaces : undefined,
78
118
  });
79
119
  }
80
120
  else if (finding.fixVersionValidationNote) {
@@ -105,6 +145,15 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
105
145
  }
106
146
  continue;
107
147
  }
148
+ if (finding.relationship === "unknown") {
149
+ skippedByKey.set(`unknown:${finding.pkg.name}@${finding.pkg.version}`, {
150
+ package: finding.pkg.name,
151
+ version: finding.pkg.version,
152
+ relationship: finding.relationship,
153
+ reason: `Dependency path for ${finding.pkg.name}@${finding.pkg.version} could not be resolved in the lockfile. Inspect your lockfile to identify which package pulls it in.`,
154
+ });
155
+ continue;
156
+ }
108
157
  if (packageManager === "npm" &&
109
158
  finding.relationship === "transitive" &&
110
159
  finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
@@ -310,8 +359,14 @@ export function findSuggestedCommandForFinding(plan, finding) {
310
359
  (item.package === finding.recommendedNpmTransitiveRemediation.package || item.package === finding.pkg.name));
311
360
  }
312
361
  if (finding.recommendedParentUpgrade) {
313
- return (item.package === finding.recommendedParentUpgrade.package &&
314
- item.targetVersion === finding.recommendedParentUpgrade.targetVersion);
362
+ if (item.package !== finding.recommendedParentUpgrade.package)
363
+ return false;
364
+ if (item.targetVersion === finding.recommendedParentUpgrade.targetVersion)
365
+ return true;
366
+ // A command targeting a higher version also satisfies a lower-version recommendation
367
+ return (looksLikeVersion(item.targetVersion) &&
368
+ looksLikeVersion(finding.recommendedParentUpgrade.targetVersion) &&
369
+ compareVersions(item.targetVersion, finding.recommendedParentUpgrade.targetVersion) >= 0);
315
370
  }
316
371
  const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
317
372
  return item.package === finding.pkg.name && item.targetVersion === directTarget;
@@ -320,6 +375,11 @@ export function findSuggestedCommandForFinding(plan, finding) {
320
375
  return null;
321
376
  if (target.command)
322
377
  return target.command;
378
+ if (target.workspaces?.length) {
379
+ const commands = buildWorkspaceInstallCommands([target], plan.packageManager);
380
+ if (commands.length > 0)
381
+ return commands.join(" && ");
382
+ }
323
383
  return `${commandPrefix(plan.packageManager)} ${target.package}@${target.targetVersion}`;
324
384
  }
325
385
  function packageManagerSourceLabel(scanInput) {
@@ -355,6 +415,7 @@ function upsertTarget(targetsByPackage, next) {
355
415
  : "parent-upgrade",
356
416
  displayTargetVersion: existing.displayTargetVersion ?? next.displayTargetVersion,
357
417
  command: existing.command ?? next.command,
418
+ workspaces: mergeStringArrays(existing.workspaces, next.workspaces),
358
419
  coverage: existing.coverage === "partial" || next.coverage === "partial"
359
420
  ? "partial"
360
421
  : existing.coverage ?? next.coverage,
@@ -366,7 +427,11 @@ function upsertTarget(targetsByPackage, next) {
366
427
  if (compareVersions(next.targetVersion, existing.targetVersion) > 0) {
367
428
  merged.targetVersion = next.targetVersion;
368
429
  merged.currentVersion = next.currentVersion ?? merged.currentVersion;
369
- merged.reason = next.reason;
430
+ // Keep the reason from the higher-severity finding so the most critical issue is visible
431
+ // in the context column. Only update the reason if next has strictly higher severity.
432
+ if (severityOrder[next.severity] > severityOrder[existing.severity]) {
433
+ merged.reason = next.reason;
434
+ }
370
435
  merged.scannedVersions = next.scannedVersions ?? merged.scannedVersions ?? null;
371
436
  merged.knownVulnerableVersions = next.knownVulnerableVersions ?? merged.knownVulnerableVersions ?? null;
372
437
  }
@@ -394,7 +459,13 @@ function buildParentUpgradeReason(finding, coverage) {
394
459
  if (coverage.coverage === "complete")
395
460
  return base;
396
461
  const remainingCount = coverage.remainingPaths.length;
397
- return `${base}; run this command, then rescan. ${remainingCount} other known path${remainingCount === 1 ? "" : "s"} may still need separate parent upgrades.`;
462
+ return `${base}; run this command, then rescan. ${remainingCount} other known ${pluralize(remainingCount, "path")} may still need separate parent upgrades.`;
463
+ }
464
+ function mergeStringArrays(a, b) {
465
+ if (!a?.length && !b?.length)
466
+ return undefined;
467
+ const result = [...new Set([...(a ?? []), ...(b ?? [])])];
468
+ return result.length > 0 ? result : undefined;
398
469
  }
399
470
  function mergePathArrays(left, right) {
400
471
  const seen = new Set();
@@ -476,6 +547,50 @@ function buildSectionTitle(kind, severity) {
476
547
  }
477
548
  return `${severityTitle} parent upgrades`;
478
549
  }
550
+ function groupByWorkspaceKey(targets) {
551
+ const groups = new Map();
552
+ for (const target of targets) {
553
+ const key = (target.workspaces ?? []).slice().sort().join("\0");
554
+ const group = groups.get(key) ?? [];
555
+ group.push(target);
556
+ groups.set(key, group);
557
+ }
558
+ return groups;
559
+ }
560
+ function buildWorkspaceInstallCommands(targets, packageManager) {
561
+ const groups = groupByWorkspaceKey(targets);
562
+ const commands = [];
563
+ for (const [wsKey, groupTargets] of groups) {
564
+ const pkgArgs = groupTargets.map(t => `${t.package}@${t.targetVersion}`).join(" ");
565
+ const workspaces = wsKey ? wsKey.split("\0") : [];
566
+ if (packageManager === "npm") {
567
+ const wsFlags = workspaces.map(ws => `-w ${ws}`).join(" ");
568
+ commands.push(`npm install${wsFlags ? " " + wsFlags : ""} ${pkgArgs}`);
569
+ }
570
+ else if (packageManager === "pnpm") {
571
+ const wsFlags = workspaces.map(ws => `--filter ./${ws}`).join(" ");
572
+ commands.push(`pnpm add${wsFlags ? " " + wsFlags : ""} ${pkgArgs}`);
573
+ }
574
+ else if (packageManager === "yarn") {
575
+ if (workspaces.length === 0) {
576
+ commands.push(`yarn add ${pkgArgs}`);
577
+ }
578
+ else {
579
+ for (const ws of workspaces) {
580
+ commands.push(`yarn workspace ${ws} add ${pkgArgs}`);
581
+ }
582
+ }
583
+ }
584
+ else if (packageManager === "bun") {
585
+ const wsFlags = workspaces.map(ws => `--filter ${ws}`).join(" ");
586
+ commands.push(`bun add${wsFlags ? " " + wsFlags : ""} ${pkgArgs}`);
587
+ }
588
+ else {
589
+ commands.push(`${commandPrefix(packageManager)} ${pkgArgs}`);
590
+ }
591
+ }
592
+ return commands;
593
+ }
479
594
  function buildCommandForTargets(targets, packageManager) {
480
595
  const explicitCommands = targets
481
596
  .map(target => target.command)
@@ -492,7 +607,13 @@ function buildCommandForTargets(targets, packageManager) {
492
607
  commandParts.push(...updateCommands);
493
608
  }
494
609
  if (installTargets.length > 0) {
495
- commandParts.push(`${commandPrefix(packageManager)} ${installTargets.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`);
610
+ const hasWorkspaces = installTargets.some(t => t.workspaces?.length);
611
+ if (hasWorkspaces) {
612
+ commandParts.push(...buildWorkspaceInstallCommands(installTargets, packageManager));
613
+ }
614
+ else {
615
+ commandParts.push(`${commandPrefix(packageManager)} ${installTargets.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`);
616
+ }
496
617
  }
497
618
  return commandParts.join(" && ");
498
619
  }
@@ -1,6 +1,16 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
2
  const packumentCache = new Map();
3
3
  const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
4
+ let registryDebugLog;
5
+ let registryBatchCounter = 0;
6
+ export function configureNpmRegistryDebug(debugLog) {
7
+ registryDebugLog = debugLog;
8
+ registryBatchCounter = 0;
9
+ }
10
+ function nextRegistryBatchId() {
11
+ registryBatchCounter += 1;
12
+ return `r-${String(registryBatchCounter).padStart(2, "0")}`;
13
+ }
4
14
  export function clearPackumentCache() {
5
15
  packumentCache.clear();
6
16
  }
@@ -11,17 +21,50 @@ export async function fetchPackument(packageName) {
11
21
  const url = `${DEFAULT_NPM_REGISTRY_URL}/${encodeURIComponent(packageName)
12
22
  .replace(/%40/g, "@")
13
23
  .replace(/%2F/g, "/")}`;
24
+ const batchId = registryDebugLog ? nextRegistryBatchId() : "";
25
+ const startedAt = registryDebugLog ? Date.now() : 0;
26
+ if (registryDebugLog) {
27
+ registryDebugLog("Registry fetch", { batchId, package: packageName, url });
28
+ }
14
29
  try {
15
30
  const response = await fetch(url);
16
31
  if (!response.ok) {
32
+ if (registryDebugLog) {
33
+ registryDebugLog("Registry response", {
34
+ batchId,
35
+ package: packageName,
36
+ status: response.status,
37
+ durationMs: Date.now() - startedAt,
38
+ versionsCount: 0,
39
+ });
40
+ }
17
41
  packumentCache.set(packageName, null);
18
42
  return null;
19
43
  }
20
44
  const json = (await response.json());
45
+ if (registryDebugLog) {
46
+ registryDebugLog("Registry response", {
47
+ batchId,
48
+ package: packageName,
49
+ status: response.status,
50
+ durationMs: Date.now() - startedAt,
51
+ versionsCount: Object.keys(json.versions ?? {}).length,
52
+ });
53
+ }
21
54
  packumentCache.set(packageName, json);
22
55
  return json;
23
56
  }
24
- catch {
57
+ catch (error) {
58
+ if (registryDebugLog) {
59
+ registryDebugLog("Registry fetch failed", {
60
+ batchId,
61
+ package: packageName,
62
+ durationMs: Date.now() - startedAt,
63
+ error: error instanceof Error
64
+ ? { message: error.message, stack: error.stack }
65
+ : String(error),
66
+ });
67
+ }
25
68
  packumentCache.set(packageName, null);
26
69
  return null;
27
70
  }
@@ -28,11 +28,17 @@ export async function resolveRecommendedParentUpgrade(finding, packages, directD
28
28
  });
29
29
  }
30
30
  // Best-effort fallback for deeper chains.
31
+ // Use the immediate child of the direct parent (not the immediate parent of the vulnerable
32
+ // package) — that's what the direct parent actually lists in its own dependencies.
33
+ const directParentIdx = viaPath.indexOf(directParentName);
34
+ if (directParentIdx < 0)
35
+ return null;
36
+ const immediateChildName = viaPath[directParentIdx + 1] ?? immediateParentName;
31
37
  return findUpgradeForImmediateIntermediate({
32
38
  directParentName,
33
39
  directParentVersion: directParent.version,
34
- immediateParentName,
35
- immediateParentInstalledVersion: findPackageVersion(packages, immediateParentName, viaPath.slice(0, -1)) ?? "",
40
+ immediateChildName,
41
+ immediateChildInstalledVersion: findPackageVersion(packages, immediateChildName, viaPath.slice(0, directParentIdx + 2)) ?? "",
36
42
  vulnerableName,
37
43
  viaPath,
38
44
  });
@@ -123,7 +129,7 @@ async function findUpgradeForExactDirectChild(args) {
123
129
  return null;
124
130
  }
125
131
  async function findUpgradeForImmediateIntermediate(args) {
126
- if (!args.immediateParentInstalledVersion || !looksLikeVersion(args.immediateParentInstalledVersion)) {
132
+ if (!args.immediateChildInstalledVersion || !looksLikeVersion(args.immediateChildInstalledVersion)) {
127
133
  return null;
128
134
  }
129
135
  const packument = await fetchPackument(args.directParentName);
@@ -134,12 +140,12 @@ async function findUpgradeForImmediateIntermediate(args) {
134
140
  .sort(compareVersions);
135
141
  for (const version of versions) {
136
142
  const manifest = packument?.versions?.[version];
137
- const depRange = manifest?.dependencies?.[args.immediateParentName] ??
138
- manifest?.optionalDependencies?.[args.immediateParentName];
143
+ const depRange = manifest?.dependencies?.[args.immediateChildName] ??
144
+ manifest?.optionalDependencies?.[args.immediateChildName];
139
145
  if (!depRange)
140
146
  continue;
141
- const stillAllowsImmediateParentInstalled = versionSatisfiesRange(args.immediateParentInstalledVersion, depRange);
142
- if (!stillAllowsImmediateParentInstalled) {
147
+ const stillAllowsInstalledChild = versionSatisfiesRange(args.immediateChildInstalledVersion, depRange);
148
+ if (!stillAllowsInstalledChild) {
143
149
  return {
144
150
  package: args.directParentName,
145
151
  currentVersion: args.directParentVersion,
@@ -147,7 +153,7 @@ async function findUpgradeForImmediateIntermediate(args) {
147
153
  viaPath: args.viaPath,
148
154
  vulnerablePackage: args.vulnerableName,
149
155
  confidence: "best-effort",
150
- reason: `${args.directParentName}@${version} no longer allows ${args.immediateParentName}@${args.immediateParentInstalledVersion} in the current path`,
156
+ reason: `${args.directParentName}@${version} no longer allows ${args.immediateChildName}@${args.immediateChildInstalledVersion} in the current path`,
151
157
  };
152
158
  }
153
159
  }