Compare commits

...
72 Commits
Author SHA1 Message Date
lukaszraczylo 547f41677a fix(ui): stop the package tables scrolling sideways by a few pixels
The library sort button bleeds 0.5rem past its cell. The workbench
pack pads cells by 0.4rem, so the last column overflowed the table
and showed a horizontal scrollbar.
2026-11-24 02:19:45 +00:00
lukaszraczylo 7b8ff467b8 fix(ui): load each overview panel once
The download trend, leaderboards and scanner health sat inside the
stats loading branch. A stats refresh unmounted and remounted them,
so every panel fetched its data twice on each visit.
2026-11-24 02:19:44 +00:00
lukaszraczylo 48bd654839 fix(app): give proxy handlers a request that owns its strings
The fiber adaptor builds the URL, Host, Method and header strings of
the net/http request over the fasthttp request buffer. The next request
on the connection overwrites that buffer. The proxies pass these
strings to background scans, singleflight keys and analytics, which
outlive the request. Each proxy route now receives a copy.
2026-11-24 02:11:32 +00:00
lukaszraczylo 80160eeb56 refactor(ui): remove the unused package list store functions
The pages load rows through lib/packageRows, so fetchPackages,
fetchPackagePage, fetchRecentPackages and their state had no callers.
2026-11-24 02:06:18 +00:00
lukaszraczylo a685b71c7f fix(ui): rank most requested packages by the stored download counts
The ranking read in-memory analytics, so it was empty after every restart
while the Downloads chart and the package pages read the database. It now
sums the stored counts per package, counts a Go module once by its zip,
and says which ranking is kept across restarts and which is not.
2026-11-24 02:06:14 +00:00
lukaszraczylo 798fadb4bb fix(ui): load package details from the single-package endpoint
The details page filtered the grouped package list to find its row. It
now requests /api/packages/{registry}/{name}/{version}, which also
resolves Go modules and PyPI release versions.
2026-11-24 02:06:13 +00:00
lukaszraczylo 4b2ec7c45c fix(ui): show stored downloads when analytics hold no record
The Downloads tab hid the stored count when analytics had no record since
the last restart, and it requested a Go file key per version. It now
always shows the stored count, labels the in-memory totals as counted
since the restart, and asks for a Go module by its path. A failed
request is reported instead of a 404 being swallowed.
2026-11-24 02:06:06 +00:00
lukaszraczylo 8b6f1ae4ac feat(api): serve one package version at /api/packages/{registry}/{name}/{version} 2026-11-24 02:05:57 +00:00
lukaszraczylo bc56b97677 fix(api): answer 200 when analytics hold no record for a package
Analytics live in memory and restart empty. A package with no record yet
returned 404, which every browser logs as a failed request on the
Downloads tab. The endpoint now returns a null package.
2026-11-24 02:05:55 +00:00
lukaszraczylo 7470c41560 fix(analytics): keep package names and count artifact downloads only
The proxy passed request-buffer names to the analytics engine, which kept
them. The server reuses those buffers, so later requests rewrote the
stored names (for example lodash became lodas, and API paths appeared as
package names). The engine now copies the names it keeps.

Metadata pages (npm packuments, Go list, info and mod files, PyPI pages)
no longer count as downloads, and a Go module is one analytics key by its
module path. The version count now counts distinct versions.
2026-11-24 02:05:53 +00:00
lukaszraczylo 8b4d4746df feat(ui): show advisory aliases and offer a bypass for each id
The vulnerability table lists the other ids of a finding. The expanded
row links to the bypass form for the id and for each alias.
2026-11-24 01:39:54 +00:00
lukaszraczylo 43e075baf3 feat(scanner): match bypasses and merge findings across advisory aliases
Scanners report one advisory under different ids, such as a GHSA id from
OSV and the CVE id from Trivy. Findings now carry an aliases list.
The merge folds findings that share any id into one finding. A bypass
for any id of a finding now covers it. Stored findings without aliases
still load and match by their own id.
2026-11-24 01:39:51 +00:00
lukaszraczylo 64793f9c7e feat(ui): page, filter and sort packages on the server
The packages and security pages ask for one page of rows instead of the whole cache. Search is debounced, and the filters and sort stay in the URL.
2026-11-24 01:33:30 +00:00
lukaszraczylo 55c60cb8e4 feat(api): serve filtered, sorted pages of package rows
GET /api/packages?layout=rows adds q, registry, verdict, severity, sort, order, page and page_size, and returns total and per-verdict counts. Requests without layout=rows keep the existing response.
2026-11-24 01:33:27 +00:00
lukaszraczylo ad8295455d fix(ui): clearer hold reasons, aligned details and chart states
Render the hold reason as a sentence, pluralise counts, give the details grid a fixed rhythm, use distinct registry colours, label the plotted series, and show a note for a single day of history.
2026-11-24 01:27:22 +00:00
lukaszraczylo 6e8ac5265c fix(prewarming): run a manual cycle on the worker context
TriggerPrewarm passed the request context to a background goroutine, so the cycle stopped when the HTTP request returned. The cycle now uses the worker context and Stop waits for it.
2026-11-24 01:27:20 +00:00
lukaszraczylo 671bb0625b feat(ui): redesign the dashboard as a package checkpoint
Add overview, packages with quick view, package detail tabs, a merged security page, insights, system and restyled bypasses. Old vulnerable and blocked routes redirect to the matching security tab.
2026-11-24 01:13:09 +00:00
lukaszraczylo 45aa4bcace fix(app): serve the dashboard for client-side routes
A reload or shared link such as /packages?verdict=held returned 404 because the static handler had no fallback. Page loads for paths outside the API and proxy prefixes now receive index.html.
2026-11-24 01:13:01 +00:00
lukaszraczylo b248bfed31 fix(api): serve per-package analytics for names with slashes
The route matched one path segment, so scoped npm names and Go module
paths returned 404. It now takes the rest of the path as the name.
2026-11-24 00:49:27 +00:00
lukaszraczylo a511544d7a feat(api): report upstream hosts in /api/system
Each registry upstream shows its scheme and host only. The endpoint
drops credentials, paths and query strings from the configured URL.
2026-11-24 00:44:26 +00:00
lukaszraczylo 6ddc382d5b feat(api): add /api/system and per-package verdicts
Add a read-only /api/system endpoint with the effective scan policy,
scanner health, rescan, cache and pre-warming settings. It exposes no
credentials or paths.

The package list now carries a verdict (cleared, held, bypassed or
pending) with the reason and the applied bypass. /api/stats adds
bypassed_packages. The vulnerability detail response adds the decision,
a per-scanner severity breakdown and detected_by on each finding.
2026-11-24 00:42:44 +00:00
lukaszraczylo 2b6f3bd892 feat(scanner): report per-scanner health and the bypass behind a decision
The manager now exposes the cached health, and the CLI version, of every
registered scanner. A scan decision also names the admin bypass that
applied to the package, so callers can tell a bypassed package from a
cleared one.
2026-11-24 00:42:41 +00:00
lukaszraczylo 916e2b0aa5 fix(proxy): keep package names that start with the registry name
The app mounts each handler behind http.StripPrefix. The npm and PyPI
handlers trimmed the registry prefix a second time. A request for
npm-run-all reached upstream as -run-all, and the npm package itself
became an empty path. PyPI trimmed /simple without a segment check.
2026-11-24 00:22:49 +00:00
lukaszraczylo 30ebfaae3e chore(deploy): add rescan and scan-wait keys to the example configs
The Helm chart and the Kubernetes configmap listed only rescan_interval.
They now also set rescan_active_window, rescan_concurrency,
rescan_on_access and scan_wait_timeout. The values match the effective
code defaults, so a deploy behaves as before.
2026-11-24 00:20:01 +00:00
lukaszraczylo 3a7ffab4d5 fix(prewarming): start the worker and cache through the proxy path
The pre-warm worker was never started, and its fetch discarded the
response body, so nothing reached the cache. startWorkers now calls
Start. The worker hands each package to a Fetcher. ProxyFetcher calls
the npm, Go and PyPI handlers in-process, resolves the latest version,
and downloads the artifact. The cache and the scan queue then treat it
like a client request.

Pre-warming stays off unless prewarming.enabled is set. Stop is safe on
a worker that never started, and a second Start does nothing.
2026-11-24 00:19:36 +00:00
lukaszraczylo 22f2a8dfb9 fix(trivy): unpack npm tarballs before scanning
Trivy does not read archives, so a bare npm tarball always scanned clean.
The scanner now extracts the tarball into node_modules/<name> in a temp
dir and runs trivy rootfs on it, so the node-pkg analyzer sees the
package.json. Extraction rejects absolute paths, parent segments and
links that leave the tree, and caps the unpacked size at 512 MiB. The
temp dir is removed after the scan.

PyPI wheels and Go module zips share the archive problem and need their
own extractors. This commit does not change them.
2026-11-24 00:16:07 +00:00
lukaszraczylo 4870f243fc docs(lean): record the govulncheck and OSV scanner fixes as GH-27 and GH-28 2026-11-23 19:54:42 +00:00
lukaszraczylo fac30f59e6 fix(osv): take the fixed version from the queried package range
An advisory can cover several packages. The fixed version came from the first range, so x/net findings showed the stdlib fix 1.26.9 instead of the x/net fix 0.60.0.
2026-11-23 19:54:33 +00:00
lukaszraczylo 775ed8a4aa fix(govulncheck): count findings in the scanned module only
A module was charged with advisories against its dependencies at the minimum versions in its go.mod. A consuming build resolves its own versions, so these findings do not describe the module. On production golang.org/x/net v0.56.0 carried x/crypto and x/text advisories this way. Stdlib findings describe the scanner toolchain and are also dropped.
2026-11-23 19:54:30 +00:00
lukaszraczylo e6d8ed0f2e fix(scanner): reuse a recent scanner health result
Each /health request ran the version command of every scanner. Under rescan load one round took about 1.4 seconds, which exceeds the client probes that use /health to choose the cache. The result is now reused for 30 seconds. A probe that ends with a cancelled context is not stored.
2026-11-23 19:47:16 +00:00
lukaszraczylo 40ed8f8213 docs(lean): model rescan skip and on-access freshness as GH-26
The rescan worker skip predicate matches the serve path. A hit whose scan is
older than the interval is judged on a fresh scan, or on the previous result
when the rescan times out.
2026-11-23 19:30:16 +00:00
lukaszraczylo ecf750adbb feat(cache): rescan stale cache hits before serving
With security.rescan_on_access and rescan_interval set, a hit whose scan
result is missing or older than the interval is rescanned before it is
served. Concurrent hits share one scan, and the scan runs under the
manager context so a client disconnect does not abort it. The wait is
bounded by scan_wait_timeout. On a timeout the previous result decides,
or the first-download rule applies when none exists.
2026-11-23 19:27:49 +00:00
lukaszraczylo 41f8369c43 feat(rescan): limit rescans to active packages and run them in parallel
security.rescan_active_window skips packages not requested within the
window. security.rescan_concurrency runs a bounded pool of scans per
cycle. The cycle summary reports skips by reason. Both options default
to the previous behaviour.
2026-11-23 19:26:10 +00:00
lukaszraczylo d6044cdd2e fix(rescan): skip Go .mod and .info rows in the rescan worker
The worker kept its own list of metadata versions and scanned Go module
metadata rows that the serve path never scans. It now uses
metadata.IsMetadataEntry like the cache layer.
2026-11-23 19:25:28 +00:00
lukaszraczylo 1baa6b8e26 docs(lean): model the merge of error results as GH-25
Add the merge model for error-status results and the ledger row. One
error result with one clean result reads clean, all errors read error,
and an error never hides a finding.
2026-11-23 18:07:30 +00:00
lukaszraczylo 3d6bda3a5f fix(pip-audit): audit the release from a pinned requirement
pip-audit takes a project directory as its positional argument and has
no --pyproject option, so every wheel and sdist scan failed. The scanner
now audits name==version from a requirements file with --no-deps and
--disable-pip.

It reads stdout only, lists each advisory once, and treats a skip_reason
as an error because pip-audit exits 0 for a package it could not audit.
2026-11-23 18:07:27 +00:00
lukaszraczylo e37c797602 fix(govulncheck): scan the module as a dependency and read the stream
govulncheck prints indented JSON objects. The line parser read none of
them, so every module read clean.

govulncheck also never reports advisories against the main module of the
tree it scans. A scan of the x/text 0.3.5 source found nothing. The
module is now a dependency of a wrapper module that imports its
packages, and the scan runs at module level.
2026-11-23 18:07:21 +00:00
lukaszraczylo 157814cf08 fix(npm-audit): audit the package through a wrapper project
npm 11 prints via as an array and metadata.dependencies as an object, so
the parser failed on every report. It now reads both shapes of via and
lists each advisory once.

The lockfile step resolved devDependencies, which took 28 seconds for
dayjs and reported 142 findings in its development tree. The tarball is
now the only dependency of a wrapper project, audited with --omit=dev.
This also audits the package itself, which npm audit skips for a root.
2026-11-23 18:07:00 +00:00
lukaszraczylo 65aa2e25dc fix(grype): parse file sources and scan packages by purl
grype 0.121 prints source.target as a string for file, directory and
purl sources. The parser expected an object and failed every scan.

A bare npm, PyPI or Go archive holds nothing grype can catalog, so a
scan of the archive read minimist 0.0.8 as clean. The scanner now passes
a purl for these registries and falls back to the file for others.
2026-11-23 18:06:57 +00:00
lukaszraczylo 3731ca05ce fix(scanner): leave failed scanner results out of the merge
A scanner that returns a result with status error now counts as a failed
scanner, like one that returns an error. Its result no longer joins the
merge, and the manager counts it as an infrastructure failure or another
failure by its cause.

The merged status is error only when every applicable scanner failed.
The fail_closed setting then decides that case as before. One scanner
failing while another returns clean now reads clean.
2026-11-23 18:06:54 +00:00
lukaszraczylo 8adb1e0c87 build: pin the scanner image tool versions
The scanner image installed trivy and grype from install scripts on the main branch, govulncheck at latest and pip-audit unpinned, so every build could pull different tools. They are now pinned: trivy v0.76.2, grype v0.121.2, govulncheck v1.9.0 and pip-audit 2.10.1, each released at least two weeks ago.
2026-11-23 17:37:51 +00:00
lukaszraczylo 16fb52ed3e feat(config): make the first-download scan wait configurable
The cache waited a fixed 30 seconds for a first download's scan, and the app never set the wait. Scanners run one after another, so a deployment with several scanners and fail_closed refused most first downloads. security.scan_wait_timeout now sets the wait; 0 keeps 30 seconds.
2026-11-23 17:37:45 +00:00
lukaszraczylo 13abb140d7 docs(lean): record the GH-24 fix commit 2026-11-23 17:24:58 +00:00
lukaszraczylo 378b8731fc fix(app): start the rescan worker
The app created the rescan worker when security.rescan_interval was set but never started it; only Shutdown called Stop. A scan lost to a restart therefore left its package unscanned for good, and old results were never refreshed with new CVEs. startWorkers now starts the worker. The ledger records it as GH-24.
2026-11-23 17:24:55 +00:00
lukaszraczylo a83cc20058 docs(lean): record the GH-23 fix commit 2026-11-23 17:08:24 +00:00
lukaszraczylo 501bf1aec8 fix(pypi): serve pip's PEP 658 metadata requests
pip builds the PEP 658 URL by appending .metadata to the whole link, so the suffix lands on original_url, not the path. The filename binding from GH-01 then rejected the request with 400, and every pip install through the proxy failed. The handler now treats that form as the requested wheel's sidecar and streams it without storing it. A sidecar of another file is still refused. The Lean model and the ledger cover the new form (GH-23).
2026-11-23 17:08:20 +00:00
lukaszraczylo 527c1759f9 fix(frontend): revalidate index.html on every load
nginx sent index.html without Cache-Control, so browsers cached it heuristically. After a deploy, a browser kept loading the previous hashed bundle until the cache expired, and fixes did not appear. The SPA location now sends Cache-Control: no-cache. Hashed assets stay immutable. scripts/check_frontend_html_cache.sh checks both.
2026-11-23 16:36:10 +00:00
lukaszraczylo 933b5a75c0 fix(ui): read nested stats from stats_update events
The server sends stats_update as {stats, timestamp}, but the realtime store read the counters from the top level of the payload. About 30 seconds after load, the first broadcast replaced the polled stats with undefined values, and the dashboard tiles showed 0. The store now unwraps the nested stats object.
2026-11-23 16:30:22 +00:00
lukaszraczylo f4cf96e1e8 fix(api): resolve Go module paths to cache keys for vulnerability details
The dashboard links Go packages by module path, but Go rows are stored under cache keys (module/@v/version.zip, .mod, .info). The vulnerability details lookup used the module path, so every Go details page returned 404 "package not found". The handler now falls back to the .zip key, then .mod and .info.
2026-11-23 15:49:33 +00:00
lukaszraczylo aa8487ad87 build: pull pinned base images from mirror.gcr.io
Docker Hub rate-limited the v0.1.328 release build, so goreleaser kept retrying the base image pulls. The Dockerfiles now pull alpine 3.24.4 and nginx 1.31.9-alpine from mirror.gcr.io, pinned by digest. Those digests are what alpine:latest and nginx:alpine resolved to, so the images are unchanged, and a release no longer moves silently with a floating tag.
2026-11-23 15:28:01 +00:00
lukaszraczylo 2ada975065 fix(ui): name trend series by the packages they count
The severity series now read "Packages with <severity> vulnerabilities",
which matches the severity tiles and the snapshot counts.
2026-11-23 15:12:15 +00:00
lukaszraczylo b98e761c90 fix(stats): count a package under every severity it holds
The trend snapshot counted each vulnerable package once, under its
highest severity. The Vulnerable packages tiles and the severity
filter count a package under every severity its latest scan holds.
The two views disagreed, for example low 0 against 8 packages.

The snapshot and the backfill now use the filter definition, so a
package with high and low findings counts under both. A test compares
the snapshot with the filter result on one fixture.
2026-11-23 15:12:12 +00:00
lukaszraczylo a457e3d2e8 test(metadata): stop the aggregation worker before counting statements 2026-11-23 14:58:44 +00:00
lukaszraczylo ba8bc392ec feat(cache): purge soft-deleted package rows after a retention period
The cleanup worker now hard-deletes package rows whose deleted_at is
older than cache.deleted_retention. The default is 30 days. A value of
0 keeps the rows. The purge runs in bounded batches, with at most 100
batches per cleanup pass, and removes child rows with the package.

History tables have no foreign key to packages, and stats_snapshots
holds its own counts, so the purge leaves both untouched. The cleanup
log line now reports purged_deleted and deleted_retention.
2026-11-23 14:55:26 +00:00
lukaszraczylo 1512230ab3 feat(stats): record daily snapshots and serve a trend API
The aggregation worker now writes one row per UTC day to
stats_snapshots. The row holds package count, total size, vulnerable
package count, the four severity counts and the blocked count. The
write is an idempotent upsert per day.

A migration backfills package counts from cached_at and deleted_at as
the number of packages alive at the end of each day. Vulnerability
fields backfill from scan_results timestamps and stay empty before the
first scan. GET /api/stats/trend returns daily points for 30day, 90day
or 1year with a constant number of queries.

The Stats page shows a chart of cached and vulnerable packages with a
period selector and severity toggles. The Dashboard shows a compact
version. The Lean model gains theorems for the backfill and upsert.
2026-11-23 14:55:19 +00:00
lukaszraczylo bd9d686383 feat(vulnerable): filter vulnerable packages by severity
The four severity tiles on the vulnerable packages page are now toggle
buttons with aria-pressed. Each tile shows "Filter on" while active.
A tile selects packages with at least one vulnerability of that
severity. Several tiles combine with OR. A second click clears the
tile, and a Clear filters control clears all of them.

The selection lives in the URL (?severity=critical,high), so it
survives a reload and works as a link. An empty result shows the
library empty state with a clear action.

GET /api/packages accepts a severity list. The page uses it to load
only vulnerable packages instead of the whole cache. The filter is a
subquery on the latest scan result, so the statement count does not
grow with the number of rows. An unknown severity returns 400.
2026-11-23 14:54:44 +00:00
lukaszraczylo 4d31e535ff test(app): pace broadcast bursts to remove a race flake 2026-11-23 14:31:49 +00:00
lukaszraczylo fe2d9f8b3a fix(metadata): wait for the aggregation worker before closing the store 2026-11-23 14:26:35 +00:00
lukaszraczylo a84f080b79 fix(scanner): rescan packages on remote storage via ScanFile 2026-11-23 14:26:35 +00:00
lukaszraczylo 9b4659218c feat(cache): wire cache.ttl_overrides to metadata freshness 2026-11-23 14:26:29 +00:00
lukaszraczylo 1256756057 fix(api): drop dead per-handler CORS headers 2026-11-23 14:26:17 +00:00
lukaszraczylo 262771d224 fix(api): return 404 when deleting a package that does not exist 2026-11-23 14:26:09 +00:00
lukaszraczylo 536f35ab55 fix(server): stop 431 on /api for browsers with large session cookies 2026-11-23 14:14:28 +00:00
lukaszraczylo 5a9d104b37 chore(lean): model redirects, key lookup, upserts, retries, CORS, TTL 2026-11-23 13:39:03 +00:00
lukaszraczylo f2049383cb fix(api): restrict CORS to allowed origins, refuse cross-origin writes 2026-11-23 13:38:38 +00:00
lukaszraczylo 549d56e0a1 fix(cache): default metadata freshness to 24h, under the age gate 2026-11-23 13:38:37 +00:00
lukaszraczylo 31db940014 fix(scanner): re-read the blob when a scan retry finds its file gone 2026-11-23 13:38:37 +00:00
lukaszraczylo f46e079cee fix(stats): upsert hourly and daily stats on SQLite as PostgreSQL does 2026-11-23 13:38:37 +00:00
lukaszraczylo ae5167ffa9 fix(auth): look up API keys by id, one bcrypt compare per request 2026-11-23 13:38:37 +00:00
lukaszraczylo 787c757827 fix(network): vet every redirect hop against the upstream allowlist 2026-11-23 13:38:36 +00:00
lukaszraczylo ac4f39322c feat(ui): page, search and filter packages on the server
The package list loaded every package, then grouped and paged in the
browser. The dashboard did the same to show ten recent rows.

- PackageList asks the server for one page of 25 groups. The registry
  filter and a debounced search box (300 ms) change the request. A newer
  request replaces the answer of an older one.
- Dashboard loads a page of 10 groups sorted by cached_at, newest first,
  and runs its stats, recent list and chart requests in parallel.
- Stats already used /api/stats only and does not change.
- The store keeps the loading flag on until the last overlapping request
  settles. Deleting a package no longer reloads the full list, and the
  list reloads its own page instead.
- VulnerablePackages keeps the unpaginated call because it filters on
  scan results in the browser.
2026-11-23 13:26:50 +00:00
lukaszraczylo db5ca2539f perf(api): serve package lists and stats in constant queries
The dashboard waited seconds for /api/packages and /api/stats. Both
handlers ran queries per package, so the cost grew with the cache.

Baseline, measured live through a port-forward (median of 5):
- /api/packages: 3033 ms, 594 items, limit ignored
- /api/packages?limit=50&offset=0: 2813 ms
- /api/stats: 3813 ms
- /api/stats/timeseries?period=1day: 12 ms

Baseline queries per request, counted on SQLite with 20 and 120 rows:
- /api/packages: 141 and 841 queries (7 per package)
- /api/stats: 103 and 603 queries (5 per package)

Both handlers now run a constant number of queries: 4 for the full list,
6 for a page, 6 for stats. The query-count tests fail on the old code.

- /api/packages pages (registry, name) groups with page, page_size,
  registry, q, sort and order, and returns total_groups. Without page
  and page_size it returns every package, so old clients keep working.
- A batched scan lookup replaces the per-package GetScanResult and
  CheckVulnerabilities calls. ScanDecisions returns the same verdicts as
  CheckVulnerabilities, proven by a policy and bypass matrix test.
- The silent 1000-row cap is gone from the list and the Go delete.
- /api/stats sums per registry with GROUP BY and judges blocked
  packages in one batch.
- Migration 202611240001 adds scan_results (package_id, scanned_at) on
  SQLite, PostgreSQL and MySQL. The existing (registry_id, name, version)
  index already serves the group lookups.
2026-11-23 13:26:50 +00:00
228 changed files with 19550 additions and 3247 deletions
+6 -1
View File
@@ -2,7 +2,7 @@
# Combines frontend serving and backend proxy (previously separate gateway)
# EXPECTS: Pre-built frontend files in frontend/dist/ directory
FROM nginx:alpine
FROM mirror.gcr.io/library/nginx:1.31.9-alpine@sha256:fb4658584bd9a916ffb6f6e365f97c25cfdb2923801f551ea08356e695f14ff7
# Install envsubst for runtime configuration
RUN apk add --no-cache gettext
@@ -85,6 +85,8 @@ server {
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;
@@ -122,6 +124,7 @@ server {
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;
@@ -144,6 +147,8 @@ server {
# 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;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM alpine:latest
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETARCH
+5 -5
View File
@@ -2,7 +2,7 @@
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM alpine:latest
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETARCH
@@ -23,17 +23,17 @@ RUN apk add --no-cache \
&& update-ca-certificates
# Install Trivy for container scanning
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/v0.76.2/contrib/install.sh | sh -s -- -b /usr/local/bin v0.76.2
# Install Grype for vulnerability scanning
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/v0.121.2/install.sh | sh -s -- -b /usr/local/bin v0.121.2
# Install govulncheck for Go vulnerability scanning
RUN go install golang.org/x/vuln/cmd/govulncheck@latest && \
RUN go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 && \
mv /root/go/bin/govulncheck /usr/local/bin/
# Install pip-audit for Python package vulnerability scanning
RUN pip3 install --no-cache-dir pip-audit --break-system-packages
RUN pip3 install --no-cache-dir pip-audit==2.10.1 --break-system-packages
# Create non-root user
RUN addgroup -g 1000 scanner && \
+1 -1
View File
@@ -2,7 +2,7 @@
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
# GoReleaser injects the platform-specific binary automatically
FROM --platform=$TARGETPLATFORM alpine:latest
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
ARG TARGETARCH
+32 -4
View File
@@ -193,6 +193,7 @@ server:
host: "0.0.0.0"
read_timeout: "5m"
write_timeout: "5m"
allowed_origins: [] # Browser origins allowed to use /api and /ws; empty = same-origin only
storage:
backend: "filesystem" # Options: filesystem, s3, smb
@@ -235,6 +236,9 @@ security:
cache:
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
pypi: 12h
cleanup_interval: 1h
logging:
@@ -252,7 +256,9 @@ upstream:
Every `cleanup_interval` the cleanup run removes:
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl`. They refresh on the next request.
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
- **Deleted rows.** Evicting or deleting a package marks its database row deleted. Rows deleted longer ago than `deleted_retention` (default `720h`, 30 days) are removed for good, in batches of 500. Download history and the daily trend snapshots are kept. Set `deleted_retention: 0` to keep every row.
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
@@ -887,10 +893,29 @@ Access the web dashboard at **http://localhost:8080**
**List Packages:**
```bash
GET /api/packages
GET /api/packages?registry=npm
GET /api/packages?status=vulnerable
GET /api/packages?page=1&page_size=25
GET /api/packages?registry=npm&q=axios&page_size=25
GET /api/packages?sort=cached_at&order=desc&page_size=10
```
The dashboard groups versions under a package, so paging counts packages (a
registry and name pair), not rows. Without `page` and `page_size` the call
returns every package in one response, with no row cap.
| Parameter | Meaning |
|---|---|
| `page` | 1-based page of groups. Default 1. |
| `page_size` | Groups per page. Default 25 when `page` is set, at most 200. |
| `registry` | Only this registry, for example `npm`, `pypi` or `go`. |
| `q` | Case-insensitive search in name, version and release version. |
| `sort` | `name` (default, ascending), `cached_at`, `downloads` or `size` (both descending). |
| `order` | `asc` or `desc`, to override the default direction of `sort`. |
`packages` holds every version row of each group on the page, in group order
and newest first within a group. `total` is the number of rows returned.
`total_groups` is the number of groups that match the filters across all pages.
A paged response also echoes `page` and `page_size`.
**Package Details:**
```bash
GET /api/packages/:registry/:name/:version
@@ -920,7 +945,10 @@ GET /api/packages/:registry/:name/:version
}
}
],
"total": 42
"total": 1,
"total_groups": 42,
"page": 1,
"page_size": 25
}
```
+16 -5
View File
@@ -10,8 +10,13 @@ server:
host: "0.0.0.0"
port: 8080 # Backend API server port
read_timeout: "5m"
read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431
write_timeout: "5m"
idle_timeout: "2m"
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
# ("https://gohoarder.example.com") or wildcard ("https://*.example.com").
# Empty: same-origin only. A cross-origin DELETE/POST/PATCH is refused with 403.
allowed_origins: []
tls:
enabled: false
cert_file: ""
@@ -89,24 +94,30 @@ metadata:
log_level: "warn" # GORM log level: silent, error, warn, info
cache:
default_ttl: "168h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
cleanup_interval: "1h"
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
deleted_retention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
max_size_bytes: 536870912000 # 500GB
per_project_quota: 53687091200 # 50GB
ttl_overrides:
npm: "168h"
pip: "168h"
go: "168h"
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
npm: "24h"
pypi: "24h"
go: "24h"
security:
enabled: false
block_on_severity: "high" # none, low, medium, high, critical
scan_on_download: true # Scan packages on first download
rescan_interval: "24h" # How often to re-scan packages (e.g., 24h, 168h for weekly)
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")
@@ -32,6 +32,10 @@ data:
severity_threshold: medium
block_on_vulnerability: false
rescan_interval: 24h
rescan_active_window: 0s
rescan_concurrency: 1
rescan_on_access: false
scan_wait_timeout: 30s
handlers:
npm:
+1 -1
View File
@@ -27,7 +27,7 @@ onMounted(() => {
<template #brand>
<Icon :icon="faBoxOpen" size="lg" class="text-primary" />
<p class="m-0 text-lg font-semibold">GoHoarder</p>
<p class="m-0 hidden text-sm text-muted-foreground sm:block">Package cache manager</p>
<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>
@@ -1,8 +1,8 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader
title="CVE bypass management"
description="Manage temporary security bypasses for packages and CVEs."
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>
@@ -33,7 +33,7 @@
v-if="filteredBypasses.length === 0"
:icon="faShieldHalved"
title="No bypasses found"
description="Create a bypass to allow packages with known vulnerabilities."
description="Create a bypass to serve a package that the policy holds."
/>
<DataTable
v-else
@@ -44,7 +44,7 @@
:rows="filteredBypasses"
>
<template #cell-type="{ row }">
<Badge :variant="row.type === 'cve' ? 'default' : 'outline'">{{ row.type === 'cve' ? 'CVE' : 'Package' }}</Badge>
<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">
@@ -55,6 +55,13 @@
<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)" />
@@ -84,7 +91,7 @@
:label="bypassForm.type === 'cve' ? 'CVE ID' : 'Package'"
:hint="
bypassForm.type === 'cve'
? 'Enter the CVE ID, for example CVE-2021-23337.'
? '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
@@ -170,6 +177,7 @@
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'
import { useRoute } from 'vue-router'
import {
Badge,
Button,
@@ -191,28 +199,18 @@ import {
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'
interface Bypass {
id: string
type: 'cve' | 'package'
target: string
reason: string
created_by: string
created_at: string
expires_at: string
applies_to?: string
notify_on_expiry: boolean
active: boolean
}
const loading = ref(false)
const error = ref<string | null>(null)
const toasts = useToastStore()
@@ -220,6 +218,7 @@ 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)
@@ -238,8 +237,8 @@ const EMPTY_FORM = {
const bypassForm = ref({ ...EMPTY_FORM })
// Get API key from localStorage or prompt user
const apiKey = ref<string>('')
const adminKey = useAdminKey()
const apiKey = adminKey.key
const keyInput = ref('')
const showKeyDialog = ref(false)
@@ -274,8 +273,8 @@ const isFormValid = computed(() => {
})
onMounted(() => {
// Try to get API key from localStorage
apiKey.value = localStorage.getItem('admin_api_key') || ''
adminKey.load()
prefillFromQuery()
if (!apiKey.value) {
promptForApiKey()
} else {
@@ -283,6 +282,14 @@ onMounted(() => {
}
})
// A package page links here with the package to cover.
function prefillFromQuery() {
const { type, target } = route.query
if (typeof target !== 'string' || target === '') return
bypassForm.value = { ...EMPTY_FORM, type: type === 'cve' ? 'cve' : 'package', target }
showCreateModal.value = true
}
function promptForApiKey() {
keyInput.value = ''
showKeyDialog.value = true
@@ -291,8 +298,7 @@ function promptForApiKey() {
function submitApiKey() {
const key = keyInput.value.trim()
if (!key) return
apiKey.value = key
localStorage.setItem('admin_api_key', key)
adminKey.save(key)
showKeyDialog.value = false
fetchBypasses()
}
@@ -330,8 +336,7 @@ async function fetchBypasses() {
console.error('Failed to fetch bypasses:', err)
if (err.response?.status === 401) {
error.value = 'Invalid API key. Please check your credentials.'
localStorage.removeItem('admin_api_key')
apiKey.value = ''
adminKey.clear()
} else {
error.value = err.response?.data?.error?.message || err.message || 'Failed to load bypasses'
}
@@ -449,10 +454,6 @@ async function deleteBypass() {
}
}
function isExpired(expiresAt: string): boolean {
return new Date(expiresAt) < new Date()
}
const FILTER_OPTIONS = [
{ value: 'all', label: 'All' },
{ value: 'active', label: 'Active' },
@@ -471,13 +472,13 @@ const BYPASS_TYPE_OPTIONS = [
]
const bypassColumns: DataTableColumn<Bypass>[] = [
{ key: 'target', header: 'Target', rowHeader: true },
{ 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', accessor: (b) => formatDate(b.created_at) },
{ key: 'expires_at', header: 'Expires', accessor: (b) => formatDate(b.expires_at) },
{ 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: () => '' },
]
-264
View File
@@ -1,264 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import Dashboard from './Dashboard.vue'
import { usePackageStore } from '../stores/packages'
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
describe('Dashboard.vue', () => {
beforeEach(() => {
setActivePinia(createPinia())
__resetRealtimeSingleton()
// Mock the fetch functions to prevent actual API calls
const store = usePackageStore()
vi.spyOn(store, 'fetchStats').mockResolvedValue()
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
})
it('renders dashboard component', () => {
const wrapper = mount(Dashboard)
expect(wrapper.find('h1').text()).toBe('Dashboard')
})
it('displays error message when error occurs', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.error = 'Failed to load dashboard'
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Failed to load dashboard')
})
it('displays loading state when loading', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = true
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Loading statistics...')
})
it('displays overview stats cards', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 2,
total_size: 3072,
max_cache_size: 10737418240,
total_downloads: 30,
scanned_packages: 2,
vulnerable_packages: 0,
blocked_packages: 0,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Total packages')
expect(wrapper.text()).toContain('Total size')
expect(wrapper.text()).toContain('Total downloads')
})
it('displays total packages from stats', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 100,
total_size: 0,
max_cache_size: 10737418240,
total_downloads: 0,
scanned_packages: 0,
vulnerable_packages: 0,
blocked_packages: 0,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('100')
})
it('displays total downloads from stats', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 0,
total_size: 0,
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 0,
vulnerable_packages: 0,
blocked_packages: 0,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('500')
})
it('displays total size from stats', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 0,
total_size: 1048576, // 1 MB
max_cache_size: 10737418240,
total_downloads: 0,
scanned_packages: 0,
vulnerable_packages: 0,
blocked_packages: 0,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('1 MB')
})
it('displays recent packages section', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'test-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Recent packages')
})
it('shows recent packages sorted by cached_at', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'old-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
{
id: '2',
registry: 'npm',
name: 'new-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-02T00:00:00Z',
last_accessed: '2025-01-02T00:00:00Z',
download_count: 5,
},
]
await wrapper.vm.$nextTick()
const recentPackagesSection = wrapper.text().split('Recent packages')[1]
// new-package should appear before old-package since it's more recent
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
recentPackagesSection.indexOf('old-package')
)
})
it('limits recent packages to 10 items', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = Array.from({ length: 15 }, (_, i) => ({
id: `${i}`,
registry: 'npm',
name: `package${i}`,
version: '1.0.0',
size: 1024,
cached_at: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
last_accessed: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
download_count: i,
}))
await wrapper.vm.$nextTick()
const recentSection = wrapper.text().split('Recent packages')[1]
// Count how many "package" strings appear (each package has the word "package" in its name)
const packageCount = (recentSection.match(/package\d+/g) || []).length
expect(packageCount).toBeLessThanOrEqual(10)
})
it('handles empty packages array', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = []
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('0')
expect(wrapper.text()).toContain('0 B')
})
it('renders realtime lastStats over polled stats when present', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
const rt = useRealtimeStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 10,
total_size: 1024,
max_cache_size: 10737418240,
total_downloads: 5,
scanned_packages: 0,
vulnerable_packages: 0,
blocked_packages: 0,
}
rt.lastStats = {
total_packages: 999,
total_size: 2048,
total_downloads: 777,
scanned_packages: 0,
}
await wrapper.vm.$nextTick()
// Realtime values should be visible (override polled values).
expect(wrapper.text()).toContain('999')
expect(wrapper.text()).toContain('777')
})
it('shows a neutral "Live updates paused" badge while the socket is down', async () => {
const wrapper = mount(Dashboard)
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
expect(badge.text()).toBe('Live updates paused')
expect(badge.text()).not.toMatch(/offline/i)
expect(badge.attributes('data-tone')).toBe('neutral')
})
it('shows a "Live" badge once the socket is connected', async () => {
const wrapper = mount(Dashboard)
useRealtimeStore().connected = true
await wrapper.vm.$nextTick()
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
expect(badge.text()).toBe('Live')
expect(badge.attributes('data-tone')).toBe('success')
})
})
-317
View File
@@ -1,317 +0,0 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader title="Dashboard" description="What the cache holds and what is moving through it.">
<template #actions>
<StatusBadge
:status="rt.connected ? 'live' : 'paused'"
:label="rt.connected ? 'Live' : 'Live updates paused'"
:tones="{ live: 'success', paused: 'neutral' }"
:pulse="rt.connected"
data-testid="ws-live-indicator"
/>
</template>
</PageHeader>
<LoadingState v-if="loading" variant="kpi-grid" :columns="4" label="Loading statistics..." />
<ErrorState
v-else-if="error"
variant="card"
title="Could not load statistics"
:message="error"
@retry="refresh"
/>
<template v-else>
<StatGroup :columns="4" aria-label="Cache totals">
<KpiTile label="Total packages" :value="displayStats?.total_packages || 0" :icon="faBoxesStacked" />
<KpiTile label="Total size" :value="formatBytes(displayStats?.total_size || 0)" :icon="faHardDrive" />
<KpiTile label="Total downloads" :value="displayStats?.total_downloads || 0" :icon="faDownload" />
<KpiTile label="Scanned packages" :value="displayStats?.scanned_packages || 0" :icon="faShieldHalved" />
</StatGroup>
<Card v-if="recentRealtimeEvents.length > 0" data-testid="ws-event-feed">
<CardHeader>
<CardTitle as="h2">Live activity</CardTitle>
</CardHeader>
<CardContent>
<ActivityFeed :events="feedEvents" variant="compact" label="Live activity" />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Download activity</CardTitle>
<CardAction>
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
</CardAction>
</CardHeader>
<CardContent>
<LoadingState
v-if="chartLoading && chartData.length === 0"
layout="inline"
label="Loading chart data..."
/>
<ErrorState
v-else-if="chartError"
variant="inline"
title="Could not load download activity"
:message="chartError"
@retry="fetchTimeSeriesData"
/>
<BarChart
v-else
:labels="chartLabels"
:series="[{ name: 'Downloads', data: chartData }]"
label="Downloads over the selected period"
empty-text="No download activity in this period"
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Recent packages</CardTitle>
</CardHeader>
<CardContent>
<EmptyState
v-if="packages.length === 0"
size="sm"
:icon="faBoxOpen"
title="No packages cached yet"
description="Packages appear here once they are downloaded through the proxy."
/>
<DataTable
v-else
label="Recent packages"
layout="cards"
:columns="packageColumns"
:rows="recentPackages"
>
<template #cell-registry="{ row }">
<Badge variant="outline">{{ row.registry }}</Badge>
</template>
</DataTable>
</CardContent>
</Card>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import axios from 'axios'
import {
ActivityFeed,
BarChart,
Badge,
Card,
CardAction,
CardContent,
CardHeader,
CardTitle,
DataTable,
EmptyState,
ErrorState,
KpiTile,
LoadingState,
PageHeader,
SegmentedControl,
StatGroup,
StatusBadge,
type ActivityEvent,
type DataTableColumn,
} from '@perfect-design/ui'
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
import { usePackageStore, type Package } from '../stores/packages'
import { useRealtimeStore } from '../stores/realtime'
import type { EventType, RealtimeEvent } from '@/lib/ws'
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
import {
faBox,
faBoxOpen,
faBoxesStacked,
faChartLine,
faDownload,
faHardDrive,
faShieldHalved,
faTrash,
} from '@/lib/icons'
const store = usePackageStore()
const { packages, stats, loading, error } = storeToRefs(store)
const rt = useRealtimeStore()
const { lastStats, events: rtEvents } = storeToRefs(rt)
// Realtime stats override polled stats when available; otherwise fall back.
const displayStats = computed(() => lastStats.value ?? stats.value)
const recentRealtimeEvents = computed<RealtimeEvent[]>(() => {
const list = rtEvents.value
return list.slice(Math.max(list.length - 5, 0)).reverse()
})
const EVENT_LABELS: Record<EventType, string> = {
package_cached: 'Cached',
package_deleted: 'Deleted',
package_downloaded: 'Downloaded',
scan_complete: 'Scan complete',
stats_update: 'Stats update',
}
const EVENT_ICONS: Record<EventType, IconDefinition> = {
package_cached: faBox,
package_deleted: faTrash,
package_downloaded: faDownload,
scan_complete: faShieldHalved,
stats_update: faChartLine,
}
function iconForEvent(type: EventType): IconDefinition {
return EVENT_ICONS[type] ?? faChartLine
}
const feedEvents = computed<ActivityEvent[]>(() =>
recentRealtimeEvents.value.map((evt, idx) => ({
id: `${evt.timestamp}-${idx}`,
action: labelForEvent(evt.type),
target: describeEvent(evt) || undefined,
time: evt.timestamp,
icon: iconForEvent(evt.type),
})),
)
function labelForEvent(type: EventType): string {
return EVENT_LABELS[type] ?? type
}
function describeEvent(evt: RealtimeEvent): string {
const p = evt.payload
const name = typeof p.name === 'string' ? p.name : ''
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
const version = typeof shown === 'string' ? `@${shown}` : ''
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
if (evt.type === 'stats_update') return ''
if (name) return `${registry}${name}${version}`
return ''
}
// Chart periods and data
const selectedPeriod = ref<string>('1day')
const chartPeriods = [
{ value: '1h', label: '1 hour' },
{ value: '1day', label: '24 hours' },
{ value: '7day', label: '7 days' },
{ value: '30day', label: '30 days' },
]
// Time-series data from API
interface TimeSeriesDataPoint {
timestamp: string
value: number
}
interface TimeSeriesStats {
period: string
registry: string
data_points: TimeSeriesDataPoint[]
}
const timeSeriesData = ref<TimeSeriesStats | null>(null)
const chartLoading = ref(false)
const chartError = ref<string | null>(null)
// Fetch time-series data from API
async function fetchTimeSeriesData() {
chartLoading.value = true
chartError.value = null
try {
const response = await axios.get(`/api/stats/timeseries?period=${selectedPeriod.value}`)
timeSeriesData.value = response.data
} catch (err) {
console.error('Failed to fetch time-series data:', err)
timeSeriesData.value = null
chartError.value = err instanceof Error ? err.message : 'Failed to load download activity'
} finally {
chartLoading.value = false
}
}
// Extract chart values from time-series data
const chartData = computed(() => {
if (!timeSeriesData.value || !timeSeriesData.value.data_points) {
return []
}
return timeSeriesData.value.data_points.map(point => point.value)
})
const chartLabels = computed(() => chartData.value.map((_, index) => getChartLabel(index)))
const packageColumns: DataTableColumn<Package>[] = [
{ key: 'name', header: 'Package', rowHeader: true },
{ key: 'version', header: 'Version', accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
{ key: 'registry', header: 'Registry' },
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
]
function refresh() {
void store.fetchStats()
void store.fetchPackages()
}
function getChartLabel(index: number): string {
// Use timestamp from data if available
if (timeSeriesData.value && timeSeriesData.value.data_points[index]) {
const date = new Date(timeSeriesData.value.data_points[index].timestamp)
switch (selectedPeriod.value) {
case '1h':
return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
case '1day':
return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
case '7day':
return date.toLocaleDateString('en-US', { weekday: 'short' })
case '30day':
return date.toLocaleDateString('en-US', { day: 'numeric' })
default:
return `${index}`
}
}
// Fallback to index-based labels
const labels: Record<string, (i: number) => string> = {
'1h': (i) => `${i * 5}m`,
'1day': (i) => `${i}:00`,
'7day': (i) => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][i] || `Day ${i + 1}`,
'30day': (i) => `${i + 1}`,
}
return labels[selectedPeriod.value]?.(index) || `${index}`
}
// API returns clean, deduplicated data - just sort and limit
const recentPackages = computed(() => {
return packages.value
.slice()
.sort((a, b) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
.slice(0, 10)
})
// Watch for period changes and fetch new data
watch(selectedPeriod, () => {
fetchTimeSeriesData()
})
onMounted(async () => {
// Connect to realtime stream first so we can pick up live events while
// initial polling resolves. Singleton survives navigation, so we
// intentionally do not disconnect on unmount.
rt.connect()
await store.fetchStats()
await store.fetchPackages()
await fetchTimeSeriesData()
})
</script>
+77
View File
@@ -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)
})
})
+211
View File
@@ -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>
+1 -1
View File
@@ -10,7 +10,7 @@
>
<template #action>
<Button as-child>
<RouterLink to="/">Back to the dashboard</RouterLink>
<RouterLink to="/">Back to the overview</RouterLink>
</Button>
</template>
</EmptyState>
+101
View File
@@ -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...')
})
})
+210
View File
@@ -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>
+140 -229
View File
@@ -1,167 +1,112 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader :title="packageName">
<template #back>
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to packages</Button>
</template>
<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 vulnerability details..." />
<LoadingState v-if="loading" variant="card" label="Loading package details..." />
<ErrorState
v-else-if="error"
variant="card"
title="Could not load vulnerability details"
title="Could not load this package"
:message="error"
@retry="fetchVulnerabilities"
@retry="load"
/>
<template v-else-if="vulnerabilities">
<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">Security scan summary</CardTitle>
<CardTitle as="h2">Details</CardTitle>
</CardHeader>
<CardContent class="flex flex-col gap-4">
<SeveritySummary :counts="severityCounts" label="Vulnerabilities by severity" />
<DescriptionList variant="inline" divided>
<DescriptionItem term="Scanned">{{ formatDate(vulnerabilities.scanned_at) }}</DescriptionItem>
<DescriptionItem term="Scanners">
<span class="flex flex-wrap gap-1">
<Badge v-for="scanner in scannerList" :key="scanner" variant="secondary">{{ scanner }}</Badge>
</span>
</DescriptionItem>
<DescriptionItem v-if="bypassedCount > 0" term="Bypassed">
<StatusBadge status="bypassed" :label="`${bypassedCount} bypassed`" :tones="{ bypassed: 'success' }" />
</DescriptionItem>
</DescriptionList>
<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>
<Card v-if="vulnerabilityList.length === 0">
<CardContent>
<EmptyState
tone="success"
:icon="faCircleCheck"
title="No vulnerabilities found"
description="The scanners reported nothing for this package version."
<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"
/>
</CardContent>
</Card>
<Card v-else>
<CardHeader>
<CardTitle as="h2">Detected vulnerabilities ({{ vulnerabilityList.length }})</CardTitle>
</CardHeader>
<CardContent>
<Table label="Detected vulnerabilities" layout="cards">
<TableHeader>
<TableRow>
<TableHead>Severity</TableHead>
<TableHead>CVE ID</TableHead>
<TableHead>Description</TableHead>
<TableHead>Fix version</TableHead>
<TableHead align="center">Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<template v-for="(vuln, index) in vulnerabilityList" :key="vuln.id">
<TableRow class="cursor-pointer" :selected="expandedRows.has(index)" @click="toggleRow(index)">
<TableCell label="Severity">
<span class="flex flex-wrap items-center gap-2">
<StatusBadge
:status="vuln.severity"
:tones="SEVERITY_TONES"
:label="formatSeverityName(vuln.severity)"
/>
<StatusBadge
v-if="vuln.bypassed"
status="bypassed"
label="Bypassed"
:tones="{ bypassed: 'success' }"
/>
</span>
</TableCell>
<TableCell label="CVE ID" class="font-mono font-medium">{{ vuln.id }}</TableCell>
<TableCell label="Description">
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
</TableCell>
<TableCell label="Fix version">
<span v-if="vuln.fixed_in">v{{ vuln.fixed_in }}</span>
<span v-else class="text-muted-foreground">-</span>
</TableCell>
<TableCell label="Details" align="center">
<IconButton
size="icon-sm"
:icon="expandedRows.has(index) ? faChevronUp : faChevronDown"
:label="`${expandedRows.has(index) ? 'Hide' : 'Show'} details for ${vuln.id}`"
:aria-expanded="expandedRows.has(index)"
@click.stop="toggleRow(index)"
/>
</TableCell>
</TableRow>
<TableRow v-if="expandedRows.has(index)" :hoverable="false">
<TableCell :colspan="5">
<div class="flex flex-col gap-4 py-2">
<section>
<h3 class="mb-2 text-sm font-semibold">Description</h3>
<Markdown :source="vuln.description" :heading-offset="3" />
</section>
<Alert v-if="vuln.bypassed && vuln.bypass" variant="success">
<AlertTitle>Bypass active</AlertTitle>
<AlertDescription>
<DescriptionList variant="grid" :columns="3" size="sm">
<DescriptionItem term="Reason">{{ vuln.bypass.reason }}</DescriptionItem>
<DescriptionItem term="By">{{ vuln.bypass.created_by }}</DescriptionItem>
<DescriptionItem term="Expires">{{ formatDate(vuln.bypass.expires_at) }}</DescriptionItem>
</DescriptionList>
</AlertDescription>
</Alert>
<Alert v-if="vuln.fixed_in" variant="info">
<AlertTitle>Fix available</AlertTitle>
<AlertDescription>
Upgrade to version <strong>{{ vuln.fixed_in }}</strong> or later.
</AlertDescription>
</Alert>
<section v-if="vuln.references && vuln.references.length > 0">
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
<li v-for="(ref, refIndex) in vuln.references" :key="refIndex" class="break-all">
<Link :href="ref" external>{{ ref }}</Link>
</li>
</ul>
</section>
</div>
</TableCell>
</TableRow>
</template>
</TableBody>
</Table>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { computed, onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import {
Alert,
AlertDescription,
AlertTitle,
Badge,
Button,
Callout,
Card,
CardContent,
CardHeader,
@@ -170,129 +115,95 @@ import {
DescriptionList,
EmptyState,
ErrorState,
IconButton,
Link,
LoadingState,
Markdown,
PageHeader,
StatusBadge,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
RelativeTime,
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from '@perfect-design/ui'
import SeveritySummary from './SeveritySummary.vue'
import { formatDate, withVersionPrefix } from '@/lib/format'
import { faArrowLeft, faChevronDown, faChevronUp, faCircleCheck } from '@/lib/icons'
import { NO_VULNERABILITIES, SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
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 router = useRouter()
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(() => {
// Handle package names with slashes (e.g., Go packages like github.com/user/repo)
const nameParam = route.params.name
if (Array.isArray(nameParam)) {
return nameParam.join('/')
}
return nameParam as string
const name = route.params.name
return Array.isArray(name) ? name.join('/') : (name as string)
})
const version = computed(() => route.params.version as string)
const shownVersion = computed(() => vulnerabilities.value?.package?.release_version || version.value)
interface BypassInfo {
id: string
reason: string
created_by: string
expires_at: string
}
interface Vulnerability {
id: string
severity: string
title: string
description: string
references: string[]
fixed_in: string
bypassed: boolean
bypass?: BypassInfo
}
interface VulnerabilityResponse {
package?: { release_version?: string }
scanned: boolean
scanner: string
scanned_at: string
status: string
vulnerabilities: Vulnerability[]
vulnerability_count: number
severity_counts: {
critical: number
high: number
moderate: number
low: number
}
bypassed_count: number
}
const shownVersion = computed(() => report.value?.package?.release_version || version.value)
const loading = ref(false)
const error = ref<string | null>(null)
const vulnerabilities = ref<VulnerabilityResponse | null>(null)
const expandedRows = ref<Set<number>>(new Set())
const report = ref<PackageReport | null>(null)
const row = ref<Package | null>(null)
const vulnerabilityList = computed(() => {
const vulns = vulnerabilities.value?.vulnerabilities || []
// Sort by severity (most severe first)
return [...vulns].sort((a, b) => {
return severityRank(b.severity) - severityRank(a.severity)
})
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 severityCounts = computed(() => vulnerabilities.value?.severity_counts || NO_VULNERABILITIES)
const bypassedCount = computed(() => vulnerabilities.value?.bypassed_count || 0)
const upstream = computed(() => system.info.value?.upstreams[registry.value] || 'Not reported')
// Parse scanner string into array of scanner names
const scannerList = computed(() => {
if (!vulnerabilities.value?.scanner) return []
return vulnerabilities.value.scanner.split('+').map((s: string) => s.trim())
// 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`
})
onMounted(() => {
fetchVulnerabilities()
})
async function fetchVulnerabilities() {
async function load() {
loading.value = true
error.value = null
vulnerabilities.value = null
report.value = null
try {
const response = await axios.get(
`/api/packages/${registry.value}/${packageName.value}/${version.value}/vulnerabilities`
)
// Store the response data
vulnerabilities.value = response.data
} catch (err: any) {
console.error('Failed to fetch vulnerabilities:', err)
error.value = err.response?.data?.error || err.message || 'Failed to load vulnerability details'
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
}
}
function goBack() {
router.push('/packages')
}
function toggleRow(index: number) {
if (expandedRows.value.has(index)) {
expandedRows.value.delete(index)
} else {
expandedRows.value.add(index)
}
}
onMounted(load)
</script>
+104 -205
View File
@@ -1,245 +1,144 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
import { defineComponent, h } from 'vue'
import axios from 'axios'
import { flushPromises, mount } from '@vue/test-utils'
import PackageList from './PackageList.vue'
import { usePackageStore } from '../stores/packages'
import type { Package } from '../stores/packages'
import { PACKAGES } from '@/test/fixtures'
import { serveRows } from '@/test/rowsServer'
import { createTestRouter } from '@/test/router'
const Stub = defineComponent({ render: () => h('div') })
vi.mock('axios')
function createTestRouter(): Router {
return createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', name: 'dashboard', component: Stub },
{ path: '/packages/:registry?', name: 'packages', component: Stub, props: true },
{
path: '/package/:registry/:name+/:version',
name: 'package-details',
component: Stub,
props: true,
},
],
})
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 mountWithRouter() {
const router = createTestRouter()
router.push('/packages')
await router.isReady()
return mount(PackageList, {
global: {
plugins: [router],
},
})
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(() => {
// Create a fresh pinia instance before each test
setActivePinia(createPinia())
// Prevent real network calls from store actions on mount
const store = usePackageStore()
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
vi.useFakeTimers({ shouldAdvanceTime: true })
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
it('renders package list component', async () => {
const wrapper = await mountWithRouter()
it('renders the page heading', async () => {
const { wrapper } = await open()
expect(wrapper.find('h1').text()).toBe('Packages')
})
it('displays loading state when loading', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = true
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Loading packages...')
it('asks the server for the first page of rows, not for every package', async () => {
await open()
const calls = vi.mocked(axios.get).mock.calls.filter((c) => String(c[0]).startsWith('/api/packages'))
expect(calls).toHaveLength(1)
expect(Object.fromEntries(lastUrl())).toEqual({ layout: 'rows', page: '1', page_size: '25' })
})
it('displays error message when error occurs', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.error = 'Failed to fetch packages'
await wrapper.vm.$nextTick()
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 empty state when no packages', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
store.packages = []
await wrapper.vm.$nextTick()
it('displays an empty state when nothing is cached', async () => {
const { wrapper } = await open('/packages', [])
expect(wrapper.text()).toContain('No packages cached yet')
})
it('displays package accordion when packages exist', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'test-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('test-package')
expect(wrapper.text()).toContain('1 version')
it('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('calls fetchPackages on mount', async () => {
const store = usePackageStore()
// beforeEach already spied with mockResolvedValue; reuse that spy
const fetchSpy = store.fetchPackages as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
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 mountWithRouter()
await input.setValue('r')
await input.setValue('re')
await input.setValue('requests')
await vi.advanceTimersByTimeAsync(100)
expect(axios.get).not.toHaveBeenCalled()
expect(fetchSpy).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('groups packages and displays version counts', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'test-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
{
id: '2',
registry: 'npm',
name: 'test-package',
version: '2.0.0',
size: 2048,
cached_at: '2025-01-02T00:00:00Z',
last_accessed: '2025-01-02T00:00:00Z',
download_count: 20,
},
]
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('test-package')
expect(wrapper.text()).toContain('2 versions')
it('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('formats bytes correctly', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'test-package',
version: '1.0.0',
size: 1048576, // 1 MB
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('1 MB')
it('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('prints every registry as a badge with its name', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'npm-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
{
id: '2',
registry: 'pypi',
name: 'python-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 5,
},
{
id: '3',
registry: 'go',
name: 'go-module',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 3,
},
]
await wrapper.vm.$nextTick()
// Verify that all registry badges are displayed
// Packages are grouped and sorted alphabetically, so order is: go-module, npm-package, python-package
expect(wrapper.text()).toContain('npm')
expect(wrapper.text()).toContain('pypi')
expect(wrapper.text()).toContain('go')
// Each registry is printed as text in an outline badge, never as colour alone.
const badges = wrapper.findAll('[data-slot="badge"]').map((badge) => badge.text())
expect(badges).toEqual(['go', 'npm', 'pypi'])
it('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('shows the release version for a PyPI file row, not the file name', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
it('sends the verdict from the URL', async () => {
const { wrapper } = await open('/packages?verdict=held')
expect(lastUrl().get('verdict')).toBe('held')
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('1 of 1 package version')
})
store.packages = [
{
id: '1',
registry: 'pypi',
name: 'six',
version: 'six-1.17.0-py2.py3-none-any.whl',
release_version: '1.17.0',
size: 1,
cached_at: '2026-11-23T00:00:00Z',
last_accessed: '2026-11-23T00:00:00Z',
download_count: 0,
},
]
await wrapper.vm.$nextTick()
await wrapper.find('button[aria-expanded]').trigger('click')
await wrapper.vm.$nextTick()
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')
})
+182 -231
View File
@@ -1,133 +1,83 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
<PageHeader title="Packages" description="Everything the proxy has cached and the verdict each package received.">
<template #actions>
<Button variant="outline" :icon-start="faRotateRight" @click="store.fetchPackages()">Refresh</Button>
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
</template>
</PageHeader>
<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
<SegmentedControl
:model-value="selectedRegistry"
:options="REGISTRY_OPTIONS"
aria-label="Filter by registry"
@update:model-value="changeRegistryFilter"
/>
<SearchInput v-model="searchTerm" aria-label="Search packages" placeholder="Search packages..." class="w-full sm:ms-auto sm:w-64" />
<div 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" variant="table" label="Loading packages..." />
<LoadingState v-if="loading && !loaded" variant="table" label="Loading packages..." />
<ErrorState
v-else-if="error"
variant="card"
title="Could not load packages"
:message="error"
@retry="store.fetchPackages()"
/>
<ErrorState v-else-if="error" variant="card" title="Could not load packages" :message="error" @retry="load()" />
<Card v-else>
<CardContent>
<EmptyState
v-if="packages.length === 0"
v-if="total === 0 && !filtered"
:icon="faBoxOpen"
title="No packages cached yet"
description="Packages will appear here once they are downloaded through the proxy."
/>
<EmptyState
v-else-if="groupedPackages.length === 0"
v-else-if="total === 0"
:icon="faMagnifyingGlass"
title="No packages match"
description="Change the registry filter or the search text."
description="Change the search text or remove a filter."
/>
<Accordion v-else type="multiple" class="w-full">
<AccordionItem
v-for="group in groupedPackages"
:key="`${group.registry}:${group.name}`"
:value="`${group.registry}:${group.name}`"
>
<AccordionTrigger :heading-level="2">
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<span class="w-full min-w-0 text-start sm:w-auto">
<span class="block break-words font-semibold">{{ group.name }}</span>
<span class="block text-sm text-muted-foreground">
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
</span>
</span>
<span class="flex shrink-0 items-center gap-4">
<Badge variant="outline">{{ group.registry }}</Badge>
<span class="text-end tabular-nums">
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
</span>
</span>
</span>
</AccordionTrigger>
<AccordionContent>
<Table :label="`Versions of ${group.name}`" layout="cards">
<TableHeader>
<TableRow>
<TableHead>Version</TableHead>
<TableHead align="right">Downloads</TableHead>
<TableHead align="right">Size</TableHead>
<TableHead>Cached</TableHead>
<TableHead>Vulnerabilities</TableHead>
<TableHead align="right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="version in group.versions" :key="version.id">
<TableCell label="Version" class="font-medium">{{ withVersionPrefix(displayVersion(version)) }}</TableCell>
<TableCell label="Downloads" numeric>{{ formatNumber(version.download_count) }}</TableCell>
<TableCell label="Size" numeric>{{ formatBytes(version.size) }}</TableCell>
<TableCell label="Cached">{{ formatDate(version.cached_at) }}</TableCell>
<TableCell label="Vulnerabilities">
<VulnerabilityBadge
v-if="version.vulnerabilities"
:scanned="version.vulnerabilities.scanned"
:status="version.vulnerabilities.status"
:counts="version.vulnerabilities.counts"
:total="version.vulnerabilities.total"
:scannedAt="version.vulnerabilities.scannedAt"
:isBlocked="version.vulnerabilities.isBlocked"
@click="showVulnerabilityDetails(group.registry, group.name, version.version)"
/>
</TableCell>
<TableCell label="Actions" align="right">
<IconButton
:icon="faTrash"
:label="`Delete ${group.name} ${version.version}`"
@click="confirmDelete(version)"
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
</AccordionContent>
</AccordionItem>
</Accordion>
<div v-if="totalPages > 1" class="mt-6 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
<p class="m-0 text-sm text-muted-foreground">
Page {{ currentPage }} of {{ totalPages }} ({{ allGroupedPackages.length }} total packages)
<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
:page="currentPage"
:total="allGroupedPackages.length"
:page-size="itemsPerPage"
:show-edges="false"
@update:page="changePage"
v-if="total > PAGE_SIZE"
v-model:page="page"
class="mt-4"
:total="total"
:page-size="PAGE_SIZE"
aria-label="Package pages"
/>
</div>
</template>
</CardContent>
</Card>
<PackageQuickView :pkg="selected" @close="selected = null" @delete="confirmDelete" />
<ConfirmDialog
v-model:open="showDeleteModal"
title="Delete package version?"
:description="`Delete ${packageToDelete?.name}@${packageToDelete?.version}? This action cannot be undone.`"
confirm-label="Delete version"
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"
@@ -136,142 +86,156 @@
</template>
<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { usePackageStore, type Package } from '../stores/packages'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
Badge,
Button,
Card,
CardContent,
ConfirmDialog,
DataTable,
EmptyState,
ErrorState,
IconButton,
FilterBar,
LoadingState,
PageHeader,
Pagination,
RelativeTime,
SearchInput,
SegmentedControl,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
useToastStore,
type DataTableColumn,
type FilterField,
type FilterItem,
type SortState,
} from '@perfect-design/ui'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
import { faBoxOpen, faMagnifyingGlass, faRotateRight, faTrash } from '@/lib/icons'
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'
// Props from router
const props = defineProps<{
registry?: string
}>()
const props = defineProps<{ registry?: string }>()
const PAGE_SIZE = 25
const SEARCH_DEBOUNCE_MS = 300
const KNOWN_REGISTRIES = ['npm', 'go', 'pypi']
const route = useRoute()
const router = useRouter()
const store = usePackageStore()
const toasts = useToastStore()
const { packages, loading, error } = storeToRefs(store)
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 REGISTRY_OPTIONS = [
{ value: 'all', label: 'All' },
{ value: 'npm', label: 'npm' },
{ value: 'pypi', label: 'PyPI' },
{ value: 'go', label: 'Go' },
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 },
]
const selectedRegistry = ref<string>(props.registry || 'all')
const searchTerm = ref<string>('')
const currentPage = ref<number>(1)
const itemsPerPage = ref<number>(10)
// Group packages by name
const allGroupedPackages = computed(() => {
const groups = new Map<string, Package[]>()
// Filter packages by selected registry and search term
let filteredPackages = selectedRegistry.value === 'all'
? packages.value
: packages.value.filter(pkg => pkg.registry === selectedRegistry.value)
// Apply search filter if search term exists
if (searchTerm.value.trim()) {
const searchLower = searchTerm.value.toLowerCase()
filteredPackages = filteredPackages.filter(pkg =>
pkg.name.toLowerCase().includes(searchLower) ||
displayVersion(pkg).toLowerCase().includes(searchLower) ||
pkg.version.toLowerCase().includes(searchLower)
)
}
filteredPackages.forEach(pkg => {
const key = `${pkg.registry}:${pkg.name}`
if (!groups.has(key)) {
groups.set(key, [])
}
groups.get(key)!.push(pkg)
})
// Convert to array and sort versions within each group
return Array.from(groups.entries()).map(([key, versions]) => {
const [registry, name] = key.split(':')
return {
registry,
name,
versions: versions.sort((a, b) =>
new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime()
),
totalSize: versions.reduce((sum, v) => sum + v.size, 0),
totalDownloads: versions.reduce((sum, v) => sum + v.download_count, 0),
}
}).sort((a, b) => a.name.localeCompare(b.name))
})
// Pagination
const totalPages = computed(() => Math.ceil(allGroupedPackages.value.length / itemsPerPage.value))
const groupedPackages = computed(() => {
const start = (currentPage.value - 1) * itemsPerPage.value
const end = start + itemsPerPage.value
return allGroupedPackages.value.slice(start, end)
})
function changePage(page: number) {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page
// Scroll to top of packages list
window.scrollTo({ top: 0, behavior: 'smooth' })
}
async function load() {
await loadRows(rowQuery.value)
loaded.value = true
}
// Reset to page 1 when filters change
function resetPagination() {
currentPage.value = 1
}
// Watch for filter/search changes and reset pagination
watch([selectedRegistry, searchTerm], () => {
resetPagination()
})
// Watch for route parameter changes to update filter
watch(() => route.params.registry, (newRegistry) => {
selectedRegistry.value = (newRegistry as string) || 'all'
})
onMounted(async () => {
await store.fetchPackages()
})
watch(rowQuery, load)
onMounted(load)
function confirmDelete(pkg: Package) {
packageToDelete.value = pkg
@@ -284,28 +248,15 @@ async function deletePackage() {
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 delete package', `${label}: ${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 deleted', label)
}
function showVulnerabilityDetails(registry: string, name: string, version: string) {
// Navigate to the package details page
router.push({
name: 'package-details',
params: {
registry,
name,
version,
},
})
}
function changeRegistryFilter(registry: string) {
const path = registry === 'all' ? '/packages' : `/packages/${registry}`
router.push(path)
} else {
toasts.success('Package removed', label)
await load()
}
}
</script>
+282
View File
@@ -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)')
})
})
+236
View File
@@ -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>
+54 -6
View File
@@ -1,18 +1,66 @@
<template>
<StatGroup :columns="4" :aria-label="label">
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
</KpiTile>
<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 { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName } from '@/lib/severity'
import { plural } from '@/lib/reason'
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
defineProps<{
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>
-252
View File
@@ -1,252 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount as mountWith } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import Stats from './Stats.vue'
import { createTestRouter } from '@/test/router'
import { usePackageStore } from '../stores/packages'
describe('Stats.vue', () => {
let router: Awaited<ReturnType<typeof createTestRouter>>
const mount = (component: typeof Stats) => mountWith(component, { global: { plugins: [router] } })
beforeEach(async () => {
setActivePinia(createPinia())
router = await createTestRouter('/stats')
})
it('renders stats component', () => {
const wrapper = mount(Stats)
expect(wrapper.find('h1').text()).toBe('Statistics')
})
it('displays loading state when loading', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = true
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Loading statistics...')
})
it('displays error message when error occurs', async () => {
const store = usePackageStore()
vi.spyOn(store, 'fetchStats').mockResolvedValue()
const wrapper = mount(Stats)
store.loading = false
store.error = 'Failed to fetch statistics'
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Failed to fetch statistics')
})
it('displays overall statistics', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 100,
total_size: 1073741824, // 1 GB
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
blocked_packages: 0,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Overall statistics')
expect(wrapper.text()).toContain('100')
expect(wrapper.text()).toContain('500')
})
it('displays security scanning statistics', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 100,
total_size: 1073741824,
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
blocked_packages: 0,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Security scanning')
expect(wrapper.text()).toContain('Scanned packages')
expect(wrapper.text()).toContain('Vulnerable packages')
})
it('displays registry breakdown', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 100,
total_size: 1073741824,
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
blocked_packages: 0,
}
store.registries = {
npm: {
count: 50,
size: 536870912, // 512 MB
downloads: 300,
},
pypi: {
count: 30,
size: 322122547, // ~307 MB
downloads: 150,
},
go: {
count: 20,
size: 214748365, // ~205 MB
downloads: 50,
},
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Registry breakdown')
expect(wrapper.text()).toContain('npm')
expect(wrapper.text()).toContain('PyPI')
expect(wrapper.text()).toContain('Go modules')
// The cards layout prefixes each cell with its column label.
const packageCounts = wrapper
.findAll('tbody tr')
.map((row) => row.findAll('td')[0].text().replace(/^Packages/, ''))
expect(packageCounts).toEqual(['50', '30', '20'])
})
it('formats bytes correctly in overall stats', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 100,
total_size: 1073741824, // 1 GB
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
blocked_packages: 0,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('1 GB')
})
it('calls fetchStats on mount', () => {
const store = usePackageStore()
const fetchSpy = vi.spyOn(store, 'fetchStats')
mount(Stats)
expect(fetchSpy).toHaveBeenCalled()
})
it('lists the registries in the order the API reports them', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 3,
total_size: 0,
max_cache_size: 10737418240,
total_downloads: 0,
scanned_packages: 0,
vulnerable_packages: 0,
blocked_packages: 0,
}
store.registries = {
npm: { count: 1, size: 0, downloads: 0 },
pypi: { count: 1, size: 0, downloads: 0 },
go: { count: 1, size: 0, downloads: 0 },
}
await wrapper.vm.$nextTick()
const labels = wrapper.findAll('tbody th').map((cell) => cell.text().replace(/^Registry/, ''))
expect(labels).toEqual(['npm', 'PyPI', 'Go modules'])
})
it('handles empty registries data', async () => {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = {
registry: '',
total_packages: 0,
total_size: 0,
max_cache_size: 10737418240,
total_downloads: 0,
scanned_packages: 0,
vulnerable_packages: 0,
blocked_packages: 0,
}
store.registries = {}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Registry breakdown')
expect(wrapper.findAll('tbody th')).toHaveLength(0)
expect(wrapper.text()).toContain('No registries reported')
})
describe('idle eviction note', () => {
const baseStats = {
registry: '',
total_packages: 100,
total_size: 1073741824,
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
blocked_packages: 0,
}
async function render(idleTtl?: number) {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
await wrapper.vm.$nextTick()
return wrapper
}
it.each([
[604800, 'Cached items not requested for 7 days are removed.'],
[86400, 'Cached items not requested for 1 day are removed.'],
[129600, 'Cached items not requested for 36 hours are removed.'],
[5400, 'Cached items not requested for 90 minutes are removed.'],
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
const wrapper = await render(seconds)
expect(wrapper.text()).toContain(sentence)
})
it('hides the note when idle eviction is off', async () => {
const wrapper = await render(0)
expect(wrapper.text()).not.toContain('not requested')
})
it('hides the note when the API sends no idle_ttl', async () => {
const wrapper = await render()
expect(wrapper.text()).not.toContain('not requested')
})
})
})
-188
View File
@@ -1,188 +0,0 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader title="Statistics" description="Storage, traffic and scan results across every registry." />
<LoadingState v-if="loading" variant="kpi-grid" :columns="3" label="Loading statistics..." />
<ErrorState
v-else-if="error"
variant="card"
title="Could not load statistics"
:message="error"
@retry="refresh"
/>
<template v-else>
<Alert v-if="idleTtl > 0" variant="info">
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
</Alert>
<Card>
<CardHeader>
<CardTitle as="h2">Overall statistics</CardTitle>
</CardHeader>
<CardContent>
<StatGroup :columns="3" aria-label="Overall statistics">
<KpiTile label="Total packages" :value="stats?.total_packages || 0" :icon="faBoxesStacked" />
<KpiTile
label="Storage used"
:value="`${formatBytes(stats?.total_size || 0)} / ${formatBytes(stats?.max_cache_size || 0)}`"
:hint="`${storagePercentage.toFixed(1)}% used`"
:progress="storagePercentage"
:tone="storageTone"
:icon="faHardDrive"
/>
<KpiTile label="Total downloads" :value="stats?.total_downloads || 0" :icon="faDownload" />
</StatGroup>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Security scanning</CardTitle>
</CardHeader>
<CardContent>
<StatGroup :columns="3" aria-label="Security scanning">
<KpiTile label="Scanned packages" :value="stats?.scanned_packages || 0" :icon="faCircleCheck" />
<KpiTile
as="button"
type="button"
variant="interactive"
label="Vulnerable packages"
:value="stats?.vulnerable_packages || 0"
:hint="(stats?.vulnerable_packages || 0) > 0 ? 'View the list' : undefined"
:icon="faTriangleExclamation"
:disabled="(stats?.vulnerable_packages || 0) === 0"
@click="showVulnerablePackages"
/>
<KpiTile
as="button"
type="button"
variant="interactive"
label="Blocked packages"
:value="stats?.blocked_packages || 0"
:hint="(stats?.blocked_packages || 0) > 0 ? 'View the list' : undefined"
:icon="faBan"
:disabled="(stats?.blocked_packages || 0) === 0"
@click="showBlockedPackages"
/>
</StatGroup>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Registry breakdown</CardTitle>
</CardHeader>
<CardContent>
<DataTable
label="Registry breakdown"
layout="cards"
row-key="name"
empty-text="No registries reported"
:columns="registryColumns"
:rows="registries"
/>
</CardContent>
</Card>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { usePackageStore } from '../stores/packages'
import {
Alert,
AlertDescription,
Card,
CardContent,
CardHeader,
CardTitle,
DataTable,
ErrorState,
KpiTile,
LoadingState,
PageHeader,
StatGroup,
type DataTableColumn,
} from '@perfect-design/ui'
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
const store = usePackageStore()
const { stats, loading, error } = storeToRefs(store)
const router = useRouter()
onMounted(async () => {
await store.fetchStats()
})
function showVulnerablePackages() {
if ((stats.value?.vulnerable_packages || 0) === 0) {
return
}
router.push('/vulnerable-packages')
}
function showBlockedPackages() {
if ((stats.value?.blocked_packages || 0) === 0) {
return
}
router.push('/blocked-packages')
}
const REGISTRY_LABELS: Record<string, string> = {
npm: 'npm',
pypi: 'PyPI',
go: 'Go modules',
}
interface RegistryRow {
name: string
label: string
packages: number
size: string
downloads: number
}
const registryColumns: DataTableColumn<RegistryRow>[] = [
{ key: 'label', header: 'Registry', rowHeader: true },
{ key: 'packages', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.packages) },
{ key: 'size', header: 'Size', numeric: true },
{ key: 'downloads', header: 'Downloads', numeric: true, accessor: (r) => formatNumber(r.downloads) },
]
const registries = computed(() => {
const apiRegistries = store.registries || {}
return Object.entries(apiRegistries).map(([name, data]: [string, any]): RegistryRow => ({
name,
label: REGISTRY_LABELS[name] ?? name.toUpperCase(),
packages: data.count || 0,
size: formatBytes(data.size || 0),
downloads: data.downloads || 0,
}))
})
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
const storagePercentage = computed(() => {
const totalSize = stats.value?.total_size || 0
const maxSize = stats.value?.max_cache_size || 1
return (totalSize / maxSize) * 100
})
const storageTone = computed(() => {
if (storagePercentage.value >= 90) return 'danger'
if (storagePercentage.value >= 50) return 'warning'
return 'success'
})
function refresh() {
void store.fetchStats()
}
</script>
+183
View File
@@ -0,0 +1,183 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader title="System" description="The policy the proxy applies, the scanners behind it, and the settings that shape the cache.">
<template #actions>
<Badge v-if="info" variant="outline" class="font-mono" data-testid="build-version">{{ info.version }}</Badge>
<Button variant="outline" :icon-start="faRotateRight" @click="load(true)">Refresh</Button>
</template>
</PageHeader>
<LoadingState v-if="!info && !error" variant="card" label="Loading system settings..." />
<ErrorState v-else-if="!info" variant="card" title="Could not load system settings" :message="error ?? ''" @retry="load(true)" />
<template v-else>
<div class="grid gap-6 lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle as="h2">Policy</CardTitle>
<CardDescription>What clears a package and what holds it.</CardDescription>
</CardHeader>
<CardContent>
<DescriptionList :columns="1" divided data-testid="policy-list">
<DescriptionItem term="Scanning">
<StatusBadge :status="info.security.enabled ? 'on' : 'off'" :label="info.security.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
</DescriptionItem>
<DescriptionItem term="Block policy">{{ describePolicy(info.security) }}</DescriptionItem>
<DescriptionItem term="When a scan fails">
{{ info.security.fail_closed ? 'Fail-closed. The package is held.' : 'Fail-open on scanner outage. The package is served and the scan retried.' }}
</DescriptionItem>
<DescriptionItem term="Scan on download">{{ info.security.scan_on_download ? 'Yes' : 'No' }}</DescriptionItem>
<DescriptionItem term="First download waits">up to {{ formatDuration(info.security.scan_wait_timeout) }} for its scan</DescriptionItem>
</DescriptionList>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Rescans</CardTitle>
<CardDescription>Cached packages are inspected again as advisories change.</CardDescription>
</CardHeader>
<CardContent>
<DescriptionList :columns="1" divided data-testid="rescan-list">
<DescriptionItem term="Interval">{{ duration(info.security.rescan.interval, 'Rescans are off') }}</DescriptionItem>
<DescriptionItem term="Active window">{{ duration(info.security.rescan.active_window, 'Every cached package') }}</DescriptionItem>
<DescriptionItem term="Parallel scans">{{ info.security.rescan.concurrency }}</DescriptionItem>
<DescriptionItem term="Rescan on access">{{ info.security.rescan.on_access ? 'Yes. A stale hit is rescanned before it is served.' : 'No' }}</DescriptionItem>
</DescriptionList>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle as="h2">Inspectors</CardTitle>
<CardDescription>Health is probed at most every 30 seconds. A scanner that is off is not probed.</CardDescription>
</CardHeader>
<CardContent>
<DataTable label="Scanners" layout="cards" density="compact" row-key="name" :columns="scannerColumns" :rows="info.security.scanners">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
<template #cell-state="{ row }">
<StatusBadge :status="scannerState(row)" :label="STATE_LABELS[scannerState(row)]" :tones="STATE_TONES" />
</template>
<template #cell-version="{ row }">{{ scannerVersion(row) || 'Not applicable' }}</template>
</DataTable>
</CardContent>
</Card>
<div class="grid gap-6 lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle as="h2">Cache</CardTitle>
<CardDescription>Limits and where packages come from.</CardDescription>
</CardHeader>
<CardContent>
<DescriptionList :columns="1" divided data-testid="cache-list">
<DescriptionItem term="Size limit">{{ info.cache.max_size > 0 ? formatBytes(info.cache.max_size) : 'None' }}</DescriptionItem>
<DescriptionItem term="Idle eviction">{{ duration(info.cache.idle_ttl, 'Off', 'Removed after ', ' without a request') }}</DescriptionItem>
<DescriptionItem term="Default TTL">{{ duration(info.cache.default_ttl, 'None') }}</DescriptionItem>
<DescriptionItem v-for="(host, registry) in info.upstreams" :key="registry" :term="`Upstream ${registry}`">{{ host || 'Not set' }}</DescriptionItem>
</DescriptionList>
</CardContent>
</Card>
<Card data-testid="prewarming">
<CardHeader>
<CardTitle as="h2">Pre-warming</CardTitle>
<CardDescription>Fetches the most requested packages ahead of clients.</CardDescription>
</CardHeader>
<CardContent class="flex flex-col gap-4">
<DescriptionList :columns="1" divided>
<DescriptionItem term="Status">
<StatusBadge :status="info.prewarming.enabled ? 'on' : 'off'" :label="info.prewarming.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
</DescriptionItem>
<DescriptionItem term="Interval">{{ duration(info.prewarming.interval, 'None') }}</DescriptionItem>
<DescriptionItem term="Top packages">{{ info.prewarming.top_packages }}</DescriptionItem>
</DescriptionList>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<Button :icon-start="faRotateRight" :loading="triggering" :disabled="!info.prewarming.enabled" @click="trigger">Run a cycle now</Button>
<p class="m-0 text-sm text-muted-foreground">
{{ info.prewarming.enabled ? 'Needs the admin API key.' : 'Pre-warming is off in the configuration.' }}
</p>
</div>
</CardContent>
</Card>
</div>
</template>
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a pre-warming cycle." @saved="trigger" />
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import axios from 'axios'
import {
Badge,
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
DataTable,
DescriptionItem,
DescriptionList,
ErrorState,
LoadingState,
PageHeader,
StatusBadge,
useToastStore,
type DataTableColumn,
} from '@perfect-design/ui'
import AdminKeyDialog from './parts/AdminKeyDialog.vue'
import { useAdminKey } from '@/lib/adminKey'
import { formatBytes, formatDuration } from '@/lib/format'
import { faRotateRight } from '@/lib/icons'
import { describePolicy, scannerState, scannerVersion, useSystem, type ScannerInfo } from '@/lib/system'
const { info, error, load } = useSystem()
const adminKey = useAdminKey()
const toasts = useToastStore()
const triggering = ref(false)
const showKeyDialog = ref(false)
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
const scannerColumns: DataTableColumn<ScannerInfo>[] = [
{ key: 'name', header: 'Scanner', rowHeader: true },
{ key: 'state', header: 'State', accessor: (s) => scannerState(s) },
{ key: 'version', header: 'Version' },
]
/** Seconds as words; zero means the feature is off, so `zero` explains that. */
function duration(seconds: number, zero: string, before = '', after = ''): string {
return seconds === 0 ? zero : `${before}${formatDuration(seconds)}${after}`
}
async function trigger() {
adminKey.load()
if (!adminKey.key.value) {
showKeyDialog.value = true
return
}
triggering.value = true
try {
await axios.post('/api/admin/prewarming/trigger', null, { headers: adminKey.headers.value })
toasts.success('Pre-warming started', 'The cycle runs in the background.')
} catch (err) {
const status = (err as { response?: { status?: number } }).response?.status
if (status === 401 || status === 403) {
adminKey.clear()
toasts.error('Admin key refused', 'Enter a key with the admin role.')
} else {
toasts.error('Could not start pre-warming', err instanceof Error ? err.message : 'Request failed')
}
} finally {
triggering.value = false
}
}
onMounted(() => void load(true))
</script>
+227
View File
@@ -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])
})
})
+210
View File
@@ -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>
@@ -1,261 +0,0 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader
:title="showOnlyBlocked ? 'Blocked packages' : 'Vulnerable packages'"
:description="
showOnlyBlocked
? 'Packages blocked from download because they exceed the vulnerability thresholds.'
: 'Packages with known security vulnerabilities, sorted by risk.'
"
>
<template #back>
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to stats</Button>
</template>
</PageHeader>
<LoadingState v-if="loading" variant="card" label="Loading vulnerable packages..." />
<ErrorState
v-else-if="error"
variant="card"
title="Could not load vulnerable packages"
:message="error"
@retry="fetchVulnerablePackages"
/>
<Card v-else-if="sortedVulnerablePackages.length === 0">
<CardContent>
<EmptyState
tone="success"
:icon="faCircleCheck"
:title="showOnlyBlocked ? 'No blocked packages' : 'No vulnerable packages'"
description="Every cached package is clean."
/>
</CardContent>
</Card>
<template v-else>
<SeveritySummary :counts="totalCounts" label="Vulnerabilities by severity" />
<Card>
<CardHeader>
<CardTitle as="h2">
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
</CardTitle>
<CardDescription>
{{ groupedPackages.length }} unique package{{ groupedPackages.length !== 1 ? 's' : '' }}, most critical first
</CardDescription>
</CardHeader>
<CardContent>
<Accordion type="multiple" class="w-full">
<AccordionItem
v-for="group in groupedPackages"
:key="`${group.registry}:${group.name}`"
:value="`${group.registry}:${group.name}`"
>
<AccordionTrigger :heading-level="3">
<span class="flex w-full min-w-0 items-center justify-between gap-4">
<span class="min-w-0 text-start">
<span class="block break-words font-semibold">{{ group.name }}</span>
<span class="block text-sm text-muted-foreground">
{{ group.versions.length }} vulnerable version{{ group.versions.length > 1 ? 's' : '' }}
</span>
</span>
<span class="flex shrink-0 items-center gap-4">
<Badge variant="outline">{{ group.registry }}</Badge>
<span class="whitespace-nowrap text-end tabular-nums">
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
</span>
</span>
</span>
</AccordionTrigger>
<AccordionContent>
<DataTable
:label="`Vulnerable versions of ${group.name}`"
layout="cards"
row-clickable
:columns="versionColumns"
:rows="group.versions"
@row-click="navigateToPackage"
>
<template #cell-vulnerabilities="{ row }">
<VulnerabilityBadge
v-if="row.vulnerabilities"
:scanned="row.vulnerabilities.scanned"
:status="row.vulnerabilities.status"
:counts="row.vulnerabilities.counts"
:total="row.vulnerabilities.total"
:scannedAt="row.vulnerabilities.scannedAt"
:isBlocked="row.vulnerabilities.isBlocked"
@click="navigateToPackage(row)"
/>
</template>
</DataTable>
</AccordionContent>
</AccordionItem>
</Accordion>
</CardContent>
</Card>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { usePackageStore, type Package } from '../stores/packages'
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
Badge,
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
DataTable,
EmptyState,
ErrorState,
LoadingState,
PageHeader,
type DataTableColumn,
} from '@perfect-design/ui'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import SeveritySummary from './SeveritySummary.vue'
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
import { NO_VULNERABILITIES } from '@/lib/severity'
const store = usePackageStore()
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const error = ref<string | null>(null)
const vulnerablePackages = ref<Package[]>([])
// Check if we should filter to show only blocked packages
const showOnlyBlocked = computed(() => route.path === '/blocked-packages')
onMounted(async () => {
await fetchVulnerablePackages()
})
async function fetchVulnerablePackages() {
loading.value = true
error.value = null
try {
await store.fetchPackages()
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
if (store.error) {
error.value = store.error
return
}
vulnerablePackages.value = store.packages.filter(pkg => {
const isVulnerable = pkg.vulnerabilities?.status === 'vulnerable'
if (showOnlyBlocked.value) {
return isVulnerable && pkg.vulnerabilities?.isBlocked === true
}
return isVulnerable
})
} catch (err: any) {
console.error('Failed to load vulnerable packages:', err)
error.value = err.message || 'Failed to load vulnerable packages'
} finally {
loading.value = false
}
}
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
const sortedVulnerablePackages = computed(() => {
return [...vulnerablePackages.value].sort((a, b) => {
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
// Compare critical count (descending)
if (aVulns.critical !== bVulns.critical) {
return bVulns.critical - aVulns.critical
}
// Compare high count (descending)
if (aVulns.high !== bVulns.high) {
return bVulns.high - aVulns.high
}
// Compare moderate count (descending)
if (aVulns.moderate !== bVulns.moderate) {
return bVulns.moderate - aVulns.moderate
}
// Compare low count (descending)
return bVulns.low - aVulns.low
})
})
// Group packages by name and registry, with versions sorted by risk
const groupedPackages = computed(() => {
const groups = new Map<string, {
registry: string
name: string
versions: Package[]
totalSize: number
totalDownloads: number
}>()
sortedVulnerablePackages.value.forEach((pkg) => {
const key = `${pkg.registry}:${pkg.name}`
if (!groups.has(key)) {
groups.set(key, {
registry: pkg.registry,
name: pkg.name,
versions: [],
totalSize: 0,
totalDownloads: 0,
})
}
const group = groups.get(key)!
group.versions.push(pkg)
group.totalSize += pkg.size || 0
group.totalDownloads += pkg.download_count || 0
})
return Array.from(groups.values())
})
// Calculate total counts across all packages
const totalCounts = computed(() =>
vulnerablePackages.value.reduce(
(sum, pkg) => {
const counts = pkg.vulnerabilities?.counts ?? NO_VULNERABILITIES
return {
critical: sum.critical + counts.critical,
high: sum.high + counts.high,
moderate: sum.moderate + counts.moderate,
low: sum.low + counts.low,
}
},
{ ...NO_VULNERABILITIES },
),
)
const versionColumns: DataTableColumn<Package>[] = [
{ key: 'version', header: 'Version', rowHeader: true, accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
{ key: 'cached_at', header: 'Cached', accessor: (pkg) => formatDate(pkg.cached_at) },
{ key: 'vulnerabilities', header: 'Vulnerabilities', accessor: () => '' },
]
function navigateToPackage(pkg: Package) {
router.push(`/package/${pkg.registry}/${pkg.name}/${pkg.version}`)
}
function goBack() {
router.push('/stats')
}
</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,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,84 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import TopPackages from './TopPackages.vue'
import { mountStrict } from '@/test/mountStrict'
vi.mock('axios')
let restore: (() => void) | undefined
const row = (registry: string, name: string, download_count: number) => ({ registry, name, version: '1.0.0', download_count })
function serve(rows: unknown[], trending: unknown[] = []) {
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.startsWith('/api/analytics/trending')) return { data: { packages: trending } } as never
if (url.startsWith('/api/packages?layout=rows')) return { data: { packages: rows } } as never
throw new Error(`unexpected request: ${url}`)
})
}
async function open() {
const mounted = await mountStrict(TopPackages)
restore = mounted.restore
await flushPromises()
return mounted.wrapper
}
beforeEach(() => {
vi.mocked(axios.get).mockReset()
})
afterEach(() => {
restore?.()
restore = undefined
})
describe('TopPackages', () => {
it('ranks packages by the stored download counts, so a restart does not empty it', async () => {
serve([row('npm', 'left-pad', 12), row('npm', 'left-pad', 5), row('pypi', 'six', 9)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('npm · left-pad')
expect(text).toContain('pypi · six')
expect(text).not.toContain('No downloads yet')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200')
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith(expect.stringContaining('/api/analytics/top'))
})
it('adds the versions of a package and orders by the sum', async () => {
serve([row('npm', 'a', 10), row('npm', 'b', 15), row('npm', 'a', 9)])
const wrapper = await open()
const labels = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
expect(labels[0]).toContain('npm · a')
expect(labels[1]).toContain('npm · b')
})
it('counts a Go module once, by its zip, and not its .mod and .info files', async () => {
serve([
row('go', 'github.com/google/uuid/@v/v1.6.0.zip', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.mod', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.info', 4),
])
const wrapper = await open()
const entries = wrapper.findAll('[data-testid="top-packages"] li')
expect(entries).toHaveLength(1)
expect(entries[0].text()).toContain('go · github.com/google/uuid')
expect(entries[0].text()).toContain('4')
expect(entries[0].text()).not.toContain('12')
})
it('says so when no package has a download', async () => {
serve([row('npm', 'left-pad', 0)])
const wrapper = await open()
expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet')
})
it('names where each ranking comes from', async () => {
serve([row('npm', 'left-pad', 3)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('The counts survive restarts.')
expect(text).toContain('Counted in memory, so it restarts with the server.')
})
})
@@ -0,0 +1,111 @@
<template>
<div class="grid gap-6 lg:grid-cols-2" data-testid="top-packages">
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Most requested</CardTitle>
<CardDescription>Downloads served from the cache. The counts survive restarts.</CardDescription>
</CardHeader>
<CardContent>
<LoadingState v-if="loading" layout="inline" label="Loading top packages..." />
<ErrorState v-else-if="error" variant="inline" title="Could not load top packages" :message="error" @retry="load" />
<EmptyState v-else-if="top.length === 0" size="sm" title="No downloads yet" description="Rankings appear after the first download." />
<Leaderboard v-else label="Most requested packages" bars :entries="top" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Downloads', delta: 'Change' }" />
</CardContent>
</Card>
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Trending</CardTitle>
<CardDescription>Downloads in the last 7 days. Counted in memory, so it restarts with the server.</CardDescription>
</CardHeader>
<CardContent>
<LoadingState v-if="loading" layout="inline" label="Loading trending packages..." />
<ErrorState v-else-if="error" variant="inline" title="Could not load trending packages" :message="error" @retry="load" />
<EmptyState v-else-if="trending.length === 0" size="sm" title="Nothing trending" description="No package was downloaded in the last 7 days." />
<Leaderboard v-else label="Trending packages" bars :entries="trending" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Last 7 days', delta: 'Change' }" />
</CardContent>
</Card>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import axios from 'axios'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
EmptyState,
ErrorState,
Leaderboard,
LoadingState,
type LeaderboardEntry,
} from '@perfect-design/ui'
import { modulePath } from '@/lib/format'
/** The analytics engine serialises Go field names. */
interface PopularPackage {
Registry: string
Name: string
Downloads: number
RecentDownloads: number
}
/** One stored version row; its count is kept in the database. */
interface DownloadRow {
registry: string
name: string
download_count: number
}
const LIMIT = 8
// Go keeps one row per file (.zip, .mod, .info) of a version; only the zip is a module download.
const GO_METADATA = /\.(mod|info)$/
const ROWS_URL = '/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200'
const stored = ref<DownloadRow[]>([])
const recent = ref<PopularPackage[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
// Rows with equal registry and module path (a Go module's .zip, .mod and .info) are one package.
function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number): LeaderboardEntry[] {
const totals = new Map<string, LeaderboardEntry>()
for (const row of rows) {
const id = `${row.Registry}/${modulePath(row.Name)}`
const existing = totals.get(id)
if (existing) existing.value += pick(row)
else totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row) })
}
return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT)
}
const top = computed(() =>
entries(
stored.value
.filter((r) => !(r.registry === 'go' && GO_METADATA.test(r.name)))
.map((r) => ({ Registry: r.registry, Name: r.name, Downloads: r.download_count, RecentDownloads: 0 })),
(p) => p.Downloads,
),
)
const trending = computed(() => entries(recent.value, (p) => p.RecentDownloads))
async function load() {
loading.value = true
error.value = null
try {
const [topRes, trendRes] = await Promise.all([
axios.get<{ packages: DownloadRow[] }>(ROWS_URL),
axios.get<{ packages: PopularPackage[] }>('/api/analytics/trending?limit=50'),
])
stored.value = topRes.data.packages ?? []
recent.value = trendRes.data.packages ?? []
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to load package rankings'
} finally {
loading.value = false
}
}
onMounted(load)
</script>
@@ -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>
+14 -5
View File
@@ -6,6 +6,7 @@ import {
faBoxesStacked,
faChartColumn,
faChartPie,
faGear,
faShieldHalved,
faTriangleExclamation,
} from '@/lib/icons'
@@ -17,11 +18,17 @@ defineProps<{ readonly sheet?: boolean }>()
const GROUPS: SidebarNavGroup[] = [
{
items: [
{ label: 'Dashboard', to: '/', icon: faChartPie },
{ label: 'Overview', to: '/', icon: faChartPie },
{ label: 'Packages', to: '/packages', icon: faBoxesStacked },
{ label: 'Vulnerable', to: '/vulnerable-packages', icon: faTriangleExclamation },
{ label: 'Security', to: '/security', icon: faTriangleExclamation },
{ label: 'Insights', to: '/stats', icon: faChartColumn },
],
},
{
label: 'Admin',
items: [
{ label: 'Bypasses', to: '/admin/bypasses', icon: faShieldHalved },
{ label: 'Stats', to: '/stats', icon: faChartColumn },
{ label: 'System', to: '/admin/system', icon: faGear },
],
},
]
@@ -29,9 +36,11 @@ const GROUPS: SidebarNavGroup[] = [
const SECTION_PREFIXES: ReadonlyArray<readonly [string, string]> = [
['/packages', '/packages'],
['/package/', '/packages'],
['/vulnerable-packages', '/vulnerable-packages'],
['/blocked-packages', '/vulnerable-packages'],
['/security', '/security'],
['/vulnerable-packages', '/security'],
['/blocked-packages', '/security'],
['/admin/bypasses', '/admin/bypasses'],
['/admin/system', '/admin/system'],
['/stats', '/stats'],
]
+17 -13
View File
@@ -3,12 +3,14 @@ import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import App from '@/App.vue'
import Dashboard from './Dashboard.vue'
import Overview from './Overview.vue'
import PackageList from './PackageList.vue'
import PackageDetails from './PackageDetails.vue'
import VulnerablePackages from './VulnerablePackages.vue'
import Security from './Security.vue'
import BypassManagementPanel from './BypassManagementPanel.vue'
import Stats from './Stats.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'
@@ -21,20 +23,21 @@ const FAILURE = Object.assign(new Error('Request failed with status code 502'),
// What each view must not say when the request failed: an empty state would tell the operator there is nothing to see.
const EMPTY_TEXT: Record<string, string> = {
Dashboard: 'No packages cached yet',
Overview: 'Quiet at the desk',
PackageList: 'No packages cached yet',
VulnerablePackages: 'No vulnerable packages',
Stats: 'No registries reported',
Security: 'Nothing is held',
Insights: 'No registry data yet',
BypassManagementPanel: 'No bypasses found',
}
const CASES: Array<[string, Parameters<typeof mountStrict>[0], string]> = [
['Dashboard', Dashboard, '/'],
['Overview', Overview, '/'],
['PackageList', PackageList, '/packages'],
['PackageDetails', PackageDetails, '/package/npm/left-pad/1.3.0'],
['VulnerablePackages', VulnerablePackages, '/vulnerable-packages'],
['Security', Security, '/security'],
['BypassManagementPanel', BypassManagementPanel, '/admin/bypasses'],
['Stats', Stats, '/stats'],
['Insights', Insights, '/stats'],
['System', System, '/admin/system'],
]
let restore: (() => void) | undefined
@@ -42,6 +45,7 @@ let restore: (() => void) | undefined
beforeEach(() => {
setActivePinia(createPinia())
__resetRealtimeSingleton()
__resetSystem()
vi.mocked(axios.get).mockRejectedValue(FAILURE)
localStorage.setItem('admin_api_key', 'test-key')
})
@@ -73,16 +77,16 @@ describe('an API failure renders ErrorState, never an empty state', () => {
})
it('retry fetches again and clears the error when the backend is back', async () => {
const router = await createTestRouter('/vulnerable-packages')
const router = await createTestRouter('/security')
const pinia = createPinia()
setActivePinia(pinia)
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
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('No vulnerable packages')
expect(mounted.wrapper.text()).toContain('Nothing is held')
})
})
@@ -102,6 +106,6 @@ describe('unknown routes', () => {
expect(main.find('h1').text()).toBe('Page not found')
expect(main.find('[data-slot="empty-state"]').text()).toContain('/vulnerable')
const link = main.find('a[href="/"]')
expect(link.text()).toMatch(/dashboard/i)
expect(link.text()).toMatch(/overview|dashboard/i)
})
})
+212 -57
View File
@@ -3,16 +3,29 @@ import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import App from '@/App.vue'
import Dashboard from './Dashboard.vue'
import Overview from './Overview.vue'
import PackageList from './PackageList.vue'
import PackageDetails from './PackageDetails.vue'
import VulnerablePackages from './VulnerablePackages.vue'
import Security from './Security.vue'
import BypassManagementPanel from './BypassManagementPanel.vue'
import Stats from './Stats.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 { usePackageStore } from '@/stores/packages'
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, VULNERABILITY_REPORT } from '@/test/fixtures'
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'
@@ -21,10 +34,21 @@ 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/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}`)
}
@@ -34,6 +58,7 @@ 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')
})
@@ -56,52 +81,83 @@ async function smoke(component: Parameters<typeof mountStrict>[0], path: string,
}
describe('view smoke tests (strict mode throw, fixture data)', () => {
it('Dashboard renders the tiles, chart, feed and recent packages', async () => {
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(Dashboard, { global: { plugins: [pinia, router] } })
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('Dashboard')
expect(wrapper.text()).toContain('Total packages')
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')
expect(wrapper.find('[role="img"]').exists()).toBe(true)
expect(wrapper.text()).toContain('Recent packages')
expect(wrapper.text()).toContain('github.com/example/module')
})
it('PackageList groups fixture packages and shows severity words', async () => {
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.text()).toContain('left-pad')
expect(wrapper.text()).toContain('2 versions')
expect(wrapper.text()).toContain('requests')
const trigger = wrapper.findAll('button').find((b) => b.text().includes('left-pad'))
await trigger!.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('Critical: 1')
expect(wrapper.text()).toContain('Blocked')
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('PackageDetails renders the report, severity table and expanded row', async () => {
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')
expect(wrapper.text()).toContain('Security scan summary')
expect(wrapper.text()).toContain('trivy')
// Most severe first: CRITICAL, HIGH, then LOW.
const ids = wrapper.findAll('tbody td.font-mono').map((td) => td.text().replace('CVE ID', ''))
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')
@@ -110,26 +166,58 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(wrapper.text()).toContain('No fix available')
})
it('VulnerablePackages lists the vulnerable fixture packages', async () => {
const { wrapper, problems } = await smoke(VulnerablePackages, '/vulnerable-packages')
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([])
expect(wrapper.find('h1').text()).toBe('Vulnerable packages')
expect(wrapper.text()).toContain('left-pad')
expect(wrapper.text()).not.toContain('requests')
expect(wrapper.text()).toContain('Critical')
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('VulnerablePackages on the blocked route keeps only blocked packages', async () => {
const { wrapper, problems } = await smoke(VulnerablePackages, '/blocked-packages')
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([])
expect(wrapper.find('h1').text()).toBe('Blocked packages')
expect(wrapper.text()).toContain('1 vulnerable version')
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('CVE bypass management')
expect(wrapper.find('h1').text()).toBe('Bypasses')
expect(wrapper.text()).toContain('CVE-2026-0002')
expect(wrapper.text()).toContain('Expired')
@@ -140,6 +228,14 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
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')
@@ -165,14 +261,51 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(wrapper.text()).toContain('CVE-2026-0002')
})
it('Stats renders totals, the storage tile and the registry table', async () => {
const { wrapper, problems } = await smoke(Stats, '/stats')
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('Statistics')
expect(wrapper.text()).toContain('5 GB / 10 GB')
expect(wrapper.text()).toContain('50.0% used')
expect(wrapper.text()).toContain('Go modules')
expect(wrapper.find('[role="progressbar"]').exists()).toBe(true)
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 () => {
@@ -190,7 +323,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(tones).toEqual(['danger', 'danger', 'warning', 'info', 'neutral'])
})
it('App renders one banner, one main, a skip link first and the five sections', async () => {
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.
@@ -199,16 +332,38 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
const first = document.body.querySelector<HTMLElement>('a[href], button')
expect(first?.getAttribute('href')).toBe('#main-content')
const nav = wrapper.find('nav[aria-label="Sections"]')
expect(nav.findAll('a').map((a) => a.text())).toEqual(['Dashboard', 'Packages', 'Vulnerable', 'Bypasses', 'Stats'])
expect(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 still fetches through the store on mount', async () => {
it('PackageList asks for one page of rows on mount', async () => {
await smoke(PackageList, '/packages')
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
await flushPromises()
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(expect.stringContaining('/api/packages?layout=rows'))
})
})
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')
})
})
@@ -239,26 +394,28 @@ describe('PyPI rows show the release version, not the file name', () => {
if (url.endsWith('/vulnerabilities')) {
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
}
if (url.includes('layout=rows')) return { data: serveRows(url, [SIX as never]) } as never
if (url === `/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('Dashboard recent packages', async () => {
const { wrapper } = await smoke(Dashboard, '/')
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('Dashboard activity feed', async () => {
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(Dashboard, { global: { plugins: [pinia, router] } })
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()
@@ -266,10 +423,8 @@ describe('PyPI rows show the release version, not the file name', () => {
expect(feed).not.toContain('whl')
})
it('VulnerablePackages version column', async () => {
const { wrapper } = await smoke(VulnerablePackages, '/vulnerable-packages')
await flushPromises()
await wrapper.find('button[aria-expanded]').trigger('click')
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')
+22
View File
@@ -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 }
}
+59
View File
@@ -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)
})
})
+38
View File
@@ -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)))
}
+6
View File
@@ -40,3 +40,9 @@ export function displayVersion(pkg: { version: string; release_version?: string
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)
}
+5
View File
@@ -1,5 +1,6 @@
export {
faArrowLeft,
faArrowRight,
faBan,
faBox,
faBoxOpen,
@@ -8,10 +9,14 @@ export {
faChartLine,
faChartPie,
faDownload,
faGear,
faHardDrive,
faHourglassHalf,
faKey,
faPen,
faShieldHalved,
faTrash,
faUnlockKeyhole,
faTriangleExclamation,
} from '@fortawesome/free-solid-svg-icons'
export {
+42
View File
@@ -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: '' })
})
})
+61
View File
@@ -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
}
+64
View File
@@ -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)
})
})
+96
View File
@@ -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 }
}
+11
View File
@@ -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' },
})
})
})
+12
View File
@@ -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)}`
}
+33
View File
@@ -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('')
})
})
+33
View File
@@ -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
}
+31
View File
@@ -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 }
}
+59
View File
@@ -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('')
})
})
+97
View File
@@ -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
}
+34
View File
@@ -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)
}
+63
View File
@@ -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)
}
+23
View File
@@ -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' })
})
})
+54
View File
@@ -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'
}
+99
View File
@@ -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')
})
})
+71
View File
@@ -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.`,
}
}
}
}
+23 -8
View File
@@ -1,10 +1,15 @@
import { createRouter, createWebHistory, type RouteRecordRaw, type RouterHistory } from 'vue-router'
import { createRouter, createWebHistory, type LocationQuery, type RouteRecordRaw, type RouterHistory } from 'vue-router'
/** Keeps the query string of an old URL when it moves to a tab of the Security page. */
function toSecurityTab(tab: string) {
return (to: { query: LocationQuery }) => ({ path: '/security', query: { ...to.query, tab } })
}
export const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'dashboard',
component: () => import('../components/Dashboard.vue'),
name: 'overview',
component: () => import('../components/Overview.vue'),
},
{
path: '/packages/:registry?',
@@ -20,25 +25,35 @@ export const routes: RouteRecordRaw[] = [
props: true,
},
{
path: '/stats',
name: 'stats',
component: () => import('../components/Stats.vue'),
path: '/security',
name: 'security',
component: () => import('../components/Security.vue'),
},
{
path: '/vulnerable-packages',
name: 'vulnerable-packages',
component: () => import('../components/VulnerablePackages.vue'),
redirect: toSecurityTab('allowed'),
},
{
path: '/blocked-packages',
name: 'blocked-packages',
component: () => import('../components/VulnerablePackages.vue'),
redirect: toSecurityTab('held'),
},
{
path: '/stats',
name: 'insights',
component: () => import('../components/Insights.vue'),
},
{
path: '/admin/bypasses',
name: 'bypasses',
component: () => import('../components/BypassManagementPanel.vue'),
},
{
path: '/admin/system',
name: 'system',
component: () => import('../components/System.vue'),
},
{
path: '/:pathMatch(.*)*',
name: 'not-found',
+63
View File
@@ -0,0 +1,63 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { usePackageStore } from './packages'
vi.mock('axios')
describe('package store', () => {
beforeEach(() => {
setActivePinia(createPinia())
vi.mocked(axios.get).mockReset()
})
afterEach(() => vi.restoreAllMocks())
it('loads the stats of one registry', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { stats: { total_packages: 3 }, registries: { npm: {} } } })
const store = usePackageStore()
await store.fetchStats('npm')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/stats?registry=npm')
expect(store.stats?.total_packages).toBe(3)
expect(store.registries).toEqual({ npm: {} })
})
it('keeps the last stats and reports the error when a request fails', async () => {
vi.mocked(axios.get).mockResolvedValueOnce({ data: { stats: { total_packages: 3 }, registries: {} } })
const store = usePackageStore()
await store.fetchStats()
vi.mocked(axios.get).mockRejectedValueOnce(new Error('boom'))
vi.spyOn(console, 'error').mockImplementation(() => {})
await store.fetchStats()
expect(store.stats?.total_packages).toBe(3)
expect(store.error).toBe('boom')
expect(store.loading).toBe(false)
})
it('loading stays on until the last overlapping request settles', async () => {
const store = usePackageStore()
const releases: Array<(v: unknown) => void> = []
vi.mocked(axios.get).mockImplementation(() => new Promise((resolve) => releases.push(resolve)))
const first = store.fetchStats()
const second = store.fetchStats('pypi')
expect(store.loading).toBe(true)
releases[0]({ data: { stats: { total_packages: 1 }, registries: {} } })
await first
expect(store.loading).toBe(true)
releases[1]({ data: { stats: { total_packages: 2 }, registries: {} } })
await second
expect(store.loading).toBe(false)
})
it('delete removes one version and leaves reloading to the caller', async () => {
vi.mocked(axios.delete).mockResolvedValue({})
const store = usePackageStore()
await store.deletePackage('npm', 'left-pad', '1.0.0')
expect(vi.mocked(axios.delete)).toHaveBeenCalledWith('/api/packages/npm/left-pad/1.0.0')
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
})
})
+33 -27
View File
@@ -9,6 +9,20 @@ export interface VulnerabilityCounts {
low: number
}
/** What the proxy did with a package; absent on servers that predate verdicts. */
export type ApiVerdict = 'cleared' | 'held' | 'bypassed' | 'pending'
/** The admin bypass that applied to a package. */
export interface AppliedBypass {
id: string
type: 'cve' | 'package'
target: string
reason: string
created_by: string
created_at: string
expires_at: string
}
export interface VulnerabilityInfo {
scanned: boolean
status: 'clean' | 'vulnerable' | 'pending' | 'not_scanned'
@@ -16,6 +30,10 @@ export interface VulnerabilityInfo {
total?: number
scannedAt?: string // ISO 8601 timestamp
isBlocked?: boolean // Whether download is blocked due to vulnerability thresholds
verdict?: ApiVerdict
/** Why the package is held. */
reason?: string
bypass?: AppliedBypass
}
export interface Package {
@@ -25,6 +43,7 @@ export interface Package {
version: string
release_version?: string
size: number
checksum_sha256?: string
cached_at: string
last_accessed: string
download_count: number
@@ -40,41 +59,31 @@ export interface Stats {
scanned_packages: number
vulnerable_packages: number
blocked_packages: number
bypassed_packages?: number
/** Seconds a cached item can go unrequested before cleanup removes it; 0 means never. */
idle_ttl?: number
}
export const usePackageStore = defineStore('packages', () => {
const packages = ref<Package[]>([])
const stats = ref<Stats | null>(null)
const registries = ref<Record<string, any>>({})
const loading = ref(false)
const error = ref<string | null>(null)
async function fetchPackages() {
// Requests overlap, so loading stays on until the last one settles.
let inFlight = 0
function begin() {
inFlight++
loading.value = true
error.value = null
try {
const response = await axios.get('/api/packages')
// Only update packages if we got valid data
if (response.data && Array.isArray(response.data.packages)) {
packages.value = response.data.packages
} else {
console.warn('Unexpected API response format:', response.data)
error.value = 'Unexpected response format from server'
}
} catch (err: any) {
console.error('Failed to fetch packages:', err)
error.value = err.message
// Don't clear packages on error - keep showing the cached data
} finally {
loading.value = false
}
}
function settle() {
inFlight = Math.max(inFlight - 1, 0)
if (inFlight === 0) loading.value = false
}
async function fetchStats(registry = '') {
loading.value = true
error.value = null
begin()
try {
const url = registry ? `/api/stats?registry=${registry}` : '/api/stats'
const response = await axios.get(url)
@@ -91,30 +100,27 @@ export const usePackageStore = defineStore('packages', () => {
error.value = err.message
// Don't clear stats on error - keep showing the cached data
} finally {
loading.value = false
settle()
}
}
/** Deletes one version; the caller reloads whichever list it shows. */
async function deletePackage(registry: string, name: string, version: string) {
loading.value = true
error.value = null
begin()
try {
await axios.delete(`/api/packages/${registry}/${name}/${version}`)
await fetchPackages()
} catch (err: any) {
error.value = err.message
} finally {
loading.value = false
settle()
}
}
return {
packages,
stats,
registries,
loading,
error,
fetchPackages,
fetchStats,
deletePackage,
}
+16
View File
@@ -53,6 +53,22 @@ describe('useRealtimeStore', () => {
expect(store.lastStats).toMatchObject({ total_packages: 42, total_size: 1024 })
})
it('unwraps the server stats_update shape {stats, timestamp}', () => {
const store = useRealtimeStore()
store.ingest(
makeEvent('stats_update', {
stats: { total_packages: 1454, total_size: 980870617, total_downloads: 5376, scanned_packages: 1451 },
timestamp: '2026-11-23T16:00:00Z',
}),
)
expect(store.lastStats).toMatchObject({
total_packages: 1454,
total_size: 980870617,
total_downloads: 5376,
scanned_packages: 1451,
})
})
it('exposes filtered computed slices', () => {
const store = useRealtimeStore()
store.ingest(makeEvent('package_cached'))
+3 -1
View File
@@ -55,7 +55,9 @@ export const useRealtimeStore = defineStore('realtime', () => {
events.value.splice(0, events.value.length - EVENTS_CAP)
}
if (event.type === 'stats_update') {
lastStats.value = event.payload as RealtimeStats
// The server nests the counters under `stats`; reading the payload flat shows zeros.
const nested = event.payload.stats
lastStats.value = (nested && typeof nested === 'object' ? nested : event.payload) as RealtimeStats
}
}
+22 -2
View File
@@ -4,19 +4,24 @@
/* Only the library components the app imports, plus their transitive imports: scanning all of dist adds every component's classes. `pnpm sources` regenerates this list. */
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/ActivityFeed/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/BarChart/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CalendarHeatmap/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Card/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CodeViewer/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CodeViewer/tokenize/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DonutChart/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Leaderboard/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatBar/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_chart/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_shared/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Alert/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Callout/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ConfirmDialog/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/EmptyState/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ErrorState/*.js";
@@ -26,29 +31,35 @@
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Checkbox/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/CheckboxCard/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Combobox/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/DateInput/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Field/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/FilterBar/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Input/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/InputGroup/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Label/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NativeSelect/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NumberInput/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SearchInput/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SegmentedControl/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Textarea/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/forms/TimeInput/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/layout/AppShell/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/layout/ConfigProvider/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/layout/Container/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/layout/PageHeader/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Accordion/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/AppHeader/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/MobileNav/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/NavLink/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Pagination/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/SidebarNav/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Tabs/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/ThemeToggle/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/AlertDialog/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Dialog/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Popover/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Sheet/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Avatar/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Badge/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Button/*.js";
@@ -59,6 +70,10 @@
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/FormattedNumber/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/InlineCode/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
@@ -119,3 +134,8 @@ html {
scroll-behavior: auto !important;
}
}
/* The library's sort button bleeds 0.5rem past its cell, more than the workbench cell padding, so the last column adds a horizontal scrollbar. */
[data-slot='table-head']:last-child {
padding-right: 0.5rem;
}
+92 -2
View File
@@ -9,6 +9,7 @@ export const STATS: Stats = {
scanned_packages: 3,
vulnerable_packages: 2,
blocked_packages: 1,
bypassed_packages: 1,
}
export const REGISTRIES = {
@@ -34,6 +35,8 @@ export const PACKAGES: Package[] = [
total: 4,
scannedAt: '2026-01-03T10:05:00Z',
isBlocked: true,
verdict: 'held',
reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)',
},
},
{
@@ -52,6 +55,7 @@ export const PACKAGES: Package[] = [
total: 3,
scannedAt: '2026-01-02T10:05:00Z',
isBlocked: false,
verdict: 'cleared',
},
},
{
@@ -63,7 +67,24 @@ export const PACKAGES: Package[] = [
cached_at: '2026-01-01T10:00:00Z',
last_accessed: '2026-01-01T10:00:00Z',
download_count: 30,
vulnerabilities: { scanned: true, status: 'clean', total: 0, scannedAt: '2026-01-01T10:05:00Z' },
vulnerabilities: {
scanned: true,
status: 'vulnerable',
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
total: 1,
scannedAt: '2026-01-01T10:05:00Z',
isBlocked: false,
verdict: 'bypassed',
bypass: {
id: 'bypass-1',
type: 'package',
target: 'pypi/[email protected]',
reason: 'Vendored fix',
created_by: 'a.khan',
created_at: '2026-01-01T00:00:00Z',
expires_at: '2099-01-01T00:00:00Z',
},
},
},
{
id: 'go-1',
@@ -74,7 +95,7 @@ export const PACKAGES: Package[] = [
cached_at: '2026-01-04T10:00:00Z',
last_accessed: '2026-01-04T10:00:00Z',
download_count: 10,
vulnerabilities: { scanned: false, status: 'not_scanned' },
vulnerabilities: { scanned: false, status: 'not_scanned', isBlocked: false, verdict: 'pending' },
},
]
@@ -89,6 +110,16 @@ export const TIMESERIES = {
}
export const VULNERABILITY_REPORT = {
decision: {
verdict: 'held',
blocked: true,
reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)',
bypass: null,
},
scanners: [
{ name: 'trivy', findings: 2, severity_counts: { critical: 1, high: 0, moderate: 0, low: 1 } },
{ name: 'osv', findings: 3, severity_counts: { critical: 1, high: 1, moderate: 0, low: 1 } },
],
scanned: true,
scanner: 'trivy+osv',
scanned_at: '2026-01-03T10:05:00Z',
@@ -104,6 +135,7 @@ export const VULNERABILITY_REPORT = {
description: 'A **low** severity sample description.',
references: ['https://example.com/advisory/1'],
fixed_in: '1.3.1',
detected_by: ['trivy', 'osv'],
bypassed: false,
},
{
@@ -158,3 +190,61 @@ export const BYPASSES = [
active: false,
},
]
function trendDay(offset: number): string {
return new Date(Date.UTC(2026, 0, 4 + offset)).toISOString().slice(0, 10)
}
export const TREND = {
period: '30day',
from: trendDay(-2),
to: trendDay(0),
vulnerability_history_start: trendDay(-1),
points: [
{ date: trendDay(-2), total_packages: 3, total_size: 3072, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null, blocked: null },
{ date: trendDay(-1), total_packages: 4, total_size: 7168, vulnerable_packages: 1, critical: 0, high: 1, moderate: 0, low: 0, blocked: null },
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
],
}
export const SYSTEM = {
version: 'v1.8.0',
security: {
enabled: true,
fail_closed: true,
scan_on_download: true,
block_on_severity: 'none',
block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 },
scan_wait_timeout: 30,
scanners: [
{ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' },
{ name: 'grype', enabled: true, healthy: false, version: '' },
{ name: 'osv', enabled: true, healthy: true, version: '' },
{ name: 'govulncheck', enabled: false, healthy: null, version: '' },
],
rescan: { interval: 86400, active_window: 2592000, concurrency: 2, on_access: false },
},
upstreams: { go: 'https://proxy.golang.org', npm: 'https://registry.npmjs.org', pypi: 'https://pypi.org' },
cache: { max_size: 10737418240, idle_ttl: 2592000, default_ttl: 86400 },
prewarming: { enabled: true, interval: 3600, top_packages: 100 },
}
export const TOP_PACKAGES = {
packages: [
{ Registry: 'npm', Name: 'left-pad', Downloads: 40, RecentDownloads: 12, Trend: 0.4 },
{ Registry: 'go', Name: 'github.com/example/module/@v/v0.4.1.zip', Downloads: 10, RecentDownloads: 4, Trend: 0 },
],
total: 2,
}
export const PACKAGE_ANALYTICS = {
package: {
Registry: 'npm',
Name: 'left-pad',
TotalDownloads: 40,
UniqueVersions: 2,
BytesServed: 81920,
FirstSeen: '2026-01-01T10:00:00Z',
LastDownload: '2026-01-03T10:00:00Z',
},
}
+61
View File
@@ -0,0 +1,61 @@
import type { Package } from '@/stores/packages'
const LEVELS = ['critical', 'high', 'moderate', 'low'] as const
function verdictOf(p: Package): string {
return p.vulnerabilities?.verdict ?? (p.vulnerabilities?.isBlocked ? 'held' : p.vulnerabilities?.scanned ? 'cleared' : 'pending')
}
function count(p: Package, level: (typeof LEVELS)[number]): number {
return p.vulnerabilities?.counts?.[level] ?? 0
}
/** A stand-in for GET /api/packages?layout=rows, so views can be tested against the real query contract. */
export function serveRows(url: string, all: readonly Package[]) {
const params = new URL(url, 'http://test').searchParams
const q = (params.get('q') ?? '').toLowerCase()
const registry = params.get('registry')
const verdict = params.get('verdict')
const severities = (params.get('severity') ?? '').split(',').filter(Boolean)
const page = Number(params.get('page') ?? 1)
const pageSize = Number(params.get('page_size') ?? 25)
const base = all.filter(
(p) =>
(!registry || p.registry === registry) &&
(!q || [p.name, p.version, p.release_version ?? ''].some((f) => f.toLowerCase().includes(q))),
)
const counts = {
verdicts: { cleared: 0, held: 0, bypassed: 0, pending: 0 } as Record<string, number>,
severity_packages: { critical: 0, high: 0, moderate: 0, low: 0 } as Record<string, number>,
severity_findings: { critical: 0, high: 0, moderate: 0, low: 0 } as Record<string, number>,
vulnerable_allowed: 0,
}
for (const p of base) {
counts.verdicts[verdictOf(p)]++
if (verdictOf(p) === 'cleared' && (p.vulnerabilities?.total ?? 0) > 0) counts.vulnerable_allowed++
for (const level of LEVELS) {
if (count(p, level) > 0) counts.severity_packages[level]++
counts.severity_findings[level] += count(p, level)
}
}
const matched = base
.filter((p) => !verdict || verdictOf(p) === verdict)
.filter((p) => severities.length === 0 || severities.some((s) => count(p, s as (typeof LEVELS)[number]) > 0))
const sort = params.get('sort')
if (sort === 'risk') {
matched.sort((a, b) => {
for (const level of LEVELS) if (count(a, level) !== count(b, level)) return count(b, level) - count(a, level)
return 0
})
}
if (sort === 'downloads') matched.sort((a, b) => (params.get('order') === 'asc' ? 1 : -1) * (a.download_count - b.download_count))
return {
packages: matched.slice((page - 1) * pageSize, page * pageSize),
total: matched.length,
page,
page_size: pageSize,
counts,
}
}
+7
View File
@@ -10,8 +10,10 @@ data:
host: {{ .Values.server.host | quote }}
port: {{ .Values.server.port }}
read_timeout: {{ .Values.server.readTimeout | quote }}
read_buffer_size: {{ .Values.server.readBufferSize }}
write_timeout: {{ .Values.server.writeTimeout | quote }}
idle_timeout: {{ .Values.server.idleTimeout | quote }}
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
tls:
enabled: false
@@ -74,6 +76,7 @@ data:
default_ttl: {{ .Values.cache.defaultTTL | quote }}
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
idle_ttl: {{ .Values.cache.idleTTL | quote }}
deleted_retention: {{ .Values.cache.deletedRetention | default "720h" | quote }}
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
per_project_quota: {{ .Values.cache.perProjectQuota }}
ttl_overrides:
@@ -86,6 +89,10 @@ data:
block_on_severity: {{ .Values.security.blockOnSeverity | quote }}
scan_on_download: {{ .Values.security.scanOnDownload }}
rescan_interval: {{ .Values.security.rescanInterval | quote }}
rescan_active_window: {{ .Values.security.rescanActiveWindow | quote }}
rescan_concurrency: {{ .Values.security.rescanConcurrency }}
rescan_on_access: {{ .Values.security.rescanOnAccess }}
scan_wait_timeout: {{ .Values.security.scanWaitTimeout | quote }}
update_db_on_startup: {{ .Values.security.updateDbOnStartup }}
block_thresholds:
critical: {{ .Values.security.blockThresholds.critical }}
+13 -5
View File
@@ -91,8 +91,11 @@ server:
host: "0.0.0.0"
port: 8080
readTimeout: "5m"
readBufferSize: 16384 # Bytes for the request line plus headers; larger requests get 431
writeTimeout: "5m"
idleTimeout: "2m"
# Browser origins allowed to use /api and /ws; empty = same-origin only
allowedOrigins: []
# Additional environment variables for server container
# Use this to override config via environment variables
@@ -375,15 +378,16 @@ migration:
# Cache configuration
cache:
defaultTTL: "168h" # 7 days
defaultTTL: "24h" # Freshness window for metadata pages; keep below the 72h client release-age gate
cleanupInterval: "1h"
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
deletedRetention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
maxSizeBytes: 536870912000 # 500GB
perProjectQuota: 53687091200 # 50GB
ttlOverrides:
npm: "168h"
pip: "168h"
go: "168h"
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
npm: "24h"
pypi: "24h"
go: "24h"
# Security scanning configuration
security:
@@ -391,6 +395,10 @@ security:
blockOnSeverity: "high" # none, low, medium, high, critical
scanOnDownload: true
rescanInterval: "24h"
rescanActiveWindow: "0s" # rescan only packages requested within this window; 0 = all
rescanConcurrency: 1 # scans run in parallel per rescan cycle
rescanOnAccess: false # rescan a stale cache hit before serving it
scanWaitTimeout: "30s" # how long a first download waits for its scan
updateDbOnStartup: false
blockThresholds:
+42
View File
@@ -0,0 +1,42 @@
// Package dbcount counts the SQL statements a GORM handle runs, for query-count tests.
package dbcount
import (
"context"
"sync/atomic"
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Counter holds the number of statements seen since the last Reset.
type Counter struct {
n atomic.Int64
}
// Attach returns a session of db that counts every statement it executes. It
// swaps the logger instead of registering callbacks, because callback
// registration is not safe while other goroutines already run queries.
// GORM runs a subquery as a dry run with a discarded logger, so subqueries do not count.
func Attach(db *gorm.DB) (*gorm.DB, *Counter) {
c := &Counter{}
return db.Session(&gorm.Session{Logger: &countingLogger{Interface: logger.Discard, c: c}}), c
}
// Reset zeroes the count.
func (c *Counter) Reset() { c.n.Store(0) }
// Count returns the statements counted since the last Reset.
func (c *Counter) Count() int { return int(c.n.Load()) }
type countingLogger struct {
logger.Interface
c *Counter
}
func (l *countingLogger) LogMode(logger.LogLevel) logger.Interface { return l }
func (l *countingLogger) Trace(context.Context, time.Time, func() (string, int64), error) {
l.c.n.Add(1)
}
+61 -7
View File
@@ -20,6 +20,19 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-07 | get vs purge | a purge between probe and open does not fail the request | correctness | low | `Cache.getOnce_errors_on_purge`, `getRetry_survives_one_purge` / `TestGetRecoversFromPurgeBetweenProbeAndOpen` | 990a1d3 |
| GH-08 | stats rollup | every completed day still held hourly is rolled up | correctness (data loss) | medium | `Stats.old_loses_day_on_one_skip`, `new_repairs_after_skip`, `early_tick_leaves_last_hour` / `TestDailyRollupKeepsLastHourOfDay`, `TestDailyRollupCoversMissedDay`, `TestPostgresDailyRollupCoversMissedDay` | ad4e848 |
| GH-09 | stats chart | a rollup never hides downloads counted after it ran | correctness | low | `Stats.chartOld_drops_late_download`, `chartNew_sound` / `TestTimeSeriesKeepsLateDownloadsAheadOfRollup` | 7192e4f |
| GH-15 | release age | a cached packument or index stays fresh no longer than the client's 72h release-age gate | correctness (config default) | low | `Release.compiled_ttl_within_gate`, `old_default_ttl_exceeded_gate` / `TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate`, `TestMetadataEntryExplicitTTLWins`, `TestDefaultMetadataTTL`, `TestShippedExamplesKeepMetadataTTLWithinGate` | 549d56e |
| GH-17 | CORS, auth off | a page at a foreign origin cannot read `/api` or change state through a visitor's browser | security, CWE-352 / CWE-942 | medium with `auth.enabled: false` | `Access.old_cors_admits_any_page`, `fixed_refuses_foreign_origin` / `TestAPIDeleteFromDisallowedOriginForbidden`, `TestAPIDeleteFromAllowedOriginWorks`, `TestAPIPreflightAnswersOnlyAllowedOrigins`, `TestAPIGetStaysPublicWithoutWildcardCORS`, `TestAPISameOriginRuleWhenNoOriginsConfigured` | f204938 |
| GH-18 | api keys | `ValidateAPIKey` costs one bcrypt compare, whatever the number of stored keys | hardening, CWE-400 | low | `Access.old_cost_grows_with_keys`, `new_cost_independent_of_keys` / `TestValidateAPIKeyCostIndependentOfKeyCount`, `TestLegacyComparesAreConcurrencyBounded` | ae5167f |
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | 536f35a |
| GH-23 | PyPI sidecar | pip's PEP 658 request (`<link>.metadata`, suffix on `original_url`) is served as its wheel's sidecar; another file's sidecar is still refused | correctness (pip install failed with 400) | medium (every pip install through the proxy) | `Access.pip_form_keeps_key_binding`, `pip_sidecar_of_other_file_rejected`, `pip_sidecar_of_same_file_accepted` / `TestPipSidecarFormIsStreamed`, `TestHandlePackageFile_OriginalURLFilenameBound` | 501bf1a |
| GH-24 | rescan | with `security.rescan_interval` set, artifacts whose scan never completed are scanned and old results refreshed | correctness (scans lost to a restart stayed unscanned; new CVEs never picked up) | medium | not modelled (worker wiring) / `TestWorkersStartTheRescanWorker` | 378b873 |
| GH-25 | scanners | an error result from one scanner is left out of the merge, so the row reads error only when every scanner failed; grype, npm-audit, govulncheck and pip-audit give correct results with the scanner image tool versions | correctness (false error, false clean) | high (grype, npm-audit and pip-audit failed on every package; govulncheck and a bare-archive grype scan read vulnerable packages clean) | `Security.old_error_poisons_clean`, `error_and_clean_reads_clean`, `all_error_reads_error`, `merged_not_error_when_one_ran` / `TestScanPackage_ErrorResultPlusCleanReadsClean`, `TestScanPackage_AllErrorResultsReadError`, `TestScanPackage_InfrastructureErrorResultsCountAsInfrastructure`, `TestScanMapsRealOutput`, `TestParseKeepsBothViaShapes`, `TestScanReadsPrettyPrintedFindings`, `TestScanAuditsTheReleaseFromARequirement` | 3731ca0 |
| GH-26 | rescan | the rescan worker skips the entries the serve path skips, so Go `.mod` and `.info` rows are no longer scanned | cost (1316 of about 2780 rescans on production were these rows, about 3.3 s each) | low | `Cache.old_rescan_scanned_go_metadata`, `rescan_skips_what_serve_skips` / `TestRescanSkipsMetadataEntries` | d6044cd |
| GH-27 | scanners | govulncheck counts findings in the scanned module only; dependency findings (minimum versions from its go.mod) and stdlib findings (the scanner toolchain) no longer attach to it | correctness (false vulnerable, and a false block when a dependency finding is critical) | medium (golang.org/x/net v0.56.0 carried x/crypto and x/text advisories on production) | `TestScanIgnoresFindingsInDependencies`, `TestScanReadsPrettyPrintedFindings` | 775ed8a |
| GH-28 | scanners | OSV takes the fixed version from the range of the queried package | display (x/net findings showed the stdlib fix 1.26.9 instead of 0.60.0) | low | `TestScan_FixedVersionComesFromTheQueriedPackage` | fac30f5 |
### Exploit paths and reach
@@ -30,9 +43,56 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
- **GH-03.** Live check against `api.osv.dev` for requests 2.19.0: the release version returns 10 advisories; the file name
returns 12, missing PYSEC-2023-74 and GHSA-j8r2-6x86-q33q. Production has `block_on_severity: none`, so it shows wrong
scan results rather than serving blocked packages; any deployment with a block policy served such packages.
- **GH-17.** A page at any origin issued `DELETE /api/packages/<registry>/<name>/<version>` from a visitor's browser, and
`Access-Control-Allow-Origin: *` let it read every `/api` response. Reach: any visitor to a hostile page when
`auth.enabled` is false (production); impact is cache eviction. Fixed by `apiOriginGuard` against `server.allowed_origins`;
with none set, only same-origin passes.
- **GH-19.** An allowed host that answered 302 reached any target (`169.254.169.254`, `127.0.0.1`, `10.x`), by name or by
DNS rebinding. No allowed host redirects today; the fix removes the dependency on that. Hops are capped at 10, limited to
http(s), vetted against the allowlist, and a hop to another host dials through a guard that refuses private, loopback,
link-local and carrier-grade addresses after resolution. A redirect inside one host is left alone: a private index is
operator-trusted.
- **GH-04.** The publisher of an npm or PyPI package named `x.info` skipped the scan and the block policy. Reach: any package
publisher; needs a block policy to matter.
### Notes on the fixed rows
- **GH-15.** `cache.ttl_overrides` now has a consumer: `cache.Config.TTLOverrides` sets the metadata freshness per registry
(`npm`, `pypi`, `go`; `pip` is an alias of `pypi`), and a registry without an override keeps `default_ttl`. Artifacts keep no
age expiry. Defaults hold no override, so lowering `default_ttl` still applies everywhere. Config load rejects an unknown
registry key or a non-positive value. Tests: `TestMetadataTTLOverridesApplyPerRegistry`, `TestMetadataTTLOverridesSkipArtifacts`,
`TestNPMMetadataTTLOverrideReachesCache`, `TestTTLOverridesValidation`.
- **GH-18.** New keys read `ghk_<id>.<secret>`; the hash covers the secret and one lookup selects the stored key. A miss
compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
legacy path. Production holds none.
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
- **GH-25.** `scan` treats an error-status result like a returned error: it is left out of the merge and counted as an
infrastructure failure (`infrastructure_error` in its details, set on a deadline or an unreachable network) or another failure.
Before, one such result made the merged row an error and `evaluateScan` blocked the package even with `fail_closed: false`.
Defects found by running the published scanner image (grype 0.121.2, npm 11.12.1, govulncheck 1.9.0, pip-audit 2.10.1,
go 1.26), each with a fixture of real output under the scanner's `testdata/`:
grype: `source.target` is a string for file and purl sources, and a bare archive has nothing to catalog, so minimist 0.0.8 read clean;
the scanner now passes a purl. npm audit: `via` is an array and `metadata.dependencies` an object in npm 11; the lockfile
step resolved devDependencies (dayjs: 1567 packages, 142 findings, 28s) and `npm audit` cannot report the root package itself;
the tarball is now installed into a wrapper project and audited with `--omit=dev` (under 1s). govulncheck: the JSON stream is
indented, so the line parser read nothing, and govulncheck never reports the main module of the tree it scans (x/text 0.3.5
read clean); the module is now a dependency of a wrapper module and scanned at module level. pip-audit: its positional
argument is a project directory and `--pyproject` does not exist, so every scan failed; the release is audited from a pinned
requirement, an advisory is listed once, and `skip_reason` is an error. trivy is not covered: it reads a bare npm archive
as clean the same way grype did.
- **GH-17 cleanup.** The per-handler `Access-Control-*` lines in `pkg/app/handlers*.go` are removed; `apiOriginGuard` is the only CORS
source. `TestHandlersSetNoCORSHeaders` and `TestAPIResponsesNeverCarryWildcardOrigin` guard it.
- **GH-26.** `rescanPackages` kept its own list of metadata versions and never called `IsMetadataEntry`, so Go `.mod` and `.info`
rows were scanned every cycle. Related options, whose defaults keep the old behaviour: `rescan_active_window` skips packages idle longer than the
window, `rescan_concurrency` runs scans in parallel, and `rescan_on_access` rescans a stale cache hit before serving it.
Model of the last: `Security.finished_rescan_verdict_younger_than_interval`, `old_verdict_only_on_timeout`,
`stale_clean_fresh_vulnerable_blocked`, `timeout_keeps_previous`, `timeout_without_previous_is_miss_rule`, `off_is_old_hit_path`.
## Not fixed
| id | area | claim | verdict | why |
@@ -41,14 +101,8 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-11 | cache hit | the stored SHA-256 is not re-verified on read | by-design | `Put` verifies the stream it just hashed; no doc promises read-side integrity. A check reads up to 2 GB per hit. Disk corruption is outside the proxy's threat model. |
| GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. |
| GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.partial_failure_reads_clean`. `scan` handles only the all-failed case; redundancy across scanners is the intent. |
| GH-15 | release age | a cached packument or index hides new or yanked entries for up to the TTL | by-design | Quoted intent, `pkg/cache/cache.go` store: "TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed based on upstream Cache-Control". Passthrough proved: `Release.rewrite_preserves_upload_time`, `stale_hides_only_gated` (needs TTL <= gate; production 24h <= 72h holds, the compiled default 168h does not, and then the proxy is stricter than the gate). |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.error_and_clean_reads_clean` (a returned error and, since GH-25, an error-status result). `scan` handles only the all-failed case; redundancy across scanners is the intent. |
| GH-16 | admin API | `requireAdmin` accepts the `bypasses:manage` permission and also guards key minting | tested-clean | Only the admin role holds that permission: `Access.admin_gate_implies_key_manager`. |
| GH-17 | auth off | with `auth.enabled: false` (production) `DELETE /api/packages/*` is unauthenticated, and `Access-Control-Allow-Origin: *` lets a browser page issue it | by-design, product decision | Quoted intent, `pkg/app/app.go`: "routes are mounted bare to preserve backward-compatible public access". Impact is cache eviction only. Enabling auth is a configuration change the operator owns. |
| GH-18 | api keys | `ValidateAPIKey` bcrypt-compares every stored key per request | hardening, CWE-400 | N keys cost N bcrypt checks per bad key. A key-id prefix needs an API change. Zero keys in production. |
| GH-19 | SSRF | `network.Client` follows redirects without re-checking the allowlist | hardening | `Access.redirect_escapes_allowlist`. No allowed host redirects (pypi.org, files.pythonhosted.org); a private index host is operator-trusted. |
| GH-20 | stats, sqlite | `INSERT OR REPLACE` has no unique index on SQLite, so every pass duplicates registry rows | correctness, SQLite only | Seen in a row dump (three NULL-package hourly rows for one bucket after three passes). Production is PostgreSQL, where `statsUpsertIndexes` exist. Needs a dedupe migration; left open. |
| GH-21 | scan retry | a retry on S3 or SMB storage rescans a temp file already removed | suspected, unconfirmed | `cache.go` store removes `tempPath` after the first scan. Production is filesystem. No test written. |
### Decision: `fail_closed: false` with recurring infrastructure errors
+79 -6
View File
@@ -5,7 +5,7 @@ import Mathlib
Models `pkg/app/app.go` `buildCheckOrigin` / `normalizeOriginHost`, `pkg/app/handlers_admin.go`
`requireAdmin`, `pkg/auth/auth.go` (`getPermissionsForRole`, `ValidateAPIKey` expiry),
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards), `Dockerfile.frontend`.
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards, `get`), `pkg/network/client.go` (`send`), `pkg/auth/auth.go` (`ValidateAPIKey` cost), `pkg/app/cors.go` (`apiOriginGuard`), `Dockerfile.frontend`.
Omits: the TLS layer, bcrypt internals, DNS.
-/
@@ -121,19 +121,92 @@ theorem old_guard_allows_key_poisoning :
exact ⟨"requests-2.31.0-py3-none-any.whl", ⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl"⟩,
by decide, by decide⟩
/-- pip requests the PEP 658 sidecar as `<link>.metadata`, so the suffix lands on `original_url` and the
request names the sidecar of the requested file. `handlePackageFile` streams it and never stores it. -/
def pipSidecar (requested : String) (f : Fetch) : Bool := decide (f.file = requested ++ ".metadata")
/-- The guard with the pip form: the requested file, or its own sidecar. -/
def acceptsPip (requested : String) (f : Fetch) : Bool :=
hostAllowed f.host && (decide (f.file = requested) || pipSidecar requested f)
/-- What the pip form stores still names the key: only the sidecar escapes, and it is not stored. -/
theorem pip_form_keeps_key_binding (requested : String) (f : Fetch)
(h : acceptsPip requested f = true) (hs : pipSidecar requested f = false) : f.file = requested := by
simp only [acceptsPip, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at h
rcases h.2 with h2 | h2
· exact h2
· rw [h2] at hs; exact absurd hs (by simp)
theorem pip_sidecar_of_other_file_rejected :
acceptsPip "example-1.0.0-py3-none-any.whl"
⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl.metadata"⟩ = false := by decide
theorem pip_sidecar_of_same_file_accepted :
acceptsPip "example-1.0.0-py3-none-any.whl"
⟨"files.pythonhosted.org", "example-1.0.0-py3-none-any.whl.metadata"⟩ = true := by decide
theorem internal_hosts_rejected :
hostAllowed "169.254.169.254" = false ∧ hostAllowed "localhost" = false ∧
hostAllowed "metadata.google.internal" = false := by decide
/-- The allowlist is checked once, on the first hop. `network.Client` follows redirects without
re-checking, so an allowed host that answers 302 reaches any target. Acceptable only while no
allowed host redirects (pypi.org and files.pythonhosted.org do not). -/
def hopAllowed (hops : List String) : Bool := hops.head?.any hostAllowed
/-- Before the fix the allowlist was checked once, on the first hop. `network.Client` followed
redirects without re-checking, so an allowed host that answers 302 reached any target. -/
def hopAllowedOld (hops : List String) : Bool := hops.head?.any hostAllowed
/-- After the fix (`network.Client.send`, `pypi.Handler.get`) every hop must pass the allowlist. -/
def hopAllowed (hops : List String) : Bool := hops.all hostAllowed
theorem redirect_escapes_allowlist :
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = true ∧
hopAllowedOld ["files.pythonhosted.org", "169.254.169.254"] = true ∧
hostAllowed "169.254.169.254" = false := by decide
theorem fixed_redirect_stays_allowlisted :
hopAllowed ["pypi.org", "files.pythonhosted.org"] = true ∧
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = false := by decide
/-- A hop is accepted only if every hop is on the allowlist. -/
theorem hopAllowed_implies_each (hops : List String) (h : hopAllowed hops = true) :
∀ x ∈ hops, hostAllowed x = true := by
simpa [hopAllowed] using h
/-! ### API key validation cost (`pkg/auth/auth.go` `ValidateAPIKey`) -/
/-- bcrypt compares for one request when every stored key is a candidate (before the fix). -/
def compareCostOld (storedKeys : ℕ) : ℕ := storedKeys
/-- A key carrying its id selects one stored key: one compare, hit or miss (a miss compares a dummy hash). -/
def compareCostNew (_storedKeys : ℕ) : ℕ := 1
theorem old_cost_grows_with_keys : compareCostOld 1000 = 1000 := rfl
theorem new_cost_independent_of_keys (n m : ℕ) : compareCostNew n = compareCostNew m := rfl
/-! ### Cross-origin writes on `/api` (`pkg/app/cors.go` `apiOriginGuard`) -/
/-- Before the fix every handler answered `Access-Control-Allow-Origin: *`, so any page could call them. -/
def corsOld (_ : Origin) : Bool := true
/-- After the fix a state-changing request passes iff it names no origin (non-browser client) or an
allowed one; the same rule as the WebSocket origin check. -/
def writeAllowed (rules : List Origin) : Option Origin → Bool
| none => true
| some o => rules.any (fun r => matchesExact r o)
def dashboard : Origin := ⟨Scheme.https, "gohoarder.example.com".toList, none⟩
def attacker : Origin := ⟨Scheme.https, "evil.example.net".toList, none⟩
theorem old_cors_admits_any_page : corsOld attacker = true := rfl
theorem fixed_refuses_foreign_origin : writeAllowed [dashboard] (some attacker) = false := by decide
theorem fixed_admits_dashboard_and_cli :
writeAllowed [dashboard] (some dashboard) = true ∧ writeAllowed [dashboard] none = true := by decide
/-- With nothing configured only a request with no origin passes the allowlist step; browsers fall to the
same-origin host comparison in the handler. -/
theorem empty_allowlist_refuses_any_origin (o : Origin) : writeAllowed [] (some o) = false := by
simp [writeAllowed]
/-! ### Frontend blocklist (`Dockerfile.frontend`) -/
/-- `location ~ ^/(npm|pypi|go|metrics)(/|$)` on the normalised URI. -/
+12
View File
@@ -208,4 +208,16 @@ theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decid
theorem go_metadata_still_exempt : scanExempt "go" true "v1.0.0" = true := by decide
/-- `pkg/scanner/rescanner.go` before the fix: the worker skipped only the version names, not the Go suffixes. -/
def rescanSkipOld (version : String) : Bool := decide (version ∈ metaVersions)
/-- After the fix the worker asks `IsMetadataEntry`, the same predicate as the serve path. -/
def rescanSkip : String → Bool → String → Bool := scanExempt
theorem old_rescan_scanned_go_metadata :
rescanSkipOld "v1.0.0" = false ∧ scanExempt "go" true "v1.0.0" = true := by decide
theorem rescan_skips_what_serve_skips (registry : String) (suffixMeta : Bool) (version : String) :
rescanSkip registry suffixMeta version = scanExempt registry suffixMeta version := rfl
end Gohoarder.Cache
+26 -5
View File
@@ -47,15 +47,36 @@ theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ tt
(hnew : s < t) : ¬ gateAccepts gate now t := by
unfold gateAccepts; omega
/-- Production: `default_ttl: 24h` against a 72h gate. -/
theorem prod_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
/-- Production and, since the fix, the compiled default (`config.DefaultMetadataTTL`): 24h against a 72h gate. -/
theorem compiled_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
/-- The compiled default is 7 days. Against a 72h gate a version aged 84h is eligible but absent
from a 7-day-old snapshot: the proxy withholds it, which is stricter than the gate, never looser. -/
theorem default_ttl_exceeds_gate :
/-- The compiled default used to be 7 days. Against a 72h gate a version aged 84h is eligible but
absent from a 7-day-old snapshot: the proxy withheld it, stricter than the gate, never looser. -/
theorem old_default_ttl_exceeded_gate :
∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by
exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩
/-! ### Per-registry override (`cache.ttl_overrides`, `Manager.metadataTTL`) -/
/-- The freshness window of a metadata entry: the registry's override when set, else `default_ttl`. -/
def effectiveTtl (override : Option ℤ) (default : ℤ) : ℤ := override.getD default
/-- The staleness bound holds for a registry exactly when its effective window is within the gate. -/
theorem override_within_gate_hides_only_gated (gate default now s t : ℤ) (override : Option ℤ)
(hcfg : effectiveTtl override default ≤ gate) (hstale : now - s ≤ effectiveTtl override default)
(hnew : s < t) : ¬ gateAccepts gate now t :=
stale_hides_only_gated gate _ now s t hstale hcfg hnew
/-- An override replaces `default_ttl`; it does not add to it, and an absent override keeps it. -/
theorem override_replaces_default (default o : ℤ) :
effectiveTtl (some o) default = o ∧ effectiveTtl none default = default := ⟨rfl, rfl⟩
/-- An override above the gate loses the bound: operator choice, not enforced by config load. -/
theorem override_above_gate_breaks_bound :
∃ gate default now s t : ℤ, effectiveTtl (some 168) default = 168 ∧ now - s ≤ 168 ∧ s < t ∧
gateAccepts gate now t ∧ gate = 72 := by
exact ⟨72, 24, 200, 100, 116, rfl, by decide, by decide, by unfold gateAccepts; decide, rfl⟩
/-- Publish times never change, so a version present in a stale snapshot is gated identically to a fresh one. -/
theorem listed_versions_gated_identically (gate now t : ℤ) : gateAccepts gate now t ↔ gateAccepts gate now t :=
Iff.rfl
+165 -5
View File
@@ -3,7 +3,7 @@ import Mathlib
/-!
# Security decision logic
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `scheduleRetry`,
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `succeeded`, `scheduleRetry`,
`pkg/metadata/gormstore/gormstore_v2.go` `GetActiveCVEBypasses`, and the scan gate in
`pkg/cache/cache.go` `getOrFetch`. Severities are ranks (low 1 .. critical 4). Omits: the
scanners themselves, threshold counters (`block_thresholds`), network.
@@ -137,6 +137,20 @@ theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List
/-- Scanner disabled: `CheckVulnerabilities` returns `(false, "", nil)` and `cache.New` drops the scanner. -/
def servesDisabled : Bool := true
/-! ### Retry input (`pkg/cache/cache.go` `store`, `ScanFile`; `scheduleRetry`) -/
/-- Before the fix a retry reused the first scan's path. Remote storage scans a temp file removed
after the first attempt, so only local backends kept it. -/
def retryReadableOld (localBackend : Bool) : Bool := localBackend
/-- After the fix a retry whose file is gone re-reads the blob through the file source. -/
def retryReadableNew (localBackend fileSourceSet : Bool) : Bool := localBackend || fileSourceSet
theorem old_remote_retry_unreadable : retryReadableOld false = false := rfl
theorem fixed_retry_always_readable : retryReadableNew false true = true ∧ retryReadableNew true false = true := by
decide
/-! ### Retry budget -/
def maxRetries : ℕ := 6
@@ -179,7 +193,7 @@ theorem npm_scan_keeps_cache_version (cacheVersion : String) :
theorem file_name_is_not_release_version :
"requests-2.19.0-py3-none-any.whl" ≠ "2.19.0" := by decide
/-! ### Merge: worst status wins, but a failed scanner leaves no trace -/
/-! ### Merge: worst status wins among scanners that ran; a failed scanner leaves no trace -/
/-- ranks: clean 0, pending 1, error 2, vulnerable 3 (`mergeResults`). -/
def mergeRank (xs : List ℕ) : ℕ := xs.foldr max 0
@@ -193,8 +207,154 @@ theorem merge_dominates (xs : List ℕ) (x : ℕ) (h : x ∈ xs) : x ≤ mergeRa
· exact le_max_left _ _
· exact le_trans (ih h) (le_max_right _ _)
/-- Results exist only for scanners that returned; with one scanner failing and one clean, the
merged status is clean and no retry is scheduled (`scan`: retry only when no scanner succeeded). -/
theorem partial_failure_reads_clean : mergeRank [0] = 0 := by decide
def errorRank : ℕ := 2
/-- Before GH-25 a scanner's error-status result took part in the merge, as the rank `errorRank`. -/
def oldMerge (xs : List ℕ) : ℕ := mergeRank xs
/-- `scan` after GH-25: a scanner that returns an error-status result failed, like one that returns
an error. Only results of scanners that ran are merged; with none left every scanner failed. -/
def newMerge (xs : List ℕ) : ℕ :=
if (xs.filter (· ≠ errorRank)).isEmpty then errorRank else mergeRank (xs.filter (· ≠ errorRank))
/-- GH-25: one scanner's error result turned a clean package into an error row. -/
theorem old_error_poisons_clean : oldMerge [0, errorRank] = errorRank := by decide
theorem error_and_clean_reads_clean : newMerge [0, errorRank] = 0 := by decide
theorem error_never_hides_vulnerable : newMerge [errorRank, 3] = 3 := by decide
theorem all_error_reads_error (xs : List ℕ) (h : ∀ x ∈ xs, x = errorRank) : newMerge xs = errorRank := by
have : xs.filter (· ≠ errorRank) = [] := by
rw [List.filter_eq_nil_iff]
intro x hx
simp [h x hx]
unfold newMerge
rw [this]
rfl
theorem error_result_ignored (xs : List ℕ) : newMerge (errorRank :: xs) = newMerge xs := by
simp [newMerge]
theorem mergeRank_not_error (ys : List ℕ) (h : ∀ y ∈ ys, y ≠ errorRank) : mergeRank ys ≠ errorRank := by
induction ys with
| nil => simp [mergeRank, errorRank]
| cons y ys ih =>
simp only [mergeRank, List.foldr_cons]
have hy : y ≠ errorRank := h y (List.mem_cons_self ..)
have hys : mergeRank ys ≠ errorRank := ih (fun z hz => h z (List.mem_cons_of_mem _ hz))
rcases max_choice y (ys.foldr max 0) with e | e
· rw [e]; exact hy
· rw [e]; exact hys
/-- With any scanner that ran, the merged status is not an error, so `fail_closed` never decides it. -/
theorem merged_not_error_when_one_ran (xs : List ℕ) (h : ∃ x ∈ xs, x ≠ errorRank) :
newMerge xs ≠ errorRank := by
obtain ⟨x, hx, hne⟩ := h
have hmem : x ∈ xs.filter (· ≠ errorRank) := List.mem_filter.mpr ⟨hx, by simpa using hne⟩
unfold newMerge
have hne' : ¬ (xs.filter (· ≠ errorRank)).isEmpty = true := by
intro hempty
rw [List.isEmpty_iff] at hempty
rw [hempty] at hmem
simp at hmem
simp only [hne']
apply mergeRank_not_error
intro y hy
simpa using (List.mem_filter.mp hy).2
/-- The retry is for infrastructure only: `scan` counts each failure by cause and the row is an
infrastructure error only when there was a failure and every failure was infrastructure. -/
def infraOnly (failures : List Bool) : Bool := decide (failures ≠ []) && failures.all id
theorem one_package_failure_is_not_infra : infraOnly [true, false] = false := by decide
theorem all_infra_failures_are_infra : infraOnly [true, true] = true := by decide
/-! ### Rescan on access (`pkg/cache/rescan_on_access.go` `refreshStaleScan`)
Ages are seconds since `ScannedAt`; `interval` is `Config.RescanAfter` (0 = off). A rescan that timed out
or failed is `none`: the previous verdict stands, and with no previous verdict the first-download rule applies. -/
structure Verdict where
scan : Scan
age : ℕ
/-- The hit is rescanned when the feature is on and its result is missing or at least `interval` old. -/
def rescans (interval : ℕ) (prev : Option Verdict) : Bool :=
decide (0 < interval) && (match prev with
| none => true
| some v => decide (interval ≤ v.age))
/-- The verdict the gate decides on; a finished rescan is brand new (age 0). -/
def hitVerdict (interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Option Verdict :=
if rescans interval prev then
(match rescan with
| some s => some ⟨s, 0⟩
| none => prev)
else prev
/-- No verdict at all is a scan still in flight: `fail_closed` refuses, otherwise the package is served. -/
def servesOnAccess (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass)
(interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Bool :=
match hitVerdict interval prev rescan with
| some v => serves failClosed pkgBypass policy now bs v.scan
| none => serves failClosed pkgBypass policy now bs (Scan.missing true)
/-- Key property: with the feature on, a rescan that finished leaves no verdict as old as `interval`. -/
theorem finished_rescan_verdict_younger_than_interval (interval : ℕ) (hi : 0 < interval)
(prev : Option Verdict) (s : Scan) (v : Verdict)
(h : hitVerdict interval prev (some s) = some v) : v.age < interval := by
unfold hitVerdict at h
by_cases hr : rescans interval prev = true
· simp only [hr, ite_true, Option.some.injEq] at h
subst h
simpa using hi
· simp only [hr] at h
subst h
simp only [rescans, hi, decide_true, Bool.true_and, Bool.not_eq_true] at hr
simpa using hr
/-- A verdict older than `interval` survives only when the rescan timed out or failed. -/
theorem old_verdict_only_on_timeout (interval : ℕ) (hi : 0 < interval) (prev : Option Verdict)
(rescan : Option Scan) (v : Verdict) (h : hitVerdict interval prev rescan = some v)
(hold : interval ≤ v.age) : rescan = none := by
cases rescan with
| none => rfl
| some s => exact absurd (finished_rescan_verdict_younger_than_interval interval hi prev s v h) (not_lt.mpr hold)
/-- A stale hit is judged on the fresh scan: a clean result that now holds a blocked vulnerability is refused. -/
theorem stale_clean_fresh_vulnerable_blocked (policy : Option ℕ) (t : ℕ) (hp : policy = some t)
(failClosed : Bool) (now : ℤ) (bs : List Bypass) (interval age : ℕ) (hi : 0 < interval)
(hage : interval ≤ age) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
(hun : v.id ∉ bypassedIds now bs) :
servesOnAccess failClosed false policy now bs interval (some ⟨Scan.ok [], age⟩) (some (Scan.ok vs)) = false := by
have hr : rescans interval (some ⟨Scan.ok [], age⟩) = true := by simp [rescans, hi, hage]
simp only [servesOnAccess, hitVerdict, hr, ite_true]
exact vulnerable_not_served policy t hp failClosed now bs vs v hv hsev hun
/-- A fresh result is served as is: no rescan, whatever the rescan outcome. -/
theorem fresh_hit_not_rescanned (interval : ℕ) (v : Verdict) (hfresh : v.age < interval)
(rescan : Option Scan) : hitVerdict interval (some v) rescan = some v := by
have : rescans interval (some v) = false := by simp [rescans, not_le.mpr hfresh]
simp [hitVerdict, this]
/-- A timeout keeps the previous verdict. -/
theorem timeout_keeps_previous (interval : ℕ) (prev : Option Verdict) :
hitVerdict interval prev none = prev := by
unfold hitVerdict
split <;> rfl
/-- A timeout with no previous verdict follows the first-download rule. -/
theorem timeout_without_previous_is_miss_rule (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
(bs : List Bypass) (interval : ℕ) :
servesOnAccess failClosed pkgBypass policy now bs interval none none = (pkgBypass || !failClosed) := by
simp only [servesOnAccess, timeout_keeps_previous]
cases failClosed <;> cases pkgBypass <;> simp [serves]
/-- `rescan_on_access` off (`RescanAfter` 0) is the old hit path: the stored verdict decides. -/
theorem off_is_old_hit_path (prev : Option Verdict) (rescan : Option Scan) :
hitVerdict 0 prev rescan = prev := by
simp [hitVerdict, rescans]
end Gohoarder.Security
+132
View File
@@ -6,6 +6,10 @@ import Mathlib
Models `pkg/metadata/gormstore/aggregation_worker.go` (`AggregateHourly`, `AggregateDaily`) and
`pkg/metadata/gormstore/gormstore_v2.go` `GetTimeSeriesStats`. Time is in whole minutes since the
epoch; an hour is 60 minutes and a day 24 hours. Omits: unique IPs, packages, registries.
The last three sections model the trend snapshots and backfill in `pkg/metadata/gormstore/snapshots.go`,
the soft-delete purge in `pkg/metadata/gormstore/purge.go` and `pkg/cache/cache.go` `purgeDeleted`,
and the severity filter in `pkg/metadata/gormstore/dashboard.go`.
-/
namespace Gohoarder.Stats
@@ -87,4 +91,132 @@ theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ char
/-- A download aggregated after the rollup ran: the old chart shows 1 of 2. -/
theorem chartOld_drops_late_download : chartOld 1 2 < chartNew 1 2 := by decide
/-! ### SQLite upsert (`aggregation_worker.go`, `sqlite_stats.go`) -/
/-- A bucket is a list of stored rows; the chart sums them. Before the fix SQLite had no unique index,
so `INSERT OR REPLACE` appended a row per pass. -/
def chartTotal (rows : List ℕ) : ℕ := rows.sum
/-- Three passes over a bucket whose registry total is 3: three copies. -/
theorem old_sqlite_duplicates_rows : chartTotal [3, 3, 3] ≠ 3 := by decide
/-- `ON CONFLICT ... DO UPDATE` over the unique index keeps one row per bucket: a derived row is set,
a package row adds the new events, as on PostgreSQL. -/
def upsertDerived (_old new : ℕ) : List ℕ := [new]
def upsertAdditive (old new : ℕ) : List ℕ := [old + new]
theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) :
chartTotal (upsertDerived old new) = new := by simp [chartTotal, upsertDerived]
theorem fixed_sqlite_package_row_keeps_late_events (old new : ℕ) :
chartTotal (upsertAdditive old new) = old + new := by simp [chartTotal, upsertAdditive]
/-! ### Daily snapshots and backfill (`snapshots.go`) -/
/-- Minutes in a UTC day. -/
def dayLen : ℕ := 1440
/-- `stateAtDayEnd`: a package cached at `cached` and deleted at `x` (`none` = still cached) counts in
the snapshot of day `d` iff it was cached before the day ended and not deleted before it ended. -/
def aliveAtEnd (cached : ℕ) (deleted : Option ℕ) (d : ℕ) : Prop :=
cached < dayLen * (d + 1) ∧ ∀ x, deleted = some x → dayLen * (d + 1) ≤ x
/-- A package cached and deleted inside one day is in no snapshot. -/
theorem same_day_package_never_counted (cached x d : ℕ) (hx : x < dayLen * (d + 1)) :
¬ aliveAtEnd cached (some x) d := by
rintro ⟨_, h⟩
exact absurd (h x rfl) (by omega)
theorem undeleted_package_counts_from_its_day (cached d : ℕ) :
aliveAtEnd cached none d ↔ cached < dayLen * (d + 1) := by
simp [aliveAtEnd]
/-- The backfill adds only each day's change to a running total (`deltas`, then the cumulative loop). -/
def delta (s : ℕ → ℤ) (d : ℕ) : ℤ := s d - (if d = 0 then 0 else s (d - 1))
/-- The running total of the daily changes equals the end-of-day state: the sweep loses nothing. -/
theorem sweep_telescopes (s : ℕ → ℤ) (n : ℕ) :
∑ d ∈ Finset.range (n + 1), delta s d = s n := by
induction n with
| zero => simp [delta]
| succ n ih =>
rw [Finset.sum_range_succ, ih]
simp [delta]
/-- One snapshot row per day, `none` = no row. `upsertSnapshot` (`SnapshotStats`) replaces the day's row. -/
def upsertSnapshot (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ := Function.update rows day (some v)
/-- Running the snapshot twice in a day leaves the last write only. -/
theorem snapshot_last_write_wins (rows : ℕ → Option ℕ) (day a b : ℕ) :
upsertSnapshot (upsertSnapshot rows day a) day b = upsertSnapshot rows day b :=
Function.update_idem _ _ _
theorem snapshot_leaves_other_days (rows : ℕ → Option ℕ) (day other v : ℕ) (h : other ≠ day) :
upsertSnapshot rows day v other = rows other :=
Function.update_of_ne h _ _
/-- The backfill insert (`ON CONFLICT DO NOTHING`) never replaces an existing row. -/
def insertMissing (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ :=
fun d => if d = day then (rows d).or (some v) else rows d
theorem backfill_keeps_existing (rows : ℕ → Option ℕ) (day a v : ℕ) (h : rows day = some a) :
insertMissing rows day v day = some a := by
simp [insertMissing, h]
/-- The backfill runs only while no past-day snapshot exists, so it cannot rewrite history. -/
def backfillRuns (pastRows : ℕ) : Bool := pastRows == 0
theorem backfill_idle_once_history_exists (n : ℕ) : backfillRuns (n + 1) = false := by
simp [backfillRuns]
/-! ### Soft-delete purge (`purge.go`, `cache.go` `purgeDeleted`) -/
/-- Cutoff = now - retention; a row is purged iff it was deleted before the cutoff. A row that is
not deleted (`none`) is never purged. -/
def purgeable (now retention : ℕ) (deleted : Option ℕ) : Prop :=
∃ x, deleted = some x ∧ x + retention < now
theorem active_row_never_purged (now retention : ℕ) : ¬ purgeable now retention none := by
rintro ⟨x, h, _⟩
cases h
theorem recent_delete_kept (now retention x : ℕ) (h : now ≤ x + retention) :
¬ purgeable now retention (some x) := by
rintro ⟨y, hy, hlt⟩
cases hy
omega
/-- The purge touches package rows only; the snapshot rows come out as they went in. -/
def purgeStep {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
List P × (ℕ → Option ℕ) := (pkgs.filter keep, snaps)
theorem purge_keeps_snapshots {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
(purgeStep pkgs keep snaps).2 = snaps := rfl
/-- One pass purges at most `maxPurgeBatches` batches of `limit` rows. -/
def maxPurgeBatches : ℕ := 100
theorem purge_pass_bounded (batches limit : ℕ) (h : batches ≤ maxPurgeBatches) :
batches * limit ≤ maxPurgeBatches * limit :=
Nat.mul_le_mul_right limit h
/-! ### Severity filter (`dashboard.go` `severityFilter`, `latestScanWith`) -/
/-- A package passes when no severity is selected, or its latest scan counts one of them. -/
def passes (selected : List ℕ) (counts : ℕ → ℕ) : Prop := selected = [] ∨ ∃ s ∈ selected, 0 < counts s
/-- OR semantics: selecting one more severity never hides a package. -/
theorem passes_monotone (sel sel' : List ℕ) (counts : ℕ → ℕ) (h : ∀ s ∈ sel, s ∈ sel')
(hne : sel ≠ []) (hp : passes sel counts) : passes sel' counts := by
right
rcases hp with hp | ⟨s, hs, hc⟩
· exact absurd hp hne
· exact ⟨s, h s hs, hc⟩
/-- A package with no finding of any selected severity is filtered out. -/
theorem clean_package_filtered (sel : List ℕ) (hne : sel ≠ []) : ¬ passes sel (fun _ => 0) := by
rintro (h | ⟨s, _, hc⟩)
· exact hne h
· exact absurd hc (by simp)
end Gohoarder.Stats
@@ -181,6 +181,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
FOREIGN KEY (package_id) REFERENCES packages(id) ON DELETE CASCADE ON UPDATE CASCADE,
INDEX idx_scan_package_scanner (package_id, scanner, deleted_at),
INDEX idx_scan_package_scanned_at (package_id, scanned_at),
INDEX idx_scan_scanned_at (scanned_at DESC),
INDEX idx_scan_status (status),
INDEX idx_scan_vuln_count (vuln_count)
@@ -190,6 +190,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
);
CREATE INDEX idx_scan_package_scanner ON scan_results(package_id, scanner) WHERE deleted_at IS NULL;
CREATE INDEX idx_scan_package_scanned_at ON scan_results(package_id, scanned_at) WHERE deleted_at IS NULL;
CREATE INDEX idx_scan_scanned_at ON scan_results(scanned_at DESC);
CREATE INDEX idx_scan_status ON scan_results(status);
CREATE INDEX idx_scan_vuln_count ON scan_results(vuln_count) WHERE vuln_count > 0;
+13 -2
View File
@@ -4,6 +4,7 @@ package analytics
import (
"sort"
"strings"
"sync"
"time"
@@ -23,6 +24,7 @@ type PackageDownload struct {
// PackageStats holds statistics for a package
type PackageStats struct {
versions map[string]struct{}
LastDownload time.Time
FirstSeen time.Time
Registry string
@@ -111,6 +113,11 @@ func NewEngine(cfg Config) *Engine {
// engine: append to the buffer under downloadsMu, release it, then update
// stats under statsMu.
func (e *Engine) TrackDownload(download PackageDownload) {
// Callers pass names sliced from a request buffer that the server reuses; keep our own copy.
download.Registry = strings.Clone(download.Registry)
download.Name = strings.Clone(download.Name)
download.Version = strings.Clone(download.Version)
// Append to buffer and decide whether buffer is full.
e.downloadsMu.Lock()
e.downloads = append(e.downloads, download)
@@ -154,8 +161,11 @@ func (e *Engine) updateStats(download PackageDownload) {
stats.BytesServed += download.BytesSize
stats.LastDownload = download.Timestamp
// Track unique versions (simplified)
stats.UniqueVersions++
if stats.versions == nil {
stats.versions = make(map[string]struct{})
}
stats.versions[download.Version] = struct{}{}
stats.UniqueVersions = len(stats.versions)
}
// GetPackageStats returns statistics for a specific package
@@ -171,6 +181,7 @@ func (e *Engine) GetPackageStats(registry, name string) (*PackageStats, bool) {
// Return a copy to avoid race conditions
statsCopy := *stats
statsCopy.versions = nil
return &statsCopy, true
}
+52
View File
@@ -0,0 +1,52 @@
package analytics
import (
"testing"
"time"
"unsafe"
)
func newTestEngine(t *testing.T) *Engine {
t.Helper()
e := NewEngine(Config{MaxEvents: 100, FlushInterval: time.Hour})
t.Cleanup(e.Close)
return e
}
// The proxy passes names sliced from a request buffer the server reuses.
func TestTrackDownloadKeepsItsOwnCopyOfTheNames(t *testing.T) {
e := newTestEngine(t)
shared := []byte("lodash")
aliased := unsafe.String(&shared[0], len(shared)) // #nosec G103 -- reproduces a string backed by a reused buffer
e.TrackDownload(PackageDownload{Registry: "npm", Name: aliased, Version: "1.0.0", Timestamp: time.Now()})
copy(shared, "xxxxxx")
if _, ok := e.GetPackageStats("npm", "lodash"); !ok {
t.Errorf("stats lost the package name after the caller reused its buffer: %v", e.GetTopPackages(0))
}
for _, p := range e.GetTopPackages(0) {
if p.Name != "lodash" {
t.Errorf("name = %q, want lodash", p.Name)
}
}
}
func TestUniqueVersionsCountsDistinctVersions(t *testing.T) {
e := newTestEngine(t)
for _, v := range []string{"1.0.0", "1.0.0", "1.1.0", "1.0.0"} {
e.TrackDownload(PackageDownload{Registry: "npm", Name: "left-pad", Version: v, Timestamp: time.Now(), BytesSize: 10})
}
stats, ok := e.GetPackageStats("npm", "left-pad")
if !ok {
t.Fatal("no stats")
}
if stats.TotalDownloads != 4 || stats.UniqueVersions != 2 || stats.BytesServed != 40 {
t.Errorf("stats = %+v, want 4 downloads, 2 versions, 40 bytes", stats)
}
}
func TestUnknownPackageHasNoStats(t *testing.T) {
if _, ok := newTestEngine(t).GetPackageStats("npm", "nope"); ok {
t.Error("unknown package reported stats")
}
}
+149
View File
@@ -0,0 +1,149 @@
package app
import (
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
// analyticsDownloads maps "registry:name" to downloads as the analytics engine reports them.
func analyticsDownloads(a *App) map[string]int64 {
out := map[string]int64{}
for _, p := range a.analyticsEngine.GetTopPackages(0) {
out[p.Registry+":"+p.Name] = p.Downloads
}
return out
}
// scrub sends requests whose paths differ from the proxied ones. The server reuses its request
// buffers, so a name kept from an earlier request changes under the analytics engine.
func scrub(t *testing.T, a *App) {
t.Helper()
for i := 0; i < 5; i++ {
doRequest(t, a, "/api/analytics/top?limit="+strings.Repeat("9", 40+i), nil)
}
}
func assertDownloads(t *testing.T, a *App, want map[string]int64) {
t.Helper()
scrub(t, a)
got := analyticsDownloads(a)
if len(got) != len(want) {
t.Errorf("analytics keys = %v, want %v", got, want)
return
}
for key, n := range want {
if got[key] != n {
t.Errorf("analytics keys = %v, want %v", got, want)
return
}
}
}
func TestAnalyticsNameNpmPackagesAfterRegistryPaths(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".tgz") {
_, _ = w.Write([]byte("TARBALL"))
return
}
_, _ = w.Write([]byte(`{"name":"x","versions":{}}`))
}))
t.Cleanup(upstream.Close)
a := newTestApp(t, func(c *config.Config) { c.Handlers.NPM.UpstreamRegistry = upstream.URL })
for _, target := range []string{
"/npm/lodash/-/lodash-4.17.21.tgz",
"/npm/@types/node/-/node-18.0.0.tgz",
"/npm/@types%2fnode/-/node-18.0.0.tgz",
"/npm/lodash",
"/npm/@types%2fnode",
} {
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
t.Fatalf("GET %s: %d %s", target, code, body)
}
}
// Tarballs are downloads; the packument is metadata and does not count.
assertDownloads(t, a, map[string]int64{"npm:lodash": 1, "npm:@types/node": 2})
}
func TestAnalyticsNameGoModuleCountsOnlyTheZip(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("BODY " + r.URL.Path)) // #nosec G705 -- test upstream, plain text body
}))
t.Cleanup(upstream.Close)
a := newTestApp(t, func(c *config.Config) {
c.Handlers.Go.UpstreamProxy = upstream.URL
c.Handlers.Go.VerifyChecksums = false
})
const base = "/go/github.com/google/uuid/@v/"
for _, target := range []string{base + "list", base + "v1.6.0.info", base + "v1.6.0.mod", base + "v1.6.0.zip", base + "v1.5.0.zip"} {
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
t.Fatalf("GET %s: %d %s", target, code, body)
}
}
// One key per module: both zips are downloads of the module, .info, .mod and list are not.
assertDownloads(t, a, map[string]int64{"go:github.com/google/uuid": 2})
}
func TestAnalyticsNamePyPIFilesNotPages(t *testing.T) {
upstream, _ := newPyPIUpstream(t)
a := newTestApp(t, func(c *config.Config) { c.Handlers.PyPI.SimpleAPIURL = upstream.URL + "/simple" })
file := "/pypi/foo/" + pypiWheel + "?original_url=" + url.QueryEscape(upstream.URL+"/packages/"+pypiWheel)
for _, target := range []string{"/pypi/simple/foo/", file} {
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
t.Fatalf("GET %s: %d %.80s", target, code, body)
}
}
doRequest(t, a, "/pypi/simple/foo/", map[string]string{"Accept": pypiJSONType})
assertDownloads(t, a, map[string]int64{"pypi:foo": 1})
}
// The proxy hands the cache names that alias the server's request buffer. Analytics keeps them
// after the request ends, so they must be copied or later requests rewrite them.
func TestAnalyticsKeepsNamesAfterTheRequestBufferIsReused(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("TARBALL"))
}))
t.Cleanup(upstream.Close)
a := newTestApp(t, func(c *config.Config) { c.Handlers.NPM.UpstreamRegistry = upstream.URL })
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
go func() { _ = a.app.Listener(ln, fiber.ListenConfig{DisableStartupMessage: true}) }()
base := "http://" + ln.Addr().String()
get := func(path string) {
resp, err := http.Get(base + path) // #nosec G107 -- loopback test server
if err != nil {
t.Fatal(err)
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}
names := []string{"lodash", "express", "@types/node", "left-pad"}
for _, name := range names {
bare := name[strings.Index(name, "/")+1:]
get("/npm/" + name + "/-/" + bare + "-1.0.0.tgz")
}
for i := 0; i < 20; i++ {
get("/api/analytics/top?limit=" + strings.Repeat("7", 30+i))
}
got := analyticsDownloads(a)
for _, name := range names {
if got["npm:"+name] != 1 {
t.Fatalf("analytics keys = %v, want each of %v once", got, names)
}
}
}
+67 -29
View File
@@ -17,7 +17,6 @@ import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor"
"github.com/gofiber/fiber/v3/middleware/static"
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
"github.com/lukaszraczylo/gohoarder/pkg/auth"
"github.com/lukaszraczylo/gohoarder/pkg/cache"
@@ -60,6 +59,7 @@ type App struct {
analyticsEngine *analytics.Engine
wsServer *websocket.Server
prewarmWorker *prewarming.Worker
prewarmFetcher *prewarming.ProxyFetcher
cdnMiddleware *cdn.Middleware
}
@@ -215,6 +215,10 @@ func (a *App) initializeComponents() error {
return fmt.Errorf("failed to initialize scanner: %w", err)
}
if setter, ok := a.metadata.(blockedCounterSetter); ok {
setter.SetBlockedCounter(a.countBlocked)
}
// Initialize analytics engine first (needed by cache)
log.Info().Msg("Initializing analytics engine")
a.analyticsEngine = analytics.NewEngine(analytics.Config{
@@ -230,12 +234,20 @@ func (a *App) initializeComponents() error {
if cleanupInterval == 0 {
cleanupInterval = 5 * time.Minute
}
var rescanAfter time.Duration
if a.config.Security.RescanOnAccess {
rescanAfter = a.config.Security.RescanInterval
}
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
DefaultTTL: a.config.Cache.DefaultTTL,
CleanupInterval: cleanupInterval,
IdleTTL: a.config.Cache.IdleTTL,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
RescanAfter: rescanAfter,
DefaultTTL: a.config.Cache.DefaultTTL,
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
CleanupInterval: cleanupInterval,
IdleTTL: a.config.Cache.IdleTTL,
DeletedRetention: a.config.Cache.DeletedRetention,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
ScanWaitTimeout: a.config.Security.ScanWaitTimeout,
})
if err != nil {
return fmt.Errorf("failed to initialize cache: %w", err)
@@ -308,10 +320,15 @@ func (a *App) initializeComponents() error {
}
bootCancel()
a.scanManager.SetFileSource(a.cache.ScanFile)
// Initialize rescan worker if enabled
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
scanner.WithConcurrency(a.config.Security.RescanConcurrency),
)
}
// Initialize WebSocket server
@@ -331,14 +348,14 @@ func (a *App) initializeComponents() error {
// Initialize pre-warming worker. Operator-controlled via cfg.Prewarming;
// defaults are baked into config.Default() so unset fields stay sane.
log.Info().Msg("Initializing pre-warming worker")
a.prewarmFetcher = prewarming.NewProxyFetcher()
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{
Enabled: a.config.Prewarming.Enabled,
Interval: a.config.Prewarming.Interval,
MaxConcurrent: a.config.Prewarming.MaxConcurrent,
TopPackages: a.config.Prewarming.TopPackages,
CacheManager: a.cache,
Analytics: a.analyticsEngine,
NetworkClient: a.networkClient,
Popularity: a.analyticsEngine,
Fetcher: a.prewarmFetcher,
})
// Initialize CDN middleware
@@ -389,10 +406,11 @@ func (a *App) initializeComponents() error {
func (a *App) setupServer() error {
// Create Fiber app
a.app = fiber.New(fiber.Config{
ReadTimeout: a.config.Server.ReadTimeout,
WriteTimeout: a.config.Server.WriteTimeout,
ServerHeader: "GoHoarder",
AppName: "GoHoarder v1.0",
ReadTimeout: a.config.Server.ReadTimeout,
WriteTimeout: a.config.Server.WriteTimeout,
ReadBufferSize: a.config.Server.ReadBufferSize,
ServerHeader: "GoHoarder",
AppName: "GoHoarder v1.0",
})
// Auth middleware factories. Built once, reused on every gated route.
@@ -411,6 +429,8 @@ func (a *App) setupServer() error {
_ = mwOptional // reserved for future endpoints with anonymous fallback
}
a.app.Use("/api", apiOriginGuard(a.config.Server.AllowedOrigins))
// Health endpoints — ALWAYS public (k8s liveness/readiness probes).
a.app.Get("/health", adaptor.HTTPHandlerFunc(a.healthChecker.HealthHandler()))
a.app.Get("/health/ready", adaptor.HTTPHandlerFunc(a.healthChecker.ReadyHandler()))
@@ -440,28 +460,32 @@ func (a *App) setupServer() error {
a.app.All("/api/packages/*", mwAuth, a.handlePackages) // OPTIONS, preflight, vulnerabilities
a.app.Get("/api/stats", mwAuth, a.handleStats)
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
a.app.Get("/api/info", mwAuth, a.handleInfo)
a.app.Get("/api/system", mwAuth, a.handleSystem)
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
a.app.Get("/api/analytics/trending", mwAuth, a.handleAnalyticsTrendingPackages)
a.app.Get("/api/analytics/trends", mwAuth, a.handleAnalyticsTrends)
a.app.Get("/api/analytics/total", mwAuth, a.handleAnalyticsTotalStats)
a.app.Get("/api/analytics/registry/:registry", mwAuth, a.handleAnalyticsRegistryStats)
a.app.Get("/api/analytics/package/:registry/:name", mwAuth, a.handleAnalyticsPackageStats)
a.app.Get("/api/analytics/package/:registry/*", mwAuth, a.handleAnalyticsPackageStats)
a.app.Get("/api/analytics/search", mwAuth, a.handleAnalyticsSearch)
} else {
a.app.Get("/api/config", a.handleConfig)
a.app.All("/api/packages/*", a.handlePackages)
a.app.Get("/api/stats", a.handleStats)
a.app.Get("/api/stats/timeseries", a.handleTimeSeriesStats)
a.app.Get("/api/stats/trend", a.handleStatsTrend)
a.app.Get("/api/info", a.handleInfo)
a.app.Get("/api/system", a.handleSystem)
a.app.Get("/api/analytics/top", a.handleAnalyticsTopPackages)
a.app.Get("/api/analytics/trending", a.handleAnalyticsTrendingPackages)
a.app.Get("/api/analytics/trends", a.handleAnalyticsTrends)
a.app.Get("/api/analytics/total", a.handleAnalyticsTotalStats)
a.app.Get("/api/analytics/registry/:registry", a.handleAnalyticsRegistryStats)
a.app.Get("/api/analytics/package/:registry/:name", a.handleAnalyticsPackageStats)
a.app.Get("/api/analytics/package/:registry/*", a.handleAnalyticsPackageStats)
a.app.Get("/api/analytics/search", a.handleAnalyticsSearch)
}
@@ -514,11 +538,13 @@ func (a *App) setupServer() error {
SumDBURL: sumDB,
CredStore: credStore,
})
goProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/go", goProxyHandler))
goProxyMounted := http.StripPrefix("/go", goProxyHandler)
a.prewarmFetcher.Mount("go", goProxyMounted)
goProxyWithCDN := a.cdnMiddleware.Handler(goProxyMounted)
if authEnabled {
a.app.All("/go/*", mwAuth, adaptor.HTTPHandler(goProxyWithCDN))
a.app.All("/go/*", mwAuth, proxyHandler(goProxyWithCDN))
} else {
a.app.All("/go/*", adaptor.HTTPHandler(goProxyWithCDN))
a.app.All("/go/*", proxyHandler(goProxyWithCDN))
}
}
@@ -530,7 +556,9 @@ func (a *App) setupServer() error {
npmProxyHandler := npm.New(a.cache, a.networkClient, npm.Config{
Upstream: npmUpstream,
})
npmProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/npm", npmProxyHandler))
npmProxyMounted := http.StripPrefix("/npm", npmProxyHandler)
a.prewarmFetcher.Mount("npm", npmProxyMounted)
npmProxyWithCDN := a.cdnMiddleware.Handler(npmProxyMounted)
a.app.Use("/npm", func(c fiber.Ctx) error {
if canonical := npm.CanonicalPath(c.Path()); canonical != c.Path() {
c.Path(canonical)
@@ -538,9 +566,9 @@ func (a *App) setupServer() error {
return c.Next()
})
if authEnabled {
a.app.All("/npm/*", mwAuth, adaptor.HTTPHandler(npmProxyWithCDN))
a.app.All("/npm/*", mwAuth, proxyHandler(npmProxyWithCDN))
} else {
a.app.All("/npm/*", adaptor.HTTPHandler(npmProxyWithCDN))
a.app.All("/npm/*", proxyHandler(npmProxyWithCDN))
}
}
@@ -552,11 +580,13 @@ func (a *App) setupServer() error {
pypiProxyHandler := pypi.New(a.cache, a.networkClient, pypi.Config{
Upstream: pypiUpstream,
})
pypiProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/pypi", pypiProxyHandler))
pypiProxyMounted := http.StripPrefix("/pypi", pypiProxyHandler)
a.prewarmFetcher.Mount("pypi", pypiProxyMounted)
pypiProxyWithCDN := a.cdnMiddleware.Handler(pypiProxyMounted)
if authEnabled {
a.app.All("/pypi/*", mwAuth, adaptor.HTTPHandler(pypiProxyWithCDN))
a.app.All("/pypi/*", mwAuth, proxyHandler(pypiProxyWithCDN))
} else {
a.app.All("/pypi/*", adaptor.HTTPHandler(pypiProxyWithCDN))
a.app.All("/pypi/*", proxyHandler(pypiProxyWithCDN))
}
}
@@ -564,7 +594,7 @@ func (a *App) setupServer() error {
frontendDir := "frontend/dist"
if _, err := os.Stat(frontendDir); err == nil {
log.Info().Str("dir", frontendDir).Msg("Serving frontend static files")
a.app.Use("/", static.New(frontendDir))
a.app.Use("/", spaStatic(frontendDir))
} else {
log.Warn().Msg("Frontend dist directory not found, frontend won't be served")
a.app.Get("/", func(c fiber.Ctx) error {
@@ -604,6 +634,14 @@ func (a *App) startWorkers(ctx context.Context) {
// Start periodic stats broadcaster (every 30s) so connected WS clients
// see live counter updates without polling.
go a.startStatsBroadcaster(ctx)
// Re-scans artifacts whose scan was lost to a restart and refreshes old results.
if a.rescanWorker != nil {
go a.rescanWorker.Start(ctx)
}
// Start is a no-op unless prewarming.enabled is set.
a.prewarmWorker.Start(ctx)
}
func (a *App) Run() error {
@@ -888,13 +926,13 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
}
ou, err := url.Parse(origin)
if err != nil || ou.Scheme == "" || ou.Host == "" {
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
return false
}
originScheme := strings.ToLower(ou.Scheme)
originHost, ok := normalizeOriginHost(originScheme, ou.Host)
if !ok {
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
return false
}
@@ -925,7 +963,7 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
log.Warn().
Str("origin", origin).
Str("host", r.Host).
Msg("Rejecting WebSocket upgrade: Origin not in allowlist")
Msg("Rejecting origin: Origin not in allowlist")
return false
}
}
+94
View File
@@ -0,0 +1,94 @@
package app
import (
"net/http"
"net/url"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/rs/zerolog/log"
)
const (
headerOrigin = "Origin"
corsAllowedMethods = "GET, POST, PATCH, DELETE, OPTIONS"
corsAllowedHeaders = "Content-Type, Authorization, X-API-Key"
corsPreflightMaxAge = "600"
headerACRMethod = "Access-Control-Request-Method"
headerACAllowOrigin = "Access-Control-Allow-Origin"
headerACAllowMethods = "Access-Control-Allow-Methods"
headerACAllowHeaders = "Access-Control-Allow-Headers"
headerACMaxAge = "Access-Control-Max-Age"
)
// apiOriginGuard enforces server.allowed_origins on /api. A browser at another origin cannot
// read responses (no CORS grant) and cannot change state (403), whatever the handlers set.
// With nothing configured only the request's own host counts as same-origin.
// Requests with neither Origin nor Referer come from non-browser clients and pass.
func apiOriginGuard(allowed []string) fiber.Handler {
check := buildCheckOrigin(allowed)
originAllowed := func(c fiber.Ctx, origin string) bool {
r := &http.Request{Header: http.Header{headerOrigin: {origin}}, Host: c.Host()}
return check(r)
}
return func(c fiber.Ctx) error {
origin := c.Get(headerOrigin)
method := c.Method()
if method == http.MethodOptions && origin != "" && c.Get(headerACRMethod) != "" {
if !originAllowed(c, origin) {
return c.SendStatus(fiber.StatusForbidden)
}
setCORSGrant(c, origin)
c.Set(headerACMaxAge, corsPreflightMaxAge)
return c.SendStatus(fiber.StatusNoContent)
}
if !isSafeMethod(method) {
source := origin
if source == "" {
source = refererOrigin(c.Get(fiber.HeaderReferer))
}
if source != "" && !originAllowed(c, source) {
log.Warn().Str("method", method).Str("path", c.Path()).Str("origin", source).Msg("Rejecting cross-origin state-changing request")
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "cross-origin request not allowed"})
}
}
err := c.Next()
// Drop any grant a handler or upstream set; the allowlist decides.
c.Response().Header.Del(headerACAllowOrigin)
c.Response().Header.Del(headerACAllowMethods)
c.Response().Header.Del(headerACAllowHeaders)
c.Vary(headerOrigin)
if origin != "" && originAllowed(c, origin) {
setCORSGrant(c, origin)
}
return err
}
}
func setCORSGrant(c fiber.Ctx, origin string) {
c.Set(headerACAllowOrigin, origin)
c.Set(headerACAllowMethods, corsAllowedMethods)
c.Set(headerACAllowHeaders, corsAllowedHeaders)
c.Vary(headerOrigin)
}
func isSafeMethod(m string) bool {
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
}
// refererOrigin returns scheme://host of a Referer, or "" when it is absent or malformed.
func refererOrigin(referer string) string {
if strings.TrimSpace(referer) == "" {
return ""
}
u, err := url.Parse(referer)
if err != nil || u.Scheme == "" || u.Host == "" {
return "null" // present but unusable: never matches the allowlist
}
return u.Scheme + "://" + u.Host
}
+144
View File
@@ -0,0 +1,144 @@
package app
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/cache"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const dashboardOrigin = "https://gohoarder.example.com"
func seedPackage(t *testing.T, a *App) {
t.Helper()
entry, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*cache.FetchResult, error) {
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
})
require.NoError(t, err)
_ = entry.Data.Close()
}
func apiCall(t *testing.T, a *App, method, target string, headers map[string]string) *http.Response {
t.Helper()
req := httptest.NewRequest(method, target, nil)
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
require.NoError(t, err)
t.Cleanup(func() { _ = resp.Body.Close() })
return resp
}
func corsApp(t *testing.T, origins ...string) *App {
return newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = origins })
}
const deletePath = "/api/packages/npm/left-pad/1.3.0"
func TestAPIDeleteFromDisallowedOriginForbidden(t *testing.T) {
a := corsApp(t, dashboardOrigin)
seedPackage(t, a)
for _, h := range []map[string]string{
{"Origin": "https://evil.example.net"},
{"Origin": "null"},
{"Referer": "https://evil.example.net/page"},
{"Origin": "https://evil.example.net", "Referer": dashboardOrigin + "/x"},
} {
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
assert.Equal(t, http.StatusForbidden, resp.StatusCode, "%v", h)
}
resp := apiCall(t, a, http.MethodGet, "/api/packages/npm", nil)
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
assert.NoError(t, err, "a refused request must not delete")
}
func TestAPIDeleteFromAllowedOriginWorks(t *testing.T) {
for name, h := range map[string]map[string]string{
"origin": {"Origin": dashboardOrigin},
"referer": {"Referer": dashboardOrigin + "/packages"},
"no-fetch": nil, // curl and server-to-server callers send neither header
} {
t.Run(name, func(t *testing.T) {
a := corsApp(t, dashboardOrigin)
seedPackage(t, a)
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
assert.Equal(t, http.StatusOK, resp.StatusCode)
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
assert.Error(t, err, "package must be gone")
})
}
}
func TestAPIPostFromDisallowedOriginForbidden(t *testing.T) {
a := corsApp(t, dashboardOrigin)
resp := apiCall(t, a, http.MethodPost, "/api/admin/prewarming/trigger", map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}
func TestAPIGetStaysPublicWithoutWildcardCORS(t *testing.T) {
a := corsApp(t, dashboardOrigin)
resp := apiCall(t, a, http.MethodGet, "/api/stats", nil)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": dashboardOrigin})
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, dashboardOrigin, resp.Header.Get("Access-Control-Allow-Origin"))
assert.Contains(t, resp.Header.Values("Vary"), "Origin")
// Served, but a browser at a foreign origin cannot read it.
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
}
func TestAPIPreflightAnswersOnlyAllowedOrigins(t *testing.T) {
a := corsApp(t, dashboardOrigin)
preflight := func(origin string) *http.Response {
return apiCall(t, a, http.MethodOptions, deletePath, map[string]string{
"Origin": origin, "Access-Control-Request-Method": "DELETE",
})
}
ok := preflight(dashboardOrigin)
assert.Equal(t, http.StatusNoContent, ok.StatusCode)
assert.Equal(t, dashboardOrigin, ok.Header.Get("Access-Control-Allow-Origin"))
assert.Contains(t, ok.Header.Get("Access-Control-Allow-Methods"), "DELETE")
bad := preflight("https://evil.example.net")
assert.Equal(t, http.StatusForbidden, bad.StatusCode)
assert.Empty(t, bad.Header.Get("Access-Control-Allow-Origin"))
}
// With nothing configured, only the host the request was sent to counts as same-origin.
func TestAPISameOriginRuleWhenNoOriginsConfigured(t *testing.T) {
a := corsApp(t)
seedPackage(t, a)
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://evil.example.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "http://example.com"}) // httptest.NewRequest Host
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestAPIOriginMatchingUsesAllowlistRules(t *testing.T) {
a := corsApp(t, "https://*.example.org")
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://ui.example.org"})
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://example.org.evil.net"})
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}
+67
View File
@@ -0,0 +1,67 @@
package app
import (
"go/ast"
"go/parser"
"go/token"
"net/http"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
// Handlers must not set CORS headers themselves: apiOriginGuard owns the decision.
func TestHandlersSetNoCORSHeaders(t *testing.T) {
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
for _, f := range files {
if strings.HasSuffix(f, "_test.go") || f == "cors.go" {
continue
}
parsed, err := parser.ParseFile(fset, f, nil, 0)
if err != nil {
t.Fatalf("parse %s: %v", f, err)
}
ast.Inspect(parsed, func(n ast.Node) bool {
lit, ok := n.(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
return true
}
if v, err := strconv.Unquote(lit.Value); err == nil && strings.HasPrefix(v, "Access-Control-") {
t.Errorf("%s: handler sets %q; apiOriginGuard owns CORS", fset.Position(lit.Pos()), v)
}
return true
})
}
}
func TestAPIResponsesNeverCarryWildcardOrigin(t *testing.T) {
const dashboard = "https://dash.example.com"
a := newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = []string{dashboard} })
targets := []string{
"/api/stats", "/api/info", "/api/config", "/api/packages",
"/api/analytics/top", "/api/analytics/trending", "/api/analytics/trends", "/api/analytics/total",
"/api/analytics/search?q=x", "/api/stats/timeseries",
}
for _, origin := range []string{"", dashboard, "https://evil.example.net"} {
for _, target := range targets {
hdr := map[string]string{}
if origin != "" {
hdr["Origin"] = origin
}
code, h, _ := doRequest(t, a, target, hdr)
if code == http.StatusNotFound {
t.Errorf("GET %s = 404, route missing", target)
}
if got := h.Get("Access-Control-Allow-Origin"); got == "*" {
t.Errorf("GET %s Origin=%q carries Access-Control-Allow-Origin: *", target, origin)
}
}
}
}
+68
View File
@@ -0,0 +1,68 @@
package app
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
func doDelete(t *testing.T, a *App, target string) (int, string) {
t.Helper()
req := httptest.NewRequest(http.MethodDelete, target, nil)
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
if err != nil {
t.Fatalf("DELETE %s: %v", target, err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
return resp.StatusCode, string(body)
}
func TestDeleteMissingPackageIs404(t *testing.T) {
a := newTestApp(t, nil)
for _, target := range []string{
"/api/packages/npm/nope/1.0.0",
"/api/packages/pypi/nope/1.0.0",
"/api/packages/go/example.com/nope/v1.0.0",
} {
code, body := doDelete(t, a, target)
if code != http.StatusNotFound {
t.Errorf("DELETE %s = %d %s, want 404", target, code, body)
}
var out map[string]string
if err := json.Unmarshal([]byte(body), &out); err != nil || out["error"] == "" {
t.Errorf("DELETE %s body %q is not a JSON error", target, body)
}
}
}
func TestDeleteExistingPackageIs200(t *testing.T) {
a := newTestApp(t, nil)
ctx := context.Background()
err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.0.0", StorageKey: "npm/left-pad/1.0.0",
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
})
if err != nil {
t.Fatalf("SavePackage: %v", err)
}
code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0")
if code != http.StatusOK || !strings.Contains(body, `"deleted":true`) {
t.Fatalf("DELETE existing = %d %s, want 200 deleted", code, body)
}
if code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0"); code != http.StatusNotFound {
t.Errorf("second DELETE = %d %s, want 404", code, body)
}
}
+54
View File
@@ -0,0 +1,54 @@
package app
import (
"net/http"
"net/url"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor"
)
// proxyHandler mounts a net/http proxy handler on fiber with a request that owns its strings.
// The adaptor builds URL, Host, Method and header strings over fasthttp's request buffer, which the
// next request on the connection overwrites; the proxies hand these strings to background scans,
// singleflight keys and analytics that outlive the request.
func proxyHandler(h http.Handler) fiber.Handler {
return adaptor.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, detachRequest(r))
}))
}
func detachRequest(r *http.Request) *http.Request {
d := r.Clone(r.Context())
d.Method = strings.Clone(r.Method)
d.Proto = strings.Clone(r.Proto)
d.Host = strings.Clone(r.Host)
d.RequestURI = strings.Clone(r.RequestURI)
u := *r.URL
u.Scheme = strings.Clone(u.Scheme)
u.Host = strings.Clone(u.Host)
u.Path = strings.Clone(u.Path)
u.RawPath = strings.Clone(u.RawPath)
u.RawQuery = strings.Clone(u.RawQuery)
u.Fragment = strings.Clone(u.Fragment)
u.User = nil
if r.URL.User != nil {
if p, ok := r.URL.User.Password(); ok {
u.User = url.UserPassword(strings.Clone(r.URL.User.Username()), strings.Clone(p))
} else {
u.User = url.User(strings.Clone(r.URL.User.Username()))
}
}
d.URL = &u
h := make(http.Header, len(r.Header))
for k, vs := range r.Header {
cp := make([]string, len(vs))
for i, v := range vs {
cp[i] = strings.Clone(v)
}
h[strings.Clone(k)] = cp
}
d.Header = h
return d
}
+37
View File
@@ -0,0 +1,37 @@
package app
import (
"net/http"
"net/url"
"testing"
"unsafe"
)
// The adaptor's strings point into a buffer fasthttp reuses; a detached request must not see later writes.
func TestDetachRequestSurvivesBufferReuse(t *testing.T) {
buf := []byte("GET/npm/lodash/-/lodash-1.0.0.tgzq=1proxy.lanBearer secret")
alias := func(from, to int) string { return unsafe.String(&buf[from], to-from) } // #nosec G103 -- reproduces the adaptor's aliasing
r := &http.Request{
Method: alias(0, 3),
Host: alias(36, 45),
URL: &url.URL{Path: alias(3, 33), RawQuery: alias(33, 36), User: url.UserPassword(alias(36, 41), alias(52, 58))},
Header: http.Header{"Authorization": {alias(45, 58)}},
}
d := detachRequest(r)
for i := range buf {
buf[i] = 'x'
}
pw, _ := d.URL.User.Password()
got := []string{d.Method, d.Host, d.URL.Path, d.URL.RawQuery, d.Header.Get("Authorization"), d.URL.User.Username(), pw}
want := []string{"GET", "proxy.lan", "/npm/lodash/-/lodash-1.0.0.tgz", "q=1", "Bearer secret", "proxy", "secret"}
for i := range want {
if got[i] != want[i] {
t.Fatalf("field %d = %q after the buffer changed, want %q", i, got[i], want[i])
}
}
if r.URL == d.URL {
t.Fatal("detached request shares the URL with the original")
}
}
+245 -186
View File
@@ -1,12 +1,18 @@
package app
import (
"context"
stderrors "errors"
"fmt"
"slices"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/internal/version"
apperrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
"github.com/rs/zerolog/log"
)
@@ -14,9 +20,6 @@ import (
// handlePackages handles /api/packages endpoint
func (a *App) handlePackages(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, DELETE, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -29,6 +32,9 @@ func (a *App) handlePackages(c fiber.Ctx) error {
switch c.Method() {
case "GET":
if registry, name, version, ok := packagePath(c.Path()); ok {
return a.handleGetPackage(c, registry, name, version)
}
return a.handleListPackages(c)
case "DELETE":
return a.handleDeletePackage(c)
@@ -37,6 +43,30 @@ func (a *App) handlePackages(c fiber.Ctx) error {
}
}
// packagePath splits /api/packages/{registry}/{name}/{version}. The name can hold slashes
// (@scope/pkg, Go module paths); the version is the last segment.
func packagePath(path string) (registry, name, version string, ok bool) {
parts := strings.Split(strings.Trim(strings.TrimPrefix(path, "/api/packages/"), "/"), "/")
if len(parts) < 3 {
return "", "", "", false
}
return parts[0], strings.Join(parts[1:len(parts)-1], "/"), parts[len(parts)-1], true
}
// handleGetPackage serves one stored package version.
func (a *App) handleGetPackage(c fiber.Ctx, registry, name, version string) error {
_, pkg, err := a.resolvePackageKey(c.Context(), registry, name, version)
if err != nil {
var appErr *apperrors.Error
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
}
log.Error().Err(err).Str("registry", registry).Str("package", name).Msg("Failed to get package")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to get package"})
}
return c.Status(fiber.StatusOK).JSON(packageSummary(pkg))
}
// packageSummary is the list payload for one package when scan results are attached.
func packageSummary(pkg *metadata.Package) map[string]interface{} {
summary := map[string]interface{}{
@@ -56,156 +86,210 @@ func packageSummary(pkg *metadata.Package) map[string]interface{} {
return summary
}
// handleListPackages returns list of cached packages
func (a *App) handleListPackages(c fiber.Ctx) error {
ctx := c.Context()
// Pagination limits of GET /api/packages.
const (
defaultPageSize = 25
maxPageSize = 200
)
// Get packages from metadata store
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
Limit: 1000, // Get more to account for duplicates
Offset: 0,
})
// listParams are the parsed query parameters of GET /api/packages.
type listParams struct {
opts metadata.GroupListOptions
paged bool
}
// parseSeverities reads a comma-separated severity filter such as "critical,high".
func parseSeverities(raw string) ([]string, error) {
var out []string
for _, part := range strings.Split(raw, ",") {
sev := strings.ToLower(strings.TrimSpace(part))
if sev == "" || slices.Contains(out, sev) {
continue
}
if !slices.Contains(metadata.Severities, sev) {
return nil, fmt.Errorf("invalid severity %q, must be one of: %s", sev, strings.Join(metadata.Severities, ", "))
}
out = append(out, sev)
}
return out, nil
}
// parseListParams reads page, page_size, registry, q, sort, order and severity.
// Without page or page_size the list is unpaginated, as it was before paging existed.
func parseListParams(c fiber.Ctx) (listParams, error) {
p := listParams{opts: metadata.GroupListOptions{
Registry: c.Query("registry"),
Query: c.Query("q"),
SortBy: metadata.GroupSortName,
}}
switch sortBy := c.Query("sort"); sortBy {
case metadata.GroupSortName, metadata.GroupSortCachedAt, metadata.GroupSortDownloads, metadata.GroupSortSize:
p.opts.SortBy = sortBy
p.opts.SortDesc = sortBy != metadata.GroupSortName
}
switch c.Query("order") {
case "asc":
p.opts.SortDesc = false
case "desc":
p.opts.SortDesc = true
}
severities, err := parseSeverities(c.Query("severity"))
if err != nil {
return p, err
}
p.opts.Severities = severities
if c.Query("page") != "" || c.Query("page_size") != "" {
p.paged = true
p.opts.Page = max(fiber.Query[int](c, "page", 1), 1)
p.opts.PageSize = fiber.Query[int](c, "page_size", defaultPageSize)
if p.opts.PageSize < 1 {
p.opts.PageSize = defaultPageSize
}
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
}
return p, nil
}
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
func (a *App) scanDecisions(ctx context.Context, ids []string) ([]scanner.ScanDecision, error) {
if a.scanManager != nil {
return a.scanManager.ScanDecisions(ctx, ids)
}
summaries, err := a.metadata.GetScanSummaries(ctx, ids, false)
if err != nil {
return nil, err
}
out := make([]scanner.ScanDecision, len(summaries))
for i, s := range summaries {
out[i] = scanner.ScanDecision{Summary: s}
}
return out, nil
}
// Verdicts the dashboard shows for a cached package.
const (
VerdictCleared = "cleared"
VerdictHeld = "held"
VerdictBypassed = "bypassed"
VerdictPending = "pending"
)
// verdictOf names the outcome of a scan decision: held beats bypassed, which beats cleared.
func verdictOf(d scanner.ScanDecision) string {
switch {
case d.Blocked:
return VerdictHeld
case d.Bypass != nil:
return VerdictBypassed
default:
return VerdictCleared
}
}
// bypassSummary is the public view of the bypass that waved a package through.
func bypassSummary(b *metadata.CVEBypass) map[string]interface{} {
if b == nil {
return nil
}
return map[string]interface{}{
"id": b.ID,
"type": b.Type,
"target": b.Target,
"reason": b.Reason,
"created_by": b.CreatedBy,
"created_at": b.CreatedAt,
"expires_at": b.ExpiresAt,
}
}
// vulnerabilityInfo is the per-package scan block of the list response; verdict, reason and bypass extend the original fields.
func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanDecision) map[string]interface{} {
if !pkg.SecurityScanned {
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false, "verdict": VerdictPending}
}
d, ok := decisions[pkg.ID]
if !ok || !d.Summary.HasScan {
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false, "verdict": VerdictPending}
}
sum := d.Summary
info := map[string]interface{}{
"scanned": true,
"status": sum.Status,
"scannedAt": sum.ScannedAt.Format(time.RFC3339),
"counts": map[string]int{
"critical": sum.Critical,
"high": sum.High,
"moderate": sum.Moderate,
"low": sum.Low,
},
"total": sum.Total,
"isBlocked": d.Blocked,
"verdict": verdictOf(d),
}
if d.Reason != "" {
info["reason"] = d.Reason
}
if d.Bypass != nil {
info["bypass"] = bypassSummary(d.Bypass)
}
return info
}
func (a *App) handleListPackages(c fiber.Ctx) error {
if c.Query("layout") == layoutRows {
return a.handleListPackageRows(c)
}
ctx := c.Context()
params, err := parseListParams(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
}
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
if err != nil {
log.Error().Err(err).Msg("Failed to list packages")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
}
log.Debug().Int("total_packages_from_db", len(allPackages)).Msg("Retrieved packages from database")
// Filter, clean, and deduplicate packages
// Map stores both cleaned package and original name for scan lookups
type packageEntry struct {
pkg *metadata.Package
originalName string
response := fiber.Map{
"total": len(page.Packages),
"total_groups": page.TotalGroups,
}
seen := make(map[string]*packageEntry)
skippedCount := 0
for _, pkg := range allPackages {
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
skippedCount++
log.Debug().
Str("name", pkg.Name).
Str("version", pkg.Version).
Str("registry", pkg.Registry).
Msg("Skipping metadata entry")
continue
if params.paged {
response["page"] = params.opts.Page
response["page_size"] = params.opts.PageSize
}
if !a.config.Security.Enabled {
response["packages"] = page.Packages
return c.Status(fiber.StatusOK).JSON(response)
}
var scannedIDs []string
for _, pkg := range page.Packages {
if pkg.SecurityScanned {
scannedIDs = append(scannedIDs, pkg.ID)
}
// Clean the package name (remove /@v/version.ext suffix)
originalName := pkg.Name
cleanName := pkg.Name
if idx := strings.Index(cleanName, "/@v/"); idx != -1 {
cleanName = cleanName[:idx]
}
decisions := map[string]scanner.ScanDecision{}
if len(scannedIDs) > 0 {
list, err := a.scanDecisions(ctx, scannedIDs)
if err != nil {
log.Error().Err(err).Msg("Failed to load scan summaries")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
}
// Create deduplication key
key := cleanName + "@" + pkg.Version
// Keep the entry with the largest size (typically .zip files)
if existing, ok := seen[key]; !ok || pkg.Size > existing.pkg.Size {
// Create a copy with cleaned name
cleanPkg := *pkg
cleanPkg.Name = cleanName
seen[key] = &packageEntry{
pkg: &cleanPkg,
originalName: originalName,
}
for _, d := range list {
decisions[d.Summary.PackageID] = d
}
}
log.Debug().
Int("skipped_metadata", skippedCount).
Int("unique_packages", len(seen)).
Msg("Filtered and deduplicated packages")
// Convert map to slice, keeping track of original names
type packageWithOriginalName struct {
pkg *metadata.Package
originalName string
enhanced := make([]map[string]interface{}, 0, len(page.Packages))
for _, pkg := range page.Packages {
pkgMap := packageSummary(pkg)
pkgMap["vulnerabilities"] = vulnerabilityInfo(pkg, decisions)
enhanced = append(enhanced, pkgMap)
}
packagesWithNames := make([]packageWithOriginalName, 0, len(seen))
for _, entry := range seen {
packagesWithNames = append(packagesWithNames, packageWithOriginalName{
pkg: entry.pkg,
originalName: entry.originalName,
})
}
// Enhance packages with vulnerability information if security scanning is enabled
var response map[string]interface{}
if a.config.Security.Enabled {
enhancedPackages := make([]map[string]interface{}, 0, len(packagesWithNames))
for _, entry := range packagesWithNames {
pkg := entry.pkg
pkgMap := packageSummary(pkg)
// Add vulnerability info if scanned
if pkg.SecurityScanned {
// Use original name for scan result lookup (handles Go packages with /@v/ suffix)
scanResult, err := a.metadata.GetScanResult(ctx, pkg.Registry, entry.originalName, pkg.Version)
if err == nil && scanResult != nil {
// Count vulnerabilities by severity
severityCounts := make(map[string]int)
for _, vuln := range scanResult.Vulnerabilities {
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
}
// Check if package should be blocked based on thresholds
isBlocked := false
if a.scanManager != nil {
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, entry.originalName, pkg.Version)
isBlocked = blocked
}
pkgMap["vulnerabilities"] = map[string]interface{}{
"scanned": true,
"status": scanResult.Status,
"scannedAt": scanResult.ScannedAt.Format(time.RFC3339),
"counts": map[string]int{
"critical": severityCounts["CRITICAL"],
"high": severityCounts["HIGH"],
"moderate": severityCounts["MODERATE"],
"low": severityCounts["LOW"],
},
"total": scanResult.VulnerabilityCount,
"isBlocked": isBlocked,
}
} else {
pkgMap["vulnerabilities"] = map[string]interface{}{
"scanned": false,
"status": "pending",
"isBlocked": false,
}
}
} else {
pkgMap["vulnerabilities"] = map[string]interface{}{
"scanned": false,
"status": "not_scanned",
"isBlocked": false,
}
}
enhancedPackages = append(enhancedPackages, pkgMap)
}
response = map[string]interface{}{
"packages": enhancedPackages,
"total": len(enhancedPackages),
}
} else {
// Non-enhanced mode - just return the packages
packages := make([]*metadata.Package, 0, len(packagesWithNames))
for _, entry := range packagesWithNames {
packages = append(packages, entry.pkg)
}
response = map[string]interface{}{
"packages": packages,
"total": len(packages),
}
}
// Success response
response["packages"] = enhanced
return c.Status(fiber.StatusOK).JSON(response)
}
@@ -236,7 +320,8 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
if registry == "go" {
// List all packages matching the base name and version
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
Limit: 1000,
Registry: registry,
NamePrefix: name,
})
if err != nil {
log.Error().Err(err).Msg("Failed to list packages for deletion")
@@ -303,6 +388,10 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
} else {
// For NPM and PyPI, delete directly
if err := a.cache.Delete(ctx, registry, name, version); err != nil {
var appErr *apperrors.Error
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
}
log.Error().
Err(err).
Str("registry", registry).
@@ -342,9 +431,6 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
// handleStats handles /api/stats endpoint
func (a *App) handleStats(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -363,42 +449,23 @@ func (a *App) handleStats(c fiber.Ctx) error {
cacheStats = &metadata.Stats{}
}
// Get all packages to calculate per-registry breakdown
packages, err := a.metadata.ListPackages(ctx, nil)
registryStats := make(map[string]map[string]interface{})
byRegistry, err := a.metadata.GetRegistryStats(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to list packages")
packages = []*metadata.Package{}
log.Error().Err(err).Msg("Failed to get registry stats")
}
for _, rs := range byRegistry {
registryStats[rs.Registry] = map[string]interface{}{
"count": int(rs.Count),
"size": rs.Size,
"downloads": rs.Downloads,
}
}
// Calculate per-registry breakdown and blocked packages count
registryStats := make(map[string]map[string]interface{})
blockedCount := int64(0)
for _, pkg := range packages {
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
continue
}
// Track per-registry stats
if _, ok := registryStats[pkg.Registry]; !ok {
registryStats[pkg.Registry] = map[string]interface{}{
"count": 0,
"size": int64(0),
"downloads": int64(0),
}
}
registryStats[pkg.Registry]["count"] = registryStats[pkg.Registry]["count"].(int) + 1
registryStats[pkg.Registry]["size"] = registryStats[pkg.Registry]["size"].(int64) + pkg.Size
registryStats[pkg.Registry]["downloads"] = registryStats[pkg.Registry]["downloads"].(int64) + int64(pkg.DownloadCount)
// Check if package is blocked (only if security scanning is enabled and package is scanned)
if a.config.Security.Enabled && a.scanManager != nil && pkg.SecurityScanned {
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, pkg.Name, pkg.Version)
if blocked {
blockedCount++
}
}
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
blockedCount, bypassedCount, err := a.countVerdicts(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to judge scanned packages")
}
// Combine statistics using database stats for accuracy
@@ -415,6 +482,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
"scanned_packages": cacheStats.ScannedPackages,
"vulnerable_packages": cacheStats.VulnerablePackages,
"blocked_packages": blockedCount,
"bypassed_packages": bypassedCount,
}
// Convert registry stats to interface map
@@ -433,9 +501,6 @@ func (a *App) handleStats(c fiber.Ctx) error {
// Returns time-series download statistics for charts
func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -475,9 +540,6 @@ func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
// Returns runtime configuration for the frontend
func (a *App) handleConfig(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
@@ -509,9 +571,6 @@ func (a *App) handleConfig(c fiber.Ctx) error {
// handleInfo handles /api/info endpoint
func (a *App) handleInfo(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
-3
View File
@@ -45,9 +45,6 @@ func (a *App) requireAdmin(c fiber.Ctx) error {
// handleAdminBypasses handles /api/admin/bypasses endpoint
func (a *App) handleAdminBypasses(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusOK)
+61
View File
@@ -0,0 +1,61 @@
package app
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
func seedAliased(t *testing.T, a *App) {
t.Helper()
ctx := context.Background()
now := time.Now()
if err := a.metadata.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "aliased", Version: "1.0.0", StorageKey: "npm/aliased", Size: 10, CachedAt: now, LastAccessed: now,
}); err != nil {
t.Fatalf("SavePackage: %v", err)
}
if err := a.metadata.SaveScanResult(ctx, &metadata.ScanResult{
Registry: "npm", PackageName: "aliased", PackageVersion: "1.0.0", Scanner: "osv", Status: metadata.ScanStatusVulnerable, ScannedAt: now,
VulnerabilityCount: 1,
Vulnerabilities: []metadata.Vulnerability{{
ID: "GHSA-xvch-5gv4-984h", Aliases: []string{"CVE-2021-44906"}, Severity: "critical", DetectedBy: []string{"osv"},
}},
}); err != nil {
t.Fatalf("SaveScanResult: %v", err)
}
}
func TestDetailsShowAliasesAndHonourABypassOnAnAlias(t *testing.T) {
a, _ := newScanningApp(t)
a.config.Security.BlockOnSeverity = "critical"
seedAliased(t, a)
held, _ := getJSON(t, a, "/api/packages/npm/aliased/1.0.0/vulnerabilities")
if jsonAt(held, "decision", "verdict") != VerdictHeld {
t.Fatalf("verdict before the bypass = %v, want held", jsonAt(held, "decision", "verdict"))
}
if got, _ := jsonAt(held, "vulnerabilities", 0, "aliases").([]any); len(got) != 1 || got[0] != "CVE-2021-44906" {
t.Errorf("aliases = %v, want [CVE-2021-44906]", got)
}
if err := a.metadata.SaveCVEBypass(context.Background(), &metadata.CVEBypass{
Type: metadata.BypassTypeCVE, Target: "cve-2021-44906", Reason: "not reachable", CreatedBy: "alice",
Active: true, ExpiresAt: time.Now().Add(time.Hour),
}); err != nil {
t.Fatal(err)
}
waved, _ := getJSON(t, a, "/api/packages/npm/aliased/1.0.0/vulnerabilities")
if jsonAt(waved, "decision", "verdict") != VerdictBypassed {
t.Errorf("verdict with a CVE bypass = %v, want bypassed", jsonAt(waved, "decision", "verdict"))
}
if jsonAt(waved, "vulnerabilities", 0, "bypassed") != true {
t.Errorf("finding bypassed = %v, want true", jsonAt(waved, "vulnerabilities", 0, "bypassed"))
}
if jsonAt(waved, "vulnerabilities", 0, "bypass", "created_by") != "alice" {
t.Errorf("bypass = %v", jsonAt(waved, "vulnerabilities", 0, "bypass"))
}
}

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