Compare commits

..
12 Commits
Author SHA1 Message Date
lukaszraczylo 946bb7f75d fixup! fixup! fixup! fixes 2026-01-02 20:07:00 +00:00
lukaszraczylo b88c2e1575 fixup! fixup! fixes 2026-01-02 19:47:15 +00:00
lukaszraczylo 1da6c3d0a3 fixup! fixes 2026-01-02 19:10:04 +00:00
lukaszraczylo c727465646 fixes 2026-01-02 18:44:10 +00:00
lukaszraczylo ce5a8fbffd fixes 2026-01-02 18:20:15 +00:00
lukaszraczylo 0f7c29c3ef fixes 2026-01-02 18:05:03 +00:00
lukaszraczylo 14c1e044f4 fixup! fixes 2026-01-02 17:51:31 +00:00
lukaszraczylo 1f6594d1e3 fixes 2026-01-02 17:31:03 +00:00
lukaszraczylo e6edf654b9 fixes 2026-01-02 15:55:36 +00:00
lukaszraczylo c6edad4402 fixes 2026-01-02 15:29:43 +00:00
lukaszraczylo 1cbf6c5d9e fixes 2026-01-02 11:49:08 +00:00
lukaszraczylo 3b8e171fdb fixes 2026-01-02 04:02:02 +00:00
424 changed files with 11490 additions and 44191 deletions
+7 -9
View File
@@ -1,4 +1,4 @@
name: Update dependencies
name: Autoupdate go.mod and go.sum
on:
workflow_dispatch:
@@ -6,16 +6,14 @@ on:
- cron: "0 3 * * *"
permissions:
actions: write
contents: write
issues: write
actions: write
pull-requests: write
jobs:
update:
uses: lukaszraczylo/shared-actions/.github/workflows/renovate-autoupdate.yaml@main
autoupdate:
uses: lukaszraczylo/shared-actions/.github/workflows/go-autoupdate.yaml@main
with:
go-version: ">=1.27"
node-working-directory: frontend
release-workflow: release.yaml
runner: self-hosted
go-version: ">=1.25"
release-workflow: "release.yaml"
secrets: inherit
+1 -7
View File
@@ -9,14 +9,8 @@ on:
- "**"
- "!main"
permissions:
contents: read
pull-requests: write
security-events: write
jobs:
pr-checks:
uses: lukaszraczylo/shared-actions/.github/workflows/go-pr.yaml@main
with:
go-version: ">=1.27"
runner: self-hosted
go-version: "1.25"
+18 -14
View File
@@ -20,22 +20,16 @@ permissions:
jobs:
release:
uses: lukaszraczylo/shared-actions/.github/workflows/go-release-cgo.yaml@main
uses: lukaszraczylo/shared-actions/.github/workflows/go-release.yaml@main
with:
go-version: ">=1.27"
# Enable frontend build
node-enabled: true
node-version: "20"
node-build-script: "cd frontend && npm install -g pnpm && pnpm install --frozen-lockfile && pnpm run build"
node-output-path: "frontend/dist"
node-cache-dependency-path: "frontend/pnpm-lock.yaml"
runner: self-hosted
go-version: "1.25"
docker-enabled: true
secrets: inherit
benchmark:
name: Publish Benchmarks
needs: release
runs-on: self-hosted
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -46,7 +40,7 @@ jobs:
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: ">=1.27"
go-version: "1.25"
- name: Run benchmarks
run: go test -bench=. -benchmem ./... -run=^# | tee output.txt
@@ -56,17 +50,27 @@ jobs:
with:
tool: "go"
output-file-path: output.txt
fail-on-alert: false
fail-on-alert: true
github-token: ${{ secrets.GITHUB_TOKEN }}
comment-on-alert: true
summary-always: true
auto-push: true
auto-push: false
benchmark-data-dir-path: "docs/bench"
- name: Push benchmark results
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add docs/bench
git diff --staged --quiet || git commit -m "Update benchmark results"
git push origin main
publish-helm-chart:
name: Publish Helm Chart
needs: release
runs-on: self-hosted
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
-6
View File
@@ -72,7 +72,6 @@ tests/fixtures/temp/
# Markdown files (except README.md)
*.md
!README.md
!lean4/FINDINGS.md
/gohoarder
*.log
@@ -80,8 +79,3 @@ tests/fixtures/temp/
test-go-proxy
frontend/node_modules
data/storage
*.pid
# Local worktrees
.worktrees/
lean4/.lake
+52 -138
View File
@@ -7,91 +7,30 @@ project_name: gohoarder
before:
hooks:
- go mod tidy
# Download and setup Zig for cross-compilation (Linux only)
- bash -c 'if [ "$(uname -s)" = "Linux" ]; then wget https://ziglang.org/download/0.15.2/zig-x86_64-linux-0.15.2.tar.xz -O /tmp/zig.tar.xz && ls -lh /tmp/zig.tar.xz && tar -xvf /tmp/zig.tar.xz -C /tmp && echo "/tmp/zig-x86_64-linux-0.15.2" >> $GITHUB_PATH; fi'
# Generate semantic version if not provided via git tag
# This script can be used by CI/CD to inject custom versions
# Usage: export GORELEASER_CURRENT_TAG=$(./script/generate-version.sh)
# - ./script/generate-version.sh
# Build configuration
# All binaries built using Zig for consistent cross-compilation
# Zig handles CGO cross-compilation without platform-specific toolchains
# Binaries are injected into Docker images (no Docker compilation)
builds:
- id: gohoarder
main: ./cmd/gohoarder
binary: gohoarder
env:
- CGO_ENABLED=1
tags:
- fts5
flags:
- -trimpath
- CGO_ENABLED=0
goos:
- linux
- darwin
- windows
goarch:
- amd64
- arm64
ldflags:
- -s -w
- -X github.com/lukaszraczylo/gohoarder/internal/version.Version={{.Version}}
- -X github.com/lukaszraczylo/gohoarder/internal/version.GitCommit={{.ShortCommit}}
- -X github.com/lukaszraczylo/gohoarder/internal/version.BuildTime={{.Date}}
goos:
- linux
- darwin
goarch:
- amd64
- arm64
ignore:
- goos: darwin
goarch: amd64
overrides:
# Use Zig only for Linux cross-compilation
- goos: linux
goarch: amd64
env:
- CGO_ENABLED=1
- CC=/tmp/zig-x86_64-linux-0.15.2/zig cc -target x86_64-linux-musl
- CXX=/tmp/zig-x86_64-linux-0.15.2/zig c++ -target x86_64-linux-musl
- goos: linux
goarch: arm64
env:
- CGO_ENABLED=1
- CC=/tmp/zig-x86_64-linux-0.15.2/zig cc -target aarch64-linux-musl
- CXX=/tmp/zig-x86_64-linux-0.15.2/zig c++ -target aarch64-linux-musl
# darwin/arm64 builds natively on macOS runner (no Zig)
- id: migrate
main: ./cmd/migrate
binary: migrate
env:
- CGO_ENABLED=1
tags:
- fts5
flags:
- -trimpath
ldflags:
- -s -w
- -X main.Version={{.Version}}
- -X main.GitCommit={{.ShortCommit}}
- -X main.BuildTime={{.Date}}
goos:
- linux
- darwin
goarch:
- amd64
- arm64
ignore:
- goos: darwin
goarch: amd64
overrides:
# Use Zig only for Linux cross-compilation
- goos: linux
goarch: amd64
env:
- CGO_ENABLED=1
- CC=/tmp/zig-x86_64-linux-0.15.2/zig cc -target x86_64-linux-musl
- CXX=/tmp/zig-x86_64-linux-0.15.2/zig c++ -target x86_64-linux-musl
- goos: linux
goarch: arm64
env:
- CGO_ENABLED=1
- CC=/tmp/zig-x86_64-linux-0.15.2/zig cc -target aarch64-linux-musl
- CXX=/tmp/zig-x86_64-linux-0.15.2/zig c++ -target aarch64-linux-musl
# darwin/arm64 builds natively on macOS runner (no Zig)
# Archives for releases
archives:
@@ -148,24 +87,8 @@ release:
prerelease: auto
# Docker images (v2 - modern syntax)
# Uses PRE-BUILT binaries from native builds (no Docker compilation - much faster!)
# GoReleaser injects the platform-specific binary into each Docker image automatically
# This avoids slow QEMU emulation for cross-architecture builds
#
# Split/Merge Build Support (GoReleaser Pro):
# - Run `goreleaser release --split` on multiple CI runners in parallel
# - Each runner builds a subset of targets (e.g., runner 1: linux/amd64, runner 2: linux/arm64)
# - Run `goreleaser release --merge` to combine all partial builds into final release
# - Significantly speeds up builds by parallelizing across multiple machines
#
# Binary Path Convention:
# - Binaries must be in linux/${TARGETARCH}/ subdirectory format
# - GoReleaser automatically places binaries there when using --split
# - COPY linux/${TARGETARCH}/binary_name in Dockerfiles
dockers_v2:
# 1. Application Engine - Main GoHoarder server
# Uses pre-built binary from 'gohoarder' build (no Docker compilation)
# linux/arm64 binary is cross-compiled using Zig (fast, no QEMU!)
- id: gohoarder-server
ids:
- gohoarder
@@ -178,21 +101,21 @@ dockers_v2:
- linux/amd64
- linux/arm64
dockerfile: Dockerfile.server
flags:
- "--pull"
- "--label=org.opencontainers.image.title=GoHoarder Server"
- "--label=org.opencontainers.image.description=Universal package cache proxy server"
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.version={{ .Version }}"
- "--label=org.opencontainers.image.created={{ .Date }}"
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
labels:
org.opencontainers.image.title: GoHoarder Server
org.opencontainers.image.description: Universal package cache proxy server
org.opencontainers.image.url: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.source: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.version: "{{ .Version }}"
org.opencontainers.image.created: "{{ .Date }}"
org.opencontainers.image.revision: "{{ .FullCommit }}"
extra_files:
- config.yaml.example
# 2. Website - Frontend Dashboard
# Note: Frontend is pre-built on CI runner and injected via frontend/dist
- id: gohoarder-frontend
ids:
- gohoarder
images:
- ghcr.io/lukaszraczylo/gohoarder-frontend
tags:
@@ -202,21 +125,18 @@ dockers_v2:
- linux/amd64
- linux/arm64
dockerfile: Dockerfile.frontend
flags:
- "--pull"
- "--label=org.opencontainers.image.title=GoHoarder Frontend"
- "--label=org.opencontainers.image.description=GoHoarder web dashboard"
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.version={{ .Version }}"
- "--label=org.opencontainers.image.created={{ .Date }}"
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
labels:
org.opencontainers.image.title: GoHoarder Frontend
org.opencontainers.image.description: GoHoarder web dashboard
org.opencontainers.image.url: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.source: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.version: "{{ .Version }}"
org.opencontainers.image.created: "{{ .Date }}"
org.opencontainers.image.revision: "{{ .FullCommit }}"
extra_files:
- frontend/dist
- frontend
# 3. Scanning Engine - Background scanner worker
# Uses pre-built binary from 'gohoarder' build (no Docker compilation)
# linux/arm64 binary is cross-compiled using Zig (fast, no QEMU!)
- id: gohoarder-scanner
ids:
- gohoarder
@@ -229,44 +149,38 @@ dockers_v2:
- linux/amd64
- linux/arm64
dockerfile: Dockerfile.scanner
flags:
- "--pull"
- "--label=org.opencontainers.image.title=GoHoarder Scanner"
- "--label=org.opencontainers.image.description=GoHoarder vulnerability scanning engine"
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.version={{ .Version }}"
- "--label=org.opencontainers.image.created={{ .Date }}"
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
labels:
org.opencontainers.image.title: GoHoarder Scanner
org.opencontainers.image.description: GoHoarder vulnerability scanning engine
org.opencontainers.image.url: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.source: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.version: "{{ .Version }}"
org.opencontainers.image.created: "{{ .Date }}"
org.opencontainers.image.revision: "{{ .FullCommit }}"
extra_files:
- config.yaml.example
# 4. Migration Engine - Database migration tool
# Uses pre-built binary from 'migrate' build (no Docker compilation)
# linux/arm64 binary is cross-compiled using Zig (fast, no QEMU!)
- id: gohoarder-migrate
# 4. Gateway - Nginx reverse proxy for unified deployment
- id: gohoarder-gateway
ids:
- migrate
- gohoarder
images:
- ghcr.io/lukaszraczylo/gohoarder-migrate
- ghcr.io/lukaszraczylo/gohoarder-gateway
tags:
- "{{ .Version }}"
- latest
platforms:
- linux/amd64
- linux/arm64
dockerfile: Dockerfile.migrate
flags:
- "--pull"
- "--label=org.opencontainers.image.title=GoHoarder Migrate"
- "--label=org.opencontainers.image.description=Database migration tool for GoHoarder V2 schema"
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
- "--label=org.opencontainers.image.version={{ .Version }}"
- "--label=org.opencontainers.image.created={{ .Date }}"
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
extra_files:
- migrations
dockerfile: Dockerfile.gateway
labels:
org.opencontainers.image.title: GoHoarder Gateway
org.opencontainers.image.description: Nginx reverse proxy for unified GoHoarder deployment
org.opencontainers.image.url: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.source: https://github.com/lukaszraczylo/gohoarder
org.opencontainers.image.version: "{{ .Version }}"
org.opencontainers.image.created: "{{ .Date }}"
org.opencontainers.image.revision: "{{ .FullCommit }}"
# Artifact signing with cosign
signs:
+33 -110
View File
@@ -1,15 +1,28 @@
# Website - Frontend Dashboard with integrated reverse proxy
# Combines frontend serving and backend proxy (previously separate gateway)
# EXPECTS: Pre-built frontend files in frontend/dist/ directory
# Website - Frontend Dashboard
# Build stage
FROM node:20-alpine AS builder
FROM mirror.gcr.io/library/nginx:1.31.9-alpine@sha256:fb4658584bd9a916ffb6f6e365f97c25cfdb2923801f551ea08356e695f14ff7
WORKDIR /build
# Copy frontend source
COPY frontend/package.json frontend/pnpm-lock.yaml ./
COPY frontend/ ./
# Install pnpm and dependencies
RUN npm install -g pnpm && \
pnpm install --frozen-lockfile
# Build the frontend
RUN pnpm run build
# Production stage
FROM nginx:alpine
# Install envsubst for runtime configuration
RUN apk add --no-cache gettext
# Copy pre-built frontend files
# These are built on the CI runner and injected via extra_files
COPY frontend/dist /usr/share/nginx/html
# Copy built frontend
COPY --from=builder /build/dist /usr/share/nginx/html
# Create runtime config injection script
RUN cat > /docker-entrypoint.d/40-inject-config.sh <<'EOF'
@@ -35,101 +48,21 @@ EOF
RUN chmod +x /docker-entrypoint.d/40-inject-config.sh
# Create nginx templates directory and configuration template with backend proxy support
RUN mkdir -p /etc/nginx/templates && \
cat > /etc/nginx/templates/default.conf.template <<'EOF'
# Upstream backend server
upstream backend {
server ${BACKEND_HOST}:${BACKEND_PORT};
keepalive 32;
}
# Cache configuration
proxy_cache_path /var/cache/nginx/static levels=1:2 keys_zone=static_cache:10m max_size=100m inactive=60m use_temp_path=off;
# Copy nginx configuration
RUN cat > /etc/nginx/conf.d/default.conf <<'EOF'
server {
listen 80;
server_name ${SERVER_NAME};
server_name _;
root /usr/share/nginx/html;
index index.html;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Client body size for package uploads
client_max_body_size 500M;
client_body_timeout 300s;
# Logging
access_log /var/log/nginx/access.log combined;
error_log /var/log/nginx/error.log warn;
# Compression
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
# API endpoints - proxy to backend
location /api/ {
# Proxy settings
proxy_pass http://backend;
proxy_http_version 1.1;
# Headers
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header Connection "";
# The backend authenticates by API-key header; browser session cookies only bloat the request.
proxy_set_header Cookie "";
# Timeouts for long-running operations
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
# Buffer settings
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
# Health check endpoint
location /health {
proxy_pass http://backend/health;
proxy_http_version 1.1;
proxy_set_header Connection "";
access_log off;
}
# The package endpoints are not part of the dashboard and stay on the
# backend Service. A catch-all 404 keeps them off the SPA fallback below.
location ~ ^/(npm|pypi|go|metrics)(/|$) {
return 404;
}
# WebSocket support
location /ws {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Cookie "";
# WebSocket timeouts
proxy_connect_timeout 7d;
proxy_send_timeout 7d;
proxy_read_timeout 7d;
# SPA routing
location / {
try_files $uri $uri/ /index.html;
}
# Runtime configuration endpoint
@@ -139,25 +72,19 @@ server {
add_header Expires "0";
}
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Frontend SPA - serve index.html for all other routes
location / {
# index.html names the hashed bundles; a cached copy keeps serving the previous release.
add_header Cache-Control "no-cache" always;
try_files $uri $uri/ /index.html;
}
}
EOF
# Create cache directory
RUN mkdir -p /var/cache/nginx/static && \
chown -R nginx:nginx /var/cache/nginx
# Expose port
EXPOSE 80
@@ -168,10 +95,6 @@ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
# Environment variables with defaults
ENV API_BASE_URL=/api \
APP_VERSION=unknown \
APP_NAME=GoHoarder \
BACKEND_HOST=gohoarder-server \
BACKEND_PORT=8080 \
SERVER_NAME=_
APP_NAME=GoHoarder
# Use nginx template substitution and start nginx
CMD ["/bin/sh", "-c", "envsubst '$$BACKEND_HOST $$BACKEND_PORT $$SERVER_NAME' < /etc/nginx/templates/default.conf.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"]
CMD ["nginx", "-g", "daemon off;"]
+197
View File
@@ -0,0 +1,197 @@
# Gateway - Nginx reverse proxy for unified deployment
# Routes traffic between frontend and backend under single vhost
FROM nginx:alpine
# Install envsubst for runtime configuration
RUN apk add --no-cache gettext
# Copy nginx configuration template
COPY <<'EOF' /etc/nginx/templates/default.conf.template
# Upstream servers
upstream backend {
server ${BACKEND_HOST}:${BACKEND_PORT};
keepalive 32;
}
upstream frontend {
server ${FRONTEND_HOST}:${FRONTEND_PORT};
keepalive 32;
}
# Rate limiting zones
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=download_limit:10m rate=5r/s;
# Cache configuration
proxy_cache_path /var/cache/nginx/static levels=1:2 keys_zone=static_cache:10m max_size=100m inactive=60m use_temp_path=off;
server {
listen 80;
server_name ${SERVER_NAME};
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Client body size for package uploads
client_max_body_size 500M;
client_body_timeout 300s;
# Logging
access_log /var/log/nginx/access.log combined;
error_log /var/log/nginx/error.log warn;
# API endpoints - proxy to backend
location /api/ {
# Rate limiting
limit_req zone=api_limit burst=20 nodelay;
# Proxy settings
proxy_pass http://backend/;
proxy_http_version 1.1;
# Headers
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
# Connection reuse
proxy_set_header Connection "";
# Timeouts for long-running operations
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
# Buffer settings
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
# Health check endpoint
location /health {
proxy_pass http://backend/health;
proxy_http_version 1.1;
proxy_set_header Connection "";
access_log off;
}
# Metrics endpoint (optional - may want to restrict access)
location /metrics {
# Uncomment to restrict to internal networks
# allow 10.0.0.0/8;
# allow 172.16.0.0/12;
# allow 192.168.0.0/16;
# deny all;
proxy_pass http://backend/metrics;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# Package download endpoints with rate limiting
location ~ ^/(npm|pypi|go)/ {
limit_req zone=download_limit burst=10 nodelay;
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
# Extended timeouts for package downloads
proxy_connect_timeout 60s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
# Large buffer for package downloads
proxy_buffering on;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
# Frontend - serve SPA
location / {
proxy_pass http://frontend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
# Cache static assets
proxy_cache static_cache;
proxy_cache_valid 200 1h;
proxy_cache_bypass $http_cache_control;
add_header X-Cache-Status $upstream_cache_status;
}
# WebSocket support (if needed for future features)
location /ws/ {
proxy_pass http://backend/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket timeouts
proxy_connect_timeout 7d;
proxy_send_timeout 7d;
proxy_read_timeout 7d;
}
}
# HTTPS server (uncomment and configure SSL certificates)
# server {
# listen 443 ssl http2;
# server_name ${SERVER_NAME};
#
# ssl_certificate /etc/nginx/ssl/cert.pem;
# ssl_certificate_key /etc/nginx/ssl/key.pem;
#
# # SSL configuration
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# ssl_session_cache shared:SSL:10m;
# ssl_session_timeout 10m;
#
# # Include all location blocks from above
# # ... (copy from HTTP server block)
# }
EOF
# Create cache directory
RUN mkdir -p /var/cache/nginx/static && \
chown -R nginx:nginx /var/cache/nginx
# Expose port
EXPOSE 80 443
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD wget --quiet --tries=1 --spider http://localhost/health || exit 1
# Environment variables with defaults
ENV BACKEND_HOST=gohoarder-server \
BACKEND_PORT=8080 \
FRONTEND_HOST=gohoarder-frontend \
FRONTEND_PORT=80 \
SERVER_NAME=_
# Use nginx with template substitution
CMD ["/bin/sh", "-c", "envsubst '$$BACKEND_HOST $$BACKEND_PORT $$FRONTEND_HOST $$FRONTEND_PORT $$SERVER_NAME' < /etc/nginx/templates/default.conf.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"]
-37
View File
@@ -1,37 +0,0 @@
# Migration Engine - Database Migration Tool
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETARCH
# Install runtime dependencies (including CGO/SQLite dependencies)
RUN apk add --no-cache \
ca-certificates \
postgresql-client \
mysql-client \
busybox-extras \
sqlite-libs \
musl \
&& update-ca-certificates
# Create non-root user
RUN addgroup -g 1000 gohoarder && \
adduser -D -u 1000 -G gohoarder gohoarder
# Copy pre-built binary from GoReleaser
# GoReleaser will automatically inject the correct binary for the target platform
# In split/merge mode, binaries are in linux/${TARGETARCH}/ subdirectories
COPY linux/${TARGETARCH}/migrate /usr/local/bin/migrate
RUN chmod +x /usr/local/bin/migrate
# Copy migration SQL files
COPY migrations /migrations
WORKDIR /app
USER gohoarder
# Run migrations
ENTRYPOINT ["/usr/local/bin/migrate"]
CMD ["--action=migrate"]
+17 -41
View File
@@ -1,12 +1,10 @@
# Scanning Engine - Background Scanner Worker
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETOS
ARG TARGETARCH
# Install scanning tools and runtime dependencies (including CGO/SQLite dependencies)
FROM alpine:latest
# Install scanning tools and runtime dependencies
RUN apk add --no-cache \
ca-certificates \
tzdata \
@@ -14,54 +12,32 @@ RUN apk add --no-cache \
curl \
wget \
bash \
sqlite-libs \
musl \
python3 \
py3-pip \
npm \
go \
&& update-ca-certificates
# Install Trivy for container scanning
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/v0.76.2/contrib/install.sh | sh -s -- -b /usr/local/bin v0.76.2
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# Install Grype for vulnerability scanning
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/v0.121.2/install.sh | sh -s -- -b /usr/local/bin v0.121.2
# Install govulncheck for Go vulnerability scanning
RUN go install golang.org/x/vuln/cmd/[email protected] && \
mv /root/go/bin/govulncheck /usr/local/bin/
# Install pip-audit for Python package vulnerability scanning
RUN pip3 install --no-cache-dir pip-audit==2.10.1 --break-system-packages
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
# Create non-root user
RUN addgroup -g 1000 scanner && \
adduser -D -u 1000 -G scanner scanner
# Create necessary directories with proper permissions
RUN mkdir -p /var/cache/gohoarder \
/var/lib/gohoarder/metadata \
/var/lib/trivy \
/tmp/gohoarder && \
chown -R scanner:scanner /var/cache/gohoarder \
/var/lib/gohoarder \
/var/lib/trivy \
/tmp/gohoarder && \
chmod -R 750 /var/cache/gohoarder \
/var/lib/gohoarder \
/var/lib/trivy
# Create necessary directories
RUN mkdir -p /data/cache /data/scans && \
chown -R scanner:scanner /data
# Copy pre-built binary from GoReleaser
# GoReleaser will automatically inject the correct binary for the target platform
# In split/merge mode, binaries are in linux/${TARGETARCH}/ subdirectories
COPY linux/${TARGETARCH}/gohoarder /usr/local/bin/gohoarder
# Copy binary (from platform-specific path)
ARG TARGETOS
ARG TARGETARCH
COPY ${TARGETOS}/${TARGETARCH}/gohoarder /usr/local/bin/gohoarder
RUN chmod +x /usr/local/bin/gohoarder
# Copy example config
COPY config.yaml.example /etc/gohoarder/config.yaml.example
WORKDIR /var/cache/gohoarder
WORKDIR /data
USER scanner
# Expose metrics port
@@ -77,7 +53,7 @@ ENV SCANNER_MODE=true \
SCANNER_INTERVAL=300
# Run the scanner in background mode
# The scanner runs the same serve command but uses SCANNER_MODE env var
# and configuration to determine its role
# Note: You may need to add a scanner-specific command to your CLI
# For now, this assumes the serve command can run in scanner mode
ENTRYPOINT ["/usr/local/bin/gohoarder"]
CMD ["serve"]
CMD ["serve", "--scanner-only"]
+13 -23
View File
@@ -1,43 +1,33 @@
# Application Engine - Main GoHoarder Server
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
# Application Engine - GoHoarder Server
ARG TARGETOS
ARG TARGETARCH
# Install runtime dependencies (CGO/SQLite requires these)
FROM alpine:latest
# Install runtime dependencies
RUN apk add --no-cache \
ca-certificates \
tzdata \
sqlite-libs \
musl \
&& update-ca-certificates
# Create non-root user
RUN addgroup -g 1000 gohoarder && \
adduser -D -u 1000 -G gohoarder gohoarder
# Create necessary directories with proper permissions
RUN mkdir -p /var/cache/gohoarder \
/var/lib/gohoarder/metadata \
/tmp/gohoarder && \
chown -R gohoarder:gohoarder /var/cache/gohoarder \
/var/lib/gohoarder \
/tmp/gohoarder && \
chmod -R 750 /var/cache/gohoarder \
/var/lib/gohoarder
# Create necessary directories
RUN mkdir -p /data/cache /data/metadata && \
chown -R gohoarder:gohoarder /data
# Copy pre-built binary from GoReleaser
# GoReleaser will automatically inject the correct binary for the target platform
# In split/merge mode, binaries are in linux/${TARGETARCH}/ subdirectories
COPY linux/${TARGETARCH}/gohoarder /usr/local/bin/gohoarder
# Copy binary (from platform-specific path)
ARG TARGETOS
ARG TARGETARCH
COPY ${TARGETOS}/${TARGETARCH}/gohoarder /usr/local/bin/gohoarder
RUN chmod +x /usr/local/bin/gohoarder
# Copy example config
COPY config.yaml.example /etc/gohoarder/config.yaml.example
WORKDIR /var/cache/gohoarder
WORKDIR /data
USER gohoarder
# Expose ports
+6 -13
View File
@@ -78,24 +78,17 @@ clean: ## Clean build artifacts
@rm -f *.db *.db-shm *.db-wal
@echo "Clean complete"
clean-db: ## Clean all local cache and database files (requires confirmation)
clean-db: ## Clean all local cache and database files (from config.yaml paths)
@echo "WARNING: This will delete all cached packages and scan results!"
@echo "Paths to be cleaned:"
@echo "Paths from config.yaml:"
@echo " - ./data/storage (package cache)"
@echo " - ./data/gohoarder.db and gohoarder.db (metadata database)"
@echo " - ./data/gohoarder.db (metadata database)"
@echo " - /tmp/trivy (Trivy cache)"
@echo ""
@printf "Are you sure you want to continue? [y/N] " && read confirm && [ "$$confirm" = "y" ] || (echo "Cancelled." && exit 1)
@read -p "Are you sure you want to continue? [y/N] " confirm && [ "$$confirm" = "y" ] || exit 1
@echo "Cleaning database and cache..."
@rm -rf ./data/storage ./data
@rm -f gohoarder.db gohoarder.db-shm gohoarder.db-wal
@rm -rf /tmp/trivy
@echo "Database and cache cleaned successfully"
clean-db-force: ## Clean all local cache and database files (no confirmation)
@echo "Cleaning database and cache..."
@rm -rf ./data/storage ./data
@rm -f gohoarder.db gohoarder.db-shm gohoarder.db-wal
@rm -rf ./data/storage
@rm -f ./data/gohoarder.db ./data/gohoarder.db-shm ./data/gohoarder.db-wal
@rm -rf /tmp/trivy
@echo "Database and cache cleaned successfully"
+6 -45
View File
@@ -193,7 +193,6 @@ server:
host: "0.0.0.0"
read_timeout: "5m"
write_timeout: "5m"
allowed_origins: [] # Browser origins allowed to use /api and /ws; empty = same-origin only
storage:
backend: "filesystem" # Options: filesystem, s3, smb
@@ -234,12 +233,7 @@ security:
enabled: true
cache:
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
pypi: 12h
cleanup_interval: 1h
default_ttl: 86400 # 24 hours in seconds
logging:
level: "info" # debug, info, warn, error
@@ -251,17 +245,6 @@ upstream:
go: "https://proxy.golang.org"
```
#### Cache cleanup
Every `cleanup_interval` the cleanup run removes:
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
- **Deleted rows.** Evicting or deleting a package marks its database row deleted. Rows deleted longer ago than `deleted_retention` (default `720h`, 30 days) are removed for good, in batches of 500. Download history and the daily trend snapshots are kept. Set `deleted_retention: 0` to keep every row.
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
### Environment Variables
All configuration values can be overridden with environment variables:
@@ -484,7 +467,7 @@ npm config set registry http://localhost:8080/npm
pip config set global.index-url http://localhost:8080/pypi/simple
# Install with credentials in request (pip handles auth)
pip install --index-url http://username:password@localhost:8080/pypi/simple private-package //trufflehog:ignore
pip install --index-url http://username:password@localhost:8080/pypi/simple private-package
```
**AWS CodeArtifact:**
@@ -501,7 +484,7 @@ pip install --index-url http://aws:$CODEARTIFACT_AUTH_TOKEN@localhost:8080/pypi/
```bash
# Configure pip to use GitHub Packages through GoHoarder
pip install --index-url http://USERNAME:GITHUB_TOKEN@localhost:8080/pypi/simple your-private-package //trufflehog:ignore
pip install --index-url http://USERNAME:GITHUB_TOKEN@localhost:8080/pypi/simple your-private-package
```
#### Go Private Modules
@@ -893,29 +876,10 @@ Access the web dashboard at **http://localhost:8080**
**List Packages:**
```bash
GET /api/packages
GET /api/packages?page=1&page_size=25
GET /api/packages?registry=npm&q=axios&page_size=25
GET /api/packages?sort=cached_at&order=desc&page_size=10
GET /api/packages?registry=npm
GET /api/packages?status=vulnerable
```
The dashboard groups versions under a package, so paging counts packages (a
registry and name pair), not rows. Without `page` and `page_size` the call
returns every package in one response, with no row cap.
| Parameter | Meaning |
|---|---|
| `page` | 1-based page of groups. Default 1. |
| `page_size` | Groups per page. Default 25 when `page` is set, at most 200. |
| `registry` | Only this registry, for example `npm`, `pypi` or `go`. |
| `q` | Case-insensitive search in name, version and release version. |
| `sort` | `name` (default, ascending), `cached_at`, `downloads` or `size` (both descending). |
| `order` | `asc` or `desc`, to override the default direction of `sort`. |
`packages` holds every version row of each group on the page, in group order
and newest first within a group. `total` is the number of rows returned.
`total_groups` is the number of groups that match the filters across all pages.
A paged response also echoes `page` and `page_size`.
**Package Details:**
```bash
GET /api/packages/:registry/:name/:version
@@ -945,10 +909,7 @@ GET /api/packages/:registry/:name/:version
}
}
],
"total": 1,
"total_groups": 42,
"page": 1,
"page_size": 25
"total": 42
}
```
+3 -4
View File
@@ -1,4 +1,3 @@
// Package commands hosts the cobra commands wired into the gohoarder CLI.
package commands
import (
@@ -36,11 +35,11 @@ func runServe(cmd *cobra.Command, args []string) error {
}
// Initialize logger
if logErr := logger.Init(logger.Config{
if err := logger.Init(logger.Config{
Level: cfg.Logging.Level,
Format: cfg.Logging.Format,
}); logErr != nil {
return fmt.Errorf("failed to initialize logger: %w", logErr)
}); err != nil {
return fmt.Errorf("failed to initialize logger: %w", err)
}
log.Info().
+7 -7
View File
@@ -23,16 +23,16 @@ var VersionCmd = &cobra.Command{
if jsonOutput {
data, err := json.MarshalIndent(info, "", " ")
if err != nil {
_, _ = fmt.Fprintf(cmd.OutOrStderr(), "Error: %v\n", err)
fmt.Fprintf(cmd.OutOrStderr(), "Error: %v\n", err)
return
}
_, _ = fmt.Fprintln(cmd.OutOrStdout(), string(data))
fmt.Fprintln(cmd.OutOrStdout(), string(data))
} else {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "GoHoarder %s\n", info.Version)
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Git Commit: %s\n", info.GitCommit)
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Built: %s\n", info.BuildTime)
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Go Version: %s\n", info.GoVersion)
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Platform: %s\n", info.Platform)
fmt.Fprintf(cmd.OutOrStdout(), "GoHoarder %s\n", info.Version)
fmt.Fprintf(cmd.OutOrStdout(), "Git Commit: %s\n", info.GitCommit)
fmt.Fprintf(cmd.OutOrStdout(), "Built: %s\n", info.BuildTime)
fmt.Fprintf(cmd.OutOrStdout(), "Go Version: %s\n", info.GoVersion)
fmt.Fprintf(cmd.OutOrStdout(), "Platform: %s\n", info.Platform)
}
},
}
-258
View File
@@ -1,258 +0,0 @@
package main
import (
"context"
"database/sql"
"flag"
"fmt"
stdlog "log"
"os"
"time"
"github.com/go-gormigrate/gormigrate/v2"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type MigrationConfig struct {
Driver string
DSN string
Action string // migrate, rollback, rollback-to, list
TargetID string // For rollback-to
LogLevel string
Timeout time.Duration
}
func main() {
cfg := MigrationConfig{}
flag.StringVar(&cfg.Driver, "driver", os.Getenv("DB_DRIVER"), "Database driver (postgres, mysql, sqlite)")
flag.StringVar(&cfg.DSN, "dsn", os.Getenv("DATABASE_URL"), "Database connection string")
flag.DurationVar(&cfg.Timeout, "timeout", 10*time.Minute, "Migration timeout")
flag.StringVar(&cfg.Action, "action", "migrate", "Action: migrate, rollback, rollback-to, list")
flag.StringVar(&cfg.TargetID, "target", "", "Target migration ID (for rollback-to)")
flag.StringVar(&cfg.LogLevel, "log-level", "info", "Log level: debug, info, warn, error")
flag.Parse()
// Setup logging
setupLogging(cfg.LogLevel)
log.Info().
Str("driver", cfg.Driver).
Str("action", cfg.Action).
Msg("Starting database migration")
if err := RunMigration(cfg); err != nil {
log.Fatal().Err(err).Msg("Migration failed")
}
log.Info().Msg("Migration completed successfully")
}
func setupLogging(level string) {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339})
switch level {
case "debug":
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case "info":
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case "warn":
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case "error":
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
default:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
}
func RunMigration(cfg MigrationConfig) error {
// Validate config
if cfg.Driver == "" {
return fmt.Errorf("driver is required (set DB_DRIVER or --driver)")
}
if cfg.DSN == "" {
return fmt.Errorf("DSN is required (set DATABASE_URL or --dsn)")
}
ctx, cancel := context.WithTimeout(context.Background(), cfg.Timeout)
defer cancel()
// Connect to database
db, err := connectToDatabase(cfg.Driver, cfg.DSN)
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
sqlDB, err := db.DB()
if err != nil {
return fmt.Errorf("failed to get sql.DB: %w", err)
}
defer func() { _ = sqlDB.Close() }()
// Wait for database to be ready
if err := waitForDB(ctx, sqlDB, 60*time.Second); err != nil {
return fmt.Errorf("database not ready: %w", err)
}
// Initialize gormigrate with custom options
opts := gormigrate.DefaultOptions
opts.TableName = "gohoarder_migrations"
m := gormigrate.New(db, opts, gormstore.GetMigrations())
log.Info().
Str("table", "gohoarder_migrations").
Msg("Migration tracking table initialized")
// Execute action
switch cfg.Action {
case "migrate":
return runMigrate(m)
case "rollback":
return runRollback(m)
case "rollback-to":
if cfg.TargetID == "" {
return fmt.Errorf("target migration ID required for rollback-to")
}
return runRollbackTo(m, cfg.TargetID)
case "list":
return listMigrations(db)
default:
return fmt.Errorf("unknown action: %s (use: migrate, rollback, rollback-to, list)", cfg.Action)
}
}
func connectToDatabase(driver, dsn string) (*gorm.DB, error) {
// Configure GORM logger using standard library log
gormLogger := logger.New(
stdlog.New(os.Stdout, "\r\n", stdlog.LstdFlags),
logger.Config{
SlowThreshold: 200 * time.Millisecond,
LogLevel: logger.Info,
IgnoreRecordNotFoundError: true,
Colorful: true,
},
)
var dialector gorm.Dialector
switch driver {
case "sqlite":
dialector = sqlite.Open(dsn)
case "postgres", "postgresql":
dialector = postgres.Open(dsn)
case "mysql":
dialector = mysql.Open(dsn)
default:
return nil, fmt.Errorf("unsupported driver: %s", driver)
}
db, err := gorm.Open(dialector, &gorm.Config{
Logger: gormLogger,
SkipDefaultTransaction: false, // Migrations should be transactional
PrepareStmt: true,
})
if err != nil {
return nil, err
}
return db, nil
}
func waitForDB(ctx context.Context, db *sql.DB, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
attempt := 0
for {
attempt++
if time.Now().After(deadline) {
return fmt.Errorf("timeout waiting for database after %d attempts", attempt)
}
if err := db.PingContext(ctx); err == nil {
log.Info().
Int("attempts", attempt).
Msg("Database is ready")
return nil
}
log.Debug().
Int("attempt", attempt).
Msg("Waiting for database...")
time.Sleep(2 * time.Second)
}
}
func runMigrate(m *gormigrate.Gormigrate) error {
log.Info().Msg("Running migrations...")
if err := m.Migrate(); err != nil {
return fmt.Errorf("migration failed: %w", err)
}
log.Info().Msg("✓ All migrations applied successfully")
return nil
}
func runRollback(m *gormigrate.Gormigrate) error {
log.Warn().Msg("Rolling back last migration...")
if err := m.RollbackLast(); err != nil {
return fmt.Errorf("rollback failed: %w", err)
}
log.Info().Msg("✓ Rollback completed")
return nil
}
func runRollbackTo(m *gormigrate.Gormigrate, targetID string) error {
log.Warn().
Str("target_id", targetID).
Msg("Rolling back to migration...")
if err := m.RollbackTo(targetID); err != nil {
return fmt.Errorf("rollback to %s failed: %w", targetID, err)
}
log.Info().
Str("target_id", targetID).
Msg("✓ Rollback completed")
return nil
}
func listMigrations(db *gorm.DB) error {
log.Info().Msg("Applied migrations:")
type Migration struct {
ID string
}
var migrations []Migration
if err := db.Table("gohoarder_migrations").Find(&migrations).Error; err != nil {
return fmt.Errorf("failed to list migrations: %w", err)
}
if len(migrations) == 0 {
log.Info().Msg(" (no migrations applied yet)")
return nil
}
for _, m := range migrations {
log.Info().Str("id", m.ID).Msg(" ✓")
}
log.Info().
Int("total", len(migrations)).
Msg("Applied migrations")
return nil
}
+10 -59
View File
@@ -10,13 +10,8 @@ server:
host: "0.0.0.0"
port: 8080 # Backend API server port
read_timeout: "5m"
read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431
write_timeout: "5m"
idle_timeout: "2m"
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
# ("https://gohoarder.example.com") or wildcard ("https://*.example.com").
# Empty: same-origin only. A cross-origin DELETE/POST/PATCH is refused with 403.
allowed_origins: []
tls:
enabled: false
cert_file: ""
@@ -45,80 +40,36 @@ storage:
domain: ""
metadata:
# Backend: sqlite, postgresql, mysql, mariadb, file
#
# Choose based on your deployment:
# - sqlite: Single instance, local storage (NOT for network filesystems like SMB/NFS!)
# - postgresql: Production, multiple replicas, works with any storage including SMB/NFS
# - mysql: Production alternative to PostgreSQL
# - file: Simple file-based metadata (limited features)
#
# IMPORTANT: SQLite + SMB/NFS = Database locked errors!
# For network storage (SMB, NFS), use PostgreSQL or MySQL.
backend: "sqlite"
connection: "file:gohoarder.db?cache=shared&mode=rwc" # Legacy, not used with GORM
backend: "sqlite" # sqlite, postgresql, file
connection: "file:gohoarder.db?cache=shared&mode=rwc"
# SQLite configuration (for local storage only)
# Use with local storage classes (local-path, hostPath, or RWX like longhorn)
# DO NOT use with SMB/NFS network storage!
sqlite:
path: "gohoarder.db"
wal_mode: true # Set to false for network filesystems if you must use SQLite
wal_mode: true
# PostgreSQL configuration (recommended for production)
# Works with any storage including SMB/NFS
# Supports multiple replicas and high availability
postgresql:
host: "localhost"
port: 5432
database: "gohoarder"
user: "gohoarder"
password: ""
ssl_mode: "disable" # disable, require, verify-ca, verify-full
# MySQL/MariaDB configuration (alternative to PostgreSQL)
# Works with any storage including SMB/NFS
mysql:
host: "localhost"
port: 3306
database: "gohoarder"
user: "gohoarder"
password: ""
charset: "utf8mb4"
parse_time: true
# GORM connection pool settings (applies to all database backends)
max_open_conns: 25 # Maximum number of open connections to the database
max_idle_conns: 5 # Maximum number of idle connections in the pool
conn_max_lifetime: 3600 # Maximum lifetime of a connection in seconds (1 hour)
log_level: "warn" # GORM log level: silent, error, warn, info
ssl_mode: "disable"
cache:
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
default_ttl: "168h" # 7 days
cleanup_interval: "1h"
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
deleted_retention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
max_size_bytes: 536870912000 # 500GB
per_project_quota: 53687091200 # 50GB
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
npm: "24h"
pypi: "24h"
go: "24h"
ttl_overrides:
npm: "168h"
pip: "168h"
go: "168h"
security:
enabled: false
block_on_severity: "high" # none, low, medium, high, critical
scan_on_download: true # Scan packages on first download
rescan_interval: "24h" # How often to re-scan packages (e.g., 24h, 168h for weekly)
rescan_active_window: "0s" # Rescan only packages requested within this window (e.g., 720h); 0 = all packages
rescan_on_access: false # Rescan a cached package on download when its scan is older than rescan_interval, before serving it
rescan_concurrency: 1 # Scans run in parallel during one rescan cycle; values below 1 mean 1
# When a scan fails on infrastructure (timeout, upstream 5xx) the package is served and the
# scan is retried every scan_retry_interval. Set fail_closed to refuse such packages instead.
fail_closed: false
# How long a first download waits for its scan before it is served (or refused with fail_closed). Default 30s.
scan_wait_timeout: "30s"
scan_retry_interval: "5m"
update_db_on_startup: false # Update vulnerability databases on startup
allowed_packages: [] # Packages that bypass security checks (format: "registry/name@version")
ignored_cves: [] # CVE IDs to ignore globally (e.g., "CVE-2021-23337")
@@ -141,7 +92,7 @@ security:
# Supports: npm, PyPI, Go, Maven, NuGet, etc.
osv:
enabled: false
api_url: "https://api.osv.dev/v1/query" # full query endpoint, not the host
api_url: "https://api.osv.dev"
timeout: "30s"
# Grype - Multi-ecosystem vulnerability scanner from Anchore
@@ -32,10 +32,6 @@ data:
severity_threshold: medium
block_on_vulnerability: false
rescan_interval: 24h
rescan_active_window: 0s
rescan_concurrency: 1
rescan_on_access: false
scan_wait_timeout: 30s
handlers:
npm:
@@ -1,6 +1,5 @@
# GoHoarder - Kubernetes Deployment (All-in-One)
# This manifest deploys all GoHoarder services under a single ingress
# The frontend includes integrated nginx reverse proxy to the backend
#
# Usage:
# kubectl create namespace gohoarder
@@ -223,13 +222,6 @@ spec:
value: "1.0.0"
- name: APP_NAME
value: GoHoarder
# Backend proxy configuration (frontend includes nginx reverse proxy)
- name: BACKEND_HOST
value: gohoarder-server
- name: BACKEND_PORT
value: "8080"
- name: SERVER_NAME
value: hoarder.i.raczylo.com
livenessProbe:
httpGet:
path: /
@@ -333,6 +325,88 @@ spec:
configMap:
name: gohoarder-config
---
# Deployment - Gateway (Nginx Reverse Proxy)
apiVersion: apps/v1
kind: Deployment
metadata:
name: gohoarder-gateway
namespace: gohoarder
labels:
app.kubernetes.io/name: gohoarder
app.kubernetes.io/component: gateway
spec:
replicas: 2
selector:
matchLabels:
app.kubernetes.io/name: gohoarder
app.kubernetes.io/component: gateway
template:
metadata:
labels:
app.kubernetes.io/name: gohoarder
app.kubernetes.io/component: gateway
spec:
containers:
- name: gateway
image: ghcr.io/lukaszraczylo/gohoarder-gateway:latest
imagePullPolicy: Always
ports:
- name: http
containerPort: 80
protocol: TCP
env:
- name: BACKEND_HOST
value: gohoarder-server
- name: BACKEND_PORT
value: "8080"
- name: FRONTEND_HOST
value: gohoarder-frontend
- name: FRONTEND_PORT
value: "80"
- name: SERVER_NAME
value: hoarder.i.raczylo.com
livenessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 5
periodSeconds: 30
readinessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 5
periodSeconds: 10
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
---
# Service - Gateway
apiVersion: v1
kind: Service
metadata:
name: gohoarder-gateway
namespace: gohoarder
labels:
app.kubernetes.io/name: gohoarder
app.kubernetes.io/component: gateway
spec:
type: ClusterIP
ports:
- name: http
port: 80
targetPort: http
protocol: TCP
selector:
app.kubernetes.io/name: gohoarder
app.kubernetes.io/component: gateway
---
# Ingress - Expose via domain
apiVersion: networking.k8s.io/v1
@@ -362,7 +436,7 @@ spec:
pathType: Prefix
backend:
service:
name: gohoarder-frontend
name: gohoarder-gateway
port:
number: 80
# Uncomment for HTTPS/TLS
@@ -403,20 +477,20 @@ spec:
averageUtilization: 80
---
# HorizontalPodAutoscaler - Frontend
# HorizontalPodAutoscaler - Gateway
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: gohoarder-frontend
name: gohoarder-gateway
namespace: gohoarder
labels:
app.kubernetes.io/name: gohoarder
app.kubernetes.io/component: frontend
app.kubernetes.io/component: gateway
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: gohoarder-frontend
name: gohoarder-gateway
minReplicas: 2
maxReplicas: 10
metrics:
+38 -14
View File
@@ -2,7 +2,7 @@ version: '3.8'
# GoHoarder - Unified Deployment Example
# This docker-compose file demonstrates deploying all GoHoarder services
# The frontend includes integrated reverse proxy to the backend
# under a single domain using the gateway reverse proxy
services:
# Backend - Main application server
@@ -39,7 +39,7 @@ services:
retries: 3
start_period: 5s
# Frontend - Web dashboard with integrated reverse proxy
# Frontend - Web dashboard
gohoarder-frontend:
image: ghcr.io/lukaszraczylo/gohoarder-frontend:latest
container_name: gohoarder-frontend
@@ -49,19 +49,8 @@ services:
- API_BASE_URL=/api
- APP_VERSION=1.0.0
- APP_NAME=GoHoarder
# Backend proxy configuration (frontend includes nginx reverse proxy)
- BACKEND_HOST=gohoarder-server
- BACKEND_PORT=8080
- SERVER_NAME=hoarder.i.raczylo.com
ports:
# Map to host port 80 (HTTP)
- "80:80"
# Map to host port 443 (HTTPS) - uncomment if using SSL
# - "443:443"
networks:
- gohoarder-internal
depends_on:
- gohoarder-server
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/"]
interval: 30s
@@ -93,6 +82,41 @@ services:
# profiles:
# - scanner
# Gateway - Nginx reverse proxy
gohoarder-gateway:
image: ghcr.io/lukaszraczylo/gohoarder-gateway:latest
container_name: gohoarder-gateway
restart: unless-stopped
environment:
# Backend service connection
- BACKEND_HOST=gohoarder-server
- BACKEND_PORT=8080
# Frontend service connection
- FRONTEND_HOST=gohoarder-frontend
- FRONTEND_PORT=80
# Server configuration
- SERVER_NAME=hoarder.i.raczylo.com
ports:
# Map to host port 80 (HTTP)
- "80:80"
# Map to host port 443 (HTTPS) - uncomment if using SSL
# - "443:443"
networks:
- gohoarder-internal
depends_on:
- gohoarder-server
- gohoarder-frontend
# Uncomment if using custom SSL certificates
# volumes:
# - ./ssl/cert.pem:/etc/nginx/ssl/cert.pem:ro
# - ./ssl/key.pem:/etc/nginx/ssl/key.pem:ro
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 5s
networks:
gohoarder-internal:
driver: bridge
@@ -120,7 +144,7 @@ volumes:
# - Metrics: http://localhost/metrics
#
# For production:
# - Enable HTTPS in the frontend container (add SSL certificates to nginx)
# - Enable HTTPS in the gateway container
# - Set up proper SSL certificates
# - Configure firewall rules
# - Set appropriate resource limits
-129
View File
@@ -1,129 +0,0 @@
# Example GoHoarder values for Traefik IngressRoute
#
# This configuration uses Traefik IngressRoute instead of standard Kubernetes Ingress
# to better handle scoped npm packages with encoded slashes.
#
# IMPORTANT: You must also configure your Traefik deployment to allow encoded slashes.
# See docs/TRAEFIK_ENCODED_SLASHES.md for Traefik configuration steps.
nameOverride: "gohoarder"
fullnameOverride: ""
global:
domain: "i.raczylo.com"
imagePullSecrets: []
replicaCount:
server: 1
frontend: 1
scanner: 1
image:
server:
repository: ghcr.io/lukaszraczylo/gohoarder-server
pullPolicy: IfNotPresent
tag: "latest"
frontend:
repository: ghcr.io/lukaszraczylo/gohoarder-frontend
pullPolicy: IfNotPresent
tag: "latest"
scanner:
repository: ghcr.io/lukaszraczylo/gohoarder-scanner
pullPolicy: IfNotPresent
tag: "latest"
# Ingress configuration for Traefik
ingress:
enabled: true
className: "traefik" # This triggers IngressRoute creation instead of Ingress
# Your GoHoarder hostname
host: "hoarder.i.raczylo.com"
# TLS configuration
tls:
enabled: true
secretName: "cert-i.raczylo.com"
# Traefik-specific settings
# These are used by the IngressRoute template
traefik:
# Reference middlewares from the traefik namespace
# These will be applied to all routes
middlewares:
- default-chain # Your existing middleware chain from traefik namespace
# ServersTransport configuration (optional)
transport:
serverName: ""
# Storage configuration
storage:
backend: "filesystem"
filesystem:
storageClass: "longhorn"
size: "100Gi"
accessMode: "ReadWriteOnce"
# Metadata storage
metadata:
backend: "sqlite"
sqlite:
persistence:
enabled: false # Using emptyDir for metadata
walMode: false
# Cache configuration
cache:
defaultTTL: "168h" # 7 days
maxSizeBytes: 536870912000 # 500GB
# Package handlers
handlers:
npm:
enabled: true
upstreamRegistry: "https://registry.npmjs.org"
pypi:
enabled: true
upstreamUrl: "https://pypi.org"
go:
enabled: true
upstreamProxy: "https://proxy.golang.org"
# Authentication
auth:
enabled: true
adminApiKey: "" # Will be auto-generated if empty
# Logging
logging:
level: "info"
format: "json"
# Resource limits
server:
resources:
limits:
cpu: 2000m
memory: 2Gi
requests:
cpu: 500m
memory: 512Mi
frontend:
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 100m
memory: 128Mi
scanner:
resources:
limits:
cpu: 2000m
memory: 4Gi
requests:
cpu: 500m
memory: 1Gi
-3
View File
@@ -5,6 +5,3 @@ VITE_BACKEND_URL=http://localhost:8080
# Frontend dev server port
# The Vite development server will run on this port
VITE_PORT=5173
# Origin sent on the dev WebSocket proxy, for a backend with an allowed-origins list
# VITE_WS_ORIGIN=https://gohoarder.example.com
-8
View File
@@ -1,8 +0,0 @@
{
"hash": "eb707743",
"configHash": "e17a1322",
"lockfileHash": "c2e83396",
"browserHash": "ab796ace",
"optimized": {},
"chunks": {}
}
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://shadcn-vue.com/schema.json",
"style": "new-york",
"typescript": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/styles/main.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"composables": "@/composables"
},
"registries": {}
}
+1
View File
@@ -0,0 +1 @@
12921
+6 -4
View File
@@ -1,11 +1,13 @@
<!DOCTYPE html>
<html lang="en" data-style="workbench">
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<link rel="icon" href="data:," />
<title>GoHoarder dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<title>GoHoarder Dashboard</title>
</head>
<body>
<div id="app"></div>
+22 -16
View File
@@ -8,30 +8,36 @@
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"sources": "node scripts/library-sources.mjs --write"
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"@fontsource/ibm-plex-mono": "5.3.0",
"@fontsource/ibm-plex-sans": "5.3.0",
"@fortawesome/free-solid-svg-icons": "7.3.1",
"@perfect-design/ui": "0.3.10",
"axios": "^1.20.0",
"pinia": "^4.0.0",
"@vueuse/core": "^14.1.0",
"axios": "^1.13.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-vue-next": "^0.562.0",
"marked": "^17.0.1",
"pinia": "^3.0.4",
"reka-ui": "^2.7.0",
"tailwind-merge": "^3.4.0",
"tailwindcss-animate": "^1.0.7",
"vue": "^3.5.26",
"vue-router": "^5.3.1"
"vue-router": "^4.6.4"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^7.0.0",
"@fortawesome/fontawesome-free": "^7.1.0",
"@tailwindcss/typography": "^0.5.19",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/vue": "^8.1.0",
"@vitejs/plugin-vue": "^6.0.3",
"@vue/test-utils": "^2.4.6",
"jsdom": "^31.0.0",
"tailwindcss": "^4.3.3",
"typescript": "^6.0.3",
"vite": "^8.0.0",
"vitest": "^5.0.3",
"autoprefixer": "^10.4.23",
"jsdom": "^27.4.0",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.19",
"typescript": "^5.9.3",
"vite": "^7.3.0",
"vitest": "^4.0.16",
"vue-tsc": "^3.2.1"
}
}
+2013 -1615
View File
File diff suppressed because it is too large Load Diff
-8
View File
@@ -1,8 +0,0 @@
allowBuilds:
esbuild: true
vue-demi: true
# Patched versions of transitive dependencies that Dependabot cannot raise on its own.
overrides:
"minimatch@<9.0.9": ^11.0.0
"esbuild@<0.28.2": ^0.28.2
"postcss-selector-parser@<6.1.4": ^7.0.0
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
-1
View File
@@ -1 +0,0 @@
export function librarySources(root: string): string[]
-94
View File
@@ -1,94 +0,0 @@
// Lists the @source lines for the @perfect-design/ui dist directories the app imports, transitively.
// `node scripts/library-sources.mjs` prints them; `--write` rewrites the block in src/styles/main.css.
import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { join, dirname, resolve, relative } from 'node:path'
export function librarySources(root) {
const dist = join(root, 'node_modules/@perfect-design/ui/dist')
function walk(dir, out = []) {
for (const e of readdirSync(dir)) {
const p = join(dir, e)
statSync(p).isDirectory() ? walk(p, out) : out.push(p)
}
return out
}
// names imported from the package entry
const names = new Set()
for (const f of walk(join(root, 'src')).filter((f) => /\.(vue|ts)$/.test(f) && !/\.(spec|test)\./.test(f))) {
const src = readFileSync(f, 'utf8')
for (const m of src.matchAll(/import\s*\{([^}]*)\}\s*from\s*'@perfect-design\/ui'/g))
for (const n of m[1].split(',')) {
const name = n.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0]
if (name && !n.trim().startsWith('type ')) names.add(name)
}
}
// name -> file: follow the barrel index.js re-exports
const resolveJs = (from, spec) => {
const base = resolve(dirname(from), spec)
for (const c of [base, base + '.js', join(base, 'index.js')]) if (existsSync(c) && statSync(c).isFile()) return c
return null
}
const exportsOf = new Map() // exported name -> file
{
const idx = join(dist, 'index.js')
const src = readFileSync(idx, 'utf8')
const localFile = new Map()
for (const m of src.matchAll(/^import\s+(?:(\w+)\s*,?\s*)?(?:\{([^}]*)\})?\s*from\s*"(\.[^"]+)";?$/gm)) {
const target = resolveJs(idx, m[3])
if (!target) continue
if (m[1]) localFile.set(m[1], target)
if (m[2]) for (const n of m[2].split(',')) { const p = n.trim().split(/\s+as\s+/); if (p[0]) localFile.set(p[1] ?? p[0], target) }
}
for (const m of src.matchAll(/^export\s*\{([^}]*)\};?$/gm))
for (const n of m[1].split(',')) {
const p = n.trim().split(/\s+as\s+/)
const local = p[0], exported = p[1] ?? p[0]
if (localFile.has(local)) exportsOf.set(exported, localFile.get(local))
}
}
const files = new Set()
const queue = []
const missing = []
for (const n of names) {
const f = exportsOf.get(n)
f ? queue.push(f) : missing.push(n)
}
while (queue.length) {
const f = queue.pop()
if (files.has(f)) continue
files.add(f)
const src = readFileSync(f, 'utf8')
for (const m of src.matchAll(/from\s*["'](\.[^"']+)["']/g)) {
const t = resolveJs(f, m[1])
if (t && !files.has(t)) queue.push(t)
}
}
const dirs = new Set([...files].map((f) => dirname(f)))
if (missing.length) throw new Error(`not exported by @perfect-design/ui: ${missing.join(', ')}`)
const rel = (d) => relative(join(root, 'src/styles'), d).split('\\').join('/')
const lines = [...dirs]
.map(rel)
.sort()
.map((d) => `@source "${d}/*.js";`)
return lines
}
if (import.meta.url === `file://${process.argv[1]}`) {
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const lines = librarySources(root)
if (process.argv.includes('--write')) {
const css = join(root, 'src/styles/main.css')
const kept = readFileSync(css, 'utf8')
.split('\n')
.filter((l) => !l.startsWith('@source '))
const at = kept.findIndex((l) => l.startsWith('/* Only the library components'))
kept.splice(at + 1, 0, ...lines)
writeFileSync(css, kept.join('\n'))
} else {
console.log(lines.join('\n'))
}
}
+57 -46
View File
@@ -1,50 +1,61 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { RouterView } from 'vue-router'
import { AppHeader, AppShell, Icon, ThemeToggle, Toaster, useThemeStore } from '@perfect-design/ui'
import AppNav from '@/components/shell/AppNav.vue'
import { faBoxOpen } from '@/lib/icons'
// init() installs the watcher that applies and persists the choice; the style is set after it so a stored value cannot override the pack.
onMounted(() => {
const theme = useThemeStore()
theme.init()
theme.setStyle('workbench')
})
</script>
<template>
<div class="flex min-h-dvh flex-col">
<!-- Rendered here, not by AppShell: the header sits above the shell, and the skip link must be the first tab stop. -->
<a
href="#main-content"
class="sr-only focus:not-sr-only focus:absolute focus:start-2 focus:top-2 focus:z-(--z-toast) focus:rounded-md focus:bg-primary focus:px-3 focus:py-2 focus:text-sm focus:text-primary-foreground"
>Skip to main content</a
>
<!-- px-6 on the bar equals the sidebar nav's p-3 plus the link's px-3, so the brand icon sits over the nav icons. -->
<!-- AppShell wraps its #header slot in its own <header> and AppHeader renders one too; outside the shell there is one banner. -->
<AppHeader sticky mobile-variant="sheet" class="[&>div]:h-(--header-h) [&>div]:px-6">
<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 checkpoint</p>
</template>
<template #actions><ThemeToggle /></template>
<template #mobile><AppNav sheet /></template>
</AppHeader>
<div class="min-h-screen bg-background">
<nav class="sticky top-0 z-50 bg-card/95 backdrop-blur-lg shadow-sm border-b">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center gap-3">
<div class="flex items-center justify-center w-10 h-10 rounded-lg bg-primary text-primary-foreground">
<i class="fas fa-box-open text-lg"></i>
</div>
<div class="flex flex-col">
<h1 class="text-lg font-semibold tracking-tight text-foreground">GoHoarder</h1>
<p class="text-xs text-muted-foreground">Package Cache Manager</p>
</div>
</div>
<div class="flex items-center gap-1">
<router-link
to="/"
class="inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-foreground/70 hover:text-foreground hover:bg-accent transition-colors"
active-class="text-foreground bg-accent"
>
<i class="fas fa-chart-pie text-sm"></i>
<span>Dashboard</span>
</router-link>
<router-link
to="/packages"
class="inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-foreground/70 hover:text-foreground hover:bg-accent transition-colors"
active-class="text-foreground bg-accent"
>
<i class="fas fa-boxes text-sm"></i>
<span>Packages</span>
</router-link>
<router-link
to="/stats"
class="inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-foreground/70 hover:text-foreground hover:bg-accent transition-colors"
active-class="text-foreground bg-accent"
>
<i class="fas fa-chart-bar text-sm"></i>
<span>Statistics</span>
</router-link>
<router-link
to="/admin/bypasses"
class="inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-foreground/70 hover:text-foreground hover:bg-accent transition-colors"
active-class="text-foreground bg-accent"
>
<i class="fas fa-shield-alt text-sm"></i>
<span>Admin</span>
</router-link>
</div>
</div>
</div>
</nav>
<!-- The aside scrolls itself, so only the aside can stick; both offsets come from --header-h. -->
<AppShell
:skip-link="false"
drawer-breakpoint="md"
sidebar-label="Sections"
content-max-width="7xl"
class="flex-1 md:[&_[data-slot=app-shell-sidebar]]:sticky md:[&_[data-slot=app-shell-sidebar]]:top-(--header-h) md:[&_[data-slot=app-shell-sidebar]]:h-[calc(100dvh-var(--header-h))] md:[&_[data-slot=app-shell-sidebar]]:self-start"
>
<template #sidebar><AppNav /></template>
<div class="py-6"><RouterView /></div>
</AppShell>
<Toaster />
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
<router-view />
</main>
</div>
</template>
<script setup lang="ts">
// App component
</script>
+363 -244
View File
@@ -1,230 +1,374 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader
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>
</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
<div>
<div class="flex justify-between items-center mb-8">
<div>
<h2 class="text-3xl font-bold text-gray-900">CVE Bypass Management</h2>
<p class="text-gray-600 mt-1">Manage temporary security bypasses for packages and CVEs</p>
</div>
<Button @click="showCreateModal = true" class="bg-green-600 hover:bg-green-700">
<i class="fas fa-plus mr-2"></i>Create Bypass
</Button>
</div>
<LoadingState v-if="loading" variant="table" label="Loading bypasses..." />
<!-- Filter Section -->
<div class="mb-6 flex flex-col sm:flex-row items-start sm:items-center gap-4">
<div class="flex items-center gap-2">
<span class="text-sm font-medium text-gray-700">Filter:</span>
<div class="flex gap-2">
<Button
@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>
<ErrorState
v-else-if="error"
variant="card"
title="Could not load bypasses"
:message="error"
@retry="fetchBypasses"
/>
<!-- Error Alert -->
<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>
<CardContent>
<EmptyState
v-if="filteredBypasses.length === 0"
:icon="faShieldHalved"
title="No bypasses found"
description="Create a bypass to serve a package that the policy holds."
/>
<DataTable
v-else
label="Bypasses"
layout="cards"
row-key="id"
:columns="bypassColumns"
:rows="filteredBypasses"
>
<template #cell-type="{ row }">
<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">
<StatusBadge
:status="row.active ? 'active' : 'inactive'"
:tones="{ active: 'success', inactive: 'neutral' }"
/>
<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)" />
<IconButton :icon="faTrash" :label="`Delete bypass for ${row.target}`" @click="confirmDeleteBypass(row)" />
</span>
</template>
</DataTable>
<CardContent class="p-6">
<div v-if="filteredBypasses.length === 0" class="text-center py-12 text-gray-500">
<i class="fas fa-shield-alt text-6xl mb-4"></i>
<p class="text-xl">No bypasses found</p>
<p class="mt-2">Create a bypass to allow packages with known vulnerabilities</p>
</div>
<div v-else class="space-y-4">
<div
v-for="bypass in filteredBypasses"
:key="bypass.id"
class="border rounded-lg p-4 hover:bg-gray-50"
:class="bypass.active ? 'border-gray-200' : 'border-gray-300 bg-gray-50'"
>
<div class="flex items-start justify-between">
<div class="flex-1">
<div class="flex items-center gap-2 mb-2">
<Badge :variant="bypass.type === 'cve' ? 'default' : 'outline'">
{{ bypass.type.toUpperCase() }}
</Badge>
<Badge
:class="bypass.active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'"
>
{{ bypass.active ? 'ACTIVE' : 'INACTIVE' }}
</Badge>
<Badge
v-if="isExpired(bypass.expires_at)"
class="bg-red-100 text-red-800"
>
EXPIRED
</Badge>
</div>
<h4 class="font-semibold text-lg text-gray-900">{{ bypass.target }}</h4>
<p class="text-sm text-gray-600 mt-1">{{ bypass.reason }}</p>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-3 text-sm text-gray-500">
<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>
</Card>
<!-- Create/Edit Bypass Modal -->
<Dialog v-model:open="showCreateModal">
<DialogContent size="lg">
<DialogContent class="max-w-2xl">
<DialogHeader>
<DialogTitle>{{ editingBypass ? 'Edit' : 'Create' }} bypass</DialogTitle>
<DialogTitle>{{ editingBypass ? 'Edit' : 'Create' }} Bypass</DialogTitle>
<DialogDescription>
{{ editingBypass ? 'Update the bypass settings.' : 'Create a temporary bypass for a CVE or package.' }}
{{ editingBypass ? 'Update bypass settings' : 'Create a temporary bypass for a CVE or package' }}
</DialogDescription>
</DialogHeader>
<form class="flex flex-col gap-4" @submit.prevent="submitBypass">
<Field v-if="!editingBypass" label="Bypass type">
<SegmentedControl v-model="bypassForm.type" :options="BYPASS_TYPE_OPTIONS" full-width />
</Field>
<div class="space-y-4 py-4">
<!-- Type Selection -->
<div v-if="!editingBypass">
<label class="text-sm font-medium text-gray-700 mb-2 block">Bypass Type</label>
<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>
<Field
v-if="!editingBypass"
:label="bypassForm.type === 'cve' ? 'CVE ID' : 'Package'"
:hint="
bypassForm.type === 'cve'
? 'Enter a CVE or GHSA id, for example CVE-2021-23337. It also covers findings that carry it as an alias.'
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions. PyPI packages use the release version, for example pypi/[email protected].'
"
required
>
<!-- Target -->
<div v-if="!editingBypass">
<label class="text-sm font-medium text-gray-700 mb-2 block">
{{ bypassForm.type === 'cve' ? 'CVE ID' : 'Package' }}
</label>
<Input
v-model="bypassForm.target"
:placeholder="bypassForm.type === 'cve' ? 'CVE-2021-23337' : 'npm/[email protected]'"
class="w-full"
/>
</Field>
<p class="text-xs text-gray-500 mt-1">
{{ 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>
<Field
v-if="!editingBypass && bypassForm.type === 'cve'"
label="Applies to (optional)"
hint="Limit this CVE bypass to one package. Leave empty to apply it to every package with this CVE."
>
<Input v-model="bypassForm.applies_to" placeholder="npm/[email protected]" />
</Field>
<Field label="Reason" hint="Explain why this bypass is needed. It is kept for the audit trail." required>
<Textarea v-model="bypassForm.reason" placeholder="No fix available, business critical dependency" />
</Field>
<Field v-if="!editingBypass" label="Created by" required>
<Input v-model="bypassForm.created_by" placeholder="[email protected]" />
</Field>
<Field
label="Expires in (hours)"
hint="Hours until this bypass expires. 168 is 7 days and 720 is 30 days."
required
>
<!-- Applies To (CVE only) -->
<div v-if="!editingBypass && bypassForm.type === 'cve'">
<label class="text-sm font-medium text-gray-700 mb-2 block">
Applies To (Optional)
</label>
<Input
:model-value="bypassForm.expires_in_hours"
v-model="bypassForm.applies_to"
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 -->
<div>
<label class="text-sm font-medium text-gray-700 mb-2 block">Reason *</label>
<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 -->
<div v-if="!editingBypass">
<label class="text-sm font-medium text-gray-700 mb-2 block">Created By *</label>
<Input
v-model="bypassForm.created_by"
placeholder="[email protected]"
class="w-full"
/>
</div>
<!-- Expires In -->
<div>
<label class="text-sm font-medium text-gray-700 mb-2 block">Expires In (Hours) *</label>
<Input
v-model.number="bypassForm.expires_in_hours"
type="number"
min="1"
placeholder="168"
@update:model-value="setExpiresInHours"
class="w-full"
/>
</Field>
<p class="text-xs text-gray-500 mt-1">
How many hours until this bypass expires (e.g., 168 = 7 days, 720 = 30 days)
</p>
</div>
<Checkbox v-if="editingBypass" v-model="bypassForm.active" label="Active" />
<!-- Active (Edit only) -->
<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>
<Checkbox v-model="bypassForm.notify_on_expiry" label="Send a notification when the bypass expires" />
<!-- Notify on Expiry -->
<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>
<Button variant="outline" @click="closeCreateModal">Cancel</Button>
<Button type="submit" :disabled="!isFormValid">{{ editingBypass ? 'Update' : 'Create' }} bypass</Button>
</DialogFooter>
</form>
<DialogFooter>
<Button @click="closeCreateModal" variant="outline">
Cancel
</Button>
<Button @click="submitBypass" :disabled="!isFormValid">
{{ editingBypass ? 'Update' : 'Create' }} Bypass
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog v-model:open="showKeyDialog">
<DialogContent size="sm">
<!-- Delete Confirmation Dialog -->
<Dialog v-model:open="showDeleteModal">
<DialogContent>
<DialogHeader>
<DialogTitle>Admin API key</DialogTitle>
<DialogDescription>Enter your admin API key to manage bypasses.</DialogDescription>
<DialogTitle>Confirm Deletion</DialogTitle>
<DialogDescription>
Are you sure you want to delete this bypass for <strong>{{ bypassToDelete?.target }}</strong>?
This action cannot be undone and the security check will be re-enabled immediately.
</DialogDescription>
</DialogHeader>
<form class="flex flex-col gap-4" @submit.prevent="submitApiKey">
<Field label="API key" required>
<Input v-model="keyInput" type="password" autocomplete="off" />
</Field>
<DialogFooter>
<Button variant="outline" @click="showKeyDialog = false">Cancel</Button>
<Button type="submit" :disabled="keyInput.trim() === ''">Continue</Button>
</DialogFooter>
</form>
<DialogFooter>
<Button @click="showDeleteModal = false" variant="outline">
Cancel
</Button>
<Button @click="deleteBypass" variant="destructive">
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmDialog
v-model:open="showDeleteModal"
title="Delete bypass?"
:description="`Delete the bypass for ${bypassToDelete?.target}? This cannot be undone and the security check is re-enabled immediately.`"
confirm-label="Delete bypass"
tone="danger"
destructive
@confirm="deleteBypass"
/>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { useRoute } from 'vue-router'
import { Button } from '@/components/ui/button'
import {
Badge,
Button,
Card,
CardContent,
Checkbox,
ConfirmDialog,
DataTable,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
EmptyState,
ErrorState,
Field,
IconButton,
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'
} from '@/components/ui/dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
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()
const successMessage = ref<string | null>(null)
const bypasses = ref<Bypass[]>([])
const activeFilter = ref<'all' | 'active' | 'expired'>('all')
const typeFilter = ref<'all' | 'cve' | 'package'>('all')
const typeFilter = ref<'' | 'cve' | 'package'>('')
const route = useRoute()
const showCreateModal = ref(false)
const showDeleteModal = ref(false)
const editingBypass = ref<Bypass | null>(null)
const bypassToDelete = ref<Bypass | null>(null)
const EMPTY_FORM = {
const bypassForm = ref({
type: 'cve' as 'cve' | 'package',
target: '',
reason: '',
@@ -233,14 +377,10 @@ const EMPTY_FORM = {
applies_to: '',
notify_on_expiry: false,
active: true,
}
})
const bypassForm = ref({ ...EMPTY_FORM })
const adminKey = useAdminKey()
const apiKey = adminKey.key
const keyInput = ref('')
const showKeyDialog = ref(false)
// Get API key from localStorage or prompt user
const apiKey = ref<string>('')
const filteredBypasses = computed(() => {
let filtered = bypasses.value
@@ -253,7 +393,7 @@ const filteredBypasses = computed(() => {
}
// Filter by type
if (typeFilter.value !== 'all') {
if (typeFilter.value) {
filtered = filtered.filter(b => b.type === typeFilter.value)
}
@@ -273,8 +413,8 @@ const isFormValid = computed(() => {
})
onMounted(() => {
adminKey.load()
prefillFromQuery()
// Try to get API key from localStorage
apiKey.value = localStorage.getItem('admin_api_key') || ''
if (!apiKey.value) {
promptForApiKey()
} else {
@@ -282,31 +422,17 @@ 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
const key = prompt('Enter your admin API key:')
if (key) {
apiKey.value = key
localStorage.setItem('admin_api_key', key)
fetchBypasses()
} else {
error.value = 'Admin API key required to manage bypasses'
}
}
function submitApiKey() {
const key = keyInput.value.trim()
if (!key) return
adminKey.save(key)
showKeyDialog.value = false
fetchBypasses()
}
watch(showKeyDialog, (open) => {
if (!open && !apiKey.value) error.value = 'Admin API key required to manage bypasses'
})
async function fetchBypasses() {
if (!apiKey.value) {
promptForApiKey()
@@ -322,7 +448,7 @@ async function fetchBypasses() {
} else if (activeFilter.value === 'expired') {
params.append('include_expired', 'true')
}
if (typeFilter.value !== 'all') {
if (typeFilter.value) {
params.append('type', typeFilter.value)
}
@@ -336,7 +462,8 @@ async function fetchBypasses() {
console.error('Failed to fetch bypasses:', err)
if (err.response?.status === 401) {
error.value = 'Invalid API key. Please check your credentials.'
adminKey.clear()
localStorage.removeItem('admin_api_key')
apiKey.value = ''
} else {
error.value = err.response?.data?.error?.message || err.message || 'Failed to load bypasses'
}
@@ -349,6 +476,8 @@ async function submitBypass() {
if (!isFormValid.value) return
loading.value = true
error.value = null
successMessage.value = null
try {
if (editingBypass.value) {
@@ -366,7 +495,7 @@ async function submitBypass() {
},
}
)
toasts.success('Bypass updated')
successMessage.value = 'Bypass updated successfully'
} else {
// Create new bypass
await axios.post(
@@ -386,14 +515,19 @@ async function submitBypass() {
},
}
)
toasts.success('Bypass created')
successMessage.value = 'Bypass created successfully'
}
closeCreateModal()
await fetchBypasses()
// Clear success message after 5 seconds
setTimeout(() => {
successMessage.value = null
}, 5000)
} catch (err: any) {
console.error('Failed to submit bypass:', err)
toasts.error('Could not save bypass', err.response?.data?.error?.message || err.message || 'Failed to save bypass')
error.value = err.response?.data?.error?.message || err.message || 'Failed to save bypass'
} finally {
loading.value = false
}
@@ -416,14 +550,18 @@ function editBypass(bypass: Bypass) {
function closeCreateModal() {
showCreateModal.value = false
}
// 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 }
})
bypassForm.value = {
type: 'cve',
target: '',
reason: '',
created_by: '',
expires_in_hours: 168,
applies_to: '',
notify_on_expiry: false,
active: true,
}
}
function confirmDeleteBypass(bypass: Bypass) {
bypassToDelete.value = bypass
@@ -434,6 +572,8 @@ async function deleteBypass() {
if (!bypassToDelete.value) return
loading.value = true
error.value = null
successMessage.value = null
try {
await axios.delete(`/api/admin/bypasses/${bypassToDelete.value.id}`, {
@@ -442,49 +582,28 @@ async function deleteBypass() {
},
})
toasts.success('Bypass deleted')
successMessage.value = 'Bypass deleted successfully'
showDeleteModal.value = false
bypassToDelete.value = null
await fetchBypasses()
// Clear success message after 5 seconds
setTimeout(() => {
successMessage.value = null
}, 5000)
} catch (err: any) {
console.error('Failed to delete bypass:', err)
toasts.error('Could not delete bypass', err.response?.data?.error?.message || err.message || 'Failed to delete bypass')
error.value = err.response?.data?.error?.message || err.message || 'Failed to delete bypass'
} finally {
loading.value = false
}
}
const FILTER_OPTIONS = [
{ 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', 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', 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: () => '' },
]
function setExpiresInHours(value: string | number) {
bypassForm.value.expires_in_hours = Number(value)
function isExpired(expiresAt: string): boolean {
return new Date(expiresAt) < new Date()
}
function formatDate(date: string): string {
return new Date(date).toLocaleString()
}
</script>
+208
View File
@@ -0,0 +1,208 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import Dashboard from './Dashboard.vue'
import { usePackageStore } from '../stores/packages'
describe('Dashboard.vue', () => {
beforeEach(() => {
setActivePinia(createPinia())
// Mock the fetch functions to prevent actual API calls
const store = usePackageStore()
vi.spyOn(store, 'fetchStats').mockResolvedValue()
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
})
it('renders dashboard component', () => {
const wrapper = mount(Dashboard)
expect(wrapper.find('h2').text()).toBe('Dashboard')
})
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,
total_downloads: 30,
scanned_packages: 2,
vulnerable_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,
total_downloads: 0,
scanned_packages: 0,
vulnerable_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,
total_downloads: 500,
scanned_packages: 0,
vulnerable_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
total_downloads: 0,
scanned_packages: 0,
vulnerable_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.packages = [
{
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')
})
it('shows recent packages sorted by cached_at', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = [
{
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,
},
{
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,
},
]
await wrapper.vm.$nextTick()
const recentPackagesSection = wrapper.text().split('Recent Packages')[1]
// new-package should appear before old-package since it's more recent
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
recentPackagesSection.indexOf('old-package')
)
})
it('limits recent packages to 10 items', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = Array.from({ length: 15 }, (_, i) => ({
id: `${i}`,
registry: 'npm',
name: `package${i}`,
version: '1.0.0',
size: 1024,
cached_at: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
last_accessed: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
download_count: i,
}))
await wrapper.vm.$nextTick()
const recentSection = wrapper.text().split('Recent Packages')[1]
// Count how many "package" strings appear (each package has the word "package" in its name)
const packageCount = (recentSection.match(/package\d+/g) || []).length
expect(packageCount).toBeLessThanOrEqual(10)
})
it('handles empty packages array', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = []
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('0')
expect(wrapper.text()).toContain('0 B')
})
})
+305
View File
@@ -0,0 +1,305 @@
<template>
<div>
<h2 class="text-3xl font-bold text-gray-900 mb-8">Dashboard</h2>
<!-- Error Alert -->
<Alert v-if="error" variant="destructive" class="mb-4">
<i class="fas fa-exclamation-circle mr-2"></i>
<AlertDescription>{{ error }}</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 statistics...</p>
</div>
<!-- Stats Grid -->
<div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
<Card class="border-0 shadow-lg hover:shadow-xl transition-shadow">
<CardContent class="p-6">
<div class="flex items-start justify-between">
<div class="space-y-2">
<p class="text-sm font-medium text-muted-foreground">Total Packages</p>
<p class="text-3xl font-bold text-foreground tracking-tight">
{{ formatNumber(stats?.total_packages || 0) }}
</p>
</div>
<div class="w-12 h-12 bg-slate-100 rounded-xl flex items-center justify-center">
<i class="fas fa-boxes text-slate-700 text-lg"></i>
</div>
</div>
</CardContent>
</Card>
<Card class="border-0 shadow-lg hover:shadow-xl transition-shadow">
<CardContent class="p-6">
<div class="flex items-start justify-between">
<div class="space-y-2">
<p class="text-sm font-medium text-muted-foreground">Total Size</p>
<p class="text-3xl font-bold text-foreground tracking-tight">
{{ formatBytes(stats?.total_size || 0) }}
</p>
</div>
<div class="w-12 h-12 bg-sky-50 rounded-xl flex items-center justify-center">
<i class="fas fa-hard-drive text-sky-600 text-lg"></i>
</div>
</div>
</CardContent>
</Card>
<Card class="border-0 shadow-lg hover:shadow-xl transition-shadow">
<CardContent class="p-6">
<div class="flex items-start justify-between">
<div class="space-y-2">
<p class="text-sm font-medium text-muted-foreground">Total Downloads</p>
<p class="text-3xl font-bold text-foreground tracking-tight">
{{ formatNumber(stats?.total_downloads || 0) }}
</p>
</div>
<div class="w-12 h-12 bg-emerald-50 rounded-xl flex items-center justify-center">
<i class="fas fa-download text-emerald-600 text-lg"></i>
</div>
</div>
</CardContent>
</Card>
<Card class="border-0 shadow-lg hover:shadow-xl transition-shadow">
<CardContent class="p-6">
<div class="flex items-start justify-between">
<div class="space-y-2">
<p class="text-sm font-medium text-muted-foreground">Scanned Packages</p>
<p class="text-3xl font-bold text-foreground tracking-tight">
{{ formatNumber(stats?.scanned_packages || 0) }}
</p>
</div>
<div class="w-12 h-12 bg-violet-50 rounded-xl flex items-center justify-center">
<i class="fas fa-shield-alt text-violet-600 text-lg"></i>
</div>
</div>
</CardContent>
</Card>
</div>
<!-- Downloads Chart -->
<Card class="border-0 shadow-lg mb-10">
<CardContent class="p-6">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-semibold text-foreground">Download Activity</h3>
<div class="flex gap-2">
<Button
v-for="period in chartPeriods"
:key="period.value"
@click="selectedPeriod = period.value"
:variant="selectedPeriod === period.value ? 'default' : 'outline'"
size="sm"
>
{{ period.label }}
</Button>
</div>
</div>
<div class="h-64 flex items-end justify-between gap-2">
<div
v-for="(value, index) in chartData"
:key="index"
class="flex-1 flex flex-col items-center gap-2"
>
<div class="w-full bg-slate-100 rounded-t-lg relative" :style="{ height: `${(value / maxChartValue) * 100}%` }">
<div class="absolute inset-0 bg-gradient-to-t from-slate-700 to-slate-500 rounded-t-lg"></div>
</div>
<span class="text-xs text-muted-foreground">{{ getChartLabel(index) }}</span>
</div>
</div>
<div v-if="chartLoading || chartData.length === 0" class="mt-4 text-center">
<p class="text-sm text-muted-foreground">
<i class="fas fa-info-circle mr-1"></i>
{{ chartLoading ? 'Loading chart data...' : 'No download activity in this period' }}
</p>
</div>
</CardContent>
</Card>
<!-- Recent Packages -->
<Card><CardContent class="p-6">
<h3 class="text-xl font-semibold text-gray-900 mb-4">
<i class="fas fa-clock mr-2"></i>Recent Packages
</h3>
<div v-if="packages.length === 0" class="text-center py-8 text-gray-500">
<i class="fas fa-inbox text-4xl mb-4"></i>
<p>No packages cached yet</p>
</div>
<div v-else class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead>
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Package
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Version
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Registry
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Size
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Downloads
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="pkg in recentPackages" :key="pkg.id">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{{ pkg.name }}
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{ pkg.version }}
</td>
<td class="px-6 py-4 whitespace-nowrap">
<Badge variant="outline" :class="getRegistryBadgeClass(pkg.registry)">
{{ pkg.registry }}
</Badge>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{ formatBytes(pkg.size) }}
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{ formatNumber(pkg.download_count) }}
</td>
</tr>
</tbody>
</table>
</div>
</CardContent>
</Card>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import axios from 'axios'
import { usePackageStore } from '../stores/packages'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { getRegistryBadgeClass } from '@/composables/useBadgeStyles'
const store = usePackageStore()
const { packages, stats, loading, error } = storeToRefs(store)
// 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)
// Fetch time-series data from API
async function fetchTimeSeriesData() {
chartLoading.value = true
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
} 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 maxChartValue = computed(() => {
if (chartData.value.length === 0) return 100
const max = Math.max(...chartData.value)
return max === 0 ? 100 : max
})
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}`
}
// API returns clean, deduplicated data - just sort and limit
const recentPackages = computed(() => {
return packages.value
.slice()
.sort((a, b) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
.slice(0, 10)
})
// Watch for period changes and fetch new data
watch(selectedPeriod, () => {
fetchTimeSeriesData()
})
onMounted(async () => {
await store.fetchStats()
await store.fetchPackages()
await fetchTimeSeriesData()
})
function formatNumber(num: number): string {
return new Intl.NumberFormat().format(num)
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}
</script>
-77
View File
@@ -1,77 +0,0 @@
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 Insights from './Insights.vue'
import { REGISTRIES, STATS, TIMESERIES, TREND } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
vi.mock('axios')
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('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('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('summarises the heatmap period next to the grid', async () => {
const { wrapper } = await open()
const summary = wrapper.get('[data-testid="heatmap-summary"]').text()
expect(summary).toContain('Total')
expect(summary).toContain(`of ${TIMESERIES.data_points.length}`)
expect(summary).toContain('Busiest day')
})
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('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)
})
})
-211
View File
@@ -1,211 +0,0 @@
<template>
<div class="flex flex-col gap-6">
<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 && !stats" variant="kpi-grid" :columns="3" label="Loading statistics..." />
<ErrorState v-else-if="error && !stats" variant="card" title="Could not load statistics" :message="error" @retry="refresh" />
<template v-else>
<Callout v-if="idleTtl > 0" type="note" size="sm">
Cached items not requested for {{ formatDuration(idleTtl) }} are removed.
</Callout>
<Card data-testid="registry-breakdown">
<CardHeader>
<CardTitle as="h2">By registry</CardTitle>
<CardDescription>Packages, disk and traffic for each upstream.</CardDescription>
</CardHeader>
<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"
/>
<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 data-testid="scan-coverage">
<CardHeader>
<CardTitle as="h2">Scan coverage</CardTitle>
<CardDescription>Share of cached package files with a scan result.</CardDescription>
</CardHeader>
<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 data-testid="daily-downloads">
<CardHeader>
<CardTitle as="h2">Daily downloads</CardTitle>
<CardDescription>The last 30 days. A stronger colour is a busier day.</CardDescription>
</CardHeader>
<CardContent>
<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." />
<div v-else class="flex flex-wrap items-start gap-x-12 gap-y-6">
<CalendarHeatmap
:data="heatData"
:start="heatStart"
:end="heatEnd"
label="Downloads per day over the last 30 days"
:cell-title="(date: string, value: number | null) => `${date}: ${value ?? 0} downloads`"
/>
<DescriptionList variant="grid" :columns="3" class="min-w-64 flex-1" data-testid="heatmap-summary">
<DescriptionItem term="Total">{{ formatNumber(heatSummary.total) }}</DescriptionItem>
<DescriptionItem term="Active days">{{ heatSummary.activeDays }} of {{ heatData.length }}</DescriptionItem>
<DescriptionItem term="Busiest day">{{ heatSummary.busiest }}</DescriptionItem>
</DescriptionList>
</div>
</CardContent>
</Card>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import axios from 'axios'
import { RouterLink } from 'vue-router'
import {
Badge,
BarChart,
Button,
CalendarHeatmap,
DescriptionItem,
DescriptionList,
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 { faRotateRight } from '@/lib/icons'
import { isoDay, type TimeSeries } from '@/lib/timeseries'
interface RegistryRow {
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: '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 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 heatPoints = ref<TimeSeries['data_points']>([])
const heatLoading = ref(false)
const heatError = ref<string | null>(null)
// 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 heatSummary = computed(() => {
const days = heatData.value
const busiest = days.reduce((max, d) => (d.value > max.value ? d : max), days[0] ?? { date: '', value: 0 })
return {
total: days.reduce((sum, d) => sum + d.value, 0),
activeDays: days.filter((d) => d.value > 0).length,
busiest: busiest.value > 0 ? `${busiest.date}, ${formatNumber(busiest.value)}` : 'None',
}
})
const heatStart = computed(() => heatData.value[0]?.date ?? '')
const heatEnd = computed(() => heatData.value[heatData.value.length - 1]?.date ?? '')
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>
-26
View File
@@ -1,26 +0,0 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader title="Page not found" />
<EmptyState
title-as="h2"
size="lg"
:icon="faMagnifyingGlass"
title="No page at this address"
:description="`Nothing lives at ${route.path}.`"
>
<template #action>
<Button as-child>
<RouterLink to="/">Back to the overview</RouterLink>
</Button>
</template>
</EmptyState>
</div>
</template>
<script setup lang="ts">
import { RouterLink, useRoute } from 'vue-router'
import { Button, EmptyState, PageHeader } from '@perfect-design/ui'
import { faMagnifyingGlass } from '@/lib/icons'
const route = useRoute()
</script>
-101
View File
@@ -1,101 +0,0 @@
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 Overview from './Overview.vue'
import { usePackageStore } from '../stores/packages'
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
import { __resetSystem } from '@/lib/system'
import { PACKAGES, REGISTRIES, STATS, SYSTEM, TIMESERIES, TOP_PACKAGES } from '@/test/fixtures'
import { serveRows } from '@/test/rowsServer'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
vi.mock('axios')
let restore: (() => void) | undefined
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.includes('layout=rows')) return { data: serveRows(url, PACKAGES) } 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
})
})
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('fetches each panel once while the stats load', async () => {
await open()
const urls = vi.mocked(axios.get).mock.calls.map(([url]) => String(url))
const count = (prefix: string) => urls.filter((u) => u.startsWith(prefix)).length
expect(count('/api/stats/timeseries')).toBe(1)
expect(count('/api/analytics/trending')).toBe(1)
expect(urls.filter((u) => u.includes('layout=rows')).length).toBe(1)
})
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('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('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('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 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...')
})
})
-210
View File
@@ -1,210 +0,0 @@
<template>
<div class="flex flex-col gap-6">
<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'"
:label="rt.connected ? 'Live' : 'Live updates paused'"
:tones="{ live: 'success', paused: 'neutral' }"
:pulse="rt.connected"
data-testid="ws-live-indicator"
/>
</template>
</PageHeader>
<PolicyLine />
<LoadingState v-if="loading && !displayStats" variant="kpi-grid" :columns="4" label="Loading statistics..." />
<ErrorState
v-else-if="error && !displayStats"
variant="card"
title="Could not load statistics"
:message="error"
@retry="refresh"
/>
<template v-else>
<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 #icon><Icon :icon="tile.icon" :class="VERDICT_TEXT[tile.verdict]" /></template>
</KpiTile>
</StatGroup>
</template>
<!-- Outside the stats loading chain: a stats refresh must not remount these and refetch their data. -->
<div class="grid items-start gap-6 xl:grid-cols-3">
<CacheCapacity
v-if="displayStats"
:used="displayStats.total_size ?? 0"
:max-size="displayStats.max_cache_size ?? 0"
:registries="registries"
/>
<LoadingState v-else-if="loading" variant="card" label="Loading cache capacity..." />
<DownloadTrend class="xl:col-span-2" />
</div>
<TopPackages />
<div class="grid gap-6 lg:grid-cols-2">
<ScannerHealth />
<Card v-if="!(error && !displayStats)" 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>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { RouterLink } from 'vue-router'
import {
ActivityFeed,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
EmptyState,
ErrorState,
Icon,
KpiTile,
LoadingState,
PageHeader,
StatGroup,
StatusBadge,
type ActivityEvent,
} from '@perfect-design/ui'
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
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 { VERDICT_LABELS, VERDICT_TEXT, type Verdict } from '@/lib/verdict'
import {
faBan,
faBox,
faBoxOpen,
faChartLine,
faCircleCheck,
faDownload,
faHourglassHalf,
faShieldHalved,
faTrash,
faUnlockKeyhole,
} from '@/lib/icons'
const store = usePackageStore()
const { stats, registries, loading, error } = storeToRefs(store)
const rt = useRealtimeStore()
const { lastStats, events: rtEvents } = storeToRefs(rt)
// 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
})
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> = {
package_cached: 'Cached',
package_deleted: 'Deleted',
package_downloaded: 'Downloaded',
scan_complete: 'Scan complete',
stats_update: 'Stats update',
}
const EVENT_ICONS: Record<EventType, IconDefinition> = {
package_cached: faBox,
package_deleted: faTrash,
package_downloaded: faDownload,
scan_complete: faShieldHalved,
stats_update: faChartLine,
}
const FEED_LENGTH = 6
const feedEvents = computed<ActivityEvent[]>(() =>
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 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}] ` : ''
return name ? `${registry}${name}${version}` : ''
}
function refresh() {
void store.fetchStats()
}
onMounted(() => {
// The realtime client is a singleton that outlives this view, so it is never disconnected here.
rt.connect()
refresh()
})
</script>
+369 -162
View File
@@ -1,209 +1,416 @@
<template>
<div class="flex flex-col gap-6">
<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>
<div class="max-w-7xl mx-auto px-4 py-8">
<!-- Header with Back Button -->
<div class="mb-6">
<Button @click="goBack" variant="ghost" class="mb-4">
<i class="fas fa-arrow-left mr-2"></i>
Back to Packages
</Button>
<div class="flex items-center gap-3">
<i class="fas fa-box text-3xl text-primary-600"></i>
<div>
<h1 class="text-3xl font-bold text-gray-900">{{ packageName }}</h1>
<div class="flex items-center gap-2 mt-2">
<Badge :class="getRegistryBadgeClass(registry)">{{ registry }}</Badge>
<Badge variant="outline" class="font-mono">v{{ version }}</Badge>
</div>
</div>
</div>
</div>
<LoadingState v-if="loading" variant="card" label="Loading package details..." />
<!-- 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 vulnerability details...</p>
</div>
<ErrorState
v-else-if="error"
variant="card"
title="Could not load this package"
:message="error"
@retry="load"
/>
<template v-else-if="report">
<Callout v-if="banner" :type="banner.type" :title="banner.title" data-testid="verdict-banner">{{ banner.body }}</Callout>
<!-- Error State -->
<Alert v-else-if="error" variant="destructive" class="mb-4">
<i class="fas fa-exclamation-circle mr-2"></i>
<AlertDescription>{{ error }}</AlertDescription>
</Alert>
<!-- Vulnerability Details -->
<div v-else-if="vulnerabilities" class="space-y-6">
<!-- Summary Card -->
<Card>
<CardHeader>
<CardTitle as="h2">Details</CardTitle>
<CardTitle class="flex items-center gap-2">
<i class="fas fa-shield-virus text-red-600"></i>
Security Scan Summary
</CardTitle>
</CardHeader>
<CardContent>
<div class="flex flex-col gap-6" data-testid="package-meta">
<DescriptionList variant="grid" :columns="3" class="items-start">
<DescriptionItem term="Size">{{ row ? formatBytes(row.size) : 'Unknown' }}</DescriptionItem>
<DescriptionItem term="Downloads">{{ row ? formatNumber(row.download_count) : 'Unknown' }}</DescriptionItem>
<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="Last scanned">
<RelativeTime v-if="report.scanned_at" :datetime="report.scanned_at" />
<template v-else>Never</template>
</DescriptionItem>
</DescriptionList>
<DescriptionList variant="grid" :columns="1" class="items-start">
<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 term="Expiry">{{ expiry }}</DescriptionItem>
</DescriptionList>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
<div class="text-center p-4 bg-red-50 rounded-lg border border-red-200">
<p class="text-3xl font-bold text-red-600">{{ severityCounts.critical }}</p>
<p class="text-sm text-gray-600 mt-1">Critical</p>
</div>
<div class="text-center p-4 bg-orange-50 rounded-lg border border-orange-200">
<p class="text-3xl font-bold text-orange-600">{{ severityCounts.high }}</p>
<p class="text-sm text-gray-600 mt-1">High</p>
</div>
<div class="text-center p-4 bg-yellow-50 rounded-lg border border-yellow-200">
<p class="text-3xl font-bold text-yellow-600">{{ severityCounts.moderate }}</p>
<p class="text-sm text-gray-600 mt-1">Moderate</p>
</div>
<div class="text-center p-4 bg-blue-50 rounded-lg border border-blue-200">
<p class="text-3xl font-bold text-blue-600">{{ severityCounts.low }}</p>
<p class="text-sm text-gray-600 mt-1">Low</p>
</div>
</div>
<Separator class="my-4" />
<div class="flex items-center justify-between text-sm">
<div class="flex flex-col gap-3">
<span class="text-gray-600">
<i class="fas fa-search mr-1"></i>
Scanned: {{ formatDate(vulnerabilities.scanned_at) }}
</span>
<div class="flex items-center gap-2">
<span class="text-gray-600">
<i class="fas fa-cog mr-1"></i>
Scanners:
</span>
<div class="flex flex-wrap gap-1">
<Badge
v-for="scanner in scannerList"
:key="scanner"
variant="secondary"
class="text-xs"
>
{{ scanner }}
</Badge>
</div>
</div>
</div>
<div v-if="bypassedCount > 0" class="flex items-center gap-2 text-green-600">
<i class="fas fa-check-circle"></i>
<span>{{ bypassedCount }} bypassed</span>
</div>
</div>
</CardContent>
</Card>
<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>
<!-- No Vulnerabilities -->
<Card v-if="vulnerabilityList.length === 0">
<CardContent class="text-center py-12">
<i class="fas fa-check-circle text-6xl text-green-500 mb-4"></i>
<p class="text-xl font-semibold text-gray-900">No Vulnerabilities Found</p>
<p class="mt-2 text-gray-600">This package is clean and safe to use</p>
</CardContent>
</Card>
<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" />
<!-- Vulnerability List -->
<Card v-else>
<CardHeader>
<CardTitle class="flex items-center gap-2">
<i class="fas fa-list text-gray-600"></i>
Detected Vulnerabilities ({{ vulnerabilityList.length }})
</CardTitle>
</CardHeader>
<CardContent class="p-0">
<div class="border-t overflow-x-auto">
<Table class="min-w-[800px]">
<TableHeader>
<TableRow class="bg-gray-50 hover:bg-gray-50">
<TableHead class="w-[100px]">Severity</TableHead>
<TableHead class="w-[180px]">CVE ID</TableHead>
<TableHead>Description</TableHead>
<TableHead class="w-[120px]">Fix Version</TableHead>
<TableHead class="w-[100px] text-center">Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<template v-for="(vuln, index) in vulnerabilityList" :key="vuln.id">
<!-- Main Row -->
<TableRow
:class="getRowClass(index, vuln.severity)"
@click="toggleRow(index)"
>
<TableCell>
<Badge :class="getSeverityBadgeClass(vuln.severity)">
{{ formatSeverityName(vuln.severity) }}
</Badge>
<span
v-if="vuln.bypassed"
class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800"
title="Bypassed"
>
<i class="fas fa-unlock text-xs"></i>
</span>
</TableCell>
<TableCell>
<span class="font-mono text-sm font-medium">{{ vuln.id }}</span>
</TableCell>
<TableCell>
<p class="text-sm text-gray-900 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
</TableCell>
<TableCell>
<span v-if="vuln.fixed_in" class="inline-flex items-center text-sm text-green-700">
<i class="fas fa-arrow-up text-xs mr-1"></i>
v{{ vuln.fixed_in }}
</span>
<span v-else class="text-sm text-gray-400">-</span>
</TableCell>
<TableCell class="text-center">
<Button
variant="ghost"
size="sm"
class="h-8 w-8 p-0"
@click.stop="toggleRow(index)"
>
<i
:class="[
'fas transition-transform',
expandedRows.has(index) ? 'fa-chevron-up' : 'fa-chevron-down'
]"
></i>
</Button>
</TableCell>
</TableRow>
<!-- Expanded Details Row -->
<TableRow v-if="expandedRows.has(index)" class="bg-gray-50 hover:bg-gray-50">
<TableCell colspan="5" class="p-0">
<div class="px-6 py-4 space-y-3">
<!-- Full Description -->
<div>
<h5 class="font-semibold text-gray-900 mb-2">Description</h5>
<div
class="text-sm text-gray-700 leading-relaxed prose prose-sm max-w-none break-words overflow-hidden"
v-html="renderMarkdown(vuln.description)"
></div>
</div>
<!-- Bypass Information -->
<div v-if="vuln.bypassed && vuln.bypass" class="bg-green-50 border border-green-200 rounded-lg p-3">
<h5 class="font-semibold text-green-900 mb-2 flex items-center gap-2">
<i class="fas fa-info-circle"></i>
Bypass Active
</h5>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-green-800">
<div class="break-words">
<span class="font-medium">Reason:</span> {{ vuln.bypass.reason }}
</div>
<div class="break-words">
<span class="font-medium">By:</span> {{ vuln.bypass.created_by }}
</div>
<div class="break-words">
<span class="font-medium">Expires:</span> {{ formatDate(vuln.bypass.expires_at) }}
</div>
</div>
</div>
<!-- Fix Information -->
<div v-if="vuln.fixed_in" class="bg-blue-50 border border-blue-200 rounded-lg p-3">
<div class="flex items-center gap-2">
<i class="fas fa-wrench text-blue-700"></i>
<span class="text-sm text-blue-900">
<span class="font-semibold">Fix Available:</span> Upgrade to version <strong>{{ vuln.fixed_in }}</strong> or later
</span>
</div>
</div>
<!-- References -->
<div v-if="vuln.references && vuln.references.length > 0">
<h5 class="font-semibold text-gray-900 mb-2 flex items-center gap-2">
<i class="fas fa-link"></i>
References ({{ vuln.references.length }})
</h5>
<div class="space-y-1.5">
<div
v-for="(ref, refIndex) in vuln.references"
:key="refIndex"
class="flex items-start gap-2 text-sm"
>
<i class="fas fa-external-link-alt text-gray-400 text-xs mt-0.5"></i>
<a
:href="ref"
target="_blank"
rel="noopener noreferrer"
class="text-blue-600 hover:text-blue-800 hover:underline break-all"
>
{{ ref }}
</a>
</div>
</div>
</div>
</div>
</TableCell>
</TableRow>
</template>
</TableBody>
</Table>
</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" :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"
/>
</TabsContent>
</Tabs>
</template>
</CardContent>
</Card>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import { marked } from 'marked'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Separator } from '@/components/ui/separator'
import {
Badge,
Callout,
Card,
CardContent,
CardHeader,
CardTitle,
DescriptionItem,
DescriptionList,
EmptyState,
ErrorState,
LoadingState,
PageHeader,
RelativeTime,
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from '@perfect-design/ui'
import SeveritySummary from './SeveritySummary.vue'
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'
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
getSeverityBadgeClass,
getRegistryBadgeClass,
getVulnerabilityBorderClass,
formatSeverityName,
} from '@/composables/useBadgeStyles'
const TABS = ['vulnerabilities', 'inspectors', 'downloads', 'bypass'] as const
type TabName = (typeof TABS)[number]
// Configure marked
marked.setOptions({
breaks: true,
gfm: true,
})
const route = useRoute()
const router = useRouter()
const system = useSystem()
const route = useRoute()
const registry = computed(() => route.params.registry as string)
// Names with slashes (scoped npm, Go modules) arrive as segments.
const packageName = computed(() => {
const name = route.params.name
return Array.isArray(name) ? name.join('/') : (name as string)
// 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 version = computed(() => route.params.version as string)
const shownVersion = computed(() => report.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 {
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 loading = ref(false)
const error = ref<string | null>(null)
const report = ref<PackageReport | null>(null)
const row = ref<Package | null>(null)
const vulnerabilities = ref<VulnerabilityResponse | null>(null)
const expandedRows = ref<Set<number>>(new Set())
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 } }))
// Severity order for sorting (higher values = more severe)
const severityOrder: Record<string, number> = {
CRITICAL: 4,
HIGH: 3,
MEDIUM: 2,
MODERATE: 2, // Treat MODERATE same as MEDIUM
LOW: 1,
UNKNOWN: 0,
}
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 vulnerabilityList = computed(() => {
const vulns = vulnerabilities.value?.vulnerabilities || []
// Sort by severity (most severe first)
return [...vulns].sort((a, b) => {
const severityA = severityOrder[a.severity.toUpperCase()] || 0
const severityB = severityOrder[b.severity.toUpperCase()] || 0
return severityB - severityA // Descending order
})
})
const upstream = computed(() => system.info.value?.upstreams[registry.value] || 'Not reported')
const severityCounts = computed(() => vulnerabilities.value?.severity_counts || { critical: 0, high: 0, moderate: 0, low: 0 })
const bypassedCount = computed(() => vulnerabilities.value?.bypassed_count || 0)
// 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`
// 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())
})
async function load() {
onMounted(() => {
fetchVulnerabilities()
})
async function fetchVulnerabilities() {
loading.value = true
error.value = null
report.value = null
vulnerabilities.value = null
try {
const encoded = `${registry.value}/${packageName.value}/${version.value}`
const [details, single] = await Promise.all([
axios.get<PackageReport>(`/api/packages/${encoded}/vulnerabilities`),
axios.get<Package>(`/api/packages/${encoded}`).catch(() => null),
system.load(),
])
report.value = details.data
row.value = single?.data ?? 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'
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'
} finally {
loading.value = false
}
}
onMounted(load)
function goBack() {
router.push('/packages')
}
function toggleRow(index: number) {
if (expandedRows.value.has(index)) {
expandedRows.value.delete(index)
} else {
expandedRows.value.add(index)
}
}
function getRowClass(index: number, severity: string): string {
const classes = ['cursor-pointer']
if (expandedRows.value.has(index)) {
classes.push('bg-gray-50')
}
classes.push(getVulnerabilityBorderClass(severity))
return classes.join(' ')
}
function formatDate(date: string): string {
return new Date(date).toLocaleString()
}
function renderMarkdown(text: string): string {
if (!text) return ''
return marked.parse(text) as string
}
</script>
+155 -113
View File
@@ -1,145 +1,187 @@
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises, mount } from '@vue/test-utils'
import PackageList from './PackageList.vue'
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 wrapper = mount(PackageList, { props: { registry: router.currentRoute.value.params.registry as string | undefined }, global: { plugins: [pinia, router] } })
await flushPromises()
return { wrapper, router }
}
import { usePackageStore } from '../stores/packages'
describe('PackageList.vue', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
// Create a fresh pinia instance before each test
setActivePinia(createPinia())
})
it('renders the page heading', async () => {
const { wrapper } = await open()
expect(wrapper.find('h1').text()).toBe('Packages')
it('renders package list component', () => {
const wrapper = mount(PackageList)
expect(wrapper.find('h2').text()).toBe('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 loading state when loading', async () => {
const wrapper = mount(PackageList)
const store = usePackageStore()
store.loading = true
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Loading packages...')
})
it('displays the error message when the load fails', async () => {
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()
it('displays error message when error occurs', async () => {
const wrapper = mount(PackageList)
const store = usePackageStore()
store.error = 'Failed to fetch packages'
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Failed to fetch packages')
})
it('displays an empty state when nothing is cached', async () => {
const { wrapper } = await open('/packages', [])
it('displays empty state when no packages', async () => {
const wrapper = mount(PackageList)
const store = usePackageStore()
store.loading = false
store.packages = []
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('No packages cached yet')
})
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('displays package accordion when packages exist', async () => {
const wrapper = mount(PackageList)
const store = usePackageStore()
store.loading = false
store.packages = [
{
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('debounces the search box into one request', async () => {
const { wrapper } = await open()
vi.mocked(axios.get).mockClear()
const input = wrapper.get('input[aria-label="Search packages"]')
it('calls fetchPackages on mount', () => {
const store = usePackageStore()
const fetchSpy = vi.spyOn(store, 'fetchPackages')
await input.setValue('r')
await input.setValue('re')
await input.setValue('requests')
await vi.advanceTimersByTimeAsync(100)
expect(axios.get).not.toHaveBeenCalled()
mount(PackageList)
await vi.advanceTimersByTimeAsync(400)
await flushPromises()
expect(axios.get).toHaveBeenCalledTimes(1)
expect(lastUrl().get('q')).toBe('requests')
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
expect(fetchSpy).toHaveBeenCalled()
})
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('groups packages and displays version counts', async () => {
const wrapper = mount(PackageList)
const store = usePackageStore()
store.loading = false
store.packages = [
{
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 vi.advanceTimersByTimeAsync(400)
await flushPromises()
expect(router.currentRoute.value.query.q).toBe('left')
it('formats bytes correctly', async () => {
const wrapper = mount(PackageList)
const store = usePackageStore()
store.loading = false
store.packages = [
{
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 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('applies correct registry badge classes', async () => {
const wrapper = mount(PackageList)
const store = usePackageStore()
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')
})
store.loading = false
store.packages = [
{
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,
},
{
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,
},
]
await wrapper.vm.$nextTick()
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')
// Verify that all registry badges are displayed
// Packages are grouped and sorted alphabetically, so order is: go-module, npm-package, python-package
expect(wrapper.text()).toContain('npm')
expect(wrapper.text()).toContain('pypi')
expect(wrapper.text()).toContain('go')
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' } 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')
// Verify badge component is used with correct classes
const html = wrapper.html()
expect(html).toContain('bg-blue-100') // npm badge
expect(html).toContain('bg-green-100') // pypi badge
expect(html).toContain('bg-yellow-100') // go badge
})
})
+376 -220
View File
@@ -1,241 +1,370 @@
<template>
<div class="flex flex-col gap-6">
<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-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>
<div class="flex justify-between items-center mb-8">
<h2 class="text-3xl font-bold text-gray-900">Packages</h2>
<Button @click="store.fetchPackages()">
<i class="fas fa-sync-alt mr-2"></i>Refresh
</Button>
</div>
<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="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="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">
{{ rangeStart }}–{{ rangeEnd }} of {{ plural(total, 'package version') }}
</p>
<DataTable
v-model:sort="sort"
label="Cached packages"
layout="cards"
density="compact"
row-clickable
:loading="loading"
:columns="columns"
:rows="rows"
@row-click="(row: Package) => (selected = row)"
<!-- Filter and Search Section -->
<div class="mb-6 flex flex-col sm:flex-row items-start sm:items-center gap-4">
<div class="flex items-center gap-2">
<span class="text-sm font-medium text-gray-700">Filter by registry:</span>
<div class="flex gap-2">
<Button
@click="changeRegistryFilter('all')"
:variant="selectedRegistry === 'all' ? 'default' : 'outline'"
size="sm"
>
<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>
<Pagination
v-if="total > PAGE_SIZE"
v-model:page="page"
class="mt-4"
:total="total"
:page-size="PAGE_SIZE"
aria-label="Package pages"
/>
</template>
All
</Button>
<Button
@click="changeRegistryFilter('npm')"
:variant="selectedRegistry === 'npm' ? 'default' : 'outline'"
size="sm"
>
<i class="fab fa-npm mr-2"></i>NPM
</Button>
<Button
@click="changeRegistryFilter('pypi')"
:variant="selectedRegistry === 'pypi' ? 'default' : 'outline'"
size="sm"
>
<i class="fab fa-python mr-2"></i>PyPI
</Button>
<Button
@click="changeRegistryFilter('go')"
:variant="selectedRegistry === 'go' ? 'default' : 'outline'"
size="sm"
>
<i class="fas fa-code mr-2"></i>Go
</Button>
</div>
</div>
<div class="flex items-center gap-2 w-full sm:w-auto sm:ml-auto">
<i class="fas fa-search text-gray-500"></i>
<Input
v-model="searchTerm"
type="text"
placeholder="Search packages..."
class="w-full sm:w-64"
/>
</div>
</div>
<!-- Error Alert -->
<Alert v-if="error" variant="destructive" class="mb-4">
<i class="fas fa-exclamation-circle mr-2"></i>
<AlertDescription>{{ error }}</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 packages...</p>
</div>
<!-- Package List -->
<Card v-else>
<CardContent class="p-6">
<div v-if="packages.length === 0" class="text-center py-12 text-gray-500">
<i class="fas fa-inbox text-6xl mb-4"></i>
<p class="text-xl">No packages cached yet</p>
<p class="mt-2">Packages will appear here once they are downloaded through the proxy</p>
</div>
<Accordion v-else type="multiple" class="w-full">
<AccordionItem
v-for="group in groupedPackages"
:key="`${group.registry}:${group.name}`"
:value="`${group.registry}:${group.name}`"
class="border-b border-gray-200"
>
<AccordionTrigger class="px-4 py-4 hover:bg-gray-50">
<div class="flex items-center justify-between w-full pr-4">
<div class="flex items-center space-x-4">
<div class="text-left">
<h4 class="font-semibold text-gray-900">{{ group.name }}</h4>
<p class="text-sm text-gray-500">{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}</p>
</div>
</div>
<div class="flex items-center space-x-6">
<Badge variant="outline" :class="getRegistryBadgeClass(group.registry)">
{{ group.registry }}
</Badge>
<div class="text-right">
<p class="text-sm font-medium text-gray-900">{{ formatBytes(group.totalSize) }}</p>
<p class="text-xs text-gray-500">{{ formatNumber(group.totalDownloads) }} downloads</p>
</div>
</div>
</div>
</AccordionTrigger>
<AccordionContent class="px-4 pb-4">
<div class="space-y-3">
<div
v-for="version in group.versions"
:key="version.id"
class="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100"
>
<div class="flex items-center space-x-4 flex-1">
<div class="flex-1">
<p class="font-medium text-gray-900">{{ version.version.startsWith('v') ? version.version : 'v' + version.version }}</p>
<div class="flex items-center space-x-4 mt-1 text-sm text-gray-500">
<span>
<i class="fas fa-download mr-1"></i>{{ formatNumber(version.download_count) }}
</span>
<span>
<i class="fas fa-hard-drive mr-1"></i>{{ formatBytes(version.size) }}
</span>
<span>
<i class="fas fa-clock mr-1"></i>{{ formatDate(version.cached_at) }}
</span>
</div>
<!-- Vulnerability Badge -->
<div v-if="version.vulnerabilities" class="mt-2">
<VulnerabilityBadge
:scanned="version.vulnerabilities.scanned"
:status="version.vulnerabilities.status"
:counts="version.vulnerabilities.counts"
:total="version.vulnerabilities.total"
:scannedAt="version.vulnerabilities.scannedAt"
@click="showVulnerabilityDetails(group.registry, group.name, version.version)"
/>
</div>
</div>
</div>
<button
@click="confirmDelete(version)"
class="text-red-600 hover:text-red-900 p-2"
title="Delete this version"
>
<i class="fas fa-trash"></i>
</button>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
<!-- Pagination -->
<div v-if="totalPages > 1" class="mt-6 flex items-center justify-between border-t pt-4">
<div class="text-sm text-gray-700">
Page {{ currentPage }} of {{ totalPages }} ({{ allGroupedPackages.length }} total packages)
</div>
<div class="flex items-center gap-2">
<Button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1"
variant="outline"
size="sm"
>
<i class="fas fa-chevron-left mr-2"></i>Previous
</Button>
<div class="flex gap-1">
<!-- First page -->
<Button
v-if="currentPage > 3"
@click="changePage(1)"
variant="outline"
size="sm"
>
1
</Button>
<span v-if="currentPage > 4" class="px-2">...</span>
<!-- Page numbers around current page -->
<Button
v-for="page in getPageNumbers()"
:key="page"
@click="changePage(page)"
:variant="page === currentPage ? 'default' : 'outline'"
size="sm"
>
{{ page }}
</Button>
<span v-if="currentPage < totalPages - 3" class="px-2">...</span>
<!-- Last page -->
<Button
v-if="currentPage < totalPages - 2"
@click="changePage(totalPages)"
variant="outline"
size="sm"
>
{{ totalPages }}
</Button>
</div>
<Button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages"
variant="outline"
size="sm"
>
Next<i class="fas fa-chevron-right ml-2"></i>
</Button>
</div>
</div>
</CardContent>
</Card>
<PackageQuickView :pkg="selected" @close="selected = null" @delete="confirmDelete" />
<!-- Delete Confirmation Dialog -->
<Dialog v-model:open="showDeleteModal">
<DialogContent>
<DialogHeader>
<DialogTitle>Confirm Deletion</DialogTitle>
<DialogDescription>
Are you sure you want to delete <strong>{{ packageToDelete?.name }}@{{ packageToDelete?.version }}</strong>?
This action cannot be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button @click="showDeleteModal = false" variant="outline">
Cancel
</Button>
<Button @click="deletePackage" variant="destructive">
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmDialog
v-model:open="showDeleteModal"
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"
/>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import { onMounted, ref, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { usePackageStore, type Package } from '../stores/packages'
import {
Badge,
Button,
Card,
CardContent,
ConfirmDialog,
DataTable,
EmptyState,
ErrorState,
FilterBar,
LoadingState,
PageHeader,
Pagination,
RelativeTime,
SearchInput,
useToastStore,
type DataTableColumn,
type FilterField,
type FilterItem,
type SortState,
} from '@perfect-design/ui'
import PackageQuickView from './parts/PackageQuickView.vue'
import VerdictBadge from './parts/VerdictBadge.vue'
import { usePackageStore, type ApiVerdict, type Package } from '../stores/packages'
import { plural } from '@/lib/reason'
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
import { packageRoute } from '@/lib/packages'
import { usePackageRows, type RowQuery, type RowSort } from '@/lib/packageRows'
import { faBoxOpen, faMagnifyingGlass, faRotateRight } from '@/lib/icons'
import { VERDICT_OPTIONS, verdictOf } from '@/lib/verdict'
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from '@/components/ui/accordion'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { getRegistryBadgeClass } from '@/composables/useBadgeStyles'
const props = defineProps<{ registry?: string }>()
// Props from router
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 { rows, total, loading, error, load: loadRows } = usePackageRows()
const store = usePackageStore()
const { packages, loading, error } = storeToRefs(store)
const loaded = ref(false)
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)
const selectedRegistry = ref<string>(props.registry || 'all')
const searchTerm = ref<string>('')
const currentPage = ref<number>(1)
const itemsPerPage = ref<number>(10)
function queryText(key: string): string {
const raw = route.query[key]
return typeof raw === 'string' ? raw : ''
}
// Group packages by name
const allGroupedPackages = computed(() => {
const groups = new Map<string, Package[]>()
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))
// Filter packages by selected registry and search term
let filteredPackages = selectedRegistry.value === 'all'
? packages.value
: packages.value.filter(pkg => pkg.registry === selectedRegistry.value)
let nextFilterId = 0
function filterItem(field: string, value: string): FilterItem {
return { id: `f${nextFilterId++}`, field, operator: 'eq', value }
}
// Apply search filter if search term exists
if (searchTerm.value.trim()) {
const searchLower = searchTerm.value.toLowerCase()
filteredPackages = filteredPackages.filter(pkg =>
pkg.name.toLowerCase().includes(searchLower) ||
pkg.version.toLowerCase().includes(searchLower)
)
}
// 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)),
],
)
filteredPackages.forEach(pkg => {
const key = `${pkg.registry}:${pkg.name}`
if (!groups.has(key)) {
groups.set(key, [])
}
groups.get(key)!.push(pkg)
})
const registryOptions = computed(() => {
const seen = new Set([...KNOWN_REGISTRIES, ...rows.value.map((p) => p.registry), ...valuesOf('registry')])
return [...seen].map((value) => ({ value, label: value }))
// Convert to array and sort versions within each group
return Array.from(groups.entries()).map(([key, versions]) => {
const [registry, name] = key.split(':')
return {
registry,
name,
versions: versions.sort((a, b) =>
new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime()
),
totalSize: versions.reduce((sum, v) => sum + v.size, 0),
totalDownloads: versions.reduce((sum, v) => sum + v.download_count, 0),
}
}).sort((a, b) => a.name.localeCompare(b.name))
})
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'] },
])
// Pagination
const totalPages = computed(() => Math.ceil(allGroupedPackages.value.length / itemsPerPage.value))
function valuesOf(field: string): string[] {
return filterItems.value.filter((f) => f.field === field).map((f) => String(f.value))
}
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([searchTerm, filterItems], () => {
const { q: _q, registry: _r, verdict: _v, ...rest } = route.query
const next: Record<string, string> = {}
if (searchTerm.value.trim()) next.q = searchTerm.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 groupedPackages = computed(() => {
const start = (currentPage.value - 1) * itemsPerPage.value
const end = start + itemsPerPage.value
return allGroupedPackages.value.slice(start, end)
})
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' },
{ key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 },
]
async function load() {
await loadRows(rowQuery.value)
loaded.value = true
function changePage(page: number) {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page
// Scroll to top of packages list
window.scrollTo({ top: 0, behavior: 'smooth' })
}
}
watch(rowQuery, load)
onMounted(load)
// Get page numbers to display around current page
function getPageNumbers(): number[] {
const pages: number[] = []
const start = Math.max(1, currentPage.value - 2)
const end = Math.min(totalPages.value, currentPage.value + 2)
for (let i = start; i <= end; i++) {
pages.push(i)
}
return pages
}
// Reset to page 1 when filters change
function resetPagination() {
currentPage.value = 1
}
// Watch for filter/search changes and reset pagination
watch([selectedRegistry, searchTerm], () => {
resetPagination()
})
// Watch for route parameter changes to update filter
watch(() => route.params.registry, (newRegistry) => {
selectedRegistry.value = (newRegistry as string) || 'all'
})
onMounted(async () => {
await store.fetchPackages()
})
function confirmDelete(pkg: Package) {
packageToDelete.value = pkg
@@ -243,20 +372,47 @@ function confirmDelete(pkg: Package) {
}
async function deletePackage() {
const target = packageToDelete.value
if (!target) return
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 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 removed', label)
await load()
if (packageToDelete.value) {
await store.deletePackage(
packageToDelete.value.registry,
packageToDelete.value.name,
packageToDelete.value.version
)
showDeleteModal.value = false
packageToDelete.value = null
}
}
function formatNumber(num: number): string {
return new Intl.NumberFormat().format(num)
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i]
}
function formatDate(date: string): string {
return new Date(date).toLocaleString()
}
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>
-282
View File
@@ -1,282 +0,0 @@
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 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')
function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package {
const full = { critical: 0, high: 0, moderate: 0, low: 0, ...counts }
return {
id: name,
registry: 'npm',
name,
version: '1.0.0',
size: 1024,
cached_at: '2026-01-03T10:00:00Z',
last_accessed: '2026-01-03T10:00:00Z',
download_count: 1,
vulnerabilities: {
scanned: true,
status: 'vulnerable',
counts: full,
total: full.critical + full.high + full.moderate + full.low,
scannedAt: '2026-01-03T10:05:00Z',
isBlocked: false,
},
}
}
const FIXTURE: Package[] = [
vulnerable('alpha-critical', { critical: 1 }),
vulnerable('bravo-high', { high: 2 }),
vulnerable('charlie-moderate', { moderate: 1 }),
vulnerable('delta-mixed', { critical: 1, moderate: 3 }),
]
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())
serve(FIXTURE)
})
afterEach(() => {
restore?.()
restore = undefined
vi.restoreAllMocks()
})
async function open(path = '/security?tab=allowed') {
const router = await createTestRouter(path)
const pinia = createPinia()
setActivePinia(pinia)
const mounted = await mountStrict(Security, { global: { plugins: [pinia, router] } })
restore = mounted.restore
await flushPromises()
return { ...mounted, router }
}
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
const tile = (wrapper: Wrapper, severity: string) => wrapper.get(`button[data-severity="${severity}"]`)
const shown = (wrapper: Wrapper) => NAMES.filter((name) => wrapper.text().includes(name))
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('Security severity filter', () => {
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
const { wrapper, problems, router } = await open()
expect(problems).toEqual([])
expect(shown(wrapper)).toEqual(NAMES)
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
expect(wrapper.text()).not.toContain('Filter on')
expect(clearButtons(wrapper)).toHaveLength(0)
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('asks the server for one page of the open tab, worst first', async () => {
await open()
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 () => {
const { wrapper } = await open()
const tiles = wrapper.findAll('button[data-severity]')
expect(tiles.map((t) => t.attributes('data-severity'))).toEqual(['critical', 'high', 'moderate', 'low'])
for (const t of tiles) {
expect(t.element.tagName).toBe('BUTTON')
expect(t.attributes('type')).toBe('button')
expect(t.attributes('tabindex')).not.toBe('-1')
expect(t.attributes('aria-pressed')).toBeDefined()
}
})
it('one click filters to that severity and shows the state in text, not colour alone', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'high').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['bravo-high'])
expect(pressed(wrapper)).toEqual(['false', 'true', 'false', 'false'])
expect(tile(wrapper, 'high').text()).toContain('Filter on')
expect(tile(wrapper, 'critical').text()).not.toContain('Filter on')
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('Showing packages with high vulnerabilities.')
expect(clearButtons(wrapper)).toHaveLength(1)
expect(router.currentRoute.value.query.severity).toBe('high')
})
it('keeps the tile counts of the whole list while a filter is on', async () => {
const { wrapper } = await open()
const before = tile(wrapper, 'critical').text()
await tile(wrapper, 'high').trigger('click')
await flushPromises()
expect(tile(wrapper, 'critical').text()).toBe(before)
expect(tile(wrapper, 'critical').text()).toContain('2 packages')
})
it('selects several severities with OR semantics', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'critical').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['alpha-critical', 'delta-mixed'])
await tile(wrapper, 'high').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
expect(router.currentRoute.value.query.severity).toBe('critical,high')
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('critical or high')
})
it('a second click toggles the filter off and removes the query', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'moderate').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(['charlie-moderate', 'delta-mixed'])
await tile(wrapper, 'moderate').trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(NAMES)
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
expect(clearButtons(wrapper)).toHaveLength(0)
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('Clear filters resets every selected severity at once', async () => {
const { wrapper, router } = await open()
await tile(wrapper, 'critical').trigger('click')
await tile(wrapper, 'high').trigger('click')
await flushPromises()
await clearButtons(wrapper)[0]!.trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(NAMES)
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('restores the filter from the URL, as after a reload or a shared link', async () => {
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'])
expect(clearButtons(wrapper)).toHaveLength(1)
})
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
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({ 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('/security?tab=allowed&severity=low')
const empty = wrapper.get('[data-slot="empty-state"]')
expect(empty.text()).toContain('No packages match the filter')
expect(shown(wrapper)).toEqual([])
// The tiles stay so the filter can be changed without leaving the page.
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'true'])
await empty.findAll('button').find((b) => b.text() === 'Clear filters')!.trigger('click')
await flushPromises()
expect(shown(wrapper)).toEqual(NAMES)
expect(wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
expect(router.currentRoute.value.query.severity).toBeUndefined()
})
it('keeps the success state when nothing has findings, filter or not', async () => {
serve([])
const { wrapper } = await open('/security?tab=allowed&severity=critical')
expect(wrapper.text()).toContain('No package carries findings under the policy')
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
})
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'
serve([...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' }
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)')
})
})
-236
View File
@@ -1,236 +0,0 @@
<template>
<div class="flex flex-col gap-6">
<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 && !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="anyFindings"
v-model="selectedSeverities"
selectable
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="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>
<Tabs v-model="tab">
<TabsList aria-label="Security sections">
<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">
<Card>
<CardHeader>
<CardTitle as="h2">{{ t.label }}</CardTitle>
<CardDescription>{{ t.description }}</CardDescription>
</CardHeader>
<CardContent>
<EmptyState
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"
>
<template v-if="hasFilter" #action>
<Button variant="outline" @click="selectedSeverities = []">Clear filters</Button>
</template>
</EmptyState>
<DataTable
v-else
v-model:sort="sort"
:label="t.label"
layout="cards"
density="compact"
row-clickable
:loading="loading"
:columns="columnsFor(t.value)"
:rows="rows"
@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>
</template>
<template #cell-scanned="{ row }">
<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>
</Tabs>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import {
Badge,
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
DataTable,
EmptyState,
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 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 { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
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 route = useRoute()
const router = useRouter()
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 } }))
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
}
// The URL is the source of truth, so a reload or a shared link restores the filter.
const selectedSeverities = computed<SeverityLevel[]>({
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
set: (levels) => {
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
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 && anyFindings.value)
const filterSummary = computed(() => selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '))
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,
}
})
watch([tab, selectedSeverities, sort], () => (page.value = 1))
const BASE_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: 'findings', header: 'Findings', accessor: (p) => p.vulnerabilities?.total ?? 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]
if (name === 'bypassed') return [...BASE_COLUMNS, { key: 'bypass', header: 'Bypass', accessor: (p) => p.vulnerabilities?.bypass?.created_by ?? '' }, SCANNED]
return [...BASE_COLUMNS, SCANNED]
}
function open(pkg: Package) {
void router.push(packageRoute(pkg))
}
async function load() {
await loadRows(rowQuery.value)
loaded.value = true
}
watch(rowQuery, load)
onMounted(load)
</script>
@@ -1,66 +0,0 @@
<template>
<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"
:key="level"
as="button"
type="button"
variant="interactive"
:label="formatSeverityName(level)"
:value="counts[level]"
:aria-pressed="isSelected(level)"
:class="['text-left', isSelected(level) && 'ring-2 ring-primary']"
:data-severity="level"
@click="toggle(level)"
>
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
<template #hint>
<span v-if="packageCounts">{{ formatPackageCount(packageCounts[level]) }}</span>
<span v-if="isSelected(level)" class="font-medium text-foreground" data-testid="severity-filter-on">
{{ packageCounts ? ' · ' : '' }}Filter on
</span>
</template>
</KpiTile>
</template>
<template v-else>
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
</KpiTile>
</template>
</StatGroup>
</template>
<script setup lang="ts">
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
import type { VulnerabilityCounts } from '../stores/packages'
import { plural } from '@/lib/reason'
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
const props = defineProps<{
counts: VulnerabilityCounts
label: string
/** Tiles become toggle buttons that edit `modelValue`. */
selectable?: boolean
/** Selected severities; several are allowed. */
modelValue?: readonly SeverityLevel[]
/** Packages per severity, shown on each tile in selectable mode. */
packageCounts?: VulnerabilityCounts
}>()
const emit = defineEmits<{ 'update:modelValue': [value: SeverityLevel[]] }>()
function isSelected(level: SeverityLevel): boolean {
return props.modelValue?.includes(level) ?? false
}
function toggle(level: SeverityLevel) {
const current = props.modelValue ?? []
const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level]
emit('update:modelValue', SEVERITY_LEVELS.filter((l) => next.includes(l)))
}
function formatPackageCount(n: number): string {
return plural(n, 'package')
}
</script>
+192
View File
@@ -0,0 +1,192 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import Stats from './Stats.vue'
import { usePackageStore } from '../stores/packages'
describe('Stats.vue', () => {
beforeEach(() => {
setActivePinia(createPinia())
})
it('renders stats component', () => {
const wrapper = mount(Stats)
expect(wrapper.find('h2').text()).toBe('Statistics')
})
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('displays error message when error occurs', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.error = 'Failed to fetch statistics'
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Failed to fetch statistics')
})
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
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
}
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,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
}
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,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
}
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 Registry')
expect(wrapper.text()).toContain('PyPI Registry')
expect(wrapper.text()).toContain('Go Modules')
expect(wrapper.text()).toContain('50 packages')
expect(wrapper.text()).toContain('30 packages')
expect(wrapper.text()).toContain('20 packages')
})
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
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
}
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('displays correct icon colors for different registries', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 3,
total_size: 0,
total_downloads: 0,
scanned_packages: 0,
vulnerable_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 containers = wrapper.findAll('.rounded-full')
expect(containers[0].classes()).toContain('bg-red-100') // npm
expect(containers[1].classes()).toContain('bg-blue-100') // pypi
expect(containers[2].classes()).toContain('bg-cyan-100') // go
})
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,
total_downloads: 0,
scanned_packages: 0,
vulnerable_packages: 0,
}
store.registries = {}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Registry Breakdown')
// Should have no registry items
const registryItems = wrapper.findAll('.bg-gray-50')
expect(registryItems.length).toBe(3) // Only the overall stats cards
})
})
+194
View File
@@ -0,0 +1,194 @@
<template>
<div>
<h2 class="text-3xl font-bold text-gray-900 mb-8">Statistics</h2>
<!-- Error Alert -->
<Alert v-if="error" variant="destructive" class="mb-4">
<i class="fas fa-exclamation-circle mr-2"></i>
<AlertDescription>{{ error }}</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 statistics...</p>
</div>
<!-- Stats Cards -->
<div v-else>
<!-- Overall Stats -->
<Card class="mb-8">
<CardContent class="p-6">
<h3 class="text-xl font-semibold text-gray-900 mb-6">
<i class="fas fa-chart-bar mr-2"></i>Overall Statistics
</h3>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="text-center p-6 bg-gray-50 rounded-lg">
<p class="text-4xl font-bold text-primary-600 mb-2">
{{ formatNumber(stats?.total_packages || 0) }}
</p>
<p class="text-sm text-gray-600">Total Packages</p>
</div>
<div class="text-center p-6 bg-gray-50 rounded-lg">
<p class="text-4xl font-bold text-blue-600 mb-2">
{{ formatBytes(stats?.total_size || 0) }}
</p>
<p class="text-sm text-gray-600">Total Storage Used</p>
</div>
<div class="text-center p-6 bg-gray-50 rounded-lg">
<p class="text-4xl font-bold text-green-600 mb-2">
{{ formatNumber(stats?.total_downloads || 0) }}
</p>
<p class="text-sm text-gray-600">Total Downloads</p>
</div>
</div>
</CardContent>
</Card>
<!-- Security Stats -->
<Card class="mb-8">
<CardContent class="p-6">
<h3 class="text-xl font-semibold text-gray-900 mb-6">
<i class="fas fa-shield-alt mr-2"></i>Security Scanning
</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="flex items-center justify-between p-6 bg-green-50 rounded-lg border border-green-200">
<div>
<p class="text-3xl font-bold text-green-600">
{{ formatNumber(stats?.scanned_packages || 0) }}
</p>
<p class="text-sm text-gray-600 mt-1">Scanned Packages</p>
</div>
<i class="fas fa-check-circle text-5xl text-green-400"></i>
</div>
<div
@click="showVulnerablePackages"
class="flex items-center justify-between p-6 bg-red-50 rounded-lg border border-red-200 cursor-pointer hover:bg-red-100 transition-colors"
:class="{ 'opacity-50': (stats?.vulnerable_packages || 0) === 0 }"
>
<div>
<p class="text-3xl font-bold text-red-600">
{{ formatNumber(stats?.vulnerable_packages || 0) }}
</p>
<p class="text-sm text-gray-600 mt-1">
Vulnerable Packages
<span v-if="(stats?.vulnerable_packages || 0) > 0" class="text-xs ml-1">(click to view)</span>
</p>
</div>
<i class="fas fa-exclamation-triangle text-5xl text-red-400"></i>
</div>
</div>
</CardContent>
</Card>
<!-- Registry Breakdown -->
<Card>
<CardContent class="p-6">
<h3 class="text-xl font-semibold text-gray-900 mb-6">
<i class="fas fa-server mr-2"></i>Registry Breakdown
</h3>
<div class="space-y-4">
<div
v-for="registry in registries"
:key="registry.name"
class="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
>
<div class="flex items-center space-x-4">
<div
class="w-12 h-12 rounded-full flex items-center justify-center"
:class="registry.color"
>
<i :class="registry.icon + ' text-2xl'"></i>
</div>
<div>
<p class="font-bold text-gray-900">{{ registry.label }}</p>
<p class="text-sm text-gray-600">{{ registry.packages }} packages</p>
</div>
</div>
<div class="text-right">
<p class="text-lg font-bold text-gray-900">{{ registry.size }}</p>
<p class="text-sm text-gray-600">{{ registry.downloads }} downloads</p>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { usePackageStore } from '../stores/packages'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card'
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')
}
// Registry configuration for icons and colors
const registryConfig: Record<string, {label: string, icon: string, color: string}> = {
npm: {
label: 'NPM Registry',
icon: 'fab fa-npm text-red-500',
color: 'bg-red-100'
},
pypi: {
label: 'PyPI Registry',
icon: 'fab fa-python text-blue-500',
color: 'bg-blue-100'
},
go: {
label: 'Go Modules',
icon: 'fas fa-code text-cyan-500',
color: 'bg-cyan-100'
}
}
const registries = computed(() => {
const apiRegistries = store.registries || {}
return Object.entries(apiRegistries).map(([name, data]: [string, any]) => {
const config = registryConfig[name] || {
label: name.toUpperCase(),
icon: 'fas fa-box',
color: 'bg-gray-100'
}
return {
name,
label: config.label,
icon: config.icon,
color: config.color,
packages: data.count || 0,
size: formatBytes(data.size || 0),
downloads: data.downloads || 0
}
})
})
function formatNumber(num: number): string {
return new Intl.NumberFormat().format(num)
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i]
}
</script>
-183
View File
@@ -1,183 +0,0 @@
<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 }">{{ scannerVersion(row) || 'Not applicable' }}</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, scannerVersion, 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>
-227
View File
@@ -1,227 +0,0 @@
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 TrendChart from './TrendChart.vue'
import { TREND } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
import { formatTrendDate, trendValues } from '@/lib/trend'
vi.mock('axios')
let restore: (() => void) | undefined
beforeEach(() => {
setActivePinia(createPinia())
vi.mocked(axios.get).mockReset()
vi.mocked(axios.get).mockResolvedValue({ data: TREND })
})
afterEach(() => {
restore?.()
restore = undefined
vi.restoreAllMocks()
})
async function open(props: Record<string, unknown> = {}) {
const router = await createTestRouter('/stats')
const mounted = await mountStrict(TrendChart, { props, global: { plugins: [router] } })
restore = mounted.restore
await flushPromises()
return mounted
}
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
describe('TrendChart', () => {
it('says so when there is a single day of history, and names the plotted series', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: TREND.points.slice(0, 1) } })
const { wrapper } = await open()
expect(wrapper.findAll('[data-testid="trend-single-day"]')).toHaveLength(1)
expect(wrapper.text()).toContain('One day of history so far')
expect(wrapper.get('[data-testid="trend-series-key"]').text()).toContain('Plotted: packages with any finding.')
})
it('does not show the single-day note with several days', async () => {
const { wrapper } = await open()
expect(wrapper.text()).not.toContain('One day of history so far')
})
it('requests the 30 day trend and draws both charts with accessible names', async () => {
const { wrapper, problems } = await open()
expect(problems).toEqual([])
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
const labels = charts(wrapper).map((c) => c.attributes('aria-label'))
expect(labels).toHaveLength(2)
expect(labels[0]).toContain('Cached packages per day, from 3 on 2 Jan 2026 to 4 on 4 Jan 2026')
expect(labels[1]).toContain('Vulnerable packages per day, from 1 on 3 Jan 2026 to 2 on 4 Jan 2026')
})
it('offers every value as text through the chart data table', async () => {
const { wrapper } = await open()
const tables = wrapper.findAll('table')
expect(tables.length).toBeGreaterThanOrEqual(2)
expect(tables[0]!.text()).toContain('Cached packages')
expect(tables[0]!.text()).toContain('4')
})
it('refetches when the period changes', async () => {
const { wrapper } = await open()
const ninety = wrapper.findAll('[role="radio"]').find((r) => r.text() === '90 days')!
await ninety.trigger('click')
await flushPromises()
expect(requested()).toEqual(['/api/stats/trend?period=30day', '/api/stats/trend?period=90day'])
})
it('draws the vulnerable total first and adds a line for each severity that is switched on', async () => {
const { wrapper } = await open()
const vulnerable = () => charts(wrapper)[1]!.attributes('aria-label')
expect(vulnerable()).not.toContain('lines for')
const critical = wrapper.findAll('button[aria-pressed]').find((b) => b.text() === 'Critical')!
expect(critical.attributes('aria-pressed')).toBe('false')
await critical.trigger('click')
await flushPromises()
expect(critical.attributes('aria-pressed')).toBe('true')
expect(vulnerable()).toContain('with lines for critical')
expect(wrapper.text()).toContain('Packages with critical vulnerabilities')
await critical.trigger('click')
await flushPromises()
expect(vulnerable()).not.toContain('lines for')
})
it('offers all four severities as toggle buttons', async () => {
const { wrapper } = await open()
const names = wrapper.findAll('button[aria-pressed]').map((b) => b.text())
expect(names).toEqual(['Critical', 'High', 'Moderate', 'Low'])
})
it('says plainly when vulnerability history starts after the first day', async () => {
const { wrapper } = await open()
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toBe('Vulnerability history starts 3 Jan 2026.')
})
it('shows no note when every day has vulnerability data', async () => {
const full = { ...TREND, vulnerability_history_start: TREND.points[0]!.date }
vi.mocked(axios.get).mockResolvedValue({ data: full })
const { wrapper } = await open()
expect(wrapper.find('[data-testid="trend-vulnerability-note"]').exists()).toBe(false)
})
it('shows an empty state instead of the vulnerable chart while no scan data exists', async () => {
const noScans = {
...TREND,
vulnerability_history_start: null,
points: TREND.points.map((p) => ({ ...p, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null })),
}
vi.mocked(axios.get).mockResolvedValue({ data: noScans })
const { wrapper, problems } = await open()
expect(problems).toEqual([])
expect(charts(wrapper)).toHaveLength(1)
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('Vulnerability history has not started')
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toContain('has not started in this period')
})
it('shows an empty state when the server holds no snapshots', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, vulnerability_history_start: null, points: [] } })
const { wrapper } = await open()
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('No history yet')
expect(charts(wrapper)).toHaveLength(0)
})
it('shows a loading state until the first answer arrives', async () => {
let resolve!: (value: unknown) => void
vi.mocked(axios.get).mockReturnValue(new Promise((r) => (resolve = r)) as never)
const { wrapper } = await open()
expect(wrapper.text()).toContain('Loading package history...')
resolve({ data: TREND })
await flushPromises()
expect(wrapper.text()).not.toContain('Loading package history...')
expect(charts(wrapper)).toHaveLength(2)
})
it('shows the error with a retry that fetches again', async () => {
vi.mocked(axios.get).mockRejectedValueOnce(new Error('Request failed with status code 502'))
const { wrapper, problems } = await open()
expect(problems).toEqual([])
const state = wrapper.get('[data-slot="error-state"]')
expect(state.text()).toContain('502')
expect(charts(wrapper)).toHaveLength(0)
await state.get('button').trigger('click')
await flushPromises()
expect(wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
expect(charts(wrapper)).toHaveLength(2)
expect(requested()).toHaveLength(2)
})
it('rejects a body without points as an error, not an empty chart', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { stats: {} } })
const { wrapper } = await open()
expect(wrapper.get('[data-slot="error-state"]').text()).toContain('Unexpected response format')
})
it('ignores an answer that a newer request has replaced', async () => {
const answers: Array<(v: unknown) => void> = []
vi.mocked(axios.get).mockImplementation(() => new Promise((r) => answers.push(r)) as never)
const { wrapper } = await open()
await wrapper.findAll('[role="radio"]').find((r) => r.text() === '1 year')!.trigger('click')
await flushPromises()
answers[1]!({ data: { ...TREND, period: '1year', points: [TREND.points[2]] } })
await flushPromises()
answers[0]!({ data: TREND })
await flushPromises()
expect(wrapper.get('svg[role="img"]').attributes('aria-label')).toContain('from 4 on 4 Jan 2026 to 4 on 4 Jan 2026')
})
describe('compact', () => {
it('always asks for 30 days, draws one chart and links to the full history', async () => {
const { wrapper, problems } = await open({ compact: true })
expect(problems).toEqual([])
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
expect(charts(wrapper)).toHaveLength(1)
expect(wrapper.find('[role="radiogroup"]').exists()).toBe(false)
expect(wrapper.find('button[aria-pressed]').exists()).toBe(false)
expect(wrapper.get('a[href="/stats"]').text()).toBe('Open the full history')
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('2 vulnerable packages on 4 Jan 2026.')
})
it('says so when the latest day has no vulnerability data', async () => {
const last = { ...TREND.points[2]!, vulnerable_packages: null }
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: [TREND.points[0]!, last] } })
const { wrapper } = await open({ compact: true })
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('Vulnerability history has not started yet.')
})
})
})
describe('trend helpers', () => {
it('formats a UTC date without shifting it with the viewer zone', () => {
expect(formatTrendDate('2026-11-23')).toBe('23 Nov')
expect(formatTrendDate('2026-01-01', true)).toBe('1 Jan 2026')
expect(formatTrendDate('not-a-date')).toBe('not-a-date')
})
it('turns unknown counts into gaps, never zeros', () => {
const values = trendValues(TREND.points, 'vulnerable_packages')
expect(values[0]).toBeNaN()
expect(values.slice(1)).toEqual([1, 2])
})
})
-210
View File
@@ -1,210 +0,0 @@
<template>
<Card data-testid="trend-card">
<CardHeader>
<CardTitle as="h2">{{ compact ? 'Cached packages' : 'Packages over time' }}</CardTitle>
<CardDescription>
{{ compact ? 'Daily total, last 30 days.' : 'The cache at the end of each UTC day.' }}
</CardDescription>
<CardAction>
<SegmentedControl v-if="!compact" v-model="period" :options="TREND_PERIODS" aria-label="Trend period" />
<Button v-else as-child variant="link" size="sm">
<RouterLink to="/stats">Open the full history</RouterLink>
</Button>
</CardAction>
</CardHeader>
<CardContent class="flex flex-col gap-8">
<LoadingState v-if="loading && !data" layout="inline" label="Loading package history..." />
<ErrorState
v-else-if="error"
variant="inline"
title="Could not load the package history"
:message="error"
@retry="load"
/>
<EmptyState
v-else-if="points.length === 0"
title="No history yet"
description="The server records the first daily snapshot when it starts, then one more each day."
/>
<template v-else>
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
<p v-if="singleDay" class="m-0 text-sm text-muted-foreground" data-testid="trend-single-day">{{ SINGLE_DAY_NOTE }}</p>
<LineChart
variant="area"
:size="compact ? 'sm' : 'md'"
:y-min="0"
:labels="labels"
:series="[{ name: 'Cached packages', data: values('total_packages'), tone: 'primary' }]"
:label="packagesLabel"
/>
</section>
<p v-if="compact" class="text-sm text-muted-foreground" data-testid="trend-compact-vulnerable">
{{ compactVulnerable }}
</p>
<section v-else class="flex flex-col gap-3" aria-labelledby="trend-vulnerable-heading">
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 id="trend-vulnerable-heading" class="text-sm font-medium">Vulnerable packages</h3>
<ToggleGroup
v-model="severities"
type="multiple"
variant="outline"
tone="primary"
size="sm"
aria-label="Add a line per severity"
>
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
{{ formatSeverityName(level) }}
</ToggleGroupItem>
</ToggleGroup>
</div>
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
{{ vulnerabilityNote }}
</p>
<p v-if="singleDay" class="m-0 text-sm text-muted-foreground">{{ SINGLE_DAY_NOTE }}</p>
<p class="m-0 text-sm text-muted-foreground" data-testid="trend-series-key">{{ seriesKey }}</p>
<LineChart
v-if="data?.vulnerability_history_start"
:y-min="0"
:labels="labels"
:series="vulnerableSeries"
:label="vulnerableLabel"
/>
<EmptyState
v-else
size="sm"
title="Vulnerability history has not started"
description="Scan results are counted from the first daily snapshot that includes them."
/>
</section>
</template>
</CardContent>
</Card>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { RouterLink } from 'vue-router'
import {
Button,
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
EmptyState,
ErrorState,
LineChart,
LoadingState,
SegmentedControl,
ToggleGroup,
ToggleGroupItem,
} from '@perfect-design/ui'
import { plural } from '@/lib/reason'
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
import {
DEFAULT_TREND_PERIOD,
SEVERITY_LINE_TONES,
TREND_PERIODS,
formatTrendDate,
trendValues,
type TrendPeriod,
type TrendPoint,
type TrendResponse,
} from '@/lib/trend'
const props = defineProps<{
/** Dashboard card: 30 days, cached packages only, a link to the full history. */
compact?: boolean
}>()
const period = ref<TrendPeriod>(DEFAULT_TREND_PERIOD)
const severities = ref<SeverityLevel[]>([])
const data = ref<TrendResponse | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
let request = 0
async function load() {
const current = ++request
loading.value = true
error.value = null
try {
const response = await axios.get(`/api/stats/trend?period=${props.compact ? DEFAULT_TREND_PERIOD : period.value}`)
if (current !== request) return
const body = response.data as TrendResponse | undefined
if (!body || !Array.isArray(body.points)) {
data.value = null
error.value = 'Unexpected response format from server'
return
}
data.value = body
} catch (err) {
if (current !== request) return
data.value = null
error.value = err instanceof Error ? err.message : 'Failed to load the package history'
} finally {
if (current === request) loading.value = false
}
}
onMounted(load)
watch(period, load)
const points = computed<TrendPoint[]>(() => data.value?.points ?? [])
const labels = computed(() => points.value.map((p) => formatTrendDate(p.date, period.value === '1year')))
const values = (key: keyof Omit<TrendPoint, 'date'>) => trendValues(points.value, key)
function span(key: keyof Omit<TrendPoint, 'date'>): string {
const known = points.value.filter((p) => p[key] !== null)
const first = known[0]
const last = known[known.length - 1]
if (!first || !last) return ''
return `from ${first[key]} on ${formatTrendDate(first.date, true)} to ${last[key]} on ${formatTrendDate(last.date, true)}`
}
const packagesLabel = computed(() => `Cached packages per day, ${span('total_packages')}`)
const vulnerableLabel = computed(() => {
const extra = severities.value.length ? `, with lines for ${severities.value.join(', ')}` : ''
return `Vulnerable packages per day, ${span('vulnerable_packages')}${extra}`
})
const vulnerableSeries = computed(() => [
{ name: 'Vulnerable packages', data: values('vulnerable_packages'), tone: 'primary' as const },
...SEVERITY_LEVELS.filter((level) => severities.value.includes(level)).map((level) => ({
name: `Packages with ${level} vulnerabilities`,
data: values(level),
tone: SEVERITY_LINE_TONES[level],
})),
])
const SINGLE_DAY_NOTE = 'One day of history so far. A line appears once there is a second day.'
const singleDay = computed(() => points.value.length === 1)
const seriesKey = computed(() => {
const all = 'Plotted: packages with any finding.'
if (severities.value.length === 0) return `${all} Select a severity to add its own line.`
return `${all} Added: ${severities.value.join(', ')}.`
})
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
const vulnerabilityNote = computed(() => {
const start = data.value?.vulnerability_history_start
const first = points.value[0]
if (!start) return 'Vulnerability history has not started in this period.'
if (first && start > first.date) return `Vulnerability history starts ${formatTrendDate(start, true)}.`
return ''
})
const compactVulnerable = computed(() => {
const last = points.value[points.value.length - 1]
const n = last?.vulnerable_packages
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
return `${plural(n, 'vulnerable package')} on ${formatTrendDate(last!.date, true)}.`
})
</script>
+88 -42
View File
@@ -1,58 +1,87 @@
<template>
<div class="flex flex-wrap items-center gap-2">
<StatusBadge
v-if="isBlocked"
status="blocked"
label="Blocked"
variant="solid"
title="Download blocked: exceeds vulnerability thresholds"
/>
<div class="flex items-center gap-2">
<!-- Critical Vulnerabilities -->
<button
v-for="level in presentLevels"
:key="level"
type="button"
:class="buttonVariants({ variant: 'ghost', size: 'xs' })"
:aria-label="`${counts[level]} ${level} ${counts[level] === 1 ? 'vulnerability' : 'vulnerabilities'}, view details`"
@click="handleClick(level)"
v-if="counts.critical > 0"
@click="handleClick('critical')"
class="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-red-100 text-red-800 hover:bg-red-200 border border-red-300 transition-colors cursor-pointer"
:title="`${counts.critical} critical vulnerabilities - click for details`"
>
<StatusBadge :status="level" :tones="SEVERITY_TONES" :label="`${formatSeverityName(level)}: ${counts[level]}`" />
<i class="fas fa-shield-virus mr-1"></i>
CRITICAL: {{ counts.critical }}
</button>
<template v-if="status === 'clean' && total === 0">
<StatusBadge
status="clean"
label="Clean"
:tones="{ clean: 'success' }"
:title="scannedAt ? `No vulnerabilities found. Scanned ${formatDate(scannedAt)}` : 'No vulnerabilities found'"
/>
<RelativeTime v-if="scannedAt" :datetime="scannedAt" variant="muted" size="xs" />
</template>
<!-- High Vulnerabilities -->
<button
v-if="counts.high > 0"
@click="handleClick('high')"
class="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-orange-100 text-orange-800 hover:bg-orange-200 border border-orange-300 transition-colors cursor-pointer"
:title="`${counts.high} high severity vulnerabilities - click for details`"
>
<i class="fas fa-exclamation-triangle mr-1"></i>
HIGH: {{ counts.high }}
</button>
<StatusBadge
<!-- Moderate Vulnerabilities -->
<button
v-if="counts.moderate > 0"
@click="handleClick('moderate')"
class="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-yellow-100 text-yellow-800 hover:bg-yellow-200 border border-yellow-300 transition-colors cursor-pointer"
:title="`${counts.moderate} moderate severity vulnerabilities - click for details`"
>
<i class="fas fa-exclamation-circle mr-1"></i>
MODERATE: {{ counts.moderate }}
</button>
<!-- Low Vulnerabilities -->
<button
v-if="counts.low > 0"
@click="handleClick('low')"
class="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-blue-100 text-blue-800 hover:bg-blue-200 border border-blue-300 transition-colors cursor-pointer"
:title="`${counts.low} low severity vulnerabilities - click for details`"
>
<i class="fas fa-info-circle mr-1"></i>
LOW: {{ counts.low }}
</button>
<!-- Clean Badge (no vulnerabilities) -->
<span
v-if="status === 'clean' && total === 0"
class="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-green-100 text-green-800 border border-green-300"
:title="scannedAt ? `No vulnerabilities found - Scanned ${formatTimestamp(scannedAt)}` : 'No vulnerabilities found'"
>
<i class="fas fa-check-circle mr-1"></i>
CLEAN
<span v-if="scannedAt" class="ml-1 text-[10px] opacity-70">
({{ formatRelativeTime(scannedAt) }})
</span>
</span>
<!-- Pending Badge -->
<span
v-if="status === 'pending'"
status="pending"
label="Scanning"
pulse
class="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-gray-100 text-gray-700 border border-gray-300"
title="Security scan in progress"
/>
>
<i class="fas fa-spinner fa-spin mr-1"></i>
SCANNING...
</span>
<StatusBadge
<!-- Not Scanned Badge -->
<span
v-if="status === 'not_scanned' || !scanned"
status="not_scanned"
label="Not scanned"
:tones="{ not_scanned: 'neutral' }"
class="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-gray-100 text-gray-600 border border-gray-300"
title="Not yet scanned for vulnerabilities"
/>
>
<i class="fas fa-question-circle mr-1"></i>
NOT SCANNED
</span>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { RelativeTime, StatusBadge, buttonVariants } from '@perfect-design/ui'
import type { VulnerabilityCounts } from '../stores/packages'
import { formatDate } from '@/lib/format'
import { NO_VULNERABILITIES, SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName } from '@/lib/severity'
interface Props {
scanned?: boolean
@@ -60,24 +89,41 @@ interface Props {
counts?: VulnerabilityCounts
total?: number
scannedAt?: string // ISO 8601 timestamp
isBlocked?: boolean // Whether download is blocked due to vulnerabilities
}
const props = withDefaults(defineProps<Props>(), {
scanned: false,
status: 'not_scanned',
total: 0,
isBlocked: false,
})
const emit = defineEmits<{
click: [severity: string]
}>()
const counts = computed(() => props.counts || NO_VULNERABILITIES)
const presentLevels = computed(() => SEVERITY_LEVELS.filter((level) => counts.value[level] > 0))
const counts = computed(() => props.counts || { critical: 0, high: 0, moderate: 0, low: 0 })
function handleClick(severity: string) {
emit('click', severity)
}
function formatTimestamp(timestamp: string): string {
const date = new Date(timestamp)
return date.toLocaleString()
}
function formatRelativeTime(timestamp: string): string {
const date = new Date(timestamp)
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffMins = Math.floor(diffMs / 60000)
const diffHours = Math.floor(diffMs / 3600000)
const diffDays = Math.floor(diffMs / 86400000)
if (diffMins < 1) return 'just now'
if (diffMins < 60) return `${diffMins}m ago`
if (diffHours < 24) return `${diffHours}h ago`
if (diffDays < 7) return `${diffDays}d ago`
return formatTimestamp(timestamp).split(',')[0] // Just the date part
}
</script>
@@ -0,0 +1,307 @@
<template>
<div class="max-w-7xl mx-auto px-4 py-8">
<!-- Header -->
<div class="mb-6">
<Button @click="goBack" variant="ghost" class="mb-4">
<i class="fas fa-arrow-left mr-2"></i>
Back to Stats
</Button>
<div class="flex items-center gap-3">
<i class="fas fa-exclamation-triangle text-3xl text-red-600"></i>
<div>
<h1 class="text-3xl font-bold text-gray-900">Vulnerable Packages</h1>
<p class="text-gray-600 mt-1">
Packages with known security vulnerabilities, sorted by risk
</p>
</div>
</div>
</div>
<!-- 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 vulnerable packages...</p>
</div>
<!-- Error State -->
<Alert v-else-if="error" variant="destructive" class="mb-4">
<i class="fas fa-exclamation-circle mr-2"></i>
<AlertDescription>{{ error }}</AlertDescription>
</Alert>
<!-- Empty State -->
<Card v-else-if="sortedVulnerablePackages.length === 0">
<CardContent class="text-center py-12">
<i class="fas fa-check-circle text-6xl text-green-500 mb-4"></i>
<p class="text-xl font-semibold text-gray-900">No Vulnerable Packages</p>
<p class="mt-2 text-gray-600">All your packages are clean and safe to use!</p>
</CardContent>
</Card>
<!-- Vulnerable Packages List -->
<div v-else class="space-y-6">
<!-- Summary Card -->
<Card>
<CardContent class="p-6">
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div class="text-center p-4 bg-red-50 rounded-lg border border-red-200">
<p class="text-3xl font-bold text-red-600">{{ criticalCount }}</p>
<p class="text-sm text-gray-600 mt-1">Critical</p>
</div>
<div class="text-center p-4 bg-orange-50 rounded-lg border border-orange-200">
<p class="text-3xl font-bold text-orange-600">{{ highCount }}</p>
<p class="text-sm text-gray-600 mt-1">High</p>
</div>
<div class="text-center p-4 bg-yellow-50 rounded-lg border border-yellow-200">
<p class="text-3xl font-bold text-yellow-600">{{ moderateCount }}</p>
<p class="text-sm text-gray-600 mt-1">Moderate</p>
</div>
<div class="text-center p-4 bg-blue-50 rounded-lg border border-blue-200">
<p class="text-3xl font-bold text-blue-600">{{ lowCount }}</p>
<p class="text-sm text-gray-600 mt-1">Low</p>
</div>
</div>
</CardContent>
</Card>
<!-- Packages List -->
<Card>
<CardContent class="p-6">
<div class="mb-4">
<h3 class="text-xl font-semibold text-gray-900">
<i class="fas fa-list mr-2"></i>
Vulnerable Packages ({{ sortedVulnerablePackages.length }})
</h3>
<p class="text-sm text-gray-600 mt-1">
{{ groupedPackages.length }} unique package{{ groupedPackages.length !== 1 ? 's' : '' }} • Sorted by risk: Critical → High → Moderate → Low
</p>
</div>
<Accordion type="multiple" class="w-full">
<AccordionItem
v-for="group in groupedPackages"
:key="`${group.registry}:${group.name}`"
:value="`${group.registry}:${group.name}`"
class="border-b border-gray-200"
>
<AccordionTrigger class="px-4 py-4 hover:bg-gray-50">
<div class="flex items-center justify-between w-full pr-4">
<div class="flex items-center space-x-4 flex-1 min-w-0">
<div class="text-left flex-1 min-w-0">
<h4 class="font-semibold text-gray-900 break-words">{{ group.name }}</h4>
<p class="text-sm text-gray-500">{{ group.versions.length }} vulnerable version{{ group.versions.length > 1 ? 's' : '' }}</p>
</div>
</div>
<div class="flex items-center space-x-6 flex-shrink-0">
<Badge variant="outline" :class="getRegistryBadgeClass(group.registry)">
{{ group.registry }}
</Badge>
<div class="text-right whitespace-nowrap">
<p class="text-sm font-medium text-gray-900">{{ formatBytes(group.totalSize) }}</p>
<p class="text-xs text-gray-500">{{ formatNumber(group.totalDownloads) }} downloads</p>
</div>
</div>
</div>
</AccordionTrigger>
<AccordionContent class="px-4 pb-4">
<div class="space-y-3">
<div
v-for="version in group.versions"
:key="version.id"
class="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 cursor-pointer"
@click="navigateToPackage(version)"
>
<div class="flex items-center space-x-4 flex-1">
<div class="flex-1">
<p class="font-medium text-gray-900">{{ version.version.startsWith('v') ? version.version : 'v' + version.version }}</p>
<div class="flex items-center space-x-4 mt-1 text-sm text-gray-500">
<span>
<i class="fas fa-download mr-1"></i>{{ formatNumber(version.download_count) }}
</span>
<span>
<i class="fas fa-hard-drive mr-1"></i>{{ formatBytes(version.size) }}
</span>
<span>
<i class="fas fa-clock mr-1"></i>{{ formatDate(version.cached_at) }}
</span>
</div>
<!-- Vulnerability Badge -->
<div v-if="version.vulnerabilities" class="mt-2">
<VulnerabilityBadge
:scanned="version.vulnerabilities.scanned"
:status="version.vulnerabilities.status"
:counts="version.vulnerabilities.counts"
:total="version.vulnerabilities.total"
:scannedAt="version.vulnerabilities.scannedAt"
@click.stop="navigateToPackage(version)"
/>
</div>
</div>
</div>
<div class="ml-4 flex-shrink-0">
<i class="fas fa-chevron-right text-gray-400"></i>
</div>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</CardContent>
</Card>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { usePackageStore, type Package } from '../stores/packages'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from '@/components/ui/accordion'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { getRegistryBadgeClass } from '@/composables/useBadgeStyles'
const store = usePackageStore()
const router = useRouter()
const loading = ref(false)
const error = ref<string | null>(null)
const vulnerablePackages = ref<Package[]>([])
onMounted(async () => {
await fetchVulnerablePackages()
})
async function fetchVulnerablePackages() {
loading.value = true
error.value = null
try {
await store.fetchPackages()
vulnerablePackages.value = store.packages.filter(
pkg => pkg.vulnerabilities?.status === 'vulnerable'
)
} catch (err: any) {
console.error('Failed to load vulnerable packages:', err)
error.value = err.message || 'Failed to load vulnerable packages'
} finally {
loading.value = false
}
}
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
const sortedVulnerablePackages = computed(() => {
return [...vulnerablePackages.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
})
})
// 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())
})
// Calculate total counts across all packages
const criticalCount = computed(() =>
vulnerablePackages.value.reduce((sum, pkg) => sum + (pkg.vulnerabilities?.counts?.critical || 0), 0)
)
const highCount = computed(() =>
vulnerablePackages.value.reduce((sum, pkg) => sum + (pkg.vulnerabilities?.counts?.high || 0), 0)
)
const moderateCount = computed(() =>
vulnerablePackages.value.reduce((sum, pkg) => sum + (pkg.vulnerabilities?.counts?.moderate || 0), 0)
)
const lowCount = computed(() =>
vulnerablePackages.value.reduce((sum, pkg) => sum + (pkg.vulnerabilities?.counts?.low || 0), 0)
)
function navigateToPackage(pkg: Package) {
router.push(`/package/${pkg.registry}/${pkg.name}/${pkg.version}`)
}
function goBack() {
router.push('/stats')
}
function formatNumber(num: number): string {
return new Intl.NumberFormat().format(num)
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i]
}
function formatDate(dateString: string): string {
if (!dateString) return 'N/A'
try {
const date = new Date(dateString)
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
} catch {
return dateString
}
}
</script>
@@ -1,46 +0,0 @@
<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>
@@ -1,119 +0,0 @@
<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>
@@ -1,86 +0,0 @@
<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),
)
// chart-1 and chart-2 are neighbouring teals in this theme, so each registry gets a distinct hue.
const REGISTRY_TONES: Record<string, DonutDatum['tone']> = { npm: 'info', go: 'primary', pypi: 'warning' }
const SPARE_TONES: DonutDatum['tone'][] = ['danger', 'success', 'muted']
const donut = computed<DonutDatum[]>(() =>
rows.value.map((r, i) => ({ label: r.registry, value: r.size, tone: REGISTRY_TONES[r.registry] ?? SPARE_TONES[i % SPARE_TONES.length] })),
)
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>
@@ -1,72 +0,0 @@
<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>
@@ -1,58 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import DownloadsPanel from './DownloadsPanel.vue'
import { PACKAGE_ANALYTICS } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
vi.mock('axios')
let restore: (() => void) | undefined
async function open(props: { registry: string; name: string; downloadCount: number }) {
const mounted = await mountStrict(DownloadsPanel, { props })
restore = mounted.restore
await flushPromises()
return mounted.wrapper
}
beforeEach(() => {
vi.mocked(axios.get).mockReset()
})
afterEach(() => {
restore?.()
restore = undefined
})
describe('DownloadsPanel', () => {
it('shows the stored count even when analytics have no record since the restart', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { package: null } })
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 12 })
expect(wrapper.text()).toContain('12')
expect(wrapper.text()).toContain('No downloads since the last restart')
expect(wrapper.text()).not.toContain('Could not load')
})
it('adds the in-memory totals and labels them as since the restart', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: PACKAGE_ANALYTICS })
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 12 })
expect(wrapper.text()).toContain('kept across restarts')
expect(wrapper.text()).toContain('2 versions since the last restart')
expect(wrapper.text()).toContain('80 KB')
})
it('asks for a Go module by its path, with no cache-file suffix', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { package: null } })
await open({ registry: 'go', name: 'github.com/google/uuid/@v/v1.6.0.zip', downloadCount: 2 })
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/analytics/package/go/github.com/google/uuid')
})
it('reports a failed request', async () => {
vi.mocked(axios.get).mockRejectedValue(new Error('boom'))
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 1 })
expect(wrapper.text()).toContain('Could not load download history')
})
})
@@ -1,81 +0,0 @@
<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" />
<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, kept across restarts" />
<template v-if="stats">
<KpiTile
label="All versions"
:value="stats.TotalDownloads"
:hint="`${stats.UniqueVersions} version${stats.UniqueVersions === 1 ? '' : 's'} since the last restart`"
/>
<KpiTile label="Data served" :value="formatBytes(stats.BytesServed)" hint="Across all versions, since the last restart" />
</template>
</StatGroup>
<DescriptionList v-if="stats" :columns="2" divided>
<DescriptionItem term="First seen since restart"><RelativeTime :datetime="stats.FirstSeen" /></DescriptionItem>
<DescriptionItem term="Last download"><RelativeTime :datetime="stats.LastDownload" /></DescriptionItem>
</DescriptionList>
<EmptyState
v-else
size="sm"
:icon="faDownload"
title="No downloads since the last restart"
description="The totals across versions are counted in memory, so they start again when the server restarts."
/>
</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; downloadCount: number }>()
const stats = ref<PackageAnalytics | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
// Analytics are keyed by package name; a Go module is named by its path.
const analyticsName = computed(() => modulePath(props.name))
async function load() {
loading.value = true
error.value = null
try {
const response = await axios.get<{ package: PackageAnalytics | null }>(
`/api/analytics/package/${props.registry}/${analyticsName.value}`,
)
stats.value = response.data.package
} catch (err) {
stats.value = null
error.value = err instanceof Error ? err.message : 'Failed to load download history'
} finally {
loading.value = false
}
}
onMounted(load)
</script>
@@ -1,48 +0,0 @@
<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>
@@ -1,68 +0,0 @@
<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 { humanReason } from '@/lib/reason'
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(() => humanReason(props.pkg?.vulnerabilities?.reason) || VERDICT_MEANINGS[verdict.value])
</script>
@@ -1,25 +0,0 @@
<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>
@@ -1,55 +0,0 @@
<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-start justify-between gap-3 rounded-md border px-3 py-2"
:data-scanner="scanner.name"
>
<span class="min-w-0">
<span class="block break-words text-sm font-medium" :title="scanner.name">{{ scanner.name }}</span>
<span v-if="scannerVersion(scanner)" class="block text-xs text-muted-foreground">{{ scannerVersion(scanner) }}</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, scannerVersion, 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>
@@ -1,84 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import TopPackages from './TopPackages.vue'
import { mountStrict } from '@/test/mountStrict'
vi.mock('axios')
let restore: (() => void) | undefined
const row = (registry: string, name: string, download_count: number) => ({ registry, name, version: '1.0.0', download_count })
function serve(rows: unknown[], trending: unknown[] = []) {
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.startsWith('/api/analytics/trending')) return { data: { packages: trending } } as never
if (url.startsWith('/api/packages?layout=rows')) return { data: { packages: rows } } as never
throw new Error(`unexpected request: ${url}`)
})
}
async function open() {
const mounted = await mountStrict(TopPackages)
restore = mounted.restore
await flushPromises()
return mounted.wrapper
}
beforeEach(() => {
vi.mocked(axios.get).mockReset()
})
afterEach(() => {
restore?.()
restore = undefined
})
describe('TopPackages', () => {
it('ranks packages by the stored download counts, so a restart does not empty it', async () => {
serve([row('npm', 'left-pad', 12), row('npm', 'left-pad', 5), row('pypi', 'six', 9)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('npm · left-pad')
expect(text).toContain('pypi · six')
expect(text).not.toContain('No downloads yet')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200')
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith(expect.stringContaining('/api/analytics/top'))
})
it('adds the versions of a package and orders by the sum', async () => {
serve([row('npm', 'a', 10), row('npm', 'b', 15), row('npm', 'a', 9)])
const wrapper = await open()
const labels = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
expect(labels[0]).toContain('npm · a')
expect(labels[1]).toContain('npm · b')
})
it('counts a Go module once, by its zip, and not its .mod and .info files', async () => {
serve([
row('go', 'github.com/google/uuid/@v/v1.6.0.zip', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.mod', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.info', 4),
])
const wrapper = await open()
const entries = wrapper.findAll('[data-testid="top-packages"] li')
expect(entries).toHaveLength(1)
expect(entries[0].text()).toContain('go · github.com/google/uuid')
expect(entries[0].text()).toContain('4')
expect(entries[0].text()).not.toContain('12')
})
it('says so when no package has a download', async () => {
serve([row('npm', 'left-pad', 0)])
const wrapper = await open()
expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet')
})
it('names where each ranking comes from', async () => {
serve([row('npm', 'left-pad', 3)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('The counts survive restarts.')
expect(text).toContain('Counted in memory, so it restarts with the server.')
})
})
@@ -1,111 +0,0 @@
<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>Downloads served from the cache. The counts survive restarts.</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. Counted in memory, so it restarts with the server.</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
}
/** One stored version row; its count is kept in the database. */
interface DownloadRow {
registry: string
name: string
download_count: number
}
const LIMIT = 8
// Go keeps one row per file (.zip, .mod, .info) of a version; only the zip is a module download.
const GO_METADATA = /\.(mod|info)$/
const ROWS_URL = '/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200'
const stored = ref<DownloadRow[]>([])
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(
stored.value
.filter((r) => !(r.registry === 'go' && GO_METADATA.test(r.name)))
.map((r) => ({ Registry: r.registry, Name: r.name, Downloads: r.download_count, RecentDownloads: 0 })),
(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: DownloadRow[] }>(ROWS_URL),
axios.get<{ packages: PopularPackage[] }>('/api/analytics/trending?limit=50'),
])
stored.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>
@@ -1,12 +0,0 @@
<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>
@@ -1,50 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import VulnerabilityTable from './VulnerabilityTable.vue'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
import type { VulnerabilityEntry } from '@/lib/report'
let restore: (() => void) | undefined
afterEach(() => {
restore?.()
restore = undefined
})
const entry = (over: Partial<VulnerabilityEntry>): VulnerabilityEntry => ({
id: 'GHSA-xvch-5gv4-984h',
severity: 'critical',
title: 'Prototype pollution',
description: '',
references: [],
fixed_in: '1.2.6',
bypassed: false,
...over,
})
async function open(vulnerabilities: VulnerabilityEntry[]) {
const router = await createTestRouter('/')
const mounted = await mountStrict(VulnerabilityTable, { props: { vulnerabilities }, global: { plugins: [router] } })
restore = mounted.restore
return mounted.wrapper
}
describe('VulnerabilityTable aliases', () => {
it('names the other ids of a finding next to its advisory id', async () => {
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
expect(w.text()).toContain('GHSA-xvch-5gv4-984h')
expect(w.text()).toContain('Also CVE-2021-44906')
})
it('shows no alias line for an older finding without aliases', async () => {
const w = await open([entry({})])
expect(w.text()).not.toContain('Also ')
})
it('offers a bypass link for the id and for each alias', async () => {
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
await w.find('tbody tr').trigger('click')
const hrefs = w.findAll('a').map((a) => a.attributes('href') ?? '')
expect(hrefs).toContain('/admin/bypasses?type=cve&target=GHSA-xvch-5gv4-984h')
expect(hrefs).toContain('/admin/bypasses?type=cve&target=CVE-2021-44906')
})
})
@@ -1,129 +0,0 @@
<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">
<span class="block">{{ vuln.id }}</span>
<span v-if="vuln.aliases?.length" class="block text-xs font-normal text-muted-foreground">
Also {{ vuln.aliases.join(', ') }}
</span>
</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>
<h3 class="mb-2 text-sm font-semibold">Bypass this advisory</h3>
<p class="m-0 mb-1 text-sm text-muted-foreground">A bypass for any of these ids covers this finding.</p>
<ul class="m-0 flex list-none flex-wrap gap-3 p-0 text-sm">
<li v-for="id in [vuln.id, ...(vuln.aliases ?? [])]" :key="id">
<Link :as="RouterLink" :to="{ path: '/admin/bypasses', query: { type: 'cve', target: id } }">{{ id }}</Link>
</li>
</ul>
</section>
<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 { RouterLink } from 'vue-router'
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>
-59
View File
@@ -1,59 +0,0 @@
<script setup lang="ts">
import { computed } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { SidebarNav, type SidebarNavGroup } from '@perfect-design/ui'
import {
faBoxesStacked,
faChartColumn,
faChartPie,
faGear,
faShieldHalved,
faTriangleExclamation,
} from '@/lib/icons'
// The sidebar slot of AppShell hides itself below md and the header's mobile slot only shows below md,
// so each placement renders one nav and the two never compete for the same viewport.
defineProps<{ readonly sheet?: boolean }>()
const GROUPS: SidebarNavGroup[] = [
{
items: [
{ label: 'Overview', to: '/', icon: faChartPie },
{ label: 'Packages', to: '/packages', icon: faBoxesStacked },
{ label: 'Security', to: '/security', icon: faTriangleExclamation },
{ label: 'Insights', to: '/stats', icon: faChartColumn },
],
},
{
label: 'Admin',
items: [
{ label: 'Bypasses', to: '/admin/bypasses', icon: faShieldHalved },
{ label: 'System', to: '/admin/system', icon: faGear },
],
},
]
const SECTION_PREFIXES: ReadonlyArray<readonly [string, string]> = [
['/packages', '/packages'],
['/package/', '/packages'],
['/security', '/security'],
['/vulnerable-packages', '/security'],
['/blocked-packages', '/security'],
['/admin/bypasses', '/admin/bypasses'],
['/admin/system', '/admin/system'],
['/stats', '/stats'],
]
const route = useRoute()
const current = computed(() => SECTION_PREFIXES.find(([prefix]) => route.path.startsWith(prefix))?.[1] ?? '/')
</script>
<template>
<SidebarNav
:groups="GROUPS"
:current="current"
:link-as="RouterLink"
:label="sheet ? 'Sections menu' : 'Sections'"
class="w-full p-3"
/>
</template>
@@ -0,0 +1,18 @@
<script setup lang="ts">
import type { AccordionRootEmits, AccordionRootProps } from "reka-ui"
import {
AccordionRoot,
useForwardPropsEmits,
} from "reka-ui"
const props = defineProps<AccordionRootProps>()
const emits = defineEmits<AccordionRootEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<AccordionRoot v-bind="forwarded">
<slot />
</AccordionRoot>
</template>
@@ -0,0 +1,22 @@
<script setup lang="ts">
import type { AccordionContentProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { AccordionContent } from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<AccordionContentProps & { class?: HTMLAttributes["class"] }>()
const delegatedProps = reactiveOmit(props, "class")
</script>
<template>
<AccordionContent
v-bind="delegatedProps"
class="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
>
<div :class="cn('pb-4 pt-0', props.class)">
<slot />
</div>
</AccordionContent>
</template>
@@ -0,0 +1,22 @@
<script setup lang="ts">
import type { AccordionItemProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { AccordionItem, useForwardProps } from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<AccordionItemProps & { class?: HTMLAttributes["class"] }>()
const delegatedProps = reactiveOmit(props, "class")
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<AccordionItem
v-bind="forwardedProps"
:class="cn('border-b', props.class)"
>
<slot />
</AccordionItem>
</template>
@@ -0,0 +1,36 @@
<script setup lang="ts">
import type { AccordionTriggerProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { ChevronDown } from "lucide-vue-next"
import {
AccordionHeader,
AccordionTrigger,
} from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<AccordionTriggerProps & { class?: HTMLAttributes["class"] }>()
const delegatedProps = reactiveOmit(props, "class")
</script>
<template>
<AccordionHeader class="flex">
<AccordionTrigger
v-bind="delegatedProps"
:class="
cn(
'flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180',
props.class,
)
"
>
<slot />
<slot name="icon">
<ChevronDown
class="h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200"
/>
</slot>
</AccordionTrigger>
</AccordionHeader>
</template>
@@ -0,0 +1,4 @@
export { default as Accordion } from "./Accordion.vue"
export { default as AccordionContent } from "./AccordionContent.vue"
export { default as AccordionItem } from "./AccordionItem.vue"
export { default as AccordionTrigger } from "./AccordionTrigger.vue"
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import type { AlertVariants } from "."
import { cn } from "@/lib/utils"
import { alertVariants } from "."
const props = defineProps<{
class?: HTMLAttributes["class"]
variant?: AlertVariants["variant"]
}>()
</script>
<template>
<div :class="cn(alertVariants({ variant }), props.class)" role="alert">
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div :class="cn('text-sm [&_p]:leading-relaxed', props.class)">
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<h5 :class="cn('mb-1 font-medium leading-none tracking-tight', props.class)">
<slot />
</h5>
</template>
+24
View File
@@ -0,0 +1,24 @@
import type { VariantProps } from "class-variance-authority"
import { cva } from "class-variance-authority"
export { default as Alert } from "./Alert.vue"
export { default as AlertDescription } from "./AlertDescription.vue"
export { default as AlertTitle } from "./AlertTitle.vue"
export const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
},
)
export type AlertVariants = VariantProps<typeof alertVariants>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import type { BadgeVariants } from "."
import { cn } from "@/lib/utils"
import { badgeVariants } from "."
const props = defineProps<{
variant?: BadgeVariants["variant"]
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div :class="cn(badgeVariants({ variant }), props.class)">
<slot />
</div>
</template>
+26
View File
@@ -0,0 +1,26 @@
import type { VariantProps } from "class-variance-authority"
import { cva } from "class-variance-authority"
export { default as Badge } from "./Badge.vue"
export const badgeVariants = cva(
"inline-flex gap-1 items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
)
export type BadgeVariants = VariantProps<typeof badgeVariants>
@@ -0,0 +1,28 @@
<script setup lang="ts">
import type { PrimitiveProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import type { ButtonVariants } from "."
import { Primitive } from "reka-ui"
import { cn } from "@/lib/utils"
import { buttonVariants } from "."
interface Props extends PrimitiveProps {
variant?: ButtonVariants["variant"]
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
}
const props = withDefaults(defineProps<Props>(), {
as: "button",
})
</script>
<template>
<Primitive
:as="as"
:as-child="asChild"
:class="cn(buttonVariants({ variant, size }), props.class)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,38 @@
import type { VariantProps } from "class-variance-authority"
import { cva } from "class-variance-authority"
export { default as Button } from "./Button.vue"
export const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
"default": "h-9 px-4 py-2",
"xs": "h-7 rounded px-2",
"sm": "h-8 rounded-md px-3 text-xs",
"lg": "h-10 rounded-md px-8",
"icon": "h-9 w-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
)
export type ButtonVariants = VariantProps<typeof buttonVariants>
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div
:class="
cn(
'rounded-xl border bg-card text-card-foreground shadow',
props.class,
)
"
>
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div :class="cn('p-6 pt-0', props.class)">
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<p :class="cn('text-sm text-muted-foreground', props.class)">
<slot />
</p>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div :class="cn('flex items-center p-6 pt-0', props.class)">
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div :class="cn('flex flex-col gap-y-1.5 p-6', props.class)">
<slot />
</div>
</template>
@@ -0,0 +1,18 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<h3
:class="
cn('font-semibold leading-none tracking-tight', props.class)
"
>
<slot />
</h3>
</template>
+6
View File
@@ -0,0 +1,6 @@
export { default as Card } from "./Card.vue"
export { default as CardContent } from "./CardContent.vue"
export { default as CardDescription } from "./CardDescription.vue"
export { default as CardFooter } from "./CardFooter.vue"
export { default as CardHeader } from "./CardHeader.vue"
export { default as CardTitle } from "./CardTitle.vue"
@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { DialogRootEmits, DialogRootProps } from "reka-ui"
import { DialogRoot, useForwardPropsEmits } from "reka-ui"
const props = defineProps<DialogRootProps>()
const emits = defineEmits<DialogRootEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<DialogRoot v-bind="forwarded">
<slot />
</DialogRoot>
</template>
@@ -0,0 +1,12 @@
<script setup lang="ts">
import type { DialogCloseProps } from "reka-ui"
import { DialogClose } from "reka-ui"
const props = defineProps<DialogCloseProps>()
</script>
<template>
<DialogClose v-bind="props">
<slot />
</DialogClose>
</template>
@@ -0,0 +1,46 @@
<script setup lang="ts">
import type { DialogContentEmits, DialogContentProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { X } from "lucide-vue-next"
import {
DialogClose,
DialogContent,
DialogOverlay,
DialogPortal,
useForwardPropsEmits,
} from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<DialogContentProps & { class?: HTMLAttributes["class"] }>()
const emits = defineEmits<DialogContentEmits>()
const delegatedProps = reactiveOmit(props, "class")
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DialogPortal>
<DialogOverlay
class="fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
/>
<DialogContent
v-bind="forwarded"
:class="
cn(
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
props.class,
)"
>
<slot />
<DialogClose
class="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"
>
<X class="w-4 h-4" />
<span class="sr-only">Close</span>
</DialogClose>
</DialogContent>
</DialogPortal>
</template>
@@ -0,0 +1,22 @@
<script setup lang="ts">
import type { DialogDescriptionProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { DialogDescription, useForwardProps } from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<DialogDescriptionProps & { class?: HTMLAttributes["class"] }>()
const delegatedProps = reactiveOmit(props, "class")
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DialogDescription
v-bind="forwardedProps"
:class="cn('text-sm text-muted-foreground', props.class)"
>
<slot />
</DialogDescription>
</template>
@@ -0,0 +1,19 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{ class?: HTMLAttributes["class"] }>()
</script>
<template>
<div
:class="
cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:gap-x-2',
props.class,
)
"
>
<slot />
</div>
</template>
@@ -0,0 +1,16 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div
:class="cn('flex flex-col gap-y-1.5 text-center sm:text-left', props.class)"
>
<slot />
</div>
</template>
@@ -0,0 +1,55 @@
<script setup lang="ts">
import type { DialogContentEmits, DialogContentProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { X } from "lucide-vue-next"
import {
DialogClose,
DialogContent,
DialogOverlay,
DialogPortal,
useForwardPropsEmits,
} from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<DialogContentProps & { class?: HTMLAttributes["class"] }>()
const emits = defineEmits<DialogContentEmits>()
const delegatedProps = reactiveOmit(props, "class")
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DialogPortal>
<DialogOverlay
class="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
>
<DialogContent
:class="
cn(
'relative z-50 grid w-full max-w-lg my-8 gap-4 border border-border bg-background p-6 shadow-lg duration-200 sm:rounded-lg md:w-full',
props.class,
)
"
v-bind="forwarded"
@pointer-down-outside="(event) => {
const originalEvent = event.detail.originalEvent;
const target = originalEvent.target as HTMLElement;
if (originalEvent.offsetX > target.clientWidth || originalEvent.offsetY > target.clientHeight) {
event.preventDefault();
}
}"
>
<slot />
<DialogClose
class="absolute top-4 right-4 p-0.5 transition-colors rounded-md hover:bg-secondary"
>
<X class="w-4 h-4" />
<span class="sr-only">Close</span>
</DialogClose>
</DialogContent>
</DialogOverlay>
</DialogPortal>
</template>
@@ -0,0 +1,27 @@
<script setup lang="ts">
import type { DialogTitleProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { reactiveOmit } from "@vueuse/core"
import { DialogTitle, useForwardProps } from "reka-ui"
import { cn } from "@/lib/utils"
const props = defineProps<DialogTitleProps & { class?: HTMLAttributes["class"] }>()
const delegatedProps = reactiveOmit(props, "class")
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DialogTitle
v-bind="forwardedProps"
:class="
cn(
'text-lg font-semibold leading-none tracking-tight',
props.class,
)
"
>
<slot />
</DialogTitle>
</template>
@@ -0,0 +1,12 @@
<script setup lang="ts">
import type { DialogTriggerProps } from "reka-ui"
import { DialogTrigger } from "reka-ui"
const props = defineProps<DialogTriggerProps>()
</script>
<template>
<DialogTrigger v-bind="props">
<slot />
</DialogTrigger>
</template>
@@ -0,0 +1,9 @@
export { default as Dialog } from "./Dialog.vue"
export { default as DialogClose } from "./DialogClose.vue"
export { default as DialogContent } from "./DialogContent.vue"
export { default as DialogDescription } from "./DialogDescription.vue"
export { default as DialogFooter } from "./DialogFooter.vue"
export { default as DialogHeader } from "./DialogHeader.vue"
export { default as DialogScrollContent } from "./DialogScrollContent.vue"
export { default as DialogTitle } from "./DialogTitle.vue"
export { default as DialogTrigger } from "./DialogTrigger.vue"

Some files were not shown because too many files have changed in this diff Show More