feat(ui): page, filter and sort packages on the server

The packages and security pages ask for one page of rows instead of the whole cache. Search is debounced, and the filters and sort stay in the URL.
This commit is contained in:
2026-11-24 01:33:30 +00:00
parent 55c60cb8e4
commit 64793f9c7e
11 changed files with 483 additions and 177 deletions
+81 -28
View File
@@ -1,48 +1,57 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises, mount } from '@vue/test-utils'
import PackageList from './PackageList.vue'
import { usePackageStore, type Package } from '../stores/packages'
import type { Package } from '../stores/packages'
import { PACKAGES } from '@/test/fixtures'
import { serveRows } from '@/test/rowsServer'
import { createTestRouter } from '@/test/router'
vi.mock('axios')
const lastUrl = () => new URL(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0]), 'http://x').searchParams
function serve(rows: Package[]) {
vi.mocked(axios.get).mockImplementation(async (url: string) => ({ data: serveRows(url, rows) }) as never)
}
async function open(path = '/packages', rows: Package[] = PACKAGES) {
serve(rows)
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 }
return { wrapper, router }
}
describe('PackageList.vue', () => {
beforeEach(() => setActivePinia(createPinia()))
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
it('renders the page heading', async () => {
const { wrapper } = await open()
expect(wrapper.find('h1').text()).toBe('Packages')
})
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('asks the server for the first page of rows, not for every package', async () => {
await open()
const calls = vi.mocked(axios.get).mock.calls.filter((c) => String(c[0]).startsWith('/api/packages'))
expect(calls).toHaveLength(1)
expect(Object.fromEntries(lastUrl())).toEqual({ layout: 'rows', page: '1', page_size: '25' })
})
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()
vi.mocked(axios.get).mockRejectedValue(new Error('Failed to fetch packages'))
const router = await createTestRouter('/packages')
const wrapper = mount(PackageList, { global: { plugins: [createPinia(), router] } })
await flushPromises()
expect(wrapper.text()).toContain('Failed to fetch packages')
})
@@ -60,31 +69,75 @@ describe('PackageList.vue', () => {
expect(text).toContain('Awaiting scan')
})
it('narrows rows with the search box and says when nothing matches', async () => {
it('debounces the search box into one request', 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)
vi.mocked(axios.get).mockClear()
const input = wrapper.get('input[aria-label="Search packages"]')
await input.setValue('nothing-like-this')
await input.setValue('r')
await input.setValue('re')
await input.setValue('requests')
await vi.advanceTimersByTimeAsync(100)
expect(axios.get).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(400)
await flushPromises()
expect(axios.get).toHaveBeenCalledTimes(1)
expect(lastUrl().get('q')).toBe('requests')
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
})
it('says nothing matches when the server returns no rows for a search', async () => {
const { wrapper } = await open()
await wrapper.get('input[aria-label="Search packages"]').setValue('nothing-like-this')
await vi.advanceTimersByTimeAsync(400)
await flushPromises()
expect(wrapper.text()).toContain('No packages match')
})
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 vi.advanceTimersByTimeAsync(400)
await flushPromises()
expect(router.currentRoute.value.query.q).toBe('left')
})
it('treats the registry path segment as a registry filter', async () => {
it('treats the registry path segment as a registry filter sent to the server', async () => {
const { wrapper } = await open('/packages/pypi')
expect(lastUrl().get('registry')).toBe('pypi')
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
expect(wrapper.text()).toContain('requests')
})
it('sends the verdict from the URL', async () => {
const { wrapper } = await open('/packages?verdict=held')
expect(lastUrl().get('verdict')).toBe('held')
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('1 of 1 package version')
})
it('pages through the server and shows the range', async () => {
const many = Array.from({ length: 60 }, (_, i) => ({ ...PACKAGES[0]!, id: `p${i}`, name: `pkg-${String(i).padStart(2, '0')}` }))
const { wrapper } = await open('/packages', many)
expect(wrapper.findAll('tbody tr')).toHaveLength(25)
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('1–25 of 60 package versions')
await wrapper.get('nav[aria-label="Package pages"] button[aria-label*="ext"]').trigger('click')
await flushPromises()
expect(lastUrl().get('page')).toBe('2')
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('26–50 of 60')
})
it('sends a column sort to the server and returns to page 1', async () => {
const { wrapper } = await open()
await wrapper.get('thead button[aria-label*="Size"], thead th button').trigger('click')
await flushPromises()
expect(lastUrl().get('page')).toBe('1')
expect(lastUrl().get('sort')).not.toBeNull()
})
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 six = { ...PACKAGES[2], version: 'six-1.17.0-py2.py3-none-any.whl', release_version: '1.17.0' } as Package
const { wrapper } = await open('/packages', [six])
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
+62 -25
View File
@@ -11,36 +11,35 @@
<FilterBar v-model="filterItems" :fields="filterFields" variant="compact" />
</div>
<LoadingState v-if="loading && packages.length === 0" variant="table" label="Loading packages..." />
<LoadingState v-if="loading && !loaded" variant="table" label="Loading packages..." />
<ErrorState v-else-if="error" variant="card" title="Could not load packages" :message="error" @retry="load()" />
<Card v-else>
<CardContent>
<EmptyState
v-if="packages.length === 0"
v-if="total === 0 && !filtered"
:icon="faBoxOpen"
title="No packages cached yet"
description="Packages will appear here once they are downloaded through the proxy."
/>
<EmptyState
v-else-if="rows.length === 0"
v-else-if="total === 0"
:icon="faMagnifyingGlass"
title="No packages match"
description="Change the search text or remove a filter."
/>
<template v-else>
<p class="m-0 mb-3 text-sm text-muted-foreground" data-testid="package-count">
{{ rows.length }} of {{ plural(packages.length, 'package version') }}
{{ rangeStart }}–{{ rangeEnd }} of {{ plural(total, 'package version') }}
</p>
<DataTable
v-model:sort="sort"
v-model:page="page"
label="Cached packages"
layout="cards"
density="compact"
row-clickable
:page-size="PAGE_SIZE"
:loading="loading"
:columns="columns"
:rows="rows"
@row-click="(row: Package) => (selected = row)"
@@ -60,6 +59,14 @@
<span v-else class="text-muted-foreground">Never</span>
</template>
</DataTable>
<Pagination
v-if="total > PAGE_SIZE"
v-model:page="page"
class="mt-4"
:total="total"
:page-size="PAGE_SIZE"
aria-label="Package pages"
/>
</template>
</CardContent>
</Card>
@@ -79,8 +86,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import {
Badge,
@@ -94,6 +100,7 @@ import {
FilterBar,
LoadingState,
PageHeader,
Pagination,
RelativeTime,
SearchInput,
useToastStore,
@@ -104,24 +111,27 @@ import {
} from '@perfect-design/ui'
import PackageQuickView from './parts/PackageQuickView.vue'
import VerdictBadge from './parts/VerdictBadge.vue'
import { usePackageStore, type Package } from '../stores/packages'
import { usePackageStore, type ApiVerdict, type Package } from '../stores/packages'
import { plural } from '@/lib/reason'
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
import { filterPackages, packageRoute } from '@/lib/packages'
import { packageRoute } from '@/lib/packages'
import { usePackageRows, type RowQuery, type RowSort } from '@/lib/packageRows'
import { faBoxOpen, faMagnifyingGlass, faRotateRight } from '@/lib/icons'
import { VERDICT_OPTIONS, VERDICT_RANK, verdictOf, type Verdict } from '@/lib/verdict'
import { VERDICT_OPTIONS, verdictOf } from '@/lib/verdict'
const props = defineProps<{ registry?: string }>()
const PAGE_SIZE = 25
const SEARCH_DEBOUNCE_MS = 300
const KNOWN_REGISTRIES = ['npm', 'go', 'pypi']
const store = usePackageStore()
const toasts = useToastStore()
const route = useRoute()
const router = useRouter()
const { packages, loading, error } = storeToRefs(store)
const { rows, total, loading, error, load: loadRows } = usePackageRows()
const loaded = ref(false)
const selected = ref<Package | null>(null)
const showDeleteModal = ref(false)
const packageToDelete = ref<Package | null>(null)
@@ -134,6 +144,13 @@ function queryText(key: string): string {
}
const query = ref(queryText('q'))
const searchTerm = ref(query.value)
let searchTimer: ReturnType<typeof setTimeout> | undefined
watch(query, (value) => {
clearTimeout(searchTimer)
searchTimer = setTimeout(() => (searchTerm.value = value), SEARCH_DEBOUNCE_MS)
})
onUnmounted(() => clearTimeout(searchTimer))
let nextFilterId = 0
function filterItem(field: string, value: string): FilterItem {
@@ -149,7 +166,7 @@ const filterItems = ref<FilterItem[]>(
)
const registryOptions = computed(() => {
const seen = new Set([...KNOWN_REGISTRIES, ...packages.value.map((p) => p.registry)])
const seen = new Set([...KNOWN_REGISTRIES, ...rows.value.map((p) => p.registry), ...valuesOf('registry')])
return [...seen].map((value) => ({ value, label: value }))
})
@@ -162,20 +179,38 @@ 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[],
}),
)
const SORT_KEYS: Record<string, RowSort> = {
name: 'name',
version: 'version',
registry: 'registry',
size: 'size',
download_count: 'downloads',
last_accessed: 'last_accessed',
scanned: 'last_scanned',
}
const rowQuery = computed<RowQuery>(() => ({
q: searchTerm.value,
registry: valuesOf('registry')[0],
verdict: valuesOf('verdict')[0] as ApiVerdict | undefined,
sort: sort.value ? SORT_KEYS[sort.value.key] : undefined,
order: sort.value?.direction === 'desc' ? 'desc' : 'asc',
page: page.value,
pageSize: PAGE_SIZE,
}))
const filtered = computed(() => Boolean(searchTerm.value.trim() || valuesOf('registry').length || valuesOf('verdict').length))
const rangeStart = computed(() => (total.value === 0 ? 0 : (page.value - 1) * PAGE_SIZE + 1))
const rangeEnd = computed(() => Math.min(page.value * PAGE_SIZE, total.value))
// A new search, filter or sort starts again from the first page.
watch([searchTerm, filterItems, sort], () => (page.value = 1))
// The URL mirrors the filters so a reload or a shared link restores the view.
watch([query, filterItems], () => {
page.value = 1
watch([searchTerm, filterItems], () => {
const { q: _q, registry: _r, verdict: _v, ...rest } = route.query
const next: Record<string, string> = {}
if (query.value.trim()) next.q = query.value.trim()
if (searchTerm.value.trim()) next.q = searchTerm.value.trim()
const [registry] = valuesOf('registry')
const [verdict] = valuesOf('verdict')
if (registry) next.registry = registry
@@ -190,14 +225,16 @@ const columns: DataTableColumn<Package>[] = [
{ 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: 'verdict', header: 'Verdict' },
{ key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 },
]
async function load() {
await store.fetchPackages()
await loadRows(rowQuery.value)
loaded.value = true
}
watch(rowQuery, load)
onMounted(load)
function confirmDelete(pkg: Package) {
+52 -6
View File
@@ -5,6 +5,7 @@ import { flushPromises } from '@vue/test-utils'
import Security from './Security.vue'
import type { Package, VulnerabilityCounts } from '@/stores/packages'
import { mountStrict } from '@/test/mountStrict'
import { serveRows } from '@/test/rowsServer'
import { createTestRouter } from '@/test/router'
vi.mock('axios')
@@ -41,9 +42,13 @@ const NAMES = FIXTURE.map((p) => p.name)
let restore: (() => void) | undefined
function serve(packages: Package[]) {
vi.mocked(axios.get).mockImplementation(async (url: string) => ({ data: serveRows(url, packages) }) as never)
}
beforeEach(() => {
setActivePinia(createPinia())
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
serve(FIXTURE)
})
afterEach(() => {
@@ -82,9 +87,27 @@ describe('Security severity filter', () => {
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('asks the server for every package, so a hold with no findings is not dropped', async () => {
it('asks the server for one page of the open tab, worst first', async () => {
await open()
expect(axios.get).toHaveBeenCalledWith('/api/packages')
const url = vi.mocked(axios.get).mock.calls.map((c) => String(c[0])).find((u) => u.includes('layout=rows'))!
const params = new URL(url, 'http://x').searchParams
expect(Object.fromEntries(params)).toEqual({
layout: 'rows',
page: '1',
page_size: '25',
verdict: 'cleared',
severity: 'critical,high,moderate,low',
sort: 'risk',
order: 'desc',
})
})
it('sends the selected severities with the open tab', async () => {
const { wrapper } = await open()
await tile(wrapper, 'high').trigger('click')
await flushPromises()
const last = String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])
expect(new URL(last, 'http://x').searchParams.get('severity')).toBe('high')
})
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
@@ -206,7 +229,7 @@ describe('Security severity filter', () => {
})
it('keeps the success state when nothing has findings, filter or not', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
serve([])
const { wrapper } = await open('/security?tab=allowed&severity=critical')
expect(wrapper.text()).toContain('No package carries findings under the policy')
@@ -217,7 +240,7 @@ describe('Security severity filter', () => {
const held = vulnerable('echo-blocked', { critical: 1 })
held.vulnerabilities!.isBlocked = true
held.vulnerabilities!.verdict = 'held'
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, held] } })
serve([...FIXTURE, held])
const { wrapper } = await open('/blocked-packages?severity=critical')
expect(wrapper.text()).toContain('echo-blocked')
@@ -227,10 +250,33 @@ describe('Security severity filter', () => {
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] } })
serve([failed])
const { wrapper } = await open('/security?tab=held')
expect(wrapper.text()).toContain('foxtrot-failed')
expect(wrapper.text()).toContain('scan failed - fail closed')
})
it('pages through the server and resets to page 1 when the filter changes', async () => {
const many = Array.from({ length: 30 }, (_, i) => vulnerable(`pkg-${String(i).padStart(2, '0')}`, { critical: 1 }))
serve(many)
const { wrapper } = await open()
expect(wrapper.findAll('tbody tr')).toHaveLength(25)
await wrapper.get('nav[aria-label="Security pages"] button[aria-label*="ext"]').trigger('click')
await flushPromises()
expect(wrapper.findAll('tbody tr')).toHaveLength(5)
expect(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])).toContain('page=2')
await tile(wrapper, 'critical').trigger('click')
await flushPromises()
expect(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])).toContain('page=1')
})
it('takes the tab counts from the server, not from the rows on screen', async () => {
const many = Array.from({ length: 30 }, (_, i) => vulnerable(`pkg-${i}`, { low: 1 }))
serve(many)
const { wrapper } = await open()
expect(wrapper.findAll('[role="tab"]').map((t) => t.text())).toContain('Vulnerable but allowed (30)')
})
})
+57 -61
View File
@@ -6,13 +6,13 @@
</template>
</PageHeader>
<LoadingState v-if="loading && packages.length === 0" variant="table" label="Loading security findings..." />
<LoadingState v-if="loading && !loaded" variant="table" label="Loading security findings..." />
<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-if="anyFindings"
v-model="selectedSeverities"
selectable
label="Findings by severity. Select a severity to filter the packages."
@@ -27,7 +27,7 @@
<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>
<TabsTrigger v-for="t in TAB_DEFS" :key="t.value" :value="t.value">{{ t.label }} ({{ tabCount(t.value) }})</TabsTrigger>
</TabsList>
<TabsContent v-for="t in TAB_DEFS" :key="t.value" :value="t.value" class="pt-4">
@@ -38,7 +38,7 @@
</CardHeader>
<CardContent>
<EmptyState
v-if="rowsFor(t.value).length === 0"
v-if="total === 0"
:icon="faCircleCheck"
:title="hasFilter ? 'No packages match the filter' : t.empty"
:description="hasFilter ? `No package here has a ${filterSummary} vulnerability.` : undefined"
@@ -49,13 +49,14 @@
</EmptyState>
<DataTable
v-else
v-model:sort="sort"
:label="t.label"
layout="cards"
density="compact"
row-clickable
:page-size="PAGE_SIZE"
:loading="loading"
:columns="columnsFor(t.value)"
:rows="rowsFor(t.value)"
:rows="rows"
@row-click="open"
>
<template #cell-name="{ row }">
@@ -86,6 +87,14 @@
<RelativeTime v-if="row.vulnerabilities?.scannedAt" :datetime="row.vulnerabilities.scannedAt" />
</template>
</DataTable>
<Pagination
v-if="total > PAGE_SIZE"
v-model:page="page"
class="mt-4"
:total="total"
:page-size="PAGE_SIZE"
aria-label="Security pages"
/>
</CardContent>
</Card>
</TabsContent>
@@ -96,7 +105,6 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import {
Badge,
@@ -111,22 +119,24 @@ import {
ErrorState,
LoadingState,
PageHeader,
Pagination,
RelativeTime,
Tabs,
TabsContent,
TabsList,
TabsTrigger,
type DataTableColumn,
type SortState,
} from '@perfect-design/ui'
import SeveritySummary from './SeveritySummary.vue'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
import type { Package, VulnerabilityCounts } from '../stores/packages'
import { displayVersion, withVersionPrefix } from '@/lib/format'
import { packageRoute } from '@/lib/packages'
import { usePackageRows, type RowQuery, type RowSort } from '@/lib/packageRows'
import { humanReason } from '@/lib/reason'
import { faCircleCheck, faRotateRight } from '@/lib/icons'
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
import { verdictOf } from '@/lib/verdict'
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
type TabName = 'held' | 'allowed' | 'bypassed'
@@ -139,10 +149,13 @@ const TAB_DEFS: ReadonlyArray<{ value: TabName; label: string; description: stri
const PAGE_SIZE = 25
const SEVERITY_QUERY = 'severity'
const store = usePackageStore()
const route = useRoute()
const router = useRouter()
const { packages, loading, error } = storeToRefs(store)
const { rows, total, counts, loading, error, load: loadRows } = usePackageRows()
const loaded = ref(false)
const page = ref(1)
const sort = ref<SortState | null>(null)
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 } }))
@@ -162,64 +175,46 @@ const selectedSeverities = computed<SeverityLevel[]>({
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
},
})
const anyFindings = computed(() => counts.value.verdicts.held + counts.value.vulnerable_allowed + counts.value.verdicts.bypassed > 0)
// 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 hasFilter = computed(() => selectedSeverities.value.length > 0 && anyFindings.value)
const filterSummary = computed(() => selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '))
/** 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)
function tabCount(name: TabName): number {
if (name === 'held') return counts.value.verdicts.held
if (name === 'bypassed') return counts.value.verdicts.bypassed
return counts.value.vulnerable_allowed
}
const severityTotals = computed<VulnerabilityCounts>(() => ({ ...counts.value.severity_findings }))
const severityPackages = computed<VulnerabilityCounts>(() => ({ ...counts.value.severity_packages }))
const SORT_KEYS: Record<string, RowSort> = { name: 'name', version: 'version', registry: 'registry', scanned: 'last_scanned' }
// "Vulnerable but allowed" is the cleared packages that have findings, so it always filters by severity.
const rowQuery = computed<RowQuery>(() => {
const severity = selectedSeverities.value.length > 0 ? selectedSeverities.value : tab.value === 'allowed' ? SEVERITY_LEVELS : []
return {
verdict: tab.value === 'allowed' ? 'cleared' : tab.value,
severity,
// Worst first unless the operator picked a column.
sort: sort.value ? SORT_KEYS[sort.value.key] : 'risk',
order: sort.value ? (sort.value.direction === 'desc' ? 'desc' : 'asc') : 'desc',
page: page.value,
pageSize: PAGE_SIZE,
}
return out
})
function risk(pkg: Package): number[] {
const c = pkg.vulnerabilities?.counts ?? NO_VULNERABILITIES
return [c.critical, c.high, c.moderate, c.low]
}
// 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
}
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
})
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
})
watch([tab, selectedSeverities, sort], () => (page.value = 1))
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: 'version', header: 'Version', sortable: true, accessor: (p) => withVersionPrefix(displayVersion(p)) },
{ key: 'registry', header: 'Registry', sortable: true },
{ 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 }
const SCANNED: DataTableColumn<Package> = { key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 }
function columnsFor(name: TabName): DataTableColumn<Package>[] {
if (name === 'held') return [...BASE_COLUMNS, { key: 'reason', header: 'Why', accessor: (p) => humanReason(p.vulnerabilities?.reason) }, SCANNED]
@@ -232,9 +227,10 @@ function open(pkg: Package) {
}
async function load() {
// Unfiltered: a package held because its scan failed has no findings, and the severity filter would drop it.
await store.fetchPackages()
await loadRows(rowQuery.value)
loaded.value = true
}
watch(rowQuery, load)
onMounted(load)
</script>
+9 -6
View File
@@ -12,7 +12,7 @@ import Insights from './Insights.vue'
import System from './System.vue'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { __resetSystem } from '@/lib/system'
import { usePackageStore } from '@/stores/packages'
import { serveRows } from '@/test/rowsServer'
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
import {
BYPASSES,
@@ -42,6 +42,7 @@ function respond(url: string) {
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
if (url.includes('layout=rows')) return { data: serveRows(url, PACKAGES) }
if (url.startsWith('/api/packages')) return { data: { packages: PACKAGES } }
throw new Error(`unexpected request: ${url}`)
}
@@ -109,7 +110,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
const { wrapper, problems } = await smoke(PackageList, '/packages')
expect(problems).toEqual([])
expect(wrapper.find('h1').text()).toBe('Packages')
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('4 of 4')
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–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)
@@ -119,7 +120,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
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.find('[data-testid="package-count"]').text()).toContain('1–1 of 1')
expect(wrapper.text()).toContain('left-pad')
expect(wrapper.text()).not.toContain('requests')
})
@@ -324,9 +325,10 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(nav.classes()).toContain('p-3')
})
it('PackageList still fetches through the store on mount', async () => {
it('PackageList asks for one page of rows on mount', async () => {
await smoke(PackageList, '/packages')
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
await flushPromises()
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(expect.stringContaining('/api/packages?layout=rows'))
})
})
@@ -347,7 +349,7 @@ describe('old URLs land on the new pages', () => {
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')
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–2 of 2')
})
})
@@ -378,6 +380,7 @@ describe('PyPI rows show the release version, not the file name', () => {
if (url.endsWith('/vulnerabilities')) {
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
}
if (url.includes('layout=rows')) return { data: serveRows(url, [SIX as never]) } as never
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
return respond(url) as never
})