feat(frontend): rebuild the bypass panel with library forms

Field, Input, Textarea, Checkbox, SegmentedControl and Dialog replace the
hand-written form. The status filter now applies the expired choice, which
the old click handler compared instead of assigning. Results show as toasts
and fetch failures as an ErrorState. Add a strict-mode smoke test per view.
This commit is contained in:
2026-11-23 02:29:14 +00:00
parent 54bc809f66
commit a5fd828410
2 changed files with 371 additions and 334 deletions
+187 -334
View File
@@ -1,347 +1,186 @@
<template> <template>
<div> <div class="flex flex-col gap-6">
<div class="flex justify-between items-center mb-8"> <PageHeader
<div> title="CVE bypass management"
<h2 class="text-3xl font-bold text-gray-900">CVE Bypass Management</h2> description="Manage temporary security bypasses for packages and CVEs."
<p class="text-gray-600 mt-1">Manage temporary security bypasses for packages and CVEs</p> >
</div> <template #actions>
<Button @click="showCreateModal = true" class="bg-green-600 hover:bg-green-700"> <Button :icon-start="faPlus" @click="showCreateModal = true">Create bypass</Button>
<i class="fas fa-plus mr-2"></i>Create Bypass </template>
</PageHeader>
<div class="flex flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-center">
<SegmentedControl v-model="activeFilter" :options="FILTER_OPTIONS" aria-label="Filter by status" />
<SegmentedControl v-model="typeFilter" :options="TYPE_OPTIONS" aria-label="Filter by type" />
<Button variant="outline" size="sm" :icon-start="faRotateRight" class="sm:ms-auto" @click="fetchBypasses">
Refresh
</Button> </Button>
</div> </div>
<!-- Filter Section --> <ErrorState
<div class="mb-6 flex flex-col sm:flex-row items-start sm:items-center gap-4"> v-if="error"
<div class="flex items-center gap-2"> variant="card"
<span class="text-sm font-medium text-gray-700">Filter:</span> title="Could not load bypasses"
<div class="flex gap-2"> :message="error"
<Button @retry="fetchBypasses"
@click="activeFilter = 'all'" />
:variant="activeFilter === 'all' ? 'default' : 'outline'"
size="sm"
>
All
</Button>
<Button
@click="activeFilter = 'active'"
:variant="activeFilter === 'active' ? 'default' : 'outline'"
size="sm"
>
<i class="fas fa-check-circle mr-1"></i>Active
</Button>
<Button
@click="activeFilter === 'expired'"
:variant="activeFilter === 'expired' ? 'default' : 'outline'"
size="sm"
>
<i class="fas fa-clock mr-1"></i>Expired
</Button>
</div>
</div>
<div class="flex items-center gap-2">
<span class="text-sm font-medium text-gray-700">Type:</span>
<div class="flex gap-2">
<Button
@click="typeFilter = ''"
:variant="typeFilter === '' ? 'default' : 'outline'"
size="sm"
>
All
</Button>
<Button
@click="typeFilter = 'cve'"
:variant="typeFilter === 'cve' ? 'default' : 'outline'"
size="sm"
>
CVE
</Button>
<Button
@click="typeFilter = 'package'"
:variant="typeFilter === 'package' ? 'default' : 'outline'"
size="sm"
>
Package
</Button>
</div>
</div>
<Button @click="fetchBypasses" variant="outline" size="sm" class="sm:ml-auto">
<i class="fas fa-sync-alt mr-2"></i>Refresh
</Button>
</div>
<!-- Error Alert --> <LoadingState v-if="loading" variant="table" label="Loading bypasses..." />
<Alert v-if="error" variant="destructive" class="mb-4">
<i class="fas fa-exclamation-circle mr-2"></i>
<AlertDescription>{{ error }}</AlertDescription>
</Alert>
<!-- Success Alert -->
<Alert v-if="successMessage" class="mb-4 bg-green-50 border-green-200">
<i class="fas fa-check-circle mr-2 text-green-600"></i>
<AlertDescription class="text-green-800">{{ successMessage }}</AlertDescription>
</Alert>
<!-- Loading State -->
<div v-if="loading" class="text-center py-12">
<i class="fas fa-spinner fa-spin text-4xl text-primary-600"></i>
<p class="mt-4 text-gray-600">Loading bypasses...</p>
</div>
<!-- Bypass List -->
<Card v-else> <Card v-else>
<CardContent class="p-6"> <CardContent>
<div v-if="filteredBypasses.length === 0" class="text-center py-12 text-gray-500"> <EmptyState
<i class="fas fa-shield-alt text-6xl mb-4"></i> v-if="filteredBypasses.length === 0"
<p class="text-xl">No bypasses found</p> :icon="faShieldHalved"
<p class="mt-2">Create a bypass to allow packages with known vulnerabilities</p> title="No bypasses found"
</div> description="Create a bypass to allow packages with known vulnerabilities."
<div v-else class="space-y-4"> />
<div <DataTable
v-for="bypass in filteredBypasses" v-else
:key="bypass.id" label="Bypasses"
class="border rounded-lg p-4 hover:bg-gray-50" layout="cards"
:class="bypass.active ? 'border-gray-200' : 'border-gray-300 bg-gray-50'" row-key="id"
> :columns="bypassColumns"
<div class="flex items-start justify-between"> :rows="filteredBypasses"
<div class="flex-1"> >
<div class="flex items-center gap-2 mb-2"> <template #cell-type="{ row }">
<Badge :variant="bypass.type === 'cve' ? 'default' : 'outline'"> <Badge :variant="row.type === 'cve' ? 'default' : 'outline'">{{ row.type === 'cve' ? 'CVE' : 'Package' }}</Badge>
{{ bypass.type.toUpperCase() }} </template>
</Badge> <template #cell-status="{ row }">
<Badge <span class="flex flex-wrap gap-1">
:class="bypass.active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'" <StatusBadge
> :status="row.active ? 'active' : 'inactive'"
{{ bypass.active ? 'ACTIVE' : 'INACTIVE' }} :tones="{ active: 'success', inactive: 'neutral' }"
</Badge> />
<Badge <StatusBadge v-if="isExpired(row.expires_at)" status="expired" :tones="{ expired: 'danger' }" />
v-if="isExpired(bypass.expires_at)" </span>
class="bg-red-100 text-red-800" </template>
> <template #cell-actions="{ row }">
EXPIRED <span class="flex gap-1">
</Badge> <IconButton :icon="faPen" :label="`Edit bypass for ${row.target}`" @click="editBypass(row)" />
</div> <IconButton :icon="faTrash" :label="`Delete bypass for ${row.target}`" @click="confirmDeleteBypass(row)" />
<h4 class="font-semibold text-lg text-gray-900">{{ bypass.target }}</h4> </span>
<p class="text-sm text-gray-600 mt-1">{{ bypass.reason }}</p> </template>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-3 text-sm text-gray-500"> </DataTable>
<div>
<i class="fas fa-user mr-1"></i>
<strong>Created by:</strong> {{ bypass.created_by }}
</div>
<div>
<i class="fas fa-calendar mr-1"></i>
<strong>Created:</strong> {{ formatDate(bypass.created_at) }}
</div>
<div>
<i class="fas fa-clock mr-1"></i>
<strong>Expires:</strong> {{ formatDate(bypass.expires_at) }}
</div>
<div v-if="bypass.applies_to">
<i class="fas fa-box mr-1"></i>
<strong>Applies to:</strong> {{ bypass.applies_to }}
</div>
</div>
</div>
<div class="flex items-center gap-2 ml-4">
<Button
@click="editBypass(bypass)"
variant="outline"
size="sm"
title="Edit bypass"
>
<i class="fas fa-edit"></i>
</Button>
<Button
@click="confirmDeleteBypass(bypass)"
variant="destructive"
size="sm"
title="Delete bypass"
>
<i class="fas fa-trash"></i>
</Button>
</div>
</div>
</div>
</div>
</CardContent> </CardContent>
</Card> </Card>
<!-- Create/Edit Bypass Modal -->
<Dialog v-model:open="showCreateModal"> <Dialog v-model:open="showCreateModal">
<DialogContent class="max-w-2xl"> <DialogContent size="lg">
<DialogHeader> <DialogHeader>
<DialogTitle>{{ editingBypass ? 'Edit' : 'Create' }} Bypass</DialogTitle> <DialogTitle>{{ editingBypass ? 'Edit' : 'Create' }} bypass</DialogTitle>
<DialogDescription> <DialogDescription>
{{ editingBypass ? 'Update bypass settings' : 'Create a temporary bypass for a CVE or package' }} {{ editingBypass ? 'Update the bypass settings.' : 'Create a temporary bypass for a CVE or package.' }}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div class="space-y-4 py-4"> <form class="flex flex-col gap-4" @submit.prevent="submitBypass">
<!-- Type Selection --> <Field v-if="!editingBypass" label="Bypass type">
<div v-if="!editingBypass"> <SegmentedControl v-model="bypassForm.type" :options="BYPASS_TYPE_OPTIONS" full-width />
<label class="text-sm font-medium text-gray-700 mb-2 block">Bypass Type</label> </Field>
<div class="flex gap-4">
<Button
@click="bypassForm.type = 'cve'"
:variant="bypassForm.type === 'cve' ? 'default' : 'outline'"
class="flex-1"
>
<i class="fas fa-bug mr-2"></i>CVE Bypass
</Button>
<Button
@click="bypassForm.type = 'package'"
:variant="bypassForm.type === 'package' ? 'default' : 'outline'"
class="flex-1"
>
<i class="fas fa-box mr-2"></i>Package Bypass
</Button>
</div>
</div>
<!-- Target --> <Field
<div v-if="!editingBypass"> v-if="!editingBypass"
<label class="text-sm font-medium text-gray-700 mb-2 block"> :label="bypassForm.type === 'cve' ? 'CVE ID' : 'Package'"
{{ bypassForm.type === 'cve' ? 'CVE ID' : 'Package' }} :hint="
</label> bypassForm.type === 'cve'
? 'Enter the CVE ID, for example CVE-2021-23337.'
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions.'
"
required
>
<Input <Input
v-model="bypassForm.target" v-model="bypassForm.target"
:placeholder="bypassForm.type === 'cve' ? 'CVE-2021-23337' : 'npm/[email protected]'" :placeholder="bypassForm.type === 'cve' ? 'CVE-2021-23337' : 'npm/[email protected]'"
class="w-full"
/> />
<p class="text-xs text-gray-500 mt-1"> </Field>
{{ bypassForm.type === 'cve' ? 'Enter the CVE ID (e.g., CVE-2021-23337)' : 'Enter package (e.g., npm/[email protected] or npm/lodash for all versions)' }}
</p>
</div>
<!-- Applies To (CVE only) --> <Field
<div v-if="!editingBypass && bypassForm.type === 'cve'"> v-if="!editingBypass && bypassForm.type === 'cve'"
<label class="text-sm font-medium text-gray-700 mb-2 block"> label="Applies to (optional)"
Applies To (Optional) hint="Limit this CVE bypass to one package. Leave empty to apply it to every package with this CVE."
</label> >
<Input <Input v-model="bypassForm.applies_to" placeholder="npm/[email protected]" />
v-model="bypassForm.applies_to" </Field>
placeholder="npm/[email protected]"
class="w-full"
/>
<p class="text-xs text-gray-500 mt-1">
Limit this CVE bypass to a specific package. Leave empty to apply to all packages with this CVE.
</p>
</div>
<!-- Reason --> <Field label="Reason" hint="Explain why this bypass is needed. It is kept for the audit trail." required>
<div> <Textarea v-model="bypassForm.reason" placeholder="No fix available, business critical dependency" />
<label class="text-sm font-medium text-gray-700 mb-2 block">Reason *</label> </Field>
<Input
v-model="bypassForm.reason"
placeholder="No fix available, business critical dependency"
class="w-full"
/>
<p class="text-xs text-gray-500 mt-1">
Explain why this bypass is needed (required for audit trail)
</p>
</div>
<!-- Created By --> <Field v-if="!editingBypass" label="Created by" required>
<div v-if="!editingBypass"> <Input v-model="bypassForm.created_by" placeholder="[email protected]" />
<label class="text-sm font-medium text-gray-700 mb-2 block">Created By *</label> </Field>
<Input
v-model="bypassForm.created_by"
placeholder="[email protected]"
class="w-full"
/>
</div>
<!-- Expires In --> <Field
<div> label="Expires in (hours)"
<label class="text-sm font-medium text-gray-700 mb-2 block">Expires In (Hours) *</label> hint="Hours until this bypass expires. 168 is 7 days and 720 is 30 days."
required
>
<Input <Input
v-model.number="bypassForm.expires_in_hours" :model-value="bypassForm.expires_in_hours"
type="number" type="number"
min="1" min="1"
placeholder="168" placeholder="168"
class="w-full" @update:model-value="setExpiresInHours"
/> />
<p class="text-xs text-gray-500 mt-1"> </Field>
How many hours until this bypass expires (e.g., 168 = 7 days, 720 = 30 days)
</p>
</div>
<!-- Active (Edit only) --> <Checkbox v-if="editingBypass" v-model="bypassForm.active" label="Active" />
<div v-if="editingBypass" class="flex items-center gap-2">
<input
type="checkbox"
v-model="bypassForm.active"
id="active-checkbox"
class="w-4 h-4"
/>
<label for="active-checkbox" class="text-sm font-medium text-gray-700">
Active
</label>
</div>
<!-- Notify on Expiry --> <Checkbox v-model="bypassForm.notify_on_expiry" label="Send a notification when the bypass expires" />
<div class="flex items-center gap-2">
<input
type="checkbox"
v-model="bypassForm.notify_on_expiry"
id="notify-checkbox"
class="w-4 h-4"
/>
<label for="notify-checkbox" class="text-sm font-medium text-gray-700">
Send notification when bypass expires
</label>
</div>
</div>
<DialogFooter> <DialogFooter>
<Button @click="closeCreateModal" variant="outline"> <Button variant="outline" @click="closeCreateModal">Cancel</Button>
Cancel <Button type="submit" :disabled="!isFormValid">{{ editingBypass ? 'Update' : 'Create' }} bypass</Button>
</Button> </DialogFooter>
<Button @click="submitBypass" :disabled="!isFormValid"> </form>
{{ editingBypass ? 'Update' : 'Create' }} Bypass
</Button>
</DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<!-- Delete Confirmation Dialog --> <ConfirmDialog
<Dialog v-model:open="showDeleteModal"> v-model:open="showDeleteModal"
<DialogContent> title="Delete bypass?"
<DialogHeader> :description="`Delete the bypass for ${bypassToDelete?.target}? This cannot be undone and the security check is re-enabled immediately.`"
<DialogTitle>Confirm Deletion</DialogTitle> confirm-label="Delete bypass"
<DialogDescription> tone="danger"
Are you sure you want to delete this bypass for <strong>{{ bypassToDelete?.target }}</strong>? destructive
This action cannot be undone and the security check will be re-enabled immediately. @confirm="deleteBypass"
</DialogDescription> />
</DialogHeader>
<DialogFooter>
<Button @click="showDeleteModal = false" variant="outline">
Cancel
</Button>
<Button @click="deleteBypass" variant="destructive">
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted } from 'vue' import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios' import axios from 'axios'
import { Button } from '@/components/ui/button'
import { import {
Badge,
Button,
Card,
CardContent,
Checkbox,
ConfirmDialog,
DataTable,
Dialog, Dialog,
DialogContent, DialogContent,
DialogDescription, DialogDescription,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@/components/ui/dialog' EmptyState,
import { Alert, AlertDescription } from '@/components/ui/alert' ErrorState,
import { Card, CardContent } from '@/components/ui/card' Field,
import { Badge } from '@/components/ui/badge' IconButton,
import { Input } from '@/components/ui/input' Input,
LoadingState,
PageHeader,
SegmentedControl,
StatusBadge,
Textarea,
useToastStore,
type DataTableColumn,
} from '@perfect-design/ui'
import { formatDate } from '@/lib/format'
import { faPen, faPlus, faRotateRight, faShieldHalved, faTrash } from '@/lib/icons'
interface Bypass { interface Bypass {
id: string id: string
@@ -358,17 +197,17 @@ interface Bypass {
const loading = ref(false) const loading = ref(false)
const error = ref<string | null>(null) const error = ref<string | null>(null)
const successMessage = ref<string | null>(null) const toasts = useToastStore()
const bypasses = ref<Bypass[]>([]) const bypasses = ref<Bypass[]>([])
const activeFilter = ref<'all' | 'active' | 'expired'>('all') const activeFilter = ref<'all' | 'active' | 'expired'>('all')
const typeFilter = ref<'' | 'cve' | 'package'>('') const typeFilter = ref<'all' | 'cve' | 'package'>('all')
const showCreateModal = ref(false) const showCreateModal = ref(false)
const showDeleteModal = ref(false) const showDeleteModal = ref(false)
const editingBypass = ref<Bypass | null>(null) const editingBypass = ref<Bypass | null>(null)
const bypassToDelete = ref<Bypass | null>(null) const bypassToDelete = ref<Bypass | null>(null)
const bypassForm = ref({ const EMPTY_FORM = {
type: 'cve' as 'cve' | 'package', type: 'cve' as 'cve' | 'package',
target: '', target: '',
reason: '', reason: '',
@@ -377,7 +216,9 @@ const bypassForm = ref({
applies_to: '', applies_to: '',
notify_on_expiry: false, notify_on_expiry: false,
active: true, active: true,
}) }
const bypassForm = ref({ ...EMPTY_FORM })
// Get API key from localStorage or prompt user // Get API key from localStorage or prompt user
const apiKey = ref<string>('') const apiKey = ref<string>('')
@@ -393,7 +234,7 @@ const filteredBypasses = computed(() => {
} }
// Filter by type // Filter by type
if (typeFilter.value) { if (typeFilter.value !== 'all') {
filtered = filtered.filter(b => b.type === typeFilter.value) filtered = filtered.filter(b => b.type === typeFilter.value)
} }
@@ -448,7 +289,7 @@ async function fetchBypasses() {
} else if (activeFilter.value === 'expired') { } else if (activeFilter.value === 'expired') {
params.append('include_expired', 'true') params.append('include_expired', 'true')
} }
if (typeFilter.value) { if (typeFilter.value !== 'all') {
params.append('type', typeFilter.value) params.append('type', typeFilter.value)
} }
@@ -476,8 +317,6 @@ async function submitBypass() {
if (!isFormValid.value) return if (!isFormValid.value) return
loading.value = true loading.value = true
error.value = null
successMessage.value = null
try { try {
if (editingBypass.value) { if (editingBypass.value) {
@@ -495,7 +334,7 @@ async function submitBypass() {
}, },
} }
) )
successMessage.value = 'Bypass updated successfully' toasts.success('Bypass updated')
} else { } else {
// Create new bypass // Create new bypass
await axios.post( await axios.post(
@@ -515,19 +354,14 @@ async function submitBypass() {
}, },
} }
) )
successMessage.value = 'Bypass created successfully' toasts.success('Bypass created')
} }
closeCreateModal() closeCreateModal()
await fetchBypasses() await fetchBypasses()
// Clear success message after 5 seconds
setTimeout(() => {
successMessage.value = null
}, 5000)
} catch (err: any) { } catch (err: any) {
console.error('Failed to submit bypass:', err) console.error('Failed to submit bypass:', err)
error.value = err.response?.data?.error?.message || err.message || 'Failed to save bypass' toasts.error('Could not save bypass', err.response?.data?.error?.message || err.message || 'Failed to save bypass')
} finally { } finally {
loading.value = false loading.value = false
} }
@@ -550,19 +384,15 @@ function editBypass(bypass: Bypass) {
function closeCreateModal() { function closeCreateModal() {
showCreateModal.value = false showCreateModal.value = false
editingBypass.value = null
bypassForm.value = {
type: 'cve',
target: '',
reason: '',
created_by: '',
expires_in_hours: 168,
applies_to: '',
notify_on_expiry: false,
active: true,
}
} }
// Also covers dismissal by Escape or the close button, so the next open never reuses an old edit.
watch(showCreateModal, (open) => {
if (open) return
editingBypass.value = null
bypassForm.value = { ...EMPTY_FORM }
})
function confirmDeleteBypass(bypass: Bypass) { function confirmDeleteBypass(bypass: Bypass) {
bypassToDelete.value = bypass bypassToDelete.value = bypass
showDeleteModal.value = true showDeleteModal.value = true
@@ -572,8 +402,6 @@ async function deleteBypass() {
if (!bypassToDelete.value) return if (!bypassToDelete.value) return
loading.value = true loading.value = true
error.value = null
successMessage.value = null
try { try {
await axios.delete(`/api/admin/bypasses/${bypassToDelete.value.id}`, { await axios.delete(`/api/admin/bypasses/${bypassToDelete.value.id}`, {
@@ -582,18 +410,13 @@ async function deleteBypass() {
}, },
}) })
successMessage.value = 'Bypass deleted successfully' toasts.success('Bypass deleted')
showDeleteModal.value = false showDeleteModal.value = false
bypassToDelete.value = null bypassToDelete.value = null
await fetchBypasses() await fetchBypasses()
// Clear success message after 5 seconds
setTimeout(() => {
successMessage.value = null
}, 5000)
} catch (err: any) { } catch (err: any) {
console.error('Failed to delete bypass:', err) console.error('Failed to delete bypass:', err)
error.value = err.response?.data?.error?.message || err.message || 'Failed to delete bypass' toasts.error('Could not delete bypass', err.response?.data?.error?.message || err.message || 'Failed to delete bypass')
} finally { } finally {
loading.value = false loading.value = false
} }
@@ -603,7 +426,37 @@ function isExpired(expiresAt: string): boolean {
return new Date(expiresAt) < new Date() return new Date(expiresAt) < new Date()
} }
function formatDate(date: string): string { const FILTER_OPTIONS = [
return new Date(date).toLocaleString() { value: 'all', label: 'All' },
{ value: 'active', label: 'Active' },
{ value: 'expired', label: 'Expired' },
]
const TYPE_OPTIONS = [
{ value: 'all', label: 'All' },
{ value: 'cve', label: 'CVE' },
{ value: 'package', label: 'Package' },
]
const BYPASS_TYPE_OPTIONS = [
{ value: 'cve', label: 'CVE bypass' },
{ value: 'package', label: 'Package bypass' },
]
const bypassColumns: DataTableColumn<Bypass>[] = [
{ key: 'target', header: 'Target', 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: 'applies_to', header: 'Applies to' },
{ key: 'actions', header: 'Actions', actions: true, accessor: () => '' },
]
function setExpiresInHours(value: string | number) {
bypassForm.value.expires_in_hours = Number(value)
} }
</script> </script>
+184
View File
@@ -0,0 +1,184 @@
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 App from '@/App.vue'
import Dashboard from './Dashboard.vue'
import PackageList from './PackageList.vue'
import PackageDetails from './PackageDetails.vue'
import VulnerablePackages from './VulnerablePackages.vue'
import BypassManagementPanel from './BypassManagementPanel.vue'
import Stats from './Stats.vue'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
import { usePackageStore } from '@/stores/packages'
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, VULNERABILITY_REPORT } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
vi.mock('axios')
const API_KEY_STORAGE = 'admin_api_key'
function respond(url: string) {
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
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.startsWith('/api/packages')) return { data: { packages: PACKAGES } }
throw new Error(`unexpected request: ${url}`)
}
let restore: (() => void) | undefined
beforeEach(() => {
setActivePinia(createPinia())
__resetRealtimeSingleton()
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
localStorage.setItem(API_KEY_STORAGE, 'test-key')
})
afterEach(() => {
restore?.()
restore = undefined
localStorage.clear()
vi.restoreAllMocks()
})
async function smoke(component: Parameters<typeof mountStrict>[0], path: string, props: Record<string, unknown> = {}) {
const router = await createTestRouter(path)
const pinia = createPinia()
setActivePinia(pinia)
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
const mounted = await mountStrict(component, { props, global: { plugins: [pinia, router] } })
restore = mounted.restore
return mounted
}
describe('view smoke tests (strict mode throw, fixture data)', () => {
it('Dashboard renders the tiles, chart, feed and recent packages', 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] } })
restore = r
await flushPromises()
expect(problems).toEqual([])
expect(wrapper.find('h1').text()).toBe('Dashboard')
expect(wrapper.text()).toContain('Total packages')
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 () => {
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')
})
it('PackageDetails renders the report, severity table and expanded row', 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')
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', ''))
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')
await flushPromises()
expect(wrapper.text()).toContain('Bypass active')
expect(wrapper.text()).toContain('No fix available')
})
it('VulnerablePackages lists the vulnerable fixture packages', async () => {
const { wrapper, problems } = await smoke(VulnerablePackages, '/vulnerable-packages')
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')
})
it('VulnerablePackages on the blocked route keeps only blocked packages', async () => {
const { wrapper, problems } = await smoke(VulnerablePackages, '/blocked-packages')
expect(problems).toEqual([])
expect(wrapper.find('h1').text()).toBe('Blocked packages')
expect(wrapper.text()).toContain('1 vulnerable version')
})
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.text()).toContain('CVE-2026-0002')
expect(wrapper.text()).toContain('Expired')
const create = wrapper.findAll('button').find((b) => b.text() === 'Create bypass')
await create!.trigger('click')
await flushPromises()
expect(document.body.textContent).toContain('Create a temporary bypass for a CVE or package.')
expect(document.body.querySelector('textarea')).not.toBeNull()
})
it('Stats renders totals, the storage tile and the registry table', async () => {
const { wrapper, problems } = await smoke(Stats, '/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)
})
it('VulnerabilityBadge prints the severity word for every tone', async () => {
const { wrapper, problems } = await smoke(VulnerabilityBadge, '/', {
scanned: true,
status: 'vulnerable',
counts: { critical: 1, high: 2, moderate: 3, low: 4 },
total: 10,
isBlocked: true,
})
expect(problems).toEqual([])
const text = wrapper.text()
for (const word of ['Blocked', 'Critical: 1', 'High: 2', 'Moderate: 3', 'Low: 4']) expect(text).toContain(word)
const tones = wrapper.findAll('[data-slot="status-badge"]').map((b) => b.attributes('data-tone'))
expect(tones).toEqual(['danger', 'danger', 'warning', 'info', 'neutral'])
})
it('App renders one banner, one main, a skip link first and the five sections', async () => {
const { wrapper, problems } = await smoke(App, '/')
expect(problems).toEqual([])
expect(document.body.querySelectorAll('header').length).toBe(1)
expect(document.body.querySelectorAll('main').length).toBe(1)
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(document.documentElement.getAttribute('data-style')).toBe('workbench')
})
it('PackageList still fetches through the store on mount', async () => {
await smoke(PackageList, '/packages')
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
})
})