feat(admin): a Svelte admin app embedded in the Worker, with read-only decided rows

The two Worker-rendered admin pages (admin-ui.ts, edit-ui.ts: 1,400 lines of
HTML and script inside template literals) are replaced by a Svelte 5 app in
web/admin/. It is built on its own and embedded in the Worker as the gitignored
worker/generated/admin-bundle.ts, so no admin code ever reaches dist/, the
service worker's precache or the packaged apps. worker/routes/admin-spa.ts
serves the shell with a per-response nonce CSP after the existing Access checks,
serves hashed assets immutably, and 404s any other path under /admin.

Queue
- Rows that are decided (approved, committed, rejected) or whose game is already
  published have no checkbox, show a lock and are skipped by select-all. The
  rules come from shared/queue-rules.ts, the same module the Worker enforces.
- Decisions confirm every row first and report skipped rows with their reasons.
- Tabs with counts, cross-status search, sort, page size, all kept in the URL.
- Keyboard: j/k, x, a, r, d, e, /, Esc, ?. Ignored while typing or composing.
- Details dialog: payload, durable decision, other rows for the game, Reopen for
  a rejected row with the reason when it cannot be reopened.
- Phone layout as cards.

Edit
- One game: every change reviewed in a diff dialog before the commit; retire;
  delete a settled override file; unsaved-change guard.
- Several games: any field, set or retire, selection kept across pages and
  genres (up to 10), each game shown in the review.

Jobs, Audit and Health get their own paged, filterable pages. Health draws its
table on a 503 too, and Test write proves the write path.

An expired Access session reloads the page once; a refusal that survives the
reload is reported instead of looping. A non-JSON response is a server error,
never "session expired".

Local development: npm run dev:admin runs the real handlers against an in-memory
D1 with demo data, and npm run preview:admin serves the built bundle through the
real serveAdmin with the production CSP. Nothing in worker/ or admin/src imports
the mock, and the Worker has no authentication switch.

Also: design tokens move to src/styles/theme.css, shared by both builds;
verify-dist fails if admin code reaches dist/; vite-plugin-pwa is declared, as
src/app.d.ts references its types; docs/ADMIN.md, DEPLOYMENT.md and CLAUDE.md
describe the new admin.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-09-17 22:46:33 +07:00
1 parent 1b6ad7be47
commit 727aadabf8
67 files changed
+5623 -1969

No files matched your search

+38
View File
@@ -303,3 +303,41 @@ scraping pipeline (`scripts/`) driven by GitHub Actions.
The gate renders only after `consent.hydrated`: rendered before storage was
read, it was baked into every prerendered page and flashed for returning
visitors.
## Admin SPA (`web/admin/`)
- **It is part of the Worker script, never of `dist/`.** `admin/vite.config.ts`
builds it and `admin/build/emit-worker-bundle.ts` writes the gitignored
`worker/generated/admin-bundle.ts`, which `worker/routes/admin-spa.ts` serves
only after `worker/index.ts` has done the Access, credential-class and CSRF
checks. `dist/` is readable by anyone, precached by the service worker and
packaged into the apps, so admin code there would be public whatever Access
says. `scripts/verify-dist.mjs` fails on `dist/admin` or any `/api/admin/`
string in `dist/`.
- **`npm run build` must keep running `build:admin`,** and `typecheck` builds it
first: `worker/index.ts` imports the generated module, so a bare
`wrangler deploy` or `tsc` without it fails. That failure is intended.
- **One script, no code splitting.** The shell's CSP is `script-src` with a
per-response nonce and nothing else, so a lazily imported chunk would be
blocked. The emitter fails the build on a second script, an inline script or
a second JS file. Do not add `'unsafe-inline'` or `'strict-dynamic'` to make a
chunk load.
- **Routes are `shared/admin-routes.ts`.** `serveAdmin` 404s every other path
under `/admin` (the old Worker served the queue for any typo). A new page goes
there AND in `App.svelte`'s `NAV`; `admin/security.test.ts` holds them equal.
- **It may import only pure modules of the public app**: `src/lib/ui/*`,
`src/lib/utils.ts`, `src/lib/prefs.svelte.ts`, `src/fonts.css`,
`src/styles/theme.css` (the design tokens, shared by both builds). Never
`$app/*` or `$lib/*`; that build cannot resolve them.
- **`admin/mock/` is a dev server, not a mode.** `npm run dev:admin` runs the
real handlers against an in-memory D1 and fake GitHub; nothing under `worker/`
or `admin/src` may import it, and the Worker has no flag that skips
authentication. Keep it that way.
- **No raw HTML.** Game names, reasons, payloads and audit detail are text
other people wrote; `{@html}` and `innerHTML` are banned by
`admin/security.test.ts`.
- **`admin/src/lib/api.ts` fetches with `redirect: "manual"`.** An opaque
redirect, 401 or 403 is a lapsed Access session and reloads the page ONCE
(guarded in sessionStorage, so a persistent refusal cannot loop). A non-JSON
body is a server error, never "session expired": that misreport hid real
Worker crashes in the old admin pages.
+171 -65
View File
@@ -139,16 +139,35 @@ D1, remains the source of truth.
## 6. The database
`f2p-admin` (D1, region APAC) already exists and is bound as `DB` in
`web/wrangler.jsonc`. It holds four tables — `ingest_queue`, `ingest_decisions`, `commit_jobs`
and `audit_log` — and never game records. (This used to say "edit drafts";
there is no such table. `/api/admin/edit` commits straight to Git with no
draft stage.) Migrations live in `web/worker/migrations/` and are
applied out of band:
`web/wrangler.jsonc`. It never holds game records. Its tables:
| Table | Holds | Migration |
|---|---|---|
| `ingest_queue` | candidate games and their review status | `0001_init.sql` |
| `ingest_decisions` | the durable approved/rejected decision per appid | `0001_init.sql` |
| `commit_jobs` | every commit the Worker attempted, written before the attempt | `0001_init.sql` |
| `audit_log` | every admin action | `0001_init.sql` |
| `admin_locks` | the reconcile lease, so the cron and a manual run never overlap | `0002_admin_state.sql` |
| `admin_state` | the dataset generation the last sweep saw | `0002_admin_state.sql` |
(An older version of this page mentioned "edit drafts"; there is no such table.
`/api/admin/edit` commits straight to Git with no draft stage.) Migrations live
in `web/worker/migrations/` and are applied out of band:
```bash
npx wrangler d1 migrations apply f2p-admin --remote
```
The Worker tolerates a missing `0002`: reconcile falls back to its per-isolate
guard and skips the sweep watermark, and `/admin/health` lists the migrations
that are not applied yet. Deploying the Worker before applying the migration is
therefore safe, just degraded.
`audit_log` and `commit_jobs` rows older than `ADMIN_RETENTION_DAYS` (180 by
default, set in `wrangler.jsonc`) are deleted once a day by the cron, and the
deletion itself is recorded as an `admin.prune` audit row. The privacy policy
states the same window; change both together.
Confirm the database is on a paid plan before depending on it: since
2026-09-01, queries that exceed the free daily row limits **fail** rather than
throttle, including the queries you would use to diagnose the problem.
@@ -332,10 +351,14 @@ When the backlog is closed, delete `scripts/backfill_discover.py`, delete
## 9. Reviewing the queue
`/admin` is the review screen. It is served by the Worker, not by the SPA:
the public app has no sign-in and no editing, so admin markup and admin
endpoint names never enter the bundle visitors download, and `/admin` cannot
fall through to the public app shell if a route changes.
`/admin` is the review screen. It is a small Svelte app (`web/admin/`) built
separately from the public site and **embedded in the Worker**
(`worker/generated/admin-bundle.ts`), never placed in `dist/`. Everything in
`dist/` is served to anyone, precached by the service worker and packaged into
the desktop and Android apps, so admin code there would be public whatever
Access says. The Worker serves the app's shell and assets only after the Access
checks, with a per-response nonce CSP, and answers 404 for any other path under
`/admin`.
Tabs across the top are the row's status, with live counts:
@@ -344,12 +367,44 @@ Tabs across the top are the row's status, with live counts:
| `pending` | proposed by the discovery sweep, awaiting a decision |
| `deferred` | set aside; still blocks the appid from being re-proposed |
| `approved` | committed to the queue file, waiting for the pipeline |
| `committed` | observed in `data/` — genuinely published |
| `failed` | the pipeline refused it, **or** nothing observed it within 12h and it aged out — read `reject_reason` |
| `rejected` | you refused it; never proposed again |
| `committed` | observed in `data/`, so genuinely published |
| `failed` | the pipeline refused it, **or** nothing observed it within 12h and it aged out. Read `reject_reason` |
| `rejected` | you refused it; never proposed again unless you reopen it |
Select with the checkboxes (or *Select all on this page*, 60 at a time), then
choose an action. The action bar appears only when something is selected.
**Read-only rows.** A row you can no longer decide has no checkbox. It shows a
lock, and *select all* skips it:
- `approved`, `committed` and `rejected` rows are already decided;
- a `pending`, `deferred` or `failed` row whose **game** is already published
(it has a committed row or an approved decision) is locked too. Approving it
would queue a link that is already live, and rejecting it would record a
rejection for a game the catalogue carries.
The server enforces the same rules (`web/shared/queue-rules.ts` is the single
definition both sides import). Anything a decision cannot touch comes back in a
**skipped** list with a reason, never silently dropped: `published`,
`not-decidable`, `open-row-exists`, `duplicate-in-request`, `no-op`,
`changed-concurrently` or `not-found`.
Select rows, then choose an action from the bar that appears at the bottom. A
confirmation lists every row, says what the action will do, and takes an
optional reason. At most 100 rows go into one decision.
Search matches a name or an appid in the current tab; tick *Search every
status* to look everywhere at once. The tab, search, sort, page and page size
are all in the URL, so a reload or a shared link lands on the same view.
Keyboard: `j`/`k` move, `x` selects, `a` approves, `r` rejects, `d` defers (or
sends back to pending), `e` opens the row, `/` searches, `Esc` clears the
selection, `?` lists them. Keys are ignored while you type in a field or while
a dialog is open, and never interrupt IME composition.
Click a game (or press `e`) for its details: the payload as submitted, the
durable decision for the game, and every other row the queue holds for the same
appid. A `rejected` row has **Reopen** there. It moves that one row back to
`pending` and deletes the rejection, but only if no other row for the game is
open or committed and the game has no approved decision; otherwise the dialog
says which of those stopped it. There is no bulk reopen, on purpose.
### The three actions are not symmetric
@@ -393,7 +448,14 @@ watched the pipeline finish.
A row the pipeline refused becomes `failed` rather than rejected — deliberately,
so one bad day (a delisting, a Steam outage) does not permanently hide a game.
On the `failed` tab the middle button becomes **Send back to pending**.
A `failed` row can be approved again, deferred, or sent **Back to pending**.
The same pass also **sweeps** undecided rows. A `pending`, `deferred` or
`failed` row whose game has appeared in `data/` by some other route (the
browser extension, a manual edit) is marked `committed` by `reconcile`, with an
approved decision, so it stops asking for a review it no longer needs. The
sweep reads the dataset only when something is approved, when you press
Reconcile, or when `data/index.json` has changed since the last sweep.
`reject_reason` says which of three things happened:
@@ -413,21 +475,34 @@ schedule is close to free.
### If something goes wrong
Every action writes to `audit_log`, and every approval writes a `commit_jobs`
row *before* the commit is attempted, so a Worker that dies mid-flight leaves a
`pending` job as evidence rather than silence:
Every action writes to `audit_log`, and every commit writes a `commit_jobs`
row *before* it is attempted, so a Worker that dies mid-flight leaves a
`pending` job as evidence rather than silence. Both have their own pages,
filterable and paged: **Jobs** (`/admin/jobs`) and **Audit** (`/admin/audit`).
The queue header warns when any job is `failed` or stuck in `pending`.
```bash
npx wrangler d1 execute f2p-admin --remote --command "SELECT status, target_path, commit_sha, error, requested_by, created_at FROM commit_jobs ORDER BY created_at DESC LIMIT 10"
```
**Health** (`/admin/health`) checks D1, the GitHub App installation, the applied
migrations and the reconcile lock live, and still draws its table when the
answer is a 503. **Test write** records a `ping` audit row, which proves the
whole write path from your browser through Access to D1.
If a commit fails the rows are left untouched, on purpose: a row marked
approved with no commit behind it is invisible to both the queue and the
reconciler. Re-approving is safe — already-queued links are skipped.
reconciler. Re-approving is safe, because already-queued links are skipped.
Read the queue directly with:
If the commit lands but D1 then fails to update the rows, the error says
exactly that, names the commit, and records an `approve.desynced` audit row.
Approving again is safe, and once the pipeline publishes the games the sweep
marks the rows committed on its own.
When the Access session lapses, the page reloads once so Access can sign you in
again. If the API still refuses straight after that reload, the page says so
instead of reloading in a loop.
The same data from the command line:
```bash
npx wrangler d1 execute f2p-admin --remote --command "SELECT status, target_path, commit_sha, error, requested_by, created_at FROM commit_jobs ORDER BY created_at DESC LIMIT 10"
npx wrangler d1 execute f2p-admin --remote --command "SELECT appid, name, release_date, status FROM ingest_queue ORDER BY first_seen_at DESC LIMIT 40"
```
@@ -480,59 +555,90 @@ re-added. Your text is combined with them rather than replacing them.
### The same thing from `/admin/edit`
`/admin/edit` (linked from the review queue) does exactly what the command
above does, and writes a byte-identical file. A formatting difference between
the two producers would turn every alternating edit into a whole-file diff, so
the equality is asserted by `web/worker/lib/override-doc.test.ts`, which
round-trips every committed `data/overrides/*.json` — all Python-written —
through the TypeScript serialiser and compares bytes. It runs in `web-ci.yml`
and in `check-overrides.yml`.
`/admin/edit` does exactly what the command above does, and writes a
byte-identical file. A formatting difference between the two producers would
turn every alternating edit into a whole-file diff, so the equality is asserted
by `web/worker/lib/override-doc.test.ts`, which round-trips every committed
`data/overrides/*.json` — all Python-written — through the TypeScript
serialiser and compares bytes. It runs in `web-ci.yml` and in
`check-overrides.yml`.
(Until 2026-09-12 this paragraph asserted that test existed. It did not; there
were no tests in the repository at all.)
**One game.** Load a game by appid, or paste its Steam URL. Each field shows
what the catalogue holds now and, where an override is active, its value, the
value from before the first edit, who set it and why. Change what you want, add
a reason, then **Review and save**: a dialog lists every change against the
catalogue and the current override before anything is committed. An overridden
field has **Retire**, which restores the pre-edit value once on the next
pipeline run. Leaving the page with unsaved changes asks first.
Load a game by appid, change the fields you want, add a reason, Save. A field
already carrying an override is marked, shows the value from before the edit,
and gets a **Retire** button. The Worker writes only
`data/overrides/<appid>.json`; it cannot touch `data/`, and the page says so
rather than letting you assume the catalogue changed.
**Several games.** Pick games by genre, up to 10 at a time; the selection is
kept across pages and genres. Choose any one field and either set a value or
retire its override, then review: the dialog loads every selected game and
shows what the change does to each, including the ones it leaves unchanged.
One commit, one override file per game.
**Deleting an override file.** Once every entry in a file is retired *and* the
pipeline has restored each value, the file no longer changes anything, and the
page offers **Delete override file**. Until then it says what is still active
or not yet restored, and the Worker checks again against the file as it is at
commit time. (`scripts/edit_game.py` removes a file only when it holds no
entries at all, active or retired, so a file with retired entries stays until
you delete it here.)
The Worker writes only `data/overrides/<appid>.json`; it cannot touch `data/`,
and the page says so rather than letting you assume the catalogue changed.
Two safeguards worth knowing:
- The Worker's validation is a deliberately weaker MIRROR of
`validate_value()` in `scripts/core/overrides.py`. It exists so you are told
immediately. The Python one is authoritative and runs on every pipeline
write, and `check-overrides.yml` runs it on every push — so anything the UI
accepts but Python would reject fails CI within a minute instead of sitting
inert. Change one, change the other.
`validate_value()` in `scripts/core/overrides.py`, and the page's own checks
mirror the Worker's (`worker/routes/edit.test.ts` holds those two equal). They
exist so you are told immediately. The Python one is authoritative and runs on
every pipeline write, and `check-overrides.yml` runs it on every push — so
anything the UI accepts but Python would reject fails CI within a minute
instead of sitting inert. Change one, change the others.
- `was` is read server-side from the catalogue, never taken from the request.
It is what Retire restores, so a client-supplied value would let a crafted
request rewrite history.
---
## What is not built yet
## Working on the admin locally
The loop is closed: new games arrive by discovery and are approved in
`/admin`, corrections are made in `/admin/edit` or from the command line, and
both land in Git. What remains:
A real Worker cannot show the admin locally: every `/admin` and `/api/admin`
request needs an Access JWT, which cannot be minted offline, so `wrangler dev`
answers 404. The admin has its own dev server instead. It runs the **real**
handlers (`worker/routes/admin.ts`, `edit.ts`) against an in-memory D1 with the
real migrations, fed by the real `data/` shards, with GitHub faked. Nothing
leaves the machine and nothing is written to disk.
- **`audit_log` pruning.** It grows only with admin actions, so it is not
urgent, but it is unbounded — decide a retention window and make it agree
with `docs/PRIVACY_POLICY.md` before that matters.
- **The Worker cannot DELETE an override file.** `scripts/edit_game.py`
removes it once the last entry is retired; the Worker's `build()` returns
`null` ("leave the file alone") in the same state, and `createCommitOnBranch`
is only ever given `fileChanges.additions`. So `/admin/edit` leaves an empty
override document where the CLI would tidy it away. Harmless — an empty
document applies nothing — but the two tools diverge here.
- **Bulk mode sets one field.** `set: { genre }` is hardcoded; there is no
bulk retire and no multi-field bulk set.
- **Bulk selection does not survive pagination** (`loadBulk()` clears it).
- **Un-rejecting is raw SQL.** Removing a row from `ingest_decisions` has no
endpoint and writes no audit row, and there is no `suppress_until`, so a
rejection is permanent until someone runs `wrangler d1 execute`.
- **No cross-isolate reconcile lock.** The in-flight guard in
`lib/reconcile.ts` covers one isolate; the cron and a manual click in
different isolates can still overlap. Left alone deliberately — every write
there is idempotent, so the only cost is duplicated fetching.
```bash
cd web
npm run dev:admin # http://localhost:5174/admin, hot reload, demo data
npm run preview:admin # the built bundle through the real serveAdmin(), production CSP
```
The demo data (`web/admin/mock/seed.ts`) has every status, rows locked because
their game is published, a rejected row that cannot be reopened, commit jobs in
every state, audit history, and an override on 730 to edit. Two switches, as
cookies set from the browser console:
| Cookie | Effect |
|---|---|
| `mock_github=down` | health reports GitHub unreachable, a 503 (or start the server with `MOCK_GITHUB=down`) |
| `mock_session=expired` | the API answers the way Access does for a lapsed session |
None of this exists in the Worker. Nothing under `worker/` or `admin/src`
imports the mock (`admin/security.test.ts` checks), and there is no flag that
could switch authentication off.
`npm run build` builds the admin after the site, and `npm run typecheck` builds
it first, because the Worker imports the generated bundle.
## Known limits
- **A rejection stays until you reopen it.** There is no `suppress_until`, so a
game rejected for a temporary reason is not offered again on its own.
- **One field per bulk change.** Several fields on several games means several
commits.
- **English only.** The admin has one audience, so it has no translations.
+16 -6
View File
@@ -11,12 +11,14 @@ deploys — there is deliberately no deploy workflow in `.github/workflows/`.
push to main
└─> Cloudflare Workers Builds (root directory: web)
npm ci → npm run build → wrangler deploy
└─> Worker "free-steam-games-list"
├─ static assets from web/dist
├─ /api/data/* → proxies GitHub raw
├─ /img/* → proxies Valve's CDN
├─ /admin → Access-gated review UI
└─ /api/ingest/* → Access service token
│ └─> Worker "free-steam-games-list"
│ ├─ static assets from web/dist
│ ├─ /api/data/* → proxies GitHub raw
│ ├─ /img/* → proxies Valve's CDN
│ ├─ /admin → Access-gated admin SPA (embedded)
│ └─ /api/ingest/* → Access service token
├─ vite build → web/dist (the public site)
└─ vite build -c admin/… → web/worker/generated/admin-bundle.ts
```
`web/wrangler.jsonc` is the only deployment config. Several fields in it are
@@ -38,6 +40,14 @@ load-bearing and easy to break:
listing it here and every request through it is refused with
`access: aud mismatch`. They are scoped by route on purpose — see
docs/ADMIN.md.
- **The admin SPA is part of the Worker script, not of `dist/`.**
`npm run build` runs `build:admin` after the site build, which writes the
gitignored `worker/generated/admin-bundle.ts` that `worker/index.ts` imports.
A `wrangler deploy` without that step fails to bundle, and that is the
intended failure: the alternative, serving the admin from `dist/`, would hand
its code to anyone, to the service worker's precache and to the packaged
apps. `scripts/verify-dist.mjs` fails the CI build if any admin code reaches
`dist/`. The bundle adds about 0.5 MB to the Worker upload.
## Data does not redeploy the site
+1 -1
View File
@@ -74,7 +74,7 @@ into the Svelte port.
| `wrangler.jsonc` | unchanged |
| `/games/[appid]` | prerendered on the web from a build-time read of `../data/*.jsonl` for SEO; **skipped in the Tauri build** (3,400 HTML files would bloat the APK) and served by the fallback instead |
| Volatile fields | `current_players`, `reviews` hydrate client-side from `/api/data/*`, so a daily data commit does not require a rebuild — which is the whole point of the proxy |
| `/admin` | untouched. Still Worker-rendered HTML, outside the SPA entirely |
| `/admin` | untouched by this migration: Worker-rendered HTML, outside the SPA entirely. (Since v4.0.0 it is its own Svelte SPA, `web/admin/`, embedded in the Worker and still never in `dist/`; see docs/ADMIN.md.) |
## What must not be lost in the port
+6
View File
@@ -17,3 +17,9 @@ dist-ssr
# holds the generated tsconfig, route manifest and type declarations that
# tsconfig.json extends - regenerated, never edited, never committed.
.svelte-kit
# The admin SPA build (admin/vite.config.ts): its output directory, and the
# module it generates for the Worker. Both are rebuilt by `npm run build:admin`;
# a committed copy could deploy an admin older than its source.
.admin-build/
worker/generated/
+110
View File
@@ -0,0 +1,110 @@
/**
* After `vite build`, turn the admin build output into a TypeScript module the
* Worker imports: worker/generated/admin-bundle.ts.
*
* Why a generated module rather than static assets or wrangler Text rules:
*
* - dist/ is served to ANYONE by the asset server, and it is also Tauri's
* frontendDist and the service worker's precache source. The admin must be
* in none of those.
* - A plain .ts module is understood identically by tsc, Vitest and
* wrangler's bundler. Text-module rules would type one way and bundle
* another.
*
* The shell's single module script gets a nonce placeholder, which
* worker/routes/admin-spa.ts replaces per response. The checks below fail the
* build if the output ever stops fitting that model (a second script, an
* inline script, code splitting, a runaway size).
*/
import { createHash } from "node:crypto";
import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { dirname, extname, join, relative } from "node:path";
import type { Plugin } from "vite";
const TEXT = new Map([
[".js", "text/javascript; charset=utf-8"],
[".css", "text/css; charset=utf-8"],
[".svg", "image/svg+xml"],
[".json", "application/json; charset=utf-8"],
]);
const BINARY = new Map([
[".woff2", "font/woff2"],
[".woff", "font/woff"],
[".png", "image/png"],
[".webp", "image/webp"],
]);
/** The Worker's admin bundle, embedded in its script: keep it modest. */
const MAX_TOTAL_BYTES = 1.5 * 1024 * 1024;
const PLACEHOLDER = "__ADMIN_NONCE__";
function walk(dir: string, out: string[] = []): string[] {
for (const name of readdirSync(dir)) {
const full = join(dir, name);
if (statSync(full).isDirectory()) walk(full, out);
else out.push(full);
}
return out;
}
export function emitWorkerBundle(options: { outDir: string; target: string }): Plugin {
return {
name: "f2p-admin-worker-bundle",
apply: "build",
closeBundle() {
let shell = readFileSync(join(options.outDir, "index.html"), "utf-8");
const scripts = [...shell.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)];
if (scripts.length !== 1) {
throw new Error(`admin bundle: expected exactly one <script> in the shell, found ${scripts.length}`);
}
const [tag, inline] = [scripts[0][0], scripts[0][1]];
if (inline.trim()) throw new Error("admin bundle: the shell's script must be external, not inline");
if (!/type="module"/.test(tag) || !/src="\/admin\/assets\/[^"]+\.js"/.test(tag)) {
throw new Error(`admin bundle: unexpected script tag ${tag}`);
}
shell = shell.replace(tag, tag.replace("<script", `<script nonce="${PLACEHOLDER}"`));
const assets: Record<string, { contentType: string; encoding: "utf8" | "base64"; body: string }> = {};
let total = Buffer.byteLength(shell);
let scriptsOut = 0;
for (const file of walk(join(options.outDir, "assets"))) {
const ext = extname(file);
const key = `/admin/${relative(options.outDir, file).split("\\").join("/")}`;
const bytes = readFileSync(file);
total += bytes.length;
if (ext === ".js") scriptsOut += 1;
if (TEXT.has(ext)) {
assets[key] = { contentType: TEXT.get(ext)!, encoding: "utf8", body: bytes.toString("utf-8") };
} else if (BINARY.has(ext)) {
assets[key] = { contentType: BINARY.get(ext)!, encoding: "base64", body: bytes.toString("base64") };
} else {
throw new Error(`admin bundle: no content type for ${key}`);
}
}
if (scriptsOut !== 1) {
throw new Error(`admin bundle: expected one JS file (codeSplitting off), found ${scriptsOut}`);
}
if (total > MAX_TOTAL_BYTES) {
throw new Error(`admin bundle: ${total} bytes exceeds the ${MAX_TOTAL_BYTES}-byte budget`);
}
const buildId = createHash("sha256")
.update(shell)
.update(Object.keys(assets).sort().join("\n"))
.digest("hex")
.slice(0, 12);
mkdirSync(dirname(options.target), { recursive: true });
writeFileSync(
options.target,
"// GENERATED by admin/build/emit-worker-bundle.ts during `npm run build:admin`.\n" +
"// Do not edit and do not commit (it is gitignored): it is rebuilt from admin/ every time.\n" +
'import type { AdminBundle } from "../lib/admin-bundle";\n\n' +
`export const ADMIN_BUNDLE: AdminBundle = ${JSON.stringify({ buildId, shell, assets })};\n`,
"utf-8",
);
this.info?.(`admin bundle ${buildId}: ${Object.keys(assets).length} assets, ${(total / 1024).toFixed(0)} KiB`);
},
};
}
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex, nofollow" />
<meta name="referrer" content="same-origin" />
<title>Admin · F2P Tracker</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+204
View File
@@ -0,0 +1,204 @@
/**
* The local admin backend, for `npm run dev:admin` and `npm run preview:admin`.
*
* A real Worker cannot run the admin locally: every /admin and /api/admin
* request needs a Cloudflare Access JWT, which cannot be minted offline, so
* `wrangler dev` answers 404 - the old admin pages could never be seen at all
* without deploying them. This plugin runs the REAL handlers
* (worker/routes/admin.ts, edit.ts) inside Vite's dev server against an
* in-memory D1 with the real migrations, fed by the real ../data shards, with
* GitHub faked. Nothing leaves the machine and nothing is written to disk.
*
* It exists ONLY in this Vite config. Nothing under worker/ or admin/src
* imports it (admin/security.test.ts checks), and there is no flag in the
* Worker that could switch authentication off.
*
* MOCK_GITHUB=down, or health reports GitHub unreachable (a 503)
* mock_github=down cookie
* x-mock-session header, "expired" answers like Access does for a lapsed
* mock_session cookie session, so the SPA's re-login path can be tried
*
* In preview mode it also serves /admin* through worker/routes/admin-spa.ts
* and the generated bundle, exactly as production does - the only way to see
* the real CSP before deploying.
*/
import { existsSync, readFileSync } from "node:fs";
import type { IncomingMessage, ServerResponse } from "node:http";
import { join } from "node:path";
import type { Plugin, ViteDevServer } from "vite";
import { isAdminRoute } from "../../shared/admin-routes";
const WEB = join(__dirname, "..", "..");
const REPO = join(WEB, "..");
interface Backend {
handle(request: Request, url: URL): Promise<Response>;
serveShell?: (request: Request, url: URL) => Response;
}
async function readBody(req: IncomingMessage): Promise<Buffer | undefined> {
if (req.method === "GET" || req.method === "HEAD") return undefined;
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
return Buffer.concat(chunks);
}
async function send(res: ServerResponse, response: Response): Promise<void> {
res.statusCode = response.status;
response.headers.forEach((value, key) => res.setHeader(key, value));
res.end(Buffer.from(await response.arrayBuffer()));
}
function loadRecords(): Record<string, unknown>[] {
const dataDir = join(REPO, "data");
const index = JSON.parse(readFileSync(join(dataDir, "index.json"), "utf-8")) as { files: { name: string }[] };
const out: Record<string, unknown>[] = [];
for (const file of index.files) {
for (const line of readFileSync(join(dataDir, file.name), "utf-8").split("\n")) {
if (!line.trim()) continue;
try {
out.push(JSON.parse(line) as Record<string, unknown>);
} catch {
/* skip */
}
}
}
return out;
}
/** Per-request switches, set by the middleware from the environment or a cookie. */
const mock = { githubDown: false };
async function createBackend(server: ViteDevServer, preview: boolean): Promise<Backend> {
const load = <T>(file: string) => server.ssrLoadModule(join(WEB, file)) as Promise<T>;
const [{ makeEnv, fakeDeps }, { SqliteD1 }, { handleAdminApi }, { seed }] = await Promise.all([
load<typeof import("../../worker/testing/fixtures")>("worker/testing/fixtures.ts"),
load<typeof import("../../worker/testing/sqlite-d1")>("worker/testing/sqlite-d1.ts"),
load<typeof import("../../worker/routes/admin")>("worker/routes/admin.ts"),
load<typeof import("./seed")>("admin/mock/seed.ts"),
]);
const records = loadRecords();
const byAppid: Record<string, any> = {};
for (const r of records) {
const appid = /\/app\/(\d+)/.exec(String(r.link ?? ""))?.[1];
if (appid) byAppid[appid] = r;
}
const now = () => new Date();
const deps = fakeDeps({
records: byAppid,
now: now(),
gh: async () =>
mock.githubDown ? new Response("unavailable", { status: 503 }) : new Response("[]", { status: 200 }),
});
deps.now = now;
let hidden = new Set<string>();
deps.fetchRaw = async (path: string) => {
const full = join(REPO, path);
if (!existsSync(full)) return null;
const text = readFileSync(full, "utf-8");
if (!/^data\/data_\d+\.jsonl$/.test(path) || !hidden.size) return text;
// The demo queue is built from real, published games; drop the ones the
// seed wants reconcile to treat as not published yet.
return text
.split("\n")
.filter((line) => !hidden.has(/\/app\/(\d+)/.exec(line)?.[1] ?? ""))
.join("\n");
};
deps.genreCounts = async () => {
const counts = new Map<string, number>();
for (const r of records) if (typeof r.genre === "string" && r.genre) counts.set(r.genre, (counts.get(r.genre) ?? 0) + 1);
return [...counts].map(([genre, count]) => ({ genre, count })).sort((a, b) => b.count - a.count);
};
deps.listByGenre = async (genre: string, limit: number, offset: number) => {
const all = records.filter((r) => r.genre === genre);
return {
total: all.length,
items: all.slice(offset, offset + limit).map((r) => ({
appid: /\/app\/(\d+)/.exec(String(r.link))?.[1] ?? "",
name: String(r.name ?? ""),
genre,
header_image: String(r.header_image ?? ""),
release_date: String(r.release_date ?? ""),
})),
};
};
const db = new SqliteD1();
const env = makeEnv(db);
hidden = seed(db, deps.repo, records as any, new Date()).hidden;
const who = { email: "you@localhost", isServiceToken: false };
const backend: Backend = {
handle: (request, url) => handleAdminApi(request, url, env, who, deps),
};
if (preview) {
const [{ serveAdmin }, generated] = await Promise.all([
load<typeof import("../../worker/routes/admin-spa")>("worker/routes/admin-spa.ts"),
load<{ ADMIN_BUNDLE: import("../../worker/lib/admin-bundle").AdminBundle }>("worker/generated/admin-bundle.ts"),
]);
backend.serveShell = (request, url) => serveAdmin(request, url, generated.ADMIN_BUNDLE);
}
return backend;
}
export function adminDevApi(options: { preview: boolean }): Plugin {
let backend: Promise<Backend> | undefined;
return {
name: "f2p-admin-dev-api",
apply: "serve",
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
const [path, search = ""] = (req.url ?? "").split("?");
const api = path.startsWith("/api/admin/");
const shell = options.preview && (path === "/admin" || path.startsWith("/admin/"));
// Dev: Vite serves the app only under its base, "/admin/", and answers
// "/admin" itself with a did-you-mean page. The app's real URLs have no
// trailing slash, so hand Vite the base while the address bar keeps
// the real path.
if (!options.preview && !api && req.method === "GET" && isAdminRoute(path)) {
req.url = `/admin/${search ? `?${search}` : ""}`;
return next();
}
if (!api && !shell) return next();
try {
// The cookie form exists so the path can be tried from a browser tab:
// document.cookie = "mock_session=expired; path=/"
if (
req.headers["x-mock-session"] === "expired" ||
/(?:^|;\s*)mock_session=expired(?:;|$)/.test(req.headers.cookie ?? "")
) {
res.statusCode = 302;
res.setHeader("Location", "https://example.cloudflareaccess.com/cdn-cgi/access/login");
return res.end();
}
mock.githubDown =
process.env.MOCK_GITHUB === "down" || /(?:^|;\s*)mock_github=down(?:;|$)/.test(req.headers.cookie ?? "");
backend ??= createBackend(server, options.preview);
const ready = await backend;
const url = new URL(req.url ?? "/", "http://localhost");
const body = await readBody(req);
const request = new Request(url, {
method: req.method,
headers: Object.entries(req.headers).flatMap(([k, v]) =>
typeof v === "string" ? [[k, v] as [string, string]] : [],
),
body,
});
if (api) return await send(res, await ready.handle(request, url));
return await send(res, ready.serveShell!(request, url));
} catch (err) {
server.config.logger.error(`[admin mock] ${err instanceof Error ? err.stack : String(err)}`);
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ error: "mock backend crashed - see the terminal" }));
}
});
},
};
}
+90
View File
@@ -0,0 +1,90 @@
/**
* The local admin backend's demo data, run through the REAL handlers.
*
* `npm run dev:admin` is the only way to see the admin before deploying it, so
* a seed that no longer fits the schema, or that stops producing the rows the
* read-only rules exist for, would quietly take that away.
*/
import { describe, expect, it } from "vitest";
import { seed } from "./seed";
import { SqliteD1 } from "../../worker/testing/sqlite-d1";
import { ADMIN, fakeDeps, makeEnv, request } from "../../worker/testing/fixtures";
import { handleAdminApi } from "../../worker/routes/admin";
import { QUEUE_STATUSES } from "../../shared/queue-rules";
const NOW = new Date("2026-09-17T12:00:00Z");
const RECORDS = Array.from({ length: 120 }, (_, i) => ({
link: `https://store.steampowered.com/app/${1000 + i}/`,
name: `Game ${i}`,
header_image: `https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/${1000 + i}/header.jpg`,
reviews: "90% (Very Positive)",
current_players: "1,234",
}));
function setup() {
const db = new SqliteD1();
const env = makeEnv(db);
const deps = fakeDeps({ now: NOW });
const { hidden } = seed(db, deps.repo, RECORDS, NOW);
// The dev server's dataset: every record except the ones the seed hides.
const shard = RECORDS.filter((r) => !hidden.has(/\/app\/(\d+)/.exec(r.link)![1]))
.map((r) => JSON.stringify(r))
.join("\n");
deps.fetchRaw = async (path) =>
path === "data/index.json"
? JSON.stringify({ last_updated: "2026-09-17T00:00:00Z", files: [{ name: "data_001.jsonl" }] })
: path === "data/data_001.jsonl"
? shard
: path === "scripts/removed_games.jsonl"
? ""
: null;
const call = async (method: string, path: string, body?: unknown) => {
const { request: req, url } = request(method, path, body);
const res = await handleAdminApi(req, url, env, ADMIN, deps);
return { status: res.status, body: (await res.json()) as Record<string, any> };
};
return { call, hidden };
}
describe("admin mock seed", () => {
it("fills every queue status", async () => {
const { call } = setup();
const { body } = await call("GET", "/api/admin/stats");
for (const status of QUEUE_STATUSES) expect(body.queue[status], status).toBeGreaterThan(0);
expect(Object.keys(body.commits).sort()).toEqual(["committed", "failed", "pending"]);
});
it("includes an undecided row locked because its game is published", async () => {
const { call } = setup();
const { body } = await call("GET", "/api/admin/queue?status=pending&limit=200");
const locked = body.items.filter((r: { published: boolean }) => r.published);
expect(locked).toHaveLength(1);
const refused = await call("POST", "/api/admin/decide", { ids: [locked[0].id], action: "approve" });
expect(refused.status).toBe(409);
expect(refused.body.skipped[0].reason).toBe("published");
});
it("includes a rejected row that cannot be reopened", async () => {
const { call } = setup();
const { body } = await call("GET", "/api/admin/queue?status=rejected&limit=200");
const blocked = body.items.find((r: { reject_reason: string }) => r.reject_reason === "wrong store page");
const res = await call("POST", "/api/admin/reopen", { id: blocked.id });
expect(res.status).toBe(409);
expect(res.body.reason).toBe("open-row-exists");
});
it("leaves the demo queue standing after a manual reconcile", async () => {
const { call } = setup();
const before = (await call("GET", "/api/admin/stats")).body.queue;
const { body } = await call("POST", "/api/admin/reconcile");
// Two of the four approvals are in the dataset, and the one published
// game's two undecided rows are swept (swept counts games). Nothing else
// moves.
expect(body).toMatchObject({ published: 2, swept: 1, removed: 0, stale: 0 });
const after = (await call("GET", "/api/admin/stats")).body.queue;
expect(after.pending).toBe(before.pending - 1);
expect(after.failed).toBe(before.failed - 1);
expect(after.approved).toBe(before.approved - 2);
expect(after.committed).toBe(before.committed + 4);
});
});
+186
View File
@@ -0,0 +1,186 @@
/**
* Demo state for `npm run dev:admin`: every queue status, rows locked because
* the game is already published, a rejected row that cannot be reopened, commit
* jobs in every state, audit history, and an override file to edit.
*
* Games are real records from ../data, so artwork, names and genres look like
* production. Nothing here is ever written anywhere but the in-memory database
* and the in-memory fake repository.
*/
import type { SqliteD1 } from "../../worker/testing/sqlite-d1";
import type { FakeRepo } from "../../worker/testing/fixtures";
interface Rec {
link: string;
name?: string;
header_image?: string;
release_date?: string;
reviews?: string;
current_players?: string;
}
const HOUR = 3_600_000;
export function seed(sqlite: SqliteD1, repo: FakeRepo, records: Rec[], now: Date): { hidden: Set<string> } {
const db = sqlite.db;
const iso = (msAgo: number) => new Date(now.getTime() - msAgo).toISOString();
const appidOf = (r: Rec) => /\/app\/(\d+)/.exec(r.link)?.[1] ?? "0";
const pct = (r: Rec) => {
const m = /(\d+)%/.exec(r.reviews ?? "");
return m ? Number(m[1]) : null;
};
const players = (r: Rec) => {
const n = Number(String(r.current_players ?? "").replace(/,/g, ""));
return Number.isFinite(n) && String(r.current_players ?? "").trim() !== "" ? n : null;
};
const insert = db.prepare(
`INSERT INTO ingest_queue (id, appid, link, name, header_image, release_date, app_type, is_free,
health_status, reviews_raw, reviews_pct, current_players_raw, current_players_num,
payload_json, source, status, decided_by, decided_at, reject_reason,
first_seen_at, last_seen_at, seen_count)
VALUES (?, ?, ?, ?, ?, ?, 'game', 1, 'ok', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
const decide = db.prepare(
"INSERT OR REPLACE INTO ingest_decisions (appid, decision, reason, decided_by, decided_at) VALUES (?, ?, ?, ?, ?)",
);
let n = 0;
const row = (
r: Rec,
status: string,
extra: { by?: string | null; at?: string | null; reason?: string | null; seenAgo?: number; source?: string } = {},
) => {
const id = `demo-${String(++n).padStart(3, "0")}`;
const seen = iso(extra.seenAgo ?? n * HOUR);
insert.run(
id,
appidOf(r),
r.link,
r.name ?? "",
r.header_image ?? "",
r.release_date ?? "",
r.reviews ?? "N/A",
pct(r),
r.current_players ?? "N/A",
players(r),
JSON.stringify({ link: r.link, name: r.name, reviews: r.reviews, current_players: r.current_players }),
extra.source ?? (n % 5 === 0 ? "extension" : "discover"),
status,
extra.by ?? null,
extra.at ?? null,
extra.reason ?? null,
seen,
iso((extra.seenAgo ?? n * HOUR) / 2),
1 + (n % 4),
);
return id;
};
const pool = records.filter((r) => r.name && r.header_image).slice(0, 110);
let i = 0;
const next = () => pool[i++ % pool.length];
const reviewer = "you@localhost";
// Games the fake repository must NOT list in data/, so reconcile sees them
// as unpublished. Every demo game is a real, published record; without this
// the first reconcile marks the whole demo queue committed.
const hidden = new Set<string>();
const hide = (r: Rec) => {
hidden.add(appidOf(r));
return r;
};
for (let k = 0; k < 45; k++) row(hide(next()), "pending");
for (let k = 0; k < 6; k++) row(hide(next()), "deferred", { seenAgo: (60 + k) * HOUR });
row(hide(next()), "failed", { reason: "never appeared in data/ or removed_games.jsonl - approve again to retry", by: reviewer, at: iso(30 * HOUR) });
row(hide(next()), "failed", { reason: "rejected by ingest pipeline", by: reviewer, at: iso(50 * HOUR) });
row(hide(next()), "failed", { reason: "superseded by a duplicate approval", by: reviewer, at: iso(52 * HOUR) });
// Two approvals the pipeline has published (a manual reconcile commits
// them) and two it has not reached yet.
for (let k = 0; k < 4; k++) {
const r = next();
if (k >= 2) hide(r);
row(r, "approved", { by: reviewer, at: iso((k + 1) * HOUR) });
}
const committed: Rec[] = [];
for (let k = 0; k < 12; k++) {
const r = next();
committed.push(r);
row(r, "committed", { by: reviewer, at: iso((20 + k) * HOUR) });
decide.run(appidOf(r), "approved", "observed in data/", "reconcile", iso((19 + k) * HOUR));
}
for (let k = 0; k < 6; k++) {
const r = hide(next());
row(r, "rejected", { by: reviewer, at: iso((70 + k) * HOUR), reason: k % 2 ? "not free-to-play" : "duplicate listing" });
decide.run(appidOf(r), "rejected", "not free-to-play", reviewer, iso((70 + k) * HOUR));
}
// Locked because the GAME is published: undecided rows for a game that
// already has a committed row. Neither may be approved, rejected or deferred.
const published = committed[0];
row(published, "pending", { seenAgo: 2 * HOUR, source: "extension" });
row(published, "failed", { reason: "never appeared in data/ or removed_games.jsonl - approve again to retry", by: reviewer, at: iso(80 * HOUR) });
// A rejected row that cannot be reopened: another row for the game is open.
const blocked = hide(next());
row(blocked, "rejected", { by: reviewer, at: iso(90 * HOUR), reason: "wrong store page" });
decide.run(appidOf(blocked), "rejected", "wrong store page", reviewer, iso(90 * HOUR));
row(blocked, "deferred", { seenAgo: 5 * HOUR });
const job = db.prepare(
`INSERT INTO commit_jobs (id, kind, status, target_path, commit_sha, error, requested_by, created_at, finished_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
const sha = (k: number) => createFakeSha(k);
job.run("job-1", "approve", "committed", "scripts/temp_info.jsonl", sha(1), null, reviewer, iso(1 * HOUR), iso(1 * HOUR));
job.run("job-2", "approve", "committed", "scripts/temp_info.jsonl", null, "nothing to commit: every link was already queued", reviewer, iso(3 * HOUR), iso(3 * HOUR));
job.run("job-3", "override", "committed", "data/overrides/730.json", sha(3), null, reviewer, iso(8 * HOUR), iso(8 * HOUR));
job.run("job-4", "approve", "failed", "scripts/temp_info.jsonl", null, "graphql HTTP 502", reviewer, iso(26 * HOUR), iso(26 * HOUR));
job.run("job-5", "override.delete", "committed", "data/overrides/440.json", sha(5), null, reviewer, iso(40 * HOUR), iso(40 * HOUR));
job.run("job-6", "approve", "pending", "scripts/temp_info.jsonl", null, null, reviewer, iso(96 * HOUR), null);
const audit = db.prepare(
"INSERT INTO audit_log (actor, action, target, detail_json, created_at) VALUES (?, ?, ?, ?, ?)",
);
const events: [string, string, string | null, unknown, number][] = [
["reconcile", "reconcile.approved", null, { checked: 4, published: 2, removed: 0, stale: 0, swept: 3 }, 0.5],
[reviewer, "approve", "job-1", { appids: ["1", "2"], sha: sha(1), appended: 2, reason: "checked store pages" }, 1],
[reviewer, "reject", null, { appids: ["3"], reason: "not free-to-play" }, 2],
[reviewer, "defer", null, { appids: ["4", "5"] }, 4],
[reviewer, "override", "730", { appids: ["730"], set: ["genre"], retire: [], sha: sha(3) }, 8],
[reviewer, "reopen", "demo-001", { appid: "10" }, 12],
[reviewer, "approve.failed", "job-4", { message: "graphql HTTP 502", count: 3 }, 26],
["retention", "admin.prune", null, { audit: 14, jobs: 3 }, 30],
[reviewer, "ping", null, { at: iso(48 * HOUR) }, 48],
];
// Oldest first: the audit view orders by id, as production rows are written.
for (const [actor, action, target, detail, hoursAgo] of [...events].sort((a, b) => b[4] - a[4])) {
audit.run(actor, action, target, JSON.stringify(detail), iso(hoursAgo * HOUR));
}
// An override on a real game: one active field and one retired one that has
// already been restored.
repo.files.set(
"data/overrides/730.json",
JSON.stringify(
{
schema: 1,
appid: "730",
link: "https://store.steampowered.com/app/730/",
name: "Counter-Strike 2",
fields: { anti_cheat_note: { value: "VAC plus server-side detection", was: "", set_by: reviewer, set_at: iso(8 * HOUR), reason: "Valve's own wording" } },
retired: { genre: { value: "Shooter", was: "FPS", retired_by: reviewer, retired_at: iso(40 * HOUR) } },
},
null,
2,
) + "\n",
);
return { hidden };
}
function createFakeSha(k: number): string {
return (k.toString(16).padStart(2, "0") + "5f0c3a9e1b7d2468ace13579bdf02468ace13579").slice(0, 40);
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Source-level rules for the admin SPA, the one page that can commit to the
* repository. Each is cheap to check here and expensive to discover in review.
*/
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";
import { ADMIN_ROUTES } from "../shared/admin-routes";
const WEB = join(__dirname, "..");
function files(dir: string, exts: string[]): string[] {
const out: string[] = [];
for (const name of readdirSync(dir)) {
const full = join(dir, name);
if (statSync(full).isDirectory()) {
if (name !== "node_modules" && name !== "generated") out.push(...files(full, exts));
} else if (exts.some((e) => name.endsWith(e)) && !/\.test\.ts$/.test(name)) {
out.push(full);
}
}
return out;
}
const adminSources = files(join(WEB, "admin", "src"), [".ts", ".svelte"]);
const read = (f: string) => readFileSync(f, "utf-8");
const rel = (f: string) => relative(WEB, f).replaceAll("\\", "/");
describe("admin SPA source rules", () => {
it("has sources to check", () => {
expect(adminSources.length).toBeGreaterThan(10);
});
it("never renders raw HTML", () => {
// Every value on these screens (game names, reasons, payloads, audit
// detail) is text somebody else wrote. Svelte escapes text; these bypass it.
const offenders = adminSources.filter((f) => /\{@html\b|\.innerHTML\b|\.outerHTML\b|insertAdjacentHTML|document\.write\(/.test(read(f)));
expect(offenders.map(rel)).toEqual([]);
});
it("never evaluates strings as code", () => {
const offenders = adminSources.filter((f) => /\beval\(|new Function\(|setTimeout\(\s*["'`]/.test(read(f)));
expect(offenders.map(rel)).toEqual([]);
});
it("keeps the mock backend out of the app and the Worker", () => {
const shipped = [...adminSources, ...files(join(WEB, "worker"), [".ts"])];
const offenders = shipped.filter((f) => /from\s+["'][^"']*admin\/mock|from\s+["']\.\.?\/(\.\.\/)*mock\//.test(read(f)));
expect(offenders.map(rel)).toEqual([]);
});
it("takes the queue's rules from shared/queue-rules.ts instead of restating them", () => {
// The old page carried its own DECIDABLE literal, and a test existed only
// to keep the two copies equal.
const offenders = adminSources.filter((f) =>
/\[\s*["']pending["']\s*,\s*["']deferred["']\s*,\s*["']failed["']\s*\]/.test(read(f)),
);
expect(offenders.map(rel)).toEqual([]);
});
it("does not reach into SvelteKit, which this build cannot resolve", () => {
const offenders = adminSources.filter((f) => /from\s+["'](\$app|\$lib|\$env)\//.test(read(f)));
expect(offenders.map(rel)).toEqual([]);
});
it("renders a view for every admin route, and links every route from the nav", () => {
const app = read(join(WEB, "admin", "src", "App.svelte"));
const navPaths = [...app.matchAll(/\{\s*path:\s*"([^"]+)"/g)].map((m) => m[1]);
expect(navPaths).toEqual([...ADMIN_ROUTES]);
for (const route of ADMIN_ROUTES) {
expect(app, `App.svelte has no branch for ${route}`).toContain(`router.route === "${route}"`);
}
});
});
describe("the public app", () => {
it("never calls the admin API", () => {
const offenders = files(join(WEB, "src"), [".ts", ".svelte"]).filter((f) => read(f).includes("/api/admin"));
expect(offenders.map(rel)).toEqual([]);
});
});
+139
View File
@@ -0,0 +1,139 @@
<script lang="ts">
import { onMount } from "svelte";
import { Toaster } from "svelte-sonner";
import Inbox from "@lucide/svelte/icons/inbox";
import SquarePen from "@lucide/svelte/icons/square-pen";
import GitCommitHorizontal from "@lucide/svelte/icons/git-commit-horizontal";
import ScrollText from "@lucide/svelte/icons/scroll-text";
import HeartPulse from "@lucide/svelte/icons/heart-pulse";
import Sun from "@lucide/svelte/icons/sun";
import Moon from "@lucide/svelte/icons/moon";
import Monitor from "@lucide/svelte/icons/monitor";
import ExternalLink from "@lucide/svelte/icons/external-link";
import { theme, type Theme } from "../../src/lib/prefs.svelte";
import { router } from "./lib/router.svelte";
import { api, SessionExpiredError } from "./lib/api";
import { reportError } from "./lib/notify";
import type { MeResponse } from "../../shared/admin-api";
import type { AdminRoute } from "../../shared/admin-routes";
import QueueView from "./views/QueueView.svelte";
import EditView from "./views/EditView.svelte";
import JobsView from "./views/JobsView.svelte";
import AuditView from "./views/AuditView.svelte";
import HealthView from "./views/HealthView.svelte";
import NotFound from "./views/NotFound.svelte";
/** Every entry in shared/admin-routes.ts, and nothing else (app.test.ts). */
const NAV: { path: AdminRoute; label: string; title: string; icon: typeof Inbox }[] = [
{ path: "/admin", label: "Queue", title: "Review queue", icon: Inbox },
{ path: "/admin/edit", label: "Edit", title: "Correct published games", icon: SquarePen },
{ path: "/admin/jobs", label: "Jobs", title: "Commit jobs", icon: GitCommitHorizontal },
{ path: "/admin/audit", label: "Audit", title: "Audit log", icon: ScrollText },
{ path: "/admin/health", label: "Health", title: "Health", icon: HeartPulse },
];
const THEMES: { value: Theme; label: string; icon: typeof Sun }[] = [
{ value: "light", label: "Light", icon: Sun },
{ value: "dark", label: "Dark", icon: Moon },
{ value: "system", label: "System", icon: Monitor },
];
let me = $state.raw<MeResponse | null>(null);
onMount(() => {
theme.hydrate();
const uninstall = router.install();
api<MeResponse>("/api/admin/me")
.then((m) => (me = m))
.catch((err) => {
if (err instanceof SessionExpiredError) reportError(err);
});
return uninstall;
});
const current = $derived(NAV.find((n) => n.path === router.route));
$effect(() => {
document.title = `${current?.title ?? "Not found"} · F2P admin`;
});
function cycleTheme() {
const i = THEMES.findIndex((t) => t.value === theme.value);
theme.set(THEMES[(i + 1) % THEMES.length].value);
}
const themeNow = $derived(THEMES.find((t) => t.value === theme.value) ?? THEMES[1]);
</script>
<div class="min-h-dvh bg-background text-foreground">
<a
href="#main"
class="sr-only z-50 rounded-md bg-primary px-3 py-2 text-primary-foreground focus:not-sr-only focus:fixed focus:top-2 focus:left-2"
>Skip to content</a
>
<header class="sticky top-0 z-30 border-b border-border bg-background/90 backdrop-blur">
<div class="mx-auto flex h-14 max-w-7xl items-center gap-2 px-4 sm:gap-4">
<a href="/admin" class="flex shrink-0 items-center gap-2 font-display text-base font-semibold">
<span class="grid size-7 place-items-center rounded-md bg-primary text-xs font-bold text-primary-foreground">F2P</span>
<span class="hidden sm:inline">Admin</span>
</a>
<nav aria-label="Admin" class="-mx-1 flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto px-1 scrollbar-thin">
{#each NAV as item (item.path)}
{@const active = router.route === item.path}
<a
href={item.path}
aria-current={active ? "page" : undefined}
class="inline-flex shrink-0 items-center gap-1.5 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors
{active ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent/60 hover:text-foreground'}"
>
<item.icon class="size-4" />
<span class="hidden md:inline">{item.label}</span>
<span class="sr-only md:hidden">{item.label}</span>
</a>
{/each}
</nav>
<div class="flex shrink-0 items-center gap-1">
{#if me}
<span class="hidden max-w-48 truncate text-xs text-muted-foreground lg:inline" title="Signed in with Cloudflare Access">
{me.email}
</span>
{/if}
<a
href="https://free-steam-games.win"
target="_blank"
rel="noopener noreferrer"
class="hidden items-center gap-1 rounded-md px-2 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground sm:inline-flex"
>
Site <ExternalLink class="size-3" />
</a>
<button
type="button"
class="rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-foreground"
title="Theme: {themeNow.label}. Click to change."
aria-label="Theme: {themeNow.label}. Click to change."
onclick={cycleTheme}
>
<themeNow.icon class="size-4" />
</button>
</div>
</div>
</header>
<main id="main" class="mx-auto max-w-7xl px-4 py-6 pb-24">
{#if router.route === "/admin"}
<QueueView />
{:else if router.route === "/admin/edit"}
<EditView />
{:else if router.route === "/admin/jobs"}
<JobsView />
{:else if router.route === "/admin/audit"}
<AuditView />
{:else if router.route === "/admin/health"}
<HealthView />
{:else}
<NotFound />
{/if}
</main>
</div>
<Toaster theme={theme.resolved} position="bottom-right" richColors closeButton />
+6
View File
@@ -0,0 +1,6 @@
/* The admin SPA's stylesheet: the public app's design system, scanned only
over the admin's own files and the shared UI components it renders. */
@import "tailwindcss" source(".");
@source "../../src/lib/ui";
@import "../../src/fonts.css";
@import "../../src/styles/theme.css";
+105
View File
@@ -0,0 +1,105 @@
<!--
A modal on the native <dialog>. showModal() gives the focus trap, inert
background, top layer and Escape for free, which is everything bits-ui was
providing - without a dependency or a portal.
-->
<script lang="ts">
import type { Snippet } from "svelte";
import X from "@lucide/svelte/icons/x";
import { cn } from "../../../src/lib/utils";
type Props = {
open: boolean;
title: string;
description?: string;
size?: "sm" | "md" | "lg" | "xl";
/** False while a request is running: Escape and the backdrop do nothing. */
dismissable?: boolean;
onclose?: () => void;
children: Snippet;
footer?: Snippet;
};
let {
open = $bindable(),
title,
description,
size = "md",
dismissable = true,
onclose,
children,
footer,
}: Props = $props();
const id = $props.id();
let dialog = $state<HTMLDialogElement>();
const WIDTH = { sm: "max-w-md", md: "max-w-xl", lg: "max-w-3xl", xl: "max-w-5xl" } as const;
$effect(() => {
if (!dialog) return;
if (open && !dialog.open) {
dialog.showModal();
// showModal() focuses the first focusable element, which is the close
// button. A dialog that asks for input marks the field it wants instead.
dialog.querySelector<HTMLElement>("[data-autofocus]")?.focus();
} else if (!open && dialog.open) dialog.close();
});
function close() {
if (dismissable) dialog?.close();
}
</script>
<dialog
bind:this={dialog}
aria-labelledby="{id}-title"
aria-describedby={description ? `${id}-desc` : undefined}
class={cn(
"m-auto max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] overflow-hidden rounded-lg border border-border bg-card p-0 text-card-foreground shadow-2xl",
"backdrop:bg-black/60 backdrop:backdrop-blur-[2px]",
WIDTH[size],
)}
oncancel={(e) => {
if (!dismissable) e.preventDefault();
}}
onclose={() => {
open = false;
onclose?.();
}}
onclick={(e) => {
// The dialog element itself is only ever the target for a click on the
// backdrop: all of its content sits inside the wrapper below.
if (e.target === dialog) close();
}}
>
{#if open}
<div class="flex max-h-[calc(100dvh-2rem)] flex-col">
<header class="flex items-start gap-3 border-b border-border px-5 py-4">
<div class="min-w-0 flex-1">
<h2 id="{id}-title" class="text-base font-semibold leading-6">{title}</h2>
{#if description}
<p id="{id}-desc" class="mt-0.5 text-sm text-muted-foreground">{description}</p>
{/if}
</div>
<button
type="button"
class="-mr-1 rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40"
aria-label="Close"
disabled={!dismissable}
onclick={close}
>
<X class="size-4" />
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto px-5 py-4">
{@render children()}
</div>
{#if footer}
<footer class="flex flex-wrap items-center justify-end gap-2 border-t border-border bg-muted/40 px-5 py-3">
{@render footer()}
</footer>
{/if}
</div>
{/if}
</dialog>
@@ -0,0 +1,14 @@
<script lang="ts">
import type { Component, Snippet } from "svelte";
type Props = { icon: Component<{ class?: string }>; title: string; children?: Snippet };
let { icon: Icon, title, children }: Props = $props();
</script>
<div class="flex flex-col items-center justify-center gap-2 px-6 py-14 text-center">
<div class="rounded-full bg-muted p-3 text-muted-foreground"><Icon class="size-5" /></div>
<p class="font-medium">{title}</p>
{#if children}
<div class="max-w-md text-sm text-muted-foreground">{@render children()}</div>
{/if}
</div>
@@ -0,0 +1,57 @@
<!-- One manual field's control. The genre list carries counts because they are
how a vague bucket gets noticed. -->
<script lang="ts">
import type { FieldSpec } from "../lib/fields";
type Props = {
spec: FieldSpec;
value: string;
id: string;
disabled?: boolean;
invalid?: boolean;
genres?: { genre: string; count: number }[];
/** The value the field held when loaded, kept selectable even when unusual. */
current?: string;
};
let { spec, value = $bindable(), id, disabled = false, invalid = false, genres = [], current = "" }: Props = $props();
const base =
"w-full rounded-md border bg-background px-3 text-sm placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50";
const border = $derived(invalid ? "border-destructive" : "border-input");
const extra = $derived(
spec.options && current && !spec.options.some((o) => o.value === current) ? current : null,
);
</script>
{#if spec.kind === "genre"}
<input
{id}
bind:value
type="text"
list="{id}-list"
maxlength="500"
autocomplete="off"
{disabled}
aria-invalid={invalid}
class="{base} {border} h-9"
/>
<datalist id="{id}-list">
{#each genres as g (g.genre)}
<option value={g.genre}>{g.count} games</option>
{/each}
</datalist>
{:else if spec.kind === "select"}
<select {id} bind:value {disabled} aria-invalid={invalid} class="{base} {border} h-9">
{#if extra !== null}
<option value={extra}>{extra} (current, not a valid choice)</option>
{/if}
{#each spec.options ?? [] as o (o.value)}
<option value={o.value}>{o.label}</option>
{/each}
</select>
{:else if spec.kind === "area"}
<textarea {id} bind:value rows="3" maxlength="500" {disabled} aria-invalid={invalid} class="{base} {border} py-2 leading-5"
></textarea>
{:else}
<input {id} bind:value type="text" maxlength="500" autocomplete="off" {disabled} aria-invalid={invalid} class="{base} {border} h-9" />
{/if}
+13
View File
@@ -0,0 +1,13 @@
<script lang="ts">
import type { Snippet } from "svelte";
import { cn } from "../../../src/lib/utils";
let { children, class: className }: { children: Snippet; class?: string } = $props();
</script>
<kbd
class={cn(
"inline-flex h-5 min-w-5 items-center justify-center rounded border border-border-strong bg-muted px-1 font-mono text-[11px] leading-none text-muted-foreground",
className,
)}>{@render children()}</kbd
>
+62
View File
@@ -0,0 +1,62 @@
<script lang="ts">
import ChevronLeft from "@lucide/svelte/icons/chevron-left";
import ChevronRight from "@lucide/svelte/icons/chevron-right";
import Button from "../../../src/lib/ui/Button.svelte";
import { rangeLabel } from "../lib/format";
type Props = {
offset: number;
limit: number;
total: number;
count: number;
disabled?: boolean;
sizes?: number[];
onpage: (offset: number) => void;
onsize?: (size: number) => void;
};
let { offset, limit, total, count, disabled = false, sizes = [25, 50, 100, 200], onpage, onsize }: Props = $props();
const page = $derived(Math.floor(offset / limit) + 1);
const pages = $derived(Math.max(1, Math.ceil(total / limit)));
</script>
<nav class="flex flex-wrap items-center justify-between gap-3 text-sm" aria-label="Pagination">
<p class="tnum text-muted-foreground" aria-live="polite">{rangeLabel(offset, count, total)}</p>
<div class="flex items-center gap-2">
{#if onsize}
<label class="flex items-center gap-2 text-muted-foreground">
<span class="hidden sm:inline">Rows</span>
<select
class="h-8 rounded-md border border-input bg-background px-2 text-sm text-foreground"
value={limit}
{disabled}
onchange={(e) => onsize(Number(e.currentTarget.value))}
>
{#each sizes as size (size)}
<option value={size}>{size}</option>
{/each}
</select>
</label>
{/if}
<Button
variant="outline"
size="sm"
disabled={disabled || offset === 0}
aria-label="Previous page"
onclick={() => onpage(Math.max(0, offset - limit))}
>
<ChevronLeft class="size-4" />
</Button>
<span class="tnum min-w-20 text-center text-muted-foreground">Page {page} of {pages}</span>
<Button
variant="outline"
size="sm"
disabled={disabled || offset + limit >= total}
aria-label="Next page"
onclick={() => onpage(offset + limit)}
>
<ChevronRight class="size-4" />
</Button>
</div>
</nav>
@@ -0,0 +1,35 @@
<script lang="ts">
import Badge, { type BadgeVariant } from "../../../src/lib/ui/Badge.svelte";
import { STATUS_HELP } from "../lib/labels";
type Props = { status: string; kind?: "queue" | "job"; class?: string };
let { status, kind = "queue", class: className }: Props = $props();
const QUEUE: Record<string, BadgeVariant> = {
pending: "info",
deferred: "secondary",
approved: "default",
committed: "success",
// A failed ROW can be decided again, so it is a warning rather than an error.
failed: "warning",
rejected: "destructive",
};
const JOB: Record<string, BadgeVariant> = {
pending: "info",
committed: "success",
conflict: "warning",
failed: "destructive",
};
const JOB_HELP: Record<string, string> = {
pending: "Started, and no result was recorded. The Worker may have stopped mid-commit.",
committed: "The commit landed, or there was nothing to commit.",
conflict: "The file changed underneath the commit on every attempt.",
failed: "The commit was refused or GitHub could not be reached. Nothing was written.",
};
const variant = $derived((kind === "job" ? JOB : QUEUE)[status] ?? "outline");
const help = $derived(kind === "job" ? JOB_HELP[status] : STATUS_HELP[status]);
</script>
<Badge {variant} class={className} title={help}>{status}</Badge>
+28
View File
@@ -0,0 +1,28 @@
<!-- Steam capsule art. A missing or refused image becomes a quiet placeholder
instead of the browser's broken-image glyph. -->
<script lang="ts">
import Gamepad2 from "@lucide/svelte/icons/gamepad-2";
import { cn } from "../../../src/lib/utils";
type Props = { src: string | null | undefined; class?: string; lazy?: boolean };
let { src, class: className, lazy = true }: Props = $props();
// Keyed on the URL, so a row reused for another game tries its image afresh.
let failedSrc = $state<string | null>(null);
const failed = $derived(!!src && failedSrc === src);
</script>
{#if src && !failed}
<img
{src}
alt=""
loading={lazy ? "lazy" : "eager"}
referrerpolicy="no-referrer"
class={cn("rounded border border-border bg-muted object-cover", className)}
onerror={() => (failedSrc = src ?? null)}
/>
{:else}
<span class={cn("grid place-items-center rounded border border-border bg-muted text-muted-foreground", className)} aria-hidden="true">
<Gamepad2 class="size-4 opacity-60" />
</span>
{/if}
+89
View File
@@ -0,0 +1,89 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { api, ApiError, SessionExpiredError } from "./api";
type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
function stubFetch(response: Response | (() => Promise<Response>)) {
const fn = vi.fn<Fetch>(typeof response === "function" ? response : async () => response);
vi.stubGlobal("fetch", fn);
return fn;
}
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json; charset=utf-8" } });
/** What fetch() returns for a redirect it was told not to follow. */
function opaqueRedirect(): Response {
const res = new Response(null, { status: 200 });
Object.defineProperty(res, "type", { value: "opaqueredirect" });
Object.defineProperty(res, "status", { value: 0 });
return res;
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("api()", () => {
it("asks fetch not to follow redirects, same-origin only", async () => {
const fetch = stubFetch(json({ ok: true }));
await api("/api/admin/me");
const init = fetch.mock.calls[0][1] as RequestInit;
// Following Access's login redirect from fetch() is what produced the
// cloudflareaccess.com connect-src violations on the old pages.
expect(init.redirect).toBe("manual");
expect(init.credentials).toBe("same-origin");
});
it("sends JSON bodies with a JSON content type", async () => {
const fetch = stubFetch(json({ ok: true }));
await api("/api/admin/decide", { method: "POST", body: { ids: ["a"], action: "approve" } });
const init = fetch.mock.calls[0][1] as RequestInit;
expect(init.method).toBe("POST");
expect(init.body).toBe('{"ids":["a"],"action":"approve"}');
expect((init.headers as Record<string, string>)["Content-Type"]).toBe("application/json");
});
it.each([
["an opaque redirect", opaqueRedirect],
["a 401", () => json({ error: "no" }, 401)],
["a 403", () => json({ error: "no" }, 403)],
])("treats %s as an expired session", async (_label, make) => {
stubFetch(make());
await expect(api("/api/admin/queue")).rejects.toBeInstanceOf(SessionExpiredError);
});
it("reports a non-JSON body as a server problem, not an expired session", async () => {
stubFetch(new Response("<html>1101</html>", { status: 500, headers: { "Content-Type": "text/html" } }));
const err = await api("/api/admin/queue").catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect(err).not.toBeInstanceOf(SessionExpiredError);
expect((err as ApiError).status).toBe(500);
});
it("surfaces the server's error message", async () => {
stubFetch(json({ error: "commit failed: graphql HTTP 502" }, 502));
await expect(api("/api/admin/decide", { method: "POST", body: {} })).rejects.toThrow("commit failed: graphql HTTP 502");
});
it("returns the body of an accepted non-2xx status", async () => {
stubFetch(json({ ok: false, github: "503" }, 503));
await expect(api("/api/admin/health", { accept: [503] })).resolves.toEqual({ ok: false, github: "503" });
});
it("turns a network failure into a readable error", async () => {
stubFetch(async () => {
throw new TypeError("Failed to fetch");
});
await expect(api("/api/admin/queue")).rejects.toThrow(/could not be reached/);
});
it("lets an abort propagate as an abort", async () => {
const controller = new AbortController();
controller.abort();
stubFetch(async () => {
throw new DOMException("aborted", "AbortError");
});
await expect(api("/api/admin/queue", { signal: controller.signal })).rejects.toMatchObject({ name: "AbortError" });
});
});
+87
View File
@@ -0,0 +1,87 @@
/**
* Every call the admin makes to /api/admin/*.
*
* Same-origin, and `redirect: "manual"` on purpose. When the Cloudflare Access
* session lapses, Access answers with a redirect to its login page; followed
* silently, that redirect lands on HTML from another origin, which the old
* pages then mis-reported as a server error. Stopped here, it surfaces as an
* opaque redirect, and the app reloads the page so Access can sign the reviewer
* in again.
*
* Writes carry no token of their own: the edge attaches the Access assertion
* to same-origin requests, and worker/index.ts additionally rejects any write
* announcing a cross-site origin.
*/
export class SessionExpiredError extends Error {
constructor() {
super("Your Cloudflare Access session has expired.");
this.name = "SessionExpiredError";
}
}
export class ApiError extends Error {
constructor(
readonly status: number,
message: string,
readonly body: unknown,
) {
super(message);
this.name = "ApiError";
}
}
export interface ApiOptions {
method?: "GET" | "POST";
body?: unknown;
signal?: AbortSignal;
/** Statuses whose JSON body is a normal answer, not an error (health: 503). */
accept?: number[];
}
export async function api<T>(path: string, options: ApiOptions = {}): Promise<T> {
let res: Response;
try {
res = await fetch(path, {
method: options.method ?? "GET",
credentials: "same-origin",
redirect: "manual",
signal: options.signal,
headers: options.body === undefined ? undefined : { "Content-Type": "application/json" },
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
} catch (err) {
if (options.signal?.aborted) throw err;
throw new ApiError(0, "The admin API could not be reached. Check the connection and try again.", null);
}
if (res.type === "opaqueredirect" || res.status === 0 || res.status === 401 || res.status === 403) {
throw new SessionExpiredError();
}
const isJson = (res.headers.get("Content-Type") ?? "").includes("application/json");
const body: unknown = isJson ? await res.json().catch(() => null) : null;
// Every route under /api/admin answers JSON, errors included (worker/index.ts
// wraps dispatch in one try/catch). A non-JSON body is therefore reported as
// what it is. The old pages called it an expired session, and that hid real
// Worker crashes behind the most misleading message on the screen.
if (!isJson) {
throw new ApiError(res.status, `The server answered ${res.status} with a non-JSON body. Check wrangler tail.`, null);
}
if (res.ok || options.accept?.includes(res.status)) return body as T;
const message =
body && typeof body === "object" && typeof (body as { error?: unknown }).error === "string"
? (body as { error: string }).error
: `The server answered ${res.status}.`;
throw new ApiError(res.status, message, body);
}
/** A readable sentence for any thrown value. */
export function errorMessage(err: unknown): string {
if (err instanceof SessionExpiredError) return err.message;
if (err instanceof Error) return err.message;
return String(err);
}
+83
View File
@@ -0,0 +1,83 @@
/**
* The seven human-judgement fields as the edit screens present them, and the
* client-side mirror of validateValue() in worker/routes/edit.ts.
*
* The mirror exists so a reviewer is told before a commit is attempted. It
* is the weakest of three copies: the Worker re-validates, and the Python
* validator in scripts/core/overrides.py is the authority. fields.test.ts runs
* both TypeScript copies over the same inputs and fails if they disagree.
*/
import { MANUAL_FIELDS, type ManualField } from "../../../shared/admin-api";
export { MANUAL_FIELDS };
export interface FieldSpec {
key: ManualField;
label: string;
kind: "genre" | "select" | "text" | "area";
options?: { value: string; label: string }[];
hint?: string;
}
export const FIELDS: FieldSpec[] = [
{ key: "genre", label: "Genre", kind: "genre", hint: "Pick from the catalogue's genres, or type a new one." },
{
key: "type_game",
label: "Type",
kind: "select",
options: [
{ value: "online", label: "online" },
{ value: "offline", label: "offline" },
],
},
{
key: "safe",
label: "Safe",
kind: "select",
options: [
{ value: "y", label: "y · safe" },
{ value: "n", label: "n · not safe" },
{ value: "?", label: "? · not reviewed" },
],
},
{ key: "anti_cheat", label: "Anti-cheat", kind: "text", hint: "For example: EasyAntiCheat, BattlEye, VAC." },
{
key: "is_kernel_ac",
label: "Kernel anti-cheat",
kind: "select",
options: [
{ value: "true", label: "true · kernel level" },
{ value: "false", label: "false · user mode or none" },
{ value: "null", label: "null · unknown" },
],
},
{ key: "anti_cheat_note", label: "Anti-cheat note", kind: "area" },
{ key: "notes", label: "Notes", kind: "area" },
];
export const FIELD_LABEL = Object.fromEntries(FIELDS.map((f) => [f.key, f.label])) as Record<ManualField, string>;
/** A stored value as a form control holds it. */
export function toForm(field: ManualField, value: unknown): string {
if (field === "is_kernel_ac") return value === true ? "true" : value === false ? "false" : "null";
return value === null || value === undefined ? "" : String(value);
}
/** A form control's text as the API expects it. */
export function toWire(field: ManualField, text: string): unknown {
if (field === "is_kernel_ac") return text === "true" ? true : text === "false" ? false : null;
return text.trim();
}
/** null when the value may be saved, else why not. */
export function validate(field: ManualField, text: string): string | null {
if (field === "is_kernel_ac") {
return ["true", "false", "null"].includes(text) ? null : "must be true, false or null";
}
const value = text.trim();
if (!value) return "empty - retire the field instead of blanking it";
if (field === "type_game" && value !== "online" && value !== "offline") return "must be 'online' or 'offline'";
if (field === "safe" && !["y", "n", "?"].includes(value)) return "must be 'y', 'n' or '?'";
if (value.length > 500) return "longer than 500 characters";
return null;
}
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { exactTime, plural, prettyJson, rangeLabel, relativeTime, shortSha, showValue } from "./format";
const NOW = Date.parse("2026-09-17T12:00:00Z");
describe("format", () => {
it("relativeTime", () => {
expect(relativeTime("2026-09-17T11:59:30Z", NOW)).toBe("just now");
expect(relativeTime("2026-09-17T09:00:00Z", NOW)).toBe("3 hours ago");
expect(relativeTime("2026-09-16T12:00:00Z", NOW)).toBe("yesterday");
expect(relativeTime(null, NOW)).toBe("—");
expect(relativeTime("not a date", NOW)).toBe("not a date");
});
it("exactTime is UTC to the minute", () => {
expect(exactTime("2026-09-17T12:04:59.123Z")).toBe("2026-09-17 12:04 UTC");
});
it("rangeLabel", () => {
expect(rangeLabel(0, 50, 646)).toBe("1–50 of 646");
expect(rangeLabel(600, 46, 646)).toBe("601–646 of 646");
expect(rangeLabel(0, 0, 0)).toBe("0 of 0");
});
it("plural and shortSha", () => {
expect(plural(1, "row")).toBe("1 row");
expect(plural(1200, "row")).toBe("1,200 rows");
expect(shortSha("0123456789abcdef")).toBe("0123456");
expect(shortSha(null)).toBe("—");
});
it("showValue distinguishes empty, null and booleans", () => {
expect(showValue("")).toBe("(empty)");
expect(showValue(null)).toBe("null");
expect(showValue(false)).toBe("false");
expect(showValue("FPS")).toBe("FPS");
});
it("prettyJson falls back to the raw text", () => {
expect(prettyJson('{"a":1}')).toBe('{\n "a": 1\n}');
expect(prettyJson("{broken")).toBe("{broken");
});
});
+68
View File
@@ -0,0 +1,68 @@
const REPO = "https://github.com/poli0981/free-steam-games-list";
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
["year", 31_536_000],
["month", 2_592_000],
["week", 604_800],
["day", 86_400],
["hour", 3_600],
["minute", 60],
];
/** "3 hours ago". The ISO string belongs in a title attribute beside it. */
export function relativeTime(iso: string | null | undefined, now = Date.now()): string {
if (!iso) return "—";
const ms = Date.parse(iso);
if (Number.isNaN(ms)) return iso;
const seconds = Math.round((ms - now) / 1000);
for (const [unit, per] of UNITS) {
if (Math.abs(seconds) >= per) return rtf.format(Math.round(seconds / per), unit);
}
return "just now";
}
/** "2026-09-17 12:04 UTC" - for tooltips and exact records. */
export function exactTime(iso: string | null | undefined): string {
if (!iso) return "";
const ms = Date.parse(iso);
if (Number.isNaN(ms)) return iso;
return new Date(ms).toISOString().slice(0, 16).replace("T", " ") + " UTC";
}
export function formatInt(n: number | null | undefined): string {
return n === null || n === undefined ? "—" : n.toLocaleString("en-US");
}
/** "1 row", "3 rows". */
export function plural(n: number, word: string): string {
return `${formatInt(n)} ${word}${n === 1 ? "" : "s"}`;
}
/** An override or catalogue value as the reviewer should read it. */
export function showValue(value: unknown): string {
if (value === null || value === undefined) return "null";
if (typeof value === "string") return value === "" ? "(empty)" : value;
return JSON.stringify(value);
}
export const shortSha = (sha: string | null | undefined): string => (sha ? sha.slice(0, 7) : "—");
export const commitUrl = (sha: string): string => `${REPO}/commit/${sha}`;
export const steamUrl = (appid: string): string => `https://store.steampowered.com/app/${appid}/`;
export const fileUrl = (path: string): string => `${REPO}/blob/main/${path}`;
/** Pretty JSON for display, or the raw text when it does not parse. */
export function prettyJson(text: string | null | undefined): string {
if (!text) return "";
try {
return JSON.stringify(JSON.parse(text), null, 2);
} catch {
return text;
}
}
/** "1-50 of 646" for a pager. */
export function rangeLabel(offset: number, count: number, total: number): string {
if (!total || !count) return `0 of ${formatInt(total)}`;
return `${formatInt(offset + 1)}–${formatInt(offset + count)} of ${formatInt(total)}`;
}
+71
View File
@@ -0,0 +1,71 @@
/**
* Every sentence the admin shows about a status, a skip or a lock. English
* only: the admin has one audience, and a translation layer would be weight
* with no reader.
*/
import type { DecideAction, LockReason, SkipReason } from "../../../shared/queue-rules";
export const STATUS_HELP: Record<string, string> = {
pending: "Waiting for a decision.",
deferred: "Put aside for later. The game stays blocked from being queued again.",
approved: "Requested for publication. Waiting for the pipeline to add it.",
committed: "Published: the game is in the catalogue.",
rejected: "Rejected. Reopen it from the details dialog.",
failed: "The pipeline did not publish it, or a duplicate approval replaced it. It can be decided again.",
};
export const LOCK_HELP: Record<LockReason, string> = {
decided: "Read-only: this row has already been decided.",
published: "Read-only: this game is already in the catalogue.",
};
export const SKIP_TEXT: Record<SkipReason, string> = {
"not-found": "no longer in the queue",
"not-decidable": "already decided",
published: "already in the catalogue",
"open-row-exists": "another open row exists for this game",
"duplicate-in-request": "another selected row for the same game was used",
"no-op": "already in that state",
"changed-concurrently": "changed by someone else first",
};
/** Why POST /reopen answered 409. */
export const REOPEN_TEXT: Record<string, string> = {
"not-rejected": "This row is no longer rejected. Someone else has changed it.",
published: "This game is already in the catalogue, so its rejection cannot be reopened.",
"open-row-exists":
"Another row for this game is still open (pending, deferred or approved) or committed. Decide that row instead.",
};
export const ACTION_LABEL: Record<DecideAction, string> = {
approve: "Approve",
reject: "Reject",
defer: "Defer",
requeue: "Back to pending",
};
export const ACTION_PAST: Record<DecideAction, string> = {
approve: "Approved",
reject: "Rejected",
defer: "Deferred",
requeue: "Moved back to pending",
};
/** What a decision does beyond the queue, stated before it is made. */
export const ACTION_CONSEQUENCE: Record<DecideAction, string> = {
approve:
"Commits the store links to scripts/temp_info.jsonl on main. The pipeline adds the games on its next run, and reconcile marks the rows committed once they appear in data/.",
reject:
"Records a rejection for each game, so discovery does not offer it again. You can reopen a rejected row later, one at a time.",
defer: "Keeps the rows open for later. The games stay blocked from being queued again.",
requeue: "Moves the rows back to pending.",
};
export const SORTS = [
{ value: "newest", label: "Newest first" },
{ value: "oldest", label: "Oldest first" },
{ value: "players", label: "Most players" },
{ value: "reviews", label: "Best reviews" },
{ value: "name", label: "Name" },
{ value: "decided", label: "Recently decided" },
] as const;
+61
View File
@@ -0,0 +1,61 @@
import { toast } from "svelte-sonner";
import { SessionExpiredError, errorMessage } from "./api";
import { commitUrl, shortSha } from "./format";
let reloading = false;
const RELOAD_KEY = "f2p-admin:session-reload";
const RELOAD_WINDOW_MS = 30_000;
export function isAbort(err: unknown): boolean {
return err instanceof DOMException && err.name === "AbortError";
}
function reloadedRecently(): boolean {
try {
return Date.now() - Number(sessionStorage.getItem(RELOAD_KEY) ?? 0) < RELOAD_WINDOW_MS;
} catch {
return false;
}
}
/**
* The one place a failed request is reported.
*
* An expired Access session reloads the page: only a full navigation lets
* Access redirect the document to its login flow. A fetch cannot follow it.
* Once only: if the API still refuses straight after that reload, reloading
* again would loop forever, so the reviewer is told instead.
*/
export function reportError(err: unknown, context?: string): void {
if (isAbort(err)) return;
if (err instanceof SessionExpiredError) {
if (reloading) return;
reloading = true;
if (reloadedRecently()) {
toast.error("The admin API still refuses this session", {
description: "Reloading did not sign you in again. Open /admin in a new tab, or check the Access policy.",
duration: Number.POSITIVE_INFINITY,
});
return;
}
try {
sessionStorage.setItem(RELOAD_KEY, String(Date.now()));
} catch {
/* storage blocked: the reload still happens, just without the loop guard */
}
toast.error("Your Cloudflare Access session has expired. Reloading to sign in again…");
setTimeout(() => location.reload(), 1200);
return;
}
toast.error(context ?? "Request failed", { description: errorMessage(err) });
}
/** The outcome of an override commit, with a link to the commit when one was made. */
export function commitToast(title: string, sha: string | null | undefined, applied = true): void {
toast.success(title, {
description: sha
? `Commit ${shortSha(sha)}.${applied ? " data/ changes on the next pipeline run." : ""}`
: "Nothing to commit: the override files already said this.",
action: sha ? { label: "View commit", onClick: () => window.open(commitUrl(sha), "_blank", "noopener") } : undefined,
});
}
+115
View File
@@ -0,0 +1,115 @@
/**
* A history router for five pages. The admin has no nested routes, no route
* parameters and no data loading to coordinate, so a framework router would be
* all weight and no function.
*
* Page state that should survive a reload or a shared link (the queue's tab,
* search, sort and page; the edit page's appid) lives in the query string and
* is read and written through `query` and `setQuery`.
*/
import { isAdminRoute, type AdminRoute } from "../../../shared/admin-routes";
type Guard = () => string | null;
class Router {
path = $state<string>(typeof location === "undefined" ? "/admin" : location.pathname);
search = $state<string>(typeof location === "undefined" ? "" : location.search);
/** Returns a confirmation message when leaving would lose work, else null. */
#guards = new Set<Guard>();
get route(): AdminRoute | null {
return isAdminRoute(this.path) ? this.path : null;
}
get query(): URLSearchParams {
return new URLSearchParams(this.search);
}
/** Register a leave-guard; returns its removal. */
guard(fn: Guard): () => void {
this.#guards.add(fn);
return () => this.#guards.delete(fn);
}
#blocked(): boolean {
for (const guard of this.#guards) {
const message = guard();
if (message && !confirm(message)) return true;
}
return false;
}
/**
* Ask the leave-guards before discarding work that a path change would not
* catch, such as loading a different game on the same page. True means go on.
*/
confirmLeave(): boolean {
return !this.#blocked();
}
navigate(to: string, options: { replace?: boolean; force?: boolean } = {}): void {
const url = new URL(to, location.origin);
if (url.pathname === this.path && url.search === this.search) return;
if (!options.force && url.pathname !== this.path && this.#blocked()) return;
history[options.replace ? "replaceState" : "pushState"](null, "", url.pathname + url.search);
this.sync();
}
/** Merge into the query string without adding a history entry. */
setQuery(updates: Record<string, string | number | null | undefined>): void {
const params = this.query;
for (const [key, value] of Object.entries(updates)) {
if (value === null || value === undefined || value === "") params.delete(key);
else params.set(key, String(value));
}
const search = params.toString();
this.navigate(this.path + (search ? `?${search}` : ""), { replace: true });
}
sync(): void {
this.path = location.pathname;
this.search = location.search;
}
/**
* Client-side navigation for plain clicks on same-origin /admin links, and
* Back/Forward. Modified clicks (new tab, download) are left to the browser.
*/
install(): () => void {
// "/admin/" is the Vite dev server's base; production redirects it.
if (location.pathname.length > 1 && location.pathname.endsWith("/")) {
history.replaceState(null, "", location.pathname.replace(/\/+$/, "") + location.search);
this.sync();
}
const onClick = (e: MouseEvent) => {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const anchor = (e.target as Element | null)?.closest?.("a");
if (!anchor || anchor.target || anchor.hasAttribute("download")) return;
const href = anchor.getAttribute("href");
if (!href || !href.startsWith("/admin")) return;
e.preventDefault();
this.navigate(href);
};
const onPop = () => this.sync();
const onBeforeUnload = (e: BeforeUnloadEvent) => {
for (const guard of this.#guards) {
if (guard()) {
e.preventDefault();
return;
}
}
};
document.addEventListener("click", onClick);
window.addEventListener("popstate", onPop);
window.addEventListener("beforeunload", onBeforeUnload);
return () => {
document.removeEventListener("click", onClick);
window.removeEventListener("popstate", onPop);
window.removeEventListener("beforeunload", onBeforeUnload);
};
}
}
export const router = new Router();
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { pageSelection, selectableIds, toggleAll } from "./selection";
const rows = [
{ id: "p1", status: "pending", published: false },
{ id: "p2", status: "pending", published: false },
{ id: "f1", status: "failed", published: false },
{ id: "pub", status: "pending", published: true },
{ id: "a1", status: "approved", published: false },
{ id: "c1", status: "committed", published: true },
{ id: "r1", status: "rejected", published: false },
];
describe("selection", () => {
it("never offers a decided or published row", () => {
expect(selectableIds(rows)).toEqual(["p1", "p2", "f1"]);
});
it("select-all selects exactly the selectable rows", () => {
const next = toggleAll(rows, new Set());
expect([...next].sort()).toEqual(["f1", "p1", "p2"]);
expect(next.has("pub")).toBe(false);
expect(next.has("c1")).toBe(false);
});
it("counts a page as fully selected without its locked rows", () => {
expect(pageSelection(rows, new Set(["p1", "p2", "f1"]))).toBe("all");
expect(pageSelection(rows, new Set(["p1"]))).toBe("some");
expect(pageSelection(rows, new Set())).toBe("none");
});
it("select-all on a full page clears only this page's rows", () => {
const next = toggleAll(rows, new Set(["p1", "p2", "f1", "elsewhere"]));
expect([...next]).toEqual(["elsewhere"]);
});
it("a page with nothing selectable reads as none, and select-all adds nothing", () => {
const locked = rows.filter((r) => ["a1", "c1", "r1", "pub"].includes(r.id));
expect(pageSelection(locked, new Set())).toBe("none");
expect(toggleAll(locked, new Set()).size).toBe(0);
});
});
+41
View File
@@ -0,0 +1,41 @@
/**
* Which rows a reviewer may select, and what "select all" means.
*
* Pure functions over plain data, kept out of the components so the rule that
* matters most on the queue screen - a locked row can never be selected, even
* by "select all" - has a test of its own (selection.test.ts).
*/
import { isSelectable } from "../../../shared/queue-rules";
interface Row {
id: string;
status: string;
published?: boolean | number | null;
}
/** Ids on this page that may be selected. */
export function selectableIds(rows: Row[]): string[] {
return rows.filter((r) => isSelectable(r)).map((r) => r.id);
}
export type PageSelection = "none" | "some" | "all";
/** The select-all checkbox's state for this page. Locked rows do not count. */
export function pageSelection(rows: Row[], selected: ReadonlySet<string>): PageSelection {
const ids = selectableIds(rows);
if (!ids.length) return "none";
const chosen = ids.filter((id) => selected.has(id)).length;
return chosen === 0 ? "none" : chosen === ids.length ? "all" : "some";
}
/**
* The selection after toggling select-all: every selectable row on the page,
* or none of them. Ids from other pages are kept; locked ids are never added.
*/
export function toggleAll(rows: Row[], selected: ReadonlySet<string>): Set<string> {
const ids = selectableIds(rows);
const next = new Set(selected);
if (pageSelection(rows, selected) === "all") ids.forEach((id) => next.delete(id));
else ids.forEach((id) => next.add(id));
return next;
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { shouldIgnore } from "./shortcuts";
/** A stand-in for event.target: closest() answers for one matched element. */
function target(tagName: string | null, type?: string) {
const el = tagName ? { tagName, getAttribute: (n: string) => (n === "type" ? (type ?? null) : null) } : null;
return { closest: () => el } as unknown as EventTarget;
}
function key(overrides: Partial<Pick<KeyboardEvent, "isComposing" | "keyCode" | "ctrlKey" | "metaKey" | "altKey" | "target">> = {}) {
return { isComposing: false, keyCode: 65, ctrlKey: false, metaKey: false, altKey: false, target: target(null), ...overrides };
}
describe("shouldIgnore", () => {
it("takes a plain key on the page", () => {
expect(shouldIgnore(key())).toBe(false);
});
it("leaves typing in a text field alone", () => {
expect(shouldIgnore(key({ target: target("INPUT", "text") }))).toBe(true);
expect(shouldIgnore(key({ target: target("INPUT", "search") }))).toBe(true);
expect(shouldIgnore(key({ target: target("INPUT") }))).toBe(true);
expect(shouldIgnore(key({ target: target("TEXTAREA") }))).toBe(true);
expect(shouldIgnore(key({ target: target("SELECT") }))).toBe(true);
});
it("does not treat a focused checkbox as typing", () => {
// Ticking a row leaves focus on its checkbox; "a" must still approve.
expect(shouldIgnore(key({ target: target("INPUT", "checkbox") }))).toBe(false);
expect(shouldIgnore(key({ target: target("INPUT", "radio") }))).toBe(false);
});
it("never interrupts IME composition", () => {
// Vietnamese Telex/VNI input composes with plain letter keys.
expect(shouldIgnore(key({ isComposing: true }))).toBe(true);
expect(shouldIgnore(key({ keyCode: 229 }))).toBe(true);
});
it("leaves modified keys to the browser", () => {
expect(shouldIgnore(key({ ctrlKey: true }))).toBe(true);
expect(shouldIgnore(key({ metaKey: true }))).toBe(true);
expect(shouldIgnore(key({ altKey: true }))).toBe(true);
});
});
+49
View File
@@ -0,0 +1,49 @@
/**
* Keyboard shortcuts for the queue, and the one rule every shortcut obeys:
* a keystroke that belongs to something else is never taken.
*/
export interface Shortcut {
key: string;
label: string;
}
export const QUEUE_SHORTCUTS: Shortcut[] = [
{ key: "j", label: "Next row" },
{ key: "k", label: "Previous row" },
{ key: "x", label: "Select or deselect the row" },
{ key: "a", label: "Approve the selection" },
{ key: "r", label: "Reject the selection" },
{ key: "d", label: "Defer, or send back to pending" },
{ key: "e", label: "Open the row's details" },
{ key: "/", label: "Search" },
{ key: "Escape", label: "Clear the selection" },
{ key: "?", label: "Show these shortcuts" },
];
/** Inputs that take no typing, so a letter key pressed on one is a shortcut. */
const KEYLESS_INPUTS = new Set(["checkbox", "radio", "button", "submit", "reset", "range", "color", "file", "image"]);
/**
* True when the key must be left alone: typing in a field, IME composition
* (Vietnamese Telex/VNI input), a modified key, or an open dialog.
*
* A focused checkbox is NOT a field. Ticking a row leaves focus on its
* checkbox, and treating that as typing made "a" do nothing straight after
* selecting - the one moment it is wanted.
*/
export function shouldIgnore(e: Pick<KeyboardEvent, "isComposing" | "keyCode" | "ctrlKey" | "metaKey" | "altKey" | "target">): boolean {
if (e.isComposing || e.keyCode === 229) return true;
if (e.ctrlKey || e.metaKey || e.altKey) return true;
const target = e.target as Element | null;
const field =
target && typeof target.closest === "function"
? target.closest("input, textarea, select, [contenteditable=''], [contenteditable='true']")
: null;
if (field) {
if (field.tagName !== "INPUT") return true;
if (!KEYLESS_INPUTS.has((field.getAttribute("type") ?? "text").toLowerCase())) return true;
}
if (typeof document !== "undefined" && document.querySelector("dialog[open]")) return true;
return false;
}
+5
View File
@@ -0,0 +1,5 @@
import { mount } from "svelte";
import "./admin.css";
import App from "./App.svelte";
mount(App, { target: document.getElementById("app")! });
+184
View File
@@ -0,0 +1,184 @@
<!-- audit_log, newest first. Entries older than the retention window are pruned
daily (worker/lib/prune.ts). -->
<script lang="ts">
import { untrack } from "svelte";
import ScrollText from "@lucide/svelte/icons/scroll-text";
import Pager from "../components/Pager.svelte";
import EmptyState from "../components/EmptyState.svelte";
import Button from "../../../src/lib/ui/Button.svelte";
import { api, errorMessage, SessionExpiredError } from "../lib/api";
import { isAbort, reportError } from "../lib/notify";
import { router } from "../lib/router.svelte";
import { exactTime, prettyJson, relativeTime } from "../lib/format";
import type { AuditEntry, Paged } from "../../../shared/admin-api";
/** Every action the Worker records. A filter, not a validator: the server checks the shape. */
const ACTIONS = [
"approve",
"approve.failed",
"approve.desynced",
"reject",
"defer",
"requeue",
"reopen",
"reconcile.manual",
"reconcile.approved",
"override",
"override.failed",
"override.delete",
"override.delete.failed",
"ingest.candidates",
"admin.prune",
"ping",
];
const SIZES = [25, 50, 100, 200];
const query = $derived(router.query);
const action = $derived(query.get("action") ?? "");
const actor = $derived(query.get("actor") ?? "");
const size = $derived(SIZES.includes(Number(query.get("size"))) ? Number(query.get("size")) : 50);
const page = $derived(Math.max(1, Math.floor(Number(query.get("page"))) || 1));
let data = $state.raw<Paged<AuditEntry> | null>(null);
let loading = $state(true);
let loadError = $state<string | null>(null);
let refresh = $state(0);
let actorText = $state(untrack(() => actor));
$effect(() => {
const params = new URLSearchParams({ limit: String(size), offset: String((page - 1) * size) });
if (action) params.set("action", action);
if (actor) params.set("actor", actor);
void refresh;
const controller = new AbortController();
untrack(() => {
loading = true;
loadError = null;
});
api<Paged<AuditEntry>>(`/api/admin/audit?${params}`, { signal: controller.signal })
.then((res) => {
data = res;
loading = false;
})
.catch((err) => {
if (isAbort(err)) return;
loading = false;
loadError = errorMessage(err);
if (err instanceof SessionExpiredError) reportError(err);
});
return () => controller.abort();
});
/** A one-line gist of the detail JSON, so most rows need no expanding. */
function gist(detail: string): string {
try {
const d = JSON.parse(detail) as Record<string, unknown>;
return Object.entries(d)
.filter(([, v]) => v !== null && v !== "" && !(Array.isArray(v) && !v.length))
.slice(0, 5)
.map(([k, v]) => `${k}: ${Array.isArray(v) ? `${v.length} item${v.length === 1 ? "" : "s"}` : typeof v === "object" ? "{…}" : String(v)}`)
.join(" · ");
} catch {
return detail;
}
}
</script>
<section class="space-y-4">
<div>
<h1 class="text-2xl font-semibold tracking-tight">Audit log</h1>
<p class="text-sm text-muted-foreground">Who did what, newest first.</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<select
aria-label="Filter by action"
class="h-9 rounded-md border border-input bg-background px-2 text-sm"
value={action}
onchange={(e) => router.setQuery({ action: e.currentTarget.value || null, page: null })}
>
<option value="">Every action</option>
{#each ACTIONS as a (a)}<option value={a}>{a}</option>{/each}
</select>
<form
class="flex gap-2"
onsubmit={(e) => {
e.preventDefault();
router.setQuery({ actor: actorText.trim() || null, page: null });
}}
>
<input
bind:value={actorText}
type="search"
placeholder="Actor, exactly (you@example.com)"
aria-label="Filter by actor"
maxlength="200"
class="h-9 w-64 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground"
/>
<Button type="submit" variant="outline" size="sm" class="h-9">Filter</Button>
</form>
<Button variant="ghost" size="sm" onclick={() => refresh++} disabled={loading}>Refresh</Button>
</div>
{#if loadError}
<p class="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm">{loadError}</p>
{:else if data && !data.items.length}
<div class="rounded-lg border border-border">
<EmptyState icon={ScrollText} title={action || actor ? "No entries match these filters" : "Nothing recorded yet"} />
</div>
{:else if data}
<div class="overflow-x-auto rounded-lg border border-border" class:opacity-60={loading}>
<table class="w-full text-sm">
<thead class="bg-muted/50 text-left text-xs text-muted-foreground">
<tr>
<th class="px-3 py-2.5">When</th>
<th class="px-3 py-2.5">Actor</th>
<th class="px-3 py-2.5">Action</th>
<th class="px-3 py-2.5">Target</th>
<th class="px-3 py-2.5">Detail</th>
</tr>
</thead>
<tbody>
{#each data.items as entry (entry.id)}
<tr class="border-t border-border align-top">
<td class="px-3 py-2 whitespace-nowrap" title={exactTime(entry.created_at)}>{relativeTime(entry.created_at)}</td>
<td class="max-w-48 truncate px-3 py-2 text-xs" title={entry.actor}>
<button
type="button"
class="hover:text-primary hover:underline"
title="Show only {entry.actor}"
onclick={() => {
actorText = entry.actor;
router.setQuery({ actor: entry.actor, page: null });
}}>{entry.actor}</button
>
</td>
<td class="px-3 py-2 font-mono text-xs whitespace-nowrap">{entry.action}</td>
<td class="max-w-40 truncate px-3 py-2 font-mono text-xs" title={entry.target ?? ""}>{entry.target ?? "—"}</td>
<td class="min-w-64 px-3 py-2 text-xs">
<details>
<summary class="cursor-pointer text-muted-foreground select-none hover:text-foreground">{gist(entry.detail_json)}</summary>
<pre class="mt-2 max-h-72 overflow-auto rounded-md bg-muted/50 p-2 font-mono text-[11px] leading-4 whitespace-pre-wrap break-words">{prettyJson(
entry.detail_json,
)}</pre>
</details>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<Pager
offset={data.offset}
limit={data.limit}
total={data.total}
count={data.items.length}
disabled={loading}
sizes={SIZES}
onpage={(o) => router.setQuery({ page: o / size + 1 === 1 ? null : o / size + 1 })}
onsize={(n) => router.setQuery({ size: n === 50 ? null : n, page: null })}
/>
{:else}
<div class="h-40 animate-pulse rounded-lg bg-muted" aria-busy="true"></div>
{/if}
</section>
+389
View File
@@ -0,0 +1,389 @@
<!--
One change to up to MAX_EDIT games at once, picked by genre.
The selection is kept across pages and genres (a Map, not the page's rows),
so a retag can gather games from two vague buckets. The review dialog loads
each selected game before anything is committed and shows what the change
does to each one.
-->
<script lang="ts">
import { untrack } from "svelte";
import { SvelteMap } from "svelte/reactivity";
import X from "@lucide/svelte/icons/x";
import LoaderCircle from "@lucide/svelte/icons/loader-circle";
import Layers from "@lucide/svelte/icons/layers";
import Button from "../../../src/lib/ui/Button.svelte";
import Dialog from "../components/Dialog.svelte";
import Thumb from "../components/Thumb.svelte";
import EmptyState from "../components/EmptyState.svelte";
import FieldEditor from "../components/FieldEditor.svelte";
import Pager from "../components/Pager.svelte";
import { api, errorMessage, SessionExpiredError } from "../lib/api";
import { commitToast, isAbort, reportError } from "../lib/notify";
import { router } from "../lib/router.svelte";
import { FIELDS, FIELD_LABEL, toWire, validate } from "../lib/fields";
import { plural, showValue } from "../lib/format";
import { MAX_EDIT } from "../../../shared/queue-rules";
import type { ByGenreResponse, EditResponse, GameResponse, ManualField } from "../../../shared/admin-api";
type Props = {
genres: { genre: string; count: number }[];
busy: boolean;
ongenres: () => void;
};
let { genres, busy = $bindable(), ongenres }: Props = $props();
const PAGE = 60;
const genre = $derived(router.query.get("genre") ?? "");
const page = $derived(Math.max(1, Math.floor(Number(router.query.get("page"))) || 1));
const offset = $derived((page - 1) * PAGE);
let list = $state.raw<ByGenreResponse | null>(null);
let loadError = $state<string | null>(null);
let loading = $state(false);
let reload = $state(0);
const selected = new SvelteMap<string, string>();
const full = $derived(selected.size >= MAX_EDIT);
let field = $state<ManualField>("genre");
let op = $state<"set" | "retire">("set");
let value = $state("");
let reason = $state("");
const spec = $derived(FIELDS.find((f) => f.key === field)!);
const valueError = $derived(op === "set" ? validate(field, value) : null);
$effect(() => {
const g = genre;
const o = offset;
void reload;
untrack(() => {
loadError = null;
if (!g) list = null;
});
if (!g) return;
const controller = new AbortController();
untrack(() => (loading = true));
api<ByGenreResponse>(`/api/admin/by-genre?${new URLSearchParams({ genre: g, limit: String(PAGE), offset: String(o) })}`, {
signal: controller.signal,
})
.then((res) => {
list = res;
loading = false;
})
.catch((err) => {
if (isAbort(err)) return;
loading = false;
loadError = errorMessage(err);
if (err instanceof SessionExpiredError) reportError(err);
});
return () => controller.abort();
});
$effect(() => {
// A new field starts from a sensible value rather than the last field's.
const f = field;
untrack(() => {
value = f === "is_kernel_ac" ? "null" : f === "safe" ? "?" : f === "type_game" ? "online" : "";
});
});
$effect(() => router.guard(() => (selected.size ? "Your bulk selection will be lost. Leave anyway?" : null)));
function toggle(appid: string, name: string) {
if (busy) return;
if (selected.has(appid)) selected.delete(appid);
else if (!full) selected.set(appid, name);
}
// ── review ──
let reviewOpen = $state(false);
let reviewGames = $state.raw<(GameResponse | { appid: string; error: string })[]>([]);
let reviewLoading = $state(false);
async function review() {
if (!selected.size || valueError || busy) return;
reviewOpen = true;
reviewLoading = true;
reviewGames = [];
const appids = [...selected.keys()];
reviewGames = await Promise.all(
appids.map((a) =>
api<GameResponse>(`/api/admin/game?appid=${a}`).catch((err: unknown) => {
if (err instanceof SessionExpiredError) reportError(err);
return { appid: a, error: errorMessage(err) };
}),
),
);
reviewLoading = false;
}
function after(g: GameResponse): { text: string; tone: "change" | "same" | "retire" } {
const active = g.override?.fields?.[field];
if (op === "retire") {
return active ? { text: `restores ${showValue(active.was)} once`, tone: "retire" } : { text: "no override on this field: unchanged", tone: "same" };
}
const next = toWire(field, value);
const current = active ? active.value : g.fields[field];
return JSON.stringify(current ?? null) === JSON.stringify(next)
? { text: `${showValue(next)} (already)`, tone: "same" }
: { text: showValue(next), tone: "change" };
}
async function commit() {
if (busy || !selected.size) return;
const appids = [...selected.keys()];
busy = true;
try {
const out = await api<EditResponse>("/api/admin/edit", {
method: "POST",
body: {
appids,
...(op === "set" ? { set: { [field]: toWire(field, value) } } : { retire: [field] }),
reason: reason.trim(),
},
});
reviewOpen = false;
commitToast(
op === "set"
? `${FIELD_LABEL[field]} set on ${plural(appids.length, "game")}`
: `${FIELD_LABEL[field]} override retired on ${plural(appids.length, "game")}`,
out.commit,
);
selected.clear();
reason = "";
reload++;
ongenres();
} catch (err) {
reportError(err, "The bulk change failed");
} finally {
busy = false;
}
}
</script>
<div class="grid gap-5 lg:grid-cols-[1fr_20rem]">
<div class="min-w-0 space-y-4">
<label class="flex max-w-md flex-col gap-1.5 text-sm">
<span class="font-medium">Games tagged</span>
<select
class="h-9 rounded-md border border-input bg-background px-2 text-sm"
value={genre}
disabled={busy || !genres.length}
onchange={(e) => router.setQuery({ genre: e.currentTarget.value || null, page: null })}
>
<option value="">{genres.length ? "Choose a genre" : "Loading genres…"}</option>
{#each genres as g (g.genre)}
<option value={g.genre}>{g.genre} ({g.count})</option>
{/each}
</select>
</label>
{#if !genre}
<div class="rounded-lg border border-border">
<EmptyState icon={Layers} title="Change several games at once">
Choose a genre to list its games, select up to {MAX_EDIT}, then set or retire one field on all of them in a single
commit.
</EmptyState>
</div>
{:else if loadError}
<p class="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm">{loadError}</p>
{:else if !list}
<div class="flex items-center gap-2 py-10 text-sm text-muted-foreground" aria-busy="true">
<LoaderCircle class="size-4 animate-spin" /> Loading games…
</div>
{:else}
<p class="text-sm text-muted-foreground">
{plural(list.total, "game")} tagged “{list.genre}”. {full ? `Selection full (${MAX_EDIT}).` : ""}
</p>
<ul class="grid gap-2 sm:grid-cols-2 xl:grid-cols-3" class:opacity-60={loading}>
{#each list.items as item (item.appid)}
{@const on = selected.has(item.appid)}
{@const blocked = !on && full}
<li>
<label
class="flex h-full cursor-pointer items-center gap-3 rounded-lg border p-2 transition-colors
{on ? 'border-primary/60 bg-primary/5' : 'border-border hover:bg-muted/40'}
{blocked ? 'cursor-not-allowed opacity-50' : ''}"
title={blocked ? `At most ${MAX_EDIT} games per change` : undefined}
>
<input
type="checkbox"
class="size-4 shrink-0 accent-primary"
checked={on}
disabled={blocked || busy}
onchange={(e) => {
toggle(item.appid, item.name);
// A refused toggle (the cap, or a click that landed before the
// disabled state rendered) must not leave the box ticked.
e.currentTarget.checked = selected.has(item.appid);
}}
/>
<Thumb src={item.header_image} class="h-9 w-[77px] shrink-0" />
<span class="min-w-0">
<span class="block truncate text-sm font-medium">{item.name || "(no name)"}</span>
<span class="block truncate text-xs text-muted-foreground">
<span class="font-mono">{item.appid}</span>{item.release_date ? ` · ${item.release_date}` : ""}
</span>
</span>
</label>
</li>
{/each}
</ul>
<Pager
offset={list.offset}
limit={PAGE}
total={list.total}
count={list.items.length}
disabled={loading || busy}
onpage={(o) => router.setQuery({ page: o / PAGE + 1 === 1 ? null : o / PAGE + 1 })}
/>
{/if}
</div>
<aside class="h-fit space-y-4 rounded-lg border border-border bg-card p-4 lg:sticky lg:top-20">
<div>
<div class="flex items-center justify-between">
<h3 class="text-sm font-semibold">Selected</h3>
<span class="tnum text-xs text-muted-foreground">{selected.size} / {MAX_EDIT}</span>
</div>
{#if selected.size}
<ul class="mt-2 flex flex-wrap gap-1.5">
{#each [...selected] as [appid, name] (appid)}
<li class="flex max-w-full items-center gap-1 rounded-md bg-muted py-0.5 pr-1 pl-2 text-xs">
<span class="truncate" title={appid}>{name || appid}</span>
<button
type="button"
class="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
aria-label="Remove {name || appid}"
disabled={busy}
onclick={() => selected.delete(appid)}
>
<X class="size-3" />
</button>
</li>
{/each}
</ul>
<button type="button" class="mt-2 text-xs text-muted-foreground hover:text-foreground hover:underline" disabled={busy} onclick={() => selected.clear()}>
Clear selection
</button>
{:else}
<p class="mt-1 text-xs text-muted-foreground">Nothing selected. Tick games in the list.</p>
{/if}
</div>
<label class="block space-y-1.5 text-sm">
<span class="font-medium">Field</span>
<select bind:value={field} disabled={busy} class="h-9 w-full rounded-md border border-input bg-background px-2 text-sm">
{#each FIELDS as f (f.key)}
<option value={f.key}>{f.label}</option>
{/each}
</select>
</label>
<fieldset class="space-y-1.5 text-sm">
<legend class="mb-1.5 font-medium">Change</legend>
<label class="flex items-center gap-2"><input type="radio" class="accent-primary" bind:group={op} value="set" disabled={busy} /> Set a value</label>
<label class="flex items-center gap-2"><input type="radio" class="accent-primary" bind:group={op} value="retire" disabled={busy} /> Retire the override</label>
</fieldset>
{#if op === "set"}
<div class="space-y-1.5 text-sm">
<label for="bulk-value" class="font-medium">New {FIELD_LABEL[field].toLowerCase()}</label>
<FieldEditor {spec} id="bulk-value" bind:value {genres} disabled={busy} invalid={!!valueError && value !== ""} />
{#if valueError && value !== ""}<p class="text-xs text-destructive">{valueError}</p>{/if}
</div>
{:else}
<p class="text-xs text-muted-foreground">
Games with an active {FIELD_LABEL[field].toLowerCase()} override get their earlier value back on the next pipeline
run. Games without one are left alone.
</p>
{/if}
<label class="block space-y-1.5 text-sm">
<span class="font-medium">Reason <span class="font-normal text-muted-foreground">(optional)</span></span>
<input
bind:value={reason}
type="text"
maxlength="300"
disabled={busy}
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
placeholder="Kept in the commit and the files"
/>
</label>
<Button class="w-full" disabled={busy || !selected.size || !!valueError} onclick={review}>
Review {plural(selected.size, "game")}
</Button>
</aside>
</div>
<Dialog
bind:open={reviewOpen}
title={op === "set"
? `Set ${FIELD_LABEL[field].toLowerCase()} on ${plural(selected.size, "game")}?`
: `Retire the ${FIELD_LABEL[field].toLowerCase()} override on ${plural(selected.size, "game")}?`}
description="One commit, one override file per game. data/ is untouched until the pipeline runs."
size="lg"
dismissable={!busy}
>
{#if reviewLoading}
<div class="flex items-center gap-2 py-8 text-sm text-muted-foreground" aria-busy="true">
<LoaderCircle class="size-4 animate-spin" /> Loading the selected games…
</div>
{:else}
<div class="overflow-x-auto rounded-md border border-border">
<table class="w-full text-sm">
<thead class="bg-muted/50 text-left text-xs text-muted-foreground">
<tr>
<th class="px-3 py-2">Game</th>
<th class="px-3 py-2">Catalogue now</th>
<th class="px-3 py-2">Override now</th>
<th class="px-3 py-2">After saving</th>
</tr>
</thead>
<tbody>
{#each reviewGames as g (g.appid)}
<tr class="border-t border-border align-top">
{#if "error" in g}
<td class="px-3 py-2 font-mono">{g.appid}</td>
<td colspan="3" class="px-3 py-2 text-destructive">{g.error}</td>
{:else}
{@const active = g.override?.fields?.[field]}
{@const outcome = after(g)}
<td class="px-3 py-2">
<span class="block max-w-52 truncate font-medium">{g.name || g.appid}</span>
<span class="font-mono text-xs text-muted-foreground">{g.appid}</span>
</td>
<td class="px-3 py-2 break-words">{showValue(g.fields[field])}</td>
<td class="px-3 py-2 break-words text-muted-foreground">
{active ? `${showValue(active.value)} (was ${showValue(active.was)})` : "none"}
</td>
<td
class="px-3 py-2 break-words {outcome.tone === 'change'
? 'font-medium text-primary'
: outcome.tone === 'retire'
? 'text-warning'
: 'text-muted-foreground'}"
>
{outcome.text}
</td>
{/if}
</tr>
{/each}
</tbody>
</table>
</div>
<p class="mt-3 text-sm">
Reason: <span class={reason.trim() ? "" : "text-muted-foreground"}>{reason.trim() || "none given"}</span>
</p>
{/if}
{#snippet footer()}
<Button variant="ghost" onclick={() => (reviewOpen = false)} disabled={busy}>Back</Button>
<Button onclick={commit} disabled={busy || reviewLoading || reviewGames.some((g) => "error" in g)}>
{#if busy}<LoaderCircle class="size-4 animate-spin" />{/if}
Commit {plural(selected.size, "override")}
</Button>
{/snippet}
</Dialog>
+255
View File
@@ -0,0 +1,255 @@
<!--
One queue row in full: the candidate as it arrived, the durable decision for
its game, and every other row the queue holds for the same game.
Reopen lives here, and only here: it acts on one rejected row at a time, by
design, never on a selection.
-->
<script lang="ts">
import { untrack } from "svelte";
import { toast } from "svelte-sonner";
import ExternalLink from "@lucide/svelte/icons/external-link";
import RotateCcw from "@lucide/svelte/icons/rotate-ccw";
import SquarePen from "@lucide/svelte/icons/square-pen";
import Lock from "@lucide/svelte/icons/lock";
import CircleAlert from "@lucide/svelte/icons/circle-alert";
import LoaderCircle from "@lucide/svelte/icons/loader-circle";
import Button from "../../../src/lib/ui/Button.svelte";
import Badge from "../../../src/lib/ui/Badge.svelte";
import Dialog from "../components/Dialog.svelte";
import Thumb from "../components/Thumb.svelte";
import StatusBadge from "../components/StatusBadge.svelte";
import { api, errorMessage, SessionExpiredError } from "../lib/api";
import { isAbort, reportError } from "../lib/notify";
import { exactTime, prettyJson, relativeTime, steamUrl } from "../lib/format";
import { LOCK_HELP, REOPEN_TEXT } from "../lib/labels";
import { lockReason } from "../../../shared/queue-rules";
import type { Candidate, ReopenResponse } from "../../../shared/admin-api";
type Props = {
id: string | null;
onclose: () => void;
onchanged: () => void;
onselect: (id: string) => void;
};
let { id, onclose, onchanged, onselect }: Props = $props();
const SITE = "https://free-steam-games.win";
let open = $state(false);
let data = $state.raw<Candidate | null>(null);
let error = $state<string | null>(null);
let confirming = $state(false);
let reopening = $state(false);
let reopenError = $state<string | null>(null);
$effect(() => {
const current = id;
untrack(() => {
data = null;
error = null;
confirming = false;
reopenError = null;
open = current !== null;
});
if (!current) return;
const controller = new AbortController();
api<Candidate>(`/api/admin/candidate?id=${encodeURIComponent(current)}`, { signal: controller.signal })
.then((c) => (data = c))
.catch((err) => {
if (isAbort(err)) return;
if (err instanceof SessionExpiredError) reportError(err);
error = errorMessage(err);
});
return () => controller.abort();
});
const lock = $derived(data ? lockReason(data) : null);
async function reopen() {
if (!data || reopening) return;
reopening = true;
reopenError = null;
try {
const res = await api<ReopenResponse | { error: string; reason: string }>("/api/admin/reopen", {
method: "POST",
body: { id: data.id },
accept: [409],
});
if ("error" in res) {
reopenError = REOPEN_TEXT[res.reason] ?? res.error;
confirming = false;
} else {
toast.success("Row reopened", { description: `${data.name || data.appid} is pending again.` });
onchanged();
open = false;
}
} catch (err) {
reportError(err, "Reopen failed");
} finally {
reopening = false;
}
}
</script>
{#snippet fact(label: string, value: string | null | undefined, title?: string)}
<div class="min-w-0">
<dt class="text-xs text-muted-foreground">{label}</dt>
<dd class="truncate text-sm" {title}>{value || "—"}</dd>
</div>
{/snippet}
<Dialog bind:open title={data?.name || (error ? "Row not loaded" : "Loading…")} size="lg" dismissable={!reopening} {onclose}>
{#if error}
<div class="flex items-start gap-3 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm">
<CircleAlert class="mt-0.5 size-4 shrink-0 text-destructive" />
<p>{error}</p>
</div>
{:else if !data}
<div class="flex items-center gap-2 py-10 text-sm text-muted-foreground" aria-busy="true">
<LoaderCircle class="size-4 animate-spin" /> Loading the row…
</div>
{:else}
<div class="space-y-5">
<div class="flex flex-col gap-4 sm:flex-row">
<Thumb src={data.header_image} lazy={false} class="aspect-[460/215] w-full shrink-0 rounded-md sm:w-56" />
<div class="min-w-0 space-y-2">
<div class="flex flex-wrap items-center gap-2">
<StatusBadge status={data.status} />
{#if data.published}<Badge variant="success">in the catalogue</Badge>{/if}
<span class="font-mono text-xs text-muted-foreground">appid {data.appid}</span>
</div>
<div class="flex flex-wrap gap-x-4 gap-y-1 text-sm">
<a class="inline-flex items-center gap-1 text-primary hover:underline" href={steamUrl(data.appid)} target="_blank" rel="noopener noreferrer">
Steam store <ExternalLink class="size-3.5" />
</a>
{#if data.published}
<a class="inline-flex items-center gap-1 text-primary hover:underline" href="{SITE}/games/{data.appid}" target="_blank" rel="noopener noreferrer">
Public page <ExternalLink class="size-3.5" />
</a>
{/if}
</div>
{#if lock}
<p class="flex items-start gap-2 text-sm text-muted-foreground">
<Lock class="mt-0.5 size-3.5 shrink-0" />
{LOCK_HELP[lock]}
</p>
{/if}
</div>
</div>
<dl class="grid grid-cols-2 gap-x-4 gap-y-3 sm:grid-cols-3">
{@render fact("Source", data.source)}
{@render fact("Type", data.app_type)}
{@render fact("Free to play", data.is_free ? "yes" : "no")}
{@render fact("Store health", data.health_status)}
{@render fact("First seen", relativeTime(data.first_seen_at), exactTime(data.first_seen_at))}
{@render fact("Last seen", relativeTime(data.last_seen_at), exactTime(data.last_seen_at))}
{@render fact("Times seen", String(data.seen_count))}
{@render fact("Decided by", data.decided_by)}
{@render fact("Decided", data.decided_at ? relativeTime(data.decided_at) : null, exactTime(data.decided_at))}
</dl>
{#if data.reject_reason}
<div class="rounded-md border border-border bg-muted/40 p-3 text-sm">
<p class="text-xs text-muted-foreground">{data.status === "rejected" ? "Rejection reason" : "Reason"}</p>
<p class="mt-0.5 break-words">{data.reject_reason}</p>
</div>
{/if}
<section class="space-y-2">
<h3 class="text-sm font-semibold">Decision for this game</h3>
{#if data.decision}
<div class="rounded-md border border-border p-3 text-sm">
<div class="flex flex-wrap items-center gap-2">
<StatusBadge status={data.decision.decision} />
<span class="text-muted-foreground" title={exactTime(data.decision.decided_at)}>
{relativeTime(data.decision.decided_at)}{data.decision.decided_by ? ` by ${data.decision.decided_by}` : ""}
</span>
</div>
{#if data.decision.reason}<p class="mt-1.5 break-words">{data.decision.reason}</p>{/if}
<p class="mt-1.5 text-xs text-muted-foreground">
{data.decision.decision === "approved"
? "Recorded when the game was seen in data/. It is what keeps every row for this game read-only."
: "Discovery will not offer this game again while this rejection stands."}
</p>
</div>
{:else}
<p class="text-sm text-muted-foreground">No durable decision is recorded for this game.</p>
{/if}
</section>
<section class="space-y-2">
<h3 class="text-sm font-semibold">Other rows for this game</h3>
{#if data.siblings.length}
<ul class="divide-y divide-border rounded-md border border-border text-sm">
{#each data.siblings as s (s.id)}
<li class="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-2">
<StatusBadge status={s.status} />
<button type="button" class="font-mono text-xs text-primary hover:underline" onclick={() => onselect(s.id)}>
{s.id}
</button>
<span class="text-xs text-muted-foreground" title={exactTime(s.first_seen_at)}>
seen {relativeTime(s.first_seen_at)}
</span>
{#if s.decided_at}
<span class="text-xs text-muted-foreground" title={exactTime(s.decided_at)}>
decided {relativeTime(s.decided_at)}{s.decided_by ? ` by ${s.decided_by}` : ""}
</span>
{/if}
{#if s.reject_reason}<span class="w-full truncate text-xs text-muted-foreground" title={s.reject_reason}>{s.reject_reason}</span>{/if}
</li>
{/each}
</ul>
{:else}
<p class="text-sm text-muted-foreground">None.</p>
{/if}
</section>
<details class="group rounded-md border border-border">
<summary class="cursor-pointer px-3 py-2 text-sm font-semibold select-none">Payload as submitted</summary>
<pre class="max-h-80 overflow-auto border-t border-border bg-muted/40 p-3 font-mono text-xs leading-5 whitespace-pre-wrap break-words">{prettyJson(
data.payload_json,
)}</pre>
</details>
</div>
{/if}
{#snippet footer()}
{#if reopenError}
<div class="flex w-full items-start gap-3 rounded-md border border-warning/40 bg-warning/10 p-3 text-sm" role="alert">
<CircleAlert class="mt-0.5 size-4 shrink-0 text-warning" />
<p>{reopenError}</p>
</div>
{/if}
{#if confirming}
<div class="w-full rounded-md border border-primary/40 bg-primary/5 p-3 text-sm" role="alert">
<p class="font-medium">Reopen this row?</p>
<p class="mt-1 text-muted-foreground">
It goes back to pending and the rejection recorded for the game is removed, so discovery can offer it again.
</p>
</div>
{/if}
{#if data?.status === "rejected"}
{#if confirming}
<Button variant="ghost" onclick={() => (confirming = false)} disabled={reopening}>Keep rejected</Button>
<Button onclick={reopen} disabled={reopening}>
{#if reopening}<LoaderCircle class="size-4 animate-spin" />{:else}<RotateCcw class="size-4" />{/if}
Reopen
</Button>
{:else}
<Button variant="outline" onclick={() => ((confirming = true), (reopenError = null))}>
<RotateCcw class="size-4" /> Reopen…
</Button>
{/if}
{/if}
{#if data?.published}
<Button variant="outline" href="/admin/edit?appid={data.appid}" onclick={() => (open = false)}>
<SquarePen class="size-4" /> Correct this game
</Button>
{/if}
<Button variant="ghost" onclick={() => (open = false)} disabled={reopening}>Close</Button>
{/snippet}
</Dialog>
+484
View File
@@ -0,0 +1,484 @@
<!--
Correct one published game by writing data/overrides/<appid>.json.
Nothing is committed until the diff dialog is confirmed, and the dialog says
what each change does: a set pins a value, a retire restores the value from
before the first edit once and then stops acting.
-->
<script lang="ts">
import { untrack } from "svelte";
import { SvelteSet } from "svelte/reactivity";
import Search from "@lucide/svelte/icons/search";
import ExternalLink from "@lucide/svelte/icons/external-link";
import Undo2 from "@lucide/svelte/icons/undo-2";
import Trash2 from "@lucide/svelte/icons/trash";
import LoaderCircle from "@lucide/svelte/icons/loader-circle";
import CircleAlert from "@lucide/svelte/icons/circle-alert";
import SquarePen from "@lucide/svelte/icons/square-pen";
import Info from "@lucide/svelte/icons/info";
import Button from "../../../src/lib/ui/Button.svelte";
import Badge from "../../../src/lib/ui/Badge.svelte";
import Dialog from "../components/Dialog.svelte";
import Thumb from "../components/Thumb.svelte";
import EmptyState from "../components/EmptyState.svelte";
import FieldEditor from "../components/FieldEditor.svelte";
import { api, errorMessage, SessionExpiredError } from "../lib/api";
import { commitToast, isAbort, reportError } from "../lib/notify";
import { router } from "../lib/router.svelte";
import { FIELDS, FIELD_LABEL, toForm, toWire, validate } from "../lib/fields";
import { exactTime, fileUrl, plural, relativeTime, showValue, steamUrl } from "../lib/format";
import type { EditResponse, GameResponse, ManualField, OverrideEntry } from "../../../shared/admin-api";
type Props = {
genres: { genre: string; count: number }[];
busy: boolean;
ongenres: () => void;
};
let { genres, busy = $bindable(), ongenres }: Props = $props();
const SITE = "https://free-steam-games.win";
const blank = () => Object.fromEntries(FIELDS.map((f) => [f.key, ""])) as Record<ManualField, string>;
const appid = $derived((router.query.get("appid") ?? "").trim());
let appidText = $state(untrack(() => appid));
let game = $state.raw<GameResponse | null>(null);
let loading = $state(false);
let loadError = $state<string | null>(null);
let reload = $state(0);
let initial = $state.raw<Record<ManualField, string>>(blank());
let form = $state<Record<ManualField, string>>(blank());
const retire = new SvelteSet<ManualField>();
let reason = $state("");
function activeOf(g: GameResponse, field: ManualField): OverrideEntry | undefined {
return g.override?.fields?.[field];
}
function retiredOf(g: GameResponse, field: ManualField): OverrideEntry | undefined {
return g.override?.retired?.[field];
}
$effect(() => {
const id = appid;
void reload;
untrack(() => {
appidText = id;
loadError = null;
});
if (!id) {
untrack(() => (game = null));
return;
}
if (!/^\d{1,10}$/.test(id)) {
untrack(() => {
game = null;
loadError = "An appid is 1 to 10 digits.";
});
return;
}
const controller = new AbortController();
untrack(() => (loading = true));
api<GameResponse>(`/api/admin/game?appid=${id}`, { signal: controller.signal })
.then((g) => {
// The form starts from what the catalogue WILL hold: the override's
// value where one is active (it may not have been applied yet),
// otherwise the catalogue's.
const next = blank();
for (const f of FIELDS) {
const active = activeOf(g, f.key);
next[f.key] = toForm(f.key, active ? active.value : g.fields[f.key]);
}
game = g;
initial = next;
form = { ...next };
retire.clear();
loading = false;
})
.catch((err) => {
if (isAbort(err)) return;
loading = false;
game = null;
loadError = errorMessage(err);
if (err instanceof SessionExpiredError) reportError(err);
});
return () => controller.abort();
});
const changes = $derived(
FIELDS.map((f) => f.key).filter((k) => !retire.has(k) && form[k].trim() !== initial[k].trim()),
);
const errors = $derived(
Object.fromEntries(changes.map((k) => [k, validate(k, form[k])]).filter(([, e]) => e)) as Partial<
Record<ManualField, string>
>,
);
const dirty = $derived(changes.length > 0 || retire.size > 0);
const invalid = $derived(Object.keys(errors).length > 0);
$effect(() => router.guard(() => (dirty ? "This game has unsaved changes. Discard them?" : null)));
function load(e: SubmitEvent) {
e.preventDefault();
const text = appidText.trim();
const parsed = /\/app\/(\d+)/.exec(text)?.[1] ?? text;
if (parsed === appid) {
reload++;
return;
}
if (!router.confirmLeave()) return;
router.setQuery({ appid: parsed || null });
}
function discard() {
form = { ...initial };
retire.clear();
}
// ── save ──
let reviewOpen = $state(false);
let deleteOpen = $state(false);
interface PlanRow {
field: ManualField;
kind: "set" | "retire";
catalogue: unknown;
active: OverrideEntry | undefined;
next: unknown;
}
const plan = $derived.by((): PlanRow[] => {
if (!game) return [];
const g = game;
return [
...changes.map((k) => ({ field: k, kind: "set" as const, catalogue: g.fields[k], active: activeOf(g, k), next: toWire(k, form[k]) })),
...[...retire].map((k) => ({ field: k, kind: "retire" as const, catalogue: g.fields[k], active: activeOf(g, k), next: activeOf(g, k)?.was })),
];
});
async function save() {
if (!game || busy || invalid || !dirty) return;
const set = Object.fromEntries(changes.map((k) => [k, toWire(k, form[k])]));
busy = true;
try {
const out = await api<EditResponse>("/api/admin/edit", {
method: "POST",
body: {
appids: [game.appid],
...(changes.length ? { set } : {}),
...(retire.size ? { retire: [...retire] } : {}),
reason: reason.trim(),
},
});
reviewOpen = false;
commitToast(`Override saved for ${game.name || game.appid}`, out.commit);
reason = "";
// Clear the form BEFORE reloading, so the leave-guard does not fire on
// work that has just been committed.
initial = { ...form };
retire.clear();
reload++;
ongenres();
} catch (err) {
reportError(err, "Saving the override failed");
} finally {
busy = false;
}
}
async function deleteFile() {
if (!game || busy) return;
busy = true;
try {
const out = await api<EditResponse>("/api/admin/edit", {
method: "POST",
body: { appids: [game.appid], delete: true, reason: reason.trim() },
});
deleteOpen = false;
commitToast("Override file deleted", out.commit, false);
reload++;
} catch (err) {
reportError(err, "Deleting the override file failed");
} finally {
busy = false;
}
}
const activeCount = $derived(Object.keys(game?.override?.fields ?? {}).length);
const retiredCount = $derived(Object.keys(game?.override?.retired ?? {}).length);
</script>
<div class="space-y-5">
<form class="flex max-w-xl gap-2" onsubmit={load}>
<div class="relative flex-1">
<Search class="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<input
bind:value={appidText}
type="text"
inputmode="numeric"
placeholder="Steam appid or store URL"
aria-label="Steam appid or store URL"
autocomplete="off"
disabled={busy}
class="h-9 w-full rounded-md border border-input bg-background pr-3 pl-8 text-sm placeholder:text-muted-foreground"
/>
</div>
<Button type="submit" variant="outline" disabled={busy || !appidText.trim()}>Load</Button>
</form>
{#if !appid}
<div class="rounded-lg border border-border">
<EmptyState icon={SquarePen} title="Correct a published game">
Load a game by its appid to change its genre, type, safety or anti-cheat details. The change is saved as an
override file, which the pipeline re-applies on every run.
</EmptyState>
</div>
{:else if loadError}
<div class="flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm">
<CircleAlert class="mt-0.5 size-4 shrink-0 text-destructive" />
<div>
<p class="font-medium">Game {appid} could not be loaded.</p>
<p class="mt-0.5 text-muted-foreground">{loadError}</p>
</div>
</div>
{:else if !game}
<div class="flex items-center gap-2 py-10 text-sm text-muted-foreground" aria-busy="true">
<LoaderCircle class="size-4 animate-spin" /> Loading game {appid}…
</div>
{:else}
<div class="flex flex-col gap-4 rounded-lg border border-border bg-card p-4 sm:flex-row" class:opacity-60={loading}>
<Thumb src={game.header_image} lazy={false} class="aspect-[460/215] w-full shrink-0 rounded-md sm:w-60" />
<div class="min-w-0 flex-1 space-y-2">
<h2 class="text-xl font-semibold">{game.name || "(no name)"}</h2>
<div class="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<span class="font-mono">{game.appid}</span>
{#if game.release_date}<span>· {game.release_date}</span>{/if}
{#if game.status}<Badge variant="outline">{game.status}</Badge>{/if}
{#if game.is_dead}<Badge variant="destructive">no players</Badge>{/if}
</div>
<div class="flex flex-wrap gap-x-4 gap-y-1 text-sm">
<a class="inline-flex items-center gap-1 text-primary hover:underline" href={steamUrl(game.appid)} target="_blank" rel="noopener noreferrer">
Steam store <ExternalLink class="size-3.5" />
</a>
<a class="inline-flex items-center gap-1 text-primary hover:underline" href="{SITE}/games/{game.appid}" target="_blank" rel="noopener noreferrer">
Public page <ExternalLink class="size-3.5" />
</a>
{#if game.override}
<a
class="inline-flex items-center gap-1 text-primary hover:underline"
href={fileUrl(`data/overrides/${game.appid}.json`)}
target="_blank"
rel="noopener noreferrer"
>
Override file <ExternalLink class="size-3.5" />
</a>
{/if}
</div>
<p class="text-sm">
{#if game.override}
{plural(activeCount, "active override")}{retiredCount ? `, ${retiredCount} retired` : ""}.
{:else}
<span class="text-muted-foreground">No override file yet. Saving creates one.</span>
{/if}
</p>
</div>
</div>
<div class="grid gap-3 lg:grid-cols-2">
{#each FIELDS as spec (spec.key)}
{@const active = activeOf(game, spec.key)}
{@const retired = retiredOf(game, spec.key)}
{@const changed = changes.includes(spec.key)}
{@const retiring = retire.has(spec.key)}
{@const error = errors[spec.key]}
<div
class="space-y-2 rounded-lg border p-3 transition-colors
{spec.kind === 'area' ? 'lg:col-span-2' : ''}
{error ? 'border-destructive/60' : retiring ? 'border-warning/60 bg-warning/5' : changed ? 'border-primary/60 bg-primary/5' : 'border-border'}"
>
<div class="flex flex-wrap items-center gap-2">
<label for="field-{spec.key}" class="text-sm font-medium">{spec.label}</label>
{#if active}
<Badge variant="info" title="Set by {active.set_by ?? 'unknown'} {relativeTime(active.set_at)}">overridden</Badge>
{:else if retired}
<Badge variant="secondary">retired</Badge>
{/if}
{#if changed}<Badge>changed</Badge>{/if}
{#if retiring}<Badge variant="warning">will retire</Badge>{/if}
<span class="ml-auto flex gap-1">
{#if changed}
<Button variant="ghost" size="sm" class="h-7" disabled={busy} onclick={() => (form[spec.key] = initial[spec.key])}>
Undo
</Button>
{/if}
{#if active}
<Button
variant="ghost"
size="sm"
class="h-7"
disabled={busy}
title="Stop overriding: restores {showValue(active.was)} on the next pipeline run"
onclick={() => {
if (retiring) retire.delete(spec.key);
else {
retire.add(spec.key);
form[spec.key] = initial[spec.key];
}
}}
>
<Undo2 class="size-3.5" />
{retiring ? "Keep override" : "Retire"}
</Button>
{/if}
</span>
</div>
<FieldEditor
{spec}
id="field-{spec.key}"
bind:value={form[spec.key]}
current={initial[spec.key]}
{genres}
disabled={busy || retiring}
invalid={!!error}
/>
{#if error}<p class="text-xs text-destructive">{error}</p>{/if}
<div class="space-y-0.5 text-xs text-muted-foreground">
<p>Catalogue now: <span class="break-words text-foreground">{showValue(game.fields[spec.key])}</span></p>
{#if active}
<p>
Override: <span class="text-foreground">{showValue(active.value)}</span> · was
<span class="text-foreground">{showValue(active.was)}</span>
{#if active.set_by}· {active.set_by}{/if}
{#if active.set_at}<span title={exactTime(active.set_at)}> · {relativeTime(active.set_at)}</span>{/if}
</p>
{#if active.reason}<p class="break-words">Reason: {active.reason}</p>{/if}
{:else if retired}
{@const restored = JSON.stringify(game.fields[spec.key] ?? null) !== JSON.stringify(retired.value ?? null)}
<p>
Retired{retired.retired_by ? ` by ${retired.retired_by}` : ""}{retired.retired_at ? ` ${relativeTime(retired.retired_at)}` : ""}:
restores <span class="text-foreground">{showValue(retired.was)}</span> ·
{restored ? "done" : "waiting for the pipeline"}
</p>
{/if}
{#if spec.hint && !active && !retired}<p>{spec.hint}</p>{/if}
</div>
</div>
{/each}
</div>
{#if game.override}
<div class="flex flex-wrap items-center gap-3 rounded-lg border border-border p-3 text-sm">
<Trash2 class="size-4 text-muted-foreground" />
{#if game.deletable.ok}
<p class="flex-1">Every entry in the override file is retired and restored, so the file can be deleted.</p>
<Button variant="outline" size="sm" class="text-destructive" disabled={busy || dirty} onclick={() => (deleteOpen = true)}>
Delete override file
</Button>
{:else}
<p class="flex-1 text-muted-foreground">The override file cannot be deleted yet: {game.deletable.reason}.</p>
{/if}
</div>
{/if}
<p class="flex items-start gap-2 text-xs text-muted-foreground">
<Info class="mt-0.5 size-3.5 shrink-0" />
<span>
Saving writes data/overrides/{game.appid}.json and nothing else. data/ changes on the next pipeline run. A field
cannot be saved empty, because the next scrape would refill it; retire the override instead.
</span>
</p>
{/if}
</div>
{#if dirty && game}
<div class="pointer-events-none sticky bottom-4 z-20 mt-4 flex justify-center">
<div
class="pointer-events-auto flex w-full max-w-3xl flex-wrap items-center gap-2 rounded-xl border border-border-strong bg-card/95 px-3 py-2 shadow-xl backdrop-blur"
>
<span class="px-1 text-sm font-medium">{plural(changes.length + retire.size, "change")}</span>
<input
bind:value={reason}
type="text"
maxlength="300"
placeholder="Reason (kept in the commit and the file)"
aria-label="Reason for the change"
disabled={busy}
class="h-8 min-w-48 flex-1 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground"
/>
<Button variant="ghost" size="sm" onclick={discard} disabled={busy}>Discard</Button>
<Button size="sm" onclick={() => (reviewOpen = true)} disabled={busy || invalid}>Review and save</Button>
</div>
</div>
{/if}
<Dialog
bind:open={reviewOpen}
title="Save {plural(plan.length, 'change')} to {game?.name || appid}?"
description="One commit to data/overrides/{appid}.json. data/ is untouched until the pipeline runs."
size="lg"
dismissable={!busy}
>
<div class="overflow-x-auto rounded-md border border-border">
<table class="w-full text-sm">
<thead class="bg-muted/50 text-left text-xs text-muted-foreground">
<tr>
<th class="px-3 py-2">Field</th>
<th class="px-3 py-2">Catalogue now</th>
<th class="px-3 py-2">Override now</th>
<th class="px-3 py-2">After saving</th>
</tr>
</thead>
<tbody>
{#each plan as row (row.field)}
<tr class="border-t border-border align-top">
<td class="px-3 py-2 font-medium whitespace-nowrap">{FIELD_LABEL[row.field]}</td>
<td class="px-3 py-2 break-words">{showValue(row.catalogue)}</td>
<td class="px-3 py-2 break-words text-muted-foreground">
{row.active ? `${showValue(row.active.value)} (was ${showValue(row.active.was)})` : "none"}
</td>
<td class="px-3 py-2 break-words">
{#if row.kind === "retire"}
<span class="text-warning">retire</span>: restores {showValue(row.next)} once
{:else}
<span class="font-medium text-primary">{showValue(row.next)}</span>
{/if}
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<p class="mt-3 text-sm">
Reason: <span class={reason.trim() ? "" : "text-muted-foreground"}>{reason.trim() || "none given"}</span>
</p>
{#snippet footer()}
<Button variant="ghost" onclick={() => (reviewOpen = false)} disabled={busy}>Back</Button>
<Button onclick={save} disabled={busy || invalid}>
{#if busy}<LoaderCircle class="size-4 animate-spin" />{/if}
Commit override
</Button>
{/snippet}
</Dialog>
<Dialog
bind:open={deleteOpen}
title="Delete the override file?"
description="Removes data/overrides/{appid}.json in one commit. Every entry in it has already done its job."
size="sm"
dismissable={!busy}
>
<p class="text-sm text-muted-foreground">
The server checks the file again at commit time and refuses if anything in it is still active.
</p>
{#snippet footer()}
<Button variant="ghost" onclick={() => (deleteOpen = false)} disabled={busy}>Cancel</Button>
<Button variant="destructive" onclick={deleteFile} disabled={busy}>
{#if busy}<LoaderCircle class="size-4 animate-spin" />{/if}
Delete file
</Button>
{/snippet}
</Dialog>
+74
View File
@@ -0,0 +1,74 @@
<script lang="ts">
import { untrack } from "svelte";
import EditGame from "./EditGame.svelte";
import BulkEdit from "./BulkEdit.svelte";
import { api, SessionExpiredError } from "../lib/api";
import { reportError } from "../lib/notify";
import { router } from "../lib/router.svelte";
import type { GenresResponse } from "../../../shared/admin-api";
const mode = $derived(router.query.get("mode") === "bulk" ? "bulk" : "one");
/** One flag for the whole page: while a commit runs, nothing else may start. */
let busy = $state(false);
let genres = $state.raw<GenresResponse["genres"]>([]);
let genresError = $state<string | null>(null);
let genresToken = $state(0);
$effect(() => {
void genresToken;
const controller = new AbortController();
untrack(() => (genresError = null));
api<GenresResponse>("/api/admin/genres", { signal: controller.signal })
.then((out) => (genres = out.genres))
.catch((err) => {
if (err instanceof DOMException && err.name === "AbortError") return;
if (err instanceof SessionExpiredError) reportError(err);
genresError = err instanceof Error ? err.message : String(err);
});
return () => controller.abort();
});
function setMode(next: "one" | "bulk") {
if (busy || next === mode || !router.confirmLeave()) return;
router.setQuery(next === "bulk" ? { mode: "bulk", appid: null } : { mode: null, genre: null, page: null });
}
</script>
<section class="space-y-5">
<div>
<h1 class="text-2xl font-semibold tracking-tight">Correct published games</h1>
<p class="text-sm text-muted-foreground">
Human corrections to genre, type, safety and anti-cheat, saved as override files that survive every pipeline run.
</p>
</div>
<div role="tablist" aria-label="Edit mode" class="inline-flex rounded-lg border border-border bg-muted/40 p-1">
{#each [{ id: "one", label: "One game" }, { id: "bulk", label: "Several games" }] as tab (tab.id)}
<button
type="button"
role="tab"
aria-selected={mode === tab.id}
disabled={busy}
class="rounded-md px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-50
{mode === tab.id ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}"
onclick={() => setMode(tab.id as "one" | "bulk")}
>
{tab.label}
</button>
{/each}
</div>
{#if genresError}
<p class="rounded-lg border border-warning/40 bg-warning/10 p-3 text-sm">
The genre list could not be loaded ({genresError}). Genre suggestions and the bulk picker are unavailable.
<button type="button" class="font-medium text-primary hover:underline" onclick={() => genresToken++}>Try again</button>
</p>
{/if}
{#if mode === "one"}
<EditGame {genres} bind:busy ongenres={() => genresToken++} />
{:else}
<BulkEdit {genres} bind:busy ongenres={() => genresToken++} />
{/if}
</section>
+200
View File
@@ -0,0 +1,200 @@
<!--
The moving parts, checked live. The table renders on a 503 too: the old page
threw on the status code and showed nothing, exactly when something was wrong.
-->
<script lang="ts">
import { untrack } from "svelte";
import { toast } from "svelte-sonner";
import CircleCheck from "@lucide/svelte/icons/circle-check";
import CircleX from "@lucide/svelte/icons/circle-x";
import TriangleAlert from "@lucide/svelte/icons/triangle-alert";
import RefreshCw from "@lucide/svelte/icons/refresh-cw";
import Send from "@lucide/svelte/icons/send";
import LoaderCircle from "@lucide/svelte/icons/loader-circle";
import Button from "../../../src/lib/ui/Button.svelte";
import StatusBadge from "../components/StatusBadge.svelte";
import { api, errorMessage, SessionExpiredError } from "../lib/api";
import { isAbort, reportError } from "../lib/notify";
import { router } from "../lib/router.svelte";
import { exactTime, formatInt, relativeTime } from "../lib/format";
import { QUEUE_STATUSES } from "../../../shared/queue-rules";
import { ADMIN_MIGRATIONS, type HealthResponse } from "../../../shared/admin-api";
let health = $state.raw<HealthResponse | null>(null);
let loading = $state(true);
let loadError = $state<string | null>(null);
let refresh = $state(0);
let pinging = $state(false);
$effect(() => {
void refresh;
const controller = new AbortController();
untrack(() => {
loading = true;
loadError = null;
});
api<HealthResponse>("/api/admin/health", { signal: controller.signal, accept: [503] })
.then((h) => {
health = h;
loading = false;
})
.catch((err) => {
if (isAbort(err)) return;
loading = false;
loadError = errorMessage(err);
if (err instanceof SessionExpiredError) reportError(err);
});
return () => controller.abort();
});
const missing = $derived(
health?.migrations ? ADMIN_MIGRATIONS.filter((m) => !health!.migrations!.includes(m)) : [],
);
async function ping() {
pinging = true;
try {
await api("/api/admin/ping", { method: "POST" });
toast.success("Write path works", {
description: "A ping row was written to the audit log.",
action: { label: "Open audit log", onClick: () => router.navigate("/admin/audit?action=ping") },
});
} catch (err) {
reportError(err, "The test write failed");
} finally {
pinging = false;
}
}
</script>
{#snippet state(ok: boolean | null, text: string)}
<span class="inline-flex items-center gap-1.5 {ok === true ? 'text-success' : ok === false ? 'text-destructive' : 'text-warning'}">
{#if ok === true}<CircleCheck class="size-4" />{:else if ok === false}<CircleX class="size-4" />{:else}<TriangleAlert class="size-4" />{/if}
{text}
</span>
{/snippet}
<section class="space-y-4">
<div class="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 class="text-2xl font-semibold tracking-tight">Health</h1>
<p class="text-sm text-muted-foreground">Checked live against D1 and the GitHub App each time this page loads.</p>
</div>
<div class="flex gap-2">
<Button variant="outline" size="sm" onclick={ping} disabled={pinging}>
{#if pinging}<LoaderCircle class="size-4 animate-spin" />{:else}<Send class="size-4" />{/if}
Test write
</Button>
<Button variant="outline" size="sm" onclick={() => refresh++} disabled={loading}>
<RefreshCw class="size-4 {loading ? 'animate-spin' : ''}" /> Refresh
</Button>
</div>
</div>
{#if loadError && !health}
<p class="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm">{loadError}</p>
{:else if !health}
<div class="h-64 animate-pulse rounded-lg bg-muted" aria-busy="true"></div>
{:else}
<div
class="flex items-center gap-3 rounded-lg border p-4 {health.ok
? 'border-success/40 bg-success/10'
: 'border-destructive/40 bg-destructive/10'}"
class:opacity-60={loading}
role="status"
>
{#if health.ok}
<CircleCheck class="size-5 text-success" />
<p class="font-medium">Everything the admin depends on is working.</p>
{:else}
<CircleX class="size-5 text-destructive" />
<p class="font-medium">Something needs attention. The rows below say what.</p>
{/if}
</div>
<div class="overflow-hidden rounded-lg border border-border" class:opacity-60={loading}>
<table class="w-full text-sm">
<tbody class="divide-y divide-border">
<tr>
<th scope="row" class="w-48 bg-muted/40 px-4 py-3 text-left font-medium">Signed in as</th>
<td class="px-4 py-3 break-all">{health.actor}</td>
</tr>
<tr>
<th scope="row" class="bg-muted/40 px-4 py-3 text-left font-medium">D1 database</th>
<td class="px-4 py-3">
{#if health.d1 === "ok"}
{@render state(true, "reachable")}
{:else}
{@render state(false, "unreachable")}
<p class="mt-1 text-xs text-muted-foreground">The error is in Workers Logs (wrangler tail).</p>
{/if}
</td>
</tr>
<tr>
<th scope="row" class="bg-muted/40 px-4 py-3 text-left font-medium">GitHub App</th>
<td class="px-4 py-3">
{#if health.github === "ok"}
{@render state(true, "installation and permissions work")}
{:else}
{@render state(false, health.github === "error" ? "request failed" : `GitHub answered ${health.github ?? "nothing"}`)}
<p class="mt-1 text-xs text-muted-foreground">
Approvals and corrections cannot commit until this works. Check the App's private key, installation
and repository permissions (docs/ADMIN.md).
</p>
{/if}
</td>
</tr>
<tr>
<th scope="row" class="bg-muted/40 px-4 py-3 text-left font-medium">Migrations</th>
<td class="px-4 py-3">
{#if health.migrations === null || health.migrations === undefined}
{@render state(null, "could not be read")}
{:else if missing.length}
{@render state(null, `${missing.length} not applied: ${missing.join(", ")}`)}
<p class="mt-1 text-xs text-muted-foreground">
The admin still works, without the reconcile lock and sweep watermark. Apply them with
<code class="rounded bg-muted px-1 font-mono">npx wrangler d1 migrations apply f2p-admin --remote</code>.
</p>
{:else}
{@render state(true, `all ${health.migrations.length} applied`)}
{/if}
</td>
</tr>
<tr>
<th scope="row" class="bg-muted/40 px-4 py-3 text-left font-medium">Reconcile lock</th>
<td class="px-4 py-3">
{#if health.lock}
<span title={exactTime(health.lock.expires_at)}>
held by <span class="font-mono text-xs">{health.lock.owner}</span>, expires {relativeTime(health.lock.expires_at)}
</span>
{:else}
<span class="text-muted-foreground">free</span>
{/if}
</td>
</tr>
<tr>
<th scope="row" class="bg-muted/40 px-4 py-3 text-left font-medium">History kept</th>
<td class="px-4 py-3">{health.retentionDays} days of audit log and commit jobs</td>
</tr>
<tr>
<th scope="row" class="bg-muted/40 px-4 py-3 text-left font-medium">Queue</th>
<td class="px-4 py-3">
{#if health.queue}
<div class="flex flex-wrap gap-2">
{#each QUEUE_STATUSES as s (s)}
<a href={s === "pending" ? "/admin" : `/admin?status=${s}`} class="inline-flex items-center gap-1.5 hover:underline">
<StatusBadge status={s} />
<span class="tnum">{formatInt(health.queue[s] ?? 0)}</span>
</a>
{/each}
</div>
{:else}
<span class="text-muted-foreground">unavailable</span>
{/if}
</td>
</tr>
</tbody>
</table>
</div>
{/if}
</section>
+166
View File
@@ -0,0 +1,166 @@
<!-- commit_jobs: every commit the Worker attempted, written before the attempt,
so a commit that died mid-flight still leaves a row here. -->
<script lang="ts">
import { untrack } from "svelte";
import GitCommitHorizontal from "@lucide/svelte/icons/git-commit-horizontal";
import ExternalLink from "@lucide/svelte/icons/external-link";
import StatusBadge from "../components/StatusBadge.svelte";
import Pager from "../components/Pager.svelte";
import EmptyState from "../components/EmptyState.svelte";
import Button from "../../../src/lib/ui/Button.svelte";
import { api, errorMessage, SessionExpiredError } from "../lib/api";
import { isAbort, reportError } from "../lib/notify";
import { router } from "../lib/router.svelte";
import { commitUrl, exactTime, fileUrl, relativeTime, shortSha } from "../lib/format";
import type { CommitJob, Paged } from "../../../shared/admin-api";
const STATUSES = ["pending", "committed", "conflict", "failed"];
const KINDS = ["approve", "override", "override.delete"];
const SIZES = [25, 50, 100, 200];
const query = $derived(router.query);
const status = $derived(STATUSES.includes(query.get("status") ?? "") ? query.get("status")! : "");
const kind = $derived(KINDS.includes(query.get("kind") ?? "") ? query.get("kind")! : "");
const size = $derived(SIZES.includes(Number(query.get("size"))) ? Number(query.get("size")) : 50);
const page = $derived(Math.max(1, Math.floor(Number(query.get("page"))) || 1));
let data = $state.raw<Paged<CommitJob> | null>(null);
let loading = $state(true);
let loadError = $state<string | null>(null);
let refresh = $state(0);
$effect(() => {
const params = new URLSearchParams({ limit: String(size), offset: String((page - 1) * size) });
if (status) params.set("status", status);
if (kind) params.set("kind", kind);
void refresh;
const controller = new AbortController();
untrack(() => {
loading = true;
loadError = null;
});
api<Paged<CommitJob>>(`/api/admin/jobs?${params}`, { signal: controller.signal })
.then((res) => {
data = res;
loading = false;
})
.catch((err) => {
if (isAbort(err)) return;
loading = false;
loadError = errorMessage(err);
if (err instanceof SessionExpiredError) reportError(err);
});
return () => controller.abort();
});
</script>
<section class="space-y-4">
<div>
<h1 class="text-2xl font-semibold tracking-tight">Commit jobs</h1>
<p class="text-sm text-muted-foreground">
Every commit the admin attempted. A job stuck in pending means the Worker stopped before it could record the result.
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<select
aria-label="Filter by status"
class="h-9 rounded-md border border-input bg-background px-2 text-sm"
value={status}
onchange={(e) => router.setQuery({ status: e.currentTarget.value || null, page: null })}
>
<option value="">Every status</option>
{#each STATUSES as s (s)}<option value={s}>{s}</option>{/each}
</select>
<select
aria-label="Filter by kind"
class="h-9 rounded-md border border-input bg-background px-2 text-sm"
value={kind}
onchange={(e) => router.setQuery({ kind: e.currentTarget.value || null, page: null })}
>
<option value="">Every kind</option>
{#each KINDS as k (k)}<option value={k}>{k}</option>{/each}
</select>
<Button variant="ghost" size="sm" onclick={() => refresh++} disabled={loading}>Refresh</Button>
</div>
{#if loadError}
<p class="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm">{loadError}</p>
{:else if data && !data.items.length}
<div class="rounded-lg border border-border">
<EmptyState icon={GitCommitHorizontal} title={status || kind ? "No jobs match these filters" : "No commits yet"} />
</div>
{:else if data}
<div class="overflow-x-auto rounded-lg border border-border" class:opacity-60={loading}>
<table class="w-full text-sm">
<thead class="bg-muted/50 text-left text-xs text-muted-foreground">
<tr>
<th class="px-3 py-2.5">Started</th>
<th class="px-3 py-2.5">Kind</th>
<th class="px-3 py-2.5">Status</th>
<th class="px-3 py-2.5">Target</th>
<th class="px-3 py-2.5">Commit</th>
<th class="px-3 py-2.5">By</th>
<th class="px-3 py-2.5">Result</th>
</tr>
</thead>
<tbody>
{#each data.items as job (job.id)}
<tr class="border-t border-border align-top">
<td class="px-3 py-2 whitespace-nowrap" title={exactTime(job.created_at)}>{relativeTime(job.created_at)}</td>
<td class="px-3 py-2 font-mono text-xs whitespace-nowrap">{job.kind}</td>
<td class="px-3 py-2"><StatusBadge status={job.status} kind="job" /></td>
<td class="max-w-64 truncate px-3 py-2 font-mono text-xs whitespace-nowrap" title={job.target_path}>
{#if /^[\w./-]+$/.test(job.target_path)}
<a class="hover:text-primary hover:underline" href={fileUrl(job.target_path)} target="_blank" rel="noopener noreferrer">
{job.target_path}
</a>
{:else}
{job.target_path}
{/if}
</td>
<td class="px-3 py-2 whitespace-nowrap">
{#if job.commit_sha}
<a
class="inline-flex items-center gap-1 font-mono text-xs text-primary hover:underline"
href={commitUrl(job.commit_sha)}
target="_blank"
rel="noopener noreferrer"
>
{shortSha(job.commit_sha)} <ExternalLink class="size-3" />
</a>
{:else}
<span class="text-muted-foreground">—</span>
{/if}
</td>
<td class="max-w-48 truncate px-3 py-2 text-xs" title={job.requested_by ?? ""}>{job.requested_by ?? "—"}</td>
<td class="max-w-80 px-3 py-2 text-xs">
{#if job.error}
<p class="line-clamp-3 break-words {job.status === 'committed' ? 'text-muted-foreground' : 'text-destructive'}" title={job.error}>
{job.error}
</p>
{:else if job.finished_at}
<span class="text-muted-foreground" title={exactTime(job.finished_at)}>finished {relativeTime(job.finished_at)}</span>
{:else}
<span class="text-warning">not finished</span>
{/if}
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<Pager
offset={data.offset}
limit={data.limit}
total={data.total}
count={data.items.length}
disabled={loading}
sizes={SIZES}
onpage={(o) => router.setQuery({ page: o / size + 1 === 1 ? null : o / size + 1 })}
onsize={(n) => router.setQuery({ size: n === 50 ? null : n, page: null })}
/>
{:else}
<div class="h-40 animate-pulse rounded-lg bg-muted" aria-busy="true"></div>
{/if}
</section>
+13
View File
@@ -0,0 +1,13 @@
<script lang="ts">
import Compass from "@lucide/svelte/icons/compass";
import EmptyState from "../components/EmptyState.svelte";
import Button from "../../../src/lib/ui/Button.svelte";
import { router } from "../lib/router.svelte";
</script>
<div class="rounded-lg border border-border">
<EmptyState icon={Compass} title="No admin page at {router.path}">
<p>The address may be mistyped.</p>
<Button class="mt-4" variant="outline" size="sm" href="/admin">Go to the queue</Button>
</EmptyState>
</div>
+785
View File
@@ -0,0 +1,785 @@
<!--
The review queue.
The rule this screen exists to enforce: a row that is already decided
(approved, committed, rejected) or whose GAME is already published has no
checkbox. It shows a lock instead, "select all" skips it, and the server
refuses it anyway (shared/queue-rules.ts is the one definition both sides
use).
-->
<script lang="ts">
import { tick, untrack } from "svelte";
import { SvelteSet } from "svelte/reactivity";
import { toast } from "svelte-sonner";
import Search from "@lucide/svelte/icons/search";
import RefreshCw from "@lucide/svelte/icons/refresh-cw";
import Lock from "@lucide/svelte/icons/lock";
import Inbox from "@lucide/svelte/icons/inbox";
import Eye from "@lucide/svelte/icons/eye";
import Keyboard from "@lucide/svelte/icons/keyboard";
import Check from "@lucide/svelte/icons/check";
import X from "@lucide/svelte/icons/x";
import Clock from "@lucide/svelte/icons/clock";
import Undo2 from "@lucide/svelte/icons/undo-2";
import TriangleAlert from "@lucide/svelte/icons/triangle-alert";
import LoaderCircle from "@lucide/svelte/icons/loader-circle";
import Button from "../../../src/lib/ui/Button.svelte";
import Badge from "../../../src/lib/ui/Badge.svelte";
import Dialog from "../components/Dialog.svelte";
import Thumb from "../components/Thumb.svelte";
import Pager from "../components/Pager.svelte";
import StatusBadge from "../components/StatusBadge.svelte";
import Kbd from "../components/Kbd.svelte";
import EmptyState from "../components/EmptyState.svelte";
import CandidateDialog from "./CandidateDialog.svelte";
import { api, errorMessage, SessionExpiredError } from "../lib/api";
import { isAbort, reportError } from "../lib/notify";
import { router } from "../lib/router.svelte";
import { pageSelection, toggleAll } from "../lib/selection";
import { QUEUE_SHORTCUTS, shouldIgnore } from "../lib/shortcuts";
import { commitUrl, exactTime, plural, relativeTime, shortSha, steamUrl } from "../lib/format";
import { ACTION_CONSEQUENCE, ACTION_LABEL, ACTION_PAST, LOCK_HELP, SKIP_TEXT, SORTS, STATUS_HELP } from "../lib/labels";
import {
MAX_DECIDE,
QUEUE_STATUSES,
allowedActions,
lockReason,
type DecideAction,
type QueueStatus,
type SkippedRow,
} from "../../../shared/queue-rules";
import type { DecideResponse, QueueItem, QueueResponse, ReconcileResponse, StatsResponse } from "../../../shared/admin-api";
const TABS: QueueStatus[] = ["pending", "deferred", "failed", "approved", "committed", "rejected"];
const SIZES = [25, 50, 100, 200];
const EMPTY: Record<QueueStatus, string> = {
pending: "Nothing is waiting for review.",
deferred: "Nothing has been put aside.",
failed: "No failed rows.",
approved: "Nothing is waiting for the pipeline.",
committed: "No published rows yet.",
rejected: "Nothing has been rejected.",
};
// ── URL state: tab, search, sort and page survive a reload or a shared link ──
const query = $derived(router.query);
const q = $derived((query.get("q") ?? "").trim());
const status = $derived.by((): QueueStatus | "all" => {
const s = query.get("status") ?? "pending";
if (s === "all") return q ? "all" : "pending";
return (QUEUE_STATUSES as readonly string[]).includes(s) ? (s as QueueStatus) : "pending";
});
const sort = $derived(SORTS.find((s) => s.value === query.get("sort"))?.value ?? "newest");
const size = $derived(SIZES.includes(Number(query.get("size"))) ? Number(query.get("size")) : 50);
const page = $derived(Math.max(1, Math.floor(Number(query.get("page"))) || 1));
const offset = $derived((page - 1) * size);
const key = $derived(`${status}|${q}|${sort}|${size}|${offset}`);
// ── data ──
let data = $state.raw<QueueResponse | null>(null);
let dataKey = "";
let loading = $state(true);
let loadError = $state<string | null>(null);
let stats = $state.raw<StatsResponse | null>(null);
let refresh = $state(0);
const selected = new SvelteSet<string>();
let cursor = $state(-1);
let busy = $state(false);
let reconciling = $state(false);
$effect(() => {
const k = key;
void refresh;
const params = new URLSearchParams({ status, sort, limit: String(size), offset: String(offset) });
if (q) params.set("q", q);
const controller = new AbortController();
untrack(() => {
loading = true;
loadError = null;
// A different listing never shows the previous one's rows, even
// briefly: a stale row that can still be clicked is how a selection
// used to pick up a row from the tab being left.
if (dataKey !== k) {
data = null;
cursor = -1;
}
selected.clear();
});
api<QueueResponse>(`/api/admin/queue?${params}`, { signal: controller.signal })
.then((res) => {
data = res;
dataKey = k;
loading = false;
if (cursor >= res.items.length) cursor = res.items.length - 1;
// Deciding the last rows of the last page leaves an empty page behind.
if (!res.items.length && res.total > 0 && res.offset > 0) {
router.setQuery({ page: Math.ceil(res.total / size) });
}
})
.catch((err) => {
if (isAbort(err)) return;
loading = false;
loadError = errorMessage(err);
if (err instanceof SessionExpiredError) reportError(err);
});
return () => controller.abort();
});
$effect(() => {
void refresh;
const controller = new AbortController();
api<StatsResponse>("/api/admin/stats", { signal: controller.signal })
.then((s) => (stats = s))
.catch((err) => {
// The tabs render without counts; only a lapsed session is worth saying.
if (err instanceof SessionExpiredError) reportError(err);
});
return () => controller.abort();
});
const rows = $derived(data?.items ?? []);
const selectable = $derived(rows.filter((r) => !lockReason(r)).length);
const selection = $derived(pageSelection(rows, selected));
const selectedRows = $derived(rows.filter((r) => selected.has(r.id)));
const maxDecide = $derived(data?.maxDecide ?? MAX_DECIDE);
const counts = $derived.by(() => {
const out: Record<DecideAction, number> = { approve: 0, reject: 0, defer: 0, requeue: 0 };
for (const r of selectedRows) for (const a of allowedActions(r)) out[a]++;
return out;
});
const showDecision = $derived(status !== "pending" && status !== "deferred");
const jobAlerts = $derived.by(() => {
const c = stats?.commits ?? {};
return (["failed", "conflict", "pending"] as const).filter((s) => (c[s] ?? 0) > 0).map((s) => ({ status: s, n: c[s] }));
});
// ── search ──
let searchText = $state(untrack(() => q));
let searchInput = $state<HTMLInputElement>();
let searchTimer: ReturnType<typeof setTimeout> | undefined;
$effect(() => {
// Back/Forward changes q under the input; typing must not be overwritten.
const value = q;
untrack(() => {
if (document.activeElement !== searchInput) searchText = value;
});
});
function applySearch() {
clearTimeout(searchTimer);
const text = searchText.trim();
if (text === q) return;
router.setQuery({ q: text || null, page: null, status: !text && status === "all" ? null : query.get("status") });
}
function setTab(tab: QueueStatus | "all") {
router.setQuery({ status: tab === "pending" ? null : tab, page: null });
}
// ── selection ──
function toggle(row: QueueItem) {
if (lockReason(row) || busy) return;
if (selected.has(row.id)) selected.delete(row.id);
else selected.add(row.id);
}
function toggleEveryRow() {
const next = toggleAll(rows, selected);
selected.clear();
for (const id of next) selected.add(id);
}
// ── decisions ──
let confirmOpen = $state(false);
let confirmAction = $state<DecideAction>("approve");
let reason = $state("");
function ask(action: DecideAction) {
if (busy || !counts[action]) return;
if (selected.size > maxDecide) {
toast.error(`At most ${maxDecide} rows per decision.`, { description: "Select fewer rows, or use a smaller page size." });
return;
}
confirmAction = action;
reason = "";
confirmOpen = true;
}
const duplicateAppids = $derived.by(() => {
const seen = new Map<string, number>();
for (const r of selectedRows) seen.set(r.appid, (seen.get(r.appid) ?? 0) + 1);
return new Set([...seen].filter(([, n]) => n > 1).map(([appid]) => appid));
});
async function decide() {
if (busy) return;
const action = confirmAction;
const sent = selectedRows.slice();
const names = new Map(sent.map((r) => [r.id, r.name || r.appid]));
const describe = (skipped: SkippedRow[]) =>
skipped.map((s) => `${names.get(s.id) ?? s.id} (${SKIP_TEXT[s.reason] ?? s.reason})`).join("; ");
busy = true;
try {
const res = await api<DecideResponse | { error: string; skipped: SkippedRow[] }>("/api/admin/decide", {
method: "POST",
body: { ids: sent.map((r) => r.id), action, reason: reason.trim() },
accept: [409],
});
if ("error" in res) {
toast.warning("Nothing was decided", { description: describe(res.skipped) });
} else {
const parts: string[] = [];
if (action === "approve") {
parts.push(res.commit ? `Commit ${shortSha(res.commit)}.` : "No commit: every link was already queued.");
}
if (res.skipped.length) parts.push(`Skipped ${res.skipped.length}: ${describe(res.skipped)}.`);
const commit = res.commit;
toast.success(`${ACTION_PAST[action]} ${plural(res.decided, "row")}`, {
description: parts.join(" ") || undefined,
action: commit ? { label: "View commit", onClick: () => window.open(commitUrl(commit), "_blank", "noopener") } : undefined,
});
}
} catch (err) {
reportError(err, `${ACTION_LABEL[action]} failed`);
} finally {
busy = false;
confirmOpen = false;
refresh++;
}
}
async function reconcile() {
if (reconciling) return;
reconciling = true;
try {
const out = await api<ReconcileResponse>("/api/admin/reconcile", { method: "POST" });
if (out.skipped) toast.info("Reconcile skipped", { description: out.skipped });
else
toast.success("Reconcile finished", {
description: `Checked ${out.checked}: ${out.published} published, ${out.removed} removed, ${out.stale} stale, ${out.swept} swept.`,
});
} catch (err) {
reportError(err, "Reconcile failed");
} finally {
reconciling = false;
refresh++;
}
}
// ── details and keyboard ──
let detailId = $state<string | null>(null);
let helpOpen = $state(false);
async function moveCursor(delta: number) {
if (!rows.length) return;
cursor = Math.min(rows.length - 1, Math.max(0, cursor + delta));
await tick();
const id = rows[cursor]?.id;
for (const el of document.querySelectorAll<HTMLElement>(`[data-row="${CSS.escape(id ?? "")}"]`)) {
if (el.offsetParent !== null) el.scrollIntoView({ block: "nearest" });
}
}
function onKey(e: KeyboardEvent) {
if (shouldIgnore(e)) return;
const row = cursor >= 0 ? rows[cursor] : undefined;
switch (e.key) {
case "j":
void moveCursor(1);
break;
case "k":
void moveCursor(-1);
break;
case "x":
if (row) toggle(row);
break;
case "a":
ask("approve");
break;
case "r":
ask("reject");
break;
case "d":
ask(counts.defer ? "defer" : "requeue");
break;
case "e":
if (row) detailId = row.id;
break;
case "/":
searchInput?.focus();
break;
case "?":
helpOpen = true;
break;
case "Escape":
if (!selected.size) return;
selected.clear();
break;
default:
return;
}
e.preventDefault();
}
</script>
<svelte:window onkeydown={onKey} />
{#snippet selectCell(row: QueueItem)}
{@const lock = lockReason(row)}
{#if lock}
<span class="inline-flex size-4 items-center justify-center text-muted-foreground" title={LOCK_HELP[lock]}>
<Lock class="size-3.5" aria-hidden="true" />
<span class="sr-only">{LOCK_HELP[lock]}</span>
</span>
{:else}
<input
type="checkbox"
class="size-4 cursor-pointer accent-primary"
checked={selected.has(row.id)}
disabled={busy}
aria-label="Select {row.name || row.appid}"
onchange={(e) => {
toggle(row);
e.currentTarget.checked = selected.has(row.id);
}}
/>
{/if}
{/snippet}
{#snippet gameCell(row: QueueItem)}
<div class="flex min-w-0 items-center gap-3">
<Thumb src={row.header_image} class="hidden h-[43px] w-[92px] shrink-0 lg:grid" />
<div class="min-w-0">
<button
type="button"
class="block max-w-full truncate text-left font-medium hover:text-primary hover:underline"
onclick={() => (detailId = row.id)}
>
{row.name || "(no name)"}
</button>
<div class="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
<a
href={steamUrl(row.appid)}
target="_blank"
rel="noopener noreferrer"
class="font-mono hover:text-foreground hover:underline"
title="Open the Steam store page">{row.appid}</a
>
{#if row.published && row.status !== "committed"}<Badge variant="success">published</Badge>{/if}
{#if row.app_type && row.app_type !== "game"}<Badge variant="outline">{row.app_type}</Badge>{/if}
{#if !row.is_free}<Badge variant="warning">not free</Badge>{/if}
{#if row.health_status && row.health_status !== "ok"}<Badge variant="warning">{row.health_status}</Badge>{/if}
<span>{row.source}</span>
</div>
</div>
</div>
{/snippet}
{#snippet decisionCell(row: QueueItem)}
{#if row.decided_at || row.reject_reason}
<div class="text-xs">
{#if row.decided_at}
<span title={exactTime(row.decided_at)}>{relativeTime(row.decided_at)}</span>
{#if row.decided_by}<span class="text-muted-foreground"> · {row.decided_by}</span>{/if}
{/if}
{#if row.reject_reason}
<p class="mt-0.5 line-clamp-2 text-muted-foreground" title={row.reject_reason}>{row.reject_reason}</p>
{/if}
</div>
{:else}
<span class="text-muted-foreground">—</span>
{/if}
{/snippet}
<section class="space-y-4">
<div class="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 class="text-2xl font-semibold tracking-tight">Review queue</h1>
<p class="text-sm text-muted-foreground">
Candidates found by discovery and the browser extension. Approving asks the pipeline to publish a game.
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
{#each jobAlerts as alert (alert.status)}
<a
href="/admin/jobs?status={alert.status}"
class="inline-flex items-center gap-1.5 rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1 text-xs font-medium text-warning hover:bg-warning/20"
>
<TriangleAlert class="size-3.5" />
{plural(alert.n, "commit job")}
{alert.status}
</a>
{/each}
<Button variant="outline" size="sm" onclick={reconcile} disabled={reconciling} title="Check approved rows against data/ now">
<RefreshCw class="size-4 {reconciling ? 'animate-spin' : ''}" />
Reconcile
</Button>
<Button variant="ghost" size="sm" onclick={() => (helpOpen = true)} aria-label="Keyboard shortcuts">
<Keyboard class="size-4" />
</Button>
</div>
</div>
<!-- tabs -->
<div class="-mx-1 overflow-x-auto px-1 scrollbar-thin">
<div role="tablist" aria-label="Queue status" class="flex min-w-max gap-1 border-b border-border">
{#each TABS as tab (tab)}
{@const n = stats?.queue[tab]}
<button
type="button"
role="tab"
aria-selected={status === tab}
title={STATUS_HELP[tab]}
class="-mb-px inline-flex items-center gap-2 border-b-2 px-3 py-2 text-sm font-medium capitalize transition-colors
{status === tab
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => setTab(tab)}
>
{tab}
<span
class="tnum rounded-full px-1.5 py-0.5 text-[11px] leading-none {status === tab
? 'bg-primary/15 text-primary'
: 'bg-muted text-muted-foreground'}"
>
{n ?? (stats ? 0 : "…")}
</span>
</button>
{/each}
{#if status === "all"}
<span role="tab" aria-selected="true" class="-mb-px border-b-2 border-primary px-3 py-2 text-sm font-medium">
All statuses
</span>
{/if}
</div>
</div>
<!-- toolbar -->
<div class="flex flex-wrap items-center gap-2">
<form
class="relative min-w-56 flex-1 sm:max-w-sm"
role="search"
onsubmit={(e) => {
e.preventDefault();
applySearch();
}}
>
<Search class="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<input
bind:this={searchInput}
bind:value={searchText}
type="search"
placeholder="Search name or appid"
aria-label="Search the queue by name or appid"
maxlength="80"
class="h-9 w-full rounded-md border border-input bg-background pr-10 pl-8 text-sm placeholder:text-muted-foreground"
oninput={() => {
clearTimeout(searchTimer);
searchTimer = setTimeout(applySearch, 350);
}}
onkeydown={(e) => {
if (e.key === "Escape") {
searchText = "";
applySearch();
searchInput?.blur();
}
}}
/>
<span class="absolute top-1/2 right-2 -translate-y-1/2"><Kbd>/</Kbd></span>
</form>
{#if q}
<label class="flex items-center gap-2 text-sm">
<input
type="checkbox"
class="size-4 accent-primary"
checked={status === "all"}
onchange={(e) => router.setQuery({ status: e.currentTarget.checked ? "all" : null, page: null })}
/>
Search every status
</label>
{/if}
<label class="ml-auto flex items-center gap-2 text-sm text-muted-foreground">
Sort
<select
class="h-9 rounded-md border border-input bg-background px-2 text-sm text-foreground"
value={sort}
onchange={(e) => router.setQuery({ sort: e.currentTarget.value === "newest" ? null : e.currentTarget.value, page: null })}
>
{#each SORTS as s (s.value)}
<option value={s.value}>{s.label}</option>
{/each}
</select>
</label>
</div>
{#if loadError && !data}
<div class="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm">
<p class="font-medium text-destructive">The queue could not be loaded.</p>
<p class="mt-1 text-muted-foreground">{loadError}</p>
<Button class="mt-3" variant="outline" size="sm" onclick={() => refresh++}>Try again</Button>
</div>
{:else if !data}
<div class="overflow-hidden rounded-lg border border-border" aria-busy="true" aria-label="Loading the queue">
{#each Array(8) as _, i (i)}
<div class="flex items-center gap-4 border-b border-border px-3 py-3 last:border-b-0">
<div class="size-4 animate-pulse rounded bg-muted"></div>
<div class="hidden h-[43px] w-[92px] animate-pulse rounded bg-muted lg:block"></div>
<div class="flex-1 space-y-2">
<div class="h-3.5 w-1/3 animate-pulse rounded bg-muted"></div>
<div class="h-3 w-1/5 animate-pulse rounded bg-muted"></div>
</div>
</div>
{/each}
</div>
{:else if !rows.length}
<div class="rounded-lg border border-border">
<EmptyState icon={Inbox} title={q ? `Nothing matches “${q}”` : EMPTY[status as QueueStatus]}>
{#if q && status !== "all"}
It may be in another tab.
<button type="button" class="font-medium text-primary hover:underline" onclick={() => setTab("all")}>
Search every status
</button>
{/if}
</EmptyState>
</div>
{:else}
<div class="relative" inert={busy || loading} class:opacity-60={loading}>
<!-- table, md and up -->
<div class="hidden overflow-x-auto rounded-lg border border-border md:block">
<table class="w-full text-sm">
<thead class="bg-muted/50 text-left text-xs font-medium text-muted-foreground">
<tr>
<th class="w-10 px-3 py-2.5">
<input
type="checkbox"
class="size-4 cursor-pointer accent-primary disabled:cursor-not-allowed"
aria-label="Select every row on this page that can be decided"
title={selectable ? "Select every row on this page that can be decided" : "Nothing on this page can be decided"}
checked={selection === "all"}
disabled={!selectable}
{@attach (node: HTMLInputElement) => {
node.indeterminate = selection === "some";
}}
onchange={toggleEveryRow}
/>
</th>
<th class="px-3 py-2.5">Game</th>
{#if status === "all"}<th class="px-3 py-2.5">Status</th>{/if}
<th class="px-3 py-2.5 text-right">Players</th>
<th class="px-3 py-2.5">Reviews</th>
<th class="px-3 py-2.5">Released</th>
<th class="px-3 py-2.5">First seen</th>
{#if showDecision}<th class="px-3 py-2.5">Decision</th>{/if}
<th class="w-10 px-3 py-2.5"><span class="sr-only">Details</span></th>
</tr>
</thead>
<tbody>
{#each rows as row, i (row.id)}
{@const lock = lockReason(row)}
<tr
data-row={row.id}
class="border-t border-border transition-colors
{selected.has(row.id) ? 'bg-primary/8' : 'hover:bg-muted/40'}
{cursor === i ? 'outline-2 -outline-offset-2 outline-primary/70' : ''}"
onclick={(e) => {
cursor = i;
// A click on the row body toggles, like a mail client; links,
// buttons and the checkbox keep their own behaviour.
if (!lock && !(e.target as Element).closest("a, button, input")) toggle(row);
}}
>
<td class="px-3 py-2">{@render selectCell(row)}</td>
<td class="max-w-[28rem] px-3 py-2">{@render gameCell(row)}</td>
{#if status === "all"}<td class="px-3 py-2"><StatusBadge status={row.status} /></td>{/if}
<td class="tnum px-3 py-2 text-right whitespace-nowrap">{row.current_players_raw || "—"}</td>
<td class="px-3 py-2 text-xs whitespace-nowrap">{row.reviews_raw || "—"}</td>
<td class="px-3 py-2 text-xs whitespace-nowrap text-muted-foreground">{row.release_date || "—"}</td>
<td class="px-3 py-2 text-xs whitespace-nowrap">
<span title={exactTime(row.first_seen_at)}>{relativeTime(row.first_seen_at)}</span>
{#if row.seen_count > 1}
<span class="text-muted-foreground" title="Seen {row.seen_count} times">×{row.seen_count}</span>
{/if}
</td>
{#if showDecision}<td class="max-w-56 px-3 py-2">{@render decisionCell(row)}</td>{/if}
<td class="px-2 py-2">
<Button variant="ghost" size="icon" class="size-8" aria-label="Details for {row.name || row.appid}" onclick={() => (detailId = row.id)}>
<Eye class="size-4" />
</Button>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<!-- cards, below md -->
<div class="space-y-2 md:hidden">
{#if selectable}
<label class="flex items-center gap-2 px-1 text-sm text-muted-foreground">
<input
type="checkbox"
class="size-4 accent-primary"
checked={selection === "all"}
{@attach (node: HTMLInputElement) => {
node.indeterminate = selection === "some";
}}
onchange={toggleEveryRow}
/>
Select every row that can be decided
</label>
{/if}
<ul class="space-y-2">
{#each rows as row, i (row.id)}
<li
data-row={row.id}
class="rounded-lg border p-3 {selected.has(row.id) ? 'border-primary/60 bg-primary/5' : 'border-border'}
{cursor === i ? 'outline-2 outline-primary/70' : ''}"
>
<div class="flex items-start gap-3">
<div class="pt-0.5">{@render selectCell(row)}</div>
<div class="min-w-0 flex-1 space-y-2">
{@render gameCell(row)}
<div class="flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground">
{#if status === "all"}<StatusBadge status={row.status} />{/if}
<span>Players {row.current_players_raw || "—"}</span>
<span>{row.reviews_raw || "No reviews"}</span>
<span title={exactTime(row.first_seen_at)}>Seen {relativeTime(row.first_seen_at)}</span>
</div>
{#if showDecision}{@render decisionCell(row)}{/if}
</div>
<Button variant="ghost" size="icon" class="size-8 shrink-0" aria-label="Details for {row.name || row.appid}" onclick={() => (detailId = row.id)}>
<Eye class="size-4" />
</Button>
</div>
</li>
{/each}
</ul>
</div>
</div>
<Pager
offset={data.offset}
limit={data.limit}
total={data.total}
count={data.count}
disabled={loading || busy}
sizes={SIZES}
onpage={(o) => router.setQuery({ page: o / size + 1 === 1 ? null : o / size + 1 })}
onsize={(n) => router.setQuery({ size: n === 50 ? null : n, page: null })}
/>
{/if}
</section>
{#if selected.size}
<div class="pointer-events-none sticky bottom-4 z-20 mt-4 flex justify-center">
<div
class="pointer-events-auto flex flex-wrap items-center gap-2 rounded-xl border border-border-strong bg-card/95 px-3 py-2 shadow-xl backdrop-blur"
role="toolbar"
aria-label="Decide the selected rows"
>
<span class="px-1 text-sm font-medium tnum">{plural(selected.size, "row")} selected</span>
{#if selected.size > maxDecide}
<span class="text-xs text-destructive">at most {maxDecide} per decision</span>
{/if}
<Button variant="ghost" size="sm" onclick={() => selected.clear()} disabled={busy}>Clear <Kbd class="hidden sm:inline-flex">Esc</Kbd></Button>
<span class="mx-1 hidden h-5 w-px bg-border sm:block"></span>
<Button size="sm" onclick={() => ask("approve")} disabled={busy || !counts.approve}>
<Check class="size-4" /> Approve <Kbd class="hidden sm:inline-flex">a</Kbd>
</Button>
<Button size="sm" variant="destructive" onclick={() => ask("reject")} disabled={busy || !counts.reject}>
<X class="size-4" /> Reject <Kbd class="hidden sm:inline-flex">r</Kbd>
</Button>
{#if counts.defer}
<Button size="sm" variant="outline" onclick={() => ask("defer")} disabled={busy}>
<Clock class="size-4" /> Defer <Kbd class="hidden sm:inline-flex">d</Kbd>
</Button>
{/if}
{#if counts.requeue}
<Button size="sm" variant="outline" onclick={() => ask("requeue")} disabled={busy}>
<Undo2 class="size-4" /> Back to pending {#if !counts.defer}<Kbd class="hidden sm:inline-flex">d</Kbd>{/if}
</Button>
{/if}
</div>
</div>
{/if}
<Dialog
bind:open={confirmOpen}
title="{ACTION_LABEL[confirmAction]} {plural(selectedRows.length, 'row')}?"
description={ACTION_CONSEQUENCE[confirmAction]}
size="lg"
dismissable={!busy}
>
<form
id="decide-form"
class="space-y-4"
onsubmit={(e) => {
e.preventDefault();
void decide();
}}
>
<ul class="max-h-72 divide-y divide-border overflow-y-auto rounded-md border border-border text-sm">
{#each selectedRows as row (row.id)}
{@const applies = allowedActions(row).includes(confirmAction)}
<li class="flex items-center gap-3 px-3 py-2">
<div class="min-w-0 flex-1">
<p class="truncate font-medium">{row.name || "(no name)"}</p>
<p class="font-mono text-xs text-muted-foreground">{row.appid}</p>
</div>
{#if !applies}
<span class="text-xs text-warning">skipped: already in that state</span>
{:else if duplicateAppids.has(row.appid)}
<span class="text-xs text-warning">same game selected twice: the newest row is used</span>
{/if}
<StatusBadge status={row.status} />
</li>
{/each}
</ul>
<label class="block space-y-1.5 text-sm">
<span class="font-medium">Reason <span class="font-normal text-muted-foreground">(optional)</span></span>
<input
bind:value={reason}
data-autofocus
type="text"
maxlength="300"
autocomplete="off"
placeholder={confirmAction === "reject"
? "Shown on the row and kept with the rejection"
: confirmAction === "approve"
? "Kept in the commit message and the audit log"
: "Kept in the audit log"}
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground"
/>
</label>
</form>
{#snippet footer()}
<Button variant="ghost" onclick={() => (confirmOpen = false)} disabled={busy}>Cancel</Button>
<Button type="submit" form="decide-form" variant={confirmAction === "reject" ? "destructive" : "default"} disabled={busy}>
{#if busy}<LoaderCircle class="size-4 animate-spin" />{/if}
{ACTION_LABEL[confirmAction]}
{plural(counts[confirmAction], "row")}
</Button>
{/snippet}
</Dialog>
<Dialog bind:open={helpOpen} title="Keyboard shortcuts" size="sm">
<dl class="grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2 text-sm">
{#each QUEUE_SHORTCUTS as s (s.key)}
<dt><Kbd>{s.key === "Escape" ? "Esc" : s.key}</Kbd></dt>
<dd>{s.label}</dd>
{/each}
</dl>
<p class="mt-4 text-xs text-muted-foreground">Shortcuts do nothing while you type in a field or a dialog is open.</p>
</Dialog>
<CandidateDialog
id={detailId}
onselect={(id) => (detailId = id)}
onclose={() => (detailId = null)}
onchanged={() => refresh++}
/>
+24
View File
@@ -0,0 +1,24 @@
{
// The admin SPA: browser code, checked by `npm run check:admin`
// (svelte-check). It reaches into ../shared and a few pure modules of the
// public app (ui components, utils, prefs); none of those may import
// SvelteKit's $app/* or $lib aliases, or this build cannot resolve them.
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["svelte", "vite/client"],
"noEmit": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": ["src/**/*.ts", "src/**/*.svelte", "../shared/**/*.ts"],
"exclude": ["../shared/**/*.test.ts", "src/**/*.test.ts"]
}
+19
View File
@@ -0,0 +1,19 @@
{
// The admin's Node-side code: its Vite config, the bundle emitter and the
// local mock backend.
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"],
"noEmit": true,
"isolatedModules": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"skipLibCheck": true
},
"include": ["vite.config.ts", "build/**/*.ts", "mock/**/*.ts", "../worker-configuration.d.ts", "../worker/env.d.ts"],
"exclude": ["mock/**/*.test.ts"]
}
+18
View File
@@ -0,0 +1,18 @@
{
// The admin SPA's unit tests: browser code (DOM types) run by Vitest on Node.
// The mock backend's test is Worker-shaped and lives in ../tsconfig.test.json.
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"],
"noEmit": true,
"isolatedModules": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"skipLibCheck": true
},
"include": ["src/**/*.test.ts", "security.test.ts"]
}
+65
View File
@@ -0,0 +1,65 @@
/**
* The admin SPA's own build. See worker/routes/admin-spa.ts for how it is
* served and admin/build/emit-worker-bundle.ts for why it is embedded in the
* Worker instead of dist/.
*
* npm run dev:admin Vite + HMR on :5174, real handlers, mock backend
* npm run build:admin .admin-build/ -> worker/generated/admin-bundle.ts
* npm run preview:admin the built bundle through the real serveAdmin (CSP)
*/
import path from "node:path";
import { defineConfig } from "vite";
import { svelte, vitePreprocess } from "@sveltejs/vite-plugin-svelte";
import tailwindcss from "@tailwindcss/vite";
import { emitWorkerBundle } from "./build/emit-worker-bundle";
import { adminDevApi } from "./mock/dev-api";
const WEB = path.resolve(__dirname, "..");
export default defineConfig(({ command, mode }) => ({
root: __dirname,
base: "/admin/",
// No public directory: every asset the admin needs is imported, hashed and
// embedded. A public/ folder would be copied beside the bundle and never
// served.
publicDir: false,
plugins: [
tailwindcss(),
// configFile false: web/svelte.config.js is the SvelteKit app's, and its
// kit options mean nothing here.
svelte({ configFile: false, preprocess: vitePreprocess() }),
command === "serve" && adminDevApi({ preview: mode === "preview" }),
command === "build" &&
emitWorkerBundle({
outDir: path.join(WEB, ".admin-build"),
target: path.join(WEB, "worker", "generated", "admin-bundle.ts"),
}),
],
server: {
port: 5174,
strictPort: true,
// The app imports web/src/lib/ui, web/shared and the fonts from
// web/node_modules, all outside this root.
fs: { allow: [WEB] },
},
build: {
outDir: path.join(WEB, ".admin-build"),
emptyOutDir: true,
target: "es2022",
// Fonts as files, not data: URIs, so font-src 'self' covers them and the
// CSS stays small.
assetsInlineLimit: 0,
cssCodeSplit: false,
modulePreload: { polyfill: false },
sourcemap: false,
rolldownOptions: {
output: {
// ONE script. The shell's CSP trusts exactly the script carrying its
// nonce; a lazily imported chunk would need 'self' or 'strict-dynamic'.
codeSplitting: false,
entryFileNames: "assets/app-[hash].js",
assetFileNames: "assets/[name]-[hash][extname]",
},
},
},
}));
+1 -1
View File
@@ -70,7 +70,7 @@ const FIXTURE: Record<string, GameSeed> = Object.fromEntries(
}),
);
export function readSeeds(dataDir: string): Record<string, GameSeed> {
function readSeeds(dataDir: string): Record<string, GameSeed> {
const indexPath = join(dataDir, "index.json");
if (!existsSync(indexPath)) {
throw new Error(
+3 -1
View File
@@ -16,7 +16,9 @@
"src/**/*.{ts,svelte}",
"src/**/*.css",
"worker/**/*.ts",
"shared/**/*.ts"
"shared/**/*.ts",
"admin/**/*.{ts,svelte}",
"build/**/*.ts"
],
// Ambient declaration for the Worker secrets, which wrangler types cannot
// see because secrets are not in wrangler.jsonc. Nothing imports it by
+1
View File
@@ -49,6 +49,7 @@
"typescript": "^6.0.3",
"unified": "^11.0.5",
"vite": "^8.0.16",
"vite-plugin-pwa": "^1.3.0",
"vitest": "^5.0.0",
"wrangler": "^4.130.0"
}
+8 -3
View File
@@ -5,12 +5,15 @@
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"dev:admin": "vite --config admin/vite.config.ts",
"preview:admin": "npm run build:admin && vite --config admin/vite.config.ts --mode preview",
"build": "vite build && npm run build:admin",
"build:admin": "vite build --config admin/vite.config.ts",
"build:desktop": "vite build",
"build:mobile": "vite build",
"analyze": "vite build --mode analyze",
"preview": "vite preview",
"typecheck": "npm run check && tsc -p tsconfig.worker.json && tsc -p tsconfig.test.json",
"typecheck": "npm run build:admin && npm run check && npm run check:admin && tsc -p admin/tsconfig.node.json && tsc -p admin/tsconfig.test.json && tsc -p tsconfig.worker.json && tsc -p tsconfig.test.json",
"knip": "knip",
"test": "vitest run",
"test:watch": "vitest",
@@ -22,8 +25,9 @@
"tauri:android:build": "tauri android build --apk",
"typecheck:worker": "tsc -p tsconfig.worker.json",
"cf:types": "wrangler types",
"cf:check": "wrangler deploy --dry-run",
"cf:check": "npm run build:admin && wrangler deploy --dry-run",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:admin": "svelte-check --tsconfig ./admin/tsconfig.json",
"fonts": "python scripts/gen-fontface.py"
},
"dependencies": {
@@ -68,6 +72,7 @@
"typescript": "^6.0.3",
"unified": "^11.0.5",
"vite": "^8.0.16",
"vite-plugin-pwa": "^1.3.0",
"vitest": "^5.0.0",
"wrangler": "^4.130.0"
},
+16
View File
@@ -14,6 +14,8 @@
* - the full consent dialog in every page (the gate rendered before storage
* was read).
*
* It also fails if any part of the admin SPA reached dist/.
*
* Usage (from web/, after a build):
* node scripts/verify-dist.mjs common checks
* node scripts/verify-dist.mjs --web + web-only expectations
@@ -80,6 +82,20 @@ for (const file of html) {
if (seen.includes(CONSENT_TITLE)) fail(`${rel}: prerendered consent dialog ("${CONSENT_TITLE}")`);
}
/* ── the admin never ships in dist/ ───────────────────────────────────── */
// dist/ is served to anyone, precached by the service worker and packaged into
// the Tauri apps. The admin SPA is embedded in the Worker instead
// (admin/build/emit-worker-bundle.ts), so no trace of it may appear here.
if (existsSync(join(DIST, "admin"))) fail("dist/admin exists - the admin SPA must only be served by the Worker");
const TEXT_EXT = /\.(html|js|mjs|css|json|webmanifest|txt|xml|map)$/;
for (const file of files) {
if (!TEXT_EXT.test(file)) continue;
if (readFileSync(file, "utf-8").includes("/api/admin/")) {
fail(`${relative(DIST, file).replace(/\\/g, "/")}: references /api/admin/ - admin code leaked into the public build`);
}
}
/* ── per-flavour expectations ─────────────────────────────────────────── */
const gamesDir = join(DIST, "games");
+13
View File
@@ -0,0 +1,13 @@
import { readdirSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { ADMIN_MIGRATIONS } from "./admin-api";
describe("ADMIN_MIGRATIONS", () => {
it("lists exactly the migration files the Worker ships", () => {
const files = readdirSync(join(__dirname, "..", "worker", "migrations"))
.filter((f) => f.endsWith(".sql"))
.sort();
expect([...ADMIN_MIGRATIONS]).toEqual(files);
});
});
+212
View File
@@ -0,0 +1,212 @@
/**
* Response shapes of /api/admin/*, as the admin SPA consumes them.
*
* Types only. The handlers in worker/routes/admin.ts and edit.ts build these
* objects; when a handler's response changes, change the matching type here
* and svelte-check points at every screen that reads it.
*/
import type { DecideAction, QueueStatus, SkippedRow } from "./queue-rules";
export interface QueueItem {
id: string;
appid: string;
link: string;
name: string;
header_image: string;
release_date: string;
app_type: string;
is_free: number;
health_status: string;
reviews_raw: string;
reviews_pct: number | null;
current_players_raw: string;
current_players_num: number | null;
source: string;
status: QueueStatus;
decided_by: string | null;
decided_at: string | null;
reject_reason: string | null;
first_seen_at: string;
last_seen_at: string;
seen_count: number;
/** The GAME is already in the catalogue (per appid, not per row). */
published: boolean;
}
export interface QueueResponse {
status: QueueStatus | "all";
offset: number;
limit: number;
q: string;
sort: string;
total: number;
count: number;
items: QueueItem[];
maxDecide: number;
}
export interface StatsResponse {
queue: Partial<Record<QueueStatus, number>>;
commits: Record<string, number>;
}
export interface Candidate {
id: string;
appid: string;
link: string;
name: string;
header_image: string;
status: QueueStatus;
reject_reason: string | null;
decided_by: string | null;
decided_at: string | null;
payload_json: string;
first_seen_at: string;
last_seen_at: string;
seen_count: number;
health_status: string;
app_type: string;
is_free: number;
source: string;
published: boolean;
decision: { decision: "approved" | "rejected"; reason: string | null; decided_by: string | null; decided_at: string } | null;
siblings: {
id: string;
status: QueueStatus;
reject_reason: string | null;
decided_by: string | null;
decided_at: string | null;
first_seen_at: string;
}[];
}
export interface DecideResponse {
action: DecideAction;
decided: number;
decidedIds: string[];
skipped: SkippedRow[];
commit?: string | null;
appended?: number;
already_queued?: number;
}
export interface ReopenResponse {
reopened: string;
appid: string | null;
}
export interface ReconcileResponse {
checked: number;
published: number;
removed: number;
stale: number;
swept: number;
skipped?: string;
}
export interface CommitJob {
id: string;
kind: string;
status: "pending" | "committed" | "conflict" | "failed";
target_path: string;
commit_sha: string | null;
error: string | null;
requested_by: string | null;
created_at: string;
finished_at: string | null;
}
export interface AuditEntry {
id: number;
actor: string;
action: string;
target: string | null;
detail_json: string;
created_at: string;
}
export interface Paged<T> {
items: T[];
total: number;
limit: number;
offset: number;
}
/**
* The D1 migrations this build expects, by file name, so the health page can
* name the ones not applied yet. admin-api.test.ts holds it equal to
* worker/migrations/.
*/
export const ADMIN_MIGRATIONS = ["0001_init.sql", "0002_admin_state.sql"] as const;
export interface HealthResponse {
ok: boolean;
actor: string;
retentionDays: number;
d1?: "ok" | "error";
github?: string;
queue?: Partial<Record<QueueStatus, number>>;
migrations?: string[] | null;
lock?: { owner: string; expires_at: string } | null;
}
export interface MeResponse {
email: string;
isServiceToken: boolean;
}
export const MANUAL_FIELDS = [
"genre",
"type_game",
"safe",
"anti_cheat",
"is_kernel_ac",
"anti_cheat_note",
"notes",
] as const;
export type ManualField = (typeof MANUAL_FIELDS)[number];
export interface OverrideEntry {
value: unknown;
was: unknown;
set_by?: string;
set_at?: string;
reason?: string;
retired_by?: string;
retired_at?: string;
}
export interface GameResponse {
appid: string;
link: string;
name: string;
header_image: string;
release_date: string;
status: string;
is_dead: boolean;
fields: Record<ManualField, unknown>;
override: { fields?: Record<string, OverrideEntry>; retired?: Record<string, OverrideEntry> } | null;
deletable: { ok: boolean; reason: string };
}
export interface GenresResponse {
genres: { genre: string; count: number }[];
}
export interface ByGenreResponse {
genre: string;
limit: number;
offset: number;
total: number;
items: { appid: string; name: string; genre: string; header_image: string; release_date: string }[];
}
export interface EditResponse {
appids: string[];
commit: string | null;
job: string;
set?: string[];
retired?: string[];
deleted?: boolean;
applied?: boolean;
}
+14
View File
@@ -0,0 +1,14 @@
/**
* Every page the admin SPA can render, by exact path.
*
* The Worker serves the app shell for exactly these (worker/routes/admin-spa.ts)
* and 404s everything else under /admin - the old Worker served the queue page
* for any /admin/* path, so a typo like /admin/edti rendered the queue. The
* SPA's router holds the same list, and a test keeps the two equal.
*/
export const ADMIN_ROUTES = ["/admin", "/admin/edit", "/admin/jobs", "/admin/audit", "/admin/health"] as const;
export type AdminRoute = (typeof ADMIN_ROUTES)[number];
export function isAdminRoute(path: string): path is AdminRoute {
return (ADMIN_ROUTES as readonly string[]).includes(path);
}
+6 -227
View File
@@ -1,4 +1,7 @@
@import "tailwindcss";
/* source("."): only src/ is scanned for class names. Without it Tailwind
auto-detects across all of web/ - worker/, admin/ and scripts/ included -
and the admin SPA's classes would ship in every public page's CSS. */
@import "tailwindcss" source(".");
/* ── Fonts ────────────────────────────────────────────────────────────────
Self-hosted, and actually loaded. index.css used to declare
@@ -18,229 +21,5 @@
───────────────────────────────────────────────────────────────────────── */
@import "./fonts.css";
/* v4 has no `darkMode: ["class"]` config key; this is the equivalent. */
@custom-variant dark (&:where(.dark, .dark *));
/* ── Design tokens ────────────────────────────────────────────────────────
The palette rework the previous file deferred, in its own words: "Kept as
raw HSL channel triples, byte-for-byte as they were under Tailwind 3, so
this migration is provably visual-neutral. The palette rework is a separate
change." This is that change.
Still raw HSL channels, because two things depend on the format:
`@theme inline` needs them bare so `bg-primary/15` resolves through
color-mix(), and lib/chart-theme.ts reads them at call time with
getComputedStyle and wraps them in hsl().
The hue moved off the stock Tailwind sky-blue. Steam's own surfaces are
blue-grey, so a blue accent on a dark blue-grey field is exactly the
generic look this rework exists to fix. The accent is a warm amber, which
reads as "free" rather than "corporate", sits far from every meaning-bearing
colour below, and stays legible on both grounds.
───────────────────────────────────────────────────────────────────────── */
:root {
/* Neutrals: a hint of warmth (hue 40) rather than dead grey, so the amber
accent looks intentional instead of pasted on. */
--background: 40 30% 98%;
--foreground: 30 12% 12%;
--card: 0 0% 100%;
--card-foreground: 30 12% 12%;
--surface-2: 40 22% 95%;
--primary: 28 88% 42%;
--primary-foreground: 40 60% 99%;
--secondary: 40 20% 94%;
--secondary-foreground: 30 14% 18%;
--muted: 40 20% 94%;
--muted-foreground: 32 8% 42%;
--accent: 40 24% 92%;
--accent-foreground: 30 14% 18%;
/* Meaning-bearing. These are NOT decoration and do not follow the accent:
review scores, safety flags and anti-cheat tiers all read through them,
and a reader has to be able to tell them apart at a glance. */
--destructive: 358 68% 47%;
--destructive-foreground: 0 0% 100%;
--success: 152 58% 32%;
--warning: 36 92% 38%;
--info: 205 80% 40%;
--border: 38 18% 87%;
--border-strong: 36 16% 76%;
--input: 38 18% 87%;
--ring: 28 88% 42%;
--radius: 0.5rem;
}
.dark {
/* Near-black with the same warm hue, not the blue-black of every other
dark theme. */
--background: 30 14% 7%;
--foreground: 40 20% 95%;
--card: 30 13% 10%;
--card-foreground: 40 20% 95%;
--surface-2: 30 12% 14%;
--primary: 34 96% 58%;
--primary-foreground: 30 40% 8%;
--secondary: 30 10% 18%;
--secondary-foreground: 40 20% 95%;
--muted: 30 11% 15%;
--muted-foreground: 38 10% 65%;
--accent: 30 10% 19%;
--accent-foreground: 40 20% 95%;
--destructive: 358 72% 62%;
--destructive-foreground: 40 20% 96%;
--success: 152 56% 50%;
--warning: 38 94% 60%;
--info: 204 88% 62%;
--border: 30 10% 19%;
--border-strong: 30 9% 29%;
--input: 30 10% 19%;
--ring: 34 96% 58%;
}
/* The v4 replacement for `theme.extend`. `inline` so the generated utilities
reference the custom properties directly, which keeps opacity modifiers
(bg-primary/15) resolving through color-mix() and lets the .dark block
re-resolve per element. */
@theme inline {
--color-border: hsl(var(--border));
--color-input: hsl(var(--input));
--color-ring: hsl(var(--ring));
--color-background: hsl(var(--background));
--color-foreground: hsl(var(--foreground));
--color-primary: hsl(var(--primary));
--color-primary-foreground: hsl(var(--primary-foreground));
--color-secondary: hsl(var(--secondary));
--color-secondary-foreground: hsl(var(--secondary-foreground));
--color-destructive: hsl(var(--destructive));
--color-destructive-foreground: hsl(var(--destructive-foreground));
--color-muted: hsl(var(--muted));
--color-muted-foreground: hsl(var(--muted-foreground));
--color-accent: hsl(var(--accent));
--color-accent-foreground: hsl(var(--accent-foreground));
--color-card: hsl(var(--card));
--color-card-foreground: hsl(var(--card-foreground));
--color-surface-2: hsl(var(--surface-2));
--color-border-strong: hsl(var(--border-strong));
--color-success: hsl(var(--success));
--color-warning: hsl(var(--warning));
--color-info: hsl(var(--info));
--radius-lg: var(--radius);
--radius-md: calc(var(--radius) - 2px);
--radius-sm: calc(var(--radius) - 4px);
/* The fallbacks matter: a variable font is a separate request, and these are
what render during it. */
--font-display: "Bricolage Grotesque Variable", "IBM Plex Sans Variable", system-ui, sans-serif;
--font-sans: "IBM Plex Sans Variable", system-ui, -apple-system, "Segoe UI", sans-serif;
--font-mono: "JetBrains Mono Variable", ui-monospace, "Cascadia Code", monospace;
}
@utility container {
width: 100%;
margin-inline: auto;
padding-inline: 1rem;
@media (width >= 40rem) { max-width: 40rem; }
@media (width >= 48rem) { max-width: 48rem; }
@media (width >= 64rem) { max-width: 64rem; }
@media (width >= 80rem) { max-width: 80rem; }
@media (width >= 1400px) { max-width: 1400px; }
}
@utility scrollbar-thin {
scrollbar-width: thin;
}
/* Numbers that sit in a column must not shift width between rows.
Measured, not assumed: IBM Plex Sans renders every digit at the SAME advance
width by default (all ten measured at 24px at font-size:40px), so its figures
are already tabular and this utility is currently a no-op. It is kept anyway
- it states the requirement, costs nothing, and is what stops the table
going ragged if the body face is ever swapped for one whose default figures
are proportional. */
@utility tnum {
font-variant-numeric: tabular-nums;
font-feature-settings: "tnum" 1;
}
@layer base {
/* v4 defaults borders to currentColor instead of gray-200; this keeps every
border on the token. */
* {
@apply border-border;
}
html {
/* Anchor navigation and in-page jumps land below the sticky header rather
than under it. */
scroll-padding-top: 5rem;
}
body {
@apply bg-background text-foreground;
font-family: var(--font-sans);
font-feature-settings: "rlig" 1, "calt" 1;
text-rendering: optimizeLegibility;
}
h1, h2, h3, .font-display {
font-family: var(--font-display);
/* Bricolage is a variable face with an optical-size axis. Letting it track
the rendered size is the whole reason to choose it over a static
display font. */
font-optical-sizing: auto;
letter-spacing: -0.015em;
}
code, kbd, pre, samp {
font-family: var(--font-mono);
}
/* index.css never had any of the next three. */
/* Visible keyboard focus everywhere, without the permanent outline that
makes mouse users disable it. */
:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
border-radius: calc(var(--radius) - 2px);
}
/* Respect the OS setting rather than animating regardless. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
::-webkit-scrollbar {
@apply h-2 w-2;
}
::-webkit-scrollbar-track {
@apply bg-transparent;
}
::-webkit-scrollbar-thumb {
@apply rounded-full bg-muted hover:bg-muted-foreground/30;
}
}
/* Keyboard users get to the content without tabbing the whole nav first. */
.skip-link {
@apply sr-only;
}
.skip-link:focus-visible {
@apply not-sr-only fixed left-4 top-4 z-50 rounded-md bg-primary px-4 py-2
font-medium text-primary-foreground shadow-lg;
}
/* Tokens, theme mapping, utilities and base styles: shared with the admin SPA. */
@import "./styles/theme.css";
+1 -1
View File
@@ -68,7 +68,7 @@ describe("zrender can parse every chart colour", () => {
});
it("every colour token, in both themes, after conversion", () => {
const css = readFileSync(join(SRC, "index.css"), "utf-8");
const css = readFileSync(join(SRC, "styles", "theme.css"), "utf-8");
let checked = 0;
for (const selector of [":root", ".dark"]) {
for (const [name, raw] of tokensIn(css, selector)) {
+231
View File
@@ -0,0 +1,231 @@
/* The design system shared by the public app (src/index.css) and the admin
SPA (admin/src/admin.css): tokens, Tailwind theme mapping, utilities and
base styles. Neither entry point should redefine any of this - a token
changed here changes both, which is the point of the file. */
/* v4 has no `darkMode: ["class"]` config key; this is the equivalent. */
@custom-variant dark (&:where(.dark, .dark *));
/* ── Design tokens ────────────────────────────────────────────────────────
The palette rework the previous file deferred, in its own words: "Kept as
raw HSL channel triples, byte-for-byte as they were under Tailwind 3, so
this migration is provably visual-neutral. The palette rework is a separate
change." This is that change.
Still raw HSL channels, because two things depend on the format:
`@theme inline` needs them bare so `bg-primary/15` resolves through
color-mix(), and lib/chart-theme.ts reads them at call time with
getComputedStyle and wraps them in hsl().
The hue moved off the stock Tailwind sky-blue. Steam's own surfaces are
blue-grey, so a blue accent on a dark blue-grey field is exactly the
generic look this rework exists to fix. The accent is a warm amber, which
reads as "free" rather than "corporate", sits far from every meaning-bearing
colour below, and stays legible on both grounds.
───────────────────────────────────────────────────────────────────────── */
:root {
/* Neutrals: a hint of warmth (hue 40) rather than dead grey, so the amber
accent looks intentional instead of pasted on. */
--background: 40 30% 98%;
--foreground: 30 12% 12%;
--card: 0 0% 100%;
--card-foreground: 30 12% 12%;
--surface-2: 40 22% 95%;
--primary: 28 88% 42%;
--primary-foreground: 40 60% 99%;
--secondary: 40 20% 94%;
--secondary-foreground: 30 14% 18%;
--muted: 40 20% 94%;
--muted-foreground: 32 8% 42%;
--accent: 40 24% 92%;
--accent-foreground: 30 14% 18%;
/* Meaning-bearing. These are NOT decoration and do not follow the accent:
review scores, safety flags and anti-cheat tiers all read through them,
and a reader has to be able to tell them apart at a glance. */
--destructive: 358 68% 47%;
--destructive-foreground: 0 0% 100%;
--success: 152 58% 32%;
--warning: 36 92% 38%;
--info: 205 80% 40%;
--border: 38 18% 87%;
--border-strong: 36 16% 76%;
--input: 38 18% 87%;
--ring: 28 88% 42%;
--radius: 0.5rem;
}
.dark {
/* Near-black with the same warm hue, not the blue-black of every other
dark theme. */
--background: 30 14% 7%;
--foreground: 40 20% 95%;
--card: 30 13% 10%;
--card-foreground: 40 20% 95%;
--surface-2: 30 12% 14%;
--primary: 34 96% 58%;
--primary-foreground: 30 40% 8%;
--secondary: 30 10% 18%;
--secondary-foreground: 40 20% 95%;
--muted: 30 11% 15%;
--muted-foreground: 38 10% 65%;
--accent: 30 10% 19%;
--accent-foreground: 40 20% 95%;
--destructive: 358 72% 62%;
--destructive-foreground: 40 20% 96%;
--success: 152 56% 50%;
--warning: 38 94% 60%;
--info: 204 88% 62%;
--border: 30 10% 19%;
--border-strong: 30 9% 29%;
--input: 30 10% 19%;
--ring: 34 96% 58%;
}
/* The v4 replacement for `theme.extend`. `inline` so the generated utilities
reference the custom properties directly, which keeps opacity modifiers
(bg-primary/15) resolving through color-mix() and lets the .dark block
re-resolve per element. */
@theme inline {
--color-border: hsl(var(--border));
--color-input: hsl(var(--input));
--color-ring: hsl(var(--ring));
--color-background: hsl(var(--background));
--color-foreground: hsl(var(--foreground));
--color-primary: hsl(var(--primary));
--color-primary-foreground: hsl(var(--primary-foreground));
--color-secondary: hsl(var(--secondary));
--color-secondary-foreground: hsl(var(--secondary-foreground));
--color-destructive: hsl(var(--destructive));
--color-destructive-foreground: hsl(var(--destructive-foreground));
--color-muted: hsl(var(--muted));
--color-muted-foreground: hsl(var(--muted-foreground));
--color-accent: hsl(var(--accent));
--color-accent-foreground: hsl(var(--accent-foreground));
--color-card: hsl(var(--card));
--color-card-foreground: hsl(var(--card-foreground));
--color-surface-2: hsl(var(--surface-2));
--color-border-strong: hsl(var(--border-strong));
--color-success: hsl(var(--success));
--color-warning: hsl(var(--warning));
--color-info: hsl(var(--info));
--radius-lg: var(--radius);
--radius-md: calc(var(--radius) - 2px);
--radius-sm: calc(var(--radius) - 4px);
/* The fallbacks matter: a variable font is a separate request, and these are
what render during it. */
--font-display: "Bricolage Grotesque Variable", "IBM Plex Sans Variable", system-ui, sans-serif;
--font-sans: "IBM Plex Sans Variable", system-ui, -apple-system, "Segoe UI", sans-serif;
--font-mono: "JetBrains Mono Variable", ui-monospace, "Cascadia Code", monospace;
}
@utility container {
width: 100%;
margin-inline: auto;
padding-inline: 1rem;
@media (width >= 40rem) { max-width: 40rem; }
@media (width >= 48rem) { max-width: 48rem; }
@media (width >= 64rem) { max-width: 64rem; }
@media (width >= 80rem) { max-width: 80rem; }
@media (width >= 1400px) { max-width: 1400px; }
}
@utility scrollbar-thin {
scrollbar-width: thin;
}
/* Numbers that sit in a column must not shift width between rows.
Measured, not assumed: IBM Plex Sans renders every digit at the SAME advance
width by default (all ten measured at 24px at font-size:40px), so its figures
are already tabular and this utility is currently a no-op. It is kept anyway
- it states the requirement, costs nothing, and is what stops the table
going ragged if the body face is ever swapped for one whose default figures
are proportional. */
@utility tnum {
font-variant-numeric: tabular-nums;
font-feature-settings: "tnum" 1;
}
@layer base {
/* v4 defaults borders to currentColor instead of gray-200; this keeps every
border on the token. */
* {
@apply border-border;
}
html {
/* Anchor navigation and in-page jumps land below the sticky header rather
than under it. */
scroll-padding-top: 5rem;
}
body {
@apply bg-background text-foreground;
font-family: var(--font-sans);
font-feature-settings: "rlig" 1, "calt" 1;
text-rendering: optimizeLegibility;
}
h1, h2, h3, .font-display {
font-family: var(--font-display);
/* Bricolage is a variable face with an optical-size axis. Letting it track
the rendered size is the whole reason to choose it over a static
display font. */
font-optical-sizing: auto;
letter-spacing: -0.015em;
}
code, kbd, pre, samp {
font-family: var(--font-mono);
}
/* index.css never had any of the next three. */
/* Visible keyboard focus everywhere, without the permanent outline that
makes mouse users disable it. */
:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
border-radius: calc(var(--radius) - 2px);
}
/* Respect the OS setting rather than animating regardless. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
::-webkit-scrollbar {
@apply h-2 w-2;
}
::-webkit-scrollbar-track {
@apply bg-transparent;
}
::-webkit-scrollbar-thumb {
@apply rounded-full bg-muted hover:bg-muted-foreground/30;
}
}
/* Keyboard users get to the content without tabbing the whole nav first. */
.skip-link {
@apply sr-only;
}
.skip-link:focus-visible {
@apply not-sr-only fixed left-4 top-4 z-50 rounded-md bg-primary px-4 py-2
font-medium text-primary-foreground shadow-lg;
}
+1 -1
View File
@@ -18,5 +18,5 @@
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true
},
"include": ["worker/**/*.test.ts", "worker", "shared", "worker-configuration.d.ts"]
"include": ["worker/**/*.test.ts", "worker", "shared", "admin/mock/**/*.test.ts", "worker-configuration.d.ts"]
}
+9 -9
View File
@@ -15,8 +15,10 @@ import { jsonError, withSecurityHeaders } from "./lib/http";
import { verifyAccessJwt, AccessUnavailableError } from "./lib/access";
import { handleAdminApi } from "./routes/admin";
import { handleIngestApi } from "./routes/ingest";
import { adminPage } from "./routes/admin-ui";
import { editPage } from "./routes/edit-ui";
import { serveAdmin } from "./routes/admin-spa";
// Generated by `npm run build:admin` (gitignored); `npm run build` runs it
// before `wrangler deploy`, and typecheck runs it before tsc.
import { ADMIN_BUNDLE } from "./generated/admin-bundle";
import { reconcileApproved } from "./lib/reconcile";
import { defaultAdminDeps } from "./lib/deps";
import { isPruneTick, pruneAdminHistory } from "./lib/prune";
@@ -207,13 +209,11 @@ async function route(
if (isIngestApi) return handleIngestApi(request, url, env, who);
if (isAdminApi) return handleAdminApi(request, url, env, who);
// /admin/edit corrects a game already in the catalogue. Same Access gate
// as the queue; it writes only data/overrides/<appid>.json.
if (pathname === "/admin/edit") return editPage(who.email);
// Served from the Worker, never from ASSETS. Falling through to the SPA
// handler here would serve the PUBLIC app shell at an admin URL.
return adminPage(who.email);
// The admin SPA: its shell for the five admin routes, its hashed assets,
// and a 404 for anything else under /admin. Served from the Worker, never
// from ASSETS - falling through to the asset server here would serve the
// PUBLIC app shell at an admin URL, and dist/ is readable by anyone.
return serveAdmin(request, url, ADMIN_BUNDLE);
}
if (pathname.startsWith("/api/")) {
+26
View File
@@ -0,0 +1,26 @@
/**
* The shape of worker/generated/admin-bundle.ts, which admin/build/
* emit-worker-bundle.ts writes at the end of `npm run build:admin`.
*
* That file is GITIGNORED and regenerated on every build, so the Worker never
* ships an admin UI older than its own source. There is deliberately no
* committed stub: a missing bundle fails typecheck and `wrangler deploy`
* loudly instead of deploying an empty admin.
*/
export interface AdminAsset {
contentType: string;
/** Text assets are stored as-is; fonts and images as base64. */
encoding: "utf8" | "base64";
body: string;
}
export interface AdminBundle {
/** Content hash of the shell and asset list, for logs and cache debugging. */
buildId: string;
/** index.html, with `__ADMIN_NONCE__` where the per-response nonce goes. */
shell: string;
/** By request path: "/admin/assets/app-1a2b3c.js". */
assets: Record<string, AdminAsset>;
}
export const NONCE_PLACEHOLDER = "__ADMIN_NONCE__";
-62
View File
@@ -36,68 +36,6 @@ export function withSecurityHeaders(res: Response): Response {
return out;
}
/**
* Steam serves capsule art from two hosts, and roughly 44% of the catalogue
* uses the fastly one. Allowlisting only akamai is a mistake this repo has
* already made once, in the service-worker cache rules.
*/
const ADMIN_IMG_HOSTS = [
"https://shared.akamai.steamstatic.com",
"https://shared.fastly.steamstatic.com",
"https://cdn.akamai.steamstatic.com",
].join(" ");
/**
* The admin pages' Content-Security-Policy.
*
* This was duplicated byte-for-byte in admin-ui.ts and edit-ui.ts, which is one
* copy too many for the policy protecting the only origin that holds a
* repository-write credential: a hardening change applied to one file and not
* the other is invisible.
*
* `default-src 'none'` already denies fonts, media, workers, frames and
* objects by fallback. object-src is repeated explicitly anyway because it is
* the directive whose absence has the worst consequences and the one a reader
* will look for. Note there is deliberately no font-src: these pages use the
* system stack, and the directive should appear the day a font is actually
* served, not before.
*/
function adminCsp(nonce: string): string {
return [
"default-src 'none'",
`script-src 'nonce-${nonce}'`,
"style-src 'unsafe-inline'",
`img-src ${ADMIN_IMG_HOSTS} data:`,
"connect-src 'self'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
].join("; ");
}
/**
* Response wrapper for the two HTML pages the Worker serves.
*
* Carries the nonce CSP plus SECURITY_HEADERS, and adds
* Cross-Origin-Opener-Policy, which public/_headers sets for the SPA but which
* the admin pages were missing - so an admin window opened from elsewhere
* stayed in the opener's browsing-context group.
*/
export function adminHtmlResponse(body: string, nonce: string): Response {
return new Response(body, {
status: 200,
headers: {
"Content-Type": "text/html; charset=utf-8",
// Per-identity and mutable; never let this sit in any cache.
"Cache-Control": "no-store, no-cache, must-revalidate",
"Content-Security-Policy": adminCsp(nonce),
"Cross-Origin-Opener-Policy": "same-origin",
...SECURITY_HEADERS,
},
});
}
/**
* Clamp a caller-supplied `limit` query parameter.
*
+82
View File
@@ -0,0 +1,82 @@
import { describe, expect, it } from "vitest";
import { adminSpaCsp, serveAdmin } from "./admin-spa";
import type { AdminBundle } from "../lib/admin-bundle";
import { ADMIN_ROUTES } from "../../shared/admin-routes";
const bundle: AdminBundle = {
buildId: "test-build",
shell:
'<!doctype html><html><head><link rel="stylesheet" href="/admin/assets/app-1.css"></head>' +
'<body><div id="app"></div><script type="module" nonce="__ADMIN_NONCE__" src="/admin/assets/app-1.js"></script></body></html>',
assets: {
"/admin/assets/app-1.js": { contentType: "text/javascript; charset=utf-8", encoding: "utf8", body: "console.log(1)" },
"/admin/assets/app-1.css": { contentType: "text/css; charset=utf-8", encoding: "utf8", body: "body{}" },
"/admin/assets/font-1.woff2": { contentType: "font/woff2", encoding: "base64", body: btoa("wOF2") },
},
};
function get(path: string, method = "GET") {
const url = new URL(`https://free-steam-games.win${path}`);
return serveAdmin(new Request(url, { method }), url, bundle);
}
describe("the admin shell", () => {
it.each(ADMIN_ROUTES.map((r) => [r]))("serves %s", async (route) => {
const res = get(route);
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toContain("text/html");
expect(res.headers.get("Cache-Control")).toContain("no-store");
});
it("puts a fresh nonce on the script, and the same one in the CSP", async () => {
const a = get("/admin");
const b = get("/admin");
const nonceOf = async (res: Response) => /nonce="([a-f0-9]{32})"/.exec(await res.text())?.[1];
const na = await nonceOf(a);
expect(na).toBeTruthy();
expect(a.headers.get("Content-Security-Policy")).toContain(`'nonce-${na}'`);
expect(await nonceOf(b)).not.toBe(na);
});
it("has a CSP that allows no inline or foreign script", () => {
const csp = adminSpaCsp("abc");
expect(csp).toContain("default-src 'none'");
expect(csp).toContain("object-src 'none'");
expect(csp).toContain("frame-ancestors 'none'");
expect(csp).toMatch(/script-src 'nonce-abc'(;|$)/);
expect(csp).not.toMatch(/script-src[^;]*'unsafe-inline'/);
});
it("redirects the trailing slash, keeping the query", () => {
const res = get("/admin/?status=failed");
expect(res.status).toBe(308);
expect(res.headers.get("Location")).toBe("/admin?status=failed");
});
});
describe("assets and everything else", () => {
it("serves exact asset paths immutably and privately", async () => {
const js = get("/admin/assets/app-1.js");
expect(js.status).toBe(200);
expect(js.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable");
expect(await js.text()).toBe("console.log(1)");
const font = get("/admin/assets/font-1.woff2");
expect(new TextDecoder().decode(await font.arrayBuffer())).toBe("wOF2");
});
it("404s unknown admin paths instead of serving the queue", () => {
// ("/admin/assets/../assets/app-1.js" is not here: the URL parser
// normalises it to the real asset path before the Worker ever sees it.)
for (const path of ["/admin/edti", "/admin/assets/", "/admin//assets/app-1.js", "/admin/assets/nope.js", "/admin/assets/__proto__"]) {
expect(get(path).status, path).toBe(404);
}
});
it("answers HEAD without a body and refuses writes", async () => {
const head = get("/admin", "HEAD");
expect(head.status).toBe(200);
expect(await head.text()).toBe("");
expect(get("/admin", "POST").status).toBe(405);
});
});
+129
View File
@@ -0,0 +1,129 @@
/**
* Serves the admin SPA - ONLY after worker/index.ts has verified the Access
* identity, the credential class and, for writes, the CSRF checks.
*
* The app is built by admin/vite.config.ts and embedded into the Worker bundle
* (worker/generated/admin-bundle.ts), not placed in dist/. That keeps every
* byte of it off the public static-asset server, out of the service worker's
* precache and out of the Tauri apps - the asset server would hand dist/ files
* to anyone, and run_worker_first is the only thing that would have stood
* between the public and the admin code.
*
* GET /admin, /admin/edit, /admin/jobs, /admin/audit, /admin/health
* -> the shell, with a fresh nonce on its one module script
* GET /admin/assets/<exact name>
* -> that asset, immutable (the name carries a content hash)
* anything else under /admin -> 404
*/
import { SECURITY_HEADERS, jsonError } from "../lib/http";
import { NONCE_PLACEHOLDER, type AdminAsset, type AdminBundle } from "../lib/admin-bundle";
import { isAdminRoute } from "../../shared/admin-routes";
/**
* Steam serves capsule art from two hosts, and roughly 44% of the catalogue
* uses the fastly one. Allowlisting only akamai is a mistake this repo has
* already made once.
*/
const IMG_HOSTS = [
"https://shared.akamai.steamstatic.com",
"https://shared.fastly.steamstatic.com",
"https://cdn.akamai.steamstatic.com",
].join(" ");
/**
* The shell's Content-Security-Policy.
*
* script-src is the nonce alone: the one module script the shell carries is
* the whole app (the build inlines every dynamic import), so nothing else ever
* needs to execute. style-src keeps 'unsafe-inline' because Svelte clones
* templates through innerHTML and a static style="" attribute in one would
* otherwise be dropped; styles cannot run code, and the previous admin pages
* had the same allowance. Fonts and images are same-origin assets or Steam
* artwork; the API is same-origin.
*/
export function adminSpaCsp(nonce: string): string {
return [
"default-src 'none'",
`script-src 'nonce-${nonce}'`,
"style-src 'self' 'unsafe-inline'",
`img-src 'self' data: ${IMG_HOSTS}`,
"font-src 'self'",
"connect-src 'self'",
"manifest-src 'none'",
"worker-src 'none'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
].join("; ");
}
const decoded = new Map<string, Uint8Array>();
function assetBody(path: string, asset: AdminAsset): BodyInit {
if (asset.encoding === "utf8") return asset.body;
let bytes = decoded.get(path);
if (!bytes) {
const bin = atob(asset.body);
bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
decoded.set(path, bytes);
}
return bytes;
}
function notFound(): Response {
return new Response("Not found", {
status: 404,
headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", ...SECURITY_HEADERS },
});
}
export function serveAdmin(request: Request, url: URL, bundle: AdminBundle): Response {
if (request.method !== "GET" && request.method !== "HEAD") {
return jsonError(405, "method not allowed");
}
const path = url.pathname;
const head = request.method === "HEAD";
if (path === "/admin/") {
return new Response(null, {
status: 308,
headers: { Location: `/admin${url.search}`, "Cache-Control": "no-store", ...SECURITY_HEADERS },
});
}
if (isAdminRoute(path)) {
// Per response, never cached: a nonce that repeats is not a nonce.
const nonce = crypto.randomUUID().replace(/-/g, "");
const html = bundle.shell.replaceAll(NONCE_PLACEHOLDER, nonce);
return new Response(head ? null : html, {
status: 200,
headers: {
"Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": adminSpaCsp(nonce),
"Cache-Control": "no-store",
"Cross-Origin-Opener-Policy": "same-origin",
"X-Admin-Build": bundle.buildId,
...SECURITY_HEADERS,
},
});
}
// Exact keys only: no normalisation, so ".." or a double slash can never
// name anything but a miss.
const asset = Object.hasOwn(bundle.assets, path) ? bundle.assets[path] : undefined;
if (asset) {
return new Response(head ? null : assetBody(path, asset), {
status: 200,
headers: {
"Content-Type": asset.contentType,
// private: these sit behind Access, so no shared cache may keep them.
"Cache-Control": "private, max-age=31536000, immutable",
...SECURITY_HEADERS,
},
});
}
return notFound();
}
-149
View File
@@ -1,149 +0,0 @@
/**
* The two Worker-rendered admin pages.
*
* These cannot be exercised by loading them: `/admin` is behind Cloudflare
* Access, so a local `wrangler dev` answers 404 and there is no way to obtain a
* valid Access JWT offline. Everything that CAN be checked without a browser is
* checked here instead — which is more than it sounds, because the pages are
* one big string and the two ways they break are a template-literal syntax
* error and an escaping mistake.
*
* The syntax case is not hypothetical: the whole document lives inside a
* TypeScript template literal, so a single backtick in a comment silently ends
* it, and a literal newline inside a JS string is a parse error the TypeScript
* compiler cannot see because to it the whole thing is just text.
*/
import { describe, it, expect } from "vitest";
import { adminPage } from "./admin-ui";
import { editPage } from "./edit-ui";
const BACKTICK = String.fromCharCode(96);
async function render(page: (actor: string) => Response, actor = "reviewer@example.com") {
const res = page(actor);
return { res, html: await res.text() };
}
/** Pull the inline script out of the rendered page. */
function inlineScript(html: string): string {
const m = /<script nonce="[a-f0-9]+">([\s\S]*?)<\/script>/.exec(html);
expect(m, "no nonced <script> found in the rendered page").not.toBeNull();
return m![1];
}
for (const [name, page] of [
["admin-ui", adminPage],
["edit-ui", editPage],
] as const) {
describe(name, () => {
it("renders an HTML document with a nonce CSP", async () => {
const { res, html } = await render(page);
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toContain("text/html");
// Per-identity and mutable: it must never sit in a cache.
expect(res.headers.get("Cache-Control")).toContain("no-store");
expect(html.startsWith("<!doctype html>")).toBe(true);
const csp = res.headers.get("Content-Security-Policy") ?? "";
expect(csp).toContain("default-src 'none'");
expect(csp).toContain("object-src 'none'");
expect(csp).toContain("frame-ancestors 'none'");
// 'unsafe-inline' on script-src would defeat the nonce entirely, on the
// one origin that holds a repository-write credential.
expect(csp).not.toContain("script-src 'unsafe-inline'");
});
it("uses the same nonce in the header and on the script tag", async () => {
const { res, html } = await render(page);
const nonce = /'nonce-([a-f0-9]+)'/.exec(res.headers.get("Content-Security-Policy") ?? "")?.[1];
expect(nonce, "no nonce in the CSP").toBeTruthy();
expect(html).toContain(`<script nonce="${nonce}">`);
});
it("issues a fresh nonce per response", async () => {
const a = page("a@example.com").headers.get("Content-Security-Policy");
const b = page("a@example.com").headers.get("Content-Security-Policy");
expect(a).not.toBe(b);
});
it("escapes the actor rather than interpolating it raw", async () => {
const { html } = await render(page, '"><img src=x onerror=alert(1)>');
expect(html).not.toContain("<img src=x onerror=alert(1)>");
expect(html).toContain("&lt;img src=x onerror=alert(1)&gt;");
});
// The failure mode this file exists for. A backtick or a literal newline
// inside a string is invisible to tsc — the page is just text to it — and
// ships a blank admin screen.
it("emits an inline script that actually parses", async () => {
const { html } = await render(page);
const js = inlineScript(html);
expect(js.length).toBeGreaterThan(500);
expect(() => new Function(js)).not.toThrow();
});
it("contains no backtick, which would end the outer template literal", async () => {
const { html } = await render(page);
expect(html.includes(BACKTICK)).toBe(false);
});
});
}
describe("admin-ui specifics", () => {
it("offers the views that previously had no UI at all", async () => {
const { html } = await render(adminPage);
// /api/admin/audit, /api/admin/health and commit_jobs existed as endpoints
// with no consumer; stats returned commit counts the page discarded.
for (const label of ["Commit jobs", "Audit log", "Health"]) {
expect(html).toContain(label);
}
});
it("knows which statuses are decidable", async () => {
const js = inlineScript((await render(adminPage)).html);
// Must mirror DECIDABLE in routes/admin.ts. If these drift, the buttons are
// enabled on tabs where every action returns 409.
expect(js).toContain('const DECIDABLE = ["pending","deferred","failed"]');
});
it("observes an Access redirect instead of following it", async () => {
const js = inlineScript((await render(adminPage)).html);
// Following the 302 from fetch() is what produced the
// cloudflareaccess.com connect-src console error.
expect(js).toContain('redirect: "manual"');
expect(js).toContain("SESSION_EXPIRED");
});
it("no longer claims every non-JSON response is an expired session", async () => {
const js = inlineScript((await render(adminPage)).html);
expect(js).not.toContain("Session expired or Access refused the request");
});
});
describe("edit-ui specifics", () => {
it("has a single page-wide busy flag", async () => {
const js = inlineScript(await editPage("a@b.c").text());
// There was none: save/saveBulk toggled only the Save button, retire()
// toggled nothing, so Retire could be double-clicked into two concurrent
// commits and tab switching stayed live mid-commit.
expect(js).toContain("function setBusy(");
expect(js).toContain("if (busy) return;");
});
it("warns before discarding an unsaved edit", async () => {
const js = inlineScript(await editPage("a@b.c").text());
expect(js).toContain("beforeunload");
});
it("clears the other mode's pending state when switching tabs", async () => {
const js = inlineScript(await editPage("a@b.c").text());
// One -> Bulk -> One used to leave `dirty` populated while recount()
// reported bulk.sel.size.
expect(js).toMatch(/if \(m !== mode\) \{[\s\S]*?dirty = \{\};[\s\S]*?bulk\.sel\.clear\(\);/);
});
it("does not report a no-op retire as success", async () => {
const js = inlineScript(await editPage("a@b.c").text());
expect(js).toContain("to retire - nothing was committed");
});
});
-714
View File
@@ -1,714 +0,0 @@
/**
* The /admin review screen, served BY THE WORKER as one self-contained page.
*
* Deliberately not part of the SPA in web/src. The public app has no sign-in
* and no editing — that was removed on purpose — so admin markup, admin logic
* and admin endpoint names have no business in a bundle every visitor
* downloads. Serving it from here also means /admin cannot fall through to the
* SPA shell if a route ever changes: worker/index.ts authenticates before it
* gets here, and there is no static asset at this path to leak.
*
* No build step and no framework: this page is a few hundred lines of DOM
* against an API that already exists, and a second toolchain to maintain would
* cost more than it saves.
*/
import { adminHtmlResponse } from "../lib/http";
export function adminPage(actor: string): Response {
// Per-response nonce. The page's only script is inline, and a nonce is what
// lets CSP stay strict without 'unsafe-inline' — which would otherwise be
// granted on the one origin that holds a repository-write credential.
const nonce = crypto.randomUUID().replace(/-/g, "");
return adminHtmlResponse(html(nonce, actor), nonce);
}
/** Escapes text interpolated into the document at render time. */
function esc(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function html(nonce: string, actor: string): string {
return `<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Review queue</title>
<style>
:root {
color-scheme: dark;
--bg: #0b0e14; --surface: #141922; --surface-2: #1c2331; --border: #2a3444;
--text: #e4e8ef; --muted: #93a0b4;
--accent: #4f9cf9; --ok: #3fb950; --warn: #d29922; --bad: #f85149;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text);
font: 14px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
a { color: var(--accent); }
header { position: sticky; top: 0; z-index: 20; background: var(--surface);
border-bottom: 1px solid var(--border); padding: 12px 20px; }
.row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
h1 { font-size: 15px; margin: 0; font-weight: 600; letter-spacing: .01em; }
.who { color: var(--muted); font-size: 12px; margin-left: auto; }
nav { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 10px; }
nav button { background: transparent; border: 1px solid transparent; color: var(--muted);
padding: 5px 11px; border-radius: 7px; cursor: pointer; font: inherit; font-size: 13px; }
nav button:hover { background: var(--surface-2); color: var(--text); }
nav button[aria-current="true"] { background: var(--surface-2); color: var(--text);
border-color: var(--border); }
nav .n { color: var(--muted); font-variant-numeric: tabular-nums; margin-left: 5px; font-size: 12px; }
main { padding: 16px 20px 120px; }
.grid { display: grid; gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(310px, 1fr)); }
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 9px;
padding: 10px; display: flex; gap: 10px; align-items: flex-start; }
.card.sel { border-color: var(--accent); background: var(--surface-2); }
.card img { width: 92px; height: 43px; object-fit: cover; border-radius: 4px;
background: var(--surface-2); flex: none; }
.card .meta { min-width: 0; flex: 1; }
.card .nm { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card .sub { color: var(--muted); font-size: 12px; margin-top: 2px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card input[type=checkbox] { width: 17px; height: 17px; accent-color: var(--accent);
cursor: pointer; flex: none; margin-top: 2px; }
.tag { display: inline-block; font-size: 11px; padding: 1px 6px; border-radius: 4px;
background: var(--surface-2); border: 1px solid var(--border); color: var(--muted); }
.bar { position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; background: var(--surface);
border-top: 1px solid var(--border); padding: 11px 20px; display: none; }
.bar.on { display: block; }
button.act { font: inherit; font-size: 13px; padding: 7px 15px; border-radius: 7px;
border: 1px solid var(--border); background: var(--surface-2); color: var(--text); cursor: pointer; }
button.act:hover:not(:disabled) { border-color: var(--muted); }
button.act:disabled { opacity: .5; cursor: not-allowed; }
button.act.go { background: var(--ok); border-color: var(--ok); color: #07130a; font-weight: 600; }
button.act.no { background: var(--bad); border-color: var(--bad); color: #1a0505; font-weight: 600; }
input[type=text], input[type=search] { font: inherit; font-size: 13px; padding: 6px 10px;
border-radius: 7px; border: 1px solid var(--border); background: var(--bg); color: var(--text); }
.msg { padding: 10px 13px; border-radius: 8px; margin-bottom: 14px; font-size: 13px;
border: 1px solid var(--border); background: var(--surface); white-space: pre-wrap; }
.msg.err { border-color: var(--bad); color: #ffb4ae; }
.msg.ok { border-color: var(--ok); color: #7ee787; }
.empty { color: var(--muted); padding: 40px 0; text-align: center; }
.pager { display: flex; gap: 10px; align-items: center; justify-content: center;
margin-top: 20px; color: var(--muted); font-size: 13px; }
select { font: inherit; font-size: 13px; padding: 6px 9px; border-radius: 7px;
border: 1px solid var(--border); background: var(--bg); color: var(--text); }
.note { color: var(--muted); font-size: 12px; }
/* reject_reason is unbounded in the schema, so an essay-length one used to
stretch the card instead of truncating. The full text is in the title. */
.tag { max-width: 190px; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap; vertical-align: bottom; margin-left: 8px; }
.linky { background: none; border: 0; color: var(--accent); cursor: pointer;
font: inherit; font-size: 12px; padding: 0 0 0 8px; text-decoration: underline; }
/* The three read-only views (commit jobs, audit log, health). */
.tbl { width: 100%; border-collapse: collapse; font-size: 12.5px;
table-layout: fixed; }
.tbl th, .tbl td { text-align: left; padding: 6px 9px; border-bottom: 1px solid var(--border);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tbl th { color: var(--muted); font-weight: 600; background: var(--surface); }
.tbl tr:hover td { background: var(--surface-2); }
dialog { background: var(--surface); color: var(--text); border: 1px solid var(--border);
border-radius: 10px; padding: 16px; max-width: min(760px, 92vw); width: 760px; }
dialog::backdrop { background: rgba(0,0,0,.6); }
dialog pre { margin: 0; max-height: 60vh; overflow: auto; font-size: 12px;
background: var(--bg); border: 1px solid var(--border); border-radius: 7px; padding: 10px;
white-space: pre-wrap; word-break: break-word; }
</style>
</head>
<body>
<header>
<div class="row">
<h1>Review queue</h1>
<input type="search" id="q" placeholder="Search every row by name or appid" style="width:260px">
<select id="sort" title="Sort order">
<option value="newest">Newest first</option>
<option value="oldest">Oldest first</option>
<option value="players">Most players</option>
<option value="reviews">Best reviews</option>
<option value="name">Name A-Z</option>
</select>
<button class="act" id="reconcile" title="Check whether approved games have appeared in data/">Reconcile</button>
<a class="act" href="/admin/edit" style="text-decoration:none" title="Correct a game already in the catalogue">Edit a game</a>
<span class="who">${esc(actor)}</span>
</div>
<nav id="views"></nav>
<nav id="tabs"></nav>
</header>
<main>
<div id="msg"></div>
<section id="queueView">
<div class="row" style="margin-bottom:12px">
<label class="row" style="gap:7px;cursor:pointer">
<input type="checkbox" id="all" style="width:17px;height:17px;accent-color:var(--accent)">
<span style="font-size:13px;color:var(--muted)">Select all on this page</span>
</label>
<span id="shown" style="font-size:13px;color:var(--muted);margin-left:auto"></span>
</div>
<div class="grid" id="grid"></div>
<div class="pager" id="pager"></div>
</section>
<section id="tableView" hidden>
<div id="tableWrap"></div>
</section>
</main>
<div class="bar" id="bar">
<div class="row">
<strong id="count">0 selected</strong>
<input type="text" id="reason" placeholder="Reason (kept with a rejection)" style="width:290px">
<span id="barNote" class="note"></span>
<span style="margin-left:auto"></span>
<button class="act" id="defer">Defer</button>
<button class="act no" id="reject">Reject</button>
<button class="act go" id="approve">Approve &amp; queue</button>
</div>
</div>
<dialog id="detail">
<div class="row" style="margin-bottom:10px">
<strong id="detailTitle">Candidate</strong>
<button class="act" id="detailClose" style="margin-left:auto">Close</button>
</div>
<pre id="detailBody"></pre>
</dialog>
<script nonce="${nonce}">
"use strict";
const PAGE = 60;
const TABS = ["pending","deferred","approved","committed","failed","rejected"];
// Mirrors DECIDABLE in routes/admin.ts. Selecting rows on any other tab and
// pressing Approve or Reject always returned 409 "no decidable rows in that
// selection", because the server guards both the read and every UPDATE with
// this set - but the buttons stayed enabled and gave no hint why.
const DECIDABLE = ["pending","deferred","failed"];
const VIEWS = [
{ id: "queue", label: "Queue" },
{ id: "jobs", label: "Commit jobs" },
{ id: "audit", label: "Audit log" },
{ id: "health", label: "Health" },
];
let view = "queue";
let status = "pending", offset = 0, items = [], sel = new Set();
let busy = false, reconciling = false;
let sortKey = "newest", query = "";
let maxDecide = 100;
// Click handlers call load() without awaiting it, so two loads can be in
// flight at once. Whoever responds LAST would otherwise win, which on a slow
// connection means clicking pending then committed can leave pending's rows
// rendered under the committed tab. Only the newest load may paint.
let seq = 0;
const $ = (id) => document.getElementById(id);
// String.fromCharCode(10) rather than an escape: this whole script lives
// inside a TypeScript template literal, where a backslash escape has to be
// doubled and is easy to get silently wrong.
const NL = String.fromCharCode(10);
const fmt = (n) => (n === null || n === undefined ? "" : Number(n).toLocaleString("en-US"));
function say(text, kind) {
$("msg").innerHTML = "";
if (!text) return;
const d = document.createElement("div");
d.className = "msg" + (kind ? " " + kind : "");
d.textContent = text;
$("msg").appendChild(d);
}
/**
* One fetch helper for the whole page.
*
* The old version treated ANY non-JSON response as an expired session. Since
* the Worker had no top-level try/catch, every server-side crash arrived as a
* Cloudflare 1101 HTML page and was therefore reported as "Session expired" -
* the most misleading diagnostic in this screen, and it hid real D1 and GitHub
* failures for as long as it existed.
*
* Two things fixed it. The Worker now always answers JSON, and this function
* distinguishes the cases: redirect:'manual' means an expired Access
* session is OBSERVED as a redirect rather than followed to
* cloudflareaccess.com - which the page CSP blocks as a connect-src violation,
* the third of the reported console errors.
*/
async function api(path, init) {
let res;
try {
res = await fetch("/api/admin/" + path, {
credentials: "same-origin",
redirect: "manual",
headers: {
"Accept": "application/json",
...(init && init.body ? { "Content-Type": "application/json" } : {}),
},
...init,
});
} catch (e) {
throw new Error("Network error reaching the admin API. Check your connection, then reload.");
}
// An opaque redirect is Access sending us to the login page. Following it
// from fetch() is what produced the cloudflareaccess.com CSP error; a
// full-page navigation is the only way to re-authenticate interactively.
if (res.type === "opaqueredirect" || res.status === 0 || res.status === 401 || res.status === 403) {
throw new Error("SESSION_EXPIRED");
}
const ct = res.headers.get("Content-Type") || "";
if (!ct.includes("application/json")) {
throw new Error("Server returned " + res.status + " and a non-JSON body. Check wrangler tail.");
}
const body = await res.json();
if (!res.ok) throw new Error(body.error || ("HTTP " + res.status));
return body;
}
function reportError(e) {
const m = String((e && e.message) || e);
if (m === "SESSION_EXPIRED") {
say("Your Cloudflare Access session expired. Reloading to sign in again...", "err");
// Full-page navigation, not fetch: Access must be able to redirect the
// document to its login flow.
setTimeout(() => window.location.reload(), 1200);
return;
}
say(m, "err");
}
function renderViews() {
$("views").innerHTML = "";
for (const v of VIEWS) {
const b = document.createElement("button");
b.textContent = v.label;
if (v.id === view) b.setAttribute("aria-current", "true");
b.addEventListener("click", () => { view = v.id; sel.clear(); load(); });
$("views").appendChild(b);
}
}
async function loadStats() {
const mine = seq;
let s = { queue: {}, commits: {} };
try { s = await api("stats"); } catch (e) { /* tabs still render with no counts */ }
if (mine !== seq) return;
$("tabs").innerHTML = "";
for (const t of TABS) {
const b = document.createElement("button");
b.textContent = t;
const n = (s.queue || {})[t] || 0;
const c = document.createElement("span");
c.className = "n";
c.textContent = n;
b.appendChild(c);
if (t === status) b.setAttribute("aria-current", "true");
b.addEventListener("click", () => { status = t; offset = 0; sel.clear(); load(); });
$("tabs").appendChild(b);
}
}
function card(it) {
const el = document.createElement("div");
el.className = "card" + (sel.has(it.id) ? " sel" : "");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.checked = sel.has(it.id);
cb.addEventListener("change", () => {
if (cb.checked) sel.add(it.id); else sel.delete(it.id);
el.classList.toggle("sel", cb.checked);
paintBar();
});
el.appendChild(cb);
if (it.header_image) {
const img = document.createElement("img");
img.src = it.header_image;
img.alt = "";
img.loading = "lazy";
img.referrerPolicy = "no-referrer";
el.appendChild(img);
}
const meta = document.createElement("div");
meta.className = "meta";
const nm = document.createElement("div");
nm.className = "nm";
// textContent, never innerHTML: every one of these strings is publisher-
// controlled text that arrived from Steam.
nm.textContent = it.name || "(no name)";
meta.appendChild(nm);
const sub = document.createElement("div");
sub.className = "sub";
// reviews_pct and current_players_num have been selected by the API since
// the schema was written and were never rendered, so the reviewer had no
// signal at all about whether a candidate was worth publishing.
const bits = [it.release_date, it.app_type, it.source];
if (it.reviews_pct !== null && it.reviews_pct !== undefined) bits.push(it.reviews_pct + "%");
if (it.current_players_num !== null && it.current_players_num !== undefined) {
bits.push(fmt(it.current_players_num) + " playing");
}
sub.textContent = bits.filter(Boolean).join(" · ");
meta.appendChild(sub);
const line = document.createElement("div");
line.className = "sub";
const a = document.createElement("a");
a.href = it.link;
a.target = "_blank";
a.rel = "noopener noreferrer";
a.textContent = it.appid;
line.appendChild(a);
const why = document.createElement("button");
why.className = "linky";
why.textContent = "details";
why.title = "The full candidate as it was proposed";
why.addEventListener("click", () => showCandidate(it.id, it.name));
line.appendChild(why);
for (const [val, title] of [[it.reject_reason, "reason"], [it.decided_by, "decided by"]]) {
if (!val) continue;
const t = document.createElement("span");
t.className = "tag";
// title as well as text: reject_reason is unbounded in the schema, so a
// long one used to stretch the card instead of truncating.
t.title = title + ": " + val;
t.textContent = val;
line.appendChild(t);
}
meta.appendChild(line);
el.appendChild(meta);
return el;
}
async function showCandidate(id, name) {
try {
const d = await api("candidate?id=" + encodeURIComponent(id));
$("detailTitle").textContent = (name || "Candidate") + " - " + d.appid;
let payload = d.payload_json;
try { payload = JSON.stringify(JSON.parse(d.payload_json), null, 2); } catch (e) { /* show raw */ }
$("detailBody").textContent =
"seen " + d.seen_count + "x, first " + d.first_seen_at + ", last " + d.last_seen_at + NL +
"health " + d.health_status + ", type " + d.app_type + ", free " + d.is_free +
", source " + d.source + NL + NL + payload;
$("detail").showModal();
} catch (e) { reportError(e); }
}
// The rows actually on screen. render() and the select-all box MUST agree on
// this: the box used to iterate the unfiltered page, so filtering to one game
// and ticking "select all" selected all 60 loaded rows while showing one card
// - and the next click approved 59 games the reviewer never saw. Filtering is
// now done by the server, so this is simply the loaded page.
function visible() { return items; }
function render() {
const show = visible();
$("grid").innerHTML = "";
if (!show.length) {
const d = document.createElement("div");
d.className = "empty";
d.textContent = query
? "No row in '" + status + "' matches " + JSON.stringify(query) + "."
: "Nothing here.";
$("grid").appendChild(d);
}
for (const it of show) $("grid").appendChild(card(it));
$("all").checked = show.length > 0 && show.every((i) => sel.has(i.id));
paintBar();
}
function paintBar() {
$("bar").classList.toggle("on", sel.size > 0);
$("count").textContent = sel.size + " selected";
const decidable = DECIDABLE.includes(status);
const requeueing = status === "failed";
$("approve").disabled = busy || !decidable;
$("reject").disabled = busy || !decidable;
$("defer").textContent = requeueing ? "Send back to pending" : "Defer";
$("defer").disabled = busy || !decidable || (!requeueing && status === "deferred");
$("barNote").textContent = decidable
? (sel.size > maxDecide ? "Over the server's limit of " + maxDecide : "")
: "Rows in '" + status + "' are already decided - nothing to do here.";
}
// keepMsg: a decision leaves a result worth reading ("commit abc1234 - 60
// appended"), and the reload that follows it must not wipe that. Only an
// explicit navigation - a tab or page change - clears the banner.
async function load(keepMsg) {
if (!keepMsg) say("");
const mine = ++seq;
renderViews();
const isQueue = view === "queue";
$("queueView").hidden = !isQueue;
$("tableView").hidden = isQueue;
$("tabs").hidden = !isQueue;
$("q").hidden = !isQueue;
$("sort").hidden = !isQueue;
if (!isQueue) { sel.clear(); paintBar(); }
try {
if (!isQueue) { await loadTable(mine); return; }
const d = await api("queue?status=" + encodeURIComponent(status) +
"&limit=" + PAGE + "&offset=" + offset +
"&sort=" + encodeURIComponent(sortKey) +
(query ? "&q=" + encodeURIComponent(query) : ""));
if (mine !== seq) return;
items = d.items || [];
if (typeof d.maxDecide === "number") maxDecide = d.maxDecide;
renderPager(d.total || 0);
$("shown").textContent = (d.total || 0) + " row(s)" + (query ? " matching" : "");
render();
await loadStats();
} catch (e) {
// A superseded request that fails is not worth reporting: the banner would
// describe a view the reviewer already navigated away from.
if (mine === seq) reportError(e);
}
}
/** Simple read-only tables for the three views that previously had no UI. */
async function loadTable(mine) {
const wrap = $("tableWrap");
wrap.innerHTML = "";
const loading = document.createElement("div");
loading.className = "empty";
loading.textContent = "Loading...";
wrap.appendChild(loading);
if (view === "health") {
const h = await api("health");
if (mine !== seq) return;
wrap.innerHTML = "";
wrap.appendChild(kv([
["overall", h.ok ? "ok" : "PROBLEM"],
["D1", h.d1],
["GitHub App", h.github],
["actor", h.actor || ""],
]));
const note = document.createElement("p");
note.className = "note";
note.textContent = "d1/github report 'ok' or 'error'. The message stays in Workers Logs on purpose - run 'wrangler tail' for the detail.";
wrap.appendChild(note);
const q = document.createElement("div");
q.className = "row";
q.style.marginTop = "14px";
for (const [k, v] of Object.entries(h.queue || {})) {
const t = document.createElement("span");
t.className = "tag";
t.textContent = k + ": " + v;
q.appendChild(t);
}
wrap.appendChild(q);
return;
}
if (view === "audit") {
const d = await api("audit?limit=200");
if (mine !== seq) return;
wrap.innerHTML = "";
wrap.appendChild(table(
["when", "actor", "action", "target", "detail"],
(d.items || []).map((r) => [r.created_at, r.actor, r.action, r.target || "", r.detail_json || ""]),
"No admin actions recorded yet.",
));
return;
}
// jobs
const d = await api("jobs?limit=200");
if (mine !== seq) return;
wrap.innerHTML = "";
wrap.appendChild(table(
["created", "kind", "status", "target", "commit", "error", "finished"],
(d.items || []).map((r) => [
r.created_at, r.kind, r.status, r.target_path,
r.commit_sha ? String(r.commit_sha).slice(0, 10) : "",
r.error || "", r.finished_at || "",
]),
"No commit jobs yet. A row is written here BEFORE each approval commit is attempted, so a 'pending' row that never finished is the evidence a commit died mid-flight.",
));
}
function kv(pairs) {
const t = document.createElement("table");
t.className = "tbl";
for (const [k, v] of pairs) {
const tr = document.createElement("tr");
const th = document.createElement("th");
th.textContent = k;
const td = document.createElement("td");
td.textContent = String(v);
tr.appendChild(th); tr.appendChild(td);
t.appendChild(tr);
}
return t;
}
function table(headers, rows, emptyText) {
if (!rows.length) {
const d = document.createElement("div");
d.className = "empty";
d.textContent = emptyText;
return d;
}
const t = document.createElement("table");
t.className = "tbl";
const hr = document.createElement("tr");
for (const h of headers) {
const th = document.createElement("th");
th.textContent = h;
hr.appendChild(th);
}
t.appendChild(hr);
for (const r of rows) {
const tr = document.createElement("tr");
for (const c of r) {
const td = document.createElement("td");
// textContent throughout: detail_json and error carry server text, and
// reject_reason carries reviewer text.
td.textContent = String(c);
td.title = String(c);
tr.appendChild(td);
}
t.appendChild(tr);
}
return t;
}
function renderPager(total) {
$("pager").innerHTML = "";
if (total <= PAGE) return;
const mk = (label, to, on) => {
const b = document.createElement("button");
b.className = "act";
b.textContent = label;
b.disabled = !on;
b.addEventListener("click", () => { offset = to; sel.clear(); load(); window.scrollTo(0, 0); });
return b;
};
$("pager").appendChild(mk("Previous", Math.max(0, offset - PAGE), offset > 0));
const span = document.createElement("span");
span.textContent = (offset + 1) + "–" + Math.min(offset + PAGE, total) + " of " + total;
$("pager").appendChild(span);
$("pager").appendChild(mk("Next", offset + PAGE, offset + PAGE < total));
}
async function decide(action) {
if (!sel.size || busy) return;
if (!DECIDABLE.includes(status)) return;
const ids = [...sel];
if (ids.length > maxDecide) {
say("Select at most " + maxDecide + " at a time - that is the server's batch limit.", "err");
return;
}
if (action === "approve" &&
!confirm("Approve " + ids.length + " game(s)? This commits them to scripts/temp_info.jsonl and starts the ingest workflow.")) return;
if (action === "reject" &&
!confirm("Reject " + ids.length + " game(s)? They will not be offered again by future sweeps.")) return;
busy = true; paintBar();
say("Working...");
try {
const out = await api("decide", {
method: "POST",
body: JSON.stringify({ ids, action, reason: $("reason").value }),
});
let m = action + ": " + out.decided + " row(s)";
if (out.commit) {
m += NL + "commit " + out.commit.slice(0, 10) +
" - " + out.appended + " appended" +
(out.already_queued ? ", " + out.already_queued + " already queued" : "") +
NL + "Ingest New Game Links will pick them up; they move to 'committed' once they appear in data/.";
} else if (action === "approve") {
// commit === null means every link was already in the queue file, so no
// commit was made. Saying "committed" here would be a lie the reviewer
// could only catch by opening the repository.
m += NL + "Already queued in scripts/temp_info.jsonl - no new commit was needed.";
}
say(m, "ok");
sel.clear();
$("reason").value = "";
await load(true);
} catch (e) {
reportError(e);
} finally {
busy = false; paintBar();
}
}
$("approve").addEventListener("click", () => decide("approve"));
$("reject").addEventListener("click", () => decide("reject"));
$("defer").addEventListener("click", () => decide(status === "failed" ? "requeue" : "defer"));
$("detailClose").addEventListener("click", () => $("detail").close());
// Debounced, because every keystroke is now a server round-trip rather than an
// array filter.
let qTimer = 0;
$("q").addEventListener("input", () => {
clearTimeout(qTimer);
qTimer = setTimeout(() => {
query = $("q").value.trim();
offset = 0;
sel.clear();
load();
}, 250);
});
$("sort").addEventListener("change", () => {
sortKey = $("sort").value;
offset = 0;
sel.clear();
load();
});
$("all").addEventListener("change", () => {
const on = $("all").checked;
for (const it of visible()) { if (on) sel.add(it.id); else sel.delete(it.id); }
render();
});
$("reconcile").addEventListener("click", async () => {
// A full run fetches index.json, every shard and removed_games.jsonl - about
// 6 MB. This button had no busy state at all, so a double-click fired two.
if (reconciling) return;
reconciling = true;
$("reconcile").disabled = true;
say("Checking data/ for approved games...");
try {
const out = await api("reconcile", { method: "POST" });
// "ok" was outside the ternary, so a hard dependency failure ("index
// unreachable", "shard unreachable") painted the GREEN success banner.
// Split on the COUNT rather than the message: bail() always reports
// checked >= 1, while the benign idle skip reports checked === 0, so this
// does not drift when the wording changes.
const bad = out.skipped && out.checked > 0;
say(out.skipped
? "Reconcile: " + out.skipped
: "Reconcile: checked " + out.checked + ", published " + out.published +
", rejected by pipeline " + out.removed +
(out.stale ? ", " + out.stale + " aged out to failed - approve again to retry" : ""),
bad ? "err" : "ok");
await load(true);
} catch (e) {
reportError(e);
} finally {
reconciling = false;
$("reconcile").disabled = false;
}
});
load();
</script>
</body>
</html>`;
}
-728
View File
@@ -1,728 +0,0 @@
/**
* /admin/edit — correct games already in the catalogue.
*
* Two modes over one API and one artifact:
* One game load by appid, change any manual field.
* Bulk pick a genre, see everything carrying it, retag up to ten in a
* single commit. This is the screen for breaking up the vague
* buckets — "Action" holds 287 games, "Adventure" 232.
*
* Same shape as admin-ui.ts and for the same reasons: served by the Worker,
* never part of the public bundle, its own per-response nonce CSP, and every
* publisher-supplied string written with textContent.
*
* The screen writes data/overrides/<appid>.json and nothing else. It cannot
* touch data/; the pipeline applies the override on its next write. The page
* says so, because a reviewer who assumes the catalogue changed immediately
* will think the edit failed.
*/
import { adminHtmlResponse } from "../lib/http";
export function editPage(actor: string): Response {
const nonce = crypto.randomUUID().replace(/-/g, "");
return adminHtmlResponse(html(nonce, actor), nonce);
}
function esc(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function html(nonce: string, actor: string): string {
return `<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Edit games</title>
<style>
:root{color-scheme:dark;
--bg:#0b0e14;--surface:#141922;--surface-2:#1c2331;--border:#2a3444;
--text:#e4e8ef;--muted:#93a0b4;--accent:#4f9cf9;--ok:#3fb950;--warn:#d29922;--bad:#f85149}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);
font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
a{color:var(--accent)}
header{position:sticky;top:0;z-index:20;background:var(--surface);
border-bottom:1px solid var(--border);padding:12px 20px}
.row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
h1{font-size:15px;margin:0;font-weight:600}
.who{color:var(--muted);font-size:12px;margin-left:auto}
nav{display:flex;gap:4px;margin-top:10px}
nav button{background:transparent;border:1px solid transparent;color:var(--muted);
padding:5px 11px;border-radius:7px;cursor:pointer;font:inherit;font-size:13px}
nav button:hover{background:var(--surface-2);color:var(--text)}
nav button[aria-current=true]{background:var(--surface-2);color:var(--text);border-color:var(--border)}
main{padding:18px 20px 96px;max-width:980px}
.card{background:var(--surface);border:1px solid var(--border);border-radius:9px;padding:14px}
.game{display:flex;gap:14px;align-items:flex-start;margin-bottom:18px}
.game img{width:132px;height:62px;object-fit:cover;border-radius:5px;background:var(--surface-2);flex:none}
.game .nm{font-weight:600;font-size:16px}
.game .sub{color:var(--muted);font-size:12px;margin-top:3px}
label{display:block;font-size:12px;color:var(--muted);margin-bottom:4px}
.field{margin-bottom:14px}
.field .now{font-size:12px;color:var(--muted);margin-top:4px}
.field.dirty{border-left:2px solid var(--accent);padding-left:10px;margin-left:-12px}
.field.over{border-left:2px solid var(--warn);padding-left:10px;margin-left:-12px}
input[type=text],input[type=search],select,textarea{font:inherit;font-size:13px;
padding:7px 10px;border-radius:7px;width:100%;
border:1px solid var(--border);background:var(--bg);color:var(--text)}
textarea{min-height:66px;resize:vertical}
button{font:inherit;font-size:13px;padding:7px 15px;border-radius:7px;
border:1px solid var(--border);background:var(--surface-2);color:var(--text);cursor:pointer}
button:hover:not(:disabled){border-color:var(--muted)}
button:disabled{opacity:.5;cursor:not-allowed}
button.go{background:var(--ok);border-color:var(--ok);color:#07130a;font-weight:600}
button.tiny{font-size:11px;padding:3px 8px}
.msg{padding:10px 13px;border-radius:8px;margin-bottom:14px;font-size:13px;
border:1px solid var(--border);background:var(--surface);white-space:pre-wrap}
.msg.err{border-color:var(--bad);color:#ffb4ae}
.msg.ok{border-color:var(--ok);color:#7ee787}
.tag{display:inline-block;font-size:11px;padding:1px 6px;border-radius:4px;
background:var(--surface-2);border:1px solid var(--border);color:var(--muted)}
.bar{position:fixed;left:0;right:0;bottom:0;background:var(--surface);
border-top:1px solid var(--border);padding:11px 20px;display:none;z-index:30}
.bar.on{display:block}
.hint{color:var(--muted);font-size:12px;margin-top:14px;line-height:1.6}
.grid{display:grid;gap:9px;grid-template-columns:repeat(auto-fill,minmax(300px,1fr))}
.pick{background:var(--surface);border:1px solid var(--border);border-radius:8px;
padding:9px;display:flex;gap:9px;align-items:flex-start}
.pick.sel{border-color:var(--accent);background:var(--surface-2)}
.pick.full{opacity:.45}
.pick img{width:84px;height:39px;object-fit:cover;border-radius:4px;background:var(--surface-2);flex:none}
.pick input{width:17px;height:17px;accent-color:var(--accent);cursor:pointer;flex:none;margin-top:2px}
.pick .nm{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}
.pick .sub{color:var(--muted);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pager{display:flex;gap:10px;align-items:center;justify-content:center;margin-top:18px;
color:var(--muted);font-size:13px}
.empty{color:var(--muted);padding:36px 0;text-align:center}
</style>
</head>
<body>
<header>
<div class="row">
<h1>Edit games</h1>
<a href="/admin" style="font-size:13px">&larr; Review queue</a>
<span class="who">${esc(actor)}</span>
</div>
<nav id="tabs">
<button id="tab-one" aria-current="true">One game</button>
<button id="tab-bulk">Bulk by genre</button>
</nav>
</header>
<main>
<div id="msg"></div>
<section id="pane-one">
<div class="row" style="margin-bottom:16px">
<input type="search" id="appid" placeholder="appid, e.g. 730" style="width:200px" inputmode="numeric">
<button id="load">Load</button>
</div>
<div id="game" class="game" hidden></div>
<div id="form" class="card" hidden></div>
</section>
<section id="pane-bulk" hidden>
<div class="row" style="margin-bottom:14px;align-items:flex-end">
<div style="flex:1;min-width:240px">
<label for="bgenre">Games currently tagged</label>
<select id="bgenre"></select>
</div>
<div style="flex:1;min-width:240px">
<label for="bnew">Retag the selected ones to</label>
<select id="bnew"></select>
</div>
</div>
<div id="bcustomwrap" hidden style="margin-bottom:14px">
<label for="bcustom">New genre</label>
<input type="text" id="bcustom" placeholder="Type a genre not in the list">
</div>
<div class="row" style="margin-bottom:10px">
<span id="bcount" style="font-size:13px;color:var(--muted)"></span>
<span id="bsel" style="font-size:13px;color:var(--muted);margin-left:auto"></span>
</div>
<div class="grid" id="blist"></div>
<div class="pager" id="bpager"></div>
</section>
<div class="hint">
Saving writes <code>data/overrides/&lt;appid&gt;.json</code> and nothing else.
<strong>data/ does not change until the next pipeline run</strong> — an override is a
standing instruction that <code>save_main()</code> re-applies on every write, which is
what makes it survive <code>refetch_all.py</code> and <code>normalize_genres.py --apply</code>.<br>
A field cannot be set empty: the next scrape would refill it and the override layer
would blank it again, rewriting shards forever. Use <em>Retire</em> to clear — it
restores the value from before your edit, once, then stops acting.
</div>
</main>
<div class="bar" id="bar">
<div class="row">
<strong id="count">0 changed</strong>
<input type="text" id="reason" placeholder="Reason (kept in the commit and the file)" style="width:320px">
<span style="margin-left:auto"></span>
<button id="reset">Discard</button>
<button class="go" id="save">Save override</button>
</div>
</div>
<script nonce="${nonce}">
"use strict";
const MAX_EDIT = 10;
const PAGE = 60;
const FIELDS = [
{k:"genre", label:"Genre", type:"genre"},
{k:"type_game", label:"Type", type:"select", opts:["online","offline"]},
{k:"safe", label:"Safe", type:"select", opts:["y","n","?"]},
{k:"anti_cheat", label:"Anti-cheat", type:"text"},
{k:"is_kernel_ac", label:"Kernel anti-cheat",type:"select", opts:["true","false","null"]},
{k:"anti_cheat_note", label:"Anti-cheat note", type:"area"},
{k:"notes", label:"Notes", type:"area"},
];
// A sentinel that cannot collide with a real genre value.
const CUSTOM = "\\u0000custom";
const $ = (id) => document.getElementById(id);
let mode = "one";
let data = null, dirty = {};
let genres = [];
let bulk = { genre: "", items: [], total: 0, offset: 0, sel: new Set() };
function say(text, kind) {
$("msg").innerHTML = "";
if (!text) return;
const d = document.createElement("div");
d.className = "msg" + (kind ? " " + kind : "");
d.textContent = text;
$("msg").appendChild(d);
}
const NL = String.fromCharCode(10);
/**
* See the matching helper in admin-ui.ts. The old version reported EVERY
* non-JSON response as an expired session, so a server-side crash - which
* arrived as a Cloudflare 1101 HTML page, the Worker having had no top-level
* try/catch - was indistinguishable from needing to log in again.
*
* redirect:'manual' observes an Access redirect rather than following it to
* cloudflareaccess.com, which the page CSP blocks as a connect-src violation.
*/
async function api(path, init) {
let res;
try {
res = await fetch("/api/admin/" + path, {
credentials: "same-origin",
redirect: "manual",
headers: { "Accept": "application/json", ...(init && init.body ? {"Content-Type":"application/json"} : {}) },
...init,
});
} catch (e) {
throw new Error("Network error reaching the admin API. Check your connection, then reload.");
}
if (res.type === "opaqueredirect" || res.status === 0 || res.status === 401 || res.status === 403) {
throw new Error("SESSION_EXPIRED");
}
const ct = res.headers.get("Content-Type") || "";
if (!ct.includes("application/json")) {
throw new Error("Server returned " + res.status + " and a non-JSON body. Check wrangler tail.");
}
const body = await res.json();
if (!res.ok) throw new Error(body.error || ("HTTP " + res.status));
return body;
}
function reportError(e) {
const m = String((e && e.message) || e);
if (m === "SESSION_EXPIRED") {
say("Your Cloudflare Access session expired. Reloading to sign in again...", "err");
setTimeout(() => window.location.reload(), 1200);
return;
}
say(m, "err");
}
/**
* One busy flag for the whole page.
*
* There was none. save() and saveBulk() toggled only $("save").disabled, and
* retire() did not even do that - so Retire could be double-clicked into two
* concurrent commits, and tab switching, Discard, Load and the genre picker
* all stayed live while a commit was in flight.
*/
let busy = false;
function setBusy(on) {
busy = on;
for (const id of ["save", "reset", "load", "tab-one", "tab-bulk", "bgenre", "bnew", "appid"]) {
const el = $(id);
if (el) el.disabled = on;
}
}
const toWire = (k, v) => k === "is_kernel_ac"
? (v === "true" ? true : v === "false" ? false : null) : v;
const toForm = (k, v) => k === "is_kernel_ac"
? (v === true ? "true" : v === false ? "false" : "null") : (v == null ? "" : String(v));
// ─────────────────────────── one-game mode ───────────────────────────
function render() {
const g = data;
$("game").hidden = false;
$("form").hidden = false;
$("game").innerHTML = "";
if (g.header_image) {
const img = document.createElement("img");
img.src = g.header_image; img.alt = ""; img.referrerPolicy = "no-referrer";
$("game").appendChild(img);
}
const meta = document.createElement("div");
const nm = document.createElement("div"); nm.className = "nm";
nm.textContent = g.name || "(no name)";
meta.appendChild(nm);
const sub = document.createElement("div"); sub.className = "sub";
sub.textContent = [g.appid, g.release_date, g.status, g.is_dead ? "dead" : ""].filter(Boolean).join(" · ");
meta.appendChild(sub);
const a = document.createElement("a");
a.href = g.link; a.target = "_blank"; a.rel = "noopener noreferrer";
a.textContent = "Steam page"; a.style.fontSize = "12px";
meta.appendChild(a);
$("game").appendChild(meta);
$("form").innerHTML = "";
for (const f of FIELDS) {
const wrap = document.createElement("div");
wrap.className = "field";
const ov = g.override && g.override.fields ? g.override.fields[f.k] : undefined;
const ret = g.override && g.override.retired ? g.override.retired[f.k] : undefined;
if (ov) wrap.classList.add("over");
const lab = document.createElement("label");
lab.textContent = f.label;
lab.htmlFor = "f_" + f.k;
if (ov) {
const t = document.createElement("span"); t.className = "tag";
t.style.marginLeft = "8px"; t.textContent = "overridden by " + (ov.set_by || "?");
lab.appendChild(t);
const b = document.createElement("button");
b.className = "tiny"; b.type = "button"; b.style.marginLeft = "8px";
b.textContent = "Retire";
b.title = "Undo this override, restoring " + JSON.stringify(ov.was);
b.addEventListener("click", () => retire(f.k, ov));
lab.appendChild(b);
} else if (ret) {
const t = document.createElement("span"); t.className = "tag";
t.style.marginLeft = "8px"; t.textContent = "retired";
lab.appendChild(t);
}
wrap.appendChild(lab);
const initial = toForm(f.k, g.fields[f.k]);
let el, custom = null;
if (f.type === "genre") {
// The genre list is the catalogue's own vocabulary, counts included:
// the counts are how a vague bucket announces itself. The current value
// is added even when the catalogue list does not contain it, so loading
// a game can never silently change its genre just because the dropdown
// could not represent it.
el = document.createElement("select");
const seen = new Set();
const add = (value, text) => {
const o = document.createElement("option");
o.value = value; o.textContent = text;
el.appendChild(o);
};
if (initial) { add(initial, initial); seen.add(initial); }
for (const gg of genres) {
if (seen.has(gg.genre)) continue;
seen.add(gg.genre);
add(gg.genre, gg.genre + " (" + gg.count + ")");
}
add(CUSTOM, "Custom…");
el.id = "f_" + f.k;
el.value = initial || (genres[0] ? genres[0].genre : CUSTOM);
custom = document.createElement("input");
custom.type = "text"; custom.id = "c_" + f.k; custom.hidden = true;
custom.placeholder = "Type a genre not in the list";
custom.style.marginTop = "6px";
custom.addEventListener("input", () => onEdit(f.k));
} else if (f.type === "select") {
el = document.createElement("select");
for (const o of f.opts) {
const opt = document.createElement("option");
opt.value = o; opt.textContent = o;
el.appendChild(opt);
}
el.id = "f_" + f.k;
el.value = initial;
} else if (f.type === "area") {
el = document.createElement("textarea"); el.id = "f_" + f.k; el.value = initial;
} else {
el = document.createElement("input"); el.type = "text"; el.id = "f_" + f.k; el.value = initial;
}
el.dataset.initial = initial;
el.addEventListener("input", () => onEdit(f.k));
el.addEventListener("change", () => onEdit(f.k));
wrap.appendChild(el);
if (custom) wrap.appendChild(custom);
const now = document.createElement("div");
now.className = "now";
now.textContent = "catalogue: " + JSON.stringify(g.fields[f.k]) +
(ov ? " was before edit: " + JSON.stringify(ov.was) : "");
wrap.appendChild(now);
$("form").appendChild(wrap);
}
recount();
}
/** What a field currently holds in the form, resolving the custom escape. */
function formValue(key) {
const el = $("f_" + key);
if (!el) return undefined;
if (el.value === CUSTOM) {
const c = $("c_" + key);
return c ? c.value.trim() : "";
}
return el.value;
}
function onEdit(key) {
const el = $("f_" + key);
const custom = $("c_" + key);
if (custom) {
const wantCustom = el.value === CUSTOM;
custom.hidden = !wantCustom;
if (wantCustom && document.activeElement !== custom) custom.focus();
}
const v = formValue(key);
// An empty value is not a change: the API refuses blanks (clearing is what
// Retire is for), so treating one as dirty would only produce a 400.
if (v === el.dataset.initial || v === "") delete dirty[key];
else dirty[key] = v;
el.closest(".field").classList.toggle("dirty", key in dirty);
recount();
}
function recount() {
const n = mode === "one" ? Object.keys(dirty).length : bulk.sel.size;
$("count").textContent = mode === "one"
? n + " changed"
: n + " selected";
$("bar").classList.toggle("on", n > 0);
}
async function load(appid, keepMsg) {
if (!keepMsg) say("");
dirty = {};
try {
data = await api("game?appid=" + encodeURIComponent(appid));
render();
history.replaceState(null, "", "/admin/edit?appid=" + encodeURIComponent(appid));
} catch (e) {
$("game").hidden = true; $("form").hidden = true;
$("bar").classList.remove("on");
say(String(e.message || e), "err");
}
}
async function save() {
const set = {};
for (const [k, v] of Object.entries(dirty)) set[k] = toWire(k, v);
if (!Object.keys(set).length) return;
if (busy) return;
setBusy(true);
say("Saving...");
try {
const out = await api("edit", {
method: "POST",
body: JSON.stringify({ appids: [data.appid], set, reason: $("reason").value }),
});
say("Saved " + out.set.join(", ") +
(out.commit ? "\\ncommit " + out.commit.slice(0, 10) : "\\nno commit needed") +
"\\ndata/ is unchanged until the next pipeline run applies it.", "ok");
$("reason").value = "";
await load(data.appid, true);
await loadGenres();
} catch (e) {
reportError(e);
} finally {
setBusy(false);
}
}
async function retire(field, ov) {
if (!confirm("Retire the override on " + field + "?\\n\\nThe value from before the edit (" +
JSON.stringify(ov.was) + ") is restored once, then the entry stops acting.")) return;
if (busy) return;
setBusy(true);
say("Retiring...");
try {
const out = await api("edit", {
method: "POST",
body: JSON.stringify({ appids: [data.appid], retire: [field], reason: $("reason").value }),
});
// Retiring a field that has no override is a no-op server-side: build()
// returns null, commitFiles() returns null, and the old message still read
// "Retired genre" - success wording for nothing having happened.
if (out.commit) {
say("Retired " + field + NL + "commit " + out.commit.slice(0, 10) +
NL + "The pre-edit value is written back on the next pipeline run.", "ok");
} else {
say("There was no override on " + field + " to retire - nothing was committed.", "err");
}
await load(data.appid, true);
} catch (e) {
reportError(e);
} finally {
setBusy(false);
}
}
// ─────────────────────────── bulk mode ───────────────────────────
/**
* The genre vocabulary, built server-side by regex-scanning ~6 MB of shards.
*
* This used to swallow every error into an empty list with no message, so a
* failure left both pickers empty, bulk mode silently doing nothing, and
* nothing on screen to say why.
*/
async function loadGenres() {
try {
const out = await api("genres");
genres = out.genres || [];
return true;
} catch (e) {
genres = [];
const m = String((e && e.message) || e);
say(m === "SESSION_EXPIRED"
? "Session expired while loading the genre list. Reload to sign in again."
: "Could not load the genre list (" + m + "). Bulk retag is unavailable until that works; one-game edits still are.",
"err");
return false;
}
}
function fillGenrePickers() {
const from = $("bgenre"), to = $("bnew");
const keepFrom = from.value, keepTo = to.value;
from.innerHTML = ""; to.innerHTML = "";
for (const g of genres) {
const a = document.createElement("option");
a.value = g.genre;
a.textContent = g.genre + " (" + g.count + " game" + (g.count === 1 ? "" : "s") + ")";
from.appendChild(a);
const b = document.createElement("option");
b.value = g.genre; b.textContent = g.genre + " (" + g.count + ")";
to.appendChild(b);
}
const c = document.createElement("option");
c.value = CUSTOM; c.textContent = "Custom…";
to.appendChild(c);
if (keepFrom) from.value = keepFrom;
if (keepTo) to.value = keepTo;
}
async function loadBulk(offset, keepMsg) {
bulk.genre = $("bgenre").value;
bulk.offset = offset || 0;
bulk.sel.clear();
if (!keepMsg) say("");
try {
const out = await api("by-genre?genre=" + encodeURIComponent(bulk.genre) +
"&limit=" + PAGE + "&offset=" + bulk.offset);
bulk.items = out.items || [];
bulk.total = out.total || 0;
renderBulk();
} catch (e) {
say(String(e.message || e), "err");
}
}
function renderBulk() {
$("bcount").textContent = bulk.total + " game" + (bulk.total === 1 ? "" : "s") +
" tagged " + JSON.stringify(bulk.genre);
$("blist").innerHTML = "";
if (!bulk.items.length) {
const d = document.createElement("div");
d.className = "empty"; d.textContent = "Nothing here.";
$("blist").appendChild(d);
}
for (const it of bulk.items) {
const el = document.createElement("div");
el.className = "pick" + (bulk.sel.has(it.appid) ? " sel" : "");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.checked = bulk.sel.has(it.appid);
// The cap is enforced here AND on the server. Disabling the rest is what
// makes the limit legible, instead of a surprise at save time.
cb.disabled = !cb.checked && bulk.sel.size >= MAX_EDIT;
if (cb.disabled) el.classList.add("full");
cb.addEventListener("change", () => {
if (cb.checked) bulk.sel.add(it.appid); else bulk.sel.delete(it.appid);
// Update in place. A full renderBulk() here would replace the very
// checkbox that was just clicked, losing keyboard focus and dropping
// rapid clicks on the floor.
syncSelection();
});
el.appendChild(cb);
if (it.header_image) {
const img = document.createElement("img");
img.src = it.header_image; img.alt = ""; img.loading = "lazy";
img.referrerPolicy = "no-referrer";
el.appendChild(img);
}
const meta = document.createElement("div");
meta.style.minWidth = "0"; meta.style.flex = "1";
const nm = document.createElement("div"); nm.className = "nm";
nm.textContent = it.name || "(no name)";
meta.appendChild(nm);
const sub = document.createElement("div"); sub.className = "sub";
sub.textContent = [it.appid, it.release_date].filter(Boolean).join(" · ");
meta.appendChild(sub);
el.appendChild(meta);
$("blist").appendChild(el);
}
syncSelection();
renderBulkPager();
}
/**
* Reflect the current selection without rebuilding the grid: highlight, the
* cap, the counter and the action bar.
*/
function syncSelection() {
const full = bulk.sel.size >= MAX_EDIT;
for (const el of document.querySelectorAll(".pick")) {
const cb = el.querySelector("input[type=checkbox]");
if (!cb) continue;
const on = cb.checked;
el.classList.toggle("sel", on);
cb.disabled = !on && full;
el.classList.toggle("full", cb.disabled);
}
$("bsel").textContent = bulk.sel.size + " / " + MAX_EDIT + " selected" +
(full ? " — limit reached" : "");
recount();
}
function renderBulkPager() {
$("bpager").innerHTML = "";
if (bulk.total <= PAGE) return;
const mk = (label, to, on) => {
const b = document.createElement("button");
b.textContent = label; b.disabled = !on;
b.addEventListener("click", () => { loadBulk(to); window.scrollTo(0, 0); });
return b;
};
$("bpager").appendChild(mk("Previous", Math.max(0, bulk.offset - PAGE), bulk.offset > 0));
const s = document.createElement("span");
s.textContent = (bulk.offset + 1) + "–" + Math.min(bulk.offset + PAGE, bulk.total) +
" of " + bulk.total;
$("bpager").appendChild(s);
$("bpager").appendChild(mk("Next", bulk.offset + PAGE, bulk.offset + PAGE < bulk.total));
}
function bulkTarget() {
const v = $("bnew").value;
return v === CUSTOM ? $("bcustom").value.trim() : v;
}
async function saveBulk() {
const target = bulkTarget();
const appids = [...bulk.sel];
if (!appids.length) return;
if (!target) { say("Choose or type the genre to retag to.", "err"); return; }
if (target === bulk.genre) { say("That is already their genre.", "err"); return; }
if (!confirm("Retag " + appids.length + " game(s) from " + JSON.stringify(bulk.genre) +
" to " + JSON.stringify(target) +
"?\\n\\nOne commit, one override file per game.")) return;
if (busy) return;
setBusy(true);
say("Saving...");
try {
const out = await api("edit", {
method: "POST",
body: JSON.stringify({ appids, set: { genre: target }, reason: $("reason").value }),
});
$("reason").value = "";
await loadGenres();
fillGenrePickers();
await loadBulk(bulk.offset, true);
// Said last, because loadBulk() repaints and the reviewer needs the sha.
say("Retagged " + appids.length + " game(s) to " + target +
(out.commit ? "\\ncommit " + out.commit.slice(0, 10) : "\\nno commit needed") +
"\\ndata/ is unchanged until the next pipeline run applies it.", "ok");
} catch (e) {
reportError(e);
} finally {
setBusy(false);
}
}
// ─────────────────────────── wiring ───────────────────────────
function setMode(m) {
if (busy) return;
// dirty belongs to one-game mode and bulk.sel to bulk mode, and neither was
// cleared on a switch. One -> Bulk -> One left dirty populated while
// recount() reported bulk.sel.size, so the counter and what Save would
// actually send disagreed.
if (m !== mode) {
dirty = {};
bulk.sel.clear();
if (data) render();
}
mode = m;
$("tab-one").setAttribute("aria-current", String(m === "one"));
$("tab-bulk").setAttribute("aria-current", String(m === "bulk"));
$("pane-one").hidden = m !== "one";
$("pane-bulk").hidden = m !== "bulk";
$("save").textContent = m === "one" ? "Save override" : "Retag selected";
say("");
recount();
if (m === "bulk" && !bulk.items.length && $("bgenre").value) loadBulk(0);
}
$("tab-one").addEventListener("click", () => setMode("one"));
$("tab-bulk").addEventListener("click", () => setMode("bulk"));
$("load").addEventListener("click", () => { const v = $("appid").value.trim(); if (v) load(v); });
$("appid").addEventListener("keydown", (e) => {
if (e.key === "Enter") { const v = $("appid").value.trim(); if (v) load(v); }
});
$("save").addEventListener("click", () => (mode === "one" ? save() : saveBulk()));
$("reset").addEventListener("click", () => {
if (mode === "one") { if (data) load(data.appid); }
else { bulk.sel.clear(); renderBulk(); }
});
$("bgenre").addEventListener("change", () => loadBulk(0));
$("bnew").addEventListener("change", () => {
const custom = $("bnew").value === CUSTOM;
$("bcustomwrap").hidden = !custom;
if (custom) $("bcustom").focus();
});
(async () => {
await loadGenres();
fillGenrePickers();
const initial = new URLSearchParams(location.search).get("appid");
if (initial) { $("appid").value = initial; load(initial); }
})();
// An edit in progress was lost with no warning on navigate or close. The
// browser shows its own generic prompt; the text is not ours to choose.
window.addEventListener("beforeunload", (e) => {
const pending = mode === "one" ? Object.keys(dirty).length : bulk.sel.size;
if (!pending && !busy) return;
e.preventDefault();
e.returnValue = "";
});
</script>
</body>
</html>`;
}
+20 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { deletable, handleEditApi } from "./edit";
import { deletable, handleEditApi, validateValue } from "./edit";
import { MANUAL_FIELDS, toWire, validate } from "../../admin/src/lib/fields";
import { ADMIN, fakeDeps, makeEnv, request } from "../testing/fixtures";
const RECORD = { link: "https://store.steampowered.com/app/730/", name: "Counter-Strike 2", genre: "FPS", safe: "?" };
@@ -95,3 +96,21 @@ describe("POST /api/admin/edit", () => {
expect((env.sqlite.db.prepare("SELECT status FROM commit_jobs").get() as any).status).toBe("failed");
});
});
describe("the admin form's validation mirror (admin/src/lib/fields.ts)", () => {
// The form warns before a commit is attempted. If its rules drift from the
// Worker's, it either blocks a valid correction or lets the reviewer reach a
// 400 it said would not happen.
const TEXT = ["", " ", "Action", " Action ", "online", "offline", "Online", "y", "n", "?", "yes", "x".repeat(500), "x".repeat(501)];
it("agrees with validateValue() for every field", () => {
for (const field of MANUAL_FIELDS) {
const inputs = field === "is_kernel_ac" ? ["true", "false", "null"] : TEXT;
for (const text of inputs) {
const client = validate(field, text) === null;
const server = validateValue(field, toWire(field, text)) === null;
expect(client, `${field} = ${JSON.stringify(text.length > 20 ? `${text.length} chars` : text)}`).toBe(server);
}
}
});
});