mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-29 06:55:23 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1432c7176b | ||
|
|
426225bd14 | ||
|
|
518d836c7b | ||
|
|
1e99b53d51 | ||
|
|
9c0420161e | ||
|
|
c685131865 | ||
|
|
e80489e55c | ||
|
|
5f4bdbed80 | ||
|
|
1b00236749 | ||
|
|
9ff6de2414 | ||
|
|
3bfc367898 | ||
|
|
6715cefd25 | ||
|
|
5518d02599 | ||
|
|
547f41677a | ||
|
|
7b8ff467b8 | ||
|
|
48bd654839 | ||
|
|
80160eeb56 | ||
|
|
a685b71c7f | ||
|
|
798fadb4bb | ||
|
|
4b2ec7c45c | ||
|
|
8b6f1ae4ac | ||
|
|
bc56b97677 | ||
|
|
7470c41560 | ||
|
|
8b4d4746df | ||
|
|
43e075baf3 | ||
|
|
64793f9c7e | ||
|
|
55c60cb8e4 | ||
|
|
ad8295455d | ||
|
|
6e8ac5265c | ||
|
|
671bb0625b | ||
|
|
45aa4bcace | ||
|
|
b248bfed31 | ||
|
|
a511544d7a | ||
|
|
6ddc382d5b | ||
|
|
2b6f3bd892 | ||
|
|
916e2b0aa5 | ||
|
|
30ebfaae3e | ||
|
|
3a7ffab4d5 | ||
|
|
22f2a8dfb9 | ||
|
|
4870f243fc | ||
|
|
fac30f59e6 | ||
|
|
775ed8a4aa | ||
|
|
e6d8ed0f2e | ||
|
|
40ed8f8213 | ||
|
|
ecf750adbb | ||
|
|
41f8369c43 | ||
|
|
d6044cdd2e | ||
|
|
1baa6b8e26 | ||
|
|
3d6bda3a5f | ||
|
|
e37c797602 | ||
|
|
157814cf08 | ||
|
|
65aa2e25dc | ||
|
|
3731ca05ce | ||
|
|
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 | ||
|
|
bcc0185924 | ||
|
|
89bf86a6e1 | ||
|
|
6f2be85b9e | ||
|
|
72143ecd3d | ||
|
|
e6fe925dcb | ||
|
|
f03a288326 | ||
|
|
6afa55b5f5 | ||
|
|
6b037a92b4 | ||
|
|
48b834a62a |
@@ -0,0 +1,21 @@
|
||||
name: Update dependencies
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 3 * * *"
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
update:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/renovate-autoupdate.yaml@main
|
||||
with:
|
||||
go-version: ">=1.27"
|
||||
node-working-directory: frontend
|
||||
release-workflow: release.yaml
|
||||
runner: self-hosted
|
||||
@@ -0,0 +1,22 @@
|
||||
name: Pull Request
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
push:
|
||||
branches:
|
||||
- "**"
|
||||
- "!main"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
security-events: write
|
||||
|
||||
jobs:
|
||||
pr-checks:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-pr.yaml@main
|
||||
with:
|
||||
go-version: ">=1.27"
|
||||
runner: self-hosted
|
||||
@@ -0,0 +1,92 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
paths-ignore:
|
||||
- "**.md"
|
||||
- "**/release.yaml"
|
||||
- "frontend/**"
|
||||
- "deployments/**"
|
||||
- "docs/**"
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
packages: write
|
||||
deployments: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-release-cgo.yaml@main
|
||||
with:
|
||||
go-version: ">=1.27"
|
||||
# Enable frontend build
|
||||
node-enabled: true
|
||||
node-version: "20"
|
||||
node-build-script: "cd frontend && npm install -g pnpm && pnpm install --frozen-lockfile && pnpm run build"
|
||||
node-output-path: "frontend/dist"
|
||||
node-cache-dependency-path: "frontend/pnpm-lock.yaml"
|
||||
runner: self-hosted
|
||||
secrets: inherit
|
||||
|
||||
benchmark:
|
||||
name: Publish Benchmarks
|
||||
needs: release
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
ref: main
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ">=1.27"
|
||||
|
||||
- name: Run benchmarks
|
||||
run: go test -bench=. -benchmem ./... -run=^# | tee output.txt
|
||||
|
||||
- name: Store benchmark result
|
||||
uses: benchmark-action/github-action-benchmark@v1
|
||||
with:
|
||||
tool: "go"
|
||||
output-file-path: output.txt
|
||||
fail-on-alert: false
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
comment-on-alert: true
|
||||
summary-always: true
|
||||
auto-push: true
|
||||
benchmark-data-dir-path: "docs/bench"
|
||||
|
||||
publish-helm-chart:
|
||||
name: Publish Helm Chart
|
||||
needs: release
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get release version
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(git describe --tags --abbrev=0 2>/dev/null || echo "0.0.0")
|
||||
VERSION=${VERSION#v}
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Trigger helm-charts release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
run: |
|
||||
gh api repos/lukaszraczylo/helm-charts/dispatches \
|
||||
-f event_type=release-chart \
|
||||
-f client_payload[chart_name]=gohoarder \
|
||||
-f client_payload[version]=${{ steps.version.outputs.version }} \
|
||||
-f client_payload[source_repo]=lukaszraczylo/gohoarder \
|
||||
-f client_payload[chart_path]=helm/gohoarder
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
# Binaries
|
||||
bin/
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
/gohoarder
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool
|
||||
*.out
|
||||
coverage.txt
|
||||
coverage.html
|
||||
|
||||
# Dependency directories
|
||||
vendor/
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Config files (keep example)
|
||||
config.yaml
|
||||
*.local.yaml
|
||||
|
||||
# Databases
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
# Cache
|
||||
/var/cache/gohoarder/
|
||||
/cache/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Temporary files
|
||||
tmp/
|
||||
temp/
|
||||
|
||||
# Security
|
||||
.env
|
||||
*.pem
|
||||
*.key
|
||||
*.crt
|
||||
|
||||
# Build artifacts
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Node modules (for frontend)
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
|
||||
# Test fixtures
|
||||
tests/fixtures/temp/
|
||||
|
||||
# Markdown files (except README.md)
|
||||
*.md
|
||||
!README.md
|
||||
!lean4/FINDINGS.md
|
||||
|
||||
/gohoarder
|
||||
*.log
|
||||
*.out
|
||||
test-go-proxy
|
||||
frontend/node_modules
|
||||
data/storage
|
||||
*.pid
|
||||
|
||||
# Local worktrees
|
||||
.worktrees/
|
||||
lean4/.lake
|
||||
@@ -0,0 +1,291 @@
|
||||
version: 2
|
||||
|
||||
# Project metadata
|
||||
project_name: gohoarder
|
||||
|
||||
# Pre-release hooks
|
||||
before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
# Download and setup Zig for cross-compilation (Linux only)
|
||||
- bash -c 'if [ "$(uname -s)" = "Linux" ]; then wget https://ziglang.org/download/0.15.2/zig-x86_64-linux-0.15.2.tar.xz -O /tmp/zig.tar.xz && ls -lh /tmp/zig.tar.xz && tar -xvf /tmp/zig.tar.xz -C /tmp && echo "/tmp/zig-x86_64-linux-0.15.2" >> $GITHUB_PATH; fi'
|
||||
|
||||
# Build configuration
|
||||
# All binaries built using Zig for consistent cross-compilation
|
||||
# Zig handles CGO cross-compilation without platform-specific toolchains
|
||||
# Binaries are injected into Docker images (no Docker compilation)
|
||||
builds:
|
||||
- id: gohoarder
|
||||
main: ./cmd/gohoarder
|
||||
binary: gohoarder
|
||||
env:
|
||||
- CGO_ENABLED=1
|
||||
tags:
|
||||
- fts5
|
||||
flags:
|
||||
- -trimpath
|
||||
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:
|
||||
- id: default
|
||||
name_template: >-
|
||||
{{ .ProjectName }}_
|
||||
{{- title .Os }}_
|
||||
{{- if eq .Arch "amd64" }}x86_64
|
||||
{{- else if eq .Arch "386" }}i386
|
||||
{{- else }}{{ .Arch }}{{ end }}
|
||||
{{- if .Arm }}v{{ .Arm }}{{ end }}
|
||||
formats:
|
||||
- tar.gz
|
||||
- zip
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
formats:
|
||||
- zip
|
||||
files:
|
||||
- README.md
|
||||
- LICENSE
|
||||
- config.yaml.example
|
||||
|
||||
# Checksum
|
||||
checksum:
|
||||
name_template: 'checksums.txt'
|
||||
algorithm: sha256
|
||||
|
||||
# Snapshot configuration
|
||||
snapshot:
|
||||
version_template: "{{ incpatch .Version }}-next"
|
||||
|
||||
# Changelog
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- '^docs:'
|
||||
- '^test:'
|
||||
- '^ci:'
|
||||
- '^chore:'
|
||||
- '^Merge'
|
||||
- '^WIP'
|
||||
- '^Update go.mod'
|
||||
- 'README'
|
||||
|
||||
# GitHub release configuration
|
||||
release:
|
||||
github:
|
||||
owner: lukaszraczylo
|
||||
name: gohoarder
|
||||
name_template: "version {{.Version}}"
|
||||
draft: false
|
||||
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
|
||||
images:
|
||||
- ghcr.io/lukaszraczylo/gohoarder-server
|
||||
tags:
|
||||
- "{{ .Version }}"
|
||||
- latest
|
||||
platforms:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
dockerfile: Dockerfile.server
|
||||
flags:
|
||||
- "--pull"
|
||||
- "--label=org.opencontainers.image.title=GoHoarder Server"
|
||||
- "--label=org.opencontainers.image.description=Universal package cache proxy server"
|
||||
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
- "--label=org.opencontainers.image.created={{ .Date }}"
|
||||
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
|
||||
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
|
||||
images:
|
||||
- ghcr.io/lukaszraczylo/gohoarder-frontend
|
||||
tags:
|
||||
- "{{ .Version }}"
|
||||
- latest
|
||||
platforms:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
dockerfile: Dockerfile.frontend
|
||||
flags:
|
||||
- "--pull"
|
||||
- "--label=org.opencontainers.image.title=GoHoarder Frontend"
|
||||
- "--label=org.opencontainers.image.description=GoHoarder web dashboard"
|
||||
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
- "--label=org.opencontainers.image.created={{ .Date }}"
|
||||
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
|
||||
extra_files:
|
||||
- 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
|
||||
images:
|
||||
- ghcr.io/lukaszraczylo/gohoarder-scanner
|
||||
tags:
|
||||
- "{{ .Version }}"
|
||||
- latest
|
||||
platforms:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
dockerfile: Dockerfile.scanner
|
||||
flags:
|
||||
- "--pull"
|
||||
- "--label=org.opencontainers.image.title=GoHoarder Scanner"
|
||||
- "--label=org.opencontainers.image.description=GoHoarder vulnerability scanning engine"
|
||||
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
- "--label=org.opencontainers.image.created={{ .Date }}"
|
||||
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
|
||||
extra_files:
|
||||
- config.yaml.example
|
||||
|
||||
# 4. Migration Engine - Database migration tool
|
||||
# Uses pre-built binary from 'migrate' build (no Docker compilation)
|
||||
# linux/arm64 binary is cross-compiled using Zig (fast, no QEMU!)
|
||||
- id: gohoarder-migrate
|
||||
ids:
|
||||
- migrate
|
||||
images:
|
||||
- ghcr.io/lukaszraczylo/gohoarder-migrate
|
||||
tags:
|
||||
- "{{ .Version }}"
|
||||
- latest
|
||||
platforms:
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
dockerfile: Dockerfile.migrate
|
||||
flags:
|
||||
- "--pull"
|
||||
- "--label=org.opencontainers.image.title=GoHoarder Migrate"
|
||||
- "--label=org.opencontainers.image.description=Database migration tool for GoHoarder V2 schema"
|
||||
- "--label=org.opencontainers.image.url=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.source=https://github.com/lukaszraczylo/gohoarder"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
- "--label=org.opencontainers.image.created={{ .Date }}"
|
||||
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
|
||||
extra_files:
|
||||
- migrations
|
||||
|
||||
# Artifact signing with cosign
|
||||
signs:
|
||||
- cmd: cosign
|
||||
signature: "${artifact}.sigstore.json"
|
||||
args:
|
||||
- sign-blob
|
||||
- "--bundle=${signature}"
|
||||
- "${artifact}"
|
||||
- "--yes"
|
||||
artifacts: checksum
|
||||
output: true
|
||||
|
||||
# Docker image signing with cosign
|
||||
docker_signs:
|
||||
- cmd: cosign
|
||||
artifacts: manifests
|
||||
output: true
|
||||
args:
|
||||
- sign
|
||||
- "${artifact}@${digest}"
|
||||
- "--yes"
|
||||
@@ -0,0 +1,177 @@
|
||||
# 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
|
||||
|
||||
FROM mirror.gcr.io/library/nginx:1.31.9-alpine@sha256:fb4658584bd9a916ffb6f6e365f97c25cfdb2923801f551ea08356e695f14ff7
|
||||
|
||||
# Install envsubst for runtime configuration
|
||||
RUN apk add --no-cache gettext
|
||||
|
||||
# Copy pre-built frontend files
|
||||
# These are built on the CI runner and injected via extra_files
|
||||
COPY frontend/dist /usr/share/nginx/html
|
||||
|
||||
# Create runtime config injection script
|
||||
RUN cat > /docker-entrypoint.d/40-inject-config.sh <<'EOF'
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Create runtime configuration file
|
||||
cat > /usr/share/nginx/html/config.js <<JSEOF
|
||||
window.__RUNTIME_CONFIG__ = {
|
||||
API_BASE_URL: "${API_BASE_URL:-/api}",
|
||||
APP_VERSION: "${APP_VERSION:-unknown}",
|
||||
APP_NAME: "${APP_NAME:-GoHoarder}"
|
||||
};
|
||||
JSEOF
|
||||
|
||||
# Substitute environment variables
|
||||
envsubst < /usr/share/nginx/html/config.js > /usr/share/nginx/html/config.tmp.js
|
||||
mv /usr/share/nginx/html/config.tmp.js /usr/share/nginx/html/config.js
|
||||
|
||||
echo "Runtime configuration injected:"
|
||||
cat /usr/share/nginx/html/config.js
|
||||
EOF
|
||||
|
||||
RUN chmod +x /docker-entrypoint.d/40-inject-config.sh
|
||||
|
||||
# Create nginx templates directory and configuration template with backend proxy support
|
||||
RUN mkdir -p /etc/nginx/templates && \
|
||||
cat > /etc/nginx/templates/default.conf.template <<'EOF'
|
||||
# Upstream backend server
|
||||
upstream backend {
|
||||
server ${BACKEND_HOST}:${BACKEND_PORT};
|
||||
keepalive 32;
|
||||
}
|
||||
|
||||
# Cache configuration
|
||||
proxy_cache_path /var/cache/nginx/static levels=1:2 keys_zone=static_cache:10m max_size=100m inactive=60m use_temp_path=off;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name ${SERVER_NAME};
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Security headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
# Client body size for package uploads
|
||||
client_max_body_size 500M;
|
||||
client_body_timeout 300s;
|
||||
|
||||
# Logging
|
||||
access_log /var/log/nginx/access.log combined;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
|
||||
# Compression
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
|
||||
|
||||
# API endpoints - proxy to backend
|
||||
location /api/ {
|
||||
# Proxy settings
|
||||
proxy_pass http://backend;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
# Headers
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
proxy_set_header Connection "";
|
||||
# The backend authenticates by API-key header; browser session cookies only bloat the request.
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# Timeouts for long-running operations
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
|
||||
# Buffer settings
|
||||
proxy_buffering on;
|
||||
proxy_buffer_size 4k;
|
||||
proxy_buffers 8 4k;
|
||||
proxy_busy_buffers_size 8k;
|
||||
}
|
||||
|
||||
# Health check endpoint
|
||||
location /health {
|
||||
proxy_pass http://backend/health;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
access_log off;
|
||||
}
|
||||
|
||||
# The package endpoints are not part of the dashboard and stay on the
|
||||
# backend Service. A catch-all 404 keeps them off the SPA fallback below.
|
||||
location ~ ^/(npm|pypi|go|metrics)(/|$) {
|
||||
return 404;
|
||||
}
|
||||
|
||||
# WebSocket support
|
||||
location /ws {
|
||||
proxy_pass http://backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# WebSocket timeouts
|
||||
proxy_connect_timeout 7d;
|
||||
proxy_send_timeout 7d;
|
||||
proxy_read_timeout 7d;
|
||||
}
|
||||
|
||||
# Runtime configuration endpoint
|
||||
location = /config.js {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache";
|
||||
add_header Expires "0";
|
||||
}
|
||||
|
||||
# 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
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD wget --quiet --tries=1 --spider http://localhost/ || exit 1
|
||||
|
||||
# Environment variables with defaults
|
||||
ENV API_BASE_URL=/api \
|
||||
APP_VERSION=unknown \
|
||||
APP_NAME=GoHoarder \
|
||||
BACKEND_HOST=gohoarder-server \
|
||||
BACKEND_PORT=8080 \
|
||||
SERVER_NAME=_
|
||||
|
||||
# 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;'"]
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,83 @@
|
||||
# Scanning Engine - Background Scanner Worker
|
||||
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
|
||||
# GoReleaser injects the platform-specific binary automatically
|
||||
|
||||
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
# Install scanning tools and runtime dependencies (including CGO/SQLite dependencies)
|
||||
RUN apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
git \
|
||||
curl \
|
||||
wget \
|
||||
bash \
|
||||
sqlite-libs \
|
||||
musl \
|
||||
python3 \
|
||||
py3-pip \
|
||||
npm \
|
||||
go \
|
||||
&& update-ca-certificates
|
||||
|
||||
# Install Trivy for container scanning
|
||||
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/v0.76.2/contrib/install.sh | sh -s -- -b /usr/local/bin v0.76.2
|
||||
|
||||
# Install Grype for vulnerability scanning
|
||||
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/v0.121.2/install.sh | sh -s -- -b /usr/local/bin v0.121.2
|
||||
|
||||
# Install govulncheck for Go vulnerability scanning
|
||||
RUN go install golang.org/x/vuln/cmd/[email protected] && \
|
||||
mv /root/go/bin/govulncheck /usr/local/bin/
|
||||
|
||||
# Install pip-audit for Python package vulnerability scanning
|
||||
RUN pip3 install --no-cache-dir pip-audit==2.10.1 --break-system-packages
|
||||
|
||||
# Create non-root user
|
||||
RUN addgroup -g 1000 scanner && \
|
||||
adduser -D -u 1000 -G scanner scanner
|
||||
|
||||
# Create necessary directories with proper permissions
|
||||
RUN mkdir -p /var/cache/gohoarder \
|
||||
/var/lib/gohoarder/metadata \
|
||||
/var/lib/trivy \
|
||||
/tmp/gohoarder && \
|
||||
chown -R scanner:scanner /var/cache/gohoarder \
|
||||
/var/lib/gohoarder \
|
||||
/var/lib/trivy \
|
||||
/tmp/gohoarder && \
|
||||
chmod -R 750 /var/cache/gohoarder \
|
||||
/var/lib/gohoarder \
|
||||
/var/lib/trivy
|
||||
|
||||
# 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
|
||||
COPY config.yaml.example /etc/gohoarder/config.yaml.example
|
||||
|
||||
WORKDIR /var/cache/gohoarder
|
||||
USER scanner
|
||||
|
||||
# Expose metrics port
|
||||
EXPOSE 9091
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=60s --timeout=30s --start-period=10s --retries=3 \
|
||||
CMD ["/usr/local/bin/gohoarder", "version"] || exit 1
|
||||
|
||||
# Environment variables for scanner mode
|
||||
ENV SCANNER_MODE=true \
|
||||
SCANNER_WORKERS=4 \
|
||||
SCANNER_INTERVAL=300
|
||||
|
||||
# Run the scanner in background mode
|
||||
# The scanner runs the same serve command but uses SCANNER_MODE env var
|
||||
# and configuration to determine its role
|
||||
ENTRYPOINT ["/usr/local/bin/gohoarder"]
|
||||
CMD ["serve"]
|
||||
@@ -0,0 +1,54 @@
|
||||
# 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
|
||||
|
||||
# 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
|
||||
RUN addgroup -g 1000 gohoarder && \
|
||||
adduser -D -u 1000 -G gohoarder gohoarder
|
||||
|
||||
# Create necessary directories with proper permissions
|
||||
RUN mkdir -p /var/cache/gohoarder \
|
||||
/var/lib/gohoarder/metadata \
|
||||
/tmp/gohoarder && \
|
||||
chown -R gohoarder:gohoarder /var/cache/gohoarder \
|
||||
/var/lib/gohoarder \
|
||||
/tmp/gohoarder && \
|
||||
chmod -R 750 /var/cache/gohoarder \
|
||||
/var/lib/gohoarder
|
||||
|
||||
# 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
|
||||
COPY config.yaml.example /etc/gohoarder/config.yaml.example
|
||||
|
||||
WORKDIR /var/cache/gohoarder
|
||||
USER gohoarder
|
||||
|
||||
# Expose ports
|
||||
# 8080: Main proxy port
|
||||
# 9090: Metrics/health port
|
||||
EXPOSE 8080 9090
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD ["/usr/local/bin/gohoarder", "version"] || exit 1
|
||||
|
||||
# Run the server
|
||||
ENTRYPOINT ["/usr/local/bin/gohoarder"]
|
||||
CMD ["serve"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Lukasz Raczylo
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,139 @@
|
||||
.PHONY: help build test test-coverage run clean install lint fmt vet
|
||||
|
||||
# Variables
|
||||
BINARY_NAME=gohoarder
|
||||
BINARY_PATH=bin/$(BINARY_NAME)
|
||||
CMD_PATH=./cmd/gohoarder
|
||||
# Generate semantic version using script, fallback to 'dev' if script fails
|
||||
VERSION?=$(shell ./script/generate-version.sh 2>/dev/null || echo "dev")
|
||||
GIT_COMMIT=$(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
|
||||
BUILD_TIME=$(shell date -u '+%Y-%m-%dT%H:%M:%SZ')
|
||||
LDFLAGS=-ldflags "-X github.com/lukaszraczylo/gohoarder/internal/version.Version=$(VERSION) \
|
||||
-X github.com/lukaszraczylo/gohoarder/internal/version.GitCommit=$(GIT_COMMIT) \
|
||||
-X github.com/lukaszraczylo/gohoarder/internal/version.BuildTime=$(BUILD_TIME)"
|
||||
|
||||
help: ## Display this help screen
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
|
||||
|
||||
build: ## Build the binary
|
||||
@echo "Building $(BINARY_NAME)..."
|
||||
@mkdir -p bin
|
||||
@go build -buildvcs=false $(LDFLAGS) -o $(BINARY_PATH) $(CMD_PATH)
|
||||
@echo "Binary built: $(BINARY_PATH)"
|
||||
|
||||
build-all: ## Build for all platforms
|
||||
@echo "Building for all platforms..."
|
||||
@mkdir -p bin
|
||||
GOOS=linux GOARCH=amd64 go build -buildvcs=false $(LDFLAGS) -o bin/$(BINARY_NAME)-linux-amd64 $(CMD_PATH)
|
||||
GOOS=linux GOARCH=arm64 go build -buildvcs=false $(LDFLAGS) -o bin/$(BINARY_NAME)-linux-arm64 $(CMD_PATH)
|
||||
GOOS=darwin GOARCH=amd64 go build -buildvcs=false $(LDFLAGS) -o bin/$(BINARY_NAME)-darwin-amd64 $(CMD_PATH)
|
||||
GOOS=darwin GOARCH=arm64 go build -buildvcs=false $(LDFLAGS) -o bin/$(BINARY_NAME)-darwin-arm64 $(CMD_PATH)
|
||||
@echo "All binaries built"
|
||||
|
||||
test: ## Run tests
|
||||
@echo "Running tests..."
|
||||
@go test -v ./...
|
||||
|
||||
test-coverage: ## Run tests with coverage
|
||||
@echo "Running tests with coverage..."
|
||||
@go test -coverprofile=coverage.out ./...
|
||||
@go tool cover -html=coverage.out -o coverage.html
|
||||
@echo "Coverage report: coverage.html"
|
||||
|
||||
test-race: ## Run tests with race detector
|
||||
@echo "Running tests with race detector..."
|
||||
@go test -race ./...
|
||||
|
||||
bench: ## Run benchmarks
|
||||
@echo "Running benchmarks..."
|
||||
@go test -bench=. -benchmem ./...
|
||||
|
||||
run: build ## Build and run both backend and frontend for development
|
||||
@echo "Starting $(BINARY_NAME) and frontend in development mode..."
|
||||
@echo ""
|
||||
@echo "Backend will run on: http://localhost:8080 (configured in config.yaml)"
|
||||
@echo "Frontend will run on: http://localhost:5173 (configured in frontend/.env)"
|
||||
@echo ""
|
||||
@echo "To change ports:"
|
||||
@echo " - Backend: Edit 'server.port' in config.yaml"
|
||||
@echo " - Frontend: Edit 'VITE_PORT' and 'VITE_BACKEND_URL' in frontend/.env"
|
||||
@echo ""
|
||||
@trap 'kill 0' SIGINT; \
|
||||
$(BINARY_PATH) serve & \
|
||||
cd frontend && pnpm dev & \
|
||||
wait
|
||||
|
||||
run-backend: build ## Build and run only the backend server
|
||||
@echo "Starting $(BINARY_NAME)..."
|
||||
@$(BINARY_PATH) serve
|
||||
|
||||
run-dev: ## Run with example config
|
||||
@echo "Starting $(BINARY_NAME) in development mode..."
|
||||
@go run $(CMD_PATH) serve --config config.yaml.example
|
||||
|
||||
clean: ## Clean build artifacts
|
||||
@echo "Cleaning..."
|
||||
@rm -rf bin/
|
||||
@rm -f coverage.out coverage.html
|
||||
@rm -f *.db *.db-shm *.db-wal
|
||||
@echo "Clean complete"
|
||||
|
||||
clean-db: ## Clean all local cache and database files (requires confirmation)
|
||||
@echo "WARNING: This will delete all cached packages and scan results!"
|
||||
@echo "Paths to be cleaned:"
|
||||
@echo " - ./data/storage (package cache)"
|
||||
@echo " - ./data/gohoarder.db and gohoarder.db (metadata database)"
|
||||
@echo " - /tmp/trivy (Trivy cache)"
|
||||
@echo ""
|
||||
@printf "Are you sure you want to continue? [y/N] " && read confirm && [ "$$confirm" = "y" ] || (echo "Cancelled." && exit 1)
|
||||
@echo "Cleaning database and cache..."
|
||||
@rm -rf ./data/storage ./data
|
||||
@rm -f gohoarder.db gohoarder.db-shm gohoarder.db-wal
|
||||
@rm -rf /tmp/trivy
|
||||
@echo "Database and cache cleaned successfully"
|
||||
|
||||
clean-db-force: ## Clean all local cache and database files (no confirmation)
|
||||
@echo "Cleaning database and cache..."
|
||||
@rm -rf ./data/storage ./data
|
||||
@rm -f gohoarder.db gohoarder.db-shm gohoarder.db-wal
|
||||
@rm -rf /tmp/trivy
|
||||
@echo "Database and cache cleaned successfully"
|
||||
|
||||
install: build ## Install the binary
|
||||
@echo "Installing $(BINARY_NAME)..."
|
||||
@cp $(BINARY_PATH) $(GOPATH)/bin/
|
||||
@echo "Installed to $(GOPATH)/bin/$(BINARY_NAME)"
|
||||
|
||||
lint: ## Run linters
|
||||
@echo "Running linters..."
|
||||
@go vet ./...
|
||||
@which golangci-lint > /dev/null || (echo "golangci-lint not installed" && exit 1)
|
||||
@golangci-lint run
|
||||
|
||||
fmt: ## Format code
|
||||
@echo "Formatting code..."
|
||||
@gofmt -s -w .
|
||||
@which goimports > /dev/null && goimports -w . || true
|
||||
|
||||
vet: ## Run go vet
|
||||
@go vet ./...
|
||||
|
||||
tidy: ## Tidy dependencies
|
||||
@go mod tidy
|
||||
|
||||
docker-build: ## Build Docker image
|
||||
@echo "Building Docker image..."
|
||||
@docker build -t $(BINARY_NAME):$(VERSION) .
|
||||
|
||||
docker-run: docker-build ## Run Docker container
|
||||
@echo "Running Docker container..."
|
||||
@docker run -p 8080:8080 $(BINARY_NAME):$(VERSION)
|
||||
|
||||
test-packages: ## Download test packages through gohoarder proxy (clean + vulnerable packages)
|
||||
@echo "Reading backend port from config.yaml..."
|
||||
@PORT=$$(grep "^ port:" config.yaml | awk '{print $$2}'); \
|
||||
if [ -z "$$PORT" ]; then PORT=8080; fi; \
|
||||
export GOHOARDER_URL="http://localhost:$$PORT"; \
|
||||
./script/test-packages.sh
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
@@ -0,0 +1,63 @@
|
||||
// Package commands hosts the cobra commands wired into the gohoarder CLI.
|
||||
package commands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/app"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/logger"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
configPath string
|
||||
)
|
||||
|
||||
// ServeCmd starts the HTTP server
|
||||
var ServeCmd = &cobra.Command{
|
||||
Use: "serve",
|
||||
Short: "Start the GoHoarder server",
|
||||
Long: "Start the HTTP server to serve as a package cache proxy",
|
||||
RunE: runServe,
|
||||
}
|
||||
|
||||
func init() {
|
||||
ServeCmd.Flags().StringVarP(&configPath, "config", "c", "", "Path to config file")
|
||||
}
|
||||
|
||||
func runServe(cmd *cobra.Command, args []string) error {
|
||||
// Load configuration
|
||||
cfg, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load config: %w", err)
|
||||
}
|
||||
|
||||
// Initialize logger
|
||||
if logErr := logger.Init(logger.Config{
|
||||
Level: cfg.Logging.Level,
|
||||
Format: cfg.Logging.Format,
|
||||
}); logErr != nil {
|
||||
return fmt.Errorf("failed to initialize logger: %w", logErr)
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Str("version", version.Version).
|
||||
Str("commit", version.GitCommit).
|
||||
Msg("Starting GoHoarder")
|
||||
|
||||
// Create and run application
|
||||
application, err := app.New(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create application: %w", err)
|
||||
}
|
||||
|
||||
// Run application (blocks until shutdown)
|
||||
if err := application.Run(); err != nil {
|
||||
return fmt.Errorf("application error: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
json "github.com/goccy/go-json"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
jsonOutput bool
|
||||
)
|
||||
|
||||
// VersionCmd displays version information
|
||||
var VersionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print version information",
|
||||
Long: "Display detailed version information about GoHoarder",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
info := version.Get()
|
||||
|
||||
if jsonOutput {
|
||||
data, err := json.MarshalIndent(info, "", " ")
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.OutOrStderr(), "Error: %v\n", err)
|
||||
return
|
||||
}
|
||||
_, _ = 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)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
VersionCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output version information as JSON")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/cmd/gohoarder/commands"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "gohoarder",
|
||||
Short: "Universal package cache proxy",
|
||||
Long: `GoHoarder is a universal pass-through cache proxy for package managers.
|
||||
Supports npm, pip, and Go modules with transparent caching, security scanning, and multi-backend storage.`,
|
||||
Version: version.Version,
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Add commands
|
||||
rootCmd.AddCommand(commands.ServeCmd)
|
||||
rootCmd.AddCommand(commands.VersionCmd)
|
||||
|
||||
// Set version template
|
||||
rootCmd.SetVersionTemplate(fmt.Sprintf(
|
||||
"GoHoarder %s\nGit Commit: %s\nBuilt: %s\nGo Version: %s\nPlatform: %s\n",
|
||||
version.Version,
|
||||
version.GitCommit,
|
||||
version.BuildTime,
|
||||
version.GoVersion,
|
||||
"GOOS/GOARCH",
|
||||
))
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
# GoHoarder Configuration Example
|
||||
#
|
||||
# Port Configuration:
|
||||
# - Backend server port is configured below (server.port)
|
||||
# - Frontend dev server uses frontend/.env (VITE_PORT and VITE_BACKEND_URL)
|
||||
# - When running `make run`, both will start with their configured ports
|
||||
# - The frontend automatically proxies /api and /ws requests to the backend
|
||||
|
||||
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: ""
|
||||
key_file: ""
|
||||
|
||||
storage:
|
||||
backend: "filesystem" # filesystem, s3, smb, nfs
|
||||
path: "/var/cache/gohoarder"
|
||||
|
||||
filesystem:
|
||||
base_path: "/var/cache/gohoarder"
|
||||
|
||||
s3:
|
||||
endpoint: "s3.amazonaws.com"
|
||||
region: "us-east-1"
|
||||
bucket: "gohoarder-cache"
|
||||
access_key_id: ""
|
||||
secret_access_key: ""
|
||||
use_ssl: true
|
||||
|
||||
smb:
|
||||
host: ""
|
||||
share: ""
|
||||
username: ""
|
||||
password: ""
|
||||
domain: ""
|
||||
|
||||
metadata:
|
||||
# Backend: sqlite, postgresql, mysql, mariadb, file
|
||||
#
|
||||
# Choose based on your deployment:
|
||||
# - sqlite: Single instance, local storage (NOT for network filesystems like SMB/NFS!)
|
||||
# - postgresql: Production, multiple replicas, works with any storage including SMB/NFS
|
||||
# - mysql: Production alternative to PostgreSQL
|
||||
# - file: Simple file-based metadata (limited features)
|
||||
#
|
||||
# IMPORTANT: SQLite + SMB/NFS = Database locked errors!
|
||||
# For network storage (SMB, NFS), use PostgreSQL or MySQL.
|
||||
backend: "sqlite"
|
||||
connection: "file:gohoarder.db?cache=shared&mode=rwc" # Legacy, not used with GORM
|
||||
|
||||
# SQLite configuration (for local storage only)
|
||||
# Use with local storage classes (local-path, hostPath, or RWX like longhorn)
|
||||
# DO NOT use with SMB/NFS network storage!
|
||||
sqlite:
|
||||
path: "gohoarder.db"
|
||||
wal_mode: true # Set to false for network filesystems if you must use SQLite
|
||||
|
||||
# PostgreSQL configuration (recommended for production)
|
||||
# Works with any storage including SMB/NFS
|
||||
# Supports multiple replicas and high availability
|
||||
postgresql:
|
||||
host: "localhost"
|
||||
port: 5432
|
||||
database: "gohoarder"
|
||||
user: "gohoarder"
|
||||
password: ""
|
||||
ssl_mode: "disable" # disable, require, verify-ca, verify-full
|
||||
|
||||
# MySQL/MariaDB configuration (alternative to PostgreSQL)
|
||||
# Works with any storage including SMB/NFS
|
||||
mysql:
|
||||
host: "localhost"
|
||||
port: 3306
|
||||
database: "gohoarder"
|
||||
user: "gohoarder"
|
||||
password: ""
|
||||
charset: "utf8mb4"
|
||||
parse_time: true
|
||||
|
||||
# GORM connection pool settings (applies to all database backends)
|
||||
max_open_conns: 25 # Maximum number of open connections to the database
|
||||
max_idle_conns: 5 # Maximum number of idle connections in the pool
|
||||
conn_max_lifetime: 3600 # Maximum lifetime of a connection in seconds (1 hour)
|
||||
log_level: "warn" # GORM log level: silent, error, warn, info
|
||||
|
||||
cache:
|
||||
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: # 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)
|
||||
rescan_active_window: "0s" # Rescan only packages requested within this window (e.g., 720h); 0 = all packages
|
||||
rescan_on_access: false # Rescan a cached package on download when its scan is older than rescan_interval, before serving it
|
||||
rescan_concurrency: 1 # Scans run in parallel during one rescan cycle; values below 1 mean 1
|
||||
# When a scan fails on infrastructure (timeout, upstream 5xx) the package is served and the
|
||||
# scan is retried every scan_retry_interval. Set fail_closed to refuse such packages instead.
|
||||
fail_closed: false
|
||||
# How long a first download waits for its scan before it is served (or refused with fail_closed). Default 30s.
|
||||
scan_wait_timeout: "30s"
|
||||
scan_retry_interval: "5m"
|
||||
update_db_on_startup: false # Update vulnerability databases on startup
|
||||
allowed_packages: [] # Packages that bypass security checks (format: "registry/name@version")
|
||||
ignored_cves: [] # CVE IDs to ignore globally (e.g., "CVE-2021-23337")
|
||||
|
||||
block_thresholds:
|
||||
critical: 0 # Max critical vulns (0 = block any)
|
||||
high: -1 # Max high vulns (-1 = unlimited)
|
||||
medium: -1 # Max medium vulns
|
||||
low: -1 # Max low vulns
|
||||
|
||||
scanners:
|
||||
# Trivy - Comprehensive vulnerability scanner from Aqua Security
|
||||
# Supports: containers, OS packages, language packages
|
||||
trivy:
|
||||
enabled: false
|
||||
timeout: "5m"
|
||||
cache_db: "/var/lib/trivy"
|
||||
|
||||
# OSV - Google's Open Source Vulnerabilities database
|
||||
# Supports: npm, PyPI, Go, Maven, NuGet, etc.
|
||||
osv:
|
||||
enabled: false
|
||||
api_url: "https://api.osv.dev/v1/query" # full query endpoint, not the host
|
||||
timeout: "30s"
|
||||
|
||||
# Grype - Multi-ecosystem vulnerability scanner from Anchore
|
||||
# Supports: all package types, containers, SBOMs
|
||||
grype:
|
||||
enabled: false
|
||||
timeout: "5m"
|
||||
|
||||
# govulncheck - Official Go vulnerability scanner from the Go team
|
||||
# Supports: Go modules only
|
||||
govulncheck:
|
||||
enabled: false
|
||||
timeout: "5m"
|
||||
|
||||
# npm-audit - npm's built-in vulnerability scanner
|
||||
# Supports: npm packages only
|
||||
npm_audit:
|
||||
enabled: false
|
||||
timeout: "2m"
|
||||
|
||||
# pip-audit - Python package vulnerability scanner
|
||||
# Supports: PyPI packages only
|
||||
pip_audit:
|
||||
enabled: false
|
||||
timeout: "2m"
|
||||
|
||||
# GitHub Advisory Database - GitHub's security advisory database
|
||||
# Supports: npm, pip, go, maven, nuget, cargo, pub
|
||||
# Optional: Set token for higher API rate limits (60 req/hour unauthenticated, 5000 req/hour authenticated)
|
||||
ghsa:
|
||||
enabled: false
|
||||
timeout: "30s"
|
||||
token: "" # Optional: GitHub personal access token (ghp_...)
|
||||
|
||||
# Static Analysis - Basic static analysis and package validation
|
||||
static:
|
||||
enabled: true
|
||||
max_package_size: 2147483648 # 2GB
|
||||
check_checksums: true
|
||||
block_suspicious: false
|
||||
allowed_licenses: []
|
||||
|
||||
auth:
|
||||
enabled: true
|
||||
key_expiration: "0" # Never expire (0), or duration like "8760h" for 1 year
|
||||
bcrypt_cost: 10
|
||||
audit_log: true
|
||||
|
||||
network:
|
||||
connect_timeout: "10s"
|
||||
read_timeout: "5m"
|
||||
write_timeout: "5m"
|
||||
max_idle_conns: 100
|
||||
max_conns_per_host: 10
|
||||
|
||||
rate_limit:
|
||||
per_api_key: 1000
|
||||
per_ip: 100
|
||||
burst_size: 50
|
||||
|
||||
circuit_breaker:
|
||||
threshold: 5
|
||||
timeout: "30s"
|
||||
reset_interval: "60s"
|
||||
|
||||
retry:
|
||||
max_attempts: 3
|
||||
initial_backoff: "1s"
|
||||
max_backoff: "30s"
|
||||
|
||||
logging:
|
||||
level: "info" # debug, info, warn, error
|
||||
format: "json" # json, pretty
|
||||
|
||||
handlers:
|
||||
go:
|
||||
enabled: true
|
||||
upstream_proxy: "https://proxy.golang.org"
|
||||
checksum_db: "https://sum.golang.org"
|
||||
verify_checksums: true
|
||||
|
||||
npm:
|
||||
enabled: true
|
||||
upstream_registry: "https://registry.npmjs.org"
|
||||
|
||||
pypi:
|
||||
enabled: true
|
||||
upstream_url: "https://pypi.org"
|
||||
simple_api_url: "https://pypi.org/simple"
|
||||
@@ -0,0 +1,416 @@
|
||||
# Kubernetes Deployment Guide
|
||||
|
||||
This directory contains Kubernetes manifests for deploying GoHoarder in a production environment.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Kubernetes Pod │
|
||||
│ ┌────────────────────────────────────────────────┐ │
|
||||
│ │ GoHoarder Container │ │
|
||||
│ │ ┌──────────────────────────────────────────┐ │ │
|
||||
│ │ │ Pattern-Based Credential Store │ │ │
|
||||
│ │ │ ├─ github.com/myorg/* → token_A │ │ │
|
||||
│ │ │ ├─ gitlab.com/team/* → token_B │ │ │
|
||||
│ │ │ └─ * → fallback_token │ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ └────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Mounted Volumes: │
|
||||
│ • config.yaml (ConfigMap) │
|
||||
│ • git-credentials.json (Secret) │
|
||||
│ • /var/lib/gohoarder/cache (PVC) │
|
||||
│ • /var/lib/gohoarder (PVC for metadata DB) │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
- `secret-git-credentials.yaml` - Git credentials for private repositories
|
||||
- `configmap-config.yaml` - Application configuration
|
||||
- `pvc.yaml` - Persistent volume claims for cache and metadata
|
||||
- `deployment.yaml` - Main application deployment
|
||||
- `service.yaml` - Service and optional ingress configuration
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Configure Git Credentials
|
||||
|
||||
Edit `secret-git-credentials.yaml` and replace the placeholder tokens with your actual tokens:
|
||||
|
||||
```yaml
|
||||
{
|
||||
"credentials": [
|
||||
{
|
||||
"pattern": "github.com/mycompany/*",
|
||||
"host": "github.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_YOUR_ACTUAL_TOKEN_HERE"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Pattern Matching Examples:**
|
||||
- `github.com/myorg/*` - Matches all repos under myorg
|
||||
- `github.com/myorg/specific-repo` - Matches only specific-repo
|
||||
- `gitlab.com/backend-team/*` - Matches all GitLab repos under backend-team
|
||||
- `*` - Fallback pattern (matches everything)
|
||||
|
||||
**Credential Priority:**
|
||||
1. Most specific pattern wins (longest match)
|
||||
2. Fallback credential (`"fallback": true`)
|
||||
3. System git config (if no matches)
|
||||
|
||||
### 2. Customize Configuration
|
||||
|
||||
Edit `configmap-config.yaml` to adjust:
|
||||
- Cache size (`max_size_bytes`)
|
||||
- Security scanning settings
|
||||
- Upstream registries
|
||||
- Logging level
|
||||
|
||||
### 3. Deploy to Kubernetes
|
||||
|
||||
```bash
|
||||
# Create namespace (optional)
|
||||
kubectl create namespace gohoarder
|
||||
|
||||
# Apply manifests
|
||||
kubectl apply -f pvc.yaml
|
||||
kubectl apply -f secret-git-credentials.yaml
|
||||
kubectl apply -f configmap-config.yaml
|
||||
kubectl apply -f deployment.yaml
|
||||
kubectl apply -f service.yaml
|
||||
|
||||
# Verify deployment
|
||||
kubectl get pods -l app=gohoarder
|
||||
kubectl logs -l app=gohoarder -f
|
||||
```
|
||||
|
||||
### 4. Configure Go Client
|
||||
|
||||
```bash
|
||||
# Set GOPROXY environment variable
|
||||
export GOPROXY=http://gohoarder.default.svc.cluster.local:8080/go,direct
|
||||
|
||||
# Or in your Dockerfile
|
||||
ENV GOPROXY=http://gohoarder.default.svc.cluster.local:8080/go,direct
|
||||
|
||||
# Test with a private module
|
||||
go get github.com/mycompany/private-module@latest
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Using External Secrets Operator (ESO)
|
||||
|
||||
If you're using External Secrets Operator, uncomment the ExternalSecret section in `secret-git-credentials.yaml` and configure your SecretStore:
|
||||
|
||||
```yaml
|
||||
apiVersion: external-secrets.io/v1beta1
|
||||
kind: ExternalSecret
|
||||
metadata:
|
||||
name: gohoarder-git-credentials
|
||||
spec:
|
||||
refreshInterval: 1h
|
||||
secretStoreRef:
|
||||
name: vault-backend
|
||||
kind: SecretStore
|
||||
target:
|
||||
name: gohoarder-git-credentials
|
||||
data:
|
||||
- secretKey: credentials.json
|
||||
remoteRef:
|
||||
key: secret/gohoarder/git-credentials
|
||||
```
|
||||
|
||||
### Storage Classes
|
||||
|
||||
For production deployments, specify appropriate storage classes:
|
||||
|
||||
```yaml
|
||||
# In pvc.yaml
|
||||
storageClassName: fast-ssd # For cache (needs fast I/O)
|
||||
storageClassName: standard # For metadata (smaller, less critical)
|
||||
```
|
||||
|
||||
### Horizontal Pod Autoscaling
|
||||
|
||||
```bash
|
||||
kubectl autoscale deployment gohoarder \
|
||||
--cpu-percent=70 \
|
||||
--min=2 \
|
||||
--max=10
|
||||
```
|
||||
|
||||
### Monitoring
|
||||
|
||||
Check health and metrics:
|
||||
|
||||
```bash
|
||||
# Health check
|
||||
kubectl port-forward svc/gohoarder 8080:8080
|
||||
curl http://localhost:8080/health
|
||||
|
||||
# Metrics (Prometheus format)
|
||||
curl http://localhost:8080/metrics
|
||||
```
|
||||
|
||||
## Multi-Organization Setup
|
||||
|
||||
### Example 1: Multiple GitHub Organizations
|
||||
|
||||
```json
|
||||
{
|
||||
"credentials": [
|
||||
{
|
||||
"pattern": "github.com/company-frontend/*",
|
||||
"host": "github.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_frontend_team_token"
|
||||
},
|
||||
{
|
||||
"pattern": "github.com/company-backend/*",
|
||||
"host": "github.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_backend_team_token"
|
||||
},
|
||||
{
|
||||
"pattern": "github.com/company-infra/*",
|
||||
"host": "github.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_infra_team_token"
|
||||
},
|
||||
{
|
||||
"pattern": "*",
|
||||
"host": "*",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_readonly_default_token",
|
||||
"fallback": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Example 2: GitHub + GitLab
|
||||
|
||||
```json
|
||||
{
|
||||
"credentials": [
|
||||
{
|
||||
"pattern": "github.com/myorg/*",
|
||||
"host": "github.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_github_token"
|
||||
},
|
||||
{
|
||||
"pattern": "gitlab.com/myteam/*",
|
||||
"host": "gitlab.com",
|
||||
"username": "oauth2",
|
||||
"token": "glpat_gitlab_token"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Example 3: Enterprise GitHub
|
||||
|
||||
```json
|
||||
{
|
||||
"credentials": [
|
||||
{
|
||||
"pattern": "github.enterprise.com/engineering/*",
|
||||
"host": "github.enterprise.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_enterprise_token"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Token Scoping**: Use fine-grained personal access tokens with minimal permissions
|
||||
- GitHub: Only `repo` scope needed for private repos
|
||||
- GitLab: Only `read_repository` scope needed
|
||||
|
||||
2. **Secret Rotation**: Regularly rotate tokens
|
||||
```bash
|
||||
# Update secret
|
||||
kubectl create secret generic gohoarder-git-credentials \
|
||||
--from-file=credentials.json=./new-credentials.json \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
|
||||
# Restart pods to pick up new credentials
|
||||
kubectl rollout restart deployment gohoarder
|
||||
```
|
||||
|
||||
3. **RBAC**: Limit who can read the secret
|
||||
```bash
|
||||
kubectl create role secret-reader \
|
||||
--verb=get,list \
|
||||
--resource=secrets \
|
||||
--resource-name=gohoarder-git-credentials
|
||||
```
|
||||
|
||||
4. **Audit Logging**: Enable Kubernetes audit logging for secret access
|
||||
|
||||
5. **Network Policies**: Restrict which pods can access GoHoarder
|
||||
```yaml
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: allow-from-build-namespace
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app: gohoarder
|
||||
ingress:
|
||||
- from:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
name: build-namespace
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Check if credentials are loaded
|
||||
|
||||
```bash
|
||||
# Check logs for credential loading
|
||||
kubectl logs -l app=gohoarder | grep "Loaded git credentials"
|
||||
|
||||
# Expected output:
|
||||
# {"level":"info","file":"/etc/gohoarder/git-credentials.json","credentials":3,"message":"Loaded git credentials from file"}
|
||||
# {"level":"debug","pattern":"github.com/myorg/*","host":"github.com","message":"Registered credential pattern"}
|
||||
```
|
||||
|
||||
### Test credential pattern matching
|
||||
|
||||
```bash
|
||||
# Enable debug logging
|
||||
kubectl set env deployment/gohoarder LOG_LEVEL=debug
|
||||
|
||||
# Watch logs during a go get request
|
||||
kubectl logs -l app=gohoarder -f
|
||||
```
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Issue**: `git clone failed: authentication required`
|
||||
- **Cause**: No matching credential pattern
|
||||
- **Solution**: Check pattern syntax in credentials.json, ensure it matches the module path
|
||||
|
||||
**Issue**: `Failed to load git credentials`
|
||||
- **Cause**: Secret not mounted or JSON syntax error
|
||||
- **Solution**: Verify secret exists and JSON is valid
|
||||
```bash
|
||||
kubectl get secret gohoarder-git-credentials
|
||||
kubectl get secret gohoarder-git-credentials -o jsonpath='{.data.credentials\.json}' | base64 -d | jq .
|
||||
```
|
||||
|
||||
**Issue**: Module fetch slow
|
||||
- **Cause**: Git clone timeout or large repository
|
||||
- **Solution**: Increase timeout in config.yaml or use upstream proxy for public modules
|
||||
|
||||
## Performance Tuning
|
||||
|
||||
### Cache Configuration
|
||||
|
||||
```yaml
|
||||
cache:
|
||||
max_size_bytes: 107374182400 # 100GB for large organizations
|
||||
default_ttl: 168h # 7 days for stable modules
|
||||
```
|
||||
|
||||
### Resource Limits
|
||||
|
||||
For high-traffic deployments:
|
||||
|
||||
```yaml
|
||||
resources:
|
||||
requests:
|
||||
memory: "2Gi"
|
||||
cpu: "1000m"
|
||||
limits:
|
||||
memory: "8Gi"
|
||||
cpu: "4000m"
|
||||
```
|
||||
|
||||
### Replicas
|
||||
|
||||
Run multiple replicas for high availability:
|
||||
|
||||
```yaml
|
||||
spec:
|
||||
replicas: 3
|
||||
```
|
||||
|
||||
## Backup and Recovery
|
||||
|
||||
### Backup Metadata Database
|
||||
|
||||
```bash
|
||||
# Backup SQLite database
|
||||
kubectl exec -it deployment/gohoarder -- \
|
||||
sqlite3 /var/lib/gohoarder/gohoarder.db ".backup /tmp/backup.db"
|
||||
|
||||
kubectl cp gohoarder-pod:/tmp/backup.db ./gohoarder-backup-$(date +%Y%m%d).db
|
||||
```
|
||||
|
||||
### Restore from Backup
|
||||
|
||||
```bash
|
||||
kubectl cp ./gohoarder-backup-20260102.db gohoarder-pod:/var/lib/gohoarder/gohoarder.db
|
||||
kubectl rollout restart deployment gohoarder
|
||||
```
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### CI/CD Pipeline (GitHub Actions)
|
||||
|
||||
```yaml
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.21'
|
||||
|
||||
- name: Configure GOPROXY
|
||||
run: |
|
||||
echo "GOPROXY=http://gohoarder.company.internal:8080/go,direct" >> $GITHUB_ENV
|
||||
|
||||
- name: Build
|
||||
run: go build ./...
|
||||
```
|
||||
|
||||
### Dockerfile
|
||||
|
||||
```dockerfile
|
||||
FROM golang:1.21-alpine
|
||||
|
||||
# Configure proxy
|
||||
ENV GOPROXY=http://gohoarder.default.svc.cluster.local:8080/go,direct
|
||||
ENV GONOPROXY=none
|
||||
ENV GONOSUMDB=github.com/yourcompany
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN go build -o myapp ./cmd/myapp
|
||||
|
||||
CMD ["/app/myapp"]
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
For issues or questions:
|
||||
- Check logs: `kubectl logs -l app=gohoarder`
|
||||
- Enable debug logging: Set `logging.level: debug` in ConfigMap
|
||||
- Review credential patterns in Secret
|
||||
@@ -0,0 +1,58 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: gohoarder-config
|
||||
namespace: default
|
||||
data:
|
||||
config.yaml: |
|
||||
server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080
|
||||
read_timeout: 30s
|
||||
write_timeout: 30s
|
||||
|
||||
cache:
|
||||
max_size_bytes: 10737418240 # 10GB
|
||||
default_ttl: 24h
|
||||
cleanup_interval: 1h
|
||||
|
||||
storage:
|
||||
backend: filesystem
|
||||
path: /var/lib/gohoarder/cache
|
||||
|
||||
metadata:
|
||||
backend: sqlite
|
||||
connection: /var/lib/gohoarder/gohoarder.db
|
||||
|
||||
security:
|
||||
enabled: true
|
||||
providers:
|
||||
- osv
|
||||
- github
|
||||
severity_threshold: medium
|
||||
block_on_vulnerability: false
|
||||
rescan_interval: 24h
|
||||
rescan_active_window: 0s
|
||||
rescan_concurrency: 1
|
||||
rescan_on_access: false
|
||||
scan_wait_timeout: 30s
|
||||
|
||||
handlers:
|
||||
npm:
|
||||
enabled: true
|
||||
upstream_registry: "https://registry.npmjs.org"
|
||||
|
||||
pypi:
|
||||
enabled: true
|
||||
upstream_index: "https://pypi.org/simple"
|
||||
|
||||
go:
|
||||
enabled: true
|
||||
upstream_proxy: "https://proxy.golang.org"
|
||||
checksum_db: "https://sum.golang.org"
|
||||
# Path to git credentials file (mounted from Secret)
|
||||
git_credentials_file: /etc/gohoarder/git-credentials.json
|
||||
|
||||
logging:
|
||||
level: info
|
||||
format: json
|
||||
@@ -0,0 +1,428 @@
|
||||
# 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
|
||||
# kubectl apply -f deployment-all-in-one.yaml -n gohoarder
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Kubernetes 1.19+
|
||||
# - Ingress controller (nginx, traefik, etc.)
|
||||
# - Persistent volume provisioner
|
||||
# - Optional: cert-manager for TLS certificates
|
||||
|
||||
---
|
||||
# Namespace
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: namespace
|
||||
|
||||
---
|
||||
# ConfigMap for application configuration
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: gohoarder-config
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: config
|
||||
data:
|
||||
# Add your configuration here or mount from a file
|
||||
# config.yaml: |
|
||||
# server:
|
||||
# port: 8080
|
||||
# ...
|
||||
|
||||
---
|
||||
# PersistentVolumeClaim for cache storage
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: gohoarder-cache
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: storage
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteMany # Multiple pods can access for scanner + server
|
||||
resources:
|
||||
requests:
|
||||
storage: 100Gi
|
||||
# storageClassName: your-storage-class # Specify your storage class
|
||||
|
||||
---
|
||||
# PersistentVolumeClaim for metadata storage
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: gohoarder-metadata
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: storage
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 10Gi
|
||||
# storageClassName: your-storage-class
|
||||
|
||||
---
|
||||
# Deployment - Application Server
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: gohoarder-server
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: server
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: server
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: server
|
||||
spec:
|
||||
containers:
|
||||
- name: server
|
||||
image: ghcr.io/lukaszraczylo/gohoarder-server:latest
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 8080
|
||||
protocol: TCP
|
||||
- name: metrics
|
||||
containerPort: 9090
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: CONFIG_FILE
|
||||
value: /config/config.yaml
|
||||
- name: STORAGE_BACKEND
|
||||
value: filesystem
|
||||
- name: STORAGE_PATH
|
||||
value: /data/cache
|
||||
- name: DB_PATH
|
||||
value: /data/metadata/gohoarder.db
|
||||
- name: LOG_LEVEL
|
||||
value: info
|
||||
- name: LOG_FORMAT
|
||||
value: json
|
||||
volumeMounts:
|
||||
- name: cache
|
||||
mountPath: /data/cache
|
||||
- name: metadata
|
||||
mountPath: /data/metadata
|
||||
- name: config
|
||||
mountPath: /config
|
||||
readOnly: true
|
||||
livenessProbe:
|
||||
exec:
|
||||
command:
|
||||
- /usr/local/bin/gohoarder
|
||||
- version
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 30
|
||||
timeoutSeconds: 10
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: 8080
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests:
|
||||
cpu: 500m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
cpu: 2000m
|
||||
memory: 2Gi
|
||||
volumes:
|
||||
- name: cache
|
||||
persistentVolumeClaim:
|
||||
claimName: gohoarder-cache
|
||||
- name: metadata
|
||||
persistentVolumeClaim:
|
||||
claimName: gohoarder-metadata
|
||||
- name: config
|
||||
configMap:
|
||||
name: gohoarder-config
|
||||
|
||||
---
|
||||
# Service - Application Server
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: gohoarder-server
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: server
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: 8080
|
||||
targetPort: http
|
||||
protocol: TCP
|
||||
- name: metrics
|
||||
port: 9090
|
||||
targetPort: metrics
|
||||
protocol: TCP
|
||||
selector:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: server
|
||||
|
||||
---
|
||||
# Deployment - Frontend
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: gohoarder-frontend
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: frontend
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
containers:
|
||||
- name: frontend
|
||||
image: ghcr.io/lukaszraczylo/gohoarder-frontend:latest
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 80
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: API_BASE_URL
|
||||
value: /api
|
||||
- name: APP_VERSION
|
||||
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: /
|
||||
port: 80
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 30
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /
|
||||
port: 80
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 256Mi
|
||||
|
||||
---
|
||||
# Service - Frontend
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: gohoarder-frontend
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: http
|
||||
protocol: TCP
|
||||
selector:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: frontend
|
||||
|
||||
---
|
||||
# Deployment - Scanner (Optional)
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: gohoarder-scanner
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: scanner
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: scanner
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: scanner
|
||||
spec:
|
||||
containers:
|
||||
- name: scanner
|
||||
image: ghcr.io/lukaszraczylo/gohoarder-scanner:latest
|
||||
imagePullPolicy: Always
|
||||
env:
|
||||
- name: CONFIG_FILE
|
||||
value: /config/config.yaml
|
||||
- name: SCANNER_MODE
|
||||
value: "true"
|
||||
- name: SCANNER_WORKERS
|
||||
value: "4"
|
||||
- name: LOG_LEVEL
|
||||
value: info
|
||||
volumeMounts:
|
||||
- name: cache
|
||||
mountPath: /data/cache
|
||||
readOnly: true
|
||||
- name: metadata
|
||||
mountPath: /data/metadata
|
||||
- name: config
|
||||
mountPath: /config
|
||||
readOnly: true
|
||||
resources:
|
||||
requests:
|
||||
cpu: 500m
|
||||
memory: 1Gi
|
||||
limits:
|
||||
cpu: 2000m
|
||||
memory: 4Gi
|
||||
volumes:
|
||||
- name: cache
|
||||
persistentVolumeClaim:
|
||||
claimName: gohoarder-cache
|
||||
- name: metadata
|
||||
persistentVolumeClaim:
|
||||
claimName: gohoarder-metadata
|
||||
- name: config
|
||||
configMap:
|
||||
name: gohoarder-config
|
||||
|
||||
---
|
||||
# Ingress - Expose via domain
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: gohoarder
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: ingress
|
||||
annotations:
|
||||
# Nginx ingress annotations
|
||||
nginx.ingress.kubernetes.io/proxy-body-size: "500m"
|
||||
nginx.ingress.kubernetes.io/proxy-read-timeout: "600"
|
||||
nginx.ingress.kubernetes.io/proxy-send-timeout: "600"
|
||||
# Enable CORS if needed
|
||||
# nginx.ingress.kubernetes.io/enable-cors: "true"
|
||||
# TLS/SSL configuration (uncomment if using cert-manager)
|
||||
# cert-manager.io/cluster-issuer: "letsencrypt-prod"
|
||||
spec:
|
||||
ingressClassName: nginx # Adjust based on your ingress controller
|
||||
rules:
|
||||
- host: hoarder.i.raczylo.com
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: gohoarder-frontend
|
||||
port:
|
||||
number: 80
|
||||
# Uncomment for HTTPS/TLS
|
||||
# tls:
|
||||
# - hosts:
|
||||
# - hoarder.i.raczylo.com
|
||||
# secretName: gohoarder-tls
|
||||
|
||||
---
|
||||
# HorizontalPodAutoscaler - Server
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
metadata:
|
||||
name: gohoarder-server
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: server
|
||||
spec:
|
||||
scaleTargetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: gohoarder-server
|
||||
minReplicas: 2
|
||||
maxReplicas: 10
|
||||
metrics:
|
||||
- type: Resource
|
||||
resource:
|
||||
name: cpu
|
||||
target:
|
||||
type: Utilization
|
||||
averageUtilization: 70
|
||||
- type: Resource
|
||||
resource:
|
||||
name: memory
|
||||
target:
|
||||
type: Utilization
|
||||
averageUtilization: 80
|
||||
|
||||
---
|
||||
# HorizontalPodAutoscaler - Frontend
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
metadata:
|
||||
name: gohoarder-frontend
|
||||
namespace: gohoarder
|
||||
labels:
|
||||
app.kubernetes.io/name: gohoarder
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
scaleTargetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: gohoarder-frontend
|
||||
minReplicas: 2
|
||||
maxReplicas: 10
|
||||
metrics:
|
||||
- type: Resource
|
||||
resource:
|
||||
name: cpu
|
||||
target:
|
||||
type: Utilization
|
||||
averageUtilization: 70
|
||||
@@ -0,0 +1,104 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: gohoarder
|
||||
namespace: default
|
||||
labels:
|
||||
app: gohoarder
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app: gohoarder
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: gohoarder
|
||||
spec:
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 1000
|
||||
fsGroup: 1000
|
||||
|
||||
containers:
|
||||
- name: gohoarder
|
||||
image: gohoarder:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 8080
|
||||
protocol: TCP
|
||||
|
||||
env:
|
||||
- name: CONFIG_FILE
|
||||
value: /etc/gohoarder/config.yaml
|
||||
|
||||
volumeMounts:
|
||||
# Configuration file
|
||||
- name: config
|
||||
mountPath: /etc/gohoarder/config.yaml
|
||||
subPath: config.yaml
|
||||
readOnly: true
|
||||
|
||||
# Git credentials (pattern-based)
|
||||
- name: git-credentials
|
||||
mountPath: /etc/gohoarder/git-credentials.json
|
||||
subPath: credentials.json
|
||||
readOnly: true
|
||||
|
||||
# Persistent storage for cache
|
||||
- name: cache
|
||||
mountPath: /var/lib/gohoarder/cache
|
||||
|
||||
# Persistent storage for metadata database
|
||||
- name: metadata
|
||||
mountPath: /var/lib/gohoarder
|
||||
|
||||
resources:
|
||||
requests:
|
||||
memory: "512Mi"
|
||||
cpu: "250m"
|
||||
limits:
|
||||
memory: "2Gi"
|
||||
cpu: "1000m"
|
||||
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 30
|
||||
timeoutSeconds: 5
|
||||
failureThreshold: 3
|
||||
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health/ready
|
||||
port: http
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 3
|
||||
|
||||
volumes:
|
||||
# ConfigMap with application configuration
|
||||
- name: config
|
||||
configMap:
|
||||
name: gohoarder-config
|
||||
|
||||
# Secret with git credentials
|
||||
- name: git-credentials
|
||||
secret:
|
||||
secretName: gohoarder-git-credentials
|
||||
defaultMode: 0400 # Read-only for owner
|
||||
|
||||
# PersistentVolumeClaim for cache
|
||||
- name: cache
|
||||
persistentVolumeClaim:
|
||||
claimName: gohoarder-cache-pvc
|
||||
|
||||
# PersistentVolumeClaim for metadata
|
||||
- name: metadata
|
||||
persistentVolumeClaim:
|
||||
claimName: gohoarder-metadata-pvc
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: gohoarder-cache-pvc
|
||||
namespace: default
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 20Gi
|
||||
# Uncomment and set your storage class if needed
|
||||
# storageClassName: fast-ssd
|
||||
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: gohoarder-metadata-pvc
|
||||
namespace: default
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 5Gi
|
||||
# Uncomment and set your storage class if needed
|
||||
# storageClassName: standard
|
||||
@@ -0,0 +1,61 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: gohoarder-git-credentials
|
||||
namespace: default
|
||||
type: Opaque
|
||||
stringData:
|
||||
credentials.json: |
|
||||
{
|
||||
"credentials": [
|
||||
{
|
||||
"pattern": "github.com/mycompany/*",
|
||||
"host": "github.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_REPLACE_WITH_YOUR_GITHUB_TOKEN",
|
||||
"fallback": false
|
||||
},
|
||||
{
|
||||
"pattern": "github.com/external-vendor/*",
|
||||
"host": "github.com",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_REPLACE_WITH_VENDOR_TOKEN",
|
||||
"fallback": false
|
||||
},
|
||||
{
|
||||
"pattern": "gitlab.com/backend-team/*",
|
||||
"host": "gitlab.com",
|
||||
"username": "oauth2",
|
||||
"token": "glpat_REPLACE_WITH_GITLAB_TOKEN",
|
||||
"fallback": false
|
||||
},
|
||||
{
|
||||
"pattern": "*",
|
||||
"host": "*",
|
||||
"username": "oauth2",
|
||||
"token": "ghp_REPLACE_WITH_DEFAULT_READONLY_TOKEN",
|
||||
"fallback": true
|
||||
}
|
||||
]
|
||||
}
|
||||
---
|
||||
# Example using External Secrets Operator (ESO)
|
||||
# Uncomment and configure if you're using ESO
|
||||
# apiVersion: external-secrets.io/v1beta1
|
||||
# kind: ExternalSecret
|
||||
# metadata:
|
||||
# name: gohoarder-git-credentials
|
||||
# namespace: default
|
||||
# spec:
|
||||
# refreshInterval: 1h
|
||||
# secretStoreRef:
|
||||
# name: vault-backend # Your SecretStore name
|
||||
# kind: SecretStore
|
||||
# target:
|
||||
# name: gohoarder-git-credentials
|
||||
# creationPolicy: Owner
|
||||
# data:
|
||||
# - secretKey: credentials.json
|
||||
# remoteRef:
|
||||
# key: secret/gohoarder/git-credentials
|
||||
# property: credentials.json
|
||||
@@ -0,0 +1,44 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: gohoarder
|
||||
namespace: default
|
||||
labels:
|
||||
app: gohoarder
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- port: 8080
|
||||
targetPort: http
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
app: gohoarder
|
||||
---
|
||||
# Optional: Ingress for external access
|
||||
# Uncomment and configure based on your ingress controller
|
||||
# apiVersion: networking.k8s.io/v1
|
||||
# kind: Ingress
|
||||
# metadata:
|
||||
# name: gohoarder
|
||||
# namespace: default
|
||||
# annotations:
|
||||
# nginx.ingress.kubernetes.io/proxy-body-size: "500m"
|
||||
# nginx.ingress.kubernetes.io/proxy-read-timeout: "600"
|
||||
# spec:
|
||||
# ingressClassName: nginx
|
||||
# rules:
|
||||
# - host: gohoarder.example.com
|
||||
# http:
|
||||
# paths:
|
||||
# - path: /
|
||||
# pathType: Prefix
|
||||
# backend:
|
||||
# service:
|
||||
# name: gohoarder
|
||||
# port:
|
||||
# name: http
|
||||
# tls:
|
||||
# - hosts:
|
||||
# - gohoarder.example.com
|
||||
# secretName: gohoarder-tls
|
||||
@@ -0,0 +1,127 @@
|
||||
version: '3.8'
|
||||
|
||||
# GoHoarder - Unified Deployment Example
|
||||
# This docker-compose file demonstrates deploying all GoHoarder services
|
||||
# The frontend includes integrated reverse proxy to the backend
|
||||
|
||||
services:
|
||||
# Backend - Main application server
|
||||
gohoarder-server:
|
||||
image: ghcr.io/lukaszraczylo/gohoarder-server:latest
|
||||
container_name: gohoarder-server
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
# Application configuration
|
||||
- CONFIG_FILE=/config/config.yaml
|
||||
# Database
|
||||
- DB_PATH=/data/metadata/gohoarder.db
|
||||
# Storage
|
||||
- STORAGE_BACKEND=filesystem
|
||||
- STORAGE_PATH=/data/cache
|
||||
# Security scanning
|
||||
- ENABLE_SCANNING=true
|
||||
- SCAN_ON_DOWNLOAD=true
|
||||
# Logging
|
||||
- LOG_LEVEL=info
|
||||
- LOG_FORMAT=json
|
||||
volumes:
|
||||
# Configuration
|
||||
- ./config.yaml:/config/config.yaml:ro
|
||||
# Data persistence
|
||||
- gohoarder-cache:/data/cache
|
||||
- gohoarder-metadata:/data/metadata
|
||||
networks:
|
||||
- gohoarder-internal
|
||||
healthcheck:
|
||||
test: ["CMD", "/usr/local/bin/gohoarder", "version"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
|
||||
# Frontend - Web dashboard with integrated reverse proxy
|
||||
gohoarder-frontend:
|
||||
image: ghcr.io/lukaszraczylo/gohoarder-frontend:latest
|
||||
container_name: gohoarder-frontend
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
# Runtime configuration - injected into /config.js
|
||||
- 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
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
|
||||
# Scanner - Background vulnerability scanner (optional)
|
||||
gohoarder-scanner:
|
||||
image: ghcr.io/lukaszraczylo/gohoarder-scanner:latest
|
||||
container_name: gohoarder-scanner
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- CONFIG_FILE=/config/config.yaml
|
||||
- SCANNER_MODE=true
|
||||
- SCANNER_WORKERS=4
|
||||
- SCANNER_INTERVAL=300
|
||||
- LOG_LEVEL=info
|
||||
volumes:
|
||||
- ./config.yaml:/config/config.yaml:ro
|
||||
- gohoarder-cache:/data/cache:ro
|
||||
- gohoarder-metadata:/data/metadata
|
||||
networks:
|
||||
- gohoarder-internal
|
||||
depends_on:
|
||||
- gohoarder-server
|
||||
# Uncomment if you want to run scanner separately
|
||||
# If commented out, scanning happens inline in the server
|
||||
# profiles:
|
||||
# - scanner
|
||||
|
||||
networks:
|
||||
gohoarder-internal:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
# Persistent storage for cached packages
|
||||
gohoarder-cache:
|
||||
driver: local
|
||||
# Persistent storage for metadata and scan results
|
||||
gohoarder-metadata:
|
||||
driver: local
|
||||
|
||||
# Usage:
|
||||
# 1. Copy this file: cp docker-compose.example.yaml docker-compose.yaml
|
||||
# 2. Copy config: cp config.yaml.example config.yaml
|
||||
# 3. Edit config.yaml with your settings
|
||||
# 4. Start services: docker-compose up -d
|
||||
# 5. View logs: docker-compose logs -f
|
||||
# 6. Stop services: docker-compose down
|
||||
#
|
||||
# Access:
|
||||
# - Web UI: http://localhost or http://hoarder.i.raczylo.com
|
||||
# - API: http://localhost/api or http://hoarder.i.raczylo.com/api
|
||||
# - Health: http://localhost/health
|
||||
# - Metrics: http://localhost/metrics
|
||||
#
|
||||
# For production:
|
||||
# - Enable HTTPS in the frontend container (add SSL certificates to nginx)
|
||||
# - Set up proper SSL certificates
|
||||
# - Configure firewall rules
|
||||
# - Set appropriate resource limits
|
||||
# - Enable monitoring and alerting
|
||||
-12650
File diff suppressed because it is too large
Load Diff
@@ -1,281 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes" />
|
||||
<style>
|
||||
html {
|
||||
font-family: BlinkMacSystemFont,-apple-system,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,"Fira Sans","Droid Sans","Helvetica Neue",Helvetica,Arial,sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
background-color: #fff;
|
||||
font-size: 16px;
|
||||
}
|
||||
body {
|
||||
color: #4a4a4a;
|
||||
margin: 8px;
|
||||
font-size: 1em;
|
||||
font-weight: 400;
|
||||
}
|
||||
header {
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
main {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
a {
|
||||
color: #3273dc;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
}
|
||||
a:hover {
|
||||
color: #000;
|
||||
}
|
||||
button {
|
||||
color: #fff;
|
||||
background-color: #3298dc;
|
||||
border-color: transparent;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #2793da;
|
||||
flex: none;
|
||||
}
|
||||
.spacer {
|
||||
flex: auto;
|
||||
}
|
||||
.small {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
footer {
|
||||
margin-top: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.header-label {
|
||||
margin-right: 4px;
|
||||
}
|
||||
.benchmark-set {
|
||||
margin: 8px 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.benchmark-title {
|
||||
font-size: 3rem;
|
||||
font-weight: 600;
|
||||
word-break: break-word;
|
||||
text-align: center;
|
||||
}
|
||||
.benchmark-graphs {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
width: 100%;
|
||||
}
|
||||
.benchmark-chart {
|
||||
max-width: 1000px;
|
||||
}
|
||||
</style>
|
||||
<title>Benchmarks</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header id="header">
|
||||
<div class="header-item">
|
||||
<strong class="header-label">Last Update:</strong>
|
||||
<span id="last-update"></span>
|
||||
</div>
|
||||
<div class="header-item">
|
||||
<strong class="header-label">Repository:</strong>
|
||||
<a id="repository-link" rel="noopener"></a>
|
||||
</div>
|
||||
</header>
|
||||
<main id="main"></main>
|
||||
<footer>
|
||||
<button id="dl-button">Download data as JSON</button>
|
||||
<div class="spacer"></div>
|
||||
<div class="small">Powered by <a rel="noopener" href="https://github.com/marketplace/actions/continuous-benchmark">github-action-benchmark</a></div>
|
||||
</footer>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
|
||||
<script src="data.js"></script>
|
||||
<script id="main-script">
|
||||
'use strict';
|
||||
(function() {
|
||||
// Colors from https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
|
||||
const toolColors = {
|
||||
cargo: '#dea584',
|
||||
go: '#00add8',
|
||||
benchmarkjs: '#f1e05a',
|
||||
benchmarkluau: '#000080',
|
||||
pytest: '#3572a5',
|
||||
googlecpp: '#f34b7d',
|
||||
catch2: '#f34b7d',
|
||||
julia: '#a270ba',
|
||||
jmh: '#b07219',
|
||||
benchmarkdotnet: '#178600',
|
||||
customBiggerIsBetter: '#38ff38',
|
||||
customSmallerIsBetter: '#ff3838',
|
||||
_: '#333333'
|
||||
};
|
||||
|
||||
function init() {
|
||||
function collectBenchesPerTestCase(entries) {
|
||||
const map = new Map();
|
||||
for (const entry of entries) {
|
||||
const {commit, date, tool, benches} = entry;
|
||||
for (const bench of benches) {
|
||||
const result = { commit, date, tool, bench };
|
||||
const arr = map.get(bench.name);
|
||||
if (arr === undefined) {
|
||||
map.set(bench.name, [result]);
|
||||
} else {
|
||||
arr.push(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
const data = window.BENCHMARK_DATA;
|
||||
|
||||
// Render header
|
||||
document.getElementById('last-update').textContent = new Date(data.lastUpdate).toString();
|
||||
const repoLink = document.getElementById('repository-link');
|
||||
repoLink.href = data.repoUrl;
|
||||
repoLink.textContent = data.repoUrl;
|
||||
|
||||
// Render footer
|
||||
document.getElementById('dl-button').onclick = () => {
|
||||
const dataUrl = 'data:,' + JSON.stringify(data, null, 2);
|
||||
const a = document.createElement('a');
|
||||
a.href = dataUrl;
|
||||
a.download = 'benchmark_data.json';
|
||||
a.click();
|
||||
};
|
||||
|
||||
// Prepare data points for charts
|
||||
return Object.keys(data.entries).map(name => ({
|
||||
name,
|
||||
dataSet: collectBenchesPerTestCase(data.entries[name]),
|
||||
}));
|
||||
}
|
||||
|
||||
function renderAllChars(dataSets) {
|
||||
|
||||
function renderGraph(parent, name, dataset) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.className = 'benchmark-chart';
|
||||
parent.appendChild(canvas);
|
||||
|
||||
const color = toolColors[dataset.length > 0 ? dataset[0].tool : '_'];
|
||||
const data = {
|
||||
labels: dataset.map(d => d.commit.id.slice(0, 7)),
|
||||
datasets: [
|
||||
{
|
||||
label: name,
|
||||
data: dataset.map(d => d.bench.value),
|
||||
borderColor: color,
|
||||
backgroundColor: color + '60', // Add alpha for #rrggbbaa
|
||||
}
|
||||
],
|
||||
};
|
||||
const options = {
|
||||
scales: {
|
||||
xAxes: [
|
||||
{
|
||||
scaleLabel: {
|
||||
display: true,
|
||||
labelString: 'commit',
|
||||
},
|
||||
}
|
||||
],
|
||||
yAxes: [
|
||||
{
|
||||
scaleLabel: {
|
||||
display: true,
|
||||
labelString: dataset.length > 0 ? dataset[0].bench.unit : '',
|
||||
},
|
||||
ticks: {
|
||||
beginAtZero: true,
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
tooltips: {
|
||||
callbacks: {
|
||||
afterTitle: items => {
|
||||
const {index} = items[0];
|
||||
const data = dataset[index];
|
||||
return '\n' + data.commit.message + '\n\n' + data.commit.timestamp + ' committed by @' + data.commit.committer.username + '\n';
|
||||
},
|
||||
label: item => {
|
||||
let label = item.value;
|
||||
const { range, unit } = dataset[item.index].bench;
|
||||
label += ' ' + unit;
|
||||
if (range) {
|
||||
label += ' (' + range + ')';
|
||||
}
|
||||
return label;
|
||||
},
|
||||
afterLabel: item => {
|
||||
const { extra } = dataset[item.index].bench;
|
||||
return extra ? '\n' + extra : '';
|
||||
}
|
||||
}
|
||||
},
|
||||
onClick: (_mouseEvent, activeElems) => {
|
||||
if (activeElems.length === 0) {
|
||||
return;
|
||||
}
|
||||
// XXX: Undocumented. How can we know the index?
|
||||
const index = activeElems[0]._index;
|
||||
const url = dataset[index].commit.url;
|
||||
window.open(url, '_blank');
|
||||
},
|
||||
};
|
||||
|
||||
new Chart(canvas, {
|
||||
type: 'line',
|
||||
data,
|
||||
options,
|
||||
});
|
||||
}
|
||||
|
||||
function renderBenchSet(name, benchSet, main) {
|
||||
const setElem = document.createElement('div');
|
||||
setElem.className = 'benchmark-set';
|
||||
main.appendChild(setElem);
|
||||
|
||||
const nameElem = document.createElement('h1');
|
||||
nameElem.className = 'benchmark-title';
|
||||
nameElem.textContent = name;
|
||||
setElem.appendChild(nameElem);
|
||||
|
||||
const graphsElem = document.createElement('div');
|
||||
graphsElem.className = 'benchmark-graphs';
|
||||
setElem.appendChild(graphsElem);
|
||||
|
||||
for (const [benchName, benches] of benchSet.entries()) {
|
||||
renderGraph(graphsElem, benchName, benches)
|
||||
}
|
||||
}
|
||||
|
||||
const main = document.getElementById('main');
|
||||
for (const {name, dataSet} of dataSets) {
|
||||
renderBenchSet(name, dataSet, main);
|
||||
}
|
||||
}
|
||||
|
||||
renderAllChars(init()); // Start
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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
|
||||
@@ -0,0 +1,10 @@
|
||||
# Backend API URL (used by Vite dev server proxy)
|
||||
# Change this if your gohoarder backend is running on a different port
|
||||
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"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-style="workbench">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<link rel="icon" href="data:," />
|
||||
<title>GoHoarder dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "gohoarder-dashboard",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"sources": "node scripts/library-sources.mjs --write"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/ibm-plex-mono": "5.3.0",
|
||||
"@fontsource/ibm-plex-sans": "5.3.0",
|
||||
"@fortawesome/free-solid-svg-icons": "7.3.1",
|
||||
"@perfect-design/ui": "0.3.11",
|
||||
"axios": "^1.20.0",
|
||||
"pinia": "^4.0.0",
|
||||
"vue": "^3.5.26",
|
||||
"vue-router": "^5.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/vue": "^8.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
"jsdom": "^31.0.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.0.0",
|
||||
"vitest": "^5.0.3",
|
||||
"vue-tsc": "^3.2.1"
|
||||
}
|
||||
}
|
||||
Generated
+3397
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
|
||||
@@ -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'))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { RouterView } from 'vue-router'
|
||||
import { AppHeader, AppShell, Icon, ThemeToggle, Toaster, useThemeStore } from '@perfect-design/ui'
|
||||
import AppNav from '@/components/shell/AppNav.vue'
|
||||
import { faBoxOpen } from '@/lib/icons'
|
||||
|
||||
// init() installs the watcher that applies and persists the choice; the style is set after it so a stored value cannot override the pack.
|
||||
onMounted(() => {
|
||||
const theme = useThemeStore()
|
||||
theme.init()
|
||||
theme.setStyle('workbench')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-h-dvh flex-col">
|
||||
<!-- Rendered here, not by AppShell: the header sits above the shell, and the skip link must be the first tab stop. -->
|
||||
<a
|
||||
href="#main-content"
|
||||
class="sr-only focus:not-sr-only focus:absolute focus:start-2 focus:top-2 focus:z-(--z-toast) focus:rounded-md focus:bg-primary focus:px-3 focus:py-2 focus:text-sm focus:text-primary-foreground"
|
||||
>Skip to main content</a
|
||||
>
|
||||
<!-- px-6 on the bar equals the sidebar nav's p-3 plus the link's px-3, so the brand icon sits over the nav icons. -->
|
||||
<!-- AppShell wraps its #header slot in its own <header> and AppHeader renders one too; outside the shell there is one banner. -->
|
||||
<AppHeader sticky mobile-variant="sheet" class="[&>div]:h-(--header-h) [&>div]:px-6">
|
||||
<template #brand>
|
||||
<Icon :icon="faBoxOpen" size="lg" class="text-primary" />
|
||||
<p class="m-0 text-lg font-semibold">GoHoarder</p>
|
||||
<p class="m-0 hidden text-sm text-muted-foreground sm:block">Package checkpoint</p>
|
||||
</template>
|
||||
<template #actions><ThemeToggle /></template>
|
||||
<template #mobile><AppNav sheet /></template>
|
||||
</AppHeader>
|
||||
|
||||
<!-- 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>
|
||||
@@ -0,0 +1,490 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="Bypasses"
|
||||
description="A bypass lets a package or an advisory through the block policy until it expires. Each one is kept for the audit trail."
|
||||
>
|
||||
<template #actions>
|
||||
<Button :icon-start="faPlus" @click="showCreateModal = true">Create bypass</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<SegmentedControl v-model="activeFilter" :options="FILTER_OPTIONS" aria-label="Filter by status" />
|
||||
<SegmentedControl v-model="typeFilter" :options="TYPE_OPTIONS" aria-label="Filter by type" />
|
||||
<Button variant="outline" size="sm" :icon-start="faRotateRight" class="sm:ms-auto" @click="fetchBypasses">
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<LoadingState v-if="loading" variant="table" label="Loading bypasses..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load bypasses"
|
||||
:message="error"
|
||||
@retry="fetchBypasses"
|
||||
/>
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="filteredBypasses.length === 0"
|
||||
:icon="faShieldHalved"
|
||||
title="No bypasses found"
|
||||
description="Create a bypass to serve a package that the policy holds."
|
||||
/>
|
||||
<DataTable
|
||||
v-else
|
||||
label="Bypasses"
|
||||
layout="cards"
|
||||
row-key="id"
|
||||
:columns="bypassColumns"
|
||||
:rows="filteredBypasses"
|
||||
>
|
||||
<template #cell-type="{ row }">
|
||||
<Badge :variant="row.type === 'cve' ? 'secondary' : 'outline'">{{ row.type === 'cve' ? 'CVE' : 'Package' }}</Badge>
|
||||
</template>
|
||||
<template #cell-status="{ row }">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<StatusBadge
|
||||
:status="row.active ? 'active' : 'inactive'"
|
||||
:tones="{ active: 'success', inactive: 'neutral' }"
|
||||
/>
|
||||
<StatusBadge v-if="isExpired(row.expires_at)" status="expired" :tones="{ expired: 'danger' }" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-created_at="{ row }"><RelativeTime :datetime="row.created_at" /></template>
|
||||
<template #cell-expires_at="{ row }">
|
||||
<span class="block">{{ formatDate(row.expires_at) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">
|
||||
<RelativeTime :datetime="row.expires_at" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-actions="{ row }">
|
||||
<span class="flex gap-1">
|
||||
<IconButton :icon="faPen" :label="`Edit bypass for ${row.target}`" @click="editBypass(row)" />
|
||||
<IconButton :icon="faTrash" :label="`Delete bypass for ${row.target}`" @click="confirmDeleteBypass(row)" />
|
||||
</span>
|
||||
</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog v-model:open="showCreateModal">
|
||||
<DialogContent size="lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ editingBypass ? 'Edit' : 'Create' }} bypass</DialogTitle>
|
||||
<DialogDescription>
|
||||
{{ editingBypass ? 'Update the bypass settings.' : 'Create a temporary bypass for a CVE or package.' }}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form class="flex flex-col gap-4" @submit.prevent="submitBypass">
|
||||
<Field v-if="!editingBypass" label="Bypass type">
|
||||
<SegmentedControl v-model="bypassForm.type" :options="BYPASS_TYPE_OPTIONS" full-width />
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
v-if="!editingBypass"
|
||||
:label="bypassForm.type === 'cve' ? 'CVE ID' : 'Package'"
|
||||
:hint="
|
||||
bypassForm.type === 'cve'
|
||||
? 'Enter a CVE or GHSA id, for example CVE-2021-23337. It also covers findings that carry it as an alias.'
|
||||
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions. PyPI packages use the release version, for example pypi/[email protected].'
|
||||
"
|
||||
required
|
||||
>
|
||||
<Input
|
||||
v-model="bypassForm.target"
|
||||
:placeholder="bypassForm.type === 'cve' ? 'CVE-2021-23337' : 'npm/[email protected]'"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
v-if="!editingBypass && bypassForm.type === 'cve'"
|
||||
label="Applies to (optional)"
|
||||
hint="Limit this CVE bypass to one package. Leave empty to apply it to every package with this CVE."
|
||||
>
|
||||
<Input v-model="bypassForm.applies_to" placeholder="npm/[email protected]" />
|
||||
</Field>
|
||||
|
||||
<Field label="Reason" hint="Explain why this bypass is needed. It is kept for the audit trail." required>
|
||||
<Textarea v-model="bypassForm.reason" placeholder="No fix available, business critical dependency" />
|
||||
</Field>
|
||||
|
||||
<Field v-if="!editingBypass" label="Created by" required>
|
||||
<Input v-model="bypassForm.created_by" placeholder="[email protected]" />
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
label="Expires in (hours)"
|
||||
hint="Hours until this bypass expires. 168 is 7 days and 720 is 30 days."
|
||||
required
|
||||
>
|
||||
<Input
|
||||
:model-value="bypassForm.expires_in_hours"
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="168"
|
||||
@update:model-value="setExpiresInHours"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Checkbox v-if="editingBypass" v-model="bypassForm.active" label="Active" />
|
||||
|
||||
<Checkbox v-model="bypassForm.notify_on_expiry" label="Send a notification when the bypass expires" />
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="closeCreateModal">Cancel</Button>
|
||||
<Button type="submit" :disabled="!isFormValid">{{ editingBypass ? 'Update' : 'Create' }} bypass</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog v-model:open="showKeyDialog">
|
||||
<DialogContent size="sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Admin API key</DialogTitle>
|
||||
<DialogDescription>Enter your admin API key to manage bypasses.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form class="flex flex-col gap-4" @submit.prevent="submitApiKey">
|
||||
<Field label="API key" required>
|
||||
<Input v-model="keyInput" type="password" autocomplete="off" />
|
||||
</Field>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="showKeyDialog = false">Cancel</Button>
|
||||
<Button type="submit" :disabled="keyInput.trim() === ''">Continue</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="showDeleteModal"
|
||||
title="Delete bypass?"
|
||||
:description="`Delete the bypass for ${bypassToDelete?.target}? This cannot be undone and the security check is re-enabled immediately.`"
|
||||
confirm-label="Delete bypass"
|
||||
tone="danger"
|
||||
destructive
|
||||
@confirm="deleteBypass"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { useRoute } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
Checkbox,
|
||||
ConfirmDialog,
|
||||
DataTable,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Field,
|
||||
IconButton,
|
||||
Input,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
RelativeTime,
|
||||
SegmentedControl,
|
||||
StatusBadge,
|
||||
Textarea,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { isExpired, type Bypass } from '@/lib/bypass'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { faPen, faPlus, faRotateRight, faShieldHalved, faTrash } from '@/lib/icons'
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const toasts = useToastStore()
|
||||
const bypasses = ref<Bypass[]>([])
|
||||
const activeFilter = ref<'all' | 'active' | 'expired'>('all')
|
||||
const typeFilter = ref<'all' | 'cve' | 'package'>('all')
|
||||
|
||||
const route = useRoute()
|
||||
const showCreateModal = ref(false)
|
||||
const showDeleteModal = ref(false)
|
||||
const editingBypass = ref<Bypass | null>(null)
|
||||
const bypassToDelete = ref<Bypass | null>(null)
|
||||
|
||||
const EMPTY_FORM = {
|
||||
type: 'cve' as 'cve' | 'package',
|
||||
target: '',
|
||||
reason: '',
|
||||
created_by: '',
|
||||
expires_in_hours: 168,
|
||||
applies_to: '',
|
||||
notify_on_expiry: false,
|
||||
active: true,
|
||||
}
|
||||
|
||||
const bypassForm = ref({ ...EMPTY_FORM })
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const apiKey = adminKey.key
|
||||
const keyInput = ref('')
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
const filteredBypasses = computed(() => {
|
||||
let filtered = bypasses.value
|
||||
|
||||
// Filter by active/expired
|
||||
if (activeFilter.value === 'active') {
|
||||
filtered = filtered.filter(b => b.active && !isExpired(b.expires_at))
|
||||
} else if (activeFilter.value === 'expired') {
|
||||
filtered = filtered.filter(b => isExpired(b.expires_at))
|
||||
}
|
||||
|
||||
// Filter by type
|
||||
if (typeFilter.value !== 'all') {
|
||||
filtered = filtered.filter(b => b.type === typeFilter.value)
|
||||
}
|
||||
|
||||
return filtered
|
||||
})
|
||||
|
||||
const isFormValid = computed(() => {
|
||||
if (editingBypass.value) {
|
||||
return bypassForm.value.reason.trim() !== '' && bypassForm.value.expires_in_hours > 0
|
||||
}
|
||||
return (
|
||||
bypassForm.value.target.trim() !== '' &&
|
||||
bypassForm.value.reason.trim() !== '' &&
|
||||
bypassForm.value.created_by.trim() !== '' &&
|
||||
bypassForm.value.expires_in_hours > 0
|
||||
)
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
adminKey.load()
|
||||
prefillFromQuery()
|
||||
if (!apiKey.value) {
|
||||
promptForApiKey()
|
||||
} else {
|
||||
fetchBypasses()
|
||||
}
|
||||
})
|
||||
|
||||
// A package page links here with the package to cover.
|
||||
function prefillFromQuery() {
|
||||
const { type, target } = route.query
|
||||
if (typeof target !== 'string' || target === '') return
|
||||
bypassForm.value = { ...EMPTY_FORM, type: type === 'cve' ? 'cve' : 'package', target }
|
||||
showCreateModal.value = true
|
||||
}
|
||||
|
||||
function promptForApiKey() {
|
||||
keyInput.value = ''
|
||||
showKeyDialog.value = true
|
||||
}
|
||||
|
||||
function submitApiKey() {
|
||||
const key = keyInput.value.trim()
|
||||
if (!key) return
|
||||
adminKey.save(key)
|
||||
showKeyDialog.value = false
|
||||
fetchBypasses()
|
||||
}
|
||||
|
||||
watch(showKeyDialog, (open) => {
|
||||
if (!open && !apiKey.value) error.value = 'Admin API key required to manage bypasses'
|
||||
})
|
||||
|
||||
async function fetchBypasses() {
|
||||
if (!apiKey.value) {
|
||||
promptForApiKey()
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const params = new URLSearchParams()
|
||||
if (activeFilter.value === 'active') {
|
||||
params.append('active_only', 'true')
|
||||
} else if (activeFilter.value === 'expired') {
|
||||
params.append('include_expired', 'true')
|
||||
}
|
||||
if (typeFilter.value !== 'all') {
|
||||
params.append('type', typeFilter.value)
|
||||
}
|
||||
|
||||
const response = await axios.get('/api/admin/bypasses?' + params.toString(), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey.value}`,
|
||||
},
|
||||
})
|
||||
bypasses.value = response.data.bypasses || []
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch bypasses:', err)
|
||||
if (err.response?.status === 401) {
|
||||
error.value = 'Invalid API key. Please check your credentials.'
|
||||
adminKey.clear()
|
||||
} else {
|
||||
error.value = err.response?.data?.error?.message || err.message || 'Failed to load bypasses'
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitBypass() {
|
||||
if (!isFormValid.value) return
|
||||
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
if (editingBypass.value) {
|
||||
// Update existing bypass
|
||||
await axios.patch(
|
||||
`/api/admin/bypasses/${editingBypass.value.id}`,
|
||||
{
|
||||
active: bypassForm.value.active,
|
||||
reason: bypassForm.value.reason,
|
||||
expires_in_hours: bypassForm.value.expires_in_hours,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey.value}`,
|
||||
},
|
||||
}
|
||||
)
|
||||
toasts.success('Bypass updated')
|
||||
} else {
|
||||
// Create new bypass
|
||||
await axios.post(
|
||||
'/api/admin/bypasses',
|
||||
{
|
||||
type: bypassForm.value.type,
|
||||
target: bypassForm.value.target,
|
||||
reason: bypassForm.value.reason,
|
||||
created_by: bypassForm.value.created_by,
|
||||
expires_in_hours: bypassForm.value.expires_in_hours,
|
||||
applies_to: bypassForm.value.applies_to || undefined,
|
||||
notify_on_expiry: bypassForm.value.notify_on_expiry,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey.value}`,
|
||||
},
|
||||
}
|
||||
)
|
||||
toasts.success('Bypass created')
|
||||
}
|
||||
|
||||
closeCreateModal()
|
||||
await fetchBypasses()
|
||||
} catch (err: any) {
|
||||
console.error('Failed to submit bypass:', err)
|
||||
toasts.error('Could not save bypass', err.response?.data?.error?.message || err.message || 'Failed to save bypass')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function editBypass(bypass: Bypass) {
|
||||
editingBypass.value = bypass
|
||||
bypassForm.value = {
|
||||
type: bypass.type,
|
||||
target: bypass.target,
|
||||
reason: bypass.reason,
|
||||
created_by: bypass.created_by,
|
||||
expires_in_hours: 168, // Default extension
|
||||
applies_to: bypass.applies_to || '',
|
||||
notify_on_expiry: bypass.notify_on_expiry,
|
||||
active: bypass.active,
|
||||
}
|
||||
showCreateModal.value = true
|
||||
}
|
||||
|
||||
function closeCreateModal() {
|
||||
showCreateModal.value = false
|
||||
}
|
||||
|
||||
// Also covers dismissal by Escape or the close button, so the next open never reuses an old edit.
|
||||
watch(showCreateModal, (open) => {
|
||||
if (open) return
|
||||
editingBypass.value = null
|
||||
bypassForm.value = { ...EMPTY_FORM }
|
||||
})
|
||||
|
||||
function confirmDeleteBypass(bypass: Bypass) {
|
||||
bypassToDelete.value = bypass
|
||||
showDeleteModal.value = true
|
||||
}
|
||||
|
||||
async function deleteBypass() {
|
||||
if (!bypassToDelete.value) return
|
||||
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
await axios.delete(`/api/admin/bypasses/${bypassToDelete.value.id}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey.value}`,
|
||||
},
|
||||
})
|
||||
|
||||
toasts.success('Bypass deleted')
|
||||
showDeleteModal.value = false
|
||||
bypassToDelete.value = null
|
||||
await fetchBypasses()
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete bypass:', err)
|
||||
toasts.error('Could not delete bypass', err.response?.data?.error?.message || err.message || 'Failed to delete bypass')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const FILTER_OPTIONS = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'active', label: 'Active' },
|
||||
{ value: 'expired', label: 'Expired' },
|
||||
]
|
||||
|
||||
const TYPE_OPTIONS = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'cve', label: 'CVE' },
|
||||
{ value: 'package', label: 'Package' },
|
||||
]
|
||||
|
||||
const BYPASS_TYPE_OPTIONS = [
|
||||
{ value: 'cve', label: 'CVE bypass' },
|
||||
{ value: 'package', label: 'Package bypass' },
|
||||
]
|
||||
|
||||
const bypassColumns: DataTableColumn<Bypass>[] = [
|
||||
{ key: 'target', header: 'Target', sortable: true, rowHeader: true },
|
||||
{ key: 'type', header: 'Type' },
|
||||
{ key: 'status', header: 'Status', accessor: (b) => (b.active ? 'active' : 'inactive') },
|
||||
{ key: 'reason', header: 'Reason' },
|
||||
{ key: 'created_by', header: 'Created by' },
|
||||
{ key: 'created_at', header: 'Created', sortable: true, accessor: (b) => Date.parse(b.created_at) },
|
||||
{ key: 'expires_at', header: 'Expires', sortable: true, accessor: (b) => Date.parse(b.expires_at) },
|
||||
{ key: 'applies_to', header: 'Applies to' },
|
||||
{ key: 'actions', header: 'Actions', actions: true, accessor: () => '' },
|
||||
]
|
||||
|
||||
function setExpiresInHours(value: string | number) {
|
||||
bypassForm.value.expires_in_hours = Number(value)
|
||||
}
|
||||
|
||||
</script>
|
||||
@@ -0,0 +1,77 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import Insights from './Insights.vue'
|
||||
import { REGISTRIES, STATS, TIMESERIES, TREND } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(stats = STATS, timeseries: unknown = TIMESERIES) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: timeseries } as never
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND } as never
|
||||
return { data: { stats, registries: REGISTRIES } } as never
|
||||
})
|
||||
const router = await createTestRouter('/stats')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(Insights, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
beforeEach(() => setActivePinia(createPinia()))
|
||||
|
||||
describe('Insights', () => {
|
||||
it('lists packages and downloads per registry', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
expect(problems).toEqual([])
|
||||
const table = wrapper.get('[data-testid="registry-breakdown"] table')
|
||||
expect(table.text()).toContain('npm280')
|
||||
expect(table.text()).toContain('go110')
|
||||
expect(table.text()).toContain('pypi130')
|
||||
})
|
||||
|
||||
it('reports scan coverage and the four outcomes', async () => {
|
||||
const { wrapper } = await open()
|
||||
const coverage = wrapper.get('[data-testid="scan-coverage"]').text()
|
||||
expect(coverage).toContain('3 of 4')
|
||||
for (const word of ['Cleared', 'Held', 'Bypassed', 'Awaiting scan']) expect(coverage).toContain(word)
|
||||
})
|
||||
|
||||
it('shades a day when there were downloads', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-testid="daily-downloads"]').find('[role="img"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('summarises the heatmap period next to the grid', async () => {
|
||||
const { wrapper } = await open()
|
||||
const summary = wrapper.get('[data-testid="heatmap-summary"]').text()
|
||||
expect(summary).toContain('Total')
|
||||
expect(summary).toContain(`of ${TIMESERIES.data_points.length}`)
|
||||
expect(summary).toContain('Busiest day')
|
||||
})
|
||||
|
||||
it('does not draw an empty heatmap for a month with no downloads', async () => {
|
||||
const quiet = { ...TIMESERIES, data_points: TIMESERIES.data_points.map((p) => ({ ...p, value: 0 })) }
|
||||
const { wrapper } = await open(STATS, quiet)
|
||||
expect(wrapper.get('[data-testid="daily-downloads"]').text()).toContain('No downloads yet')
|
||||
})
|
||||
|
||||
it('never shows a hit rate or evictions, which the server does not track', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toMatch(/hit rate|evict/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,211 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Insights" description="How the cache grows, what each registry holds, and how much of it the scanners have covered.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="refresh">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading && !stats" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
|
||||
<ErrorState v-else-if="error && !stats" variant="card" title="Could not load statistics" :message="error" @retry="refresh" />
|
||||
|
||||
<template v-else>
|
||||
<Callout v-if="idleTtl > 0" type="note" size="sm">
|
||||
Cached items not requested for {{ formatDuration(idleTtl) }} are removed.
|
||||
</Callout>
|
||||
|
||||
<Card data-testid="registry-breakdown">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">By registry</CardTitle>
|
||||
<CardDescription>Packages, disk and traffic for each upstream.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<EmptyState v-if="registryRows.length === 0" size="sm" title="No registry data yet" description="Each registry appears after its first download." />
|
||||
<template v-else>
|
||||
<BarChart
|
||||
:labels="registryRows.map((r) => r.registry)"
|
||||
:series="[
|
||||
{ name: 'Packages', data: registryRows.map((r) => r.count) },
|
||||
{ name: 'Downloads', data: registryRows.map((r) => r.downloads) },
|
||||
]"
|
||||
label="Packages and downloads by registry"
|
||||
/>
|
||||
<DataTable label="Registry breakdown" layout="cards" row-key="registry" :columns="registryColumns" :rows="registryRows">
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-share="{ row }">
|
||||
<StatBar label="Share of disk" hide-label :value="row.size" :max="Math.max(totalSize, 1)" :value-text="sharePercent(row.size)" />
|
||||
</template>
|
||||
</DataTable>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card data-testid="scan-coverage">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Scan coverage</CardTitle>
|
||||
<CardDescription>Share of cached package files with a scan result.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<StatBar
|
||||
label="Scanned"
|
||||
:value="stats?.scanned_packages ?? 0"
|
||||
:max="Math.max(stats?.total_packages ?? 0, 1)"
|
||||
:value-text="`${stats?.scanned_packages ?? 0} of ${stats?.total_packages ?? 0}`"
|
||||
/>
|
||||
<StatGroup :columns="4" aria-label="Scan outcomes">
|
||||
<KpiTile v-for="tile in outcomeTiles" :key="tile.verdict" :as="RouterLink" :to="tile.to" variant="interactive" :label="tile.label" :value="tile.value" />
|
||||
</StatGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card data-testid="daily-downloads">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Daily downloads</CardTitle>
|
||||
<CardDescription>The last 30 days. A stronger colour is a busier day.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="heatLoading && heatData.length === 0" layout="inline" label="Loading daily downloads..." />
|
||||
<ErrorState v-else-if="heatError" variant="inline" title="Could not load daily downloads" :message="heatError" @retry="loadHeatmap" />
|
||||
<EmptyState v-else-if="heatData.length === 0" size="sm" title="No downloads yet" description="Days fill in as clients request packages." />
|
||||
<div v-else class="flex flex-wrap items-start gap-x-12 gap-y-6">
|
||||
<CalendarHeatmap
|
||||
:data="heatData"
|
||||
:start="heatStart"
|
||||
:end="heatEnd"
|
||||
label="Downloads per day over the last 30 days"
|
||||
:cell-title="(date: string, value: number | null) => `${date}: ${value ?? 0} downloads`"
|
||||
/>
|
||||
<DescriptionList variant="grid" :columns="3" class="min-w-64 flex-1" data-testid="heatmap-summary">
|
||||
<DescriptionItem term="Total">{{ formatNumber(heatSummary.total) }}</DescriptionItem>
|
||||
<DescriptionItem term="Active days">{{ heatSummary.activeDays }} of {{ heatData.length }}</DescriptionItem>
|
||||
<DescriptionItem term="Busiest day">{{ heatSummary.busiest }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
BarChart,
|
||||
Button,
|
||||
CalendarHeatmap,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
Callout,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatBar,
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
import { isoDay, type TimeSeries } from '@/lib/timeseries'
|
||||
|
||||
interface RegistryRow {
|
||||
registry: string
|
||||
count: number
|
||||
size: number
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, registries, loading, error } = storeToRefs(store)
|
||||
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl ?? 0)
|
||||
const totalSize = computed(() => stats.value?.total_size ?? 0)
|
||||
|
||||
const registryRows = computed<RegistryRow[]>(() =>
|
||||
Object.entries(registries.value)
|
||||
.map(([registry, r]) => ({ registry, count: r.count ?? 0, size: r.size ?? 0, downloads: r.downloads ?? 0 }))
|
||||
.sort((a, b) => b.size - a.size),
|
||||
)
|
||||
|
||||
function sharePercent(size: number): string {
|
||||
return totalSize.value > 0 ? `${Math.round((size / totalSize.value) * 100)}%` : '0%'
|
||||
}
|
||||
|
||||
const registryColumns: DataTableColumn<RegistryRow>[] = [
|
||||
{ key: 'registry', header: 'Registry', rowHeader: true },
|
||||
{ key: 'count', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.count) },
|
||||
{ key: 'size', header: 'Disk', numeric: true, accessor: (r) => formatBytes(r.size) },
|
||||
{ key: 'downloads', header: 'Downloads', numeric: true, accessor: (r) => formatNumber(r.downloads) },
|
||||
{ key: 'share', header: 'Share of disk', accessor: (r) => r.size },
|
||||
]
|
||||
|
||||
const outcomeTiles = computed(() => {
|
||||
const s = stats.value
|
||||
const total = s?.total_packages ?? 0
|
||||
const scanned = s?.scanned_packages ?? 0
|
||||
const held = s?.blocked_packages ?? 0
|
||||
const bypassed = s?.bypassed_packages ?? 0
|
||||
return [
|
||||
{ verdict: 'cleared', label: 'Cleared', value: Math.max(scanned - held - bypassed, 0), to: '/packages?verdict=cleared' },
|
||||
{ verdict: 'held', label: 'Held', value: held, to: '/security?tab=held' },
|
||||
{ verdict: 'bypassed', label: 'Bypassed', value: bypassed, to: '/security?tab=bypassed' },
|
||||
{ verdict: 'pending', label: 'Awaiting scan', value: Math.max(total - scanned, 0), to: '/packages?verdict=pending' },
|
||||
]
|
||||
})
|
||||
|
||||
const heatPoints = ref<TimeSeries['data_points']>([])
|
||||
const heatLoading = ref(false)
|
||||
const heatError = ref<string | null>(null)
|
||||
|
||||
// An all-zero month has nothing to shade, so it reads as empty.
|
||||
const heatData = computed(() =>
|
||||
heatPoints.value.some((p) => p.value > 0) ? heatPoints.value.map((p) => ({ date: isoDay(p.timestamp), value: p.value })) : [],
|
||||
)
|
||||
const heatSummary = computed(() => {
|
||||
const days = heatData.value
|
||||
const busiest = days.reduce((max, d) => (d.value > max.value ? d : max), days[0] ?? { date: '', value: 0 })
|
||||
return {
|
||||
total: days.reduce((sum, d) => sum + d.value, 0),
|
||||
activeDays: days.filter((d) => d.value > 0).length,
|
||||
busiest: busiest.value > 0 ? `${busiest.date}, ${formatNumber(busiest.value)}` : 'None',
|
||||
}
|
||||
})
|
||||
const heatStart = computed(() => heatData.value[0]?.date ?? '')
|
||||
const heatEnd = computed(() => heatData.value[heatData.value.length - 1]?.date ?? '')
|
||||
|
||||
async function loadHeatmap() {
|
||||
heatLoading.value = true
|
||||
heatError.value = null
|
||||
try {
|
||||
const response = await axios.get<TimeSeries>('/api/stats/timeseries?period=30day')
|
||||
heatPoints.value = response.data.data_points ?? []
|
||||
} catch (err) {
|
||||
heatError.value = err instanceof Error ? err.message : 'Failed to load daily downloads'
|
||||
} finally {
|
||||
heatLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void loadHeatmap()
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
@@ -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 overview</RouterLink>
|
||||
</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { RouterLink, useRoute } from 'vue-router'
|
||||
import { Button, EmptyState, PageHeader } from '@perfect-design/ui'
|
||||
import { faMagnifyingGlass } from '@/lib/icons'
|
||||
|
||||
const route = useRoute()
|
||||
</script>
|
||||
@@ -0,0 +1,101 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import Overview from './Overview.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { PACKAGES, REGISTRIES, STATS, SYSTEM, TIMESERIES, TOP_PACKAGES } from '@/test/fixtures'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/system')) return { data: SYSTEM } as never
|
||||
if (url.includes('layout=rows')) return { data: serveRows(url, PACKAGES) } as never
|
||||
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES } as never
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES } as never
|
||||
return { data: { stats: STATS, registries: REGISTRIES } } as never
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open() {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
describe('Overview', () => {
|
||||
it('fetches each panel once while the stats load', async () => {
|
||||
await open()
|
||||
const urls = vi.mocked(axios.get).mock.calls.map(([url]) => String(url))
|
||||
const count = (prefix: string) => urls.filter((u) => u.startsWith(prefix)).length
|
||||
expect(count('/api/stats/timeseries')).toBe(1)
|
||||
expect(count('/api/analytics/trending')).toBe(1)
|
||||
expect(urls.filter((u) => u.includes('layout=rows')).length).toBe(1)
|
||||
})
|
||||
|
||||
it('counts each verdict from the stats', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
expect(problems).toEqual([])
|
||||
const count = (verdict: string) => wrapper.get(`[data-verdict="${verdict}"]`).text()
|
||||
// 4 cached, 3 scanned, 1 held, 1 bypassed.
|
||||
expect(count('cleared')).toMatch(/Cleared\s*1/)
|
||||
expect(count('held')).toMatch(/Held\s*1/)
|
||||
expect(count('bypassed')).toMatch(/Bypassed\s*1/)
|
||||
expect(count('pending')).toMatch(/Awaiting scan\s*1/)
|
||||
})
|
||||
|
||||
it('links each verdict to the page that lists it', async () => {
|
||||
const { wrapper } = await open()
|
||||
const href = (verdict: string) => wrapper.get(`[data-verdict="${verdict}"]`).attributes('href')
|
||||
expect(href('held')).toBe('/security?tab=held')
|
||||
expect(href('bypassed')).toBe('/security?tab=bypassed')
|
||||
expect(href('pending')).toBe('/packages?verdict=pending')
|
||||
})
|
||||
|
||||
it('never shows a hit rate or evictions, which the server does not track', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toMatch(/hit rate|evict/i)
|
||||
})
|
||||
|
||||
it('lets a live stats frame override polled counters without losing the rest', async () => {
|
||||
const { wrapper } = await open()
|
||||
useRealtimeStore().lastStats = { blocked_packages: 5 }
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[data-verdict="held"]').text()).toMatch(/Held\s*5/)
|
||||
expect(wrapper.get('[data-verdict="bypassed"]').text()).toMatch(/Bypassed\s*1/)
|
||||
})
|
||||
|
||||
it('shows loading while statistics are in flight', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
usePackageStore().loading = true
|
||||
vi.spyOn(usePackageStore(), 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
expect(mounted.wrapper.text()).toContain('Loading statistics...')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,210 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Overview" description="Packages arrive at the proxy, the scanners inspect them, and each is cleared, held or waved through.">
|
||||
<template #actions>
|
||||
<StatusBadge
|
||||
:status="rt.connected ? 'live' : 'paused'"
|
||||
:label="rt.connected ? 'Live' : 'Live updates paused'"
|
||||
:tones="{ live: 'success', paused: 'neutral' }"
|
||||
:pulse="rt.connected"
|
||||
data-testid="ws-live-indicator"
|
||||
/>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<PolicyLine />
|
||||
|
||||
<LoadingState v-if="loading && !displayStats" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error && !displayStats"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<StatGroup :columns="4" aria-label="Verdicts" data-testid="verdict-strip">
|
||||
<KpiTile
|
||||
v-for="tile in verdictTiles"
|
||||
:key="tile.verdict"
|
||||
:as="RouterLink"
|
||||
:to="tile.to"
|
||||
variant="interactive"
|
||||
:label="VERDICT_LABELS[tile.verdict]"
|
||||
:value="tile.value"
|
||||
:hint="tile.hint"
|
||||
:data-verdict="tile.verdict"
|
||||
>
|
||||
<template #icon><Icon :icon="tile.icon" :class="VERDICT_TEXT[tile.verdict]" /></template>
|
||||
</KpiTile>
|
||||
</StatGroup>
|
||||
</template>
|
||||
|
||||
<!-- Outside the stats loading chain: a stats refresh must not remount these and refetch their data. -->
|
||||
<div class="grid items-start gap-6 xl:grid-cols-3">
|
||||
<CacheCapacity
|
||||
v-if="displayStats"
|
||||
:used="displayStats.total_size ?? 0"
|
||||
:max-size="displayStats.max_cache_size ?? 0"
|
||||
:registries="registries"
|
||||
/>
|
||||
<LoadingState v-else-if="loading" variant="card" label="Loading cache capacity..." />
|
||||
<DownloadTrend class="xl:col-span-2" />
|
||||
</div>
|
||||
|
||||
<TopPackages />
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<ScannerHealth />
|
||||
<Card v-if="!(error && !displayStats)" class="min-w-0" data-testid="ws-event-feed">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Live activity</CardTitle>
|
||||
<CardDescription>What the proxy just did.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="feedEvents.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="Quiet at the desk"
|
||||
description="Cached, downloaded and scanned packages appear here as they happen."
|
||||
/>
|
||||
<ActivityFeed v-else :events="feedEvents" variant="compact" label="Live activity" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
ActivityFeed,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Icon,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatGroup,
|
||||
StatusBadge,
|
||||
type ActivityEvent,
|
||||
} from '@perfect-design/ui'
|
||||
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import CacheCapacity from './parts/CacheCapacity.vue'
|
||||
import DownloadTrend from './parts/DownloadTrend.vue'
|
||||
import PolicyLine from './parts/PolicyLine.vue'
|
||||
import ScannerHealth from './parts/ScannerHealth.vue'
|
||||
import TopPackages from './parts/TopPackages.vue'
|
||||
import { usePackageStore, type Stats } from '../stores/packages'
|
||||
import { useRealtimeStore } from '../stores/realtime'
|
||||
import type { EventType, RealtimeEvent } from '@/lib/ws'
|
||||
import { VERDICT_LABELS, VERDICT_TEXT, type Verdict } from '@/lib/verdict'
|
||||
import {
|
||||
faBan,
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
faChartLine,
|
||||
faCircleCheck,
|
||||
faDownload,
|
||||
faHourglassHalf,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
faUnlockKeyhole,
|
||||
} from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, registries, loading, error } = storeToRefs(store)
|
||||
|
||||
const rt = useRealtimeStore()
|
||||
const { lastStats, events: rtEvents } = storeToRefs(rt)
|
||||
|
||||
// A live stats frame can lack counters the polled response carries, so it overlays rather than replaces.
|
||||
const displayStats = computed<Stats | null>(() => {
|
||||
if (!stats.value && !lastStats.value) return null
|
||||
return { ...stats.value, ...lastStats.value } as Stats
|
||||
})
|
||||
|
||||
interface VerdictTile {
|
||||
verdict: Verdict
|
||||
value: number
|
||||
hint: string
|
||||
to: string
|
||||
icon: IconDefinition
|
||||
}
|
||||
|
||||
const verdictTiles = computed<VerdictTile[]>(() => {
|
||||
const s = displayStats.value
|
||||
const total = s?.total_packages ?? 0
|
||||
const scanned = s?.scanned_packages ?? 0
|
||||
const held = s?.blocked_packages ?? 0
|
||||
const bypassed = s?.bypassed_packages ?? 0
|
||||
const tiles: Array<[Verdict, number, string, string, IconDefinition]> = [
|
||||
['cleared', Math.max(scanned - held - bypassed, 0), 'Scanned and served', '/packages?verdict=cleared', faCircleCheck],
|
||||
['held', held, 'Blocked with a 403', '/security?tab=held', faBan],
|
||||
['bypassed', bypassed, 'Served under an admin bypass', '/security?tab=bypassed', faUnlockKeyhole],
|
||||
['pending', Math.max(total - scanned, 0), 'No scan result yet', '/packages?verdict=pending', faHourglassHalf],
|
||||
]
|
||||
return tiles.map(([verdict, value, hint, to, icon]) => ({ verdict, value, hint, to, icon }))
|
||||
})
|
||||
|
||||
const EVENT_LABELS: Record<EventType, string> = {
|
||||
package_cached: 'Cached',
|
||||
package_deleted: 'Deleted',
|
||||
package_downloaded: 'Downloaded',
|
||||
scan_complete: 'Scan complete',
|
||||
stats_update: 'Stats update',
|
||||
}
|
||||
|
||||
const EVENT_ICONS: Record<EventType, IconDefinition> = {
|
||||
package_cached: faBox,
|
||||
package_deleted: faTrash,
|
||||
package_downloaded: faDownload,
|
||||
scan_complete: faShieldHalved,
|
||||
stats_update: faChartLine,
|
||||
}
|
||||
|
||||
const FEED_LENGTH = 6
|
||||
|
||||
const feedEvents = computed<ActivityEvent[]>(() =>
|
||||
rtEvents.value
|
||||
.filter((evt) => evt.type !== 'stats_update')
|
||||
.slice(-FEED_LENGTH)
|
||||
.reverse()
|
||||
.map((evt, idx) => ({
|
||||
id: `${evt.timestamp}-${idx}`,
|
||||
action: EVENT_LABELS[evt.type] ?? evt.type,
|
||||
target: describeEvent(evt) || undefined,
|
||||
time: evt.timestamp,
|
||||
icon: EVENT_ICONS[evt.type] ?? faChartLine,
|
||||
})),
|
||||
)
|
||||
|
||||
function describeEvent(evt: RealtimeEvent): string {
|
||||
const p = evt.payload
|
||||
const name = typeof p.name === 'string' ? p.name : ''
|
||||
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
|
||||
const version = typeof shown === 'string' ? `@${shown}` : ''
|
||||
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
|
||||
return name ? `${registry}${name}${version}` : ''
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// The realtime client is a singleton that outlives this view, so it is never disconnected here.
|
||||
rt.connect()
|
||||
refresh()
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,209 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader :title="packageName" back-href="/packages" back-label="Back to packages">
|
||||
<template #description>
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline">{{ registry }}</Badge>
|
||||
<Badge variant="outline" class="font-mono">{{ withVersionPrefix(shownVersion) }}</Badge>
|
||||
<VerdictBadge v-if="report" :verdict="verdict" />
|
||||
</span>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="card" label="Loading package details..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load this package"
|
||||
:message="error"
|
||||
@retry="load"
|
||||
/>
|
||||
|
||||
<template v-else-if="report">
|
||||
<Callout v-if="banner" :type="banner.type" :title="banner.title" data-testid="verdict-banner">{{ banner.body }}</Callout>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div class="flex flex-col gap-6" data-testid="package-meta">
|
||||
<DescriptionList variant="grid" :columns="3" class="items-start">
|
||||
<DescriptionItem term="Size">{{ row ? formatBytes(row.size) : 'Unknown' }}</DescriptionItem>
|
||||
<DescriptionItem term="Downloads">{{ row ? formatNumber(row.download_count) : 'Unknown' }}</DescriptionItem>
|
||||
<DescriptionItem term="Upstream">{{ upstream }}</DescriptionItem>
|
||||
<DescriptionItem term="Cached">
|
||||
<RelativeTime v-if="row" :datetime="row.cached_at" />
|
||||
<template v-else>Unknown</template>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Last accessed">
|
||||
<RelativeTime v-if="row" :datetime="row.last_accessed" />
|
||||
<template v-else>Unknown</template>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Last scanned">
|
||||
<RelativeTime v-if="report.scanned_at" :datetime="report.scanned_at" />
|
||||
<template v-else>Never</template>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<DescriptionList variant="grid" :columns="1" class="items-start">
|
||||
<DescriptionItem term="Checksum (SHA-256)" :copyable="Boolean(row?.checksum_sha256)" :copy-text="row?.checksum_sha256">
|
||||
<span class="break-all font-mono text-xs">{{ row?.checksum_sha256 || 'Not recorded' }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Expiry">{{ expiry }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Tabs v-model="tab">
|
||||
<TabsList aria-label="Package sections">
|
||||
<TabsTrigger value="vulnerabilities">Vulnerabilities ({{ report.vulnerability_count }})</TabsTrigger>
|
||||
<TabsTrigger value="inspectors">Inspectors</TabsTrigger>
|
||||
<TabsTrigger value="downloads">Downloads</TabsTrigger>
|
||||
<TabsTrigger value="bypass">Bypass</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="vulnerabilities" class="pt-4">
|
||||
<div class="flex flex-col gap-4">
|
||||
<SeveritySummary :counts="severityCounts" label="Findings by severity" />
|
||||
<EmptyState
|
||||
v-if="report.vulnerabilities.length === 0"
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
:title="report.scanned ? 'No vulnerabilities found' : 'Not scanned yet'"
|
||||
:description="report.scanned ? 'The scanners reported nothing for this package version.' : 'Findings appear here once a scan completes.'"
|
||||
/>
|
||||
<VulnerabilityTable v-else :vulnerabilities="report.vulnerabilities" />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="inspectors" class="pt-4">
|
||||
<InspectorMatrix :registry="registry" :results="report.scanners" :configured="configured" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="downloads" class="pt-4">
|
||||
<DownloadsPanel :registry="registry" :name="packageName" :download-count="row?.download_count ?? 0" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="bypass" class="pt-4">
|
||||
<BypassPanel
|
||||
:applied="report.decision.bypass"
|
||||
:registry="registry"
|
||||
:name="packageName"
|
||||
:version="version"
|
||||
:release-version="report.package?.release_version"
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Callout,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
RelativeTime,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import BypassPanel from './parts/BypassPanel.vue'
|
||||
import DownloadsPanel from './parts/DownloadsPanel.vue'
|
||||
import InspectorMatrix from './parts/InspectorMatrix.vue'
|
||||
import VerdictBadge from './parts/VerdictBadge.vue'
|
||||
import VulnerabilityTable from './parts/VulnerabilityTable.vue'
|
||||
import type { Package } from '../stores/packages'
|
||||
import { formatBytes, formatDate, formatNumber, formatDuration, withVersionPrefix } from '@/lib/format'
|
||||
import { faCircleCheck } from '@/lib/icons'
|
||||
import type { PackageReport } from '@/lib/report'
|
||||
import { NO_VULNERABILITIES } from '@/lib/severity'
|
||||
import { describePolicy, useSystem } from '@/lib/system'
|
||||
import type { Verdict } from '@/lib/verdict'
|
||||
import { verdictBanner } from '@/lib/verdictBanner'
|
||||
|
||||
const TABS = ['vulnerabilities', 'inspectors', 'downloads', 'bypass'] as const
|
||||
type TabName = (typeof TABS)[number]
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const system = useSystem()
|
||||
|
||||
const registry = computed(() => route.params.registry as string)
|
||||
// Names with slashes (scoped npm, Go modules) arrive as segments.
|
||||
const packageName = computed(() => {
|
||||
const name = route.params.name
|
||||
return Array.isArray(name) ? name.join('/') : (name as string)
|
||||
})
|
||||
const version = computed(() => route.params.version as string)
|
||||
const shownVersion = computed(() => report.value?.package?.release_version || version.value)
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const report = ref<PackageReport | null>(null)
|
||||
const row = ref<Package | null>(null)
|
||||
|
||||
const tab = ref<TabName>(TABS.find((t) => t === route.query.tab) ?? 'vulnerabilities')
|
||||
watch(tab, (value) => void router.replace({ query: { ...route.query, tab: value === 'vulnerabilities' ? undefined : value } }))
|
||||
|
||||
const severityCounts = computed(() => report.value?.severity_counts ?? NO_VULNERABILITIES)
|
||||
const configured = computed(() => system.info.value?.security.scanners ?? [])
|
||||
const verdict = computed<Verdict>(() => report.value?.decision.verdict ?? 'unscanned')
|
||||
|
||||
const banner = computed(() => {
|
||||
if (!report.value) return null
|
||||
const sec = system.info.value?.security
|
||||
return verdictBanner(report.value, sec ? describePolicy(sec) : '', sec?.fail_closed ?? false)
|
||||
})
|
||||
|
||||
const upstream = computed(() => system.info.value?.upstreams[registry.value] || 'Not reported')
|
||||
|
||||
// Idle eviction is the only expiry the server enforces on a cached package.
|
||||
const expiry = computed(() => {
|
||||
const idle = system.info.value?.cache.idle_ttl
|
||||
if (idle === undefined) return 'Not reported'
|
||||
if (idle === 0) return 'Never. Idle eviction is off.'
|
||||
const last = row.value ? Date.parse(row.value.last_accessed) : Number.NaN
|
||||
const after = `Removed after ${formatDuration(idle)} without a request`
|
||||
return Number.isNaN(last) ? after : `${after}, on ${formatDate(new Date(last + idle * 1000).toISOString())} if unused`
|
||||
})
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
report.value = null
|
||||
try {
|
||||
const encoded = `${registry.value}/${packageName.value}/${version.value}`
|
||||
const [details, single] = await Promise.all([
|
||||
axios.get<PackageReport>(`/api/packages/${encoded}/vulnerabilities`),
|
||||
axios.get<Package>(`/api/packages/${encoded}`).catch(() => null),
|
||||
system.load(),
|
||||
])
|
||||
report.value = details.data
|
||||
row.value = single?.data ?? null
|
||||
} catch (err: unknown) {
|
||||
const e = err as { response?: { data?: { error?: string } }; message?: string }
|
||||
error.value = e.response?.data?.error || e.message || 'Failed to load package details'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import PackageList from './PackageList.vue'
|
||||
import type { Package } from '../stores/packages'
|
||||
import { PACKAGES } from '@/test/fixtures'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
const lastUrl = () => new URL(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0]), 'http://x').searchParams
|
||||
|
||||
function serve(rows: Package[]) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => ({ data: serveRows(url, rows) }) as never)
|
||||
}
|
||||
|
||||
async function open(path = '/packages', rows: Package[] = PACKAGES) {
|
||||
serve(rows)
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const wrapper = mount(PackageList, { props: { registry: router.currentRoute.value.params.registry as string | undefined }, global: { plugins: [pinia, router] } })
|
||||
await flushPromises()
|
||||
return { wrapper, router }
|
||||
}
|
||||
|
||||
describe('PackageList.vue', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('renders the page heading', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
})
|
||||
|
||||
it('asks the server for the first page of rows, not for every package', async () => {
|
||||
await open()
|
||||
const calls = vi.mocked(axios.get).mock.calls.filter((c) => String(c[0]).startsWith('/api/packages'))
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(Object.fromEntries(lastUrl())).toEqual({ layout: 'rows', page: '1', page_size: '25' })
|
||||
})
|
||||
|
||||
it('displays the error message when the load fails', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValue(new Error('Failed to fetch packages'))
|
||||
const router = await createTestRouter('/packages')
|
||||
const wrapper = mount(PackageList, { global: { plugins: [createPinia(), router] } })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('Failed to fetch packages')
|
||||
})
|
||||
|
||||
it('displays an empty state when nothing is cached', async () => {
|
||||
const { wrapper } = await open('/packages', [])
|
||||
expect(wrapper.text()).toContain('No packages cached yet')
|
||||
})
|
||||
|
||||
it('shows one row per version with its size, downloads and verdict word', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(PACKAGES.length)
|
||||
const text = wrapper.text()
|
||||
expect(text).toContain('2 KB')
|
||||
expect(text).toContain('Held')
|
||||
expect(text).toContain('Awaiting scan')
|
||||
})
|
||||
|
||||
it('debounces the search box into one request', async () => {
|
||||
const { wrapper } = await open()
|
||||
vi.mocked(axios.get).mockClear()
|
||||
const input = wrapper.get('input[aria-label="Search packages"]')
|
||||
|
||||
await input.setValue('r')
|
||||
await input.setValue('re')
|
||||
await input.setValue('requests')
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(axios.get).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(400)
|
||||
await flushPromises()
|
||||
expect(axios.get).toHaveBeenCalledTimes(1)
|
||||
expect(lastUrl().get('q')).toBe('requests')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('says nothing matches when the server returns no rows for a search', async () => {
|
||||
const { wrapper } = await open()
|
||||
await wrapper.get('input[aria-label="Search packages"]').setValue('nothing-like-this')
|
||||
await vi.advanceTimersByTimeAsync(400)
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('No packages match')
|
||||
})
|
||||
|
||||
it('writes the search to the URL so a reload restores it', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await wrapper.get('input[aria-label="Search packages"]').setValue('left')
|
||||
await vi.advanceTimersByTimeAsync(400)
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query.q).toBe('left')
|
||||
})
|
||||
|
||||
it('treats the registry path segment as a registry filter sent to the server', async () => {
|
||||
const { wrapper } = await open('/packages/pypi')
|
||||
expect(lastUrl().get('registry')).toBe('pypi')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
|
||||
expect(wrapper.text()).toContain('requests')
|
||||
})
|
||||
|
||||
it('sends the verdict from the URL', async () => {
|
||||
const { wrapper } = await open('/packages?verdict=held')
|
||||
expect(lastUrl().get('verdict')).toBe('held')
|
||||
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('1 of 1 package version')
|
||||
})
|
||||
|
||||
it('pages through the server and shows the range', async () => {
|
||||
const many = Array.from({ length: 60 }, (_, i) => ({ ...PACKAGES[0]!, id: `p${i}`, name: `pkg-${String(i).padStart(2, '0')}` }))
|
||||
const { wrapper } = await open('/packages', many)
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(25)
|
||||
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('1–25 of 60 package versions')
|
||||
|
||||
await wrapper.get('nav[aria-label="Package pages"] button[aria-label*="ext"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(lastUrl().get('page')).toBe('2')
|
||||
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('26–50 of 60')
|
||||
})
|
||||
|
||||
it('sends a column sort to the server and returns to page 1', async () => {
|
||||
const { wrapper } = await open()
|
||||
await wrapper.get('thead button[aria-label*="Size"], thead th button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(lastUrl().get('page')).toBe('1')
|
||||
expect(lastUrl().get('sort')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('shows the release version of a PyPI file row, not the file name', async () => {
|
||||
const six = { ...PACKAGES[2], version: 'six-1.17.0-py2.py3-none-any.whl', release_version: '1.17.0' } as Package
|
||||
const { wrapper } = await open('/packages', [six])
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,262 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached and the verdict each package received.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<SearchInput v-model="query" aria-label="Search packages" placeholder="Search by name or version..." class="w-full sm:max-w-md" />
|
||||
<FilterBar v-model="filterItems" :fields="filterFields" variant="compact" />
|
||||
</div>
|
||||
|
||||
<LoadingState v-if="loading && !loaded" variant="table" label="Loading packages..." />
|
||||
|
||||
<ErrorState v-else-if="error" variant="card" title="Could not load packages" :message="error" @retry="load()" />
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="total === 0 && !filtered"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages will appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="total === 0"
|
||||
:icon="faMagnifyingGlass"
|
||||
title="No packages match"
|
||||
description="Change the search text or remove a filter."
|
||||
/>
|
||||
<template v-else>
|
||||
<p class="m-0 mb-3 text-sm text-muted-foreground" data-testid="package-count">
|
||||
{{ rangeStart }}–{{ rangeEnd }} of {{ plural(total, 'package version') }}
|
||||
</p>
|
||||
<DataTable
|
||||
v-model:sort="sort"
|
||||
label="Cached packages"
|
||||
layout="cards"
|
||||
density="compact"
|
||||
row-clickable
|
||||
:loading="loading"
|
||||
:columns="columns"
|
||||
:rows="rows"
|
||||
@row-click="(row: Package) => (selected = row)"
|
||||
>
|
||||
<template #cell-name="{ row }">
|
||||
<RouterLink :to="packageRoute(row)" class="break-words font-medium text-foreground underline-offset-4 hover:underline">
|
||||
{{ row.name }}
|
||||
</RouterLink>
|
||||
</template>
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-size="{ row }">{{ formatBytes(row.size) }}</template>
|
||||
<template #cell-download_count="{ row }">{{ formatNumber(row.download_count) }}</template>
|
||||
<template #cell-last_accessed="{ row }"><RelativeTime :datetime="row.last_accessed" /></template>
|
||||
<template #cell-verdict="{ row }"><VerdictBadge :verdict="verdictOf(row)" /></template>
|
||||
<template #cell-scanned="{ row }">
|
||||
<RelativeTime v-if="row.vulnerabilities?.scannedAt" :datetime="row.vulnerabilities.scannedAt" />
|
||||
<span v-else class="text-muted-foreground">Never</span>
|
||||
</template>
|
||||
</DataTable>
|
||||
<Pagination
|
||||
v-if="total > PAGE_SIZE"
|
||||
v-model:page="page"
|
||||
class="mt-4"
|
||||
:total="total"
|
||||
:page-size="PAGE_SIZE"
|
||||
aria-label="Package pages"
|
||||
/>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<PackageQuickView :pkg="selected" @close="selected = null" @delete="confirmDelete" />
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="showDeleteModal"
|
||||
title="Remove package version?"
|
||||
:description="`Remove ${packageToDelete?.name}@${packageToDelete?.version} from the cache? Clients can fetch it again from upstream.`"
|
||||
confirm-label="Remove version"
|
||||
tone="danger"
|
||||
destructive
|
||||
@confirm="deletePackage"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
ConfirmDialog,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
FilterBar,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
Pagination,
|
||||
RelativeTime,
|
||||
SearchInput,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
type FilterField,
|
||||
type FilterItem,
|
||||
type SortState,
|
||||
} from '@perfect-design/ui'
|
||||
import PackageQuickView from './parts/PackageQuickView.vue'
|
||||
import VerdictBadge from './parts/VerdictBadge.vue'
|
||||
import { usePackageStore, type ApiVerdict, type Package } from '../stores/packages'
|
||||
import { plural } from '@/lib/reason'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { usePackageRows, type RowQuery, type RowSort } from '@/lib/packageRows'
|
||||
import { faBoxOpen, faMagnifyingGlass, faRotateRight } from '@/lib/icons'
|
||||
import { VERDICT_OPTIONS, verdictOf } from '@/lib/verdict'
|
||||
|
||||
const props = defineProps<{ registry?: string }>()
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
const KNOWN_REGISTRIES = ['npm', 'go', 'pypi']
|
||||
|
||||
const store = usePackageStore()
|
||||
const toasts = useToastStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { rows, total, loading, error, load: loadRows } = usePackageRows()
|
||||
|
||||
const loaded = ref(false)
|
||||
const selected = ref<Package | null>(null)
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
const sort = ref<SortState | null>(null)
|
||||
const page = ref(1)
|
||||
|
||||
function queryText(key: string): string {
|
||||
const raw = route.query[key]
|
||||
return typeof raw === 'string' ? raw : ''
|
||||
}
|
||||
|
||||
const query = ref(queryText('q'))
|
||||
const searchTerm = ref(query.value)
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(query, (value) => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => (searchTerm.value = value), SEARCH_DEBOUNCE_MS)
|
||||
})
|
||||
onUnmounted(() => clearTimeout(searchTimer))
|
||||
|
||||
let nextFilterId = 0
|
||||
function filterItem(field: string, value: string): FilterItem {
|
||||
return { id: `f${nextFilterId++}`, field, operator: 'eq', value }
|
||||
}
|
||||
|
||||
// The path segment is the pre-redesign way to pick a registry, so it still seeds the filter.
|
||||
const filterItems = ref<FilterItem[]>(
|
||||
[
|
||||
...[props.registry || queryText('registry')].filter(Boolean).map((r) => filterItem('registry', r)),
|
||||
...[queryText('verdict')].filter(Boolean).map((v) => filterItem('verdict', v)),
|
||||
],
|
||||
)
|
||||
|
||||
const registryOptions = computed(() => {
|
||||
const seen = new Set([...KNOWN_REGISTRIES, ...rows.value.map((p) => p.registry), ...valuesOf('registry')])
|
||||
return [...seen].map((value) => ({ value, label: value }))
|
||||
})
|
||||
|
||||
const filterFields = computed<FilterField[]>(() => [
|
||||
{ id: 'registry', label: 'Registry', type: 'select', options: registryOptions.value, operators: ['eq'] },
|
||||
{ id: 'verdict', label: 'Verdict', type: 'select', options: VERDICT_OPTIONS, operators: ['eq'] },
|
||||
])
|
||||
|
||||
function valuesOf(field: string): string[] {
|
||||
return filterItems.value.filter((f) => f.field === field).map((f) => String(f.value))
|
||||
}
|
||||
|
||||
const SORT_KEYS: Record<string, RowSort> = {
|
||||
name: 'name',
|
||||
version: 'version',
|
||||
registry: 'registry',
|
||||
size: 'size',
|
||||
download_count: 'downloads',
|
||||
last_accessed: 'last_accessed',
|
||||
scanned: 'last_scanned',
|
||||
}
|
||||
|
||||
const rowQuery = computed<RowQuery>(() => ({
|
||||
q: searchTerm.value,
|
||||
registry: valuesOf('registry')[0],
|
||||
verdict: valuesOf('verdict')[0] as ApiVerdict | undefined,
|
||||
sort: sort.value ? SORT_KEYS[sort.value.key] : undefined,
|
||||
order: sort.value?.direction === 'desc' ? 'desc' : 'asc',
|
||||
page: page.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
}))
|
||||
|
||||
const filtered = computed(() => Boolean(searchTerm.value.trim() || valuesOf('registry').length || valuesOf('verdict').length))
|
||||
const rangeStart = computed(() => (total.value === 0 ? 0 : (page.value - 1) * PAGE_SIZE + 1))
|
||||
const rangeEnd = computed(() => Math.min(page.value * PAGE_SIZE, total.value))
|
||||
|
||||
// A new search, filter or sort starts again from the first page.
|
||||
watch([searchTerm, filterItems, sort], () => (page.value = 1))
|
||||
|
||||
// The URL mirrors the filters so a reload or a shared link restores the view.
|
||||
watch([searchTerm, filterItems], () => {
|
||||
const { q: _q, registry: _r, verdict: _v, ...rest } = route.query
|
||||
const next: Record<string, string> = {}
|
||||
if (searchTerm.value.trim()) next.q = searchTerm.value.trim()
|
||||
const [registry] = valuesOf('registry')
|
||||
const [verdict] = valuesOf('verdict')
|
||||
if (registry) next.registry = registry
|
||||
if (verdict) next.verdict = verdict
|
||||
void router.replace({ path: '/packages', query: { ...rest, ...next } })
|
||||
})
|
||||
|
||||
const columns: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', sortable: true, rowHeader: true },
|
||||
{ key: 'version', header: 'Version', sortable: true, accessor: (p) => withVersionPrefix(displayVersion(p)) },
|
||||
{ key: 'registry', header: 'Registry', sortable: true },
|
||||
{ key: 'size', header: 'Size', sortable: true, numeric: true },
|
||||
{ key: 'download_count', header: 'Downloads', sortable: true, numeric: true },
|
||||
{ key: 'last_accessed', header: 'Last accessed', sortable: true, accessor: (p) => Date.parse(p.last_accessed) || 0 },
|
||||
{ key: 'verdict', header: 'Verdict' },
|
||||
{ key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 },
|
||||
]
|
||||
|
||||
async function load() {
|
||||
await loadRows(rowQuery.value)
|
||||
loaded.value = true
|
||||
}
|
||||
|
||||
watch(rowQuery, load)
|
||||
onMounted(load)
|
||||
|
||||
function confirmDelete(pkg: Package) {
|
||||
packageToDelete.value = pkg
|
||||
showDeleteModal.value = true
|
||||
}
|
||||
|
||||
async function deletePackage() {
|
||||
const target = packageToDelete.value
|
||||
if (!target) return
|
||||
await store.deletePackage(target.registry, target.name, target.version)
|
||||
showDeleteModal.value = false
|
||||
packageToDelete.value = null
|
||||
selected.value = null
|
||||
const label = `${target.name}@${target.version}`
|
||||
if (store.error) {
|
||||
toasts.error('Could not remove package', `${label}: ${store.error}`)
|
||||
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
|
||||
store.error = null
|
||||
} else {
|
||||
toasts.success('Package removed', label)
|
||||
await load()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,282 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import Security from './Security.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package {
|
||||
const full = { critical: 0, high: 0, moderate: 0, low: 0, ...counts }
|
||||
return {
|
||||
id: name,
|
||||
registry: 'npm',
|
||||
name,
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2026-01-03T10:00:00Z',
|
||||
last_accessed: '2026-01-03T10:00:00Z',
|
||||
download_count: 1,
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: full,
|
||||
total: full.critical + full.high + full.moderate + full.low,
|
||||
scannedAt: '2026-01-03T10:05:00Z',
|
||||
isBlocked: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const FIXTURE: Package[] = [
|
||||
vulnerable('alpha-critical', { critical: 1 }),
|
||||
vulnerable('bravo-high', { high: 2 }),
|
||||
vulnerable('charlie-moderate', { moderate: 1 }),
|
||||
vulnerable('delta-mixed', { critical: 1, moderate: 3 }),
|
||||
]
|
||||
const NAMES = FIXTURE.map((p) => p.name)
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
function serve(packages: Package[]) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => ({ data: serveRows(url, packages) }) as never)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
serve(FIXTURE)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/security?tab=allowed') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(Security, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return { ...mounted, router }
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
|
||||
const tile = (wrapper: Wrapper, severity: string) => wrapper.get(`button[data-severity="${severity}"]`)
|
||||
const shown = (wrapper: Wrapper) => NAMES.filter((name) => wrapper.text().includes(name))
|
||||
const pressed = (wrapper: Wrapper) =>
|
||||
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
|
||||
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
|
||||
|
||||
describe('Security severity filter', () => {
|
||||
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
|
||||
const { wrapper, problems, router } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(wrapper.text()).not.toContain('Filter on')
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('asks the server for one page of the open tab, worst first', async () => {
|
||||
await open()
|
||||
const url = vi.mocked(axios.get).mock.calls.map((c) => String(c[0])).find((u) => u.includes('layout=rows'))!
|
||||
const params = new URL(url, 'http://x').searchParams
|
||||
expect(Object.fromEntries(params)).toEqual({
|
||||
layout: 'rows',
|
||||
page: '1',
|
||||
page_size: '25',
|
||||
verdict: 'cleared',
|
||||
severity: 'critical,high,moderate,low',
|
||||
sort: 'risk',
|
||||
order: 'desc',
|
||||
})
|
||||
})
|
||||
|
||||
it('sends the selected severities with the open tab', async () => {
|
||||
const { wrapper } = await open()
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
const last = String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])
|
||||
expect(new URL(last, 'http://x').searchParams.get('severity')).toBe('high')
|
||||
})
|
||||
|
||||
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tiles = wrapper.findAll('button[data-severity]')
|
||||
|
||||
expect(tiles.map((t) => t.attributes('data-severity'))).toEqual(['critical', 'high', 'moderate', 'low'])
|
||||
for (const t of tiles) {
|
||||
expect(t.element.tagName).toBe('BUTTON')
|
||||
expect(t.attributes('type')).toBe('button')
|
||||
expect(t.attributes('tabindex')).not.toBe('-1')
|
||||
expect(t.attributes('aria-pressed')).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('one click filters to that severity and shows the state in text, not colour alone', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(['bravo-high'])
|
||||
expect(pressed(wrapper)).toEqual(['false', 'true', 'false', 'false'])
|
||||
expect(tile(wrapper, 'high').text()).toContain('Filter on')
|
||||
expect(tile(wrapper, 'critical').text()).not.toContain('Filter on')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('Showing packages with high vulnerabilities.')
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
expect(router.currentRoute.value.query.severity).toBe('high')
|
||||
})
|
||||
|
||||
it('keeps the tile counts of the whole list while a filter is on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const before = tile(wrapper, 'critical').text()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(tile(wrapper, 'critical').text()).toBe(before)
|
||||
expect(tile(wrapper, 'critical').text()).toContain('2 packages')
|
||||
})
|
||||
|
||||
it('selects several severities with OR semantics', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBe('critical,high')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('critical or high')
|
||||
})
|
||||
|
||||
it('a second click toggles the filter off and removes the query', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['charlie-moderate', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('Clear filters resets every selected severity at once', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
await clearButtons(wrapper)[0]!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('restores the filter from the URL, as after a reload or a shared link', async () => {
|
||||
const { wrapper } = await open('/security?tab=allowed&severity=high,critical')
|
||||
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
|
||||
const { wrapper, router } = await open('/security?tab=allowed&severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ tab: 'allowed', ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/security?tab=allowed&severity=low')
|
||||
|
||||
const empty = wrapper.get('[data-slot="empty-state"]')
|
||||
expect(empty.text()).toContain('No packages match the filter')
|
||||
expect(shown(wrapper)).toEqual([])
|
||||
// The tiles stay so the filter can be changed without leaving the page.
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'true'])
|
||||
|
||||
await empty.findAll('button').find((b) => b.text() === 'Clear filters')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the success state when nothing has findings, filter or not', async () => {
|
||||
serve([])
|
||||
const { wrapper } = await open('/security?tab=allowed&severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No package carries findings under the policy')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('lists a held package under Held, not under Vulnerable but allowed', async () => {
|
||||
const held = vulnerable('echo-blocked', { critical: 1 })
|
||||
held.vulnerabilities!.isBlocked = true
|
||||
held.vulnerabilities!.verdict = 'held'
|
||||
serve([...FIXTURE, held])
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
|
||||
it('lists a held package that has no findings, such as a failed scan', async () => {
|
||||
const failed = vulnerable('foxtrot-failed', {})
|
||||
failed.vulnerabilities = { scanned: true, status: 'clean', isBlocked: true, verdict: 'held', reason: 'scan failed - fail closed' }
|
||||
serve([failed])
|
||||
const { wrapper } = await open('/security?tab=held')
|
||||
|
||||
expect(wrapper.text()).toContain('foxtrot-failed')
|
||||
expect(wrapper.text()).toContain('scan failed - fail closed')
|
||||
})
|
||||
|
||||
it('pages through the server and resets to page 1 when the filter changes', async () => {
|
||||
const many = Array.from({ length: 30 }, (_, i) => vulnerable(`pkg-${String(i).padStart(2, '0')}`, { critical: 1 }))
|
||||
serve(many)
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(25)
|
||||
|
||||
await wrapper.get('nav[aria-label="Security pages"] button[aria-label*="ext"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(5)
|
||||
expect(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])).toContain('page=2')
|
||||
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await flushPromises()
|
||||
expect(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])).toContain('page=1')
|
||||
})
|
||||
|
||||
it('takes the tab counts from the server, not from the rows on screen', async () => {
|
||||
const many = Array.from({ length: 30 }, (_, i) => vulnerable(`pkg-${i}`, { low: 1 }))
|
||||
serve(many)
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.findAll('[role="tab"]').map((t) => t.text())).toContain('Vulnerable but allowed (30)')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Security" description="Packages the scanners found something in, and what the policy did about each.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading && !loaded" variant="table" label="Loading security findings..." />
|
||||
|
||||
<ErrorState v-else-if="error" variant="card" title="Could not load security findings" :message="error" @retry="load" />
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary
|
||||
v-if="anyFindings"
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
label="Findings by severity. Select a severity to filter the packages."
|
||||
:counts="severityTotals"
|
||||
:package-counts="severityPackages"
|
||||
/>
|
||||
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="m-0 text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="selectedSeverities = []">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Tabs v-model="tab">
|
||||
<TabsList aria-label="Security sections">
|
||||
<TabsTrigger v-for="t in TAB_DEFS" :key="t.value" :value="t.value">{{ t.label }} ({{ tabCount(t.value) }})</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent v-for="t in TAB_DEFS" :key="t.value" :value="t.value" class="pt-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">{{ t.label }}</CardTitle>
|
||||
<CardDescription>{{ t.description }}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="total === 0"
|
||||
:icon="faCircleCheck"
|
||||
:title="hasFilter ? 'No packages match the filter' : t.empty"
|
||||
:description="hasFilter ? `No package here has a ${filterSummary} vulnerability.` : undefined"
|
||||
>
|
||||
<template v-if="hasFilter" #action>
|
||||
<Button variant="outline" @click="selectedSeverities = []">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
<DataTable
|
||||
v-else
|
||||
v-model:sort="sort"
|
||||
:label="t.label"
|
||||
layout="cards"
|
||||
density="compact"
|
||||
row-clickable
|
||||
:loading="loading"
|
||||
:columns="columnsFor(t.value)"
|
||||
:rows="rows"
|
||||
@row-click="open"
|
||||
>
|
||||
<template #cell-name="{ row }">
|
||||
<RouterLink :to="packageRoute(row)" class="break-words font-medium text-foreground underline-offset-4 hover:underline">
|
||||
{{ row.name }}
|
||||
</RouterLink>
|
||||
</template>
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-findings="{ row }">
|
||||
<VulnerabilityBadge
|
||||
v-if="row.vulnerabilities"
|
||||
:scanned="row.vulnerabilities.scanned"
|
||||
:status="row.vulnerabilities.status"
|
||||
:counts="row.vulnerabilities.counts"
|
||||
:total="row.vulnerabilities.total"
|
||||
@click="open(row)"
|
||||
/>
|
||||
</template>
|
||||
<template #cell-bypass="{ row }">
|
||||
<span v-if="row.vulnerabilities?.bypass" class="block text-sm">
|
||||
{{ row.vulnerabilities.bypass.created_by }}
|
||||
<span class="block text-xs text-muted-foreground">
|
||||
expires <RelativeTime :datetime="row.vulnerabilities.bypass.expires_at" />
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-scanned="{ row }">
|
||||
<RelativeTime v-if="row.vulnerabilities?.scannedAt" :datetime="row.vulnerabilities.scannedAt" />
|
||||
</template>
|
||||
</DataTable>
|
||||
<Pagination
|
||||
v-if="total > PAGE_SIZE"
|
||||
v-model:page="page"
|
||||
class="mt-4"
|
||||
:total="total"
|
||||
:page-size="PAGE_SIZE"
|
||||
aria-label="Security pages"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
Pagination,
|
||||
RelativeTime,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
type DataTableColumn,
|
||||
type SortState,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import type { Package, VulnerabilityCounts } from '../stores/packages'
|
||||
import { displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { usePackageRows, type RowQuery, type RowSort } from '@/lib/packageRows'
|
||||
import { humanReason } from '@/lib/reason'
|
||||
import { faCircleCheck, faRotateRight } from '@/lib/icons'
|
||||
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
type TabName = 'held' | 'allowed' | 'bypassed'
|
||||
|
||||
const TAB_DEFS: ReadonlyArray<{ value: TabName; label: string; description: string; empty: string }> = [
|
||||
{ value: 'held', label: 'Held', description: 'At or over the block policy. Clients get a 403 until the package is fixed or bypassed.', empty: 'Nothing is held' },
|
||||
{ value: 'allowed', label: 'Vulnerable but allowed', description: 'Findings exist, but none reach the block policy. Clients are served these.', empty: 'No package carries findings under the policy' },
|
||||
{ value: 'bypassed', label: 'Bypassed', description: 'An admin bypass lets these through despite their findings.', empty: 'No bypass is in effect' },
|
||||
]
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { rows, total, counts, loading, error, load: loadRows } = usePackageRows()
|
||||
|
||||
const loaded = ref(false)
|
||||
const page = ref(1)
|
||||
const sort = ref<SortState | null>(null)
|
||||
|
||||
const tab = ref<TabName>(TAB_DEFS.find((t) => t.value === route.query.tab)?.value ?? 'held')
|
||||
watch(tab, (value) => void router.replace({ query: { ...route.query, tab: value } }))
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
|
||||
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
|
||||
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
|
||||
}
|
||||
|
||||
// The URL is the source of truth, so a reload or a shared link restores the filter.
|
||||
const selectedSeverities = computed<SeverityLevel[]>({
|
||||
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
|
||||
set: (levels) => {
|
||||
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
|
||||
const anyFindings = computed(() => counts.value.verdicts.held + counts.value.vulnerable_allowed + counts.value.verdicts.bypassed > 0)
|
||||
// With nothing to filter the tiles are hidden, so a leftover ?severity= must not claim a filter is on.
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0 && anyFindings.value)
|
||||
const filterSummary = computed(() => selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '))
|
||||
|
||||
function tabCount(name: TabName): number {
|
||||
if (name === 'held') return counts.value.verdicts.held
|
||||
if (name === 'bypassed') return counts.value.verdicts.bypassed
|
||||
return counts.value.vulnerable_allowed
|
||||
}
|
||||
|
||||
const severityTotals = computed<VulnerabilityCounts>(() => ({ ...counts.value.severity_findings }))
|
||||
const severityPackages = computed<VulnerabilityCounts>(() => ({ ...counts.value.severity_packages }))
|
||||
|
||||
const SORT_KEYS: Record<string, RowSort> = { name: 'name', version: 'version', registry: 'registry', scanned: 'last_scanned' }
|
||||
|
||||
// "Vulnerable but allowed" is the cleared packages that have findings, so it always filters by severity.
|
||||
const rowQuery = computed<RowQuery>(() => {
|
||||
const severity = selectedSeverities.value.length > 0 ? selectedSeverities.value : tab.value === 'allowed' ? SEVERITY_LEVELS : []
|
||||
return {
|
||||
verdict: tab.value === 'allowed' ? 'cleared' : tab.value,
|
||||
severity,
|
||||
// Worst first unless the operator picked a column.
|
||||
sort: sort.value ? SORT_KEYS[sort.value.key] : 'risk',
|
||||
order: sort.value ? (sort.value.direction === 'desc' ? 'desc' : 'asc') : 'desc',
|
||||
page: page.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
}
|
||||
})
|
||||
|
||||
watch([tab, selectedSeverities, sort], () => (page.value = 1))
|
||||
|
||||
const BASE_COLUMNS: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', sortable: true, rowHeader: true },
|
||||
{ key: 'version', header: 'Version', sortable: true, accessor: (p) => withVersionPrefix(displayVersion(p)) },
|
||||
{ key: 'registry', header: 'Registry', sortable: true },
|
||||
{ key: 'findings', header: 'Findings', accessor: (p) => p.vulnerabilities?.total ?? 0 },
|
||||
]
|
||||
const SCANNED: DataTableColumn<Package> = { key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 }
|
||||
|
||||
function columnsFor(name: TabName): DataTableColumn<Package>[] {
|
||||
if (name === 'held') return [...BASE_COLUMNS, { key: 'reason', header: 'Why', accessor: (p) => humanReason(p.vulnerabilities?.reason) }, SCANNED]
|
||||
if (name === 'bypassed') return [...BASE_COLUMNS, { key: 'bypass', header: 'Bypass', accessor: (p) => p.vulnerabilities?.bypass?.created_by ?? '' }, SCANNED]
|
||||
return [...BASE_COLUMNS, SCANNED]
|
||||
}
|
||||
|
||||
function open(pkg: Package) {
|
||||
void router.push(packageRoute(pkg))
|
||||
}
|
||||
|
||||
async function load() {
|
||||
await loadRows(rowQuery.value)
|
||||
loaded.value = true
|
||||
}
|
||||
|
||||
watch(rowQuery, load)
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,66 @@
|
||||
<template>
|
||||
<StatGroup :columns="4" class="grid-cols-2! lg:grid-cols-4!" :aria-label="label">
|
||||
<template v-if="selectable">
|
||||
<KpiTile
|
||||
v-for="level in SEVERITY_LEVELS"
|
||||
:key="level"
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
:label="formatSeverityName(level)"
|
||||
:value="counts[level]"
|
||||
:aria-pressed="isSelected(level)"
|
||||
:class="['text-left', isSelected(level) && 'ring-2 ring-primary']"
|
||||
:data-severity="level"
|
||||
@click="toggle(level)"
|
||||
>
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
<template #hint>
|
||||
<span v-if="packageCounts">{{ formatPackageCount(packageCounts[level]) }}</span>
|
||||
<span v-if="isSelected(level)" class="font-medium text-foreground" data-testid="severity-filter-on">
|
||||
{{ packageCounts ? ' · ' : '' }}Filter on
|
||||
</span>
|
||||
</template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
<template v-else>
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
</StatGroup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
|
||||
import type { VulnerabilityCounts } from '../stores/packages'
|
||||
import { plural } from '@/lib/reason'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const props = defineProps<{
|
||||
counts: VulnerabilityCounts
|
||||
label: string
|
||||
/** Tiles become toggle buttons that edit `modelValue`. */
|
||||
selectable?: boolean
|
||||
/** Selected severities; several are allowed. */
|
||||
modelValue?: readonly SeverityLevel[]
|
||||
/** Packages per severity, shown on each tile in selectable mode. */
|
||||
packageCounts?: VulnerabilityCounts
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: SeverityLevel[]] }>()
|
||||
|
||||
function isSelected(level: SeverityLevel): boolean {
|
||||
return props.modelValue?.includes(level) ?? false
|
||||
}
|
||||
|
||||
function toggle(level: SeverityLevel) {
|
||||
const current = props.modelValue ?? []
|
||||
const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level]
|
||||
emit('update:modelValue', SEVERITY_LEVELS.filter((l) => next.includes(l)))
|
||||
}
|
||||
|
||||
function formatPackageCount(n: number): string {
|
||||
return plural(n, 'package')
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,186 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="System" description="The policy the proxy applies, the scanners behind it, and the settings that shape the cache.">
|
||||
<template #actions>
|
||||
<Badge v-if="info" variant="outline" class="font-mono" data-testid="build-version">{{ info.version }}</Badge>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load(true)">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="!info && !error" variant="card" label="Loading system settings..." />
|
||||
<ErrorState v-else-if="!info" variant="card" title="Could not load system settings" :message="error ?? ''" @retry="load(true)" />
|
||||
|
||||
<template v-else>
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Policy</CardTitle>
|
||||
<CardDescription>What clears a package and what holds it.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="policy-list">
|
||||
<DescriptionItem term="Scanning">
|
||||
<StatusBadge :status="info.security.enabled ? 'on' : 'off'" :label="info.security.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Block policy">{{ describePolicy(info.security) }}</DescriptionItem>
|
||||
<DescriptionItem term="When a scan fails">
|
||||
{{ info.security.fail_closed ? 'Fail-closed. The package is held.' : 'Fail-open on scanner outage. The package is served and the scan retried.' }}
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Scan on download">{{ info.security.scan_on_download ? 'Yes' : 'No' }}</DescriptionItem>
|
||||
<DescriptionItem term="First download waits">up to {{ formatDuration(info.security.scan_wait_timeout) }} for its scan</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Rescans</CardTitle>
|
||||
<CardDescription>Cached packages are inspected again as advisories change.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="rescan-list">
|
||||
<DescriptionItem term="Interval">{{ duration(info.security.rescan.interval, 'Rescans are off') }}</DescriptionItem>
|
||||
<DescriptionItem term="Active window">{{ duration(info.security.rescan.active_window, 'Every cached package') }}</DescriptionItem>
|
||||
<DescriptionItem term="Parallel scans">{{ info.security.rescan.concurrency }}</DescriptionItem>
|
||||
<DescriptionItem term="Rescan on access">{{ info.security.rescan.on_access ? 'Yes. A stale hit is rescanned before it is served.' : 'No' }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<RescanPanel :enabled="info.security.enabled" :concurrency="info.security.rescan.concurrency" />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Inspectors</CardTitle>
|
||||
<CardDescription>Health is probed at most every 30 seconds. A scanner that is off is not probed.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DataTable label="Scanners" layout="cards" density="compact" row-key="name" :columns="scannerColumns" :rows="info.security.scanners">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-state="{ row }">
|
||||
<StatusBadge :status="scannerState(row)" :label="STATE_LABELS[scannerState(row)]" :tones="STATE_TONES" />
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ scannerVersion(row) || 'Not applicable' }}</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Cache</CardTitle>
|
||||
<CardDescription>Limits and where packages come from.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="cache-list">
|
||||
<DescriptionItem term="Size limit">{{ info.cache.max_size > 0 ? formatBytes(info.cache.max_size) : 'None' }}</DescriptionItem>
|
||||
<DescriptionItem term="Idle eviction">{{ duration(info.cache.idle_ttl, 'Off', 'Removed after ', ' without a request') }}</DescriptionItem>
|
||||
<DescriptionItem term="Default TTL">{{ duration(info.cache.default_ttl, 'None') }}</DescriptionItem>
|
||||
<DescriptionItem v-for="(host, registry) in info.upstreams" :key="registry" :term="`Upstream ${registry}`">{{ host || 'Not set' }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card data-testid="prewarming">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Pre-warming</CardTitle>
|
||||
<CardDescription>Fetches the most requested packages ahead of clients.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<DescriptionList :columns="1" divided>
|
||||
<DescriptionItem term="Status">
|
||||
<StatusBadge :status="info.prewarming.enabled ? 'on' : 'off'" :label="info.prewarming.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Interval">{{ duration(info.prewarming.interval, 'None') }}</DescriptionItem>
|
||||
<DescriptionItem term="Top packages">{{ info.prewarming.top_packages }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Button :icon-start="faRotateRight" :loading="triggering" :disabled="!info.prewarming.enabled" @click="trigger">Run a cycle now</Button>
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
{{ info.prewarming.enabled ? 'Needs the admin API key.' : 'Pre-warming is off in the configuration.' }}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a pre-warming cycle." @saved="trigger" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatusBadge,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import AdminKeyDialog from './parts/AdminKeyDialog.vue'
|
||||
import RescanPanel from './parts/RescanPanel.vue'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { formatBytes, formatDuration } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
import { describePolicy, scannerState, scannerVersion, useSystem, type ScannerInfo } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
const adminKey = useAdminKey()
|
||||
const toasts = useToastStore()
|
||||
|
||||
const triggering = ref(false)
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
|
||||
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
|
||||
|
||||
const scannerColumns: DataTableColumn<ScannerInfo>[] = [
|
||||
{ key: 'name', header: 'Scanner', rowHeader: true },
|
||||
{ key: 'state', header: 'State', accessor: (s) => scannerState(s) },
|
||||
{ key: 'version', header: 'Version' },
|
||||
]
|
||||
|
||||
/** Seconds as words; zero means the feature is off, so `zero` explains that. */
|
||||
function duration(seconds: number, zero: string, before = '', after = ''): string {
|
||||
return seconds === 0 ? zero : `${before}${formatDuration(seconds)}${after}`
|
||||
}
|
||||
|
||||
async function trigger() {
|
||||
adminKey.load()
|
||||
if (!adminKey.key.value) {
|
||||
showKeyDialog.value = true
|
||||
return
|
||||
}
|
||||
triggering.value = true
|
||||
try {
|
||||
await axios.post('/api/admin/prewarming/trigger', null, { headers: adminKey.headers.value })
|
||||
toasts.success('Pre-warming started', 'The cycle runs in the background.')
|
||||
} catch (err) {
|
||||
const status = (err as { response?: { status?: number } }).response?.status
|
||||
if (status === 401 || status === 403) {
|
||||
adminKey.clear()
|
||||
toasts.error('Admin key refused', 'Enter a key with the admin role.')
|
||||
} else {
|
||||
toasts.error('Could not start pre-warming', err instanceof Error ? err.message : 'Request failed')
|
||||
}
|
||||
} finally {
|
||||
triggering.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void load(true))
|
||||
</script>
|
||||
@@ -0,0 +1,227 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { TREND } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import { formatTrendDate, trendValues } from '@/lib/trend'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockReset()
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: TREND })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(props: Record<string, unknown> = {}) {
|
||||
const router = await createTestRouter('/stats')
|
||||
const mounted = await mountStrict(TrendChart, { props, global: { plugins: [router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
|
||||
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
|
||||
|
||||
describe('TrendChart', () => {
|
||||
it('says so when there is a single day of history, and names the plotted series', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: TREND.points.slice(0, 1) } })
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.findAll('[data-testid="trend-single-day"]')).toHaveLength(1)
|
||||
expect(wrapper.text()).toContain('One day of history so far')
|
||||
expect(wrapper.get('[data-testid="trend-series-key"]').text()).toContain('Plotted: packages with any finding.')
|
||||
})
|
||||
|
||||
it('does not show the single-day note with several days', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toContain('One day of history so far')
|
||||
})
|
||||
|
||||
it('requests the 30 day trend and draws both charts with accessible names', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
const labels = charts(wrapper).map((c) => c.attributes('aria-label'))
|
||||
expect(labels).toHaveLength(2)
|
||||
expect(labels[0]).toContain('Cached packages per day, from 3 on 2 Jan 2026 to 4 on 4 Jan 2026')
|
||||
expect(labels[1]).toContain('Vulnerable packages per day, from 1 on 3 Jan 2026 to 2 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
it('offers every value as text through the chart data table', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tables = wrapper.findAll('table')
|
||||
|
||||
expect(tables.length).toBeGreaterThanOrEqual(2)
|
||||
expect(tables[0]!.text()).toContain('Cached packages')
|
||||
expect(tables[0]!.text()).toContain('4')
|
||||
})
|
||||
|
||||
it('refetches when the period changes', async () => {
|
||||
const { wrapper } = await open()
|
||||
const ninety = wrapper.findAll('[role="radio"]').find((r) => r.text() === '90 days')!
|
||||
|
||||
await ninety.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day', '/api/stats/trend?period=90day'])
|
||||
})
|
||||
|
||||
it('draws the vulnerable total first and adds a line for each severity that is switched on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const vulnerable = () => charts(wrapper)[1]!.attributes('aria-label')
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
|
||||
const critical = wrapper.findAll('button[aria-pressed]').find((b) => b.text() === 'Critical')!
|
||||
expect(critical.attributes('aria-pressed')).toBe('false')
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(critical.attributes('aria-pressed')).toBe('true')
|
||||
expect(vulnerable()).toContain('with lines for critical')
|
||||
expect(wrapper.text()).toContain('Packages with critical vulnerabilities')
|
||||
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
})
|
||||
|
||||
it('offers all four severities as toggle buttons', async () => {
|
||||
const { wrapper } = await open()
|
||||
const names = wrapper.findAll('button[aria-pressed]').map((b) => b.text())
|
||||
expect(names).toEqual(['Critical', 'High', 'Moderate', 'Low'])
|
||||
})
|
||||
|
||||
it('says plainly when vulnerability history starts after the first day', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toBe('Vulnerability history starts 3 Jan 2026.')
|
||||
})
|
||||
|
||||
it('shows no note when every day has vulnerability data', async () => {
|
||||
const full = { ...TREND, vulnerability_history_start: TREND.points[0]!.date }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: full })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.find('[data-testid="trend-vulnerability-note"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('shows an empty state instead of the vulnerable chart while no scan data exists', async () => {
|
||||
const noScans = {
|
||||
...TREND,
|
||||
vulnerability_history_start: null,
|
||||
points: TREND.points.map((p) => ({ ...p, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null })),
|
||||
}
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: noScans })
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('Vulnerability history has not started')
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toContain('has not started in this period')
|
||||
})
|
||||
|
||||
it('shows an empty state when the server holds no snapshots', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, vulnerability_history_start: null, points: [] } })
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('No history yet')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shows a loading state until the first answer arrives', async () => {
|
||||
let resolve!: (value: unknown) => void
|
||||
vi.mocked(axios.get).mockReturnValue(new Promise((r) => (resolve = r)) as never)
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading package history...')
|
||||
resolve({ data: TREND })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).not.toContain('Loading package history...')
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('shows the error with a retry that fetches again', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValueOnce(new Error('Request failed with status code 502'))
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
const state = wrapper.get('[data-slot="error-state"]')
|
||||
expect(state.text()).toContain('502')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
|
||||
await state.get('button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
expect(requested()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('rejects a body without points as an error, not an empty chart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { stats: {} } })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-slot="error-state"]').text()).toContain('Unexpected response format')
|
||||
})
|
||||
|
||||
it('ignores an answer that a newer request has replaced', async () => {
|
||||
const answers: Array<(v: unknown) => void> = []
|
||||
vi.mocked(axios.get).mockImplementation(() => new Promise((r) => answers.push(r)) as never)
|
||||
const { wrapper } = await open()
|
||||
await wrapper.findAll('[role="radio"]').find((r) => r.text() === '1 year')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
answers[1]!({ data: { ...TREND, period: '1year', points: [TREND.points[2]] } })
|
||||
await flushPromises()
|
||||
answers[0]!({ data: TREND })
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.get('svg[role="img"]').attributes('aria-label')).toContain('from 4 on 4 Jan 2026 to 4 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
describe('compact', () => {
|
||||
it('always asks for 30 days, draws one chart and links to the full history', async () => {
|
||||
const { wrapper, problems } = await open({ compact: true })
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.find('[role="radiogroup"]').exists()).toBe(false)
|
||||
expect(wrapper.find('button[aria-pressed]').exists()).toBe(false)
|
||||
expect(wrapper.get('a[href="/stats"]').text()).toBe('Open the full history')
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('2 vulnerable packages on 4 Jan 2026.')
|
||||
})
|
||||
|
||||
it('says so when the latest day has no vulnerability data', async () => {
|
||||
const last = { ...TREND.points[2]!, vulnerable_packages: null }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: [TREND.points[0]!, last] } })
|
||||
const { wrapper } = await open({ compact: true })
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('Vulnerability history has not started yet.')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('trend helpers', () => {
|
||||
it('formats a UTC date without shifting it with the viewer zone', () => {
|
||||
expect(formatTrendDate('2026-11-23')).toBe('23 Nov')
|
||||
expect(formatTrendDate('2026-01-01', true)).toBe('1 Jan 2026')
|
||||
expect(formatTrendDate('not-a-date')).toBe('not-a-date')
|
||||
})
|
||||
|
||||
it('turns unknown counts into gaps, never zeros', () => {
|
||||
const values = trendValues(TREND.points, 'vulnerable_packages')
|
||||
expect(values[0]).toBeNaN()
|
||||
expect(values.slice(1)).toEqual([1, 2])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,210 @@
|
||||
<template>
|
||||
<Card data-testid="trend-card">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">{{ compact ? 'Cached packages' : 'Packages over time' }}</CardTitle>
|
||||
<CardDescription>
|
||||
{{ compact ? 'Daily total, last 30 days.' : 'The cache at the end of each UTC day.' }}
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<SegmentedControl v-if="!compact" v-model="period" :options="TREND_PERIODS" aria-label="Trend period" />
|
||||
<Button v-else as-child variant="link" size="sm">
|
||||
<RouterLink to="/stats">Open the full history</RouterLink>
|
||||
</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-8">
|
||||
<LoadingState v-if="loading && !data" layout="inline" label="Loading package history..." />
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="inline"
|
||||
title="Could not load the package history"
|
||||
:message="error"
|
||||
@retry="load"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="points.length === 0"
|
||||
title="No history yet"
|
||||
description="The server records the first daily snapshot when it starts, then one more each day."
|
||||
/>
|
||||
<template v-else>
|
||||
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
|
||||
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
|
||||
<p v-if="singleDay" class="m-0 text-sm text-muted-foreground" data-testid="trend-single-day">{{ SINGLE_DAY_NOTE }}</p>
|
||||
<LineChart
|
||||
variant="area"
|
||||
:size="compact ? 'sm' : 'md'"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="[{ name: 'Cached packages', data: values('total_packages'), tone: 'primary' }]"
|
||||
:label="packagesLabel"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<p v-if="compact" class="text-sm text-muted-foreground" data-testid="trend-compact-vulnerable">
|
||||
{{ compactVulnerable }}
|
||||
</p>
|
||||
|
||||
<section v-else class="flex flex-col gap-3" aria-labelledby="trend-vulnerable-heading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 id="trend-vulnerable-heading" class="text-sm font-medium">Vulnerable packages</h3>
|
||||
<ToggleGroup
|
||||
v-model="severities"
|
||||
type="multiple"
|
||||
variant="outline"
|
||||
tone="primary"
|
||||
size="sm"
|
||||
aria-label="Add a line per severity"
|
||||
>
|
||||
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
|
||||
{{ formatSeverityName(level) }}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
|
||||
{{ vulnerabilityNote }}
|
||||
</p>
|
||||
<p v-if="singleDay" class="m-0 text-sm text-muted-foreground">{{ SINGLE_DAY_NOTE }}</p>
|
||||
<p class="m-0 text-sm text-muted-foreground" data-testid="trend-series-key">{{ seriesKey }}</p>
|
||||
<LineChart
|
||||
v-if="data?.vulnerability_history_start"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="vulnerableSeries"
|
||||
:label="vulnerableLabel"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else
|
||||
size="sm"
|
||||
title="Vulnerability history has not started"
|
||||
description="Scan results are counted from the first daily snapshot that includes them."
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LineChart,
|
||||
LoadingState,
|
||||
SegmentedControl,
|
||||
ToggleGroup,
|
||||
ToggleGroupItem,
|
||||
} from '@perfect-design/ui'
|
||||
import { plural } from '@/lib/reason'
|
||||
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
import {
|
||||
DEFAULT_TREND_PERIOD,
|
||||
SEVERITY_LINE_TONES,
|
||||
TREND_PERIODS,
|
||||
formatTrendDate,
|
||||
trendValues,
|
||||
type TrendPeriod,
|
||||
type TrendPoint,
|
||||
type TrendResponse,
|
||||
} from '@/lib/trend'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Dashboard card: 30 days, cached packages only, a link to the full history. */
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const period = ref<TrendPeriod>(DEFAULT_TREND_PERIOD)
|
||||
const severities = ref<SeverityLevel[]>([])
|
||||
const data = ref<TrendResponse | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
let request = 0
|
||||
|
||||
async function load() {
|
||||
const current = ++request
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/trend?period=${props.compact ? DEFAULT_TREND_PERIOD : period.value}`)
|
||||
if (current !== request) return
|
||||
const body = response.data as TrendResponse | undefined
|
||||
if (!body || !Array.isArray(body.points)) {
|
||||
data.value = null
|
||||
error.value = 'Unexpected response format from server'
|
||||
return
|
||||
}
|
||||
data.value = body
|
||||
} catch (err) {
|
||||
if (current !== request) return
|
||||
data.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load the package history'
|
||||
} finally {
|
||||
if (current === request) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
watch(period, load)
|
||||
|
||||
const points = computed<TrendPoint[]>(() => data.value?.points ?? [])
|
||||
const labels = computed(() => points.value.map((p) => formatTrendDate(p.date, period.value === '1year')))
|
||||
const values = (key: keyof Omit<TrendPoint, 'date'>) => trendValues(points.value, key)
|
||||
|
||||
function span(key: keyof Omit<TrendPoint, 'date'>): string {
|
||||
const known = points.value.filter((p) => p[key] !== null)
|
||||
const first = known[0]
|
||||
const last = known[known.length - 1]
|
||||
if (!first || !last) return ''
|
||||
return `from ${first[key]} on ${formatTrendDate(first.date, true)} to ${last[key]} on ${formatTrendDate(last.date, true)}`
|
||||
}
|
||||
|
||||
const packagesLabel = computed(() => `Cached packages per day, ${span('total_packages')}`)
|
||||
const vulnerableLabel = computed(() => {
|
||||
const extra = severities.value.length ? `, with lines for ${severities.value.join(', ')}` : ''
|
||||
return `Vulnerable packages per day, ${span('vulnerable_packages')}${extra}`
|
||||
})
|
||||
|
||||
const vulnerableSeries = computed(() => [
|
||||
{ name: 'Vulnerable packages', data: values('vulnerable_packages'), tone: 'primary' as const },
|
||||
...SEVERITY_LEVELS.filter((level) => severities.value.includes(level)).map((level) => ({
|
||||
name: `Packages with ${level} vulnerabilities`,
|
||||
data: values(level),
|
||||
tone: SEVERITY_LINE_TONES[level],
|
||||
})),
|
||||
])
|
||||
|
||||
const SINGLE_DAY_NOTE = 'One day of history so far. A line appears once there is a second day.'
|
||||
const singleDay = computed(() => points.value.length === 1)
|
||||
|
||||
const seriesKey = computed(() => {
|
||||
const all = 'Plotted: packages with any finding.'
|
||||
if (severities.value.length === 0) return `${all} Select a severity to add its own line.`
|
||||
return `${all} Added: ${severities.value.join(', ')}.`
|
||||
})
|
||||
|
||||
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
|
||||
const vulnerabilityNote = computed(() => {
|
||||
const start = data.value?.vulnerability_history_start
|
||||
const first = points.value[0]
|
||||
if (!start) return 'Vulnerability history has not started in this period.'
|
||||
if (first && start > first.date) return `Vulnerability history starts ${formatTrendDate(start, true)}.`
|
||||
return ''
|
||||
})
|
||||
|
||||
const compactVulnerable = computed(() => {
|
||||
const last = points.value[points.value.length - 1]
|
||||
const n = last?.vulnerable_packages
|
||||
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
|
||||
return `${plural(n, 'vulnerable package')} on ${formatTrendDate(last!.date, true)}.`
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,83 @@
|
||||
<template>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge
|
||||
v-if="isBlocked"
|
||||
status="blocked"
|
||||
label="Blocked"
|
||||
variant="solid"
|
||||
title="Download blocked: exceeds vulnerability thresholds"
|
||||
/>
|
||||
|
||||
<button
|
||||
v-for="level in presentLevels"
|
||||
:key="level"
|
||||
type="button"
|
||||
:class="buttonVariants({ variant: 'ghost', size: 'xs' })"
|
||||
:aria-label="`${counts[level]} ${level} ${counts[level] === 1 ? 'vulnerability' : 'vulnerabilities'}, view details`"
|
||||
@click="handleClick(level)"
|
||||
>
|
||||
<StatusBadge :status="level" :tones="SEVERITY_TONES" :label="`${formatSeverityName(level)}: ${counts[level]}`" />
|
||||
</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>
|
||||
|
||||
<StatusBadge
|
||||
v-if="status === 'pending'"
|
||||
status="pending"
|
||||
label="Scanning"
|
||||
pulse
|
||||
title="Security scan in progress"
|
||||
/>
|
||||
|
||||
<StatusBadge
|
||||
v-if="status === 'not_scanned' || !scanned"
|
||||
status="not_scanned"
|
||||
label="Not scanned"
|
||||
:tones="{ not_scanned: 'neutral' }"
|
||||
title="Not yet scanned for vulnerabilities"
|
||||
/>
|
||||
</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
|
||||
status?: 'clean' | 'vulnerable' | 'pending' | 'not_scanned'
|
||||
counts?: VulnerabilityCounts
|
||||
total?: number
|
||||
scannedAt?: string // ISO 8601 timestamp
|
||||
isBlocked?: boolean // Whether download is blocked due to vulnerabilities
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
scanned: false,
|
||||
status: 'not_scanned',
|
||||
total: 0,
|
||||
isBlocked: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
click: [severity: string]
|
||||
}>()
|
||||
|
||||
const counts = computed(() => props.counts || NO_VULNERABILITIES)
|
||||
const presentLevels = computed(() => SEVERITY_LEVELS.filter((level) => counts.value[level] > 0))
|
||||
|
||||
function handleClick(severity: string) {
|
||||
emit('click', severity)
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,46 @@
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="(value: boolean) => emit('update:open', value)">
|
||||
<DialogContent size="sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Admin API key</DialogTitle>
|
||||
<DialogDescription>{{ description }}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form class="flex flex-col gap-4" @submit.prevent="submit">
|
||||
<Field label="API key" required>
|
||||
<Input v-model="draft" type="password" autocomplete="off" />
|
||||
</Field>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="emit('update:open', false)">Cancel</Button>
|
||||
<Button type="submit" :disabled="draft.trim() === ''">Continue</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Field, Input } from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
|
||||
const props = defineProps<{ open: boolean; description: string }>()
|
||||
const emit = defineEmits<{ 'update:open': [open: boolean]; saved: [] }>()
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const draft = ref('')
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) draft.value = ''
|
||||
},
|
||||
)
|
||||
|
||||
function submit() {
|
||||
const value = draft.value.trim()
|
||||
if (!value) return
|
||||
adminKey.save(value)
|
||||
emit('update:open', false)
|
||||
emit('saved')
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,119 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<section v-if="applied" class="flex flex-col gap-3" aria-labelledby="bypass-applied-heading">
|
||||
<h3 id="bypass-applied-heading" class="m-0 text-sm font-semibold">Bypass in effect</h3>
|
||||
<DescriptionList :columns="2" divided data-testid="applied-bypass">
|
||||
<DescriptionItem term="Scope">{{ applied.type === 'package' ? 'Whole package' : 'One advisory' }}</DescriptionItem>
|
||||
<DescriptionItem term="Target"><InlineCode>{{ applied.target }}</InlineCode></DescriptionItem>
|
||||
<DescriptionItem term="Reason">{{ applied.reason }}</DescriptionItem>
|
||||
<DescriptionItem term="Created by">{{ applied.created_by }}</DescriptionItem>
|
||||
<DescriptionItem term="Created"><RelativeTime :datetime="applied.created_at" /></DescriptionItem>
|
||||
<DescriptionItem term="Expires">{{ formatDate(applied.expires_at) }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</section>
|
||||
<p v-else class="m-0 text-sm text-muted-foreground">No bypass applies to this package.</p>
|
||||
|
||||
<section class="flex flex-col gap-3" aria-labelledby="bypass-list-heading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 id="bypass-list-heading" class="m-0 text-sm font-semibold">Bypasses that cover this package</h3>
|
||||
<Button :as="RouterLink" :to="addRoute" variant="outline" size="sm" :icon-start="faPlus">Add a bypass</Button>
|
||||
</div>
|
||||
<Callout v-if="!adminKey.key.value" type="note" size="sm" title="Admin key needed">
|
||||
Listing bypasses needs the admin API key. Enter it on the
|
||||
<Link :as="RouterLink" to="/admin/bypasses">Bypasses page</Link>.
|
||||
</Callout>
|
||||
<LoadingState v-else-if="loading" layout="inline" label="Loading bypasses..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load bypasses" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="covering.length === 0" size="sm" title="No bypass covers this package" description="Add one to serve it despite the findings." />
|
||||
<DataTable v-else label="Bypasses covering this package" layout="cards" density="compact" :columns="columns" :rows="covering">
|
||||
<template #cell-status="{ row }">
|
||||
<StatusBadge :status="statusOf(row)" :label="STATUS_LABELS[statusOf(row)]" :tones="STATUS_TONES" />
|
||||
</template>
|
||||
<template #cell-target="{ row }"><InlineCode>{{ row.target }}</InlineCode></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
Callout,
|
||||
DataTable,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
InlineCode,
|
||||
Link,
|
||||
LoadingState,
|
||||
RelativeTime,
|
||||
StatusBadge,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { bypassesFor, isExpired, type Bypass } from '@/lib/bypass'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { faPlus } from '@/lib/icons'
|
||||
import type { AppliedBypass } from '@/stores/packages'
|
||||
|
||||
const props = defineProps<{
|
||||
applied: AppliedBypass | null
|
||||
registry: string
|
||||
name: string
|
||||
version: string
|
||||
releaseVersion?: string
|
||||
}>()
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const all = ref<Bypass[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
type BypassStatus = 'active' | 'expired' | 'inactive'
|
||||
const STATUS_LABELS: Record<BypassStatus, string> = { active: 'Active', expired: 'Expired', inactive: 'Inactive' }
|
||||
const STATUS_TONES = { active: 'success', expired: 'neutral', inactive: 'neutral' } as const
|
||||
|
||||
function statusOf(b: Bypass): BypassStatus {
|
||||
if (isExpired(b.expires_at)) return 'expired'
|
||||
return b.active ? 'active' : 'inactive'
|
||||
}
|
||||
|
||||
const covering = computed(() =>
|
||||
bypassesFor(all.value, { registry: props.registry, name: props.name, version: props.version, releaseVersion: props.releaseVersion }),
|
||||
)
|
||||
|
||||
const addRoute = computed(() => ({
|
||||
path: '/admin/bypasses',
|
||||
query: { type: 'package', target: `${props.registry}/${props.name}@${props.releaseVersion || props.version}` },
|
||||
}))
|
||||
|
||||
const columns: DataTableColumn<Bypass>[] = [
|
||||
{ key: 'target', header: 'Target', rowHeader: true },
|
||||
{ key: 'type', header: 'Type' },
|
||||
{ key: 'status', header: 'Status', accessor: (b) => statusOf(b) },
|
||||
{ key: 'reason', header: 'Reason' },
|
||||
{ key: 'created_by', header: 'Created by' },
|
||||
{ key: 'expires_at', header: 'Expires', accessor: (b) => formatDate(b.expires_at) },
|
||||
]
|
||||
|
||||
async function load() {
|
||||
if (!adminKey.key.value) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<{ bypasses: Bypass[] }>('/api/admin/bypasses?include_expired=true', { headers: adminKey.headers.value })
|
||||
all.value = response.data.bypasses ?? []
|
||||
} catch (err) {
|
||||
const status = (err as { response?: { status?: number } }).response?.status
|
||||
error.value = status === 401 || status === 403 ? 'The admin key was refused.' : err instanceof Error ? err.message : 'Failed to load bypasses'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,86 @@
|
||||
<template>
|
||||
<Card class="min-w-0" data-testid="cache-capacity">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Cache capacity</CardTitle>
|
||||
<CardDescription>Disk the cache holds, by registry.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<StatBar
|
||||
v-if="maxSize > 0"
|
||||
label="Used"
|
||||
tone="auto"
|
||||
:value="used"
|
||||
:max="maxSize"
|
||||
:value-text="`${formatBytes(used)} of ${formatBytes(maxSize)}`"
|
||||
/>
|
||||
<p v-else class="m-0 text-sm text-muted-foreground">
|
||||
<span class="font-medium text-foreground">{{ formatBytes(used) }}</span> used. No size limit is set.
|
||||
</p>
|
||||
|
||||
<EmptyState v-if="rows.length === 0" size="sm" title="Nothing cached" description="Each registry appears here after its first download." />
|
||||
<template v-else>
|
||||
<DonutChart
|
||||
:data="donut"
|
||||
:value-formatter="formatBytes"
|
||||
center-text="cached"
|
||||
label="Cache size by registry"
|
||||
layout="stacked"
|
||||
size="md"
|
||||
/>
|
||||
<DataTable label="Cache by registry" layout="cards" density="compact" :columns="columns" :rows="rows" row-key="registry">
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
</DataTable>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
Badge,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
DonutChart,
|
||||
EmptyState,
|
||||
StatBar,
|
||||
type DataTableColumn,
|
||||
type DonutDatum,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, formatNumber } from '@/lib/format'
|
||||
|
||||
export interface RegistryUsage {
|
||||
registry: string
|
||||
count: number
|
||||
size: number
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
used: number
|
||||
maxSize: number
|
||||
registries: Record<string, { count?: number; size?: number; downloads?: number }>
|
||||
}>()
|
||||
|
||||
const rows = computed<RegistryUsage[]>(() =>
|
||||
Object.entries(props.registries)
|
||||
.map(([registry, r]) => ({ registry, count: r.count ?? 0, size: r.size ?? 0, downloads: r.downloads ?? 0 }))
|
||||
.sort((a, b) => b.size - a.size),
|
||||
)
|
||||
// chart-1 and chart-2 are neighbouring teals in this theme, so each registry gets a distinct hue.
|
||||
const REGISTRY_TONES: Record<string, DonutDatum['tone']> = { npm: 'info', go: 'primary', pypi: 'warning' }
|
||||
const SPARE_TONES: DonutDatum['tone'][] = ['danger', 'success', 'muted']
|
||||
const donut = computed<DonutDatum[]>(() =>
|
||||
rows.value.map((r, i) => ({ label: r.registry, value: r.size, tone: REGISTRY_TONES[r.registry] ?? SPARE_TONES[i % SPARE_TONES.length] })),
|
||||
)
|
||||
|
||||
const columns: DataTableColumn<RegistryUsage>[] = [
|
||||
{ key: 'registry', header: 'Registry', rowHeader: true },
|
||||
{ key: 'count', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.count) },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (r) => formatBytes(r.size) },
|
||||
]
|
||||
</script>
|
||||
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<Card class="min-w-0" data-testid="download-trend">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Downloads</CardTitle>
|
||||
<CardDescription>Packages served to clients, in UTC.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<div class="flex sm:justify-end">
|
||||
<SegmentedControl v-model="period" :options="DOWNLOAD_PERIODS" aria-label="Download period" />
|
||||
</div>
|
||||
<LoadingState v-if="loading && points.length === 0" layout="inline" label="Loading downloads..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load downloads" :message="error" @retry="load" />
|
||||
<LineChart
|
||||
v-else
|
||||
variant="area"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="[{ name: 'Downloads', data: values, tone: 'primary' }]"
|
||||
:label="`Downloads over the last ${periodLabel}, ${total} in total`"
|
||||
empty-text="No downloads in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
ErrorState,
|
||||
LineChart,
|
||||
LoadingState,
|
||||
SegmentedControl,
|
||||
} from '@perfect-design/ui'
|
||||
import { DOWNLOAD_PERIODS, bucketLabel, type DownloadPeriod, type TimeSeries } from '@/lib/timeseries'
|
||||
|
||||
const period = ref<DownloadPeriod>('1day')
|
||||
const data = ref<TimeSeries | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
let request = 0
|
||||
|
||||
const points = computed(() => data.value?.data_points ?? [])
|
||||
const values = computed(() => points.value.map((p) => p.value))
|
||||
const labels = computed(() => points.value.map((p) => bucketLabel(period.value, p.timestamp)))
|
||||
const total = computed(() => values.value.reduce((sum, v) => sum + v, 0))
|
||||
const periodLabel = computed(() => DOWNLOAD_PERIODS.find((p) => p.value === period.value)?.label ?? '')
|
||||
|
||||
async function load() {
|
||||
const current = ++request
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<TimeSeries>(`/api/stats/timeseries?period=${period.value}`)
|
||||
if (current === request) data.value = response.data
|
||||
} catch (err) {
|
||||
if (current !== request) return
|
||||
data.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load downloads'
|
||||
} finally {
|
||||
if (current === request) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(period, load)
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,58 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import DownloadsPanel from './DownloadsPanel.vue'
|
||||
import { PACKAGE_ANALYTICS } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
async function open(props: { registry: string; name: string; downloadCount: number }) {
|
||||
const mounted = await mountStrict(DownloadsPanel, { props })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(axios.get).mockReset()
|
||||
})
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
})
|
||||
|
||||
describe('DownloadsPanel', () => {
|
||||
it('shows the stored count even when analytics have no record since the restart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { package: null } })
|
||||
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 12 })
|
||||
|
||||
expect(wrapper.text()).toContain('12')
|
||||
expect(wrapper.text()).toContain('No downloads since the last restart')
|
||||
expect(wrapper.text()).not.toContain('Could not load')
|
||||
})
|
||||
|
||||
it('adds the in-memory totals and labels them as since the restart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: PACKAGE_ANALYTICS })
|
||||
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 12 })
|
||||
|
||||
expect(wrapper.text()).toContain('kept across restarts')
|
||||
expect(wrapper.text()).toContain('2 versions since the last restart')
|
||||
expect(wrapper.text()).toContain('80 KB')
|
||||
})
|
||||
|
||||
it('asks for a Go module by its path, with no cache-file suffix', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { package: null } })
|
||||
await open({ registry: 'go', name: 'github.com/google/uuid/@v/v1.6.0.zip', downloadCount: 2 })
|
||||
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/analytics/package/go/github.com/google/uuid')
|
||||
})
|
||||
|
||||
it('reports a failed request', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValue(new Error('boom'))
|
||||
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 1 })
|
||||
expect(wrapper.text()).toContain('Could not load download history')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading download history..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load download history" :message="error" @retry="load" />
|
||||
<div v-else class="flex flex-col gap-4">
|
||||
<StatGroup :columns="3" aria-label="Downloads of this package">
|
||||
<KpiTile label="This version" :value="downloadCount" hint="Times served from the cache, kept across restarts" />
|
||||
<template v-if="stats">
|
||||
<KpiTile
|
||||
label="All versions"
|
||||
:value="stats.TotalDownloads"
|
||||
:hint="`${stats.UniqueVersions} version${stats.UniqueVersions === 1 ? '' : 's'} since the last restart`"
|
||||
/>
|
||||
<KpiTile label="Data served" :value="formatBytes(stats.BytesServed)" hint="Across all versions, since the last restart" />
|
||||
</template>
|
||||
</StatGroup>
|
||||
<DescriptionList v-if="stats" :columns="2" divided>
|
||||
<DescriptionItem term="First seen since restart"><RelativeTime :datetime="stats.FirstSeen" /></DescriptionItem>
|
||||
<DescriptionItem term="Last download"><RelativeTime :datetime="stats.LastDownload" /></DescriptionItem>
|
||||
</DescriptionList>
|
||||
<EmptyState
|
||||
v-else
|
||||
size="sm"
|
||||
:icon="faDownload"
|
||||
title="No downloads since the last restart"
|
||||
description="The totals across versions are counted in memory, so they start again when the server restarts."
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
RelativeTime,
|
||||
StatGroup,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, modulePath } from '@/lib/format'
|
||||
import { faDownload } from '@/lib/icons'
|
||||
|
||||
/** The analytics engine serialises Go field names. */
|
||||
interface PackageAnalytics {
|
||||
TotalDownloads: number
|
||||
UniqueVersions: number
|
||||
BytesServed: number
|
||||
FirstSeen: string
|
||||
LastDownload: string
|
||||
}
|
||||
|
||||
const props = defineProps<{ registry: string; name: string; downloadCount: number }>()
|
||||
|
||||
const stats = ref<PackageAnalytics | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Analytics are keyed by package name; a Go module is named by its path.
|
||||
const analyticsName = computed(() => modulePath(props.name))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<{ package: PackageAnalytics | null }>(
|
||||
`/api/analytics/package/${props.registry}/${analyticsName.value}`,
|
||||
)
|
||||
stats.value = response.data.package
|
||||
} catch (err) {
|
||||
stats.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load download history'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
Each scanner reports its own findings before they are merged. A finding several scanners agree on counts once in the verdict.
|
||||
</p>
|
||||
<DataTable label="Findings by scanner and severity" layout="cards" density="compact" row-key="name" :columns="columns" :rows="rows">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-status="{ row }">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge :status="row.status" :label="INSPECTOR_STATUS_LABELS[row.status]" :tones="STATUS_TONES" />
|
||||
<StatusBadge v-if="row.health === 'down'" status="down" label="Unavailable now" :tones="{ down: 'danger' }" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ row.version ? `v${row.version}` : 'Not reported' }}</template>
|
||||
</DataTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { DataTable, StatusBadge, type DataTableColumn } from '@perfect-design/ui'
|
||||
import { INSPECTOR_STATUS_LABELS, inspectorRows, type InspectorRow, type ScannerResult } from '@/lib/inspectors'
|
||||
import type { ScannerInfo } from '@/lib/system'
|
||||
|
||||
const props = defineProps<{
|
||||
registry: string
|
||||
results: readonly ScannerResult[]
|
||||
configured: readonly ScannerInfo[]
|
||||
}>()
|
||||
|
||||
const STATUS_TONES = { reported: 'success', 'no-result': 'warning', 'not-applicable': 'neutral', off: 'neutral' } as const
|
||||
|
||||
const rows = computed(() => inspectorRows(props.registry, props.results, props.configured))
|
||||
|
||||
function count(row: InspectorRow, level: 'critical' | 'high' | 'moderate' | 'low'): string {
|
||||
return row.counts ? String(row.counts[level]) : '–'
|
||||
}
|
||||
|
||||
const columns: DataTableColumn<InspectorRow>[] = [
|
||||
{ key: 'name', header: 'Scanner', rowHeader: true },
|
||||
{ key: 'critical', header: 'Critical', numeric: true, accessor: (r) => count(r, 'critical') },
|
||||
{ key: 'high', header: 'High', numeric: true, accessor: (r) => count(r, 'high') },
|
||||
{ key: 'moderate', header: 'Moderate', numeric: true, accessor: (r) => count(r, 'moderate') },
|
||||
{ key: 'low', header: 'Low', numeric: true, accessor: (r) => count(r, 'low') },
|
||||
{ key: 'status', header: 'Status' },
|
||||
{ key: 'version', header: 'Version' },
|
||||
]
|
||||
</script>
|
||||
@@ -0,0 +1,68 @@
|
||||
<template>
|
||||
<Sheet :open="pkg !== null" @update:open="(open: boolean) => !open && emit('close')">
|
||||
<SheetContent side="right" size="md">
|
||||
<template v-if="pkg">
|
||||
<SheetHeader>
|
||||
<SheetTitle class="break-words">{{ pkg.name }}</SheetTitle>
|
||||
<SheetDescription>{{ withVersionPrefix(displayVersion(pkg)) }} from {{ pkg.registry }}</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div class="flex flex-col gap-5 px-4 pb-4">
|
||||
<div class="flex flex-col gap-2">
|
||||
<VerdictBadge :verdict="verdict" class="self-start" />
|
||||
<p v-if="explanation" class="m-0 text-sm text-muted-foreground" data-testid="quick-view-reason">{{ explanation }}</p>
|
||||
</div>
|
||||
|
||||
<SeveritySummary v-if="pkg.vulnerabilities?.counts" class="grid-cols-2! lg:grid-cols-2!" :counts="pkg.vulnerabilities.counts" label="Findings by severity" />
|
||||
|
||||
<DescriptionList :columns="1" divided>
|
||||
<DescriptionItem term="Size">{{ formatBytes(pkg.size) }}</DescriptionItem>
|
||||
<DescriptionItem term="Downloads">{{ formatNumber(pkg.download_count) }}</DescriptionItem>
|
||||
<DescriptionItem term="Cached"><RelativeTime :datetime="pkg.cached_at" /></DescriptionItem>
|
||||
<DescriptionItem term="Last accessed"><RelativeTime :datetime="pkg.last_accessed" /></DescriptionItem>
|
||||
<DescriptionItem term="Last scanned">
|
||||
<RelativeTime v-if="pkg.vulnerabilities?.scannedAt" :datetime="pkg.vulnerabilities.scannedAt" />
|
||||
<template v-else>Never</template>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
|
||||
<SheetFooter>
|
||||
<Button :as="RouterLink" :to="packageRoute(pkg)" :icon-end="faArrowRight">Open full page</Button>
|
||||
<Button variant="outline" :icon-start="faTrash" @click="emit('delete', pkg)">Remove from cache</Button>
|
||||
</SheetFooter>
|
||||
</template>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
RelativeTime,
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from '../SeveritySummary.vue'
|
||||
import VerdictBadge from './VerdictBadge.vue'
|
||||
import type { Package } from '@/stores/packages'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { humanReason } from '@/lib/reason'
|
||||
import { faArrowRight, faTrash } from '@/lib/icons'
|
||||
import { VERDICT_MEANINGS, verdictOf } from '@/lib/verdict'
|
||||
|
||||
const props = defineProps<{ pkg: Package | null }>()
|
||||
const emit = defineEmits<{ close: []; delete: [pkg: Package] }>()
|
||||
|
||||
const verdict = computed(() => (props.pkg ? verdictOf(props.pkg) : 'unscanned'))
|
||||
const explanation = computed(() => humanReason(props.pkg?.vulnerabilities?.reason) || VERDICT_MEANINGS[verdict.value])
|
||||
</script>
|
||||
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<p class="m-0 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground" data-testid="policy-line">
|
||||
<template v-if="info">
|
||||
<span class="font-medium text-foreground">Policy</span>
|
||||
<span>{{ describePolicy(info.security) }}</span>
|
||||
<span v-if="info.security.enabled">{{ info.security.fail_closed ? 'Fail-closed' : 'Fail-open on scanner outage' }}.</span>
|
||||
<span v-if="info.security.enabled">{{ enabledScanners }} of {{ info.security.scanners.length }} scanners on.</span>
|
||||
<Link :as="RouterLink" to="/admin/system">System settings</Link>
|
||||
</template>
|
||||
<span v-else-if="error">Policy unavailable: {{ error }}</span>
|
||||
<span v-else>Loading policy...</span>
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import { Link } from '@perfect-design/ui'
|
||||
import { describePolicy, useSystem } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
const enabledScanners = computed(() => info.value?.security.scanners.filter((s) => s.enabled).length ?? 0)
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
@@ -0,0 +1,162 @@
|
||||
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 RescanPanel from './RescanPanel.vue'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
const idle = { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 }
|
||||
const running = { enabled: true, running: true, scope: 'vulnerable', queued: 10, done: 3, failed: 1, elapsed_seconds: 40, eta_seconds: 60 }
|
||||
let estimate: unknown
|
||||
const finished = { ...running, running: false, done: 9 }
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
let statuses: Array<typeof idle | typeof running>
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.setItem('admin_api_key', 'test-key')
|
||||
statuses = [idle]
|
||||
estimate = { vulnerable: { artifacts: 12, seconds: 30 }, all: { artifacts: 1200, seconds: 6000 }, avg_scan_seconds: 10, concurrency: 2 }
|
||||
vi.mocked(axios.get).mockReset()
|
||||
vi.mocked(axios.post).mockReset()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url === '/api/admin/rescan/status') return { data: statuses.length > 1 ? statuses.shift() : statuses[0] } as never
|
||||
if (url === '/api/admin/rescan/estimate') return { data: estimate } as never
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
localStorage.clear()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
async function open(props = { enabled: true, concurrency: 2 }) {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(RescanPanel, { props, global: { plugins: [pinia] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
const body = () => document.body.textContent ?? ''
|
||||
function dialogButton(label: string): HTMLButtonElement {
|
||||
const btn = [...document.body.querySelectorAll('[role="alertdialog"] button, [role="dialog"] button')].find((b) => b.textContent?.trim() === label)
|
||||
if (!btn) throw new Error(`no button "${label}"`)
|
||||
return btn as HTMLButtonElement
|
||||
}
|
||||
|
||||
describe('RescanPanel', () => {
|
||||
it('starts a vulnerable rescan with the admin key and shows progress', async () => {
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
|
||||
statuses = [idle, running]
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'vulnerable' }, { headers: { Authorization: 'Bearer test-key' } })
|
||||
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned, 1 failed, of 10 queued')
|
||||
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
|
||||
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('A rescan is running')
|
||||
})
|
||||
|
||||
it('asks before rescanning everything and says how long it takes', async () => {
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 1200, scope: 'all' } })
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
|
||||
expect(body()).toContain('re-runs all scanners on every cached artifact')
|
||||
expect(body()).toContain('1,200 artifacts, 2 at a time and 10.0 seconds each on recent scans: roughly 100 minutes')
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/admin/rescan/estimate', { headers: { Authorization: 'Bearer test-key' } })
|
||||
|
||||
dialogButton('Rescan everything').click()
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'all' }, expect.anything())
|
||||
})
|
||||
|
||||
it('does not invent an estimate before any scan was timed', async () => {
|
||||
estimate = { vulnerable: { artifacts: 1, seconds: null }, all: { artifacts: 7, seconds: null }, avg_scan_seconds: 0, concurrency: 2 }
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(body()).toContain('No scan has been timed yet, so there is no estimate.')
|
||||
expect(body()).not.toContain('roughly')
|
||||
})
|
||||
|
||||
it('shows the live rate and the time left while a rescan runs', async () => {
|
||||
statuses = [running]
|
||||
const wrapper = await open()
|
||||
// 4 processed in 40 s is 6 a minute; the server says 60 s remain.
|
||||
expect(wrapper.get('[data-testid="rescan-live"]').text()).toBe('6.0 artifacts a minute. About 1 minute left.')
|
||||
})
|
||||
|
||||
it('polls until the rescan finishes and then stops', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
|
||||
statuses = [idle, running, running, finished]
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
const statusCalls = () => vi.mocked(axios.get).mock.calls.filter(([url]) => url === '/api/admin/rescan/status').length
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2100)
|
||||
await vi.advanceTimersByTimeAsync(2100)
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('Finished.')
|
||||
const settled = statusCalls()
|
||||
await vi.advanceTimersByTimeAsync(10000)
|
||||
expect(statusCalls()).toBe(settled)
|
||||
})
|
||||
|
||||
it('shows the running rescan when the server answers 409', async () => {
|
||||
vi.mocked(axios.post).mockRejectedValue({ response: { status: 409 } })
|
||||
statuses = [idle, running]
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned')
|
||||
})
|
||||
|
||||
it('is disabled and explains why when scanning is off', async () => {
|
||||
const wrapper = await open({ enabled: false, concurrency: 2 })
|
||||
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
|
||||
expect(wrapper.get('[data-testid="rescan-all"]').attributes('disabled')).toBeDefined()
|
||||
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('Security scanning is off')
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('asks for the admin key before it posts anything', async () => {
|
||||
localStorage.clear()
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
|
||||
expect(body()).toContain('Enter your admin API key to start a rescan.')
|
||||
})
|
||||
|
||||
it('asks for the admin key before it sizes a full rescan', async () => {
|
||||
localStorage.clear()
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith('/api/admin/rescan/estimate', expect.anything())
|
||||
expect(body()).toContain('Enter your admin API key to start a rescan.')
|
||||
})
|
||||
|
||||
it('forgets a key the server refuses', async () => {
|
||||
vi.mocked(axios.post).mockRejectedValue({ response: { status: 403 } })
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(localStorage.getItem('admin_api_key')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,201 @@
|
||||
<template>
|
||||
<Card data-testid="rescan-panel">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Rescan</CardTitle>
|
||||
<CardDescription>Scan cached packages again now, without waiting for the interval. Stored findings are refreshed with the current scanners.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Button :icon-start="faRotateRight" :loading="starting === 'vulnerable'" :disabled="blocked" data-testid="rescan-vulnerable" @click="start('vulnerable')">
|
||||
Rescan vulnerable packages
|
||||
</Button>
|
||||
<Button variant="outline" :icon-start="faRotateRight" :loading="starting === 'all'" :disabled="blocked" data-testid="rescan-all" @click="askAll">
|
||||
Rescan everything
|
||||
</Button>
|
||||
</div>
|
||||
<p class="m-0 text-sm text-muted-foreground" data-testid="rescan-note">{{ note }}</p>
|
||||
|
||||
<div v-if="status && status.queued > 0" class="flex flex-col gap-2" data-testid="rescan-progress">
|
||||
<Progress :model-value="processed" :max="status.queued" label="Rescan progress" show-value />
|
||||
<p class="m-0 text-sm" data-testid="rescan-counts">
|
||||
{{ status.running ? 'Running.' : 'Finished.' }}
|
||||
{{ formatNumber(status.done) }} scanned, {{ formatNumber(status.failed) }} failed, of {{ formatNumber(status.queued) }} queued.
|
||||
</p>
|
||||
<p v-if="status.running && liveRate" class="m-0 text-sm text-muted-foreground" data-testid="rescan-live">{{ liveRate }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="confirmOpen"
|
||||
title="Rescan every cached package?"
|
||||
:description="everythingWarning"
|
||||
confirm-label="Rescan everything"
|
||||
@confirm="start('all')"
|
||||
/>
|
||||
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a rescan." @saved="resume" />
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, ConfirmDialog, Progress, useToastStore } from '@perfect-design/ui'
|
||||
import AdminKeyDialog from './AdminKeyDialog.vue'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { formatApproxDuration, formatNumber } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
|
||||
type Scope = 'vulnerable' | 'all'
|
||||
|
||||
/** Response of GET /api/admin/rescan/status. */
|
||||
interface RescanStatus {
|
||||
enabled: boolean
|
||||
running: boolean
|
||||
scope: string
|
||||
queued: number
|
||||
done: number
|
||||
failed: number
|
||||
elapsed_seconds?: number
|
||||
/** Absent until the first artifact is processed. */
|
||||
eta_seconds?: number
|
||||
}
|
||||
|
||||
/** Response of GET /api/admin/rescan/estimate; seconds is null until a scan has been timed. */
|
||||
interface RescanEstimate {
|
||||
vulnerable: { artifacts: number; seconds: number | null }
|
||||
all: { artifacts: number; seconds: number | null }
|
||||
avg_scan_seconds: number
|
||||
concurrency: number
|
||||
}
|
||||
|
||||
const props = defineProps<{ enabled: boolean; concurrency: number }>()
|
||||
|
||||
const POLL_MS = 2000
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const toasts = useToastStore()
|
||||
|
||||
const status = ref<RescanStatus | null>(null)
|
||||
const starting = ref<Scope | null>(null)
|
||||
const confirmOpen = ref(false)
|
||||
const showKeyDialog = ref(false)
|
||||
const estimate = ref<RescanEstimate | null>(null)
|
||||
let pendingScope: Scope | null = null
|
||||
let pendingConfirm = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const running = computed(() => status.value?.running === true)
|
||||
const blocked = computed(() => !props.enabled || running.value || starting.value !== null)
|
||||
const processed = computed(() => (status.value ? status.value.done + status.value.failed : 0))
|
||||
const note = computed(() => {
|
||||
if (!props.enabled) return 'Security scanning is off in the configuration.'
|
||||
if (running.value) return 'A rescan is running. Another one can start when it finishes.'
|
||||
return 'Needs the admin API key. The rescan runs in the background.'
|
||||
})
|
||||
const liveRate = computed(() => {
|
||||
const st = status.value
|
||||
const elapsed = st?.elapsed_seconds ?? 0
|
||||
if (!st || processed.value === 0 || elapsed <= 0) return ''
|
||||
const perMinute = (processed.value / elapsed) * 60
|
||||
const rate = `${perMinute < 10 ? perMinute.toFixed(1) : formatNumber(Math.round(perMinute))} artifacts a minute`
|
||||
return st.eta_seconds === undefined ? rate : `${rate}. About ${formatApproxDuration(st.eta_seconds)} left.`
|
||||
})
|
||||
const everythingWarning = computed(() => {
|
||||
const base = 'This re-runs all scanners on every cached artifact.'
|
||||
const est = estimate.value
|
||||
const all = est?.all
|
||||
if (!est || !all) return `${base} It can take a long time.`
|
||||
const count = `${formatNumber(all.artifacts)} artifacts`
|
||||
if (all.seconds === null) return `${base} ${count} are cached. No scan has been timed yet, so there is no estimate.`
|
||||
const { avg_scan_seconds: avg, concurrency } = est
|
||||
return `${base} ${count}, ${concurrency} at a time and ${avg.toFixed(1)} seconds each on recent scans: roughly ${formatApproxDuration(all.seconds)}.`
|
||||
})
|
||||
|
||||
function errorStatus(err: unknown): number | undefined {
|
||||
return (err as { response?: { status?: number } }).response?.status
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const res = await axios.get<RescanStatus>('/api/admin/rescan/status', { headers: adminKey.headers.value })
|
||||
status.value = res.data
|
||||
return res.data
|
||||
}
|
||||
|
||||
function schedulePoll() {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(async () => {
|
||||
try {
|
||||
if ((await refresh()).running) schedulePoll()
|
||||
} catch {
|
||||
// The next click shows the error; a failed poll must not toast every two seconds.
|
||||
}
|
||||
}, POLL_MS)
|
||||
}
|
||||
|
||||
async function askAll() {
|
||||
adminKey.load()
|
||||
if (!adminKey.key.value) {
|
||||
pendingConfirm = true
|
||||
showKeyDialog.value = true
|
||||
return
|
||||
}
|
||||
confirmOpen.value = true
|
||||
try {
|
||||
estimate.value = (await axios.get<RescanEstimate>('/api/admin/rescan/estimate', { headers: adminKey.headers.value })).data
|
||||
} catch {
|
||||
estimate.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function start(scope: Scope) {
|
||||
adminKey.load()
|
||||
if (!adminKey.key.value) {
|
||||
pendingScope = scope
|
||||
showKeyDialog.value = true
|
||||
return
|
||||
}
|
||||
starting.value = scope
|
||||
try {
|
||||
const res = await axios.post<{ queued: number }>('/api/admin/rescan', { scope }, { headers: adminKey.headers.value })
|
||||
toasts.success('Rescan started', `${formatNumber(res.data.queued)} artifacts queued.`)
|
||||
await refresh()
|
||||
if (status.value?.running) schedulePoll()
|
||||
} catch (err) {
|
||||
const code = errorStatus(err)
|
||||
if (code === 409) {
|
||||
toasts.info('A rescan is already running', 'Wait for it to finish.')
|
||||
await refresh().then(schedulePoll, () => undefined)
|
||||
} else if (code === 401 || code === 403) {
|
||||
adminKey.clear()
|
||||
toasts.error('Admin key refused', 'Enter a key with the admin role.')
|
||||
} else {
|
||||
toasts.error('Could not start the rescan', err instanceof Error ? err.message : 'Request failed')
|
||||
}
|
||||
} finally {
|
||||
starting.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function resume() {
|
||||
const scope = pendingScope
|
||||
pendingScope = null
|
||||
if (pendingConfirm) {
|
||||
pendingConfirm = false
|
||||
void askAll()
|
||||
} else if (scope) {
|
||||
void start(scope)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
adminKey.load()
|
||||
if (!props.enabled || !adminKey.key.value) return
|
||||
try {
|
||||
if ((await refresh()).running) schedulePoll()
|
||||
} catch {
|
||||
// Progress is optional here; a stale or missing key surfaces when the admin starts a rescan.
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => clearTimeout(timer))
|
||||
</script>
|
||||
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<Card data-testid="scanner-health">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Inspectors</CardTitle>
|
||||
<CardDescription>The scanners that examine each package. Health is probed every 30 seconds.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ErrorState v-if="error && !info" variant="inline" title="Could not load scanners" :message="error" @retry="load(true)" />
|
||||
<LoadingState v-else-if="!info" layout="inline" label="Loading scanners..." />
|
||||
<EmptyState
|
||||
v-else-if="!info.security.enabled"
|
||||
size="sm"
|
||||
title="Scanning is off"
|
||||
description="Packages are served without inspection."
|
||||
/>
|
||||
<ul v-else class="m-0 grid list-none grid-cols-1 gap-2 p-0 sm:grid-cols-2 xl:grid-cols-3">
|
||||
<li
|
||||
v-for="scanner in info.security.scanners"
|
||||
:key="scanner.name"
|
||||
class="flex items-start justify-between gap-3 rounded-md border px-3 py-2"
|
||||
:data-scanner="scanner.name"
|
||||
>
|
||||
<span class="min-w-0">
|
||||
<span class="block break-words text-sm font-medium" :title="scanner.name">{{ scanner.name }}</span>
|
||||
<span v-if="scannerVersion(scanner)" class="block text-xs text-muted-foreground">{{ scannerVersion(scanner) }}</span>
|
||||
</span>
|
||||
<StatusBadge :status="scannerState(scanner)" :label="STATE_LABELS[scannerState(scanner)]" :tones="STATE_TONES" />
|
||||
</li>
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
StatusBadge,
|
||||
} from '@perfect-design/ui'
|
||||
import { scannerState, scannerVersion, useSystem } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
|
||||
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
|
||||
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import TopPackages from './TopPackages.vue'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
const row = (registry: string, name: string, download_count: number) => ({ registry, name, version: '1.0.0', download_count })
|
||||
|
||||
function serve(rows: unknown[], trending: unknown[] = []) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/analytics/trending')) return { data: { packages: trending } } as never
|
||||
if (url.startsWith('/api/packages?layout=rows')) return { data: { packages: rows } } as never
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
})
|
||||
}
|
||||
|
||||
async function open() {
|
||||
const mounted = await mountStrict(TopPackages)
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(axios.get).mockReset()
|
||||
})
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
})
|
||||
|
||||
describe('TopPackages', () => {
|
||||
it('ranks packages by the stored download counts, so a restart does not empty it', async () => {
|
||||
serve([row('npm', 'left-pad', 12), row('npm', 'left-pad', 5), row('pypi', 'six', 9)])
|
||||
const wrapper = await open()
|
||||
|
||||
const text = wrapper.get('[data-testid="top-packages"]').text()
|
||||
expect(text).toContain('npm · left-pad')
|
||||
expect(text).toContain('pypi · six')
|
||||
expect(text).not.toContain('No downloads yet')
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200')
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith(expect.stringContaining('/api/analytics/top'))
|
||||
})
|
||||
|
||||
it('adds the versions of a package and orders by the sum', async () => {
|
||||
serve([row('npm', 'a', 10), row('npm', 'b', 15), row('npm', 'a', 9)])
|
||||
const wrapper = await open()
|
||||
const labels = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
|
||||
expect(labels[0]).toContain('npm · a')
|
||||
expect(labels[1]).toContain('npm · b')
|
||||
})
|
||||
|
||||
it('counts a Go module once, by its zip, and not its .mod and .info files', async () => {
|
||||
serve([
|
||||
row('go', 'github.com/google/uuid/@v/v1.6.0.zip', 4),
|
||||
row('go', 'github.com/google/uuid/@v/v1.6.0.mod', 4),
|
||||
row('go', 'github.com/google/uuid/@v/v1.6.0.info', 4),
|
||||
])
|
||||
const wrapper = await open()
|
||||
const entries = wrapper.findAll('[data-testid="top-packages"] li')
|
||||
expect(entries).toHaveLength(1)
|
||||
expect(entries[0].text()).toContain('go · github.com/google/uuid')
|
||||
expect(entries[0].text()).toContain('4')
|
||||
expect(entries[0].text()).not.toContain('12')
|
||||
})
|
||||
|
||||
it('says so when no package has a download', async () => {
|
||||
serve([row('npm', 'left-pad', 0)])
|
||||
const wrapper = await open()
|
||||
expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet')
|
||||
})
|
||||
|
||||
it('shows the change against the previous 7 days for trending packages', async () => {
|
||||
serve([], [
|
||||
{ Registry: 'npm', Name: 'left-pad', Downloads: 9, RecentDownloads: 9, PreviousDownloads: 4 },
|
||||
{ Registry: 'npm', Name: 'six', Downloads: 3, RecentDownloads: 3, PreviousDownloads: 8 },
|
||||
])
|
||||
const wrapper = await open()
|
||||
const rows = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
|
||||
const pad = rows.find((r) => r.includes('left-pad'))
|
||||
const six = rows.find((r) => r.includes('six'))
|
||||
expect(pad).toMatch(/\+5/)
|
||||
expect(six).toMatch(/[-−]5/)
|
||||
})
|
||||
|
||||
it('names where each ranking comes from', async () => {
|
||||
serve([row('npm', 'left-pad', 3)])
|
||||
const wrapper = await open()
|
||||
const text = wrapper.get('[data-testid="top-packages"]').text()
|
||||
expect(text).toContain('The counts survive restarts.')
|
||||
expect(text).toContain('the change from the 7 days before')
|
||||
expect(text).not.toContain('restarts with the server')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
<template>
|
||||
<div class="grid gap-6 lg:grid-cols-2" data-testid="top-packages">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Most requested</CardTitle>
|
||||
<CardDescription>Downloads served from the cache. The counts survive restarts.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading top packages..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load top packages" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="top.length === 0" size="sm" title="No downloads yet" description="Rankings appear after the first download." />
|
||||
<Leaderboard v-else label="Most requested packages" bars :entries="top" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Downloads', delta: 'Change' }" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Trending</CardTitle>
|
||||
<CardDescription>Downloads in the last 7 days, and the change from the 7 days before. The counts survive restarts.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading trending packages..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load trending packages" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="trending.length === 0" size="sm" title="Nothing trending" description="No package was downloaded in the last 7 days." />
|
||||
<Leaderboard v-else label="Trending packages" bars :entries="trending" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Last 7 days', delta: 'Change' }" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Leaderboard,
|
||||
LoadingState,
|
||||
type LeaderboardEntry,
|
||||
} from '@perfect-design/ui'
|
||||
import { modulePath } from '@/lib/format'
|
||||
|
||||
/** The trending endpoint serialises Go field names. */
|
||||
interface PopularPackage {
|
||||
Registry: string
|
||||
Name: string
|
||||
Downloads: number
|
||||
RecentDownloads: number
|
||||
PreviousDownloads?: number
|
||||
}
|
||||
|
||||
/** One stored version row; its count is kept in the database. */
|
||||
interface DownloadRow {
|
||||
registry: string
|
||||
name: string
|
||||
download_count: number
|
||||
}
|
||||
|
||||
const LIMIT = 8
|
||||
// Go keeps one row per file (.zip, .mod, .info) of a version; only the zip is a module download.
|
||||
const GO_METADATA = /\.(mod|info)$/
|
||||
const ROWS_URL = '/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200'
|
||||
const stored = ref<DownloadRow[]>([])
|
||||
const recent = ref<PopularPackage[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Rows with equal registry and module path (a Go module's .zip, .mod and .info) are one package.
|
||||
function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number, change?: (p: PopularPackage) => number): LeaderboardEntry[] {
|
||||
const totals = new Map<string, LeaderboardEntry>()
|
||||
for (const row of rows) {
|
||||
const id = `${row.Registry}/${modulePath(row.Name)}`
|
||||
const existing = totals.get(id)
|
||||
if (existing) {
|
||||
existing.value += pick(row)
|
||||
if (change) existing.delta = (existing.delta ?? 0) + change(row)
|
||||
} else {
|
||||
totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row), ...(change ? { delta: change(row) } : {}) })
|
||||
}
|
||||
}
|
||||
return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT)
|
||||
}
|
||||
|
||||
const top = computed(() =>
|
||||
entries(
|
||||
stored.value
|
||||
.filter((r) => !(r.registry === 'go' && GO_METADATA.test(r.name)))
|
||||
.map((r) => ({ Registry: r.registry, Name: r.name, Downloads: r.download_count, RecentDownloads: 0 })),
|
||||
(p) => p.Downloads,
|
||||
),
|
||||
)
|
||||
const trending = computed(() =>
|
||||
entries(
|
||||
recent.value,
|
||||
(p) => p.RecentDownloads,
|
||||
(p) => p.RecentDownloads - (p.PreviousDownloads ?? 0),
|
||||
),
|
||||
)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const [topRes, trendRes] = await Promise.all([
|
||||
axios.get<{ packages: DownloadRow[] }>(ROWS_URL),
|
||||
axios.get<{ packages: PopularPackage[] }>('/api/analytics/trending?limit=50'),
|
||||
])
|
||||
stored.value = topRes.data.packages ?? []
|
||||
recent.value = trendRes.data.packages ?? []
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load package rankings'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,12 @@
|
||||
<template>
|
||||
<StatusBadge :status="verdict" :label="VERDICT_LABELS[verdict]" :tones="TONES" :title="VERDICT_MEANINGS[verdict]" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { StatusBadge } from '@perfect-design/ui'
|
||||
import { VERDICT_LABELS, VERDICT_MEANINGS, VERDICT_TONES, type Verdict } from '@/lib/verdict'
|
||||
|
||||
defineProps<{ verdict: Verdict }>()
|
||||
|
||||
const TONES = VERDICT_TONES
|
||||
</script>
|
||||
@@ -0,0 +1,50 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import VulnerabilityTable from './VulnerabilityTable.vue'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import type { VulnerabilityEntry } from '@/lib/report'
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
})
|
||||
|
||||
const entry = (over: Partial<VulnerabilityEntry>): VulnerabilityEntry => ({
|
||||
id: 'GHSA-xvch-5gv4-984h',
|
||||
severity: 'critical',
|
||||
title: 'Prototype pollution',
|
||||
description: '',
|
||||
references: [],
|
||||
fixed_in: '1.2.6',
|
||||
bypassed: false,
|
||||
...over,
|
||||
})
|
||||
|
||||
async function open(vulnerabilities: VulnerabilityEntry[]) {
|
||||
const router = await createTestRouter('/')
|
||||
const mounted = await mountStrict(VulnerabilityTable, { props: { vulnerabilities }, global: { plugins: [router] } })
|
||||
restore = mounted.restore
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
describe('VulnerabilityTable aliases', () => {
|
||||
it('names the other ids of a finding next to its advisory id', async () => {
|
||||
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
|
||||
expect(w.text()).toContain('GHSA-xvch-5gv4-984h')
|
||||
expect(w.text()).toContain('Also CVE-2021-44906')
|
||||
})
|
||||
|
||||
it('shows no alias line for an older finding without aliases', async () => {
|
||||
const w = await open([entry({})])
|
||||
expect(w.text()).not.toContain('Also ')
|
||||
})
|
||||
|
||||
it('offers a bypass link for the id and for each alias', async () => {
|
||||
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
|
||||
await w.find('tbody tr').trigger('click')
|
||||
const hrefs = w.findAll('a').map((a) => a.attributes('href') ?? '')
|
||||
expect(hrefs).toContain('/admin/bypasses?type=cve&target=GHSA-xvch-5gv4-984h')
|
||||
expect(hrefs).toContain('/admin/bypasses?type=cve&target=CVE-2021-44906')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
<template>
|
||||
<Table label="Detected vulnerabilities" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Severity</TableHead>
|
||||
<TableHead>Advisory</TableHead>
|
||||
<TableHead>Summary</TableHead>
|
||||
<TableHead>Fixed in</TableHead>
|
||||
<TableHead>Found by</TableHead>
|
||||
<TableHead align="center">Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<template v-for="vuln in sorted" :key="vuln.id">
|
||||
<TableRow class="cursor-pointer" :selected="isOpen(vuln.id)" @click="toggle(vuln.id)">
|
||||
<TableCell label="Severity">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge :status="vuln.severity" :tones="SEVERITY_TONES" :label="formatSeverityName(vuln.severity)" />
|
||||
<StatusBadge v-if="vuln.bypassed" status="bypassed" label="Bypassed" :tones="{ bypassed: 'info' }" />
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Advisory" class="font-mono font-medium">
|
||||
<span class="block">{{ vuln.id }}</span>
|
||||
<span v-if="vuln.aliases?.length" class="block text-xs font-normal text-muted-foreground">
|
||||
Also {{ vuln.aliases.join(', ') }}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Summary">
|
||||
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
|
||||
</TableCell>
|
||||
<TableCell label="Fixed in">
|
||||
<span v-if="vuln.fixed_in">{{ withVersionPrefix(vuln.fixed_in) }}</span>
|
||||
<span v-else class="text-muted-foreground">No fix yet</span>
|
||||
</TableCell>
|
||||
<TableCell label="Found by">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<Badge v-for="scanner in vuln.detected_by ?? []" :key="scanner" variant="secondary">{{ scanner }}</Badge>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Details" align="center">
|
||||
<IconButton
|
||||
size="icon-sm"
|
||||
:icon="isOpen(vuln.id) ? faChevronUp : faChevronDown"
|
||||
:label="`${isOpen(vuln.id) ? 'Hide' : 'Show'} details for ${vuln.id}`"
|
||||
:aria-expanded="isOpen(vuln.id)"
|
||||
@click.stop="toggle(vuln.id)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
<TableRow v-if="isOpen(vuln.id)" :hoverable="false">
|
||||
<TableCell :colspan="6">
|
||||
<div class="flex flex-col gap-4 py-2">
|
||||
<section v-if="vuln.description">
|
||||
<h3 class="mb-2 text-sm font-semibold">Description</h3>
|
||||
<Markdown :source="vuln.description" :heading-offset="3" />
|
||||
</section>
|
||||
|
||||
<Callout v-if="vuln.bypassed && vuln.bypass" type="note" title="Bypass active" size="sm">
|
||||
{{ vuln.bypass.reason }}. Created by {{ vuln.bypass.created_by }}, expires {{ formatDate(vuln.bypass.expires_at) }}.
|
||||
</Callout>
|
||||
|
||||
<Callout v-if="vuln.fixed_in" type="tip" title="Fix available" size="sm">
|
||||
Upgrade to <strong>{{ withVersionPrefix(vuln.fixed_in) }}</strong> or later.
|
||||
</Callout>
|
||||
|
||||
<section>
|
||||
<h3 class="mb-2 text-sm font-semibold">Bypass this advisory</h3>
|
||||
<p class="m-0 mb-1 text-sm text-muted-foreground">A bypass for any of these ids covers this finding.</p>
|
||||
<ul class="m-0 flex list-none flex-wrap gap-3 p-0 text-sm">
|
||||
<li v-for="id in [vuln.id, ...(vuln.aliases ?? [])]" :key="id">
|
||||
<Link :as="RouterLink" :to="{ path: '/admin/bypasses', query: { type: 'cve', target: id } }">{{ id }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section v-if="vuln.references && vuln.references.length > 0">
|
||||
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
|
||||
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li v-for="ref in vuln.references" :key="ref" class="break-all">
|
||||
<Link :href="ref" external>{{ ref }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Callout,
|
||||
IconButton,
|
||||
Link,
|
||||
Markdown,
|
||||
StatusBadge,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import type { VulnerabilityEntry } from '@/lib/report'
|
||||
import { faChevronDown, faChevronUp } from '@/lib/icons'
|
||||
import { SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
|
||||
|
||||
const props = defineProps<{ vulnerabilities: readonly VulnerabilityEntry[] }>()
|
||||
|
||||
const open = ref(new Set<string>())
|
||||
const sorted = computed(() => [...props.vulnerabilities].sort((a, b) => severityRank(b.severity) - severityRank(a.severity)))
|
||||
|
||||
function isOpen(id: string): boolean {
|
||||
return open.value.has(id)
|
||||
}
|
||||
|
||||
function toggle(id: string) {
|
||||
const next = new Set(open.value)
|
||||
if (!next.delete(id)) next.add(id)
|
||||
open.value = next
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { RouterLink, useRoute } from 'vue-router'
|
||||
import { SidebarNav, type SidebarNavGroup } from '@perfect-design/ui'
|
||||
import {
|
||||
faBoxesStacked,
|
||||
faChartColumn,
|
||||
faChartPie,
|
||||
faGear,
|
||||
faShieldHalved,
|
||||
faTriangleExclamation,
|
||||
} from '@/lib/icons'
|
||||
|
||||
// The sidebar slot of AppShell hides itself below md and the header's mobile slot only shows below md,
|
||||
// so each placement renders one nav and the two never compete for the same viewport.
|
||||
defineProps<{ readonly sheet?: boolean }>()
|
||||
|
||||
const GROUPS: SidebarNavGroup[] = [
|
||||
{
|
||||
items: [
|
||||
{ label: 'Overview', to: '/', icon: faChartPie },
|
||||
{ label: 'Packages', to: '/packages', icon: faBoxesStacked },
|
||||
{ label: 'Security', to: '/security', icon: faTriangleExclamation },
|
||||
{ label: 'Insights', to: '/stats', icon: faChartColumn },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Admin',
|
||||
items: [
|
||||
{ label: 'Bypasses', to: '/admin/bypasses', icon: faShieldHalved },
|
||||
{ label: 'System', to: '/admin/system', icon: faGear },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const SECTION_PREFIXES: ReadonlyArray<readonly [string, string]> = [
|
||||
['/packages', '/packages'],
|
||||
['/package/', '/packages'],
|
||||
['/security', '/security'],
|
||||
['/vulnerable-packages', '/security'],
|
||||
['/blocked-packages', '/security'],
|
||||
['/admin/bypasses', '/admin/bypasses'],
|
||||
['/admin/system', '/admin/system'],
|
||||
['/stats', '/stats'],
|
||||
]
|
||||
|
||||
const route = useRoute()
|
||||
const current = computed(() => SECTION_PREFIXES.find(([prefix]) => route.path.startsWith(prefix))?.[1] ?? '/')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SidebarNav
|
||||
:groups="GROUPS"
|
||||
:current="current"
|
||||
:link-as="RouterLink"
|
||||
:label="sheet ? 'Sections menu' : 'Sections'"
|
||||
class="w-full p-3"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,111 @@
|
||||
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 Overview from './Overview.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import Security from './Security.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Insights from './Insights.vue'
|
||||
import System from './System.vue'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
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> = {
|
||||
Overview: 'Quiet at the desk',
|
||||
PackageList: 'No packages cached yet',
|
||||
Security: 'Nothing is held',
|
||||
Insights: 'No registry data yet',
|
||||
BypassManagementPanel: 'No bypasses found',
|
||||
}
|
||||
|
||||
const CASES: Array<[string, Parameters<typeof mountStrict>[0], string]> = [
|
||||
['Overview', Overview, '/'],
|
||||
['PackageList', PackageList, '/packages'],
|
||||
['PackageDetails', PackageDetails, '/package/npm/left-pad/1.3.0'],
|
||||
['Security', Security, '/security'],
|
||||
['BypassManagementPanel', BypassManagementPanel, '/admin/bypasses'],
|
||||
['Insights', Insights, '/stats'],
|
||||
['System', System, '/admin/system'],
|
||||
]
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
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('/security')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(Security, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
await mounted.wrapper.find('[data-slot="error-state"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(mounted.wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(mounted.wrapper.text()).toContain('Nothing is held')
|
||||
})
|
||||
})
|
||||
|
||||
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(/overview|dashboard/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,461 @@
|
||||
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 Overview from './Overview.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import Security from './Security.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Insights from './Insights.vue'
|
||||
import System from './System.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import {
|
||||
BYPASSES,
|
||||
PACKAGES,
|
||||
PACKAGE_ANALYTICS,
|
||||
REGISTRIES,
|
||||
STATS,
|
||||
SYSTEM,
|
||||
TIMESERIES,
|
||||
TOP_PACKAGES,
|
||||
TREND,
|
||||
VULNERABILITY_REPORT,
|
||||
} from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
const API_KEY_STORAGE = 'admin_api_key'
|
||||
|
||||
function respond(url: string) {
|
||||
if (url.startsWith('/api/system')) return { data: SYSTEM }
|
||||
if (url.startsWith('/api/admin/rescan/status')) return { data: { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 } }
|
||||
if (url.startsWith('/api/analytics/package/')) return { data: PACKAGE_ANALYTICS }
|
||||
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES }
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND }
|
||||
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
|
||||
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
|
||||
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
|
||||
if (url.includes('layout=rows')) return { data: serveRows(url, PACKAGES) }
|
||||
const single = /^\/api\/packages\/([^/]+)\/(.+)\/([^/?]+)$/.exec(url)
|
||||
if (single) {
|
||||
const row = PACKAGES.find((p) => p.registry === single[1] && p.name === single[2] && p.version === single[3])
|
||||
if (!row) throw Object.assign(new Error('not found'), { response: { status: 404 } })
|
||||
return { data: row }
|
||||
}
|
||||
if (url.startsWith('/api/packages')) return { data: { packages: PACKAGES } }
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
}
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
|
||||
localStorage.setItem(API_KEY_STORAGE, 'test-key')
|
||||
})
|
||||
|
||||
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('Overview renders the verdict strip, policy, capacity, trend, rankings, inspectors and feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'left-pad', version: '1.3.0', registry: 'npm' }, timestamp: Date.now() }]
|
||||
const { wrapper, problems, restore: r } = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Overview')
|
||||
|
||||
const strip = wrapper.find('[data-testid="verdict-strip"]').text()
|
||||
for (const word of ['Cleared', 'Held', 'Bypassed', 'Awaiting scan']) expect(strip).toContain(word)
|
||||
// 3 scanned, 1 held, 1 bypassed: 1 cleared; 4 cached, 3 scanned: 1 awaiting.
|
||||
expect(wrapper.find('[data-verdict="cleared"]').text()).toContain('1')
|
||||
expect(wrapper.find('[data-verdict="held"]').attributes('href')).toBe('/security?tab=held')
|
||||
|
||||
expect(wrapper.find('[data-testid="policy-line"]').text()).toContain('Blocks any CRITICAL.')
|
||||
expect(wrapper.find('[data-testid="policy-line"]').text()).toContain('Fail-closed')
|
||||
expect(wrapper.find('[data-testid="cache-capacity"]').text()).toContain('5 GB of 10 GB')
|
||||
expect(wrapper.find('[data-testid="download-trend"] [role="img"]').exists()).toBe(true)
|
||||
expect(wrapper.find('[data-testid="top-packages"]').text()).toContain('npm · left-pad')
|
||||
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('grype')
|
||||
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('Unavailable')
|
||||
expect(wrapper.find('[data-testid="ws-event-feed"]').text()).toContain('left-pad')
|
||||
})
|
||||
|
||||
it('PackageList shows a verdict for each row and filters by it', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–4 of 4')
|
||||
const text = wrapper.text()
|
||||
for (const word of ['left-pad', 'requests', 'github.com/example/module', 'Held', 'Cleared', 'Bypassed', 'Awaiting scan']) {
|
||||
expect(text).toContain(word)
|
||||
}
|
||||
})
|
||||
|
||||
it('PackageList seeds the verdict filter from the URL', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages?verdict=held')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–1 of 1')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).not.toContain('requests')
|
||||
})
|
||||
|
||||
it('PackageList opens a quick view with a link to the full page', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages?verdict=held')
|
||||
await wrapper.find('tbody tr').trigger('click')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const sheet = document.body.querySelector('[data-slot="sheet-content"]')
|
||||
expect(sheet?.textContent).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
expect(sheet?.querySelector('a[href^="/package/npm/left-pad/1.3.0"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('PackageDetails explains the verdict and lists findings most severe first', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('left-pad')
|
||||
|
||||
const banner = wrapper.find('[data-testid="verdict-banner"]').text()
|
||||
expect(banner).toContain('Held: CVE-2026-0003 is HIGH')
|
||||
expect(banner).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
|
||||
const meta = wrapper.find('[data-testid="package-meta"]').text()
|
||||
expect(meta).toContain('2 KB')
|
||||
expect(meta).toContain('https://registry.npmjs.org')
|
||||
expect(meta).toContain('Removed after 30 days without a request')
|
||||
|
||||
const ids = wrapper.findAll('tbody td.font-mono').map((td) => td.text().replace('Advisory', ''))
|
||||
expect(ids.slice(0, 3)).toEqual(['CVE-2026-0002', 'CVE-2026-0003', 'CVE-2026-0001'])
|
||||
|
||||
await wrapper.find('button[aria-label^="Show details for CVE-2026-0002"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('Bypass active')
|
||||
expect(wrapper.text()).toContain('No fix available')
|
||||
})
|
||||
|
||||
it('PackageDetails reads its own row, not the grouped package list', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
expect(problems).toEqual([])
|
||||
const urls = vi.mocked(axios.get).mock.calls.map((c) => String(c[0]))
|
||||
expect(urls).toContain('/api/packages/npm/left-pad/1.3.0')
|
||||
expect(urls.filter((u) => u.startsWith('/api/packages?'))).toEqual([])
|
||||
expect(wrapper.text()).toContain('2 KB')
|
||||
})
|
||||
|
||||
it('PackageDetails Inspectors tab shows one row per scanner', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0?tab=inspectors')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0?tab=inspectors')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const panel = wrapper.find('[role="tabpanel"]:not([hidden])')
|
||||
const text = panel.text()
|
||||
for (const word of ['trivy', 'osv', 'grype', 'govulncheck', 'v0.58.1', 'No result', 'Off']) expect(text).toContain(word)
|
||||
})
|
||||
|
||||
it('PackageDetails Downloads tab reads the per-package analytics', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0?tab=downloads')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0?tab=downloads')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/analytics/package/npm/left-pad')
|
||||
expect(wrapper.text()).toContain('80 KB')
|
||||
})
|
||||
|
||||
it('Security splits packages by what the policy did', async () => {
|
||||
const { wrapper, problems } = await smoke(Security, '/security')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Security')
|
||||
const triggers = wrapper.findAll('[role="tab"]').map((t) => t.text())
|
||||
expect(triggers).toEqual(['Held (1)', 'Vulnerable but allowed (1)', 'Bypassed (1)'])
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
})
|
||||
|
||||
it('Security opens on the tab named in the URL', async () => {
|
||||
const { wrapper, problems } = await smoke(Security, '/security?tab=bypassed')
|
||||
expect(problems).toEqual([])
|
||||
const selected = wrapper.findAll('[role="tab"]').find((t) => t.attributes('aria-selected') === 'true')
|
||||
expect(selected?.text()).toBe('Bypassed (1)')
|
||||
expect(wrapper.text()).toContain('a.khan')
|
||||
})
|
||||
|
||||
it('BypassManagementPanel lists bypasses and opens the create dialog', async () => {
|
||||
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Bypasses')
|
||||
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 opens the form prefilled from a package page link', async () => {
|
||||
const { problems } = await smoke(BypassManagementPanel, '/admin/bypasses?type=package&target=npm/[email protected]')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const input = Array.from(document.body.querySelectorAll<HTMLInputElement>('input')).find((i) => i.value === 'npm/[email protected]')
|
||||
expect(input).toBeDefined()
|
||||
})
|
||||
|
||||
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
|
||||
localStorage.clear()
|
||||
const prompt = vi.spyOn(window, 'prompt')
|
||||
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('Insights renders the registry breakdown, scan coverage and daily downloads', async () => {
|
||||
const { wrapper, problems } = await smoke(Insights, '/stats')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Insights')
|
||||
const breakdown = wrapper.find('[data-testid="registry-breakdown"]').text()
|
||||
for (const word of ['npm', 'pypi', 'go', '2 GB']) expect(breakdown).toContain(word)
|
||||
expect(wrapper.find('[data-testid="scan-coverage"]').text()).toContain('3 of 4')
|
||||
expect(wrapper.find('[data-testid="daily-downloads"] [role="img"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('System shows the policy, scanners, rescans, cache, pre-warming and build version', async () => {
|
||||
const { wrapper, problems } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('System')
|
||||
expect(wrapper.find('[data-testid="build-version"]').text()).toBe('v1.8.0')
|
||||
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Blocks any CRITICAL.')
|
||||
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Fail-closed')
|
||||
expect(wrapper.find('[data-testid="rescan-list"]').text()).toContain('1 day')
|
||||
expect(wrapper.find('[data-testid="cache-list"]').text()).toContain('10 GB')
|
||||
expect(wrapper.text()).toContain('v0.58.1')
|
||||
expect(wrapper.find('[data-testid="prewarming"] button').text()).toContain('Run a cycle now')
|
||||
})
|
||||
|
||||
it('System starts a pre-warming cycle with the admin key', async () => {
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: {} })
|
||||
const { wrapper } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).toHaveBeenCalledWith(
|
||||
'/api/admin/prewarming/trigger',
|
||||
null,
|
||||
expect.objectContaining({ headers: { Authorization: 'Bearer test-key' } }),
|
||||
)
|
||||
})
|
||||
|
||||
it('System asks for the key before it triggers anything', async () => {
|
||||
localStorage.clear()
|
||||
const { wrapper } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
|
||||
expect(document.body.textContent).toContain('Enter your admin API key to start a pre-warming cycle.')
|
||||
})
|
||||
|
||||
it('VulnerabilityBadge prints the severity word for every tone', async () => {
|
||||
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 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(['Overview', 'Packages', 'Security', 'Insights', 'Bypasses', 'System'])
|
||||
expect(document.documentElement.getAttribute('data-style')).toBe('workbench')
|
||||
// Brand column and sidebar items share one left edge: 6 spacing units each.
|
||||
expect(document.body.querySelector('header')?.className).toContain('[&>div]:px-6')
|
||||
expect(nav.classes()).toContain('p-3')
|
||||
})
|
||||
|
||||
it('PackageList asks for one page of rows on mount', async () => {
|
||||
await smoke(PackageList, '/packages')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(expect.stringContaining('/api/packages?layout=rows'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('old URLs land on the new pages', () => {
|
||||
it.each([
|
||||
['/vulnerable-packages', '/security', 'allowed'],
|
||||
['/blocked-packages', '/security', 'held'],
|
||||
])('%s redirects to %s with tab %s', async (from, path, tab) => {
|
||||
const router = await createTestRouter(from)
|
||||
expect(router.currentRoute.value.path).toBe(path)
|
||||
expect(router.currentRoute.value.query.tab).toBe(tab)
|
||||
})
|
||||
|
||||
it('keeps the severity filter of the old link', async () => {
|
||||
const router = await createTestRouter('/vulnerable-packages?severity=critical')
|
||||
expect(router.currentRoute.value.query).toEqual({ severity: 'critical', tab: 'allowed' })
|
||||
})
|
||||
|
||||
it('/packages/npm still seeds the registry filter', async () => {
|
||||
const { wrapper } = await smoke(PackageList, '/packages/npm', { registry: 'npm' })
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–2 of 2')
|
||||
})
|
||||
})
|
||||
|
||||
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.includes('layout=rows')) return { data: serveRows(url, [SIX as never]) } as never
|
||||
if (url === `/api/packages/pypi/six/${FILE}`) return { data: SIX } as never
|
||||
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
|
||||
return respond(url) as never
|
||||
})
|
||||
})
|
||||
|
||||
it('PackageList version column', async () => {
|
||||
const { wrapper } = await smoke(PackageList, '/packages')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('Overview activity feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
|
||||
const { wrapper, restore: r } = await mountStrict(Overview, { 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('Security version column', async () => {
|
||||
const { wrapper } = await smoke(Security, '/security?tab=allowed')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
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]')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const STORAGE_KEY = 'admin_api_key'
|
||||
|
||||
const key = ref(typeof localStorage === 'undefined' ? '' : (localStorage.getItem(STORAGE_KEY) ?? ''))
|
||||
|
||||
/** The admin API key the dashboard sends with admin calls; kept in localStorage. */
|
||||
export function useAdminKey() {
|
||||
function load() {
|
||||
key.value = localStorage.getItem(STORAGE_KEY) ?? ''
|
||||
}
|
||||
function save(value: string) {
|
||||
key.value = value
|
||||
localStorage.setItem(STORAGE_KEY, value)
|
||||
}
|
||||
function clear() {
|
||||
key.value = ''
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
const headers = computed(() => ({ Authorization: `Bearer ${key.value}` }))
|
||||
return { key, headers, load, save, clear }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { bypassesFor, isLive, type Bypass } from './bypass'
|
||||
|
||||
function bypass(over: Partial<Bypass>): Bypass {
|
||||
return {
|
||||
id: 'b',
|
||||
type: 'package',
|
||||
target: 'npm/left-pad',
|
||||
reason: 'r',
|
||||
created_by: 'a',
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
notify_on_expiry: false,
|
||||
active: true,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('bypassesFor', () => {
|
||||
const pkg = { registry: 'npm', name: 'left-pad', version: '1.3.0' }
|
||||
|
||||
it('matches a package bypass by name and by name@version', () => {
|
||||
const all = [
|
||||
bypass({ id: 'any', target: 'npm/left-pad' }),
|
||||
bypass({ id: 'pinned', target: 'npm/[email protected]' }),
|
||||
bypass({ id: 'other-version', target: 'npm/[email protected]' }),
|
||||
bypass({ id: 'other-package', target: 'npm/lodash' }),
|
||||
]
|
||||
expect(bypassesFor(all, pkg).map((b) => b.id)).toEqual(['any', 'pinned'])
|
||||
})
|
||||
|
||||
it('matches a CVE bypass with no scope or a scope on this package', () => {
|
||||
const all = [
|
||||
bypass({ id: 'global', type: 'cve', target: 'CVE-1' }),
|
||||
bypass({ id: 'scoped', type: 'cve', target: 'CVE-2', applies_to: 'npm/[email protected]' }),
|
||||
bypass({ id: 'elsewhere', type: 'cve', target: 'CVE-3', applies_to: 'npm/lodash' }),
|
||||
]
|
||||
expect(bypassesFor(all, pkg).map((b) => b.id)).toEqual(['global', 'scoped'])
|
||||
})
|
||||
|
||||
it('keys Go packages by module path, not by cache key', () => {
|
||||
const go = { registry: 'go', name: 'github.com/a/b/@v/v1.0.0.zip', version: 'v1.0.0' }
|
||||
expect(bypassesFor([bypass({ target: 'go/github.com/a/[email protected]' })], go)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('matches a PyPI release version', () => {
|
||||
const py = { registry: 'pypi', name: 'six', version: 'six-1.0.tar.gz', releaseVersion: '1.0' }
|
||||
expect(bypassesFor([bypass({ target: 'pypi/[email protected]' })], py)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isLive', () => {
|
||||
it('requires active and unexpired', () => {
|
||||
const now = Date.parse('2026-06-01T00:00:00Z')
|
||||
expect(isLive(bypass({}), now)).toBe(true)
|
||||
expect(isLive(bypass({ active: false }), now)).toBe(false)
|
||||
expect(isLive(bypass({ expires_at: '2026-01-01T00:00:00Z' }), now)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
export interface Bypass {
|
||||
id: string
|
||||
type: 'cve' | 'package'
|
||||
target: string
|
||||
reason: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
expires_at: string
|
||||
applies_to?: string
|
||||
notify_on_expiry: boolean
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export function isExpired(expiresAt: string, now = Date.now()): boolean {
|
||||
return Date.parse(expiresAt) < now
|
||||
}
|
||||
|
||||
/** Active and not yet expired. */
|
||||
export function isLive(bypass: Bypass, now = Date.now()): boolean {
|
||||
return bypass.active && !isExpired(bypass.expires_at, now)
|
||||
}
|
||||
|
||||
/** Bypass keys use the module path for Go, where stored rows end in `/@v/<version>.<ext>`. */
|
||||
function bypassName(registry: string, name: string): string {
|
||||
const at = name.indexOf('/@v/')
|
||||
return registry === 'go' && at !== -1 ? name.slice(0, at) : name
|
||||
}
|
||||
|
||||
/** The bypasses that cover one package version, by the same keys the server matches. */
|
||||
export function bypassesFor(
|
||||
all: readonly Bypass[],
|
||||
pkg: { registry: string; name: string; version: string; releaseVersion?: string },
|
||||
): Bypass[] {
|
||||
const base = `${pkg.registry}/${bypassName(pkg.registry, pkg.name)}`
|
||||
const keys = new Set([`${base}@${pkg.version}`, base])
|
||||
if (pkg.releaseVersion) keys.add(`${base}@${pkg.releaseVersion}`)
|
||||
return all.filter((b) => (b.type === 'package' ? keys.has(b.target) : !b.applies_to || keys.has(b.applies_to)))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatApproxDuration, 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)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatApproxDuration', () => {
|
||||
it.each([
|
||||
[0, '1 second'],
|
||||
[40, '40 seconds'],
|
||||
[59.4, '59 seconds'],
|
||||
[60, '1 minute'],
|
||||
[750, '13 minutes'],
|
||||
[7199, '120 minutes'],
|
||||
[7200, '2 hours'],
|
||||
[36000, '10 hours'],
|
||||
])('%d seconds reads %s', (seconds, expected) => {
|
||||
expect(formatApproxDuration(seconds)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
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')
|
||||
}
|
||||
|
||||
/** A span in the largest fitting unit, rounded: "40 seconds", "12 minutes", "3 hours". */
|
||||
export function formatApproxDuration(seconds: number): string {
|
||||
if (seconds < SECONDS_PER_MINUTE) return plural(Math.max(1, Math.round(seconds)), 'second')
|
||||
if (seconds < 2 * SECONDS_PER_HOUR) return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
|
||||
return plural(Math.round(seconds / SECONDS_PER_HOUR), 'hour')
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/** Go cache keys end in `/@v/<version>.<ext>`; the module path is what a person recognises. */
|
||||
export function modulePath(name: string): string {
|
||||
const at = name.indexOf('/@v/')
|
||||
return at === -1 ? name : name.slice(0, at)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export {
|
||||
faArrowLeft,
|
||||
faArrowRight,
|
||||
faBan,
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
faBoxesStacked,
|
||||
faChartColumn,
|
||||
faChartLine,
|
||||
faChartPie,
|
||||
faDownload,
|
||||
faGear,
|
||||
faHardDrive,
|
||||
faHourglassHalf,
|
||||
faKey,
|
||||
faPen,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
faUnlockKeyhole,
|
||||
faTriangleExclamation,
|
||||
} from '@fortawesome/free-solid-svg-icons'
|
||||
export {
|
||||
faCircleCheck,
|
||||
faMagnifyingGlass,
|
||||
faPlus,
|
||||
faRotateRight,
|
||||
faChevronDown,
|
||||
faChevronUp,
|
||||
} from '@perfect-design/ui/lib/icons'
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { inspectorRows, type ScannerResult } from './inspectors'
|
||||
import type { ScannerInfo } from './system'
|
||||
|
||||
const counts = (critical: number) => ({ critical, high: 0, moderate: 0, low: 0 })
|
||||
|
||||
const configured: ScannerInfo[] = [
|
||||
{ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' },
|
||||
{ name: 'grype', enabled: true, healthy: false, version: '' },
|
||||
{ name: 'govulncheck', enabled: true, healthy: true, version: '1.1.4' },
|
||||
{ name: 'pip-audit', enabled: false, healthy: null, version: '' },
|
||||
]
|
||||
|
||||
describe('inspectorRows', () => {
|
||||
it('lists reporting scanners first, with their counts and the configured version', () => {
|
||||
const results: ScannerResult[] = [{ name: 'trivy', findings: 1, severity_counts: counts(1) }]
|
||||
const [first] = inspectorRows('npm', results, configured)
|
||||
expect(first).toMatchObject({ name: 'trivy', status: 'reported', version: '0.58.1', findings: 1, health: 'healthy' })
|
||||
expect(first.counts?.critical).toBe(1)
|
||||
})
|
||||
|
||||
it('explains each scanner that did not report', () => {
|
||||
const rows = inspectorRows('npm', [{ name: 'trivy', findings: 0, severity_counts: counts(0) }], configured)
|
||||
const status = Object.fromEntries(rows.map((r) => [r.name, r.status]))
|
||||
expect(status).toEqual({
|
||||
trivy: 'reported',
|
||||
grype: 'no-result',
|
||||
govulncheck: 'not-applicable',
|
||||
'pip-audit': 'off',
|
||||
})
|
||||
})
|
||||
|
||||
it('flags a reporting scanner that is now unhealthy', () => {
|
||||
const rows = inspectorRows('npm', [{ name: 'grype', findings: 0, severity_counts: counts(0) }], configured)
|
||||
expect(rows[0].health).toBe('down')
|
||||
})
|
||||
|
||||
it('keeps a reported scanner that is no longer configured', () => {
|
||||
const rows = inspectorRows('npm', [{ name: 'retired', findings: 2, severity_counts: counts(2) }], configured)
|
||||
expect(rows[0]).toMatchObject({ name: 'retired', health: null, version: '' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { scannerState, type ScannerInfo, type ScannerState } from '@/lib/system'
|
||||
import type { VulnerabilityCounts } from '@/stores/packages'
|
||||
|
||||
/** One entry of the `scanners` array on a package's vulnerability response. */
|
||||
export interface ScannerResult {
|
||||
name: string
|
||||
findings: number
|
||||
severity_counts: VulnerabilityCounts
|
||||
}
|
||||
|
||||
/** Ecosystem-specific scanners only inspect their own registry (mirrors the server's shouldRunScanner). */
|
||||
const REGISTRY_SCANNERS: Record<string, string> = { govulncheck: 'go', 'npm-audit': 'npm', 'pip-audit': 'pypi' }
|
||||
|
||||
export type InspectorStatus = 'reported' | 'no-result' | 'not-applicable' | 'off'
|
||||
|
||||
export interface InspectorRow {
|
||||
name: string
|
||||
version: string
|
||||
status: InspectorStatus
|
||||
health: ScannerState | null
|
||||
counts: VulnerabilityCounts | null
|
||||
findings: number | null
|
||||
}
|
||||
|
||||
export const INSPECTOR_STATUS_LABELS: Record<InspectorStatus, string> = {
|
||||
reported: 'Reported',
|
||||
'no-result': 'No result',
|
||||
'not-applicable': 'Not applicable',
|
||||
off: 'Off',
|
||||
}
|
||||
|
||||
/**
|
||||
* Scanner by severity for one package: every scanner that reported, then each configured scanner that did not,
|
||||
* with the reason it is absent where the registry explains it.
|
||||
*/
|
||||
export function inspectorRows(
|
||||
registry: string,
|
||||
results: readonly ScannerResult[],
|
||||
configured: readonly ScannerInfo[],
|
||||
): InspectorRow[] {
|
||||
const byName = new Map(configured.map((s) => [s.name, s]))
|
||||
const rows: InspectorRow[] = results.map((r) => {
|
||||
const info = byName.get(r.name)
|
||||
return {
|
||||
name: r.name,
|
||||
version: info?.version ?? '',
|
||||
status: 'reported',
|
||||
health: info ? scannerState(info) : null,
|
||||
counts: r.severity_counts,
|
||||
findings: r.findings,
|
||||
}
|
||||
})
|
||||
const reported = new Set(results.map((r) => r.name))
|
||||
for (const info of configured) {
|
||||
if (reported.has(info.name)) continue
|
||||
const own = REGISTRY_SCANNERS[info.name]
|
||||
const status: InspectorStatus = !info.enabled ? 'off' : own && own !== registry ? 'not-applicable' : 'no-result'
|
||||
rows.push({ name: info.name, version: info.version, status, health: scannerState(info), counts: null, findings: null })
|
||||
}
|
||||
return rows
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import axios from 'axios'
|
||||
import { rowsUrl, usePackageRows } from './packageRows'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
describe('rowsUrl', () => {
|
||||
it('asks for the rows layout with the page', () => {
|
||||
expect(rowsUrl({ page: 2, pageSize: 25 })).toBe('/api/packages?layout=rows&page=2&page_size=25')
|
||||
})
|
||||
|
||||
it('adds only the filters that are set', () => {
|
||||
const url = rowsUrl({ q: ' left ', registry: 'npm', verdict: 'held', severity: ['critical', 'high'], sort: 'size', order: 'desc', page: 1, pageSize: 50 })
|
||||
const params = new URL(url, 'http://x').searchParams
|
||||
expect(Object.fromEntries(params)).toEqual({
|
||||
layout: 'rows',
|
||||
page: '1',
|
||||
page_size: '50',
|
||||
q: 'left',
|
||||
registry: 'npm',
|
||||
verdict: 'held',
|
||||
severity: 'critical,high',
|
||||
sort: 'size',
|
||||
order: 'desc',
|
||||
})
|
||||
})
|
||||
|
||||
it('sends an order only with a sort key', () => {
|
||||
expect(rowsUrl({ order: 'desc', page: 1, pageSize: 25 })).not.toContain('order')
|
||||
})
|
||||
})
|
||||
|
||||
describe('usePackageRows', () => {
|
||||
beforeEach(() => vi.mocked(axios.get).mockReset())
|
||||
|
||||
it('keeps the answer of the last query when an earlier one returns late', async () => {
|
||||
let releaseFirst: (v: unknown) => void = () => {}
|
||||
vi.mocked(axios.get)
|
||||
.mockImplementationOnce(() => new Promise((resolve) => (releaseFirst = resolve)))
|
||||
.mockResolvedValueOnce({ data: { packages: [{ id: 'new' }], total: 1, page: 1, page_size: 25 } })
|
||||
const { rows, total, load } = usePackageRows()
|
||||
|
||||
const first = load({ q: 'a', page: 1, pageSize: 25 })
|
||||
await load({ q: 'ab', page: 1, pageSize: 25 })
|
||||
releaseFirst({ data: { packages: [{ id: 'old' }], total: 9, page: 1, page_size: 25 } })
|
||||
await first
|
||||
|
||||
expect(rows.value.map((r) => r.id)).toEqual(['new'])
|
||||
expect(total.value).toBe(1)
|
||||
})
|
||||
|
||||
it('reports a failure without clearing the rows it already has', async () => {
|
||||
vi.mocked(axios.get)
|
||||
.mockResolvedValueOnce({ data: { packages: [{ id: 'a' }], total: 1, page: 1, page_size: 25 } })
|
||||
.mockRejectedValueOnce(new Error('Request failed with status code 502'))
|
||||
const { rows, error, load } = usePackageRows()
|
||||
|
||||
await load({ page: 1, pageSize: 25 })
|
||||
await load({ page: 2, pageSize: 25 })
|
||||
|
||||
expect(error.value).toContain('502')
|
||||
expect(rows.value).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
import { ref, type Ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import type { ApiVerdict, Package } from '@/stores/packages'
|
||||
|
||||
export type RowSort = 'name' | 'version' | 'registry' | 'size' | 'downloads' | 'last_accessed' | 'last_scanned' | 'risk'
|
||||
|
||||
export interface RowQuery {
|
||||
q?: string
|
||||
registry?: string
|
||||
verdict?: ApiVerdict
|
||||
severity?: readonly string[]
|
||||
sort?: RowSort
|
||||
order?: 'asc' | 'desc'
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
type Tally = Record<'critical' | 'high' | 'moderate' | 'low', number>
|
||||
|
||||
/** Counts over the registry and search matches, before the verdict and severity filters. */
|
||||
export interface RowCounts {
|
||||
verdicts: Record<ApiVerdict, number>
|
||||
severity_packages: Tally
|
||||
severity_findings: Tally
|
||||
vulnerable_allowed: number
|
||||
}
|
||||
|
||||
export interface RowsResponse {
|
||||
packages: Package[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
counts: RowCounts
|
||||
}
|
||||
|
||||
export const EMPTY_COUNTS: RowCounts = {
|
||||
verdicts: { cleared: 0, held: 0, bypassed: 0, pending: 0 },
|
||||
severity_packages: { critical: 0, high: 0, moderate: 0, low: 0 },
|
||||
severity_findings: { critical: 0, high: 0, moderate: 0, low: 0 },
|
||||
vulnerable_allowed: 0,
|
||||
}
|
||||
|
||||
/** URL of one page of package rows; empty filters are left out. */
|
||||
export function rowsUrl(query: RowQuery): string {
|
||||
const params = new URLSearchParams({ layout: 'rows', page: String(query.page), page_size: String(query.pageSize) })
|
||||
if (query.q?.trim()) params.set('q', query.q.trim())
|
||||
if (query.registry) params.set('registry', query.registry)
|
||||
if (query.verdict) params.set('verdict', query.verdict)
|
||||
if (query.severity?.length) params.set('severity', query.severity.join(','))
|
||||
if (query.sort) params.set('sort', query.sort)
|
||||
if (query.sort && query.order) params.set('order', query.order)
|
||||
return `/api/packages?${params.toString()}`
|
||||
}
|
||||
|
||||
export interface PackageRows {
|
||||
rows: Ref<Package[]>
|
||||
total: Ref<number>
|
||||
counts: Ref<RowCounts>
|
||||
loading: Ref<boolean>
|
||||
error: Ref<string | null>
|
||||
load: (query: RowQuery) => Promise<void>
|
||||
}
|
||||
|
||||
/** One page of rows from the server. An answer to an older request is dropped, so the last query wins. */
|
||||
export function usePackageRows(): PackageRows {
|
||||
const rows = ref<Package[]>([])
|
||||
const total = ref(0)
|
||||
const counts = ref<RowCounts>(EMPTY_COUNTS)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
let latest = 0
|
||||
|
||||
async function load(query: RowQuery) {
|
||||
const request = ++latest
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const { data } = await axios.get(rowsUrl(query))
|
||||
if (request !== latest) return
|
||||
if (!data || !Array.isArray(data.packages)) {
|
||||
error.value = 'Unexpected response format from server'
|
||||
return
|
||||
}
|
||||
rows.value = data.packages
|
||||
total.value = Number.isFinite(data.total) ? data.total : data.packages.length
|
||||
counts.value = data.counts ?? EMPTY_COUNTS
|
||||
} catch (err) {
|
||||
if (request !== latest) return
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load packages'
|
||||
} finally {
|
||||
if (request === latest) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return { rows, total, counts, loading, error, load }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { packageRoute } from './packages'
|
||||
|
||||
describe('packageRoute', () => {
|
||||
it('splits a name with slashes into route segments', () => {
|
||||
expect(packageRoute({ registry: 'go', name: 'github.com/a/b', version: 'v1.0.0' })).toEqual({
|
||||
name: 'package-details',
|
||||
params: { registry: 'go', name: ['github.com', 'a', 'b'], version: 'v1.0.0' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { RouteLocationRaw } from 'vue-router'
|
||||
import type { Package } from '@/stores/packages'
|
||||
import { displayVersion } from '@/lib/format'
|
||||
|
||||
/** Route of a package's full page. A name with slashes becomes the repeatable `name` segments. */
|
||||
export function packageRoute(pkg: Pick<Package, 'registry' | 'name' | 'version'>): RouteLocationRaw {
|
||||
return { name: 'package-details', params: { registry: pkg.registry, name: pkg.name.split('/'), version: pkg.version } }
|
||||
}
|
||||
|
||||
export function packageLabel(pkg: Package): string {
|
||||
return `${pkg.name} ${displayVersion(pkg)}`
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { humanReason, plural } from './reason'
|
||||
|
||||
describe('plural', () => {
|
||||
it.each([
|
||||
[0, '0 findings'],
|
||||
[1, '1 finding'],
|
||||
[2, '2 findings'],
|
||||
])('%i', (n, want) => expect(plural(n, 'finding')).toBe(want))
|
||||
})
|
||||
|
||||
describe('humanReason', () => {
|
||||
it('rewrites a zero threshold as "any"', () => {
|
||||
expect(humanReason('Package has 1 CRITICAL vulnerabilities (threshold: 0)')).toBe('1 critical finding. Policy holds any critical finding.')
|
||||
})
|
||||
|
||||
it('states a count threshold and pluralises both numbers', () => {
|
||||
expect(humanReason('Package has 5 HIGH vulnerabilities (threshold: 3)')).toBe('5 high findings. Policy holds more than 3 high findings.')
|
||||
expect(humanReason('Package has 2 LOW vulnerabilities (threshold: 1)')).toBe('2 low findings. Policy holds more than 1 low finding.')
|
||||
})
|
||||
|
||||
it('rewrites a severity-floor reason', () => {
|
||||
expect(humanReason('Package has HIGH or CRITICAL vulnerabilities')).toBe('Has a high or critical finding. Policy holds a finding at that level.')
|
||||
expect(humanReason('Package has MODERATE, HIGH, or CRITICAL vulnerabilities')).toBe(
|
||||
'Has a moderate, high or critical finding. Policy holds a finding at that level.',
|
||||
)
|
||||
})
|
||||
|
||||
it('passes an unknown or empty reason through', () => {
|
||||
expect(humanReason('scan failed - fail closed')).toBe('scan failed - fail closed')
|
||||
expect(humanReason(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { formatSeverityName } from '@/lib/severity'
|
||||
|
||||
/** "1 finding", "2 findings". */
|
||||
export function plural(count: number, noun: string): string {
|
||||
return `${count} ${noun}${count === 1 ? '' : 's'}`
|
||||
}
|
||||
|
||||
const THRESHOLD_REASON = /^Package has (\d+) (CRITICAL|HIGH|MODERATE|MEDIUM|LOW) vulnerabilities \(threshold: (-?\d+)\)$/i
|
||||
const FLOOR_REASON = /^Package has ([A-Za-z, ]+?) vulnerabilities$/
|
||||
|
||||
/** Turns the server's hold reason into a sentence a reader can act on. Unknown reasons pass through. */
|
||||
export function humanReason(reason: string | undefined): string {
|
||||
if (!reason) return ''
|
||||
const t = THRESHOLD_REASON.exec(reason)
|
||||
if (t) {
|
||||
const count = Number(t[1])
|
||||
const level = t[2].toLowerCase()
|
||||
const limit = Number(t[3])
|
||||
const rule = limit <= 0 ? `Policy holds any ${level} finding.` : `Policy holds more than ${plural(limit, `${level} finding`)}.`
|
||||
return `${plural(count, `${level} finding`)}. ${rule}`
|
||||
}
|
||||
const f = FLOOR_REASON.exec(reason)
|
||||
if (f) {
|
||||
const levels = f[1]
|
||||
.split(/,\s*(?:or\s+)?|\s+or\s+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map((s) => formatSeverityName(s).toLowerCase())
|
||||
const named = levels.length > 1 ? `${levels.slice(0, -1).join(', ')} or ${levels[levels.length - 1]}` : levels[0]
|
||||
return `Has a ${named} finding. Policy holds a finding at that level.`
|
||||
}
|
||||
return reason
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ScannerResult } from '@/lib/inspectors'
|
||||
import type { AppliedBypass, ApiVerdict, VulnerabilityCounts } from '@/stores/packages'
|
||||
|
||||
export interface VulnerabilityEntry {
|
||||
id: string
|
||||
severity: string
|
||||
title: string
|
||||
description: string
|
||||
references: string[]
|
||||
fixed_in: string
|
||||
detected_by?: string[]
|
||||
aliases?: string[]
|
||||
bypassed: boolean
|
||||
bypass?: { id: string; reason: string; created_by: string; expires_at: string }
|
||||
}
|
||||
|
||||
/** Response of GET /api/packages/{registry}/{name}/{version}/vulnerabilities. */
|
||||
export interface PackageReport {
|
||||
package?: { release_version?: string }
|
||||
scanned: boolean
|
||||
scanner?: string
|
||||
scanned_at?: string
|
||||
status: string
|
||||
message?: string
|
||||
vulnerabilities: VulnerabilityEntry[]
|
||||
vulnerability_count: number
|
||||
severity_counts?: VulnerabilityCounts
|
||||
bypassed_count?: number
|
||||
scanners: ScannerResult[]
|
||||
decision: { verdict: ApiVerdict; blocked: boolean; reason: string; bypass: AppliedBypass | null }
|
||||
}
|
||||
@@ -0,0 +1,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,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describePolicy, scannerState, scannerVersion, type SystemInfo } from './system'
|
||||
|
||||
function security(over: Partial<SystemInfo['security']>): SystemInfo['security'] {
|
||||
return {
|
||||
enabled: true,
|
||||
fail_closed: true,
|
||||
scan_on_download: true,
|
||||
block_on_severity: 'none',
|
||||
block_thresholds: { critical: -1, high: -1, moderate: -1, low: -1 },
|
||||
scan_wait_timeout: 30,
|
||||
scanners: [],
|
||||
rescan: { interval: 0, active_window: 0, concurrency: 1, on_access: false },
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('describePolicy', () => {
|
||||
it('names a critical-only threshold policy', () => {
|
||||
const policy = describePolicy(security({ block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 } }))
|
||||
expect(policy).toBe('Blocks any CRITICAL.')
|
||||
})
|
||||
|
||||
it('states a count threshold', () => {
|
||||
const policy = describePolicy(security({ block_thresholds: { critical: 0, high: 3, moderate: -1, low: -1 } }))
|
||||
expect(policy).toBe('Blocks any CRITICAL, more than 3 HIGH.')
|
||||
})
|
||||
|
||||
it('expands the block-on-severity floor to every level at or above it', () => {
|
||||
expect(describePolicy(security({ block_on_severity: 'high' }))).toBe('Blocks any CRITICAL or HIGH.')
|
||||
})
|
||||
|
||||
it('does not repeat a level the thresholds already cover', () => {
|
||||
const policy = describePolicy(security({ block_on_severity: 'critical', block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 } }))
|
||||
expect(policy).toBe('Blocks any CRITICAL.')
|
||||
})
|
||||
|
||||
it('says so when nothing blocks and when scanning is off', () => {
|
||||
expect(describePolicy(security({}))).toBe('No severity blocks a package.')
|
||||
expect(describePolicy(security({ enabled: false }))).toBe('Scanning is off. Every package is served.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scannerState', () => {
|
||||
it('maps config and probe to a state', () => {
|
||||
expect(scannerState({ name: 'a', enabled: false, healthy: null, version: '' })).toBe('off')
|
||||
expect(scannerState({ name: 'a', enabled: true, healthy: false, version: '' })).toBe('down')
|
||||
expect(scannerState({ name: 'a', enabled: true, healthy: true, version: '' })).toBe('healthy')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scannerVersion', () => {
|
||||
it('shows the version, API for hosted databases, and nothing for a scanner that is off', () => {
|
||||
expect(scannerVersion({ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' })).toBe('v0.58.1')
|
||||
expect(scannerVersion({ name: 'osv', enabled: true, healthy: true, version: '' })).toBe('API')
|
||||
expect(scannerVersion({ name: 'grype', enabled: true, healthy: false, version: '' })).toBe('Version not reported')
|
||||
expect(scannerVersion({ name: 'npm-audit', enabled: false, healthy: null, version: '' })).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
|
||||
export interface ScannerInfo {
|
||||
name: string
|
||||
enabled: boolean
|
||||
/** Null while the scanner is off or has not been probed. */
|
||||
healthy: boolean | null
|
||||
version: string
|
||||
}
|
||||
|
||||
/** Response of GET /api/system. Durations are seconds; a negative threshold means unlimited. */
|
||||
export interface SystemInfo {
|
||||
version: string
|
||||
security: {
|
||||
enabled: boolean
|
||||
fail_closed: boolean
|
||||
scan_on_download: boolean
|
||||
block_on_severity: string
|
||||
block_thresholds: { critical: number; high: number; moderate: number; low: number }
|
||||
scan_wait_timeout: number
|
||||
scanners: ScannerInfo[]
|
||||
rescan: { interval: number; active_window: number; concurrency: number; on_access: boolean }
|
||||
}
|
||||
upstreams: Record<string, string>
|
||||
cache: { max_size: number; idle_ttl: number; default_ttl: number }
|
||||
prewarming: { enabled: boolean; interval: number; top_packages: number }
|
||||
}
|
||||
|
||||
export type ScannerState = 'healthy' | 'down' | 'off'
|
||||
|
||||
export function scannerState(scanner: ScannerInfo): ScannerState {
|
||||
if (!scanner.enabled) return 'off'
|
||||
return scanner.healthy === false ? 'down' : 'healthy'
|
||||
}
|
||||
|
||||
// These scanners query a hosted database, so they have no local binary version.
|
||||
const API_SCANNERS = new Set(['osv', 'github-advisory-database'])
|
||||
|
||||
/** Version line for a scanner: empty when it is off, "API" for hosted databases. */
|
||||
export function scannerVersion(scanner: ScannerInfo): string {
|
||||
if (!scanner.enabled) return ''
|
||||
if (scanner.version) return `v${scanner.version}`
|
||||
return API_SCANNERS.has(scanner.name) ? 'API' : 'Version not reported'
|
||||
}
|
||||
|
||||
const SEVERITY_NAMES = { critical: 'CRITICAL', high: 'HIGH', moderate: 'MODERATE', low: 'LOW' } as const
|
||||
const SEVERITY_ORDER = ['critical', 'high', 'moderate', 'low'] as const
|
||||
|
||||
/** The block policy in words, from the threshold counts and the block-on-severity floor. */
|
||||
export function describePolicy(security: SystemInfo['security']): string {
|
||||
if (!security.enabled) return 'Scanning is off. Every package is served.'
|
||||
const parts: string[] = []
|
||||
for (const level of SEVERITY_ORDER) {
|
||||
const limit = security.block_thresholds[level]
|
||||
if (limit < 0) continue
|
||||
parts.push(limit === 0 ? `any ${SEVERITY_NAMES[level]}` : `more than ${limit} ${SEVERITY_NAMES[level]}`)
|
||||
}
|
||||
const floor = security.block_on_severity.toLowerCase() as keyof typeof SEVERITY_NAMES
|
||||
if (floor in SEVERITY_NAMES) {
|
||||
const covered = SEVERITY_ORDER.slice(0, SEVERITY_ORDER.indexOf(floor) + 1).map((l) => SEVERITY_NAMES[l])
|
||||
parts.push(`any ${covered.join(' or ')}`)
|
||||
}
|
||||
return parts.length === 0 ? 'No severity blocks a package.' : `Blocks ${[...new Set(parts)].join(', ')}.`
|
||||
}
|
||||
|
||||
const info = ref<SystemInfo | null>(null)
|
||||
const error = ref<string | null>(null)
|
||||
let inflight: Promise<void> | null = null
|
||||
|
||||
/** Shared GET /api/system state; concurrent callers share one request. */
|
||||
export function useSystem() {
|
||||
function load(force = false): Promise<void> {
|
||||
if (info.value && !force) return Promise.resolve()
|
||||
inflight ??= axios
|
||||
.get<SystemInfo>('/api/system')
|
||||
.then((res) => {
|
||||
info.value = res.data
|
||||
error.value = null
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
error.value = err instanceof Error ? err.message : 'Could not load system settings'
|
||||
})
|
||||
.finally(() => {
|
||||
inflight = null
|
||||
})
|
||||
return inflight
|
||||
}
|
||||
return { info, error, load }
|
||||
}
|
||||
|
||||
/** Test hook: forgets the cached response. */
|
||||
export function __resetSystem(): void {
|
||||
info.value = null
|
||||
error.value = null
|
||||
inflight = null
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
export type DownloadPeriod = '1h' | '1day' | '7day' | '30day'
|
||||
|
||||
export const DOWNLOAD_PERIODS: { value: DownloadPeriod; label: string }[] = [
|
||||
{ value: '1h', label: '1 hour' },
|
||||
{ value: '1day', label: '24 hours' },
|
||||
{ value: '7day', label: '7 days' },
|
||||
{ value: '30day', label: '30 days' },
|
||||
]
|
||||
|
||||
export interface TimeSeriesPoint {
|
||||
timestamp: string
|
||||
value: number
|
||||
}
|
||||
|
||||
export interface TimeSeries {
|
||||
period: DownloadPeriod
|
||||
registry: string
|
||||
data_points: TimeSeriesPoint[]
|
||||
}
|
||||
|
||||
/** Axis label of one bucket: a time of day for hourly spans, a day otherwise. */
|
||||
export function bucketLabel(period: DownloadPeriod, timestamp: string): string {
|
||||
const date = new Date(timestamp)
|
||||
if (Number.isNaN(date.getTime())) return timestamp
|
||||
if (period === '1h' || period === '1day') {
|
||||
return date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' })
|
||||
}
|
||||
return date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' })
|
||||
}
|
||||
|
||||
/** "2026-11-04T00:00:00Z" as "2026-11-04", the date form the heatmap reads. */
|
||||
export function isoDay(timestamp: string): string {
|
||||
return timestamp.slice(0, 10)
|
||||
}
|
||||
@@ -0,0 +1,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)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { verdictOf, VERDICT_LABELS } from './verdict'
|
||||
|
||||
describe('verdictOf', () => {
|
||||
it.each([
|
||||
['the server verdict when present', { scanned: true, status: 'vulnerable', verdict: 'bypassed', isBlocked: false }, 'bypassed'],
|
||||
['held for a blocked package from an older server', { scanned: true, status: 'vulnerable', isBlocked: true }, 'held'],
|
||||
['cleared for a scanned package from an older server', { scanned: true, status: 'clean' }, 'cleared'],
|
||||
['pending for an unscanned package', { scanned: false, status: 'pending' }, 'pending'],
|
||||
] as const)('%s', (_name, vulnerabilities, want) => {
|
||||
expect(verdictOf({ vulnerabilities: { ...vulnerabilities } })).toBe(want)
|
||||
})
|
||||
|
||||
it('is unscanned when the server sends no scan block, as with scanning off', () => {
|
||||
expect(verdictOf({})).toBe('unscanned')
|
||||
})
|
||||
})
|
||||
|
||||
describe('VERDICT_LABELS', () => {
|
||||
it('uses the checkpoint vocabulary', () => {
|
||||
expect(VERDICT_LABELS).toMatchObject({ cleared: 'Cleared', held: 'Held', bypassed: 'Bypassed', pending: 'Awaiting scan' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Package } from '@/stores/packages'
|
||||
|
||||
/** The customs-desk outcome of a package; `unscanned` is a server with scanning off. */
|
||||
export type Verdict = 'cleared' | 'held' | 'bypassed' | 'pending' | 'unscanned'
|
||||
|
||||
export const VERDICT_LABELS: Record<Verdict, string> = {
|
||||
cleared: 'Cleared',
|
||||
held: 'Held',
|
||||
bypassed: 'Bypassed',
|
||||
pending: 'Awaiting scan',
|
||||
unscanned: 'Not scanned',
|
||||
}
|
||||
|
||||
export const VERDICT_TONES: Record<Verdict, 'success' | 'danger' | 'info' | 'warning' | 'neutral'> = {
|
||||
cleared: 'success',
|
||||
held: 'danger',
|
||||
bypassed: 'info',
|
||||
pending: 'warning',
|
||||
unscanned: 'neutral',
|
||||
}
|
||||
|
||||
/** Text colour of a verdict's icon; the label is always shown beside it. */
|
||||
export const VERDICT_TEXT: Record<Verdict, string> = {
|
||||
cleared: 'text-success',
|
||||
held: 'text-destructive',
|
||||
bypassed: 'text-info',
|
||||
pending: 'text-warning',
|
||||
unscanned: 'text-muted-foreground',
|
||||
}
|
||||
|
||||
/** One sentence per verdict, for tooltips and headings. */
|
||||
export const VERDICT_MEANINGS: Record<Verdict, string> = {
|
||||
cleared: 'Scanned and under the block policy. Served to clients.',
|
||||
held: 'At or over the block policy. Clients get a 403.',
|
||||
bypassed: 'An admin bypass applies. Served to clients.',
|
||||
pending: 'No scan result yet.',
|
||||
unscanned: 'Security scanning is off.',
|
||||
}
|
||||
|
||||
export const VERDICT_OPTIONS = (['cleared', 'held', 'bypassed', 'pending'] as const).map((value) => ({
|
||||
value,
|
||||
label: VERDICT_LABELS[value],
|
||||
}))
|
||||
|
||||
/** Sort order for a verdict column: worst first. */
|
||||
export const VERDICT_RANK: Record<Verdict, number> = { held: 4, pending: 3, bypassed: 2, cleared: 1, unscanned: 0 }
|
||||
|
||||
export function verdictOf(pkg: Pick<Package, 'vulnerabilities'>): Verdict {
|
||||
const info = pkg.vulnerabilities
|
||||
if (!info) return 'unscanned'
|
||||
if (info.verdict) return info.verdict
|
||||
if (info.isBlocked) return 'held'
|
||||
return info.scanned ? 'cleared' : 'pending'
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { verdictBanner } from './verdictBanner'
|
||||
import type { PackageReport } from './report'
|
||||
|
||||
function report(over: Partial<PackageReport>): PackageReport {
|
||||
return {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
vulnerabilities: [],
|
||||
vulnerability_count: 0,
|
||||
scanners: [],
|
||||
decision: { verdict: 'cleared', blocked: false, reason: '', bypass: null },
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
const vuln = (id: string, severity: string, extra: object = {}) => ({
|
||||
id,
|
||||
severity,
|
||||
title: '',
|
||||
description: '',
|
||||
references: [],
|
||||
fixed_in: '',
|
||||
bypassed: false,
|
||||
...extra,
|
||||
})
|
||||
|
||||
describe('verdictBanner', () => {
|
||||
it('names the blocking advisory, its severity, the policy and the fix', () => {
|
||||
const banner = verdictBanner(
|
||||
report({
|
||||
vulnerabilities: [vuln('CVE-2021-44906', 'CRITICAL', { fixed_in: '1.2.6' }), vuln('CVE-2022-0001', 'LOW')],
|
||||
decision: { verdict: 'held', blocked: true, reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)', bypass: null },
|
||||
}),
|
||||
'Blocks any CRITICAL.',
|
||||
true,
|
||||
)
|
||||
expect(banner.type).toBe('danger')
|
||||
expect(banner.title).toBe('Held: CVE-2021-44906 is CRITICAL')
|
||||
expect(banner.body).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
expect(banner.body).not.toContain('threshold')
|
||||
expect(banner.body).toContain('403')
|
||||
expect(banner.body).toContain('Fixed in v1.2.6')
|
||||
})
|
||||
|
||||
it('summarises many blockers and ignores bypassed ones', () => {
|
||||
const vulns = ['A', 'B', 'C', 'D', 'E'].map((id) => vuln(id, 'critical'))
|
||||
vulns.push(vuln('Z', 'critical', { bypassed: true }))
|
||||
const banner = verdictBanner(report({ vulnerabilities: vulns, decision: { verdict: 'held', blocked: true, reason: '', bypass: null } }), '', true)
|
||||
expect(banner.title).toBe('Held: A, B, C and 2 more are CRITICAL')
|
||||
})
|
||||
|
||||
it('falls back to the reason when no finding explains the hold', () => {
|
||||
const banner = verdictBanner(
|
||||
report({ decision: { verdict: 'held', blocked: true, reason: 'scan failed - fail closed', bypass: null } }),
|
||||
'Blocks any CRITICAL.',
|
||||
true,
|
||||
)
|
||||
expect(banner.title).toBe('Held: scan failed - fail closed')
|
||||
})
|
||||
|
||||
it('says who bypassed a package and when it expires', () => {
|
||||
const banner = verdictBanner(
|
||||
report({
|
||||
decision: {
|
||||
verdict: 'bypassed',
|
||||
blocked: false,
|
||||
reason: '',
|
||||
bypass: {
|
||||
id: 'b1',
|
||||
type: 'package',
|
||||
target: 'npm/x@1',
|
||||
reason: 'Vendored fix',
|
||||
created_by: 'a.khan',
|
||||
created_at: '2026-11-01T00:00:00Z',
|
||||
expires_at: '2026-12-01T00:00:00Z',
|
||||
},
|
||||
},
|
||||
}),
|
||||
'',
|
||||
true,
|
||||
)
|
||||
expect(banner.type).toBe('note')
|
||||
expect(banner.title).toBe('Bypassed: Vendored fix')
|
||||
expect(banner.body).toContain('a.khan')
|
||||
expect(banner.body).toContain('package bypass')
|
||||
})
|
||||
|
||||
it('reports an unscanned package by the fail-closed rule', () => {
|
||||
const base = report({ scanned: false, decision: { verdict: 'pending', blocked: false, reason: '', bypass: null } })
|
||||
expect(verdictBanner(base, '', true).body).toContain('held until one does')
|
||||
expect(verdictBanner(base, '', false).body).not.toContain('held')
|
||||
})
|
||||
|
||||
it('counts findings that stay under the policy', () => {
|
||||
expect(verdictBanner(report({ vulnerability_count: 2 }), '', true).body).toContain('2 findings below the block policy')
|
||||
expect(verdictBanner(report({}), '', true).body).toContain('reported nothing')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { PackageReport } from '@/lib/report'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import { humanReason, plural } from '@/lib/reason'
|
||||
import { formatSeverityName, severityRank } from '@/lib/severity'
|
||||
|
||||
export interface BannerContent {
|
||||
type: 'danger' | 'success' | 'note' | 'warning'
|
||||
title: string
|
||||
body: string
|
||||
}
|
||||
|
||||
const MAX_NAMED = 3
|
||||
|
||||
function listIds(ids: readonly string[]): string {
|
||||
const shown = ids.slice(0, MAX_NAMED).join(', ')
|
||||
return ids.length > MAX_NAMED ? `${shown} and ${ids.length - MAX_NAMED} more` : shown
|
||||
}
|
||||
|
||||
function heldBanner(report: PackageReport, policy: string): BannerContent {
|
||||
const live = report.vulnerabilities.filter((v) => !v.bypassed)
|
||||
const top = live.reduce((max, v) => Math.max(max, severityRank(v.severity)), 0)
|
||||
const blockers = live.filter((v) => severityRank(v.severity) === top)
|
||||
const reason = humanReason(report.decision.reason)
|
||||
const clients = 'Clients that request this version get a 403.'
|
||||
if (blockers.length === 0) {
|
||||
return { type: 'danger', title: `Held: ${reason || 'the scan did not complete'}`, body: `${policy} ${clients}`.trim() }
|
||||
}
|
||||
const verb = blockers.length === 1 ? 'is' : 'are'
|
||||
const fixes = [...new Set(blockers.map((b) => b.fixed_in).filter(Boolean))]
|
||||
const fix = fixes.length > 0 ? ` Fixed in ${fixes.map(withVersionPrefix).join(', ')}.` : ' No fixed version is listed.'
|
||||
return {
|
||||
type: 'danger',
|
||||
title: `Held: ${listIds(blockers.map((b) => b.id))} ${verb} ${formatSeverityName(blockers[0].severity).toUpperCase()}`,
|
||||
body: `${reason || policy} ${clients}${fix}`.replace(/\s+/g, ' ').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
/** The sentence at the top of a package page: what the verdict is and why. */
|
||||
export function verdictBanner(report: PackageReport, policy: string, failClosed: boolean): BannerContent {
|
||||
const { verdict, bypass } = report.decision
|
||||
switch (verdict) {
|
||||
case 'held':
|
||||
return heldBanner(report, policy)
|
||||
case 'bypassed': {
|
||||
const scope = bypass?.type === 'package' ? 'package' : 'advisory'
|
||||
return {
|
||||
type: 'note',
|
||||
title: `Bypassed: ${bypass?.reason ?? 'an admin bypass applies'}`,
|
||||
body: bypass
|
||||
? `${bypass.created_by} created this ${scope} bypass on ${formatDate(bypass.created_at)}. It expires on ${formatDate(bypass.expires_at)}. Clients are served this version.`
|
||||
: 'Clients are served this version.',
|
||||
}
|
||||
}
|
||||
case 'pending':
|
||||
return {
|
||||
type: 'warning',
|
||||
title: 'Awaiting scan',
|
||||
body: failClosed
|
||||
? 'No scanner has reported on this version yet. The policy is fail-closed, so it is held until one does.'
|
||||
: 'No scanner has reported on this version yet.',
|
||||
}
|
||||
default: {
|
||||
const n = report.vulnerability_count
|
||||
return {
|
||||
type: 'success',
|
||||
title: 'Cleared: no finding reaches the block policy',
|
||||
body: n === 0 ? 'The scanners reported nothing. Clients are served this version.' : `${plural(n, 'finding')} below the block policy. Clients are served this version.`,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Lightweight WebSocket client with auto-reconnect, heartbeat, and pub/sub.
|
||||
*
|
||||
* Backend (pkg/websocket/server.go) emits envelopes shaped like:
|
||||
* { "type": "package_cached", "timestamp": "2026-04-28T12:34:56Z", "data": {...} }
|
||||
*
|
||||
* We normalize this into RealtimeEvent { type, payload, timestamp(number ms) }.
|
||||
*/
|
||||
|
||||
export type EventType =
|
||||
| 'package_deleted'
|
||||
| 'package_cached'
|
||||
| 'package_downloaded'
|
||||
| 'scan_complete'
|
||||
| 'stats_update'
|
||||
|
||||
export interface RealtimeEvent {
|
||||
type: EventType
|
||||
payload: Record<string, unknown>
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
type WildcardListener = '*'
|
||||
type ListenerKey = EventType | WildcardListener
|
||||
type Listener = (e: RealtimeEvent) => void
|
||||
|
||||
const KNOWN_EVENT_TYPES: ReadonlySet<string> = new Set<EventType>([
|
||||
'package_deleted',
|
||||
'package_cached',
|
||||
'package_downloaded',
|
||||
'scan_complete',
|
||||
'stats_update',
|
||||
])
|
||||
|
||||
const RECONNECT_BASE_MS = 1_000
|
||||
const RECONNECT_MAX_MS = 30_000
|
||||
const HEARTBEAT_INTERVAL_MS = 25_000
|
||||
const RECONNECT_QUEUE_CAP = 50
|
||||
|
||||
interface OutboundMessage {
|
||||
action: string
|
||||
data?: unknown
|
||||
}
|
||||
|
||||
function defaultUrl(): string {
|
||||
if (typeof window === 'undefined' || !window.location) {
|
||||
return 'ws://localhost/ws'
|
||||
}
|
||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
return `${proto}//${window.location.host}/ws`
|
||||
}
|
||||
|
||||
function isKnownEventType(value: unknown): value is EventType {
|
||||
return typeof value === 'string' && KNOWN_EVENT_TYPES.has(value)
|
||||
}
|
||||
|
||||
function coerceTimestamp(raw: unknown): number {
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
||||
return raw
|
||||
}
|
||||
if (typeof raw === 'string') {
|
||||
const parsed = Date.parse(raw)
|
||||
if (!Number.isNaN(parsed)) return parsed
|
||||
}
|
||||
return Date.now()
|
||||
}
|
||||
|
||||
function parseEvent(text: string): RealtimeEvent | null {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!parsed || typeof parsed !== 'object') return null
|
||||
const obj = parsed as Record<string, unknown>
|
||||
|
||||
// Server may also emit `{ type: "pong" }` style control frames; ignore those.
|
||||
if (!isKnownEventType(obj.type)) return null
|
||||
|
||||
const payloadSource = obj.payload ?? obj.data
|
||||
const payload =
|
||||
payloadSource && typeof payloadSource === 'object'
|
||||
? (payloadSource as Record<string, unknown>)
|
||||
: {}
|
||||
|
||||
return {
|
||||
type: obj.type,
|
||||
payload,
|
||||
timestamp: coerceTimestamp(obj.timestamp),
|
||||
}
|
||||
}
|
||||
|
||||
export class WSClient {
|
||||
readonly url: string
|
||||
private socket: WebSocket | null = null
|
||||
private listeners: Map<ListenerKey, Set<Listener>> = new Map()
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private reconnectAttempts = 0
|
||||
private explicitlyClosed = false
|
||||
private outboundQueue: OutboundMessage[] = []
|
||||
private _connected = false
|
||||
|
||||
constructor(url?: string) {
|
||||
this.url = url ?? defaultUrl()
|
||||
}
|
||||
|
||||
get connected(): boolean {
|
||||
return this._connected
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
this.explicitlyClosed = false
|
||||
this.openSocket()
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.explicitlyClosed = true
|
||||
this.clearReconnect()
|
||||
this.stopHeartbeat()
|
||||
this._connected = false
|
||||
if (this.socket) {
|
||||
try {
|
||||
this.socket.close()
|
||||
} catch {
|
||||
/* swallow */
|
||||
}
|
||||
this.socket = null
|
||||
}
|
||||
}
|
||||
|
||||
on(type: ListenerKey, cb: Listener): () => void {
|
||||
let bucket = this.listeners.get(type)
|
||||
if (!bucket) {
|
||||
bucket = new Set()
|
||||
this.listeners.set(type, bucket)
|
||||
}
|
||||
bucket.add(cb)
|
||||
return () => {
|
||||
const current = this.listeners.get(type)
|
||||
if (!current) return
|
||||
current.delete(cb)
|
||||
if (current.size === 0) this.listeners.delete(type)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message. If not connected, queue (capped) and flush on open.
|
||||
*/
|
||||
send(msg: OutboundMessage): void {
|
||||
if (this.socket && this._connected && this.socket.readyState === 1) {
|
||||
try {
|
||||
this.socket.send(JSON.stringify(msg))
|
||||
return
|
||||
} catch {
|
||||
/* fall through to queue */
|
||||
}
|
||||
}
|
||||
if (this.outboundQueue.length >= RECONNECT_QUEUE_CAP) {
|
||||
this.outboundQueue.shift()
|
||||
}
|
||||
this.outboundQueue.push(msg)
|
||||
}
|
||||
|
||||
private openSocket(): void {
|
||||
const Ctor: typeof WebSocket | undefined =
|
||||
typeof WebSocket !== 'undefined'
|
||||
? WebSocket
|
||||
: (globalThis as unknown as { WebSocket?: typeof WebSocket }).WebSocket
|
||||
if (!Ctor) {
|
||||
// No WebSocket available (e.g. SSR); silently bail.
|
||||
return
|
||||
}
|
||||
|
||||
let socket: WebSocket
|
||||
try {
|
||||
socket = new Ctor(this.url)
|
||||
} catch {
|
||||
this.scheduleReconnect()
|
||||
return
|
||||
}
|
||||
this.socket = socket
|
||||
|
||||
socket.onopen = () => {
|
||||
this._connected = true
|
||||
this.reconnectAttempts = 0
|
||||
this.startHeartbeat()
|
||||
this.flushQueue()
|
||||
}
|
||||
|
||||
socket.onmessage = (ev: MessageEvent) => {
|
||||
const data = ev.data
|
||||
if (typeof data !== 'string') return
|
||||
const evt = parseEvent(data)
|
||||
if (!evt) return
|
||||
this.dispatch(evt)
|
||||
}
|
||||
|
||||
socket.onerror = () => {
|
||||
// onclose handles reconnect; nothing to do here.
|
||||
}
|
||||
|
||||
socket.onclose = () => {
|
||||
this._connected = false
|
||||
this.stopHeartbeat()
|
||||
this.socket = null
|
||||
if (!this.explicitlyClosed) {
|
||||
this.scheduleReconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private dispatch(event: RealtimeEvent): void {
|
||||
const exact = this.listeners.get(event.type)
|
||||
if (exact) {
|
||||
for (const cb of exact) {
|
||||
try {
|
||||
cb(event)
|
||||
} catch (err) {
|
||||
console.error('[ws] listener error', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
const wild = this.listeners.get('*')
|
||||
if (wild) {
|
||||
for (const cb of wild) {
|
||||
try {
|
||||
cb(event)
|
||||
} catch (err) {
|
||||
console.error('[ws] listener error', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private flushQueue(): void {
|
||||
if (!this.socket || !this._connected) return
|
||||
const queued = this.outboundQueue.splice(0)
|
||||
for (const msg of queued) {
|
||||
try {
|
||||
this.socket.send(JSON.stringify(msg))
|
||||
} catch {
|
||||
// requeue and bail
|
||||
this.outboundQueue.unshift(msg)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private startHeartbeat(): void {
|
||||
this.stopHeartbeat()
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
if (this.socket && this._connected) {
|
||||
try {
|
||||
this.socket.send(JSON.stringify({ action: 'ping' }))
|
||||
} catch {
|
||||
/* swallow; reconnect path will handle */
|
||||
}
|
||||
}
|
||||
}, HEARTBEAT_INTERVAL_MS)
|
||||
}
|
||||
|
||||
private stopHeartbeat(): void {
|
||||
if (this.heartbeatTimer !== null) {
|
||||
clearInterval(this.heartbeatTimer)
|
||||
this.heartbeatTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.explicitlyClosed) return
|
||||
this.clearReconnect()
|
||||
const delay = Math.min(
|
||||
RECONNECT_MAX_MS,
|
||||
RECONNECT_BASE_MS * 2 ** this.reconnectAttempts,
|
||||
)
|
||||
this.reconnectAttempts += 1
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null
|
||||
this.openSocket()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
private clearReconnect(): void {
|
||||
if (this.reconnectTimer !== null) {
|
||||
clearTimeout(this.reconnectTimer)
|
||||
this.reconnectTimer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test-only helpers — exported under a namespace so production code does not
|
||||
// reach into reconnect math accidentally.
|
||||
export const __wsInternals = {
|
||||
RECONNECT_BASE_MS,
|
||||
RECONNECT_MAX_MS,
|
||||
HEARTBEAT_INTERVAL_MS,
|
||||
parseEvent,
|
||||
defaultUrl,
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user