cve-lite-cli 1.26.0 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +147 -398
  2. package/dist/advisory/osv-advisory-source.js +5 -3
  3. package/dist/cli/advisories-init.js +24 -0
  4. package/dist/cli/args.js +36 -0
  5. package/dist/cli/help.js +9 -5
  6. package/dist/cli/overrides.js +20 -16
  7. package/dist/constants.js +1 -0
  8. package/dist/index.js +61 -39
  9. package/dist/maintenance/dm001-maintenance-risk.js +63 -0
  10. package/dist/maintenance/types.js +1 -0
  11. package/dist/osv/cache.js +49 -50
  12. package/dist/output/debug.js +2 -1
  13. package/dist/output/formatters.js +17 -3
  14. package/dist/output/html-reporter.js +156 -102
  15. package/dist/output/logos.js +1 -1
  16. package/dist/output/maintenance-findings-html.js +56 -0
  17. package/dist/output/maintenance-findings-json.js +3 -0
  18. package/dist/output/maintenance-terminal.js +80 -0
  19. package/dist/output/override-findings-html.js +24 -28
  20. package/dist/output/override-findings-sarif.js +34 -24
  21. package/dist/output/override-findings-terminal.js +19 -2
  22. package/dist/output/printers.js +19 -6
  23. package/dist/output/sarif.js +14 -6
  24. package/dist/output/spinner.js +5 -0
  25. package/dist/output/write-outputs.js +3 -1
  26. package/dist/overrides/context-builder.js +29 -0
  27. package/dist/overrides/detectors/index.js +6 -0
  28. package/dist/overrides/detectors/oa009-stale-floor.js +80 -0
  29. package/dist/overrides/detectors/pd001-override-only-phantom.js +32 -0
  30. package/dist/overrides/detectors/pd002-transitive-only-phantom.js +34 -0
  31. package/dist/overrides/detectors/phantom-utils.js +21 -0
  32. package/dist/overrides/fixer.js +21 -1
  33. package/dist/remediation/cooldown.js +74 -0
  34. package/dist/remediation/fix-commands.js +42 -2
  35. package/dist/remediation/npm-registry.js +11 -0
  36. package/dist/remediation/parent-upgrade.js +114 -18
  37. package/dist/scan/multi-folder-scan.js +35 -10
  38. package/dist/scanner.js +86 -22
  39. package/dist/usage/scanner.js +60 -1
  40. package/dist/utils/network.js +77 -0
  41. package/dist/utils/sarif.js +4 -0
  42. package/dist/utils/severity.js +6 -0
  43. package/package.json +2 -1
@@ -70,7 +70,7 @@ export function applyFix(opts) {
70
70
  }
71
71
  if (!dryRun && applied.length > 0) {
72
72
  const indent = detectIndent(original);
73
- writeFileSync(pkgPath, JSON.stringify(state, null, indent) + "\n");
73
+ writeFileSync(pkgPath, JSON.stringify(pruneEmptyOverrideContainers(state), null, indent) + "\n");
74
74
  }
75
75
  return {
76
76
  appliedAt: new Date().toISOString(),
@@ -79,6 +79,26 @@ export function applyFix(opts) {
79
79
  skipped,
80
80
  };
81
81
  }
82
+ function isEmpty(val) {
83
+ return !!val && typeof val === "object" && !Array.isArray(val) && Object.keys(val).length === 0;
84
+ }
85
+ function pruneEmptyOverrideContainers(doc) {
86
+ const result = { ...doc };
87
+ for (const key of ["overrides", "resolutions"]) {
88
+ if (isEmpty(result[key]))
89
+ delete result[key];
90
+ }
91
+ const pnpm = result.pnpm;
92
+ if (pnpm && typeof pnpm === "object" && !Array.isArray(pnpm)) {
93
+ const pnpmObj = { ...pnpm };
94
+ if (isEmpty(pnpmObj.overrides))
95
+ delete pnpmObj.overrides;
96
+ result.pnpm = Object.keys(pnpmObj).length === 0 ? undefined : pnpmObj;
97
+ if (result.pnpm === undefined)
98
+ delete result.pnpm;
99
+ }
100
+ return result;
101
+ }
82
102
  function detectIndent(raw) {
83
103
  const m = raw.match(/^\{\n([ \t]+)/);
84
104
  if (!m)
@@ -0,0 +1,74 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { parse as parseYaml } from "yaml";
4
+ // Design basis - verified against current PM docs. npm: days; pnpm/yarn: minutes.
5
+ const PM_CONFIG = {
6
+ npm: { file: ".npmrc", key: "min-release-age", unitMs: 86_400_000, unitLabel: "day", format: "ini" },
7
+ pnpm: { file: "pnpm-workspace.yaml", key: "minimumReleaseAge", unitMs: 60_000, unitLabel: "min", format: "yaml" },
8
+ yarn: { file: ".yarnrc.yml", key: "npmMinimalAgeGate", unitMs: 60_000, unitLabel: "min", format: "yaml" },
9
+ };
10
+ function readIniValue(contents, key) {
11
+ for (const rawLine of contents.split(/\r?\n/)) {
12
+ const line = rawLine.trim();
13
+ if (!line || line.startsWith("#") || line.startsWith(";"))
14
+ continue;
15
+ const eq = line.indexOf("=");
16
+ if (eq === -1)
17
+ continue;
18
+ if (line.slice(0, eq).trim() === key)
19
+ return line.slice(eq + 1).trim();
20
+ }
21
+ return null;
22
+ }
23
+ function readYamlValue(contents, key) {
24
+ try {
25
+ const doc = parseYaml(contents);
26
+ if (doc && typeof doc === "object" && key in doc) {
27
+ return doc[key];
28
+ }
29
+ }
30
+ catch {
31
+ // fall through to null
32
+ }
33
+ return null;
34
+ }
35
+ /**
36
+ * Reads the project-level release cooldown configured for the detected package
37
+ * manager and normalizes it to milliseconds. Returns null when no usable
38
+ * cooldown is configured (absent file/key, value 0, or malformed). Never throws.
39
+ * CVE Lite never invents a cooldown - this only surfaces what the team set.
40
+ */
41
+ export function readConfiguredCooldown(projectPath, pm) {
42
+ const cfg = PM_CONFIG[pm];
43
+ const filePath = path.join(projectPath, cfg.file);
44
+ let contents;
45
+ try {
46
+ contents = fs.readFileSync(filePath, "utf-8");
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ const raw = cfg.format === "ini" ? readIniValue(contents, cfg.key) : readYamlValue(contents, cfg.key);
52
+ const value = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : NaN;
53
+ if (!Number.isFinite(value) || value <= 0)
54
+ return null;
55
+ return {
56
+ windowMs: value * cfg.unitMs,
57
+ windowLabel: `${value} ${cfg.unitLabel}`,
58
+ sourceFile: cfg.file,
59
+ };
60
+ }
61
+ /**
62
+ * Returns a cooldown warning when a recommended fix version was published within
63
+ * the configured window, else null. Pure comparison - all inputs injected.
64
+ */
65
+ export function cooldownWarningFor(publishedAtIso, cooldown, nowMs) {
66
+ if (!cooldown || !publishedAtIso)
67
+ return null;
68
+ const publishedMs = Date.parse(publishedAtIso);
69
+ if (!Number.isFinite(publishedMs))
70
+ return null;
71
+ if (nowMs - publishedMs >= cooldown.windowMs)
72
+ return null;
73
+ return { publishedAt: publishedAtIso, windowLabel: cooldown.windowLabel, sourceFile: cooldown.sourceFile };
74
+ }
@@ -1,3 +1,4 @@
1
+ import path from "node:path";
1
2
  import { severityOrder } from "../constants.js";
2
3
  import { compareVersions, looksLikeVersion } from "../utils/version.js";
3
4
  import { getPrimaryParent } from "../utils/finding.js";
@@ -7,6 +8,12 @@ import { buildNpmWorkspaceMap } from "../parsers/package-lock.js";
7
8
  import { buildPnpmWorkspaceMap } from "../parsers/pnpm-lock.js";
8
9
  import { buildYarnWorkspaceMap } from "../parsers/yarn-lock.js";
9
10
  import { buildBunWorkspaceMap } from "../parsers/bun-lock.js";
11
+ import { readConfiguredCooldown, cooldownWarningFor } from "./cooldown.js";
12
+ import { isVerifiedUpgrade } from "./parent-upgrade.js";
13
+ // Rendered next to a parent-upgrade fix target whose recommendedParentUpgrade
14
+ // could not be verified end-to-end (parent-upgrade.ts confidence: "unverified").
15
+ // Shared across terminal and HTML output so the wording stays in sync.
16
+ export const UNVERIFIED_PARENT_UPGRADE_NOTE = "⚠ unverified - rescan after upgrading to confirm this resolves the finding";
10
17
  export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
11
18
  const packageManager = inferPackageManager(scanInput);
12
19
  if (!packageManager)
@@ -241,6 +248,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
241
248
  chainProof: chainForParentUpgrade?.chain,
242
249
  chainSafeVersion: chainForParentUpgrade?.safeVersion,
243
250
  chainVulnerablePackage: chainForParentUpgrade ? finding.pkg.name : undefined,
251
+ confidence: finding.recommendedParentUpgrade.confidence,
244
252
  });
245
253
  continue;
246
254
  }
@@ -336,6 +344,15 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
336
344
  return kindDelta;
337
345
  return a.package.localeCompare(b.package);
338
346
  });
347
+ const nowMs = options?.nowMs ?? Date.now();
348
+ if (scanInput.filePath && (packageManager === "npm" || packageManager === "pnpm" || packageManager === "yarn")) {
349
+ const cooldown = readConfiguredCooldown(path.dirname(scanInput.filePath), packageManager);
350
+ if (cooldown) {
351
+ for (const target of targets) {
352
+ target.cooldownWarning = cooldownWarningFor(target.fixVersionPublishedAt, cooldown, nowMs);
353
+ }
354
+ }
355
+ }
339
356
  const skipped = [...skippedByKey.values()].sort((a, b) => a.package.localeCompare(b.package));
340
357
  const sections = buildSections(targets, packageManager);
341
358
  const command = targets.length > 0
@@ -351,7 +368,21 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
351
368
  coveredFindingCount: 0,
352
369
  totalFindingCount: findings.length,
353
370
  };
354
- plan.coveredFindingCount = findings.filter(f => findSuggestedCommandForFinding(plan, f) !== null).length;
371
+ // A finding only counts as covered when it has a matching fix target AND that
372
+ // target isn't an unverified parent upgrade - an unverified recommendation may
373
+ // not actually resolve the finding, so it must not inflate the "fix all" claim.
374
+ plan.coveredFindingCount = findings.filter(f => {
375
+ const target = findFixTargetForFinding(plan, f);
376
+ if (!target)
377
+ return false;
378
+ // Coverage is a per-finding property, not a per-target one: two unrelated
379
+ // findings can merge into the same target (same package upgrade), so a
380
+ // finding's own recommendedParentUpgrade confidence - not the blended
381
+ // target confidence - decides whether it is genuinely covered.
382
+ if (f.recommendedParentUpgrade)
383
+ return isVerifiedUpgrade(f.recommendedParentUpgrade.confidence);
384
+ return true;
385
+ }).length;
355
386
  if (options?.subfolder) {
356
387
  const prefix = `cd ${options.subfolder} && `;
357
388
  if (plan.command)
@@ -405,7 +436,7 @@ export function commandPrefix(packageManager) {
405
436
  function devFlag(packageManager) {
406
437
  return packageManager === "bun" ? "--dev" : "-D";
407
438
  }
408
- export function findSuggestedCommandForFinding(plan, finding) {
439
+ export function findFixTargetForFinding(plan, finding) {
409
440
  const target = plan.targets.find(item => {
410
441
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
411
442
  return (item.kind === "parent-update" &&
@@ -429,6 +460,10 @@ export function findSuggestedCommandForFinding(plan, finding) {
429
460
  const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
430
461
  return item.package === finding.pkg.name && item.targetVersion === directTarget;
431
462
  });
463
+ return target ?? null;
464
+ }
465
+ export function findSuggestedCommandForFinding(plan, finding) {
466
+ const target = findFixTargetForFinding(plan, finding);
432
467
  if (!target)
433
468
  return null;
434
469
  if (target.command)
@@ -485,6 +520,11 @@ function upsertTarget(targetsByPackage, next) {
485
520
  chainProof: existing.chainProof ?? next.chainProof,
486
521
  chainSafeVersion: existing.chainSafeVersion ?? next.chainSafeVersion,
487
522
  chainVulnerablePackage: existing.chainVulnerablePackage ?? next.chainVulnerablePackage,
523
+ // Conservative: if either contributing finding's recommendation is unverified,
524
+ // keep the merged target unverified rather than overstate coverage.
525
+ confidence: existing.confidence === "unverified" || next.confidence === "unverified"
526
+ ? "unverified"
527
+ : existing.confidence ?? next.confidence,
488
528
  };
489
529
  if (looksLikeVersion(existing.targetVersion) && looksLikeVersion(next.targetVersion)) {
490
530
  if (compareVersions(next.targetVersion, existing.targetVersion) > 0) {
@@ -27,6 +27,7 @@ export async function fetchPackument(packageName) {
27
27
  if (registryDebugLog) {
28
28
  registryDebugLog("Registry fetch", { batchId, package: packageName, url });
29
29
  }
30
+ let transientFailure = false;
30
31
  try {
31
32
  const response = await fetch(url);
32
33
  if (!response.ok) {
@@ -39,6 +40,10 @@ export async function fetchPackument(packageName) {
39
40
  versionsCount: 0,
40
41
  });
41
42
  }
43
+ if (response.status === 404) {
44
+ return null;
45
+ }
46
+ transientFailure = true;
42
47
  return null;
43
48
  }
44
49
  const json = (await response.json());
@@ -54,6 +59,7 @@ export async function fetchPackument(packageName) {
54
59
  return json;
55
60
  }
56
61
  catch (error) {
62
+ transientFailure = true;
57
63
  if (registryDebugLog) {
58
64
  registryDebugLog("Registry fetch failed", {
59
65
  batchId,
@@ -66,6 +72,11 @@ export async function fetchPackument(packageName) {
66
72
  }
67
73
  return null;
68
74
  }
75
+ finally {
76
+ if (transientFailure) {
77
+ packumentCache.delete(packageName);
78
+ }
79
+ }
69
80
  })();
70
81
  packumentCache.set(packageName, promise);
71
82
  return promise;
@@ -1,5 +1,8 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
+ export function isVerifiedUpgrade(confidence) {
4
+ return confidence === "verified";
5
+ }
3
6
  export async function resolveRecommendedParentUpgrade(finding, packages, directDependencyNames, options) {
4
7
  if (finding.relationship !== "transitive")
5
8
  return null;
@@ -28,9 +31,9 @@ export async function resolveRecommendedParentUpgrade(finding, packages, directD
28
31
  viaPath,
29
32
  });
30
33
  }
31
- // Best-effort fallback for deeper chains.
34
+ // Deeper chains: verify along the path before recommending.
32
35
  // Use the immediate child of the direct parent (not the immediate parent of the vulnerable
33
- // package) — that's what the direct parent actually lists in its own dependencies.
36
+ // package) - that's what the direct parent actually lists in its own dependencies.
34
37
  const directParentIdx = viaPath.indexOf(directParentName);
35
38
  if (directParentIdx < 0)
36
39
  return null;
@@ -41,6 +44,8 @@ export async function resolveRecommendedParentUpgrade(finding, packages, directD
41
44
  immediateChildName,
42
45
  immediateChildInstalledVersion: findPackageVersion(packages, immediateChildName, viaPath.slice(0, directParentIdx + 2)) ?? "",
43
46
  vulnerableName,
47
+ vulnerableFixedVersion: finding.validatedFirstFixedVersion ?? finding.firstFixedVersion,
48
+ pathAfterParent: viaPath.slice(directParentIdx + 1),
44
49
  viaPath,
45
50
  });
46
51
  }
@@ -102,6 +107,48 @@ function startsWithPath(path, prefix) {
102
107
  }
103
108
  return true;
104
109
  }
110
+ /**
111
+ * Highest published, non-prerelease version of `name` that satisfies `range`,
112
+ * or null if none do (or the packument cannot be fetched).
113
+ */
114
+ export async function resolveHighestSatisfying(name, range) {
115
+ const packument = await fetchPackument(name);
116
+ const versions = Object.keys(packument?.versions ?? {})
117
+ .filter(looksLikeVersion)
118
+ .filter(v => !isPreReleaseVersion(v))
119
+ .filter(version => versionSatisfiesRange(version, range))
120
+ .sort(compareVersions);
121
+ return versions.at(-1) ?? null;
122
+ }
123
+ /**
124
+ * Walk `pathNames` (in order, ending with `vulnerableName`) starting from
125
+ * `startManifest`, resolving each declared range to its highest published
126
+ * version to find what the vulnerable package would actually resolve to.
127
+ *
128
+ * - A dep dropped mid-path means the vulnerable package is no longer pulled
129
+ * via this path: `{ terminalVersion: null, resolvable: true }`.
130
+ * - A range that cannot be resolved to any published version means the walk
131
+ * cannot be verified: `{ terminalVersion: null, resolvable: false }`.
132
+ */
133
+ export async function resolvePathTerminalVersion(startManifest, pathNames, vulnerableName) {
134
+ let currentManifest = startManifest;
135
+ for (const nextName of pathNames) {
136
+ const range = currentManifest.dependencies?.[nextName] ?? currentManifest.optionalDependencies?.[nextName];
137
+ if (range === undefined) {
138
+ return { terminalVersion: null, resolvable: true };
139
+ }
140
+ const resolved = await resolveHighestSatisfying(nextName, range);
141
+ if (resolved === null) {
142
+ return { terminalVersion: null, resolvable: false };
143
+ }
144
+ if (nextName === vulnerableName) {
145
+ return { terminalVersion: resolved, resolvable: true };
146
+ }
147
+ const nextPackument = await fetchPackument(nextName);
148
+ currentManifest = nextPackument?.versions?.[resolved] ?? {};
149
+ }
150
+ return { terminalVersion: null, resolvable: true };
151
+ }
105
152
  async function findUpgradeForExactDirectChild(args) {
106
153
  const packument = await fetchPackument(args.directParentName);
107
154
  const versions = Object.keys(packument?.versions ?? {})
@@ -126,13 +173,17 @@ async function findUpgradeForExactDirectChild(args) {
126
173
  targetVersion: version,
127
174
  viaPath: args.viaPath,
128
175
  vulnerablePackage: args.vulnerableName,
129
- confidence: "exact-direct-child",
176
+ confidence: "verified",
130
177
  reason: `${args.directParentName}@${version} no longer allows ${args.vulnerableName}@${args.vulnerableInstalledVersion}${args.vulnerableFixedVersion ? ` and allows ${args.vulnerableFixedVersion}+` : ""}`,
131
178
  };
132
179
  }
133
180
  }
134
181
  return null;
135
182
  }
183
+ // Bound how many candidate parent versions we resolve the full path for, to keep
184
+ // network cost reasonable. Packuments are process-cached, so shared path prefixes
185
+ // across candidates are cheap, but the terminal walk still fetches per link.
186
+ const MAX_CANDIDATE_PARENT_VERSIONS = 25;
136
187
  async function findUpgradeForImmediateIntermediate(args) {
137
188
  if (!args.immediateChildInstalledVersion || !looksLikeVersion(args.immediateChildInstalledVersion)) {
138
189
  return null;
@@ -142,25 +193,70 @@ async function findUpgradeForImmediateIntermediate(args) {
142
193
  .filter(looksLikeVersion)
143
194
  .filter(v => !isPreReleaseVersion(v))
144
195
  .filter(version => compareVersions(version, args.directParentVersion) > 0)
145
- .sort(compareVersions);
196
+ .sort(compareVersions)
197
+ .slice(0, MAX_CANDIDATE_PARENT_VERSIONS);
198
+ // Three outcomes:
199
+ // 1. A candidate whose subtree resolves the vulnerable package to a fixed
200
+ // version (or drops it entirely) -> recommend it, verified.
201
+ // 2. Every candidate is resolvable but none reaches a fixed version -> null
202
+ // (honest: no parent upgrade currently resolves this).
203
+ // 3. Some candidate could not be verified (a range/packument we could not
204
+ // resolve) -> fall back to the old "no longer allows the installed child"
205
+ // heuristic, but label it unverified.
206
+ let sawUnverifiable = false;
207
+ let heuristicFallback = null;
146
208
  for (const version of versions) {
147
209
  const manifest = packument?.versions?.[version];
148
- const depRange = manifest?.dependencies?.[args.immediateChildName] ??
149
- manifest?.optionalDependencies?.[args.immediateChildName];
150
- if (!depRange)
210
+ if (!manifest)
211
+ continue;
212
+ const walk = await resolvePathTerminalVersion(manifest, args.pathAfterParent, args.vulnerableName);
213
+ if (walk.resolvable) {
214
+ const isFixed = walk.terminalVersion === null ||
215
+ (args.vulnerableFixedVersion != null &&
216
+ compareVersions(walk.terminalVersion, args.vulnerableFixedVersion) >= 0);
217
+ if (isFixed) {
218
+ // "verified" means verified against declared dependency ranges along this
219
+ // path (each link resolved to its highest published satisfying version),
220
+ // not an install-level guarantee - npm dedup/hoisting can still land a
221
+ // lower version. This is the honest upper bound we can compute without
222
+ // reimplementing npm's resolver.
223
+ const reason = walk.terminalVersion === null
224
+ ? `${args.directParentName}@${version} no longer pulls ${args.vulnerableName} on this path`
225
+ : `${args.directParentName}@${version} resolves ${args.vulnerableName} to ${walk.terminalVersion}${args.vulnerableFixedVersion ? `, at or above the fix ${args.vulnerableFixedVersion}` : ""}`;
226
+ return {
227
+ package: args.directParentName,
228
+ currentVersion: args.directParentVersion,
229
+ targetVersion: version,
230
+ viaPath: args.viaPath,
231
+ vulnerablePackage: args.vulnerableName,
232
+ confidence: "verified",
233
+ reason,
234
+ };
235
+ }
151
236
  continue;
152
- const stillAllowsInstalledChild = versionSatisfiesRange(args.immediateChildInstalledVersion, depRange);
153
- if (!stillAllowsInstalledChild) {
154
- return {
155
- package: args.directParentName,
156
- currentVersion: args.directParentVersion,
157
- targetVersion: version,
158
- viaPath: args.viaPath,
159
- vulnerablePackage: args.vulnerableName,
160
- confidence: "best-effort",
161
- reason: `${args.directParentName}@${version} no longer allows ${args.immediateChildName}@${args.immediateChildInstalledVersion} in the current path`,
162
- };
163
237
  }
238
+ // Could not verify this candidate's subtree. Remember the first candidate that
239
+ // also satisfies the old heuristic (parent no longer allows the installed
240
+ // immediate child) as an explicitly-unverified fallback.
241
+ sawUnverifiable = true;
242
+ if (!heuristicFallback) {
243
+ const depRange = manifest.dependencies?.[args.immediateChildName] ??
244
+ manifest.optionalDependencies?.[args.immediateChildName];
245
+ if (depRange && !versionSatisfiesRange(args.immediateChildInstalledVersion, depRange)) {
246
+ heuristicFallback = {
247
+ package: args.directParentName,
248
+ currentVersion: args.directParentVersion,
249
+ targetVersion: version,
250
+ viaPath: args.viaPath,
251
+ vulnerablePackage: args.vulnerableName,
252
+ confidence: "unverified",
253
+ reason: `${args.directParentName}@${version} may resolve ${args.vulnerableName}, but this could not be verified; rescan after upgrading to confirm`,
254
+ };
255
+ }
256
+ }
257
+ }
258
+ if (sawUnverifiable && heuristicFallback) {
259
+ return heuristicFallback;
164
260
  }
165
261
  return null;
166
262
  }
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
2
  import process from "node:process";
3
+ import { EXIT_OK, EXIT_FINDINGS, EXIT_ERROR } from "../types.js";
3
4
  import { loadMultiplePackages } from "../parsers/multi-package.js";
4
5
  import { scanPackages, buildCoverageNotes } from "../scanner.js";
5
6
  import { sortFindingsForOutput } from "../output/formatters.js";
@@ -15,6 +16,8 @@ import { chalk } from "../utils/chalk.js";
15
16
  import { getCliVersion } from "../utils/version-info.js";
16
17
  import { buildOverrideContext, audit } from "../overrides/index.js";
17
18
  import { NULL_AUDIT_LOG } from "../audit-log/index.js";
19
+ import { detectDM001 } from "../maintenance/dm001-maintenance-risk.js";
20
+ import { reachesFailOn } from "../utils/severity.js";
18
21
  export async function runMultiFolderScan(params) {
19
22
  const searchDepth = Math.max(0, Number(params.options.searchDepth || DEFAULT_SEARCH_DEPTH));
20
23
  const folders = loadMultiplePackages(params.projectRoot, !!params.options.prodOnly, searchDepth);
@@ -32,7 +35,7 @@ export async function runMultiFolderScan(params) {
32
35
  directDependencyNames,
33
36
  scanSource: scanInput.source,
34
37
  scanFilePath: scanInput.filePath,
35
- });
38
+ }, undefined, params.fetchImpl);
36
39
  const sorted = sortFindingsForOutput(findings);
37
40
  const coverage = buildCoverageNotes(scanInput, offline);
38
41
  const minSeverity = normalizeSeverity(params.options.minSeverity || "medium");
@@ -49,6 +52,11 @@ export async function runMultiFolderScan(params) {
49
52
  const overrideAudit = await audit(overrideCtx, { checkNetwork: !!params.options.checkNetwork });
50
53
  overrideFindings = overrideAudit.findings;
51
54
  }
55
+ // Maintenance risk per folder, mirroring the --check-overrides pattern above.
56
+ let maintenanceFindings = [];
57
+ if (params.options.checkMaintenance) {
58
+ maintenanceFindings = await detectDM001(sorted, offline);
59
+ }
52
60
  results.push({
53
61
  subfolder,
54
62
  scanInput,
@@ -59,6 +67,7 @@ export async function runMultiFolderScan(params) {
59
67
  tableFindings,
60
68
  allPackages: scanInput.packages,
61
69
  overrideFindings,
70
+ maintenanceFindings,
62
71
  });
63
72
  }
64
73
  return results;
@@ -67,18 +76,15 @@ export async function handleMultiFolderScan(params) {
67
76
  const results = await runMultiFolderScan(params);
68
77
  if (results.length === 0) {
69
78
  console.log(chalk.yellow("No scannable packages found in any subfolder."));
70
- process.exit(0);
71
- return;
79
+ return EXIT_OK;
72
80
  }
73
81
  if (params.options.fix) {
74
82
  console.error(chalk.yellow("--fix is not yet supported in multi-folder mode. Run cve-lite . from each subfolder individually."));
75
- process.exit(1);
76
- return;
83
+ return EXIT_ERROR;
77
84
  }
78
85
  if (params.options.sarif || params.options.cdx) {
79
86
  console.error(chalk.yellow("--sarif and --cdx are not yet supported in multi-folder mode."));
80
- process.exit(1);
81
- return;
87
+ return EXIT_ERROR;
82
88
  }
83
89
  if (params.options.json) {
84
90
  const { serializeFinding } = await import("../output/formatters.js");
@@ -92,6 +98,11 @@ export async function handleMultiFolderScan(params) {
92
98
  overrideFindings: results.flatMap(r => r.overrideFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
93
99
  }
94
100
  : {}),
101
+ ...(params.options.checkMaintenance
102
+ ? {
103
+ maintenanceFindings: results.flatMap(r => r.maintenanceFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
104
+ }
105
+ : {}),
95
106
  scannedAt: new Date().toISOString(),
96
107
  }, null, 2));
97
108
  }
@@ -101,7 +112,14 @@ export async function handleMultiFolderScan(params) {
101
112
  const { renderOverrideFindings } = await import("../output/override-findings-terminal.js");
102
113
  for (const r of results) {
103
114
  process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray("override hygiene")}\n`);
104
- console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose }));
115
+ console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose, projectPath: path.join(params.projectRoot, r.subfolder) }));
116
+ }
117
+ }
118
+ if (params.options.checkMaintenance) {
119
+ const { renderMaintenanceFindings } = await import("../output/maintenance-terminal.js");
120
+ for (const r of results) {
121
+ process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray("maintenance risk")}\n`);
122
+ console.log(renderMaintenanceFindings(r.maintenanceFindings, { verbose: !!params.options.verbose }));
105
123
  }
106
124
  }
107
125
  if (!params.options.checkOverrides && !params.options.ratchet) {
@@ -128,6 +146,13 @@ export async function handleMultiFolderScan(params) {
128
146
  }
129
147
  const failLevel = normalizeSeverity(params.options.failOn);
130
148
  const allSorted = results.flatMap(r => r.sorted);
131
- const shouldFail = allSorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
132
- process.exit(shouldFail ? 1 : 0);
149
+ const allOverrideFindings = results.flatMap(r => r.overrideFindings);
150
+ const allMaintenanceFindings = results.flatMap(r => r.maintenanceFindings);
151
+ // Mirror single-folder exit policy in src/index.ts: CVE + override + maintenance
152
+ // all count toward --fail-on. Without overrides here, multi-folder CI using
153
+ // --check-overrides --fail-on high would exit 0 despite high OA findings.
154
+ const shouldFail = allSorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]) ||
155
+ reachesFailOn(allOverrideFindings, params.options.failOn) ||
156
+ reachesFailOn(allMaintenanceFindings, params.options.failOn);
157
+ return shouldFail ? EXIT_FINDINGS : EXIT_OK;
133
158
  }