feat(ui): redesign the dashboard as a package checkpoint

Add overview, packages with quick view, package detail tabs, a merged security page, insights, system and restyled bypasses. Old vulnerable and blocked routes redirect to the matching security tab.
This commit is contained in:
2026-11-24 01:13:09 +00:00
parent 45aa4bcace
commit 671bb0625b
50 changed files with 3022 additions and 1937 deletions
+22
View File
@@ -0,0 +1,22 @@
import { computed, ref } from 'vue'
const STORAGE_KEY = 'admin_api_key'
const key = ref(typeof localStorage === 'undefined' ? '' : (localStorage.getItem(STORAGE_KEY) ?? ''))
/** The admin API key the dashboard sends with admin calls; kept in localStorage. */
export function useAdminKey() {
function load() {
key.value = localStorage.getItem(STORAGE_KEY) ?? ''
}
function save(value: string) {
key.value = value
localStorage.setItem(STORAGE_KEY, value)
}
function clear() {
key.value = ''
localStorage.removeItem(STORAGE_KEY)
}
const headers = computed(() => ({ Authorization: `Bearer ${key.value}` }))
return { key, headers, load, save, clear }
}
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest'
import { bypassesFor, isLive, type Bypass } from './bypass'
function bypass(over: Partial<Bypass>): Bypass {
return {
id: 'b',
type: 'package',
target: 'npm/left-pad',
reason: 'r',
created_by: 'a',
created_at: '2026-01-01T00:00:00Z',
expires_at: '2099-01-01T00:00:00Z',
notify_on_expiry: false,
active: true,
...over,
}
}
describe('bypassesFor', () => {
const pkg = { registry: 'npm', name: 'left-pad', version: '1.3.0' }
it('matches a package bypass by name and by name@version', () => {
const all = [
bypass({ id: 'any', target: 'npm/left-pad' }),
bypass({ id: 'pinned', target: 'npm/[email protected]' }),
bypass({ id: 'other-version', target: 'npm/[email protected]' }),
bypass({ id: 'other-package', target: 'npm/lodash' }),
]
expect(bypassesFor(all, pkg).map((b) => b.id)).toEqual(['any', 'pinned'])
})
it('matches a CVE bypass with no scope or a scope on this package', () => {
const all = [
bypass({ id: 'global', type: 'cve', target: 'CVE-1' }),
bypass({ id: 'scoped', type: 'cve', target: 'CVE-2', applies_to: 'npm/[email protected]' }),
bypass({ id: 'elsewhere', type: 'cve', target: 'CVE-3', applies_to: 'npm/lodash' }),
]
expect(bypassesFor(all, pkg).map((b) => b.id)).toEqual(['global', 'scoped'])
})
it('keys Go packages by module path, not by cache key', () => {
const go = { registry: 'go', name: 'github.com/a/b/@v/v1.0.0.zip', version: 'v1.0.0' }
expect(bypassesFor([bypass({ target: 'go/github.com/a/[email protected]' })], go)).toHaveLength(1)
})
it('matches a PyPI release version', () => {
const py = { registry: 'pypi', name: 'six', version: 'six-1.0.tar.gz', releaseVersion: '1.0' }
expect(bypassesFor([bypass({ target: 'pypi/[email protected]' })], py)).toHaveLength(1)
})
})
describe('isLive', () => {
it('requires active and unexpired', () => {
const now = Date.parse('2026-06-01T00:00:00Z')
expect(isLive(bypass({}), now)).toBe(true)
expect(isLive(bypass({ active: false }), now)).toBe(false)
expect(isLive(bypass({ expires_at: '2026-01-01T00:00:00Z' }), now)).toBe(false)
})
})
+38
View File
@@ -0,0 +1,38 @@
export interface Bypass {
id: string
type: 'cve' | 'package'
target: string
reason: string
created_by: string
created_at: string
expires_at: string
applies_to?: string
notify_on_expiry: boolean
active: boolean
}
export function isExpired(expiresAt: string, now = Date.now()): boolean {
return Date.parse(expiresAt) < now
}
/** Active and not yet expired. */
export function isLive(bypass: Bypass, now = Date.now()): boolean {
return bypass.active && !isExpired(bypass.expires_at, now)
}
/** Bypass keys use the module path for Go, where stored rows end in `/@v/<version>.<ext>`. */
function bypassName(registry: string, name: string): string {
const at = name.indexOf('/@v/')
return registry === 'go' && at !== -1 ? name.slice(0, at) : name
}
/** The bypasses that cover one package version, by the same keys the server matches. */
export function bypassesFor(
all: readonly Bypass[],
pkg: { registry: string; name: string; version: string; releaseVersion?: string },
): Bypass[] {
const base = `${pkg.registry}/${bypassName(pkg.registry, pkg.name)}`
const keys = new Set([`${base}@${pkg.version}`, base])
if (pkg.releaseVersion) keys.add(`${base}@${pkg.releaseVersion}`)
return all.filter((b) => (b.type === 'package' ? keys.has(b.target) : !b.applies_to || keys.has(b.applies_to)))
}
+6
View File
@@ -40,3 +40,9 @@ export function displayVersion(pkg: { version: string; release_version?: string
export function withVersionPrefix(version: string): string {
return version.startsWith('v') ? version : 'v' + version
}
/** Go cache keys end in `/@v/<version>.<ext>`; the module path is what a person recognises. */
export function modulePath(name: string): string {
const at = name.indexOf('/@v/')
return at === -1 ? name : name.slice(0, at)
}
+5
View File
@@ -1,5 +1,6 @@
export {
faArrowLeft,
faArrowRight,
faBan,
faBox,
faBoxOpen,
@@ -8,10 +9,14 @@ export {
faChartLine,
faChartPie,
faDownload,
faGear,
faHardDrive,
faHourglassHalf,
faKey,
faPen,
faShieldHalved,
faTrash,
faUnlockKeyhole,
faTriangleExclamation,
} from '@fortawesome/free-solid-svg-icons'
export {
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { inspectorRows, type ScannerResult } from './inspectors'
import type { ScannerInfo } from './system'
const counts = (critical: number) => ({ critical, high: 0, moderate: 0, low: 0 })
const configured: ScannerInfo[] = [
{ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' },
{ name: 'grype', enabled: true, healthy: false, version: '' },
{ name: 'govulncheck', enabled: true, healthy: true, version: '1.1.4' },
{ name: 'pip-audit', enabled: false, healthy: null, version: '' },
]
describe('inspectorRows', () => {
it('lists reporting scanners first, with their counts and the configured version', () => {
const results: ScannerResult[] = [{ name: 'trivy', findings: 1, severity_counts: counts(1) }]
const [first] = inspectorRows('npm', results, configured)
expect(first).toMatchObject({ name: 'trivy', status: 'reported', version: '0.58.1', findings: 1, health: 'healthy' })
expect(first.counts?.critical).toBe(1)
})
it('explains each scanner that did not report', () => {
const rows = inspectorRows('npm', [{ name: 'trivy', findings: 0, severity_counts: counts(0) }], configured)
const status = Object.fromEntries(rows.map((r) => [r.name, r.status]))
expect(status).toEqual({
trivy: 'reported',
grype: 'no-result',
govulncheck: 'not-applicable',
'pip-audit': 'off',
})
})
it('flags a reporting scanner that is now unhealthy', () => {
const rows = inspectorRows('npm', [{ name: 'grype', findings: 0, severity_counts: counts(0) }], configured)
expect(rows[0].health).toBe('down')
})
it('keeps a reported scanner that is no longer configured', () => {
const rows = inspectorRows('npm', [{ name: 'retired', findings: 2, severity_counts: counts(2) }], configured)
expect(rows[0]).toMatchObject({ name: 'retired', health: null, version: '' })
})
})
+61
View File
@@ -0,0 +1,61 @@
import { scannerState, type ScannerInfo, type ScannerState } from '@/lib/system'
import type { VulnerabilityCounts } from '@/stores/packages'
/** One entry of the `scanners` array on a package's vulnerability response. */
export interface ScannerResult {
name: string
findings: number
severity_counts: VulnerabilityCounts
}
/** Ecosystem-specific scanners only inspect their own registry (mirrors the server's shouldRunScanner). */
const REGISTRY_SCANNERS: Record<string, string> = { govulncheck: 'go', 'npm-audit': 'npm', 'pip-audit': 'pypi' }
export type InspectorStatus = 'reported' | 'no-result' | 'not-applicable' | 'off'
export interface InspectorRow {
name: string
version: string
status: InspectorStatus
health: ScannerState | null
counts: VulnerabilityCounts | null
findings: number | null
}
export const INSPECTOR_STATUS_LABELS: Record<InspectorStatus, string> = {
reported: 'Reported',
'no-result': 'No result',
'not-applicable': 'Not applicable',
off: 'Off',
}
/**
* Scanner by severity for one package: every scanner that reported, then each configured scanner that did not,
* with the reason it is absent where the registry explains it.
*/
export function inspectorRows(
registry: string,
results: readonly ScannerResult[],
configured: readonly ScannerInfo[],
): InspectorRow[] {
const byName = new Map(configured.map((s) => [s.name, s]))
const rows: InspectorRow[] = results.map((r) => {
const info = byName.get(r.name)
return {
name: r.name,
version: info?.version ?? '',
status: 'reported',
health: info ? scannerState(info) : null,
counts: r.severity_counts,
findings: r.findings,
}
})
const reported = new Set(results.map((r) => r.name))
for (const info of configured) {
if (reported.has(info.name)) continue
const own = REGISTRY_SCANNERS[info.name]
const status: InspectorStatus = !info.enabled ? 'off' : own && own !== registry ? 'not-applicable' : 'no-result'
rows.push({ name: info.name, version: info.version, status, health: scannerState(info), counts: null, findings: null })
}
return rows
}
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest'
import { filterPackages, packageRoute } from './packages'
import { PACKAGES } from '@/test/fixtures'
const none = { query: '', registries: [], verdicts: [] } as const
describe('filterPackages', () => {
it('returns every package for an empty filter', () => {
expect(filterPackages(PACKAGES, none)).toHaveLength(PACKAGES.length)
})
it('matches the query on name and version, ignoring case', () => {
expect(filterPackages(PACKAGES, { ...none, query: 'LEFT-PAD' }).map((p) => p.id)).toEqual(['npm-1', 'npm-2'])
expect(filterPackages(PACKAGES, { ...none, query: '2.31' }).map((p) => p.id)).toEqual(['pypi-1'])
})
it('matches the release version of a PyPI file row', () => {
const rows = [{ ...PACKAGES[2], version: 'six-1.17.0.whl', release_version: '1.17.0' }]
expect(filterPackages(rows, { ...none, query: '1.17.0' })).toHaveLength(1)
})
it('treats several registries or verdicts as any-of, and the filters as all-of', () => {
expect(filterPackages(PACKAGES, { ...none, registries: ['npm', 'go'] })).toHaveLength(3)
expect(filterPackages(PACKAGES, { ...none, verdicts: ['held', 'pending'] }).map((p) => p.id)).toEqual(['npm-1', 'go-1'])
expect(filterPackages(PACKAGES, { query: 'left', registries: ['npm'], verdicts: ['held'] }).map((p) => p.id)).toEqual(['npm-1'])
})
})
describe('packageRoute', () => {
it('splits a name with slashes into route segments', () => {
expect(packageRoute({ registry: 'go', name: 'github.com/a/b', version: 'v1.0.0' })).toEqual({
name: 'package-details',
params: { registry: 'go', name: ['github.com', 'a', 'b'], version: 'v1.0.0' },
})
})
})
+37
View File
@@ -0,0 +1,37 @@
import type { RouteLocationRaw } from 'vue-router'
import type { Package } from '@/stores/packages'
import { displayVersion } from '@/lib/format'
import { verdictOf, type Verdict } from '@/lib/verdict'
export interface PackageFilters {
query: string
/** Empty means every registry. */
registries: readonly string[]
/** Empty means every verdict. */
verdicts: readonly Verdict[]
}
/** Case-insensitive match on name, version or release version, as the server search does. */
function matchesQuery(pkg: Package, query: string): boolean {
const needle = query.trim().toLowerCase()
if (!needle) return true
return [pkg.name, pkg.version, pkg.release_version ?? ''].some((field) => field.toLowerCase().includes(needle))
}
export function filterPackages(packages: readonly Package[], filters: PackageFilters): Package[] {
return packages.filter(
(pkg) =>
matchesQuery(pkg, filters.query) &&
(filters.registries.length === 0 || filters.registries.includes(pkg.registry)) &&
(filters.verdicts.length === 0 || filters.verdicts.includes(verdictOf(pkg))),
)
}
/** Route of a package's full page. A name with slashes becomes the repeatable `name` segments. */
export function packageRoute(pkg: Pick<Package, 'registry' | 'name' | 'version'>): RouteLocationRaw {
return { name: 'package-details', params: { registry: pkg.registry, name: pkg.name.split('/'), version: pkg.version } }
}
export function packageLabel(pkg: Package): string {
return `${pkg.name} ${displayVersion(pkg)}`
}
+30
View File
@@ -0,0 +1,30 @@
import type { ScannerResult } from '@/lib/inspectors'
import type { AppliedBypass, ApiVerdict, VulnerabilityCounts } from '@/stores/packages'
export interface VulnerabilityEntry {
id: string
severity: string
title: string
description: string
references: string[]
fixed_in: string
detected_by?: string[]
bypassed: boolean
bypass?: { id: string; reason: string; created_by: string; expires_at: string }
}
/** Response of GET /api/packages/{registry}/{name}/{version}/vulnerabilities. */
export interface PackageReport {
package?: { release_version?: string }
scanned: boolean
scanner?: string
scanned_at?: string
status: string
message?: string
vulnerabilities: VulnerabilityEntry[]
vulnerability_count: number
severity_counts?: VulnerabilityCounts
bypassed_count?: number
scanners: ScannerResult[]
decision: { verdict: ApiVerdict; blocked: boolean; reason: string; bypass: AppliedBypass | null }
}
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest'
import { describePolicy, scannerState, type SystemInfo } from './system'
function security(over: Partial<SystemInfo['security']>): SystemInfo['security'] {
return {
enabled: true,
fail_closed: true,
scan_on_download: true,
block_on_severity: 'none',
block_thresholds: { critical: -1, high: -1, moderate: -1, low: -1 },
scan_wait_timeout: 30,
scanners: [],
rescan: { interval: 0, active_window: 0, concurrency: 1, on_access: false },
...over,
}
}
describe('describePolicy', () => {
it('names a critical-only threshold policy', () => {
const policy = describePolicy(security({ block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 } }))
expect(policy).toBe('Blocks any CRITICAL.')
})
it('states a count threshold', () => {
const policy = describePolicy(security({ block_thresholds: { critical: 0, high: 3, moderate: -1, low: -1 } }))
expect(policy).toBe('Blocks any CRITICAL, more than 3 HIGH.')
})
it('expands the block-on-severity floor to every level at or above it', () => {
expect(describePolicy(security({ block_on_severity: 'high' }))).toBe('Blocks any CRITICAL or HIGH.')
})
it('does not repeat a level the thresholds already cover', () => {
const policy = describePolicy(security({ block_on_severity: 'critical', block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 } }))
expect(policy).toBe('Blocks any CRITICAL.')
})
it('says so when nothing blocks and when scanning is off', () => {
expect(describePolicy(security({}))).toBe('No severity blocks a package.')
expect(describePolicy(security({ enabled: false }))).toBe('Scanning is off. Every package is served.')
})
})
describe('scannerState', () => {
it('maps config and probe to a state', () => {
expect(scannerState({ name: 'a', enabled: false, healthy: null, version: '' })).toBe('off')
expect(scannerState({ name: 'a', enabled: true, healthy: false, version: '' })).toBe('down')
expect(scannerState({ name: 'a', enabled: true, healthy: true, version: '' })).toBe('healthy')
})
})
+87
View File
@@ -0,0 +1,87 @@
import { ref } from 'vue'
import axios from 'axios'
export interface ScannerInfo {
name: string
enabled: boolean
/** Null while the scanner is off or has not been probed. */
healthy: boolean | null
version: string
}
/** Response of GET /api/system. Durations are seconds; a negative threshold means unlimited. */
export interface SystemInfo {
version: string
security: {
enabled: boolean
fail_closed: boolean
scan_on_download: boolean
block_on_severity: string
block_thresholds: { critical: number; high: number; moderate: number; low: number }
scan_wait_timeout: number
scanners: ScannerInfo[]
rescan: { interval: number; active_window: number; concurrency: number; on_access: boolean }
}
upstreams: Record<string, string>
cache: { max_size: number; idle_ttl: number; default_ttl: number }
prewarming: { enabled: boolean; interval: number; top_packages: number }
}
export type ScannerState = 'healthy' | 'down' | 'off'
export function scannerState(scanner: ScannerInfo): ScannerState {
if (!scanner.enabled) return 'off'
return scanner.healthy === false ? 'down' : 'healthy'
}
const SEVERITY_NAMES = { critical: 'CRITICAL', high: 'HIGH', moderate: 'MODERATE', low: 'LOW' } as const
const SEVERITY_ORDER = ['critical', 'high', 'moderate', 'low'] as const
/** The block policy in words, from the threshold counts and the block-on-severity floor. */
export function describePolicy(security: SystemInfo['security']): string {
if (!security.enabled) return 'Scanning is off. Every package is served.'
const parts: string[] = []
for (const level of SEVERITY_ORDER) {
const limit = security.block_thresholds[level]
if (limit < 0) continue
parts.push(limit === 0 ? `any ${SEVERITY_NAMES[level]}` : `more than ${limit} ${SEVERITY_NAMES[level]}`)
}
const floor = security.block_on_severity.toLowerCase() as keyof typeof SEVERITY_NAMES
if (floor in SEVERITY_NAMES) {
const covered = SEVERITY_ORDER.slice(0, SEVERITY_ORDER.indexOf(floor) + 1).map((l) => SEVERITY_NAMES[l])
parts.push(`any ${covered.join(' or ')}`)
}
return parts.length === 0 ? 'No severity blocks a package.' : `Blocks ${[...new Set(parts)].join(', ')}.`
}
const info = ref<SystemInfo | null>(null)
const error = ref<string | null>(null)
let inflight: Promise<void> | null = null
/** Shared GET /api/system state; concurrent callers share one request. */
export function useSystem() {
function load(force = false): Promise<void> {
if (info.value && !force) return Promise.resolve()
inflight ??= axios
.get<SystemInfo>('/api/system')
.then((res) => {
info.value = res.data
error.value = null
})
.catch((err: unknown) => {
error.value = err instanceof Error ? err.message : 'Could not load system settings'
})
.finally(() => {
inflight = null
})
return inflight
}
return { info, error, load }
}
/** Test hook: forgets the cached response. */
export function __resetSystem(): void {
info.value = null
error.value = null
inflight = null
}
+34
View File
@@ -0,0 +1,34 @@
export type DownloadPeriod = '1h' | '1day' | '7day' | '30day'
export const DOWNLOAD_PERIODS: { value: DownloadPeriod; label: string }[] = [
{ value: '1h', label: '1 hour' },
{ value: '1day', label: '24 hours' },
{ value: '7day', label: '7 days' },
{ value: '30day', label: '30 days' },
]
export interface TimeSeriesPoint {
timestamp: string
value: number
}
export interface TimeSeries {
period: DownloadPeriod
registry: string
data_points: TimeSeriesPoint[]
}
/** Axis label of one bucket: a time of day for hourly spans, a day otherwise. */
export function bucketLabel(period: DownloadPeriod, timestamp: string): string {
const date = new Date(timestamp)
if (Number.isNaN(date.getTime())) return timestamp
if (period === '1h' || period === '1day') {
return date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' })
}
return date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' })
}
/** "2026-11-04T00:00:00Z" as "2026-11-04", the date form the heatmap reads. */
export function isoDay(timestamp: string): string {
return timestamp.slice(0, 10)
}
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest'
import { verdictOf, VERDICT_LABELS } from './verdict'
describe('verdictOf', () => {
it.each([
['the server verdict when present', { scanned: true, status: 'vulnerable', verdict: 'bypassed', isBlocked: false }, 'bypassed'],
['held for a blocked package from an older server', { scanned: true, status: 'vulnerable', isBlocked: true }, 'held'],
['cleared for a scanned package from an older server', { scanned: true, status: 'clean' }, 'cleared'],
['pending for an unscanned package', { scanned: false, status: 'pending' }, 'pending'],
] as const)('%s', (_name, vulnerabilities, want) => {
expect(verdictOf({ vulnerabilities: { ...vulnerabilities } })).toBe(want)
})
it('is unscanned when the server sends no scan block, as with scanning off', () => {
expect(verdictOf({})).toBe('unscanned')
})
})
describe('VERDICT_LABELS', () => {
it('uses the checkpoint vocabulary', () => {
expect(VERDICT_LABELS).toMatchObject({ cleared: 'Cleared', held: 'Held', bypassed: 'Bypassed', pending: 'Awaiting scan' })
})
})
+54
View File
@@ -0,0 +1,54 @@
import type { Package } from '@/stores/packages'
/** The customs-desk outcome of a package; `unscanned` is a server with scanning off. */
export type Verdict = 'cleared' | 'held' | 'bypassed' | 'pending' | 'unscanned'
export const VERDICT_LABELS: Record<Verdict, string> = {
cleared: 'Cleared',
held: 'Held',
bypassed: 'Bypassed',
pending: 'Awaiting scan',
unscanned: 'Not scanned',
}
export const VERDICT_TONES: Record<Verdict, 'success' | 'danger' | 'info' | 'warning' | 'neutral'> = {
cleared: 'success',
held: 'danger',
bypassed: 'info',
pending: 'warning',
unscanned: 'neutral',
}
/** Text colour of a verdict's icon; the label is always shown beside it. */
export const VERDICT_TEXT: Record<Verdict, string> = {
cleared: 'text-success',
held: 'text-destructive',
bypassed: 'text-info',
pending: 'text-warning',
unscanned: 'text-muted-foreground',
}
/** One sentence per verdict, for tooltips and headings. */
export const VERDICT_MEANINGS: Record<Verdict, string> = {
cleared: 'Scanned and under the block policy. Served to clients.',
held: 'At or over the block policy. Clients get a 403.',
bypassed: 'An admin bypass applies. Served to clients.',
pending: 'No scan result yet.',
unscanned: 'Security scanning is off.',
}
export const VERDICT_OPTIONS = (['cleared', 'held', 'bypassed', 'pending'] as const).map((value) => ({
value,
label: VERDICT_LABELS[value],
}))
/** Sort order for a verdict column: worst first. */
export const VERDICT_RANK: Record<Verdict, number> = { held: 4, pending: 3, bypassed: 2, cleared: 1, unscanned: 0 }
export function verdictOf(pkg: Pick<Package, 'vulnerabilities'>): Verdict {
const info = pkg.vulnerabilities
if (!info) return 'unscanned'
if (info.verdict) return info.verdict
if (info.isBlocked) return 'held'
return info.scanned ? 'cleared' : 'pending'
}
+98
View File
@@ -0,0 +1,98 @@
import { describe, expect, it } from 'vitest'
import { verdictBanner } from './verdictBanner'
import type { PackageReport } from './report'
function report(over: Partial<PackageReport>): PackageReport {
return {
scanned: true,
status: 'vulnerable',
vulnerabilities: [],
vulnerability_count: 0,
scanners: [],
decision: { verdict: 'cleared', blocked: false, reason: '', bypass: null },
...over,
}
}
const vuln = (id: string, severity: string, extra: object = {}) => ({
id,
severity,
title: '',
description: '',
references: [],
fixed_in: '',
bypassed: false,
...extra,
})
describe('verdictBanner', () => {
it('names the blocking advisory, its severity, the policy and the fix', () => {
const banner = verdictBanner(
report({
vulnerabilities: [vuln('CVE-2021-44906', 'CRITICAL', { fixed_in: '1.2.6' }), vuln('CVE-2022-0001', 'LOW')],
decision: { verdict: 'held', blocked: true, reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)', bypass: null },
}),
'Blocks any CRITICAL.',
true,
)
expect(banner.type).toBe('danger')
expect(banner.title).toBe('Held: CVE-2021-44906 is CRITICAL')
expect(banner.body).toContain('Blocks any CRITICAL.')
expect(banner.body).toContain('403')
expect(banner.body).toContain('Fixed in v1.2.6')
})
it('summarises many blockers and ignores bypassed ones', () => {
const vulns = ['A', 'B', 'C', 'D', 'E'].map((id) => vuln(id, 'critical'))
vulns.push(vuln('Z', 'critical', { bypassed: true }))
const banner = verdictBanner(report({ vulnerabilities: vulns, decision: { verdict: 'held', blocked: true, reason: '', bypass: null } }), '', true)
expect(banner.title).toBe('Held: A, B, C and 2 more are CRITICAL')
})
it('falls back to the reason when no finding explains the hold', () => {
const banner = verdictBanner(
report({ decision: { verdict: 'held', blocked: true, reason: 'scan failed - fail closed', bypass: null } }),
'Blocks any CRITICAL.',
true,
)
expect(banner.title).toBe('Held: scan failed - fail closed')
})
it('says who bypassed a package and when it expires', () => {
const banner = verdictBanner(
report({
decision: {
verdict: 'bypassed',
blocked: false,
reason: '',
bypass: {
id: 'b1',
type: 'package',
target: 'npm/x@1',
reason: 'Vendored fix',
created_by: 'a.khan',
created_at: '2026-11-01T00:00:00Z',
expires_at: '2026-12-01T00:00:00Z',
},
},
}),
'',
true,
)
expect(banner.type).toBe('note')
expect(banner.title).toBe('Bypassed: Vendored fix')
expect(banner.body).toContain('a.khan')
expect(banner.body).toContain('package bypass')
})
it('reports an unscanned package by the fail-closed rule', () => {
const base = report({ scanned: false, decision: { verdict: 'pending', blocked: false, reason: '', bypass: null } })
expect(verdictBanner(base, '', true).body).toContain('held until one does')
expect(verdictBanner(base, '', false).body).not.toContain('held')
})
it('counts findings that stay under the policy', () => {
expect(verdictBanner(report({ vulnerability_count: 2 }), '', true).body).toContain('2 findings below the block policy')
expect(verdictBanner(report({}), '', true).body).toContain('reported nothing')
})
})
+70
View File
@@ -0,0 +1,70 @@
import type { PackageReport } from '@/lib/report'
import { formatDate, withVersionPrefix } from '@/lib/format'
import { formatSeverityName, severityRank } from '@/lib/severity'
export interface BannerContent {
type: 'danger' | 'success' | 'note' | 'warning'
title: string
body: string
}
const MAX_NAMED = 3
function listIds(ids: readonly string[]): string {
const shown = ids.slice(0, MAX_NAMED).join(', ')
return ids.length > MAX_NAMED ? `${shown} and ${ids.length - MAX_NAMED} more` : shown
}
function heldBanner(report: PackageReport, policy: string): BannerContent {
const live = report.vulnerabilities.filter((v) => !v.bypassed)
const top = live.reduce((max, v) => Math.max(max, severityRank(v.severity)), 0)
const blockers = live.filter((v) => severityRank(v.severity) === top)
const reason = report.decision.reason
const clients = 'Clients that request this version get a 403.'
if (blockers.length === 0) {
return { type: 'danger', title: `Held: ${reason || 'the scan did not complete'}`, body: `${policy} ${clients}`.trim() }
}
const verb = blockers.length === 1 ? 'is' : 'are'
const fixes = [...new Set(blockers.map((b) => b.fixed_in).filter(Boolean))]
const fix = fixes.length > 0 ? ` Fixed in ${fixes.map(withVersionPrefix).join(', ')}.` : ' No fixed version is listed.'
return {
type: 'danger',
title: `Held: ${listIds(blockers.map((b) => b.id))} ${verb} ${formatSeverityName(blockers[0].severity).toUpperCase()}`,
body: `${policy} ${reason ? `${reason}. ` : ''}${clients}${fix}`.replace(/\s+/g, ' ').trim(),
}
}
/** The sentence at the top of a package page: what the verdict is and why. */
export function verdictBanner(report: PackageReport, policy: string, failClosed: boolean): BannerContent {
const { verdict, bypass } = report.decision
switch (verdict) {
case 'held':
return heldBanner(report, policy)
case 'bypassed': {
const scope = bypass?.type === 'package' ? 'package' : 'advisory'
return {
type: 'note',
title: `Bypassed: ${bypass?.reason ?? 'an admin bypass applies'}`,
body: bypass
? `${bypass.created_by} created this ${scope} bypass on ${formatDate(bypass.created_at)}. It expires on ${formatDate(bypass.expires_at)}. Clients are served this version.`
: 'Clients are served this version.',
}
}
case 'pending':
return {
type: 'warning',
title: 'Awaiting scan',
body: failClosed
? 'No scanner has reported on this version yet. The policy is fail-closed, so it is held until one does.'
: 'No scanner has reported on this version yet.',
}
default: {
const n = report.vulnerability_count
return {
type: 'success',
title: 'Cleared: no finding reaches the block policy',
body: n === 0 ? 'The scanners reported nothing. Clients are served this version.' : `${n} finding${n === 1 ? '' : 's'} below the block policy. Clients are served this version.`,
}
}
}
}