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