mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-27 06:46:01 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8adb1e0c87 | ||
|
|
16fb52ed3e | ||
|
|
13abb140d7 | ||
|
|
378b8731fc | ||
|
|
a83cc20058 | ||
|
|
501bf1aec8 | ||
|
|
527c1759f9 | ||
|
|
933b5a75c0 | ||
|
|
f4cf96e1e8 | ||
|
|
aa8487ad87 | ||
|
|
2ada975065 | ||
|
|
b98e761c90 | ||
|
|
a457e3d2e8 | ||
|
|
ba8bc392ec | ||
|
|
1512230ab3 | ||
|
|
bd9d686383 | ||
|
|
4d31e535ff | ||
|
|
fe2d9f8b3a | ||
|
|
a84f080b79 | ||
|
|
9b4659218c | ||
|
|
1256756057 | ||
|
|
262771d224 | ||
|
|
536f35ab55 | ||
|
|
5a9d104b37 | ||
|
|
f2049383cb | ||
|
|
549d56e0a1 | ||
|
|
31db940014 | ||
|
|
f46e079cee | ||
|
|
ae5167ffa9 | ||
|
|
787c757827 | ||
|
|
ac4f39322c | ||
|
|
db5ca2539f | ||
|
|
a7b9917696 | ||
|
|
3143de3a3f | ||
|
|
f0b37ea719 | ||
|
|
7192e4ff3e | ||
|
|
ad4e848e2b | ||
|
|
990a1d3409 | ||
|
|
440279aa50 | ||
|
|
1f31256769 | ||
|
|
4713524778 | ||
|
|
5c9f7e6af3 | ||
|
|
6f604367da | ||
|
|
c98720c02e | ||
|
|
9a44683fbd | ||
|
|
d6edd40d79 | ||
|
|
99c885cd88 | ||
|
|
c022824d2b | ||
|
|
5420480ef8 | ||
|
|
bde9eebf3d | ||
|
|
f65c0cc1f3 | ||
|
|
947b264d94 | ||
|
|
1c9b04fba4 | ||
|
|
fb25501ae4 | ||
|
|
f0b7139a92 | ||
|
|
879ece368e | ||
|
|
81e3f9c74f | ||
|
|
24dfb6eace | ||
|
|
a5fd828410 | ||
|
|
54bc809f66 | ||
|
|
041c6e8012 | ||
|
|
0a0286df41 | ||
|
|
b88f9d2c99 | ||
|
|
d38eb34e06 | ||
|
|
ea00fac0fe | ||
|
|
1fefe03e8f | ||
|
|
a69e96d75c | ||
|
|
d653a32bd5 | ||
|
|
1d0363b247 | ||
|
|
380b3b9d1c | ||
|
|
a313ac1096 | ||
|
|
65b2f23486 | ||
|
|
cfab914a24 | ||
|
|
00a2d2f6ed | ||
|
|
379fd53c73 | ||
|
|
de75f67720 | ||
|
|
6a37d56e33 | ||
|
|
57cbdcdb67 | ||
|
|
951f501ff6 | ||
|
|
c57c4ccfb0 | ||
|
|
138edbede7 | ||
|
|
3ae90aa0ee | ||
|
|
d71371674d | ||
|
|
cc0f56f6db | ||
|
|
a174afee73 | ||
|
|
046e074be5 | ||
|
|
2e0f095ea9 | ||
|
|
c38916aebb | ||
|
|
015f48b468 | ||
|
|
ad5b03ba60 | ||
|
|
819465e83f | ||
|
|
eec24a5894 | ||
|
|
9be1d85bf9 | ||
|
|
5107fd728f | ||
|
|
24106f82be | ||
|
|
4c94e2bf15 | ||
|
|
00582d3203 | ||
|
|
dd66f8e84a | ||
|
|
b283c43a12 | ||
|
|
bb919aea90 | ||
|
|
61cc52380f | ||
|
|
61d633dfeb | ||
|
|
9913fdabfe | ||
|
|
b576bb19b1 | ||
|
|
0c6a143c2a | ||
|
|
ebedc37ffb | ||
|
|
1c70a4f643 | ||
|
|
afb61661ab | ||
|
|
e5026bc422 | ||
|
|
93d78c141d | ||
|
|
0b6104d01f | ||
|
|
1a7f45c6f5 | ||
|
|
616abc8701 | ||
|
|
1bb258ef59 | ||
|
|
9c2da8fe7a | ||
|
|
e1715cdc7a | ||
|
|
c58e4f23ff | ||
|
|
2e7a3263a5 | ||
|
|
34340895a3 | ||
|
|
5a2c25d0e6 | ||
|
|
37874387e7 | ||
|
|
70d6c8988a | ||
|
|
20470bfd3e | ||
|
|
dbbe254bfc | ||
|
|
08552d8968 | ||
|
|
7e8ba3d4e2 | ||
|
|
f72b481720 | ||
|
|
7d75dac29c | ||
|
|
80928c6e21 | ||
|
|
5bcbe08573 | ||
|
|
5c86b9a5e6 | ||
|
|
e246206e9c | ||
|
|
3c33bcdd61 | ||
|
|
cc7d822a0a | ||
|
|
30e113fbbe | ||
|
|
cbceb6101b | ||
|
|
3b6d2e7258 | ||
|
|
328f764024 | ||
|
|
8f5ed9c972 | ||
|
|
21d004eae9 | ||
|
|
436633bc68 | ||
|
|
8fae680cbe | ||
|
|
b172788741 | ||
|
|
48c12a4869 | ||
|
|
8396284de3 | ||
|
|
d57a21817b | ||
|
|
1ebb4cfd95 | ||
|
|
8112b4859f | ||
|
|
a412b61d8d | ||
|
|
cbfb16aebd | ||
|
|
854245c4f3 | ||
|
|
d96e724755 | ||
|
|
d0b3d82508 | ||
|
|
6d4ce976c7 | ||
|
|
d760757c46 | ||
|
|
67d87ed66b | ||
|
|
22fc1b454b | ||
|
|
2c483445a1 | ||
|
|
f5beaea3e0 | ||
|
|
4d61ed1557 | ||
|
|
f1bcfa02f5 | ||
|
|
16e09c0515 | ||
|
|
0ff7719d8a | ||
|
|
1d7ee6c27b | ||
|
|
e00233943b | ||
|
|
6c2448bb03 | ||
|
|
a511c380ba | ||
|
|
fa66501e5c | ||
|
|
35ea5b8a5b | ||
|
|
e5d7242dc1 | ||
|
|
3c994687ff | ||
|
|
171386f7a7 | ||
|
|
edeb2eca0c | ||
|
|
7fb596aafd | ||
|
|
eb4517a45d | ||
|
|
fa1b8cf6c4 | ||
|
|
a5ac6f41e2 | ||
|
|
7de67d6a7a | ||
|
|
db5dfef2d5 | ||
|
|
b6a0a0800f | ||
|
|
36b99d528e | ||
|
|
601455cb9b | ||
|
|
e0a489e471 | ||
|
|
aa4b79ab0c | ||
|
|
8db5aa099b | ||
|
|
47f63e3b06 | ||
|
|
43f23900e0 | ||
|
|
3a113557cd | ||
|
|
22163595fd | ||
|
|
4dc7e2fcfb | ||
|
|
557ebc8410 | ||
|
|
2c82cd8a7a | ||
|
|
47cc2900a6 | ||
|
|
c6e7c0d4c8 | ||
|
|
c6ad90f742 | ||
|
|
dfc7d0c917 | ||
|
|
4442cb3062 | ||
|
|
3ce6d274d5 | ||
|
|
ce7cb769b3 | ||
|
|
f3a210fd8d | ||
|
|
c7f05c426f | ||
|
|
bd3e8f024c | ||
|
|
c390074f1c | ||
|
|
43d39bb07a | ||
|
|
a95cd85155 | ||
|
|
d48079e859 | ||
|
|
12a629c652 | ||
|
|
e39d6a0f0d | ||
|
|
3c8b3eb46c | ||
|
|
c8bc8eca8f | ||
|
|
d5979a8b88 | ||
|
|
c38d6bec0d | ||
|
|
1616a7d42d | ||
|
|
ec21194229 | ||
|
|
8967d313e0 | ||
|
|
75eda36638 | ||
|
|
2a3666ae7c | ||
|
|
ab45e2f511 | ||
|
|
6b8f8443fb | ||
|
|
e451ec5f1f | ||
|
|
3898756bf6 | ||
|
|
3c22e53c2e | ||
|
|
12a75bf77d | ||
|
|
1211320939 | ||
|
|
86f7d974e7 | ||
|
|
f0eaf695ab | ||
|
|
cfceb063ee | ||
|
|
76b38c5c10 | ||
|
|
ae85e74094 | ||
|
|
e08cab3311 | ||
|
|
c9a124e708 | ||
|
|
640c54201f | ||
|
|
ba632c4c14 | ||
|
|
bd07e45c05 | ||
|
|
69ef5a478a | ||
|
|
2b425d4012 | ||
|
|
875fd9025a | ||
|
|
1fc61b1ec3 | ||
|
|
c38209d8d1 | ||
|
|
4ffb17757c | ||
|
|
5dcf1cf6b0 | ||
|
|
923651d11a | ||
|
|
fedb40c826 | ||
|
|
b9cd641db3 | ||
|
|
ddad5883fe | ||
|
|
b25dfcd263 | ||
|
|
8c85532c86 | ||
|
|
7e9b0067f1 | ||
|
|
7fb2ed6d8d | ||
|
|
65446ddbe7 | ||
|
|
205a8c0ee5 | ||
|
|
9462c66edf | ||
|
|
7c727df4f8 | ||
|
|
26fd95cea9 | ||
|
|
79c46f3b1e | ||
|
|
33f371967f | ||
|
|
7cc93d768d | ||
|
|
a1b7f871bf | ||
|
|
9ee7df5f50 | ||
|
|
180254581c | ||
|
|
28752e7602 | ||
|
|
d589cc0ffa | ||
|
|
97a1954a1b | ||
|
|
f98ce363dd | ||
|
|
f17f0b3310 | ||
|
|
140f19ed6f | ||
|
|
1e9ac2a9f2 | ||
|
|
aeb67f7dd9 | ||
|
|
afc0ece8d0 | ||
|
|
170d5a9f08 | ||
|
|
6e351f1a25 | ||
|
|
d67cc0bf8e | ||
|
|
239b7e1f75 | ||
|
|
9f1d134d7d | ||
|
|
2dfad4f4e3 | ||
|
|
defa86573e | ||
|
|
0880cc45f7 | ||
|
|
0c2dc0795a | ||
|
|
af81f6c99b | ||
|
|
a46af4b645 | ||
|
|
fe3c0ebb63 | ||
|
|
b3e15180af | ||
|
|
6735ed2071 | ||
|
|
2f379efc83 | ||
|
|
5f8e3b4dee | ||
|
|
0704a3b7c8 | ||
|
|
b22129fcba | ||
|
|
210602566e | ||
|
|
1e39f9f2f4 | ||
|
|
a98ee60d8b | ||
|
|
1293ca4f9d | ||
|
|
2e95518d48 | ||
|
|
0388d99d9e | ||
|
|
113564b497 | ||
|
|
b78e6e79e3 | ||
|
|
3b26752e3c | ||
|
|
ec3312d836 | ||
|
|
f1913087e4 | ||
|
|
eae3e33e7e | ||
|
|
2e8baad645 | ||
|
|
e6f127cf9e | ||
|
|
a1e16c989b | ||
|
|
955250650e | ||
|
|
85c76150f5 | ||
|
|
1baf0993de | ||
|
|
434a15076e | ||
|
|
4e7350363d | ||
|
|
38edd735b6 | ||
|
|
c207aa72e9 | ||
|
|
bf0925a4fc | ||
|
|
bc854aa183 | ||
|
|
c4bb2f6e3a | ||
|
|
8848656193 | ||
|
|
3ecff61114 | ||
|
|
f86943b884 | ||
|
|
448bb70ac8 | ||
|
|
d63ae21133 | ||
|
|
f71414bbb1 | ||
|
|
bdcacfc8db | ||
|
|
a36080c6de | ||
|
|
0e6510636d | ||
|
|
276d406fb6 | ||
|
|
fb79d82072 | ||
|
|
bbcbeeaf88 | ||
|
|
9f4d8fc777 | ||
|
|
1f781f6620 | ||
|
|
8a9d786b1a | ||
|
|
e1a02a6d69 | ||
|
|
5c8565367c | ||
|
|
9db929ed8b | ||
|
|
0a2c5f6c2c | ||
|
|
ae632a3dd7 | ||
|
|
c212077478 | ||
|
|
af5e08a864 | ||
|
|
adc7388ee1 | ||
|
|
116ba9b006 | ||
|
|
03860dcb49 | ||
|
|
a1ec05b210 | ||
|
|
dc1d507a20 | ||
|
|
72f284f987 | ||
|
|
ef11972274 | ||
|
|
96f9f4a36c | ||
|
|
311e4d13f6 | ||
|
|
f936dfa359 | ||
|
|
c1103630f0 | ||
|
|
64f6f5cda4 | ||
|
|
0be529f7be | ||
|
|
c0061b99e3 | ||
|
|
b129279fb8 |
@@ -1,4 +1,4 @@
|
||||
name: Autoupdate go.mod and go.sum
|
||||
name: Update dependencies
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -6,14 +6,16 @@ on:
|
||||
- cron: "0 3 * * *"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
autoupdate:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-autoupdate.yaml@main
|
||||
update:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/renovate-autoupdate.yaml@main
|
||||
with:
|
||||
go-version: ">=1.25"
|
||||
release-workflow: "release.yaml"
|
||||
secrets: inherit
|
||||
go-version: ">=1.27"
|
||||
node-working-directory: frontend
|
||||
release-workflow: release.yaml
|
||||
runner: self-hosted
|
||||
|
||||
@@ -9,8 +9,14 @@ 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.25"
|
||||
go-version: ">=1.27"
|
||||
runner: self-hosted
|
||||
|
||||
@@ -20,16 +20,22 @@ permissions:
|
||||
|
||||
jobs:
|
||||
release:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-release.yaml@main
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-release-cgo.yaml@main
|
||||
with:
|
||||
go-version: "1.25"
|
||||
docker-enabled: true
|
||||
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
|
||||
secrets: inherit
|
||||
|
||||
benchmark:
|
||||
name: Publish Benchmarks
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -40,7 +46,7 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
go-version: ">=1.27"
|
||||
|
||||
- name: Run benchmarks
|
||||
run: go test -bench=. -benchmem ./... -run=^# | tee output.txt
|
||||
@@ -50,27 +56,17 @@ jobs:
|
||||
with:
|
||||
tool: "go"
|
||||
output-file-path: output.txt
|
||||
fail-on-alert: true
|
||||
fail-on-alert: false
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
comment-on-alert: true
|
||||
summary-always: true
|
||||
auto-push: false
|
||||
auto-push: true
|
||||
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: ubuntu-latest
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -72,6 +72,7 @@ tests/fixtures/temp/
|
||||
# Markdown files (except README.md)
|
||||
*.md
|
||||
!README.md
|
||||
!lean4/FINDINGS.md
|
||||
|
||||
/gohoarder
|
||||
*.log
|
||||
@@ -80,3 +81,7 @@ test-go-proxy
|
||||
frontend/node_modules
|
||||
data/storage
|
||||
*.pid
|
||||
|
||||
# Local worktrees
|
||||
.worktrees/
|
||||
lean4/.lake
|
||||
|
||||
+138
-52
@@ -7,30 +7,91 @@ project_name: gohoarder
|
||||
before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
# 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
|
||||
# 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'
|
||||
|
||||
# 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=0
|
||||
goos:
|
||||
- linux
|
||||
- darwin
|
||||
- windows
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
- CGO_ENABLED=1
|
||||
tags:
|
||||
- fts5
|
||||
flags:
|
||||
- -trimpath
|
||||
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:
|
||||
@@ -87,8 +148,24 @@ 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
|
||||
@@ -101,21 +178,21 @@ dockers_v2:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
dockerfile: Dockerfile.server
|
||||
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 }}"
|
||||
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 }}"
|
||||
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:
|
||||
@@ -125,18 +202,21 @@ dockers_v2:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
dockerfile: Dockerfile.frontend
|
||||
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 }}"
|
||||
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 }}"
|
||||
extra_files:
|
||||
- frontend
|
||||
- frontend/dist
|
||||
|
||||
# 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
|
||||
@@ -149,38 +229,44 @@ dockers_v2:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
dockerfile: Dockerfile.scanner
|
||||
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 }}"
|
||||
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 }}"
|
||||
extra_files:
|
||||
- config.yaml.example
|
||||
|
||||
# 4. Gateway - Nginx reverse proxy for unified deployment
|
||||
- id: gohoarder-gateway
|
||||
# 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
|
||||
ids:
|
||||
- gohoarder
|
||||
- migrate
|
||||
images:
|
||||
- ghcr.io/lukaszraczylo/gohoarder-gateway
|
||||
- ghcr.io/lukaszraczylo/gohoarder-migrate
|
||||
tags:
|
||||
- "{{ .Version }}"
|
||||
- latest
|
||||
platforms:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
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 }}"
|
||||
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
|
||||
|
||||
# Artifact signing with cosign
|
||||
signs:
|
||||
|
||||
+110
-33
@@ -1,28 +1,15 @@
|
||||
# Website - Frontend Dashboard
|
||||
# Build stage
|
||||
FROM node:20-alpine AS builder
|
||||
# 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
|
||||
|
||||
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
|
||||
FROM mirror.gcr.io/library/nginx:1.31.9-alpine@sha256:fb4658584bd9a916ffb6f6e365f97c25cfdb2923801f551ea08356e695f14ff7
|
||||
|
||||
# Install envsubst for runtime configuration
|
||||
RUN apk add --no-cache gettext
|
||||
|
||||
# Copy built frontend
|
||||
COPY --from=builder /build/dist /usr/share/nginx/html
|
||||
# Copy pre-built frontend files
|
||||
# These are built on the CI runner and injected via extra_files
|
||||
COPY frontend/dist /usr/share/nginx/html
|
||||
|
||||
# Create runtime config injection script
|
||||
RUN cat > /docker-entrypoint.d/40-inject-config.sh <<'EOF'
|
||||
@@ -48,21 +35,101 @@ EOF
|
||||
|
||||
RUN chmod +x /docker-entrypoint.d/40-inject-config.sh
|
||||
|
||||
# Copy nginx configuration
|
||||
RUN cat > /etc/nginx/conf.d/default.conf <<'EOF'
|
||||
# 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;
|
||||
|
||||
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;
|
||||
|
||||
# SPA routing
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
# 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;
|
||||
}
|
||||
|
||||
# Runtime configuration endpoint
|
||||
@@ -72,19 +139,25 @@ 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
|
||||
|
||||
@@ -95,6 +168,10 @@ 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
|
||||
APP_NAME=GoHoarder \
|
||||
BACKEND_HOST=gohoarder-server \
|
||||
BACKEND_PORT=8080 \
|
||||
SERVER_NAME=_
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
# 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;'"]
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
# 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;'"]
|
||||
@@ -0,0 +1,37 @@
|
||||
# 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"]
|
||||
+25
-10
@@ -1,10 +1,12 @@
|
||||
# Scanning Engine - Background Scanner Worker
|
||||
ARG TARGETOS
|
||||
# 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
|
||||
|
||||
FROM alpine:latest
|
||||
|
||||
# Install scanning tools and runtime dependencies
|
||||
# Install scanning tools and runtime dependencies (including CGO/SQLite dependencies)
|
||||
RUN apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
@@ -12,13 +14,26 @@ 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/main/contrib/install.sh | sh -s -- -b /usr/local/bin
|
||||
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/v0.76.2/contrib/install.sh | sh -s -- -b /usr/local/bin v0.76.2
|
||||
|
||||
# Install Grype for vulnerability scanning
|
||||
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
|
||||
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
|
||||
|
||||
# Create non-root user
|
||||
RUN addgroup -g 1000 scanner && \
|
||||
@@ -37,10 +52,10 @@ RUN mkdir -p /var/cache/gohoarder \
|
||||
/var/lib/gohoarder \
|
||||
/var/lib/trivy
|
||||
|
||||
# Copy binary (from platform-specific path)
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
COPY ${TARGETOS}/${TARGETARCH}/gohoarder /usr/local/bin/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}/gohoarder /usr/local/bin/gohoarder
|
||||
RUN chmod +x /usr/local/bin/gohoarder
|
||||
|
||||
# Copy example config
|
||||
|
||||
+13
-9
@@ -1,13 +1,17 @@
|
||||
# Application Engine - GoHoarder Server
|
||||
ARG TARGETOS
|
||||
# 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
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
FROM alpine:latest
|
||||
|
||||
# Install runtime dependencies
|
||||
# Install runtime dependencies (CGO/SQLite requires these)
|
||||
RUN apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
sqlite-libs \
|
||||
musl \
|
||||
&& update-ca-certificates
|
||||
|
||||
# Create non-root user
|
||||
@@ -24,10 +28,10 @@ RUN mkdir -p /var/cache/gohoarder \
|
||||
chmod -R 750 /var/cache/gohoarder \
|
||||
/var/lib/gohoarder
|
||||
|
||||
# Copy binary (from platform-specific path)
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
COPY ${TARGETOS}/${TARGETARCH}/gohoarder /usr/local/bin/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}/gohoarder /usr/local/bin/gohoarder
|
||||
RUN chmod +x /usr/local/bin/gohoarder
|
||||
|
||||
# Copy example config
|
||||
|
||||
@@ -78,17 +78,24 @@ clean: ## Clean build artifacts
|
||||
@rm -f *.db *.db-shm *.db-wal
|
||||
@echo "Clean complete"
|
||||
|
||||
clean-db: ## Clean all local cache and database files (from config.yaml paths)
|
||||
clean-db: ## Clean all local cache and database files (requires confirmation)
|
||||
@echo "WARNING: This will delete all cached packages and scan results!"
|
||||
@echo "Paths from config.yaml:"
|
||||
@echo "Paths to be cleaned:"
|
||||
@echo " - ./data/storage (package cache)"
|
||||
@echo " - ./data/gohoarder.db (metadata database)"
|
||||
@echo " - ./data/gohoarder.db and gohoarder.db (metadata database)"
|
||||
@echo " - /tmp/trivy (Trivy cache)"
|
||||
@echo ""
|
||||
@read -p "Are you sure you want to continue? [y/N] " confirm && [ "$$confirm" = "y" ] || exit 1
|
||||
@printf "Are you sure you want to continue? [y/N] " && read confirm && [ "$$confirm" = "y" ] || (echo "Cancelled." && exit 1)
|
||||
@echo "Cleaning database and cache..."
|
||||
@rm -rf ./data/storage
|
||||
@rm -f ./data/gohoarder.db ./data/gohoarder.db-shm ./data/gohoarder.db-wal
|
||||
@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 /tmp/trivy
|
||||
@echo "Database and cache cleaned successfully"
|
||||
|
||||
|
||||
@@ -193,6 +193,7 @@ 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
|
||||
@@ -233,7 +234,12 @@ security:
|
||||
enabled: true
|
||||
|
||||
cache:
|
||||
default_ttl: 86400 # 24 hours in seconds
|
||||
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
|
||||
|
||||
logging:
|
||||
level: "info" # debug, info, warn, error
|
||||
@@ -245,6 +251,17 @@ 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:
|
||||
@@ -876,10 +893,29 @@ Access the web dashboard at **http://localhost:8080**
|
||||
**List Packages:**
|
||||
```bash
|
||||
GET /api/packages
|
||||
GET /api/packages?registry=npm
|
||||
GET /api/packages?status=vulnerable
|
||||
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
|
||||
```
|
||||
|
||||
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
|
||||
@@ -909,7 +945,10 @@ GET /api/packages/:registry/:name/:version
|
||||
}
|
||||
}
|
||||
],
|
||||
"total": 42
|
||||
"total": 1,
|
||||
"total_groups": 42,
|
||||
"page": 1,
|
||||
"page_size": 25
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// Package commands hosts the cobra commands wired into the gohoarder CLI.
|
||||
package commands
|
||||
|
||||
import (
|
||||
@@ -35,11 +36,11 @@ func runServe(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
// Initialize logger
|
||||
if err := logger.Init(logger.Config{
|
||||
if logErr := logger.Init(logger.Config{
|
||||
Level: cfg.Logging.Level,
|
||||
Format: cfg.Logging.Format,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("failed to initialize logger: %w", err)
|
||||
}); logErr != nil {
|
||||
return fmt.Errorf("failed to initialize logger: %w", logErr)
|
||||
}
|
||||
|
||||
log.Info().
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
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
|
||||
}
|
||||
+56
-10
@@ -10,8 +10,13 @@ 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: ""
|
||||
@@ -40,36 +45,77 @@ storage:
|
||||
domain: ""
|
||||
|
||||
metadata:
|
||||
backend: "sqlite" # sqlite, postgresql, file
|
||||
connection: "file:gohoarder.db?cache=shared&mode=rwc"
|
||||
# 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
|
||||
|
||||
# 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
|
||||
wal_mode: true # Set to false for network filesystems if you must use SQLite
|
||||
|
||||
# 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"
|
||||
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
|
||||
|
||||
cache:
|
||||
default_ttl: "168h" # 7 days
|
||||
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
|
||||
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:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
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)
|
||||
# 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")
|
||||
@@ -92,7 +138,7 @@ security:
|
||||
# Supports: npm, PyPI, Go, Maven, NuGet, etc.
|
||||
osv:
|
||||
enabled: false
|
||||
api_url: "https://api.osv.dev"
|
||||
api_url: "https://api.osv.dev/v1/query" # full query endpoint, not the host
|
||||
timeout: "30s"
|
||||
|
||||
# Grype - Multi-ecosystem vulnerability scanner from Anchore
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# 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
|
||||
@@ -222,6 +223,13 @@ 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: /
|
||||
@@ -325,88 +333,6 @@ 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
|
||||
@@ -436,7 +362,7 @@ spec:
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: gohoarder-gateway
|
||||
name: gohoarder-frontend
|
||||
port:
|
||||
number: 80
|
||||
# Uncomment for HTTPS/TLS
|
||||
@@ -477,20 +403,20 @@ spec:
|
||||
averageUtilization: 80
|
||||
|
||||
---
|
||||
# HorizontalPodAutoscaler - Gateway
|
||||
# HorizontalPodAutoscaler - Frontend
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
metadata:
|
||||
name: gohoarder-gateway
|
||||
name: gohoarder-frontend
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: gateway
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
scaleTargetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: gohoarder-gateway
|
||||
name: gohoarder-frontend
|
||||
minReplicas: 2
|
||||
maxReplicas: 10
|
||||
metrics:
|
||||
|
||||
+14
-38
@@ -2,7 +2,7 @@ version: '3.8'
|
||||
|
||||
# GoHoarder - Unified Deployment Example
|
||||
# This docker-compose file demonstrates deploying all GoHoarder services
|
||||
# under a single domain using the gateway reverse proxy
|
||||
# The frontend includes integrated reverse proxy to the backend
|
||||
|
||||
services:
|
||||
# Backend - Main application server
|
||||
@@ -39,7 +39,7 @@ services:
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
|
||||
# Frontend - Web dashboard
|
||||
# Frontend - Web dashboard with integrated reverse proxy
|
||||
gohoarder-frontend:
|
||||
image: ghcr.io/lukaszraczylo/gohoarder-frontend:latest
|
||||
container_name: gohoarder-frontend
|
||||
@@ -49,8 +49,19 @@ 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
|
||||
@@ -82,41 +93,6 @@ 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
|
||||
@@ -144,7 +120,7 @@ volumes:
|
||||
# - Metrics: http://localhost/metrics
|
||||
#
|
||||
# For production:
|
||||
# - Enable HTTPS in the gateway container
|
||||
# - Enable HTTPS in the frontend container (add SSL certificates to nginx)
|
||||
# - Set up proper SSL certificates
|
||||
# - Configure firewall rules
|
||||
# - Set appropriate resource limits
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
# 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
|
||||
@@ -5,3 +5,6 @@ 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
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"hash": "eb707743",
|
||||
"configHash": "e17a1322",
|
||||
"lockfileHash": "c2e83396",
|
||||
"browserHash": "ab796ace",
|
||||
"optimized": {},
|
||||
"chunks": {}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"$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": {}
|
||||
}
|
||||
+4
-6
@@ -1,13 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<html lang="en" data-style="workbench">
|
||||
<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" />
|
||||
<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>
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<link rel="icon" href="data:," />
|
||||
<title>GoHoarder dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
+16
-22
@@ -8,36 +8,30 @@
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage"
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"sources": "node scripts/library-sources.mjs --write"
|
||||
},
|
||||
"dependencies": {
|
||||
"@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",
|
||||
"@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",
|
||||
"vue": "^3.5.26",
|
||||
"vue-router": "^4.6.4"
|
||||
"vue-router": "^5.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@fortawesome/fontawesome-free": "^7.1.0",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@testing-library/jest-dom": "^7.0.0",
|
||||
"@testing-library/vue": "^8.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
"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",
|
||||
"jsdom": "^31.0.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.0.0",
|
||||
"vitest": "^5.0.3",
|
||||
"vue-tsc": "^3.2.1"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+1621
-2019
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,8 @@
|
||||
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
|
||||
@@ -1,6 +0,0 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export function librarySources(root: string): string[]
|
||||
@@ -0,0 +1,94 @@
|
||||
// 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'))
|
||||
}
|
||||
}
|
||||
+47
-58
@@ -1,61 +1,50 @@
|
||||
<template>
|
||||
<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>
|
||||
<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'
|
||||
|
||||
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
|
||||
<router-view />
|
||||
</main>
|
||||
// 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 cache manager</p>
|
||||
</template>
|
||||
<template #actions><ThemeToggle /></template>
|
||||
<template #mobile><AppNav sheet /></template>
|
||||
</AppHeader>
|
||||
|
||||
<!-- 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 />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// App component
|
||||
</script>
|
||||
|
||||
@@ -1,347 +1,204 @@
|
||||
<template>
|
||||
<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
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="CVE bypass management"
|
||||
description="Manage temporary security bypasses for packages and CVEs."
|
||||
>
|
||||
<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
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 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>
|
||||
<LoadingState v-if="loading" variant="table" label="Loading bypasses..." />
|
||||
|
||||
<!-- Error Alert -->
|
||||
<Alert v-if="error" variant="destructive" class="mb-4">
|
||||
<i class="fas fa-exclamation-circle mr-2"></i>
|
||||
<AlertDescription>{{ error }}</AlertDescription>
|
||||
</Alert>
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load bypasses"
|
||||
:message="error"
|
||||
@retry="fetchBypasses"
|
||||
/>
|
||||
|
||||
<!-- 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 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>
|
||||
<EmptyState
|
||||
v-if="filteredBypasses.length === 0"
|
||||
:icon="faShieldHalved"
|
||||
title="No bypasses found"
|
||||
description="Create a bypass to allow packages with known vulnerabilities."
|
||||
/>
|
||||
<DataTable
|
||||
v-else
|
||||
label="Bypasses"
|
||||
layout="cards"
|
||||
row-key="id"
|
||||
:columns="bypassColumns"
|
||||
:rows="filteredBypasses"
|
||||
>
|
||||
<template #cell-type="{ row }">
|
||||
<Badge :variant="row.type === 'cve' ? 'default' : '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-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>
|
||||
</Card>
|
||||
|
||||
<!-- Create/Edit Bypass Modal -->
|
||||
<Dialog v-model:open="showCreateModal">
|
||||
<DialogContent class="max-w-2xl">
|
||||
<DialogContent size="lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ editingBypass ? 'Edit' : 'Create' }} Bypass</DialogTitle>
|
||||
<DialogTitle>{{ editingBypass ? 'Edit' : 'Create' }} bypass</DialogTitle>
|
||||
<DialogDescription>
|
||||
{{ editingBypass ? 'Update bypass settings' : 'Create a temporary bypass for a CVE or package' }}
|
||||
{{ editingBypass ? 'Update the bypass settings.' : 'Create a temporary bypass for a CVE or package.' }}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<!-- Target -->
|
||||
<div v-if="!editingBypass">
|
||||
<label class="text-sm font-medium text-gray-700 mb-2 block">
|
||||
{{ bypassForm.type === 'cve' ? 'CVE ID' : 'Package' }}
|
||||
</label>
|
||||
<Field
|
||||
v-if="!editingBypass"
|
||||
:label="bypassForm.type === 'cve' ? 'CVE ID' : 'Package'"
|
||||
:hint="
|
||||
bypassForm.type === 'cve'
|
||||
? 'Enter the CVE ID, for example CVE-2021-23337.'
|
||||
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions. PyPI packages use the release version, for example pypi/[email protected].'
|
||||
"
|
||||
required
|
||||
>
|
||||
<Input
|
||||
v-model="bypassForm.target"
|
||||
:placeholder="bypassForm.type === 'cve' ? 'CVE-2021-23337' : 'npm/[email protected]'"
|
||||
class="w-full"
|
||||
/>
|
||||
<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>
|
||||
|
||||
<!-- 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
|
||||
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>
|
||||
<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>
|
||||
|
||||
<!-- 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>
|
||||
<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>
|
||||
|
||||
<!-- 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>
|
||||
<Field v-if="!editingBypass" label="Created by" required>
|
||||
<Input v-model="bypassForm.created_by" placeholder="[email protected]" />
|
||||
</Field>
|
||||
|
||||
<!-- Expires In -->
|
||||
<div>
|
||||
<label class="text-sm font-medium text-gray-700 mb-2 block">Expires In (Hours) *</label>
|
||||
<Field
|
||||
label="Expires in (hours)"
|
||||
hint="Hours until this bypass expires. 168 is 7 days and 720 is 30 days."
|
||||
required
|
||||
>
|
||||
<Input
|
||||
v-model.number="bypassForm.expires_in_hours"
|
||||
:model-value="bypassForm.expires_in_hours"
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="168"
|
||||
class="w-full"
|
||||
@update:model-value="setExpiresInHours"
|
||||
/>
|
||||
<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>
|
||||
</Field>
|
||||
|
||||
<!-- 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-if="editingBypass" v-model="bypassForm.active" label="Active" />
|
||||
|
||||
<!-- 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>
|
||||
<Checkbox v-model="bypassForm.notify_on_expiry" label="Send a notification when the bypass expires" />
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="closeCreateModal" variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button @click="submitBypass" :disabled="!isFormValid">
|
||||
{{ editingBypass ? 'Update' : 'Create' }} Bypass
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="closeCreateModal">Cancel</Button>
|
||||
<Button type="submit" :disabled="!isFormValid">{{ editingBypass ? 'Update' : 'Create' }} bypass</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- Delete Confirmation Dialog -->
|
||||
<Dialog v-model:open="showDeleteModal">
|
||||
<DialogContent>
|
||||
<Dialog v-model:open="showKeyDialog">
|
||||
<DialogContent size="sm">
|
||||
<DialogHeader>
|
||||
<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>
|
||||
<DialogTitle>Admin API key</DialogTitle>
|
||||
<DialogDescription>Enter your admin API key to manage bypasses.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button @click="showDeleteModal = false" variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button @click="deleteBypass" variant="destructive">
|
||||
Delete
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
<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>
|
||||
</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 } from 'vue'
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
Checkbox,
|
||||
ConfirmDialog,
|
||||
DataTable,
|
||||
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'
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Field,
|
||||
IconButton,
|
||||
Input,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
SegmentedControl,
|
||||
StatusBadge,
|
||||
Textarea,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { faPen, faPlus, faRotateRight, faShieldHalved, faTrash } from '@/lib/icons'
|
||||
|
||||
interface Bypass {
|
||||
id: string
|
||||
@@ -358,17 +215,17 @@ interface Bypass {
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const successMessage = ref<string | null>(null)
|
||||
const toasts = useToastStore()
|
||||
const bypasses = ref<Bypass[]>([])
|
||||
const activeFilter = ref<'all' | 'active' | 'expired'>('all')
|
||||
const typeFilter = ref<'' | 'cve' | 'package'>('')
|
||||
const typeFilter = ref<'all' | 'cve' | 'package'>('all')
|
||||
|
||||
const showCreateModal = ref(false)
|
||||
const showDeleteModal = ref(false)
|
||||
const editingBypass = ref<Bypass | null>(null)
|
||||
const bypassToDelete = ref<Bypass | null>(null)
|
||||
|
||||
const bypassForm = ref({
|
||||
const EMPTY_FORM = {
|
||||
type: 'cve' as 'cve' | 'package',
|
||||
target: '',
|
||||
reason: '',
|
||||
@@ -377,10 +234,14 @@ const bypassForm = ref({
|
||||
applies_to: '',
|
||||
notify_on_expiry: false,
|
||||
active: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bypassForm = ref({ ...EMPTY_FORM })
|
||||
|
||||
// Get API key from localStorage or prompt user
|
||||
const apiKey = ref<string>('')
|
||||
const keyInput = ref('')
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
const filteredBypasses = computed(() => {
|
||||
let filtered = bypasses.value
|
||||
@@ -393,7 +254,7 @@ const filteredBypasses = computed(() => {
|
||||
}
|
||||
|
||||
// Filter by type
|
||||
if (typeFilter.value) {
|
||||
if (typeFilter.value !== 'all') {
|
||||
filtered = filtered.filter(b => b.type === typeFilter.value)
|
||||
}
|
||||
|
||||
@@ -423,16 +284,23 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
function promptForApiKey() {
|
||||
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'
|
||||
}
|
||||
keyInput.value = ''
|
||||
showKeyDialog.value = true
|
||||
}
|
||||
|
||||
function submitApiKey() {
|
||||
const key = keyInput.value.trim()
|
||||
if (!key) return
|
||||
apiKey.value = key
|
||||
localStorage.setItem('admin_api_key', 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()
|
||||
@@ -448,7 +316,7 @@ async function fetchBypasses() {
|
||||
} else if (activeFilter.value === 'expired') {
|
||||
params.append('include_expired', 'true')
|
||||
}
|
||||
if (typeFilter.value) {
|
||||
if (typeFilter.value !== 'all') {
|
||||
params.append('type', typeFilter.value)
|
||||
}
|
||||
|
||||
@@ -476,8 +344,6 @@ async function submitBypass() {
|
||||
if (!isFormValid.value) return
|
||||
|
||||
loading.value = true
|
||||
error.value = null
|
||||
successMessage.value = null
|
||||
|
||||
try {
|
||||
if (editingBypass.value) {
|
||||
@@ -495,7 +361,7 @@ async function submitBypass() {
|
||||
},
|
||||
}
|
||||
)
|
||||
successMessage.value = 'Bypass updated successfully'
|
||||
toasts.success('Bypass updated')
|
||||
} else {
|
||||
// Create new bypass
|
||||
await axios.post(
|
||||
@@ -515,19 +381,14 @@ async function submitBypass() {
|
||||
},
|
||||
}
|
||||
)
|
||||
successMessage.value = 'Bypass created successfully'
|
||||
toasts.success('Bypass created')
|
||||
}
|
||||
|
||||
closeCreateModal()
|
||||
await fetchBypasses()
|
||||
|
||||
// Clear success message after 5 seconds
|
||||
setTimeout(() => {
|
||||
successMessage.value = null
|
||||
}, 5000)
|
||||
} catch (err: any) {
|
||||
console.error('Failed to submit bypass:', err)
|
||||
error.value = err.response?.data?.error?.message || err.message || 'Failed to save bypass'
|
||||
toasts.error('Could not save bypass', err.response?.data?.error?.message || err.message || 'Failed to save bypass')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -550,19 +411,15 @@ function editBypass(bypass: Bypass) {
|
||||
|
||||
function closeCreateModal() {
|
||||
showCreateModal.value = false
|
||||
editingBypass.value = null
|
||||
bypassForm.value = {
|
||||
type: 'cve',
|
||||
target: '',
|
||||
reason: '',
|
||||
created_by: '',
|
||||
expires_in_hours: 168,
|
||||
applies_to: '',
|
||||
notify_on_expiry: false,
|
||||
active: true,
|
||||
}
|
||||
}
|
||||
|
||||
// Also covers dismissal by Escape or the close button, so the next open never reuses an old edit.
|
||||
watch(showCreateModal, (open) => {
|
||||
if (open) return
|
||||
editingBypass.value = null
|
||||
bypassForm.value = { ...EMPTY_FORM }
|
||||
})
|
||||
|
||||
function confirmDeleteBypass(bypass: Bypass) {
|
||||
bypassToDelete.value = bypass
|
||||
showDeleteModal.value = true
|
||||
@@ -572,8 +429,6 @@ 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}`, {
|
||||
@@ -582,18 +437,13 @@ async function deleteBypass() {
|
||||
},
|
||||
})
|
||||
|
||||
successMessage.value = 'Bypass deleted successfully'
|
||||
toasts.success('Bypass deleted')
|
||||
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)
|
||||
error.value = err.response?.data?.error?.message || err.message || 'Failed to delete bypass'
|
||||
toasts.error('Could not delete bypass', err.response?.data?.error?.message || err.message || 'Failed to delete bypass')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -603,7 +453,37 @@ function isExpired(expiresAt: string): boolean {
|
||||
return new Date(expiresAt) < new Date()
|
||||
}
|
||||
|
||||
function formatDate(date: string): string {
|
||||
return new Date(date).toLocaleString()
|
||||
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', rowHeader: true },
|
||||
{ key: 'type', header: 'Type' },
|
||||
{ key: 'status', header: 'Status', accessor: (b) => (b.active ? 'active' : 'inactive') },
|
||||
{ key: 'reason', header: 'Reason' },
|
||||
{ key: 'created_by', header: 'Created by' },
|
||||
{ key: 'created_at', header: 'Created', accessor: (b) => formatDate(b.created_at) },
|
||||
{ key: 'expires_at', header: 'Expires', accessor: (b) => formatDate(b.expires_at) },
|
||||
{ key: 'applies_to', header: 'Applies to' },
|
||||
{ key: 'actions', header: 'Actions', actions: true, accessor: () => '' },
|
||||
]
|
||||
|
||||
function setExpiresInHours(value: string | number) {
|
||||
bypassForm.value.expires_in_hours = Number(value)
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
@@ -1,21 +1,28 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
describe('Dashboard.vue', () => {
|
||||
beforeEach(() => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Dashboard) => mountWith(component, { global: { plugins: [router] } })
|
||||
|
||||
beforeEach(async () => {
|
||||
router = await createTestRouter('/')
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
// Mock the fetch functions to prevent actual API calls
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchRecentPackages').mockResolvedValue()
|
||||
})
|
||||
|
||||
it('renders dashboard component', () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
expect(wrapper.find('h2').text()).toBe('Dashboard')
|
||||
expect(wrapper.find('h1').text()).toBe('Dashboard')
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
@@ -47,15 +54,17 @@ describe('Dashboard.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 2,
|
||||
total_size: 3072,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 30,
|
||||
scanned_packages: 2,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Total Packages')
|
||||
expect(wrapper.text()).toContain('Total Size')
|
||||
expect(wrapper.text()).toContain('Total Downloads')
|
||||
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 () => {
|
||||
@@ -67,9 +76,11 @@ describe('Dashboard.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
@@ -85,9 +96,11 @@ describe('Dashboard.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
@@ -103,9 +116,11 @@ describe('Dashboard.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 1048576, // 1 MB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
@@ -117,7 +132,7 @@ describe('Dashboard.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -131,25 +146,15 @@ describe('Dashboard.vue', () => {
|
||||
]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Recent Packages')
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
})
|
||||
|
||||
it('shows recent packages sorted by cached_at', async () => {
|
||||
it('lists recent packages in the order the store holds them, newest first', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.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,
|
||||
},
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '2',
|
||||
registry: 'npm',
|
||||
@@ -160,49 +165,82 @@ describe('Dashboard.vue', () => {
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'old-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const recentPackagesSection = wrapper.text().split('Recent Packages')[1]
|
||||
const recentPackagesSection = wrapper.text().split('Recent packages')[1]
|
||||
|
||||
// new-package should appear before old-package since it's more recent
|
||||
// The store sorts by cached_at; the view keeps that order
|
||||
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 = []
|
||||
store.recentPackages = []
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('0')
|
||||
expect(wrapper.text()).toContain('0 B')
|
||||
})
|
||||
|
||||
it('renders realtime lastStats over polled stats when present', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
const rt = useRealtimeStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 10,
|
||||
total_size: 1024,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 5,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
rt.lastStats = {
|
||||
total_packages: 999,
|
||||
total_size: 2048,
|
||||
total_downloads: 777,
|
||||
scanned_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Realtime values should be visible (override polled values).
|
||||
expect(wrapper.text()).toContain('999')
|
||||
expect(wrapper.text()).toContain('777')
|
||||
})
|
||||
|
||||
it('shows a neutral "Live updates paused" badge while the socket is down', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live updates paused')
|
||||
expect(badge.text()).not.toMatch(/offline/i)
|
||||
expect(badge.attributes('data-tone')).toBe('neutral')
|
||||
})
|
||||
|
||||
it('shows a "Live" badge once the socket is connected', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
useRealtimeStore().connected = true
|
||||
await wrapper.vm.$nextTick()
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live')
|
||||
expect(badge.attributes('data-tone')).toBe('success')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,179 +1,103 @@
|
||||
<template>
|
||||
<div>
|
||||
<h2 class="text-3xl font-bold text-gray-900 mb-8">Dashboard</h2>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Dashboard" description="What the cache holds and what is moving through it.">
|
||||
<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>
|
||||
|
||||
<!-- Error Alert -->
|
||||
<Alert v-if="error" variant="destructive" class="mb-4">
|
||||
<i class="fas fa-exclamation-circle mr-2"></i>
|
||||
<AlertDescription>{{ error }}</AlertDescription>
|
||||
</Alert>
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
|
||||
<!-- 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>
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<!-- 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>
|
||||
<template v-else>
|
||||
<StatGroup :columns="4" aria-label="Cache totals">
|
||||
<KpiTile label="Total packages" :value="displayStats?.total_packages || 0" :icon="faBoxesStacked" />
|
||||
<KpiTile label="Total size" :value="formatBytes(displayStats?.total_size || 0)" :icon="faHardDrive" />
|
||||
<KpiTile label="Total downloads" :value="displayStats?.total_downloads || 0" :icon="faDownload" />
|
||||
<KpiTile label="Scanned packages" :value="displayStats?.scanned_packages || 0" :icon="faShieldHalved" />
|
||||
</StatGroup>
|
||||
|
||||
<Card 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>
|
||||
<Card v-if="recentRealtimeEvents.length > 0" data-testid="ws-event-feed">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Live activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ActivityFeed :events="feedEvents" variant="compact" label="Live activity" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 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>
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Download activity</CardTitle>
|
||||
<CardAction>
|
||||
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState
|
||||
v-if="chartLoading && chartData.length === 0"
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
:series="[{ name: 'Downloads', data: chartData }]"
|
||||
label="Downloads over the selected period"
|
||||
empty-text="No download activity in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<TrendChart compact class="min-w-0" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Recent packages</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="recentPackages.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<DataTable
|
||||
v-else
|
||||
label="Recent packages"
|
||||
layout="cards"
|
||||
:columns="packageColumns"
|
||||
:rows="recentPackages"
|
||||
>
|
||||
<template #cell-registry="{ row }">
|
||||
<Badge variant="outline">{{ row.registry }}</Badge>
|
||||
</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -181,23 +105,110 @@
|
||||
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'
|
||||
import {
|
||||
ActivityFeed,
|
||||
BarChart,
|
||||
Badge,
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
SegmentedControl,
|
||||
StatGroup,
|
||||
StatusBadge,
|
||||
type ActivityEvent,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { useRealtimeStore } from '../stores/realtime'
|
||||
import type { EventType, RealtimeEvent } from '@/lib/ws'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import {
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
faBoxesStacked,
|
||||
faChartLine,
|
||||
faDownload,
|
||||
faHardDrive,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
} from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { packages, stats, loading, error } = storeToRefs(store)
|
||||
const { recentPackages, stats, loading, error } = storeToRefs(store)
|
||||
|
||||
const rt = useRealtimeStore()
|
||||
const { lastStats, events: rtEvents } = storeToRefs(rt)
|
||||
|
||||
// Realtime stats override polled stats when available; otherwise fall back.
|
||||
const displayStats = computed(() => lastStats.value ?? stats.value)
|
||||
|
||||
const recentRealtimeEvents = computed<RealtimeEvent[]>(() => {
|
||||
const list = rtEvents.value
|
||||
return list.slice(Math.max(list.length - 5, 0)).reverse()
|
||||
})
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
function iconForEvent(type: EventType): IconDefinition {
|
||||
return EVENT_ICONS[type] ?? faChartLine
|
||||
}
|
||||
|
||||
const feedEvents = computed<ActivityEvent[]>(() =>
|
||||
recentRealtimeEvents.value.map((evt, idx) => ({
|
||||
id: `${evt.timestamp}-${idx}`,
|
||||
action: labelForEvent(evt.type),
|
||||
target: describeEvent(evt) || undefined,
|
||||
time: evt.timestamp,
|
||||
icon: iconForEvent(evt.type),
|
||||
})),
|
||||
)
|
||||
|
||||
function labelForEvent(type: EventType): string {
|
||||
return EVENT_LABELS[type] ?? type
|
||||
}
|
||||
|
||||
function describeEvent(evt: RealtimeEvent): string {
|
||||
const p = evt.payload
|
||||
const name = typeof p.name === 'string' ? p.name : ''
|
||||
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
|
||||
const version = typeof shown === 'string' ? `@${shown}` : ''
|
||||
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
|
||||
if (evt.type === 'stats_update') return ''
|
||||
if (name) return `${registry}${name}${version}`
|
||||
return ''
|
||||
}
|
||||
|
||||
// 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' },
|
||||
{ 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
|
||||
@@ -214,16 +225,19 @@ interface TimeSeriesStats {
|
||||
|
||||
const timeSeriesData = ref<TimeSeriesStats | null>(null)
|
||||
const chartLoading = ref(false)
|
||||
const chartError = ref<string | null>(null)
|
||||
|
||||
// Fetch time-series data from API
|
||||
async function fetchTimeSeriesData() {
|
||||
chartLoading.value = true
|
||||
chartError.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/timeseries?period=${selectedPeriod.value}`)
|
||||
timeSeriesData.value = response.data
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch time-series data:', err)
|
||||
timeSeriesData.value = null
|
||||
chartError.value = err instanceof Error ? err.message : 'Failed to load download activity'
|
||||
} finally {
|
||||
chartLoading.value = false
|
||||
}
|
||||
@@ -237,11 +251,20 @@ const chartData = computed(() => {
|
||||
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
|
||||
})
|
||||
const chartLabels = computed(() => chartData.value.map((_, index) => getChartLabel(index)))
|
||||
|
||||
const packageColumns: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', rowHeader: true },
|
||||
{ key: 'version', header: 'Version', accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
|
||||
{ key: 'registry', header: 'Registry' },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
|
||||
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
|
||||
]
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void store.fetchRecentPackages()
|
||||
}
|
||||
|
||||
function getChartLabel(index: number): string {
|
||||
// Use timestamp from data if available
|
||||
@@ -272,34 +295,17 @@ function getChartLabel(index: number): string {
|
||||
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()
|
||||
// Connect to realtime stream first so we can pick up live events while
|
||||
// initial polling resolves. Singleton survives navigation, so we
|
||||
// intentionally do not disconnect on unmount.
|
||||
rt.connect()
|
||||
await Promise.all([store.fetchStats(), store.fetchRecentPackages(), 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>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<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 dashboard</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>
|
||||
@@ -1,250 +1,154 @@
|
||||
<template>
|
||||
<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>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader :title="packageName">
|
||||
<template #back>
|
||||
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to packages</Button>
|
||||
</template>
|
||||
<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>
|
||||
</span>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<!-- 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>
|
||||
<LoadingState v-if="loading" variant="card" label="Loading vulnerability details..." />
|
||||
|
||||
<!-- 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>
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load vulnerability details"
|
||||
:message="error"
|
||||
@retry="fetchVulnerabilities"
|
||||
/>
|
||||
|
||||
<!-- Vulnerability Details -->
|
||||
<div v-else-if="vulnerabilities" class="space-y-6">
|
||||
<!-- Summary Card -->
|
||||
<template v-else-if="vulnerabilities">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
<i class="fas fa-shield-virus text-red-600"></i>
|
||||
Security Scan Summary
|
||||
</CardTitle>
|
||||
<CardTitle as="h2">Security scan summary</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<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) }}
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<SeveritySummary :counts="severityCounts" label="Vulnerabilities by severity" />
|
||||
<DescriptionList variant="inline" divided>
|
||||
<DescriptionItem term="Scanned">{{ formatDate(vulnerabilities.scanned_at) }}</DescriptionItem>
|
||||
<DescriptionItem term="Scanners">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<Badge v-for="scanner in scannerList" :key="scanner" variant="secondary">{{ scanner }}</Badge>
|
||||
</span>
|
||||
<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>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="bypassedCount > 0" term="Bypassed">
|
||||
<StatusBadge status="bypassed" :label="`${bypassedCount} bypassed`" :tones="{ bypassed: 'success' }" />
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 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>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
title="No vulnerabilities found"
|
||||
description="The scanners reported nothing for this package version."
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 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>
|
||||
<CardTitle as="h2">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
|
||||
<CardContent>
|
||||
<Table label="Detected vulnerabilities" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Severity</TableHead>
|
||||
<TableHead>CVE ID</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead>Fix version</TableHead>
|
||||
<TableHead align="center">Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<template v-for="(vuln, index) in vulnerabilityList" :key="vuln.id">
|
||||
<TableRow class="cursor-pointer" :selected="expandedRows.has(index)" @click="toggleRow(index)">
|
||||
<TableCell label="Severity">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge
|
||||
:status="vuln.severity"
|
||||
:tones="SEVERITY_TONES"
|
||||
:label="formatSeverityName(vuln.severity)"
|
||||
/>
|
||||
<StatusBadge
|
||||
v-if="vuln.bypassed"
|
||||
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>
|
||||
status="bypassed"
|
||||
label="Bypassed"
|
||||
:tones="{ bypassed: 'success' }"
|
||||
/>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="CVE ID" class="font-mono font-medium">{{ vuln.id }}</TableCell>
|
||||
<TableCell label="Description">
|
||||
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
|
||||
</TableCell>
|
||||
<TableCell label="Fix version">
|
||||
<span v-if="vuln.fixed_in">v{{ vuln.fixed_in }}</span>
|
||||
<span v-else class="text-muted-foreground">-</span>
|
||||
</TableCell>
|
||||
<TableCell label="Details" align="center">
|
||||
<IconButton
|
||||
size="icon-sm"
|
||||
:icon="expandedRows.has(index) ? faChevronUp : faChevronDown"
|
||||
:label="`${expandedRows.has(index) ? 'Hide' : 'Show'} details for ${vuln.id}`"
|
||||
:aria-expanded="expandedRows.has(index)"
|
||||
@click.stop="toggleRow(index)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
<!-- 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>
|
||||
<TableRow v-if="expandedRows.has(index)" :hoverable="false">
|
||||
<TableCell :colspan="5">
|
||||
<div class="flex flex-col gap-4 py-2">
|
||||
<section>
|
||||
<h3 class="mb-2 text-sm font-semibold">Description</h3>
|
||||
<Markdown :source="vuln.description" :heading-offset="3" />
|
||||
</section>
|
||||
|
||||
<!-- 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>
|
||||
<Alert v-if="vuln.bypassed && vuln.bypass" variant="success">
|
||||
<AlertTitle>Bypass active</AlertTitle>
|
||||
<AlertDescription>
|
||||
<DescriptionList variant="grid" :columns="3" size="sm">
|
||||
<DescriptionItem term="Reason">{{ vuln.bypass.reason }}</DescriptionItem>
|
||||
<DescriptionItem term="By">{{ vuln.bypass.created_by }}</DescriptionItem>
|
||||
<DescriptionItem term="Expires">{{ formatDate(vuln.bypass.expires_at) }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<!-- 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>
|
||||
<Alert v-if="vuln.fixed_in" variant="info">
|
||||
<AlertTitle>Fix available</AlertTitle>
|
||||
<AlertDescription>
|
||||
Upgrade to version <strong>{{ vuln.fixed_in }}</strong> or later.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<!-- 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>
|
||||
<section v-if="vuln.references && vuln.references.length > 0">
|
||||
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
|
||||
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li v-for="(ref, refIndex) in vuln.references" :key="refIndex" class="break-all">
|
||||
<Link :href="ref" external>{{ ref }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -252,32 +156,37 @@
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import axios from 'axios'
|
||||
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 {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
IconButton,
|
||||
Link,
|
||||
LoadingState,
|
||||
Markdown,
|
||||
PageHeader,
|
||||
StatusBadge,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
getSeverityBadgeClass,
|
||||
getRegistryBadgeClass,
|
||||
getVulnerabilityBorderClass,
|
||||
formatSeverityName,
|
||||
} from '@/composables/useBadgeStyles'
|
||||
|
||||
// Configure marked
|
||||
marked.setOptions({
|
||||
breaks: true,
|
||||
gfm: true,
|
||||
})
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faChevronDown, faChevronUp, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
@@ -292,6 +201,7 @@ const packageName = computed(() => {
|
||||
return nameParam as string
|
||||
})
|
||||
const version = computed(() => route.params.version as string)
|
||||
const shownVersion = computed(() => vulnerabilities.value?.package?.release_version || version.value)
|
||||
|
||||
interface BypassInfo {
|
||||
id: string
|
||||
@@ -312,6 +222,7 @@ interface Vulnerability {
|
||||
}
|
||||
|
||||
interface VulnerabilityResponse {
|
||||
package?: { release_version?: string }
|
||||
scanned: boolean
|
||||
scanner: string
|
||||
scanned_at: string
|
||||
@@ -332,27 +243,15 @@ const error = ref<string | null>(null)
|
||||
const vulnerabilities = ref<VulnerabilityResponse | null>(null)
|
||||
const expandedRows = ref<Set<number>>(new Set())
|
||||
|
||||
// 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 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
|
||||
return severityRank(b.severity) - severityRank(a.severity)
|
||||
})
|
||||
})
|
||||
|
||||
const severityCounts = computed(() => vulnerabilities.value?.severity_counts || { critical: 0, high: 0, moderate: 0, low: 0 })
|
||||
const severityCounts = computed(() => vulnerabilities.value?.severity_counts || NO_VULNERABILITIES)
|
||||
const bypassedCount = computed(() => vulnerabilities.value?.bypassed_count || 0)
|
||||
|
||||
// Parse scanner string into array of scanner names
|
||||
@@ -396,21 +295,4 @@ function toggleRow(index: number) {
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
|
||||
@@ -1,22 +1,64 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
|
||||
import { defineComponent, h } from 'vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
|
||||
type Row = ReturnType<typeof usePackageStore>['packagePage']['packages'][number]
|
||||
|
||||
// A page as the server sends it: whole groups, flattened to rows.
|
||||
function setRows(store: ReturnType<typeof usePackageStore>, packages: Row[]) {
|
||||
const groups = new Set(packages.map((p) => `${p.registry}:${p.name}`))
|
||||
store.packagePage = { packages, totalGroups: groups.size, page: 1, pageSize: 25 }
|
||||
}
|
||||
|
||||
const Stub = defineComponent({ render: () => h('div') })
|
||||
|
||||
function createTestRouter(): Router {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/', name: 'dashboard', component: Stub },
|
||||
{ path: '/packages/:registry?', name: 'packages', component: Stub, props: true },
|
||||
{
|
||||
path: '/package/:registry/:name+/:version',
|
||||
name: 'package-details',
|
||||
component: Stub,
|
||||
props: true,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
async function mountWithRouter() {
|
||||
const router = createTestRouter()
|
||||
router.push('/packages')
|
||||
await router.isReady()
|
||||
return mount(PackageList, {
|
||||
global: {
|
||||
plugins: [router],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('PackageList.vue', () => {
|
||||
beforeEach(() => {
|
||||
// Create a fresh pinia instance before each test
|
||||
setActivePinia(createPinia())
|
||||
// Prevent real network calls from store actions on mount
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchPackagePage').mockResolvedValue()
|
||||
})
|
||||
|
||||
it('renders package list component', () => {
|
||||
const wrapper = mount(PackageList)
|
||||
expect(wrapper.find('h2').text()).toBe('Packages')
|
||||
it('renders package list component', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
const wrapper = mount(PackageList)
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = true
|
||||
@@ -26,7 +68,7 @@ describe('PackageList.vue', () => {
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const wrapper = mount(PackageList)
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.error = 'Failed to fetch packages'
|
||||
@@ -36,22 +78,22 @@ describe('PackageList.vue', () => {
|
||||
})
|
||||
|
||||
it('displays empty state when no packages', async () => {
|
||||
const wrapper = mount(PackageList)
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = []
|
||||
setRows(store, [])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('No packages cached yet')
|
||||
})
|
||||
|
||||
it('displays package accordion when packages exist', async () => {
|
||||
const wrapper = mount(PackageList)
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -62,28 +104,30 @@ describe('PackageList.vue', () => {
|
||||
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('calls fetchPackages on mount', () => {
|
||||
it('asks the server for the first page on mount', async () => {
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = vi.spyOn(store, 'fetchPackages')
|
||||
// beforeEach already spied with mockResolvedValue; reuse that spy
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
|
||||
mount(PackageList)
|
||||
await mountWithRouter()
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('groups packages and displays version counts', async () => {
|
||||
const wrapper = mount(PackageList)
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -104,7 +148,7 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 20,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
@@ -112,11 +156,11 @@ describe('PackageList.vue', () => {
|
||||
})
|
||||
|
||||
it('formats bytes correctly', async () => {
|
||||
const wrapper = mount(PackageList)
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -127,18 +171,28 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 MB')
|
||||
})
|
||||
|
||||
it('applies correct registry badge classes', async () => {
|
||||
const wrapper = mount(PackageList)
|
||||
it('prints every registry as a badge with its name', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '3',
|
||||
registry: 'go',
|
||||
name: 'go-module',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 3,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -159,29 +213,113 @@ describe('PackageList.vue', () => {
|
||||
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()
|
||||
|
||||
// Verify that all registry badges are displayed
|
||||
// Packages are grouped and sorted alphabetically, so order is: go-module, npm-package, python-package
|
||||
// The server sends groups in name order: go-module, npm-package, python-package
|
||||
expect(wrapper.text()).toContain('npm')
|
||||
expect(wrapper.text()).toContain('pypi')
|
||||
expect(wrapper.text()).toContain('go')
|
||||
|
||||
// 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
|
||||
// Each registry is printed as text in an outline badge, never as colour alone.
|
||||
const badges = wrapper.findAll('[data-slot="badge"]').map((badge) => badge.text())
|
||||
expect(badges).toEqual(['go', 'npm', 'pypi'])
|
||||
})
|
||||
|
||||
it('shows the release version for a PyPI file row, not the file name', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'pypi',
|
||||
name: 'six',
|
||||
version: 'six-1.17.0-py2.py3-none-any.whl',
|
||||
release_version: '1.17.0',
|
||||
size: 1,
|
||||
cached_at: '2026-11-23T00:00:00Z',
|
||||
last_accessed: '2026-11-23T00:00:00Z',
|
||||
download_count: 0,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
describe('server-side paging, search and registry filter', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('debounces the search box into one request with q and page 1', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
|
||||
const input = wrapper.find('input[type="search"], input')
|
||||
await input.setValue('l')
|
||||
await input.setValue('le')
|
||||
await input.setValue('left')
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'all', q: 'left' })
|
||||
})
|
||||
|
||||
it('sends the registry of the route with every request', async () => {
|
||||
const router = createTestRouter()
|
||||
router.push('/packages/pypi')
|
||||
await router.isReady()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
mount(PackageList, { props: { registry: 'pypi' }, global: { plugins: [router] } })
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'pypi', q: '' })
|
||||
})
|
||||
|
||||
it('pages through the server, not the loaded rows', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.packagePage = {
|
||||
packages: [
|
||||
{ id: '1', registry: 'npm', name: 'a', version: '1', size: 1, cached_at: '2025-01-01T00:00:00Z', last_accessed: '2025-01-01T00:00:00Z', download_count: 0 },
|
||||
],
|
||||
totalGroups: 60,
|
||||
page: 1,
|
||||
pageSize: 25,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.text()).toContain('Page 1 of 3 (60 total packages)')
|
||||
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
|
||||
const next = wrapper.findAll('button').find((b) => /next/i.test(b.attributes('aria-label') ?? b.text()))
|
||||
await next!.trigger('click')
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 2, pageSize: 25, registry: 'all', q: '' })
|
||||
})
|
||||
|
||||
it('says no packages match when a filter empties the page', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
setRows(store, [])
|
||||
await wrapper.find('input').setValue('zzz')
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(wrapper.text()).toContain('No packages match')
|
||||
expect(wrapper.text()).not.toContain('No packages cached yet')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,240 +1,142 @@
|
||||
<template>
|
||||
<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 class="flex flex-col gap-6">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
|
||||
<SegmentedControl
|
||||
:model-value="selectedRegistry"
|
||||
:options="REGISTRY_OPTIONS"
|
||||
aria-label="Filter by registry"
|
||||
@update:model-value="changeRegistryFilter"
|
||||
/>
|
||||
<SearchInput v-model="searchTerm" aria-label="Search packages" placeholder="Search packages..." class="w-full sm:ms-auto sm:w-64" />
|
||||
</div>
|
||||
|
||||
<!-- 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"
|
||||
>
|
||||
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>
|
||||
<LoadingState v-if="loading" variant="table" label="Loading packages..." />
|
||||
|
||||
<!-- Error Alert -->
|
||||
<Alert v-if="error" variant="destructive" class="mb-4">
|
||||
<i class="fas fa-exclamation-circle mr-2"></i>
|
||||
<AlertDescription>{{ error }}</AlertDescription>
|
||||
</Alert>
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load packages"
|
||||
:message="error"
|
||||
@retry="load()"
|
||||
/>
|
||||
|
||||
<!-- 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>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="totalGroups === 0 && !filtersActive"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages will appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="groups.length === 0"
|
||||
:icon="faMagnifyingGlass"
|
||||
title="No packages match"
|
||||
description="Change the registry filter or the search text."
|
||||
/>
|
||||
<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">
|
||||
<AccordionItem
|
||||
v-for="group in groups"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
<AccordionTrigger :heading-level="2">
|
||||
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
|
||||
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||
<span class="w-full min-w-0 text-start sm:w-auto">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
</span>
|
||||
</span>
|
||||
<span class="flex shrink-0 items-center gap-4">
|
||||
<Badge variant="outline">{{ group.registry }}</Badge>
|
||||
<span class="text-end tabular-nums">
|
||||
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<Table :label="`Versions of ${group.name}`" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Version</TableHead>
|
||||
<TableHead align="right">Downloads</TableHead>
|
||||
<TableHead align="right">Size</TableHead>
|
||||
<TableHead>Cached</TableHead>
|
||||
<TableHead>Vulnerabilities</TableHead>
|
||||
<TableHead align="right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="version in group.versions" :key="version.id">
|
||||
<TableCell label="Version" class="font-medium">{{ withVersionPrefix(displayVersion(version)) }}</TableCell>
|
||||
<TableCell label="Downloads" numeric>{{ formatNumber(version.download_count) }}</TableCell>
|
||||
<TableCell label="Size" numeric>{{ formatBytes(version.size) }}</TableCell>
|
||||
<TableCell label="Cached">{{ formatDate(version.cached_at) }}</TableCell>
|
||||
<TableCell label="Vulnerabilities">
|
||||
<VulnerabilityBadge
|
||||
v-if="version.vulnerabilities"
|
||||
:scanned="version.vulnerabilities.scanned"
|
||||
:status="version.vulnerabilities.status"
|
||||
:counts="version.vulnerabilities.counts"
|
||||
:total="version.vulnerabilities.total"
|
||||
:scannedAt="version.vulnerabilities.scannedAt"
|
||||
:isBlocked="version.vulnerabilities.isBlocked"
|
||||
@click="showVulnerabilityDetails(group.registry, group.name, version.version)"
|
||||
/>
|
||||
</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>
|
||||
</TableCell>
|
||||
<TableCell label="Actions" align="right">
|
||||
<IconButton
|
||||
:icon="faTrash"
|
||||
:label="`Delete ${group.name} ${version.version}`"
|
||||
@click="confirmDelete(version)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<!-- 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 v-if="totalPages > 1" class="mt-6 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
Page {{ currentPage }} of {{ totalPages }} ({{ totalGroups }} total packages)
|
||||
</p>
|
||||
<Pagination
|
||||
:page="currentPage"
|
||||
:total="totalGroups"
|
||||
:page-size="PAGE_SIZE"
|
||||
:show-edges="false"
|
||||
@update:page="changePage"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 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="Delete package version?"
|
||||
:description="`Delete ${packageToDelete?.name}@${packageToDelete?.version}? This action cannot be undone.`"
|
||||
confirm-label="Delete version"
|
||||
tone="danger"
|
||||
destructive
|
||||
@confirm="deletePackage"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, computed, watch } from 'vue'
|
||||
import { onBeforeUnmount, onMounted, ref, computed, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
@@ -243,22 +145,30 @@ import {
|
||||
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'
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
ConfirmDialog,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
IconButton,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
Pagination,
|
||||
SearchInput,
|
||||
SegmentedControl,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
useToastStore,
|
||||
} from '@perfect-design/ui'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { getRegistryBadgeClass } from '@/composables/useBadgeStyles'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faBoxOpen, faMagnifyingGlass, faRotateRight, faTrash } from '@/lib/icons'
|
||||
|
||||
// Props from router
|
||||
const props = defineProps<{
|
||||
@@ -268,103 +178,89 @@ const props = defineProps<{
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = usePackageStore()
|
||||
const { packages, loading, error } = storeToRefs(store)
|
||||
const toasts = useToastStore()
|
||||
const { packagePage, loading, error } = storeToRefs(store)
|
||||
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
const REGISTRY_OPTIONS = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'npm', label: 'npm' },
|
||||
{ value: 'pypi', label: 'PyPI' },
|
||||
{ value: 'go', label: 'Go' },
|
||||
]
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
|
||||
const selectedRegistry = ref<string>(props.registry || 'all')
|
||||
const searchTerm = ref<string>('')
|
||||
// What the server was last asked: the search text lags the input by the debounce.
|
||||
const activeQuery = ref<string>('')
|
||||
const currentPage = ref<number>(1)
|
||||
const itemsPerPage = ref<number>(10)
|
||||
|
||||
// Group packages by name
|
||||
const allGroupedPackages = computed(() => {
|
||||
const groups = new Map<string, Package[]>()
|
||||
const totalGroups = computed(() => packagePage.value.totalGroups)
|
||||
const totalPages = computed(() => Math.ceil(totalGroups.value / PAGE_SIZE))
|
||||
const filtersActive = computed(() => selectedRegistry.value !== 'all' || activeQuery.value.trim() !== '')
|
||||
|
||||
// Filter packages by selected registry and search term
|
||||
let filteredPackages = selectedRegistry.value === 'all'
|
||||
? packages.value
|
||||
: packages.value.filter(pkg => pkg.registry === selectedRegistry.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 server pages whole (registry, name) groups and sends every version row of each.
|
||||
const groups = computed(() => {
|
||||
const byKey = new Map<string, { registry: string; name: string; versions: Package[] }>()
|
||||
for (const pkg of packagePage.value.packages) {
|
||||
const key = `${pkg.registry}\u0000${pkg.name}`
|
||||
let group = byKey.get(key)
|
||||
if (!group) {
|
||||
group = { registry: pkg.registry, name: pkg.name, versions: [] }
|
||||
byKey.set(key, group)
|
||||
}
|
||||
group.versions.push(pkg)
|
||||
}
|
||||
return Array.from(byKey.values()).map((group) => ({
|
||||
...group,
|
||||
totalSize: group.versions.reduce((sum, v) => sum + v.size, 0),
|
||||
totalDownloads: group.versions.reduce((sum, v) => sum + v.download_count, 0),
|
||||
}))
|
||||
})
|
||||
|
||||
filteredPackages.forEach(pkg => {
|
||||
const key = `${pkg.registry}:${pkg.name}`
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, [])
|
||||
}
|
||||
groups.get(key)!.push(pkg)
|
||||
async function load() {
|
||||
await store.fetchPackagePage({
|
||||
page: currentPage.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
registry: selectedRegistry.value,
|
||||
q: activeQuery.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))
|
||||
})
|
||||
|
||||
// Pagination
|
||||
const totalPages = computed(() => Math.ceil(allGroupedPackages.value.length / itemsPerPage.value))
|
||||
|
||||
const groupedPackages = computed(() => {
|
||||
const start = (currentPage.value - 1) * itemsPerPage.value
|
||||
const end = start + itemsPerPage.value
|
||||
return allGroupedPackages.value.slice(start, end)
|
||||
})
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
if (page >= 1 && page <= totalPages.value) {
|
||||
currentPage.value = page
|
||||
void load()
|
||||
// Scroll to top of packages list
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
// A burst of keystrokes asks the server once.
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(searchTerm, (term) => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => {
|
||||
if (term === activeQuery.value) return
|
||||
activeQuery.value = term
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
}, SEARCH_DEBOUNCE_MS)
|
||||
})
|
||||
onBeforeUnmount(() => clearTimeout(searchTimer))
|
||||
|
||||
// Watch for route parameter changes to update filter
|
||||
watch(() => route.params.registry, (newRegistry) => {
|
||||
selectedRegistry.value = (newRegistry as string) || 'all'
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await store.fetchPackages()
|
||||
})
|
||||
onMounted(load)
|
||||
|
||||
function confirmDelete(pkg: Package) {
|
||||
packageToDelete.value = pkg
|
||||
@@ -372,33 +268,27 @@ function confirmDelete(pkg: Package) {
|
||||
}
|
||||
|
||||
async function deletePackage() {
|
||||
if (packageToDelete.value) {
|
||||
await store.deletePackage(
|
||||
packageToDelete.value.registry,
|
||||
packageToDelete.value.name,
|
||||
packageToDelete.value.version
|
||||
)
|
||||
showDeleteModal.value = false
|
||||
packageToDelete.value = null
|
||||
const target = packageToDelete.value
|
||||
if (!target) return
|
||||
await store.deletePackage(target.registry, target.name, target.version)
|
||||
showDeleteModal.value = false
|
||||
packageToDelete.value = null
|
||||
const label = `${target.name}@${target.version}`
|
||||
if (store.error) {
|
||||
toasts.error('Could not delete package', `${label}: ${store.error}`)
|
||||
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
|
||||
store.error = null
|
||||
} else {
|
||||
toasts.success('Package deleted', label)
|
||||
await load()
|
||||
// Deleting the last group of the last page leaves that page empty.
|
||||
if (packagePage.value.packages.length === 0 && totalGroups.value > 0 && currentPage.value > 1) {
|
||||
currentPage.value = Math.max(totalPages.value, 1)
|
||||
await load()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function 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({
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<template>
|
||||
<StatGroup :columns="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="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 { 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 `${n} package${n === 1 ? '' : 's'}`
|
||||
}
|
||||
</script>
|
||||
@@ -1,17 +1,22 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Stats from './Stats.vue'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
|
||||
describe('Stats.vue', () => {
|
||||
beforeEach(() => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Stats) => mountWith(component, { global: { plugins: [router] } })
|
||||
|
||||
beforeEach(async () => {
|
||||
setActivePinia(createPinia())
|
||||
router = await createTestRouter('/stats')
|
||||
})
|
||||
|
||||
it('renders stats component', () => {
|
||||
const wrapper = mount(Stats)
|
||||
expect(wrapper.find('h2').text()).toBe('Statistics')
|
||||
expect(wrapper.find('h1').text()).toBe('Statistics')
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
@@ -25,9 +30,11 @@ describe('Stats.vue', () => {
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
const wrapper = mount(Stats)
|
||||
|
||||
store.loading = false
|
||||
store.error = 'Failed to fetch statistics'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
@@ -43,13 +50,15 @@ describe('Stats.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824, // 1 GB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Overall Statistics')
|
||||
expect(wrapper.text()).toContain('Overall statistics')
|
||||
expect(wrapper.text()).toContain('100')
|
||||
expect(wrapper.text()).toContain('500')
|
||||
})
|
||||
@@ -63,15 +72,17 @@ describe('Stats.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Security Scanning')
|
||||
expect(wrapper.text()).toContain('Scanned Packages')
|
||||
expect(wrapper.text()).toContain('Vulnerable Packages')
|
||||
expect(wrapper.text()).toContain('Security scanning')
|
||||
expect(wrapper.text()).toContain('Scanned packages')
|
||||
expect(wrapper.text()).toContain('Vulnerable packages')
|
||||
})
|
||||
|
||||
it('displays registry breakdown', async () => {
|
||||
@@ -83,9 +94,11 @@ describe('Stats.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {
|
||||
npm: {
|
||||
@@ -106,13 +119,15 @@ describe('Stats.vue', () => {
|
||||
}
|
||||
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')
|
||||
expect(wrapper.text()).toContain('Registry breakdown')
|
||||
expect(wrapper.text()).toContain('npm')
|
||||
expect(wrapper.text()).toContain('PyPI')
|
||||
expect(wrapper.text()).toContain('Go modules')
|
||||
// The cards layout prefixes each cell with its column label.
|
||||
const packageCounts = wrapper
|
||||
.findAll('tbody tr')
|
||||
.map((row) => row.findAll('td')[0].text().replace(/^Packages/, ''))
|
||||
expect(packageCounts).toEqual(['50', '30', '20'])
|
||||
})
|
||||
|
||||
it('formats bytes correctly in overall stats', async () => {
|
||||
@@ -124,9 +139,11 @@ describe('Stats.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824, // 1 GB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
@@ -142,7 +159,7 @@ describe('Stats.vue', () => {
|
||||
expect(fetchSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('displays correct icon colors for different registries', async () => {
|
||||
it('lists the registries in the order the API reports them', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
@@ -151,9 +168,11 @@ describe('Stats.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 3,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {
|
||||
npm: { count: 1, size: 0, downloads: 0 },
|
||||
@@ -162,10 +181,8 @@ describe('Stats.vue', () => {
|
||||
}
|
||||
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
|
||||
const labels = wrapper.findAll('tbody th').map((cell) => cell.text().replace(/^Registry/, ''))
|
||||
expect(labels).toEqual(['npm', 'PyPI', 'Go modules'])
|
||||
})
|
||||
|
||||
it('handles empty registries data', async () => {
|
||||
@@ -177,16 +194,59 @@ describe('Stats.vue', () => {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Registry Breakdown')
|
||||
// Should have no registry items
|
||||
const registryItems = wrapper.findAll('.bg-gray-50')
|
||||
expect(registryItems.length).toBe(3) // Only the overall stats cards
|
||||
expect(wrapper.text()).toContain('Registry breakdown')
|
||||
expect(wrapper.findAll('tbody th')).toHaveLength(0)
|
||||
expect(wrapper.text()).toContain('No registries reported')
|
||||
})
|
||||
|
||||
describe('idle eviction note', () => {
|
||||
const baseStats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
|
||||
async function render(idleTtl?: number) {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
|
||||
await wrapper.vm.$nextTick()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
it.each([
|
||||
[604800, 'Cached items not requested for 7 days are removed.'],
|
||||
[86400, 'Cached items not requested for 1 day are removed.'],
|
||||
[129600, 'Cached items not requested for 36 hours are removed.'],
|
||||
[5400, 'Cached items not requested for 90 minutes are removed.'],
|
||||
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
|
||||
const wrapper = await render(seconds)
|
||||
expect(wrapper.text()).toContain(sentence)
|
||||
})
|
||||
|
||||
it('hides the note when idle eviction is off', async () => {
|
||||
const wrapper = await render(0)
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
|
||||
it('hides the note when the API sends no idle_ttl', async () => {
|
||||
const wrapper = await render()
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+148
-151
@@ -1,119 +1,93 @@
|
||||
<template>
|
||||
<div>
|
||||
<h2 class="text-3xl font-bold text-gray-900 mb-8">Statistics</h2>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Statistics" description="Storage, traffic and scan results across every registry." />
|
||||
|
||||
<!-- Error Alert -->
|
||||
<Alert v-if="error" variant="destructive" class="mb-4">
|
||||
<i class="fas fa-exclamation-circle mr-2"></i>
|
||||
<AlertDescription>{{ error }}</AlertDescription>
|
||||
</Alert>
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
|
||||
<!-- 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>
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<!-- 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>
|
||||
<template v-else>
|
||||
<Alert v-if="idleTtl > 0" variant="info">
|
||||
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<!-- 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>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Overall statistics</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StatGroup :columns="3" aria-label="Overall statistics">
|
||||
<KpiTile label="Total packages" :value="stats?.total_packages || 0" :icon="faBoxesStacked" />
|
||||
<KpiTile
|
||||
label="Storage used"
|
||||
:value="`${formatBytes(stats?.total_size || 0)} / ${formatBytes(stats?.max_cache_size || 0)}`"
|
||||
:hint="`${storagePercentage.toFixed(1)}% used`"
|
||||
:progress="storagePercentage"
|
||||
:tone="storageTone"
|
||||
:icon="faHardDrive"
|
||||
/>
|
||||
<KpiTile label="Total downloads" :value="stats?.total_downloads || 0" :icon="faDownload" />
|
||||
</StatGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Security scanning</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StatGroup :columns="3" aria-label="Security scanning">
|
||||
<KpiTile label="Scanned packages" :value="stats?.scanned_packages || 0" :icon="faCircleCheck" />
|
||||
<KpiTile
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
label="Vulnerable packages"
|
||||
:value="stats?.vulnerable_packages || 0"
|
||||
:hint="(stats?.vulnerable_packages || 0) > 0 ? 'View the list' : undefined"
|
||||
:icon="faTriangleExclamation"
|
||||
:disabled="(stats?.vulnerable_packages || 0) === 0"
|
||||
@click="showVulnerablePackages"
|
||||
/>
|
||||
<KpiTile
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
label="Blocked packages"
|
||||
:value="stats?.blocked_packages || 0"
|
||||
:hint="(stats?.blocked_packages || 0) > 0 ? 'View the list' : undefined"
|
||||
:icon="faBan"
|
||||
:disabled="(stats?.blocked_packages || 0) === 0"
|
||||
@click="showBlockedPackages"
|
||||
/>
|
||||
</StatGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Registry breakdown</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
label="Registry breakdown"
|
||||
layout="cards"
|
||||
row-key="name"
|
||||
empty-text="No registries reported"
|
||||
:columns="registryColumns"
|
||||
:rows="registries"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -122,8 +96,24 @@ 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'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, loading, error } = storeToRefs(store)
|
||||
@@ -141,54 +131,61 @@ function showVulnerablePackages() {
|
||||
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'
|
||||
function showBlockedPackages() {
|
||||
if ((stats.value?.blocked_packages || 0) === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/blocked-packages')
|
||||
}
|
||||
|
||||
const REGISTRY_LABELS: Record<string, string> = {
|
||||
npm: 'npm',
|
||||
pypi: 'PyPI',
|
||||
go: 'Go modules',
|
||||
}
|
||||
|
||||
interface RegistryRow {
|
||||
name: string
|
||||
label: string
|
||||
packages: number
|
||||
size: string
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const registryColumns: DataTableColumn<RegistryRow>[] = [
|
||||
{ key: 'label', header: 'Registry', rowHeader: true },
|
||||
{ key: 'packages', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.packages) },
|
||||
{ key: 'size', header: 'Size', numeric: true },
|
||||
{ key: 'downloads', header: 'Downloads', numeric: true, accessor: (r) => formatNumber(r.downloads) },
|
||||
]
|
||||
|
||||
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
|
||||
}
|
||||
})
|
||||
return Object.entries(apiRegistries).map(([name, data]: [string, any]): RegistryRow => ({
|
||||
name,
|
||||
label: REGISTRY_LABELS[name] ?? name.toUpperCase(),
|
||||
packages: data.count || 0,
|
||||
size: formatBytes(data.size || 0),
|
||||
downloads: data.downloads || 0,
|
||||
}))
|
||||
})
|
||||
|
||||
function formatNumber(num: number): string {
|
||||
return new Intl.NumberFormat().format(num)
|
||||
}
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
|
||||
|
||||
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]
|
||||
const storagePercentage = computed(() => {
|
||||
const totalSize = stats.value?.total_size || 0
|
||||
const maxSize = stats.value?.max_cache_size || 1
|
||||
return (totalSize / maxSize) * 100
|
||||
})
|
||||
|
||||
const storageTone = computed(() => {
|
||||
if (storagePercentage.value >= 90) return 'danger'
|
||||
if (storagePercentage.value >= 50) return 'warning'
|
||||
return 'success'
|
||||
})
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
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('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])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
<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>
|
||||
<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"
|
||||
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>
|
||||
<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 { 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],
|
||||
})),
|
||||
])
|
||||
|
||||
// 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 `${n} vulnerable package${n === 1 ? '' : 's'} on ${formatTrendDate(last!.date, true)}.`
|
||||
})
|
||||
</script>
|
||||
@@ -1,87 +1,58 @@
|
||||
<template>
|
||||
<div class="flex items-center gap-2">
|
||||
<!-- Critical Vulnerabilities -->
|
||||
<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"
|
||||
/>
|
||||
|
||||
<button
|
||||
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`"
|
||||
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)"
|
||||
>
|
||||
<i class="fas fa-shield-virus mr-1"></i>
|
||||
CRITICAL: {{ counts.critical }}
|
||||
<StatusBadge :status="level" :tones="SEVERITY_TONES" :label="`${formatSeverityName(level)}: ${counts[level]}`" />
|
||||
</button>
|
||||
|
||||
<!-- 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>
|
||||
<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>
|
||||
|
||||
<!-- 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
|
||||
<StatusBadge
|
||||
v-if="status === 'pending'"
|
||||
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"
|
||||
status="pending"
|
||||
label="Scanning"
|
||||
pulse
|
||||
title="Security scan in progress"
|
||||
>
|
||||
<i class="fas fa-spinner fa-spin mr-1"></i>
|
||||
SCANNING...
|
||||
</span>
|
||||
/>
|
||||
|
||||
<!-- Not Scanned Badge -->
|
||||
<span
|
||||
<StatusBadge
|
||||
v-if="status === 'not_scanned' || !scanned"
|
||||
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"
|
||||
status="not_scanned"
|
||||
label="Not scanned"
|
||||
:tones="{ not_scanned: 'neutral' }"
|
||||
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
|
||||
@@ -89,41 +60,24 @@ 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 || { critical: 0, high: 0, moderate: 0, low: 0 })
|
||||
const counts = computed(() => props.counts || NO_VULNERABILITIES)
|
||||
const presentLevels = computed(() => SEVERITY_LEVELS.filter((level) => counts.value[level] > 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,226 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
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 ALL_SEVERITIES = 'critical,high,moderate,low'
|
||||
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
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/vulnerable-packages') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { 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('VulnerablePackages 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 vulnerable packages only', async () => {
|
||||
await open()
|
||||
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
|
||||
})
|
||||
|
||||
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('/vulnerable-packages?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('/vulnerable-packages?severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
|
||||
|
||||
const 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 is vulnerable, filter or not', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('still narrows to blocked packages on the blocked route', async () => {
|
||||
const blocked = vulnerable('echo-blocked', { critical: 1 })
|
||||
blocked.vulnerabilities!.isBlocked = true
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
})
|
||||
@@ -1,180 +1,197 @@
|
||||
<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>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
:title="showOnlyBlocked ? 'Blocked packages' : 'Vulnerable packages'"
|
||||
:description="
|
||||
showOnlyBlocked
|
||||
? 'Packages blocked from download because they exceed the vulnerability thresholds.'
|
||||
: 'Packages with known security vulnerabilities, sorted by risk.'
|
||||
"
|
||||
>
|
||||
<template #back>
|
||||
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to stats</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<!-- 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>
|
||||
<LoadingState v-if="loading" variant="card" label="Loading vulnerable packages..." />
|
||||
|
||||
<!-- 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>
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load vulnerable packages"
|
||||
:message="error"
|
||||
@retry="fetchVulnerablePackages"
|
||||
/>
|
||||
|
||||
<!-- 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>
|
||||
<Card v-else-if="vulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
:title="showOnlyBlocked ? 'No blocked packages' : 'No vulnerable packages'"
|
||||
description="Every cached package is clean."
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 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>
|
||||
<template v-else>
|
||||
<SeveritySummary
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
:counts="totalCounts"
|
||||
:package-counts="packageCounts"
|
||||
label="Vulnerabilities by severity. Select a severity to filter the packages."
|
||||
/>
|
||||
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Card v-if="sortedVulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
:icon="faCircleCheck"
|
||||
title="No packages match the filter"
|
||||
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button variant="outline" @click="clearFilters">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 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>
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">
|
||||
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{{ groupedPackages.length }} unique package{{ groupedPackages.length !== 1 ? 's' : '' }}, most critical first
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Accordion type="multiple" class="w-full">
|
||||
<AccordionItem
|
||||
v-for="group in groupedPackages"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
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 :heading-level="3">
|
||||
<span class="flex w-full min-w-0 items-center justify-between gap-4">
|
||||
<span class="min-w-0 text-start">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} vulnerable version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
</span>
|
||||
</span>
|
||||
<span class="flex shrink-0 items-center gap-4">
|
||||
<Badge variant="outline">{{ group.registry }}</Badge>
|
||||
<span class="whitespace-nowrap text-end tabular-nums">
|
||||
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent 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>
|
||||
<DataTable
|
||||
:label="`Vulnerable versions of ${group.name}`"
|
||||
layout="cards"
|
||||
row-clickable
|
||||
:columns="versionColumns"
|
||||
:rows="group.versions"
|
||||
@row-click="navigateToPackage"
|
||||
>
|
||||
<template #cell-vulnerabilities="{ row }">
|
||||
<VulnerabilityBadge
|
||||
v-if="row.vulnerabilities"
|
||||
:scanned="row.vulnerabilities.scanned"
|
||||
:status="row.vulnerabilities.status"
|
||||
:counts="row.vulnerabilities.counts"
|
||||
:total="row.vulnerabilities.total"
|
||||
:scannedAt="row.vulnerabilities.scannedAt"
|
||||
:isBlocked="row.vulnerabilities.isBlocked"
|
||||
@click="navigateToPackage(row)"
|
||||
/>
|
||||
</template>
|
||||
</DataTable>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
</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 { useRouter, useRoute } from 'vue-router'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from '@/components/ui/accordion'
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { getRegistryBadgeClass } from '@/composables/useBadgeStyles'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const store = usePackageStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
/** 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 hasFilter = computed(() => selectedSeverities.value.length > 0)
|
||||
const filterSummary = computed(() =>
|
||||
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
|
||||
)
|
||||
|
||||
function clearFilters() {
|
||||
selectedSeverities.value = []
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerablePackages = ref<Package[]>([])
|
||||
|
||||
// Check if we should filter to show only blocked packages
|
||||
const showOnlyBlocked = computed(() => route.path === '/blocked-packages')
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchVulnerablePackages()
|
||||
})
|
||||
@@ -184,10 +201,20 @@ async function fetchVulnerablePackages() {
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
await store.fetchPackages()
|
||||
vulnerablePackages.value = store.packages.filter(
|
||||
pkg => pkg.vulnerabilities?.status === 'vulnerable'
|
||||
)
|
||||
// The server drops clean packages; the toggles below narrow the rest without another request.
|
||||
await store.fetchPackages({ severity: SEVERITY_LEVELS })
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
return
|
||||
}
|
||||
vulnerablePackages.value = store.packages.filter(pkg => {
|
||||
const isVulnerable = pkg.vulnerabilities?.status === 'vulnerable'
|
||||
if (showOnlyBlocked.value) {
|
||||
return isVulnerable && pkg.vulnerabilities?.isBlocked === true
|
||||
}
|
||||
return isVulnerable
|
||||
})
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load vulnerable packages:', err)
|
||||
error.value = err.message || 'Failed to load vulnerable packages'
|
||||
@@ -196,9 +223,17 @@ async function fetchVulnerablePackages() {
|
||||
}
|
||||
}
|
||||
|
||||
// A package passes when it has at least one vulnerability of any selected severity.
|
||||
const filteredPackages = computed(() => {
|
||||
if (!hasFilter.value) return vulnerablePackages.value
|
||||
return vulnerablePackages.value.filter((pkg) =>
|
||||
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
|
||||
)
|
||||
})
|
||||
|
||||
// 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) => {
|
||||
return [...filteredPackages.value].sort((a, b) => {
|
||||
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
@@ -252,22 +287,40 @@ const groupedPackages = computed(() => {
|
||||
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)
|
||||
// Packages holding at least one vulnerability of each severity, before any filter.
|
||||
const packageCounts = computed<VulnerabilityCounts>(() => {
|
||||
const counts = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of vulnerablePackages.value) {
|
||||
for (const level of SEVERITY_LEVELS) {
|
||||
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages, before any filter
|
||||
const totalCounts = computed(() =>
|
||||
vulnerablePackages.value.reduce(
|
||||
(sum, pkg) => {
|
||||
const counts = pkg.vulnerabilities?.counts ?? NO_VULNERABILITIES
|
||||
return {
|
||||
critical: sum.critical + counts.critical,
|
||||
high: sum.high + counts.high,
|
||||
moderate: sum.moderate + counts.moderate,
|
||||
low: sum.low + counts.low,
|
||||
}
|
||||
},
|
||||
{ ...NO_VULNERABILITIES },
|
||||
),
|
||||
)
|
||||
|
||||
const 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)
|
||||
)
|
||||
const versionColumns: DataTableColumn<Package>[] = [
|
||||
{ key: 'version', header: 'Version', rowHeader: true, accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
|
||||
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
|
||||
{ key: 'cached_at', header: 'Cached', accessor: (pkg) => formatDate(pkg.cached_at) },
|
||||
{ key: 'vulnerabilities', header: 'Vulnerabilities', accessor: () => '' },
|
||||
]
|
||||
|
||||
function navigateToPackage(pkg: Package) {
|
||||
router.push(`/package/${pkg.registry}/${pkg.name}/${pkg.version}`)
|
||||
@@ -276,32 +329,4 @@ function navigateToPackage(pkg: Package) {
|
||||
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>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<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,
|
||||
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: 'Dashboard', to: '/', icon: faChartPie },
|
||||
{ label: 'Packages', to: '/packages', icon: faBoxesStacked },
|
||||
{ label: 'Vulnerable', to: '/vulnerable-packages', icon: faTriangleExclamation },
|
||||
{ label: 'Bypasses', to: '/admin/bypasses', icon: faShieldHalved },
|
||||
{ label: 'Stats', to: '/stats', icon: faChartColumn },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const SECTION_PREFIXES: ReadonlyArray<readonly [string, string]> = [
|
||||
['/packages', '/packages'],
|
||||
['/package/', '/packages'],
|
||||
['/vulnerable-packages', '/vulnerable-packages'],
|
||||
['/blocked-packages', '/vulnerable-packages'],
|
||||
['/admin/bypasses', '/admin/bypasses'],
|
||||
['/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>
|
||||
@@ -1,18 +0,0 @@
|
||||
<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>
|
||||
@@ -1,22 +0,0 @@
|
||||
<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>
|
||||
@@ -1,22 +0,0 @@
|
||||
<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>
|
||||
@@ -1,36 +0,0 @@
|
||||
<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>
|
||||
@@ -1,4 +0,0 @@
|
||||
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"
|
||||
@@ -1,17 +0,0 @@
|
||||
<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>
|
||||
@@ -1,14 +0,0 @@
|
||||
<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>
|
||||
@@ -1,14 +0,0 @@
|
||||
<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>
|
||||
@@ -1,24 +0,0 @@
|
||||
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>
|
||||
@@ -1,17 +0,0 @@
|
||||
<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>
|
||||
@@ -1,26 +0,0 @@
|
||||
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>
|
||||
@@ -1,28 +0,0 @@
|
||||
<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>
|
||||
@@ -1,38 +0,0 @@
|
||||
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>
|
||||
@@ -1,21 +0,0 @@
|
||||
<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>
|
||||
@@ -1,14 +0,0 @@
|
||||
<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>
|
||||
@@ -1,14 +0,0 @@
|
||||
<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>
|
||||
@@ -1,14 +0,0 @@
|
||||
<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>
|
||||
@@ -1,14 +0,0 @@
|
||||
<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>
|
||||
@@ -1,18 +0,0 @@
|
||||
<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>
|
||||
@@ -1,6 +0,0 @@
|
||||
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"
|
||||
@@ -1,15 +0,0 @@
|
||||
<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>
|
||||
@@ -1,12 +0,0 @@
|
||||
<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>
|
||||
@@ -1,46 +0,0 @@
|
||||
<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>
|
||||
@@ -1,22 +0,0 @@
|
||||
<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>
|
||||
@@ -1,19 +0,0 @@
|
||||
<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>
|
||||
@@ -1,16 +0,0 @@
|
||||
<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>
|
||||
@@ -1,55 +0,0 @@
|
||||
<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>
|
||||
@@ -1,27 +0,0 @@
|
||||
<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>
|
||||
@@ -1,12 +0,0 @@
|
||||
<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>
|
||||
@@ -1,9 +0,0 @@
|
||||
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"
|
||||
@@ -1,24 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { useVModel } from "@vueuse/core"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<{
|
||||
defaultValue?: string | number
|
||||
modelValue?: string | number
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
|
||||
const emits = defineEmits<{
|
||||
(e: "update:modelValue", payload: string | number): void
|
||||
}>()
|
||||
|
||||
const modelValue = useVModel(props, "modelValue", emits, {
|
||||
passive: true,
|
||||
defaultValue: props.defaultValue,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input v-model="modelValue" :class="cn('flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50', props.class)">
|
||||
</template>
|
||||
@@ -1 +0,0 @@
|
||||
export { default as Input } from "./Input.vue"
|
||||
@@ -1,29 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { SeparatorProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { Separator } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = withDefaults(defineProps<
|
||||
SeparatorProps & { class?: HTMLAttributes["class"] }
|
||||
>(), {
|
||||
orientation: "horizontal",
|
||||
decorative: true,
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class")
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Separator
|
||||
v-bind="delegatedProps"
|
||||
:class="
|
||||
cn(
|
||||
'shrink-0 bg-border',
|
||||
props.orientation === 'horizontal' ? 'h-px w-full' : 'w-px h-full',
|
||||
props.class,
|
||||
)
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
@@ -1 +0,0 @@
|
||||
export { default as Separator } from "./Separator.vue"
|
||||
@@ -1,14 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface SkeletonProps {
|
||||
class?: HTMLAttributes["class"]
|
||||
}
|
||||
|
||||
const props = defineProps<SkeletonProps>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="cn('animate-pulse rounded-md bg-primary/10', props.class)" />
|
||||
</template>
|
||||
@@ -1 +0,0 @@
|
||||
export { default as Skeleton } from "./Skeleton.vue"
|
||||
@@ -1,15 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative w-full overflow-auto">
|
||||
<table :class="cn('w-full caption-bottom text-sm', props.class)">
|
||||
<slot />
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,13 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<tbody :class="cn('[&_tr:last-child]:border-0', props.class)">
|
||||
<slot />
|
||||
</tbody>
|
||||
</template>
|
||||
@@ -1,13 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<td :class="cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', props.class)">
|
||||
<slot />
|
||||
</td>
|
||||
</template>
|
||||
@@ -1,13 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<th :class="cn('h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0', props.class)">
|
||||
<slot />
|
||||
</th>
|
||||
</template>
|
||||
@@ -1,13 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<thead :class="cn('[&_tr]:border-b', props.class)">
|
||||
<slot />
|
||||
</thead>
|
||||
</template>
|
||||
@@ -1,13 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<tr :class="cn('border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted', props.class)">
|
||||
<slot />
|
||||
</tr>
|
||||
</template>
|
||||
@@ -1,6 +0,0 @@
|
||||
export { default as Table } from './Table.vue'
|
||||
export { default as TableHeader } from './TableHeader.vue'
|
||||
export { default as TableBody } from './TableBody.vue'
|
||||
export { default as TableRow } from './TableRow.vue'
|
||||
export { default as TableHead } from './TableHead.vue'
|
||||
export { default as TableCell } from './TableCell.vue'
|
||||
@@ -0,0 +1,107 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import App from '@/App.vue'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Stats from './Stats.vue'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
const FAILURE = Object.assign(new Error('Request failed with status code 502'), {
|
||||
response: { status: 502, data: {} },
|
||||
})
|
||||
|
||||
// What each view must not say when the request failed: an empty state would tell the operator there is nothing to see.
|
||||
const EMPTY_TEXT: Record<string, string> = {
|
||||
Dashboard: 'No packages cached yet',
|
||||
PackageList: 'No packages cached yet',
|
||||
VulnerablePackages: 'No vulnerable packages',
|
||||
Stats: 'No registries reported',
|
||||
BypassManagementPanel: 'No bypasses found',
|
||||
}
|
||||
|
||||
const CASES: Array<[string, Parameters<typeof mountStrict>[0], string]> = [
|
||||
['Dashboard', Dashboard, '/'],
|
||||
['PackageList', PackageList, '/packages'],
|
||||
['PackageDetails', PackageDetails, '/package/npm/left-pad/1.3.0'],
|
||||
['VulnerablePackages', VulnerablePackages, '/vulnerable-packages'],
|
||||
['BypassManagementPanel', BypassManagementPanel, '/admin/bypasses'],
|
||||
['Stats', Stats, '/stats'],
|
||||
]
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
vi.mocked(axios.get).mockRejectedValue(FAILURE)
|
||||
localStorage.setItem('admin_api_key', 'test-key')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('an API failure renders ErrorState, never an empty state', () => {
|
||||
it.each(CASES)('%s', async (name, component, path) => {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(component, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
|
||||
const state = mounted.wrapper.find('[data-slot="error-state"]')
|
||||
expect(state.exists()).toBe(true)
|
||||
expect(state.text()).toContain('502')
|
||||
expect(state.find('button').text()).toMatch(/try again/i)
|
||||
expect(mounted.wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
|
||||
if (EMPTY_TEXT[name]) expect(mounted.wrapper.text()).not.toContain(EMPTY_TEXT[name])
|
||||
})
|
||||
|
||||
it('retry fetches again and clears the error when the backend is back', async () => {
|
||||
const router = await createTestRouter('/vulnerable-packages')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
await mounted.wrapper.find('[data-slot="error-state"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(mounted.wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(mounted.wrapper.text()).toContain('No vulnerable packages')
|
||||
})
|
||||
})
|
||||
|
||||
describe('unknown routes', () => {
|
||||
it('render NotFound with a link to the dashboard', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: {} })
|
||||
const router = await createTestRouter('/vulnerable')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(App, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
|
||||
expect(mounted.problems).toEqual([])
|
||||
const main = mounted.wrapper.find('main')
|
||||
expect(main.find('h1').text()).toBe('Page not found')
|
||||
expect(main.find('[data-slot="empty-state"]').text()).toContain('/vulnerable')
|
||||
const link = main.find('a[href="/"]')
|
||||
expect(link.text()).toMatch(/dashboard/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,306 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import App from '@/App.vue'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Stats from './Stats.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { usePackageStore } from '@/stores/packages'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
const API_KEY_STORAGE = 'admin_api_key'
|
||||
|
||||
function respond(url: string) {
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND }
|
||||
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
|
||||
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
|
||||
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
|
||||
if (url.startsWith('/api/packages')) return { data: { packages: PACKAGES } }
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
}
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
|
||||
localStorage.setItem(API_KEY_STORAGE, 'test-key')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function smoke(component: Parameters<typeof mountStrict>[0], path: string, props: Record<string, unknown> = {}) {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(component, { props, global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
return mounted
|
||||
}
|
||||
|
||||
describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
it('Dashboard renders the tiles, chart, feed and recent packages', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'left-pad', version: '1.3.0', registry: 'npm' }, timestamp: Date.now() }]
|
||||
const { wrapper, problems, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Dashboard')
|
||||
expect(wrapper.text()).toContain('Total packages')
|
||||
expect(wrapper.find('[data-testid="ws-event-feed"]').text()).toContain('left-pad')
|
||||
expect(wrapper.find('[role="img"]').exists()).toBe(true)
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
expect(wrapper.text()).toContain('github.com/example/module')
|
||||
})
|
||||
|
||||
it('PackageList groups fixture packages and shows severity words', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).toContain('2 versions')
|
||||
expect(wrapper.text()).toContain('requests')
|
||||
|
||||
const trigger = wrapper.findAll('button').find((b) => b.text().includes('left-pad'))
|
||||
await trigger!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('Critical: 1')
|
||||
expect(wrapper.text()).toContain('Blocked')
|
||||
})
|
||||
|
||||
it('PackageDetails renders the report, severity table and expanded row', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('left-pad')
|
||||
expect(wrapper.text()).toContain('Security scan summary')
|
||||
expect(wrapper.text()).toContain('trivy')
|
||||
|
||||
// Most severe first: CRITICAL, HIGH, then LOW.
|
||||
const ids = wrapper.findAll('tbody td.font-mono').map((td) => td.text().replace('CVE ID', ''))
|
||||
expect(ids.slice(0, 3)).toEqual(['CVE-2026-0002', 'CVE-2026-0003', 'CVE-2026-0001'])
|
||||
|
||||
await wrapper.find('button[aria-label^="Show details for CVE-2026-0002"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('Bypass active')
|
||||
expect(wrapper.text()).toContain('No fix available')
|
||||
})
|
||||
|
||||
it('VulnerablePackages lists the vulnerable fixture packages', async () => {
|
||||
const { wrapper, problems } = await smoke(VulnerablePackages, '/vulnerable-packages')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Vulnerable packages')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).not.toContain('requests')
|
||||
expect(wrapper.text()).toContain('Critical')
|
||||
})
|
||||
|
||||
it('VulnerablePackages on the blocked route keeps only blocked packages', async () => {
|
||||
const { wrapper, problems } = await smoke(VulnerablePackages, '/blocked-packages')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Blocked packages')
|
||||
expect(wrapper.text()).toContain('1 vulnerable version')
|
||||
})
|
||||
|
||||
it('BypassManagementPanel lists bypasses and opens the create dialog', async () => {
|
||||
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('CVE bypass management')
|
||||
expect(wrapper.text()).toContain('CVE-2026-0002')
|
||||
expect(wrapper.text()).toContain('Expired')
|
||||
|
||||
const create = wrapper.findAll('button').find((b) => b.text() === 'Create bypass')
|
||||
await create!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(document.body.textContent).toContain('Create a temporary bypass for a CVE or package.')
|
||||
expect(document.body.querySelector('textarea')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
|
||||
localStorage.clear()
|
||||
const prompt = vi.spyOn(window, 'prompt')
|
||||
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(prompt).not.toHaveBeenCalled()
|
||||
expect(document.body.textContent).toContain('Enter your admin API key to manage bypasses.')
|
||||
|
||||
const input = document.body.querySelector<HTMLInputElement>('input[type="password"]')
|
||||
expect(input).not.toBeNull()
|
||||
input!.value = 'secret-key'
|
||||
input!.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await flushPromises()
|
||||
document.body.querySelector<HTMLFormElement>('input[type="password"]')!.form!.requestSubmit()
|
||||
await flushPromises()
|
||||
|
||||
expect(localStorage.getItem('admin_api_key')).toBe('secret-key')
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/api/admin/bypasses'),
|
||||
expect.objectContaining({ headers: { Authorization: 'Bearer secret-key' } }),
|
||||
)
|
||||
expect(wrapper.text()).toContain('CVE-2026-0002')
|
||||
})
|
||||
|
||||
it('Stats renders totals, the storage tile and the registry table', async () => {
|
||||
const { wrapper, problems } = await smoke(Stats, '/stats')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Statistics')
|
||||
expect(wrapper.text()).toContain('5 GB / 10 GB')
|
||||
expect(wrapper.text()).toContain('50.0% used')
|
||||
expect(wrapper.text()).toContain('Go modules')
|
||||
expect(wrapper.find('[role="progressbar"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('VulnerabilityBadge prints the severity word for every tone', async () => {
|
||||
const { wrapper, problems } = await smoke(VulnerabilityBadge, '/', {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: { critical: 1, high: 2, moderate: 3, low: 4 },
|
||||
total: 10,
|
||||
isBlocked: true,
|
||||
})
|
||||
expect(problems).toEqual([])
|
||||
const text = wrapper.text()
|
||||
for (const word of ['Blocked', 'Critical: 1', 'High: 2', 'Moderate: 3', 'Low: 4']) expect(text).toContain(word)
|
||||
const tones = wrapper.findAll('[data-slot="status-badge"]').map((b) => b.attributes('data-tone'))
|
||||
expect(tones).toEqual(['danger', 'danger', 'warning', 'info', 'neutral'])
|
||||
})
|
||||
|
||||
it('App renders one banner, one main, a skip link first and the five sections', async () => {
|
||||
const { wrapper, problems } = await smoke(App, '/')
|
||||
expect(problems).toEqual([])
|
||||
// A page's own <header> inside <main> is not a banner landmark.
|
||||
expect(document.body.querySelectorAll('header:not(main header)').length).toBe(1)
|
||||
expect(document.body.querySelectorAll('main').length).toBe(1)
|
||||
const first = document.body.querySelector<HTMLElement>('a[href], button')
|
||||
expect(first?.getAttribute('href')).toBe('#main-content')
|
||||
const nav = wrapper.find('nav[aria-label="Sections"]')
|
||||
expect(nav.findAll('a').map((a) => a.text())).toEqual(['Dashboard', 'Packages', 'Vulnerable', 'Bypasses', 'Stats'])
|
||||
expect(document.documentElement.getAttribute('data-style')).toBe('workbench')
|
||||
// Brand column and sidebar items share one left edge: 6 spacing units each.
|
||||
expect(document.body.querySelector('header')?.className).toContain('[&>div]:px-6')
|
||||
expect(nav.classes()).toContain('p-3')
|
||||
})
|
||||
|
||||
it('PackageList still fetches through the store on mount', async () => {
|
||||
await smoke(PackageList, '/packages')
|
||||
expect(usePackageStore().packagePage.packages.length).toBe(PACKAGES.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PyPI rows show the release version, not the file name', () => {
|
||||
const FILE = 'six-1.17.0-py2.py3-none-any.whl'
|
||||
const SIX = {
|
||||
id: 'pypi-six',
|
||||
registry: 'pypi',
|
||||
name: 'six',
|
||||
version: FILE,
|
||||
release_version: '1.17.0',
|
||||
size: 1,
|
||||
cached_at: '2026-02-01T10:00:00Z',
|
||||
last_accessed: '2026-02-01T10:00:00Z',
|
||||
download_count: 1,
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
|
||||
total: 1,
|
||||
scannedAt: '2026-02-01T10:05:00Z',
|
||||
isBlocked: false,
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.endsWith('/vulnerabilities')) {
|
||||
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
|
||||
}
|
||||
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
|
||||
return respond(url) as never
|
||||
})
|
||||
})
|
||||
|
||||
it('Dashboard recent packages', async () => {
|
||||
const { wrapper } = await smoke(Dashboard, '/')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('Dashboard activity feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
|
||||
const { wrapper, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
const feed = wrapper.find('[data-testid="ws-event-feed"]').text()
|
||||
expect(feed).toContain('[email protected]')
|
||||
expect(feed).not.toContain('whl')
|
||||
})
|
||||
|
||||
it('VulnerablePackages version column', async () => {
|
||||
const { wrapper } = await smoke(VulnerablePackages, '/vulnerable-packages')
|
||||
await flushPromises()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('PackageDetails header badge', async () => {
|
||||
const { wrapper } = await smoke(PackageDetails, `/package/pypi/six/${FILE}`)
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push(`/package/pypi/six/${FILE}`)
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('PackageDetails falls back to the route version without a release version', async () => {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
|
||||
const { wrapper } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.3.0')
|
||||
})
|
||||
|
||||
it('bypass form tells PyPI users to use the release version', async () => {
|
||||
const { wrapper } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
await wrapper.findAll('button').find((b) => b.text() === 'Create bypass')!.trigger('click')
|
||||
await flushPromises()
|
||||
const pkg = Array.from(document.body.querySelectorAll<HTMLElement>('button, [role="radio"]')).find((e) => e.textContent?.trim() === 'Package bypass')
|
||||
pkg!.click()
|
||||
await flushPromises()
|
||||
expect(document.body.textContent).toContain('pypi/[email protected]')
|
||||
})
|
||||
})
|
||||
@@ -1,59 +0,0 @@
|
||||
/**
|
||||
* Shared badge styling utilities for consistent UI across the application
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get Tailwind CSS classes for severity badges (light theme)
|
||||
* @param severity - Severity level (CRITICAL, HIGH, MODERATE/MEDIUM, LOW)
|
||||
* @returns Tailwind CSS class string
|
||||
*/
|
||||
export function getSeverityBadgeClass(severity: string): string {
|
||||
const classes: Record<string, string> = {
|
||||
CRITICAL: 'bg-red-100 text-red-800 border-red-300',
|
||||
HIGH: 'bg-orange-100 text-orange-800 border-orange-300',
|
||||
MEDIUM: 'bg-yellow-100 text-yellow-800 border-yellow-300',
|
||||
MODERATE: 'bg-yellow-100 text-yellow-800 border-yellow-300',
|
||||
LOW: 'bg-blue-100 text-blue-800 border-blue-300',
|
||||
}
|
||||
return classes[severity.toUpperCase()] || 'bg-gray-100 text-gray-800 border-gray-300'
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Tailwind CSS classes for registry badges (light theme)
|
||||
* @param registry - Registry name (npm, pypi, go)
|
||||
* @returns Tailwind CSS class string
|
||||
*/
|
||||
export function getRegistryBadgeClass(registry: string): string {
|
||||
const classes: Record<string, string> = {
|
||||
npm: 'bg-red-100 text-red-800 border-red-300',
|
||||
pypi: 'bg-blue-100 text-blue-800 border-blue-300',
|
||||
go: 'bg-cyan-100 text-cyan-800 border-cyan-300',
|
||||
}
|
||||
return classes[registry.toLowerCase()] || 'bg-gray-100 text-gray-800 border-gray-300'
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Tailwind CSS classes for vulnerability border indicators
|
||||
* @param severity - Severity level (CRITICAL, HIGH, MODERATE/MEDIUM, LOW)
|
||||
* @returns Tailwind CSS class string for left border
|
||||
*/
|
||||
export function getVulnerabilityBorderClass(severity: string): string {
|
||||
const classes: Record<string, string> = {
|
||||
CRITICAL: 'border-l-4 border-l-red-600',
|
||||
HIGH: 'border-l-4 border-l-orange-500',
|
||||
MEDIUM: 'border-l-4 border-l-yellow-500',
|
||||
MODERATE: 'border-l-4 border-l-yellow-500',
|
||||
LOW: 'border-l-4 border-l-blue-500',
|
||||
}
|
||||
return classes[severity.toUpperCase()] || 'border-l-4 border-l-gray-500'
|
||||
}
|
||||
|
||||
/**
|
||||
* Format severity name for display (title case)
|
||||
* @param severity - Severity level (e.g., "CRITICAL", "HIGH")
|
||||
* @returns Formatted severity name (e.g., "Critical", "High")
|
||||
*/
|
||||
export function formatSeverityName(severity: string): string {
|
||||
const normalized = severity.toUpperCase()
|
||||
return normalized.charAt(0) + normalized.slice(1).toLowerCase()
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatDuration } from './format'
|
||||
|
||||
describe('formatDuration', () => {
|
||||
it.each([
|
||||
[604800, '7 days'],
|
||||
[86400, '1 day'],
|
||||
[129600, '36 hours'],
|
||||
[3600, '1 hour'],
|
||||
[5400, '90 minutes'],
|
||||
[60, '1 minute'],
|
||||
])('formats %i seconds as %s', (seconds, expected) => {
|
||||
expect(formatDuration(seconds)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const BYTES_PER_UNIT = 1024
|
||||
|
||||
export function formatNumber(num: number): string {
|
||||
return new Intl.NumberFormat().format(num)
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 B'
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(BYTES_PER_UNIT))
|
||||
return Math.round((bytes / Math.pow(BYTES_PER_UNIT, i)) * 100) / 100 + ' ' + BYTE_UNITS[i]
|
||||
}
|
||||
|
||||
const SECONDS_PER_DAY = 86400
|
||||
const SECONDS_PER_HOUR = 3600
|
||||
const SECONDS_PER_MINUTE = 60
|
||||
|
||||
function plural(n: number, unit: string): string {
|
||||
return `${n} ${unit}${n === 1 ? '' : 's'}`
|
||||
}
|
||||
|
||||
/** Whole days, hours or minutes, using the largest unit that divides the span evenly. */
|
||||
export function formatDuration(seconds: number): string {
|
||||
if (seconds % SECONDS_PER_DAY === 0) return plural(seconds / SECONDS_PER_DAY, 'day')
|
||||
if (seconds % SECONDS_PER_HOUR === 0) return plural(seconds / SECONDS_PER_HOUR, 'hour')
|
||||
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
|
||||
}
|
||||
|
||||
export function formatDate(date: string): string {
|
||||
if (!date) return 'N/A'
|
||||
const parsed = new Date(date)
|
||||
return Number.isNaN(parsed.getTime()) ? date : parsed.toLocaleString()
|
||||
}
|
||||
|
||||
/** PyPI rows key on the file name; show the release version when the API sends one. */
|
||||
export function displayVersion(pkg: { version: string; release_version?: string }): string {
|
||||
return pkg.release_version || pkg.version
|
||||
}
|
||||
|
||||
export function withVersionPrefix(version: string): string {
|
||||
return version.startsWith('v') ? version : 'v' + version
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export {
|
||||
faArrowLeft,
|
||||
faBan,
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
faBoxesStacked,
|
||||
faChartColumn,
|
||||
faChartLine,
|
||||
faChartPie,
|
||||
faDownload,
|
||||
faHardDrive,
|
||||
faPen,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
faTriangleExclamation,
|
||||
} from '@fortawesome/free-solid-svg-icons'
|
||||
export {
|
||||
faCircleCheck,
|
||||
faMagnifyingGlass,
|
||||
faPlus,
|
||||
faRotateRight,
|
||||
faChevronDown,
|
||||
faChevronUp,
|
||||
} from '@perfect-design/ui/lib/icons'
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { VulnerabilityCounts } from '@/stores/packages'
|
||||
|
||||
export type SeverityTone = 'danger' | 'warning' | 'info' | 'neutral'
|
||||
|
||||
export const SEVERITY_TONES: Record<string, SeverityTone> = {
|
||||
critical: 'danger',
|
||||
high: 'warning',
|
||||
moderate: 'info',
|
||||
medium: 'info',
|
||||
low: 'neutral',
|
||||
}
|
||||
|
||||
export const SEVERITY_RANK: Record<string, number> = {
|
||||
critical: 4,
|
||||
high: 3,
|
||||
moderate: 2,
|
||||
medium: 2,
|
||||
low: 1,
|
||||
}
|
||||
|
||||
export const SEVERITY_LEVELS = ['critical', 'high', 'moderate', 'low'] as const
|
||||
export type SeverityLevel = (typeof SEVERITY_LEVELS)[number]
|
||||
|
||||
export const NO_VULNERABILITIES: VulnerabilityCounts = { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
export function severityRank(severity: string): number {
|
||||
return SEVERITY_RANK[severity.toLowerCase()] ?? 0
|
||||
}
|
||||
|
||||
export function formatSeverityName(severity: string): string {
|
||||
const lower = severity.toLowerCase()
|
||||
return lower.charAt(0).toUpperCase() + lower.slice(1)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { SeverityLevel } from '@/lib/severity'
|
||||
|
||||
export type TrendPeriod = '30day' | '90day' | '1year'
|
||||
|
||||
export const TREND_PERIODS: { value: TrendPeriod; label: string }[] = [
|
||||
{ value: '30day', label: '30 days' },
|
||||
{ value: '90day', label: '90 days' },
|
||||
{ value: '1year', label: '1 year' },
|
||||
]
|
||||
|
||||
export const DEFAULT_TREND_PERIOD: TrendPeriod = '30day'
|
||||
|
||||
/** One UTC day. A null count is unknown (no scan history yet), not zero. */
|
||||
export interface TrendPoint {
|
||||
date: string
|
||||
total_packages: number
|
||||
total_size: number
|
||||
vulnerable_packages: number | null
|
||||
critical: number | null
|
||||
high: number | null
|
||||
moderate: number | null
|
||||
low: number | null
|
||||
blocked: number | null
|
||||
}
|
||||
|
||||
export interface TrendResponse {
|
||||
period: TrendPeriod
|
||||
from: string
|
||||
to: string
|
||||
/** First day in the window with vulnerability data; null when the window has none. */
|
||||
vulnerability_history_start: string | null
|
||||
points: TrendPoint[]
|
||||
}
|
||||
|
||||
/** Chart tone of each severity line, from the LineChart tone set. */
|
||||
export const SEVERITY_LINE_TONES: Record<SeverityLevel, 'danger' | 'warning' | 'info' | 'muted'> = {
|
||||
critical: 'danger',
|
||||
high: 'warning',
|
||||
moderate: 'info',
|
||||
low: 'muted',
|
||||
}
|
||||
|
||||
/** "2026-11-23" as "23 Nov", read in UTC so the label never shifts a day with the viewer's zone. */
|
||||
export function formatTrendDate(iso: string, withYear = false): string {
|
||||
const date = new Date(`${iso}T00:00:00Z`)
|
||||
if (Number.isNaN(date.getTime())) return iso
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: withYear ? 'numeric' : undefined,
|
||||
timeZone: 'UTC',
|
||||
})
|
||||
}
|
||||
|
||||
/** Chart values of one count; unknown days become NaN, which breaks the line instead of drawing zero. */
|
||||
export function trendValues(points: readonly TrendPoint[], key: keyof Omit<TrendPoint, 'date'>): number[] {
|
||||
return points.map((p) => p[key] ?? Number.NaN)
|
||||
}
|
||||
|
||||
/** True when some day in the window has no vulnerability data. */
|
||||
export function hasUnknownVulnerabilityDays(points: readonly TrendPoint[]): boolean {
|
||||
return points.some((p) => p.vulnerable_packages === null)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { ClassValue } from "clsx"
|
||||
import { clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { WSClient, __wsInternals, type RealtimeEvent } from './ws'
|
||||
|
||||
/**
|
||||
* Minimal WebSocket stub mimicking the parts of the browser API the WSClient
|
||||
* touches: readyState, onopen, onmessage, onclose, onerror, send, close.
|
||||
*/
|
||||
class StubWebSocket {
|
||||
static OPEN = 1
|
||||
static CLOSED = 3
|
||||
static instances: StubWebSocket[] = []
|
||||
|
||||
url: string
|
||||
readyState = 0
|
||||
sent: string[] = []
|
||||
onopen: ((ev: Event) => void) | null = null
|
||||
onmessage: ((ev: MessageEvent) => void) | null = null
|
||||
onclose: ((ev: CloseEvent) => void) | null = null
|
||||
onerror: ((ev: Event) => void) | null = null
|
||||
|
||||
constructor(url: string) {
|
||||
this.url = url
|
||||
StubWebSocket.instances.push(this)
|
||||
}
|
||||
|
||||
// Test helpers
|
||||
open(): void {
|
||||
this.readyState = StubWebSocket.OPEN
|
||||
this.onopen?.(new Event('open'))
|
||||
}
|
||||
|
||||
receive(data: unknown): void {
|
||||
const text = typeof data === 'string' ? data : JSON.stringify(data)
|
||||
this.onmessage?.({ data: text } as MessageEvent)
|
||||
}
|
||||
|
||||
triggerClose(): void {
|
||||
this.readyState = StubWebSocket.CLOSED
|
||||
this.onclose?.({} as CloseEvent)
|
||||
}
|
||||
|
||||
// Real API
|
||||
send(payload: string): void {
|
||||
this.sent.push(payload)
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.readyState = StubWebSocket.CLOSED
|
||||
this.onclose?.({} as CloseEvent)
|
||||
}
|
||||
}
|
||||
|
||||
const originalWebSocket = (globalThis as { WebSocket?: typeof WebSocket }).WebSocket
|
||||
|
||||
beforeEach(() => {
|
||||
StubWebSocket.instances = []
|
||||
;(globalThis as unknown as { WebSocket: unknown }).WebSocket = StubWebSocket
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
;(globalThis as unknown as { WebSocket: unknown }).WebSocket = originalWebSocket
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('parseEvent', () => {
|
||||
it('normalizes backend envelope (data + RFC3339 timestamp)', () => {
|
||||
const evt = __wsInternals.parseEvent(
|
||||
JSON.stringify({
|
||||
type: 'package_cached',
|
||||
timestamp: '2026-04-28T12:00:00Z',
|
||||
data: { name: 'lodash', version: '4.17.21', registry: 'npm' },
|
||||
}),
|
||||
)
|
||||
expect(evt).not.toBeNull()
|
||||
expect(evt!.type).toBe('package_cached')
|
||||
expect(evt!.payload).toMatchObject({ name: 'lodash' })
|
||||
expect(evt!.timestamp).toBe(Date.parse('2026-04-28T12:00:00Z'))
|
||||
})
|
||||
|
||||
it('drops malformed JSON', () => {
|
||||
expect(__wsInternals.parseEvent('not-json{{')).toBeNull()
|
||||
})
|
||||
|
||||
it('drops unknown event types (e.g. control frames)', () => {
|
||||
expect(
|
||||
__wsInternals.parseEvent(JSON.stringify({ type: 'pong' })),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts numeric timestamp', () => {
|
||||
const evt = __wsInternals.parseEvent(
|
||||
JSON.stringify({ type: 'stats_update', timestamp: 1234567890, data: {} }),
|
||||
)
|
||||
expect(evt!.timestamp).toBe(1234567890)
|
||||
})
|
||||
})
|
||||
|
||||
describe('WSClient', () => {
|
||||
it('connects and dispatches typed events to subscribers', () => {
|
||||
const client = new WSClient('ws://test/ws')
|
||||
const received: RealtimeEvent[] = []
|
||||
client.on('package_cached', (e) => received.push(e))
|
||||
client.connect()
|
||||
|
||||
const sock = StubWebSocket.instances[0]
|
||||
expect(sock).toBeDefined()
|
||||
sock.open()
|
||||
sock.receive({
|
||||
type: 'package_cached',
|
||||
timestamp: '2026-04-28T00:00:00Z',
|
||||
data: { name: 'foo' },
|
||||
})
|
||||
|
||||
expect(received).toHaveLength(1)
|
||||
expect(received[0].type).toBe('package_cached')
|
||||
expect(received[0].payload.name).toBe('foo')
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('forwards events to wildcard subscribers', () => {
|
||||
const client = new WSClient('ws://test/ws')
|
||||
const seen: string[] = []
|
||||
client.on('*', (e) => seen.push(e.type))
|
||||
client.connect()
|
||||
const sock = StubWebSocket.instances[0]
|
||||
sock.open()
|
||||
sock.receive({ type: 'scan_complete', data: {} })
|
||||
sock.receive({ type: 'package_deleted', data: {} })
|
||||
expect(seen).toEqual(['scan_complete', 'package_deleted'])
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('unsubscribe stops further dispatches', () => {
|
||||
const client = new WSClient('ws://test/ws')
|
||||
let count = 0
|
||||
const off = client.on('package_cached', () => {
|
||||
count += 1
|
||||
})
|
||||
client.connect()
|
||||
const sock = StubWebSocket.instances[0]
|
||||
sock.open()
|
||||
sock.receive({ type: 'package_cached', data: {} })
|
||||
expect(count).toBe(1)
|
||||
off()
|
||||
sock.receive({ type: 'package_cached', data: {} })
|
||||
expect(count).toBe(1)
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('auto-reconnects with backoff after unexpected close', () => {
|
||||
vi.useFakeTimers()
|
||||
const client = new WSClient('ws://test/ws')
|
||||
client.connect()
|
||||
const first = StubWebSocket.instances[0]
|
||||
first.open()
|
||||
first.triggerClose()
|
||||
|
||||
// First reconnect happens after RECONNECT_BASE_MS (1s).
|
||||
vi.advanceTimersByTime(__wsInternals.RECONNECT_BASE_MS)
|
||||
expect(StubWebSocket.instances.length).toBe(2)
|
||||
|
||||
// Second drop -> next backoff is 2s.
|
||||
StubWebSocket.instances[1].open()
|
||||
StubWebSocket.instances[1].triggerClose()
|
||||
vi.advanceTimersByTime(__wsInternals.RECONNECT_BASE_MS * 2)
|
||||
expect(StubWebSocket.instances.length).toBe(3)
|
||||
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('does not reconnect after explicit close', () => {
|
||||
vi.useFakeTimers()
|
||||
const client = new WSClient('ws://test/ws')
|
||||
client.connect()
|
||||
const sock = StubWebSocket.instances[0]
|
||||
sock.open()
|
||||
client.close()
|
||||
vi.advanceTimersByTime(60_000)
|
||||
expect(StubWebSocket.instances.length).toBe(1)
|
||||
})
|
||||
|
||||
it('emits heartbeat ping every 25s', () => {
|
||||
vi.useFakeTimers()
|
||||
const client = new WSClient('ws://test/ws')
|
||||
client.connect()
|
||||
const sock = StubWebSocket.instances[0]
|
||||
sock.open()
|
||||
expect(sock.sent).toHaveLength(0)
|
||||
vi.advanceTimersByTime(__wsInternals.HEARTBEAT_INTERVAL_MS)
|
||||
expect(sock.sent).toHaveLength(1)
|
||||
expect(JSON.parse(sock.sent[0])).toEqual({ action: 'ping' })
|
||||
vi.advanceTimersByTime(__wsInternals.HEARTBEAT_INTERVAL_MS)
|
||||
expect(sock.sent).toHaveLength(2)
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('queues outbound messages while disconnected and flushes on open', () => {
|
||||
const client = new WSClient('ws://test/ws')
|
||||
client.send({ action: 'subscribe', data: ['package_cached'] })
|
||||
client.connect()
|
||||
const sock = StubWebSocket.instances[0]
|
||||
expect(sock.sent).toHaveLength(0)
|
||||
sock.open()
|
||||
expect(sock.sent).toHaveLength(1)
|
||||
expect(JSON.parse(sock.sent[0])).toMatchObject({ action: 'subscribe' })
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('drops malformed inbound JSON without throwing', () => {
|
||||
const client = new WSClient('ws://test/ws')
|
||||
let count = 0
|
||||
client.on('*', () => {
|
||||
count += 1
|
||||
})
|
||||
client.connect()
|
||||
const sock = StubWebSocket.instances[0]
|
||||
sock.open()
|
||||
sock.receive('not-json{{{')
|
||||
sock.receive({ type: 'unknown_type', data: {} })
|
||||
expect(count).toBe(0)
|
||||
client.close()
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user