Private/VulnerabilityFeeds.ps1

$script:WsaVulnerabilityPriorityCachePath = $null
$script:WsaEpssApiUri = 'https://api.first.org/data/v1/epss'
$script:WsaEpssCsvUri = 'https://epss.empiricalsecurity.com/epss_scores-current.csv.gz'
$script:WsaKevUri = 'https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json'
$script:WsaPriorityCacheSchemaVersion = 1

function Get-WsaPriorityUtcNow {
    [CmdletBinding()]
    [OutputType([DateTimeOffset])]
    param()

    return [DateTimeOffset]::UtcNow
}

function Test-WsaCveId {
    [CmdletBinding()]
    [OutputType([bool])]
    param([AllowNull()][object]$CveId)

    if ($null -eq $CveId) {
        return $false
    }

    return [regex]::IsMatch([string]$CveId, '^CVE-[0-9]{4}-[0-9]{4,}$', [Text.RegularExpressions.RegexOptions]::IgnoreCase)
}

function Test-WsaPriorityProperty {
    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [AllowNull()][object]$InputObject,
        [Parameter(Mandatory = $true)][string]$Name
    )

    return $null -ne $InputObject -and $null -ne $InputObject.PSObject.Properties[$Name]
}

function ConvertTo-WsaProbability {
    [CmdletBinding()]
    [OutputType([double])]
    param(
        [Parameter(Mandatory = $true)][AllowNull()][object]$Value,
        [Parameter(Mandatory = $true)][string]$FieldName
    )

    if ($null -eq $Value -or $Value -is [bool]) {
        throw [System.FormatException]::new("$FieldName is missing or is not numeric.")
    }

    $parsed = 0.0
    $text = [string]$Value
    if ([string]::IsNullOrWhiteSpace($text) -or
        -not [double]::TryParse($text, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$parsed) -or
        [double]::IsNaN($parsed) -or [double]::IsInfinity($parsed) -or
        $parsed -lt 0.0 -or $parsed -gt 1.0) {
        throw [System.FormatException]::new("$FieldName must be a finite number between 0 and 1.")
    }

    return [double]$parsed
}

function ConvertTo-WsaUtcDateOffset {
    [CmdletBinding()]
    [OutputType([DateTimeOffset])]
    param(
        [Parameter(Mandatory = $true)][AllowNull()][object]$Value,
        [Parameter(Mandatory = $true)][string]$FieldName
    )

    if ($null -eq $Value) {
        throw [System.FormatException]::new("$FieldName is required.")
    }
    if ($Value -is [DateTimeOffset]) {
        return ([DateTimeOffset]$Value).ToUniversalTime()
    }
    if ($Value -is [DateTime]) {
        $dateTime = [DateTime]$Value
        if ($dateTime.Kind -eq [DateTimeKind]::Unspecified) {
            return [DateTimeOffset]::new($dateTime, [TimeSpan]::Zero)
        }
        return [DateTimeOffset]::new($dateTime).ToUniversalTime()
    }

    $parsed = [DateTimeOffset]::MinValue
    $styles = [Globalization.DateTimeStyles]::AssumeUniversal -bor [Globalization.DateTimeStyles]::AdjustToUniversal
    if (-not [DateTimeOffset]::TryParse([string]$Value, [Globalization.CultureInfo]::InvariantCulture, $styles, [ref]$parsed)) {
        throw [System.FormatException]::new("$FieldName is not a valid timestamp.")
    }

    return $parsed.ToUniversalTime()
}

function Resolve-WsaAssetCriticality {
    [CmdletBinding()]
    param([AllowNull()][object]$AssetCriticality)

    if ($null -eq $AssetCriticality -or ($AssetCriticality -is [string] -and [string]::IsNullOrWhiteSpace([string]$AssetCriticality))) {
        return [PSCustomObject]@{
            AssetCriticality = 'Default'
            AssetMultiplier = 1.0
        }
    }

    if ($AssetCriticality -is [bool]) {
        throw [System.ArgumentException]::new('AssetCriticality cannot be a Boolean value.')
    }

    $role = $null
    $multiplier = 0.0
    if ($AssetCriticality -is [string]) {
        $text = ([string]$AssetCriticality).Trim()
        switch ($text.ToUpperInvariant()) {
            'DOMAINCONTROLLER' {
                return [PSCustomObject]@{ AssetCriticality = 'DomainController'; AssetMultiplier = 1.25 }
            }
            'SERVER' {
                return [PSCustomObject]@{ AssetCriticality = 'Server'; AssetMultiplier = 1.10 }
            }
            'WORKSTATION' {
                return [PSCustomObject]@{ AssetCriticality = 'Workstation'; AssetMultiplier = 1.00 }
            }
        }

        if ($text -notmatch '^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$') {
            throw [System.ArgumentException]::new('AssetCriticality must be a named role or an invariant-culture number from 0.5 through 2.0.')
        }
        if (-not [double]::TryParse($text, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$multiplier)) {
            throw [System.ArgumentException]::new('AssetCriticality is not a valid numeric multiplier.')
        }
    }
    else {
        $allowedTypes = @(
            'System.Byte', 'System.SByte', 'System.Int16', 'System.UInt16',
            'System.Int32', 'System.UInt32', 'System.Int64', 'System.UInt64',
            'System.Single', 'System.Double', 'System.Decimal'
        )
        if ($null -eq $AssetCriticality -or $allowedTypes -notcontains $AssetCriticality.GetType().FullName) {
            throw [System.ArgumentException]::new('AssetCriticality must be a named role or numeric multiplier.')
        }
        $multiplier = [double]$AssetCriticality
    }

    if ([double]::IsNaN($multiplier) -or [double]::IsInfinity($multiplier) -or $multiplier -lt 0.5 -or $multiplier -gt 2.0) {
        throw [System.ArgumentException]::new('AssetCriticality must be a finite number from 0.5 through 2.0.')
    }

    return [PSCustomObject]@{
        AssetCriticality = 'Custom'
        AssetMultiplier = [double]$multiplier
    }
}

function Resolve-WsaSeverityImpact {
    [CmdletBinding()]
    param([AllowNull()][object]$Severity)

    if ($null -eq $Severity) {
        return $null
    }

    switch (([string]$Severity).Trim().ToUpperInvariant()) {
        'CRITICAL' { return 40 }
        'HIGH' { return 30 }
        'MEDIUM' { return 20 }
        'LOW' { return 10 }
        default { return $null }
    }
}

function Resolve-WsaScoreSource {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$EpssSource,
        [Parameter(Mandatory = $true)][string]$KevSource
    )

    if ($EpssSource -eq 'Unavailable' -and $KevSource -eq 'Unavailable') {
        return 'Unavailable'
    }
    if ($EpssSource -eq 'Unavailable' -or $KevSource -eq 'Unavailable') {
        return 'Partial'
    }
    if ($EpssSource -eq 'Stale' -or $KevSource -eq 'Stale') {
        return 'Stale'
    }
    if ($EpssSource -eq 'Live' -or $KevSource -eq 'Live') {
        return 'Live'
    }
    if ($EpssSource -eq 'Cache' -or $KevSource -eq 'Cache') {
        return 'Cache'
    }

    return 'Unavailable'
}

function Resolve-WsaPriorityScore {
    [CmdletBinding()]
    param(
        [AllowNull()][object]$Severity,
        [AllowNull()][object]$EpssScore,
        [AllowNull()][object]$KevStatus,
        [Parameter(Mandatory = $true)][double]$AssetMultiplier,
        [Parameter(Mandatory = $true)][string]$EpssSource,
        [Parameter(Mandatory = $true)][string]$KevSource,
        [bool]$ValidCve = $true
    )

    $scoreSource = Resolve-WsaScoreSource -EpssSource $EpssSource -KevSource $KevSource
    $result = [PSCustomObject]@{
        PriorityScore = $null
        PriorityTier = 'Unscored'
        PriorityStatus = 'Unscored'
        UnscoredReason = $null
        ScoreSource = $scoreSource
    }

    if (-not $ValidCve) {
        $result.UnscoredReason = 'InvalidCve'
        $result.ScoreSource = 'Unavailable'
        return $result
    }

    if ($true -eq $KevStatus) {
        $result.PriorityScore = 100.0
        $result.PriorityTier = 'Critical'
        $result.PriorityStatus = 'Scored'
        return $result
    }

    if ($EpssSource -eq 'Unavailable' -and $KevSource -eq 'Unavailable') {
        $result.UnscoredReason = 'FeedsUnavailable'
        return $result
    }

    if ($null -eq $KevStatus) {
        $result.UnscoredReason = 'KevUnavailable'
        return $result
    }

    $impact = Resolve-WsaSeverityImpact -Severity $Severity
    if ($null -eq $impact) {
        $result.UnscoredReason = 'MissingSeverity'
        return $result
    }

    if ($null -eq $EpssScore) {
        if ($EpssSource -eq 'NotScored') {
            $result.UnscoredReason = 'EpssNotScored'
        }
        else {
            $result.UnscoredReason = 'EpssUnavailable'
        }
        return $result
    }

    $probability = ConvertTo-WsaProbability -Value $EpssScore -FieldName 'EPSS score'
    $rawScore = [double]$impact + (60.0 * $probability)
    $score = [Math]::Round([Math]::Min(100.0, $AssetMultiplier * $rawScore), 2)
    $result.PriorityScore = $score
    $result.PriorityStatus = 'Scored'
    if ($score -ge 80.0) {
        $result.PriorityTier = 'Critical'
    }
    elseif ($score -ge 60.0) {
        $result.PriorityTier = 'High'
    }
    elseif ($score -ge 30.0) {
        $result.PriorityTier = 'Medium'
    }
    else {
        $result.PriorityTier = 'Low'
    }

    return $result
}

function Get-WsaPriorityCacheRoot {
    [CmdletBinding()]
    param([AllowNull()][string]$CachePath)

    if (-not [string]::IsNullOrWhiteSpace($CachePath)) {
        return $CachePath
    }
    if (-not [string]::IsNullOrWhiteSpace($env:WSA_VULNERABILITY_PRIORITY_CACHE_PATH)) {
        return $env:WSA_VULNERABILITY_PRIORITY_CACHE_PATH
    }
    if (-not [string]::IsNullOrWhiteSpace($env:WSA_VULNERABILITY_PRIORITY_CACHE)) {
        return $env:WSA_VULNERABILITY_PRIORITY_CACHE
    }
    if (-not [string]::IsNullOrWhiteSpace($script:WsaVulnerabilityPriorityCachePath)) {
        return $script:WsaVulnerabilityPriorityCachePath
    }
    if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
        return (Join-Path $env:LOCALAPPDATA 'WindowsSecurityAudit\VulnerabilityPriority')
    }
    if (-not [string]::IsNullOrWhiteSpace($env:HOME)) {
        return (Join-Path $env:HOME '.local/share/WindowsSecurityAudit/VulnerabilityPriority')
    }

    return (Join-Path ([IO.Path]::GetTempPath()) 'WindowsSecurityAudit/VulnerabilityPriority')
}

function Protect-WsaPriorityCacheAcl {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$Path)

    if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
        return
    }

    $acl = Get-Acl -LiteralPath $Path -ErrorAction Stop
    $acl.SetAccessRuleProtection($true, $false)
    foreach ($rule in @($acl.Access)) {
        $acl.RemoveAccessRuleAll($rule)
    }

    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $systemSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
    $inheritance = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit
    foreach ($sid in @($identity.User, $systemSid)) {
        $rule = [Security.AccessControl.FileSystemAccessRule]::new(
            $sid,
            [Security.AccessControl.FileSystemRights]::FullControl,
            $inheritance,
            [Security.AccessControl.PropagationFlags]::None,
            [Security.AccessControl.AccessControlType]::Allow)
        $acl.AddAccessRule($rule)
    }
    Set-Acl -LiteralPath $Path -AclObject $acl -ErrorAction Stop
}

function Initialize-WsaPriorityCacheDirectory {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$Path)

    if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
        $null = New-Item -Path $Path -ItemType Directory -Force -ErrorAction Stop
    }
    if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) {
        Protect-WsaPriorityCacheAcl -Path $Path
    }

    return $Path
}

function Invoke-WsaEpssApiRequest {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$Uri)

    try {
        [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
    }
    catch {
        Write-Verbose "Could not enforce TLS 1.2: $($_.Exception.Message)"
    }

    return Invoke-RestMethod -Uri $Uri -Method Get -TimeoutSec 60 -ErrorAction Stop
}

function Invoke-WsaPriorityFileDownload {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$Uri,
        [Parameter(Mandatory = $true)][string]$OutFile
    )

    try {
        [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
    }
    catch {
        Write-Verbose "Could not enforce TLS 1.2: $($_.Exception.Message)"
    }

    Invoke-WebRequest -Uri $Uri -OutFile $OutFile -MaximumRedirection 10 -TimeoutSec 120 -UseBasicParsing -ErrorAction Stop
}

function Get-WsaHttpStatusCode {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)]$ErrorRecord)

    $exception = $ErrorRecord.Exception
    if (-not (Test-WsaPriorityProperty -InputObject $exception -Name 'Response')) {
        return $null
    }
    $response = $exception.Response
    if ($null -ne $response -and $null -ne $response.PSObject.Properties['StatusCode'] -and $null -ne $response.StatusCode) {
        try {
            return [int]$response.StatusCode
        }
        catch {
            return $null
        }
    }
    return $null
}

function Get-WsaRetryAfterSeconds {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)]$ErrorRecord)

    $exception = $ErrorRecord.Exception
    if (-not (Test-WsaPriorityProperty -InputObject $exception -Name 'Response')) {
        return $null
    }
    $response = $exception.Response
    if ($null -eq $response -or $null -eq $response.PSObject.Properties['Headers'] -or $null -eq $response.Headers) {
        return $null
    }

    $headers = $response.Headers
    $value = $null
    try {
        $value = $headers['Retry-After']
    }
    catch {
        $value = $null
    }
    if ($null -eq $value -and $null -ne $headers.PSObject.Properties['RetryAfter'] -and $null -ne $headers.RetryAfter) {
        $retryAfter = $headers.RetryAfter
        if ($null -ne $retryAfter.PSObject.Properties['Delta'] -and $null -ne $retryAfter.Delta) {
            return [Math]::Max(0, [int][Math]::Ceiling($retryAfter.Delta.TotalSeconds))
        }
        if ($null -ne $retryAfter.PSObject.Properties['Date'] -and $null -ne $retryAfter.Date) {
            $value = $retryAfter.Date
        }
    }
    if ($null -eq $value) {
        return $null
    }

    $seconds = 0
    if ([int]::TryParse([string]$value, [Globalization.NumberStyles]::Integer, [Globalization.CultureInfo]::InvariantCulture, [ref]$seconds)) {
        return [Math]::Max(0, $seconds)
    }

    try {
        $date = ConvertTo-WsaUtcDateOffset -Value $value -FieldName 'Retry-After'
        $now = Get-WsaPriorityUtcNow
        return [Math]::Max(0, [int][Math]::Ceiling(($date - $now).TotalSeconds))
    }
    catch {
        return $null
    }
}

function Invoke-WsaEpssApiPage {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$Uri)

    for ($attempt = 1; $attempt -le 2; $attempt++) {
        try {
            return Invoke-WsaEpssApiRequest -Uri $Uri
        }
        catch {
            $statusCode = Get-WsaHttpStatusCode -ErrorRecord $_
            if ($statusCode -ne 429 -or $attempt -eq 2) {
                throw
            }
            $retryAfter = Get-WsaRetryAfterSeconds -ErrorRecord $_
            if ($null -eq $retryAfter) {
                $retryAfter = 1
            }
            if ($retryAfter -gt 30) {
                throw
            }
            Start-Sleep -Seconds $retryAfter
        }
    }
}

function New-WsaEpssBatch {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string[]]$CveIds)

    $seen = @{}
    $orderedIds = New-Object 'System.Collections.Generic.List[string]'
    foreach ($id in $CveIds) {
        if (-not (Test-WsaCveId -CveId $id)) {
            throw [System.ArgumentException]::new('EPSS batches can contain only valid CVE IDs.')
        }
        $normalized = ([string]$id).ToUpperInvariant()
        if ($normalized.Length -gt 1800) {
            throw [System.ArgumentException]::new("A single CVE ID is $($normalized.Length) characters and exceeds the 1800-character EPSS batch limit.")
        }
        if (-not $seen.ContainsKey($normalized)) {
            $seen[$normalized] = $true
            $orderedIds.Add($normalized)
        }
    }

    $batches = New-Object 'System.Collections.Generic.List[object]'
    $current = New-Object 'System.Collections.Generic.List[string]'
    $length = 0
    foreach ($id in $orderedIds) {
        $additional = $id.Length
        if ($current.Count -gt 0) {
            $additional++
        }
        if ($current.Count -gt 0 -and ($length + $additional) -gt 1800) {
            $batches.Add($current.ToArray())
            $current = New-Object 'System.Collections.Generic.List[string]'
            $length = 0
            $additional = $id.Length
        }
        $current.Add($id)
        $length += $additional
    }
    if ($current.Count -gt 0) {
        $batches.Add($current.ToArray())
    }

    return $batches.ToArray()
}

function Get-WsaEpssApiData {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string[]]$CveIds)

    $entries = @{}
    $covered = @{}
    $latestDate = $null
    $modelVersion = $null
    foreach ($batch in @(New-WsaEpssBatch -CveIds $CveIds)) {
        $batchIds = @($batch)
        $requested = @{}
        foreach ($id in $batchIds) {
            $requested[$id] = $true
            $covered[$id] = $true
        }
        $escapedIds = [Uri]::EscapeDataString($batchIds -join ',')
        $offset = 0
        $total = $null
        $received = 0
        do {
            $uri = "${script:WsaEpssApiUri}?cve=$escapedIds&scope=public&limit=100&offset=$offset"
            $response = Invoke-WsaEpssApiPage -Uri $uri
            if ($response -is [string]) {
                $response = $response | ConvertFrom-Json -ErrorAction Stop
            }
            if ($null -eq $response -or
                -not (Test-WsaPriorityProperty -InputObject $response -Name 'status') -or
                ([string]$response.status).ToUpperInvariant() -ne 'OK') {
                throw [System.FormatException]::new('EPSS API returned an invalid status.')
            }
            if ((Test-WsaPriorityProperty -InputObject $response -Name 'status-code') -and [int]$response.'status-code' -ne 200) {
                throw [System.FormatException]::new('EPSS API returned a non-success status code.')
            }
            if (-not (Test-WsaPriorityProperty -InputObject $response -Name 'total') -or
                -not (Test-WsaPriorityProperty -InputObject $response -Name 'offset') -or
                -not (Test-WsaPriorityProperty -InputObject $response -Name 'data')) {
                throw [System.FormatException]::new('EPSS API response is missing pagination or data fields.')
            }

            $responseTotal = 0
            $responseOffset = 0
            if (-not [int]::TryParse([string]$response.total, [Globalization.NumberStyles]::Integer, [Globalization.CultureInfo]::InvariantCulture, [ref]$responseTotal) -or $responseTotal -lt 0 -or
                -not [int]::TryParse([string]$response.offset, [Globalization.NumberStyles]::Integer, [Globalization.CultureInfo]::InvariantCulture, [ref]$responseOffset) -or $responseOffset -ne $offset) {
                throw [System.FormatException]::new('EPSS API pagination metadata is invalid.')
            }
            if ($null -eq $total) {
                $total = $responseTotal
            }
            elseif ($total -ne $responseTotal) {
                throw [System.FormatException]::new('EPSS API total changed between pages.')
            }
            if ($total -gt $batchIds.Count) {
                throw [System.FormatException]::new('EPSS API returned more results than requested.')
            }

            $rows = @($response.data)
            if ($received + $rows.Count -gt $total) {
                throw [System.FormatException]::new('EPSS API returned too many rows.')
            }
            foreach ($row in $rows) {
                if (-not (Test-WsaPriorityProperty -InputObject $row -Name 'cve') -or
                    -not (Test-WsaPriorityProperty -InputObject $row -Name 'epss') -or
                    -not (Test-WsaPriorityProperty -InputObject $row -Name 'percentile') -or
                    -not (Test-WsaPriorityProperty -InputObject $row -Name 'date')) {
                    throw [System.FormatException]::new('EPSS API returned an incomplete row.')
                }
                $id = ([string]$row.cve).ToUpperInvariant()
                if (-not (Test-WsaCveId -CveId $id) -or -not $requested.ContainsKey($id) -or $entries.ContainsKey($id)) {
                    throw [System.FormatException]::new('EPSS API returned an unexpected or duplicate CVE row.')
                }
                $epss = ConvertTo-WsaProbability -Value $row.epss -FieldName 'EPSS score'
                $percentile = ConvertTo-WsaProbability -Value $row.percentile -FieldName 'EPSS percentile'
                $scoreDate = ConvertTo-WsaUtcDateOffset -Value $row.date -FieldName 'EPSS score date'
                $scoreDateText = $scoreDate.ToString('yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)
                $entries[$id] = [PSCustomObject]@{
                    CVEId = $id
                    EpssScore = $epss
                    EpssPercentile = $percentile
                    EpssScoreDate = $scoreDateText
                }
                if ($null -eq $latestDate -or $scoreDate -gt $latestDate) {
                    $latestDate = $scoreDate
                }
            }
            if ((Test-WsaPriorityProperty -InputObject $response -Name 'version') -and $null -ne $response.version) {
                $modelVersion = [string]$response.version
            }
            $received += $rows.Count
            if ($received -lt $total -and $rows.Count -eq 0) {
                throw [System.FormatException]::new('EPSS API response was truncated.')
            }
            $offset = $received
        } while ($received -lt $total)
    }

    return [PSCustomObject]@{
        Entries = $entries
        CoveredCves = $covered
        ScoreDate = if ($null -ne $latestDate) { $latestDate.ToString('yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture) } else { $null }
        ModelVersion = $modelVersion
        SourceUrl = $script:WsaEpssApiUri
    }
}

function Read-WsaEpssCsv {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$Path,
        [Parameter(Mandatory = $true)][string[]]$CveIds
    )

    $requested = @{}
    foreach ($id in $CveIds) {
        if (Test-WsaCveId -CveId $id) {
            $requested[([string]$id).ToUpperInvariant()] = $true
        }
    }

    $fileStream = $null
    $gzipStream = $null
    $reader = $null
    try {
        $fileStream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
        $gzipStream = [IO.Compression.GZipStream]::new($fileStream, [IO.Compression.CompressionMode]::Decompress)
        $reader = [IO.StreamReader]::new($gzipStream, [Text.Encoding]::UTF8, $true)
        $modelLine = $reader.ReadLine()
        if ($null -eq $modelLine) {
            throw [System.FormatException]::new('EPSS CSV is empty or truncated.')
        }
        $modelMatch = [regex]::Match($modelLine, '^#model_version:([^,\r\n]+),score_date:([^,\r\n]+)$')
        if (-not $modelMatch.Success) {
            throw [System.FormatException]::new('EPSS CSV model header is missing or malformed.')
        }
        $modelVersion = $modelMatch.Groups[1].Value.Trim()
        $scoreDateValue = $modelMatch.Groups[2].Value.Trim()
        if ([string]::IsNullOrWhiteSpace($modelVersion)) {
            throw [System.FormatException]::new('EPSS CSV model version is empty.')
        }
        $scoreDate = ConvertTo-WsaUtcDateOffset -Value $scoreDateValue -FieldName 'EPSS CSV score_date'

        $header = $reader.ReadLine()
        if ($null -eq $header) {
            throw [System.FormatException]::new('EPSS CSV column header is missing.')
        }
        $columns = $header.Split(',')
        if ($columns.Count -lt 3 -or $columns[0].Trim() -cne 'cve' -or $columns[1].Trim() -cne 'epss' -or $columns[2].Trim() -cne 'percentile') {
            throw [System.FormatException]::new('EPSS CSV column header is invalid.')
        }

        $entries = @{}
        $rowCount = 0
        while ($null -ne ($line = $reader.ReadLine())) {
            if ($line.Length -eq 0) {
                continue
            }
            $rowCount++
            $fields = $line.Split(',')
            if ($fields.Count -ne $columns.Count -or $fields.Count -lt 3) {
                throw [System.FormatException]::new('EPSS CSV contains a malformed data row.')
            }
            $id = $fields[0].Trim().ToUpperInvariant()
            if (-not (Test-WsaCveId -CveId $id)) {
                throw [System.FormatException]::new('EPSS CSV contains an invalid CVE ID.')
            }
            $epss = ConvertTo-WsaProbability -Value $fields[1].Trim() -FieldName 'EPSS CSV score'
            $percentile = ConvertTo-WsaProbability -Value $fields[2].Trim() -FieldName 'EPSS CSV percentile'
            if ($requested.ContainsKey($id)) {
                if ($entries.ContainsKey($id)) {
                    throw [System.FormatException]::new('EPSS CSV contains a duplicate requested CVE.')
                }
                $entries[$id] = [PSCustomObject]@{
                    CVEId = $id
                    EpssScore = $epss
                    EpssPercentile = $percentile
                    EpssScoreDate = $scoreDate.ToString('o', [Globalization.CultureInfo]::InvariantCulture)
                }
            }
        }
        if ($rowCount -eq 0) {
            throw [System.FormatException]::new('EPSS CSV contains no score rows.')
        }

        $covered = @{}
        foreach ($id in $requested.Keys) {
            $covered[$id] = $true
        }
        return [PSCustomObject]@{
            Entries = $entries
            CoveredCves = $covered
            ScoreDate = $scoreDate.ToString('o', [Globalization.CultureInfo]::InvariantCulture)
            ModelVersion = $modelVersion
            SourceUrl = $script:WsaEpssCsvUri
        }
    }
    finally {
        if ($null -ne $reader) { $reader.Dispose() }
        elseif ($null -ne $gzipStream) { $gzipStream.Dispose() }
        if ($null -ne $fileStream) { $fileStream.Dispose() }
    }
}

function Read-WsaKevCatalog {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$Path)

    $json = [IO.File]::ReadAllText($Path, [Text.Encoding]::UTF8) | ConvertFrom-Json -ErrorAction Stop
    foreach ($property in @('catalogVersion', 'dateReleased', 'count', 'vulnerabilities')) {
        if (-not (Test-WsaPriorityProperty -InputObject $json -Name $property)) {
            throw [System.FormatException]::new("KEV catalog is missing $property.")
        }
    }
    if ($null -eq $json.catalogVersion -or [string]::IsNullOrWhiteSpace([string]$json.catalogVersion)) {
        throw [System.FormatException]::new('KEV catalog version is empty.')
    }
    $dateReleased = ConvertTo-WsaUtcDateOffset -Value $json.dateReleased -FieldName 'KEV dateReleased'
    $declaredCount = 0
    if (-not [int]::TryParse([string]$json.count, [Globalization.NumberStyles]::Integer, [Globalization.CultureInfo]::InvariantCulture, [ref]$declaredCount) -or $declaredCount -lt 0) {
        throw [System.FormatException]::new('KEV catalog count is invalid.')
    }
    $vulnerabilities = @($json.vulnerabilities)
    if ($null -eq $json.vulnerabilities -and $declaredCount -ne 0) {
        throw [System.FormatException]::new('KEV catalog vulnerabilities are missing.')
    }
    if ($declaredCount -ne $vulnerabilities.Count) {
        throw [System.FormatException]::new('KEV catalog count does not match the vulnerability array.')
    }

    $entries = @{}
    $requiredFields = @('cveID', 'vendorProject', 'product', 'dateAdded', 'dueDate', 'requiredAction', 'knownRansomwareCampaignUse')
    foreach ($item in $vulnerabilities) {
        foreach ($field in $requiredFields) {
            if (-not (Test-WsaPriorityProperty -InputObject $item -Name $field) -or $null -eq $item.$field) {
                throw [System.FormatException]::new("KEV entry is missing $field.")
            }
        }
        $id = ([string]$item.cveID).ToUpperInvariant()
        if (-not (Test-WsaCveId -CveId $id)) {
            throw [System.FormatException]::new('KEV catalog contains an invalid CVE ID.')
        }
        if ($entries.ContainsKey($id)) {
            throw [System.FormatException]::new('KEV catalog contains a duplicate CVE ID.')
        }
        $ransomware = ([string]$item.knownRansomwareCampaignUse).Trim()
        if ($ransomware -notin @('Known', 'Unknown')) {
            throw [System.FormatException]::new('KEV ransomware status must be Known or Unknown.')
        }

        $dateAdded = [DateTime]::MinValue
        $dueDate = [DateTime]::MinValue
        if (-not [DateTime]::TryParseExact([string]$item.dateAdded, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::None, [ref]$dateAdded) -or
            -not [DateTime]::TryParseExact([string]$item.dueDate, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::None, [ref]$dueDate)) {
            throw [System.FormatException]::new('KEV entry contains an invalid dateAdded or dueDate.')
        }
        foreach ($textField in @('vendorProject', 'product', 'requiredAction')) {
            if ([string]::IsNullOrWhiteSpace([string]$item.$textField)) {
                throw [System.FormatException]::new("KEV entry field $textField is empty.")
            }
        }

        $entries[$id] = [PSCustomObject]@{
            CVEId = $id
            VendorProject = [string]$item.vendorProject
            Product = [string]$item.product
            DateAdded = $dateAdded
            DueDate = $dueDate
            RequiredAction = [string]$item.requiredAction
            RansomwareStatus = $ransomware
        }
    }

    return [PSCustomObject]@{
        Entries = $entries
        CatalogVersion = [string]$json.catalogVersion
        DateReleased = $dateReleased.ToString('o', [Globalization.CultureInfo]::InvariantCulture)
        Count = $declaredCount
        SourceUrl = $script:WsaKevUri
    }
}

function Get-WsaPriorityFileHash {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$Path)

    $stream = $null
    $sha = $null
    try {
        $sha = [Security.Cryptography.SHA256]::Create()
        $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
        return ([BitConverter]::ToString($sha.ComputeHash($stream))).Replace('-', '').ToLowerInvariant()
    }
    finally {
        if ($null -ne $stream) { $stream.Dispose() }
        if ($null -ne $sha) { $sha.Dispose() }
    }
}

function Move-WsaPriorityCacheFile {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$Path,
        [Parameter(Mandatory = $true)][string]$Destination
    )

    if (Test-Path -LiteralPath $Destination -PathType Leaf) {
        [IO.File]::Replace($Path, $Destination, $null)
    }
    else {
        [IO.File]::Move($Path, $Destination)
    }
}

function Write-WsaPriorityJsonFile {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$Path,
        [Parameter(Mandatory = $true)][AllowNull()]$Value
    )

    $directory = Split-Path -Parent $Path
    $tempPath = Join-Path $directory (([IO.Path]::GetFileName($Path)) + '.' + [Guid]::NewGuid().ToString('N') + '.tmp')
    try {
        $json = ConvertTo-Json -InputObject $Value -Depth 10 -ErrorAction Stop
        [IO.File]::WriteAllText($tempPath, $json, [Text.UTF8Encoding]::new($false))
        Move-WsaPriorityCacheFile -Path $tempPath -Destination $Path
    }
    finally {
        if (Test-Path -LiteralPath $tempPath -PathType Leaf) {
            Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
        }
    }
}

function Get-WsaPriorityCacheLayout {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][ValidateSet('EpssApi', 'EpssCsv', 'Kev')][string]$Feed)

    switch ($Feed) {
        'EpssApi' {
            return [PSCustomObject]@{
                BaseName = 'epss-api-cache'
                DataSuffix = '.data.json'
                ManifestName = 'epss-api-cache.manifest.json'
                LegacyDataName = 'epss-api-cache.json'
                LegacyMetadataName = 'epss-api-cache.metadata.json'
            }
        }
        'EpssCsv' {
            return [PSCustomObject]@{
                BaseName = 'epss-csv'
                DataSuffix = '.data.csv.gz'
                ManifestName = 'epss-csv.manifest.json'
                LegacyDataName = 'epss_scores-current.csv.gz'
                LegacyMetadataName = 'epss-csv.metadata.json'
            }
        }
        'Kev' {
            return [PSCustomObject]@{
                BaseName = 'kev'
                DataSuffix = '.data.json'
                ManifestName = 'kev.manifest.json'
                LegacyDataName = 'known_exploited_vulnerabilities.json'
                LegacyMetadataName = 'kev.metadata.json'
            }
        }
    }
}

function New-WsaPriorityCacheGenerationPaths {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][ValidateSet('EpssApi', 'EpssCsv', 'Kev')][string]$Feed
    )

    $layout = Get-WsaPriorityCacheLayout -Feed $Feed
    $generation = [Guid]::NewGuid().ToString('N')
    $dataFile = $layout.BaseName + '.' + $generation + $layout.DataSuffix
    $metadataFile = $layout.BaseName + '.' + $generation + '.metadata.json'
    return [PSCustomObject]@{
        Generation = $generation
        DataFile = $dataFile
        MetadataFile = $metadataFile
        DataPath = Join-Path $CachePath $dataFile
        MetadataPath = Join-Path $CachePath $metadataFile
        ManifestPath = Join-Path $CachePath $layout.ManifestName
    }
}

function Resolve-WsaPriorityCachePaths {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][ValidateSet('EpssApi', 'EpssCsv', 'Kev')][string]$Feed
    )

    $layout = Get-WsaPriorityCacheLayout -Feed $Feed
    $manifestPath = Join-Path $CachePath $layout.ManifestName
    if (Test-Path -LiteralPath $manifestPath -PathType Leaf) {
        $manifest = [IO.File]::ReadAllText($manifestPath, [Text.Encoding]::UTF8) | ConvertFrom-Json -ErrorAction Stop
        foreach ($property in @('SchemaVersion', 'Feed', 'Generation', 'DataFile', 'MetadataFile', 'MetadataSha256')) {
            if (-not (Test-WsaPriorityProperty -InputObject $manifest -Name $property)) {
                throw [System.FormatException]::new("Cache manifest is missing $property.")
            }
        }
        if ([int]$manifest.SchemaVersion -ne $script:WsaPriorityCacheSchemaVersion -or [string]$manifest.Feed -cne $Feed) {
            throw [System.FormatException]::new('Cache manifest schema or feed is invalid.')
        }

        $generation = [string]$manifest.Generation
        if ($generation -cnotmatch '^[0-9a-f]{32}$') {
            throw [System.FormatException]::new('Cache manifest generation is invalid.')
        }
        $expectedDataFile = $layout.BaseName + '.' + $generation + $layout.DataSuffix
        $expectedMetadataFile = $layout.BaseName + '.' + $generation + '.metadata.json'
        if ([string]$manifest.DataFile -cne $expectedDataFile -or [string]$manifest.MetadataFile -cne $expectedMetadataFile) {
            throw [System.FormatException]::new('Cache manifest file names do not match its generation.')
        }

        $dataPath = Join-Path $CachePath $expectedDataFile
        $metadataPath = Join-Path $CachePath $expectedMetadataFile
        if (-not (Test-Path -LiteralPath $dataPath -PathType Leaf) -or -not (Test-Path -LiteralPath $metadataPath -PathType Leaf)) {
            throw [System.FormatException]::new('Cache manifest refers to a missing generation.')
        }
        $metadataHash = Get-WsaPriorityFileHash -Path $metadataPath
        if (-not [string]::Equals([string]$manifest.MetadataSha256, $metadataHash, [StringComparison]::OrdinalIgnoreCase)) {
            throw [System.FormatException]::new('Cache metadata hash does not match its manifest.')
        }
        return [PSCustomObject]@{
            Generation = $generation
            DataFile = $expectedDataFile
            MetadataFile = $expectedMetadataFile
            DataPath = $dataPath
            MetadataPath = $metadataPath
            ManifestPath = $manifestPath
        }
    }

    return [PSCustomObject]@{
        Generation = $null
        DataFile = $layout.LegacyDataName
        MetadataFile = $layout.LegacyMetadataName
        DataPath = Join-Path $CachePath $layout.LegacyDataName
        MetadataPath = Join-Path $CachePath $layout.LegacyMetadataName
        ManifestPath = $manifestPath
    }
}

function Test-WsaPriorityCacheExists {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][ValidateSet('EpssApi', 'EpssCsv', 'Kev')][string]$Feed
    )

    $layout = Get-WsaPriorityCacheLayout -Feed $Feed
    if (Test-Path -LiteralPath (Join-Path $CachePath $layout.ManifestName) -PathType Leaf) {
        return $true
    }
    return (Test-Path -LiteralPath (Join-Path $CachePath $layout.LegacyDataName) -PathType Leaf) -and
        (Test-Path -LiteralPath (Join-Path $CachePath $layout.LegacyMetadataName) -PathType Leaf)
}

function Publish-WsaPriorityCacheGeneration {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]$Paths,
        [Parameter(Mandatory = $true)][ValidateSet('EpssApi', 'EpssCsv', 'Kev')][string]$Feed
    )

    $manifest = [PSCustomObject]@{
        SchemaVersion = $script:WsaPriorityCacheSchemaVersion
        Feed = $Feed
        Generation = $Paths.Generation
        DataFile = $Paths.DataFile
        MetadataFile = $Paths.MetadataFile
        MetadataSha256 = Get-WsaPriorityFileHash -Path $Paths.MetadataPath
    }
    Write-WsaPriorityJsonFile -Path $Paths.ManifestPath -Value $manifest
}

function Remove-WsaPriorityCacheGeneration {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)]$Paths)

    foreach ($path in @($Paths.DataPath, $Paths.MetadataPath)) {
        if (Test-Path -LiteralPath $path -PathType Leaf) {
            Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
        }
    }
}

function Read-WsaPriorityMetadata {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$Path,
        [Parameter(Mandatory = $true)][string]$Feed,
        [Parameter(Mandatory = $true)][string]$DataPath
    )

    $metadata = [IO.File]::ReadAllText($Path, [Text.Encoding]::UTF8) | ConvertFrom-Json -ErrorAction Stop
    foreach ($property in @('SchemaVersion', 'Feed', 'FetchedAtUtc', 'SourceUrl', 'Coverage', 'CveIds', 'ContentSha256')) {
        if (-not (Test-WsaPriorityProperty -InputObject $metadata -Name $property)) {
            throw [System.FormatException]::new("Cache metadata is missing $property.")
        }
    }
    if ([int]$metadata.SchemaVersion -ne $script:WsaPriorityCacheSchemaVersion -or [string]$metadata.Feed -cne $Feed) {
        throw [System.FormatException]::new('Cache metadata schema or feed is invalid.')
    }
    $fetchedAt = ConvertTo-WsaUtcDateOffset -Value $metadata.FetchedAtUtc -FieldName 'Cache FetchedAtUtc'
    if ([string]::IsNullOrWhiteSpace([string]$metadata.SourceUrl) -or [string]::IsNullOrWhiteSpace([string]$metadata.ContentSha256)) {
        throw [System.FormatException]::new('Cache metadata source or content hash is empty.')
    }
    if (-not (Test-Path -LiteralPath $DataPath -PathType Leaf)) {
        throw [System.FormatException]::new('Cache data file is missing.')
    }
    $actualHash = Get-WsaPriorityFileHash -Path $DataPath
    if (-not [string]::Equals([string]$metadata.ContentSha256, $actualHash, [StringComparison]::OrdinalIgnoreCase)) {
        throw [System.FormatException]::new('Cache content hash does not match its metadata.')
    }
    if ($Feed -eq 'EpssApi') {
        if ([string]$metadata.Coverage -ne 'Subset') {
            throw [System.FormatException]::new('EPSS API cache must declare subset coverage.')
        }
        $coverage = @{}
        foreach ($id in @($metadata.CveIds)) {
            if (-not (Test-WsaCveId -CveId $id)) {
                throw [System.FormatException]::new('EPSS API cache coverage contains an invalid CVE.')
            }
            $normalized = ([string]$id).ToUpperInvariant()
            if ($coverage.ContainsKey($normalized)) {
                throw [System.FormatException]::new('EPSS API cache coverage contains duplicates.')
            }
            $coverage[$normalized] = $true
        }
        if ($coverage.Count -eq 0) {
            throw [System.FormatException]::new('EPSS API cache coverage is empty.')
        }
    }
    elseif ([string]$metadata.Coverage -ne 'Full') {
        throw [System.FormatException]::new("$Feed cache must declare full coverage.")
    }

    $metadata | Add-Member -NotePropertyName FetchedAt -NotePropertyValue $fetchedAt -Force
    return $metadata
}

function Test-WsaPriorityCacheFresh {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]$Metadata,
        [Parameter(Mandatory = $true)][DateTimeOffset]$Now,
        [Parameter(Mandatory = $true)][int]$MaxAgeHours
    )

    $age = $Now - $Metadata.FetchedAt
    return $age.TotalMilliseconds -ge 0 -and $age.TotalHours -lt $MaxAgeHours
}

function New-WsaEpssFeedResult {
    [CmdletBinding()]
    param(
        [hashtable]$Entries = @{},
        [hashtable]$CoveredCves = @{},
        [string]$Source = 'Unavailable',
        [AllowNull()][string]$ScoreDate,
        [AllowNull()][string]$ModelVersion,
        [AllowNull()][string]$FetchedAtUtc,
        [AllowNull()][string]$Error
    )

    return [PSCustomObject]@{
        Entries = $Entries
        CoveredCves = $CoveredCves
        Source = $Source
        ScoreDate = $ScoreDate
        ModelVersion = $ModelVersion
        FetchedAtUtc = $FetchedAtUtc
        Error = $Error
    }
}

function New-WsaKevFeedResult {
    [CmdletBinding()]
    param(
        [hashtable]$Entries = @{},
        [string]$Source = 'Unavailable',
        [AllowNull()][string]$CatalogVersion,
        [AllowNull()][string]$DateReleased,
        [AllowNull()][string]$FetchedAtUtc,
        [AllowNull()][string]$Error
    )

    return [PSCustomObject]@{
        Entries = $Entries
        Source = $Source
        CatalogVersion = $CatalogVersion
        DateReleased = $DateReleased
        FetchedAtUtc = $FetchedAtUtc
        Error = $Error
    }
}

function Read-WsaEpssApiCache {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][DateTimeOffset]$Now,
        [Parameter(Mandatory = $true)][int]$MaxAgeHours
    )

    $paths = Resolve-WsaPriorityCachePaths -CachePath $CachePath -Feed 'EpssApi'
    $dataPath = $paths.DataPath
    $metadataPath = $paths.MetadataPath
    $metadata = Read-WsaPriorityMetadata -Path $metadataPath -Feed 'EpssApi' -DataPath $dataPath
    $jsonText = [IO.File]::ReadAllText($dataPath, [Text.Encoding]::UTF8)
    $data = $jsonText | ConvertFrom-Json -ErrorAction Stop
    if ($null -eq $data -and $jsonText -notmatch '^\s*\[\s*\]\s*$') {
        throw [System.FormatException]::new('EPSS API cache data is null or malformed.')
    }
    $coverage = @{}
    foreach ($id in @($metadata.CveIds)) {
        $coverage[([string]$id).ToUpperInvariant()] = $true
    }
    $entries = @{}
    foreach ($row in @($data)) {
        foreach ($field in @('CVEId', 'EpssScore', 'EpssPercentile', 'EpssScoreDate')) {
            if (-not (Test-WsaPriorityProperty -InputObject $row -Name $field) -or $null -eq $row.$field) {
                throw [System.FormatException]::new("EPSS API cache row is missing $field.")
            }
        }
        $id = ([string]$row.CVEId).ToUpperInvariant()
        if (-not (Test-WsaCveId -CveId $id) -or -not $coverage.ContainsKey($id) -or $entries.ContainsKey($id)) {
            throw [System.FormatException]::new('EPSS API cache contains an unexpected or duplicate CVE.')
        }
        $scoreDate = ConvertTo-WsaUtcDateOffset -Value $row.EpssScoreDate -FieldName 'Cached EPSS score date'
        $entries[$id] = [PSCustomObject]@{
            CVEId = $id
            EpssScore = ConvertTo-WsaProbability -Value $row.EpssScore -FieldName 'Cached EPSS score'
            EpssPercentile = ConvertTo-WsaProbability -Value $row.EpssPercentile -FieldName 'Cached EPSS percentile'
            EpssScoreDate = $scoreDate.ToString('yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)
        }
    }
    $scoreDate = $null
    if ((Test-WsaPriorityProperty -InputObject $metadata -Name 'ScoreDate') -and $null -ne $metadata.ScoreDate) {
        $scoreDate = [string]$metadata.ScoreDate
    }
    $modelVersion = $null
    if ((Test-WsaPriorityProperty -InputObject $metadata -Name 'ModelVersion') -and $null -ne $metadata.ModelVersion) {
        $modelVersion = [string]$metadata.ModelVersion
    }
    $result = New-WsaEpssFeedResult -Entries $entries -CoveredCves $coverage -Source 'Cache' -ScoreDate $scoreDate -ModelVersion $modelVersion -FetchedAtUtc $metadata.FetchedAtUtc
    $result | Add-Member -NotePropertyName Metadata -NotePropertyValue $metadata
    $result | Add-Member -NotePropertyName IsFresh -NotePropertyValue (Test-WsaPriorityCacheFresh -Metadata $metadata -Now $Now -MaxAgeHours $MaxAgeHours)
    $result | Add-Member -NotePropertyName Kind -NotePropertyValue 'Api'
    return $result
}

function Read-WsaEpssCsvCache {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][string[]]$CveIds,
        [Parameter(Mandatory = $true)][DateTimeOffset]$Now,
        [Parameter(Mandatory = $true)][int]$MaxAgeHours
    )

    $paths = Resolve-WsaPriorityCachePaths -CachePath $CachePath -Feed 'EpssCsv'
    $dataPath = $paths.DataPath
    $metadataPath = $paths.MetadataPath
    $metadata = Read-WsaPriorityMetadata -Path $metadataPath -Feed 'EpssCsv' -DataPath $dataPath
    foreach ($field in @('ScoreDate', 'ModelVersion')) {
        if (-not (Test-WsaPriorityProperty -InputObject $metadata -Name $field) -or $null -eq $metadata.$field) {
            throw [System.FormatException]::new("EPSS CSV cache metadata is missing $field.")
        }
    }
    $data = Read-WsaEpssCsv -Path $dataPath -CveIds $CveIds
    $metadataScoreDate = ConvertTo-WsaUtcDateOffset -Value $metadata.ScoreDate -FieldName 'Cached EPSS CSV ScoreDate'
    $dataScoreDate = ConvertTo-WsaUtcDateOffset -Value $data.ScoreDate -FieldName 'EPSS CSV ScoreDate'
    if ($metadataScoreDate -ne $dataScoreDate -or [string]$metadata.ModelVersion -cne [string]$data.ModelVersion) {
        throw [System.FormatException]::new('EPSS CSV cache data and metadata do not match.')
    }
    $result = New-WsaEpssFeedResult -Entries $data.Entries -CoveredCves $data.CoveredCves -Source 'Cache' -ScoreDate $data.ScoreDate -ModelVersion $data.ModelVersion -FetchedAtUtc $metadata.FetchedAtUtc
    $result | Add-Member -NotePropertyName Metadata -NotePropertyValue $metadata
    $result | Add-Member -NotePropertyName IsFresh -NotePropertyValue (Test-WsaPriorityCacheFresh -Metadata $metadata -Now $Now -MaxAgeHours $MaxAgeHours)
    $result | Add-Member -NotePropertyName Kind -NotePropertyValue 'Csv'
    return $result
}

function Read-WsaKevCache {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][DateTimeOffset]$Now,
        [Parameter(Mandatory = $true)][int]$MaxAgeHours
    )

    $paths = Resolve-WsaPriorityCachePaths -CachePath $CachePath -Feed 'Kev'
    $dataPath = $paths.DataPath
    $metadataPath = $paths.MetadataPath
    $metadata = Read-WsaPriorityMetadata -Path $metadataPath -Feed 'Kev' -DataPath $dataPath
    foreach ($field in @('CatalogVersion', 'DateReleased')) {
        if (-not (Test-WsaPriorityProperty -InputObject $metadata -Name $field) -or $null -eq $metadata.$field) {
            throw [System.FormatException]::new("KEV cache metadata is missing $field.")
        }
    }
    $data = Read-WsaKevCatalog -Path $dataPath
    $metadataDateReleased = ConvertTo-WsaUtcDateOffset -Value $metadata.DateReleased -FieldName 'Cached KEV DateReleased'
    $dataDateReleased = ConvertTo-WsaUtcDateOffset -Value $data.DateReleased -FieldName 'KEV DateReleased'
    if ([string]$metadata.CatalogVersion -cne [string]$data.CatalogVersion -or $metadataDateReleased -ne $dataDateReleased) {
        throw [System.FormatException]::new('KEV cache data and metadata do not match.')
    }
    $result = New-WsaKevFeedResult -Entries $data.Entries -Source 'Cache' -CatalogVersion $data.CatalogVersion -DateReleased $data.DateReleased -FetchedAtUtc $metadata.FetchedAtUtc
    $result | Add-Member -NotePropertyName Metadata -NotePropertyValue $metadata
    $result | Add-Member -NotePropertyName IsFresh -NotePropertyValue (Test-WsaPriorityCacheFresh -Metadata $metadata -Now $Now -MaxAgeHours $MaxAgeHours)
    return $result
}

function Save-WsaEpssApiCache {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)]$Data,
        [Parameter(Mandatory = $true)][string[]]$CveIds,
        [Parameter(Mandatory = $true)][DateTimeOffset]$FetchedAt
    )

    $coverage = @()
    $seen = @{}
    foreach ($id in ($CveIds | Sort-Object)) {
        $normalized = ([string]$id).ToUpperInvariant()
        if (-not (Test-WsaCveId -CveId $normalized)) {
            throw [System.ArgumentException]::new('Cannot cache coverage for an invalid CVE.')
        }
        if (-not $seen.ContainsKey($normalized)) {
            $seen[$normalized] = $true
            $coverage += $normalized
        }
    }
    $rows = @($Data.Entries.Values | Sort-Object CVEId)
    $paths = New-WsaPriorityCacheGenerationPaths -CachePath $CachePath -Feed 'EpssApi'
    $committed = $false
    try {
        Write-WsaPriorityJsonFile -Path $paths.DataPath -Value $rows
        $metadata = [PSCustomObject]@{
            SchemaVersion = $script:WsaPriorityCacheSchemaVersion
            Feed = 'EpssApi'
            FetchedAtUtc = $FetchedAt.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture)
            SourceUrl = $script:WsaEpssApiUri
            ScoreDate = $Data.ScoreDate
            ModelVersion = $Data.ModelVersion
            DateReleased = $null
            CatalogVersion = $null
            Coverage = 'Subset'
            CveIds = $coverage
            ContentSha256 = Get-WsaPriorityFileHash -Path $paths.DataPath
        }
        Write-WsaPriorityJsonFile -Path $paths.MetadataPath -Value $metadata
        Publish-WsaPriorityCacheGeneration -Paths $paths -Feed 'EpssApi'
        $committed = $true
    }
    finally {
        if (-not $committed) {
            Remove-WsaPriorityCacheGeneration -Paths $paths
        }
    }
}

function Save-WsaEpssCsvDownload {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][string]$DownloadPath,
        [Parameter(Mandatory = $true)]$Data,
        [Parameter(Mandatory = $true)][DateTimeOffset]$FetchedAt
    )

    $hash = Get-WsaPriorityFileHash -Path $DownloadPath
    $paths = New-WsaPriorityCacheGenerationPaths -CachePath $CachePath -Feed 'EpssCsv'
    $committed = $false
    try {
        Move-WsaPriorityCacheFile -Path $DownloadPath -Destination $paths.DataPath
        $metadata = [PSCustomObject]@{
            SchemaVersion = $script:WsaPriorityCacheSchemaVersion
            Feed = 'EpssCsv'
            FetchedAtUtc = $FetchedAt.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture)
            SourceUrl = $script:WsaEpssCsvUri
            ScoreDate = $Data.ScoreDate
            ModelVersion = $Data.ModelVersion
            DateReleased = $null
            CatalogVersion = $null
            Coverage = 'Full'
            CveIds = @()
            ContentSha256 = $hash
        }
        Write-WsaPriorityJsonFile -Path $paths.MetadataPath -Value $metadata
        Publish-WsaPriorityCacheGeneration -Paths $paths -Feed 'EpssCsv'
        $committed = $true
    }
    finally {
        if (-not $committed) {
            Remove-WsaPriorityCacheGeneration -Paths $paths
        }
    }
}

function Save-WsaKevDownload {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][string]$DownloadPath,
        [Parameter(Mandatory = $true)]$Data,
        [Parameter(Mandatory = $true)][DateTimeOffset]$FetchedAt
    )

    $hash = Get-WsaPriorityFileHash -Path $DownloadPath
    $paths = New-WsaPriorityCacheGenerationPaths -CachePath $CachePath -Feed 'Kev'
    $committed = $false
    try {
        Move-WsaPriorityCacheFile -Path $DownloadPath -Destination $paths.DataPath
        $metadata = [PSCustomObject]@{
            SchemaVersion = $script:WsaPriorityCacheSchemaVersion
            Feed = 'Kev'
            FetchedAtUtc = $FetchedAt.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture)
            SourceUrl = $script:WsaKevUri
            ScoreDate = $null
            ModelVersion = $null
            DateReleased = $Data.DateReleased
            CatalogVersion = $Data.CatalogVersion
            Coverage = 'Full'
            CveIds = @()
            ContentSha256 = $hash
        }
        Write-WsaPriorityJsonFile -Path $paths.MetadataPath -Value $metadata
        Publish-WsaPriorityCacheGeneration -Paths $paths -Feed 'Kev'
        $committed = $true
    }
    finally {
        if (-not $committed) {
            Remove-WsaPriorityCacheGeneration -Paths $paths
        }
    }
}

function Test-WsaEpssCoverage {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]$Feed,
        [Parameter(Mandatory = $true)][string[]]$CveIds
    )

    foreach ($id in $CveIds) {
        if (-not $Feed.CoveredCves.ContainsKey(([string]$id).ToUpperInvariant())) {
            return $false
        }
    }
    return $true
}

function Select-WsaEpssCache {
    [CmdletBinding()]
    param(
        [AllowNull()]$CsvCache,
        [AllowNull()]$ApiCache,
        [Parameter(Mandatory = $true)][string[]]$CveIds,
        [bool]$AllowStale,
        [bool]$IgnoreFresh
    )

    $candidates = @()
    foreach ($candidate in @($CsvCache, $ApiCache)) {
        if ($null -eq $candidate) {
            continue
        }
        if ($candidate.IsFresh) {
            if ($IgnoreFresh) {
                continue
            }
        }
        elseif (-not $AllowStale) {
            continue
        }
        $rank = 0
        if ($candidate.Kind -eq 'Csv') {
            $rank = 300
        }
        elseif (Test-WsaEpssCoverage -Feed $candidate -CveIds $CveIds) {
            $rank = 200
        }
        else {
            $rank = 100
        }
        if ($candidate.IsFresh) {
            $rank += 1000
        }
        $candidate | Add-Member -NotePropertyName SelectionRank -NotePropertyValue $rank -Force
        $candidates += $candidate
    }

    return $candidates | Sort-Object -Property SelectionRank -Descending | Select-Object -First 1
}

function Get-WsaLiveEpssCsv {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [Parameter(Mandatory = $true)][string[]]$CveIds
    )

    Initialize-WsaPriorityCacheDirectory -Path $CachePath | Out-Null
    $tempPath = Join-Path $CachePath ('epss_scores-current.' + [Guid]::NewGuid().ToString('N') + '.tmp')
    try {
        Invoke-WsaPriorityFileDownload -Uri $script:WsaEpssCsvUri -OutFile $tempPath
        $data = Read-WsaEpssCsv -Path $tempPath -CveIds $CveIds
        $fetchedAt = Get-WsaPriorityUtcNow
        try {
            Save-WsaEpssCsvDownload -CachePath $CachePath -DownloadPath $tempPath -Data $data -FetchedAt $fetchedAt
        }
        catch {
            Write-Warning "EPSS CSV was validated but could not be cached: $($_.Exception.Message)"
        }
        return New-WsaEpssFeedResult -Entries $data.Entries -CoveredCves $data.CoveredCves -Source 'Live' -ScoreDate $data.ScoreDate -ModelVersion $data.ModelVersion -FetchedAtUtc $fetchedAt.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture)
    }
    finally {
        if (Test-Path -LiteralPath $tempPath -PathType Leaf) {
            Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
        }
    }
}

function Get-WsaLiveKev {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$CachePath)

    Initialize-WsaPriorityCacheDirectory -Path $CachePath | Out-Null
    $tempPath = Join-Path $CachePath ('known_exploited_vulnerabilities.' + [Guid]::NewGuid().ToString('N') + '.tmp')
    try {
        Invoke-WsaPriorityFileDownload -Uri $script:WsaKevUri -OutFile $tempPath
        $data = Read-WsaKevCatalog -Path $tempPath
        $fetchedAt = Get-WsaPriorityUtcNow
        try {
            Save-WsaKevDownload -CachePath $CachePath -DownloadPath $tempPath -Data $data -FetchedAt $fetchedAt
        }
        catch {
            Write-Warning "KEV catalog was validated but could not be cached: $($_.Exception.Message)"
        }
        return New-WsaKevFeedResult -Entries $data.Entries -Source 'Live' -CatalogVersion $data.CatalogVersion -DateReleased $data.DateReleased -FetchedAtUtc $fetchedAt.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture)
    }
    finally {
        if (Test-Path -LiteralPath $tempPath -PathType Leaf) {
            Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
        }
    }
}

function Get-WsaEpssFeed {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string[]]$CveIds,
        [Parameter(Mandatory = $true)][string]$CachePath,
        [ValidateSet('Auto', 'Api', 'Csv')][string]$Mode = 'Auto',
        [int]$CacheMaxAgeHours = 24,
        [switch]$Offline,
        [switch]$AllowStaleCache,
        [switch]$ForceRefresh
    )

    if ($CveIds.Count -eq 0) {
        return New-WsaEpssFeedResult
    }
    $now = Get-WsaPriorityUtcNow
    $csvCache = $null
    $apiCache = $null
    $cacheErrors = New-Object 'System.Collections.Generic.List[string]'
    if (Test-WsaPriorityCacheExists -CachePath $CachePath -Feed 'EpssCsv') {
        try {
            $csvCache = Read-WsaEpssCsvCache -CachePath $CachePath -CveIds $CveIds -Now $now -MaxAgeHours $CacheMaxAgeHours
        }
        catch {
            $cacheErrors.Add("CSV cache: $($_.Exception.Message)")
        }
    }
    if (Test-WsaPriorityCacheExists -CachePath $CachePath -Feed 'EpssApi') {
        try {
            $apiCache = Read-WsaEpssApiCache -CachePath $CachePath -Now $now -MaxAgeHours $CacheMaxAgeHours
        }
        catch {
            $cacheErrors.Add("API cache: $($_.Exception.Message)")
        }
    }

    $initial = Select-WsaEpssCache -CsvCache $csvCache -ApiCache $apiCache -CveIds $CveIds -AllowStale:($Offline.IsPresent -and $AllowStaleCache.IsPresent) -IgnoreFresh:($ForceRefresh.IsPresent -and -not $Offline.IsPresent)
    if ($null -ne $initial -and ($Offline.IsPresent -or (Test-WsaEpssCoverage -Feed $initial -CveIds $CveIds))) {
        $initial.Source = if ($initial.IsFresh) { 'Cache' } else { 'Stale' }
        return $initial
    }
    if ($Offline.IsPresent) {
        $message = 'No eligible cached EPSS data is available.'
        if ($cacheErrors.Count -gt 0) {
            $message += ' ' + ($cacheErrors -join '; ')
        }
        return New-WsaEpssFeedResult -Error $message
    }

    $refreshError = $null
    try {
        $batchCount = @(New-WsaEpssBatch -CveIds $CveIds).Count
        if ($Mode -eq 'Api' -or ($Mode -eq 'Auto' -and $batchCount -eq 1)) {
            Initialize-WsaPriorityCacheDirectory -Path $CachePath | Out-Null
            $data = Get-WsaEpssApiData -CveIds $CveIds
            $fetchedAt = Get-WsaPriorityUtcNow
            try {
                Save-WsaEpssApiCache -CachePath $CachePath -Data $data -CveIds $CveIds -FetchedAt $fetchedAt
            }
            catch {
                Write-Warning "EPSS API data was validated but could not be cached: $($_.Exception.Message)"
            }
            return New-WsaEpssFeedResult -Entries $data.Entries -CoveredCves $data.CoveredCves -Source 'Live' -ScoreDate $data.ScoreDate -ModelVersion $data.ModelVersion -FetchedAtUtc $fetchedAt.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture)
        }
        return Get-WsaLiveEpssCsv -CachePath $CachePath -CveIds $CveIds
    }
    catch {
        $refreshError = $_.Exception.Message
    }

    $fallback = Select-WsaEpssCache -CsvCache $csvCache -ApiCache $apiCache -CveIds $CveIds -AllowStale:$AllowStaleCache.IsPresent -IgnoreFresh:$false
    if ($null -ne $fallback) {
        $fallback.Source = if ($fallback.IsFresh) { 'Cache' } else { 'Stale' }
        $fallback.Error = $refreshError
        return $fallback
    }
    $message = "EPSS refresh failed: $refreshError"
    if ($cacheErrors.Count -gt 0) {
        $message += ' ' + ($cacheErrors -join '; ')
    }
    return New-WsaEpssFeedResult -Error $message
}

function Get-WsaKevFeed {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$CachePath,
        [int]$CacheMaxAgeHours = 24,
        [switch]$Offline,
        [switch]$AllowStaleCache,
        [switch]$ForceRefresh
    )

    $now = Get-WsaPriorityUtcNow
    $cache = $null
    $cacheError = $null
    if (Test-WsaPriorityCacheExists -CachePath $CachePath -Feed 'Kev') {
        try {
            $cache = Read-WsaKevCache -CachePath $CachePath -Now $now -MaxAgeHours $CacheMaxAgeHours
        }
        catch {
            $cacheError = $_.Exception.Message
        }
    }
    if ($null -ne $cache -and ($cache.IsFresh -or $Offline.IsPresent) -and
        ($cache.IsFresh -or $AllowStaleCache.IsPresent) -and
        (-not $ForceRefresh.IsPresent -or $Offline.IsPresent)) {
        $cache.Source = if ($cache.IsFresh) { 'Cache' } else { 'Stale' }
        return $cache
    }
    if ($Offline.IsPresent) {
        $message = 'No eligible cached KEV catalog is available.'
        if ($cacheError) {
            $message += " $cacheError"
        }
        return New-WsaKevFeedResult -Error $message
    }

    $refreshError = $null
    try {
        return Get-WsaLiveKev -CachePath $CachePath
    }
    catch {
        $refreshError = $_.Exception.Message
    }
    if ($null -ne $cache -and ($cache.IsFresh -or $AllowStaleCache.IsPresent)) {
        $cache.Source = if ($cache.IsFresh) { 'Cache' } else { 'Stale' }
        $cache.Error = $refreshError
        return $cache
    }
    $message = "KEV refresh failed: $refreshError"
    if ($cacheError) {
        $message += " $cacheError"
    }
    return New-WsaKevFeedResult -Error $message
}