mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
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:
@@ -27,7 +27,7 @@ onMounted(() => {
|
||||
<template #brand>
|
||||
<Icon :icon="faBoxOpen" size="lg" class="text-primary" />
|
||||
<p class="m-0 text-lg font-semibold">GoHoarder</p>
|
||||
<p class="m-0 hidden text-sm text-muted-foreground sm:block">Package cache manager</p>
|
||||
<p class="m-0 hidden text-sm text-muted-foreground sm:block">Package checkpoint</p>
|
||||
</template>
|
||||
<template #actions><ThemeToggle /></template>
|
||||
<template #mobile><AppNav sheet /></template>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="CVE bypass management"
|
||||
description="Manage temporary security bypasses for packages and CVEs."
|
||||
title="Bypasses"
|
||||
description="A bypass lets a package or an advisory through the block policy until it expires. Each one is kept for the audit trail."
|
||||
>
|
||||
<template #actions>
|
||||
<Button :icon-start="faPlus" @click="showCreateModal = true">Create bypass</Button>
|
||||
@@ -33,7 +33,7 @@
|
||||
v-if="filteredBypasses.length === 0"
|
||||
:icon="faShieldHalved"
|
||||
title="No bypasses found"
|
||||
description="Create a bypass to allow packages with known vulnerabilities."
|
||||
description="Create a bypass to serve a package that the policy holds."
|
||||
/>
|
||||
<DataTable
|
||||
v-else
|
||||
@@ -44,7 +44,7 @@
|
||||
:rows="filteredBypasses"
|
||||
>
|
||||
<template #cell-type="{ row }">
|
||||
<Badge :variant="row.type === 'cve' ? 'default' : 'outline'">{{ row.type === 'cve' ? 'CVE' : 'Package' }}</Badge>
|
||||
<Badge :variant="row.type === 'cve' ? 'secondary' : 'outline'">{{ row.type === 'cve' ? 'CVE' : 'Package' }}</Badge>
|
||||
</template>
|
||||
<template #cell-status="{ row }">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
@@ -55,6 +55,13 @@
|
||||
<StatusBadge v-if="isExpired(row.expires_at)" status="expired" :tones="{ expired: 'danger' }" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-created_at="{ row }"><RelativeTime :datetime="row.created_at" /></template>
|
||||
<template #cell-expires_at="{ row }">
|
||||
<span class="block">{{ formatDate(row.expires_at) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">
|
||||
<RelativeTime :datetime="row.expires_at" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-actions="{ row }">
|
||||
<span class="flex gap-1">
|
||||
<IconButton :icon="faPen" :label="`Edit bypass for ${row.target}`" @click="editBypass(row)" />
|
||||
@@ -170,6 +177,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { useRoute } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
@@ -191,28 +199,18 @@ import {
|
||||
Input,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
RelativeTime,
|
||||
SegmentedControl,
|
||||
StatusBadge,
|
||||
Textarea,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { isExpired, type Bypass } from '@/lib/bypass'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { faPen, faPlus, faRotateRight, faShieldHalved, faTrash } from '@/lib/icons'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const toasts = useToastStore()
|
||||
@@ -220,6 +218,7 @@ const bypasses = ref<Bypass[]>([])
|
||||
const activeFilter = ref<'all' | 'active' | 'expired'>('all')
|
||||
const typeFilter = ref<'all' | 'cve' | 'package'>('all')
|
||||
|
||||
const route = useRoute()
|
||||
const showCreateModal = ref(false)
|
||||
const showDeleteModal = ref(false)
|
||||
const editingBypass = ref<Bypass | null>(null)
|
||||
@@ -238,8 +237,8 @@ const EMPTY_FORM = {
|
||||
|
||||
const bypassForm = ref({ ...EMPTY_FORM })
|
||||
|
||||
// Get API key from localStorage or prompt user
|
||||
const apiKey = ref<string>('')
|
||||
const adminKey = useAdminKey()
|
||||
const apiKey = adminKey.key
|
||||
const keyInput = ref('')
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
@@ -274,8 +273,8 @@ const isFormValid = computed(() => {
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
// Try to get API key from localStorage
|
||||
apiKey.value = localStorage.getItem('admin_api_key') || ''
|
||||
adminKey.load()
|
||||
prefillFromQuery()
|
||||
if (!apiKey.value) {
|
||||
promptForApiKey()
|
||||
} else {
|
||||
@@ -283,6 +282,14 @@ onMounted(() => {
|
||||
}
|
||||
})
|
||||
|
||||
// A package page links here with the package to cover.
|
||||
function prefillFromQuery() {
|
||||
const { type, target } = route.query
|
||||
if (typeof target !== 'string' || target === '') return
|
||||
bypassForm.value = { ...EMPTY_FORM, type: type === 'cve' ? 'cve' : 'package', target }
|
||||
showCreateModal.value = true
|
||||
}
|
||||
|
||||
function promptForApiKey() {
|
||||
keyInput.value = ''
|
||||
showKeyDialog.value = true
|
||||
@@ -291,8 +298,7 @@ function promptForApiKey() {
|
||||
function submitApiKey() {
|
||||
const key = keyInput.value.trim()
|
||||
if (!key) return
|
||||
apiKey.value = key
|
||||
localStorage.setItem('admin_api_key', key)
|
||||
adminKey.save(key)
|
||||
showKeyDialog.value = false
|
||||
fetchBypasses()
|
||||
}
|
||||
@@ -330,8 +336,7 @@ async function fetchBypasses() {
|
||||
console.error('Failed to fetch bypasses:', err)
|
||||
if (err.response?.status === 401) {
|
||||
error.value = 'Invalid API key. Please check your credentials.'
|
||||
localStorage.removeItem('admin_api_key')
|
||||
apiKey.value = ''
|
||||
adminKey.clear()
|
||||
} else {
|
||||
error.value = err.response?.data?.error?.message || err.message || 'Failed to load bypasses'
|
||||
}
|
||||
@@ -449,10 +454,6 @@ async function deleteBypass() {
|
||||
}
|
||||
}
|
||||
|
||||
function isExpired(expiresAt: string): boolean {
|
||||
return new Date(expiresAt) < new Date()
|
||||
}
|
||||
|
||||
const FILTER_OPTIONS = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'active', label: 'Active' },
|
||||
@@ -471,13 +472,13 @@ const BYPASS_TYPE_OPTIONS = [
|
||||
]
|
||||
|
||||
const bypassColumns: DataTableColumn<Bypass>[] = [
|
||||
{ key: 'target', header: 'Target', rowHeader: true },
|
||||
{ key: 'target', header: 'Target', sortable: true, rowHeader: true },
|
||||
{ key: 'type', header: 'Type' },
|
||||
{ key: 'status', header: 'Status', accessor: (b) => (b.active ? 'active' : 'inactive') },
|
||||
{ key: 'reason', header: 'Reason' },
|
||||
{ key: 'created_by', header: 'Created by' },
|
||||
{ key: 'created_at', header: 'Created', accessor: (b) => formatDate(b.created_at) },
|
||||
{ key: 'expires_at', header: 'Expires', accessor: (b) => formatDate(b.expires_at) },
|
||||
{ key: 'created_at', header: 'Created', sortable: true, accessor: (b) => Date.parse(b.created_at) },
|
||||
{ key: 'expires_at', header: 'Expires', sortable: true, accessor: (b) => Date.parse(b.expires_at) },
|
||||
{ key: 'applies_to', header: 'Applies to' },
|
||||
{ key: 'actions', header: 'Actions', actions: true, accessor: () => '' },
|
||||
]
|
||||
|
||||
@@ -1,252 +1,69 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Stats from './Stats.vue'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import Insights from './Insights.vue'
|
||||
import { REGISTRIES, STATS, TIMESERIES, TREND } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
|
||||
describe('Stats.vue', () => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Stats) => mountWith(component, { global: { plugins: [router] } })
|
||||
vi.mock('axios')
|
||||
|
||||
beforeEach(async () => {
|
||||
setActivePinia(createPinia())
|
||||
router = await createTestRouter('/stats')
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(stats = STATS, timeseries: unknown = TIMESERIES) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: timeseries } as never
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND } as never
|
||||
return { data: { stats, registries: REGISTRIES } } as never
|
||||
})
|
||||
const router = await createTestRouter('/stats')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(Insights, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
beforeEach(() => setActivePinia(createPinia()))
|
||||
|
||||
describe('Insights', () => {
|
||||
it('lists packages and downloads per registry', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
expect(problems).toEqual([])
|
||||
const table = wrapper.get('[data-testid="registry-breakdown"] table')
|
||||
expect(table.text()).toContain('npm280')
|
||||
expect(table.text()).toContain('go110')
|
||||
expect(table.text()).toContain('pypi130')
|
||||
})
|
||||
|
||||
it('renders stats component', () => {
|
||||
const wrapper = mount(Stats)
|
||||
expect(wrapper.find('h1').text()).toBe('Statistics')
|
||||
it('reports scan coverage and the four outcomes', async () => {
|
||||
const { wrapper } = await open()
|
||||
const coverage = wrapper.get('[data-testid="scan-coverage"]').text()
|
||||
expect(coverage).toContain('3 of 4')
|
||||
for (const word of ['Cleared', 'Held', 'Bypassed', 'Awaiting scan']) expect(coverage).toContain(word)
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = true
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading statistics...')
|
||||
it('shades a day when there were downloads', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-testid="daily-downloads"]').find('[role="img"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
const wrapper = mount(Stats)
|
||||
|
||||
store.loading = false
|
||||
store.error = 'Failed to fetch statistics'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Failed to fetch statistics')
|
||||
it('does not draw an empty heatmap for a month with no downloads', async () => {
|
||||
const quiet = { ...TIMESERIES, data_points: TIMESERIES.data_points.map((p) => ({ ...p, value: 0 })) }
|
||||
const { wrapper } = await open(STATS, quiet)
|
||||
expect(wrapper.get('[data-testid="daily-downloads"]').text()).toContain('No downloads yet')
|
||||
})
|
||||
|
||||
it('displays overall statistics', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824, // 1 GB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Overall statistics')
|
||||
expect(wrapper.text()).toContain('100')
|
||||
expect(wrapper.text()).toContain('500')
|
||||
})
|
||||
|
||||
it('displays security scanning statistics', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Security scanning')
|
||||
expect(wrapper.text()).toContain('Scanned packages')
|
||||
expect(wrapper.text()).toContain('Vulnerable packages')
|
||||
})
|
||||
|
||||
it('displays registry breakdown', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {
|
||||
npm: {
|
||||
count: 50,
|
||||
size: 536870912, // 512 MB
|
||||
downloads: 300,
|
||||
},
|
||||
pypi: {
|
||||
count: 30,
|
||||
size: 322122547, // ~307 MB
|
||||
downloads: 150,
|
||||
},
|
||||
go: {
|
||||
count: 20,
|
||||
size: 214748365, // ~205 MB
|
||||
downloads: 50,
|
||||
},
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Registry breakdown')
|
||||
expect(wrapper.text()).toContain('npm')
|
||||
expect(wrapper.text()).toContain('PyPI')
|
||||
expect(wrapper.text()).toContain('Go modules')
|
||||
// The cards layout prefixes each cell with its column label.
|
||||
const packageCounts = wrapper
|
||||
.findAll('tbody tr')
|
||||
.map((row) => row.findAll('td')[0].text().replace(/^Packages/, ''))
|
||||
expect(packageCounts).toEqual(['50', '30', '20'])
|
||||
})
|
||||
|
||||
it('formats bytes correctly in overall stats', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824, // 1 GB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 GB')
|
||||
})
|
||||
|
||||
it('calls fetchStats on mount', () => {
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = vi.spyOn(store, 'fetchStats')
|
||||
|
||||
mount(Stats)
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lists the registries in the order the API reports them', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 3,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {
|
||||
npm: { count: 1, size: 0, downloads: 0 },
|
||||
pypi: { count: 1, size: 0, downloads: 0 },
|
||||
go: { count: 1, size: 0, downloads: 0 },
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const labels = wrapper.findAll('tbody th').map((cell) => cell.text().replace(/^Registry/, ''))
|
||||
expect(labels).toEqual(['npm', 'PyPI', 'Go modules'])
|
||||
})
|
||||
|
||||
it('handles empty registries data', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Registry breakdown')
|
||||
expect(wrapper.findAll('tbody th')).toHaveLength(0)
|
||||
expect(wrapper.text()).toContain('No registries reported')
|
||||
})
|
||||
|
||||
describe('idle eviction note', () => {
|
||||
const baseStats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
|
||||
async function render(idleTtl?: number) {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
|
||||
await wrapper.vm.$nextTick()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
it.each([
|
||||
[604800, 'Cached items not requested for 7 days are removed.'],
|
||||
[86400, 'Cached items not requested for 1 day are removed.'],
|
||||
[129600, 'Cached items not requested for 36 hours are removed.'],
|
||||
[5400, 'Cached items not requested for 90 minutes are removed.'],
|
||||
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
|
||||
const wrapper = await render(seconds)
|
||||
expect(wrapper.text()).toContain(sentence)
|
||||
})
|
||||
|
||||
it('hides the note when idle eviction is off', async () => {
|
||||
const wrapper = await render(0)
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
|
||||
it('hides the note when the API sends no idle_ttl', async () => {
|
||||
const wrapper = await render()
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
it('never shows a hit rate or evictions, which the server does not track', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toMatch(/hit rate|evict/i)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,89 +1,83 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Statistics" description="Storage, traffic and scan results across every registry." />
|
||||
<PageHeader title="Insights" description="How the cache grows, what each registry holds, and how much of it the scanners have covered.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="refresh">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
<LoadingState v-if="loading && !stats" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
<ErrorState v-else-if="error && !stats" variant="card" title="Could not load statistics" :message="error" @retry="refresh" />
|
||||
|
||||
<template v-else>
|
||||
<Alert v-if="idleTtl > 0" variant="info">
|
||||
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
|
||||
</Alert>
|
||||
<Callout v-if="idleTtl > 0" type="note" size="sm">
|
||||
Cached items not requested for {{ formatDuration(idleTtl) }} are removed.
|
||||
</Callout>
|
||||
|
||||
<Card>
|
||||
<Card data-testid="registry-breakdown">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Overall statistics</CardTitle>
|
||||
<CardTitle as="h2">By registry</CardTitle>
|
||||
<CardDescription>Packages, disk and traffic for each upstream.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StatGroup :columns="3" aria-label="Overall statistics">
|
||||
<KpiTile label="Total packages" :value="stats?.total_packages || 0" :icon="faBoxesStacked" />
|
||||
<KpiTile
|
||||
label="Storage used"
|
||||
:value="`${formatBytes(stats?.total_size || 0)} / ${formatBytes(stats?.max_cache_size || 0)}`"
|
||||
:hint="`${storagePercentage.toFixed(1)}% used`"
|
||||
:progress="storagePercentage"
|
||||
:tone="storageTone"
|
||||
:icon="faHardDrive"
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<EmptyState v-if="registryRows.length === 0" size="sm" title="No registry data yet" description="Each registry appears after its first download." />
|
||||
<template v-else>
|
||||
<BarChart
|
||||
:labels="registryRows.map((r) => r.registry)"
|
||||
:series="[
|
||||
{ name: 'Packages', data: registryRows.map((r) => r.count) },
|
||||
{ name: 'Downloads', data: registryRows.map((r) => r.downloads) },
|
||||
]"
|
||||
label="Packages and downloads by registry"
|
||||
/>
|
||||
<KpiTile label="Total downloads" :value="stats?.total_downloads || 0" :icon="faDownload" />
|
||||
</StatGroup>
|
||||
<DataTable label="Registry breakdown" layout="cards" row-key="registry" :columns="registryColumns" :rows="registryRows">
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-share="{ row }">
|
||||
<StatBar label="Share of disk" hide-label :value="row.size" :max="Math.max(totalSize, 1)" :value-text="sharePercent(row.size)" />
|
||||
</template>
|
||||
</DataTable>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<Card data-testid="scan-coverage">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Security scanning</CardTitle>
|
||||
<CardTitle as="h2">Scan coverage</CardTitle>
|
||||
<CardDescription>Share of cached package files with a scan result.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StatGroup :columns="3" aria-label="Security scanning">
|
||||
<KpiTile label="Scanned packages" :value="stats?.scanned_packages || 0" :icon="faCircleCheck" />
|
||||
<KpiTile
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
label="Vulnerable packages"
|
||||
:value="stats?.vulnerable_packages || 0"
|
||||
:hint="(stats?.vulnerable_packages || 0) > 0 ? 'View the list' : undefined"
|
||||
:icon="faTriangleExclamation"
|
||||
:disabled="(stats?.vulnerable_packages || 0) === 0"
|
||||
@click="showVulnerablePackages"
|
||||
/>
|
||||
<KpiTile
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
label="Blocked packages"
|
||||
:value="stats?.blocked_packages || 0"
|
||||
:hint="(stats?.blocked_packages || 0) > 0 ? 'View the list' : undefined"
|
||||
:icon="faBan"
|
||||
:disabled="(stats?.blocked_packages || 0) === 0"
|
||||
@click="showBlockedPackages"
|
||||
/>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<StatBar
|
||||
label="Scanned"
|
||||
:value="stats?.scanned_packages ?? 0"
|
||||
:max="Math.max(stats?.total_packages ?? 0, 1)"
|
||||
:value-text="`${stats?.scanned_packages ?? 0} of ${stats?.total_packages ?? 0}`"
|
||||
/>
|
||||
<StatGroup :columns="4" aria-label="Scan outcomes">
|
||||
<KpiTile v-for="tile in outcomeTiles" :key="tile.verdict" :as="RouterLink" :to="tile.to" variant="interactive" :label="tile.label" :value="tile.value" />
|
||||
</StatGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card>
|
||||
<Card data-testid="daily-downloads">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Registry breakdown</CardTitle>
|
||||
<CardTitle as="h2">Daily downloads</CardTitle>
|
||||
<CardDescription>The last 30 days. A darker square is a busier day.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
label="Registry breakdown"
|
||||
layout="cards"
|
||||
row-key="name"
|
||||
empty-text="No registries reported"
|
||||
:columns="registryColumns"
|
||||
:rows="registries"
|
||||
<LoadingState v-if="heatLoading && heatData.length === 0" layout="inline" label="Loading daily downloads..." />
|
||||
<ErrorState v-else-if="heatError" variant="inline" title="Could not load daily downloads" :message="heatError" @retry="loadHeatmap" />
|
||||
<EmptyState v-else-if="heatData.length === 0" size="sm" title="No downloads yet" description="Days fill in as clients request packages." />
|
||||
<CalendarHeatmap
|
||||
v-else
|
||||
:data="heatData"
|
||||
fit
|
||||
:start="heatStart"
|
||||
:end="heatEnd"
|
||||
label="Downloads per day over the last 30 days"
|
||||
:cell-title="(date: string, value: number | null) => `${date}: ${value ?? 0} downloads`"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -92,100 +86,110 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
Badge,
|
||||
BarChart,
|
||||
Button,
|
||||
CalendarHeatmap,
|
||||
Callout,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatBar,
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, loading, error } = storeToRefs(store)
|
||||
const router = useRouter()
|
||||
|
||||
onMounted(async () => {
|
||||
await store.fetchStats()
|
||||
})
|
||||
|
||||
function showVulnerablePackages() {
|
||||
if ((stats.value?.vulnerable_packages || 0) === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/vulnerable-packages')
|
||||
}
|
||||
|
||||
function showBlockedPackages() {
|
||||
if ((stats.value?.blocked_packages || 0) === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/blocked-packages')
|
||||
}
|
||||
|
||||
const REGISTRY_LABELS: Record<string, string> = {
|
||||
npm: 'npm',
|
||||
pypi: 'PyPI',
|
||||
go: 'Go modules',
|
||||
}
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
import { isoDay, type TimeSeries } from '@/lib/timeseries'
|
||||
|
||||
interface RegistryRow {
|
||||
name: string
|
||||
label: string
|
||||
packages: number
|
||||
size: string
|
||||
registry: string
|
||||
count: number
|
||||
size: number
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, registries, loading, error } = storeToRefs(store)
|
||||
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl ?? 0)
|
||||
const totalSize = computed(() => stats.value?.total_size ?? 0)
|
||||
|
||||
const registryRows = computed<RegistryRow[]>(() =>
|
||||
Object.entries(registries.value)
|
||||
.map(([registry, r]) => ({ registry, count: r.count ?? 0, size: r.size ?? 0, downloads: r.downloads ?? 0 }))
|
||||
.sort((a, b) => b.size - a.size),
|
||||
)
|
||||
|
||||
function sharePercent(size: number): string {
|
||||
return totalSize.value > 0 ? `${Math.round((size / totalSize.value) * 100)}%` : '0%'
|
||||
}
|
||||
|
||||
const registryColumns: DataTableColumn<RegistryRow>[] = [
|
||||
{ key: 'label', header: 'Registry', rowHeader: true },
|
||||
{ key: 'packages', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.packages) },
|
||||
{ key: 'size', header: 'Size', numeric: true },
|
||||
{ key: 'registry', header: 'Registry', rowHeader: true },
|
||||
{ key: 'count', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.count) },
|
||||
{ key: 'size', header: 'Disk', numeric: true, accessor: (r) => formatBytes(r.size) },
|
||||
{ key: 'downloads', header: 'Downloads', numeric: true, accessor: (r) => formatNumber(r.downloads) },
|
||||
{ key: 'share', header: 'Share of disk', accessor: (r) => r.size },
|
||||
]
|
||||
|
||||
const registries = computed(() => {
|
||||
const apiRegistries = store.registries || {}
|
||||
return Object.entries(apiRegistries).map(([name, data]: [string, any]): RegistryRow => ({
|
||||
name,
|
||||
label: REGISTRY_LABELS[name] ?? name.toUpperCase(),
|
||||
packages: data.count || 0,
|
||||
size: formatBytes(data.size || 0),
|
||||
downloads: data.downloads || 0,
|
||||
}))
|
||||
const outcomeTiles = computed(() => {
|
||||
const s = stats.value
|
||||
const total = s?.total_packages ?? 0
|
||||
const scanned = s?.scanned_packages ?? 0
|
||||
const held = s?.blocked_packages ?? 0
|
||||
const bypassed = s?.bypassed_packages ?? 0
|
||||
return [
|
||||
{ verdict: 'cleared', label: 'Cleared', value: Math.max(scanned - held - bypassed, 0), to: '/packages?verdict=cleared' },
|
||||
{ verdict: 'held', label: 'Held', value: held, to: '/security?tab=held' },
|
||||
{ verdict: 'bypassed', label: 'Bypassed', value: bypassed, to: '/security?tab=bypassed' },
|
||||
{ verdict: 'pending', label: 'Awaiting scan', value: Math.max(total - scanned, 0), to: '/packages?verdict=pending' },
|
||||
]
|
||||
})
|
||||
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
|
||||
const heatPoints = ref<TimeSeries['data_points']>([])
|
||||
const heatLoading = ref(false)
|
||||
const heatError = ref<string | null>(null)
|
||||
|
||||
const storagePercentage = computed(() => {
|
||||
const totalSize = stats.value?.total_size || 0
|
||||
const maxSize = stats.value?.max_cache_size || 1
|
||||
return (totalSize / maxSize) * 100
|
||||
})
|
||||
// An all-zero month has nothing to shade, so it reads as empty.
|
||||
const heatData = computed(() =>
|
||||
heatPoints.value.some((p) => p.value > 0) ? heatPoints.value.map((p) => ({ date: isoDay(p.timestamp), value: p.value })) : [],
|
||||
)
|
||||
const heatStart = computed(() => heatData.value[0]?.date ?? '')
|
||||
const heatEnd = computed(() => heatData.value[heatData.value.length - 1]?.date ?? '')
|
||||
|
||||
const storageTone = computed(() => {
|
||||
if (storagePercentage.value >= 90) return 'danger'
|
||||
if (storagePercentage.value >= 50) return 'warning'
|
||||
return 'success'
|
||||
})
|
||||
async function loadHeatmap() {
|
||||
heatLoading.value = true
|
||||
heatError.value = null
|
||||
try {
|
||||
const response = await axios.get<TimeSeries>('/api/stats/timeseries?period=30day')
|
||||
heatPoints.value = response.data.data_points ?? []
|
||||
} catch (err) {
|
||||
heatError.value = err instanceof Error ? err.message : 'Failed to load daily downloads'
|
||||
} finally {
|
||||
heatLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void loadHeatmap()
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
>
|
||||
<template #action>
|
||||
<Button as-child>
|
||||
<RouterLink to="/">Back to the dashboard</RouterLink>
|
||||
<RouterLink to="/">Back to the overview</RouterLink>
|
||||
</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
|
||||
@@ -1,246 +1,90 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import Overview from './Overview.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { REGISTRIES, STATS, SYSTEM, TIMESERIES, TOP_PACKAGES } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
describe('Dashboard.vue', () => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Dashboard) => mountWith(component, { global: { plugins: [router] } })
|
||||
vi.mock('axios')
|
||||
|
||||
beforeEach(async () => {
|
||||
router = await createTestRouter('/')
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
// Mock the fetch functions to prevent actual API calls
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchRecentPackages').mockResolvedValue()
|
||||
})
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
it('renders dashboard component', () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
expect(wrapper.find('h1').text()).toBe('Dashboard')
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/system')) return { data: SYSTEM } as never
|
||||
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES } as never
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES } as never
|
||||
return { data: { stats: STATS, registries: REGISTRIES } } as never
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.error = 'Failed to load dashboard'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Failed to load dashboard')
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = true
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading statistics...')
|
||||
})
|
||||
|
||||
it('displays overview stats cards', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 2,
|
||||
total_size: 3072,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 30,
|
||||
scanned_packages: 2,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Total packages')
|
||||
expect(wrapper.text()).toContain('Total size')
|
||||
expect(wrapper.text()).toContain('Total downloads')
|
||||
})
|
||||
|
||||
it('displays total packages from stats', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('100')
|
||||
})
|
||||
|
||||
it('displays total downloads from stats', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('500')
|
||||
})
|
||||
|
||||
it('displays total size from stats', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 1048576, // 1 MB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 MB')
|
||||
})
|
||||
|
||||
it('displays recent packages section', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open() {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
describe('Overview', () => {
|
||||
it('counts each verdict from the stats', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
expect(problems).toEqual([])
|
||||
const count = (verdict: string) => wrapper.get(`[data-verdict="${verdict}"]`).text()
|
||||
// 4 cached, 3 scanned, 1 held, 1 bypassed.
|
||||
expect(count('cleared')).toMatch(/Cleared\s*1/)
|
||||
expect(count('held')).toMatch(/Held\s*1/)
|
||||
expect(count('bypassed')).toMatch(/Bypassed\s*1/)
|
||||
expect(count('pending')).toMatch(/Awaiting scan\s*1/)
|
||||
})
|
||||
|
||||
it('lists recent packages in the order the store holds them, newest first', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '2',
|
||||
registry: 'npm',
|
||||
name: 'new-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-02T00:00:00Z',
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'old-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const recentPackagesSection = wrapper.text().split('Recent packages')[1]
|
||||
|
||||
// The store sorts by cached_at; the view keeps that order
|
||||
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
|
||||
recentPackagesSection.indexOf('old-package')
|
||||
)
|
||||
it('links each verdict to the page that lists it', async () => {
|
||||
const { wrapper } = await open()
|
||||
const href = (verdict: string) => wrapper.get(`[data-verdict="${verdict}"]`).attributes('href')
|
||||
expect(href('held')).toBe('/security?tab=held')
|
||||
expect(href('bypassed')).toBe('/security?tab=bypassed')
|
||||
expect(href('pending')).toBe('/packages?verdict=pending')
|
||||
})
|
||||
|
||||
it('handles empty packages array', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.recentPackages = []
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('0')
|
||||
expect(wrapper.text()).toContain('0 B')
|
||||
})
|
||||
|
||||
it('renders realtime lastStats over polled stats when present', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
const rt = useRealtimeStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 10,
|
||||
total_size: 1024,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 5,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
rt.lastStats = {
|
||||
total_packages: 999,
|
||||
total_size: 2048,
|
||||
total_downloads: 777,
|
||||
scanned_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Realtime values should be visible (override polled values).
|
||||
expect(wrapper.text()).toContain('999')
|
||||
expect(wrapper.text()).toContain('777')
|
||||
it('never shows a hit rate or evictions, which the server does not track', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toMatch(/hit rate|evict/i)
|
||||
})
|
||||
|
||||
it('shows a neutral "Live updates paused" badge while the socket is down', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live updates paused')
|
||||
expect(badge.text()).not.toMatch(/offline/i)
|
||||
expect(badge.attributes('data-tone')).toBe('neutral')
|
||||
it('lets a live stats frame override polled counters without losing the rest', async () => {
|
||||
const { wrapper } = await open()
|
||||
useRealtimeStore().lastStats = { blocked_packages: 5 }
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[data-verdict="held"]').text()).toMatch(/Held\s*5/)
|
||||
expect(wrapper.get('[data-verdict="bypassed"]').text()).toMatch(/Bypassed\s*1/)
|
||||
})
|
||||
|
||||
it('shows a "Live" badge once the socket is connected', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
useRealtimeStore().connected = true
|
||||
await wrapper.vm.$nextTick()
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live')
|
||||
expect(badge.attributes('data-tone')).toBe('success')
|
||||
it('shows loading while statistics are in flight', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
usePackageStore().loading = true
|
||||
vi.spyOn(usePackageStore(), 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
expect(mounted.wrapper.text()).toContain('Loading statistics...')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Dashboard" description="What the cache holds and what is moving through it.">
|
||||
<PageHeader title="Overview" description="Packages arrive at the proxy, the scanners inspect them, and each is cleared, held or waved through.">
|
||||
<template #actions>
|
||||
<StatusBadge
|
||||
:status="rt.connected ? 'live' : 'paused'"
|
||||
@@ -12,10 +12,12 @@
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
<PolicyLine />
|
||||
|
||||
<LoadingState v-if="loading && !displayStats" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
v-else-if="error && !displayStats"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@@ -23,138 +25,129 @@
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<StatGroup :columns="4" aria-label="Cache totals">
|
||||
<KpiTile label="Total packages" :value="displayStats?.total_packages || 0" :icon="faBoxesStacked" />
|
||||
<KpiTile label="Total size" :value="formatBytes(displayStats?.total_size || 0)" :icon="faHardDrive" />
|
||||
<KpiTile label="Total downloads" :value="displayStats?.total_downloads || 0" :icon="faDownload" />
|
||||
<KpiTile label="Scanned packages" :value="displayStats?.scanned_packages || 0" :icon="faShieldHalved" />
|
||||
</StatGroup>
|
||||
|
||||
<Card v-if="recentRealtimeEvents.length > 0" data-testid="ws-event-feed">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Live activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ActivityFeed :events="feedEvents" variant="compact" label="Live activity" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Download activity</CardTitle>
|
||||
<CardAction>
|
||||
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState
|
||||
v-if="chartLoading && chartData.length === 0"
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
:series="[{ name: 'Downloads', data: chartData }]"
|
||||
label="Downloads over the selected period"
|
||||
empty-text="No download activity in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<TrendChart compact class="min-w-0" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Recent packages</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="recentPackages.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<DataTable
|
||||
v-else
|
||||
label="Recent packages"
|
||||
layout="cards"
|
||||
:columns="packageColumns"
|
||||
:rows="recentPackages"
|
||||
<StatGroup :columns="4" aria-label="Verdicts" data-testid="verdict-strip">
|
||||
<KpiTile
|
||||
v-for="tile in verdictTiles"
|
||||
:key="tile.verdict"
|
||||
:as="RouterLink"
|
||||
:to="tile.to"
|
||||
variant="interactive"
|
||||
:label="VERDICT_LABELS[tile.verdict]"
|
||||
:value="tile.value"
|
||||
:hint="tile.hint"
|
||||
:data-verdict="tile.verdict"
|
||||
>
|
||||
<template #cell-registry="{ row }">
|
||||
<Badge variant="outline">{{ row.registry }}</Badge>
|
||||
</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<template #icon><Icon :icon="tile.icon" :class="VERDICT_TEXT[tile.verdict]" /></template>
|
||||
</KpiTile>
|
||||
</StatGroup>
|
||||
|
||||
<div class="grid items-start gap-6 xl:grid-cols-3">
|
||||
<CacheCapacity :used="displayStats?.total_size ?? 0" :max-size="displayStats?.max_cache_size ?? 0" :registries="registries" />
|
||||
<DownloadTrend class="xl:col-span-2" />
|
||||
</div>
|
||||
|
||||
<TopPackages />
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<ScannerHealth />
|
||||
<Card class="min-w-0" data-testid="ws-event-feed">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Live activity</CardTitle>
|
||||
<CardDescription>What the proxy just did.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="feedEvents.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="Quiet at the desk"
|
||||
description="Cached, downloaded and scanned packages appear here as they happen."
|
||||
/>
|
||||
<ActivityFeed v-else :events="feedEvents" variant="compact" label="Live activity" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
ActivityFeed,
|
||||
BarChart,
|
||||
Badge,
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Icon,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
SegmentedControl,
|
||||
StatGroup,
|
||||
StatusBadge,
|
||||
type ActivityEvent,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import CacheCapacity from './parts/CacheCapacity.vue'
|
||||
import DownloadTrend from './parts/DownloadTrend.vue'
|
||||
import PolicyLine from './parts/PolicyLine.vue'
|
||||
import ScannerHealth from './parts/ScannerHealth.vue'
|
||||
import TopPackages from './parts/TopPackages.vue'
|
||||
import { usePackageStore, type Stats } from '../stores/packages'
|
||||
import { useRealtimeStore } from '../stores/realtime'
|
||||
import type { EventType, RealtimeEvent } from '@/lib/ws'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { VERDICT_LABELS, VERDICT_TEXT, type Verdict } from '@/lib/verdict'
|
||||
import {
|
||||
faBan,
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
faBoxesStacked,
|
||||
faChartLine,
|
||||
faCircleCheck,
|
||||
faDownload,
|
||||
faHardDrive,
|
||||
faHourglassHalf,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
faUnlockKeyhole,
|
||||
} from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { recentPackages, stats, loading, error } = storeToRefs(store)
|
||||
const { stats, registries, loading, error } = storeToRefs(store)
|
||||
|
||||
const rt = useRealtimeStore()
|
||||
const { lastStats, events: rtEvents } = storeToRefs(rt)
|
||||
|
||||
// Realtime stats override polled stats when available; otherwise fall back.
|
||||
const displayStats = computed(() => lastStats.value ?? stats.value)
|
||||
// A live stats frame can lack counters the polled response carries, so it overlays rather than replaces.
|
||||
const displayStats = computed<Stats | null>(() => {
|
||||
if (!stats.value && !lastStats.value) return null
|
||||
return { ...stats.value, ...lastStats.value } as Stats
|
||||
})
|
||||
|
||||
const recentRealtimeEvents = computed<RealtimeEvent[]>(() => {
|
||||
const list = rtEvents.value
|
||||
return list.slice(Math.max(list.length - 5, 0)).reverse()
|
||||
interface VerdictTile {
|
||||
verdict: Verdict
|
||||
value: number
|
||||
hint: string
|
||||
to: string
|
||||
icon: IconDefinition
|
||||
}
|
||||
|
||||
const verdictTiles = computed<VerdictTile[]>(() => {
|
||||
const s = displayStats.value
|
||||
const total = s?.total_packages ?? 0
|
||||
const scanned = s?.scanned_packages ?? 0
|
||||
const held = s?.blocked_packages ?? 0
|
||||
const bypassed = s?.bypassed_packages ?? 0
|
||||
const tiles: Array<[Verdict, number, string, string, IconDefinition]> = [
|
||||
['cleared', Math.max(scanned - held - bypassed, 0), 'Scanned and served', '/packages?verdict=cleared', faCircleCheck],
|
||||
['held', held, 'Blocked with a 403', '/security?tab=held', faBan],
|
||||
['bypassed', bypassed, 'Served under an admin bypass', '/security?tab=bypassed', faUnlockKeyhole],
|
||||
['pending', Math.max(total - scanned, 0), 'No scan result yet', '/packages?verdict=pending', faHourglassHalf],
|
||||
]
|
||||
return tiles.map(([verdict, value, hint, to, icon]) => ({ verdict, value, hint, to, icon }))
|
||||
})
|
||||
|
||||
const EVENT_LABELS: Record<EventType, string> = {
|
||||
@@ -173,139 +166,38 @@ const EVENT_ICONS: Record<EventType, IconDefinition> = {
|
||||
stats_update: faChartLine,
|
||||
}
|
||||
|
||||
function iconForEvent(type: EventType): IconDefinition {
|
||||
return EVENT_ICONS[type] ?? faChartLine
|
||||
}
|
||||
const FEED_LENGTH = 6
|
||||
|
||||
const feedEvents = computed<ActivityEvent[]>(() =>
|
||||
recentRealtimeEvents.value.map((evt, idx) => ({
|
||||
id: `${evt.timestamp}-${idx}`,
|
||||
action: labelForEvent(evt.type),
|
||||
target: describeEvent(evt) || undefined,
|
||||
time: evt.timestamp,
|
||||
icon: iconForEvent(evt.type),
|
||||
})),
|
||||
rtEvents.value
|
||||
.filter((evt) => evt.type !== 'stats_update')
|
||||
.slice(-FEED_LENGTH)
|
||||
.reverse()
|
||||
.map((evt, idx) => ({
|
||||
id: `${evt.timestamp}-${idx}`,
|
||||
action: EVENT_LABELS[evt.type] ?? evt.type,
|
||||
target: describeEvent(evt) || undefined,
|
||||
time: evt.timestamp,
|
||||
icon: EVENT_ICONS[evt.type] ?? faChartLine,
|
||||
})),
|
||||
)
|
||||
|
||||
function labelForEvent(type: EventType): string {
|
||||
return EVENT_LABELS[type] ?? type
|
||||
}
|
||||
|
||||
function describeEvent(evt: RealtimeEvent): string {
|
||||
const p = evt.payload
|
||||
const name = typeof p.name === 'string' ? p.name : ''
|
||||
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
|
||||
const version = typeof shown === 'string' ? `@${shown}` : ''
|
||||
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
|
||||
if (evt.type === 'stats_update') return ''
|
||||
if (name) return `${registry}${name}${version}`
|
||||
return ''
|
||||
return name ? `${registry}${name}${version}` : ''
|
||||
}
|
||||
|
||||
// Chart periods and data
|
||||
const selectedPeriod = ref<string>('1day')
|
||||
const chartPeriods = [
|
||||
{ value: '1h', label: '1 hour' },
|
||||
{ value: '1day', label: '24 hours' },
|
||||
{ value: '7day', label: '7 days' },
|
||||
{ value: '30day', label: '30 days' },
|
||||
]
|
||||
|
||||
// Time-series data from API
|
||||
interface TimeSeriesDataPoint {
|
||||
timestamp: string
|
||||
value: number
|
||||
}
|
||||
|
||||
interface TimeSeriesStats {
|
||||
period: string
|
||||
registry: string
|
||||
data_points: TimeSeriesDataPoint[]
|
||||
}
|
||||
|
||||
const timeSeriesData = ref<TimeSeriesStats | null>(null)
|
||||
const chartLoading = ref(false)
|
||||
const chartError = ref<string | null>(null)
|
||||
|
||||
// Fetch time-series data from API
|
||||
async function fetchTimeSeriesData() {
|
||||
chartLoading.value = true
|
||||
chartError.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/timeseries?period=${selectedPeriod.value}`)
|
||||
timeSeriesData.value = response.data
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch time-series data:', err)
|
||||
timeSeriesData.value = null
|
||||
chartError.value = err instanceof Error ? err.message : 'Failed to load download activity'
|
||||
} finally {
|
||||
chartLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Extract chart values from time-series data
|
||||
const chartData = computed(() => {
|
||||
if (!timeSeriesData.value || !timeSeriesData.value.data_points) {
|
||||
return []
|
||||
}
|
||||
return timeSeriesData.value.data_points.map(point => point.value)
|
||||
})
|
||||
|
||||
const chartLabels = computed(() => chartData.value.map((_, index) => getChartLabel(index)))
|
||||
|
||||
const packageColumns: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', rowHeader: true },
|
||||
{ key: 'version', header: 'Version', accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
|
||||
{ key: 'registry', header: 'Registry' },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
|
||||
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
|
||||
]
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void store.fetchRecentPackages()
|
||||
}
|
||||
|
||||
function getChartLabel(index: number): string {
|
||||
// Use timestamp from data if available
|
||||
if (timeSeriesData.value && timeSeriesData.value.data_points[index]) {
|
||||
const date = new Date(timeSeriesData.value.data_points[index].timestamp)
|
||||
|
||||
switch (selectedPeriod.value) {
|
||||
case '1h':
|
||||
return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
|
||||
case '1day':
|
||||
return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
|
||||
case '7day':
|
||||
return date.toLocaleDateString('en-US', { weekday: 'short' })
|
||||
case '30day':
|
||||
return date.toLocaleDateString('en-US', { day: 'numeric' })
|
||||
default:
|
||||
return `${index}`
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to index-based labels
|
||||
const labels: Record<string, (i: number) => string> = {
|
||||
'1h': (i) => `${i * 5}m`,
|
||||
'1day': (i) => `${i}:00`,
|
||||
'7day': (i) => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][i] || `Day ${i + 1}`,
|
||||
'30day': (i) => `${i + 1}`,
|
||||
}
|
||||
return labels[selectedPeriod.value]?.(index) || `${index}`
|
||||
}
|
||||
|
||||
// Watch for period changes and fetch new data
|
||||
watch(selectedPeriod, () => {
|
||||
fetchTimeSeriesData()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
// Connect to realtime stream first so we can pick up live events while
|
||||
// initial polling resolves. Singleton survives navigation, so we
|
||||
// intentionally do not disconnect on unmount.
|
||||
onMounted(() => {
|
||||
// The realtime client is a singleton that outlives this view, so it is never disconnected here.
|
||||
rt.connect()
|
||||
await Promise.all([store.fetchStats(), store.fetchRecentPackages(), fetchTimeSeriesData()])
|
||||
refresh()
|
||||
})
|
||||
|
||||
</script>
|
||||
|
||||
@@ -1,167 +1,108 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader :title="packageName">
|
||||
<template #back>
|
||||
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to packages</Button>
|
||||
</template>
|
||||
<PageHeader :title="packageName" back-href="/packages" back-label="Back to packages">
|
||||
<template #description>
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline">{{ registry }}</Badge>
|
||||
<Badge variant="outline" class="font-mono">{{ withVersionPrefix(shownVersion) }}</Badge>
|
||||
<VerdictBadge v-if="report" :verdict="verdict" />
|
||||
</span>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="card" label="Loading vulnerability details..." />
|
||||
<LoadingState v-if="loading" variant="card" label="Loading package details..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load vulnerability details"
|
||||
title="Could not load this package"
|
||||
:message="error"
|
||||
@retry="fetchVulnerabilities"
|
||||
@retry="load"
|
||||
/>
|
||||
|
||||
<template v-else-if="vulnerabilities">
|
||||
<template v-else-if="report">
|
||||
<Callout v-if="banner" :type="banner.type" :title="banner.title" data-testid="verdict-banner">{{ banner.body }}</Callout>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Security scan summary</CardTitle>
|
||||
<CardTitle as="h2">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<SeveritySummary :counts="severityCounts" label="Vulnerabilities by severity" />
|
||||
<DescriptionList variant="inline" divided>
|
||||
<DescriptionItem term="Scanned">{{ formatDate(vulnerabilities.scanned_at) }}</DescriptionItem>
|
||||
<DescriptionItem term="Scanners">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<Badge v-for="scanner in scannerList" :key="scanner" variant="secondary">{{ scanner }}</Badge>
|
||||
</span>
|
||||
<CardContent>
|
||||
<DescriptionList variant="grid" :columns="3" data-testid="package-meta">
|
||||
<DescriptionItem term="Size">{{ row ? formatBytes(row.size) : 'Unknown' }}</DescriptionItem>
|
||||
<DescriptionItem term="Downloads">{{ row ? formatNumber(row.download_count) : 'Unknown' }}</DescriptionItem>
|
||||
<DescriptionItem term="Checksum (SHA-256)" :copyable="Boolean(row?.checksum_sha256)" :copy-text="row?.checksum_sha256">
|
||||
<span class="break-all font-mono text-xs">{{ row?.checksum_sha256 || 'Not recorded' }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="bypassedCount > 0" term="Bypassed">
|
||||
<StatusBadge status="bypassed" :label="`${bypassedCount} bypassed`" :tones="{ bypassed: 'success' }" />
|
||||
<DescriptionItem term="Upstream">{{ upstream }}</DescriptionItem>
|
||||
<DescriptionItem term="Cached">
|
||||
<RelativeTime v-if="row" :datetime="row.cached_at" />
|
||||
<template v-else>Unknown</template>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Last accessed">
|
||||
<RelativeTime v-if="row" :datetime="row.last_accessed" />
|
||||
<template v-else>Unknown</template>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Expiry">{{ expiry }}</DescriptionItem>
|
||||
<DescriptionItem term="Last scanned">
|
||||
<RelativeTime v-if="report.scanned_at" :datetime="report.scanned_at" />
|
||||
<template v-else>Never</template>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-if="vulnerabilityList.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
title="No vulnerabilities found"
|
||||
description="The scanners reported nothing for this package version."
|
||||
<Tabs v-model="tab">
|
||||
<TabsList aria-label="Package sections">
|
||||
<TabsTrigger value="vulnerabilities">Vulnerabilities ({{ report.vulnerability_count }})</TabsTrigger>
|
||||
<TabsTrigger value="inspectors">Inspectors</TabsTrigger>
|
||||
<TabsTrigger value="downloads">Downloads</TabsTrigger>
|
||||
<TabsTrigger value="bypass">Bypass</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="vulnerabilities" class="pt-4">
|
||||
<div class="flex flex-col gap-4">
|
||||
<SeveritySummary :counts="severityCounts" label="Findings by severity" />
|
||||
<EmptyState
|
||||
v-if="report.vulnerabilities.length === 0"
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
:title="report.scanned ? 'No vulnerabilities found' : 'Not scanned yet'"
|
||||
:description="report.scanned ? 'The scanners reported nothing for this package version.' : 'Findings appear here once a scan completes.'"
|
||||
/>
|
||||
<VulnerabilityTable v-else :vulnerabilities="report.vulnerabilities" />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="inspectors" class="pt-4">
|
||||
<InspectorMatrix :registry="registry" :results="report.scanners" :configured="configured" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="downloads" class="pt-4">
|
||||
<DownloadsPanel :registry="registry" :name="packageName" :version="version" :download-count="row?.download_count ?? 0" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="bypass" class="pt-4">
|
||||
<BypassPanel
|
||||
:applied="report.decision.bypass"
|
||||
:registry="registry"
|
||||
:name="packageName"
|
||||
:version="version"
|
||||
:release-version="report.package?.release_version"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Detected vulnerabilities ({{ vulnerabilityList.length }})</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table label="Detected vulnerabilities" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Severity</TableHead>
|
||||
<TableHead>CVE ID</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead>Fix version</TableHead>
|
||||
<TableHead align="center">Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<template v-for="(vuln, index) in vulnerabilityList" :key="vuln.id">
|
||||
<TableRow class="cursor-pointer" :selected="expandedRows.has(index)" @click="toggleRow(index)">
|
||||
<TableCell label="Severity">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge
|
||||
:status="vuln.severity"
|
||||
:tones="SEVERITY_TONES"
|
||||
:label="formatSeverityName(vuln.severity)"
|
||||
/>
|
||||
<StatusBadge
|
||||
v-if="vuln.bypassed"
|
||||
status="bypassed"
|
||||
label="Bypassed"
|
||||
:tones="{ bypassed: 'success' }"
|
||||
/>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="CVE ID" class="font-mono font-medium">{{ vuln.id }}</TableCell>
|
||||
<TableCell label="Description">
|
||||
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
|
||||
</TableCell>
|
||||
<TableCell label="Fix version">
|
||||
<span v-if="vuln.fixed_in">v{{ vuln.fixed_in }}</span>
|
||||
<span v-else class="text-muted-foreground">-</span>
|
||||
</TableCell>
|
||||
<TableCell label="Details" align="center">
|
||||
<IconButton
|
||||
size="icon-sm"
|
||||
:icon="expandedRows.has(index) ? faChevronUp : faChevronDown"
|
||||
:label="`${expandedRows.has(index) ? 'Hide' : 'Show'} details for ${vuln.id}`"
|
||||
:aria-expanded="expandedRows.has(index)"
|
||||
@click.stop="toggleRow(index)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
<TableRow v-if="expandedRows.has(index)" :hoverable="false">
|
||||
<TableCell :colspan="5">
|
||||
<div class="flex flex-col gap-4 py-2">
|
||||
<section>
|
||||
<h3 class="mb-2 text-sm font-semibold">Description</h3>
|
||||
<Markdown :source="vuln.description" :heading-offset="3" />
|
||||
</section>
|
||||
|
||||
<Alert v-if="vuln.bypassed && vuln.bypass" variant="success">
|
||||
<AlertTitle>Bypass active</AlertTitle>
|
||||
<AlertDescription>
|
||||
<DescriptionList variant="grid" :columns="3" size="sm">
|
||||
<DescriptionItem term="Reason">{{ vuln.bypass.reason }}</DescriptionItem>
|
||||
<DescriptionItem term="By">{{ vuln.bypass.created_by }}</DescriptionItem>
|
||||
<DescriptionItem term="Expires">{{ formatDate(vuln.bypass.expires_at) }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Alert v-if="vuln.fixed_in" variant="info">
|
||||
<AlertTitle>Fix available</AlertTitle>
|
||||
<AlertDescription>
|
||||
Upgrade to version <strong>{{ vuln.fixed_in }}</strong> or later.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<section v-if="vuln.references && vuln.references.length > 0">
|
||||
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
|
||||
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li v-for="(ref, refIndex) in vuln.references" :key="refIndex" class="break-all">
|
||||
<Link :href="ref" external>{{ ref }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
Badge,
|
||||
Button,
|
||||
Callout,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
@@ -170,129 +111,97 @@ import {
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
IconButton,
|
||||
Link,
|
||||
LoadingState,
|
||||
Markdown,
|
||||
PageHeader,
|
||||
StatusBadge,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
RelativeTime,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faChevronDown, faChevronUp, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
|
||||
import BypassPanel from './parts/BypassPanel.vue'
|
||||
import DownloadsPanel from './parts/DownloadsPanel.vue'
|
||||
import InspectorMatrix from './parts/InspectorMatrix.vue'
|
||||
import VerdictBadge from './parts/VerdictBadge.vue'
|
||||
import VulnerabilityTable from './parts/VulnerabilityTable.vue'
|
||||
import type { Package } from '../stores/packages'
|
||||
import { formatBytes, formatDate, formatNumber, formatDuration, withVersionPrefix } from '@/lib/format'
|
||||
import { faCircleCheck } from '@/lib/icons'
|
||||
import type { PackageReport } from '@/lib/report'
|
||||
import { NO_VULNERABILITIES } from '@/lib/severity'
|
||||
import { describePolicy, useSystem } from '@/lib/system'
|
||||
import type { Verdict } from '@/lib/verdict'
|
||||
import { verdictBanner } from '@/lib/verdictBanner'
|
||||
|
||||
const TABS = ['vulnerabilities', 'inspectors', 'downloads', 'bypass'] as const
|
||||
type TabName = (typeof TABS)[number]
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const system = useSystem()
|
||||
|
||||
const registry = computed(() => route.params.registry as string)
|
||||
// Names with slashes (scoped npm, Go modules) arrive as segments.
|
||||
const packageName = computed(() => {
|
||||
// Handle package names with slashes (e.g., Go packages like github.com/user/repo)
|
||||
const nameParam = route.params.name
|
||||
if (Array.isArray(nameParam)) {
|
||||
return nameParam.join('/')
|
||||
}
|
||||
return nameParam as string
|
||||
const name = route.params.name
|
||||
return Array.isArray(name) ? name.join('/') : (name as string)
|
||||
})
|
||||
const version = computed(() => route.params.version as string)
|
||||
const shownVersion = computed(() => vulnerabilities.value?.package?.release_version || version.value)
|
||||
|
||||
interface BypassInfo {
|
||||
id: string
|
||||
reason: string
|
||||
created_by: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
interface Vulnerability {
|
||||
id: string
|
||||
severity: string
|
||||
title: string
|
||||
description: string
|
||||
references: string[]
|
||||
fixed_in: string
|
||||
bypassed: boolean
|
||||
bypass?: BypassInfo
|
||||
}
|
||||
|
||||
interface VulnerabilityResponse {
|
||||
package?: { release_version?: string }
|
||||
scanned: boolean
|
||||
scanner: string
|
||||
scanned_at: string
|
||||
status: string
|
||||
vulnerabilities: Vulnerability[]
|
||||
vulnerability_count: number
|
||||
severity_counts: {
|
||||
critical: number
|
||||
high: number
|
||||
moderate: number
|
||||
low: number
|
||||
}
|
||||
bypassed_count: number
|
||||
}
|
||||
const shownVersion = computed(() => report.value?.package?.release_version || version.value)
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerabilities = ref<VulnerabilityResponse | null>(null)
|
||||
const expandedRows = ref<Set<number>>(new Set())
|
||||
const report = ref<PackageReport | null>(null)
|
||||
const row = ref<Package | null>(null)
|
||||
|
||||
const vulnerabilityList = computed(() => {
|
||||
const vulns = vulnerabilities.value?.vulnerabilities || []
|
||||
// Sort by severity (most severe first)
|
||||
return [...vulns].sort((a, b) => {
|
||||
return severityRank(b.severity) - severityRank(a.severity)
|
||||
})
|
||||
const tab = ref<TabName>(TABS.find((t) => t === route.query.tab) ?? 'vulnerabilities')
|
||||
watch(tab, (value) => void router.replace({ query: { ...route.query, tab: value === 'vulnerabilities' ? undefined : value } }))
|
||||
|
||||
const severityCounts = computed(() => report.value?.severity_counts ?? NO_VULNERABILITIES)
|
||||
const configured = computed(() => system.info.value?.security.scanners ?? [])
|
||||
const verdict = computed<Verdict>(() => report.value?.decision.verdict ?? 'unscanned')
|
||||
|
||||
const banner = computed(() => {
|
||||
if (!report.value) return null
|
||||
const sec = system.info.value?.security
|
||||
return verdictBanner(report.value, sec ? describePolicy(sec) : '', sec?.fail_closed ?? false)
|
||||
})
|
||||
|
||||
const severityCounts = computed(() => vulnerabilities.value?.severity_counts || NO_VULNERABILITIES)
|
||||
const bypassedCount = computed(() => vulnerabilities.value?.bypassed_count || 0)
|
||||
const upstream = computed(() => system.info.value?.upstreams[registry.value] || 'Not reported')
|
||||
|
||||
// Parse scanner string into array of scanner names
|
||||
const scannerList = computed(() => {
|
||||
if (!vulnerabilities.value?.scanner) return []
|
||||
return vulnerabilities.value.scanner.split('+').map((s: string) => s.trim())
|
||||
// Idle eviction is the only expiry the server enforces on a cached package.
|
||||
const expiry = computed(() => {
|
||||
const idle = system.info.value?.cache.idle_ttl
|
||||
if (idle === undefined) return 'Not reported'
|
||||
if (idle === 0) return 'Never. Idle eviction is off.'
|
||||
const last = row.value ? Date.parse(row.value.last_accessed) : Number.NaN
|
||||
const after = `Removed after ${formatDuration(idle)} without a request`
|
||||
return Number.isNaN(last) ? after : `${after}, on ${formatDate(new Date(last + idle * 1000).toISOString())} if unused`
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
fetchVulnerabilities()
|
||||
})
|
||||
|
||||
async function fetchVulnerabilities() {
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
vulnerabilities.value = null
|
||||
|
||||
report.value = null
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`/api/packages/${registry.value}/${packageName.value}/${version.value}/vulnerabilities`
|
||||
)
|
||||
// Store the response data
|
||||
vulnerabilities.value = response.data
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch vulnerabilities:', err)
|
||||
error.value = err.response?.data?.error || err.message || 'Failed to load vulnerability details'
|
||||
const encoded = `${registry.value}/${packageName.value}/${version.value}`
|
||||
const [details, list] = await Promise.all([
|
||||
axios.get<PackageReport>(`/api/packages/${encoded}/vulnerabilities`),
|
||||
axios
|
||||
.get<{ packages: Package[] }>(`/api/packages?registry=${encodeURIComponent(registry.value)}&q=${encodeURIComponent(packageName.value)}`)
|
||||
.catch(() => null),
|
||||
system.load(),
|
||||
])
|
||||
report.value = details.data
|
||||
row.value = list?.data.packages?.find((p) => p.name === packageName.value && p.version === version.value) ?? null
|
||||
} catch (err: unknown) {
|
||||
const e = err as { response?: { data?: { error?: string } }; message?: string }
|
||||
error.value = e.response?.data?.error || e.message || 'Failed to load package details'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
router.push('/packages')
|
||||
}
|
||||
|
||||
function toggleRow(index: number) {
|
||||
if (expandedRows.value.has(index)) {
|
||||
expandedRows.value.delete(index)
|
||||
} else {
|
||||
expandedRows.value.add(index)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
@@ -1,325 +1,92 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
|
||||
import { defineComponent, h } from 'vue'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import PackageList from './PackageList.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { PACKAGES } from '@/test/fixtures'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
type Row = ReturnType<typeof usePackageStore>['packagePage']['packages'][number]
|
||||
|
||||
// A page as the server sends it: whole groups, flattened to rows.
|
||||
function setRows(store: ReturnType<typeof usePackageStore>, packages: Row[]) {
|
||||
const groups = new Set(packages.map((p) => `${p.registry}:${p.name}`))
|
||||
store.packagePage = { packages, totalGroups: groups.size, page: 1, pageSize: 25 }
|
||||
}
|
||||
|
||||
const Stub = defineComponent({ render: () => h('div') })
|
||||
|
||||
function createTestRouter(): Router {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/', name: 'dashboard', component: Stub },
|
||||
{ path: '/packages/:registry?', name: 'packages', component: Stub, props: true },
|
||||
{
|
||||
path: '/package/:registry/:name+/:version',
|
||||
name: 'package-details',
|
||||
component: Stub,
|
||||
props: true,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
async function mountWithRouter() {
|
||||
const router = createTestRouter()
|
||||
router.push('/packages')
|
||||
await router.isReady()
|
||||
return mount(PackageList, {
|
||||
global: {
|
||||
plugins: [router],
|
||||
},
|
||||
async function open(path = '/packages', rows: Package[] = PACKAGES) {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchPackages').mockImplementation(async () => {
|
||||
store.packages = rows
|
||||
})
|
||||
const wrapper = mount(PackageList, { props: { registry: router.currentRoute.value.params.registry as string | undefined }, global: { plugins: [pinia, router] } })
|
||||
await flushPromises()
|
||||
return { wrapper, store, router }
|
||||
}
|
||||
|
||||
describe('PackageList.vue', () => {
|
||||
beforeEach(() => {
|
||||
// Create a fresh pinia instance before each test
|
||||
setActivePinia(createPinia())
|
||||
// Prevent real network calls from store actions on mount
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchPackagePage').mockResolvedValue()
|
||||
})
|
||||
beforeEach(() => setActivePinia(createPinia()))
|
||||
|
||||
it('renders package list component', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
it('renders the page heading', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
it('loads every package once on mount', async () => {
|
||||
const { store } = await open()
|
||||
expect(store.fetchPackages).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('displays loading state while the first load runs', async () => {
|
||||
const { wrapper, store } = await open('/packages', [])
|
||||
store.loading = true
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading packages...')
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
it('displays the error message when the load fails', async () => {
|
||||
const { wrapper, store } = await open('/packages', [])
|
||||
store.error = 'Failed to fetch packages'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Failed to fetch packages')
|
||||
})
|
||||
|
||||
it('displays empty state when no packages', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
it('displays an empty state when nothing is cached', async () => {
|
||||
const { wrapper } = await open('/packages', [])
|
||||
expect(wrapper.text()).toContain('No packages cached yet')
|
||||
})
|
||||
|
||||
it('displays package accordion when packages exist', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
expect(wrapper.text()).toContain('1 version')
|
||||
it('shows one row per version with its size, downloads and verdict word', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(PACKAGES.length)
|
||||
const text = wrapper.text()
|
||||
expect(text).toContain('2 KB')
|
||||
expect(text).toContain('Held')
|
||||
expect(text).toContain('Awaiting scan')
|
||||
})
|
||||
|
||||
it('asks the server for the first page on mount', async () => {
|
||||
const store = usePackageStore()
|
||||
// beforeEach already spied with mockResolvedValue; reuse that spy
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
it('narrows rows with the search box and says when nothing matches', async () => {
|
||||
const { wrapper } = await open()
|
||||
const input = wrapper.get('input[type="search"], input[aria-label="Search packages"]')
|
||||
await input.setValue('requests')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
|
||||
|
||||
await mountWithRouter()
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalled()
|
||||
await input.setValue('nothing-like-this')
|
||||
expect(wrapper.text()).toContain('No packages match')
|
||||
})
|
||||
|
||||
it('groups packages and displays version counts', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '2.0.0',
|
||||
size: 2048,
|
||||
cached_at: '2025-01-02T00:00:00Z',
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 20,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
expect(wrapper.text()).toContain('2 versions')
|
||||
it('writes the search to the URL so a reload restores it', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await wrapper.get('input[aria-label="Search packages"]').setValue('left')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query.q).toBe('left')
|
||||
})
|
||||
|
||||
it('formats bytes correctly', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '1.0.0',
|
||||
size: 1048576, // 1 MB
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 MB')
|
||||
it('treats the registry path segment as a registry filter', async () => {
|
||||
const { wrapper } = await open('/packages/pypi')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
|
||||
expect(wrapper.text()).toContain('requests')
|
||||
})
|
||||
|
||||
it('prints every registry as a badge with its name', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [
|
||||
{
|
||||
id: '3',
|
||||
registry: 'go',
|
||||
name: 'go-module',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 3,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'npm-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
registry: 'pypi',
|
||||
name: 'python-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Verify that all registry badges are displayed
|
||||
// The server sends groups in name order: go-module, npm-package, python-package
|
||||
expect(wrapper.text()).toContain('npm')
|
||||
expect(wrapper.text()).toContain('pypi')
|
||||
expect(wrapper.text()).toContain('go')
|
||||
|
||||
// Each registry is printed as text in an outline badge, never as colour alone.
|
||||
const badges = wrapper.findAll('[data-slot="badge"]').map((badge) => badge.text())
|
||||
expect(badges).toEqual(['go', 'npm', 'pypi'])
|
||||
})
|
||||
|
||||
it('shows the release version for a PyPI file row, not the file name', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'pypi',
|
||||
name: 'six',
|
||||
version: 'six-1.17.0-py2.py3-none-any.whl',
|
||||
release_version: '1.17.0',
|
||||
size: 1,
|
||||
cached_at: '2026-11-23T00:00:00Z',
|
||||
last_accessed: '2026-11-23T00:00:00Z',
|
||||
download_count: 0,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
it('shows the release version of a PyPI file row, not the file name', async () => {
|
||||
const six = { ...PACKAGES[2], version: 'six-1.17.0-py2.py3-none-any.whl', release_version: '1.17.0' }
|
||||
const { wrapper } = await open('/packages', [six])
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
describe('server-side paging, search and registry filter', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('debounces the search box into one request with q and page 1', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
|
||||
const input = wrapper.find('input[type="search"], input')
|
||||
await input.setValue('l')
|
||||
await input.setValue('le')
|
||||
await input.setValue('left')
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'all', q: 'left' })
|
||||
})
|
||||
|
||||
it('sends the registry of the route with every request', async () => {
|
||||
const router = createTestRouter()
|
||||
router.push('/packages/pypi')
|
||||
await router.isReady()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
mount(PackageList, { props: { registry: 'pypi' }, global: { plugins: [router] } })
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'pypi', q: '' })
|
||||
})
|
||||
|
||||
it('pages through the server, not the loaded rows', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.packagePage = {
|
||||
packages: [
|
||||
{ id: '1', registry: 'npm', name: 'a', version: '1', size: 1, cached_at: '2025-01-01T00:00:00Z', last_accessed: '2025-01-01T00:00:00Z', download_count: 0 },
|
||||
],
|
||||
totalGroups: 60,
|
||||
page: 1,
|
||||
pageSize: 25,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.text()).toContain('Page 1 of 3 (60 total packages)')
|
||||
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
|
||||
const next = wrapper.findAll('button').find((b) => /next/i.test(b.attributes('aria-label') ?? b.text()))
|
||||
await next!.trigger('click')
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 2, pageSize: 25, registry: 'all', q: '' })
|
||||
})
|
||||
|
||||
it('says no packages match when a filter empties the page', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
setRows(store, [])
|
||||
await wrapper.find('input').setValue('zzz')
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(wrapper.text()).toContain('No packages match')
|
||||
expect(wrapper.text()).not.toContain('No packages cached yet')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,133 +1,76 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached and the verdict each package received.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
|
||||
<SegmentedControl
|
||||
:model-value="selectedRegistry"
|
||||
:options="REGISTRY_OPTIONS"
|
||||
aria-label="Filter by registry"
|
||||
@update:model-value="changeRegistryFilter"
|
||||
/>
|
||||
<SearchInput v-model="searchTerm" aria-label="Search packages" placeholder="Search packages..." class="w-full sm:ms-auto sm:w-64" />
|
||||
<div class="flex flex-col gap-3">
|
||||
<SearchInput v-model="query" aria-label="Search packages" placeholder="Search by name or version..." class="w-full sm:max-w-md" />
|
||||
<FilterBar v-model="filterItems" :fields="filterFields" variant="compact" />
|
||||
</div>
|
||||
|
||||
<LoadingState v-if="loading" variant="table" label="Loading packages..." />
|
||||
<LoadingState v-if="loading && packages.length === 0" variant="table" label="Loading packages..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load packages"
|
||||
:message="error"
|
||||
@retry="load()"
|
||||
/>
|
||||
<ErrorState v-else-if="error" variant="card" title="Could not load packages" :message="error" @retry="load()" />
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="totalGroups === 0 && !filtersActive"
|
||||
v-if="packages.length === 0"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages will appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="groups.length === 0"
|
||||
v-else-if="rows.length === 0"
|
||||
:icon="faMagnifyingGlass"
|
||||
title="No packages match"
|
||||
description="Change the registry filter or the search text."
|
||||
description="Change the search text or remove a filter."
|
||||
/>
|
||||
<Accordion v-else type="multiple" class="w-full">
|
||||
<AccordionItem
|
||||
v-for="group in groups"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
<AccordionTrigger :heading-level="2">
|
||||
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
|
||||
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||
<span class="w-full min-w-0 text-start sm:w-auto">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
</span>
|
||||
</span>
|
||||
<span class="flex shrink-0 items-center gap-4">
|
||||
<Badge variant="outline">{{ group.registry }}</Badge>
|
||||
<span class="text-end tabular-nums">
|
||||
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<Table :label="`Versions of ${group.name}`" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Version</TableHead>
|
||||
<TableHead align="right">Downloads</TableHead>
|
||||
<TableHead align="right">Size</TableHead>
|
||||
<TableHead>Cached</TableHead>
|
||||
<TableHead>Vulnerabilities</TableHead>
|
||||
<TableHead align="right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="version in group.versions" :key="version.id">
|
||||
<TableCell label="Version" class="font-medium">{{ withVersionPrefix(displayVersion(version)) }}</TableCell>
|
||||
<TableCell label="Downloads" numeric>{{ formatNumber(version.download_count) }}</TableCell>
|
||||
<TableCell label="Size" numeric>{{ formatBytes(version.size) }}</TableCell>
|
||||
<TableCell label="Cached">{{ formatDate(version.cached_at) }}</TableCell>
|
||||
<TableCell label="Vulnerabilities">
|
||||
<VulnerabilityBadge
|
||||
v-if="version.vulnerabilities"
|
||||
:scanned="version.vulnerabilities.scanned"
|
||||
:status="version.vulnerabilities.status"
|
||||
:counts="version.vulnerabilities.counts"
|
||||
:total="version.vulnerabilities.total"
|
||||
:scannedAt="version.vulnerabilities.scannedAt"
|
||||
:isBlocked="version.vulnerabilities.isBlocked"
|
||||
@click="showVulnerabilityDetails(group.registry, group.name, version.version)"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell label="Actions" align="right">
|
||||
<IconButton
|
||||
:icon="faTrash"
|
||||
:label="`Delete ${group.name} ${version.version}`"
|
||||
@click="confirmDelete(version)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<div v-if="totalPages > 1" class="mt-6 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
Page {{ currentPage }} of {{ totalPages }} ({{ totalGroups }} total packages)
|
||||
<template v-else>
|
||||
<p class="m-0 mb-3 text-sm text-muted-foreground" data-testid="package-count">
|
||||
{{ rows.length }} of {{ packages.length }} package versions
|
||||
</p>
|
||||
<Pagination
|
||||
:page="currentPage"
|
||||
:total="totalGroups"
|
||||
<DataTable
|
||||
v-model:sort="sort"
|
||||
v-model:page="page"
|
||||
label="Cached packages"
|
||||
layout="cards"
|
||||
density="compact"
|
||||
row-clickable
|
||||
:page-size="PAGE_SIZE"
|
||||
:show-edges="false"
|
||||
@update:page="changePage"
|
||||
/>
|
||||
</div>
|
||||
:columns="columns"
|
||||
:rows="rows"
|
||||
@row-click="(row: Package) => (selected = row)"
|
||||
>
|
||||
<template #cell-name="{ row }">
|
||||
<RouterLink :to="packageRoute(row)" class="break-words font-medium text-foreground underline-offset-4 hover:underline">
|
||||
{{ row.name }}
|
||||
</RouterLink>
|
||||
</template>
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-size="{ row }">{{ formatBytes(row.size) }}</template>
|
||||
<template #cell-download_count="{ row }">{{ formatNumber(row.download_count) }}</template>
|
||||
<template #cell-last_accessed="{ row }"><RelativeTime :datetime="row.last_accessed" /></template>
|
||||
<template #cell-verdict="{ row }"><VerdictBadge :verdict="verdictOf(row)" /></template>
|
||||
<template #cell-scanned="{ row }">
|
||||
<RelativeTime v-if="row.vulnerabilities?.scannedAt" :datetime="row.vulnerabilities.scannedAt" />
|
||||
<span v-else class="text-muted-foreground">Never</span>
|
||||
</template>
|
||||
</DataTable>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<PackageQuickView :pkg="selected" @close="selected = null" @delete="confirmDelete" />
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="showDeleteModal"
|
||||
title="Delete package version?"
|
||||
:description="`Delete ${packageToDelete?.name}@${packageToDelete?.version}? This action cannot be undone.`"
|
||||
confirm-label="Delete version"
|
||||
title="Remove package version?"
|
||||
:description="`Remove ${packageToDelete?.name}@${packageToDelete?.version} from the cache? Clients can fetch it again from upstream.`"
|
||||
confirm-label="Remove version"
|
||||
tone="danger"
|
||||
destructive
|
||||
@confirm="deletePackage"
|
||||
@@ -136,130 +79,124 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, computed, watch } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
ConfirmDialog,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
IconButton,
|
||||
FilterBar,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
Pagination,
|
||||
RelativeTime,
|
||||
SearchInput,
|
||||
SegmentedControl,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
type FilterField,
|
||||
type FilterItem,
|
||||
type SortState,
|
||||
} from '@perfect-design/ui'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faBoxOpen, faMagnifyingGlass, faRotateRight, faTrash } from '@/lib/icons'
|
||||
import PackageQuickView from './parts/PackageQuickView.vue'
|
||||
import VerdictBadge from './parts/VerdictBadge.vue'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { filterPackages, packageRoute } from '@/lib/packages'
|
||||
import { faBoxOpen, faMagnifyingGlass, faRotateRight } from '@/lib/icons'
|
||||
import { VERDICT_OPTIONS, VERDICT_RANK, verdictOf, type Verdict } from '@/lib/verdict'
|
||||
|
||||
// Props from router
|
||||
const props = defineProps<{
|
||||
registry?: string
|
||||
}>()
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = usePackageStore()
|
||||
const toasts = useToastStore()
|
||||
const { packagePage, loading, error } = storeToRefs(store)
|
||||
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
const REGISTRY_OPTIONS = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'npm', label: 'npm' },
|
||||
{ value: 'pypi', label: 'PyPI' },
|
||||
{ value: 'go', label: 'Go' },
|
||||
]
|
||||
const props = defineProps<{ registry?: string }>()
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
const KNOWN_REGISTRIES = ['npm', 'go', 'pypi']
|
||||
|
||||
const selectedRegistry = ref<string>(props.registry || 'all')
|
||||
const searchTerm = ref<string>('')
|
||||
// What the server was last asked: the search text lags the input by the debounce.
|
||||
const activeQuery = ref<string>('')
|
||||
const currentPage = ref<number>(1)
|
||||
const store = usePackageStore()
|
||||
const toasts = useToastStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { packages, loading, error } = storeToRefs(store)
|
||||
|
||||
const totalGroups = computed(() => packagePage.value.totalGroups)
|
||||
const totalPages = computed(() => Math.ceil(totalGroups.value / PAGE_SIZE))
|
||||
const filtersActive = computed(() => selectedRegistry.value !== 'all' || activeQuery.value.trim() !== '')
|
||||
const selected = ref<Package | null>(null)
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
const sort = ref<SortState | null>(null)
|
||||
const page = ref(1)
|
||||
|
||||
// The server pages whole (registry, name) groups and sends every version row of each.
|
||||
const groups = computed(() => {
|
||||
const byKey = new Map<string, { registry: string; name: string; versions: Package[] }>()
|
||||
for (const pkg of packagePage.value.packages) {
|
||||
const key = `${pkg.registry}\u0000${pkg.name}`
|
||||
let group = byKey.get(key)
|
||||
if (!group) {
|
||||
group = { registry: pkg.registry, name: pkg.name, versions: [] }
|
||||
byKey.set(key, group)
|
||||
}
|
||||
group.versions.push(pkg)
|
||||
}
|
||||
return Array.from(byKey.values()).map((group) => ({
|
||||
...group,
|
||||
totalSize: group.versions.reduce((sum, v) => sum + v.size, 0),
|
||||
totalDownloads: group.versions.reduce((sum, v) => sum + v.download_count, 0),
|
||||
}))
|
||||
function queryText(key: string): string {
|
||||
const raw = route.query[key]
|
||||
return typeof raw === 'string' ? raw : ''
|
||||
}
|
||||
|
||||
const query = ref(queryText('q'))
|
||||
|
||||
let nextFilterId = 0
|
||||
function filterItem(field: string, value: string): FilterItem {
|
||||
return { id: `f${nextFilterId++}`, field, operator: 'eq', value }
|
||||
}
|
||||
|
||||
// The path segment is the pre-redesign way to pick a registry, so it still seeds the filter.
|
||||
const filterItems = ref<FilterItem[]>(
|
||||
[
|
||||
...[props.registry || queryText('registry')].filter(Boolean).map((r) => filterItem('registry', r)),
|
||||
...[queryText('verdict')].filter(Boolean).map((v) => filterItem('verdict', v)),
|
||||
],
|
||||
)
|
||||
|
||||
const registryOptions = computed(() => {
|
||||
const seen = new Set([...KNOWN_REGISTRIES, ...packages.value.map((p) => p.registry)])
|
||||
return [...seen].map((value) => ({ value, label: value }))
|
||||
})
|
||||
|
||||
const filterFields = computed<FilterField[]>(() => [
|
||||
{ id: 'registry', label: 'Registry', type: 'select', options: registryOptions.value, operators: ['eq'] },
|
||||
{ id: 'verdict', label: 'Verdict', type: 'select', options: VERDICT_OPTIONS, operators: ['eq'] },
|
||||
])
|
||||
|
||||
function valuesOf(field: string): string[] {
|
||||
return filterItems.value.filter((f) => f.field === field).map((f) => String(f.value))
|
||||
}
|
||||
|
||||
const rows = computed(() =>
|
||||
filterPackages(packages.value, {
|
||||
query: query.value,
|
||||
registries: valuesOf('registry'),
|
||||
verdicts: valuesOf('verdict') as Verdict[],
|
||||
}),
|
||||
)
|
||||
|
||||
// The URL mirrors the filters so a reload or a shared link restores the view.
|
||||
watch([query, filterItems], () => {
|
||||
page.value = 1
|
||||
const { q: _q, registry: _r, verdict: _v, ...rest } = route.query
|
||||
const next: Record<string, string> = {}
|
||||
if (query.value.trim()) next.q = query.value.trim()
|
||||
const [registry] = valuesOf('registry')
|
||||
const [verdict] = valuesOf('verdict')
|
||||
if (registry) next.registry = registry
|
||||
if (verdict) next.verdict = verdict
|
||||
void router.replace({ path: '/packages', query: { ...rest, ...next } })
|
||||
})
|
||||
|
||||
const columns: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', sortable: true, rowHeader: true },
|
||||
{ key: 'version', header: 'Version', sortable: true, accessor: (p) => withVersionPrefix(displayVersion(p)) },
|
||||
{ key: 'registry', header: 'Registry', sortable: true },
|
||||
{ key: 'size', header: 'Size', sortable: true, numeric: true },
|
||||
{ key: 'download_count', header: 'Downloads', sortable: true, numeric: true },
|
||||
{ key: 'last_accessed', header: 'Last accessed', sortable: true, accessor: (p) => Date.parse(p.last_accessed) || 0 },
|
||||
{ key: 'verdict', header: 'Verdict', sortable: true, accessor: (p) => VERDICT_RANK[verdictOf(p)] },
|
||||
{ key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 },
|
||||
]
|
||||
|
||||
async function load() {
|
||||
await store.fetchPackagePage({
|
||||
page: currentPage.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
registry: selectedRegistry.value,
|
||||
q: activeQuery.value,
|
||||
})
|
||||
await store.fetchPackages()
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
if (page >= 1 && page <= totalPages.value) {
|
||||
currentPage.value = page
|
||||
void load()
|
||||
// Scroll to top of packages list
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
}
|
||||
|
||||
// A burst of keystrokes asks the server once.
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(searchTerm, (term) => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => {
|
||||
if (term === activeQuery.value) return
|
||||
activeQuery.value = term
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
}, SEARCH_DEBOUNCE_MS)
|
||||
})
|
||||
onBeforeUnmount(() => clearTimeout(searchTimer))
|
||||
|
||||
// Watch for route parameter changes to update filter
|
||||
watch(() => route.params.registry, (newRegistry) => {
|
||||
selectedRegistry.value = (newRegistry as string) || 'all'
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
})
|
||||
|
||||
onMounted(load)
|
||||
|
||||
function confirmDelete(pkg: Package) {
|
||||
@@ -273,36 +210,15 @@ async function deletePackage() {
|
||||
await store.deletePackage(target.registry, target.name, target.version)
|
||||
showDeleteModal.value = false
|
||||
packageToDelete.value = null
|
||||
selected.value = null
|
||||
const label = `${target.name}@${target.version}`
|
||||
if (store.error) {
|
||||
toasts.error('Could not delete package', `${label}: ${store.error}`)
|
||||
toasts.error('Could not remove package', `${label}: ${store.error}`)
|
||||
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
|
||||
store.error = null
|
||||
} else {
|
||||
toasts.success('Package deleted', label)
|
||||
toasts.success('Package removed', label)
|
||||
await load()
|
||||
// Deleting the last group of the last page leaves that page empty.
|
||||
if (packagePage.value.packages.length === 0 && totalGroups.value > 0 && currentPage.value > 1) {
|
||||
currentPage.value = Math.max(totalPages.value, 1)
|
||||
await load()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showVulnerabilityDetails(registry: string, name: string, version: string) {
|
||||
// Navigate to the package details page
|
||||
router.push({
|
||||
name: 'package-details',
|
||||
params: {
|
||||
registry,
|
||||
name,
|
||||
version,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function changeRegistryFilter(registry: string) {
|
||||
const path = registry === 'all' ? '/packages' : `/packages/${registry}`
|
||||
router.push(path)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import Security from './Security.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
@@ -31,7 +31,6 @@ function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_SEVERITIES = 'critical,high,moderate,low'
|
||||
const FIXTURE: Package[] = [
|
||||
vulnerable('alpha-critical', { critical: 1 }),
|
||||
vulnerable('bravo-high', { high: 2 }),
|
||||
@@ -53,11 +52,11 @@ afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/vulnerable-packages') {
|
||||
async function open(path = '/security?tab=allowed') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
const mounted = await mountStrict(Security, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return { ...mounted, router }
|
||||
@@ -71,7 +70,7 @@ const pressed = (wrapper: Wrapper) =>
|
||||
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
|
||||
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
|
||||
|
||||
describe('VulnerablePackages severity filter', () => {
|
||||
describe('Security severity filter', () => {
|
||||
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
|
||||
const { wrapper, problems, router } = await open()
|
||||
|
||||
@@ -83,9 +82,9 @@ describe('VulnerablePackages severity filter', () => {
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('asks the server for vulnerable packages only', async () => {
|
||||
it('asks the server for every package, so a hold with no findings is not dropped', async () => {
|
||||
await open()
|
||||
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
|
||||
expect(axios.get).toHaveBeenCalledWith('/api/packages')
|
||||
})
|
||||
|
||||
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
|
||||
@@ -172,7 +171,7 @@ describe('VulnerablePackages severity filter', () => {
|
||||
})
|
||||
|
||||
it('restores the filter from the URL, as after a reload or a shared link', async () => {
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=high,critical')
|
||||
const { wrapper } = await open('/security?tab=allowed&severity=high,critical')
|
||||
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
@@ -180,17 +179,17 @@ describe('VulnerablePackages severity filter', () => {
|
||||
})
|
||||
|
||||
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=bogus&ref=mail')
|
||||
const { wrapper, router } = await open('/security?tab=allowed&severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
|
||||
expect(router.currentRoute.value.query).toEqual({ tab: 'allowed', ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
|
||||
const { wrapper, router } = await open('/security?tab=allowed&severity=low')
|
||||
|
||||
const empty = wrapper.get('[data-slot="empty-state"]')
|
||||
expect(empty.text()).toContain('No packages match the filter')
|
||||
@@ -206,21 +205,32 @@ describe('VulnerablePackages severity filter', () => {
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the success state when nothing is vulnerable, filter or not', async () => {
|
||||
it('keeps the success state when nothing has findings, filter or not', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=critical')
|
||||
const { wrapper } = await open('/security?tab=allowed&severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(wrapper.text()).toContain('No package carries findings under the policy')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('still narrows to blocked packages on the blocked route', async () => {
|
||||
const blocked = vulnerable('echo-blocked', { critical: 1 })
|
||||
blocked.vulnerabilities!.isBlocked = true
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
|
||||
it('lists a held package under Held, not under Vulnerable but allowed', async () => {
|
||||
const held = vulnerable('echo-blocked', { critical: 1 })
|
||||
held.vulnerabilities!.isBlocked = true
|
||||
held.vulnerabilities!.verdict = 'held'
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, held] } })
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
|
||||
it('lists a held package that has no findings, such as a failed scan', async () => {
|
||||
const failed = vulnerable('foxtrot-failed', {})
|
||||
failed.vulnerabilities = { scanned: true, status: 'clean', isBlocked: true, verdict: 'held', reason: 'scan failed - fail closed' }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [failed] } })
|
||||
const { wrapper } = await open('/security?tab=held')
|
||||
|
||||
expect(wrapper.text()).toContain('foxtrot-failed')
|
||||
expect(wrapper.text()).toContain('scan failed - fail closed')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,140 +1,104 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
:title="showOnlyBlocked ? 'Blocked packages' : 'Vulnerable packages'"
|
||||
:description="
|
||||
showOnlyBlocked
|
||||
? 'Packages blocked from download because they exceed the vulnerability thresholds.'
|
||||
: 'Packages with known security vulnerabilities, sorted by risk.'
|
||||
"
|
||||
>
|
||||
<template #back>
|
||||
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to stats</Button>
|
||||
<PageHeader title="Security" description="Packages the scanners found something in, and what the policy did about each.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="card" label="Loading vulnerable packages..." />
|
||||
<LoadingState v-if="loading && packages.length === 0" variant="table" label="Loading security findings..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load vulnerable packages"
|
||||
:message="error"
|
||||
@retry="fetchVulnerablePackages"
|
||||
/>
|
||||
|
||||
<Card v-else-if="vulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
:title="showOnlyBlocked ? 'No blocked packages' : 'No vulnerable packages'"
|
||||
description="Every cached package is clean."
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ErrorState v-else-if="error" variant="card" title="Could not load security findings" :message="error" @retry="load" />
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary
|
||||
v-if="everyBucketed.length > 0"
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
:counts="totalCounts"
|
||||
:package-counts="packageCounts"
|
||||
label="Vulnerabilities by severity. Select a severity to filter the packages."
|
||||
label="Findings by severity. Select a severity to filter the packages."
|
||||
:counts="severityTotals"
|
||||
:package-counts="severityPackages"
|
||||
/>
|
||||
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
|
||||
<p class="m-0 text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="selectedSeverities = []">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Card v-if="sortedVulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
:icon="faCircleCheck"
|
||||
title="No packages match the filter"
|
||||
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button variant="outline" @click="clearFilters">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Tabs v-model="tab">
|
||||
<TabsList aria-label="Security sections">
|
||||
<TabsTrigger v-for="t in TAB_DEFS" :key="t.value" :value="t.value">{{ t.label }} ({{ buckets[t.value].length }})</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">
|
||||
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{{ groupedPackages.length }} unique package{{ groupedPackages.length !== 1 ? 's' : '' }}, most critical first
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Accordion type="multiple" class="w-full">
|
||||
<AccordionItem
|
||||
v-for="group in groupedPackages"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
<AccordionTrigger :heading-level="3">
|
||||
<span class="flex w-full min-w-0 items-center justify-between gap-4">
|
||||
<span class="min-w-0 text-start">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} vulnerable version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
<TabsContent v-for="t in TAB_DEFS" :key="t.value" :value="t.value" class="pt-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">{{ t.label }}</CardTitle>
|
||||
<CardDescription>{{ t.description }}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="rowsFor(t.value).length === 0"
|
||||
:icon="faCircleCheck"
|
||||
:title="hasFilter ? 'No packages match the filter' : t.empty"
|
||||
:description="hasFilter ? `No package here has a ${filterSummary} vulnerability.` : undefined"
|
||||
>
|
||||
<template v-if="hasFilter" #action>
|
||||
<Button variant="outline" @click="selectedSeverities = []">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
<DataTable
|
||||
v-else
|
||||
:label="t.label"
|
||||
layout="cards"
|
||||
density="compact"
|
||||
row-clickable
|
||||
:page-size="PAGE_SIZE"
|
||||
:columns="columnsFor(t.value)"
|
||||
:rows="rowsFor(t.value)"
|
||||
@row-click="open"
|
||||
>
|
||||
<template #cell-name="{ row }">
|
||||
<RouterLink :to="packageRoute(row)" class="break-words font-medium text-foreground underline-offset-4 hover:underline">
|
||||
{{ row.name }}
|
||||
</RouterLink>
|
||||
</template>
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-findings="{ row }">
|
||||
<VulnerabilityBadge
|
||||
v-if="row.vulnerabilities"
|
||||
:scanned="row.vulnerabilities.scanned"
|
||||
:status="row.vulnerabilities.status"
|
||||
:counts="row.vulnerabilities.counts"
|
||||
:total="row.vulnerabilities.total"
|
||||
@click="open(row)"
|
||||
/>
|
||||
</template>
|
||||
<template #cell-bypass="{ row }">
|
||||
<span v-if="row.vulnerabilities?.bypass" class="block text-sm">
|
||||
{{ row.vulnerabilities.bypass.created_by }}
|
||||
<span class="block text-xs text-muted-foreground">
|
||||
expires <RelativeTime :datetime="row.vulnerabilities.bypass.expires_at" />
|
||||
</span>
|
||||
</span>
|
||||
<span class="flex shrink-0 items-center gap-4">
|
||||
<Badge variant="outline">{{ group.registry }}</Badge>
|
||||
<span class="whitespace-nowrap text-end tabular-nums">
|
||||
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<DataTable
|
||||
:label="`Vulnerable versions of ${group.name}`"
|
||||
layout="cards"
|
||||
row-clickable
|
||||
:columns="versionColumns"
|
||||
:rows="group.versions"
|
||||
@row-click="navigateToPackage"
|
||||
>
|
||||
<template #cell-vulnerabilities="{ row }">
|
||||
<VulnerabilityBadge
|
||||
v-if="row.vulnerabilities"
|
||||
:scanned="row.vulnerabilities.scanned"
|
||||
:status="row.vulnerabilities.status"
|
||||
:counts="row.vulnerabilities.counts"
|
||||
:total="row.vulnerabilities.total"
|
||||
:scannedAt="row.vulnerabilities.scannedAt"
|
||||
:isBlocked="row.vulnerabilities.isBlocked"
|
||||
@click="navigateToPackage(row)"
|
||||
/>
|
||||
</template>
|
||||
</DataTable>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
<template #cell-scanned="{ row }">
|
||||
<RelativeTime v-if="row.vulnerabilities?.scannedAt" :datetime="row.vulnerabilities.scannedAt" />
|
||||
</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
@@ -147,19 +111,40 @@ import {
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
RelativeTime,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import { displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { faCircleCheck, faRotateRight } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
import { verdictOf } from '@/lib/verdict'
|
||||
|
||||
type TabName = 'held' | 'allowed' | 'bypassed'
|
||||
|
||||
const TAB_DEFS: ReadonlyArray<{ value: TabName; label: string; description: string; empty: string }> = [
|
||||
{ value: 'held', label: 'Held', description: 'At or over the block policy. Clients get a 403 until the package is fixed or bypassed.', empty: 'Nothing is held' },
|
||||
{ value: 'allowed', label: 'Vulnerable but allowed', description: 'Findings exist, but none reach the block policy. Clients are served these.', empty: 'No package carries findings under the policy' },
|
||||
{ value: 'bypassed', label: 'Bypassed', description: 'An admin bypass lets these through despite their findings.', empty: 'No bypass is in effect' },
|
||||
]
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
const store = usePackageStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { packages, loading, error } = storeToRefs(store)
|
||||
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
const tab = ref<TabName>(TAB_DEFS.find((t) => t.value === route.query.tab)?.value ?? 'held')
|
||||
watch(tab, (value) => void router.replace({ query: { ...route.query, tab: value } }))
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
@@ -176,157 +161,79 @@ const selectedSeverities = computed<SeverityLevel[]>({
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0)
|
||||
const filterSummary = computed(() =>
|
||||
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
|
||||
)
|
||||
// With nothing to filter the tiles are hidden, so a leftover ?severity= must not claim a filter is on.
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0 && everyBucketed.value.length > 0)
|
||||
const filterSummary = computed(() => selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '))
|
||||
|
||||
function clearFilters() {
|
||||
selectedSeverities.value = []
|
||||
/** Packages with findings, by what the policy did. A package with no findings is not a security matter. */
|
||||
const buckets = computed<Record<TabName, Package[]>>(() => {
|
||||
const out: Record<TabName, Package[]> = { held: [], allowed: [], bypassed: [] }
|
||||
for (const pkg of packages.value) {
|
||||
const verdict = verdictOf(pkg)
|
||||
if (verdict === 'held') out.held.push(pkg)
|
||||
else if (verdict === 'bypassed') out.bypassed.push(pkg)
|
||||
else if (verdict === 'cleared' && (pkg.vulnerabilities?.total ?? 0) > 0) out.allowed.push(pkg)
|
||||
}
|
||||
return out
|
||||
})
|
||||
|
||||
function risk(pkg: Package): number[] {
|
||||
const c = pkg.vulnerabilities?.counts ?? NO_VULNERABILITIES
|
||||
return [c.critical, c.high, c.moderate, c.low]
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerablePackages = ref<Package[]>([])
|
||||
|
||||
// Check if we should filter to show only blocked packages
|
||||
const showOnlyBlocked = computed(() => route.path === '/blocked-packages')
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchVulnerablePackages()
|
||||
})
|
||||
|
||||
async function fetchVulnerablePackages() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
// The server drops clean packages; the toggles below narrow the rest without another request.
|
||||
await store.fetchPackages({ severity: SEVERITY_LEVELS })
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
return
|
||||
}
|
||||
vulnerablePackages.value = store.packages.filter(pkg => {
|
||||
const isVulnerable = pkg.vulnerabilities?.status === 'vulnerable'
|
||||
if (showOnlyBlocked.value) {
|
||||
return isVulnerable && pkg.vulnerabilities?.isBlocked === true
|
||||
}
|
||||
return isVulnerable
|
||||
})
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load vulnerable packages:', err)
|
||||
error.value = err.message || 'Failed to load vulnerable packages'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
// Worst first: more critical, then high, then moderate, then low.
|
||||
function byRisk(a: Package, b: Package): number {
|
||||
const [ra, rb] = [risk(a), risk(b)]
|
||||
for (let i = 0; i < ra.length; i++) if (ra[i] !== rb[i]) return rb[i] - ra[i]
|
||||
return 0
|
||||
}
|
||||
|
||||
// A package passes when it has at least one vulnerability of any selected severity.
|
||||
const filteredPackages = computed(() => {
|
||||
if (!hasFilter.value) return vulnerablePackages.value
|
||||
return vulnerablePackages.value.filter((pkg) =>
|
||||
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
|
||||
)
|
||||
function passesFilter(pkg: Package): boolean {
|
||||
if (!hasFilter.value) return true
|
||||
return selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0)
|
||||
}
|
||||
|
||||
function rowsFor(name: TabName): Package[] {
|
||||
return buckets.value[name].filter(passesFilter).sort(byRisk)
|
||||
}
|
||||
|
||||
const everyBucketed = computed(() => [...buckets.value.held, ...buckets.value.allowed, ...buckets.value.bypassed])
|
||||
|
||||
const severityTotals = computed<VulnerabilityCounts>(() => {
|
||||
const totals = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of everyBucketed.value) for (const level of SEVERITY_LEVELS) totals[level] += pkg.vulnerabilities?.counts?.[level] ?? 0
|
||||
return totals
|
||||
})
|
||||
|
||||
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
|
||||
const sortedVulnerablePackages = computed(() => {
|
||||
return [...filteredPackages.value].sort((a, b) => {
|
||||
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
// Compare critical count (descending)
|
||||
if (aVulns.critical !== bVulns.critical) {
|
||||
return bVulns.critical - aVulns.critical
|
||||
}
|
||||
|
||||
// Compare high count (descending)
|
||||
if (aVulns.high !== bVulns.high) {
|
||||
return bVulns.high - aVulns.high
|
||||
}
|
||||
|
||||
// Compare moderate count (descending)
|
||||
if (aVulns.moderate !== bVulns.moderate) {
|
||||
return bVulns.moderate - aVulns.moderate
|
||||
}
|
||||
|
||||
// Compare low count (descending)
|
||||
return bVulns.low - aVulns.low
|
||||
})
|
||||
const severityPackages = computed<VulnerabilityCounts>(() => {
|
||||
const totals = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of everyBucketed.value) for (const level of SEVERITY_LEVELS) if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) totals[level]++
|
||||
return totals
|
||||
})
|
||||
|
||||
// Group packages by name and registry, with versions sorted by risk
|
||||
const groupedPackages = computed(() => {
|
||||
const groups = new Map<string, {
|
||||
registry: string
|
||||
name: string
|
||||
versions: Package[]
|
||||
totalSize: number
|
||||
totalDownloads: number
|
||||
}>()
|
||||
|
||||
sortedVulnerablePackages.value.forEach((pkg) => {
|
||||
const key = `${pkg.registry}:${pkg.name}`
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, {
|
||||
registry: pkg.registry,
|
||||
name: pkg.name,
|
||||
versions: [],
|
||||
totalSize: 0,
|
||||
totalDownloads: 0,
|
||||
})
|
||||
}
|
||||
const group = groups.get(key)!
|
||||
group.versions.push(pkg)
|
||||
group.totalSize += pkg.size || 0
|
||||
group.totalDownloads += pkg.download_count || 0
|
||||
})
|
||||
|
||||
return Array.from(groups.values())
|
||||
})
|
||||
|
||||
// Packages holding at least one vulnerability of each severity, before any filter.
|
||||
const packageCounts = computed<VulnerabilityCounts>(() => {
|
||||
const counts = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of vulnerablePackages.value) {
|
||||
for (const level of SEVERITY_LEVELS) {
|
||||
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages, before any filter
|
||||
const totalCounts = computed(() =>
|
||||
vulnerablePackages.value.reduce(
|
||||
(sum, pkg) => {
|
||||
const counts = pkg.vulnerabilities?.counts ?? NO_VULNERABILITIES
|
||||
return {
|
||||
critical: sum.critical + counts.critical,
|
||||
high: sum.high + counts.high,
|
||||
moderate: sum.moderate + counts.moderate,
|
||||
low: sum.low + counts.low,
|
||||
}
|
||||
},
|
||||
{ ...NO_VULNERABILITIES },
|
||||
),
|
||||
)
|
||||
|
||||
const versionColumns: DataTableColumn<Package>[] = [
|
||||
{ key: 'version', header: 'Version', rowHeader: true, accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
|
||||
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
|
||||
{ key: 'cached_at', header: 'Cached', accessor: (pkg) => formatDate(pkg.cached_at) },
|
||||
{ key: 'vulnerabilities', header: 'Vulnerabilities', accessor: () => '' },
|
||||
const BASE_COLUMNS: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', sortable: true, rowHeader: true },
|
||||
{ key: 'version', header: 'Version', accessor: (p) => withVersionPrefix(displayVersion(p)) },
|
||||
{ key: 'registry', header: 'Registry' },
|
||||
{ key: 'findings', header: 'Findings', accessor: (p) => p.vulnerabilities?.total ?? 0 },
|
||||
]
|
||||
const SCANNED: DataTableColumn<Package> = { key: 'scanned', header: 'Last scanned', accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 }
|
||||
|
||||
function navigateToPackage(pkg: Package) {
|
||||
router.push(`/package/${pkg.registry}/${pkg.name}/${pkg.version}`)
|
||||
function columnsFor(name: TabName): DataTableColumn<Package>[] {
|
||||
if (name === 'held') return [...BASE_COLUMNS, { key: 'reason', header: 'Why', accessor: (p) => p.vulnerabilities?.reason ?? '' }, SCANNED]
|
||||
if (name === 'bypassed') return [...BASE_COLUMNS, { key: 'bypass', header: 'Bypass', accessor: (p) => p.vulnerabilities?.bypass?.created_by ?? '' }, SCANNED]
|
||||
return [...BASE_COLUMNS, SCANNED]
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
router.push('/stats')
|
||||
function open(pkg: Package) {
|
||||
void router.push(packageRoute(pkg))
|
||||
}
|
||||
|
||||
async function load() {
|
||||
// Unfiltered: a package held because its scan failed has no findings, and the severity filter would drop it.
|
||||
await store.fetchPackages()
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<StatGroup :columns="4" :aria-label="label">
|
||||
<StatGroup :columns="4" class="grid-cols-2! lg:grid-cols-4!" :aria-label="label">
|
||||
<template v-if="selectable">
|
||||
<KpiTile
|
||||
v-for="level in SEVERITY_LEVELS"
|
||||
@@ -10,7 +10,7 @@
|
||||
:label="formatSeverityName(level)"
|
||||
:value="counts[level]"
|
||||
:aria-pressed="isSelected(level)"
|
||||
:class="isSelected(level) && 'ring-2 ring-primary'"
|
||||
:class="['text-left', isSelected(level) && 'ring-2 ring-primary']"
|
||||
:data-severity="level"
|
||||
@click="toggle(level)"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="System" description="The policy the proxy applies, the scanners behind it, and the settings that shape the cache.">
|
||||
<template #actions>
|
||||
<Badge v-if="info" variant="outline" class="font-mono" data-testid="build-version">{{ info.version }}</Badge>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load(true)">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="!info && !error" variant="card" label="Loading system settings..." />
|
||||
<ErrorState v-else-if="!info" variant="card" title="Could not load system settings" :message="error ?? ''" @retry="load(true)" />
|
||||
|
||||
<template v-else>
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Policy</CardTitle>
|
||||
<CardDescription>What clears a package and what holds it.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="policy-list">
|
||||
<DescriptionItem term="Scanning">
|
||||
<StatusBadge :status="info.security.enabled ? 'on' : 'off'" :label="info.security.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Block policy">{{ describePolicy(info.security) }}</DescriptionItem>
|
||||
<DescriptionItem term="When a scan fails">
|
||||
{{ info.security.fail_closed ? 'Fail-closed. The package is held.' : 'Fail-open on scanner outage. The package is served and the scan retried.' }}
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Scan on download">{{ info.security.scan_on_download ? 'Yes' : 'No' }}</DescriptionItem>
|
||||
<DescriptionItem term="First download waits">up to {{ formatDuration(info.security.scan_wait_timeout) }} for its scan</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Rescans</CardTitle>
|
||||
<CardDescription>Cached packages are inspected again as advisories change.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="rescan-list">
|
||||
<DescriptionItem term="Interval">{{ duration(info.security.rescan.interval, 'Rescans are off') }}</DescriptionItem>
|
||||
<DescriptionItem term="Active window">{{ duration(info.security.rescan.active_window, 'Every cached package') }}</DescriptionItem>
|
||||
<DescriptionItem term="Parallel scans">{{ info.security.rescan.concurrency }}</DescriptionItem>
|
||||
<DescriptionItem term="Rescan on access">{{ info.security.rescan.on_access ? 'Yes. A stale hit is rescanned before it is served.' : 'No' }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Inspectors</CardTitle>
|
||||
<CardDescription>Health is probed at most every 30 seconds. A scanner that is off is not probed.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DataTable label="Scanners" layout="cards" density="compact" row-key="name" :columns="scannerColumns" :rows="info.security.scanners">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-state="{ row }">
|
||||
<StatusBadge :status="scannerState(row)" :label="STATE_LABELS[scannerState(row)]" :tones="STATE_TONES" />
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ row.version ? `v${row.version}` : 'Not reported' }}</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Cache</CardTitle>
|
||||
<CardDescription>Limits and where packages come from.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="cache-list">
|
||||
<DescriptionItem term="Size limit">{{ info.cache.max_size > 0 ? formatBytes(info.cache.max_size) : 'None' }}</DescriptionItem>
|
||||
<DescriptionItem term="Idle eviction">{{ duration(info.cache.idle_ttl, 'Off', 'Removed after ', ' without a request') }}</DescriptionItem>
|
||||
<DescriptionItem term="Default TTL">{{ duration(info.cache.default_ttl, 'None') }}</DescriptionItem>
|
||||
<DescriptionItem v-for="(host, registry) in info.upstreams" :key="registry" :term="`Upstream ${registry}`">{{ host || 'Not set' }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card data-testid="prewarming">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Pre-warming</CardTitle>
|
||||
<CardDescription>Fetches the most requested packages ahead of clients.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<DescriptionList :columns="1" divided>
|
||||
<DescriptionItem term="Status">
|
||||
<StatusBadge :status="info.prewarming.enabled ? 'on' : 'off'" :label="info.prewarming.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Interval">{{ duration(info.prewarming.interval, 'None') }}</DescriptionItem>
|
||||
<DescriptionItem term="Top packages">{{ info.prewarming.top_packages }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Button :icon-start="faRotateRight" :loading="triggering" :disabled="!info.prewarming.enabled" @click="trigger">Run a cycle now</Button>
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
{{ info.prewarming.enabled ? 'Needs the admin API key.' : 'Pre-warming is off in the configuration.' }}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a pre-warming cycle." @saved="trigger" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatusBadge,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import AdminKeyDialog from './parts/AdminKeyDialog.vue'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { formatBytes, formatDuration } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
import { describePolicy, scannerState, useSystem, type ScannerInfo } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
const adminKey = useAdminKey()
|
||||
const toasts = useToastStore()
|
||||
|
||||
const triggering = ref(false)
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
|
||||
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
|
||||
|
||||
const scannerColumns: DataTableColumn<ScannerInfo>[] = [
|
||||
{ key: 'name', header: 'Scanner', rowHeader: true },
|
||||
{ key: 'state', header: 'State', accessor: (s) => scannerState(s) },
|
||||
{ key: 'version', header: 'Version' },
|
||||
]
|
||||
|
||||
/** Seconds as words; zero means the feature is off, so `zero` explains that. */
|
||||
function duration(seconds: number, zero: string, before = '', after = ''): string {
|
||||
return seconds === 0 ? zero : `${before}${formatDuration(seconds)}${after}`
|
||||
}
|
||||
|
||||
async function trigger() {
|
||||
adminKey.load()
|
||||
if (!adminKey.key.value) {
|
||||
showKeyDialog.value = true
|
||||
return
|
||||
}
|
||||
triggering.value = true
|
||||
try {
|
||||
await axios.post('/api/admin/prewarming/trigger', null, { headers: adminKey.headers.value })
|
||||
toasts.success('Pre-warming started', 'The cycle runs in the background.')
|
||||
} catch (err) {
|
||||
const status = (err as { response?: { status?: number } }).response?.status
|
||||
if (status === 401 || status === 403) {
|
||||
adminKey.clear()
|
||||
toasts.error('Admin key refused', 'Enter a key with the admin role.')
|
||||
} else {
|
||||
toasts.error('Could not start pre-warming', err instanceof Error ? err.message : 'Request failed')
|
||||
}
|
||||
} finally {
|
||||
triggering.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void load(true))
|
||||
</script>
|
||||
@@ -0,0 +1,46 @@
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="(value: boolean) => emit('update:open', value)">
|
||||
<DialogContent size="sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Admin API key</DialogTitle>
|
||||
<DialogDescription>{{ description }}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form class="flex flex-col gap-4" @submit.prevent="submit">
|
||||
<Field label="API key" required>
|
||||
<Input v-model="draft" type="password" autocomplete="off" />
|
||||
</Field>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="emit('update:open', false)">Cancel</Button>
|
||||
<Button type="submit" :disabled="draft.trim() === ''">Continue</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Field, Input } from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
|
||||
const props = defineProps<{ open: boolean; description: string }>()
|
||||
const emit = defineEmits<{ 'update:open': [open: boolean]; saved: [] }>()
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const draft = ref('')
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) draft.value = ''
|
||||
},
|
||||
)
|
||||
|
||||
function submit() {
|
||||
const value = draft.value.trim()
|
||||
if (!value) return
|
||||
adminKey.save(value)
|
||||
emit('update:open', false)
|
||||
emit('saved')
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,119 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<section v-if="applied" class="flex flex-col gap-3" aria-labelledby="bypass-applied-heading">
|
||||
<h3 id="bypass-applied-heading" class="m-0 text-sm font-semibold">Bypass in effect</h3>
|
||||
<DescriptionList :columns="2" divided data-testid="applied-bypass">
|
||||
<DescriptionItem term="Scope">{{ applied.type === 'package' ? 'Whole package' : 'One advisory' }}</DescriptionItem>
|
||||
<DescriptionItem term="Target"><InlineCode>{{ applied.target }}</InlineCode></DescriptionItem>
|
||||
<DescriptionItem term="Reason">{{ applied.reason }}</DescriptionItem>
|
||||
<DescriptionItem term="Created by">{{ applied.created_by }}</DescriptionItem>
|
||||
<DescriptionItem term="Created"><RelativeTime :datetime="applied.created_at" /></DescriptionItem>
|
||||
<DescriptionItem term="Expires">{{ formatDate(applied.expires_at) }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</section>
|
||||
<p v-else class="m-0 text-sm text-muted-foreground">No bypass applies to this package.</p>
|
||||
|
||||
<section class="flex flex-col gap-3" aria-labelledby="bypass-list-heading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 id="bypass-list-heading" class="m-0 text-sm font-semibold">Bypasses that cover this package</h3>
|
||||
<Button :as="RouterLink" :to="addRoute" variant="outline" size="sm" :icon-start="faPlus">Add a bypass</Button>
|
||||
</div>
|
||||
<Callout v-if="!adminKey.key.value" type="note" size="sm" title="Admin key needed">
|
||||
Listing bypasses needs the admin API key. Enter it on the
|
||||
<Link :as="RouterLink" to="/admin/bypasses">Bypasses page</Link>.
|
||||
</Callout>
|
||||
<LoadingState v-else-if="loading" layout="inline" label="Loading bypasses..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load bypasses" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="covering.length === 0" size="sm" title="No bypass covers this package" description="Add one to serve it despite the findings." />
|
||||
<DataTable v-else label="Bypasses covering this package" layout="cards" density="compact" :columns="columns" :rows="covering">
|
||||
<template #cell-status="{ row }">
|
||||
<StatusBadge :status="statusOf(row)" :label="STATUS_LABELS[statusOf(row)]" :tones="STATUS_TONES" />
|
||||
</template>
|
||||
<template #cell-target="{ row }"><InlineCode>{{ row.target }}</InlineCode></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
Callout,
|
||||
DataTable,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
InlineCode,
|
||||
Link,
|
||||
LoadingState,
|
||||
RelativeTime,
|
||||
StatusBadge,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { bypassesFor, isExpired, type Bypass } from '@/lib/bypass'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { faPlus } from '@/lib/icons'
|
||||
import type { AppliedBypass } from '@/stores/packages'
|
||||
|
||||
const props = defineProps<{
|
||||
applied: AppliedBypass | null
|
||||
registry: string
|
||||
name: string
|
||||
version: string
|
||||
releaseVersion?: string
|
||||
}>()
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const all = ref<Bypass[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
type BypassStatus = 'active' | 'expired' | 'inactive'
|
||||
const STATUS_LABELS: Record<BypassStatus, string> = { active: 'Active', expired: 'Expired', inactive: 'Inactive' }
|
||||
const STATUS_TONES = { active: 'success', expired: 'neutral', inactive: 'neutral' } as const
|
||||
|
||||
function statusOf(b: Bypass): BypassStatus {
|
||||
if (isExpired(b.expires_at)) return 'expired'
|
||||
return b.active ? 'active' : 'inactive'
|
||||
}
|
||||
|
||||
const covering = computed(() =>
|
||||
bypassesFor(all.value, { registry: props.registry, name: props.name, version: props.version, releaseVersion: props.releaseVersion }),
|
||||
)
|
||||
|
||||
const addRoute = computed(() => ({
|
||||
path: '/admin/bypasses',
|
||||
query: { type: 'package', target: `${props.registry}/${props.name}@${props.releaseVersion || props.version}` },
|
||||
}))
|
||||
|
||||
const columns: DataTableColumn<Bypass>[] = [
|
||||
{ key: 'target', header: 'Target', rowHeader: true },
|
||||
{ key: 'type', header: 'Type' },
|
||||
{ key: 'status', header: 'Status', accessor: (b) => statusOf(b) },
|
||||
{ key: 'reason', header: 'Reason' },
|
||||
{ key: 'created_by', header: 'Created by' },
|
||||
{ key: 'expires_at', header: 'Expires', accessor: (b) => formatDate(b.expires_at) },
|
||||
]
|
||||
|
||||
async function load() {
|
||||
if (!adminKey.key.value) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<{ bypasses: Bypass[] }>('/api/admin/bypasses?include_expired=true', { headers: adminKey.headers.value })
|
||||
all.value = response.data.bypasses ?? []
|
||||
} catch (err) {
|
||||
const status = (err as { response?: { status?: number } }).response?.status
|
||||
error.value = status === 401 || status === 403 ? 'The admin key was refused.' : err instanceof Error ? err.message : 'Failed to load bypasses'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<Card class="min-w-0" data-testid="cache-capacity">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Cache capacity</CardTitle>
|
||||
<CardDescription>Disk the cache holds, by registry.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<StatBar
|
||||
v-if="maxSize > 0"
|
||||
label="Used"
|
||||
tone="auto"
|
||||
:value="used"
|
||||
:max="maxSize"
|
||||
:value-text="`${formatBytes(used)} of ${formatBytes(maxSize)}`"
|
||||
/>
|
||||
<p v-else class="m-0 text-sm text-muted-foreground">
|
||||
<span class="font-medium text-foreground">{{ formatBytes(used) }}</span> used. No size limit is set.
|
||||
</p>
|
||||
|
||||
<EmptyState v-if="rows.length === 0" size="sm" title="Nothing cached" description="Each registry appears here after its first download." />
|
||||
<template v-else>
|
||||
<DonutChart
|
||||
:data="donut"
|
||||
:value-formatter="formatBytes"
|
||||
center-text="cached"
|
||||
label="Cache size by registry"
|
||||
layout="stacked"
|
||||
size="md"
|
||||
/>
|
||||
<DataTable label="Cache by registry" layout="cards" density="compact" :columns="columns" :rows="rows" row-key="registry">
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
</DataTable>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
Badge,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
DonutChart,
|
||||
EmptyState,
|
||||
StatBar,
|
||||
type DataTableColumn,
|
||||
type DonutDatum,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, formatNumber } from '@/lib/format'
|
||||
|
||||
export interface RegistryUsage {
|
||||
registry: string
|
||||
count: number
|
||||
size: number
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
used: number
|
||||
maxSize: number
|
||||
registries: Record<string, { count?: number; size?: number; downloads?: number }>
|
||||
}>()
|
||||
|
||||
const rows = computed<RegistryUsage[]>(() =>
|
||||
Object.entries(props.registries)
|
||||
.map(([registry, r]) => ({ registry, count: r.count ?? 0, size: r.size ?? 0, downloads: r.downloads ?? 0 }))
|
||||
.sort((a, b) => b.size - a.size),
|
||||
)
|
||||
const donut = computed<DonutDatum[]>(() => rows.value.map((r) => ({ label: r.registry, value: r.size })))
|
||||
|
||||
const columns: DataTableColumn<RegistryUsage>[] = [
|
||||
{ key: 'registry', header: 'Registry', rowHeader: true },
|
||||
{ key: 'count', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.count) },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (r) => formatBytes(r.size) },
|
||||
]
|
||||
</script>
|
||||
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<Card class="min-w-0" data-testid="download-trend">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Downloads</CardTitle>
|
||||
<CardDescription>Packages served to clients, in UTC.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<div class="flex sm:justify-end">
|
||||
<SegmentedControl v-model="period" :options="DOWNLOAD_PERIODS" aria-label="Download period" />
|
||||
</div>
|
||||
<LoadingState v-if="loading && points.length === 0" layout="inline" label="Loading downloads..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load downloads" :message="error" @retry="load" />
|
||||
<LineChart
|
||||
v-else
|
||||
variant="area"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="[{ name: 'Downloads', data: values, tone: 'primary' }]"
|
||||
:label="`Downloads over the last ${periodLabel}, ${total} in total`"
|
||||
empty-text="No downloads in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
ErrorState,
|
||||
LineChart,
|
||||
LoadingState,
|
||||
SegmentedControl,
|
||||
} from '@perfect-design/ui'
|
||||
import { DOWNLOAD_PERIODS, bucketLabel, type DownloadPeriod, type TimeSeries } from '@/lib/timeseries'
|
||||
|
||||
const period = ref<DownloadPeriod>('1day')
|
||||
const data = ref<TimeSeries | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
let request = 0
|
||||
|
||||
const points = computed(() => data.value?.data_points ?? [])
|
||||
const values = computed(() => points.value.map((p) => p.value))
|
||||
const labels = computed(() => points.value.map((p) => bucketLabel(period.value, p.timestamp)))
|
||||
const total = computed(() => values.value.reduce((sum, v) => sum + v, 0))
|
||||
const periodLabel = computed(() => DOWNLOAD_PERIODS.find((p) => p.value === period.value)?.label ?? '')
|
||||
|
||||
async function load() {
|
||||
const current = ++request
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<TimeSeries>(`/api/stats/timeseries?period=${period.value}`)
|
||||
if (current === request) data.value = response.data
|
||||
} catch (err) {
|
||||
if (current !== request) return
|
||||
data.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load downloads'
|
||||
} finally {
|
||||
if (current === request) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(period, load)
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,82 @@
|
||||
<template>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading download history..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load download history" :message="error" @retry="load" />
|
||||
<EmptyState
|
||||
v-else-if="!stats"
|
||||
size="sm"
|
||||
:icon="faDownload"
|
||||
title="No download history"
|
||||
description="The server records downloads in memory, so history starts at its last restart."
|
||||
/>
|
||||
<div v-else class="flex flex-col gap-4">
|
||||
<StatGroup :columns="3" aria-label="Downloads of this package">
|
||||
<KpiTile label="This version" :value="downloadCount" hint="Times served from the cache" />
|
||||
<KpiTile
|
||||
:label="isGo ? 'Module zip' : 'All versions'"
|
||||
:value="stats.TotalDownloads"
|
||||
:hint="isGo ? 'Downloads of this version' : `${stats.UniqueVersions} version${stats.UniqueVersions === 1 ? '' : 's'} seen`"
|
||||
/>
|
||||
<KpiTile label="Data served" :value="formatBytes(stats.BytesServed)" :hint="isGo ? 'This version' : 'Across all versions'" />
|
||||
</StatGroup>
|
||||
<DescriptionList :columns="2" divided>
|
||||
<DescriptionItem term="First seen"><RelativeTime :datetime="stats.FirstSeen" /></DescriptionItem>
|
||||
<DescriptionItem term="Last download"><RelativeTime :datetime="stats.LastDownload" /></DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
RelativeTime,
|
||||
StatGroup,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, modulePath } from '@/lib/format'
|
||||
import { faDownload } from '@/lib/icons'
|
||||
|
||||
/** The analytics engine serialises Go field names. */
|
||||
interface PackageAnalytics {
|
||||
TotalDownloads: number
|
||||
UniqueVersions: number
|
||||
BytesServed: number
|
||||
FirstSeen: string
|
||||
LastDownload: string
|
||||
}
|
||||
|
||||
const props = defineProps<{ registry: string; name: string; version: string; downloadCount: number }>()
|
||||
|
||||
const isGo = computed(() => props.registry === 'go')
|
||||
|
||||
const stats = ref<PackageAnalytics | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Go analytics are keyed by cache file, one per version.
|
||||
const analyticsName = computed(() => (isGo.value ? `${modulePath(props.name)}/@v/${props.version}.zip` : props.name))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<{ package: PackageAnalytics }>(
|
||||
`/api/analytics/package/${props.registry}/${analyticsName.value}`,
|
||||
)
|
||||
stats.value = response.data.package
|
||||
} catch (err) {
|
||||
stats.value = null
|
||||
const status = (err as { response?: { status?: number } }).response?.status
|
||||
if (status !== 404) error.value = err instanceof Error ? err.message : 'Failed to load download history'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
Each scanner reports its own findings before they are merged. A finding several scanners agree on counts once in the verdict.
|
||||
</p>
|
||||
<DataTable label="Findings by scanner and severity" layout="cards" density="compact" row-key="name" :columns="columns" :rows="rows">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-status="{ row }">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge :status="row.status" :label="INSPECTOR_STATUS_LABELS[row.status]" :tones="STATUS_TONES" />
|
||||
<StatusBadge v-if="row.health === 'down'" status="down" label="Unavailable now" :tones="{ down: 'danger' }" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ row.version ? `v${row.version}` : 'Not reported' }}</template>
|
||||
</DataTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { DataTable, StatusBadge, type DataTableColumn } from '@perfect-design/ui'
|
||||
import { INSPECTOR_STATUS_LABELS, inspectorRows, type InspectorRow, type ScannerResult } from '@/lib/inspectors'
|
||||
import type { ScannerInfo } from '@/lib/system'
|
||||
|
||||
const props = defineProps<{
|
||||
registry: string
|
||||
results: readonly ScannerResult[]
|
||||
configured: readonly ScannerInfo[]
|
||||
}>()
|
||||
|
||||
const STATUS_TONES = { reported: 'success', 'no-result': 'warning', 'not-applicable': 'neutral', off: 'neutral' } as const
|
||||
|
||||
const rows = computed(() => inspectorRows(props.registry, props.results, props.configured))
|
||||
|
||||
function count(row: InspectorRow, level: 'critical' | 'high' | 'moderate' | 'low'): string {
|
||||
return row.counts ? String(row.counts[level]) : '–'
|
||||
}
|
||||
|
||||
const columns: DataTableColumn<InspectorRow>[] = [
|
||||
{ key: 'name', header: 'Scanner', rowHeader: true },
|
||||
{ key: 'critical', header: 'Critical', numeric: true, accessor: (r) => count(r, 'critical') },
|
||||
{ key: 'high', header: 'High', numeric: true, accessor: (r) => count(r, 'high') },
|
||||
{ key: 'moderate', header: 'Moderate', numeric: true, accessor: (r) => count(r, 'moderate') },
|
||||
{ key: 'low', header: 'Low', numeric: true, accessor: (r) => count(r, 'low') },
|
||||
{ key: 'status', header: 'Status' },
|
||||
{ key: 'version', header: 'Version' },
|
||||
]
|
||||
</script>
|
||||
@@ -0,0 +1,67 @@
|
||||
<template>
|
||||
<Sheet :open="pkg !== null" @update:open="(open: boolean) => !open && emit('close')">
|
||||
<SheetContent side="right" size="md">
|
||||
<template v-if="pkg">
|
||||
<SheetHeader>
|
||||
<SheetTitle class="break-words">{{ pkg.name }}</SheetTitle>
|
||||
<SheetDescription>{{ withVersionPrefix(displayVersion(pkg)) }} from {{ pkg.registry }}</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div class="flex flex-col gap-5 px-4 pb-4">
|
||||
<div class="flex flex-col gap-2">
|
||||
<VerdictBadge :verdict="verdict" class="self-start" />
|
||||
<p v-if="explanation" class="m-0 text-sm text-muted-foreground" data-testid="quick-view-reason">{{ explanation }}</p>
|
||||
</div>
|
||||
|
||||
<SeveritySummary v-if="pkg.vulnerabilities?.counts" class="grid-cols-2! lg:grid-cols-2!" :counts="pkg.vulnerabilities.counts" label="Findings by severity" />
|
||||
|
||||
<DescriptionList :columns="1" divided>
|
||||
<DescriptionItem term="Size">{{ formatBytes(pkg.size) }}</DescriptionItem>
|
||||
<DescriptionItem term="Downloads">{{ formatNumber(pkg.download_count) }}</DescriptionItem>
|
||||
<DescriptionItem term="Cached"><RelativeTime :datetime="pkg.cached_at" /></DescriptionItem>
|
||||
<DescriptionItem term="Last accessed"><RelativeTime :datetime="pkg.last_accessed" /></DescriptionItem>
|
||||
<DescriptionItem term="Last scanned">
|
||||
<RelativeTime v-if="pkg.vulnerabilities?.scannedAt" :datetime="pkg.vulnerabilities.scannedAt" />
|
||||
<template v-else>Never</template>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
|
||||
<SheetFooter>
|
||||
<Button :as="RouterLink" :to="packageRoute(pkg)" :icon-end="faArrowRight">Open full page</Button>
|
||||
<Button variant="outline" :icon-start="faTrash" @click="emit('delete', pkg)">Remove from cache</Button>
|
||||
</SheetFooter>
|
||||
</template>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
RelativeTime,
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from '../SeveritySummary.vue'
|
||||
import VerdictBadge from './VerdictBadge.vue'
|
||||
import type { Package } from '@/stores/packages'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { faArrowRight, faTrash } from '@/lib/icons'
|
||||
import { VERDICT_MEANINGS, verdictOf } from '@/lib/verdict'
|
||||
|
||||
const props = defineProps<{ pkg: Package | null }>()
|
||||
const emit = defineEmits<{ close: []; delete: [pkg: Package] }>()
|
||||
|
||||
const verdict = computed(() => (props.pkg ? verdictOf(props.pkg) : 'unscanned'))
|
||||
const explanation = computed(() => props.pkg?.vulnerabilities?.reason || VERDICT_MEANINGS[verdict.value])
|
||||
</script>
|
||||
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<p class="m-0 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground" data-testid="policy-line">
|
||||
<template v-if="info">
|
||||
<span class="font-medium text-foreground">Policy</span>
|
||||
<span>{{ describePolicy(info.security) }}</span>
|
||||
<span v-if="info.security.enabled">{{ info.security.fail_closed ? 'Fail-closed' : 'Fail-open on scanner outage' }}.</span>
|
||||
<span v-if="info.security.enabled">{{ enabledScanners }} of {{ info.security.scanners.length }} scanners on.</span>
|
||||
<Link :as="RouterLink" to="/admin/system">System settings</Link>
|
||||
</template>
|
||||
<span v-else-if="error">Policy unavailable: {{ error }}</span>
|
||||
<span v-else>Loading policy...</span>
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import { Link } from '@perfect-design/ui'
|
||||
import { describePolicy, useSystem } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
const enabledScanners = computed(() => info.value?.security.scanners.filter((s) => s.enabled).length ?? 0)
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<Card data-testid="scanner-health">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Inspectors</CardTitle>
|
||||
<CardDescription>The scanners that examine each package. Health is probed every 30 seconds.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ErrorState v-if="error && !info" variant="inline" title="Could not load scanners" :message="error" @retry="load(true)" />
|
||||
<LoadingState v-else-if="!info" layout="inline" label="Loading scanners..." />
|
||||
<EmptyState
|
||||
v-else-if="!info.security.enabled"
|
||||
size="sm"
|
||||
title="Scanning is off"
|
||||
description="Packages are served without inspection."
|
||||
/>
|
||||
<ul v-else class="m-0 grid list-none grid-cols-1 gap-2 p-0 sm:grid-cols-2 xl:grid-cols-3">
|
||||
<li
|
||||
v-for="scanner in info.security.scanners"
|
||||
:key="scanner.name"
|
||||
class="flex items-center justify-between gap-3 rounded-md border px-3 py-2"
|
||||
:data-scanner="scanner.name"
|
||||
>
|
||||
<span class="min-w-0">
|
||||
<span class="block truncate text-sm font-medium">{{ scanner.name }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ scanner.version ? `v${scanner.version}` : 'version not reported' }}</span>
|
||||
</span>
|
||||
<StatusBadge :status="scannerState(scanner)" :label="STATE_LABELS[scannerState(scanner)]" :tones="STATE_TONES" />
|
||||
</li>
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
StatusBadge,
|
||||
} from '@perfect-design/ui'
|
||||
import { scannerState, useSystem } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
|
||||
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
|
||||
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
@@ -0,0 +1,94 @@
|
||||
<template>
|
||||
<div class="grid gap-6 lg:grid-cols-2" data-testid="top-packages">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Most requested</CardTitle>
|
||||
<CardDescription>Total downloads since the server started.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading top packages..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load top packages" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="top.length === 0" size="sm" title="No downloads yet" description="Rankings appear after the first download." />
|
||||
<Leaderboard v-else label="Most requested packages" bars :entries="top" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Downloads', delta: 'Change' }" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Trending</CardTitle>
|
||||
<CardDescription>Downloads in the last 7 days.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading trending packages..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load trending packages" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="trending.length === 0" size="sm" title="Nothing trending" description="No package was downloaded in the last 7 days." />
|
||||
<Leaderboard v-else label="Trending packages" bars :entries="trending" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Last 7 days', delta: 'Change' }" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Leaderboard,
|
||||
LoadingState,
|
||||
type LeaderboardEntry,
|
||||
} from '@perfect-design/ui'
|
||||
import { modulePath } from '@/lib/format'
|
||||
|
||||
/** The analytics engine serialises Go field names. */
|
||||
interface PopularPackage {
|
||||
Registry: string
|
||||
Name: string
|
||||
Downloads: number
|
||||
RecentDownloads: number
|
||||
}
|
||||
|
||||
const LIMIT = 8
|
||||
const popular = ref<PopularPackage[]>([])
|
||||
const recent = ref<PopularPackage[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Rows with equal registry and module path (a Go module's .zip, .mod and .info) are one package.
|
||||
function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number): LeaderboardEntry[] {
|
||||
const totals = new Map<string, LeaderboardEntry>()
|
||||
for (const row of rows) {
|
||||
const id = `${row.Registry}/${modulePath(row.Name)}`
|
||||
const existing = totals.get(id)
|
||||
if (existing) existing.value += pick(row)
|
||||
else totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row) })
|
||||
}
|
||||
return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT)
|
||||
}
|
||||
|
||||
const top = computed(() => entries(popular.value, (p) => p.Downloads))
|
||||
const trending = computed(() => entries(recent.value, (p) => p.RecentDownloads))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const [topRes, trendRes] = await Promise.all([
|
||||
axios.get<{ packages: PopularPackage[] }>('/api/analytics/top?limit=50'),
|
||||
axios.get<{ packages: PopularPackage[] }>('/api/analytics/trending?limit=50'),
|
||||
])
|
||||
popular.value = topRes.data.packages ?? []
|
||||
recent.value = trendRes.data.packages ?? []
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load package rankings'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,12 @@
|
||||
<template>
|
||||
<StatusBadge :status="verdict" :label="VERDICT_LABELS[verdict]" :tones="TONES" :title="VERDICT_MEANINGS[verdict]" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { StatusBadge } from '@perfect-design/ui'
|
||||
import { VERDICT_LABELS, VERDICT_MEANINGS, VERDICT_TONES, type Verdict } from '@/lib/verdict'
|
||||
|
||||
defineProps<{ verdict: Verdict }>()
|
||||
|
||||
const TONES = VERDICT_TONES
|
||||
</script>
|
||||
@@ -0,0 +1,113 @@
|
||||
<template>
|
||||
<Table label="Detected vulnerabilities" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Severity</TableHead>
|
||||
<TableHead>Advisory</TableHead>
|
||||
<TableHead>Summary</TableHead>
|
||||
<TableHead>Fixed in</TableHead>
|
||||
<TableHead>Found by</TableHead>
|
||||
<TableHead align="center">Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<template v-for="vuln in sorted" :key="vuln.id">
|
||||
<TableRow class="cursor-pointer" :selected="isOpen(vuln.id)" @click="toggle(vuln.id)">
|
||||
<TableCell label="Severity">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge :status="vuln.severity" :tones="SEVERITY_TONES" :label="formatSeverityName(vuln.severity)" />
|
||||
<StatusBadge v-if="vuln.bypassed" status="bypassed" label="Bypassed" :tones="{ bypassed: 'info' }" />
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Advisory" class="font-mono font-medium">{{ vuln.id }}</TableCell>
|
||||
<TableCell label="Summary">
|
||||
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
|
||||
</TableCell>
|
||||
<TableCell label="Fixed in">
|
||||
<span v-if="vuln.fixed_in">{{ withVersionPrefix(vuln.fixed_in) }}</span>
|
||||
<span v-else class="text-muted-foreground">No fix yet</span>
|
||||
</TableCell>
|
||||
<TableCell label="Found by">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<Badge v-for="scanner in vuln.detected_by ?? []" :key="scanner" variant="secondary">{{ scanner }}</Badge>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Details" align="center">
|
||||
<IconButton
|
||||
size="icon-sm"
|
||||
:icon="isOpen(vuln.id) ? faChevronUp : faChevronDown"
|
||||
:label="`${isOpen(vuln.id) ? 'Hide' : 'Show'} details for ${vuln.id}`"
|
||||
:aria-expanded="isOpen(vuln.id)"
|
||||
@click.stop="toggle(vuln.id)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
<TableRow v-if="isOpen(vuln.id)" :hoverable="false">
|
||||
<TableCell :colspan="6">
|
||||
<div class="flex flex-col gap-4 py-2">
|
||||
<section v-if="vuln.description">
|
||||
<h3 class="mb-2 text-sm font-semibold">Description</h3>
|
||||
<Markdown :source="vuln.description" :heading-offset="3" />
|
||||
</section>
|
||||
|
||||
<Callout v-if="vuln.bypassed && vuln.bypass" type="note" title="Bypass active" size="sm">
|
||||
{{ vuln.bypass.reason }}. Created by {{ vuln.bypass.created_by }}, expires {{ formatDate(vuln.bypass.expires_at) }}.
|
||||
</Callout>
|
||||
|
||||
<Callout v-if="vuln.fixed_in" type="tip" title="Fix available" size="sm">
|
||||
Upgrade to <strong>{{ withVersionPrefix(vuln.fixed_in) }}</strong> or later.
|
||||
</Callout>
|
||||
|
||||
<section v-if="vuln.references && vuln.references.length > 0">
|
||||
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
|
||||
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li v-for="ref in vuln.references" :key="ref" class="break-all">
|
||||
<Link :href="ref" external>{{ ref }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import {
|
||||
Badge,
|
||||
Callout,
|
||||
IconButton,
|
||||
Link,
|
||||
Markdown,
|
||||
StatusBadge,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import type { VulnerabilityEntry } from '@/lib/report'
|
||||
import { faChevronDown, faChevronUp } from '@/lib/icons'
|
||||
import { SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
|
||||
|
||||
const props = defineProps<{ vulnerabilities: readonly VulnerabilityEntry[] }>()
|
||||
|
||||
const open = ref(new Set<string>())
|
||||
const sorted = computed(() => [...props.vulnerabilities].sort((a, b) => severityRank(b.severity) - severityRank(a.severity)))
|
||||
|
||||
function isOpen(id: string): boolean {
|
||||
return open.value.has(id)
|
||||
}
|
||||
|
||||
function toggle(id: string) {
|
||||
const next = new Set(open.value)
|
||||
if (!next.delete(id)) next.add(id)
|
||||
open.value = next
|
||||
}
|
||||
</script>
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
faBoxesStacked,
|
||||
faChartColumn,
|
||||
faChartPie,
|
||||
faGear,
|
||||
faShieldHalved,
|
||||
faTriangleExclamation,
|
||||
} from '@/lib/icons'
|
||||
@@ -17,11 +18,17 @@ defineProps<{ readonly sheet?: boolean }>()
|
||||
const GROUPS: SidebarNavGroup[] = [
|
||||
{
|
||||
items: [
|
||||
{ label: 'Dashboard', to: '/', icon: faChartPie },
|
||||
{ label: 'Overview', to: '/', icon: faChartPie },
|
||||
{ label: 'Packages', to: '/packages', icon: faBoxesStacked },
|
||||
{ label: 'Vulnerable', to: '/vulnerable-packages', icon: faTriangleExclamation },
|
||||
{ label: 'Security', to: '/security', icon: faTriangleExclamation },
|
||||
{ label: 'Insights', to: '/stats', icon: faChartColumn },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Admin',
|
||||
items: [
|
||||
{ label: 'Bypasses', to: '/admin/bypasses', icon: faShieldHalved },
|
||||
{ label: 'Stats', to: '/stats', icon: faChartColumn },
|
||||
{ label: 'System', to: '/admin/system', icon: faGear },
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -29,9 +36,11 @@ const GROUPS: SidebarNavGroup[] = [
|
||||
const SECTION_PREFIXES: ReadonlyArray<readonly [string, string]> = [
|
||||
['/packages', '/packages'],
|
||||
['/package/', '/packages'],
|
||||
['/vulnerable-packages', '/vulnerable-packages'],
|
||||
['/blocked-packages', '/vulnerable-packages'],
|
||||
['/security', '/security'],
|
||||
['/vulnerable-packages', '/security'],
|
||||
['/blocked-packages', '/security'],
|
||||
['/admin/bypasses', '/admin/bypasses'],
|
||||
['/admin/system', '/admin/system'],
|
||||
['/stats', '/stats'],
|
||||
]
|
||||
|
||||
|
||||
@@ -3,12 +3,14 @@ import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import App from '@/App.vue'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import Overview from './Overview.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import Security from './Security.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Stats from './Stats.vue'
|
||||
import Insights from './Insights.vue'
|
||||
import System from './System.vue'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
@@ -21,20 +23,21 @@ const FAILURE = Object.assign(new Error('Request failed with status code 502'),
|
||||
|
||||
// What each view must not say when the request failed: an empty state would tell the operator there is nothing to see.
|
||||
const EMPTY_TEXT: Record<string, string> = {
|
||||
Dashboard: 'No packages cached yet',
|
||||
Overview: 'Quiet at the desk',
|
||||
PackageList: 'No packages cached yet',
|
||||
VulnerablePackages: 'No vulnerable packages',
|
||||
Stats: 'No registries reported',
|
||||
Security: 'Nothing is held',
|
||||
Insights: 'No registry data yet',
|
||||
BypassManagementPanel: 'No bypasses found',
|
||||
}
|
||||
|
||||
const CASES: Array<[string, Parameters<typeof mountStrict>[0], string]> = [
|
||||
['Dashboard', Dashboard, '/'],
|
||||
['Overview', Overview, '/'],
|
||||
['PackageList', PackageList, '/packages'],
|
||||
['PackageDetails', PackageDetails, '/package/npm/left-pad/1.3.0'],
|
||||
['VulnerablePackages', VulnerablePackages, '/vulnerable-packages'],
|
||||
['Security', Security, '/security'],
|
||||
['BypassManagementPanel', BypassManagementPanel, '/admin/bypasses'],
|
||||
['Stats', Stats, '/stats'],
|
||||
['Insights', Insights, '/stats'],
|
||||
['System', System, '/admin/system'],
|
||||
]
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
@@ -42,6 +45,7 @@ let restore: (() => void) | undefined
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockRejectedValue(FAILURE)
|
||||
localStorage.setItem('admin_api_key', 'test-key')
|
||||
})
|
||||
@@ -73,16 +77,16 @@ describe('an API failure renders ErrorState, never an empty state', () => {
|
||||
})
|
||||
|
||||
it('retry fetches again and clears the error when the backend is back', async () => {
|
||||
const router = await createTestRouter('/vulnerable-packages')
|
||||
const router = await createTestRouter('/security')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
const mounted = await mountStrict(Security, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
await mounted.wrapper.find('[data-slot="error-state"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(mounted.wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(mounted.wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(mounted.wrapper.text()).toContain('Nothing is held')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -102,6 +106,6 @@ describe('unknown routes', () => {
|
||||
expect(main.find('h1').text()).toBe('Page not found')
|
||||
expect(main.find('[data-slot="empty-state"]').text()).toContain('/vulnerable')
|
||||
const link = main.find('a[href="/"]')
|
||||
expect(link.text()).toMatch(/dashboard/i)
|
||||
expect(link.text()).toMatch(/overview|dashboard/i)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,16 +3,29 @@ import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import App from '@/App.vue'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import Overview from './Overview.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import Security from './Security.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Stats from './Stats.vue'
|
||||
import Insights from './Insights.vue'
|
||||
import System from './System.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { usePackageStore } from '@/stores/packages'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import {
|
||||
BYPASSES,
|
||||
PACKAGES,
|
||||
PACKAGE_ANALYTICS,
|
||||
REGISTRIES,
|
||||
STATS,
|
||||
SYSTEM,
|
||||
TIMESERIES,
|
||||
TOP_PACKAGES,
|
||||
TREND,
|
||||
VULNERABILITY_REPORT,
|
||||
} from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
@@ -21,6 +34,9 @@ vi.mock('axios')
|
||||
const API_KEY_STORAGE = 'admin_api_key'
|
||||
|
||||
function respond(url: string) {
|
||||
if (url.startsWith('/api/system')) return { data: SYSTEM }
|
||||
if (url.startsWith('/api/analytics/package/')) return { data: PACKAGE_ANALYTICS }
|
||||
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES }
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND }
|
||||
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
|
||||
@@ -35,6 +51,7 @@ let restore: (() => void) | undefined
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
|
||||
localStorage.setItem(API_KEY_STORAGE, 'test-key')
|
||||
})
|
||||
@@ -57,52 +74,84 @@ async function smoke(component: Parameters<typeof mountStrict>[0], path: string,
|
||||
}
|
||||
|
||||
describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
it('Dashboard renders the tiles, chart, feed and recent packages', async () => {
|
||||
it('Overview renders the verdict strip, policy, capacity, trend, rankings, inspectors and feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'left-pad', version: '1.3.0', registry: 'npm' }, timestamp: Date.now() }]
|
||||
const { wrapper, problems, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
|
||||
const { wrapper, problems, restore: r } = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Dashboard')
|
||||
expect(wrapper.text()).toContain('Total packages')
|
||||
expect(wrapper.find('h1').text()).toBe('Overview')
|
||||
|
||||
const strip = wrapper.find('[data-testid="verdict-strip"]').text()
|
||||
for (const word of ['Cleared', 'Held', 'Bypassed', 'Awaiting scan']) expect(strip).toContain(word)
|
||||
// 3 scanned, 1 held, 1 bypassed: 1 cleared; 4 cached, 3 scanned: 1 awaiting.
|
||||
expect(wrapper.find('[data-verdict="cleared"]').text()).toContain('1')
|
||||
expect(wrapper.find('[data-verdict="held"]').attributes('href')).toBe('/security?tab=held')
|
||||
|
||||
expect(wrapper.find('[data-testid="policy-line"]').text()).toContain('Blocks any CRITICAL.')
|
||||
expect(wrapper.find('[data-testid="policy-line"]').text()).toContain('Fail-closed')
|
||||
expect(wrapper.find('[data-testid="cache-capacity"]').text()).toContain('5 GB of 10 GB')
|
||||
expect(wrapper.find('[data-testid="download-trend"] [role="img"]').exists()).toBe(true)
|
||||
expect(wrapper.find('[data-testid="top-packages"]').text()).toContain('npm · left-pad')
|
||||
expect(wrapper.find('[data-testid="top-packages"]').text()).toContain('go · github.com/example/module')
|
||||
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('grype')
|
||||
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('Unavailable')
|
||||
expect(wrapper.find('[data-testid="ws-event-feed"]').text()).toContain('left-pad')
|
||||
expect(wrapper.find('[role="img"]').exists()).toBe(true)
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
expect(wrapper.text()).toContain('github.com/example/module')
|
||||
})
|
||||
|
||||
it('PackageList groups fixture packages and shows severity words', async () => {
|
||||
it('PackageList shows a verdict for each row and filters by it', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).toContain('2 versions')
|
||||
expect(wrapper.text()).toContain('requests')
|
||||
|
||||
const trigger = wrapper.findAll('button').find((b) => b.text().includes('left-pad'))
|
||||
await trigger!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('Critical: 1')
|
||||
expect(wrapper.text()).toContain('Blocked')
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('4 of 4')
|
||||
const text = wrapper.text()
|
||||
for (const word of ['left-pad', 'requests', 'github.com/example/module', 'Held', 'Cleared', 'Bypassed', 'Awaiting scan']) {
|
||||
expect(text).toContain(word)
|
||||
}
|
||||
})
|
||||
|
||||
it('PackageDetails renders the report, severity table and expanded row', async () => {
|
||||
it('PackageList seeds the verdict filter from the URL', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages?verdict=held')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1 of 4')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).not.toContain('requests')
|
||||
})
|
||||
|
||||
it('PackageList opens a quick view with a link to the full page', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages?verdict=held')
|
||||
await wrapper.find('tbody tr').trigger('click')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const sheet = document.body.querySelector('[data-slot="sheet-content"]')
|
||||
expect(sheet?.textContent).toContain('Package has 1 CRITICAL vulnerabilities')
|
||||
expect(sheet?.querySelector('a[href^="/package/npm/left-pad/1.3.0"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('PackageDetails explains the verdict and lists findings most severe first', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('left-pad')
|
||||
expect(wrapper.text()).toContain('Security scan summary')
|
||||
expect(wrapper.text()).toContain('trivy')
|
||||
|
||||
// Most severe first: CRITICAL, HIGH, then LOW.
|
||||
const ids = wrapper.findAll('tbody td.font-mono').map((td) => td.text().replace('CVE ID', ''))
|
||||
const banner = wrapper.find('[data-testid="verdict-banner"]').text()
|
||||
expect(banner).toContain('Held: CVE-2026-0003 is HIGH')
|
||||
expect(banner).toContain('Blocks any CRITICAL.')
|
||||
|
||||
const meta = wrapper.find('[data-testid="package-meta"]').text()
|
||||
expect(meta).toContain('2 KB')
|
||||
expect(meta).toContain('https://registry.npmjs.org')
|
||||
expect(meta).toContain('Removed after 30 days without a request')
|
||||
|
||||
const ids = wrapper.findAll('tbody td.font-mono').map((td) => td.text().replace('Advisory', ''))
|
||||
expect(ids.slice(0, 3)).toEqual(['CVE-2026-0002', 'CVE-2026-0003', 'CVE-2026-0001'])
|
||||
|
||||
await wrapper.find('button[aria-label^="Show details for CVE-2026-0002"]').trigger('click')
|
||||
@@ -111,26 +160,49 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(wrapper.text()).toContain('No fix available')
|
||||
})
|
||||
|
||||
it('VulnerablePackages lists the vulnerable fixture packages', async () => {
|
||||
const { wrapper, problems } = await smoke(VulnerablePackages, '/vulnerable-packages')
|
||||
it('PackageDetails Inspectors tab shows one row per scanner', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0?tab=inspectors')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0?tab=inspectors')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Vulnerable packages')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).not.toContain('requests')
|
||||
expect(wrapper.text()).toContain('Critical')
|
||||
const panel = wrapper.find('[role="tabpanel"]:not([hidden])')
|
||||
const text = panel.text()
|
||||
for (const word of ['trivy', 'osv', 'grype', 'govulncheck', 'v0.58.1', 'No result', 'Off']) expect(text).toContain(word)
|
||||
})
|
||||
|
||||
it('VulnerablePackages on the blocked route keeps only blocked packages', async () => {
|
||||
const { wrapper, problems } = await smoke(VulnerablePackages, '/blocked-packages')
|
||||
it('PackageDetails Downloads tab reads the per-package analytics', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0?tab=downloads')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0?tab=downloads')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Blocked packages')
|
||||
expect(wrapper.text()).toContain('1 vulnerable version')
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/analytics/package/npm/left-pad')
|
||||
expect(wrapper.text()).toContain('80 KB')
|
||||
})
|
||||
|
||||
it('Security splits packages by what the policy did', async () => {
|
||||
const { wrapper, problems } = await smoke(Security, '/security')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Security')
|
||||
const triggers = wrapper.findAll('[role="tab"]').map((t) => t.text())
|
||||
expect(triggers).toEqual(['Held (1)', 'Vulnerable but allowed (1)', 'Bypassed (1)'])
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).toContain('Package has 1 CRITICAL vulnerabilities')
|
||||
})
|
||||
|
||||
it('Security opens on the tab named in the URL', async () => {
|
||||
const { wrapper, problems } = await smoke(Security, '/security?tab=bypassed')
|
||||
expect(problems).toEqual([])
|
||||
const selected = wrapper.findAll('[role="tab"]').find((t) => t.attributes('aria-selected') === 'true')
|
||||
expect(selected?.text()).toBe('Bypassed (1)')
|
||||
expect(wrapper.text()).toContain('a.khan')
|
||||
})
|
||||
|
||||
it('BypassManagementPanel lists bypasses and opens the create dialog', async () => {
|
||||
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('CVE bypass management')
|
||||
expect(wrapper.find('h1').text()).toBe('Bypasses')
|
||||
expect(wrapper.text()).toContain('CVE-2026-0002')
|
||||
expect(wrapper.text()).toContain('Expired')
|
||||
|
||||
@@ -141,6 +213,14 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(document.body.querySelector('textarea')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('BypassManagementPanel opens the form prefilled from a package page link', async () => {
|
||||
const { problems } = await smoke(BypassManagementPanel, '/admin/bypasses?type=package&target=npm/[email protected]')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const input = Array.from(document.body.querySelectorAll<HTMLInputElement>('input')).find((i) => i.value === 'npm/[email protected]')
|
||||
expect(input).toBeDefined()
|
||||
})
|
||||
|
||||
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
|
||||
localStorage.clear()
|
||||
const prompt = vi.spyOn(window, 'prompt')
|
||||
@@ -166,14 +246,51 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(wrapper.text()).toContain('CVE-2026-0002')
|
||||
})
|
||||
|
||||
it('Stats renders totals, the storage tile and the registry table', async () => {
|
||||
const { wrapper, problems } = await smoke(Stats, '/stats')
|
||||
it('Insights renders the registry breakdown, scan coverage and daily downloads', async () => {
|
||||
const { wrapper, problems } = await smoke(Insights, '/stats')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Statistics')
|
||||
expect(wrapper.text()).toContain('5 GB / 10 GB')
|
||||
expect(wrapper.text()).toContain('50.0% used')
|
||||
expect(wrapper.text()).toContain('Go modules')
|
||||
expect(wrapper.find('[role="progressbar"]').exists()).toBe(true)
|
||||
expect(wrapper.find('h1').text()).toBe('Insights')
|
||||
const breakdown = wrapper.find('[data-testid="registry-breakdown"]').text()
|
||||
for (const word of ['npm', 'pypi', 'go', '2 GB']) expect(breakdown).toContain(word)
|
||||
expect(wrapper.find('[data-testid="scan-coverage"]').text()).toContain('3 of 4')
|
||||
expect(wrapper.find('[data-testid="daily-downloads"] [role="img"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('System shows the policy, scanners, rescans, cache, pre-warming and build version', async () => {
|
||||
const { wrapper, problems } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('System')
|
||||
expect(wrapper.find('[data-testid="build-version"]').text()).toBe('v1.8.0')
|
||||
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Blocks any CRITICAL.')
|
||||
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Fail-closed')
|
||||
expect(wrapper.find('[data-testid="rescan-list"]').text()).toContain('1 day')
|
||||
expect(wrapper.find('[data-testid="cache-list"]').text()).toContain('10 GB')
|
||||
expect(wrapper.text()).toContain('v0.58.1')
|
||||
expect(wrapper.find('[data-testid="prewarming"] button').text()).toContain('Run a cycle now')
|
||||
})
|
||||
|
||||
it('System starts a pre-warming cycle with the admin key', async () => {
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: {} })
|
||||
const { wrapper } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).toHaveBeenCalledWith(
|
||||
'/api/admin/prewarming/trigger',
|
||||
null,
|
||||
expect.objectContaining({ headers: { Authorization: 'Bearer test-key' } }),
|
||||
)
|
||||
})
|
||||
|
||||
it('System asks for the key before it triggers anything', async () => {
|
||||
localStorage.clear()
|
||||
const { wrapper } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
|
||||
expect(document.body.textContent).toContain('Enter your admin API key to start a pre-warming cycle.')
|
||||
})
|
||||
|
||||
it('VulnerabilityBadge prints the severity word for every tone', async () => {
|
||||
@@ -191,7 +308,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(tones).toEqual(['danger', 'danger', 'warning', 'info', 'neutral'])
|
||||
})
|
||||
|
||||
it('App renders one banner, one main, a skip link first and the five sections', async () => {
|
||||
it('App renders one banner, one main, a skip link first and the sections', async () => {
|
||||
const { wrapper, problems } = await smoke(App, '/')
|
||||
expect(problems).toEqual([])
|
||||
// A page's own <header> inside <main> is not a banner landmark.
|
||||
@@ -200,7 +317,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
const first = document.body.querySelector<HTMLElement>('a[href], button')
|
||||
expect(first?.getAttribute('href')).toBe('#main-content')
|
||||
const nav = wrapper.find('nav[aria-label="Sections"]')
|
||||
expect(nav.findAll('a').map((a) => a.text())).toEqual(['Dashboard', 'Packages', 'Vulnerable', 'Bypasses', 'Stats'])
|
||||
expect(nav.findAll('a').map((a) => a.text())).toEqual(['Overview', 'Packages', 'Security', 'Insights', 'Bypasses', 'System'])
|
||||
expect(document.documentElement.getAttribute('data-style')).toBe('workbench')
|
||||
// Brand column and sidebar items share one left edge: 6 spacing units each.
|
||||
expect(document.body.querySelector('header')?.className).toContain('[&>div]:px-6')
|
||||
@@ -209,7 +326,28 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
|
||||
it('PackageList still fetches through the store on mount', async () => {
|
||||
await smoke(PackageList, '/packages')
|
||||
expect(usePackageStore().packagePage.packages.length).toBe(PACKAGES.length)
|
||||
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('old URLs land on the new pages', () => {
|
||||
it.each([
|
||||
['/vulnerable-packages', '/security', 'allowed'],
|
||||
['/blocked-packages', '/security', 'held'],
|
||||
])('%s redirects to %s with tab %s', async (from, path, tab) => {
|
||||
const router = await createTestRouter(from)
|
||||
expect(router.currentRoute.value.path).toBe(path)
|
||||
expect(router.currentRoute.value.query.tab).toBe(tab)
|
||||
})
|
||||
|
||||
it('keeps the severity filter of the old link', async () => {
|
||||
const router = await createTestRouter('/vulnerable-packages?severity=critical')
|
||||
expect(router.currentRoute.value.query).toEqual({ severity: 'critical', tab: 'allowed' })
|
||||
})
|
||||
|
||||
it('/packages/npm still seeds the registry filter', async () => {
|
||||
const { wrapper } = await smoke(PackageList, '/packages/npm', { registry: 'npm' })
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('2 of 4')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -245,21 +383,21 @@ describe('PyPI rows show the release version, not the file name', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('Dashboard recent packages', async () => {
|
||||
const { wrapper } = await smoke(Dashboard, '/')
|
||||
it('PackageList version column', async () => {
|
||||
const { wrapper } = await smoke(PackageList, '/packages')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('Dashboard activity feed', async () => {
|
||||
it('Overview activity feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
|
||||
const { wrapper, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
|
||||
const { wrapper, restore: r } = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
const feed = wrapper.find('[data-testid="ws-event-feed"]').text()
|
||||
@@ -267,10 +405,8 @@ describe('PyPI rows show the release version, not the file name', () => {
|
||||
expect(feed).not.toContain('whl')
|
||||
})
|
||||
|
||||
it('VulnerablePackages version column', async () => {
|
||||
const { wrapper } = await smoke(VulnerablePackages, '/vulnerable-packages')
|
||||
await flushPromises()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
it('Security version column', async () => {
|
||||
const { wrapper } = await smoke(Security, '/security?tab=allowed')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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)))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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: '' })
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -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' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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)}`
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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' })
|
||||
})
|
||||
})
|
||||
@@ -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'
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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.`,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw, type RouterHistory } from 'vue-router'
|
||||
import { createRouter, createWebHistory, type LocationQuery, type RouteRecordRaw, type RouterHistory } from 'vue-router'
|
||||
|
||||
/** Keeps the query string of an old URL when it moves to a tab of the Security page. */
|
||||
function toSecurityTab(tab: string) {
|
||||
return (to: { query: LocationQuery }) => ({ path: '/security', query: { ...to.query, tab } })
|
||||
}
|
||||
|
||||
export const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'dashboard',
|
||||
component: () => import('../components/Dashboard.vue'),
|
||||
name: 'overview',
|
||||
component: () => import('../components/Overview.vue'),
|
||||
},
|
||||
{
|
||||
path: '/packages/:registry?',
|
||||
@@ -20,25 +25,35 @@ export const routes: RouteRecordRaw[] = [
|
||||
props: true,
|
||||
},
|
||||
{
|
||||
path: '/stats',
|
||||
name: 'stats',
|
||||
component: () => import('../components/Stats.vue'),
|
||||
path: '/security',
|
||||
name: 'security',
|
||||
component: () => import('../components/Security.vue'),
|
||||
},
|
||||
{
|
||||
path: '/vulnerable-packages',
|
||||
name: 'vulnerable-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
redirect: toSecurityTab('allowed'),
|
||||
},
|
||||
{
|
||||
path: '/blocked-packages',
|
||||
name: 'blocked-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
redirect: toSecurityTab('held'),
|
||||
},
|
||||
{
|
||||
path: '/stats',
|
||||
name: 'insights',
|
||||
component: () => import('../components/Insights.vue'),
|
||||
},
|
||||
{
|
||||
path: '/admin/bypasses',
|
||||
name: 'bypasses',
|
||||
component: () => import('../components/BypassManagementPanel.vue'),
|
||||
},
|
||||
{
|
||||
path: '/admin/system',
|
||||
name: 'system',
|
||||
component: () => import('../components/System.vue'),
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'not-found',
|
||||
|
||||
@@ -9,6 +9,20 @@ export interface VulnerabilityCounts {
|
||||
low: number
|
||||
}
|
||||
|
||||
/** What the proxy did with a package; absent on servers that predate verdicts. */
|
||||
export type ApiVerdict = 'cleared' | 'held' | 'bypassed' | 'pending'
|
||||
|
||||
/** The admin bypass that applied to a package. */
|
||||
export interface AppliedBypass {
|
||||
id: string
|
||||
type: 'cve' | 'package'
|
||||
target: string
|
||||
reason: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
export interface VulnerabilityInfo {
|
||||
scanned: boolean
|
||||
status: 'clean' | 'vulnerable' | 'pending' | 'not_scanned'
|
||||
@@ -16,6 +30,10 @@ export interface VulnerabilityInfo {
|
||||
total?: number
|
||||
scannedAt?: string // ISO 8601 timestamp
|
||||
isBlocked?: boolean // Whether download is blocked due to vulnerability thresholds
|
||||
verdict?: ApiVerdict
|
||||
/** Why the package is held. */
|
||||
reason?: string
|
||||
bypass?: AppliedBypass
|
||||
}
|
||||
|
||||
export interface Package {
|
||||
@@ -25,6 +43,7 @@ export interface Package {
|
||||
version: string
|
||||
release_version?: string
|
||||
size: number
|
||||
checksum_sha256?: string
|
||||
cached_at: string
|
||||
last_accessed: string
|
||||
download_count: number
|
||||
@@ -40,6 +59,7 @@ export interface Stats {
|
||||
scanned_packages: number
|
||||
vulnerable_packages: number
|
||||
blocked_packages: number
|
||||
bypassed_packages?: number
|
||||
/** Seconds a cached item can go unrequested before cleanup removes it; 0 means never. */
|
||||
idle_ttl?: number
|
||||
}
|
||||
|
||||
@@ -4,20 +4,24 @@
|
||||
/* Only the library components the app imports, plus their transitive imports: scanning all of dist adds every component's classes. `pnpm sources` regenerates this list. */
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/ActivityFeed/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/BarChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CalendarHeatmap/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Card/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CodeViewer/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CodeViewer/tokenize/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DonutChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Leaderboard/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatBar/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_chart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_shared/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Alert/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Callout/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ConfirmDialog/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/EmptyState/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ErrorState/*.js";
|
||||
@@ -27,29 +31,34 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Checkbox/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/CheckboxCard/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Combobox/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/DateInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Field/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/FilterBar/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Input/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/InputGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Label/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NativeSelect/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NumberInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SearchInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SegmentedControl/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Textarea/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/TimeInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/AppShell/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/ConfigProvider/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/Container/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/PageHeader/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Accordion/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/AppHeader/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/MobileNav/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/NavLink/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Pagination/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/SidebarNav/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Tabs/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/ThemeToggle/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/AlertDialog/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Dialog/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Popover/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Sheet/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Avatar/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Badge/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Button/*.js";
|
||||
@@ -62,6 +71,8 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/FormattedNumber/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/InlineCode/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
|
||||
|
||||
@@ -9,6 +9,7 @@ export const STATS: Stats = {
|
||||
scanned_packages: 3,
|
||||
vulnerable_packages: 2,
|
||||
blocked_packages: 1,
|
||||
bypassed_packages: 1,
|
||||
}
|
||||
|
||||
export const REGISTRIES = {
|
||||
@@ -34,6 +35,8 @@ export const PACKAGES: Package[] = [
|
||||
total: 4,
|
||||
scannedAt: '2026-01-03T10:05:00Z',
|
||||
isBlocked: true,
|
||||
verdict: 'held',
|
||||
reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -52,6 +55,7 @@ export const PACKAGES: Package[] = [
|
||||
total: 3,
|
||||
scannedAt: '2026-01-02T10:05:00Z',
|
||||
isBlocked: false,
|
||||
verdict: 'cleared',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -63,7 +67,24 @@ export const PACKAGES: Package[] = [
|
||||
cached_at: '2026-01-01T10:00:00Z',
|
||||
last_accessed: '2026-01-01T10:00:00Z',
|
||||
download_count: 30,
|
||||
vulnerabilities: { scanned: true, status: 'clean', total: 0, scannedAt: '2026-01-01T10:05:00Z' },
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
|
||||
total: 1,
|
||||
scannedAt: '2026-01-01T10:05:00Z',
|
||||
isBlocked: false,
|
||||
verdict: 'bypassed',
|
||||
bypass: {
|
||||
id: 'bypass-1',
|
||||
type: 'package',
|
||||
target: 'pypi/[email protected]',
|
||||
reason: 'Vendored fix',
|
||||
created_by: 'a.khan',
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'go-1',
|
||||
@@ -74,7 +95,7 @@ export const PACKAGES: Package[] = [
|
||||
cached_at: '2026-01-04T10:00:00Z',
|
||||
last_accessed: '2026-01-04T10:00:00Z',
|
||||
download_count: 10,
|
||||
vulnerabilities: { scanned: false, status: 'not_scanned' },
|
||||
vulnerabilities: { scanned: false, status: 'not_scanned', isBlocked: false, verdict: 'pending' },
|
||||
},
|
||||
]
|
||||
|
||||
@@ -89,6 +110,16 @@ export const TIMESERIES = {
|
||||
}
|
||||
|
||||
export const VULNERABILITY_REPORT = {
|
||||
decision: {
|
||||
verdict: 'held',
|
||||
blocked: true,
|
||||
reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)',
|
||||
bypass: null,
|
||||
},
|
||||
scanners: [
|
||||
{ name: 'trivy', findings: 2, severity_counts: { critical: 1, high: 0, moderate: 0, low: 1 } },
|
||||
{ name: 'osv', findings: 3, severity_counts: { critical: 1, high: 1, moderate: 0, low: 1 } },
|
||||
],
|
||||
scanned: true,
|
||||
scanner: 'trivy+osv',
|
||||
scanned_at: '2026-01-03T10:05:00Z',
|
||||
@@ -104,6 +135,7 @@ export const VULNERABILITY_REPORT = {
|
||||
description: 'A **low** severity sample description.',
|
||||
references: ['https://example.com/advisory/1'],
|
||||
fixed_in: '1.3.1',
|
||||
detected_by: ['trivy', 'osv'],
|
||||
bypassed: false,
|
||||
},
|
||||
{
|
||||
@@ -174,3 +206,45 @@ export const TREND = {
|
||||
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
|
||||
],
|
||||
}
|
||||
|
||||
export const SYSTEM = {
|
||||
version: 'v1.8.0',
|
||||
security: {
|
||||
enabled: true,
|
||||
fail_closed: true,
|
||||
scan_on_download: true,
|
||||
block_on_severity: 'none',
|
||||
block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 },
|
||||
scan_wait_timeout: 30,
|
||||
scanners: [
|
||||
{ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' },
|
||||
{ name: 'grype', enabled: true, healthy: false, version: '' },
|
||||
{ name: 'osv', enabled: true, healthy: true, version: '' },
|
||||
{ name: 'govulncheck', enabled: false, healthy: null, version: '' },
|
||||
],
|
||||
rescan: { interval: 86400, active_window: 2592000, concurrency: 2, on_access: false },
|
||||
},
|
||||
upstreams: { go: 'https://proxy.golang.org', npm: 'https://registry.npmjs.org', pypi: 'https://pypi.org' },
|
||||
cache: { max_size: 10737418240, idle_ttl: 2592000, default_ttl: 86400 },
|
||||
prewarming: { enabled: true, interval: 3600, top_packages: 100 },
|
||||
}
|
||||
|
||||
export const TOP_PACKAGES = {
|
||||
packages: [
|
||||
{ Registry: 'npm', Name: 'left-pad', Downloads: 40, RecentDownloads: 12, Trend: 0.4 },
|
||||
{ Registry: 'go', Name: 'github.com/example/module/@v/v0.4.1.zip', Downloads: 10, RecentDownloads: 4, Trend: 0 },
|
||||
],
|
||||
total: 2,
|
||||
}
|
||||
|
||||
export const PACKAGE_ANALYTICS = {
|
||||
package: {
|
||||
Registry: 'npm',
|
||||
Name: 'left-pad',
|
||||
TotalDownloads: 40,
|
||||
UniqueVersions: 2,
|
||||
BytesServed: 81920,
|
||||
FirstSeen: '2026-01-01T10:00:00Z',
|
||||
LastDownload: '2026-01-03T10:00:00Z',
|
||||
},
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user