cve-lite-cli 1.17.3 → 1.18.1

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.
@@ -4,6 +4,25 @@ function parseJsonc(text) {
4
4
  // bun.lock uses JSONC (trailing commas). Strip them before parsing.
5
5
  return JSON.parse(text.replace(/,(\s*[}\]])/g, "$1"));
6
6
  }
7
+ export function buildBunWorkspaceMap(filePath) {
8
+ const raw = parseJsonc(fs.readFileSync(filePath, "utf8"));
9
+ const workspaces = raw?.workspaces ?? {};
10
+ const map = new Map();
11
+ for (const [workspacePath, workspace] of Object.entries(workspaces)) {
12
+ for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
13
+ const depSection = workspace?.[depSectionName];
14
+ if (!depSection || typeof depSection !== "object")
15
+ continue;
16
+ for (const depName of Object.keys(depSection)) {
17
+ const existing = map.get(depName) ?? [];
18
+ if (!existing.includes(workspacePath)) {
19
+ map.set(depName, [...existing, workspacePath]);
20
+ }
21
+ }
22
+ }
23
+ }
24
+ return map;
25
+ }
7
26
  export function loadFromBunLock(filePath, prodOnly) {
8
27
  const raw = parseJsonc(fs.readFileSync(filePath, "utf8"));
9
28
  const packages = raw?.packages ?? {};
@@ -1,6 +1,29 @@
1
1
  import fs from "node:fs";
2
2
  import { upsertPackage, normalizeNodeModulesPath } from "./utils.js";
3
3
  import { loadNpmLockGraph } from "./npm-lock-graph.js";
4
+ export function buildNpmWorkspaceMap(filePath) {
5
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
6
+ const map = new Map();
7
+ if (!raw.packages || typeof raw.packages !== "object")
8
+ return map;
9
+ for (const [pkgPath, meta] of Object.entries(raw.packages)) {
10
+ if (pkgPath.includes("node_modules/"))
11
+ continue;
12
+ const workspacePath = pkgPath === "" ? "." : pkgPath;
13
+ for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
14
+ const depSection = meta?.[depSectionName];
15
+ if (!depSection || typeof depSection !== "object")
16
+ continue;
17
+ for (const depName of Object.keys(depSection)) {
18
+ const existing = map.get(depName) ?? [];
19
+ if (!existing.includes(workspacePath)) {
20
+ map.set(depName, [...existing, workspacePath]);
21
+ }
22
+ }
23
+ }
24
+ }
25
+ return map;
26
+ }
4
27
  export function loadFromPackageLock(filePath, prodOnly) {
5
28
  const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
6
29
  const map = new Map();
@@ -5,6 +5,26 @@ import { upsertPackage } from "./utils.js";
5
5
  import { uniquePathArrays } from "../utils/array.js";
6
6
  const MAX_PATHS_PER_PACKAGE = 5;
7
7
  const MAX_PATH_DEPTH = 10;
8
+ export function buildPnpmWorkspaceMap(filePath) {
9
+ const content = fs.readFileSync(filePath, "utf8");
10
+ const parsed = YAML.parse(content);
11
+ const importers = parsed?.importers ?? {};
12
+ const map = new Map();
13
+ for (const [importerPath, importer] of Object.entries(importers)) {
14
+ for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
15
+ const depSection = importer?.[depSectionName];
16
+ if (!depSection || typeof depSection !== "object")
17
+ continue;
18
+ for (const depName of Object.keys(depSection)) {
19
+ const existing = map.get(depName) ?? [];
20
+ if (!existing.includes(importerPath)) {
21
+ map.set(depName, [...existing, importerPath]);
22
+ }
23
+ }
24
+ }
25
+ }
26
+ return map;
27
+ }
8
28
  export function loadFromPnpmLock(filePath, prodOnly) {
9
29
  const content = fs.readFileSync(filePath, "utf8");
10
30
  const parsed = YAML.parse(content);
@@ -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) => {
@@ -56,6 +81,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
56
81
  if (directTarget &&
57
82
  isUpgradeTarget(finding.pkg.version, directTarget) &&
58
83
  validatedFieldOk) {
84
+ const pkgWorkspaces = workspaceMap.get(finding.pkg.name)?.filter(w => w !== ".") ?? [];
59
85
  upsertTarget(targetsByPackage, {
60
86
  package: finding.pkg.name,
61
87
  currentVersion: finding.pkg.version,
@@ -75,6 +101,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
75
101
  : null,
76
102
  reason: `Direct upgrade target for ${finding.pkg.name}@${finding.pkg.version}`,
77
103
  usage: finding.usage ?? null,
104
+ workspaces: pkgWorkspaces.length > 0 ? pkgWorkspaces : undefined,
78
105
  });
79
106
  }
80
107
  else if (finding.fixVersionValidationNote) {
@@ -112,7 +139,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
112
139
  package: finding.recommendedNpmTransitiveRemediation.package,
113
140
  currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
114
141
  targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
115
- displayTargetVersion: "within current range",
142
+ displayTargetVersion: "lockfile refresh",
116
143
  scannedVersions: null,
117
144
  knownVulnerableVersions: null,
118
145
  kind: "parent-update",
@@ -120,8 +147,8 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
120
147
  severity: finding.severity,
121
148
  adjusted: false,
122
149
  adjustmentNote: null,
123
- reason: `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range to pick up ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion}.`,
124
- command: `npm update ${finding.recommendedNpmTransitiveRemediation.package}`,
150
+ reason: `${finding.recommendedNpmTransitiveRemediation.package}@${finding.recommendedNpmTransitiveRemediation.currentVersion} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} — refreshing the lockfile is enough.`,
151
+ command: buildNpmUpdateCommand(finding.recommendedNpmTransitiveRemediation.package, finding.recommendedNpmTransitiveRemediation.workspaces),
125
152
  usage: finding.usage ?? null,
126
153
  });
127
154
  continue;
@@ -186,12 +213,26 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
186
213
  if (packageManager !== "npm" &&
187
214
  finding.relationship === "transitive" &&
188
215
  finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
189
- const primaryParent = getPrimaryParent(finding);
190
- skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
216
+ const lockfileRefreshCommand = packageManager === "pnpm"
217
+ ? buildPnpmLockfileRefreshCommand(finding.pkg.name, finding.recommendedNpmTransitiveRemediation.workspaces)
218
+ : packageManager === "yarn"
219
+ ? `yarn upgrade ${finding.pkg.name}`
220
+ : `bun update ${finding.pkg.name}`;
221
+ upsertTarget(targetsByPackage, {
191
222
  package: finding.pkg.name,
192
- version: finding.pkg.version,
193
- relationship: finding.relationship,
194
- 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.`,
223
+ currentVersion: finding.pkg.version,
224
+ targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
225
+ displayTargetVersion: "lockfile refresh",
226
+ scannedVersions: null,
227
+ knownVulnerableVersions: null,
228
+ kind: "parent-update",
229
+ urgent,
230
+ severity: finding.severity,
231
+ adjusted: false,
232
+ adjustmentNote: null,
233
+ reason: `${finding.pkg.name}@${finding.pkg.version} can be refreshed to ${finding.recommendedNpmTransitiveRemediation.targetChildVersion}+ — no parent upgrade needed.`,
234
+ command: lockfileRefreshCommand,
235
+ usage: finding.usage ?? null,
195
236
  });
196
237
  continue;
197
238
  }
@@ -235,14 +276,18 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
235
276
  const command = targets.length > 0
236
277
  ? buildCommandForTargets(targets, packageManager)
237
278
  : null;
238
- return {
279
+ const plan = {
239
280
  packageManager,
240
281
  sourceLabel: packageManagerSourceLabel(scanInput),
241
282
  command,
242
283
  sections,
243
284
  targets,
244
285
  skipped,
286
+ coveredFindingCount: 0,
287
+ totalFindingCount: findings.length,
245
288
  };
289
+ plan.coveredFindingCount = findings.filter(f => findSuggestedCommandForFinding(plan, f) !== null).length;
290
+ return plan;
246
291
  }
247
292
  function inferPackageManager(scanInput) {
248
293
  if (scanInput.source === "package-lock")
@@ -255,6 +300,26 @@ function inferPackageManager(scanInput) {
255
300
  return "bun";
256
301
  return null;
257
302
  }
303
+ function buildNpmUpdateCommand(pkg, workspaces) {
304
+ const nonRoot = (workspaces ?? []).filter(w => w !== ".");
305
+ if (nonRoot.length === 1) {
306
+ return `npm update --workspace=${nonRoot[0]} ${pkg}`;
307
+ }
308
+ if (nonRoot.length > 1) {
309
+ return `npm update --workspaces ${pkg}`;
310
+ }
311
+ return `npm update ${pkg}`;
312
+ }
313
+ function buildPnpmLockfileRefreshCommand(pkg, workspaces) {
314
+ if (!workspaces || workspaces.length === 0 || workspaces.length > 1) {
315
+ return `pnpm update --recursive --no-save ${pkg}`;
316
+ }
317
+ const workspace = workspaces[0];
318
+ if (workspace === ".") {
319
+ return `pnpm update --no-save ${pkg}`;
320
+ }
321
+ return `pnpm -C ${workspace} update --no-save ${pkg}`;
322
+ }
258
323
  function commandPrefix(packageManager) {
259
324
  if (packageManager === "npm")
260
325
  return "npm install";
@@ -268,8 +333,8 @@ export function findSuggestedCommandForFinding(plan, finding) {
268
333
  const target = plan.targets.find(item => {
269
334
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
270
335
  return (item.kind === "parent-update" &&
271
- item.package === finding.recommendedNpmTransitiveRemediation.package &&
272
- item.targetVersion === finding.recommendedNpmTransitiveRemediation.targetChildVersion);
336
+ item.targetVersion === finding.recommendedNpmTransitiveRemediation.targetChildVersion &&
337
+ (item.package === finding.recommendedNpmTransitiveRemediation.package || item.package === finding.pkg.name));
273
338
  }
274
339
  if (finding.recommendedParentUpgrade) {
275
340
  return (item.package === finding.recommendedParentUpgrade.package &&
@@ -282,6 +347,11 @@ export function findSuggestedCommandForFinding(plan, finding) {
282
347
  return null;
283
348
  if (target.command)
284
349
  return target.command;
350
+ if (target.workspaces?.length) {
351
+ const commands = buildWorkspaceInstallCommands([target], plan.packageManager);
352
+ if (commands.length > 0)
353
+ return commands.join(" && ");
354
+ }
285
355
  return `${commandPrefix(plan.packageManager)} ${target.package}@${target.targetVersion}`;
286
356
  }
287
357
  function packageManagerSourceLabel(scanInput) {
@@ -317,6 +387,7 @@ function upsertTarget(targetsByPackage, next) {
317
387
  : "parent-upgrade",
318
388
  displayTargetVersion: existing.displayTargetVersion ?? next.displayTargetVersion,
319
389
  command: existing.command ?? next.command,
390
+ workspaces: mergeStringArrays(existing.workspaces, next.workspaces),
320
391
  coverage: existing.coverage === "partial" || next.coverage === "partial"
321
392
  ? "partial"
322
393
  : existing.coverage ?? next.coverage,
@@ -356,7 +427,13 @@ function buildParentUpgradeReason(finding, coverage) {
356
427
  if (coverage.coverage === "complete")
357
428
  return base;
358
429
  const remainingCount = coverage.remainingPaths.length;
359
- return `${base}; run this command, then rescan. ${remainingCount} other known path${remainingCount === 1 ? "" : "s"} may still need separate parent upgrades.`;
430
+ return `${base}; run this command, then rescan. ${remainingCount} other known ${pluralize(remainingCount, "path")} may still need separate parent upgrades.`;
431
+ }
432
+ function mergeStringArrays(a, b) {
433
+ if (!a?.length && !b?.length)
434
+ return undefined;
435
+ const result = [...new Set([...(a ?? []), ...(b ?? [])])];
436
+ return result.length > 0 ? result : undefined;
360
437
  }
361
438
  function mergePathArrays(left, right) {
362
439
  const seen = new Set();
@@ -382,7 +459,9 @@ function buildSections(targets, packageManager) {
382
459
  const groups = [];
383
460
  const sectionOrder = [
384
461
  { kind: "urgent", severity: "critical" },
462
+ { kind: "parent-update", severity: "critical" },
385
463
  { kind: "urgent", severity: "high" },
464
+ { kind: "parent-update", severity: "high" },
386
465
  { kind: "direct", severity: "medium" },
387
466
  { kind: "direct", severity: "low" },
388
467
  { kind: "direct", severity: "unknown" },
@@ -398,7 +477,9 @@ function buildSections(targets, packageManager) {
398
477
  ];
399
478
  for (const entry of sectionOrder) {
400
479
  const sectionTargets = targets.filter(target => {
401
- const targetKind = target.urgent ? "urgent" : target.adjusted ? "direct-adjusted" : target.kind;
480
+ const targetKind = target.kind === "parent-update"
481
+ ? "parent-update"
482
+ : target.urgent ? "urgent" : target.adjusted ? "direct-adjusted" : target.kind;
402
483
  return targetKind === entry.kind && target.severity === entry.severity;
403
484
  });
404
485
  if (sectionTargets.length === 0)
@@ -434,6 +515,50 @@ function buildSectionTitle(kind, severity) {
434
515
  }
435
516
  return `${severityTitle} parent upgrades`;
436
517
  }
518
+ function groupByWorkspaceKey(targets) {
519
+ const groups = new Map();
520
+ for (const target of targets) {
521
+ const key = (target.workspaces ?? []).slice().sort().join("\0");
522
+ const group = groups.get(key) ?? [];
523
+ group.push(target);
524
+ groups.set(key, group);
525
+ }
526
+ return groups;
527
+ }
528
+ function buildWorkspaceInstallCommands(targets, packageManager) {
529
+ const groups = groupByWorkspaceKey(targets);
530
+ const commands = [];
531
+ for (const [wsKey, groupTargets] of groups) {
532
+ const pkgArgs = groupTargets.map(t => `${t.package}@${t.targetVersion}`).join(" ");
533
+ const workspaces = wsKey ? wsKey.split("\0") : [];
534
+ if (packageManager === "npm") {
535
+ const wsFlags = workspaces.map(ws => `-w ${ws}`).join(" ");
536
+ commands.push(`npm install${wsFlags ? " " + wsFlags : ""} ${pkgArgs}`);
537
+ }
538
+ else if (packageManager === "pnpm") {
539
+ const wsFlags = workspaces.map(ws => `--filter ./${ws}`).join(" ");
540
+ commands.push(`pnpm add${wsFlags ? " " + wsFlags : ""} ${pkgArgs}`);
541
+ }
542
+ else if (packageManager === "yarn") {
543
+ if (workspaces.length === 0) {
544
+ commands.push(`yarn add ${pkgArgs}`);
545
+ }
546
+ else {
547
+ for (const ws of workspaces) {
548
+ commands.push(`yarn workspace ${ws} add ${pkgArgs}`);
549
+ }
550
+ }
551
+ }
552
+ else if (packageManager === "bun") {
553
+ const wsFlags = workspaces.map(ws => `--filter ${ws}`).join(" ");
554
+ commands.push(`bun add${wsFlags ? " " + wsFlags : ""} ${pkgArgs}`);
555
+ }
556
+ else {
557
+ commands.push(`${commandPrefix(packageManager)} ${pkgArgs}`);
558
+ }
559
+ }
560
+ return commands;
561
+ }
437
562
  function buildCommandForTargets(targets, packageManager) {
438
563
  const explicitCommands = targets
439
564
  .map(target => target.command)
@@ -450,7 +575,13 @@ function buildCommandForTargets(targets, packageManager) {
450
575
  commandParts.push(...updateCommands);
451
576
  }
452
577
  if (installTargets.length > 0) {
453
- commandParts.push(`${commandPrefix(packageManager)} ${installTargets.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`);
578
+ const hasWorkspaces = installTargets.some(t => t.workspaces?.length);
579
+ if (hasWorkspaces) {
580
+ commandParts.push(...buildWorkspaceInstallCommands(installTargets, packageManager));
581
+ }
582
+ else {
583
+ commandParts.push(`${commandPrefix(packageManager)} ${installTargets.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`);
584
+ }
454
585
  }
455
586
  return commandParts.join(" && ");
456
587
  }
@@ -1,6 +1,48 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
3
  import { findSafeVersionWithinParentRange } from "./npm-transitive-graph.js";
4
+ export async function resolveTransitiveRemediationViaRegistry(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
+ if (directParentName !== immediateParentName)
15
+ return null;
16
+ if (!looksLikeVersion(directParent.version))
17
+ return null;
18
+ const vulnerableName = args.finding.pkg.name;
19
+ const fixHint = args.finding.validatedFirstFixedVersion ?? args.finding.firstFixedVersion;
20
+ const safeCandidates = await findSafeChildCandidates(vulnerableName, args.finding.pkg.version, fixHint);
21
+ if (safeCandidates.length === 0)
22
+ return null;
23
+ const packument = await fetchPackument(directParentName);
24
+ const parentManifest = packument?.versions?.[directParent.version];
25
+ const depRange = parentManifest?.dependencies?.[vulnerableName] ??
26
+ parentManifest?.optionalDependencies?.[vulnerableName];
27
+ if (!depRange)
28
+ return null;
29
+ const inRangeTarget = [...safeCandidates]
30
+ .sort(compareVersions)
31
+ .filter(v => versionSatisfiesRange(v, depRange))
32
+ .at(-1);
33
+ if (!inRangeTarget)
34
+ return null;
35
+ const workspaces = collectWorkspacesFromAllPaths(args.finding.dependencyPaths ?? [], args.workspaceMap);
36
+ return {
37
+ kind: "update-parent-within-range",
38
+ package: directParentName,
39
+ currentVersion: directParent.version,
40
+ targetChildVersion: inRangeTarget,
41
+ viaPath,
42
+ reason: `${directParentName}@${directParent.version} already allows ${vulnerableName}@${inRangeTarget} within the current dependency range`,
43
+ workspaces,
44
+ };
45
+ }
4
46
  export async function resolveNpmTransitiveRemediation(args) {
5
47
  if (args.finding.relationship !== "transitive")
6
48
  return null;
@@ -38,6 +80,7 @@ export async function resolveNpmTransitiveRemediation(args) {
38
80
  candidates: safeCandidates,
39
81
  });
40
82
  if (inRangeTarget) {
83
+ const workspaces = collectWorkspacesFromAllPaths(args.finding.dependencyPaths ?? [], args.workspaceMap);
41
84
  return {
42
85
  kind: "update-parent-within-range",
43
86
  package: directParentName,
@@ -45,6 +88,7 @@ export async function resolveNpmTransitiveRemediation(args) {
45
88
  targetChildVersion: inRangeTarget,
46
89
  viaPath,
47
90
  reason: `${directParentName}@${directParent.version} already allows ${vulnerableName}@${inRangeTarget} within the current dependency range`,
91
+ workspaces,
48
92
  };
49
93
  }
50
94
  // The upgrade-parent-to-version path needs the parent's published manifests
@@ -236,3 +280,22 @@ function parseCoreVersion(version) {
236
280
  const [major = "0", minor = "0", patch = "0"] = version.split(/[+-]/)[0].split(".");
237
281
  return [Number(major), Number(minor), Number(patch)];
238
282
  }
283
+ function collectWorkspacesFromAllPaths(dependencyPaths, workspaceMap) {
284
+ if (!workspaceMap)
285
+ return undefined;
286
+ const workspaceSet = new Set();
287
+ for (const path of dependencyPaths) {
288
+ if (path.length !== 3)
289
+ continue;
290
+ const parentName = path[1];
291
+ if (!parentName)
292
+ continue;
293
+ const wsForParent = workspaceMap.get(parentName);
294
+ if (wsForParent) {
295
+ for (const ws of wsForParent) {
296
+ workspaceSet.add(ws);
297
+ }
298
+ }
299
+ }
300
+ return workspaceSet.size > 0 ? [...workspaceSet] : undefined;
301
+ }
package/dist/scanner.js CHANGED
@@ -9,8 +9,12 @@ 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";
12
+ import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry } from "./remediation/npm-transitive-resolution.js";
13
13
  import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js";
14
+ import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
15
+ import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
16
+ import { buildBunWorkspaceMap } from "./parsers/bun-lock.js";
17
+ import { pluralize } from "./utils/string.js";
14
18
  export function createAdvisorySource(options) {
15
19
  const offline = !!options?.offline || !!options?.offlineDb;
16
20
  if (offline) {
@@ -71,7 +75,7 @@ export async function scanPackages(packages, batchSize, options, context) {
71
75
  uncachedPackages.push(pkg);
72
76
  }
73
77
  const chunks = chunk(uncachedPackages, batchSize);
74
- spinner.update(`Scanning OSV in ${chunks.length} parallel batch${chunks.length === 1 ? "" : "es"}...`);
78
+ spinner.update(`Scanning OSV in ${chunks.length} parallel ${pluralize(chunks.length, "batch", "batches")}...`);
75
79
  const allAdvisoryResults = await runWithConcurrency(chunks, 5, c => advisorySource.queryBatch(c));
76
80
  for (let i = 0; i < chunks.length; i++) {
77
81
  const chunkItems = chunks[i];
@@ -90,7 +94,7 @@ export async function scanPackages(packages, batchSize, options, context) {
90
94
  spinner.succeed("Loaded package matches from cache");
91
95
  }
92
96
  else {
93
- spinner.succeed(`Queried OSV in ${chunks.length} batch${chunks.length === 1 ? "" : "es"}`);
97
+ spinner.succeed(`Queried OSV in ${chunks.length} ${pluralize(chunks.length, "batch", "batches")}`);
94
98
  }
95
99
  }
96
100
  else {
@@ -131,7 +135,7 @@ export async function scanPackages(packages, batchSize, options, context) {
131
135
  cache.entries[id] = null;
132
136
  }
133
137
  }
134
- detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail record${ids.length === 1 ? "" : "s"}`);
138
+ detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail ${pluralize(ids.length, "record")}`);
135
139
  }
136
140
  catch (error) {
137
141
  detailSpinner.fail("Failed while fetching vulnerability details");
@@ -153,7 +157,7 @@ export async function scanPackages(packages, batchSize, options, context) {
153
157
  // ignore missing local records so scans remain resilient to partial DB state
154
158
  }
155
159
  }
156
- detailSpinner.succeed(`Loaded ${ids.length} local advisory detail record${ids.length === 1 ? "" : "s"}`);
160
+ detailSpinner.succeed(`Loaded ${ids.length} local advisory detail ${pluralize(ids.length, "record")}`);
157
161
  }
158
162
  catch (error) {
159
163
  detailSpinner.fail("Failed while loading local advisory details");
@@ -191,6 +195,34 @@ export async function scanPackages(packages, batchSize, options, context) {
191
195
  const npmTransitiveGraph = context?.scanSource === "package-lock" && context.scanFilePath
192
196
  ? createNpmTransitiveGraphFromLockfile(context.scanFilePath)
193
197
  : null;
198
+ const npmWorkspaceMap = (() => {
199
+ try {
200
+ return context?.scanSource === "package-lock" && context.scanFilePath
201
+ ? buildNpmWorkspaceMap(context.scanFilePath) : null;
202
+ }
203
+ catch {
204
+ return null;
205
+ }
206
+ })();
207
+ const pnpmWorkspaceMap = (() => {
208
+ try {
209
+ return context?.scanSource === "pnpm-lock" && context.scanFilePath
210
+ ? buildPnpmWorkspaceMap(context.scanFilePath) : null;
211
+ }
212
+ catch {
213
+ return null;
214
+ }
215
+ })();
216
+ const bunWorkspaceMap = (() => {
217
+ try {
218
+ return context?.scanSource === "bun-lock" && context.scanFilePath
219
+ ? buildBunWorkspaceMap(context.scanFilePath) : null;
220
+ }
221
+ catch {
222
+ return null;
223
+ }
224
+ })();
225
+ const lockfileWorkspaceMap = pnpmWorkspaceMap ?? bunWorkspaceMap ?? null;
194
226
  const npmRemediationCache = new Map();
195
227
  const parentUpgradeCache = new Map();
196
228
  const directValidationCount = offline ? 0 : findings.length;
@@ -233,6 +265,7 @@ export async function scanPackages(packages, batchSize, options, context) {
233
265
  packages,
234
266
  directDependencyNames: context?.directDependencyNames,
235
267
  offline,
268
+ workspaceMap: npmWorkspaceMap,
236
269
  });
237
270
  npmRemediationCache.set(remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null);
238
271
  }
@@ -253,6 +286,25 @@ export async function scanPackages(packages, batchSize, options, context) {
253
286
  continue;
254
287
  }
255
288
  }
289
+ if (!offline && !npmTransitiveGraph) {
290
+ if (npmRemediationCache.has(remediationCacheKey)) {
291
+ finding.recommendedNpmTransitiveRemediation =
292
+ npmRemediationCache.get(remediationCacheKey) ?? undefined;
293
+ }
294
+ else {
295
+ finding.recommendedNpmTransitiveRemediation = await resolveTransitiveRemediationViaRegistry({
296
+ finding,
297
+ packages,
298
+ directDependencyNames: context?.directDependencyNames,
299
+ workspaceMap: lockfileWorkspaceMap,
300
+ });
301
+ npmRemediationCache.set(remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null);
302
+ }
303
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
304
+ finding.recommendedParentUpgrade = undefined;
305
+ continue;
306
+ }
307
+ }
256
308
  if (parentUpgradeCache.has(remediationCacheKey)) {
257
309
  finding.recommendedParentUpgrade = parentUpgradeCache.get(remediationCacheKey) ?? undefined;
258
310
  }
@@ -332,7 +384,7 @@ async function validateDirectFixTargets(findings, onFinding) {
332
384
  continue;
333
385
  }
334
386
  finding.fixVersionValidationNote =
335
- `Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package version${lowestKnownResolution.candidatesChecked === 1 ? "" : "s"} above current version (${lowestKnownResolution.candidatesKnownVulnerable} still known vulnerable); using lowest known non-vulnerable version ${lowestKnownResolution.resolvedVersion}.`;
387
+ `Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package ${pluralize(lowestKnownResolution.candidatesChecked, "version")} above current version (${lowestKnownResolution.candidatesKnownVulnerable} still known vulnerable); using lowest known non-vulnerable version ${lowestKnownResolution.resolvedVersion}.`;
336
388
  continue;
337
389
  }
338
390
  if (!fixedVersionHint) {
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- const IGNORED_DIRS = new Set(["node_modules", ".git", "dist", "build", "coverage"]);
3
+ // Shared with lockfile scanning in utils/file.ts; additions affect both code paths.
4
+ import { EXCLUDED_DIRS } from "../constants.js";
4
5
  const ALLOWED_EXTS = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"]);
5
6
  // Matches:
6
7
  // import { foo } from 'pkg'
@@ -46,7 +47,7 @@ export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
46
47
  return;
47
48
  const fullPath = path.join(dir, entry.name);
48
49
  if (entry.isDirectory()) {
49
- if (!IGNORED_DIRS.has(entry.name) && !entry.name.startsWith(".")) {
50
+ if (!EXCLUDED_DIRS.has(entry.name) && !entry.name.startsWith(".")) {
50
51
  walk(fullPath);
51
52
  }
52
53
  }