cve-lite-cli 1.27.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.
@@ -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
  }
@@ -16,6 +16,8 @@ import { chalk } from "../utils/chalk.js";
16
16
  import { getCliVersion } from "../utils/version-info.js";
17
17
  import { buildOverrideContext, audit } from "../overrides/index.js";
18
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";
19
21
  export async function runMultiFolderScan(params) {
20
22
  const searchDepth = Math.max(0, Number(params.options.searchDepth || DEFAULT_SEARCH_DEPTH));
21
23
  const folders = loadMultiplePackages(params.projectRoot, !!params.options.prodOnly, searchDepth);
@@ -33,7 +35,7 @@ export async function runMultiFolderScan(params) {
33
35
  directDependencyNames,
34
36
  scanSource: scanInput.source,
35
37
  scanFilePath: scanInput.filePath,
36
- });
38
+ }, undefined, params.fetchImpl);
37
39
  const sorted = sortFindingsForOutput(findings);
38
40
  const coverage = buildCoverageNotes(scanInput, offline);
39
41
  const minSeverity = normalizeSeverity(params.options.minSeverity || "medium");
@@ -50,6 +52,11 @@ export async function runMultiFolderScan(params) {
50
52
  const overrideAudit = await audit(overrideCtx, { checkNetwork: !!params.options.checkNetwork });
51
53
  overrideFindings = overrideAudit.findings;
52
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
+ }
53
60
  results.push({
54
61
  subfolder,
55
62
  scanInput,
@@ -60,6 +67,7 @@ export async function runMultiFolderScan(params) {
60
67
  tableFindings,
61
68
  allPackages: scanInput.packages,
62
69
  overrideFindings,
70
+ maintenanceFindings,
63
71
  });
64
72
  }
65
73
  return results;
@@ -90,6 +98,11 @@ export async function handleMultiFolderScan(params) {
90
98
  overrideFindings: results.flatMap(r => r.overrideFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
91
99
  }
92
100
  : {}),
101
+ ...(params.options.checkMaintenance
102
+ ? {
103
+ maintenanceFindings: results.flatMap(r => r.maintenanceFindings.map(f => ({ ...f, subfolder: r.subfolder }))),
104
+ }
105
+ : {}),
93
106
  scannedAt: new Date().toISOString(),
94
107
  }, null, 2));
95
108
  }
@@ -102,6 +115,13 @@ export async function handleMultiFolderScan(params) {
102
115
  console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose, projectPath: path.join(params.projectRoot, r.subfolder) }));
103
116
  }
104
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 }));
123
+ }
124
+ }
105
125
  if (!params.options.checkOverrides && !params.options.ratchet) {
106
126
  for (const r of results) {
107
127
  const subfolderPath = path.join(params.projectRoot, r.subfolder);
@@ -126,6 +146,13 @@ export async function handleMultiFolderScan(params) {
126
146
  }
127
147
  const failLevel = normalizeSeverity(params.options.failOn);
128
148
  const allSorted = results.flatMap(r => r.sorted);
129
- const shouldFail = allSorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
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);
130
157
  return shouldFail ? EXIT_FINDINGS : EXIT_OK;
131
158
  }
package/dist/scanner.js CHANGED
@@ -18,6 +18,8 @@ import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
18
18
  import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
19
19
  import { buildBunWorkspaceMap } from "./parsers/bun-lock.js";
20
20
  import { pluralize } from "./utils/string.js";
21
+ import { extractErrorMessage } from "./utils/network.js";
22
+ import { logWarn } from "./output/formatters.js";
21
23
  export function createAdvisorySource(options) {
22
24
  const offline = !!options?.offline || !!options?.offlineDb;
23
25
  if (offline) {
@@ -33,7 +35,7 @@ export function createAdvisorySource(options) {
33
35
  };
34
36
  }
35
37
  return {
36
- advisorySource: new OsvAdvisorySource(options?.osvUrl, options?.debugLog),
38
+ advisorySource: new OsvAdvisorySource(options?.osvUrl, options?.debugLog, options?.fetchImpl),
37
39
  offline: false,
38
40
  sourceLabel: options?.osvUrl
39
41
  ? `custom OSV endpoint (${options.osvUrl})`
@@ -57,13 +59,22 @@ function inferPackageManagerForChain(source) {
57
59
  return "bun";
58
60
  return null;
59
61
  }
60
- export async function scanPackages(packages, batchSize, options, context, debugLog) {
62
+ function isTransientFailure(error) {
63
+ if (!(error instanceof Error))
64
+ return true;
65
+ const msg = error.message;
66
+ if (msg.includes(" 404 ") || msg.includes(" 410 "))
67
+ return false;
68
+ return true;
69
+ }
70
+ export async function scanPackages(packages, batchSize, options, context, debugLog, fetchImpl) {
61
71
  const log = debugLog ?? (() => { });
62
72
  const sourceContext = createAdvisorySource({
63
73
  osvUrl: options.osvUrl,
64
74
  offline: options.offline,
65
75
  offlineDb: options.offlineDb,
66
76
  debugLog: log,
77
+ fetchImpl,
67
78
  });
68
79
  const offline = sourceContext.offline;
69
80
  const cacheDirOverride = options.cacheDir;
@@ -151,42 +162,57 @@ export async function scanPackages(packages, batchSize, options, context, debugL
151
162
  }
152
163
  const idSet = new Set(results.flatMap(r => r.vulnIds));
153
164
  const vulnMap = new Map();
165
+ const transientDetailIds = new Set();
166
+ const offlineMissingDetailIds = new Set();
154
167
  if (idSet.size > 0 && !offline) {
155
168
  const ids = [...idSet];
156
169
  const detailSpinner = createSpinner("Fetching vulnerability details...", options);
157
170
  try {
158
- // cache.entries holds OsvVuln detail records. Unlike cache.queryEntries (which has a
159
- // 30-minute staleness check applied earlier in this function), detail records have no
160
- // expiry — they are considered valid for the lifetime of the cache file. The check below
161
- // is therefore a simple presence check, not a staleness check. This is intentional and
162
- // matches the original behaviour. Fetches run concurrently because there is no ordering
163
- // dependency between CVE ID detail requests.
171
+ const nowMs = Date.now();
164
172
  const uncachedIds = [];
165
173
  for (const id of ids) {
166
- if (id in cache.entries) {
167
- const cached = cache.entries[id];
168
- if (cached)
169
- vulnMap.set(id, cached);
174
+ const cached = cache.entries[id];
175
+ if (cached && !isEntryStale(cached, nowMs)) {
176
+ if (cached.vuln) {
177
+ vulnMap.set(id, cached.vuln);
178
+ }
170
179
  }
171
180
  else {
172
181
  uncachedIds.push(id);
173
182
  }
174
183
  }
175
- // Fetch all uncached IDs concurrently
176
184
  if (uncachedIds.length > 0) {
177
185
  detailSpinner.update(`Fetching ${uncachedIds.length} vulnerability details...`);
186
+ const cachedAt = new Date().toISOString();
178
187
  await runWithConcurrency(uncachedIds, 10, async (id) => {
179
188
  try {
180
189
  const detail = await advisorySource.getVuln(id);
181
190
  vulnMap.set(id, detail);
182
- cache.entries[id] = detail;
191
+ cache.entries[id] = { vuln: detail, cachedAt };
183
192
  }
184
- catch {
185
- cache.entries[id] = null;
193
+ catch (error) {
194
+ if (isTransientFailure(error)) {
195
+ transientDetailIds.add(id);
196
+ log("OSV detail transient failure", {
197
+ advisoryId: id,
198
+ error: extractErrorMessage(error),
199
+ });
200
+ }
201
+ else {
202
+ cache.entries[id] = { vuln: null, cachedAt };
203
+ log("OSV detail confirmed missing", { advisoryId: id });
204
+ }
186
205
  }
187
206
  });
188
207
  }
189
- detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail ${pluralize(ids.length, "record")}`);
208
+ const successCount = ids.filter(id => vulnMap.has(id)).length;
209
+ const failureCount = ids.length - successCount;
210
+ if (failureCount > 0) {
211
+ detailSpinner.warn(`Loaded ${successCount}/${ids.length} vulnerability detail ${pluralize(ids.length, "record")} (${failureCount} ${pluralize(failureCount, "failure")})`);
212
+ }
213
+ else {
214
+ detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail ${pluralize(ids.length, "record")}`);
215
+ }
190
216
  }
191
217
  catch (error) {
192
218
  detailSpinner.fail("Failed while fetching vulnerability details");
@@ -203,10 +229,17 @@ export async function scanPackages(packages, batchSize, options, context, debugL
203
229
  vulnMap.set(id, detail);
204
230
  }
205
231
  catch {
206
- // ignore missing local records so scans remain resilient to partial DB state
232
+ offlineMissingDetailIds.add(id);
207
233
  }
208
234
  });
209
- detailSpinner.succeed(`Loaded ${ids.length} local advisory detail ${pluralize(ids.length, "record")}`);
235
+ const successCount = ids.filter(id => vulnMap.has(id)).length;
236
+ const failureCount = ids.length - successCount;
237
+ if (failureCount > 0) {
238
+ detailSpinner.warn(`Loaded ${successCount}/${ids.length} local advisory detail ${pluralize(ids.length, "record")} (${failureCount} ${pluralize(failureCount, "missing")})`);
239
+ }
240
+ else {
241
+ detailSpinner.succeed(`Loaded ${ids.length} local advisory detail ${pluralize(ids.length, "record")}`);
242
+ }
210
243
  }
211
244
  catch (error) {
212
245
  detailSpinner.fail("Failed while loading local advisory details");
@@ -220,6 +253,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
220
253
  const vulnerabilities = result.vulnIds
221
254
  .map(id => vulnMap.get(id))
222
255
  .filter((v) => Boolean(v));
256
+ const unresolvedIds = result.vulnIds.filter(id => !vulnMap.has(id));
223
257
  const severity = maxSeverity(vulnerabilities);
224
258
  const cveAliases = unique(vulnerabilities.flatMap(v => (v.aliases ?? []).filter(a => a.startsWith("CVE-"))));
225
259
  const dependencyPaths = result.pkg.paths ?? [];
@@ -240,8 +274,28 @@ export async function scanPackages(packages, batchSize, options, context, debugL
240
274
  validatedTargetKnownVulnerableVersions: null,
241
275
  recommendedParentUpgrade: undefined,
242
276
  recommendedNpmTransitiveRemediation: undefined,
277
+ ...(unresolvedIds.length > 0 ? { unresolvedAdvisoryIds: unresolvedIds } : {}),
243
278
  };
244
279
  });
280
+ const unresolvedDetailIds = idSet.size > 0
281
+ ? [...idSet].filter(id => !vulnMap.has(id))
282
+ : [];
283
+ if (unresolvedDetailIds.length > 0) {
284
+ const transientCount = unresolvedDetailIds.filter(id => transientDetailIds.has(id)).length;
285
+ const offlineCount = unresolvedDetailIds.filter(id => offlineMissingDetailIds.has(id)).length;
286
+ const otherCount = unresolvedDetailIds.length - transientCount - offlineCount;
287
+ const parts = [];
288
+ if (transientCount > 0) {
289
+ parts.push(`${transientCount} from transient failures — re-run to retry`);
290
+ }
291
+ if (offlineCount > 0) {
292
+ parts.push(`${offlineCount} missing from local advisory database — refresh to sync`);
293
+ }
294
+ if (otherCount > 0) {
295
+ parts.push(`${otherCount} could not be resolved`);
296
+ }
297
+ logWarn(`⚠ ${unresolvedDetailIds.length} advisory detail ${pluralize(unresolvedDetailIds.length, "lookup")} missing from findings. ${parts.join("; ")}.`, { json: options.json });
298
+ }
245
299
  for (const finding of findings) {
246
300
  if (finding.vulnerabilities.some(v => v.id.startsWith("MAL-"))) {
247
301
  if (isGitSource(finding.pkg)) {
@@ -395,7 +449,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
395
449
  targetVersion: finding.recommendedNpmTransitiveRemediation.targetVersion ?? "",
396
450
  viaPath: finding.recommendedNpmTransitiveRemediation.viaPath,
397
451
  vulnerablePackage: finding.pkg.name,
398
- confidence: "exact-direct-child",
452
+ confidence: "verified",
399
453
  reason: finding.recommendedNpmTransitiveRemediation.reason,
400
454
  };
401
455
  continue;
@@ -432,7 +486,12 @@ export async function scanPackages(packages, batchSize, options, context, debugL
432
486
  parentUpgradeCache.set(remediationCacheKey, finding.recommendedParentUpgrade ?? null);
433
487
  }
434
488
  }
435
- catch {
489
+ catch (error) {
490
+ log("Remediation failed", {
491
+ package: finding.pkg.name,
492
+ version: finding.pkg.version,
493
+ error: error instanceof Error ? error.message : String(error),
494
+ });
436
495
  finding.recommendedNpmTransitiveRemediation = undefined;
437
496
  finding.recommendedParentUpgrade = undefined;
438
497
  }
@@ -448,7 +507,12 @@ export async function scanPackages(packages, batchSize, options, context, debugL
448
507
  try {
449
508
  finding.chainResolution = await resolveChainFix(finding, installedVersions, chainPm, { offline });
450
509
  }
451
- catch {
510
+ catch (error) {
511
+ log("Chain resolution failed", {
512
+ package: finding.pkg.name,
513
+ version: finding.pkg.version,
514
+ error: error instanceof Error ? error.message : String(error),
515
+ });
452
516
  finding.chainResolution = null;
453
517
  }
454
518
  }));
@@ -1,3 +1,6 @@
1
+ import https from "node:https";
2
+ import fs from "node:fs";
3
+ import { rootCertificates } from "node:tls";
1
4
  export function extractErrorMessage(error) {
2
5
  if (!(error instanceof Error))
3
6
  return String(error);
@@ -151,3 +154,66 @@ export function getNetworkErrorHint(error, errorMessage) {
151
154
  return blockedAdvisoryRequestHint();
152
155
  return fetchErrorCaCertHint();
153
156
  }
157
+ export function createCertAwareFetch(caCertPath) {
158
+ // Lazily create the agent on first use so that callers can be wired up before
159
+ // the cert path is validated. validateOptions() in index.ts catches invalid
160
+ // paths before any actual request is made.
161
+ let agent;
162
+ function getAgent() {
163
+ if (!agent) {
164
+ const ca = fs.readFileSync(caCertPath);
165
+ agent = new https.Agent({ ca: [...rootCertificates, ca] });
166
+ }
167
+ return agent;
168
+ }
169
+ return async (input, init) => {
170
+ const url = typeof input === "string"
171
+ ? input
172
+ : input instanceof URL
173
+ ? input.href
174
+ : input.url;
175
+ if (!url.startsWith("https://")) {
176
+ return fetch(input, init);
177
+ }
178
+ return new Promise((resolve, reject) => {
179
+ const parsed = new URL(url);
180
+ const method = (init?.method ?? "GET").toUpperCase();
181
+ const rawHeaders = init?.headers;
182
+ const headers = rawHeaders
183
+ ? Object.fromEntries(new Headers(rawHeaders).entries())
184
+ : {};
185
+ const reqOptions = {
186
+ hostname: parsed.hostname,
187
+ port: parsed.port ? parseInt(parsed.port, 10) : 443,
188
+ path: parsed.pathname + parsed.search,
189
+ method,
190
+ headers,
191
+ agent: getAgent(),
192
+ };
193
+ const req = https.request(reqOptions, res => {
194
+ const chunks = [];
195
+ res.on("data", (chunk) => chunks.push(chunk));
196
+ res.on("end", () => {
197
+ const body = Buffer.concat(chunks);
198
+ const responseHeaders = {};
199
+ for (const [key, val] of Object.entries(res.headers)) {
200
+ if (val !== undefined) {
201
+ responseHeaders[key] = Array.isArray(val) ? val.join(", ") : val;
202
+ }
203
+ }
204
+ resolve(new Response(body, {
205
+ status: res.statusCode ?? 200,
206
+ statusText: res.statusMessage ?? "",
207
+ headers: responseHeaders,
208
+ }));
209
+ });
210
+ res.on("error", reject);
211
+ });
212
+ req.on("error", reject);
213
+ if (init?.body != null) {
214
+ req.write(init.body);
215
+ }
216
+ req.end();
217
+ });
218
+ };
219
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.27.0",
3
+ "version": "1.28.0",
4
4
  "description": "Developer-friendly CLI for scanning JS/TS projects for dependency vulnerabilities using local lockfiles and OSV",
5
5
  "type": "module",
6
6
  "bin": {