Compare commits

..
104 Commits
Author SHA1 Message Date
github-actions[bot]andGitHub 1432c7176b chore(deps): update dependencies
Automated dependency update. All tests passed.
2026-11-27 03:16:49 +00:00
github-actions[bot]andGitHub 426225bd14 chore(deps): update module github.com/valyala/fasthttp to v1.80.0
Automated dependency update. All tests passed.
2026-11-26 03:16:45 +00:00
github-actions[bot]andGitHub 518d836c7b chore(deps): update dependency @testing-library/jest-dom to v8
Automated dependency update. All tests passed.
2026-11-24 03:18:45 +00:00
lukaszraczylo 1e99b53d51 fix(auth): accept the bootstrap admin key on the boot that creates it
The server loaded the API key cache before it created the admin key
from GOHOARDER_BOOTSTRAP_ADMIN_KEY. The new key was therefore refused
until the next restart. Bootstrap now runs before the cache loads.
2026-11-24 02:55:37 +00:00
lukaszraczylo 9c0420161e fix(metadata): leave Go metadata files out of the registry stats
GetRegistryStats counted Go .mod and .info rows while GetStats and the
package rows left them out. The overview registry table therefore
showed more Go packages than the totals. Both stores now use the
artifact filter.
2026-11-24 02:51:18 +00:00
lukaszraczylo c685131865 feat(security): size the rescan from measured scan times
The confirmation for a full rescan used a fixed guess of 10 seconds per
artifact. Scans now record their wall time in scan_results. The new
GET /api/admin/rescan/estimate returns the artifact count of each scope
and the time at the configured concurrency, from the average of recent
scans. While a rescan runs, the status reports elapsed time and an ETA,
and the panel shows the live rate.
2026-11-24 02:49:28 +00:00
lukaszraczylo e80489e55c fix(analytics): make the trending windows contiguous
Hourly rows are kept for 7 days, so the previous week came from daily
rollups that ended at a day boundary. Downloads between that boundary and
the start of the recent week counted in neither. The boundary day is now
its rollup minus the hourly rows after the boundary.
2026-11-24 02:44:09 +00:00
lukaszraczylo 5f4bdbed80 fix(metadata): treat .mod and .info names as metadata for Go only
GetStats, the package list and the stats snapshots dropped any registry's
names that end in .mod or .info. An npm or PyPI package with such a name
vanished from the counts. The filter now matches IsMetadataEntry.
2026-11-24 02:43:17 +00:00
lukaszraczylo 1b00236749 test(gormstore): stop the background aggregator in time-series stores
Rollup tests set the worker clock while the background aggregation loop
read it, so the race detector failed about one run in ten. These stores
now stop the loop, and the tests drive aggregation by hand.
2026-11-24 02:42:11 +00:00
lukaszraczylo 9ff6de2414 feat(security): add an admin-triggered rescan
POST /api/admin/rescan queues a background rescan of the cached
artifacts with scope vulnerable or all. It ignores the active window and
the age of the last scan, runs on the server context and uses the rescan
worker concurrency. A second request while a run is active gets 409.
GET /api/admin/rescan/status reports queued, done, failed and running.
The System page gets a Rescan section with progress and a confirmation
for the full rescan.
2026-11-24 02:38:24 +00:00
lukaszraczylo 3bfc367898 feat(analytics): serve trending packages from persisted downloads
Trending read the in-memory analytics engine, which restarts empty. The
endpoint now ranks packages by the last 7 days of stored downloads and
reports the previous 7 days for the change. It counts a Go module once
and skips metadata entries. A daily time_bucket index serves the range
read. The Overview panel shows the change and no longer says the data
resets on restart.
2026-11-24 02:33:21 +00:00
lukaszraczylo 6715cefd25 fix(packages): list only cache artifacts in the package rows
The rows layout listed Go .mod and .info files. They are never scanned,
so they showed as pending and made the page total larger than /api/stats.
The group query now applies the same artifact filter as GetStats.
2026-11-24 02:32:58 +00:00
lukaszraczylo 5518d02599 fix(ui): size the last table column for the full sort button bleed
The sort button is 1rem wider than its cell but shifts left only by the cell padding. The last column now pads by the difference, so no table scrolls sideways.
2026-11-24 02:23:05 +00:00
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
lukaszraczylo a7b9917696 chore(lean): model cache, keys, scan policy, access, release age and stats
Six Lean 4 + Mathlib modules prove or refute the audited properties and cite the Go files they model. FINDINGS.md records each verdict with its Lean theorem, Go test and fix commit. The axiom audit and the currency check live in lean4/scripts.
2026-11-23 13:16:52 +00:00
lukaszraczylo 3143de3a3f fix(scanner): scan PyPI artifacts by release version, not file name
PyPI artifacts are cached under their file name, and the scanners received that name as the version. OSV parsed it as a version below every range, so it missed vulnerabilities that affect the real release (for requests 2.19.0, PYSEC-2023-74 and GHSA-j8r2-6x86-q33q) and reported others that do not. Scanners now receive the release version stored on the package row. The saved result stays keyed by the cache version.
2026-11-23 13:15:34 +00:00
lukaszraczylo f0b37ea719 fix(cache): scan npm and PyPI packages named like Go metadata
IsMetadataEntry treated any name ending in .mod or .info as metadata. An npm or PyPI package with such a name skipped the vulnerability scan and was never blocked. The suffix rule now applies to the go registry only.
2026-11-23 13:15:34 +00:00
lukaszraczylo 7192e4ff3e fix(stats): keep downloads that a daily rollup has not counted yet
The time series let a day's rollup replace the hourly rows and events for that day. A download aggregated after the rollup ran vanished from the chart until the next pass. The chart now takes the larger of the two figures.
2026-11-23 13:15:34 +00:00
lukaszraczylo ad4e848e2b fix(stats): roll up every completed day still held hourly
The daily pass rolled up only yesterday, once a day at hour 0. A pass that ran before its last hour was aggregated, or that a restart skipped, left that day short or empty, and the hourly rows were deleted after seven days. Each pass now recomputes the six completed days before today.
2026-11-23 13:15:33 +00:00
lukaszraczylo 990a1d3409 fix(cache): retry once when a purge removes the blob during a hit
Get probed the blob in getOrFetch and opened it again after the singleflight. A purge between the two returned a storage error to the client. Get now resolves the entry a second time, which sees the miss and fetches again.
2026-11-23 13:15:33 +00:00
lukaszraczylo 440279aa50 fix(cache): stop LRU eviction spinning and failing overlapping stores
evict re-listed the same 100 rows forever when every delete failed, and an
overlapping store received a quota error because a flag rejected the second
eviction. Eviction now returns when a pass deletes nothing, and a second
caller waits for the running eviction.
2026-11-23 13:15:33 +00:00
lukaszraczylo 1f31256769 fix(storage): release replaced bytes when a key is overwritten
Put added the new size to the usage counter without subtracting the file it
replaced. Each overwrite inflated usage until restart and could trip the
quota on a cache that was not full.
2026-11-23 13:15:33 +00:00
lukaszraczylo 4713524778 fix(scanner): honour CVE bypasses under block_on_severity LOW
The LOW policy counted every vulnerability, including bypassed ones, so an
active bypass never unblocked a package. It now counts only the remaining
vulnerabilities.
2026-11-23 13:15:33 +00:00
lukaszraczylo 5c9f7e6af3 fix(pypi): bind original_url to the requested file name
The cache key is built from the request path, but the upstream fetch used
the original_url query value. Any file on an allowed host could be stored
under another package's key. The handler now rejects an original_url whose
file name differs from the requested file.
2026-11-23 13:15:32 +00:00
lukaszraczylo 6f604367da fix(websocket): start the event loop and throttle drop warnings
The app built the websocket server but never called Start, so nothing read the 256-slot broadcast channel. After the first 256 events every event was dropped with a warning, and dashboard clients blocked forever on the unbuffered register channel, leaking a goroutine per connection and never receiving events. Run now starts the loop with the other workers. Dropped events are counted in gohoarder_websocket_events_dropped_total and warned about at most once a minute.
2026-11-23 12:56:32 +00:00
lukaszraczylo c98720c02e docs: describe cache.idle_ttl and the cleanup run
Document the new idle_ttl key in the example config and the README.
Explain that artifacts never expire by age and that metadata entries
refresh after default_ttl.
2026-11-23 12:50:01 +00:00
lukaszraczylo 9a44683fbd feat(ui): note the idle eviction window on the stats page
The stats page now reads idle_ttl from the stats API. It shows
"Cached items not requested for 7 days are removed." in an info alert.
The note stays hidden when idle eviction is off.
2026-11-23 12:50:00 +00:00
lukaszraczylo d6edd40d79 feat(cache): evict items idle past cache.idle_ttl
Every cached item got a 7-day expiry at store time. A popular tarball
left the cache seven days after it was cached, however often clients
requested it.

Artifacts now get no age-based expiry. Cleanup removes any item whose
last_accessed is older than cache.idle_ttl (default 168h, 0 disables).
It reads the items in bounded batches of 500 through the indexed
last_accessed column and deletes them through deletePackage. Metadata
entries keep the freshness expiry from default_ttl.

Startup and each cleanup run clear the expiry that earlier versions set
on artifact rows. Cleanup records the idle and ttl eviction reasons and
logs the count and bytes freed. The stats API reports idle_ttl in
seconds. Package deletes are soft deletes and no history table has a
foreign key to packages, so download history stays intact.
2026-11-23 12:49:47 +00:00
lukaszraczylo 99c885cd88 fix(ui): stack package rows on phones and drop pager edge buttons
At 320px the package name shared a row with the registry badge, size and downloads, so it had about 90px and scoped names broke mid-word. Below sm the name now takes the full width with the meta row underneath. The pager's first and last buttons wrapped onto a second line inside the card; the page list already reaches the first and last pages, so the edge buttons are off.
2026-11-23 12:29:40 +00:00
lukaszraczylo c022824d2b fix(ui): swap native key prompt for a dialog; add favicon 2026-11-23 03:18:43 +00:00
lukaszraczylo 5420480ef8 fix(metadata): keep created_at on CVE bypass edit; repair MySQL suite 2026-11-23 03:18:42 +00:00
lukaszraczylo bde9eebf3d fix(ui): show the PyPI release version in every version display 2026-11-23 03:18:42 +00:00
github-actions[bot]andGitHub f65c0cc1f3 chore(deps): update dependencies
Automated dependency update. All tests passed.
2026-11-23 03:17:22 +00:00
276 changed files with 24821 additions and 3405 deletions
+2
View File
@@ -72,6 +72,7 @@ tests/fixtures/temp/
# Markdown files (except README.md)
*.md
!README.md
!lean4/FINDINGS.md
/gohoarder
*.log
@@ -83,3 +84,4 @@ data/storage
# Local worktrees
.worktrees/
lean4/.lake
+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
+43 -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
@@ -233,7 +234,12 @@ security:
enabled: true
cache:
default_ttl: 86400 # 24 hours in seconds
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
pypi: 12h
cleanup_interval: 1h
logging:
level: "info" # debug, info, warn, error
@@ -245,6 +251,17 @@ upstream:
go: "https://proxy.golang.org"
```
#### Cache cleanup
Every `cleanup_interval` the cleanup run removes:
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
- **Deleted rows.** Evicting or deleting a package marks its database row deleted. Rows deleted longer ago than `deleted_retention` (default `720h`, 30 days) are removed for good, in batches of 500. Download history and the daily trend snapshots are kept. Set `deleted_retention: 0` to keep every row.
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
### Environment Variables
All configuration values can be overridden with environment variables:
@@ -876,10 +893,29 @@ Access the web dashboard at **http://localhost:8080**
**List Packages:**
```bash
GET /api/packages
GET /api/packages?registry=npm
GET /api/packages?status=vulnerable
GET /api/packages?page=1&page_size=25
GET /api/packages?registry=npm&q=axios&page_size=25
GET /api/packages?sort=cached_at&order=desc&page_size=10
```
The dashboard groups versions under a package, so paging counts packages (a
registry and name pair), not rows. Without `page` and `page_size` the call
returns every package in one response, with no row cap.
| Parameter | Meaning |
|---|---|
| `page` | 1-based page of groups. Default 1. |
| `page_size` | Groups per page. Default 25 when `page` is set, at most 200. |
| `registry` | Only this registry, for example `npm`, `pypi` or `go`. |
| `q` | Case-insensitive search in name, version and release version. |
| `sort` | `name` (default, ascending), `cached_at`, `downloads` or `size` (both descending). |
| `order` | `asc` or `desc`, to override the default direction of `sort`. |
`packages` holds every version row of each group on the page, in group order
and newest first within a group. `total` is the number of rows returned.
`total_groups` is the number of groups that match the filters across all pages.
A paged response also echoes `page` and `page_size`.
**Package Details:**
```bash
GET /api/packages/:registry/:name/:version
@@ -909,7 +945,10 @@ GET /api/packages/:registry/:name/:version
}
}
],
"total": 42
"total": 1,
"total_groups": 42,
"page": 1,
"page_size": 25
}
```
+17 -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,23 +94,30 @@ metadata:
log_level: "warn" # GORM log level: silent, error, warn, info
cache:
default_ttl: "168h" # 7 days
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
cleanup_interval: "1h"
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
deleted_retention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
max_size_bytes: 536870912000 # 500GB
per_project_quota: 53687091200 # 50GB
ttl_overrides:
npm: "168h"
pip: "168h"
go: "168h"
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
npm: "24h"
pypi: "24h"
go: "24h"
security:
enabled: false
block_on_severity: "high" # none, low, medium, high, critical
scan_on_download: true # Scan packages on first download
rescan_interval: "24h" # How often to re-scan packages (e.g., 24h, 168h for weekly)
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:
+3
View File
@@ -5,3 +5,6 @@ VITE_BACKEND_URL=http://localhost:8080
# Frontend dev server port
# The Vite development server will run on this port
VITE_PORT=5173
# Origin sent on the dev WebSocket proxy, for a backend with an allowed-origins list
# VITE_WS_ORIGIN=https://gohoarder.example.com
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<link rel="icon" href="data:," />
<title>GoHoarder dashboard</title>
</head>
<body>
+2 -2
View File
@@ -15,7 +15,7 @@
"@fontsource/ibm-plex-mono": "5.3.0",
"@fontsource/ibm-plex-sans": "5.3.0",
"@fortawesome/free-solid-svg-icons": "7.3.1",
"@perfect-design/ui": "0.3.10",
"@perfect-design/ui": "0.3.11",
"axios": "^1.20.0",
"pinia": "^4.0.0",
"vue": "^3.5.26",
@@ -23,7 +23,7 @@
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^7.0.0",
"@testing-library/jest-dom": "^8.0.0",
"@testing-library/vue": "^8.1.0",
"@vitejs/plugin-vue": "^6.0.3",
"@vue/test-utils": "^2.4.6",
+154 -97
View File
@@ -23,36 +23,36 @@ importers:
specifier: 7.3.1
version: 7.3.1
'@perfect-design/ui':
specifier: 0.3.10
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))
specifier: 0.3.11
version: 0.3.11([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))
axios:
specifier: ^1.20.0
version: 1.21.1
version: 1.21.1([email protected]([email protected]))([email protected])
pinia:
specifier: ^4.0.0
version: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
version: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
vue:
specifier: ^3.5.26
version: 3.5.45([email protected])
version: 3.5.46([email protected])
vue-router:
specifier: ^5.3.1
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected]))
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected]))
devDependencies:
'@tailwindcss/vite':
specifier: ^4.3.3
version: 4.3.5([email protected]([email protected])([email protected]))
'@testing-library/jest-dom':
specifier: ^7.0.0
version: 7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
specifier: ^8.0.0
version: 8.0.0(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
'@testing-library/vue':
specifier: ^8.1.0
version: 8.1.0(@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))
version: 8.1.0(@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))
'@vitejs/plugin-vue':
specifier: ^6.0.3
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]5([email protected]))
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]6([email protected]))
'@vue/test-utils':
specifier: ^2.4.6
version: 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
version: 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
jsdom:
specifier: ^31.0.0
version: 31.0.1
@@ -353,8 +353,8 @@ packages:
'@oxc-project/[email protected]':
resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
'@perfect-design/[email protected]0':
resolution: {integrity: sha512-nFpY8dK6braHsRPVdX3bUCrkPNfwiUj2KfvUfLdFRFlfBRaqrkNGx2QkmNu/L0rdNe6JQj6Mvdrb+LnC/sFg8Q==}
'@perfect-design/[email protected]1':
resolution: {integrity: sha512-vu7liBjd6ZndJWio3gt1EHmOVi1VAcPQ/v+8xQRLvrIH9Bd43ZYsgsh+JITpBRmagYyAxPjo1zFU7ma/I6lVmg==}
peerDependencies:
pinia: ^3.0.0 || ^4.0.0
tailwindcss: ^4.1.0
@@ -561,12 +561,12 @@ packages:
resolution: {integrity: sha512-FlS4ZWlp97iiNWig0Muq8p+3rVDjRiYE+YKGbAqXOu9nwJFFOdL00kFpz42M+4huzYi86vAK1sOOfyOG45muIQ==}
engines: {node: '>=14'}
'@testing-library/jest-dom@7.0.1':
resolution: {integrity: sha512-oMDTC3oA+6CXSO2JZnvOI7CA6oVub6kij5ggk9ohwye5slmkwxYDXcPOVxgMw/RQlticjtO0C1RZkR97HgrWMw==}
'@testing-library/jest-dom@8.0.0':
resolution: {integrity: sha512-Nu45KEeFgP/ydCMipnisMblq6YHViqEFi3fKN0a40s+zdKDDD7vEPCEavS0i7i4RxmclcEIL8q2o42pu+WgNgg==}
engines: {node: '>=22', npm: '>=6', yarn: '>=1'}
peerDependencies:
'@testing-library/dom': '>=10 <11'
vitest: '>= 0.32'
vitest: '>=5 <6'
peerDependenciesMeta:
vitest:
optional: true
@@ -654,18 +654,30 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==}
'@vue/[email protected]':
resolution: {integrity: sha512-yb+N8/mgBcoeqCJPVyJI/D3OphLrSMXnB3ZQUNmRLU/1fsMW4bFfdJWNi9oIj7+EA3ULKKkP7b/VCpcYQYeiuQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==}
'@vue/[email protected]':
resolution: {integrity: sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==}
'@vue/[email protected]':
resolution: {integrity: sha512-Bj3lCSw3DQnDRDxw115XqdLDd0+18Nftlgd8OXSGG+ud74hxJIE17eYrM+VWgQrTMsvJbLh9Hzf2MkwAzru36Q==}
'@vue/[email protected]':
resolution: {integrity: sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==}
'@vue/[email protected]':
resolution: {integrity: sha512-hjUvMxGh+QIgegwksfp6BRBYleE/a8veZHvTR6sa+o+bM4HU+WnrUZlhN0X+pDcsl8Lhwmbu72xPvLMk3XUwog==}
'@vue/[email protected]':
resolution: {integrity: sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==}
'@vue/[email protected]':
resolution: {integrity: sha512-qebChL3aP0m1k+TlSf+fZWvOwAf3flBCi5o+n01ykR3DX4mTIWheFltmoiQ12+z66/4cGeXqbB2P7sPWkGhQNQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-6u4vXBlIBAC1wMplIZgpyPn7uh/s4Bf6F5bMzvLv+EdJ0aHs/+4B7Ygv864EStQSjRbsRzTko/kUG1A1IejQ3A==}
@@ -678,17 +690,17 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-kRB+3hHg0c+BdD1XLAvwjVMQd5pC05zijSlPDRI3ERvC/s04JlRs5upy2KjeMg/9m9oD5zuMVh9yVvkKfZqoJg==}
'@vue/[email protected]5':
resolution: {integrity: sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==}
'@vue/[email protected]6':
resolution: {integrity: sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==}
'@vue/[email protected]5':
resolution: {integrity: sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==}
'@vue/[email protected]6':
resolution: {integrity: sha512-eJUzKAUaHAmtnys/l9qduPzUnBrYMkmsCU7TN+vbSOSpm8kcETT7nacKxIO4MBej/XiOraVzq+lSeZv7o1//jQ==}
'@vue/[email protected]5':
resolution: {integrity: sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==}
'@vue/[email protected]6':
resolution: {integrity: sha512-6L7lbBvXTYBFFjIt25a0pgdpmn3Ns8RqUnNVibRzF4bgyiWJvqOhKEV5MXYWKlCttZE3aGeJN8mveo+6IrIKXA==}
'@vue/[email protected]5':
resolution: {integrity: sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==}
'@vue/[email protected]6':
resolution: {integrity: sha512-4mc0YWREc6OZ5pDCigvKPDzIUV+aciiH92yvyTS6xaHHxW/80rMceQQn11pYe7OEEBt2YQgYWR9zF8QF30GJUQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==}
@@ -696,6 +708,9 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==}
'@vue/[email protected]':
resolution: {integrity: sha512-kTB6s2p34cA/xXSpt17G0enU9A3F3pdm+o5GZgE3WGXXXpXJ5SVBsRhgCJNCc+ekGAzY0T7Hjyo5yEfwencBlg==}
peerDependencies:
@@ -855,8 +870,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
[email protected].3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
[email protected].4:
resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==}
[email protected]:
resolution: {integrity: sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==}
@@ -1476,6 +1491,10 @@ packages:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
[email protected]:
resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==}
engines: {node: '>=6.0.0'}
[email protected]:
resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}
@@ -1710,8 +1729,8 @@ packages:
peerDependencies:
typescript: '>=5.0.0'
[email protected]5:
resolution: {integrity: sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==}
[email protected]6:
resolution: {integrity: sha512-0kW5CgfjMPBqmH158049SaE1muufp+K/ZyrwvSEwrwYky6QB7zL2y8kXfruneKb9O12eh0xAJL6CVSpzb9o0Kg==}
peerDependencies:
typescript: '*'
peerDependenciesMeta:
@@ -1901,11 +1920,11 @@ snapshots:
'@floating-ui/[email protected]': {}
'@floating-ui/[email protected]([email protected]5([email protected]))':
'@floating-ui/[email protected]([email protected]6([email protected]))':
dependencies:
'@floating-ui/dom': 1.8.0
'@floating-ui/utils': 0.2.12
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@fontsource/[email protected]': {}
@@ -1948,13 +1967,13 @@ snapshots:
'@oxc-project/[email protected]': {}
'@perfect-design/[email protected]0([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))':
'@perfect-design/[email protected]1([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))':
dependencies:
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
reka-ui: 2.11.0([email protected]5([email protected]))
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
reka-ui: 2.11.0([email protected]6([email protected]))
tailwind-merge: 3.7.1
tailwindcss: 4.3.5
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@rolldown/[email protected]':
optional: true
@@ -2077,10 +2096,10 @@ snapshots:
'@tanstack/[email protected]': {}
'@tanstack/[email protected]([email protected]5([email protected]))':
'@tanstack/[email protected]([email protected]6([email protected]))':
dependencies:
'@tanstack/virtual-core': 3.13.14
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@testing-library/[email protected]':
dependencies:
@@ -2104,11 +2123,11 @@ snapshots:
lz-string: 1.5.0
pretty-format: 27.5.1
'@testing-library/jest-dom@7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))':
'@testing-library/jest-dom@8.0.0(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))':
dependencies:
'@adobe/css-tools': 4.4.4
'@testing-library/dom': 10.4.2
aria-query: 5.1.3
aria-query: 5.3.0
css.escape: 1.5.1
dom-accessibility-api: 0.6.3
picocolors: 1.1.1
@@ -2116,12 +2135,12 @@ snapshots:
optionalDependencies:
vitest: 5.1.1([email protected])([email protected]([email protected])([email protected]))
'@testing-library/[email protected](@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))':
'@testing-library/[email protected](@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))':
dependencies:
'@babel/runtime': 7.28.4
'@testing-library/dom': 9.3.4
'@vue/test-utils': 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
vue: 3.5.45([email protected])
'@vue/test-utils': 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
vue: 3.5.46([email protected])
optionalDependencies:
'@vue/compiler-sfc': 3.5.45
transitivePeerDependencies:
@@ -2141,11 +2160,11 @@ snapshots:
'@types/[email protected]': {}
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]5([email protected]))':
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]6([email protected]))':
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.3.8([email protected])([email protected])
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@vitest/[email protected]([email protected]([email protected])([email protected]))':
dependencies:
@@ -2182,7 +2201,7 @@ snapshots:
optionalDependencies:
typescript: 6.0.3
'@vue-macros/[email protected]([email protected]5([email protected]))':
'@vue-macros/[email protected]([email protected]6([email protected]))':
dependencies:
'@vue/compiler-sfc': 3.5.45
ast-kit: 2.2.0
@@ -2190,7 +2209,7 @@ snapshots:
magic-string-ast: 1.0.3
unplugin-utils: 0.3.2
optionalDependencies:
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@vue/[email protected]':
dependencies:
@@ -2208,6 +2227,14 @@ snapshots:
estree-walker: 2.0.2
source-map-js: 1.2.2
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
'@vue/shared': 3.5.46
entities: 7.0.1
estree-walker: 2.0.2
source-map-js: 1.2.4
'@vue/[email protected]':
dependencies:
'@vue/compiler-core': 3.5.44
@@ -2218,6 +2245,11 @@ snapshots:
'@vue/compiler-core': 3.5.45
'@vue/shared': 3.5.45
'@vue/[email protected]':
dependencies:
'@vue/compiler-core': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
@@ -2230,11 +2262,28 @@ snapshots:
postcss: 8.5.32
source-map-js: 1.2.2
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
'@vue/compiler-core': 3.5.46
'@vue/compiler-dom': 3.5.46
'@vue/compiler-ssr': 3.5.46
'@vue/shared': 3.5.46
estree-walker: 2.0.2
magic-string: 0.30.21
postcss: 8.5.32
source-map-js: 1.2.4
'@vue/[email protected]':
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/shared': 3.5.45
'@vue/[email protected]':
dependencies:
'@vue/compiler-dom': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]':
dependencies:
'@vue/devtools-kit': 8.2.1
@@ -2258,61 +2307,63 @@ snapshots:
path-browserify: 1.0.1
picomatch: 4.0.7
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/shared': 3.5.45
'@vue/shared': 3.5.46
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/reactivity': 3.5.45
'@vue/shared': 3.5.45
'@vue/reactivity': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/reactivity': 3.5.45
'@vue/runtime-core': 3.5.45
'@vue/shared': 3.5.45
csstype: 3.2.3
'@vue/reactivity': 3.5.46
'@vue/runtime-core': 3.5.46
'@vue/shared': 3.5.46
csstype: 3.2.4
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/compiler-ssr': 3.5.45
'@vue/runtime-dom': 3.5.45
'@vue/shared': 3.5.45
'@vue/compiler-ssr': 3.5.46
'@vue/runtime-dom': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]': {}
'@vue/[email protected]': {}
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
'@vue/[email protected]': {}
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/compiler-dom': 3.5.46
js-beautify: 2.0.3
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
vue-component-type-helpers: 3.3.12
optionalDependencies:
'@vue/server-renderer': 3.5.45
'@vue/server-renderer': 3.5.46
'@vueuse/[email protected]([email protected]5([email protected]))':
'@vueuse/[email protected]([email protected]6([email protected]))':
dependencies:
'@types/web-bluetooth': 0.0.21
'@vueuse/metadata': 14.4.0
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
vue: 3.5.45([email protected])
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
vue: 3.5.46([email protected])
'@vueuse/[email protected]': {}
'@vueuse/[email protected]([email protected]5([email protected]))':
'@vueuse/[email protected]([email protected]6([email protected]))':
dependencies:
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
[email protected]: {}
[email protected]: {}
[email protected]:
[email protected]([email protected]):
dependencies:
debug: 4.4.3
debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2368,11 +2419,11 @@ snapshots:
dependencies:
possible-typed-array-names: 1.1.0
[email protected]:
[email protected]([email protected]([email protected]))([email protected]):
dependencies:
follow-redirects: 1.16.3
follow-redirects: 1.16.3([email protected]([email protected]))
form-data: 4.0.6
https-proxy-agent: 5.0.1
https-proxy-agent: 5.0.1([email protected])
proxy-from-env: 2.1.0
transitivePeerDependencies:
- debug
@@ -2445,7 +2496,7 @@ snapshots:
[email protected]: {}
[email protected].3: {}
[email protected].4: {}
[email protected]:
dependencies:
@@ -2454,9 +2505,11 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
[email protected]:
[email protected]([email protected]):
dependencies:
ms: 2.1.3
optionalDependencies:
supports-color: 7.2.0
[email protected]: {}
@@ -2600,7 +2653,9 @@ snapshots:
optionalDependencies:
picomatch: 4.0.7
[email protected]: {}
[email protected]([email protected]([email protected])):
optionalDependencies:
debug: 4.4.3([email protected])
[email protected]:
dependencies:
@@ -2675,10 +2730,10 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
[email protected]:
[email protected]([email protected]):
dependencies:
agent-base: 6.0.2
debug: 4.4.3
agent-base: 6.0.2([email protected])
debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2968,11 +3023,11 @@ snapshots:
[email protected]: {}
[email protected](@vue/[email protected])([email protected])([email protected]5([email protected])):
[email protected](@vue/[email protected])([email protected])([email protected]6([email protected])):
dependencies:
'@vue/devtools-api': 8.2.1
nostics: 1.3.0
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
optionalDependencies:
typescript: 6.0.3
@@ -3030,18 +3085,18 @@ snapshots:
gopd: 1.2.0
set-function-name: 2.0.2
[email protected]([email protected]5([email protected])):
[email protected]([email protected]6([email protected])):
dependencies:
'@floating-ui/vue': 2.0.1([email protected]5([email protected]))
'@floating-ui/vue': 2.0.1([email protected]6([email protected]))
'@internationalized/date': 3.10.1
'@internationalized/number': 3.6.5
'@tanstack/vue-virtual': 3.13.14([email protected]5([email protected]))
'@vueuse/core': 14.4.0([email protected]5([email protected]))
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
'@tanstack/vue-virtual': 3.13.14([email protected]6([email protected]))
'@vueuse/core': 14.4.0([email protected]6([email protected]))
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
aria-hidden: 1.2.6
defu: 6.1.7
ohash: 2.0.11
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
[email protected]:
dependencies:
@@ -3124,6 +3179,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]:
@@ -3240,9 +3297,9 @@ snapshots:
[email protected]: {}
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected])):
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected])):
dependencies:
'@vue-macros/common': 3.1.4([email protected]5([email protected]))
'@vue-macros/common': 3.1.4([email protected]6([email protected]))
'@vue/devtools-api': 8.2.1
ast-walker-scope: 0.10.0
chokidar: 6.0.0
@@ -3258,10 +3315,10 @@ snapshots:
tinyglobby: 0.2.17
unplugin: 3.7.0([email protected])([email protected])([email protected]([email protected])([email protected]))
unplugin-utils: 0.3.2
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
optionalDependencies:
'@vue/compiler-sfc': 3.5.45
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
vite: 8.3.8([email protected])([email protected])
transitivePeerDependencies:
- '@farmfe/core'
@@ -3280,13 +3337,13 @@ snapshots:
'@vue/language-core': 3.3.14
typescript: 6.0.3
[email protected]5([email protected]):
[email protected]6([email protected]):
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/compiler-sfc': 3.5.45
'@vue/runtime-dom': 3.5.45
'@vue/server-renderer': 3.5.45
'@vue/shared': 3.5.45
'@vue/compiler-dom': 3.5.46
'@vue/compiler-sfc': 3.5.46
'@vue/runtime-dom': 3.5.46
'@vue/server-renderer': 3.5.46
'@vue/shared': 3.5.46
optionalDependencies:
typescript: 6.0.3
+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,8 +91,8 @@
:label="bypassForm.type === 'cve' ? 'CVE ID' : 'Package'"
:hint="
bypassForm.type === 'cve'
? 'Enter the CVE ID, for example CVE-2021-23337.'
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions.'
? '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
>
@@ -137,6 +144,24 @@
</DialogContent>
</Dialog>
<Dialog v-model:open="showKeyDialog">
<DialogContent size="sm">
<DialogHeader>
<DialogTitle>Admin API key</DialogTitle>
<DialogDescription>Enter your admin API key to manage bypasses.</DialogDescription>
</DialogHeader>
<form class="flex flex-col gap-4" @submit.prevent="submitApiKey">
<Field label="API key" required>
<Input v-model="keyInput" type="password" autocomplete="off" />
</Field>
<DialogFooter>
<Button variant="outline" @click="showKeyDialog = false">Cancel</Button>
<Button type="submit" :disabled="keyInput.trim() === ''">Continue</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<ConfirmDialog
v-model:open="showDeleteModal"
title="Delete bypass?"
@@ -152,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,
@@ -173,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()
@@ -202,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)
@@ -220,8 +237,10 @@ 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)
const filteredBypasses = computed(() => {
let filtered = bypasses.value
@@ -254,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 {
@@ -263,17 +282,31 @@ onMounted(() => {
}
})
function promptForApiKey() {
const key = prompt('Enter your admin API key:')
if (key) {
apiKey.value = key
localStorage.setItem('admin_api_key', key)
fetchBypasses()
} else {
error.value = 'Admin API key required to manage bypasses'
}
// A package page links here with the package to cover.
function prefillFromQuery() {
const { type, target } = route.query
if (typeof target !== 'string' || target === '') return
bypassForm.value = { ...EMPTY_FORM, type: type === 'cve' ? 'cve' : 'package', target }
showCreateModal.value = true
}
function promptForApiKey() {
keyInput.value = ''
showKeyDialog.value = true
}
function submitApiKey() {
const key = keyInput.value.trim()
if (!key) return
adminKey.save(key)
showKeyDialog.value = false
fetchBypasses()
}
watch(showKeyDialog, (open) => {
if (!open && !apiKey.value) error.value = 'Admin API key required to manage bypasses'
})
async function fetchBypasses() {
if (!apiKey.value) {
promptForApiKey()
@@ -303,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'
}
@@ -422,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' },
@@ -444,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')
})
})
-316
View File
@@ -1,316 +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 { formatBytes, formatNumber } 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 version = typeof p.version === 'string' ? `@${p.version}` : ''
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' },
{ 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>
+141 -228
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">v{{ version }}</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,127 +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 } 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)
interface BypassInfo {
id: string
reason: string
created_by: string
expires_at: string
}
interface Vulnerability {
id: string
severity: string
title: string
description: string
references: string[]
fixed_in: string
bypassed: boolean
bypass?: BypassInfo
}
interface VulnerabilityResponse {
scanned: boolean
scanner: string
scanned_at: string
status: string
vulnerabilities: Vulnerability[]
vulnerability_count: number
severity_counts: {
critical: number
high: number
moderate: number
low: number
}
bypassed_count: number
}
const 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 -229
View File
@@ -1,131 +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">
<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 }} 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"
@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"
@@ -134,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
@@ -282,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>
-210
View File
@@ -1,210 +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')
})
})
-180
View File
@@ -1,180 +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>
<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 {
Card,
CardContent,
CardHeader,
CardTitle,
DataTable,
ErrorState,
KpiTile,
LoadingState,
PageHeader,
StatGroup,
type DataTableColumn,
} from '@perfect-design/ui'
import { formatBytes, 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 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>
+186
View File
@@ -0,0 +1,186 @@
<template>
<div class="flex flex-col gap-6">
<PageHeader title="System" description="The policy the proxy applies, the scanners behind it, and the settings that shape the cache.">
<template #actions>
<Badge v-if="info" variant="outline" class="font-mono" data-testid="build-version">{{ info.version }}</Badge>
<Button variant="outline" :icon-start="faRotateRight" @click="load(true)">Refresh</Button>
</template>
</PageHeader>
<LoadingState v-if="!info && !error" variant="card" label="Loading system settings..." />
<ErrorState v-else-if="!info" variant="card" title="Could not load system settings" :message="error ?? ''" @retry="load(true)" />
<template v-else>
<div class="grid gap-6 lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle as="h2">Policy</CardTitle>
<CardDescription>What clears a package and what holds it.</CardDescription>
</CardHeader>
<CardContent>
<DescriptionList :columns="1" divided data-testid="policy-list">
<DescriptionItem term="Scanning">
<StatusBadge :status="info.security.enabled ? 'on' : 'off'" :label="info.security.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
</DescriptionItem>
<DescriptionItem term="Block policy">{{ describePolicy(info.security) }}</DescriptionItem>
<DescriptionItem term="When a scan fails">
{{ info.security.fail_closed ? 'Fail-closed. The package is held.' : 'Fail-open on scanner outage. The package is served and the scan retried.' }}
</DescriptionItem>
<DescriptionItem term="Scan on download">{{ info.security.scan_on_download ? 'Yes' : 'No' }}</DescriptionItem>
<DescriptionItem term="First download waits">up to {{ formatDuration(info.security.scan_wait_timeout) }} for its scan</DescriptionItem>
</DescriptionList>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Rescans</CardTitle>
<CardDescription>Cached packages are inspected again as advisories change.</CardDescription>
</CardHeader>
<CardContent>
<DescriptionList :columns="1" divided data-testid="rescan-list">
<DescriptionItem term="Interval">{{ duration(info.security.rescan.interval, 'Rescans are off') }}</DescriptionItem>
<DescriptionItem term="Active window">{{ duration(info.security.rescan.active_window, 'Every cached package') }}</DescriptionItem>
<DescriptionItem term="Parallel scans">{{ info.security.rescan.concurrency }}</DescriptionItem>
<DescriptionItem term="Rescan on access">{{ info.security.rescan.on_access ? 'Yes. A stale hit is rescanned before it is served.' : 'No' }}</DescriptionItem>
</DescriptionList>
</CardContent>
</Card>
</div>
<RescanPanel :enabled="info.security.enabled" :concurrency="info.security.rescan.concurrency" />
<Card>
<CardHeader>
<CardTitle as="h2">Inspectors</CardTitle>
<CardDescription>Health is probed at most every 30 seconds. A scanner that is off is not probed.</CardDescription>
</CardHeader>
<CardContent>
<DataTable label="Scanners" layout="cards" density="compact" row-key="name" :columns="scannerColumns" :rows="info.security.scanners">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
<template #cell-state="{ row }">
<StatusBadge :status="scannerState(row)" :label="STATE_LABELS[scannerState(row)]" :tones="STATE_TONES" />
</template>
<template #cell-version="{ row }">{{ scannerVersion(row) || 'Not applicable' }}</template>
</DataTable>
</CardContent>
</Card>
<div class="grid gap-6 lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle as="h2">Cache</CardTitle>
<CardDescription>Limits and where packages come from.</CardDescription>
</CardHeader>
<CardContent>
<DescriptionList :columns="1" divided data-testid="cache-list">
<DescriptionItem term="Size limit">{{ info.cache.max_size > 0 ? formatBytes(info.cache.max_size) : 'None' }}</DescriptionItem>
<DescriptionItem term="Idle eviction">{{ duration(info.cache.idle_ttl, 'Off', 'Removed after ', ' without a request') }}</DescriptionItem>
<DescriptionItem term="Default TTL">{{ duration(info.cache.default_ttl, 'None') }}</DescriptionItem>
<DescriptionItem v-for="(host, registry) in info.upstreams" :key="registry" :term="`Upstream ${registry}`">{{ host || 'Not set' }}</DescriptionItem>
</DescriptionList>
</CardContent>
</Card>
<Card data-testid="prewarming">
<CardHeader>
<CardTitle as="h2">Pre-warming</CardTitle>
<CardDescription>Fetches the most requested packages ahead of clients.</CardDescription>
</CardHeader>
<CardContent class="flex flex-col gap-4">
<DescriptionList :columns="1" divided>
<DescriptionItem term="Status">
<StatusBadge :status="info.prewarming.enabled ? 'on' : 'off'" :label="info.prewarming.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
</DescriptionItem>
<DescriptionItem term="Interval">{{ duration(info.prewarming.interval, 'None') }}</DescriptionItem>
<DescriptionItem term="Top packages">{{ info.prewarming.top_packages }}</DescriptionItem>
</DescriptionList>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<Button :icon-start="faRotateRight" :loading="triggering" :disabled="!info.prewarming.enabled" @click="trigger">Run a cycle now</Button>
<p class="m-0 text-sm text-muted-foreground">
{{ info.prewarming.enabled ? 'Needs the admin API key.' : 'Pre-warming is off in the configuration.' }}
</p>
</div>
</CardContent>
</Card>
</div>
</template>
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a pre-warming cycle." @saved="trigger" />
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import axios from 'axios'
import {
Badge,
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
DataTable,
DescriptionItem,
DescriptionList,
ErrorState,
LoadingState,
PageHeader,
StatusBadge,
useToastStore,
type DataTableColumn,
} from '@perfect-design/ui'
import AdminKeyDialog from './parts/AdminKeyDialog.vue'
import RescanPanel from './parts/RescanPanel.vue'
import { useAdminKey } from '@/lib/adminKey'
import { formatBytes, formatDuration } from '@/lib/format'
import { faRotateRight } from '@/lib/icons'
import { describePolicy, scannerState, scannerVersion, useSystem, type ScannerInfo } from '@/lib/system'
const { info, error, load } = useSystem()
const adminKey = useAdminKey()
const toasts = useToastStore()
const triggering = ref(false)
const showKeyDialog = ref(false)
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
const scannerColumns: DataTableColumn<ScannerInfo>[] = [
{ key: 'name', header: 'Scanner', rowHeader: true },
{ key: 'state', header: 'State', accessor: (s) => scannerState(s) },
{ key: 'version', header: 'Version' },
]
/** Seconds as words; zero means the feature is off, so `zero` explains that. */
function duration(seconds: number, zero: string, before = '', after = ''): string {
return seconds === 0 ? zero : `${before}${formatDuration(seconds)}${after}`
}
async function trigger() {
adminKey.load()
if (!adminKey.key.value) {
showKeyDialog.value = true
return
}
triggering.value = true
try {
await axios.post('/api/admin/prewarming/trigger', null, { headers: adminKey.headers.value })
toasts.success('Pre-warming started', 'The cycle runs in the background.')
} catch (err) {
const status = (err as { response?: { status?: number } }).response?.status
if (status === 401 || status === 403) {
adminKey.clear()
toasts.error('Admin key refused', 'Enter a key with the admin role.')
} else {
toasts.error('Could not start pre-warming', err instanceof Error ? err.message : 'Request failed')
}
} finally {
triggering.value = false
}
}
onMounted(() => void load(true))
</script>
+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,162 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import RescanPanel from './RescanPanel.vue'
import { mountStrict } from '@/test/mountStrict'
vi.mock('axios')
const idle = { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 }
const running = { enabled: true, running: true, scope: 'vulnerable', queued: 10, done: 3, failed: 1, elapsed_seconds: 40, eta_seconds: 60 }
let estimate: unknown
const finished = { ...running, running: false, done: 9 }
let restore: (() => void) | undefined
let statuses: Array<typeof idle | typeof running>
beforeEach(() => {
localStorage.setItem('admin_api_key', 'test-key')
statuses = [idle]
estimate = { vulnerable: { artifacts: 12, seconds: 30 }, all: { artifacts: 1200, seconds: 6000 }, avg_scan_seconds: 10, concurrency: 2 }
vi.mocked(axios.get).mockReset()
vi.mocked(axios.post).mockReset()
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url === '/api/admin/rescan/status') return { data: statuses.length > 1 ? statuses.shift() : statuses[0] } as never
if (url === '/api/admin/rescan/estimate') return { data: estimate } as never
throw new Error(`unexpected request: ${url}`)
})
})
afterEach(() => {
restore?.()
restore = undefined
localStorage.clear()
vi.useRealTimers()
})
async function open(props = { enabled: true, concurrency: 2 }) {
const pinia = createPinia()
setActivePinia(pinia)
const mounted = await mountStrict(RescanPanel, { props, global: { plugins: [pinia] } })
restore = mounted.restore
await flushPromises()
return mounted.wrapper
}
const body = () => document.body.textContent ?? ''
function dialogButton(label: string): HTMLButtonElement {
const btn = [...document.body.querySelectorAll('[role="alertdialog"] button, [role="dialog"] button')].find((b) => b.textContent?.trim() === label)
if (!btn) throw new Error(`no button "${label}"`)
return btn as HTMLButtonElement
}
describe('RescanPanel', () => {
it('starts a vulnerable rescan with the admin key and shows progress', async () => {
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
statuses = [idle, running]
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'vulnerable' }, { headers: { Authorization: 'Bearer test-key' } })
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned, 1 failed, of 10 queued')
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('A rescan is running')
})
it('asks before rescanning everything and says how long it takes', async () => {
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 1200, scope: 'all' } })
const wrapper = await open()
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
await flushPromises()
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
expect(body()).toContain('re-runs all scanners on every cached artifact')
expect(body()).toContain('1,200 artifacts, 2 at a time and 10.0 seconds each on recent scans: roughly 100 minutes')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/admin/rescan/estimate', { headers: { Authorization: 'Bearer test-key' } })
dialogButton('Rescan everything').click()
await flushPromises()
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'all' }, expect.anything())
})
it('does not invent an estimate before any scan was timed', async () => {
estimate = { vulnerable: { artifacts: 1, seconds: null }, all: { artifacts: 7, seconds: null }, avg_scan_seconds: 0, concurrency: 2 }
const wrapper = await open()
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
await flushPromises()
expect(body()).toContain('No scan has been timed yet, so there is no estimate.')
expect(body()).not.toContain('roughly')
})
it('shows the live rate and the time left while a rescan runs', async () => {
statuses = [running]
const wrapper = await open()
// 4 processed in 40 s is 6 a minute; the server says 60 s remain.
expect(wrapper.get('[data-testid="rescan-live"]').text()).toBe('6.0 artifacts a minute. About 1 minute left.')
})
it('polls until the rescan finishes and then stops', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
statuses = [idle, running, running, finished]
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
const statusCalls = () => vi.mocked(axios.get).mock.calls.filter(([url]) => url === '/api/admin/rescan/status').length
await vi.advanceTimersByTimeAsync(2100)
await vi.advanceTimersByTimeAsync(2100)
await flushPromises()
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('Finished.')
const settled = statusCalls()
await vi.advanceTimersByTimeAsync(10000)
expect(statusCalls()).toBe(settled)
})
it('shows the running rescan when the server answers 409', async () => {
vi.mocked(axios.post).mockRejectedValue({ response: { status: 409 } })
statuses = [idle, running]
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned')
})
it('is disabled and explains why when scanning is off', async () => {
const wrapper = await open({ enabled: false, concurrency: 2 })
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
expect(wrapper.get('[data-testid="rescan-all"]').attributes('disabled')).toBeDefined()
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('Security scanning is off')
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
})
it('asks for the admin key before it posts anything', async () => {
localStorage.clear()
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
expect(body()).toContain('Enter your admin API key to start a rescan.')
})
it('asks for the admin key before it sizes a full rescan', async () => {
localStorage.clear()
const wrapper = await open()
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
await flushPromises()
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith('/api/admin/rescan/estimate', expect.anything())
expect(body()).toContain('Enter your admin API key to start a rescan.')
})
it('forgets a key the server refuses', async () => {
vi.mocked(axios.post).mockRejectedValue({ response: { status: 403 } })
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(localStorage.getItem('admin_api_key')).toBeNull()
})
})
@@ -0,0 +1,201 @@
<template>
<Card data-testid="rescan-panel">
<CardHeader>
<CardTitle as="h2">Rescan</CardTitle>
<CardDescription>Scan cached packages again now, without waiting for the interval. Stored findings are refreshed with the current scanners.</CardDescription>
</CardHeader>
<CardContent class="flex flex-col gap-4">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<Button :icon-start="faRotateRight" :loading="starting === 'vulnerable'" :disabled="blocked" data-testid="rescan-vulnerable" @click="start('vulnerable')">
Rescan vulnerable packages
</Button>
<Button variant="outline" :icon-start="faRotateRight" :loading="starting === 'all'" :disabled="blocked" data-testid="rescan-all" @click="askAll">
Rescan everything
</Button>
</div>
<p class="m-0 text-sm text-muted-foreground" data-testid="rescan-note">{{ note }}</p>
<div v-if="status && status.queued > 0" class="flex flex-col gap-2" data-testid="rescan-progress">
<Progress :model-value="processed" :max="status.queued" label="Rescan progress" show-value />
<p class="m-0 text-sm" data-testid="rescan-counts">
{{ status.running ? 'Running.' : 'Finished.' }}
{{ formatNumber(status.done) }} scanned, {{ formatNumber(status.failed) }} failed, of {{ formatNumber(status.queued) }} queued.
</p>
<p v-if="status.running && liveRate" class="m-0 text-sm text-muted-foreground" data-testid="rescan-live">{{ liveRate }}</p>
</div>
</CardContent>
<ConfirmDialog
v-model:open="confirmOpen"
title="Rescan every cached package?"
:description="everythingWarning"
confirm-label="Rescan everything"
@confirm="start('all')"
/>
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a rescan." @saved="resume" />
</Card>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import axios from 'axios'
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, ConfirmDialog, Progress, useToastStore } from '@perfect-design/ui'
import AdminKeyDialog from './AdminKeyDialog.vue'
import { useAdminKey } from '@/lib/adminKey'
import { formatApproxDuration, formatNumber } from '@/lib/format'
import { faRotateRight } from '@/lib/icons'
type Scope = 'vulnerable' | 'all'
/** Response of GET /api/admin/rescan/status. */
interface RescanStatus {
enabled: boolean
running: boolean
scope: string
queued: number
done: number
failed: number
elapsed_seconds?: number
/** Absent until the first artifact is processed. */
eta_seconds?: number
}
/** Response of GET /api/admin/rescan/estimate; seconds is null until a scan has been timed. */
interface RescanEstimate {
vulnerable: { artifacts: number; seconds: number | null }
all: { artifacts: number; seconds: number | null }
avg_scan_seconds: number
concurrency: number
}
const props = defineProps<{ enabled: boolean; concurrency: number }>()
const POLL_MS = 2000
const adminKey = useAdminKey()
const toasts = useToastStore()
const status = ref<RescanStatus | null>(null)
const starting = ref<Scope | null>(null)
const confirmOpen = ref(false)
const showKeyDialog = ref(false)
const estimate = ref<RescanEstimate | null>(null)
let pendingScope: Scope | null = null
let pendingConfirm = false
let timer: ReturnType<typeof setTimeout> | undefined
const running = computed(() => status.value?.running === true)
const blocked = computed(() => !props.enabled || running.value || starting.value !== null)
const processed = computed(() => (status.value ? status.value.done + status.value.failed : 0))
const note = computed(() => {
if (!props.enabled) return 'Security scanning is off in the configuration.'
if (running.value) return 'A rescan is running. Another one can start when it finishes.'
return 'Needs the admin API key. The rescan runs in the background.'
})
const liveRate = computed(() => {
const st = status.value
const elapsed = st?.elapsed_seconds ?? 0
if (!st || processed.value === 0 || elapsed <= 0) return ''
const perMinute = (processed.value / elapsed) * 60
const rate = `${perMinute < 10 ? perMinute.toFixed(1) : formatNumber(Math.round(perMinute))} artifacts a minute`
return st.eta_seconds === undefined ? rate : `${rate}. About ${formatApproxDuration(st.eta_seconds)} left.`
})
const everythingWarning = computed(() => {
const base = 'This re-runs all scanners on every cached artifact.'
const est = estimate.value
const all = est?.all
if (!est || !all) return `${base} It can take a long time.`
const count = `${formatNumber(all.artifacts)} artifacts`
if (all.seconds === null) return `${base} ${count} are cached. No scan has been timed yet, so there is no estimate.`
const { avg_scan_seconds: avg, concurrency } = est
return `${base} ${count}, ${concurrency} at a time and ${avg.toFixed(1)} seconds each on recent scans: roughly ${formatApproxDuration(all.seconds)}.`
})
function errorStatus(err: unknown): number | undefined {
return (err as { response?: { status?: number } }).response?.status
}
async function refresh() {
const res = await axios.get<RescanStatus>('/api/admin/rescan/status', { headers: adminKey.headers.value })
status.value = res.data
return res.data
}
function schedulePoll() {
clearTimeout(timer)
timer = setTimeout(async () => {
try {
if ((await refresh()).running) schedulePoll()
} catch {
// The next click shows the error; a failed poll must not toast every two seconds.
}
}, POLL_MS)
}
async function askAll() {
adminKey.load()
if (!adminKey.key.value) {
pendingConfirm = true
showKeyDialog.value = true
return
}
confirmOpen.value = true
try {
estimate.value = (await axios.get<RescanEstimate>('/api/admin/rescan/estimate', { headers: adminKey.headers.value })).data
} catch {
estimate.value = null
}
}
async function start(scope: Scope) {
adminKey.load()
if (!adminKey.key.value) {
pendingScope = scope
showKeyDialog.value = true
return
}
starting.value = scope
try {
const res = await axios.post<{ queued: number }>('/api/admin/rescan', { scope }, { headers: adminKey.headers.value })
toasts.success('Rescan started', `${formatNumber(res.data.queued)} artifacts queued.`)
await refresh()
if (status.value?.running) schedulePoll()
} catch (err) {
const code = errorStatus(err)
if (code === 409) {
toasts.info('A rescan is already running', 'Wait for it to finish.')
await refresh().then(schedulePoll, () => undefined)
} else if (code === 401 || code === 403) {
adminKey.clear()
toasts.error('Admin key refused', 'Enter a key with the admin role.')
} else {
toasts.error('Could not start the rescan', err instanceof Error ? err.message : 'Request failed')
}
} finally {
starting.value = null
}
}
function resume() {
const scope = pendingScope
pendingScope = null
if (pendingConfirm) {
pendingConfirm = false
void askAll()
} else if (scope) {
void start(scope)
}
}
onMounted(async () => {
adminKey.load()
if (!props.enabled || !adminKey.key.value) return
try {
if ((await refresh()).running) schedulePoll()
} catch {
// Progress is optional here; a stale or missing key surfaces when the admin starts a rescan.
}
})
onUnmounted(() => clearTimeout(timer))
</script>
@@ -0,0 +1,55 @@
<template>
<Card data-testid="scanner-health">
<CardHeader>
<CardTitle as="h2">Inspectors</CardTitle>
<CardDescription>The scanners that examine each package. Health is probed every 30 seconds.</CardDescription>
</CardHeader>
<CardContent>
<ErrorState v-if="error && !info" variant="inline" title="Could not load scanners" :message="error" @retry="load(true)" />
<LoadingState v-else-if="!info" layout="inline" label="Loading scanners..." />
<EmptyState
v-else-if="!info.security.enabled"
size="sm"
title="Scanning is off"
description="Packages are served without inspection."
/>
<ul v-else class="m-0 grid list-none grid-cols-1 gap-2 p-0 sm:grid-cols-2 xl:grid-cols-3">
<li
v-for="scanner in info.security.scanners"
:key="scanner.name"
class="flex items-start justify-between gap-3 rounded-md border px-3 py-2"
:data-scanner="scanner.name"
>
<span class="min-w-0">
<span class="block break-words text-sm font-medium" :title="scanner.name">{{ scanner.name }}</span>
<span v-if="scannerVersion(scanner)" class="block text-xs text-muted-foreground">{{ scannerVersion(scanner) }}</span>
</span>
<StatusBadge :status="scannerState(scanner)" :label="STATE_LABELS[scannerState(scanner)]" :tones="STATE_TONES" />
</li>
</ul>
</CardContent>
</Card>
</template>
<script setup lang="ts">
import { onMounted } from 'vue'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
EmptyState,
ErrorState,
LoadingState,
StatusBadge,
} from '@perfect-design/ui'
import { scannerState, scannerVersion, useSystem } from '@/lib/system'
const { info, error, load } = useSystem()
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
onMounted(() => void load())
</script>
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import TopPackages from './TopPackages.vue'
import { mountStrict } from '@/test/mountStrict'
vi.mock('axios')
let restore: (() => void) | undefined
const row = (registry: string, name: string, download_count: number) => ({ registry, name, version: '1.0.0', download_count })
function serve(rows: unknown[], trending: unknown[] = []) {
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.startsWith('/api/analytics/trending')) return { data: { packages: trending } } as never
if (url.startsWith('/api/packages?layout=rows')) return { data: { packages: rows } } as never
throw new Error(`unexpected request: ${url}`)
})
}
async function open() {
const mounted = await mountStrict(TopPackages)
restore = mounted.restore
await flushPromises()
return mounted.wrapper
}
beforeEach(() => {
vi.mocked(axios.get).mockReset()
})
afterEach(() => {
restore?.()
restore = undefined
})
describe('TopPackages', () => {
it('ranks packages by the stored download counts, so a restart does not empty it', async () => {
serve([row('npm', 'left-pad', 12), row('npm', 'left-pad', 5), row('pypi', 'six', 9)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('npm · left-pad')
expect(text).toContain('pypi · six')
expect(text).not.toContain('No downloads yet')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200')
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith(expect.stringContaining('/api/analytics/top'))
})
it('adds the versions of a package and orders by the sum', async () => {
serve([row('npm', 'a', 10), row('npm', 'b', 15), row('npm', 'a', 9)])
const wrapper = await open()
const labels = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
expect(labels[0]).toContain('npm · a')
expect(labels[1]).toContain('npm · b')
})
it('counts a Go module once, by its zip, and not its .mod and .info files', async () => {
serve([
row('go', 'github.com/google/uuid/@v/v1.6.0.zip', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.mod', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.info', 4),
])
const wrapper = await open()
const entries = wrapper.findAll('[data-testid="top-packages"] li')
expect(entries).toHaveLength(1)
expect(entries[0].text()).toContain('go · github.com/google/uuid')
expect(entries[0].text()).toContain('4')
expect(entries[0].text()).not.toContain('12')
})
it('says so when no package has a download', async () => {
serve([row('npm', 'left-pad', 0)])
const wrapper = await open()
expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet')
})
it('shows the change against the previous 7 days for trending packages', async () => {
serve([], [
{ Registry: 'npm', Name: 'left-pad', Downloads: 9, RecentDownloads: 9, PreviousDownloads: 4 },
{ Registry: 'npm', Name: 'six', Downloads: 3, RecentDownloads: 3, PreviousDownloads: 8 },
])
const wrapper = await open()
const rows = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
const pad = rows.find((r) => r.includes('left-pad'))
const six = rows.find((r) => r.includes('six'))
expect(pad).toMatch(/\+5/)
expect(six).toMatch(/[-−]5/)
})
it('names where each ranking comes from', async () => {
serve([row('npm', 'left-pad', 3)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('The counts survive restarts.')
expect(text).toContain('the change from the 7 days before')
expect(text).not.toContain('restarts with the server')
})
})
@@ -0,0 +1,122 @@
<template>
<div class="grid gap-6 lg:grid-cols-2" data-testid="top-packages">
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Most requested</CardTitle>
<CardDescription>Downloads served from the cache. The counts survive restarts.</CardDescription>
</CardHeader>
<CardContent>
<LoadingState v-if="loading" layout="inline" label="Loading top packages..." />
<ErrorState v-else-if="error" variant="inline" title="Could not load top packages" :message="error" @retry="load" />
<EmptyState v-else-if="top.length === 0" size="sm" title="No downloads yet" description="Rankings appear after the first download." />
<Leaderboard v-else label="Most requested packages" bars :entries="top" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Downloads', delta: 'Change' }" />
</CardContent>
</Card>
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Trending</CardTitle>
<CardDescription>Downloads in the last 7 days, and the change from the 7 days before. The counts survive restarts.</CardDescription>
</CardHeader>
<CardContent>
<LoadingState v-if="loading" layout="inline" label="Loading trending packages..." />
<ErrorState v-else-if="error" variant="inline" title="Could not load trending packages" :message="error" @retry="load" />
<EmptyState v-else-if="trending.length === 0" size="sm" title="Nothing trending" description="No package was downloaded in the last 7 days." />
<Leaderboard v-else label="Trending packages" bars :entries="trending" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Last 7 days', delta: 'Change' }" />
</CardContent>
</Card>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import axios from 'axios'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
EmptyState,
ErrorState,
Leaderboard,
LoadingState,
type LeaderboardEntry,
} from '@perfect-design/ui'
import { modulePath } from '@/lib/format'
/** The trending endpoint serialises Go field names. */
interface PopularPackage {
Registry: string
Name: string
Downloads: number
RecentDownloads: number
PreviousDownloads?: number
}
/** One stored version row; its count is kept in the database. */
interface DownloadRow {
registry: string
name: string
download_count: number
}
const LIMIT = 8
// Go keeps one row per file (.zip, .mod, .info) of a version; only the zip is a module download.
const GO_METADATA = /\.(mod|info)$/
const ROWS_URL = '/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200'
const stored = ref<DownloadRow[]>([])
const recent = ref<PopularPackage[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
// Rows with equal registry and module path (a Go module's .zip, .mod and .info) are one package.
function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number, change?: (p: PopularPackage) => number): LeaderboardEntry[] {
const totals = new Map<string, LeaderboardEntry>()
for (const row of rows) {
const id = `${row.Registry}/${modulePath(row.Name)}`
const existing = totals.get(id)
if (existing) {
existing.value += pick(row)
if (change) existing.delta = (existing.delta ?? 0) + change(row)
} else {
totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row), ...(change ? { delta: change(row) } : {}) })
}
}
return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT)
}
const top = computed(() =>
entries(
stored.value
.filter((r) => !(r.registry === 'go' && GO_METADATA.test(r.name)))
.map((r) => ({ Registry: r.registry, Name: r.name, Downloads: r.download_count, RecentDownloads: 0 })),
(p) => p.Downloads,
),
)
const trending = computed(() =>
entries(
recent.value,
(p) => p.RecentDownloads,
(p) => p.RecentDownloads - (p.PreviousDownloads ?? 0),
),
)
async function load() {
loading.value = true
error.value = null
try {
const [topRes, trendRes] = await Promise.all([
axios.get<{ packages: DownloadRow[] }>(ROWS_URL),
axios.get<{ packages: PopularPackage[] }>('/api/analytics/trending?limit=50'),
])
stored.value = topRes.data.packages ?? []
recent.value = trendRes.data.packages ?? []
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to load package rankings'
} finally {
loading.value = false
}
}
onMounted(load)
</script>
@@ -0,0 +1,12 @@
<template>
<StatusBadge :status="verdict" :label="VERDICT_LABELS[verdict]" :tones="TONES" :title="VERDICT_MEANINGS[verdict]" />
</template>
<script setup lang="ts">
import { StatusBadge } from '@perfect-design/ui'
import { VERDICT_LABELS, VERDICT_MEANINGS, VERDICT_TONES, type Verdict } from '@/lib/verdict'
defineProps<{ verdict: Verdict }>()
const TONES = VERDICT_TONES
</script>
@@ -0,0 +1,50 @@
import { afterEach, describe, expect, it } from 'vitest'
import VulnerabilityTable from './VulnerabilityTable.vue'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
import type { VulnerabilityEntry } from '@/lib/report'
let restore: (() => void) | undefined
afterEach(() => {
restore?.()
restore = undefined
})
const entry = (over: Partial<VulnerabilityEntry>): VulnerabilityEntry => ({
id: 'GHSA-xvch-5gv4-984h',
severity: 'critical',
title: 'Prototype pollution',
description: '',
references: [],
fixed_in: '1.2.6',
bypassed: false,
...over,
})
async function open(vulnerabilities: VulnerabilityEntry[]) {
const router = await createTestRouter('/')
const mounted = await mountStrict(VulnerabilityTable, { props: { vulnerabilities }, global: { plugins: [router] } })
restore = mounted.restore
return mounted.wrapper
}
describe('VulnerabilityTable aliases', () => {
it('names the other ids of a finding next to its advisory id', async () => {
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
expect(w.text()).toContain('GHSA-xvch-5gv4-984h')
expect(w.text()).toContain('Also CVE-2021-44906')
})
it('shows no alias line for an older finding without aliases', async () => {
const w = await open([entry({})])
expect(w.text()).not.toContain('Also ')
})
it('offers a bypass link for the id and for each alias', async () => {
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
await w.find('tbody tr').trigger('click')
const hrefs = w.findAll('a').map((a) => a.attributes('href') ?? '')
expect(hrefs).toContain('/admin/bypasses?type=cve&target=GHSA-xvch-5gv4-984h')
expect(hrefs).toContain('/admin/bypasses?type=cve&target=CVE-2021-44906')
})
})
@@ -0,0 +1,129 @@
<template>
<Table label="Detected vulnerabilities" layout="cards">
<TableHeader>
<TableRow>
<TableHead>Severity</TableHead>
<TableHead>Advisory</TableHead>
<TableHead>Summary</TableHead>
<TableHead>Fixed in</TableHead>
<TableHead>Found by</TableHead>
<TableHead align="center">Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<template v-for="vuln in sorted" :key="vuln.id">
<TableRow class="cursor-pointer" :selected="isOpen(vuln.id)" @click="toggle(vuln.id)">
<TableCell label="Severity">
<span class="flex flex-wrap items-center gap-2">
<StatusBadge :status="vuln.severity" :tones="SEVERITY_TONES" :label="formatSeverityName(vuln.severity)" />
<StatusBadge v-if="vuln.bypassed" status="bypassed" label="Bypassed" :tones="{ bypassed: 'info' }" />
</span>
</TableCell>
<TableCell label="Advisory" class="font-mono font-medium">
<span class="block">{{ vuln.id }}</span>
<span v-if="vuln.aliases?.length" class="block text-xs font-normal text-muted-foreground">
Also {{ vuln.aliases.join(', ') }}
</span>
</TableCell>
<TableCell label="Summary">
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
</TableCell>
<TableCell label="Fixed in">
<span v-if="vuln.fixed_in">{{ withVersionPrefix(vuln.fixed_in) }}</span>
<span v-else class="text-muted-foreground">No fix yet</span>
</TableCell>
<TableCell label="Found by">
<span class="flex flex-wrap gap-1">
<Badge v-for="scanner in vuln.detected_by ?? []" :key="scanner" variant="secondary">{{ scanner }}</Badge>
</span>
</TableCell>
<TableCell label="Details" align="center">
<IconButton
size="icon-sm"
:icon="isOpen(vuln.id) ? faChevronUp : faChevronDown"
:label="`${isOpen(vuln.id) ? 'Hide' : 'Show'} details for ${vuln.id}`"
:aria-expanded="isOpen(vuln.id)"
@click.stop="toggle(vuln.id)"
/>
</TableCell>
</TableRow>
<TableRow v-if="isOpen(vuln.id)" :hoverable="false">
<TableCell :colspan="6">
<div class="flex flex-col gap-4 py-2">
<section v-if="vuln.description">
<h3 class="mb-2 text-sm font-semibold">Description</h3>
<Markdown :source="vuln.description" :heading-offset="3" />
</section>
<Callout v-if="vuln.bypassed && vuln.bypass" type="note" title="Bypass active" size="sm">
{{ vuln.bypass.reason }}. Created by {{ vuln.bypass.created_by }}, expires {{ formatDate(vuln.bypass.expires_at) }}.
</Callout>
<Callout v-if="vuln.fixed_in" type="tip" title="Fix available" size="sm">
Upgrade to <strong>{{ withVersionPrefix(vuln.fixed_in) }}</strong> or later.
</Callout>
<section>
<h3 class="mb-2 text-sm font-semibold">Bypass this advisory</h3>
<p class="m-0 mb-1 text-sm text-muted-foreground">A bypass for any of these ids covers this finding.</p>
<ul class="m-0 flex list-none flex-wrap gap-3 p-0 text-sm">
<li v-for="id in [vuln.id, ...(vuln.aliases ?? [])]" :key="id">
<Link :as="RouterLink" :to="{ path: '/admin/bypasses', query: { type: 'cve', target: id } }">{{ id }}</Link>
</li>
</ul>
</section>
<section v-if="vuln.references && vuln.references.length > 0">
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
<li v-for="ref in vuln.references" :key="ref" class="break-all">
<Link :href="ref" external>{{ ref }}</Link>
</li>
</ul>
</section>
</div>
</TableCell>
</TableRow>
</template>
</TableBody>
</Table>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { RouterLink } from 'vue-router'
import {
Badge,
Callout,
IconButton,
Link,
Markdown,
StatusBadge,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@perfect-design/ui'
import { formatDate, withVersionPrefix } from '@/lib/format'
import type { VulnerabilityEntry } from '@/lib/report'
import { faChevronDown, faChevronUp } from '@/lib/icons'
import { SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
const props = defineProps<{ vulnerabilities: readonly VulnerabilityEntry[] }>()
const open = ref(new Set<string>())
const sorted = computed(() => [...props.vulnerabilities].sort((a, b) => severityRank(b.severity) - severityRank(a.severity)))
function isOpen(id: string): boolean {
return open.value.has(id)
}
function toggle(id: string) {
const next = new Set(open.value)
if (!next.delete(id)) next.add(id)
open.value = next
}
</script>
+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)
})
})
+322 -49
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,22 @@ vi.mock('axios')
const API_KEY_STORAGE = 'admin_api_key'
function respond(url: string) {
if (url.startsWith('/api/system')) return { data: SYSTEM }
if (url.startsWith('/api/admin/rescan/status')) return { data: { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 } }
if (url.startsWith('/api/analytics/package/')) return { data: PACKAGE_ANALYTICS }
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES }
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
if (url.startsWith('/api/stats/trend')) return { data: TREND }
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
if (url.includes('layout=rows')) return { data: serveRows(url, PACKAGES) }
const single = /^\/api\/packages\/([^/]+)\/(.+)\/([^/?]+)$/.exec(url)
if (single) {
const row = PACKAGES.find((p) => p.registry === single[1] && p.name === single[2] && p.version === single[3])
if (!row) throw Object.assign(new Error('not found'), { response: { status: 404 } })
return { data: row }
}
if (url.startsWith('/api/packages')) return { data: { packages: PACKAGES } }
throw new Error(`unexpected request: ${url}`)
}
@@ -34,6 +59,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 +82,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 +167,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,14 +229,84 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(document.body.querySelector('textarea')).not.toBeNull()
})
it('Stats renders totals, the storage tile and the registry table', async () => {
const { wrapper, problems } = await smoke(Stats, '/stats')
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([])
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)
const input = Array.from(document.body.querySelectorAll<HTMLInputElement>('input')).find((i) => i.value === 'npm/[email protected]')
expect(input).toBeDefined()
})
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
localStorage.clear()
const prompt = vi.spyOn(window, 'prompt')
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
await flushPromises()
expect(problems).toEqual([])
expect(prompt).not.toHaveBeenCalled()
expect(document.body.textContent).toContain('Enter your admin API key to manage bypasses.')
const input = document.body.querySelector<HTMLInputElement>('input[type="password"]')
expect(input).not.toBeNull()
input!.value = 'secret-key'
input!.dispatchEvent(new Event('input', { bubbles: true }))
await flushPromises()
document.body.querySelector<HTMLFormElement>('input[type="password"]')!.form!.requestSubmit()
await flushPromises()
expect(localStorage.getItem('admin_api_key')).toBe('secret-key')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(
expect.stringContaining('/api/admin/bypasses'),
expect.objectContaining({ headers: { Authorization: 'Bearer secret-key' } }),
)
expect(wrapper.text()).toContain('CVE-2026-0002')
})
it('Insights renders the registry breakdown, scan coverage and daily downloads', async () => {
const { wrapper, problems } = await smoke(Insights, '/stats')
expect(problems).toEqual([])
expect(wrapper.find('h1').text()).toBe('Insights')
const breakdown = wrapper.find('[data-testid="registry-breakdown"]').text()
for (const word of ['npm', 'pypi', 'go', '2 GB']) expect(breakdown).toContain(word)
expect(wrapper.find('[data-testid="scan-coverage"]').text()).toContain('3 of 4')
expect(wrapper.find('[data-testid="daily-downloads"] [role="img"]').exists()).toBe(true)
})
it('System shows the policy, scanners, rescans, cache, pre-warming and build version', async () => {
const { wrapper, problems } = await smoke(System, '/admin/system')
await flushPromises()
expect(problems).toEqual([])
expect(wrapper.find('h1').text()).toBe('System')
expect(wrapper.find('[data-testid="build-version"]').text()).toBe('v1.8.0')
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Blocks any CRITICAL.')
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Fail-closed')
expect(wrapper.find('[data-testid="rescan-list"]').text()).toContain('1 day')
expect(wrapper.find('[data-testid="cache-list"]').text()).toContain('10 GB')
expect(wrapper.text()).toContain('v0.58.1')
expect(wrapper.find('[data-testid="prewarming"] button').text()).toContain('Run a cycle now')
})
it('System starts a pre-warming cycle with the admin key', async () => {
vi.mocked(axios.post).mockResolvedValue({ data: {} })
const { wrapper } = await smoke(System, '/admin/system')
await flushPromises()
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
await flushPromises()
expect(vi.mocked(axios.post)).toHaveBeenCalledWith(
'/api/admin/prewarming/trigger',
null,
expect.objectContaining({ headers: { Authorization: 'Bearer test-key' } }),
)
})
it('System asks for the key before it triggers anything', async () => {
localStorage.clear()
const { wrapper } = await smoke(System, '/admin/system')
await flushPromises()
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
await flushPromises()
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
expect(document.body.textContent).toContain('Enter your admin API key to start a pre-warming cycle.')
})
it('VulnerabilityBadge prints the severity word for every tone', async () => {
@@ -165,7 +324,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.
@@ -174,15 +333,129 @@ 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')
})
})
describe('PyPI rows show the release version, not the file name', () => {
const FILE = 'six-1.17.0-py2.py3-none-any.whl'
const SIX = {
id: 'pypi-six',
registry: 'pypi',
name: 'six',
version: FILE,
release_version: '1.17.0',
size: 1,
cached_at: '2026-02-01T10:00:00Z',
last_accessed: '2026-02-01T10:00:00Z',
download_count: 1,
vulnerabilities: {
scanned: true,
status: 'vulnerable',
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
total: 1,
scannedAt: '2026-02-01T10:05:00Z',
isBlocked: false,
},
}
beforeEach(() => {
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.endsWith('/vulnerabilities')) {
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
}
if (url.includes('layout=rows')) return { data: serveRows(url, [SIX as never]) } as never
if (url === `/api/packages/pypi/six/${FILE}`) return { data: SIX } as never
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
return respond(url) as never
})
})
it('PackageList version column', async () => {
const { wrapper } = await smoke(PackageList, '/packages')
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('Overview activity feed', async () => {
const router = await createTestRouter('/')
const pinia = createPinia()
setActivePinia(pinia)
const rt = useRealtimeStore()
vi.spyOn(rt, 'connect').mockImplementation(() => {})
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
const { wrapper, restore: r } = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
restore = r
await flushPromises()
const feed = wrapper.find('[data-testid="ws-event-feed"]').text()
expect(feed).toContain('[email protected]')
expect(feed).not.toContain('whl')
})
it('Security version column', async () => {
const { wrapper } = await smoke(Security, '/security?tab=allowed')
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('PackageDetails header badge', async () => {
const { wrapper } = await smoke(PackageDetails, `/package/pypi/six/${FILE}`)
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
await router.push(`/package/pypi/six/${FILE}`)
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('PackageDetails falls back to the route version without a release version', async () => {
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
const { wrapper } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
await router.push('/package/npm/left-pad/1.3.0')
await flushPromises()
expect(wrapper.text()).toContain('v1.3.0')
})
it('bypass form tells PyPI users to use the release version', async () => {
const { wrapper } = await smoke(BypassManagementPanel, '/admin/bypasses')
await wrapper.findAll('button').find((b) => b.text() === 'Create bypass')!.trigger('click')
await flushPromises()
const pkg = Array.from(document.body.querySelectorAll<HTMLElement>('button, [role="radio"]')).find((e) => e.textContent?.trim() === 'Package bypass')
pkg!.click()
await flushPromises()
expect(document.body.textContent).toContain('pypi/[email protected]')
})
})
+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)))
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { formatApproxDuration, formatDuration } from './format'
describe('formatDuration', () => {
it.each([
[604800, '7 days'],
[86400, '1 day'],
[129600, '36 hours'],
[3600, '1 hour'],
[5400, '90 minutes'],
[60, '1 minute'],
])('formats %i seconds as %s', (seconds, expected) => {
expect(formatDuration(seconds)).toBe(expected)
})
})
describe('formatApproxDuration', () => {
it.each([
[0, '1 second'],
[40, '40 seconds'],
[59.4, '59 seconds'],
[60, '1 minute'],
[750, '13 minutes'],
[7199, '120 minutes'],
[7200, '2 hours'],
[36000, '10 hours'],
])('%d seconds reads %s', (seconds, expected) => {
expect(formatApproxDuration(seconds)).toBe(expected)
})
})
+28
View File
@@ -11,6 +11,28 @@ export function formatBytes(bytes: number): string {
return Math.round((bytes / Math.pow(BYTES_PER_UNIT, i)) * 100) / 100 + ' ' + BYTE_UNITS[i]
}
const SECONDS_PER_DAY = 86400
const SECONDS_PER_HOUR = 3600
const SECONDS_PER_MINUTE = 60
function plural(n: number, unit: string): string {
return `${n} ${unit}${n === 1 ? '' : 's'}`
}
/** Whole days, hours or minutes, using the largest unit that divides the span evenly. */
export function formatDuration(seconds: number): string {
if (seconds % SECONDS_PER_DAY === 0) return plural(seconds / SECONDS_PER_DAY, 'day')
if (seconds % SECONDS_PER_HOUR === 0) return plural(seconds / SECONDS_PER_HOUR, 'hour')
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
}
/** A span in the largest fitting unit, rounded: "40 seconds", "12 minutes", "3 hours". */
export function formatApproxDuration(seconds: number): string {
if (seconds < SECONDS_PER_MINUTE) return plural(Math.max(1, Math.round(seconds)), 'second')
if (seconds < 2 * SECONDS_PER_HOUR) return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
return plural(Math.round(seconds / SECONDS_PER_HOUR), 'hour')
}
export function formatDate(date: string): string {
if (!date) return 'N/A'
const parsed = new Date(date)
@@ -25,3 +47,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()
})
})
+35 -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,39 +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)
@@ -89,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
}
}
+23 -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,39 +31,50 @@
@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";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Icon/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/IconButton/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Link/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Progress/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ScrollArea/*.js";
@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 +135,8 @@ html {
scroll-behavior: auto !important;
}
}
/* The library sort button is 1rem wider than its cell but shifts left only by the cell padding, so the last column overflows the table. */
[data-slot='table-head']:last-child {
padding-right: calc(1rem - var(--spacing) * 2);
}
+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,
}
}
+3
View File
@@ -5,6 +5,7 @@ import { themeBootScript } from '@perfect-design/ui/stores/theme-boot'
// Get backend URL from environment or use default
const BACKEND_URL = process.env.VITE_BACKEND_URL || 'http://localhost:8080'
const WS_ORIGIN = process.env.VITE_WS_ORIGIN
const FRONTEND_PORT = parseInt(process.env.VITE_PORT || '5173')
// Applies the saved colour mode before first paint so a dark system never flashes light.
@@ -33,6 +34,8 @@ export default defineConfig({
target: BACKEND_URL.replace('http', 'ws'),
ws: true,
changeOrigin: true,
// A backend with an origin allowlist refuses the dev server origin; set this to an allowed one.
...(WS_ORIGIN ? { headers: { Origin: WS_ORIGIN } } : {}),
},
},
},
+7 -7
View File
@@ -15,6 +15,7 @@ require (
github.com/gorilla/websocket v1.5.3
github.com/lib/pq v1.12.3
github.com/prometheus/client_golang v1.25.0
github.com/prometheus/client_model v0.6.3
github.com/rs/zerolog v1.35.1
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
@@ -49,7 +50,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
github.com/aws/smithy-go v1.28.9 // indirect
github.com/aws/smithy-go v1.28.10 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
@@ -70,7 +71,7 @@ require (
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/gofiber/schema v1.10.0 // indirect
github.com/gofiber/schema v1.10.2 // indirect
github.com/gofiber/utils/v2 v2.6.5 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/go-uuid v1.0.4 // indirect
@@ -87,7 +88,7 @@ require (
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/klauspost/compress v1.20.5 // indirect
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5 // indirect
github.com/magiconair/properties v1.18.13 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
@@ -99,7 +100,7 @@ require (
github.com/moby/moby/client v0.6.3 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.5.0 // indirect
github.com/moby/sys/user v0.5.1 // indirect
github.com/moby/sys/userns v0.2.1 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/molecule-man/go-brrr v1.3.1 // indirect
@@ -110,7 +111,6 @@ require (
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/philhofer/fwd v1.2.1 // indirect
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/sagikazarmark/locafero v0.12.0 // indirect
@@ -125,9 +125,9 @@ require (
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.79.0 // indirect
github.com/valyala/fasthttp v1.80.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
+14 -14
View File
@@ -42,8 +42,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY=
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 h1:my9Y6lxcqvPV5k4OTqnxr8XbiTDDRos1leEh050Z93U=
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
@@ -105,8 +105,8 @@ github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI=
github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
github.com/gofiber/schema v1.10.0 h1:d/2/NpHOVD0f29aNvM3KSPmaEDLJZvxW5edtN4Ymd8U=
github.com/gofiber/schema v1.10.0/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
github.com/gofiber/schema v1.10.2 h1:mjqtglIvi/+NK3gJTra6wKOaBLZYx+tdNu7xtaCVPOg=
github.com/gofiber/schema v1.10.2/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
github.com/gofiber/utils/v2 v2.6.5 h1:rU+8ao6LKi3fKOA3sEjfLv1T+2C2IwomeVmEKaqkr4A=
github.com/gofiber/utils/v2 v2.6.5/go.mod h1:OqPxdhDW7fPz0dupDanqf4e5O15IyFKy724y/EY9RI4=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -149,8 +149,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -187,8 +187,8 @@ github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9Kou
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
github.com/moby/sys/user v0.5.0 h1:5+S4lyoavGyX1DGs68NW8xpx48T9+a7ogSUc0KjZg8Y=
github.com/moby/sys/user v0.5.0/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
github.com/moby/sys/user v0.5.1 h1:IMM/21OvpU2icUZczWBwLMf8iBEx1bOoiCQqcy1eKu0=
github.com/moby/sys/user v0.5.1/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8=
github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
@@ -218,8 +218,8 @@ github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/n
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
@@ -271,15 +271,15 @@ github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqo
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.79.0 h1:32ur91W4kWG+1s6x3oDlP8/KNmjlZZlUzSSC4p9LSWE=
github.com/valyala/fasthttp v1.79.0/go.mod h1:NQN+PlgP93+JRPnCiApN5XwnI24oMQf8kuzrxtsTy9A=
github.com/valyala/fasthttp v1.80.0 h1:10pVr/QLFGbSX8ikDS0i+wOi2AGY2Sy0TACVpoiG+7U=
github.com/valyala/fasthttp v1.80.0/go.mod h1:oulvtxx5dQeORu6sKWaJItcnWXRqiGmrTFQ4gmZjLFM=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/auto/sdk v1.2.2 h1:ErNn7NW2t1F9CFBLb9iyPMyLRbcEd07l5m/StCe9AEE=
go.opentelemetry.io/auto/sdk v1.2.2/go.mod h1:Ca3X8ec6gdTYjAirla//dnp05ECtQPfN4Ut74OJLVsQ=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
+8
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
@@ -73,6 +75,8 @@ data:
cache:
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:
@@ -85,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 }}
+14 -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,14 +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:
@@ -390,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)
}
+1
View File
@@ -0,0 +1 @@
.lake/
+126
View File
@@ -0,0 +1,126 @@
# Lean audit findings
Audit of GoHoarder at c98720c (v0.1.303) with Lean 4 + Mathlib v4.36.0. Models live in
`lean4/Gohoarder/*.lean`; each cites the Go files it models. Statements are "proved about the model".
A Lean counterexample is never the evidence alone: every fixed row has a Go test that failed first.
Build: `cd lean4 && lake exe cache get && lake build && lake env lean scripts/Axioms.lean`.
Currency: `sh lean4/scripts/check_currency.sh origin/main`.
## Fixed
| id | area | claim | class | severity | evidence (Lean / Go test) | fix commit |
|----|------|-------|-------|----------|---------------------------|------------|
| GH-01 | PyPI fetch | the file fetched from `original_url` is the file the cache key names | security, CWE-345 | high | `Access.old_guard_allows_key_poisoning`, `fixed_guard_binds_key` / `TestHandlePackageFile_OriginalURLFilenameBound` | 5c9f7e6 |
| GH-02 | scan decision | a bypassed CVE never blocks, under any `block_on_severity` | correctness (over-block) | low | `Security.old_low_ignores_bypass`, `fully_bypassed_never_blocks` / `TestCheckVulnerabilities_BypassedCVENeverBlocks` | 4713524 |
| GH-03 | PyPI scan | scanners are asked about the release version, not the file name | security, CWE-693 | high when a block policy is set | `Security.scan_asks_release_version`, `file_name_is_not_release_version` / `TestScanAsksScannersForReleaseVersion` | 3143de3 |
| GH-04 | scan gate | an npm or PyPI package named `*.info` or `*.mod` is scanned | security, CWE-693 | medium | `Cache.npm_named_like_go_metadata_is_scanned`, `old_exempted_npm_package` / `TestCacheHitScansPackagesNamedLikeGoMetadata`, `TestIsMetadataEntry` | f0b37ea |
| GH-05 | storage quota | `used` equals bytes on disk after an overwrite | correctness | low | `Cache.put_keeps_usage_exact`, `old_put_inflates_usage` / `TestPutOverwriteKeepsUsageExact`, `TestPutOverwriteWithinQuota` | 1f31256 |
| GH-06 | LRU eviction | eviction terminates; an overlapping store waits instead of failing | correctness | medium | `Cache.old_evict_is_stuck`, `fixed_evict_measure_falls` / `TestEvictTerminatesWhenDeletesFail`, `TestEvictWaitsForRunningEviction` | 440279a |
| 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
- **GH-01.** A client requests `/pypi/<victim>/<victim-file>?original_url=https://files.pythonhosted.org/.../<attacker-file>`.
The host is on the allowlist, the key is `pypi/<victim>/<victim-file>`, and an uncached key stores the attacker's
file. Every later client gets it; OSV judges the victim's name and version. The attacker publishes the file on PyPI
and needs no credentials. Reach: any network client of `/pypi`, unauthenticated when `auth.enabled` is false (production).
- **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 |
|----|------|-------|---------|-----|
| GH-10 | key path | `keyToPath` rewrites `..` instead of rejecting; distinct keys share a path | hardening, unreachable | `Keys.keyToPath_not_injective`. A probe through the full app showed the HTTP layer resolves literal `..` and answers 404 to encoded slashes (`/npm/lodash/-/lodash-1.0.0/../../x.tgz` reached upstream as `/lodash/-/lodash-x.tgz`). No key with `..` reaches storage. |
| 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.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`. |
### Decision: `fail_closed: false` with recurring infrastructure errors
Served: a package with no scan row while a scan is in flight, and a package whose every scanner failed on infrastructure
(`Security.unscanned_served_iff`, `infra_error_served_forever`). Retries: at most 6 at 5 minute spacing, 7 scans, 30
minutes (`retry_terminates`, `retry_window_minutes`); after that the error row stays and the package stays served until
the rescan worker runs (needs `rescan_interval`). Quoted intent: `pkg/cache/cache.go` "A wait that times out serves the
package unless FailClosed is set"; `scanner.go` "Scan failed on infrastructure, serving package; scan will be retried";
production config "A scan that fails on infrastructure is retried and the package is served (fail_closed false)".
Verdict: acceptable for production, whose only scanner is OSV, a remote service that cannot be made to time out by package
content. Residual risk: with file-based scanners (trivy, grype, pip-audit) a crafted package that makes the scanner time out
is served unscanned, because a deadline counts as infrastructure. Run those with `fail_closed: true`. No code change.
## Negative matrices (do not re-run)
| surface | runs | a leak would look like | verdict |
|---------|------|------------------------|---------|
| frontend nginx blocklist (`Dockerfile.frontend` template on nginx:alpine, stub backend) | 30 raw paths: `//npm`, `/./npm`, `%6Epm`, `/api/../npm`, `/api/..%2fnpm`, `/health/..%2fnpm`, `/ws/..%2fnpm`, `/api/..\npm`, `/api/..;/npm`, `/api/%5c..%5cnpm`, `/api/..%252fnpm`, `/npm?x=1`, `/metrics/` and more | 200 from the backend for `/npm`, `/pypi`, `/go` or `/metrics` | all 404 or SPA. `/NPM/x` returns the SPA page, not the proxy. |
| backend re-interpretation of the six paths nginx forwarded raw | `/api/..\npm/x`, `/api/..;/npm/x`, `/api/%5c..%5cnpm/x`, `/api/%2e%2e%5cnpm/x`, `/api/..%252fnpm/x`, `/api/;/../npm/x` against the full app | 200 from the npm handler | all 404 |
| WebSocket origin check | `Access.default_port_equivalent`, `scheme_mismatch_rejected`, `port_mismatch_rejected`, `glob_rejects_label_prefix`, `glob_rejects_suffix_trick` | an origin outside the allowlist accepted | clean. Same-origin mode compares host only; documented: "the Origin host must match the Host header". |
| history totals under eviction | existing `TestPostgresHistoryTablesHaveNoPackageForeignKey`, `checkDeleteKeepsDownloadHistory` | totals fall after a package delete | clean: history tables carry no foreign key to packages. |
+6
View File
@@ -0,0 +1,6 @@
import Gohoarder.Cache
import Gohoarder.Keys
import Gohoarder.Security
import Gohoarder.Access
import Gohoarder.Release
import Gohoarder.Stats
+224
View File
@@ -0,0 +1,224 @@
import Mathlib
/-!
# Access control and upstream fetch guards
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, `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.
-/
namespace Gohoarder.Access
/-! ### WebSocket origin -/
inductive Scheme | http | https
deriving DecidableEq
def defaultPort : Scheme → ℕ
| Scheme.http => 80
| Scheme.https => 443
/-- An origin after `strings.ToLower`: host labels plus an optional explicit port. -/
structure Origin where
scheme : Scheme
host : List Char
port : Option ℕ
/-- `normalizeOriginHost`: a port equal to the scheme default is dropped; compare on the effective port. -/
def effPort (o : Origin) : ℕ := o.port.getD (defaultPort o.scheme)
/-- An exact allowlist rule matches iff scheme, host and effective port agree (`buildCheckOrigin`). -/
def matchesExact (rule o : Origin) : Bool :=
decide (rule.scheme = o.scheme) && decide (rule.host = o.host) && decide (effPort rule = effPort o)
theorem default_port_equivalent (s : Scheme) (h : List Char) :
matchesExact ⟨s, h, none⟩ ⟨s, h, some (defaultPort s)⟩ = true := by
simp [matchesExact, effPort]
theorem scheme_mismatch_rejected (rule o : Origin) (h : rule.scheme ≠ o.scheme) :
matchesExact rule o = false := by
simp [matchesExact, h]
theorem port_mismatch_rejected (s : Scheme) (h : List Char) (p q : ℕ) (hp : p ≠ q) :
matchesExact ⟨s, h, some p⟩ ⟨s, h, some q⟩ = false := by
simp [matchesExact, effPort, hp]
/-- Wildcard rule `https://*.d`: `strings.HasSuffix(host, ".d")` or host = `d`. -/
def matchesGlob (d host : List Char) : Bool :=
decide (host = d) || decide (('.' :: d) <:+ host)
/-- The leading dot pins the match to a label boundary: `evilexample.com` is not under `example.com`. -/
theorem glob_rejects_label_prefix :
matchesGlob "example.com".toList "evilexample.com".toList = false := by decide
theorem glob_accepts_subdomain :
matchesGlob "example.com".toList "app.example.com".toList = true := by decide
theorem glob_rejects_suffix_trick :
matchesGlob "example.com".toList "example.com.evil.net".toList = false := by decide
/-! ### Admin gate -/
inductive Role | readonly | readwrite | admin
deriving DecidableEq
/-- `getPermissionsForRole`, restricted to the bypass-management and key-management permissions. -/
def canManageBypasses : Role → Bool
| Role.admin => true
| _ => false
def canManageKeys : Role → Bool
| Role.admin => true
| _ => false
/-- `requireAdmin` admits a key with the admin role or the `bypasses:manage` permission; it also
guards `/api/admin/keys`. No other role holds that permission, so no escalation to key minting. -/
def requireAdminPasses (r : Role) : Bool := decide (r = Role.admin) || canManageBypasses r
theorem admin_gate_implies_key_manager (r : Role) (h : requireAdminPasses r = true) :
canManageKeys r = true := by
cases r <;> simp_all [requireAdminPasses, canManageBypasses, canManageKeys]
/-- `ValidateAPIKey`: a key is a candidate iff it has no expiry or `now <= expiresAt`. -/
def keyLive (now : ℤ) (exp : Option ℤ) : Bool :=
match exp with
| none => true
| some e => decide (now ≤ e)
theorem expired_key_rejected (now e : ℤ) (h : e < now) : keyLive now (some e) = false := by
simp [keyLive, not_le.mpr h]
/-! ### PyPI `original_url` guards -/
/-- A fetch the handler would perform: host and file name of `original_url`. -/
structure Fetch where
host : String
file : String
def allowedHosts : List String := ["pypi.org", "files.pythonhosted.org", "pythonhosted.org"]
/-- `isAllowedPyPIHost`: listed hosts, or a subdomain of pythonhosted.org (suffix on characters). -/
def hostAllowed (h : String) : Bool :=
decide (h ∈ allowedHosts) || decide (".pythonhosted.org".toList <:+ h.toList)
/-- Before the fix: host allowlist only. The cache key is `pypi/<name>/<requested file>`. -/
def acceptsOld (f : Fetch) : Bool := hostAllowed f.host
/-- After the fix: the fetched file must be the requested one. -/
def acceptsNew (requested : String) (f : Fetch) : Bool := hostAllowed f.host && decide (f.file = requested)
/-- Integrity of the cache key: what is stored under a key is the file the key names. -/
theorem fixed_guard_binds_key (requested : String) (f : Fetch) (h : acceptsNew requested f = true) :
f.file = requested := by
simp only [acceptsNew, Bool.and_eq_true, decide_eq_true_eq] at h
exact h.2
/-- Before the fix any file on an allowed host was stored under any requested name. -/
theorem old_guard_allows_key_poisoning :
∃ requested f, acceptsOld f = true ∧ f.file ≠ requested := by
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
/-- 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 :
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. -/
def blocked (first : String) (rest : String) : Bool :=
decide (first ∈ ["npm", "pypi", "go", "metrics"]) && (decide (rest.toList = []) || decide (rest.toList.head? = some '/'))
theorem blocklist_covers_registries :
blocked "npm" "/x" = true ∧ blocked "pypi" "" = true ∧ blocked "go" "/@v/list" = true ∧
blocked "metrics" "" = true := by decide
/-- A prefix that merely starts with a registry name is not blocked, and is not proxied either: the
`/health` and `/api/` locations are the only ones with a backend. -/
theorem blocklist_is_segment_exact : blocked "npmx" "" = false := by decide
end Gohoarder.Access
+223
View File
@@ -0,0 +1,223 @@
import Mathlib
/-!
# Cache lifecycle
Models `pkg/cache/cache.go`: `store` (expiry), `getOrFetch` and `Get` (hit path,
retry), `purge` and `cleanup` (idle eviction), `evict` (LRU).
What it omits: wall-clock skew, the storage backend, byte-level I/O.
-/
namespace Gohoarder.Cache
/-! ### Expiry: artifacts never expire by age, metadata pages do -/
/-- `pkg/cache/cache.go` `store`: only metadata entries get `now + DefaultTTL`. -/
def expiryFor (isMeta : Bool) (now ttl : ℤ) : Option ℤ :=
if isMeta then some (now + ttl) else none
/-- `pkg/cache/cache.go` `getOrFetch`: `pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt)`. -/
def expired (e : Option ℤ) (now : ℤ) : Prop := ∃ x, e = some x ∧ x < now
theorem artifact_never_expires (now ttl t : ℤ) : ¬ expired (expiryFor false now ttl) t := by
simp [expiryFor, expired]
theorem metadata_expires_after_ttl (now ttl t : ℤ) (h : now + ttl < t) :
expired (expiryFor true now ttl) t :=
⟨now + ttl, by simp [expiryFor], h⟩
theorem metadata_fresh_within_ttl (now ttl t : ℤ) (h : t ≤ now + ttl) :
¬ expired (expiryFor true now ttl) t := by
simp only [expired, expiryFor, ite_true, Option.some.injEq, exists_eq_left']
omega
/-! ### Idle eviction -/
/-- `pkg/cache/cache.go` `cleanup`: cutoff = now - IdleTTL; due iff `LastAccessed.Before(cutoff)`. -/
def idleDue (now idleTTL lastAccessed : ℤ) : Prop := lastAccessed < now - idleTTL
theorem idle_keeps_recent (now idleTTL la : ℤ) (h : now - la ≤ idleTTL) :
¬ idleDue now idleTTL la := by
unfold idleDue; omega
theorem idle_removes_stale (now idleTTL la : ℤ) (h : idleTTL < now - la) :
idleDue now idleTTL la := by
unfold idleDue; omega
/-- A request refreshes `LastAccessed` (`UpdateDownloadCount`), so a hit is never idle-due at that instant. -/
theorem touch_defers_idle (now idleTTL : ℤ) (h : 0 ≤ idleTTL) : ¬ idleDue now idleTTL now := by
unfold idleDue; omega
/-! ### Interleavings of a hit and a purge -/
/-- One step of the concurrent schedule on a single entry. -/
inductive Step
| touch (t : ℤ) -- a request refreshes LastAccessed
| check -- purge's `stillDue` re-read
| del -- purge's `deletePackage`
deriving DecidableEq
structure World where
last : ℤ
present : Bool
checked : Bool -- the last `check` found the entry due
deriving DecidableEq
def run (cutoff : ℤ) : World → List Step → World
| w, [] => w
| w, Step.touch t :: s => run cutoff { w with last := t } s
| w, Step.check :: s => run cutoff { w with checked := decide (w.last < cutoff) } s
| w, Step.del :: s => run cutoff { w with present := if w.checked then false else w.present } s
/-- Check and delete are two steps (`purge`: `stillDue(current)` then `deletePackage`), so a
request between them is lost: the entry is deleted although `LastAccessed >= cutoff`. This is
the window `Get` now covers with its retry. -/
theorem purge_window_deletes_fresh_entry :
let w := run 10 ⟨0, true, false⟩ [Step.check, Step.touch 20, Step.del]
w.present = false ∧ 10 ≤ w.last := by
decide
/-- With no request inside the window the purge honours `stillDue`. -/
theorem purge_without_window_keeps_fresh (cutoff t : ℤ) (h : cutoff ≤ t) :
(run cutoff ⟨0, true, false⟩ [Step.touch t, Step.check, Step.del]).present = true := by
simp [run, not_lt.mpr h]
/-! ### `Get`: probe, then open -/
inductive Outcome | served | refetched | error
deriving DecidableEq
/-- Before the fix: probe in `getOrFetch`, open after the singleflight; `purgedBetween` is a delete
between the two. -/
def getOnce (present purgedBetween : Bool) : Outcome :=
if present then (if purgedBetween then Outcome.error else Outcome.served) else Outcome.refetched
/-- `Get` with `getAttempts = 2`: the second pass re-probes the (now missing) blob and fetches. -/
def getRetry (present d1 d2 : Bool) : Outcome :=
match getOnce present d1 with
| Outcome.error => if d2 then Outcome.error else Outcome.refetched
| o => o
theorem getOnce_errors_on_purge : getOnce true true = Outcome.error := rfl
/-- At most one purge per `Get` never reaches the client as an error. -/
theorem getRetry_survives_one_purge (present d1 d2 : Bool) (h : ¬ (d1 = true ∧ d2 = true)) :
getRetry present d1 d2 ≠ Outcome.error := by
cases present <;> cases d1 <;> cases d2 <;> simp_all [getRetry, getOnce]
/-! ### LRU eviction -/
/-- `evict`: delete oldest first until `freed >= needed`; `sizes` is the oldest-first listing. -/
def evictFreed : List ℕ → ℕ → ℕ
| [], _ => 0
| s :: rest, needed => if needed = 0 then 0 else s + evictFreed rest (needed - s)
theorem evictFreed_le_total (sizes : List ℕ) (needed : ℕ) : evictFreed sizes needed ≤ sizes.sum := by
induction sizes generalizing needed with
| nil => simp [evictFreed]
| cons s rest ih =>
unfold evictFreed
split_ifs
· simp
· simp only [List.sum_cons]; have := ih (needed - s); omega
theorem evictFreed_ge (sizes : List ℕ) (needed : ℕ) (h : needed ≤ sizes.sum) :
needed ≤ evictFreed sizes needed := by
induction sizes generalizing needed with
| nil => simpa [evictFreed] using h
| cons s rest ih =>
unfold evictFreed
split_ifs with h0
· omega
· simp only [List.sum_cons] at h
have := ih (needed - s) (by omega)
omega
/-- After `store` evicts for `needed = used + size - limit` and the listing held enough bytes,
usage including the new entry is within the cap. -/
theorem lru_keeps_cap (used size limit : ℕ) (sizes : List ℕ)
(hroom : used + size - limit ≤ sizes.sum) :
used + size - evictFreed sizes (used + size - limit) ≤ limit := by
have h1 := evictFreed_ge sizes (used + size - limit) hroom
omega
/-- When the listing cannot free enough (`freed < needed`) `evict` still returns nil, so the cap
rests on the backend's `Put` quota check (`filesystem.go` `Put`). The hypothesis of `lru_keeps_cap`
fails here, and the result exceeds the cap. -/
theorem lru_cap_needs_enough_evictable :
∃ used size limit : ℕ, ∃ sizes : List ℕ,
used + size - evictFreed sizes (used + size - limit) > limit := by
exact ⟨100, 10, 100, [5], by decide⟩
/-- The entry being stored is not in the metadata listing (`SavePackage` runs after `Put`), so
eviction never deletes it. -/
theorem evict_spares_unlisted (listed : List String) (new : String) (h : new ∉ listed) :
∀ victim ∈ listed.take 100, victim ≠ new := by
intro v hv hv'
exact h (hv' ▸ List.mem_of_mem_take hv)
/-- One eviction pass: `n` listed rows of which `d` can be deleted; the rest are listed again. -/
def passRemaining (n d : ℕ) : ℕ := n - d
/-- Before the fix the loop continued on `n >= limit` only; a pass that deletes nothing re-lists
the same rows and never ends. -/
theorem old_evict_is_stuck (n : ℕ) : passRemaining n 0 = n := by simp [passRemaining]
/-- After the fix a pass continues only if it deleted a row, so the row count strictly falls. -/
theorem fixed_evict_measure_falls (n d : ℕ) (hd : 0 < d) (hdn : d ≤ n) : passRemaining n d < n := by
unfold passRemaining; omega
/-! ### Quota accounting: overwriting a key
`pkg/storage/filesystem/filesystem.go` `Put`: `fs.used` tracks bytes on disk. -/
/-- After the fix: an overwrite releases the bytes of the file it replaces. -/
def usedAfterPut (used replaced written : ℕ) : ℕ := used - replaced + written
/-- Before the fix: the replaced bytes stayed counted. -/
def usedAfterPutOld (used written : ℕ) : ℕ := used + written
/-- If `used` is the sum of the stored sizes, `other + replaced`, the counter stays exact. -/
theorem put_keeps_usage_exact (other replaced written : ℕ) :
usedAfterPut (other + replaced) replaced written = other + written := by
unfold usedAfterPut; omega
/-- Two writes of one key (400 then 300 bytes) leave 700 counted, 300 on disk. -/
theorem old_put_inflates_usage : usedAfterPutOld (usedAfterPutOld 0 400) 300 = 700 ∧
usedAfterPut (usedAfterPut 0 0 400) 400 300 = 300 := by decide
/-! ### Which entries skip the scan
`pkg/metadata/interface.go` `IsMetadataEntry`; the scan gate in `getOrFetch` and `store`. -/
def metaVersions : List String := ["list", "page", "latest", "metadata"]
/-- After the fix the `.mod` / `.info` name suffix exempts Go entries only. -/
def scanExempt (registry : String) (nameSuffixMeta : Bool) (version : String) : Bool :=
decide (version ∈ metaVersions) || (decide (registry = "go") && nameSuffixMeta)
/-- Before the fix the suffix exempted any registry. -/
def scanExemptOld (nameSuffixMeta : Bool) (version : String) : Bool :=
decide (version ∈ metaVersions) || nameSuffixMeta
theorem npm_named_like_go_metadata_is_scanned (v : String) (hv : v ∉ metaVersions) :
scanExempt "npm" true v = false := by
simp [scanExempt, hv]
theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decide
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
+146
View File
@@ -0,0 +1,146 @@
import Mathlib
/-!
# Storage keys, path safety, canonicalisation
Models `pkg/cache/cache.go` `generateStorageKey`, `pkg/storage/filesystem/filesystem.go`
`keyToPath`, `pkg/proxy/npm/npm.go` `CanonicalPath`, and `pkg/proxy/pypi/pypi.go`
`extractVersionFromFilename`. Omits: symlinks (the store writes through `os.Root`), Unicode.
-/
namespace Gohoarder.Keys
/-! ### `keyToPath`: segment normalisation -/
/-- `filepath.Clean` plus the strip loop in `keyToPath`: `.` and empty segments vanish, `..` pops
a segment and is dropped at the root. Segments are kept in reverse order. -/
def cleanRev : List String → List String → List String
| acc, [] => acc
| acc, seg :: rest =>
if seg = "." ∨ seg = "" then cleanRev acc rest
else if seg = ".." then cleanRev acc.tail rest
else cleanRev (seg :: acc) rest
def clean (segs : List String) : List String := (cleanRev [] segs).reverse
theorem cleanRev_no_dotdot (segs acc : List String) (h : ".." ∉ acc) : ".." ∉ cleanRev acc segs := by
induction segs generalizing acc with
| nil => simpa [cleanRev] using h
| cons seg rest ih =>
unfold cleanRev
split_ifs with h1 h2
· exact ih acc h
· exact ih acc.tail (fun hm => h (List.mem_of_mem_tail hm))
· apply ih
simp only [List.mem_cons, not_or]
exact ⟨fun e => h2 e.symm, h⟩
/-- No cleaned key contains a `..` segment, so the joined path stays under the store root. -/
theorem clean_stays_in_root (segs : List String) : ".." ∉ clean segs := by
unfold clean
simpa using cleanRev_no_dotdot segs [] (by simp)
/-- The sanitiser rewrites; it does not reject. Distinct keys collapse onto one path. -/
theorem keyToPath_not_injective :
clean ["npm", "pkg", "..", "other", "1.0.0"] = clean ["npm", "other", "1.0.0"] ∧
["npm", "pkg", "..", "other", "1.0.0"] ≠ ["npm", "other", "1.0.0"] := by
decide
theorem keyToPath_traversal_is_clamped :
clean ["..", "..", "etc", "passwd"] = ["etc", "passwd"] := by decide
/-! ### Key injectivity: `registry/name/version` -/
/-- `generateStorageKey`: join with `/`. -/
def key (registry name version : String) : List String := [registry, name, version]
/-- Over segment lists the tuple is recoverable; `String.intercalate "/"` is injective exactly
when the parts contain no `/`. -/
theorem key_injective (r n v r' n' v' : String) (h : key r n v = key r' n' v') :
r = r' ∧ n = n' ∧ v = v' := by
simp only [key, List.cons.injEq, and_true] at h
exact ⟨h.1, h.2.1, h.2.2⟩
/-- With `/` inside a part the joined string collides: npm `@x/y` + `b` and `@x` + `y/b`. The
second tuple needs an upstream 200 at a path npm never serves, so the proxy cannot store it. -/
theorem joined_key_collides_with_slash :
String.intercalate "/" ["npm", "@x/y", "b"] = String.intercalate "/" ["npm", "@x", "y/b"] := by
decide
/-! ### `npm.CanonicalPath`: escaped scope separator -/
inductive Tok | scope | esc | sl | other
deriving DecidableEq
/-- Rewrites the first escaped `/` of the first segment (`CanonicalPath`'s `strings.Cut`). -/
def rewriteFirst : List Tok → List Tok
| [] => []
| Tok.sl :: r => Tok.sl :: r
| Tok.esc :: r => Tok.sl :: r
| Tok.scope :: r => Tok.scope :: rewriteFirst r
| Tok.other :: r => Tok.other :: rewriteFirst r
/-- `CanonicalPath` acts only on a segment starting with `@`. -/
def canon : List Tok → List Tok
| Tok.scope :: r => Tok.scope :: rewriteFirst r
| p => p
theorem rewriteFirst_idem (r : List Tok) : rewriteFirst (rewriteFirst r) = rewriteFirst r := by
induction r with
| nil => rfl
| cons t rest ih => cases t <;> simp [rewriteFirst, ih]
/-- Canonicalisation is idempotent: a second pass finds the separator the first one wrote. -/
theorem canon_idem (p : List Tok) : canon (canon p) = canon p := by
cases p with
| nil => rfl
| cons t r => cases t <;> simp [canon, rewriteFirst_idem]
/-- The rewrite adds at most one separator, so a name cannot smuggle extra path segments. -/
theorem rewriteFirst_adds_one_sep (r : List Tok) :
(rewriteFirst r).count Tok.sl ≤ r.count Tok.sl + 1 := by
induction r with
| nil => simp [rewriteFirst]
| cons t rest ih =>
cases t <;> simp [rewriteFirst, List.count_cons] at * <;> omega
theorem canon_adds_one_sep (p : List Tok) : (canon p).count Tok.sl ≤ p.count Tok.sl + 1 := by
cases p with
| nil => simp [canon]
| cons t r =>
have := rewriteFirst_adds_one_sep r
cases t <;> simp [canon, List.count_cons] at * <;> omega
/-- The escape that survives in the name part (`@a%2fb%2fc` gives `@a/b%2fc`) is later rejected:
Fiber answers 404 to an escaped slash, which `TestNPMScopedNames` and the traversal probe
(`/npm/@s%2fn%2f..%2f..%2fx` returns 404) exercise. -/
theorem canon_keeps_later_escape :
canon [Tok.scope, Tok.esc, Tok.other, Tok.esc, Tok.other] =
[Tok.scope, Tok.sl, Tok.other, Tok.esc, Tok.other] := by decide
/-! ### PyPI version from a file name -/
/-- Wheel (PEP 427): the version is the second `-` segment when it starts with a digit. -/
def startsWithDigit (v : String) : Bool :=
match v.toList with
| c :: _ => c.isDigit
| [] => false
def wheelVersion (segs : List String) : Option String :=
match segs with
| _ :: v :: _ => if startsWithDigit v then some v else none
| _ => none
/-- A well-formed wheel name `dist-version-...` yields its version, whatever follows. -/
theorem wheelVersion_correct (d v : String) (rest : List String) (hv : startsWithDigit v = true) :
wheelVersion (d :: v :: rest) = some v := by
simp [wheelVersion, hv]
/-- The cache version for a PyPI file is the file name, which is unique per file, while the
release version is shared by all files of a release (`release_version`). Two files of one release
have different keys and one release key: bypasses by release cover both, by design. -/
theorem pypi_key_per_file_release_shared (name f1 f2 : String) (h : f1 ≠ f2) :
key "pypi" name f1 ≠ key "pypi" name f2 := by
intro e; exact h (key_injective _ _ _ _ _ _ e).2.2
end Gohoarder.Keys
+84
View File
@@ -0,0 +1,84 @@
import Mathlib
/-!
# Release-age passthrough
Models `pkg/proxy/npm/npm.go` `rewriteMetadataURLs`, `pkg/proxy/pypi/simple_json.go`
`rewriteJSONPage`, and the packument/index freshness TTL in `pkg/cache/cache.go`. A client gate
accepts a version when `now - publishedAt >= gate`. Omits: JSON parsing, number formatting.
-/
namespace Gohoarder.Release
/-- A JSON object as key/value pairs. -/
abbrev Obj := List (String × String)
/-- `rewriteJSONPage`: only the `url` value of a file entry changes. -/
def rewriteFile (proxy : String) (o : Obj) : Obj :=
o.map fun kv => if kv.1 = "url" then (kv.1, proxy) else kv
theorem rewrite_preserves_upload_time (proxy : String) (o : Obj) (t : String)
(h : ("upload-time", t) ∈ o) : ("upload-time", t) ∈ rewriteFile proxy o := by
unfold rewriteFile
exact List.mem_map.mpr ⟨("upload-time", t), h, by simp⟩
theorem rewrite_preserves_other_keys (proxy : String) (o : Obj) (k v : String) (hk : k ≠ "url")
(h : (k, v) ∈ o) : (k, v) ∈ rewriteFile proxy o := by
unfold rewriteFile
exact List.mem_map.mpr ⟨(k, v), h, by simp [hk]⟩
theorem rewrite_keeps_keys (proxy : String) (o : Obj) : (rewriteFile proxy o).map Prod.fst = o.map Prod.fst := by
unfold rewriteFile
simp only [List.map_map]
congr 1
funext kv
simp only [Function.comp]
split_ifs <;> simp
/-! ### Staleness against a minimum-age gate -/
/-- The gate accepts a version published at `t` when it is at least `gate` old. -/
def gateAccepts (gate now t : ℤ) : Prop := gate ≤ now - t
/-- A version missing from a snapshot taken at `s` was published after `s`. If the snapshot is at
most `ttl` old and `ttl <= gate`, the missing version is younger than the gate, so the gate would
have refused it anyway: staleness hides nothing the gate allows. -/
theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ ttl) (httl : ttl ≤ gate)
(hnew : s < t) : ¬ gateAccepts gate now t := by
unfold gateAccepts; omega
/-- 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 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
end Gohoarder.Release
+360
View File
@@ -0,0 +1,360 @@
import Mathlib
/-!
# Security decision logic
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.
-/
namespace Gohoarder.Security
structure Vuln where
id : ℕ
sev : ℕ
structure Bypass where
cve : ℕ
covers : Bool -- `AppliesTo` empty or equal to this package
active : Bool
expiresAt : ℤ
/-- `GetActiveCVEBypasses`: `active = true AND expires_at > now`. -/
def activeAt (now : ℤ) (b : Bypass) : Bool := b.active && decide (now < b.expiresAt)
def bypassedIds (now : ℤ) (bs : List Bypass) : List ℕ :=
(bs.filter fun b => activeAt now b && b.covers).map (·.cve)
/-- The vulnerabilities no bypass covers (`severityCounts` loop). -/
def remaining (now : ℤ) (bs : List Bypass) (vs : List Vuln) : List Vuln :=
vs.filter fun v => decide (v.id ∉ bypassedIds now bs)
/-- `block_on_severity`: `none` for "none"/empty, else block when a remaining vulnerability has
rank at or above the threshold. -/
def blocksBySeverity (policy : Option ℕ) (vs : List Vuln) : Bool :=
match policy with
| none => false
| some t => vs.any fun v => decide (t ≤ v.sev)
def decideSev (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) : Bool :=
blocksBySeverity policy (remaining now bs vs)
/-- The LOW branch before the fix: `len(result.Vulnerabilities) > 0`, bypasses ignored. -/
def decideLowOld (vs : List Vuln) : Bool := decide (0 < vs.length)
theorem expired_bypass_inactive (now : ℤ) (b : Bypass) (h : b.expiresAt ≤ now) : activeAt now b = false := by
simp [activeAt, not_lt.mpr h]
theorem inactive_bypass_ignored (now : ℤ) (b : Bypass) (h : b.active = false) : activeAt now b = false := by
simp [activeAt, h]
/-- Every vulnerability bypassed by an active, covering bypass: nothing blocks, for any policy. -/
theorem fully_bypassed_never_blocks (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln)
(h : ∀ v ∈ vs, v.id ∈ bypassedIds now bs) : decideSev policy now bs vs = false := by
have : remaining now bs vs = [] := by
simp only [remaining, List.filter_eq_nil_iff, decide_eq_true_eq, not_not]
exact h
simp [decideSev, this, blocksBySeverity]
cases policy <;> simp
/-- A vulnerability at or above the policy that no active bypass covers blocks. -/
theorem uncovered_vuln_blocks (t : ℕ) (now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln)
(hv : v ∈ vs) (hsev : t ≤ v.sev) (hun : v.id ∉ bypassedIds now bs) :
decideSev (some t) now bs vs = true := by
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq]
refine ⟨v, ?_, hsev⟩
simp [remaining, hv, hun]
/-- Adding a bypass never turns an allow into a block. -/
theorem bypass_monotone (policy : Option ℕ) (now : ℤ) (b : Bypass) (bs : List Bypass) (vs : List Vuln)
(h : decideSev policy now (b :: bs) vs = true) : decideSev policy now bs vs = true := by
cases policy with
| none => simp [decideSev, blocksBySeverity] at h
| some t =>
simp only [decideSev, blocksBySeverity, List.any_eq_true, decide_eq_true_eq, remaining,
List.mem_filter] at h ⊢
obtain ⟨v, ⟨hv, hn⟩, hs⟩ := h
refine ⟨v, ⟨hv, ?_⟩, hs⟩
intro hmem
apply hn
simp only [bypassedIds, List.filter_cons] at hmem ⊢
split_ifs <;> simp_all
/-- Before the fix, LOW blocked a package whose only vulnerability was bypassed. -/
theorem old_low_ignores_bypass :
let vs := [Vuln.mk 1 1]
let bs := [Bypass.mk 1 true true 100]
decideLowOld vs = true ∧ decideSev (some 1) 0 bs vs = false := by
decide
/-! ### Serve decision -/
inductive Scan
| missing (inflight : Bool) -- no result row; `isInflight` while a scan runs
| err (infra : Bool) -- every scanner failed
| ok (vs : List Vuln)
/-- `CheckVulnerabilities` and the gate: `true` means the package is served. -/
def serves (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
Scan → Bool
| s =>
if pkgBypass then true else
match s with
| Scan.missing inflight => !failClosed && inflight
| Scan.err infra => !failClosed && infra
| Scan.ok vs => !decideSev policy now bs vs
theorem fail_closed_blocks_without_verdict (policy : Option ℕ) (now : ℤ) (bs : List Bypass) (s : Scan)
(hs : (∃ i, s = Scan.missing i) ∨ (∃ i, s = Scan.err i)) :
serves true false policy now bs s = false := by
rcases hs with ⟨i, rfl⟩ | ⟨i, rfl⟩ <;> simp [serves]
/-- A vulnerable package is not served when policy blocks, unless a package bypass covers it. -/
theorem vulnerable_not_served (policy : Option ℕ) (t : ℕ) (hp : policy = some t) (failClosed : Bool)
(now : ℤ) (bs : List Bypass) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
(hun : v.id ∉ bypassedIds now bs) :
serves failClosed false policy now bs (Scan.ok vs) = false := by
subst hp
simp [serves, uncovered_vuln_blocks t now bs vs v hv hsev hun]
/-- With `fail_closed = false`, exactly these states serve a package with no verdict: a scan in
flight, or every scanner failing on infrastructure. A package bypass serves in any state. -/
theorem unscanned_served_iff (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
(bs : List Bypass) (i : Bool) :
(serves failClosed pkgBypass policy now bs (Scan.missing i) = true ↔
pkgBypass = true ∨ (failClosed = false ∧ i = true)) ∧
(serves failClosed pkgBypass policy now bs (Scan.err i) = true ↔
pkgBypass = true ∨ (failClosed = false ∧ i = true)) := by
cases failClosed <;> cases pkgBypass <;> cases i <;> simp [serves]
/-- The infra-error record never changes with retries, so the package stays served. -/
theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List Bypass) :
serves false false policy now bs (Scan.err true) = true := by
simp [serves]
/-- 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
def retryIntervalMin : ℕ := 5
/-- Scans run from `attempt`: `scan` schedules attempt+1 only when infra-only and `attempt < maxRetries`. -/
def scansFrom : ℕ → ℕ
| 0 => 1
| k + 1 => 1 + scansFrom k
theorem scansFrom_eq (k : ℕ) : scansFrom k = k + 1 := by
induction k with
| zero => rfl
| succ k ih => simp only [scansFrom, ih]; omega
theorem scans_total : scansFrom maxRetries = maxRetries + 1 := scansFrom_eq _
theorem retry_window_minutes : maxRetries * retryIntervalMin = 30 := by decide
/-- The attempt counter is bounded, so a package that keeps failing on infrastructure is scanned at most 7 times. -/
theorem retry_terminates (attempt : ℕ) : scansFrom (maxRetries - attempt) ≤ maxRetries + 1 := by
rw [scansFrom_eq]; omega
/-! ### Which version scanners are asked about
`pkg/scanner/scanner.go` `scanVersion`: PyPI artifacts are cached under their file name. -/
def scanVersion (release cacheVersion : String) : String :=
if release = "" then cacheVersion else release
theorem scan_asks_release_version (release cacheVersion : String) (h : release ≠ "") :
scanVersion release cacheVersion = release := by
simp [scanVersion, h]
theorem npm_scan_keeps_cache_version (cacheVersion : String) :
scanVersion "" cacheVersion = cacheVersion := by
simp [scanVersion]
/-- Before the fix scanners received the file name, which is never a release version. -/
theorem file_name_is_not_release_version :
"requests-2.19.0-py3-none-any.whl" ≠ "2.19.0" := by decide
/-! ### 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
theorem merge_dominates (xs : List ℕ) (x : ℕ) (h : x ∈ xs) : x ≤ mergeRank xs := by
induction xs with
| nil => simp at h
| cons y ys ih =>
simp only [mergeRank, List.foldr_cons]
rcases List.mem_cons.mp h with rfl | h
· exact le_max_left _ _
· exact le_trans (ih h) (le_max_right _ _)
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
+222
View File
@@ -0,0 +1,222 @@
import Mathlib
/-!
# Stats and time series
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
/-! ### Hourly pass: each event is counted once -/
/-- `AggregateHourly`: cutoff hour = floor((now - 5min) / 60); events in earlier hours move to
`hr` and are deleted, in one transaction. -/
def cutoffHour (nowMin : ℤ) : ℤ := (nowMin - 5) / 60
def moveEvents (c : ℤ) (ev hr : ℤ → ℕ) : (ℤ → ℕ) × (ℤ → ℕ) :=
(fun h => if h < c then 0 else ev h, fun h => hr h + if h < c then ev h else 0)
/-- Per hour, events plus hourly rows are unchanged by a pass: nothing is counted twice or dropped. -/
theorem hourly_pass_conserves (c : ℤ) (ev hr : ℤ → ℕ) (h : ℤ) :
(moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h = ev h + hr h := by
simp only [moveEvents]
split_ifs <;> omega
theorem hourly_pass_conserves_sum (c : ℤ) (ev hr : ℤ → ℕ) (S : Finset ℤ) :
∑ h ∈ S, ((moveEvents c ev hr).1 h + (moveEvents c ev hr).2 h) = ∑ h ∈ S, (ev h + hr h) :=
Finset.sum_congr rfl fun h _ => hourly_pass_conserves c ev hr h
/-- Within five minutes after the hour the cutoff is still the previous hour, so the last hour of a
day is not aggregated by a pass at `hh:00`-`hh:04`. -/
theorem early_tick_leaves_last_hour (hourIdx m : ℤ) (hm0 : 0 ≤ m) (hm : m < 5) :
cutoffHour (60 * hourIdx + m) = hourIdx - 1 := by
unfold cutoffHour; omega
theorem late_tick_covers_last_hour (hourIdx m : ℤ) (hm0 : 5 ≤ m) (hm : m < 60) :
cutoffHour (60 * hourIdx + m) = hourIdx := by
unfold cutoffHour; omega
/-! ### Daily pass: which days are rolled up -/
def retentionDays : ℕ := 7
/-- Days recomputed by each pass (`rollupDays`). -/
def rollupDays : ℕ := 6
/-- A pass on day `t` rolls up day `d` (before: only yesterday). -/
def oldRolls (t d : ℕ) : Prop := d + 1 = t
def newRolls (t d : ℕ) : Prop := d + 1 ≤ t ∧ t ≤ d + rollupDays
theorem rollup_window_below_retention : rollupDays < retentionDays := by decide
/-- The pass on day `t` deletes hourly rows older than 7 days: hours of day `d` survive it
whenever `t < d + 7`. The new window ends at `d + 6`, inside that bound. -/
theorem new_window_inside_retention (t d : ℕ) (h : newRolls t d) : t < d + retentionDays := by
unfold newRolls at h; unfold retentionDays rollupDays at *; omega
/-- A day is rolled up if some pass day (hour-0 tick) falls in its window. -/
def covered (rolls : ℕ → ℕ → Prop) (passes : Set ℕ) (d : ℕ) : Prop := ∃ t ∈ passes, rolls t d
/-- Before: skipping the one pass on day d+1 (restart at midnight) loses day d for good. -/
theorem old_loses_day_on_one_skip (d : ℕ) :
¬ covered oldRolls {t | t ≠ d + 1} d := by
rintro ⟨t, ht, h⟩
unfold oldRolls at h
exact ht h.symm
/-- After: any single surviving pass in the next six days repairs it. -/
theorem new_repairs_after_skip (d : ℕ) : covered newRolls {t | t ≠ d + 1} d :=
⟨d + 2, by simp, by unfold newRolls rollupDays; omega⟩
/-! ### Chart: rollup against hourly rows and events -/
/-- Before: `counts[day] = rollup`. After: the larger of rollup and hourly+events. -/
def chartOld (rollup live : ℕ) : ℕ := rollup
def chartNew (rollup live : ℕ) : ℕ := max rollup live
/-- Rollup and live (hourly rows + events) each count a subset of the day's downloads, so the
larger is the better lower bound and never exceeds the truth. -/
theorem chartNew_sound (truth rollup live : ℕ) (hr : rollup ≤ truth) (hl : live ≤ truth) :
chartNew rollup live ≤ truth := max_le hr hl
theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ chartNew rollup live :=
le_max_left _ _
/-- 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
+96
View File
@@ -0,0 +1,96 @@
{"version": "1.3.0",
"packagesDir": ".lake/packages",
"packages":
[{"url": "https://github.com/leanprover-community/mathlib4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
"name": "mathlib",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.36.0",
"inherited": false,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/plausible",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "054b228ce0ac61d767c6e71ba73a24728f191b72",
"name": "plausible",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/LeanSearchClient",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "4fb58e749ef3fc0395fe274f6cab70c2ea85f1c9",
"name": "LeanSearchClient",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/import-graph",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "8370c640afcd1cc3fb1cb9bf1560cc66eafee5e0",
"name": "importGraph",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/ProofWidgets4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "2f0f3520daeac2d9310ff25b7a877a0e5cdaa203",
"name": "proofwidgets",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/aesop",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "66ff77cf0c4c898799e4b94d14db55f7a02d0c5a",
"name": "aesop",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/quote4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "ff055a2fcc835935e0ae607339b455a5f5896b4b",
"name": "Qq",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/batteries",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "b4b25a3886a16daacaf6615c2eea7170a6e8f458",
"name": "batteries",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover/lean4-cli",
"type": "git",
"subDir": null,
"scope": "leanprover",
"rev": "50810f72af7618bee62fe9800dc26e806c188703",
"name": "Cli",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.36.0",
"inherited": true,
"configFile": "lakefile.toml"}],
"name": "gohoarder",
"lakeDir": ".lake",
"fixedToolchain": false}

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