cve-lite-cli 1.10.0 → 1.12.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.
@@ -0,0 +1,238 @@
1
+ import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
+ import { fetchPackument } from "./npm-registry.js";
3
+ import { findSafeVersionWithinParentRange } from "./npm-transitive-graph.js";
4
+ export async function resolveNpmTransitiveRemediation(args) {
5
+ if (args.finding.relationship !== "transitive")
6
+ return null;
7
+ const viaPath = getBestPath(args.finding);
8
+ if (!viaPath || viaPath.length < 3)
9
+ return null;
10
+ const directParentContext = resolveDirectParentContext(viaPath, args.packages, args.directDependencyNames);
11
+ if (!directParentContext)
12
+ return null;
13
+ const { directParentName, immediateParentName, directParent } = directParentContext;
14
+ const vulnerableName = args.finding.pkg.name;
15
+ // Task 3 keeps the graph-aware resolution focused on exact direct-child npm paths.
16
+ if (directParentName !== immediateParentName) {
17
+ return null;
18
+ }
19
+ const parentNodeId = resolveParentNodeId({
20
+ graph: args.graph,
21
+ parentName: directParentName,
22
+ parentVersion: directParent.version,
23
+ childName: vulnerableName,
24
+ childVersion: args.finding.pkg.version,
25
+ });
26
+ if (!parentNodeId)
27
+ return null;
28
+ const fixHint = args.finding.validatedFirstFixedVersion ?? args.finding.firstFixedVersion;
29
+ const safeCandidates = args.offline
30
+ ? buildOfflineSafeCandidates(args.finding.pkg.version, fixHint)
31
+ : await findSafeChildCandidates(vulnerableName, args.finding.pkg.version, fixHint);
32
+ if (safeCandidates.length === 0)
33
+ return null;
34
+ const inRangeTarget = findSafeVersionWithinParentRange({
35
+ graph: args.graph,
36
+ parentNodeId,
37
+ childName: vulnerableName,
38
+ candidates: safeCandidates,
39
+ });
40
+ if (inRangeTarget) {
41
+ return {
42
+ kind: "update-parent-within-range",
43
+ package: directParentName,
44
+ currentVersion: directParent.version,
45
+ targetChildVersion: inRangeTarget,
46
+ viaPath,
47
+ reason: `${directParentName}@${directParent.version} already allows ${vulnerableName}@${inRangeTarget} within the current dependency range`,
48
+ };
49
+ }
50
+ // The upgrade-parent-to-version path needs the parent's published manifests
51
+ // to find a newer parent version that no longer pulls in the vulnerable child.
52
+ // That data only comes from the npm registry, so it can't run offline.
53
+ if (args.offline)
54
+ return null;
55
+ const parentPackument = await fetchPackument(directParentName);
56
+ const parentVersions = Object.keys(parentPackument?.versions ?? {})
57
+ .filter(looksLikeVersion)
58
+ .filter(version => !isPreReleaseVersion(version))
59
+ .filter(version => compareVersions(version, directParent.version) > 0)
60
+ .sort(compareVersions);
61
+ for (const version of parentVersions) {
62
+ const manifest = parentPackument?.versions?.[version];
63
+ const depRange = manifest?.dependencies?.[vulnerableName] ??
64
+ manifest?.optionalDependencies?.[vulnerableName];
65
+ if (!depRange)
66
+ continue;
67
+ const targetChildVersion = highestVersionSatisfyingRange(safeCandidates, depRange);
68
+ if (!targetChildVersion)
69
+ continue;
70
+ const stillAllowsInstalled = versionSatisfiesRange(args.finding.pkg.version, depRange);
71
+ if (stillAllowsInstalled && compareVersions(targetChildVersion, args.finding.pkg.version) <= 0) {
72
+ continue;
73
+ }
74
+ return {
75
+ kind: "upgrade-parent-to-version",
76
+ package: directParentName,
77
+ currentVersion: directParent.version,
78
+ targetVersion: version,
79
+ targetChildVersion,
80
+ viaPath,
81
+ reason: `${directParentName}@${version} no longer allows ${vulnerableName}@${args.finding.pkg.version} and allows ${targetChildVersion}+`,
82
+ };
83
+ }
84
+ return null;
85
+ }
86
+ function getBestPath(finding) {
87
+ const paths = finding.dependencyPaths ?? [];
88
+ if (paths.length === 0)
89
+ return null;
90
+ return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
91
+ }
92
+ function findDirectDependency(packages, name, directDependencyNames) {
93
+ for (const pkg of packages) {
94
+ if (pkg.name !== name)
95
+ continue;
96
+ if (directDependencyNames?.has(name)) {
97
+ return pkg;
98
+ }
99
+ const paths = pkg.paths ?? [];
100
+ if (paths.some(path => path.at(-1) === name && path.length >= 2)) {
101
+ return pkg;
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+ function resolveDirectParentContext(viaPath, packages, directDependencyNames) {
107
+ const immediateParentName = viaPath[viaPath.length - 2];
108
+ const candidateSegments = viaPath.slice(1, -1);
109
+ const directParentCandidates = directDependencyNames
110
+ ? candidateSegments.filter(segment => directDependencyNames.has(segment))
111
+ : [viaPath[1]].filter(Boolean);
112
+ const directParentName = directParentCandidates[0];
113
+ if (!directParentName)
114
+ return null;
115
+ const directParent = findDirectDependency(packages, directParentName, directDependencyNames);
116
+ if (!directParent)
117
+ return null;
118
+ return { directParentName, immediateParentName, directParent };
119
+ }
120
+ function buildOfflineSafeCandidates(installedVersion, fixedVersionHint) {
121
+ if (!fixedVersionHint || !looksLikeVersion(fixedVersionHint))
122
+ return [];
123
+ if (isPreReleaseVersion(fixedVersionHint))
124
+ return [];
125
+ if (compareVersions(fixedVersionHint, installedVersion) <= 0)
126
+ return [];
127
+ return [fixedVersionHint];
128
+ }
129
+ async function findSafeChildCandidates(packageName, installedVersion, fixedVersionHint) {
130
+ const packument = await fetchPackument(packageName);
131
+ if (!packument)
132
+ return [];
133
+ return Object.keys(packument.versions ?? {})
134
+ .filter(looksLikeVersion)
135
+ .filter(version => !isPreReleaseVersion(version))
136
+ .filter(version => compareVersions(version, installedVersion) > 0)
137
+ .filter(version => !fixedVersionHint || compareVersions(version, fixedVersionHint) >= 0)
138
+ .sort(compareVersions);
139
+ }
140
+ function resolveParentNodeId(args) {
141
+ const candidateNodeIds = args.graph.nodeIdsFor(args.parentName, args.parentVersion);
142
+ if (candidateNodeIds.length === 0)
143
+ return null;
144
+ for (const nodeId of candidateNodeIds) {
145
+ const childNodeIds = args.graph.childrenFor(nodeId);
146
+ const hasMatchingChild = childNodeIds.some((childNodeId) => {
147
+ const childNode = args.graph.getNode(childNodeId);
148
+ return childNode?.name === args.childName && childNode.version === args.childVersion;
149
+ });
150
+ if (!hasMatchingChild)
151
+ continue;
152
+ if (!args.graph.rangeFor(nodeId, args.childName))
153
+ continue;
154
+ return nodeId;
155
+ }
156
+ for (const nodeId of candidateNodeIds) {
157
+ if (args.graph.rangeFor(nodeId, args.childName)) {
158
+ return nodeId;
159
+ }
160
+ }
161
+ return candidateNodeIds[0] ?? null;
162
+ }
163
+ function highestVersionSatisfyingRange(candidates, rawRange) {
164
+ const matches = candidates.filter(candidate => versionSatisfiesRange(candidate, rawRange)).sort(compareVersions);
165
+ return matches.at(-1) ?? null;
166
+ }
167
+ function versionSatisfiesRange(version, rawRange) {
168
+ const range = rawRange.trim();
169
+ if (!range)
170
+ return false;
171
+ if (range === "*" || range === "latest")
172
+ return true;
173
+ const orParts = range.split("||").map(part => part.trim()).filter(Boolean);
174
+ return orParts.some(part => satisfiesAndRange(version, part));
175
+ }
176
+ function satisfiesAndRange(version, range) {
177
+ const normalized = normalizeRange(range);
178
+ if (!normalized)
179
+ return false;
180
+ const tokens = normalized.split(/\s+/).filter(Boolean);
181
+ return tokens.every(token => satisfiesComparator(version, token));
182
+ }
183
+ function normalizeRange(range) {
184
+ const trimmed = range.trim();
185
+ if (!trimmed)
186
+ return null;
187
+ if (looksLikeVersion(trimmed)) {
188
+ return `=${trimmed}`;
189
+ }
190
+ if (trimmed.startsWith("^")) {
191
+ const base = trimmed.slice(1);
192
+ if (!looksLikeVersion(base))
193
+ return null;
194
+ const [major, minor, patch] = parseCoreVersion(base);
195
+ if (major > 0)
196
+ return `>=${base} <${major + 1}.0.0`;
197
+ if (minor > 0)
198
+ return `>=${base} <0.${minor + 1}.0`;
199
+ return `>=${base} <0.0.${patch + 1}`;
200
+ }
201
+ if (trimmed.startsWith("~")) {
202
+ const base = trimmed.slice(1);
203
+ if (!looksLikeVersion(base))
204
+ return null;
205
+ const [major, minor] = parseCoreVersion(base);
206
+ return `>=${base} <${major}.${minor + 1}.0`;
207
+ }
208
+ return trimmed;
209
+ }
210
+ function satisfiesComparator(version, comparator) {
211
+ const token = comparator.trim();
212
+ if (!token)
213
+ return true;
214
+ const match = token.match(/^(<=|>=|<|>|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[-+][^\s]+)?)$/);
215
+ if (!match)
216
+ return false;
217
+ const operator = match[1] ?? "=";
218
+ const target = match[2];
219
+ const cmp = compareVersions(version, target);
220
+ switch (operator) {
221
+ case "<":
222
+ return cmp < 0;
223
+ case "<=":
224
+ return cmp <= 0;
225
+ case ">":
226
+ return cmp > 0;
227
+ case ">=":
228
+ return cmp >= 0;
229
+ case "=":
230
+ return cmp === 0;
231
+ default:
232
+ return false;
233
+ }
234
+ }
235
+ function parseCoreVersion(version) {
236
+ const [major = "0", minor = "0", patch = "0"] = version.split(/[+-]/)[0].split(".");
237
+ return [Number(major), Number(minor), Number(patch)];
238
+ }
@@ -1,20 +1,23 @@
1
1
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
- export async function resolveRecommendedParentUpgrade(finding, packages) {
3
+ export async function resolveRecommendedParentUpgrade(finding, packages, directDependencyNames, options) {
4
4
  if (finding.relationship !== "transitive")
5
5
  return null;
6
+ // Both branches below need the parent's published manifests, which only the
7
+ // npm registry can supply; there's no offline-safe path for this resolver.
8
+ if (options?.offline)
9
+ return null;
6
10
  const viaPath = getBestPath(finding);
7
11
  if (!viaPath || viaPath.length < 3)
8
12
  return null;
9
- const directParentName = viaPath[1];
10
- const immediateParentName = viaPath[viaPath.length - 2];
11
- const vulnerableName = finding.pkg.name;
12
- const directParent = findDirectDependency(packages, directParentName);
13
- if (!directParent)
13
+ const directParentContext = resolveDirectParentContext(viaPath, packages, directDependencyNames);
14
+ if (!directParentContext)
14
15
  return null;
16
+ const { directParentName, immediateParentName, directParent } = directParentContext;
17
+ const vulnerableName = finding.pkg.name;
15
18
  // Common reliable case:
16
19
  // project -> sanitize-html -> lodash
17
- if (viaPath.length === 3) {
20
+ if (directParentName === immediateParentName) {
18
21
  return findUpgradeForExactDirectChild({
19
22
  directParentName,
20
23
  directParentVersion: directParent.version,
@@ -40,17 +43,34 @@ function getBestPath(finding) {
40
43
  return null;
41
44
  return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
42
45
  }
43
- function findDirectDependency(packages, name) {
46
+ function findDirectDependency(packages, name, directDependencyNames) {
44
47
  for (const pkg of packages) {
45
48
  if (pkg.name !== name)
46
49
  continue;
50
+ if (directDependencyNames?.has(name)) {
51
+ return pkg;
52
+ }
47
53
  const paths = pkg.paths ?? [];
48
- if (paths.some(path => path.length === 2 && path[1] === name)) {
54
+ if (paths.some(path => path.at(-1) === name && path.length >= 2)) {
49
55
  return pkg;
50
56
  }
51
57
  }
52
58
  return null;
53
59
  }
60
+ function resolveDirectParentContext(viaPath, packages, directDependencyNames) {
61
+ const immediateParentName = viaPath[viaPath.length - 2];
62
+ const candidateSegments = viaPath.slice(1, -1);
63
+ const directParentCandidates = directDependencyNames
64
+ ? candidateSegments.filter(segment => directDependencyNames.has(segment))
65
+ : [viaPath[1]].filter(Boolean);
66
+ const directParentName = directParentCandidates[0];
67
+ if (!directParentName)
68
+ return null;
69
+ const directParent = findDirectDependency(packages, directParentName, directDependencyNames);
70
+ if (!directParent)
71
+ return null;
72
+ return { directParentName, immediateParentName, directParent };
73
+ }
54
74
  function findPackageVersion(packages, name, pathPrefix) {
55
75
  for (const pkg of packages) {
56
76
  if (pkg.name !== name)
package/dist/scanner.js CHANGED
@@ -9,6 +9,8 @@ import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
9
9
  import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
10
10
  import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
11
11
  import { resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion } from "./remediation/npm-registry.js";
12
+ import { resolveNpmTransitiveRemediation } from "./remediation/npm-transitive-resolution.js";
13
+ import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js";
12
14
  export function createAdvisorySource(options) {
13
15
  const offline = !!options?.offline || !!options?.offlineDb;
14
16
  if (offline) {
@@ -180,21 +182,97 @@ export async function scanPackages(packages, batchSize, options, context) {
180
182
  validatedTargetScannedVersions: null,
181
183
  validatedTargetKnownVulnerableVersions: null,
182
184
  recommendedParentUpgrade: undefined,
185
+ recommendedNpmTransitiveRemediation: undefined,
183
186
  };
184
187
  });
185
- if (!offline) {
186
- await validateDirectFixTargets(findings);
187
- }
188
- for (const finding of findings) {
189
- if (finding.relationship !== "transitive" || offline)
190
- continue;
188
+ const npmTransitiveGraph = context?.scanSource === "package-lock" && context.scanFilePath
189
+ ? createNpmTransitiveGraphFromLockfile(context.scanFilePath)
190
+ : null;
191
+ const npmRemediationCache = new Map();
192
+ const parentUpgradeCache = new Map();
193
+ const directValidationCount = offline ? 0 : findings.length;
194
+ const transitiveRemediationCount = findings.filter(finding => finding.relationship === "transitive").length;
195
+ const analysisStepCount = directValidationCount + transitiveRemediationCount;
196
+ if (analysisStepCount > 0) {
197
+ const analysisSpinner = createSpinner("Analyzing vulnerability findings...", options);
198
+ let completedSteps = 0;
199
+ const updateAnalysisProgress = (phase, subject) => {
200
+ completedSteps += 1;
201
+ analysisSpinner.update(`Analyzing vulnerability findings ${completedSteps}/${analysisStepCount}: ${phase} ${subject}...`);
202
+ };
191
203
  try {
192
- finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade(finding, packages);
204
+ if (!offline) {
205
+ await validateDirectFixTargets(findings, (finding) => {
206
+ updateAnalysisProgress("validating fix target for", `${finding.pkg.name}@${finding.pkg.version}`);
207
+ });
208
+ }
209
+ for (const finding of findings) {
210
+ if (finding.relationship !== "transitive")
211
+ continue;
212
+ updateAnalysisProgress("resolving remediation for", `${finding.pkg.name}@${finding.pkg.version}`);
213
+ const remediationCacheKey = JSON.stringify({
214
+ package: finding.pkg.name,
215
+ version: finding.pkg.version,
216
+ dependencyPaths: finding.dependencyPaths,
217
+ firstFixedVersion: finding.firstFixedVersion,
218
+ validatedFirstFixedVersion: finding.validatedFirstFixedVersion ?? null,
219
+ });
220
+ try {
221
+ if (npmTransitiveGraph) {
222
+ if (npmRemediationCache.has(remediationCacheKey)) {
223
+ finding.recommendedNpmTransitiveRemediation =
224
+ npmRemediationCache.get(remediationCacheKey) ?? undefined;
225
+ }
226
+ else {
227
+ finding.recommendedNpmTransitiveRemediation = await resolveNpmTransitiveRemediation({
228
+ finding,
229
+ graph: npmTransitiveGraph,
230
+ packages,
231
+ directDependencyNames: context?.directDependencyNames,
232
+ offline,
233
+ });
234
+ npmRemediationCache.set(remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null);
235
+ }
236
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version") {
237
+ finding.recommendedParentUpgrade = {
238
+ package: finding.recommendedNpmTransitiveRemediation.package,
239
+ currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
240
+ targetVersion: finding.recommendedNpmTransitiveRemediation.targetVersion ?? "",
241
+ viaPath: finding.recommendedNpmTransitiveRemediation.viaPath,
242
+ vulnerablePackage: finding.pkg.name,
243
+ confidence: "exact-direct-child",
244
+ reason: finding.recommendedNpmTransitiveRemediation.reason,
245
+ };
246
+ continue;
247
+ }
248
+ if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
249
+ finding.recommendedParentUpgrade = undefined;
250
+ continue;
251
+ }
252
+ }
253
+ if (parentUpgradeCache.has(remediationCacheKey)) {
254
+ finding.recommendedParentUpgrade = parentUpgradeCache.get(remediationCacheKey) ?? undefined;
255
+ }
256
+ else {
257
+ finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade(finding, packages, context?.directDependencyNames, { offline });
258
+ parentUpgradeCache.set(remediationCacheKey, finding.recommendedParentUpgrade ?? null);
259
+ }
260
+ }
261
+ catch {
262
+ finding.recommendedNpmTransitiveRemediation = undefined;
263
+ finding.recommendedParentUpgrade = undefined;
264
+ }
265
+ }
266
+ analysisSpinner.succeed("Analyzed vulnerability findings");
193
267
  }
194
- catch {
195
- finding.recommendedParentUpgrade = undefined;
268
+ catch (error) {
269
+ analysisSpinner.fail("Failed while analyzing vulnerability findings");
270
+ throw error;
196
271
  }
197
272
  }
273
+ else if (!offline) {
274
+ await validateDirectFixTargets(findings);
275
+ }
198
276
  return findings;
199
277
  }
200
278
  catch (error) {
@@ -205,9 +283,35 @@ export async function scanPackages(packages, batchSize, options, context) {
205
283
  sourceContext.cleanup();
206
284
  }
207
285
  }
208
- async function validateDirectFixTargets(findings) {
286
+ function createNpmTransitiveGraphFromLockfile(filePath) {
287
+ try {
288
+ const lockGraph = loadNpmLockGraph(filePath, { includePaths: false });
289
+ return {
290
+ nodeIdsFor(name, version) {
291
+ return lockGraph.nodeIdsFor(name, version);
292
+ },
293
+ getNode(nodeId) {
294
+ const node = lockGraph.getNode(nodeId);
295
+ return node
296
+ ? { id: node.id, name: node.name, version: node.version, packagePath: node.packagePath }
297
+ : null;
298
+ },
299
+ childrenFor(nodeId) {
300
+ return lockGraph.childrenFor(nodeId);
301
+ },
302
+ rangeFor(parentNodeId, childName) {
303
+ return lockGraph.rangeFor(parentNodeId, childName);
304
+ },
305
+ };
306
+ }
307
+ catch {
308
+ return null;
309
+ }
310
+ }
311
+ async function validateDirectFixTargets(findings, onFinding) {
209
312
  const directCandidates = findings.filter(finding => finding.vulnerabilities.length > 0);
210
313
  for (const finding of directCandidates) {
314
+ onFinding?.(finding);
211
315
  const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities);
212
316
  const fixedVersionHint = finding.firstFixedVersion;
213
317
  if (lowestKnownResolution.resolvedVersion) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.10.0",
3
+ "version": "1.12.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": {