import { getRemediationPaths } from "./utils/finding.js"; import type { CacheFile, FetchLike, Finding, NpmTransitiveGraph, OsvVuln, PackageRef, ParentUpgradeBlocker, ParsedOptions, ScanCompleteness, ScanDiagnostic, ScanDiagnosticCode, ScanInput } from "./types.js"; import { findParentUpgradeBlockers } from "./remediation/parent-upgrade-blockers.js"; import { readWorkspaceMemberManifests } from "./utils/package-json.js"; import { fetchEpssScores } from "./epss/client.js"; import type { PublishedFixVersionResolution } from "./remediation/npm-registry.js"; import { chunk, runWithConcurrency, uniquePathArrays } from "./utils/array.js"; import { isPrivateRegistrySource, isGitSource, hasCommitShaPinning } from "./utils/advisory.js"; import { collapseAliasedDuplicates, extractCveAliases, hasMaliciousAdvisory } from "./utils/vuln.js"; import { compareVersions, isPep440Ecosystem, isPreReleaseVersion, looksLikeVersion, normalizeAdvisoryVersion, normalizePep503PackageName } from "./utils/version.js"; import { pep440UnreadableApplies, readPep440Range, versionInPep440Window, type Pep440UnreadableBoundary, type Pep440Window } from "./utils/versions/osv-range.js"; import { pep440FinalRelease } from "./utils/versions/pep440.js"; import { loadCache, saveCache, isEntryStale } from "./osv/cache.js"; import { osvCacheKey } from "./utils/osv-endpoint.js"; import { maxSeverity } from "./osv/severity.js"; import { createSpinner } from "./output/spinner.js"; import { OsvAdvisorySource } from "./advisory/osv-advisory-source.js"; import { AdvisorySource } from "./advisory/advisory-source.js"; import { LocalAdvisorySource } from "./advisory/local-advisory-source.js"; import { NpmAdvisoryResponseError, queryNpmAdvisoryGaps } from "./advisory/npm-advisory-source.js"; import { AdvisoryDbMetadata, LocalAdvisoryDatabase } from "./advisory/local-db.js"; import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js"; import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js"; import { configureNpmRegistry, configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, runWithObserver, } from "./remediation/npm-registry.js"; import { countBySeverity } from "./utils/severity.js"; import { isNpmLockSource, packageManagerForSource } from "./utils/package-manager-source.js"; import { type LockParentGraph, resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry, } from "./remediation/npm-transitive-resolution.js"; import { resolveChainFix } from "./remediation/transitive-chain-resolver.js"; import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js"; import { loadPnpmLockGraph } from "./parsers/pnpm-lock-graph.js"; import { loadYarnLockGraph } from "./parsers/yarn-lock-graph.js"; import { loadBunLockGraph } from "./parsers/bun-lock-graph.js"; import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js"; import { buildNpmWorkspaceMap } from "./parsers/package-lock.js"; import { buildBunWorkspaceMap } from "./parsers/bun-lock.js"; import { pluralize } from "./utils/string.js"; import { npmLsCommand, UNSAFE_LS_INSTRUCTION } from "./utils/shell-quote.js"; import path from "node:path"; import { type DebugLogger } from "./output/debug.js"; import { resolveRegistryConfig } from "./utils/registry-config.js"; import { extractErrorMessage } from "./utils/network.js"; import { sanitizeOutputString } from "./utils/sanitize.js"; import { logWarn } from "./output/formatters.js"; import { formatDiagnosticMessage, isCompleteGivenDiagnostics } from "./scan/completeness.js"; import { resolveAdvisoryDetail } from "./advisory/detail-resolution.js"; import { loadPypiTargetAdvisories, targetAdvisoryKey, type PypiTargetAdvisories } from "./advisory/pypi-target-advisories.js"; import { packageInstanceKey, registryPackage, registryPackageName } from "./utils/package-identity.js"; type ScanClassificationContext = { directDependencyNames?: ReadonlySet | null; scanSource?: ScanInput["source"]; scanFilePath?: string | null; }; type AdvisorySourceContext = { advisorySource: AdvisorySource; offline: boolean; sourceLabel: string; advisoryDbMetadata: AdvisoryDbMetadata | null; advisoryDbIsStale: boolean; cleanup: () => void; }; /** * Advisory id namespaces OSV does not serve. Ids with these prefixes come from * a different source, so OSV failing to resolve them is expected and must not * be reported as missing detail. */ const OSV_FOREIGN_ID_PREFIXES = ["NPM-"] as const; type PackageMatch = { pkg: PackageRef; vulnIds: string[]; unreadable?: boolean }; export function createAdvisorySource(options?: { osvUrl?: string; offline?: boolean; offlineDb?: string; debugLog?: DebugLogger; fetchImpl?: FetchLike; }): AdvisorySourceContext { const offline = !!options?.offline || !!options?.offlineDb; if (offline) { const dbPath = getDefaultAdvisoryDbPath(options?.offlineDb); const db = new LocalAdvisoryDatabase(dbPath, { readonly: true }); return { advisorySource: new LocalAdvisorySource(db), offline: true, sourceLabel: `local advisory database (${dbPath})`, advisoryDbMetadata: db.getMetadata(), advisoryDbIsStale: isAdvisoryDbStale(db.getMetadata()), cleanup: () => db.close(), }; } return { advisorySource: new OsvAdvisorySource(options?.osvUrl, options?.debugLog, options?.fetchImpl), offline: false, sourceLabel: options?.osvUrl ? `custom OSV endpoint (${options.osvUrl})` : "OSV + npm registry advisory (https://api.osv.dev)", advisoryDbMetadata: null, advisoryDbIsStale: false, cleanup: () => {}, }; } // Python transitive remediation arrives with the parent-range check; the npm resolver must never see PyPI names. function canUseNpmResolver(finding: Finding): boolean { return !isPep440Ecosystem(finding.pkg.ecosystem); } function getPackageCacheKey(pkg: PackageRef): string { return `${pkg.ecosystem}:${registryPackageName(pkg)}@${pkg.version}`; } async function loadPypiTargetAdvisoriesWithSpinner( packages: PackageRef[], params: Omit[0], "packages" | "osvUrl"> & { options: ParsedOptions }, ): Promise { if (!packages.some(pkg => isPep440Ecosystem(pkg.ecosystem))) return new Map(); const { options, ...lookup } = params; const spinner = createSpinner("Loading every advisory for Python packages to check fix targets...", options); const loaded = await loadPypiTargetAdvisories({ packages, ...lookup, osvUrl: options.osvUrl }); const failed = [...loaded.values()].filter(vulns => vulns === null).length; if (failed > 0) { spinner.warn(`Could not load every advisory for ${failed} Python ${pluralize(failed, "package")}; no fix target is confirmed for ${failed === 1 ? "it" : "them"}`); } else { spinner.succeed(`Loaded every advisory for ${loaded.size} Python ${pluralize(loaded.size, "package")}`); } return loaded; } // A stale cached copy keeps a finding reported (#1456) but can describe an // older affected window, so it never confirms a PyPI upgrade target. function withoutStaleDetails(vulnMap: Map, staleIds: Map): Map { if (staleIds.size === 0) return vulnMap; return new Map([...vulnMap].filter(([id]) => !staleIds.has(id))); } function mergeResultsByPackage(results: PackageMatch[]): PackageMatch[] { const map = new Map(); for (const result of results) { const key = packageInstanceKey(result.pkg); const existing = map.get(key); if (existing) { for (const id of result.vulnIds) { if (!existing.vulnIds.includes(id)) existing.vulnIds.push(id); } if (result.unreadable) existing.unreadable = true; } else { map.set(key, { pkg: result.pkg, vulnIds: [...result.vulnIds], ...(result.unreadable ? { unreadable: true } : {}), }); } } return [...map.values()]; } type NpmAdvisoryPass = { advisories: Array<{ pkg: PackageRef; vulns: OsvVuln[] }>; failureCount: number; malformedCount: number; cacheChanged: boolean; }; async function loadNpmAdvisories( packages: PackageRef[], cache: CacheFile, { fetchImpl, offline, noCache, log }: { fetchImpl?: FetchLike; offline: boolean; noCache?: boolean; log: DebugLogger }, ): Promise { const advisories: NpmAdvisoryPass["advisories"] = []; const result = { advisories, failureCount: 0, malformedCount: 0, cacheChanged: false }; if (offline) return result; const nowMs = Date.now(); const cachedAt = new Date(nowMs).toISOString(); const uncached: PackageRef[] = []; for (const pkg of packages) { if (pkg.ecosystem !== "npm") continue; const cached = noCache ? undefined : cache.npmAdvisoryEntries[getPackageCacheKey(pkg)]; if (cached && !isEntryStale(cached, nowMs)) advisories.push({ pkg, vulns: cached.vulns }); else uncached.push(pkg); } if (uncached.length === 0) return result; const malformedPackages = new Set(); let fetched: Awaited>; try { fetched = await queryNpmAdvisoryGaps(uncached.map(registryPackage), { fetchImpl, offline, debugLog: log, onMalformedPackage: name => malformedPackages.add(name), }); } catch (error) { if (error instanceof NpmAdvisoryResponseError) result.malformedCount = uncached.length; else result.failureCount = uncached.length; log("npm advisory query failed", { error: extractErrorMessage(error), packages: uncached.length }); for (const pkg of uncached) { const key = getPackageCacheKey(pkg); if (cache.npmAdvisoryEntries[key]) { delete cache.npmAdvisoryEntries[key]; result.cacheChanged = true; } } return result; } result.malformedCount = uncached.filter(pkg => malformedPackages.has(registryPackageName(pkg))).length; for (const pkg of uncached) { const vulns = fetched.find(row => row.pkg.name === registryPackageName(pkg) && row.pkg.version === pkg.version)?.vulns ?? []; const key = getPackageCacheKey(pkg); if (malformedPackages.has(registryPackageName(pkg))) delete cache.npmAdvisoryEntries[key]; else cache.npmAdvisoryEntries[key] = { vulns, cachedAt }; advisories.push({ pkg, vulns }); } result.cacheChanged = true; return result; } export async function scanPackages( packages: PackageRef[], batchSize: number, options: ParsedOptions, context?: ScanClassificationContext, debugLog?: DebugLogger, fetchImpl?: FetchLike, ): Promise<{ findings: Finding[]; completeness: ScanCompleteness }> { const log: DebugLogger = debugLog ?? (() => {}); const sourceContext = createAdvisorySource({ osvUrl: options.osvUrl, offline: options.offline, offlineDb: options.offlineDb, debugLog: log, fetchImpl, }); const offline = sourceContext.offline; const cacheDirOverride = options.cacheDir; const spinner = createSpinner( offline ? "Scanning dependencies against the local advisory database..." : "Scanning dependencies against OSV...", options, ); const advisorySource = sourceContext.advisorySource; if (!offline && options.debug) { configureNpmRegistryDebug(log); } // Point metadata lookups at the registry this project installs from, so a fix // version is validated against the registry the user would actually install it // from rather than against public npm. Unconfigured projects resolve to the // public registry, which is the previous behaviour. const registryConfig = resolveRegistryConfig({ projectPath: context?.scanFilePath ? path.dirname(context.scanFilePath) : process.cwd(), packageManager: packageManagerForSource(context?.scanSource), }); configureNpmRegistry(registryConfig); if (options.debug) { log("Registry config", { registry: registryConfig.registry, scopes: Object.keys(registryConfig.scopes), sourceFile: registryConfig.sourceFile, }); } const cache = loadCache(cacheDirOverride, options.debug ? log : undefined); try { const results: PackageMatch[] = []; const unreadableBoundaryPackageLabels: string[] = []; const uncachedPackages: PackageRef[] = []; if (!offline) { const nowMs = Date.now(); let hits = 0; let misses = 0; for (const pkg of packages) { const cacheKey = osvCacheKey(getPackageCacheKey(pkg), options.osvUrl); if (!options.noCache) { const cached = cache.queryEntries[cacheKey]; if (cached && !isEntryStale(cached, nowMs)) { hits += 1; if (cached.vulnIds.length > 0) { results.push({ pkg, vulnIds: cached.vulnIds }); } continue; } } misses += 1; uncachedPackages.push(pkg); } const chunks = chunk(uncachedPackages, batchSize); const reason = options.noCache ? "no-cache mode" : "stale or missing entry"; log("Cache check", { hits, misses, reason, uncachedBatches: chunks.length }); spinner.update(`Scanning OSV in ${chunks.length} parallel ${pluralize(chunks.length, "batch", "batches")}...`); const osvScanStartedAt = Date.now(); let batchCounter = 0; const allAdvisoryResults = await runWithConcurrency( chunks, 5, c => { batchCounter += 1; const batchId = `b-${String(batchCounter).padStart(2, "0")}`; return advisorySource.queryBatch(c.map(registryPackage), { batchId }); }, { onError: "stop" }, ); const cachedAt = new Date().toISOString(); for (let i = 0; i < chunks.length; i++) { const chunkItems = chunks[i]!; const rows = allAdvisoryResults[i] ?? []; for (let j = 0; j < chunkItems.length; j++) { const pkg = chunkItems[j]!; const row = rows[j]; if (row && (row.package !== registryPackageName(pkg) || row.version !== pkg.version)) { throw new Error( `OSV result identity mismatch at index ${j}: expected ${registryPackageName(pkg)}@${pkg.version}, got ${row.package}@${row.version}`, ); } const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean); cache.queryEntries[osvCacheKey(getPackageCacheKey(pkg), options.osvUrl)] = { vulnIds, cachedAt }; if (vulnIds.length > 0) { results.push({ pkg, vulnIds }); } } } if (chunks.length > 0) { log("OSV scan complete", { totalBatches: chunks.length, totalDurationMs: Date.now() - osvScanStartedAt, packagesWithVulns: results.length, }); } if (chunks.length === 0) { spinner.succeed("Loaded package matches from cache"); } else { spinner.succeed(`Queried OSV in ${chunks.length} ${pluralize(chunks.length, "batch", "batches")}`); } } else { const advisoryResult = await advisorySource.queryBatch(packages.map(registryPackage), { batchId: "offline" }); const rows = advisoryResult ?? []; for (let i = 0; i < packages.length; i++) { const pkg = packages[i]; const row = rows[i]; const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean); const unreadable = row?.unreadableBoundary === true; if (unreadable) unreadableBoundaryPackageLabels.push(packageLabel(pkg)); if (vulnIds.length > 0) { results.push({ pkg, vulnIds, ...(unreadable ? { unreadable: true } : {}) }); } } spinner.succeed("Loaded package matches from the local advisory database"); } const vulnMap = new Map(); const npmAdvisories = await loadNpmAdvisories(packages, cache, { fetchImpl, offline, noCache: options.noCache, log, }); const { cacheChanged: wroteNpmAdvisoryEntries, failureCount: npmAdvisoryFailureCount, malformedCount: npmAdvisoryMalformedCount } = npmAdvisories; const existingVulnIds = new Set(results.flatMap(result => result.vulnIds)); for (const { pkg, vulns } of npmAdvisories.advisories) { const newVulns = vulns.filter(vuln => !existingVulnIds.has(vuln.id)); if (newVulns.length === 0) continue; results.push({ pkg, vulnIds: newVulns.map(vuln => vuln.id) }); for (const vuln of newVulns) vulnMap.set(vuln.id, vuln); } const idSet = new Set(results.flatMap(r => r.vulnIds)); const transientDetailIds = new Set(); const offlineMissingDetailIds = new Set(); const confirmedMissingDetailIds = new Set(); // Advisory id -> when the cached copy that stood in for a failed lookup was fetched. const staleDetailCachedAt = new Map(); if (idSet.size > 0 && !offline) { // Only ask OSV for ids OSV can own. The npm registry advisory source // (#1056) contributes NPM-prefixed ids from its own namespace, and // api.osv.dev/v1/vulns/NPM-... is a 404 by definition. Sending them // anyway made every online scan of a project carrying npm-sourced // advisories report `partial` with "findings may be incomplete", when // nothing was missing: the detail was looked for in the wrong database. const ids = [...idSet].filter( (id) => !OSV_FOREIGN_ID_PREFIXES.some((prefix) => id.startsWith(prefix)), ); const detailSpinner = createSpinner("Fetching vulnerability details...", options); try { const nowMs = Date.now(); const uncachedIds: string[] = []; for (const id of ids) { // Same gap as the npm advisory block above: the advisory detail cache // was read regardless of the flag, so a --no-cache run could still // restore a previously cached detail, including a negative entry that // marks the scan incomplete. The write below stays unguarded, as it is // for the other caches (#1166). const cached = options.noCache ? undefined : cache.entries[osvCacheKey(id, options.osvUrl)]; if (cached && !isEntryStale(cached, nowMs)) { if (cached.vuln) { vulnMap.set(id, cached.vuln); } else { // Negative cache hit: the record was confirmed missing earlier. // The detail is still unresolved, so the scan stays incomplete. confirmedMissingDetailIds.add(id); } } else { if (!vulnMap.has(id)) { uncachedIds.push(id); } } } if (uncachedIds.length > 0) { detailSpinner.update(`Fetching ${uncachedIds.length} vulnerability details...`); const cachedAt = new Date().toISOString(); await runWithConcurrency(uncachedIds, 10, async (id) => { // --no-cache promises fresh data only, so it gets the retries but // never the stale fallback. const staleEntry = options.noCache ? undefined : cache.entries[osvCacheKey(id, options.osvUrl)]; const resolution = await resolveAdvisoryDetail({ id, fetchDetail: (advisoryId) => advisorySource.getVuln(advisoryId), staleEntry, }); switch (resolution.kind) { case "fresh": vulnMap.set(id, resolution.vuln); cache.entries[osvCacheKey(id, options.osvUrl)] = { vuln: resolution.vuln, cachedAt }; break; case "stale": // Left as it is in the cache, so it keeps its real age. vulnMap.set(id, resolution.vuln); staleDetailCachedAt.set(id, resolution.cachedAt); log("OSV detail served from stale cache", { advisoryId: id, cachedAt: resolution.cachedAt }); break; case "confirmed-missing": confirmedMissingDetailIds.add(id); cache.entries[osvCacheKey(id, options.osvUrl)] = { vuln: null, cachedAt }; log("OSV detail confirmed missing", { advisoryId: id }); break; case "transient": transientDetailIds.add(id); log("OSV detail transient failure", { advisoryId: id, error: extractErrorMessage(resolution.error), }); break; } }); } const successCount = ids.filter(id => vulnMap.has(id)).length; const failureCount = ids.length - successCount; if (failureCount > 0) { detailSpinner.warn( `Loaded ${successCount}/${ids.length} vulnerability detail ${pluralize(ids.length, "record")} (${failureCount} ${pluralize(failureCount, "failure")})`, ); } else { detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail ${pluralize(ids.length, "record")}`); } } catch (error) { detailSpinner.fail("Failed while fetching vulnerability details"); throw error; } } else if (idSet.size > 0 && offline) { const ids = [...idSet]; const detailSpinner = createSpinner("Loading local advisory details...", options); try { await runWithConcurrency(ids, 10, async (id) => { try { const detail = await advisorySource.getVuln(id); vulnMap.set(id, detail); } catch { offlineMissingDetailIds.add(id); } }); const successCount = ids.filter(id => vulnMap.has(id)).length; const failureCount = ids.length - successCount; if (failureCount > 0) { detailSpinner.warn( `Loaded ${successCount}/${ids.length} local advisory detail ${pluralize(ids.length, "record")} (${failureCount} ${pluralize(failureCount, "missing")})`, ); } else { detailSpinner.succeed(`Loaded ${ids.length} local advisory detail ${pluralize(ids.length, "record")}`); } } catch (error) { detailSpinner.fail("Failed while loading local advisory details"); throw error; } } const pypiTargetAdvisories: PypiTargetAdvisories = offline ? new Map() : await loadPypiTargetAdvisoriesWithSpinner(results.map(result => result.pkg), { advisorySource, cache, noCache: options.noCache, knownDetails: withoutStaleDetails(vulnMap, staleDetailCachedAt), log, options, }); if (!offline && (idSet.size > 0 || wroteNpmAdvisoryEntries)) { saveCache(cache, cacheDirOverride, options.debug ? log : undefined); } const remediationResults = mergeResultsByPackage(results).flatMap(result => result.pkg.npmRemediationCopies?.map(pkg => ({ ...result, pkg })) ?? [result], ); const findings: Finding[] = remediationResults.map(result => { // Collapse advisory records OSV marks as the same vulnerability before // anything downstream counts them, so the terminal, JSON, SARIF, both SBOM // formats and the HTML report all see one list. const vulnerabilities = collapseAliasedDuplicates( result.vulnIds.map(id => vulnMap.get(id)).filter((v): v is OsvVuln => Boolean(v)), ); const unresolvedIds = result.vulnIds.filter(id => !vulnMap.has(id)); const severity = vulnerabilities.length === 0 && unresolvedIds.length > 0 ? "unknown" : maxSeverity(vulnerabilities); const cveAliases = extractCveAliases(vulnerabilities); // Mixed Yarn reachability must retain parent remediation; direct declarations // are carried separately on the resolved package for their own fix targets. const transitivePaths = result.pkg.yarnTransitivePaths ?? []; const mixedYarn = !!result.pkg.yarnDirectWorkspaces?.length && transitivePaths.length > 0; const dependencyPaths = mixedYarn ? uniquePathArrays([...(result.pkg.paths ?? []), ...transitivePaths]) : result.pkg.paths ?? []; const relationship = mixedYarn ? "transitive" : classifyRelationship( dependencyPaths, result.pkg.name, context?.directDependencyNames, result.pkg.workspaceDirect === true, ); const selectedFix = selectFixedVersion( vulnerabilities, registryPackageName(result.pkg), result.pkg.ecosystem, result.pkg.version, // A PyPI package missing from the map (offline, or a source that cannot list // every advisory) has no complete set to check a target against. isPep440Ecosystem(result.pkg.ecosystem) ? pypiTargetAdvisories.get(targetAdvisoryKey(result.pkg)) ?? null : undefined, ); const advisoryBoundaryUnreadable = selectedFix.unreadable || result.unreadable === true; return { pkg: result.pkg, vulnerabilities, severity, cveAliases, dependencyPaths, relationship, firstFixedVersion: advisoryBoundaryUnreadable ? null : selectedFix.version, ...(advisoryBoundaryUnreadable ? { advisoryBoundaryUnreadable: true } : {}), validatedFirstFixedVersion: null, fixVersionValidationNote: advisoryBoundaryUnreadable ? null : selectedFix.note ?? null, fixVersionPublishedAt: null, validatedTargetScannedVersions: null, validatedTargetKnownVulnerableVersions: null, recommendedParentUpgrade: undefined, recommendedNpmTransitiveRemediation: undefined, ...(unresolvedIds.length > 0 ? { unresolvedAdvisoryIds: unresolvedIds } : {}), }; }); // Parent resolvers interpret path segments as registry names. Until they // support aliases, do not let them recommend a different package that // happens to be published under an installed alias's name. const aliasNames = new Set(packages.filter(pkg => pkg.registryName).map(pkg => pkg.name)); // A bundled child is replaced by the parent archive. Its declared range // cannot establish which version a new archive actually ships. const manualRemediationFindings = new Set(findings.filter(finding => finding.relationship === "transitive" && (finding.pkg.npmBundled || getRemediationPaths(finding).some(path => path.some(name => aliasNames.has(name)))), )); const unresolvedDetailIds = idSet.size > 0 ? [...idSet].filter(id => !vulnMap.has(id)) : []; if (unresolvedDetailIds.length > 0) { const transientCount = unresolvedDetailIds.filter(id => transientDetailIds.has(id)).length; const offlineCount = unresolvedDetailIds.filter(id => offlineMissingDetailIds.has(id)).length; const confirmedCount = unresolvedDetailIds.filter(id => confirmedMissingDetailIds.has(id)).length; const otherCount = unresolvedDetailIds.length - transientCount - offlineCount - confirmedCount; const parts: string[] = []; if (transientCount > 0) { parts.push(`${transientCount} from transient failures: re-run to retry`); } if (offlineCount > 0) { parts.push(`${offlineCount} missing from local advisory database: refresh to sync`); } if (confirmedCount > 0) { parts.push(`${confirmedCount} confirmed missing from the OSV API`); } if (otherCount > 0) { parts.push(`${otherCount} could not be resolved`); } logWarn( `⚠ ${unresolvedDetailIds.length} advisory detail ${pluralize(unresolvedDetailIds.length, "lookup")} missing from findings. ${parts.join("; ")}.`, { json: options.json, output: options.output }, ); } for (const finding of findings) { if (hasMaliciousAdvisory(finding.vulnerabilities)) { if (isGitSource(finding.pkg)) { finding.maliciousGitSource = true; finding.maliciousGitSourcePinned = hasCommitShaPinning(finding.pkg); } else if (isPrivateRegistrySource(finding.pkg)) { finding.maliciousUnverifiable = true; } } } const npmTransitiveGraph = isNpmLockSource(context?.scanSource) && context?.scanFilePath ? createNpmTransitiveGraphFromLockfile(context.scanFilePath, log, packages.length) : null; const lockParentGraph = loadLockParentGraph(context?.scanSource, context?.scanFilePath, log); const workspaceMemberNames = readWorkspaceMemberNames(context?.scanFilePath); const npmWorkspaceMap = (() => { try { return isNpmLockSource(context?.scanSource) && context?.scanFilePath ? buildNpmWorkspaceMap(context.scanFilePath) : null; } catch (error) { log("Workspace map", { type: "npm", status: "failed", error: error instanceof Error ? error.message : String(error), }); return null; } })(); if (npmWorkspaceMap) { log("Workspace map", { type: "npm", dependencyCount: npmWorkspaceMap.size, }); } const pnpmWorkspaceMap = (() => { try { return context?.scanSource === "pnpm-lock" && context.scanFilePath ? buildPnpmWorkspaceMap(context.scanFilePath) : null; } catch (error) { log("Workspace map", { type: "pnpm", status: "failed", error: error instanceof Error ? error.message : String(error), }); return null; } })(); if (pnpmWorkspaceMap) { log("Workspace map", { type: "pnpm", dependencyCount: pnpmWorkspaceMap.size, }); } const bunWorkspaceMap = (() => { try { return context?.scanSource === "bun-lock" && context.scanFilePath ? buildBunWorkspaceMap(context.scanFilePath) : null; } catch (error) { log("Workspace map", { type: "bun", status: "failed", error: error instanceof Error ? error.message : String(error), }); return null; } })(); if (bunWorkspaceMap) { log("Workspace map", { type: "bun", dependencyCount: bunWorkspaceMap.size, }); } const lockfileWorkspaceMap = pnpmWorkspaceMap ?? bunWorkspaceMap ?? null; const packumentFailures = new Set(); let registryPolicyBlocked = false; const remediationFailures = new Map(); let chainResolutionFailureCount = 0; let directCount = 0; let transitiveCount = 0; await runWithObserver({ onTransientFailure(name) { packumentFailures.add(name); }, onPolicyBlocked() { registryPolicyBlocked = true; }, }, async () => { const npmRemediationCache = new Map(); const parentUpgradeCache = new Map(); const directValidationCount = offline ? 0 : findings.filter(f => !isPep440Ecosystem(f.pkg.ecosystem)).length; for (const finding of findings) { if (finding.relationship === "direct") directCount++; else if (finding.relationship === "transitive") transitiveCount++; } const transitiveRemediationCount = findings.filter(f => f.relationship === "transitive" && canUseNpmResolver(f)).length; const analysisStepCount = directValidationCount + transitiveRemediationCount; if (analysisStepCount > 0) { const analysisSpinner = createSpinner("Analyzing vulnerability findings...", options); let completedSteps = 0; const updateAnalysisProgress = (phase: string, subject: string) => { completedSteps += 1; analysisSpinner.update( `Analyzing vulnerability findings ${completedSteps}/${analysisStepCount}: ${phase} ${subject}...`, ); }; try { if (!offline) { const npmVersionCacheUpdated = await validateDirectFixTargets(findings, (finding) => { updateAnalysisProgress("validating fix target for", `${finding.pkg.name}@${finding.pkg.version}`); }, { cache, noCache: options.noCache, debugLog: log, advisorySource }); if (npmVersionCacheUpdated) { saveCache(cache, cacheDirOverride, options.debug ? log : undefined); } } // Pre-warm packument cache for all packages needed in the remediation loop. // This converts N sequential registry round-trips into one concurrent burst, // after which the loop runs entirely from the in-memory packument cache. if (!offline) { const packumentsToPrewarm = new Set(); for (const finding of findings) { if (finding.relationship !== "transitive") continue; if (!canUseNpmResolver(finding)) continue; if (manualRemediationFindings.has(finding)) { continue; } packumentsToPrewarm.add(finding.pkg.name); const paths = getRemediationPaths(finding); if (paths.length > 0 && paths[0].length >= 2) { packumentsToPrewarm.add(paths[0][paths[0].length - 2]); } } if (packumentsToPrewarm.size > 0) { await runWithConcurrency([...packumentsToPrewarm], 8, async (name) => { await fetchPackument(name); }); } } for (const finding of findings) { if (finding.relationship !== "transitive") continue; if (!canUseNpmResolver(finding)) continue; updateAnalysisProgress("resolving remediation for", `${finding.pkg.name}@${finding.pkg.version}`); if (finding.pkg.npmBundled) continue; if (manualRemediationFindings.has(finding)) { const lsCommand = npmLsCommand(finding.pkg.name); const lookup = lsCommand ? `Run \`${lsCommand}\`` : UNSAFE_LS_INSTRUCTION; const aliasNote = `Automatic parent remediation is unavailable for paths containing an npm alias. ${lookup} to inspect the declaring dependency, then rescan after updating it.`; finding.fixVersionValidationNote = [finding.fixVersionValidationNote, aliasNote].filter(Boolean).join(" "); continue; } const remediationCacheKey = JSON.stringify({ package: finding.pkg.name, version: finding.pkg.version, dependencyPaths: getRemediationPaths(finding), firstFixedVersion: finding.firstFixedVersion, validatedFirstFixedVersion: finding.validatedFirstFixedVersion ?? null, }); try { if (npmTransitiveGraph) { if (npmRemediationCache.has(remediationCacheKey)) { finding.recommendedNpmTransitiveRemediation = npmRemediationCache.get(remediationCacheKey) ?? undefined; } else { finding.recommendedNpmTransitiveRemediation = await resolveNpmTransitiveRemediation({ finding, graph: npmTransitiveGraph, packages, directDependencyNames: context?.directDependencyNames, offline, workspaceMap: npmWorkspaceMap, }); npmRemediationCache.set( remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null, ); } if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version") { finding.recommendedParentUpgrade = { package: finding.recommendedNpmTransitiveRemediation.package, currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion, targetVersion: finding.recommendedNpmTransitiveRemediation.targetVersion ?? "", viaPath: finding.recommendedNpmTransitiveRemediation.viaPath, vulnerablePackage: finding.pkg.name, confidence: "verified", reason: finding.recommendedNpmTransitiveRemediation.reason, }; finding.parentUpgradeBlockers = await blockersForParentUpgrade(finding, { packages, workspaceMemberNames, npmGraph: npmTransitiveGraph, }); continue; } if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") { finding.recommendedParentUpgrade = undefined; continue; } } if (!offline && !npmTransitiveGraph) { if (npmRemediationCache.has(remediationCacheKey)) { finding.recommendedNpmTransitiveRemediation = npmRemediationCache.get(remediationCacheKey) ?? undefined; } else { finding.recommendedNpmTransitiveRemediation = await resolveTransitiveRemediationViaRegistry({ finding, packages, directDependencyNames: context?.directDependencyNames, workspaceMap: lockfileWorkspaceMap, parentGraph: lockParentGraph, }); npmRemediationCache.set( remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null, ); } if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") { finding.recommendedParentUpgrade = undefined; continue; } } if (parentUpgradeCache.has(remediationCacheKey)) { finding.recommendedParentUpgrade = parentUpgradeCache.get(remediationCacheKey) ?? undefined; } else { finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade( finding, packages, context?.directDependencyNames, { offline }, ); parentUpgradeCache.set(remediationCacheKey, finding.recommendedParentUpgrade ?? null); } finding.parentUpgradeBlockers = await blockersForParentUpgrade(finding, { packages, workspaceMemberNames, npmGraph: npmTransitiveGraph, lockParentGraph, }); } catch (error) { const packageName = finding.pkg.name; remediationFailures.set(packageName, (remediationFailures.get(packageName) ?? 0) + 1); log("Remediation failed", { package: packageName, version: finding.pkg.version, error: error instanceof Error ? error.message : String(error), }); finding.recommendedNpmTransitiveRemediation = undefined; finding.recommendedParentUpgrade = undefined; } } analysisSpinner.succeed("Analyzed vulnerability findings"); // Chain fix resolution: pre-compute validated chain for transitive findings const chainPm = packageManagerForSource(context?.scanSource); if (chainPm) { await Promise.all( findings .filter(f => f.relationship === "transitive" && canUseNpmResolver(f) && getRemediationPaths(f).length && !manualRemediationFindings.has(f)) .map(async (finding) => { try { finding.chainResolution = await resolveChainFix( finding, packages, chainPm, { offline, workspaceMemberNames, parentGraph: lockParentGraph }, ); } catch (error) { chainResolutionFailureCount += 1; log("Chain resolution failed", { package: finding.pkg.name, version: finding.pkg.version, error: error instanceof Error ? error.message : String(error), }); finding.chainResolution = null; } }), ); } } catch (error) { analysisSpinner.fail("Failed while analyzing vulnerability findings"); throw error; } } else if (!offline) { const npmVersionCacheUpdated = await validateDirectFixTargets(findings, undefined, { cache, noCache: options.noCache, debugLog: log, advisorySource, }); if (npmVersionCacheUpdated) { saveCache(cache, cacheDirOverride, options.debug ? log : undefined); } } }); if (registryPolicyBlocked && registryConfig.sourceFile) { const source = path.basename(registryConfig.sourceFile); console.warn(`Warning: The registry from ${source} was blocked because repository settings cannot use plain HTTP or private addresses. To use it, set NPM_CONFIG_REGISTRY for the scan, or on Windows remove the registry from the project's config and set it in your user-level config (~/.npmrc or ~/.yarnrc.yml).`); } const severityCounts = countBySeverity(findings); log("Findings classified", { total: findings.length, direct: directCount, transitive: transitiveCount, critical: severityCounts.critical, high: severityCounts.high, medium: severityCounts.medium, low: severityCounts.low, unknown: severityCounts.unknown, }); const diagnostics = buildCompletenessDiagnostics({ npmAdvisoryFailureCount, npmAdvisoryMalformedCount, transientDetailIds, offlineMissingDetailIds, confirmedMissingDetailIds, staleDetailCachedAt, packumentFailures, remediationFailures, chainResolutionFailureCount, unreadableBoundaryPackageLabels, unreadableFixPackageLabels: findings.filter(finding => finding.advisoryBoundaryUnreadable).map(finding => packageLabel(finding.pkg)), }); const completeness: ScanCompleteness = { complete: isCompleteGivenDiagnostics(diagnostics), diagnostics, }; if (!offline) { await enrichWithEpssScores(findings, fetchImpl); } return { findings, completeness }; } catch (error) { spinner.fail("Scan failed"); throw error; } finally { sourceContext.cleanup(); } } // Direct dependencies that keep the vulnerable copy installed after the // recommended parent upgrade, judged against the first safe version (#1457). async function blockersForParentUpgrade( finding: Finding, graphs: { packages: PackageRef[]; workspaceMemberNames: ReadonlySet; npmGraph?: NpmTransitiveGraph | null; lockParentGraph?: LockParentGraph | null; }, ): Promise { const upgrade = finding.recommendedParentUpgrade; // Without a known fixed version, test the child version the upgrade moves to. const safeVersion = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion ?? finding.recommendedNpmTransitiveRemediation?.targetChildVersion; if (!upgrade || !safeVersion) return undefined; const blockers = await findParentUpgradeBlockers({ childName: finding.pkg.name, childVersion: finding.pkg.version, targetChildVersion: safeVersion, upgradedParent: upgrade.package, packages: graphs.packages, workspaceMemberNames: graphs.workspaceMemberNames, npmGraph: graphs.npmGraph, lockParentGraph: graphs.lockParentGraph, }); return blockers.length > 0 ? blockers : undefined; } function readWorkspaceMemberNames(scanFilePath: string | null | undefined): Set { if (!scanFilePath) return new Set(); return new Set(readWorkspaceMemberManifests(path.dirname(scanFilePath)) .map(member => member.manifest.name) .filter((name): name is string => typeof name === "string")); } function createNpmTransitiveGraphFromLockfile( filePath: string, log: DebugLogger, packageCount: number, ): NpmTransitiveGraph | null { try { const lockGraph = loadNpmLockGraph(filePath, { includePaths: false }); log("npm transitive graph", { status: "built", nodes: packageCount }); return { nodeIdsFor(name: string, version: string | null) { return lockGraph.nodeIdsFor(name, version); }, getNode(nodeId: string) { return lockGraph.getNode(nodeId); }, childrenFor(nodeId: string) { return lockGraph.childrenFor(nodeId); }, rangeFor(parentNodeId: string, childName: string) { return lockGraph.rangeFor(parentNodeId, childName); }, parentsFor(nodeId: string) { return lockGraph.parentsFor(nodeId); }, peerRangesFor(nodeId: string) { return lockGraph.peerRangesFor?.(nodeId) ?? []; }, }; } catch (error) { log("npm transitive graph", { status: "failed", error: error instanceof Error ? error.message : String(error), }); return null; } } // Every parent of each package, for the lockfiles whose remediation goes through // the registry. A within-range update has to suit all of them (#1291). Without // it the route falls back to the one parent the recorded path names. function loadLockParentGraph( source: ScanInput["source"] | undefined, filePath: string | undefined | null, log: DebugLogger, ): LockParentGraph | null { if (!filePath) return null; try { if (source === "pnpm-lock") return loadPnpmLockGraph(filePath); if (source === "yarn-lock") return loadYarnLockGraph(filePath); if (source === "bun-lock") return loadBunLockGraph(filePath); } catch (error) { log("lock parent graph", { status: "failed", error: extractErrorMessage(error) }); } return null; } async function validateDirectFixTargets( findings: Finding[], onFinding?: (finding: Finding) => void, options?: { cache: ReturnType; noCache?: boolean; debugLog?: DebugLogger; advisorySource?: AdvisorySource; }, ): Promise { const directCandidates = findings.filter(finding => finding.vulnerabilities.length > 0 && !isPep440Ecosystem(finding.pkg.ecosystem)); const results = await runWithConcurrency( directCandidates, 8, async (finding) => { onFinding?.(finding); return validateOneDirectFixTarget(finding, options); }, ); return results.some(Boolean); } async function validateOneDirectFixTarget( finding: Finding, options?: { cache: ReturnType; noCache?: boolean; debugLog?: DebugLogger; advisorySource?: AdvisorySource; }, ): Promise { if (isPep440Ecosystem(finding.pkg.ecosystem) || finding.advisoryBoundaryUnreadable) return false; let npmVersionCacheUpdated = false; const debugLog = options?.debugLog; const logFixValidation = () => { debugLog?.("Fix validation", { package: finding.pkg.name, installed: finding.pkg.version, resolvedFixVersion: finding.validatedFirstFixedVersion, verified: Boolean(finding.validatedFirstFixedVersion), }); }; // The advisory source re-checks the proposed version for advisories // introduced above the installed one, which never matched this finding. const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion( registryPackageName(finding.pkg), finding.pkg.version, finding.vulnerabilities, { advisorySource: options?.advisorySource, proposedVersion: finding.firstFixedVersion }, ); const fixedVersionHint = finding.firstFixedVersion; const setPublishedDate = ( resolution: PublishedFixVersionResolution, ) => { const date = resolution.publishedAt; finding.fixVersionPublishedAt = date; if (!date || !options?.cache) return; const cacheKey = `${registryPackageName(finding.pkg)}@${finding.validatedFirstFixedVersion!}`; const existing = options.cache.npmVersionEntries?.[cacheKey]; if (!options.noCache && existing?.publishedAt === date) return; options.cache.npmVersionEntries ??= {}; options.cache.npmVersionEntries[cacheKey] = { publishedAt: date, cachedAt: new Date().toISOString(), }; npmVersionCacheUpdated = true; }; if (lowestKnownResolution.resolvedVersion && lowestKnownResolution.verified) { finding.validatedFirstFixedVersion = lowestKnownResolution.resolvedVersion; finding.validatedTargetScannedVersions = lowestKnownResolution.candidatesChecked; finding.validatedTargetKnownVulnerableVersions = lowestKnownResolution.candidatesKnownVulnerable; if (!fixedVersionHint || fixedVersionHint === lowestKnownResolution.resolvedVersion) { finding.fixVersionValidationNote = null; setPublishedDate(lowestKnownResolution); logFixValidation(); return npmVersionCacheUpdated; } const hintResolution = await resolvePublishedFixVersion(registryPackageName(finding.pkg), fixedVersionHint); if ( hintResolution.resolvedVersion === lowestKnownResolution.resolvedVersion && hintResolution.note ) { finding.fixVersionValidationNote = hintResolution.note; finding.advisoryHintUnavailable = hintResolution.advisoryHintUnavailable ?? false; // date is for the validated version, not the hint setPublishedDate(lowestKnownResolution); logFixValidation(); return npmVersionCacheUpdated; } finding.fixVersionValidationNote = `Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package ${pluralize(lowestKnownResolution.candidatesChecked, "version")} above current version (${lowestKnownResolution.candidatesKnownVulnerable} still known vulnerable); using lowest known non-vulnerable version ${lowestKnownResolution.resolvedVersion}.`; setPublishedDate(lowestKnownResolution); logFixValidation(); return npmVersionCacheUpdated; } if (!fixedVersionHint) { finding.validatedFirstFixedVersion = null; finding.fixVersionValidationNote = lowestKnownResolution.note; finding.validatedTargetScannedVersions = null; finding.validatedTargetKnownVulnerableVersions = null; finding.fixVersionPublishedAt = null; logFixValidation(); return npmVersionCacheUpdated; } const resolution = await resolvePublishedFixVersion(registryPackageName(finding.pkg), fixedVersionHint); // Publication confirms availability, not that every advisory is fixed. finding.validatedFirstFixedVersion = null; finding.fixVersionValidationNote = [ lowestKnownResolution.note ?? `A non-vulnerable version could not be confirmed for ${finding.pkg.name}.`, resolution.note, ].filter(Boolean).join(" "); // The note above is two notes joined, so the only honest way to know whether // the hint was missing from the registry is to carry the resolver's own answer. finding.advisoryHintUnavailable = resolution.advisoryHintUnavailable ?? false; finding.validatedTargetScannedVersions = null; finding.validatedTargetKnownVulnerableVersions = null; finding.fixVersionPublishedAt = null; logFixValidation(); return npmVersionCacheUpdated; } function isAdvisoryDbStale(metadata: AdvisoryDbMetadata): boolean { if (!metadata.lastSyncAt) { return true; } const timestamp = Date.parse(metadata.lastSyncAt); if (Number.isNaN(timestamp)) { return true; } return Date.now() - timestamp > ADVISORY_DB_STALE_AFTER_MS; } function classifyRelationship( paths: string[][], packageName?: string, directDependencyNames?: ReadonlySet | null, workspaceDirect = false, ): "direct" | "transitive" | "unknown" { if (packageName && directDependencyNames?.has(packageName)) { // The package name is declared as a direct dependency. But when multiple versions // of the same package are installed (one direct, one transitive), the name alone // is not enough - we need to verify this specific installed version is the direct // one. A direct install has a path ["project", name], or // ["project", workspaceName, name] with parser-confirmed workspace identity. // A registry parent can share a workspace name, so the display path alone // cannot prove that this resolved version is a workspace dependency. // Longer paths describe a different (transitive) installed version. if (paths.length === 0) return "direct"; // no path data - trust the name const hasDirectPath = paths.some(p => p.length <= 2 || (p.length === 3 && workspaceDirect)); return hasDirectPath ? "direct" : "transitive"; } if (paths.length === 0) return "unknown"; if (directDependencyNames) return "transitive"; const shortest = Math.min(...paths.map(p => p.length)); if (shortest <= 2) return "direct"; return "transitive"; } /** * Does this `affected[]` entry describe the package being scanned? * * Permissive by design, matching `resolveLowestKnownNonVulnerableVersion` in * remediation/npm-registry.ts: an entry is excluded only when it positively * identifies a *different* package. An entry that omits the name (or the * ecosystem) is kept, so an advisory with sparse metadata still contributes * its fix rather than silently dropping to "no fix known". */ function affectedEntryMatchesPackage( affected: NonNullable[number], packageName: string, ecosystem: string, ): boolean { const affectedName = affected.package?.name; if (affectedName) { if (isPep440Ecosystem(ecosystem)) { if (normalizePep503PackageName(affectedName) !== normalizePep503PackageName(packageName)) { return false; } } else if (affectedName !== packageName) { return false; } } const affectedEcosystem = affected.package?.ecosystem?.toLowerCase(); if (affectedEcosystem && affectedEcosystem !== ecosystem.toLowerCase()) return false; return true; } /** * True when `version` sits inside the half-open window `[introduced, fixed)`. * * `introduced` of "0" (or absent) means the window has no lower bound, which is * how OSV expresses "every version before the fix". */ function versionWithinAffectedWindow( version: string, introduced: string | null, fixed: string, ecosystem: string, ): boolean { if (introduced && introduced !== "0") { // Advisories write boundaries with fewer than three components. Semver pads // `2` to 2.0.0. PEP 440 keeps `2`, which compares equal to 2.0.0. A value // that is not a version at all still returns null and the window is skipped. const normalizedIntroduced = normalizeAdvisoryVersion(introduced, ecosystem); if (!normalizedIntroduced) return false; if (compareVersions(version, normalizedIntroduced, ecosystem) < 0) return false; } return compareVersions(version, fixed, ecosystem) < 0; } /** * Every usable fixed version one advisory declares for this package, split into * all of them and those whose affected window contains the installed version. */ function collectAdvisoryFixes( vuln: OsvVuln, packageName: string, ecosystem: string, installedVersion?: string, ): { all: string[]; onInstalledBranch: string[] } { const all: string[] = []; // An advisory that patches two release branches declares a fix per branch, and // the other branch's fix is a downgrade across a major boundary rather than a // remediation. const onInstalledBranch: string[] = []; for (const affected of vuln.affected ?? []) { // An advisory may list several packages with different fix versions. // Without this filter the minimum across all of them was returned, so a // package inherited another package's (lower) fix and the scan reported a // version that does not fix it. if (!affectedEntryMatchesPackage(affected, packageName, ecosystem)) continue; for (const range of affected.ranges ?? []) { // Events are ordered, and a single range can reintroduce a vulnerability, // so `introduced` is tracked as the walk proceeds and reset once its // matching `fixed` closes the window. let introduced: string | null = null; for (const event of range.events ?? []) { if (event.introduced) { introduced = event.introduced; continue; } // `fixed: "1.22"` is 1.22.0 for npm. PEP 440 keeps `1.22`, which compares // equal to 1.22.0, and a post-release such as `2026.3.post1` stays a fix. // Requiring a strict X.Y.Z here discarded the event, and a finding whose // every candidate was discarded reported "no fix available", which tells // a developer to stop looking for a fix that exists (#1192). A value that // cannot be read in full is still dropped, so a commit hash from a GIT // range never becomes a fix version. const fixed = normalizeAdvisoryVersion(event.fixed, ecosystem); if (!fixed || isPreReleaseVersion(fixed, ecosystem)) continue; all.push(fixed); if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed, ecosystem)) { onInstalledBranch.push(fixed); } introduced = null; } } } return { all, onInstalledBranch }; } export function findFirstFixedVersion( vulns: OsvVuln[], packageName: string, ecosystem: string, installedVersion?: string, ): string | null { return selectFixedVersion(vulns, packageName, ecosystem, installedVersion).version; } /** * The fix to recommend, and whether a PyPI boundary that might contain the * installed version could not be read. An unreadable boundary leaves the * version null and does not stop the scan. npm never sets `unreadable`. * `note` explains a PyPI finding left without a target although fixes exist. * * `targetAdvisories` is every advisory OSV holds for a PyPI package, including * ones that do not affect the installed version. It only narrows the target: * a candidate fix must clear their windows too. Null means that list could not * be loaded, so no target is confirmed. Undefined means it was not looked up. */ export function selectFixedVersion( vulns: OsvVuln[], packageName: string, ecosystem: string, installedVersion?: string, targetAdvisories?: OsvVuln[] | null, ): SelectedFix { if (isPep440Ecosystem(ecosystem)) { return selectPep440FixedVersion(vulns, packageName, ecosystem, installedVersion, targetAdvisories); } return { version: selectNpmFixedVersion(vulns, packageName, ecosystem, installedVersion), unreadable: false, }; } type SelectedFix = { version: string | null; unreadable: boolean; note?: string }; function selectNpmFixedVersion( vulns: OsvVuln[], packageName: string, ecosystem: string, installedVersion?: string, ): string | null { const everyKnownFix: string[] = []; // One entry per advisory: the earliest version clearing THAT advisory on the // branch the install sits on. const perAdvisoryFixes: string[] = []; const byVersion = (left: string, right: string) => compareVersions(left, right, ecosystem); for (const vuln of vulns) { const { all, onInstalledBranch } = collectAdvisoryFixes( vuln, packageName, ecosystem, installedVersion, ); everyKnownFix.push(...all); if (onInstalledBranch.length > 0) { // Lowest WITHIN one advisory: the branch fix, not the other branch's. perAdvisoryFixes.push(onInstalledBranch.sort(byVersion)[0]!); } } // Highest ACROSS advisories: the caller needs a version clear of all of them, // and stopping at the lowest leaves every advisory fixed above it still live. if (perAdvisoryFixes.length > 0) { return perAdvisoryFixes.sort(byVersion)[perAdvisoryFixes.length - 1]!; } // No declared window contains the installed version, so there is no branch to // scope to. Falling back to every known fix keeps a finding's remediation // visible rather than reporting none. if (everyKnownFix.length === 0) return null; return everyKnownFix.sort(byVersion)[0]!; } function selectPep440FixedVersion( vulns: OsvVuln[], packageName: string, ecosystem: string, installedVersion?: string, targetAdvisories?: OsvVuln[] | null, ): SelectedFix { if (installedVersion && !looksLikeVersion(installedVersion, ecosystem)) { return { version: null, unreadable: true }; } const everyKnownFix: string[] = []; const perAdvisoryFixes: string[] = []; let unreadable = false; let blocked = false; // The installed version is affected without a fix of its own: listed by name, // or inside a window closed by last_affected or a pre-release. Only a fix checked against // every advisory for the package can be named. let needsValidatedTarget = false; const byVersion = (left: string, right: string) => compareVersions(left, right, ecosystem); for (const vuln of vulns) { const branchFixes: string[] = []; let advisoryUnreadable = false; let heldWithoutFix = false; for (const affected of vuln.affected ?? []) { if (!affectedEntryMatchesPackage(affected, packageName, ecosystem)) continue; if (installedVersion && pep440VersionIsListed(installedVersion, affected.versions ?? [], ecosystem)) { needsValidatedTarget = true; } for (const range of affected.ranges ?? []) { const rangeType = range.type; if (rangeType === "GIT") continue; if (rangeType && rangeType !== "ECOSYSTEM" && rangeType !== "SEMVER") continue; const read = readPep440Range(range.events ?? []); if (!installedVersion) { if (read.unreadable.length > 0) advisoryUnreadable = true; } else if (read.unreadable.some(boundary => pep440UnreadableApplies(installedVersion, boundary))) { advisoryUnreadable = true; } for (const fix of read.fixes) { if (!isPreReleaseVersion(fix, ecosystem)) everyKnownFix.push(fix); } if (!installedVersion) continue; for (const window of read.windows) { if (!versionInPep440Window(installedVersion, window)) continue; if (window.fixed && !isPreReleaseVersion(window.fixed, ecosystem)) branchFixes.push(window.fixed); // A window closed by last_affected or a pre-release fix ends at a known // version, so a later release from any advisory can still clear it. // Only an open window blocks. else if (window.lastAffected || window.fixed) needsValidatedTarget = true; else heldWithoutFix = true; } } } if (advisoryUnreadable) { unreadable = true; continue; } if (heldWithoutFix) blocked = true; else if (branchFixes.length > 0) perAdvisoryFixes.push(branchFixes.sort(byVersion)[0]!); } if (unreadable) return { version: null, unreadable: true }; if (blocked) return { version: null, unreadable: false }; if ((perAdvisoryFixes.length > 0 || needsValidatedTarget) && installedVersion) { if (targetAdvisories === null) { return { version: null, unreadable: false, note: `No upgrade target is confirmed: the scan could not load every advisory for ${packageName}, so no fixed version could be checked against all of them. Re-run the scan online to retry, or review every advisory for ${packageName} before upgrading.`, }; } const evidence = collectPep440TargetEvidence( // The target list comes first: a finding can carry a stale cached copy of // an advisory, while the target list only holds records fetched fresh. uniqueById([...(targetAdvisories ?? []), ...vulns]), packageName, ecosystem, ); return selectPep440FixClearOfEveryWindow(packageName, installedVersion, evidence); } // No window contains the installed version. A fix it has already reached can // still be named (a patched 2.x build still names the 1.x fix). A later fix // it has not reached belongs to another window, and recommending it would // treat an unaffected version as vulnerable. if (everyKnownFix.length === 0) return { version: null, unreadable: false }; if (installedVersion && everyKnownFix.every(fix => byVersion(installedVersion, fix) < 0)) { return { version: null, unreadable: false }; } return { version: everyKnownFix.sort(byVersion)[0]!, unreadable: false }; } /** What a PyPI upgrade target has to clear, read from every advisory for the package. */ type Pep440TargetEvidence = { fixes: string[]; windows: Pep440Window[]; /** Boundaries that did not parse. One that could reach a candidate leaves it unconfirmed. */ unreadable: Pep440UnreadableBoundary[]; /** Versions an advisory lists as affected one by one, canonical. */ listedVersions: string[]; }; function uniqueById(vulns: OsvVuln[]): OsvVuln[] { const seen = new Map(); for (const vuln of vulns) if (!seen.has(vuln.id)) seen.set(vuln.id, vuln); return [...seen.values()]; } function collectPep440TargetEvidence( vulns: OsvVuln[], packageName: string, ecosystem: string, ): Pep440TargetEvidence { const evidence: Pep440TargetEvidence = { fixes: [], windows: [], unreadable: [], listedVersions: [] }; for (const vuln of vulns) { for (const affected of vuln.affected ?? []) { if (!affectedEntryMatchesPackage(affected, packageName, ecosystem)) continue; for (const listed of affected.versions ?? []) { // A listed version that does not parse cannot equal a readable candidate. const canonical = normalizeAdvisoryVersion(listed, ecosystem); if (canonical) evidence.listedVersions.push(canonical); } for (const range of affected.ranges ?? []) { if (range.type === "GIT") continue; if (range.type && range.type !== "ECOSYSTEM" && range.type !== "SEMVER") continue; const read = readPep440Range(range.events ?? []); for (const fix of read.fixes) { // A pre-release is never the target, but the release it leads to can be. // Assumes this release was published to PyPI; there is no registry lookup here. const release = isPreReleaseVersion(fix, ecosystem) ? pep440FinalRelease(fix) : fix; if (release) evidence.fixes.push(release); } evidence.windows.push(...read.windows); evidence.unreadable.push(...read.unreadable); } } } return evidence; } function pep440VersionIsListed(version: string, listed: string[], ecosystem: string): boolean { return listed.some(entry => { const canonical = normalizeAdvisoryVersion(entry, ecosystem); return canonical !== null && compareVersions(version, canonical, ecosystem) === 0; }); } function pep440CandidateIsClear(candidate: string, evidence: Pep440TargetEvidence): boolean { if (evidence.windows.some(window => versionInPep440Window(candidate, window))) return false; if (evidence.listedVersions.some(listed => compareVersions(candidate, listed, "PyPI") === 0)) return false; return !evidence.unreadable.some(boundary => pep440UnreadableApplies(candidate, boundary)); } const MAX_FIXES_IN_NOTE = 5; /** * The lowest known fix above the installed version that no affected * window contains, from any advisory for the package. Each advisory's own fix * only clears that advisory's window: another advisory, or a later window of * the same one, can still cover it. A fix an advisory lists as affected, or one * an unreadable boundary could still cover, is not confirmed clear either. With * no candidate left the version is null and the note says why. */ function selectPep440FixClearOfEveryWindow( packageName: string, installedVersion: string, evidence: Pep440TargetEvidence, ): SelectedFix { const candidates = [...new Set(evidence.fixes)] // The installed version sits in a window or is listed, so a fix equal to it is never clear. .filter(fix => compareVersions(fix, installedVersion, "PyPI") > 0) .sort((left, right) => compareVersions(left, right, "PyPI")); const clear = candidates.find(fix => pep440CandidateIsClear(fix, evidence)); if (clear) return { version: clear, unreadable: false }; if (candidates.length === 0) { return { version: null, unreadable: false, note: `No fixed version of ${packageName} is named above ${installedVersion} by its advisories, so no upgrade target is known.`, }; } const shown = candidates.length > MAX_FIXES_IN_NOTE ? `${candidates.slice(0, MAX_FIXES_IN_NOTE).join(", ")} and ${candidates.length - MAX_FIXES_IN_NOTE} more` : candidates.join(", "); return { version: null, unreadable: false, note: `No safe version of ${packageName} is known: every fixed version its advisories name above ${installedVersion} (${shown}) is still affected by one of them or could not be confirmed outside their affected ranges.`, }; } // Lockfile names and versions are attacker-controlled and land in terminal, // CI log and JSON text, so strip control characters and line breaks first. function packageLabel(pkg: PackageRef): string { return sanitizeOutputString(`${pkg.name}@${pkg.version}`); } function buildCompletenessDiagnostics(params: { npmAdvisoryFailureCount: number; npmAdvisoryMalformedCount: number; transientDetailIds: Set; offlineMissingDetailIds: Set; confirmedMissingDetailIds: Set; staleDetailCachedAt: Map; packumentFailures: Set; remediationFailures: Map; chainResolutionFailureCount: number; unreadableBoundaryPackageLabels: string[]; unreadableFixPackageLabels: string[]; }): ScanDiagnostic[] { const diagnostics: ScanDiagnostic[] = []; function addDiagnostic( code: ScanDiagnosticCode, count: number, impact: ScanDiagnostic["impact"], { affectedPackageCount, oldestCachedAt, packages }: { affectedPackageCount?: number; oldestCachedAt?: string; packages?: string[] } = {}, ): void { if (count === 0) return; diagnostics.push({ code, severity: "warning", message: formatDiagnosticMessage(code, count, { affectedPackageCount, impact, oldestCachedAt, packages }), impact, count, ...(affectedPackageCount === undefined ? {} : { affectedPackageCount }), ...(oldestCachedAt === undefined ? {} : { oldestCachedAt }), ...(packages === undefined ? {} : { packages }), }); } const remediationTotal = [...params.remediationFailures.values()].reduce((sum, c) => sum + c, 0); addDiagnostic("NPM_ADVISORY_FETCH_FAILURE", params.npmAdvisoryFailureCount, "detection"); addDiagnostic("NPM_ADVISORY_MALFORMED_RESPONSE", params.npmAdvisoryMalformedCount, "detection"); addDiagnostic("OSV_DETAIL_TRANSIENT_FAILURE", params.transientDetailIds.size, "detection"); addDiagnostic("OSV_DETAIL_OFFLINE_MISSING", params.offlineMissingDetailIds.size, "detection"); addDiagnostic("OSV_DETAIL_CONFIRMED_MISSING", params.confirmedMissingDetailIds.size, "detection"); const staleDates = [...params.staleDetailCachedAt.values()].sort(); addDiagnostic("OSV_DETAIL_STALE_CACHE_USED", staleDates.length, "freshness", { oldestCachedAt: staleDates[0] }); addDiagnostic("PACKUMENT_FETCH_FAILURE", params.packumentFailures.size, "remediation"); addDiagnostic("REMEDIATION_FAILURE", remediationTotal, "remediation", { affectedPackageCount: params.remediationFailures.size, }); addDiagnostic("CHAIN_RESOLUTION_FAILURE", params.chainResolutionFailureCount, "remediation"); addDiagnostic("UNREADABLE_PYPI_BOUNDARY", params.unreadableBoundaryPackageLabels.length, "detection", { packages: params.unreadableBoundaryPackageLabels, }); addDiagnostic("UNREADABLE_PYPI_BOUNDARY", params.unreadableFixPackageLabels.length, "remediation", { packages: params.unreadableFixPackageLabels, }); return diagnostics; } async function enrichWithEpssScores(findings: Finding[], fetchImpl?: FetchLike): Promise { const allCves = [...new Set(findings.flatMap(f => f.cveAliases))]; if (allCves.length === 0) return; const epssMap = await fetchEpssScores(allCves, fetchImpl); if (epssMap.size === 0) return; for (const finding of findings) { const scores = finding.cveAliases.flatMap(cve => { const score = epssMap.get(cve.toUpperCase()); return score ? [score] : []; }); if (scores.length > 0) finding.epssScores = scores; } } export function buildCoverageNotes(scanInput: ScanInput, offline: boolean): string[] { const notes = [ "CVE Lite CLI checks package versions against OSV advisories. It does not prove exploitability or runtime reachability.", ]; if (scanInput.source !== "requirements-txt") { notes.push("Installed node_modules contents are not verified in this scan."); } notes.push( "Container images, binaries, secrets, and IaC files are not scanned.", "Monorepo workspace boundaries are only partially modeled in this version.", ); if (scanInput.mode === "manifest-fallback") { notes.push("Manifest fallback is limited to direct dependencies pinned to exact versions. It does not resolve transitive dependencies from package.json alone."); } if (offline) { notes.push("Offline mode uses the local advisory database and does not make outbound advisory API calls."); } return notes; }