-
-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathdependency-analysis.ts
More file actions
434 lines (386 loc) · 14.4 KB
/
dependency-analysis.ts
File metadata and controls
434 lines (386 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import type {
OsvQueryResponse,
OsvBatchResponse,
OsvVulnerability,
OsvSeverityLevel,
VulnerabilitySummary,
DependencyDepth,
PackageVulnerabilityInfo,
VulnerabilityTreeResult,
DeprecatedPackageInfo,
UrlDependencyInfo,
OsvAffected,
OsvRange,
} from '#shared/types/dependency-analysis'
import { mapWithConcurrency } from '#shared/utils/async'
import { resolveDependencyTree } from './dependency-resolver'
import * as semver from 'semver'
/** Maximum concurrent requests for fetching vulnerability details */
const OSV_DETAIL_CONCURRENCY = 25
/** Package info needed for OSV queries */
interface PackageQueryInfo {
name: string
version: string
depth: DependencyDepth
path: string[]
}
/**
* Query OSV batch API to find which packages have vulnerabilities.
* Returns indices of packages that have vulnerabilities (for follow-up detailed queries).
* @see https://google.github.io/osv.dev/post-v1-querybatch/
*/
async function queryOsvBatch(
packages: PackageQueryInfo[],
): Promise<{ vulnerableIndices: number[]; failed: boolean }> {
if (packages.length === 0) return { vulnerableIndices: [], failed: false }
try {
const response = await $fetch<OsvBatchResponse>('https://api.osv.dev/v1/querybatch', {
method: 'POST',
body: {
queries: packages.map(pkg => ({
package: { name: pkg.name, ecosystem: 'npm' },
version: pkg.version,
})),
},
})
// Find indices of packages that have vulnerabilities
const vulnerableIndices: number[] = []
for (let i = 0; i < response.results.length; i++) {
const result = response.results[i]
if (result?.vulns && result.vulns.length > 0) {
vulnerableIndices.push(i)
}
// Warn if pagination token present (>1000 vulns for single query or >3000 total)
// This is extremely unlikely for npm packages but log for visibility
if (result?.next_page_token) {
// oxlint-disable-next-line no-console -- warn about paginated results
console.warn(
`[dep-analysis] OSV batch result has pagination token for package index ${i} ` +
`(${packages[i]?.name}@${packages[i]?.version}) - some vulnerabilities may be missing`,
)
}
}
return { vulnerableIndices, failed: false }
} catch (error) {
// oxlint-disable-next-line no-console -- log OSV API failures for debugging
console.warn(`[dep-analysis] OSV batch query failed:`, error)
return { vulnerableIndices: [], failed: true }
}
}
/**
* Query OSV for full vulnerability details for a single package.
* Only called for packages known to have vulnerabilities.
*/
async function queryOsvDetails(pkg: PackageQueryInfo): Promise<PackageVulnerabilityInfo | null> {
try {
const response = await $fetch<OsvQueryResponse>('https://api.osv.dev/v1/query', {
method: 'POST',
body: {
package: { name: pkg.name, ecosystem: 'npm' },
version: pkg.version,
},
})
const vulns = response.vulns || []
if (vulns.length === 0) return null
const counts = { total: vulns.length, critical: 0, high: 0, moderate: 0, low: 0 }
const vulnerabilities: VulnerabilitySummary[] = []
const severityOrder: Record<OsvSeverityLevel, number> = {
critical: 0,
high: 1,
moderate: 2,
low: 3,
unknown: 4,
}
const sortedVulns = [...vulns].sort(
(a, b) => severityOrder[getSeverityLevel(a)] - severityOrder[getSeverityLevel(b)],
)
for (const vuln of sortedVulns) {
const severity = getSeverityLevel(vuln)
if (severity === 'critical') counts.critical++
else if (severity === 'high') counts.high++
else if (severity === 'moderate') counts.moderate++
else if (severity === 'low') counts.low++
vulnerabilities.push({
id: vuln.id,
summary: vuln.summary || 'No description available',
severity,
aliases: vuln.aliases || [],
url: getVulnerabilityUrl(vuln),
fixedIn: getFixedVersion(vuln.affected, pkg.name, pkg.version),
})
}
return {
name: pkg.name,
version: pkg.version,
depth: pkg.depth,
path: pkg.path,
vulnerabilities,
counts,
}
} catch (error) {
// oxlint-disable-next-line no-console -- log OSV API failures for debugging
console.warn(`[dep-analysis] OSV detail query failed for ${pkg.name}@${pkg.version}:`, error)
return null
}
}
function getVulnerabilityUrl(vuln: OsvVulnerability): string {
if (vuln.id.startsWith('GHSA-')) {
return `https://github.com/advisories/${vuln.id}`
}
const cveAlias = vuln.aliases?.find(a => a.startsWith('CVE-'))
if (cveAlias) {
return `https://nvd.nist.gov/vuln/detail/${cveAlias}`
}
return `https://osv.dev/vulnerability/${vuln.id}`
}
/**
* Parse OSV range events into introduced/fixed pairs.
* OSV events form a timeline: [introduced, fixed, introduced, fixed, ...]
* A single range can have multiple introduced/fixed pairs representing
* periods where the vulnerability was active, was fixed, and was reintroduced.
* @see https://ossf.github.io/osv-schema/#affectedrangesevents-fields
*/
function parseRangeIntervals(range: OsvRange): Array<{ introduced: string; fixed?: string }> {
const intervals: Array<{ introduced: string; fixed?: string }> = []
let currentIntroduced: string | undefined
for (const event of range.events) {
if (event.introduced !== undefined) {
// Start a new interval (close previous open one if any)
if (currentIntroduced !== undefined) {
intervals.push({ introduced: currentIntroduced })
}
currentIntroduced = event.introduced
} else if (event.fixed !== undefined && currentIntroduced !== undefined) {
intervals.push({ introduced: currentIntroduced, fixed: event.fixed })
currentIntroduced = undefined
}
}
// Handle trailing introduced with no fixed (still vulnerable)
if (currentIntroduced !== undefined) {
intervals.push({ introduced: currentIntroduced })
}
return intervals
}
/**
* Extract the fixed version for a specific package version from vulnerability data.
* Finds all intervals that contain the current version and returns the closest fix,
* preferring a nearby backport over a distant major-version bump.
* @see https://ossf.github.io/osv-schema/#affectedrangesevents-fields
*/
function getFixedVersion(
affected: OsvAffected[] | undefined,
packageName: string,
currentVersion: string,
): string | undefined {
if (!affected) return undefined
// Find all affected entries for this specific package
const packageAffectedEntries = affected.filter(
a => a.package.ecosystem === 'npm' && a.package.name === packageName,
)
// Collect all matching fixed versions across all ranges
const matchingFixedVersions: string[] = []
for (const entry of packageAffectedEntries) {
if (!entry.ranges) continue
for (const range of entry.ranges) {
// Only handle SEMVER ranges (most common for npm)
if (range.type !== 'SEMVER') continue
const intervals = parseRangeIntervals(range)
for (const interval of intervals) {
const introVersion = interval.introduced === '0' ? '0.0.0' : interval.introduced
try {
const afterIntro = semver.gte(currentVersion, introVersion)
const beforeFixed = !interval.fixed || semver.lt(currentVersion, interval.fixed)
if (afterIntro && beforeFixed && interval.fixed) {
matchingFixedVersions.push(interval.fixed)
}
} catch {
continue
}
}
}
}
if (matchingFixedVersions.length === 0) return undefined
if (matchingFixedVersions.length === 1) return matchingFixedVersions[0]
// Return the lowest (closest) fixed version — the smallest bump from the current version
return matchingFixedVersions.sort(semver.compare)[0]
}
function getSeverityLevel(vuln: OsvVulnerability): OsvSeverityLevel {
const dbSeverity = vuln.database_specific?.severity?.toLowerCase()
if (dbSeverity) {
if (dbSeverity === 'critical') return 'critical'
if (dbSeverity === 'high') return 'high'
if (dbSeverity === 'moderate' || dbSeverity === 'medium') return 'moderate'
if (dbSeverity === 'low') return 'low'
}
const severityEntry = vuln.severity?.[0]
if (severityEntry?.score) {
const match = severityEntry.score.match(/(?:^|[/:])(\d+(?:\.\d+)?)$/)
if (match?.[1]) {
const score = parseFloat(match[1])
if (score >= 9.0) return 'critical'
if (score >= 7.0) return 'high'
if (score >= 4.0) return 'moderate'
if (score > 0) return 'low'
}
}
return 'unknown'
}
/**
* Check if a dependency URL is a git: or https: URL that should be flagged.
*/
function isUrlDependency(url: string): boolean {
return (
url.startsWith('git:') ||
url.startsWith('git+') ||
url.startsWith('http:') ||
url.startsWith('https:') ||
url.startsWith('file:')
)
}
/**
* Scan a package's dependencies for git: and https: URLs.
* Returns a map of package names to their URL dependencies.
*/
async function scanUrlDependencies(
name: string,
version: string,
depth: DependencyDepth,
path: string[],
): Promise<UrlDependencyInfo[]> {
try {
const packument = await fetchNpmPackage(name)
const versionData = packument.versions[version]
if (!versionData) return []
const urlDeps: UrlDependencyInfo[] = []
// Include devDependencies only for the root package
const allDeps = depth === 'root'
? {
...versionData.dependencies,
...versionData.optionalDependencies,
...versionData.devDependencies,
}
: {
...versionData.dependencies,
...versionData.optionalDependencies,
}
// URL dependencies are children of the current package, so their depth is one level deeper
const dependencyDepth: DependencyDepth = depth === 'root' ? 'direct' : 'transitive'
for (const [depName, depUrl] of Object.entries(allDeps || {})) {
if (isUrlDependency(depUrl)) {
urlDeps.push({
name: depName,
url: depUrl,
depth: dependencyDepth,
path: [...path, `${depName}@${depUrl}`],
})
}
}
return urlDeps
} catch (error) {
// oxlint-disable-next-line no-console -- log URL dependency scan failures for debugging
console.warn(`[dep-analysis] URL dependency scan failed for ${name}@${version}:`, error)
return []
}
}
/**
* Analyze entire dependency tree for vulnerabilities and deprecated packages.
* Uses OSV batch API for efficient vulnerability discovery, then fetches
* full details only for packages with known vulnerabilities.
*/
export const analyzeDependencyTree = defineCachedFunction(
async (name: string, version: string): Promise<VulnerabilityTreeResult> => {
// Resolve all packages in the tree with depth tracking
const resolved = await resolveDependencyTree(name, version, { trackDepth: true })
// Convert to array with query info
const packages: PackageQueryInfo[] = Array.from(resolved.values(), pkg => ({
name: pkg.name,
version: pkg.version,
depth: pkg.depth!,
path: pkg.path || [],
}))
// Collect deprecated packages (no API call needed - already in packument data)
const deprecatedPackages: DeprecatedPackageInfo[] = [...resolved.values()]
.filter(pkg => pkg.deprecated)
.map(pkg => ({
name: pkg.name,
version: pkg.version,
depth: pkg.depth!,
path: pkg.path || [],
message: pkg.deprecated!,
}))
.sort((a, b) => {
// Sort by depth (root → direct → transitive)
const depthOrder: Record<DependencyDepth, number> = { root: 0, direct: 1, transitive: 2 }
return depthOrder[a.depth] - depthOrder[b.depth]
})
// Scan for git: and https: URL dependencies in all packages
const urlDepResults = await mapWithConcurrency(
packages,
pkg => scanUrlDependencies(pkg.name, pkg.version, pkg.depth, pkg.path),
OSV_DETAIL_CONCURRENCY,
)
const urlDependencies = urlDepResults.flat()
// Step 1: Use batch API to find which packages have vulnerabilities
// This is much faster than individual queries - one request for all packages
const { vulnerableIndices, failed: batchFailed } = await queryOsvBatch(packages)
let vulnerablePackages: PackageVulnerabilityInfo[] = []
let failedQueries = batchFailed ? packages.length : 0
if (!batchFailed && vulnerableIndices.length > 0) {
// Step 2: Fetch full vulnerability details only for packages with vulns
// This is typically a small fraction of total packages
const detailResults = await mapWithConcurrency(
vulnerableIndices,
i => queryOsvDetails(packages[i]!),
OSV_DETAIL_CONCURRENCY,
)
for (const result of detailResults) {
if (result) {
vulnerablePackages.push(result)
} else {
failedQueries++
}
}
}
// Sort by depth (root → direct → transitive), then by severity
const depthOrder: Record<DependencyDepth, number> = { root: 0, direct: 1, transitive: 2 }
vulnerablePackages.sort((a, b) => {
if (a.depth !== b.depth) return depthOrder[a.depth] - depthOrder[b.depth]
if (a.counts.critical !== b.counts.critical) return b.counts.critical - a.counts.critical
if (a.counts.high !== b.counts.high) return b.counts.high - a.counts.high
if (a.counts.moderate !== b.counts.moderate) return b.counts.moderate - a.counts.moderate
return b.counts.total - a.counts.total
})
// Aggregate total counts
const totalCounts = { total: 0, critical: 0, high: 0, moderate: 0, low: 0 }
for (const pkg of vulnerablePackages) {
totalCounts.total += pkg.counts.total
totalCounts.critical += pkg.counts.critical
totalCounts.high += pkg.counts.high
totalCounts.moderate += pkg.counts.moderate
totalCounts.low += pkg.counts.low
}
// Log if batch query failed entirely
if (batchFailed) {
// oxlint-disable-next-line no-console -- critical error logging
console.error(
`[dep-analysis] Critical: OSV batch query failed for ${name}@${version} (${packages.length} packages)`,
)
}
return {
package: name,
version,
vulnerablePackages,
deprecatedPackages,
urlDependencies,
totalPackages: packages.length,
failedQueries,
totalCounts,
}
},
{
maxAge: 60 * 60,
swr: true,
name: 'dependency-analysis',
getKey: (name: string, version: string) => `v3:${name}@${version}`,
},
)