From 0963cd4cffac3b2e66f325aa978b823bd6b173d9 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:52:19 -0300 Subject: [PATCH 1/7] Add ranked leaderboard functionality and related tests - Implemented the ranked challenge protocol in `src/ranked/api.ts` for handling ranked runs. - Created control tracking for input methods in `src/ranked/controls.ts`. - Developed local score storage management in `src/ranked/localScores.ts`. - Established a session management system for ranked runs in `src/ranked/session.ts`. - Added tests for the ranked API, control tracking, and local score management in `tests/ranked.test.ts`. - Configured TypeScript settings for the server in `server/tsconfig.json`. - Added configuration files for Cloudflare Workers in `server/wrangler.toml` and `server/wrangler.bench.toml`. - Created unit tests for the weekly window functionality in `server/tests/week.test.ts`. --- docs/leaderboard-backend.md | 357 ++++ phaser-asteroids/.gitignore | 4 + phaser-asteroids/package.json | 6 +- phaser-asteroids/scripts/lib/browserPlay.mjs | 90 + phaser-asteroids/scripts/ranked-browser.mjs | 224 +++ phaser-asteroids/server/.dev.vars.example | 5 + phaser-asteroids/server/README.md | 17 + phaser-asteroids/server/bench/worker.ts | 23 + .../server/migrations/0001_init.sql | 69 + phaser-asteroids/server/package-lock.json | 1562 +++++++++++++++++ phaser-asteroids/server/package.json | 19 + .../server/scripts/bench-workerd.mjs | 94 + .../server/scripts/worker-e2e.mjs | 216 +++ phaser-asteroids/server/src/body.ts | 76 + phaser-asteroids/server/src/config.ts | 98 ++ phaser-asteroids/server/src/crypto.ts | 42 + phaser-asteroids/server/src/d1.ts | 34 + phaser-asteroids/server/src/db.ts | 22 + phaser-asteroids/server/src/errors.ts | 13 + phaser-asteroids/server/src/leaderboard.ts | 121 ++ phaser-asteroids/server/src/nickname.ts | 31 + phaser-asteroids/server/src/ratelimit.ts | 26 + phaser-asteroids/server/src/router.ts | 198 +++ phaser-asteroids/server/src/runs.ts | 307 ++++ phaser-asteroids/server/src/verify.ts | 94 + phaser-asteroids/server/src/week.ts | 87 + phaser-asteroids/server/src/worker.ts | 22 + phaser-asteroids/server/testing/bot.d.mts | 20 + phaser-asteroids/server/testing/bot.mjs | 111 ++ phaser-asteroids/server/testing/sqliteDb.ts | 71 + phaser-asteroids/server/tests/harness.ts | 163 ++ .../server/tests/leaderboard.test.ts | 216 +++ .../server/tests/lifecycle.test.ts | 545 ++++++ phaser-asteroids/server/tests/week.test.ts | 69 + phaser-asteroids/server/tsconfig.json | 9 + phaser-asteroids/server/wrangler.bench.toml | 3 + phaser-asteroids/server/wrangler.toml | 48 + phaser-asteroids/src/ranked/api.ts | 198 +++ phaser-asteroids/src/ranked/controls.ts | 36 + phaser-asteroids/src/ranked/env.d.ts | 8 + phaser-asteroids/src/ranked/localScores.ts | 73 + phaser-asteroids/src/ranked/session.ts | 106 ++ phaser-asteroids/src/scenes/GameScene.ts | 99 +- phaser-asteroids/src/scenes/StartScene.ts | 44 +- phaser-asteroids/tests/ranked.test.ts | 192 ++ phaser-asteroids/vite.config.ts | 2 +- 46 files changed, 5859 insertions(+), 11 deletions(-) create mode 100644 docs/leaderboard-backend.md create mode 100644 phaser-asteroids/scripts/lib/browserPlay.mjs create mode 100644 phaser-asteroids/scripts/ranked-browser.mjs create mode 100644 phaser-asteroids/server/.dev.vars.example create mode 100644 phaser-asteroids/server/README.md create mode 100644 phaser-asteroids/server/bench/worker.ts create mode 100644 phaser-asteroids/server/migrations/0001_init.sql create mode 100644 phaser-asteroids/server/package-lock.json create mode 100644 phaser-asteroids/server/package.json create mode 100644 phaser-asteroids/server/scripts/bench-workerd.mjs create mode 100644 phaser-asteroids/server/scripts/worker-e2e.mjs create mode 100644 phaser-asteroids/server/src/body.ts create mode 100644 phaser-asteroids/server/src/config.ts create mode 100644 phaser-asteroids/server/src/crypto.ts create mode 100644 phaser-asteroids/server/src/d1.ts create mode 100644 phaser-asteroids/server/src/db.ts create mode 100644 phaser-asteroids/server/src/errors.ts create mode 100644 phaser-asteroids/server/src/leaderboard.ts create mode 100644 phaser-asteroids/server/src/nickname.ts create mode 100644 phaser-asteroids/server/src/ratelimit.ts create mode 100644 phaser-asteroids/server/src/router.ts create mode 100644 phaser-asteroids/server/src/runs.ts create mode 100644 phaser-asteroids/server/src/verify.ts create mode 100644 phaser-asteroids/server/src/week.ts create mode 100644 phaser-asteroids/server/src/worker.ts create mode 100644 phaser-asteroids/server/testing/bot.d.mts create mode 100644 phaser-asteroids/server/testing/bot.mjs create mode 100644 phaser-asteroids/server/testing/sqliteDb.ts create mode 100644 phaser-asteroids/server/tests/harness.ts create mode 100644 phaser-asteroids/server/tests/leaderboard.test.ts create mode 100644 phaser-asteroids/server/tests/lifecycle.test.ts create mode 100644 phaser-asteroids/server/tests/week.test.ts create mode 100644 phaser-asteroids/server/tsconfig.json create mode 100644 phaser-asteroids/server/wrangler.bench.toml create mode 100644 phaser-asteroids/server/wrangler.toml create mode 100644 phaser-asteroids/src/ranked/api.ts create mode 100644 phaser-asteroids/src/ranked/controls.ts create mode 100644 phaser-asteroids/src/ranked/env.d.ts create mode 100644 phaser-asteroids/src/ranked/localScores.ts create mode 100644 phaser-asteroids/src/ranked/session.ts create mode 100644 phaser-asteroids/tests/ranked.test.ts diff --git a/docs/leaderboard-backend.md b/docs/leaderboard-backend.md new file mode 100644 index 0000000..a4a3d5e --- /dev/null +++ b/docs/leaderboard-backend.md @@ -0,0 +1,357 @@ +# Phaser Asteroids — Secure Online Leaderboard Backend (Phase 2) + +> **Status:** Implemented and tested locally (Node + real workerd/D1 runtime + real Chromium). **Not deployed.** Nothing in this repository talks to a Cloudflare account. +> **Code:** `phaser-asteroids/server/` (backend), `phaser-asteroids/src/ranked/` (browser client), builds on `phaser-asteroids/src/replay/` (Phase 1, see [deterministic-replay.md](deterministic-replay.md)). + +The single security rule: **no score enters the public leaderboard unless the server independently reproduces it from a ranked run the server itself issued.** The browser never sends a score; it sends the inputs it played, and the server replays them with the same deterministic engine. + +--- + +## 1. Architecture + +``` + Browser (GitHub Pages) Cloudflare Worker + D1 (SQLite) + ────────────────────── ───────────────────────────────── + ?ranked ── POST /api/v1/runs ─────────────► issue run: id, secret token, random seed, + rules version, approved config, expiry ──► runs (status=issued) + ◄─────────── 201 {runId, token, seed, …} ─── + play locally with the server's seed/config + (60 Hz fixed step, records input changes) + game over + ── POST /runs/:id/submit ─────────► rate limit → check token → read bounded body → claim run + Bearer token, gzip replay (issued→verifying) → verifyReplay() → finalize + accepted: INSERT scores + UPDATE runs (one atomic batch) + ◄──────────── 200 {score, ranks} ─────────── rejected: runs.status=rejected (terminal) + GET /api/v1/leaderboard/all-time|weekly ───► read-only, top N, bounded paging +``` + +Layers, from portable to provider-specific: + +| Layer | Files (`server/src/`) | Knows about Cloudflare? | +| --- | --- | --- | +| Replay engine (Phase 1, unchanged) | `../../src/replay/*`, `../../src/core/*` | No | +| Ranked verification policy | `verify.ts` | No | +| Run lifecycle, ranking, nicknames, weeks, rate limits | `runs.ts`, `leaderboard.ts`, `nickname.ts`, `week.ts`, `ratelimit.ts`, `body.ts` | No (SQL goes through the `Db` interface in `db.ts`) | +| HTTP routing (`Request` → `Response`) | `router.ts` | No (Web-standard types only) | +| Cloudflare glue | `worker.ts`, `d1.ts`, `wrangler.toml` | **Yes** — about 60 lines | + +Moving to another host means writing a new `Db` adapter (the unit tests already do this for `node:sqlite`) and a new entry point. + +There is **one** replay engine. The Worker bundles the same `verifyReplay()` the browser tests use; `scripts/bench-workerd.mjs` confirms it produces bit-identical scores inside workerd. + +## 2. Hosting strategy and justification + +**Chosen: Cloudflare Workers (Paid plan) + D1.** Synchronous verification inside the submit request; no queues, Durable Objects, R2 or Redis. + +Verified against Cloudflare's current documentation (fetched 2026-10-22): + +| | Workers Free | Workers Paid | +| --- | --- | --- | +| CPU time per HTTP request | **10 ms** | 30 s default, configurable to 5 min | +| Memory per isolate | 128 MB | 128 MB | +| Price | $0 | **US$5 / month** (10 M requests and 30 M CPU-ms included; then $0.30 / M requests, $0.02 / M CPU-ms) | +| D1 | 5 GB, 5 M rows read/day, 100 k rows written/day | 5 GB, 25 B reads/month, 50 M writes/month included | + +**Free plan is not viable:** replay verification costs 50–250 ms of CPU, 5–25× the 10 ms cap. D1 itself would have been fine on Free; the Worker CPU limit is the blocker. The implementation therefore targets **Workers Paid. It is not activated; that needs your approval and your account.** + +### Measured: the verifier inside the Workers runtime + +`npm run bench:workerd` runs the real `verifyReplay()` in workerd (`wrangler dev --local`) and times whole requests from outside the isolate (in-isolate clocks do not advance during CPU work). Windows x64, Node 22.14, wrangler 4.151.3, median of 7 requests, two separate runs: + +| Scenario | Ticks | Score | Body | workerd (2 runs) | Node, same machine | +| --- | --- | --- | --- | --- | --- | +| 2-min game | 7,621 | 9,114 | 680 KB | 56–77 ms | 40–57 ms | +| 10-min game | 36,554 | 40,634 | 3.3 MB | 134–195 ms | 194–244 ms | +| 2-min stress | 13,416 | 15,042 | 954 KB | 51–61 ms | 66–69 ms | +| Maximum-size body (67,945 changes, 7.5 MiB) | — | (rejected after parse + 36 k ticks) | 7.5 MiB | 225 ms median, 289 max | — | + +Scores in workerd equal Node's exactly. A 10-minute game is a few hundred ms of CPU against a 30 s limit. `wrangler.toml` sets `limits.cpu_ms = 5000` as a runaway-loop safety net. + +Caveats, stated plainly: this is **local** workerd, not Cloudflare's network. Local workerd does not necessarily enforce production's 128 MB isolate cap; the 7.5 MiB / 68 k-change case ran without trouble, and the 8 MiB body limit was chosen so parsed data plus simulation stays well under 128 MB by a wide margin, but real CPU/memory should be confirmed with `wrangler tail` and the dashboard after the first deployment (see §14). + +### Cost estimate (Workers Paid) + +Assumptions: each submission is one `POST /runs` + one `POST /submit` + ~10 leaderboard reads (12 requests); verification 300 ms CPU (conservative; measured 50–225 ms); ~15 D1 rows written per run (run, score, updates, rate-limit counters, indexes). + +| Submissions / month | Requests | Worker CPU | D1 rows written | Estimated bill | +| --- | --- | --- | --- | --- | +| 100 | ~1.2 k | ~30 s | ~1.5 k | **$5.00** (base fee) | +| 1,000 | ~12 k | ~5 min (1% of included) | ~15 k | **$5.00** | +| 10,000 | ~120 k | ~50 min (10% of included) | ~150 k | **$5.00** | + +All three sit inside the included allowances; the bill is the flat base fee. Overage would only start around 100 k submissions/month for CPU. The `submit` global rate limit (default 1,200/hour) caps worst-case CPU at about 6 CPU-minutes/hour even under attack. + +### Node-compatible alternative (not needed, not built) + +Because the service code is portable, any small Node host (a ~$5 VPS, Fly.io/Render-class container) running the same router with a SQLite/Postgres `Db` adapter would work and has no CPU cap. I did not research those providers' current pricing for this phase (the Worker proved suitable), so treat that as an unverified option rather than a quoted figure. + +## 3. Ranked run lifecycle + +``` +(no run) ──POST /runs──► issued ──claim──► verifying ──finalize──► accepted terminal, owns exactly one scores row + │ │ └─────finalize──► rejected terminal + │ └──── release (internal error only) ──► issued + └── time passes ──► expired (derived: issued and expires_at ≤ now; pruned after a day) +``` + +Every arrow is a **single conditional SQL statement or one atomic batch**, so the database—not process memory—decides races (§7). + +**What the server decides at issue time** (`POST /api/v1/runs`): a UUIDv4 run id; a 256-bit random bearer token (only its SHA-256 is stored); a CSPRNG 32-bit seed; the rules version; the approved config (`{playerCount:1, livesMode:"independent", friendlyFire:false, speed:[1,1]}`); `created_at`; `expires_at`. The request body is ignored: the client cannot influence any of it. A salted hash of the caller's IP is kept for abuse triage; the IP itself is not stored. + +**MVP ranked rules:** single player only, standard lives, existing scoring. The replay header must carry exactly the issued seed, rules version and config (extra config keys are a mismatch). The experimental `?verified&seed=` developer path remains but can never be submitted: only a server challenge carries a token. + +### Timing policy + +| Rule | Value | Why | +| --- | --- | --- | +| Challenge lifetime | **60 minutes** from issue (`RUN_TTL_SECONDS`, 60 s–24 h) | Covers the longest allowed run plus long pauses | +| Minimum elapsed time | simulated duration (`totalTicks / 60`) must be ≤ real time since issue **+ 2 s** | The fixed-step runner never advances more than real time (and not at all while paused), so a legitimate client cannot finish faster than its replay claims. Rejects "10 minutes of play submitted 5 s after issue" (`too_fast`) before any simulation runs | +| Maximum length | **72,000 ticks = 20 simulated minutes** | Bounds CPU and memory | +| Pause / tab suspension / blur | Allowed | Simulation time stands still while paused, wall time continues; both sides of the inequality stay true. Only the 60-minute window limits how long a player can sit paused | + +**This does not prove a human played.** A bot can generate a replay offline and simply wait. See §12. + +## 4. Replay submission and verification + +`POST /api/v1/runs/:id/submit`, `Authorization: Bearer `, body JSON `{ replay, nickname?, controls? }`, optionally `Content-Encoding: gzip`. + +Order of work (cheap and fail-fast first): + +1. **Rate limit** (per hashed client + global) — before anything else. +2. **Run lookup, token check (constant-time on hashes), state check** (rejected → 409, expired → 410) — before reading the body. +3. **Bounded body read** (§ limits below), SHA-256 of the decoded bytes. +4. Already accepted? Same body → idempotent 200; different body → 409. +5. **Envelope**: UTF-8 JSON object with a `replay` object; nickname validated; `controls` whitelisted. +6. **Claim** (atomic). +7. `verifyRankedReplay()`: rules version still served → seed → rules → exact config → `totalTicks` bounds → elapsed-time rule → **`verifyReplay()`** (Phase 1: schema validation, full re-simulation, strict game-over boundary, claim cross-check). +8. **Finalize** (atomic): accepted with the **server-computed** score, or rejected. + +`claimedResult` inside the replay is never used as a score. Phase 1's verifier cross-checks it and a disagreement is a rejection (`score_mismatch`). + +### Payload limits (`server/src/config.ts`, enforced in `body.ts` and `verify.ts`) + +| Limit | Value | Enforcement | +| --- | --- | --- | +| Compressed request | 1 MiB | `Content-Length` pre-check, then bytes counted while streaming; stream cancelled when exceeded | +| Decompressed / plain body | 8 MiB | Same, and the inflate stream is counted and cancelled at the limit (a 32 MiB-of-spaces gzip bomb is refused with 413) | +| Encodings | `identity`, `gzip` | Others → 415 | +| Ticks | 72,000 | `too_long` | +| Input changes | ≤ ticks (the replay schema allows at most one change per tick; Phase 1 also caps at 100 k) | Structure validation | +| Structure/types | every field type- and range-checked by Phase 1's `validateReplayStructure` | Before simulation | +| Simulation work | ≤ 72,000 ticks, bounded entity counts in the game itself | `limits.cpu_ms = 5000` as a backstop | + +Reference points: a 10-minute replay is 3.3 MB raw / ~210 KB gzipped, well inside the limits. + +### Failure and retry semantics (deliberate) + +| Situation | Result | Consumes the run? | +| --- | --- | --- | +| Truncated/oversized/non-JSON body, bad gzip, wrong envelope, invalid nickname | 4xx | **No** — fix and resend | +| Replay content fails verification (schema, seed, rules, config, too fast, no game over, extra ticks, score claim mismatch) | 422 `replay_rejected` + `reason` | **Yes**, terminal (no oracle for iterating on forgeries) | +| Internal error while recording (database down, bug) | 503 | **No** — the claim is released; retry later | +| Verifier crashes on a crafted payload | 422 `invalid_replay` | Yes (a crafted payload cannot be resubmitted forever) | +| Response lost after acceptance; client resends identical bytes | 200, `replayed: true`, same score id | Idempotent | +| Another request is mid-verification | 409 `run_in_progress` + `Retry-After` | No | +| Worker died holding a claim | After a 30 s lease any request may take over | No | + +## 5. Database schema + +Migration `server/migrations/0001_init.sql` (applied to D1 with `wrangler d1 migrations apply`): + +**`runs`** — `id` (PK, UUID), `token_hash`, `seed` (0…2³²−1), `rules_version`, `config_json`, `created_at`, `expires_at`, `status` (`issued|verifying|accepted|rejected`), `claim_token`, `claimed_at`, `replay_hash` (SHA-256 of the submitted body: enables idempotent retries; **not** proof of authenticity), `finished_at`, `score_id`, `reject_reason`, `reject_detail`, `issuer_hash`. CHECK constraints tie `status='accepted'` ⇔ `score_id` set and `status='rejected'` ⇔ `reject_reason` set. + +**`scores`** — `id` (PK, UUID, public), `run_id` (**UNIQUE**, FK → runs), `score`, `nickname`, `completed_at` (server clock), `rules_version`, `ticks`, `duration_ms`, `asteroids_destroyed`, `ufos_destroyed`, `reported_controls` (**untrusted** client metadata), `visibility` (`visible|hidden`), `hidden_reason`, `hidden_at`. + +**`rate_limits`** — `(bucket, window_start)` PK, `count`. + +Indexes: partial board index `(rules_version, score DESC, completed_at ASC, id ASC) WHERE visibility='visible' AND score>0` (serves every leaderboard read) and `(rules_version, completed_at)` for weekly ranges. **Replays are not stored.** Only `replay_hash` is kept. Housekeeping (daily cron): abandoned runs a day past expiry, rejected runs after 30 days, stale rate-limit rows. Accepted runs are kept. + +## 6. API contracts + +All JSON, all under `/api/v1`. Errors: `{"error":{"code":"…","message":"…", …}}`. + +### `POST /runs` → 201 + +```json +{ + "runId": "8c9f3e1a-5b0e-4f55-8d71-2d9bf0a1c001", + "token": "kQ3x…43 chars of base64url…", + "seed": 3898162777, + "rulesVersion": "1.0.0", + "schemaVersion": 1, + "tickRate": 60, + "config": { "playerCount": 1, "livesMode": "independent", "friendlyFire": false, "speed": [1, 1] }, + "issuedAt": "2026-10-22T15:00:00.000Z", + "expiresAt": "2026-10-22T16:00:00.000Z" +} +``` +The `token` is shown once. Errors: 429 `rate_limited` (+ `Retry-After`), 403 `origin_not_allowed`. + +### `POST /runs/:id/submit` → 200 + +Request body (before optional gzip): `{"replay": {header, inputs, totalTicks, claimedResult?}, "nickname": "Dave J", "controls": {"scheme": "keyboard"}}`. + +```json +{ + "status": "accepted", + "replayed": false, + "score": { "id": "c649cb33-…", "nickname": "Dave J", "score": 9114, "completedAt": "2026-10-22T15:03:11.204Z", "durationSeconds": 127.02 }, + "ranks": { "allTime": 3, "weekly": 1 } +} +``` +Rejection (422): +```json +{ "error": { "code": "replay_rejected", "message": "The replay did not verify", "status": "rejected", "reason": "score_mismatch", "detail": "Score mismatch: claimed 9214 but independently calculated 9114" } } +``` +`reason` ∈ `invalid_replay, seed_mismatch, rules_mismatch, config_mismatch, too_long, too_fast, not_game_over, score_mismatch`. + +| Status | `error.code` | Meaning | +| --- | --- | --- | +| 400 | `invalid_json`, `invalid_submission`, `invalid_nickname`, `invalid_body`, `empty_body` | Envelope/transport problem; run still open | +| 401 | `invalid_token` | Missing/wrong token | +| 404 | `run_not_found` | Unknown or malformed run id | +| 409 | `run_rejected`, `run_already_submitted`, `run_in_progress`, `run_busy` | Terminal or busy state | +| 410 | `run_expired` | Past `expiresAt` | +| 413 | `payload_too_large` | Over a size limit | +| 415 | `unsupported_encoding` | Not identity/gzip | +| 422 | `replay_rejected` | Verification failed | +| 429 | `rate_limited` | Throttled | +| 503 | `service_unavailable` | Could not record; retry | + +### `GET /leaderboard/all-time` and `/leaderboard/weekly` → 200 + +Query: `limit` (1–100, default 10), `offset` (0–1000). Anything else → 400 `invalid_parameter`. + +```json +{ + "scope": "weekly", "rulesVersion": "1.0.0", + "timeZone": "America/Halifax", "weekStart": "2026-10-19T03:00:00.000Z", "weekEnd": "2026-10-26T03:00:00.000Z", + "limit": 10, "offset": 0, "total": 42, + "entries": [ { "id": "c649cb33-…", "rank": 1, "nickname": "Dave J", "score": 9114, "completedAt": "2026-10-22T15:03:11.204Z", "durationSeconds": 127.02 } ] +} +``` +### `GET /scores/:id` → 200 `{ "score": {…}, "ranks": { "allTime": 3, "weekly": 1 } }` (404 if unknown **or hidden**) +### `GET /health` → `{ "ok": true, "rulesVersion": "1.0.0", "schemaVersion": 1, "maxTicks": 72000, "time": "…" }` +### `POST /admin/scores/:id/visibility` — body `{"visible": false, "reason": "offensive"}`, `Authorization: Bearer `. The route does not exist (404) unless `ADMIN_TOKEN` (≥ 16 chars) is configured; never sends CORS headers; failed attempts are rate limited. + +Public entries expose only `id, rank, nickname, score, completedAt, durationSeconds`. + +## 7. Atomic, one-use submission + +* **Claim:** `UPDATE runs SET status='verifying', claim_token=?, … WHERE id=? AND expires_at>? AND (status='issued' OR (status='verifying' AND claimed_at<=?lease))`. `changes = 1` means this request owns the run; everyone else gets the current state (409 / idempotent 200). +* **Finalize (one atomic `batch`):** `INSERT INTO scores … SELECT … WHERE EXISTS (SELECT 1 FROM runs WHERE id=? AND status='verifying' AND claim_token=?)` then `UPDATE runs SET status='accepted', score_id=? WHERE … claim_token=?`. If the claim was lost to a lease takeover, neither statement does anything. +* **Backstop:** `scores.run_id UNIQUE`. A bug in the state machine still cannot create two entries for a run (tested by inserting a duplicate directly). + +Tested: 12 simultaneous identical submissions and 5 simultaneous *different* ones on one database; 16 requests spread over **4 separate SQLite connections** to one file (the multi-instance case); injected database failures at the score insert and at claim release; a 10-way concurrent submit against the real Worker/D1. + +*Honesty note:* workerd runs the CPU-bound verification of one isolate's requests one at a time, so in the real-Worker test the later requests arrive after the first has finished and are answered idempotently. The genuinely interleaved race (claim vs claim) is exercised by the multi-connection SQLite tests, which run the identical SQL. + +## 8. Scoring-version compatibility policy + +* `GAMEPLAY_RULES_VERSION` (`src/replay/constants.ts`) must change whenever physics, spawning, collision or scoring changes. The server only verifies the version it was built with, and the replay header and the run must both match it. +* Leaderboards **only rank scores of the current rules version**; older scores stay in the table (not deleted) but are not mixed in. +* A client built for different rules refuses to start ranked play (`update_required`) when the challenge's rules version differs from its own. +* Deploy the new game and the new Worker together. Runs issued before a server upgrade can no longer be reproduced and are rejected with `rules_mismatch` (a player mid-game at deploy time loses that one run). + +## 9. Weekly / all-time definitions + +* **All-time:** visible scores > 0 under the current rules version. +* **Weekly:** the same, with `completed_at` in `[Monday 00:00, next Monday 00:00)` in **America/Halifax**, from the server's own completion timestamp. Window boundaries are computed with real zone offsets, so a DST week is 167 or 169 hours. Tested: ordinary week, the exact instants either side of Monday midnight, spring (2026-03-08) and autumn (2026-11-01) changes, the New Year week, and a year of random instants tiling without gaps or overlaps. +* **Order:** score descending, then earlier `completed_at`, then smaller `id`. Ranks are ordinal (no shared places). Hidden, zero-score, and other-version entries are excluded; ranks of lower entries shift when an entry is hidden. +* Zero-score runs are accepted (the run is finished, one-use) but never listed. + +## 10. Abuse prevention + +One-use run ids; CSPRNG tokens and seeds; expiry; atomic state transitions; per-client and global rate limits stored in the database (exact, shared by all instances); credentials and cheap checks before the body is read; strict size/encoding limits; validation before simulation; minimum-elapsed-time rule; rejection of non-approved configuration; an `Origin` allow-list for browser POSTs (hygiene, not authentication); nickname charset with no markup characters; admin routes disabled by default; no frontend API key (none would be secret). Rate limits (defaults, env-tunable): 30 run starts and 30 submissions per client-hash per hour; 3,000 starts and 1,200 submissions per hour globally. Client identity is a salted hash of `CF-Connecting-IP`, used only as one coarse layer; shared networks share a bucket, so limits are generous and nothing is *granted* based on an IP. Turnstile was not added: it adds friction and the main risk (bots playing well) is not something it fixes. + +Minimal logging (no IPs, nicknames or tokens): `run_rejected`, `verifier_threw`, `submit_failed`, `unhandled`, `prune`. + +Moderation: `POST /admin/scores/:id/visibility`, or directly: `wrangler d1 execute asteroids-leaderboard --remote --command "UPDATE scores SET visibility='hidden', hidden_reason='…', hidden_at=strftime('%s','now')*1000 WHERE id='…'"`. + +## 11. What an attacker can and cannot do + +Assume the attacker reads the JavaScript, edits local state, hand-writes replay JSON, runs the simulation headlessly, scripts inputs, replays HTTP requests and calls the API directly. + +| Attack | Outcome | +| --- | --- | +| POST a score, or a replay with an inflated claimed score | Rejected: the server's own replay decides | +| Choose a convenient seed, rules version or co-op/speed config | Rejected: must equal what the server issued | +| Edit, reorder, pad or truncate inputs | Rejected (`invalid_replay`/`score_mismatch`/`not_game_over`) | +| Reuse a token / re-send a captured request | Same bytes → the original result, no second entry; different bytes → 409 | +| Use another run's token | 401 | +| Submit a long replay immediately | `too_fast` | +| Flood run starts or submissions | 429; global CPU ceiling | +| Gzip bomb / giant body / truncated upload | 413 / 400 without consuming CPU on simulation | +| Submit from a hostile web page | Refused by Origin check; a token is required anyway | + +## 12. Remaining security limitations (not hidden) + +1. **Bots are not detected.** The seed is revealed at issue time, so an attacker can run an optimizer or AI offline against *that exact seed* for up to the challenge lifetime (60 min), then submit a perfectly valid replay that a human could never produce. A bot (like `server/testing/bot.mjs`) is indistinguishable from a player. Verification proves the score is *reproducible under the rules*, not that it was *achieved by a person*. Mitigations available later: shorter challenge lifetime, statistical input analysis (reaction-time/APM heuristics), hiding top replays for review, Turnstile, device-level reputation. +2. **No identity.** Nicknames are not unique and not owned. A browser-local score list is a convenience only; clearing storage or switching devices loses it. Anyone can use any nickname. +3. **Reported controls are self-declared.** `reported_controls` is for analysis; a modified client can lie, and ranking never depends on it. +4. **Offensive nicknames** are limited by charset only; there is no word filter. Moderation is after-the-fact (hide). +5. **Denial of service** is bounded, not prevented: a flood of cheap requests still costs request fees, and the global rate limits can be exhausted by an attacker to block legitimate starts/submissions. Consider a Cloudflare WAF rate-limiting rule at the edge (an account setting, not done here). +6. **Rate limiting by IP** is imperfect in both directions (shared NATs, rotating proxies). +7. **In-flight runs lost on deploy** if rules change; a run longer than 20 simulated minutes cannot be submitted (the client reports it; the game does not yet stop the run at the cap). +8. **Memory/CPU limits have been checked on local workerd only**, not on Cloudflare's network. +9. **Only single-player, keyboard-driven ranked play was exercised end-to-end in a browser.** Touch and gamepad metadata are unit-tested (`tests/ranked.test.ts`) but not driven through a ranked browser run. +10. **D1 is a single-region primary** and there is no backup beyond D1 Time Travel. + +## 13. Local setup and testing + +Requires Node 22+ (`node:sqlite` is used by tests; workerd is downloaded by `npm install`) and a Chrome/Edge for the browser tests (or `CHROME_PATH`). + +```bash +cd phaser-asteroids && npm install +cd server && npm install # wrangler, @types/node (devDependencies only) + +# Run the API locally (workerd + local D1 under server/.wrangler/state; no Cloudflare account needed) +npm run migrate:local +npm run dev # http://127.0.0.1:8787 +# optional secrets for local admin/IP hashing: server/.dev.vars (git-ignored) +# ADMIN_TOKEN=some-long-random-string-of-16+chars +# IP_HASH_SALT=any-random-string + +# Run the game against it (separate terminal, from phaser-asteroids/) +npm run dev # http://localhost:5173 +# open http://localhost:5173/?ranked=1&nick=YourName (PLAY now requests a server-issued run) +``` + +| Command (from `phaser-asteroids/`) | What it proves | Runtime | +| --- | --- | --- | +| `npm test` | All unit tests, including server (`node:sqlite`, same SQL/migrations) and client | local, mocked clock | +| `npm run test:server` | Only the 108 server tests: lifecycle, forgery, concurrency, limits, leaderboard, weeks, moderation, nicknames, rate limits | local, mocked clock | +| `npm run test:worker` | 32 HTTP checks against the **real Worker in workerd with a real local D1** and the real clock | local service | +| `npm run test:ranked` | **Chromium → game → Worker → D1 → leaderboard**, plus casual play with the backend down | local service, real browser | +| `npm run bench:workerd` | CPU/latency of the verifier in workerd | local service | +| `npm run typecheck`, `cd server && npx tsc --noEmit -p tsconfig.json` | Types | — | + +Nothing above is a test against production Cloudflare infrastructure. + +## 14. Deployment procedure (not executed; needs your approval and account) + +1. `cd phaser-asteroids/server && npx wrangler login` and upgrade the account to **Workers Paid** in the dashboard (US$5/month). +2. `npx wrangler d1 create asteroids-leaderboard` — paste the printed `database_id` into `[env.production]` in `wrangler.toml`. +3. Set `ALLOWED_ORIGINS` in `[env.production.vars]` (default `https://djblackett.github.io`; include a custom domain if used). +4. `npx wrangler d1 migrations apply asteroids-leaderboard --env production --remote` +5. Secrets: `npx wrangler secret put IP_HASH_SALT --env production` (any long random string) and, if you want moderation via API, `npx wrangler secret put ADMIN_TOKEN --env production` (≥ 16 chars). +6. `npx wrangler deploy --env production` — note the `*.workers.dev` URL (or attach a custom domain). +7. Check: `curl https:///api/v1/health`. +8. Point the game at it: build the site with `VITE_LEADERBOARD_API_URL=https://` (for GitHub Pages, set it in the build workflow's environment). Until it is set, `?ranked` shows "Ranked play is not available in this build" and casual play is untouched. +9. Smoke test: open `https://…/?ranked=1`, play a short game, confirm the score on `GET /api/v1/leaderboard/all-time`. + +**Monitoring:** `npx wrangler tail --env production` (look for `run_rejected`, `verifier_threw`, `submit_failed`, `unhandled`); Cloudflare dashboard → Workers → Metrics (CPU time p50/p99, errors) and D1 metrics. Confirm real-world CPU per verification stays well under the 5 s cap. + +**Rollback:** `npx wrangler rollback --env production` restores the previous Worker version (also available in the dashboard). Migrations are forward-only; 0001 is additive. For data problems, D1 Time Travel: `npx wrangler d1 time-travel restore asteroids-leaderboard --env production --timestamp=`. Removing `VITE_LEADERBOARD_API_URL` from the site build turns ranked play off without touching the backend. + +## 15. Future client UI integration + +Everything the UI needs is already exposed by the game and API: + +* **Start:** `requestChallenge()` / `StartScene.startRanked()` (`src/ranked/api.ts`); replace the `?ranked` dev flag with a menu item. +* **State:** `rankedSession` (`src/ranked/session.ts`) with phases `requesting → playing → submitting → accepted | rejected | failed | abandoned`; mirrored on `window.__ASTEROIDS_RANKED__` for tests. +* **Result:** `outcome.score` and `outcome.ranks` (all-time and weekly rank) after acceptance; the game-over screen already shows one status line. +* **Personal best:** `src/ranked/localScores.ts` keeps accepted `{id, score, at}` on this device; `GET /scores/:id` returns the current rank for each id. +* **Nickname:** `?nick=` / stored value today; add an input and let the server's 400 `invalid_nickname` message drive validation text. +* **Leaderboard screen:** `GET /leaderboard/weekly|all-time` (page with `limit`/`offset`). Render nicknames with text APIs only. Show `weekEnd` as the reset time. +* Handle `failed`/`rejected` by offering "Play again (ranked)" which goes back to the title and requests a *new* challenge, as RETRY already does. diff --git a/phaser-asteroids/.gitignore b/phaser-asteroids/.gitignore index edfaeff..c0886e8 100644 --- a/phaser-asteroids/.gitignore +++ b/phaser-asteroids/.gitignore @@ -3,3 +3,7 @@ dist/ *.log scripts/.smoke-output/ .node/ + +# Leaderboard backend local state and secrets +server/.wrangler/ +server/.dev.vars diff --git a/phaser-asteroids/package.json b/phaser-asteroids/package.json index 14b027e..879908a 100644 --- a/phaser-asteroids/package.json +++ b/phaser-asteroids/package.json @@ -20,7 +20,11 @@ "test:touch": "npm run build && node scripts/touch.mjs", "test:music": "npm run build && node scripts/music.mjs", "test:menu": "npm run build && node scripts/menu.mjs", - "test:pages": "npm run build && node scripts/pages-check.mjs" + "test:pages": "npm run build && node scripts/pages-check.mjs", + "test:server": "vitest run server/tests", + "test:ranked": "npm run build && node scripts/ranked-browser.mjs", + "test:worker": "npm run build && node server/scripts/worker-e2e.mjs", + "bench:workerd": "npm run build && node server/scripts/bench-workerd.mjs" }, "dependencies": { "phaser": "4.2.1" diff --git a/phaser-asteroids/scripts/lib/browserPlay.mjs b/phaser-asteroids/scripts/lib/browserPlay.mjs new file mode 100644 index 0000000..cbd5969 --- /dev/null +++ b/phaser-asteroids/scripts/lib/browserPlay.mjs @@ -0,0 +1,90 @@ +// Plays a real game in Chromium through the keyboard: hunts asteroids and power-ups until it has scored, then flies into an asteroid +// to end the run naturally. Same approach as the Phase 1 nonzero-score browser test (scripts/replay-browser.mjs), reusable. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** Returns the largest combo observed. The caller waits for game over (the ship is flying into an asteroid when this returns). */ +export async function playUntilScoredThenDie(page, { maxSteps = 300 } = {}) { + let seekSuicide = false; + let rotating = null; + let thrusting = false; + let maxCombo = 0; + + for (let step = 0; step < maxSteps; step++) { + const status = await page.evaluate(() => { + const sim = window.__game.scene.getScene('GameScene').sim; + if (sim.isGameOver) return { isOver: true }; + return { + isOver: false, + px: sim.player.position.x, + py: sim.player.position.y, + rot: sim.player.rotation, + score: sim.totalScore, + combo: sim.combo.count, + lasers: sim.player.laser.shotsRemaining, + powerups: sim.powerups.filter((p) => p.alive).map((p) => ({ x: p.position.x, y: p.position.y })), + asteroids: sim.asteroids.filter((a) => a.alive && !a.dying).map((a) => ({ x: a.position.x, y: a.position.y })), + }; + }); + if (status.isOver) break; + maxCombo = Math.max(maxCombo, status.combo); + if (!seekSuicide && ((status.score >= 60 && maxCombo >= 2) || status.score >= 150 || step >= 200)) seekSuicide = true; + + let target = null; + let isPowerup = false; + if (!seekSuicide && status.powerups.length > 0) { + target = status.powerups[0]; + isPowerup = true; + } else if (status.asteroids.length > 0) { + let best = Infinity; + for (const a of status.asteroids) { + const d = Math.hypot(a.x - status.px, a.y - status.py); + if (d < best) { + best = d; + target = a; + } + } + } + if (!target) { + await sleep(50); + continue; + } + + const dx = target.x - status.px; + const dy = target.y - status.py; + const dist = Math.hypot(dx, dy); + const heading = ((((Math.atan2(-dx, dy) * 180) / Math.PI) % 360) + 360) % 360; + let diff = heading - status.rot; + while (diff < -180) diff += 360; + while (diff > 180) diff -= 360; + + const want = diff < -12 ? 'KeyA' : diff > 12 ? 'KeyD' : null; + if (want !== rotating) { + if (rotating) await page.keyboard.up(rotating); + if (want) await page.keyboard.down(want); + rotating = want; + } + + if (seekSuicide) { + if (!thrusting) { + await page.keyboard.down('KeyW'); + thrusting = true; + } + } else { + if (Math.abs(diff) < 30) { + await page.keyboard.press('Space'); + if (status.lasers > 0 && step % 12 === 0) await page.keyboard.press('KeyE'); + } + if (step === 25 || step === 55) await page.keyboard.press('ShiftLeft'); + const shouldThrust = isPowerup || (dist > 350 && Math.abs(diff) < 20); + if (shouldThrust !== thrusting) { + await page.keyboard[shouldThrust ? 'down' : 'up']('KeyW'); + thrusting = shouldThrust; + } + } + await sleep(60); + } + + if (rotating) await page.keyboard.up(rotating); + if (!thrusting) await page.keyboard.down('KeyW'); + return maxCombo; +} diff --git a/phaser-asteroids/scripts/ranked-browser.mjs b/phaser-asteroids/scripts/ranked-browser.mjs new file mode 100644 index 0000000..50b29af --- /dev/null +++ b/phaser-asteroids/scripts/ranked-browser.mjs @@ -0,0 +1,224 @@ +// End-to-end: real Chromium -> real game build -> real Cloudflare Worker runtime (workerd) -> real local D1 database -> public API. +// Nothing about verification is mocked. Also proves casual play is unaffected when the backend is offline. +// +// npm run test:ranked (builds first) +// +// Lifecycle exercised: +// Chromium asks for a ranked run -> Worker issues seed/config -> the browser plays the deterministic game and records inputs -> +// at game over it submits the recording -> the Worker replays it independently -> D1 stores the SERVER's score -> +// GET /leaderboard returns that score. +import { spawn, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { chromium } from 'playwright-core'; +import { playUntilScoredThenDie } from './lib/browserPlay.mjs'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const serverDir = path.join(root, 'server'); +const { verifyReplay } = await import(pathToFileURL(path.join(root, 'dist', 'node', 'index.js')).href); +const GAME_PORT = Number(process.env.RANKED_GAME_PORT ?? 4410); // must be in wrangler.toml ALLOWED_ORIGINS +const API_PORT = Number(process.env.RANKED_API_PORT ?? 8793); +const GAME = `http://127.0.0.1:${GAME_PORT}/`; +const API = `http://127.0.0.1:${API_PORT}`; +const persist = fs.mkdtempSync(path.join(os.tmpdir(), 'asteroids-ranked-e2e-')); +const wranglerBin = path.join(serverDir, 'node_modules', 'wrangler', 'bin', 'wrangler.js'); +const env = { ...process.env, WRANGLER_SEND_METRICS: 'false', CI: '1', NO_COLOR: '1' }; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let failures = 0; +let total = 0; +function check(name, ok, detail = '') { + total++; + if (!ok) failures++; + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` -- ${detail}` : ''}`); +} + +function findChrome() { + const candidates = [ + process.env.CHROME_PATH, + 'C:/Program Files/Google/Chrome/Application/chrome.exe', + 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe', + 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/usr/bin/google-chrome', + '/usr/bin/chromium', + '/usr/bin/chromium-browser', + ].filter(Boolean); + const found = candidates.find((p) => fs.existsSync(p)); + if (!found) throw new Error('No Chrome/Chromium found. Set CHROME_PATH to a browser executable.'); + return found; +} + +async function waitFor(url, ok = (s) => s === 200) { + for (let i = 0; i < 200; i++) { + const status = await new Promise((resolve) => http.get(url, (res) => (res.resume(), resolve(res.statusCode))).on('error', () => resolve(0))); + if (ok(status)) return; + await sleep(150); + } + throw new Error(`${url} did not come up`); +} + +if (!fs.existsSync(path.join(root, 'dist', 'index.html')) || !fs.existsSync(path.join(root, 'dist', 'node', 'index.js'))) { + throw new Error('dist/ is missing; run `npm run build` first.'); +} + +const migrate = spawnSync(process.execPath, [wranglerBin, 'd1', 'migrations', 'apply', 'asteroids-leaderboard', '--local', '--persist-to', persist], { cwd: serverDir, env, encoding: 'utf8' }); +check('local D1 migrated from the repository migration files', migrate.status === 0, migrate.status === 0 ? '' : (migrate.stdout + migrate.stderr).slice(-300)); +if (migrate.status !== 0) process.exit(1); + +const worker = spawn( + process.execPath, + [wranglerBin, 'dev', '--local', '--port', String(API_PORT), '--persist-to', persist, '--var', 'IP_HASH_SALT:ranked-e2e'], + { cwd: serverDir, env, stdio: ['ignore', 'pipe', 'pipe'] }, +); +let workerLog = ''; +worker.stdout.on('data', (d) => (workerLog += d)); +worker.stderr.on('data', (d) => (workerLog += d)); +const preview = spawn(process.execPath, [path.join(root, 'node_modules', 'vite', 'bin', 'vite.js'), 'preview', '--port', String(GAME_PORT), '--strictPort', '--host', '127.0.0.1'], { cwd: root, stdio: 'ignore' }); +const stopAll = () => { + worker.kill(); + preview.kill(); +}; +process.on('exit', stopAll); + +let browser; +try { + await waitFor(`${API}/api/v1/health`); + await waitFor(GAME); + browser = await chromium.launch({ executablePath: findChrome(), headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }); + + // ------------------------------------------------------------------------------------------------------------------------ + console.log('\n--- Part 1: ranked run, Chromium -> Worker -> D1 -> leaderboard ---'); + const page = await browser.newPage({ viewport: { width: 1280, height: 720 } }); + const apiCalls = []; + page.on('request', (r) => r.url().startsWith(API) && apiCalls.push(`${r.method()} ${new URL(r.url()).pathname}`)); + const NICK = 'Browser Ace'; + + let record = null; + let browserScore = 0; + let attempts = 0; + let maxCombo = 0; + while (attempts < 4) { + attempts++; + await page.goto(`${GAME}?ranked=1&api=${encodeURIComponent(API)}&nick=${encodeURIComponent(NICK)}&debug=1`); + await page.waitForFunction(() => window.__game?.scene.isActive('StartScene'), null, { timeout: 20000 }); + await page.keyboard.press('Space'); // PLAY: asks the server for a challenge first + await page.waitForFunction(() => window.__game?.scene.isActive('GameScene'), null, { timeout: 10000 }); + await page.waitForFunction(() => window.__ASTEROIDS_REPLAY__?.isVerified === true, null, { timeout: 5000 }); + + const session = await page.evaluate(() => ({ ranked: window.__ASTEROIDS_RANKED__, seed: window.__ASTEROIDS_REPLAY__.seed })); + if (attempts === 1) { + check('challenge issued by the server before play (phase=playing, run id held)', session.ranked?.phase === 'playing' && /^[0-9a-f-]{36}$/.test(session.ranked.runId ?? '')); + check('simulation seed is the server-issued seed, not the default or a URL value', Number.isInteger(session.seed) && session.seed > 1); + check('the challenge came from POST /api/v1/runs', apiCalls.includes('POST /api/v1/runs')); + const urlSeedIgnored = await page.evaluate(() => new URLSearchParams(location.search).has('seed')); + check('no client-chosen seed in the launch URL', urlSeedIgnored === false); + } + + maxCombo = await playUntilScoredThenDie(page); + await page.waitForFunction(() => window.__ASTEROIDS_REPLAY__?.isGameOver() === true, null, { timeout: 60000, polling: 50 }); + browserScore = await page.evaluate(() => window.__ASTEROIDS_REPLAY__.getScore()); + record = await page.evaluate(() => window.__ASTEROIDS_REPLAY__.getReplay()); + if (browserScore > 0) break; + console.log(` attempt ${attempts} scored 0; asking for a fresh server-issued run`); + } + check('browser game reached game over with a nonzero score', browserScore > 0, `score=${browserScore} after ${attempts} attempt(s), max combo ${maxCombo}`); + + await page.waitForFunction(() => ['accepted', 'rejected', 'failed'].includes(window.__ASTEROIDS_RANKED__?.phase), null, { timeout: 45000 }); + const ranked = await page.evaluate(() => window.__ASTEROIDS_RANKED__); + check('browser submitted the recording and the server accepted it', ranked.phase === 'accepted', `phase=${ranked.phase} ${ranked.message}`); + check('server-verified score equals the browser\'s own score', ranked.verifiedScore === browserScore, `server=${ranked.verifiedScore} browser=${browserScore}`); + check('submission POSTed to /submit (gzip) exactly once', apiCalls.filter((c) => /POST \/api\/v1\/runs\/[0-9a-f-]+\/submit/.test(c)).length === 1); + + const node = verifyReplay(record); + check('an independent Node replay agrees with the server\'s score', node.valid && node.calculatedScore === ranked.verifiedScore, `node=${node.calculatedScore}`); + check('recording carries no client score for the server to trust (claim only cross-checked)', record.claimedResult?.score === browserScore); + + const overlay = await page.evaluate(() => { + const texts = []; + const walk = (list) => list.forEach((o) => (o.type === 'Text' ? texts.push(o.text) : o.list && walk(o.list))); + walk(window.__game.scene.getScene('GameScene').children.list); + const t = texts; + return t.find((x) => x.startsWith('VERIFIED')) ?? t.find((x) => x.startsWith('RANKED')) ?? ''; + }); + check('game-over screen shows the server-verified result', overlay.startsWith('VERIFIED'), overlay); + + const board = await (await fetch(`${API}/api/v1/leaderboard/all-time`)).json(); + const weekly = await (await fetch(`${API}/api/v1/leaderboard/weekly`)).json(); + const entry = board.entries.find((e) => e.id === ranked.outcome.score.id); + check('GET /leaderboard/all-time returns that score', !!entry && entry.score === browserScore && entry.nickname === NICK, JSON.stringify(entry)); + check('GET /leaderboard/weekly returns it too', weekly.entries.some((e) => e.id === ranked.outcome.score.id)); + check('exactly one score row exists', board.total === 1); + + const stored = await page.evaluate(() => localStorage.getItem('asteroids.rankedScores')); + check('device-local personal best remembers the accepted score id', !!stored && JSON.parse(stored)[0].id === ranked.outcome.score.id); + + const sql = spawnSync( + process.execPath, + [wranglerBin, 'd1', 'execute', 'asteroids-leaderboard', '--local', '--persist-to', persist, '--json', '--command', 'SELECT s.score, s.reported_controls, s.ticks, r.status, r.seed FROM scores s JOIN runs r ON r.id = s.run_id'], + { cwd: serverDir, env, encoding: 'utf8' }, + ); + let row = null; + try { + row = JSON.parse(sql.stdout)[0].results[0]; + } catch {} + check('D1 holds the authoritative score and the run is terminal (accepted)', row?.score === browserScore && row?.status === 'accepted', JSON.stringify(row)); + check('D1 stored the server-issued seed that the browser used', row?.seed === record.header.seed); + check('reported control scheme was recorded as untrusted metadata (keyboard)', row?.reported_controls === 'keyboard', `reported_controls=${row?.reported_controls}`); + + // The challenge is single-use: nothing in the page can resubmit it. + const reused = await page.evaluate(() => window.__ASTEROIDS_RANKED__.runId); + const resubmit = await fetch(`${API}/api/v1/runs/${reused}/submit`, { method: 'POST', headers: { authorization: 'Bearer guessed-token' }, body: '{}' }); + check('a guessed credential cannot touch the finished run (401)', resubmit.status === 401); + + // After game over, RETRY returns to the title screen: a ranked challenge is never silently reused or downgraded. + await sleep(2200); + await page.keyboard.press('KeyR'); + await page.waitForFunction(() => window.__game?.scene.isActive('StartScene'), null, { timeout: 5000 }); + check('RETRY after a ranked game returns to the title screen (needs a new server challenge)', true); + + // ------------------------------------------------------------------------------------------------------------------------ + console.log('\n--- Part 2: backend offline ---'); + worker.kill(); + await sleep(1500); + const offline = await fetch(`${API}/api/v1/health`).then(() => true, () => false); + check('the backend is really down', offline === false); + + const casual = await browser.newPage({ viewport: { width: 1280, height: 720 } }); + const casualApiCalls = []; + casual.on('request', (r) => /\/api\/v1\//.test(r.url()) && casualApiCalls.push(r.url())); + await casual.goto(`${GAME}?debug=1&api=${encodeURIComponent(API)}`); + await casual.waitForFunction(() => window.__game?.scene.isActive('StartScene'), null, { timeout: 20000 }); + await casual.keyboard.press('Space'); + await casual.waitForFunction(() => window.__game?.scene.isActive('GameScene'), null, { timeout: 5000 }); + const t1 = await casual.evaluate(() => window.__game.scene.getScene('GameScene').sim.time); + await sleep(1200); + const t2 = await casual.evaluate(() => window.__game.scene.getScene('GameScene').sim.time); + check('casual game starts instantly and runs with the backend offline', t2 - t1 > 0.8, `sim clock advanced ${(t2 - t1).toFixed(2)} s in ~1.2 s`); + check('casual game is not a recorded/verified run and has no ranked state', await casual.evaluate(() => !window.__ASTEROIDS_REPLAY__ && !window.__ASTEROIDS_RANKED__)); + check('casual game never contacts the leaderboard API', casualApiCalls.length === 0, `${casualApiCalls.length} calls`); + await casual.close(); + + const down = await browser.newPage({ viewport: { width: 1280, height: 720 } }); + await down.goto(`${GAME}?ranked=1&debug=1&api=${encodeURIComponent(API)}`); + await down.waitForFunction(() => window.__game?.scene.isActive('StartScene'), null, { timeout: 20000 }); + await down.keyboard.press('Space'); + await down.waitForFunction(() => window.__ASTEROIDS_RANKED__?.phase === 'failed', null, { timeout: 15000 }); + const stay = await down.evaluate(() => ({ start: window.__game.scene.isActive('StartScene'), game: window.__game.scene.isActive('GameScene') })); + check('ranked request with the backend down stays on the title screen (no silent casual game)', stay.start && !stay.game); + const noteText = await down.evaluate(() => window.__game.scene.getScene('StartScene').children.list.filter((o) => o.type === 'Text').map((o) => o.text).find((t) => t.startsWith('RANKED')) ?? ''); + check('the player is told ranked play is unavailable and can retry', /RANKED UNAVAILABLE/.test(noteText), noteText); + await down.close(); +} finally { + await browser?.close(); + stopAll(); + await sleep(500); + fs.rmSync(persist, { recursive: true, force: true }); +} + +console.log(`\n${total - failures}/${total} ranked browser-to-backend checks passed\n`); +if (failures) console.log('Worker log tail:\n' + workerLog.slice(-1500)); +process.exit(failures ? 1 : 0); diff --git a/phaser-asteroids/server/.dev.vars.example b/phaser-asteroids/server/.dev.vars.example new file mode 100644 index 0000000..013e0fa --- /dev/null +++ b/phaser-asteroids/server/.dev.vars.example @@ -0,0 +1,5 @@ +# Copy to .dev.vars (git-ignored) for local `wrangler dev`. Production uses `wrangler secret put`. +# ADMIN_TOKEN enables POST /api/v1/admin/scores/:id/visibility (must be 16+ characters). Omit it and the admin routes do not exist. +ADMIN_TOKEN=change-me-to-a-long-random-string +# Salt for hashing client IPs into rate-limit buckets. +IP_HASH_SALT=change-me-too diff --git a/phaser-asteroids/server/README.md b/phaser-asteroids/server/README.md new file mode 100644 index 0000000..90d03bc --- /dev/null +++ b/phaser-asteroids/server/README.md @@ -0,0 +1,17 @@ +# Asteroids leaderboard backend + +Cloudflare Worker + D1. A ranked score is accepted only if the server replays the player's recorded inputs, with the seed and configuration the server itself issued, and reproduces the result. + +Full design, API contracts, security analysis, cost estimate and deployment steps: [`../../docs/leaderboard-backend.md`](../../docs/leaderboard-backend.md). + +```bash +npm install # wrangler + @types/node (dev only) +npm run migrate:local # creates the local D1 database (server/.wrangler/state) +npm run dev # http://127.0.0.1:8787 (workerd, no Cloudflare account needed) +``` + +From `phaser-asteroids/`: `npm run test:server` (unit/adversarial), `npm run test:worker` (real workerd + D1), `npm run test:ranked` (Chromium end to end). + +Layout: `src/` portable service (+ `worker.ts`/`d1.ts` Cloudflare glue), `migrations/`, `tests/`, `testing/` (SQLite test adapter, autonomous bot), `scripts/` (integration and benchmark), `bench/` (feasibility Worker), `wrangler.toml`. + +Local secrets go in `.dev.vars` (git-ignored); copy `.dev.vars.example`. Nothing here deploys anything. diff --git a/phaser-asteroids/server/bench/worker.ts b/phaser-asteroids/server/bench/worker.ts new file mode 100644 index 0000000..ad63176 --- /dev/null +++ b/phaser-asteroids/server/bench/worker.ts @@ -0,0 +1,23 @@ +// Feasibility spike: runs the real verifyReplay() inside the Workers runtime (workerd) and reports timings. +// Not part of the product Worker. Used only by scripts/bench-workerd.mjs. +import { verifyReplay } from '../../src/replay/verifier'; + +export default { + async fetch(request: Request): Promise { + const t0 = performance.now(); + const d0 = Date.now(); + const text = await request.text(); + const parsed = JSON.parse(text); + const result = verifyReplay(parsed, { requireGameOver: true }); + return Response.json({ + valid: result.valid, + score: result.calculatedScore, + ticks: result.totalTicks, + error: result.error ?? null, + // In production Workers these clocks only advance on I/O, so they read ~0 for pure CPU work; the harness + // therefore measures wall time from outside. + insidePerfMs: performance.now() - t0, + insideDateMs: Date.now() - d0, + }); + }, +}; diff --git a/phaser-asteroids/server/migrations/0001_init.sql b/phaser-asteroids/server/migrations/0001_init.sql new file mode 100644 index 0000000..92a51db --- /dev/null +++ b/phaser-asteroids/server/migrations/0001_init.sql @@ -0,0 +1,69 @@ +-- Phaser Asteroids leaderboard: initial schema (SQLite dialect, applied by Cloudflare D1 migrations). +-- +-- Two principal tables: +-- runs one row per server-issued ranked challenge. Its `status` is a one-way state machine: +-- issued -> verifying -> accepted | rejected (verifying -> issued only when a claimant fails internally) +-- accepted and rejected are terminal. Every transition is a conditional UPDATE, so the database, not process memory, +-- decides who wins a race. +-- scores one row per *accepted* run, holding the score the SERVER computed by replaying the run. UNIQUE(run_id) is the final +-- backstop: even a bug in the state machine cannot give one run two leaderboard entries. +-- Plus a small fixed-window counter table for rate limiting. Replays themselves are never stored (only a hash, see runs.replay_hash). +-- All timestamps are integer milliseconds since the Unix epoch, taken from the server clock. + +CREATE TABLE runs ( + id TEXT PRIMARY KEY, -- random UUID, public (it appears in URLs) + token_hash TEXT NOT NULL, -- SHA-256 hex of the secret run token; the token itself is never stored + seed INTEGER NOT NULL CHECK (seed BETWEEN 0 AND 4294967295), + rules_version TEXT NOT NULL, -- GAMEPLAY_RULES_VERSION the run must be replayed under + config_json TEXT NOT NULL, -- the approved GameConfig, as issued + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'issued' CHECK (status IN ('issued', 'verifying', 'accepted', 'rejected')), + claim_token TEXT, -- random nonce held by the request currently verifying this run + claimed_at INTEGER, -- when that claim began (a stale claim can be taken over, see claimLeaseMs) + replay_hash TEXT, -- SHA-256 hex of the submitted body: makes a retry idempotent. NOT proof of authenticity. + finished_at INTEGER, -- when the run reached a terminal state + score_id TEXT, -- set exactly when status = 'accepted' + reject_reason TEXT, -- short machine code, set exactly when status = 'rejected' + reject_detail TEXT, -- truncated human-readable detail for diagnostics + issuer_hash TEXT, -- salted hash of the requester's IP (never the IP itself), for abuse triage only + CHECK ((status = 'accepted') = (score_id IS NOT NULL)), + CHECK ((status = 'rejected') = (reject_reason IS NOT NULL)) +); + +CREATE INDEX idx_runs_expires ON runs (expires_at); +CREATE INDEX idx_runs_finished ON runs (finished_at); + +CREATE TABLE scores ( + id TEXT PRIMARY KEY, -- random UUID, the public identifier of a leaderboard entry + run_id TEXT NOT NULL UNIQUE REFERENCES runs (id), + score INTEGER NOT NULL CHECK (score >= 0), + nickname TEXT NOT NULL, -- sanitised (see src/nickname.ts) + completed_at INTEGER NOT NULL, -- server time at which verification finished: drives the weekly window + rules_version TEXT NOT NULL, -- boards never mix rules versions + ticks INTEGER NOT NULL, + duration_ms INTEGER NOT NULL, -- simulated duration (ticks / 60 Hz), verified + asteroids_destroyed INTEGER NOT NULL DEFAULT 0, + ufos_destroyed INTEGER NOT NULL DEFAULT 0, + reported_controls TEXT NOT NULL DEFAULT 'unknown', -- UNTRUSTED client-reported control scheme; analysis only, never used for ranking + visibility TEXT NOT NULL DEFAULT 'visible' CHECK (visibility IN ('visible', 'hidden')), + hidden_reason TEXT, + hidden_at INTEGER +); + +-- Serves every leaderboard read: filter on rules version, order by (score DESC, completed_at ASC, id ASC). +-- Partial: hidden and zero-score entries never appear on a board, so they cost the index nothing. +CREATE INDEX idx_scores_board ON scores (rules_version, score DESC, completed_at ASC, id ASC) + WHERE visibility = 'visible' AND score > 0; + +-- Serves weekly reads and ranks (range scan on completed_at within a rules version). +CREATE INDEX idx_scores_week ON scores (rules_version, completed_at) + WHERE visibility = 'visible' AND score > 0; + +-- Fixed-window request counters. One row per (bucket key, window start); pruned by the scheduled cleanup. +CREATE TABLE rate_limits ( + bucket TEXT NOT NULL, + window_start INTEGER NOT NULL, + count INTEGER NOT NULL, + PRIMARY KEY (bucket, window_start) +) WITHOUT ROWID; diff --git a/phaser-asteroids/server/package-lock.json b/phaser-asteroids/server/package-lock.json new file mode 100644 index 0000000..bb456b2 --- /dev/null +++ b/phaser-asteroids/server/package-lock.json @@ -0,0 +1,1562 @@ +{ + "name": "asteroids-leaderboard-server", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "asteroids-leaderboard-server", + "version": "0.1.0", + "devDependencies": { + "@types/node": "^22.20.5", + "wrangler": "4.151.3" + } + }, + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", + "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261019.1.tgz", + "integrity": "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261019.1.tgz", + "integrity": "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261019.1.tgz", + "integrity": "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261019.1.tgz", + "integrity": "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261019.1.tgz", + "integrity": "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/miniflare": { + "version": "5.20261019.1-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.1-beta.tgz", + "integrity": "sha512-1n7MN2UqZnPniyYAqNuV1YEAaja66ozKGVCc5ZTmYQhTubnoAwGLccwb+ZWYLOajuw3pOaJ70u//bZMuURlRew==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.5", + "undici": "7.29.1", + "workerd": "1.20261019.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/undici": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", + "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unenv": { + "version": "2.0.0-rc.24", + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz", + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3" + } + }, + "node_modules/workerd": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261019.1.tgz", + "integrity": "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20261019.1", + "@cloudflare/workerd-darwin-arm64": "1.20261019.1", + "@cloudflare/workerd-linux-64": "1.20261019.1", + "@cloudflare/workerd-linux-arm64": "1.20261019.1", + "@cloudflare/workerd-windows-64": "1.20261019.1" + } + }, + "node_modules/wrangler": { + "version": "4.151.3", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.151.3.tgz", + "integrity": "sha512-mzPQLmkAhZUV7CdiAhE+hiIAJlS9xPL6vZe1B8oQFuWxFu7nmQnvHAVjcAcabwSGkXFXH9uspzXwHOFrfbQmqQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.0", + "@cloudflare/unenv-preset": "2.16.2", + "blake3-wasm": "2.1.5", + "esbuild": "0.28.2", + "miniflare": "5.20261019.1-beta", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20261019.1" + }, + "bin": { + "cf-wrangler": "bin/cf-wrangler.js", + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.0.0" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^5.20261019.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + } + } +} diff --git a/phaser-asteroids/server/package.json b/phaser-asteroids/server/package.json new file mode 100644 index 0000000..04da92b --- /dev/null +++ b/phaser-asteroids/server/package.json @@ -0,0 +1,19 @@ +{ + "name": "asteroids-leaderboard-server", + "private": true, + "version": "0.1.0", + "type": "module", + "description": "Cloudflare Worker + D1 leaderboard that independently replays ranked runs. See ../docs/leaderboard-backend.md.", + "scripts": { + "dev": "wrangler dev --local", + "migrate:local": "wrangler d1 migrations apply asteroids-leaderboard --local", + "typecheck": "tsc --noEmit -p tsconfig.json", + "test": "vitest run --root .. server/tests", + "test:worker": "node scripts/worker-e2e.mjs", + "bench:workerd": "node scripts/bench-workerd.mjs" + }, + "devDependencies": { + "@types/node": "^22.20.5", + "wrangler": "4.151.3" + } +} diff --git a/phaser-asteroids/server/scripts/bench-workerd.mjs b/phaser-asteroids/server/scripts/bench-workerd.mjs new file mode 100644 index 0000000..b00ac5d --- /dev/null +++ b/phaser-asteroids/server/scripts/bench-workerd.mjs @@ -0,0 +1,94 @@ +// Benchmarks replay verification inside the real Workers runtime (workerd via `wrangler dev --local`). +// Measures end-to-end request time from outside the isolate (in-isolate clocks do not advance during CPU work). +// +// npm run build (in ..) # builds dist/node for the bot +// node scripts/bench-workerd.mjs +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { generateBotReplay } from '../testing/bot.mjs'; + +const serverDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const engine = await import(pathToFileURL(path.join(serverDir, '..', 'dist', 'node', 'index.js')).href); +const PORT = Number(process.env.BENCH_PORT ?? 8791); +const ITER = 7; + +const wrangler = spawn(process.execPath, [path.join(serverDir, 'node_modules', 'wrangler', 'bin', 'wrangler.js'), 'dev', '--local', '-c', 'wrangler.bench.toml', '--port', String(PORT)], { + cwd: serverDir, + env: { ...process.env, WRANGLER_SEND_METRICS: 'false', CI: '1' }, + stdio: ['ignore', 'pipe', 'pipe'], +}); +let log = ''; +wrangler.stdout.on('data', (d) => (log += d)); +wrangler.stderr.on('data', (d) => (log += d)); +const stop = () => wrangler.kill(); +process.on('exit', stop); + +async function waitReady() { + for (let i = 0; i < 150; i++) { + try { + const r = await fetch(`http://127.0.0.1:${PORT}/`, { method: 'POST', body: '{}' }); + if (r.status) return; + } catch {} + await new Promise((r) => setTimeout(r, 200)); + } + throw new Error('wrangler dev did not start:\n' + log); +} + +const median = (a) => [...a].sort((x, y) => x - y)[Math.floor(a.length / 2)]; + +try { + await waitReady(); + console.log(`workerd via wrangler ${process.env.npm_package_version ?? ''} | node ${process.version} | ${process.platform} ${process.arch}\n`); + const cases = [ + ['2-min game', { seed: 54321 }], + ['10-min game', { seed: 4018 }], + ['2-min stress', { seed: 54321, stress: true }], + ]; + console.log('| scenario | ticks | score | raw JSON | workerd median | min | max | node median |'); + console.log('| --- | --- | --- | --- | --- | --- | --- | --- |'); + for (const [name, opts] of cases) { + const run = generateBotReplay(engine, opts); + const body = JSON.stringify(run.replay); + const times = []; + let last; + for (let i = 0; i < ITER; i++) { + const t = performance.now(); + const res = await fetch(`http://127.0.0.1:${PORT}/`, { method: 'POST', body }); + last = await res.json(); + times.push(performance.now() - t); + } + if (!last.valid || last.score !== run.score) throw new Error(`workerd result mismatch for ${name}: ${JSON.stringify(last)} vs node ${run.score}`); + const nodeTimes = []; + for (let i = 0; i < ITER; i++) { + const t = performance.now(); + engine.verifyReplay(JSON.parse(body)); + nodeTimes.push(performance.now() - t); + } + console.log(`| ${name} | ${last.ticks} | ${last.score} | ${(body.length / 1024).toFixed(0)} KB | ${median(times).toFixed(0)} ms | ${Math.min(...times).toFixed(0)} | ${Math.max(...times).toFixed(0)} | ${median(nodeTimes).toFixed(0)} ms |`); + } + + // Worst case for memory: the largest structurally valid body the ranked limits allow (72,000 input changes), parsed and validated + // in full, then simulated up to the point where the ship dies and the extra inputs are found to be impossible. + const big = generateBotReplay(engine, { seed: 4018 }).replay; + const maxTicks = 72000; + big.totalTicks = maxTicks; + delete big.claimedResult; + const lastTick = big.inputs[big.inputs.length - 1].tick; + for (let t = lastTick + 1; t < maxTicks; t++) big.inputs.push({ tick: t, input: { rotate: (t % 7) / 7, move: 1, shoot: t % 3 === 0, steer: { heading: (t * 3.17) % 360, mode: 'assist' } } }); + const bigBody = JSON.stringify(big); + const bigTimes = []; + let bigLast; + for (let i = 0; i < 5; i++) { + const t = performance.now(); + const res = await fetch(`http://127.0.0.1:${PORT}/`, { method: 'POST', body: bigBody }); + bigLast = await res.json(); + bigTimes.push(performance.now() - t); + } + console.log( + `\nmax-size body: ${big.inputs.length} input changes, ${(bigBody.length / 1024 / 1024).toFixed(1)} MiB raw (ranked limit 8 MiB), ` + + `workerd median ${median(bigTimes).toFixed(0)} ms, max ${Math.max(...bigTimes).toFixed(0)} ms, isolate survived; verdict valid=${bigLast.valid} (${bigLast.error})`, + ); +} finally { + stop(); +} diff --git a/phaser-asteroids/server/scripts/worker-e2e.mjs b/phaser-asteroids/server/scripts/worker-e2e.mjs new file mode 100644 index 0000000..fb0cad3 --- /dev/null +++ b/phaser-asteroids/server/scripts/worker-e2e.mjs @@ -0,0 +1,216 @@ +// Integration test against the REAL Worker runtime (workerd via `wrangler dev --local`) with a real local D1 database and the +// real clock. Nothing is mocked: runs are issued by the Worker, games are played by the headless bot, recordings are submitted over +// HTTP (some gzip-compressed, some concurrently) and read back through the public API. +// +// npm run build (in ..) # builds dist/node for the bot +// node scripts/worker-e2e.mjs (or: npm run test:worker in this folder) +// +// It takes about a minute because ranked runs cannot be submitted before the time they took to play has really elapsed. +import { spawn, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { gzipSync } from 'node:zlib'; +import { generateBotReplay } from '../testing/bot.mjs'; + +const serverDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const engine = await import(pathToFileURL(path.join(serverDir, '..', 'dist', 'node', 'index.js')).href); +const PORT = Number(process.env.WORKER_E2E_PORT ?? 8792); +const BASE = `http://127.0.0.1:${PORT}`; +const ADMIN = 'e2e-admin-token-0123456789abcdef'; +const persist = fs.mkdtempSync(path.join(os.tmpdir(), 'asteroids-lb-e2e-')); +const wranglerBin = path.join(serverDir, 'node_modules', 'wrangler', 'bin', 'wrangler.js'); +const env = { ...process.env, WRANGLER_SEND_METRICS: 'false', CI: '1', NO_COLOR: '1' }; + +let failures = 0; +let total = 0; +function check(name, ok, detail = '') { + total++; + if (!ok) failures++; + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` -- ${detail}` : ''}`); +} +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// 1. Create the local D1 database from the real migration files. +const migrate = spawnSync(process.execPath, [wranglerBin, 'd1', 'migrations', 'apply', 'asteroids-leaderboard', '--local', '--persist-to', persist], { cwd: serverDir, env, encoding: 'utf8' }); +check('D1 migrations apply cleanly (local)', migrate.status === 0, migrate.status === 0 ? '' : (migrate.stdout + migrate.stderr).slice(-400)); +if (migrate.status !== 0) process.exit(1); + +// 2. Start the Worker. +const worker = spawn( + process.execPath, + [wranglerBin, 'dev', '--local', '--port', String(PORT), '--persist-to', persist, '--test-scheduled', '--var', `ADMIN_TOKEN:${ADMIN}`, '--var', 'IP_HASH_SALT:e2e-salt'], + { cwd: serverDir, env, stdio: ['ignore', 'pipe', 'pipe'] }, +); +let log = ''; +worker.stdout.on('data', (d) => (log += d)); +worker.stderr.on('data', (d) => (log += d)); +const stop = () => worker.kill(); +process.on('exit', stop); + +async function waitReady() { + for (let i = 0; i < 200; i++) { + try { + if ((await fetch(`${BASE}/api/v1/health`)).ok) return; + } catch {} + await sleep(200); + } + throw new Error('Worker did not start:\n' + log); +} + +async function api(method, p, { token, body, headers = {} } = {}) { + const res = await fetch(BASE + p, { method, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...headers }, body }); + const text = await res.text(); + let json = null; + try { + json = JSON.parse(text); + } catch {} + return { status: res.status, json, headers: res.headers, text }; +} +const startRun = () => api('POST', '/api/v1/runs').then((r) => r.json); +const submitBody = (replay, extra = {}) => JSON.stringify({ replay, ...extra }); + +/** Issues runs until the bot, playing the server's own seed, finishes a short game with a positive score. */ +async function playableRun() { + for (let i = 0; i < 40; i++) { + const run = await startRun(); + const bot = generateBotReplay(engine, { seed: run.seed, spin: true }); + if (bot.gameOver && bot.score > 0 && bot.ticks < 1800) return { run, bot }; + } + throw new Error('could not find a short scoring game'); +} + +try { + await waitReady(); + console.log(`\nWorker ready at ${BASE} (workerd + local D1, state in ${persist})\n`); + + // --- challenge issuance ------------------------------------------------------------------------------------------------- + const health = await api('GET', '/api/v1/health'); + check('health reports rules version', health.json?.rulesVersion === '1.0.0'); + const probe = await api('POST', '/api/v1/runs', { body: JSON.stringify({ seed: 1, config: { playerCount: 2 } }), headers: { 'content-type': 'application/json' } }); + check('POST /runs issues a challenge (201) with server-chosen seed and approved config', probe.status === 201 && probe.json.seed !== 1 && probe.json.config.playerCount === 1); + check('challenge carries id, secret token, rules version, expiry', !!probe.json.runId && probe.json.token?.length >= 40 && probe.json.rulesVersion === '1.0.0' && Date.parse(probe.json.expiresAt) > Date.now()); + + // --- prepare several real games, all played against server-issued seeds ----------------------------------------------------- + const honest = await playableRun(); + const forged = await playableRun(); + const wrongSeed = await playableRun(); + const impatient = await playableRun(); + const hidden = await playableRun(); + const nonOwner = await playableRun(); + const t0 = Date.now(); + console.log(`Prepared 6 server-seeded games (honest score ${honest.bot.score}, ${honest.bot.ticks} ticks).`); + + // Submissions that do not depend on elapsed time. + const wrongToken = await api('POST', `/api/v1/runs/${nonOwner.run.runId}/submit`, { token: honest.run.token, body: submitBody(nonOwner.bot.replay) }); + check("another run's token cannot submit this run (401)", wrongToken.status === 401); + const noToken = await api('POST', `/api/v1/runs/${nonOwner.run.runId}/submit`, { body: submitBody(nonOwner.bot.replay) }); + check('missing token is refused (401)', noToken.status === 401); + const unknown = await api('POST', `/api/v1/runs/00000000-0000-4000-8000-000000000000/submit`, { token: 'x', body: '{}' }); + check('unknown run id is 404', unknown.status === 404); + + const bomb = gzipSync(Buffer.alloc(40 * 1024 * 1024, 0x20)); + const bombRes = await api('POST', `/api/v1/runs/${nonOwner.run.runId}/submit`, { token: nonOwner.run.token, body: bomb, headers: { 'content-encoding': 'gzip' } }); + check('gzip bomb (40 MiB inflated) is refused with 413 inside workerd', bombRes.status === 413, `status=${bombRes.status}`); + const trunc = submitBody(nonOwner.bot.replay).slice(0, 500); + const truncRes = await api('POST', `/api/v1/runs/${nonOwner.run.runId}/submit`, { token: nonOwner.run.token, body: trunc }); + check('truncated JSON is refused (400) without burning the run', truncRes.status === 400); + const badGzip = await api('POST', `/api/v1/runs/${nonOwner.run.runId}/submit`, { token: nonOwner.run.token, body: gzipSync(Buffer.from('{"replay":{}}')).subarray(0, 10), headers: { 'content-encoding': 'gzip' } }); + check('truncated gzip is refused (400)', badGzip.status === 400, `status=${badGzip.status}`); + + // A ten-minute recording claimed seconds after issue. + const tenMinute = structuredClone(impatient.bot.replay); + tenMinute.totalTicks = 36000; + delete tenMinute.claimedResult; + const fast = await api('POST', `/api/v1/runs/${impatient.run.runId}/submit`, { token: impatient.run.token, body: submitBody(tenMinute) }); + check('a ten-minute replay submitted seconds after issue is rejected (too_fast)', fast.status === 422 && fast.json.error.reason === 'too_fast', JSON.stringify(fast.json?.error?.reason)); + + // Wait until the honest games have really taken as long as they claim. + const needMs = Math.max(honest.bot.ticks, forged.bot.ticks, wrongSeed.bot.ticks, hidden.bot.ticks) * (1000 / 60) + 1500; + const waitMs = Math.max(0, needMs - (Date.now() - t0)); + console.log(`Waiting ${(waitMs / 1000).toFixed(1)} s for the real clock to catch up with the longest game...`); + await sleep(waitMs); + + // --- forgeries ------------------------------------------------------------------------------------------------------------- + const inflated = structuredClone(forged.bot.replay); + inflated.claimedResult.score += 5000; + const forgedRes = await api('POST', `/api/v1/runs/${forged.run.runId}/submit`, { token: forged.run.token, body: submitBody(inflated) }); + check('inflated score claim is rejected (422 score_mismatch)', forgedRes.status === 422 && forgedRes.json.error.reason === 'score_mismatch'); + const forgedAgain = await api('POST', `/api/v1/runs/${forged.run.runId}/submit`, { token: forged.run.token, body: submitBody(forged.bot.replay) }); + check('a rejected run is terminal even with a corrected replay (409)', forgedAgain.status === 409); + + const swapped = structuredClone(wrongSeed.bot.replay); + swapped.header.seed = (swapped.header.seed + 1) >>> 0; + const seedRes = await api('POST', `/api/v1/runs/${wrongSeed.run.runId}/submit`, { token: wrongSeed.run.token, body: submitBody(swapped) }); + check('replay with a different seed is rejected (seed_mismatch)', seedRes.status === 422 && seedRes.json.error.reason === 'seed_mismatch'); + + // --- the honest run: concurrent, mixed gzip / identity, with duplicate and replayed requests ------------------------------------ + const body = submitBody(honest.bot.replay, { nickname: 'E2E Pilot', controls: { scheme: 'keyboard' } }); + const gz = gzipSync(Buffer.from(body)); + console.log(`Honest recording: ${(body.length / 1024).toFixed(0)} KB raw, ${(gz.length / 1024).toFixed(0)} KB gzip`); + const tSubmit = performance.now(); + const results = await Promise.all( + Array.from({ length: 10 }, (_, i) => + i % 2 === 0 + ? api('POST', `/api/v1/runs/${honest.run.runId}/submit`, { token: honest.run.token, body: gz, headers: { 'content-encoding': 'gzip' } }) + : api('POST', `/api/v1/runs/${honest.run.runId}/submit`, { token: honest.run.token, body }), + ), + ); + const submitMs = performance.now() - tSubmit; + const accepted = results.filter((r) => r.status === 200); + const fresh = accepted.filter((r) => r.json.replayed === false); + const ids = new Set(accepted.map((r) => r.json.score.id)); + check('10 simultaneous submissions of one run: at least one 200, exactly one NEW acceptance', accepted.length >= 1 && fresh.length === 1, `statuses=${results.map((r) => r.status).join(',')}`); + check('every acceptance refers to the same single score id', ids.size === 1); + check('server-calculated score equals the independent Node result', accepted[0].json.score.score === honest.bot.score, `server=${accepted[0].json.score.score} node=${honest.bot.score} (${submitMs.toFixed(0)} ms for the batch)`); + check('others were told to retry (409) rather than double-accepting', results.every((r) => r.status === 200 || r.status === 409)); + const replayedHttp = await api('POST', `/api/v1/runs/${honest.run.runId}/submit`, { token: honest.run.token, body }); + check('re-sending the recorded request returns the same score, flagged replayed', replayedHttp.status === 200 && replayedHttp.json.replayed === true && replayedHttp.json.score.id === [...ids][0]); + const other = await api('POST', `/api/v1/runs/${honest.run.runId}/submit`, { token: honest.run.token, body: submitBody(honest.bot.replay, { nickname: 'Intruder' }) }); + check('a different payload for the accepted run is refused (409)', other.status === 409); + + // --- leaderboard ----------------------------------------------------------------------------------------------------------- + const allTime = await api('GET', '/api/v1/leaderboard/all-time'); + const weekly = await api('GET', '/api/v1/leaderboard/weekly'); + check('all-time board contains exactly the one verified score', allTime.json.total === 1 && allTime.json.entries[0].score === honest.bot.score && allTime.json.entries[0].nickname === 'E2E Pilot'); + check('weekly board contains it with the Halifax window', weekly.json.entries.length === 1 && weekly.json.timeZone === 'America/Halifax', `${weekly.json.weekStart} -> ${weekly.json.weekEnd}`); + const detail = await api('GET', `/api/v1/scores/${[...ids][0]}`); + check('score lookup returns ranks', detail.json.ranks.allTime === 1 && detail.json.ranks.weekly === 1); + check('forged / wrong-seed / impatient runs left nothing on the board', allTime.json.entries.every((e) => e.score === honest.bot.score)); + + // --- moderation ------------------------------------------------------------------------------------------------------------ + const hiddenBody = submitBody(hidden.bot.replay, { nickname: 'Hide Me' }); + const hiddenSubmit = await api('POST', `/api/v1/runs/${hidden.run.runId}/submit`, { token: hidden.run.token, body: hiddenBody }); + check('second honest run accepted', hiddenSubmit.status === 200); + const noAuth = await api('POST', `/api/v1/admin/scores/${hiddenSubmit.json.score.id}/visibility`, { body: '{"visible":false}' }); + check('admin endpoint refuses requests without the token (401)', noAuth.status === 401); + const hide = await api('POST', `/api/v1/admin/scores/${hiddenSubmit.json.score.id}/visibility`, { token: ADMIN, body: JSON.stringify({ visible: false, reason: 'e2e' }) }); + const afterHide = await api('GET', '/api/v1/leaderboard/all-time'); + check('hidden entry disappears from the public board', hide.status === 200 && afterHide.json.entries.every((e) => e.nickname !== 'Hide Me')); + + // --- CORS and housekeeping ------------------------------------------------------------------------------------------------- + const pre = await api('OPTIONS', '/api/v1/runs', { headers: { origin: 'http://127.0.0.1:4410', 'access-control-request-method': 'POST' } }); + check('CORS preflight allows the configured game origin', pre.status === 204 && pre.headers.get('access-control-allow-origin') === 'http://127.0.0.1:4410'); + const evil = await api('POST', '/api/v1/runs', { headers: { origin: 'https://evil.example' } }); + check('a browser origin that is not allow-listed is refused (403)', evil.status === 403); + const cron = await fetch(`${BASE}/__scheduled?cron=17+7+*+*+*`); + check('scheduled cleanup handler runs', cron.status === 200, `status=${cron.status}`); + + // --- rate limiting (last: it exhausts this client's start budget) --------------------------------------------------------- + let limited = null; + for (let i = 0; i < 40 && !limited; i++) { + const r = await api('POST', '/api/v1/runs'); + if (r.status === 429) limited = r; + } + check('run starts are rate limited (429 with Retry-After)', !!limited && Number(limited.headers.get('retry-after')) > 0); + const stillRead = await api('GET', '/api/v1/leaderboard/all-time'); + check('public reads still work while a client is throttled', stillRead.status === 200); +} finally { + stop(); + await sleep(500); + fs.rmSync(persist, { recursive: true, force: true }); +} + +console.log(`\n${total - failures}/${total} real-Worker integration checks passed\n`); +process.exit(failures ? 1 : 0); diff --git a/phaser-asteroids/server/src/body.ts b/phaser-asteroids/server/src/body.ts new file mode 100644 index 0000000..f6f49ea --- /dev/null +++ b/phaser-asteroids/server/src/body.ts @@ -0,0 +1,76 @@ +import { ApiError } from './errors'; + +export interface BodyLimits { + /** Maximum bytes accepted on the wire when Content-Encoding is gzip. */ + maxCompressedBytes: number; + /** Maximum bytes of body after any decoding. Also the wire limit for an uncompressed body. */ + maxBodyBytes: number; +} + +/** + * Reads a request body with hard limits at every stage, so no input can make the Worker buffer or inflate an unbounded amount: + * 1. only identity or gzip Content-Encoding is accepted; + * 2. a declared Content-Length over the wire limit is refused before reading; + * 3. the stream is counted as it arrives and cancelled the moment it exceeds the limit (Content-Length can lie or be absent); + * 4. a gzip body is inflated through a stream that is again counted and cancelled at the decoded limit (a "zip bomb" stops at + * maxBodyBytes of output, however small its compressed form). + */ +export async function readBoundedBody(request: Request, limits: BodyLimits): Promise { + const encoding = (request.headers.get('content-encoding') ?? 'identity').trim().toLowerCase(); + if (encoding !== 'identity' && encoding !== 'gzip') { + throw new ApiError(415, 'unsupported_encoding', 'Content-Encoding must be identity or gzip'); + } + const wireLimit = encoding === 'gzip' ? limits.maxCompressedBytes : limits.maxBodyBytes; + + const declared = request.headers.get('content-length'); + if (declared !== null) { + const n = Number(declared); + if (!Number.isFinite(n) || n < 0) throw new ApiError(400, 'bad_content_length', 'Invalid Content-Length'); + if (n > wireLimit) throw tooLarge(wireLimit); + } + if (!request.body) throw new ApiError(400, 'empty_body', 'Request body is required'); + + const wire = await collect(request.body, wireLimit, 'request body'); + if (encoding === 'identity') return wire; + + let inflated: ReadableStream; + try { + inflated = new Response(wire as BodyInit).body!.pipeThrough(new DecompressionStream('gzip')) as ReadableStream; + } catch { + throw new ApiError(400, 'invalid_gzip', 'Body is not valid gzip data'); + } + return collect(inflated, limits.maxBodyBytes, 'decompressed body'); +} + +function tooLarge(limit: number): ApiError { + return new ApiError(413, 'payload_too_large', `Request body exceeds the ${limit} byte limit`); +} + +async function collect(stream: ReadableStream, limit: number, what: string): Promise { + const reader = stream.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > limit) { + await reader.cancel().catch(() => undefined); + throw tooLarge(limit); + } + chunks.push(value); + } + } catch (e) { + if (e instanceof ApiError) throw e; + // A stream that errors part-way is a truncated upload or corrupt gzip: the client can simply retry. + throw new ApiError(400, 'invalid_body', `Could not read ${what}: it was truncated or corrupt`); + } + const out = new Uint8Array(total); + let offset = 0; + for (const c of chunks) { + out.set(c, offset); + offset += c.byteLength; + } + return out; +} diff --git a/phaser-asteroids/server/src/config.ts b/phaser-asteroids/server/src/config.ts new file mode 100644 index 0000000..723d4a1 --- /dev/null +++ b/phaser-asteroids/server/src/config.ts @@ -0,0 +1,98 @@ +import type { GameConfig } from '../../src/core/gameConfig'; +import { FIXED_TICK_RATE, GAMEPLAY_RULES_VERSION, REPLAY_SCHEMA_VERSION } from '../../src/replay/constants'; +import type { D1Like } from './d1'; + +/** + * The only gameplay configuration a ranked run may use: the classic one-player game. The server issues it with every + * challenge and compares it to the replay header; the browser never gets to choose any part of it. + */ +export const RANKED_CONFIG: Readonly = Object.freeze({ + playerCount: 1, + livesMode: 'independent', + friendlyFire: false, + speed: Object.freeze([1, 1]) as unknown as readonly [number, number], +}); + +export const RANKED_RULES_VERSION = GAMEPLAY_RULES_VERSION; +export const RANKED_SCHEMA_VERSION = REPLAY_SCHEMA_VERSION; +export const RANKED_TICK_RATE = FIXED_TICK_RATE; + +/** Bindings and variables the Worker receives (see wrangler.toml). Everything except `DB` is optional so local runs need no setup. */ +export interface Env { + DB: D1Like; + /** Comma-separated browser origins allowed to call the API, e.g. `https://djblackett.github.io`. Empty: no browser origin is allowed. */ + ALLOWED_ORIGINS?: string; + /** Bearer secret for /api/v1/admin/*. Unset (or shorter than 16 characters): the admin routes do not exist. Set with `wrangler secret put ADMIN_TOKEN`. */ + ADMIN_TOKEN?: string; + /** Secret salt for hashing client IPs into rate-limit buckets. Set with `wrangler secret put IP_HASH_SALT`. */ + IP_HASH_SALT?: string; + RUN_TTL_SECONDS?: string; + START_PER_IP_PER_HOUR?: string; + SUBMIT_PER_IP_PER_HOUR?: string; + START_GLOBAL_PER_HOUR?: string; + SUBMIT_GLOBAL_PER_HOUR?: string; +} + +export interface ServerSettings { + rulesVersion: string; + /** How long after issue a run can still be submitted. Covers a maximum-length run plus pauses and tab suspension. */ + runTtlMs: number; + /** A run being verified is "claimed"; a claim older than this is considered abandoned (the Worker died) and can be taken over. */ + claimLeaseMs: number; + /** A replay may not claim more simulated time than has really elapsed since the challenge was issued, plus this tolerance. */ + elapsedSlackMs: number; + /** Request body limits. Compressed applies to Content-Encoding: gzip on the wire; body applies to the decoded JSON text. */ + maxCompressedBytes: number; + maxBodyBytes: number; + /** Simulation work limit. Also bounds the number of input changes, since at most one change is recorded per tick. */ + maxTicks: number; + rate: { + windowMs: number; + startPerIp: number; + submitPerIp: number; + startGlobal: number; + submitGlobal: number; + adminFailuresPerIp: number; + }; + page: { defaultLimit: number; maxLimit: number; maxOffset: number }; + timeZone: string; + allowedOrigins: readonly string[]; + adminToken: string | null; + ipHashSalt: string; +} + +const MIB = 1024 * 1024; + +function intFromEnv(raw: string | undefined, fallback: number, min: number, max: number): number { + if (raw === undefined || raw.trim() === '') return fallback; + const n = Number(raw); + return Number.isInteger(n) && n >= min && n <= max ? n : fallback; +} + +export function loadSettings(env: Partial> = {}): ServerSettings { + return { + rulesVersion: RANKED_RULES_VERSION, + runTtlMs: intFromEnv(env.RUN_TTL_SECONDS, 3600, 60, 86_400) * 1000, + claimLeaseMs: 30_000, + elapsedSlackMs: 2_000, + maxCompressedBytes: 1 * MIB, + maxBodyBytes: 8 * MIB, + maxTicks: 20 * 60 * RANKED_TICK_RATE, // 72,000 ticks = 20 simulated minutes + rate: { + windowMs: 3_600_000, + startPerIp: intFromEnv(env.START_PER_IP_PER_HOUR, 30, 1, 100_000), + submitPerIp: intFromEnv(env.SUBMIT_PER_IP_PER_HOUR, 30, 1, 100_000), + startGlobal: intFromEnv(env.START_GLOBAL_PER_HOUR, 3000, 1, 10_000_000), + submitGlobal: intFromEnv(env.SUBMIT_GLOBAL_PER_HOUR, 1200, 1, 10_000_000), + adminFailuresPerIp: 10, + }, + page: { defaultLimit: 10, maxLimit: 100, maxOffset: 1000 }, + timeZone: 'America/Halifax', + allowedOrigins: (env.ALLOWED_ORIGINS ?? '') + .split(',') + .map((o) => o.trim().replace(/\/$/, '')) + .filter(Boolean), + adminToken: env.ADMIN_TOKEN && env.ADMIN_TOKEN.length >= 16 ? env.ADMIN_TOKEN : null, + ipHashSalt: env.IP_HASH_SALT ?? 'dev-only-salt', + }; +} diff --git a/phaser-asteroids/server/src/crypto.ts b/phaser-asteroids/server/src/crypto.ts new file mode 100644 index 0000000..a5fb94c --- /dev/null +++ b/phaser-asteroids/server/src/crypto.ts @@ -0,0 +1,42 @@ +/** Web Crypto helpers (available identically in Workers, Node 20+ and browsers). */ + +const encoder = new TextEncoder(); + +export function toHex(bytes: Uint8Array): string { + let out = ''; + for (const b of bytes) out += b.toString(16).padStart(2, '0'); + return out; +} + +export function toBase64Url(bytes: Uint8Array): string { + let bin = ''; + for (const b of bytes) bin += String.fromCharCode(b); + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +/** 256 bits of CSPRNG output, base64url: the secret that authorises submitting one run. */ +export function randomToken(byteLength = 32): string { + return toBase64Url(crypto.getRandomValues(new Uint8Array(byteLength))); +} + +/** Unpredictable unsigned 32-bit simulation seed. */ +export function randomSeed(): number { + return crypto.getRandomValues(new Uint32Array(1))[0]!; +} + +export function randomId(): string { + return crypto.randomUUID(); +} + +export async function sha256Hex(data: string | Uint8Array): Promise { + const bytes = typeof data === 'string' ? encoder.encode(data) : data; + return toHex(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes as BufferSource))); +} + +/** Compares two strings without an early exit on the first differing character. */ +export function constantTimeEqual(a: string, b: string): boolean { + const len = Math.max(a.length, b.length); + let diff = a.length ^ b.length; + for (let i = 0; i < len; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0); + return diff === 0; +} diff --git a/phaser-asteroids/server/src/d1.ts b/phaser-asteroids/server/src/d1.ts new file mode 100644 index 0000000..d09cf7c --- /dev/null +++ b/phaser-asteroids/server/src/d1.ts @@ -0,0 +1,34 @@ +import type { Db, SqlValue, Statement } from './db'; + +/** The slice of Cloudflare's D1 API this service uses, declared structurally so no Workers type package is needed. */ +export interface D1Like { + prepare(sql: string): D1PreparedLike; + batch(statements: D1PreparedLike[]): Promise>; +} + +export interface D1PreparedLike { + bind(...values: unknown[]): D1PreparedLike; + run(): Promise<{ meta: { changes?: number } }>; + all(): Promise<{ results: T[] }>; + first(): Promise; +} + +export function d1Db(d1: D1Like): Db { + const prep = (sql: string, params: SqlValue[] = []) => d1.prepare(sql).bind(...params); + return { + async all(sql: string, params?: SqlValue[]) { + return (await prep(sql, params).all()).results; + }, + first(sql: string, params?: SqlValue[]) { + return prep(sql, params).first(); + }, + async run(sql, params) { + const res = await prep(sql, params).run(); + return { changes: res.meta.changes ?? 0 }; + }, + async batch(statements: Statement[]) { + const results = await d1.batch(statements.map((s) => prep(s.sql, s.params))); + return results.map((r) => ({ changes: r.meta.changes ?? 0 })); + }, + }; +} diff --git a/phaser-asteroids/server/src/db.ts b/phaser-asteroids/server/src/db.ts new file mode 100644 index 0000000..5dd54a1 --- /dev/null +++ b/phaser-asteroids/server/src/db.ts @@ -0,0 +1,22 @@ +/** + * The only database surface the service code uses. Two adapters implement it: `d1.ts` (Cloudflare D1, production) and + * `testing/sqliteDb.ts` (node:sqlite, unit tests). Both speak SQLite, so the SQL in the service is written once. + * + * `batch` is the atomic primitive: all statements commit or none do (D1 has no interactive transactions, only batches). + * Everything that must be race-free is expressed either as one conditional statement or as one batch. + */ +export type SqlValue = string | number | null; + +export interface Statement { + sql: string; + params: SqlValue[]; +} + +export interface Db { + all(sql: string, params?: SqlValue[]): Promise; + first(sql: string, params?: SqlValue[]): Promise; + /** Rows changed by the statement. */ + run(sql: string, params?: SqlValue[]): Promise<{ changes: number }>; + /** Executes the statements atomically and in order; returns the rows changed by each. */ + batch(statements: Statement[]): Promise>; +} diff --git a/phaser-asteroids/server/src/errors.ts b/phaser-asteroids/server/src/errors.ts new file mode 100644 index 0000000..01455ae --- /dev/null +++ b/phaser-asteroids/server/src/errors.ts @@ -0,0 +1,13 @@ +/** An error that maps directly to an HTTP response: `{ "error": { "code", "message", ...extra } }`. */ +export class ApiError extends Error { + constructor( + readonly status: number, + readonly code: string, + message: string, + readonly extra: Record = {}, + readonly headers: Record = {}, + ) { + super(message); + this.name = 'ApiError'; + } +} diff --git a/phaser-asteroids/server/src/leaderboard.ts b/phaser-asteroids/server/src/leaderboard.ts new file mode 100644 index 0000000..b5c057a --- /dev/null +++ b/phaser-asteroids/server/src/leaderboard.ts @@ -0,0 +1,121 @@ +import type { Db, SqlValue } from './db'; +import type { ServerSettings } from './config'; +import { weekWindow, type WeekWindow } from './week'; + +/** + * What the public API exposes about an entry. Deliberately small: no run id, no control metadata, no moderation fields. + * `nickname` is plain text restricted to letters, numbers, space and `_ . ! -`; clients should still render it as text. + */ +export interface PublicScore { + id: string; + rank: number; + nickname: string; + score: number; + completedAt: string; + durationSeconds: number; +} + +export type Scope = 'all-time' | 'weekly'; + +interface ScoreRow { + id: string; + nickname: string; + score: number; + completed_at: number; + duration_ms: number; + rules_version: string; +} + +export interface LeaderboardPage { + scope: Scope; + rulesVersion: string; + timeZone?: string; + weekStart?: string; + weekEnd?: string; + limit: number; + offset: number; + total: number; + entries: PublicScore[]; +} + +/** + * Ranking: highest verified score first; ties go to whoever finished first, then to the smaller id so the order is total and + * stable. Ranks are therefore ordinal (1, 2, 3 ...) with no shared places. Only visible, positive, current-rules scores count. + */ +const ORDER = 'score DESC, completed_at ASC, id ASC'; +const ELIGIBLE = "visibility = 'visible' AND score > 0 AND rules_version = ?"; + +const toPublic = (row: ScoreRow, rank: number): PublicScore => ({ + id: row.id, + rank, + nickname: row.nickname, + score: row.score, + completedAt: new Date(row.completed_at).toISOString(), + durationSeconds: Math.round(row.duration_ms / 10) / 100, +}); + +function windowFilter(scope: Scope, window: WeekWindow | null): { sql: string; params: SqlValue[] } { + if (scope === 'weekly' && window) return { sql: ' AND completed_at >= ? AND completed_at < ?', params: [window.startMs, window.endMs] }; + return { sql: '', params: [] }; +} + +export async function getLeaderboard( + db: Db, + settings: ServerSettings, + now: number, + scope: Scope, + limit: number, + offset: number, +): Promise { + const window = scope === 'weekly' ? weekWindow(now, settings.timeZone) : null; + const f = windowFilter(scope, window); + const base: SqlValue[] = [settings.rulesVersion, ...f.params]; + + const rows = await db.all( + `SELECT id, nickname, score, completed_at, duration_ms, rules_version FROM scores + WHERE ${ELIGIBLE}${f.sql} ORDER BY ${ORDER} LIMIT ? OFFSET ?`, + [...base, limit, offset], + ); + const total = (await db.first<{ n: number }>(`SELECT COUNT(*) AS n FROM scores WHERE ${ELIGIBLE}${f.sql}`, base))?.n ?? 0; + + return { + scope, + rulesVersion: settings.rulesVersion, + ...(window && { timeZone: window.timeZone, weekStart: new Date(window.startMs).toISOString(), weekEnd: new Date(window.endMs).toISOString() }), + limit, + offset, + total, + entries: rows.map((row, i) => toPublic(row, offset + i + 1)), + }; +} + +/** 1-based ordinal rank of one score on a board, or null if it is not on that board (hidden, zero, other rules, other week). */ +export async function rankOf(db: Db, settings: ServerSettings, now: number, scope: Scope, row: ScoreRow): Promise { + if (row.rules_version !== settings.rulesVersion || row.score <= 0) return null; + const window = scope === 'weekly' ? weekWindow(now, settings.timeZone) : null; + if (window && (row.completed_at < window.startMs || row.completed_at >= window.endMs)) return null; + const f = windowFilter(scope, window); + const better = await db.first<{ n: number }>( + `SELECT COUNT(*) AS n FROM scores WHERE ${ELIGIBLE}${f.sql} + AND (score > ? OR (score = ? AND (completed_at < ? OR (completed_at = ? AND id < ?))))`, + [settings.rulesVersion, ...f.params, row.score, row.score, row.completed_at, row.completed_at, row.id], + ); + return (better?.n ?? 0) + 1; +} + +export interface ScoreDetail { + score: Omit & { rank: number | null }; + ranks: { allTime: number | null; weekly: number | null }; +} + +export async function getScoreRow(db: Db, id: string): Promise<(ScoreRow & { visibility: string }) | null> { + return db.first(`SELECT id, nickname, score, completed_at, duration_ms, rules_version, visibility FROM scores WHERE id = ?`, [id]); +} + +/** A single entry with its all-time and current-week ranks. Hidden entries are indistinguishable from unknown ones. */ +export async function getScoreDetail(db: Db, settings: ServerSettings, now: number, id: string): Promise { + const row = await getScoreRow(db, id); + if (!row || row.visibility !== 'visible') return null; + const [allTime, weekly] = await Promise.all([rankOf(db, settings, now, 'all-time', row), rankOf(db, settings, now, 'weekly', row)]); + return { score: { ...toPublic(row, allTime ?? 0), rank: allTime }, ranks: { allTime, weekly } }; +} diff --git a/phaser-asteroids/server/src/nickname.ts b/phaser-asteroids/server/src/nickname.ts new file mode 100644 index 0000000..56c6184 --- /dev/null +++ b/phaser-asteroids/server/src/nickname.ts @@ -0,0 +1,31 @@ +export const NICKNAME_MIN = 3; +export const NICKNAME_MAX = 16; +export const DEFAULT_NICKNAME = 'Anonymous'; + +export type NicknameResult = { ok: true; value: string } | { ok: false; message: string }; + +/** Letters and digits (any script), plus space and a few arcade-friendly marks. No `< > & " '`, so a nickname can never form markup. */ +const ALLOWED = /^[\p{L}\p{N}][\p{L}\p{N} _.!-]*$/u; + +/** + * Normalises and validates an optional arcade nickname: NFC, outer whitespace trimmed, inner whitespace runs collapsed to one + * space, 3-16 characters (counted as Unicode code points), starting with a letter or digit. An absent nickname becomes + * "Anonymous". The result is plain text: clients must still render it with textContent / escaping, never as HTML. + */ +export function sanitizeNickname(input: unknown): NicknameResult { + if (input === undefined || input === null) return { ok: true, value: DEFAULT_NICKNAME }; + if (typeof input !== 'string') return { ok: false, message: 'nickname must be a string' }; + if (input.length > 256) return { ok: false, message: 'nickname is too long' }; + + const value = input.normalize('NFC').trim().replace(/\s+/gu, ' '); + if (value === '') return { ok: true, value: DEFAULT_NICKNAME }; + + const length = [...value].length; + if (length < NICKNAME_MIN || length > NICKNAME_MAX) { + return { ok: false, message: `nickname must be ${NICKNAME_MIN}-${NICKNAME_MAX} characters` }; + } + if (!ALLOWED.test(value)) { + return { ok: false, message: 'nickname may contain letters, numbers, spaces and _ . ! - only, and must start with a letter or number' }; + } + return { ok: true, value }; +} diff --git a/phaser-asteroids/server/src/ratelimit.ts b/phaser-asteroids/server/src/ratelimit.ts new file mode 100644 index 0000000..87d60c6 --- /dev/null +++ b/phaser-asteroids/server/src/ratelimit.ts @@ -0,0 +1,26 @@ +import type { Db } from './db'; +import { ApiError } from './errors'; + +/** + * Fixed-window counters kept in the database. One atomic upsert per check, so the count is exact across Worker instances + * (unlike Cloudflare's edge rate-limiting binding, which is approximate and per location). Used to bound request volume and, + * more importantly, the CPU spent on replay verification; it is NOT what makes a run single-use (see runs.ts). + */ +export async function hitRateLimit(db: Db, bucket: string, limit: number, windowMs: number, now: number): Promise { + const windowStart = Math.floor(now / windowMs) * windowMs; + const row = await db.first<{ count: number }>( + `INSERT INTO rate_limits (bucket, window_start, count) VALUES (?, ?, 1) + ON CONFLICT (bucket, window_start) DO UPDATE SET count = count + 1 + RETURNING count`, + [bucket, windowStart], + ); + if ((row?.count ?? 0) > limit) { + const retryAfter = Math.max(1, Math.ceil((windowStart + windowMs - now) / 1000)); + throw new ApiError(429, 'rate_limited', 'Too many requests; try again later', { retryAfterSeconds: retryAfter }, { 'Retry-After': String(retryAfter) }); + } +} + +/** Deletes counters from windows that can no longer matter. */ +export async function pruneRateLimits(db: Db, now: number, windowMs: number): Promise { + return (await db.run('DELETE FROM rate_limits WHERE window_start < ?', [now - 2 * windowMs])).changes; +} diff --git a/phaser-asteroids/server/src/router.ts b/phaser-asteroids/server/src/router.ts new file mode 100644 index 0000000..4a50dd0 --- /dev/null +++ b/phaser-asteroids/server/src/router.ts @@ -0,0 +1,198 @@ +import { RANKED_SCHEMA_VERSION } from './config'; +import { constantTimeEqual, sha256Hex } from './crypto'; +import { readBoundedBody } from './body'; +import { ApiError } from './errors'; +import { getLeaderboard, getScoreDetail, type Scope } from './leaderboard'; +import { hitRateLimit } from './ratelimit'; +import { createRun, setScoreVisibility, submitRun, type ServiceDeps } from './runs'; + +const API = '/api/v1'; + +/** + * The whole HTTP surface, as a plain Web `Request` -> `Response` function with no Cloudflare types, so it runs unchanged in a + * Worker, in Node (tests) or behind any other fetch-style host. + * + * GET /api/v1/health + * POST /api/v1/runs issue a ranked challenge + * POST /api/v1/runs/:id/submit submit the recording for that challenge (Bearer run token) + * GET /api/v1/leaderboard/all-time|weekly ?limit=&offset= + * GET /api/v1/scores/:id one entry with its ranks + * POST /api/v1/admin/scores/:id/visibility hide / unhide (Bearer ADMIN_TOKEN; absent unless configured) + */ +export async function handleRequest(request: Request, deps: ServiceDeps): Promise { + const origin = request.headers.get('origin'); + const url = new URL(request.url); + const isAdmin = url.pathname.startsWith(`${API}/admin/`); + const cors = isAdmin ? {} : corsHeaders(origin, deps); + + try { + if (request.method === 'OPTIONS') return preflight(cors); + const res = await route(request, url, origin, deps); + return withHeaders(res, cors); + } catch (e) { + if (e instanceof ApiError) { + return withHeaders( + json({ error: { code: e.code, message: e.message, ...e.extra } }, e.status, { 'Cache-Control': 'no-store', ...e.headers }), + cors, + ); + } + console.error(JSON.stringify({ evt: 'unhandled', path: url.pathname, error: String(e) })); + return withHeaders(json({ error: { code: 'internal_error', message: 'Unexpected server error' } }, 500, { 'Cache-Control': 'no-store' }), cors); + } +} + +async function route(request: Request, url: URL, origin: string | null, deps: ServiceDeps): Promise { + const { settings } = deps; + const path = url.pathname.replace(/\/+$/, ''); + const method = request.method; + + if (path === `${API}/health`) { + only(method, 'GET'); + return json({ ok: true, rulesVersion: settings.rulesVersion, schemaVersion: RANKED_SCHEMA_VERSION, maxTicks: settings.maxTicks, time: new Date(deps.now()).toISOString() }); + } + + if (path === `${API}/runs`) { + only(method, 'POST'); + requireAllowedOrigin(origin, deps); + const ipHash = await clientHash(request, deps); + await hitRateLimit(deps.db, `start:ip:${ipHash}`, settings.rate.startPerIp, settings.rate.windowMs, deps.now()); + await hitRateLimit(deps.db, 'start:global', settings.rate.startGlobal, settings.rate.windowMs, deps.now()); + const run = await createRun(deps, ipHash); + return json(run, 201, { 'Cache-Control': 'no-store' }); + } + + const submit = /^\/api\/v1\/runs\/([^/]+)\/submit$/.exec(path); + if (submit) { + only(method, 'POST'); + requireAllowedOrigin(origin, deps); + const ipHash = await clientHash(request, deps); + // Throttle before doing any work, so an abusive client cannot make us spend CPU. The global bucket is the hard ceiling on + // how much replay verification the service will perform per hour. + await hitRateLimit(deps.db, `submit:ip:${ipHash}`, settings.rate.submitPerIp, settings.rate.windowMs, deps.now()); + await hitRateLimit(deps.db, 'submit:global', settings.rate.submitGlobal, settings.rate.windowMs, deps.now()); + const result = await submitRun(deps, { + runId: submit[1]!, + token: bearer(request), + readBody: () => readBoundedBody(request, settings), + }); + return json(result, 200, { 'Cache-Control': 'no-store' }); + } + + const board = /^\/api\/v1\/leaderboard\/(all-time|weekly)$/.exec(path); + if (board) { + only(method, 'GET'); + const limit = intParam(url, 'limit', settings.page.defaultLimit, 1, settings.page.maxLimit); + const offset = intParam(url, 'offset', 0, 0, settings.page.maxOffset); + const page = await getLeaderboard(deps.db, settings, deps.now(), board[1] as Scope, limit, offset); + return json(page, 200, { 'Cache-Control': 'public, max-age=5' }); + } + + const score = /^\/api\/v1\/scores\/([^/]+)$/.exec(path); + if (score) { + only(method, 'GET'); + const detail = await getScoreDetail(deps.db, settings, deps.now(), score[1]!); + if (!detail) throw new ApiError(404, 'score_not_found', 'No such score'); + return json(detail, 200, { 'Cache-Control': 'public, max-age=5' }); + } + + const visibility = /^\/api\/v1\/admin\/scores\/([^/]+)\/visibility$/.exec(path); + if (visibility && settings.adminToken) { + only(method, 'POST'); + await requireAdmin(request, deps); + const body = await readJsonObject(request); + if (typeof body.visible !== 'boolean') throw new ApiError(400, 'invalid_request', '"visible" must be true or false'); + const reason = typeof body.reason === 'string' ? body.reason : null; + const changed = await setScoreVisibility(deps.db, visibility[1]!, body.visible, reason, deps.now()); + if (!changed) throw new ApiError(404, 'score_not_found', 'No such score'); + return json({ id: visibility[1], visible: body.visible }, 200, { 'Cache-Control': 'no-store' }); + } + + throw new ApiError(404, 'not_found', 'No such route'); +} + +// --- helpers --------------------------------------------------------------------------------------------------------------- + +function only(method: string, allowed: string): void { + if (method !== allowed) throw new ApiError(405, 'method_not_allowed', `Use ${allowed}`, {}, { Allow: allowed }); +} + +function bearer(request: Request): string | null { + const header = request.headers.get('authorization'); + const m = header ? /^Bearer\s+(\S+)$/i.exec(header) : null; + return m ? m[1]! : null; +} + +async function clientHash(request: Request, deps: ServiceDeps): Promise { + const ip = request.headers.get('cf-connecting-ip') ?? 'unknown'; + return (await sha256Hex(`${deps.settings.ipHashSalt}|${ip}`)).slice(0, 32); +} + +async function requireAdmin(request: Request, deps: ServiceDeps): Promise { + const token = bearer(request); + const expected = deps.settings.adminToken!; + const ok = !!token && constantTimeEqual(await sha256Hex(token), await sha256Hex(expected)); + if (ok) return; + await hitRateLimit(deps.db, `admin-fail:${await clientHash(request, deps)}`, deps.settings.rate.adminFailuresPerIp, deps.settings.rate.windowMs, deps.now()); + throw new ApiError(401, 'unauthorized', 'Admin credentials required'); +} + +async function readJsonObject(request: Request): Promise> { + const bytes = await readBoundedBody(request, { maxCompressedBytes: 4096, maxBodyBytes: 4096 }); + try { + const value: unknown = JSON.parse(new TextDecoder().decode(bytes)); + if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record; + } catch { + /* fall through */ + } + throw new ApiError(400, 'invalid_json', 'Body must be a JSON object'); +} + +function intParam(url: URL, name: string, fallback: number, min: number, max: number): number { + const raw = url.searchParams.get(name); + if (raw === null) return fallback; + const n = Number(raw); + if (!/^\d+$/.test(raw) || !Number.isSafeInteger(n) || n < min || n > max) { + throw new ApiError(400, 'invalid_parameter', `"${name}" must be an integer from ${min} to ${max}`); + } + return n; +} + +/** + * Browsers always send Origin on cross-origin POSTs. One that is not on the allow-list is refused outright (a stray site cannot make a + * visitor's browser burn rate limit or request challenges). Requests with no Origin (curl, scripts, tests) are fine: this is + * hygiene, not authentication, since anyone can call the API directly. + */ +function requireAllowedOrigin(origin: string | null, deps: ServiceDeps): void { + if (origin && !deps.settings.allowedOrigins.includes(origin)) { + throw new ApiError(403, 'origin_not_allowed', 'This origin may not use the ranked API'); + } +} + +function corsHeaders(origin: string | null, deps: ServiceDeps): Record { + if (!origin || !deps.settings.allowedOrigins.includes(origin)) return { Vary: 'Origin' }; + return { 'Access-Control-Allow-Origin': origin, Vary: 'Origin' }; +} + +function preflight(cors: Record): Response { + if (!cors['Access-Control-Allow-Origin']) return new Response(null, { status: 403, headers: cors }); + return new Response(null, { + status: 204, + headers: { + ...cors, + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Content-Encoding', + 'Access-Control-Max-Age': '600', + }, + }); +} + +function json(body: unknown, status = 200, headers: Record = {}): Response { + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', ...headers } }); +} + +function withHeaders(res: Response, extra: Record): Response { + const headers = new Headers(res.headers); + for (const [k, v] of Object.entries(extra)) headers.set(k, v); + headers.set('X-Content-Type-Options', 'nosniff'); + return new Response(res.body, { status: res.status, headers }); +} diff --git a/phaser-asteroids/server/src/runs.ts b/phaser-asteroids/server/src/runs.ts new file mode 100644 index 0000000..65fd178 --- /dev/null +++ b/phaser-asteroids/server/src/runs.ts @@ -0,0 +1,307 @@ +import type { GameConfig } from '../../src/core/gameConfig'; +import { RANKED_CONFIG, RANKED_SCHEMA_VERSION, RANKED_TICK_RATE, type ServerSettings } from './config'; +import { constantTimeEqual, randomId, randomSeed, randomToken, sha256Hex } from './crypto'; +import type { Db } from './db'; +import { ApiError } from './errors'; +import { getScoreRow, rankOf, type PublicScore } from './leaderboard'; +import { sanitizeNickname } from './nickname'; +import { verifyRankedReplay, type IssuedRunFacts, type RankedVerdict } from './verify'; + +/** + * Ranked run lifecycle (see migrations/0001_init.sql for the table): + * + * issued --claim--> verifying --finalize--> accepted (terminal; exactly one scores row) + * | \-finalize--> rejected (terminal; the replay failed verification) + * \--release--> issued (only when the claimant hit an internal error, so the player may retry) + * + * Every arrow is ONE conditional statement (or one batch) whose WHERE clause names the state it expects, so under any number of + * simultaneous requests, on any number of Worker instances, the database lets exactly one of them make each move. + */ + +export interface ServiceDeps { + db: Db; + settings: ServerSettings; + now: () => number; + /** Replaceable in tests only; production always uses verifyRankedReplay. */ + verify?: (replay: unknown, run: IssuedRunFacts, now: number, settings: ServerSettings) => RankedVerdict; +} + +export interface IssuedRun { + runId: string; + /** Secret that authorises submitting this run. Shown once; only its hash is stored. */ + token: string; + seed: number; + rulesVersion: string; + schemaVersion: number; + tickRate: number; + config: GameConfig; + issuedAt: string; + expiresAt: string; +} + +interface RunRow { + id: string; + token_hash: string; + seed: number; + rules_version: string; + config_json: string; + created_at: number; + expires_at: number; + status: 'issued' | 'verifying' | 'accepted' | 'rejected'; + claim_token: string | null; + claimed_at: number | null; + replay_hash: string | null; + finished_at: number | null; + score_id: string | null; + reject_reason: string | null; + reject_detail: string | null; +} + +export interface AcceptedSubmission { + status: 'accepted'; + /** True when this response repeats an earlier acceptance of the identical body (a retry after a lost response). */ + replayed: boolean; + score: Omit; + ranks: { allTime: number | null; weekly: number | null }; +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + +/** Control categories the client may report. Informational and untrusted: never used to rank or to accept. */ +export const REPORTED_CONTROLS = ['keyboard', 'gamepad', 'touch-classic', 'touch-point', 'touch-assisted', 'mixed', 'unknown'] as const; + +export function sanitizeControls(input: unknown): string { + const scheme = input && typeof input === 'object' ? (input as { scheme?: unknown }).scheme : input; + return typeof scheme === 'string' && (REPORTED_CONTROLS as readonly string[]).includes(scheme) ? scheme : 'unknown'; +} + +// --- issuing --------------------------------------------------------------------------------------------------------------- + +export async function createRun(deps: ServiceDeps, issuerHash: string | null): Promise { + const { db, settings } = deps; + const now = deps.now(); + const run: IssuedRun = { + runId: randomId(), + token: randomToken(), + seed: randomSeed(), + rulesVersion: settings.rulesVersion, + schemaVersion: RANKED_SCHEMA_VERSION, + tickRate: RANKED_TICK_RATE, + config: { ...RANKED_CONFIG, speed: [...RANKED_CONFIG.speed] as [number, number] }, + issuedAt: new Date(now).toISOString(), + expiresAt: new Date(now + settings.runTtlMs).toISOString(), + }; + await db.run( + `INSERT INTO runs (id, token_hash, seed, rules_version, config_json, created_at, expires_at, status, issuer_hash) + VALUES (?, ?, ?, ?, ?, ?, ?, 'issued', ?)`, + [run.runId, await sha256Hex(run.token), run.seed, run.rulesVersion, JSON.stringify(run.config), now, now + settings.runTtlMs, issuerHash], + ); + return run; +} + +// --- submitting ------------------------------------------------------------------------------------------------------------ + +export interface SubmitInput { + runId: string; + /** The bearer token from the Authorization header, or null if absent. */ + token: string | null; + /** Reads the (size-bounded) body. Called only after the run and its token have been checked. */ + readBody: () => Promise; +} + +const loadRun = (db: Db, id: string) => db.first('SELECT * FROM runs WHERE id = ?', [id]); + +export async function submitRun(deps: ServiceDeps, input: SubmitInput): Promise { + const { db, settings } = deps; + + // 1. Cheap checks that never touch the body: does the run exist, is the caller entitled to it, is it still open? + if (!UUID.test(input.runId)) throw new ApiError(404, 'run_not_found', 'No such run'); + const run = await loadRun(db, input.runId); + if (!run) throw new ApiError(404, 'run_not_found', 'No such run'); + if (!input.token || !constantTimeEqual(await sha256Hex(input.token), run.token_hash)) { + throw new ApiError(401, 'invalid_token', 'Missing or invalid run token'); + } + if (run.status === 'rejected') throw rejectedError(run); + if (run.status === 'issued' && run.expires_at <= deps.now()) throw expiredError(); + + // 2. Read and hash the body. Problems up to and including step 3 are about the transport or the envelope, not about the play + // itself, so they do not consume the run: the client can fix or repeat the request. + const body = await input.readBody(); + const replayHash = await sha256Hex(body); + + if (run.status === 'accepted') return acceptedAgain(deps, run, replayHash); + + // 3. Envelope: JSON object with a replay object, an optional nickname and optional reported controls. + let payload: unknown; + try { + payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body)); + } catch { + throw new ApiError(400, 'invalid_json', 'Body is not valid UTF-8 JSON'); + } + if (!isRecord(payload) || !isRecord(payload.replay)) { + throw new ApiError(400, 'invalid_submission', 'Body must be a JSON object with a "replay" object'); + } + const nickname = sanitizeNickname(payload.nickname); + if (!nickname.ok) throw new ApiError(400, 'invalid_nickname', nickname.message); + const controls = sanitizeControls(payload.controls); + + // 4. Claim. From here the outcome is decided by the database: exactly one concurrent request can win this UPDATE. + const claimToken = randomId(); + const claimedAt = deps.now(); + const claim = await db.run( + `UPDATE runs SET status = 'verifying', claim_token = ?, claimed_at = ?, replay_hash = ? + WHERE id = ? AND expires_at > ? AND (status = 'issued' OR (status = 'verifying' AND claimed_at <= ?))`, + [claimToken, claimedAt, replayHash, run.id, claimedAt, claimedAt - settings.claimLeaseMs], + ); + if (claim.changes !== 1) return resolveLostClaim(deps, run.id, replayHash); + + // 5. Verify and finalize. Any request that holds the claim must leave the run accepted, rejected, or released. + try { + let verdict: RankedVerdict; + try { + const facts: IssuedRunFacts = { + seed: run.seed, + rulesVersion: run.rules_version, + config: JSON.parse(run.config_json) as GameConfig, + createdAt: run.created_at, + }; + verdict = (deps.verify ?? verifyRankedReplay)(payload.replay, facts, claimedAt, settings); + } catch (e) { + // A replay that crashes the verifier cannot be scored. Treat it as a rejection (not a retryable error) so a crafted + // payload cannot be resubmitted indefinitely; the stack trace goes to the operator's logs. + console.error(JSON.stringify({ evt: 'verifier_threw', run: run.id, error: String(e) })); + verdict = { ok: false, code: 'invalid_replay', detail: 'verification could not complete' }; + } + + if (!verdict.ok) { + await db.run( + `UPDATE runs SET status = 'rejected', claim_token = NULL, finished_at = ?, reject_reason = ?, reject_detail = ? + WHERE id = ? AND status = 'verifying' AND claim_token = ?`, + [deps.now(), verdict.code, verdict.detail.slice(0, 300), run.id, claimToken], + ); + console.warn(JSON.stringify({ evt: 'run_rejected', run: run.id, reason: verdict.code })); + throw new ApiError(422, 'replay_rejected', 'The replay did not verify', { status: 'rejected', reason: verdict.code, detail: verdict.detail.slice(0, 300) }); + } + + const result = verdict.result; + const scoreId = randomId(); + const completedAt = deps.now(); + const row = [ + scoreId, + run.id, + result.calculatedScore, + nickname.value, + completedAt, + run.rules_version, + result.totalTicks, + Math.round(result.simulatedDuration * 1000), + result.stats.asteroidsDestroyed, + result.stats.ufosDestroyed, + controls, + ]; + const [inserted, updated] = await db.batch([ + { + sql: `INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms, + asteroids_destroyed, ufos_destroyed, reported_controls) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? + WHERE EXISTS (SELECT 1 FROM runs WHERE id = ? AND status = 'verifying' AND claim_token = ?)`, + params: [...row, run.id, claimToken], + }, + { + sql: `UPDATE runs SET status = 'accepted', claim_token = NULL, finished_at = ?, score_id = ? + WHERE id = ? AND status = 'verifying' AND claim_token = ?`, + params: [completedAt, scoreId, run.id, claimToken], + }, + ]); + if (inserted?.changes !== 1 || updated?.changes !== 1) return resolveLostClaim(deps, run.id, replayHash); + + return await buildAccepted(deps, scoreId, false); + } catch (e) { + if (e instanceof ApiError) throw e; + // Internal failure (database unavailable, bug): give the claim back so the player can retry, and never leave a score behind. + console.error(JSON.stringify({ evt: 'submit_failed', run: run.id, error: String(e) })); + await db + .run( + `UPDATE runs SET status = 'issued', claim_token = NULL, claimed_at = NULL, replay_hash = NULL + WHERE id = ? AND status = 'verifying' AND claim_token = ?`, + [run.id, claimToken], + ) + .catch(() => undefined); // if even this fails, the claim lease lets a later request take over + throw new ApiError(503, 'service_unavailable', 'The score could not be recorded; please retry', {}, { 'Retry-After': '5' }); + } +} + +/** We did not win the claim (or lost it before finalizing): report what actually happened to the run. */ +async function resolveLostClaim(deps: ServiceDeps, runId: string, replayHash: string): Promise { + const current = await loadRun(deps.db, runId); + if (!current) throw new ApiError(404, 'run_not_found', 'No such run'); + switch (current.status) { + case 'accepted': + return acceptedAgain(deps, current, replayHash); + case 'rejected': + throw rejectedError(current); + case 'verifying': + throw new ApiError(409, 'run_in_progress', 'This run is being verified by another request; retry shortly', {}, { 'Retry-After': '2' }); + default: + // Back to 'issued' means expiry (otherwise our claim would have succeeded) or a release race. + if (current.expires_at <= deps.now()) throw expiredError(); + throw new ApiError(409, 'run_busy', 'The run changed state during submission; retry', {}, { 'Retry-After': '1' }); + } +} + +async function acceptedAgain(deps: ServiceDeps, run: RunRow, replayHash: string): Promise { + if (run.replay_hash !== replayHash || !run.score_id) { + throw new ApiError(409, 'run_already_submitted', 'This run has already been submitted and accepted'); + } + return buildAccepted(deps, run.score_id, true); +} + +async function buildAccepted(deps: ServiceDeps, scoreId: string, replayed: boolean): Promise { + const { db, settings } = deps; + const row = await getScoreRow(db, scoreId); + if (!row) throw new Error(`accepted run references missing score ${scoreId}`); + const now = deps.now(); + const visible = row.visibility === 'visible'; + const [allTime, weekly] = visible + ? await Promise.all([rankOf(db, settings, now, 'all-time', row), rankOf(db, settings, now, 'weekly', row)]) + : [null, null]; + return { + status: 'accepted', + replayed, + score: { + id: row.id, + nickname: row.nickname, + score: row.score, + completedAt: new Date(row.completed_at).toISOString(), + durationSeconds: Math.round(row.duration_ms / 10) / 100, + }, + ranks: { allTime, weekly }, + }; +} + +const expiredError = () => new ApiError(410, 'run_expired', 'This ranked run has expired; start a new one'); +const rejectedError = (run: RunRow) => + new ApiError(409, 'run_rejected', 'This run was already submitted and rejected', { status: 'rejected', reason: run.reject_reason }); + +const isRecord = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); + +// --- housekeeping & moderation --------------------------------------------------------------------------------------------- + +const DAY_MS = 86_400_000; + +/** Deletes data that can no longer matter. Accepted runs are kept (their scores reference them). */ +export async function pruneStaleRuns(db: Db, now: number): Promise<{ abandoned: number; rejected: number }> { + const abandoned = await db.run(`DELETE FROM runs WHERE status IN ('issued', 'verifying') AND expires_at < ?`, [now - DAY_MS]); + const rejected = await db.run(`DELETE FROM runs WHERE status = 'rejected' AND finished_at < ?`, [now - 30 * DAY_MS]); + return { abandoned: abandoned.changes, rejected: rejected.changes }; +} + +export async function setScoreVisibility(db: Db, scoreId: string, visible: boolean, reason: string | null, now: number): Promise { + const res = await db.run( + visible + ? `UPDATE scores SET visibility = 'visible', hidden_reason = NULL, hidden_at = NULL WHERE id = ?` + : `UPDATE scores SET visibility = 'hidden', hidden_reason = ?, hidden_at = ? WHERE id = ?`, + visible ? [scoreId] : [reason ? reason.slice(0, 200) : null, now, scoreId], + ); + return res.changes === 1; +} diff --git a/phaser-asteroids/server/src/verify.ts b/phaser-asteroids/server/src/verify.ts new file mode 100644 index 0000000..a4b3b8b --- /dev/null +++ b/phaser-asteroids/server/src/verify.ts @@ -0,0 +1,94 @@ +import type { GameConfig } from '../../src/core/gameConfig'; +import { FIXED_TICK_RATE } from '../../src/replay/constants'; +import { verifyReplay } from '../../src/replay/verifier'; +import type { VerificationResult } from '../../src/replay/types'; +import type { ServerSettings } from './config'; + +/** What the server issued for this run; the replay must agree with every field. */ +export interface IssuedRunFacts { + seed: number; + rulesVersion: string; + config: GameConfig; + createdAt: number; +} + +export type RejectCode = + | 'invalid_replay' + | 'seed_mismatch' + | 'rules_mismatch' + | 'config_mismatch' + | 'too_long' + | 'too_fast' + | 'not_game_over' + | 'score_mismatch'; + +export type RankedVerdict = + | { ok: true; result: VerificationResult } + | { ok: false; code: RejectCode; detail: string }; + +const reject = (code: RejectCode, detail: string): RankedVerdict => ({ ok: false, code, detail }); + +/** Exactly the approved fields, with exactly the approved values (extra keys are a mismatch too). */ +function configMatches(actual: unknown, expected: GameConfig): boolean { + if (!actual || typeof actual !== 'object' || Array.isArray(actual)) return false; + const a = actual as Record; + const keys = Object.keys(a).sort(); + if (keys.join(',') !== Object.keys(expected).sort().join(',')) return false; + return ( + a.playerCount === expected.playerCount && + a.livesMode === expected.livesMode && + a.friendlyFire === expected.friendlyFire && + Array.isArray(a.speed) && + a.speed.length === expected.speed.length && + expected.speed.every((s, i) => (a.speed as unknown[])[i] === s) + ); +} + +/** + * Decides whether `replay` is a legitimate recording of the run the server issued, and if so returns the score the server itself + * calculated by simulating it. The cheap checks come first so that obviously unacceptable submissions never reach the + * simulation. `now` is the server clock when the submission was claimed. + * + * Whatever the replay says about its own score (`claimedResult`) is never used as the score; verifyReplay only cross-checks it, + * and a disagreement is a rejection. + */ +export function verifyRankedReplay(replay: unknown, run: IssuedRunFacts, now: number, settings: ServerSettings): RankedVerdict { + if (!replay || typeof replay !== 'object' || Array.isArray(replay)) return reject('invalid_replay', 'replay must be an object'); + const r = replay as { header?: Record; totalTicks?: unknown }; + const header = r.header; + if (!header || typeof header !== 'object' || Array.isArray(header)) return reject('invalid_replay', 'replay header is missing'); + + // The verifier in this deployment only knows one rules version. A run issued before an upgrade can no longer be reproduced. + if (run.rulesVersion !== settings.rulesVersion) { + return reject('rules_mismatch', `this run was issued under rules ${run.rulesVersion}; the server now verifies ${settings.rulesVersion}`); + } + if (header.seed !== run.seed) return reject('seed_mismatch', 'replay seed is not the seed issued for this run'); + if (header.rulesVersion !== run.rulesVersion) { + return reject('rules_mismatch', `replay rules version ${String(header.rulesVersion)} is not the issued ${run.rulesVersion}`); + } + if (!configMatches(header.config, run.config)) return reject('config_mismatch', 'replay config is not the approved ranked configuration'); + + const totalTicks = r.totalTicks; + if (typeof totalTicks !== 'number' || !Number.isInteger(totalTicks) || totalTicks <= 0) { + return reject('invalid_replay', 'totalTicks must be a positive integer'); + } + if (totalTicks > settings.maxTicks) return reject('too_long', `replay exceeds the ranked limit of ${settings.maxTicks} ticks`); + + // The game clock cannot run faster than the wall clock: ticks advance at most once per 1/60 s of real time, and the client + // could not begin playing before the challenge existed. This rejects "ten minutes of play submitted five seconds later". + // It cannot prove a human played; a bot may simply wait. + const simulatedMs = (totalTicks * 1000) / FIXED_TICK_RATE; + const elapsedMs = now - run.createdAt; + if (simulatedMs > elapsedMs + settings.elapsedSlackMs) { + return reject('too_fast', `replay covers ${Math.round(simulatedMs)} ms of play but only ${Math.max(0, Math.round(elapsedMs))} ms have passed since the challenge was issued`); + } + + const result = verifyReplay(replay, { maxTicks: settings.maxTicks, requireGameOver: true }); + if (result.valid) return { ok: true, result }; + + if (result.discrepancy) return reject('score_mismatch', result.discrepancy); + // verifyReplay reports a recording that simply stops before the ship is destroyed with a real tick count but phase !== 'gameOver'; + // structural failures return zeroed results. + if (result.totalTicks > 0 && result.phase !== 'gameOver') return reject('not_game_over', result.error ?? 'run did not end in game over'); + return reject('invalid_replay', result.error ?? 'replay failed verification'); +} diff --git a/phaser-asteroids/server/src/week.ts b/phaser-asteroids/server/src/week.ts new file mode 100644 index 0000000..252c40c --- /dev/null +++ b/phaser-asteroids/server/src/week.ts @@ -0,0 +1,87 @@ +/** + * The weekly leaderboard window: Monday 00:00 to the next Monday 00:00 in a named IANA time zone (default America/Halifax), + * computed from the server's own clock. "Local midnight" is converted to a UTC instant with the zone's real offset at that + * moment, so a week that contains a daylight-saving change is 167 or 169 hours long rather than a fixed 168. + */ + +export interface WeekWindow { + /** Inclusive, epoch ms. */ + startMs: number; + /** Exclusive, epoch ms: the start of the following week. */ + endMs: number; + timeZone: string; +} + +interface ZonedParts { + year: number; + month: number; // 1-12 + day: number; + hour: number; + minute: number; + second: number; + /** 1 = Monday ... 7 = Sunday */ + isoWeekday: number; +} + +const WEEKDAYS: Record = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 }; +const formatters = new Map(); + +function formatterFor(timeZone: string): Intl.DateTimeFormat { + let f = formatters.get(timeZone); + if (!f) { + f = new Intl.DateTimeFormat('en-US', { + timeZone, + hourCycle: 'h23', + weekday: 'short', + year: 'numeric', + month: 'numeric', + day: 'numeric', + hour: 'numeric', + minute: 'numeric', + second: 'numeric', + }); + formatters.set(timeZone, f); + } + return f; +} + +export function zonedParts(ms: number, timeZone: string): ZonedParts { + const out: Record = {}; + for (const p of formatterFor(timeZone).formatToParts(new Date(ms))) out[p.type] = p.value; + return { + year: Number(out.year), + month: Number(out.month), + day: Number(out.day), + hour: Number(out.hour), + minute: Number(out.minute), + second: Number(out.second), + isoWeekday: WEEKDAYS[out.weekday!] ?? 1, + }; +} + +/** The zone's UTC offset (local minus UTC) in ms at the instant `ms`. */ +function offsetAt(ms: number, timeZone: string): number { + const p = zonedParts(ms, timeZone); + const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second); + return asUtc - Math.floor(ms / 1000) * 1000; +} + +/** The UTC instant at which the wall clock in `timeZone` reads 00:00:00 on the given calendar date. */ +function localMidnightUtc(year: number, month: number, day: number, timeZone: string): number { + const naive = Date.UTC(year, month - 1, day); + // Two refinement steps settle on the right offset even when the offset at `naive` differs from the offset at midnight. + const first = naive - offsetAt(naive, timeZone); + return naive - offsetAt(first, timeZone); +} + +export function weekWindow(nowMs: number, timeZone: string): WeekWindow { + const local = zonedParts(nowMs, timeZone); + // Calendar arithmetic on the local date only (Date.UTC normalises overflowing days), so DST never skews it. + const monday = new Date(Date.UTC(local.year, local.month - 1, local.day - (local.isoWeekday - 1))); + const nextMonday = new Date(Date.UTC(monday.getUTCFullYear(), monday.getUTCMonth(), monday.getUTCDate() + 7)); + return { + startMs: localMidnightUtc(monday.getUTCFullYear(), monday.getUTCMonth() + 1, monday.getUTCDate(), timeZone), + endMs: localMidnightUtc(nextMonday.getUTCFullYear(), nextMonday.getUTCMonth() + 1, nextMonday.getUTCDate(), timeZone), + timeZone, + }; +} diff --git a/phaser-asteroids/server/src/worker.ts b/phaser-asteroids/server/src/worker.ts new file mode 100644 index 0000000..e9801bc --- /dev/null +++ b/phaser-asteroids/server/src/worker.ts @@ -0,0 +1,22 @@ +import { loadSettings, type Env } from './config'; +import { d1Db } from './d1'; +import { pruneRateLimits } from './ratelimit'; +import { handleRequest } from './router'; +import { pruneStaleRuns } from './runs'; + +/** Cloudflare Worker entry: wires the D1 binding and environment variables into the portable service. */ +export default { + async fetch(request: Request, env: Env): Promise { + return handleRequest(request, { db: d1Db(env.DB), settings: loadSettings(env), now: Date.now }); + }, + + /** Daily housekeeping (cron trigger in wrangler.toml): drops abandoned runs, old rejected runs and stale rate-limit counters. */ + async scheduled(_event: unknown, env: Env): Promise { + const db = d1Db(env.DB); + const settings = loadSettings(env); + const now = Date.now(); + const runs = await pruneStaleRuns(db, now); + const limits = await pruneRateLimits(db, now, settings.rate.windowMs); + console.log(JSON.stringify({ evt: 'prune', ...runs, rateLimitRows: limits })); + }, +}; diff --git a/phaser-asteroids/server/testing/bot.d.mts b/phaser-asteroids/server/testing/bot.d.mts new file mode 100644 index 0000000..e888733 --- /dev/null +++ b/phaser-asteroids/server/testing/bot.d.mts @@ -0,0 +1,20 @@ +import type { GameConfig } from '../../src/core/gameConfig'; +import type { ReplayRecord } from '../../src/replay'; + +export interface BotOptions { + seed: number; + config?: GameConfig; + stress?: boolean; + maxTicks?: number; + idle?: boolean; + spin?: boolean; +} + +export interface BotRun { + replay: ReplayRecord; + score: number; + gameOver: boolean; + ticks: number; +} + +export function generateBotReplay(engine: unknown, opts: BotOptions): BotRun; diff --git a/phaser-asteroids/server/testing/bot.mjs b/phaser-asteroids/server/testing/bot.mjs new file mode 100644 index 0000000..ecad7cf --- /dev/null +++ b/phaser-asteroids/server/testing/bot.mjs @@ -0,0 +1,111 @@ +// Autonomous evasion-and-combat bot that produces genuine, game-over-terminated replays for tests and benchmarks. +// The engine is injected ({ GameSim, ReplayRecorder, seededRng, toPlayerInput, toRecordedInput, FIXED_DT }) so the same +// bot runs against the TypeScript sources (vitest) and the built Node bundle (dist/node/index.js, plain Node scripts). +// +// This is test tooling. It is also exactly the kind of automated player the server cannot tell apart from a human; see +// "Remaining security limitations" in docs/leaderboard-backend.md. + +const DEFAULT_CONFIG = { playerCount: 1, livesMode: 'independent', friendlyFire: false, speed: [1, 1] }; + +/** + * @param engine injected replay engine + * @param opts { seed, config?, stress?, maxTicks?, idle? } + * spin: sit still, sweep the cannon back and forth and fire (short games that still score) + * idle: skip all play so the ship is simply destroyed by the first asteroid (a very short, zero-ish score run) + * maxTicks: stop early; if game over was not reached the replay is an "abandoned" run + */ +export function generateBotReplay(engine, opts) { + const { GameSim, ReplayRecorder, seededRng, toPlayerInput, toRecordedInput, FIXED_DT } = engine; + const seed = opts.seed >>> 0; + const config = opts.config ?? DEFAULT_CONFIG; + const maxTicks = opts.maxTicks ?? 108000; + const recorder = new ReplayRecorder(seed, config); + const sim = new GameSim({ rng: seededRng(seed), config }); + + for (let tick = 0; tick < maxTicks; tick++) { + const rawInput = opts.idle + ? { rotate: 0, move: 0, shoot: false } + : opts.spin + ? { rotate: tick % 240 < 120 ? 1 : -1, move: 0, shoot: true } + : decide(sim, tick, !!opts.stress); + const effective = toPlayerInput(toRecordedInput(rawInput)); + recorder.recordTick(tick, effective, sim); + sim.step(FIXED_DT, effective); + if (sim.isGameOver) { + recorder.markGameOver(sim); + break; + } + } + return { replay: recorder.exportReplay(), score: sim.totalScore, gameOver: sim.isGameOver, ticks: recorder.ticks }; +} + +function decide(sim, tick, stress) { + const px = sim.player.position.x; + const py = sim.player.position.y; + let dangerX = 0; + let dangerY = 0; + let anyDanger = false; + let minD = Infinity; + let closest = null; + + for (const a of sim.asteroids) { + if (!a.alive || a.dying) continue; + const dx = px - a.position.x; + const dy = py - a.position.y; + const d = Math.hypot(dx, dy); + if (d < 300) { + anyDanger = true; + const force = (300 - d) / (d + 1); + dangerX += (dx / d) * force; + dangerY += (dy / d) * force; + if (d < minD) { + minD = d; + closest = a; + } + } + } + for (const u of sim.ufos) { + if (!u.alive) continue; + const dx = px - u.position.x; + const dy = py - u.position.y; + const d = Math.hypot(dx, dy); + if (d < 300) { + anyDanger = true; + dangerX += (dx / d) * 2; + dangerY += (dy / d) * 2; + if (d < minD) minD = d; + } + } + for (const s of sim.ufoShots) { + if (!s.alive) continue; + const dx = px - s.position.x; + const dy = py - s.position.y; + const d = Math.hypot(dx, dy); + if (d < 150) { + anyDanger = true; + dangerX += (dx / d) * 4; + dangerY += (dy / d) * 4; + } + } + if (px < 200) dangerX += (200 - px) / 40; + if (px > 1080) dangerX -= (px - 1080) / 40; + if (py < 150) dangerY += (150 - py) / 40; + if (py > 570) dangerY -= (py - 570) / 40; + + let targetAngle = 0; + let move = 0; + let boost = false; + let laser = false; + if (minD < 120 && closest && sim.player.boost.cooldown <= 0 && tick % 2 === 0) { + boost = true; + move = 1; + const rdx = closest.position.x - px; + const rdy = closest.position.y - py; + targetAngle = ((((Math.atan2(-rdx, rdy) * 180) / Math.PI) % 360) + 360) % 360; + } else if (anyDanger) { + targetAngle = ((((Math.atan2(-dangerX, dangerY) * 180) / Math.PI) % 360) + 360) % 360; + move = 1; + if (minD < 220 && (stress || tick % 2 === 0)) laser = true; + } + return { rotate: 0, move, shoot: stress ? true : tick % 4 === 0, boost, laser, steer: { mode: 'assist', heading: targetAngle } }; +} diff --git a/phaser-asteroids/server/testing/sqliteDb.ts b/phaser-asteroids/server/testing/sqliteDb.ts new file mode 100644 index 0000000..d819f7e --- /dev/null +++ b/phaser-asteroids/server/testing/sqliteDb.ts @@ -0,0 +1,71 @@ +// Test-only adapter: runs the exact production SQL (and the exact migration files) on Node's built-in SQLite. +// Production uses Cloudflare D1 (src/d1.ts); both speak the same SQLite dialect. +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import type { Db, SqlValue, Statement } from '../src/db'; + +const migrationsDir = path.resolve(import.meta.dirname, '..', 'migrations'); + +export interface SqliteDb extends Db { + exec(sql: string): void; + close(): void; +} + +/** + * Opens a database with the migrations applied. No `file`: a private in-memory database. A file path lets several connections + * share one database, which is how the tests imitate several Worker instances. + */ +export function openSqliteDb(file = ':memory:'): SqliteDb { + const raw = new DatabaseSync(file); + raw.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 10000;'); + if (file !== ':memory:') raw.exec('PRAGMA journal_mode = WAL;'); + + const hasSchema = raw.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'runs'").get(); + if (!hasSchema) { + const files = readdirSync(migrationsDir) + .filter((f) => f.endsWith('.sql')) + .sort(); + for (const f of files) raw.exec(readFileSync(path.join(migrationsDir, f)).toString()); + } + + const run = (sql: string, params: SqlValue[] = []) => ({ changes: Number(raw.prepare(sql).run(...params).changes) }); + + return { + async all(sql: string, params: SqlValue[] = []) { + return raw.prepare(sql).all(...params) as T[]; + }, + async first(sql: string, params: SqlValue[] = []) { + return (raw.prepare(sql).get(...params) as T | undefined) ?? null; + }, + async run(sql, params) { + return run(sql, params); + }, + async batch(statements: Statement[]) { + raw.exec('BEGIN IMMEDIATE'); + try { + const out = statements.map((s) => run(s.sql, s.params)); + raw.exec('COMMIT'); + return out; + } catch (e) { + raw.exec('ROLLBACK'); + throw e; + } + }, + exec: (sql) => raw.exec(sql), + close: () => raw.close(), + }; +} + +/** Wraps a Db so chosen statements fail, to test that failures never leave a half-accepted run behind. */ +export function faultyDb(inner: Db, shouldFail: (sql: string) => boolean): Db { + const check = (sql: string) => { + if (shouldFail(sql)) throw new Error('simulated database failure'); + }; + return { + all: async (sql, params) => (check(sql), inner.all(sql, params)), + first: async (sql, params) => (check(sql), inner.first(sql, params)), + run: async (sql, params) => (check(sql), inner.run(sql, params)), + batch: async (statements) => (statements.forEach((s) => check(s.sql)), inner.batch(statements)), + }; +} diff --git a/phaser-asteroids/server/tests/harness.ts b/phaser-asteroids/server/tests/harness.ts new file mode 100644 index 0000000..ca7d913 --- /dev/null +++ b/phaser-asteroids/server/tests/harness.ts @@ -0,0 +1,163 @@ +import { gzipSync } from 'node:zlib'; +import * as engine from '../../src/replay'; +import type { ReplayRecord } from '../../src/replay'; +import { loadSettings, type ServerSettings } from '../src/config'; +import type { Db } from '../src/db'; +import { handleRequest } from '../src/router'; +import type { IssuedRun, ServiceDeps } from '../src/runs'; +import { generateBotReplay, type BotOptions, type BotRun } from '../testing/bot.mjs'; +import { openSqliteDb, type SqliteDb } from '../testing/sqliteDb'; + +export const T0 = Date.UTC(2026, 9, 22, 15, 0, 0); // Thu 2026-10-22 12:00 in Halifax (ADT) + +export interface Clock { + t: number; + now: () => number; + advance: (ms: number) => void; +} + +export function makeClock(start = T0): Clock { + const clock: Clock = { t: start, now: () => clock.t, advance: (ms) => void (clock.t += ms) }; + return clock; +} + +const botCache = new Map(); + +/** Genuine game-over-terminated replay for `seed`, from the shared autonomous bot. Cached: generation costs 50-400 ms. */ +export function botRun(seed: number, opts: Omit = {}): BotRun { + const key = `${seed}:${JSON.stringify(opts)}`; + let run = botCache.get(key); + if (!run) { + run = generateBotReplay(engine, { seed, ...opts }); + botCache.set(key, run); + } + return structuredClone(run); +} + +/** 2-minute game, score 9114 (the Phase 1 reference run). */ +export const REFERENCE_SEED = 54321; + +export interface Harness { + db: SqliteDb; + clock: Clock; + settings: ServerSettings; + deps: ServiceDeps; + /** Sends a request through the real router. */ + call: (method: string, path: string, init?: CallInit) => Promise; + /** POST /runs, optionally rewriting the server-chosen seed in the DB so a cached replay can be reused (test-only shortcut). */ + start: (opts?: { seed?: number; ip?: string }) => Promise; + /** Submits a replay for `run` as a well-behaved client would. */ + submit: (run: IssuedRun, replay: unknown, extra?: SubmitExtra) => Promise; + /** Advances the clock as if the replay had been played in real time, then submits. */ + playAndSubmit: (run: IssuedRun, replay: ReplayRecord, extra?: SubmitExtra) => Promise; +} + +export interface CallInit { + headers?: Record; + body?: BodyInit | null; + json?: unknown; + ip?: string; + token?: string; +} + +export interface SubmitExtra { + nickname?: unknown; + controls?: unknown; + token?: string | null; + gzip?: boolean; + /** Replaces the whole serialized body. */ + rawBody?: string | Uint8Array; + ip?: string; +} + +export interface ApiResponse { + status: number; + headers: Headers; + body: any; +} + +export function makeHarness(opts: { db?: SqliteDb; clock?: Clock; settings?: Partial; dbWrap?: (db: Db) => Db } = {}): Harness { + const db = opts.db ?? openSqliteDb(); + const clock = opts.clock ?? makeClock(); + const settings: ServerSettings = { ...loadSettings({ ADMIN_TOKEN: 'test-admin-token-1234567890', IP_HASH_SALT: 'test-salt' }), ...opts.settings }; + const deps: ServiceDeps = { db: opts.dbWrap ? opts.dbWrap(db) : db, settings, now: clock.now }; + + const call: Harness['call'] = async (method, path, init = {}) => { + const headers = new Headers(init.headers); + if (init.ip) headers.set('cf-connecting-ip', init.ip); + if (init.token) headers.set('authorization', `Bearer ${init.token}`); + let body = init.body ?? null; + if (init.json !== undefined) { + body = JSON.stringify(init.json); + headers.set('content-type', 'application/json'); + } + const res = await handleRequest(new Request(`https://api.test${path}`, { method, headers, body }), deps); + const text = await res.text(); + let parsed: unknown = text; + try { + parsed = text ? JSON.parse(text) : null; + } catch { + /* not JSON */ + } + return { status: res.status, headers: res.headers, body: parsed }; + }; + + const start: Harness['start'] = async ({ seed, ip } = {}) => { + const res = await call('POST', '/api/v1/runs', { ip: ip ?? '203.0.113.7' }); + if (res.status !== 201) throw new Error(`start failed: ${res.status} ${JSON.stringify(res.body)}`); + const run = res.body as IssuedRun; + if (seed !== undefined) { + await db.run('UPDATE runs SET seed = ? WHERE id = ?', [seed, run.runId]); + run.seed = seed; + } + return run; + }; + + const submit: Harness['submit'] = (run, replay, extra = {}) => { + const headers: Record = { 'content-type': 'application/json' }; + let body: BodyInit; + if (extra.rawBody !== undefined) body = extra.rawBody as BodyInit; + else { + const json = JSON.stringify({ replay, nickname: extra.nickname, controls: extra.controls }); + body = json; + } + if (extra.gzip) { + body = gzipSync(typeof body === 'string' ? Buffer.from(body) : (body as Uint8Array)) as unknown as BodyInit; + headers['content-encoding'] = 'gzip'; + } + const token = extra.token === undefined ? run.token : extra.token; + return call('POST', `/api/v1/runs/${run.runId}/submit`, { headers, body, token: token ?? undefined, ip: extra.ip ?? '203.0.113.7' }); + }; + + const playAndSubmit: Harness['playAndSubmit'] = (run, replay, extra) => { + clock.advance((replay.totalTicks / 60) * 1000 + 1500); + return submit(run, replay, extra); + }; + + return { db, clock, settings, deps, call, start, submit, playAndSubmit }; +} + +/** Inserts an accepted run + score directly (for leaderboard tests that need many rows quickly). */ +export async function insertScore( + db: Db, + s: { id?: string; score: number; nickname?: string; completedAt: number; rules?: string; visibility?: 'visible' | 'hidden' }, +): Promise { + const id = s.id ?? crypto.randomUUID(); + const runId = crypto.randomUUID(); + await db.batch([ + { + sql: `INSERT INTO runs (id, token_hash, seed, rules_version, config_json, created_at, expires_at, status, finished_at, score_id) + VALUES (?, 'x', 1, ?, '{}', ?, ?, 'accepted', ?, ?)`, + params: [runId, s.rules ?? '1.0.0', s.completedAt - 60_000, s.completedAt + 3_600_000, s.completedAt, id], + }, + { + sql: `INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms, visibility) + VALUES (?, ?, ?, ?, ?, ?, 3600, 60000, ?)`, + params: [id, runId, s.score, s.nickname ?? 'Tester', s.completedAt, s.rules ?? '1.0.0', s.visibility ?? 'visible'], + }, + ]); + return id; +} + +export const count = async (db: Db, table: string, where = '1=1'): Promise => + (await db.first<{ n: number }>(`SELECT COUNT(*) AS n FROM ${table} WHERE ${where}`))!.n; diff --git a/phaser-asteroids/server/tests/leaderboard.test.ts b/phaser-asteroids/server/tests/leaderboard.test.ts new file mode 100644 index 0000000..8a09939 --- /dev/null +++ b/phaser-asteroids/server/tests/leaderboard.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, it } from 'vitest'; +import { sanitizeNickname } from '../src/nickname'; +import { weekWindow } from '../src/week'; +import { botRun, insertScore, makeClock, makeHarness, REFERENCE_SEED, T0 } from './harness'; + +const HOUR = 3_600_000; +const DAY = 24 * HOUR; +type Entry = { id: string; rank: number; nickname: string; score: number }; +const scores = (b: { entries: Entry[] }) => b.entries.map((e) => e.score); + +describe('leaderboard ordering', () => { + it('sorts highest first, ties go to the earlier finisher, then to the smaller id; ranks are ordinal', async () => { + const h = makeHarness(); + await insertScore(h.db, { id: 'b', score: 500, completedAt: T0 - 5 * HOUR }); + await insertScore(h.db, { id: 'a', score: 500, completedAt: T0 - 5 * HOUR }); // same score, same instant: id decides + await insertScore(h.db, { id: 'c', score: 500, completedAt: T0 - 9 * HOUR }); // earlier: first among the 500s + await insertScore(h.db, { id: 'd', score: 900, completedAt: T0 }); + await insertScore(h.db, { id: 'e', score: 100, completedAt: T0 }); + const res = await h.call('GET', '/api/v1/leaderboard/all-time'); + expect(res.body.entries.map((e: Entry) => [e.id, e.rank])).toEqual([['d', 1], ['c', 2], ['a', 3], ['b', 4], ['e', 5]]); + expect(res.body.total).toBe(5); + }); + + it('excludes hidden, zero-score and other-rules entries', async () => { + const h = makeHarness(); + await insertScore(h.db, { score: 300, completedAt: T0 }); + await insertScore(h.db, { score: 9999, completedAt: T0, visibility: 'hidden' }); + await insertScore(h.db, { score: 0, completedAt: T0 }); + await insertScore(h.db, { score: 8888, completedAt: T0, rules: '0.9.0' }); + const res = await h.call('GET', '/api/v1/leaderboard/all-time'); + expect(scores(res.body)).toEqual([300]); + expect(res.body.total).toBe(1); + }); + + it('exposes only public display fields', async () => { + const h = makeHarness(); + await insertScore(h.db, { score: 300, completedAt: T0, nickname: 'Pilot One' }); + const entry = (await h.call('GET', '/api/v1/leaderboard/all-time')).body.entries[0]; + expect(Object.keys(entry).sort()).toEqual(['completedAt', 'durationSeconds', 'id', 'nickname', 'rank', 'score']); + }); + + it('rejected and unsubmitted runs never appear', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + await h.start(); + const bad = botRun(REFERENCE_SEED); + bad.replay.claimedResult!.score += 1; + await h.playAndSubmit(run, bad.replay); + expect((await h.call('GET', '/api/v1/leaderboard/all-time')).body.total).toBe(0); + }); +}); + +describe('pagination is bounded', () => { + it('defaults to 10, honours limit/offset and reports total', async () => { + const h = makeHarness(); + for (let i = 1; i <= 25; i++) await insertScore(h.db, { score: i * 10, completedAt: T0 }); + const first = await h.call('GET', '/api/v1/leaderboard/all-time'); + expect(first.body.entries).toHaveLength(10); + expect(first.body.entries[0].score).toBe(250); + const page = await h.call('GET', '/api/v1/leaderboard/all-time?limit=5&offset=10'); + expect(scores(page.body)).toEqual([150, 140, 130, 120, 110]); + expect(page.body.entries[0].rank).toBe(11); + expect(page.body.total).toBe(25); + expect((await h.call('GET', '/api/v1/leaderboard/all-time?limit=100')).body.entries).toHaveLength(25); + }); + + it.each(['limit=0', 'limit=101', 'limit=-1', 'limit=abc', 'limit=1.5', 'offset=1001', 'offset=-5', 'limit=1e3', 'limit=99999999999999999999'])( + 'refuses %s', + async (q) => { + const h = makeHarness(); + expect((await h.call('GET', `/api/v1/leaderboard/all-time?${q}`)).status).toBe(400); + }, + ); +}); + +describe('weekly leaderboard', () => { + it('only counts scores completed inside the current Halifax week, using the server timestamp', async () => { + const clock = makeClock(Date.UTC(2026, 9, 22, 15, 0, 0)); // Thursday + const h = makeHarness({ clock }); + const w = weekWindow(clock.t, 'America/Halifax'); + await insertScore(h.db, { id: 'in-start', score: 100, completedAt: w.startMs }); + await insertScore(h.db, { id: 'in-end', score: 200, completedAt: w.endMs - 1 }); + await insertScore(h.db, { id: 'before', score: 9000, completedAt: w.startMs - 1 }); + await insertScore(h.db, { id: 'after', score: 9001, completedAt: w.endMs }); + const res = await h.call('GET', '/api/v1/leaderboard/weekly'); + expect(res.body.entries.map((e: Entry) => e.id)).toEqual(['in-end', 'in-start']); + expect(res.body).toMatchObject({ timeZone: 'America/Halifax', weekStart: '2026-10-19T03:00:00.000Z', weekEnd: '2026-10-26T03:00:00.000Z' }); + const all = await h.call('GET', '/api/v1/leaderboard/all-time'); + expect(all.body.total).toBe(4); + }); + + it('rolls over at Halifax Monday midnight', async () => { + const clock = makeClock(Date.UTC(2026, 9, 26, 2, 59, 59)); // Sunday 23:59:59 ADT + const h = makeHarness({ clock }); + await insertScore(h.db, { id: 'sunday', score: 100, completedAt: clock.t }); + expect((await h.call('GET', '/api/v1/leaderboard/weekly')).body.entries.map((e: Entry) => e.id)).toEqual(['sunday']); + clock.advance(1000); // Monday 00:00:00 ADT + expect((await h.call('GET', '/api/v1/leaderboard/weekly')).body.entries).toEqual([]); + expect((await h.call('GET', '/api/v1/leaderboard/all-time')).body.total).toBe(1); + }); + + it('a verified run lands on both boards with consistent ranks', async () => { + const h = makeHarness(); + await insertScore(h.db, { score: 20000, completedAt: T0 - 30 * DAY, nickname: 'Old Champ' }); // all-time only + await insertScore(h.db, { score: 100, completedAt: T0 - HOUR }); + const run = await h.start({ seed: REFERENCE_SEED }); + const res = await h.playAndSubmit(run, botRun(REFERENCE_SEED).replay); + expect(res.body.ranks).toEqual({ allTime: 2, weekly: 1 }); + const detail = await h.call('GET', `/api/v1/scores/${res.body.score.id}`); + expect(detail.body.ranks).toEqual({ allTime: 2, weekly: 1 }); + expect(detail.body.score.score).toBe(9114); + }); +}); + +describe('moderation', () => { + const admin = { authorization: 'Bearer test-admin-token-1234567890' }; + + it('hiding removes an entry from boards and lookups; unhiding restores it', async () => { + const h = makeHarness(); + const id = await insertScore(h.db, { score: 700, completedAt: T0, nickname: 'Rude Name' }); + await insertScore(h.db, { score: 300, completedAt: T0 }); + const url = `/api/v1/admin/scores/${id}/visibility`; + + const hide = await h.call('POST', url, { headers: admin, json: { visible: false, reason: 'offensive' } }); + expect(hide.status).toBe(200); + expect(scores((await h.call('GET', '/api/v1/leaderboard/all-time')).body)).toEqual([300]); + expect((await h.call('GET', `/api/v1/scores/${id}`)).status).toBe(404); + expect((await h.db.first<{ hidden_reason: string }>('SELECT hidden_reason FROM scores WHERE id = ?', [id]))!.hidden_reason).toBe('offensive'); + + await h.call('POST', url, { headers: admin, json: { visible: true } }); + expect(scores((await h.call('GET', '/api/v1/leaderboard/all-time')).body)).toEqual([700, 300]); + }); + + it('shifts ranks of the entries below a hidden one', async () => { + const h = makeHarness(); + const top = await insertScore(h.db, { score: 700, completedAt: T0 }); + const second = await insertScore(h.db, { score: 300, completedAt: T0 }); + expect((await h.call('GET', `/api/v1/scores/${second}`)).body.ranks.allTime).toBe(2); + await h.call('POST', `/api/v1/admin/scores/${top}/visibility`, { headers: admin, json: { visible: false } }); + expect((await h.call('GET', `/api/v1/scores/${second}`)).body.ranks.allTime).toBe(1); + }); + + it('requires the admin token; failures are rate limited; unknown ids are 404', async () => { + const h = makeHarness(); + const id = await insertScore(h.db, { score: 700, completedAt: T0 }); + const url = `/api/v1/admin/scores/${id}/visibility`; + expect((await h.call('POST', url, { json: { visible: false } })).status).toBe(401); + expect((await h.call('POST', url, { headers: { authorization: 'Bearer wrong' }, json: { visible: false } })).status).toBe(401); + expect((await h.call('POST', `/api/v1/admin/scores/${crypto.randomUUID()}/visibility`, { headers: admin, json: { visible: false } })).status).toBe(404); + expect((await h.call('POST', url, { headers: admin, json: { visible: 'yes' } })).status).toBe(400); + for (let i = 0; i < 12; i++) await h.call('POST', url, { headers: { authorization: 'Bearer nope' }, json: { visible: false } }); + expect((await h.call('POST', url, { headers: { authorization: 'Bearer nope' }, json: { visible: false } })).status).toBe(429); + expect((await h.db.first<{ visibility: string }>('SELECT visibility FROM scores'))!.visibility).toBe('visible'); + }); + + it('admin routes do not exist when no (sufficiently long) token is configured, and never send CORS headers', async () => { + const h = makeHarness({ settings: { adminToken: null } }); + const id = await insertScore(h.db, { score: 700, completedAt: T0 }); + const res = await h.call('POST', `/api/v1/admin/scores/${id}/visibility`, { headers: admin, json: { visible: false } }); + expect(res.status).toBe(404); + const h2 = makeHarness({ settings: { allowedOrigins: ['https://game.example'] } }); + const res2 = await h2.call('POST', `/api/v1/admin/scores/x/visibility`, { headers: { ...admin, origin: 'https://game.example' }, json: { visible: false } }); + expect(res2.headers.get('access-control-allow-origin')).toBeNull(); + }); +}); + +describe('nickname validation', () => { + const ok = (v: unknown) => { + const r = sanitizeNickname(v); + return r.ok ? r.value : null; + }; + it('accepts 3-16 letter/number names with spaces and _ . ! -', () => { + expect(ok('ACE')).toBe('ACE'); + expect(ok('Space Cadet_99')).toBe('Space Cadet_99'); + expect(ok('Zoë-Ann!')).toBe('Zoë-Ann!'); + expect(ok('A'.repeat(16))).toBe('A'.repeat(16)); + expect(ok('日本語プレイヤー')).toBe('日本語プレイヤー'); + }); + it('trims, collapses whitespace and normalises to NFC', () => { + expect(ok(' a b c ')).toBe('a b c'); + expect(ok('Café Bar')).toBe('Café Bar'); + expect(ok('tab\tsplit')).toBe('tab split'); + }); + it('absent or blank becomes Anonymous', () => { + expect(ok(undefined)).toBe('Anonymous'); + expect(ok(null)).toBe('Anonymous'); + expect(ok(' ')).toBe('Anonymous'); + }); + it.each(['ab', 'A'.repeat(17), 'hi', 'a&b', "o'neil", 'quote"d', '_underscore', '...', 'nul\u0000l', 'zero​width', 'rtl‮evil', 'emoji 😀 yes', 5, {}, [], true])( + 'refuses %j', + (v) => { + expect(ok(v)).toBeNull(); + }, + ); +}); + +describe('routing hygiene', () => { + it('health reports the supported rules version', async () => { + const h = makeHarness(); + const res = await h.call('GET', '/api/v1/health'); + expect(res.body).toMatchObject({ ok: true, rulesVersion: '1.0.0', schemaVersion: 1 }); + }); + it('wrong methods and unknown paths get JSON errors', async () => { + const h = makeHarness(); + expect((await h.call('GET', '/api/v1/runs')).status).toBe(405); + expect((await h.call('POST', '/api/v1/leaderboard/all-time')).status).toBe(405); + expect((await h.call('GET', '/api/v1/nope')).status).toBe(404); + expect((await h.call('GET', '/api/v1/scores/does-not-exist')).status).toBe(404); + }); + it('sends nosniff and no-store on mutating responses', async () => { + const h = makeHarness(); + const res = await h.call('POST', '/api/v1/runs'); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + expect(res.headers.get('cache-control')).toBe('no-store'); + }); +}); diff --git a/phaser-asteroids/server/tests/lifecycle.test.ts b/phaser-asteroids/server/tests/lifecycle.test.ts new file mode 100644 index 0000000..8fc6cc5 --- /dev/null +++ b/phaser-asteroids/server/tests/lifecycle.test.ts @@ -0,0 +1,545 @@ +import { gzipSync } from 'node:zlib'; +import { describe, expect, it, vi } from 'vitest'; +import type { ReplayRecord } from '../../src/replay'; +import { faultyDb, openSqliteDb } from '../testing/sqliteDb'; +import { botRun, count, makeClock, makeHarness, REFERENCE_SEED, T0 } from './harness'; + +// Replaying real games is CPU-heavy; do not let a busy machine turn that into a spurious timeout. +vi.setConfig({ testTimeout: 60_000 }); + +const reference = () => botRun(REFERENCE_SEED); + +describe('starting a ranked run', () => { + it('issues a server-chosen seed, rules version, approved config and expiry', async () => { + const h = makeHarness(); + const run = await h.start(); + expect(run.runId).toMatch(/^[0-9a-f-]{36}$/); + expect(run.token.length).toBeGreaterThanOrEqual(40); + expect(Number.isInteger(run.seed) && run.seed >= 0 && run.seed <= 0xffffffff).toBe(true); + expect(run.rulesVersion).toBe('1.0.0'); + expect(run.tickRate).toBe(60); + expect(run.config).toEqual({ playerCount: 1, livesMode: 'independent', friendlyFire: false, speed: [1, 1] }); + expect(Date.parse(run.expiresAt) - Date.parse(run.issuedAt)).toBe(h.settings.runTtlMs); + expect(Date.parse(run.issuedAt)).toBe(T0); + }); + + it('stores only a hash of the token', async () => { + const h = makeHarness(); + const run = await h.start(); + const row = await h.db.first<{ token_hash: string }>('SELECT token_hash FROM runs WHERE id = ?', [run.runId]); + expect(row!.token_hash).toMatch(/^[0-9a-f]{64}$/); + expect(JSON.stringify(row)).not.toContain(run.token); + }); + + it('ignores anything the client tries to choose (seed, config, rules) in the request', async () => { + const h = makeHarness(); + const res = await h.call('POST', '/api/v1/runs', { + json: { seed: 1, config: { playerCount: 2 }, rulesVersion: '0.0.1' }, + ip: '198.51.100.1', + }); + expect(res.status).toBe(201); + expect(res.body.seed).not.toBe(1); + expect(res.body.config.playerCount).toBe(1); + expect(res.body.rulesVersion).toBe('1.0.0'); + }); + + it('issues unique ids, tokens and (practically) unique seeds', async () => { + const h = makeHarness({ settings: { rate: { ...makeHarness().settings.rate, startPerIp: 1000, startGlobal: 1000 } } }); + const runs = await Promise.all(Array.from({ length: 60 }, () => h.start())); + expect(new Set(runs.map((r) => r.runId)).size).toBe(60); + expect(new Set(runs.map((r) => r.token)).size).toBe(60); + expect(new Set(runs.map((r) => r.seed)).size).toBeGreaterThan(55); + }); +}); + +describe('submitting a legitimate run', () => { + it('accepts it and stores the score the SERVER computed', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + const res = await h.playAndSubmit(run, bot.replay, { nickname: 'Dave J', controls: { scheme: 'keyboard' } }); + expect(res.status).toBe(200); + expect(res.body.status).toBe('accepted'); + expect(res.body.replayed).toBe(false); + expect(res.body.score.score).toBe(9114); + expect(res.body.score.nickname).toBe('Dave J'); + expect(res.body.ranks).toEqual({ allTime: 1, weekly: 1 }); + + const row = await h.db.first>('SELECT * FROM scores'); + expect(row).toMatchObject({ score: 9114, ticks: bot.ticks, reported_controls: 'keyboard', visibility: 'visible', rules_version: '1.0.0' }); + expect(await count(h.db, 'runs', "status = 'accepted'")).toBe(1); + expect(await count(h.db, 'scores')).toBe(1); + + const board = await h.call('GET', '/api/v1/leaderboard/all-time'); + expect(board.body.entries.map((e: { score: number }) => e.score)).toEqual([9114]); + }); + + it('ignores the score the client claims when it is not consistent, and never takes it as the score', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + // Strip the claim: the server still computes (and stores) its own number, not any number the client could have supplied. + delete (bot.replay as { claimedResult?: unknown }).claimedResult; + const res = await h.playAndSubmit(run, bot.replay); + expect(res.status).toBe(200); + expect(res.body.score.score).toBe(9114); + }); +}); + +describe('forged and invalid recordings are rejected', () => { + async function rejectedWith(mutate: (r: ReplayRecord) => void, reason: string, seed = REFERENCE_SEED) { + const h = makeHarness(); + const run = await h.start({ seed }); + const bot = botRun(seed); + mutate(bot.replay); + const res = await h.playAndSubmit(run, bot.replay); + expect(res.status).toBe(422); + expect(res.body.error.code).toBe('replay_rejected'); + expect(res.body.error.reason).toBe(reason); + expect(await count(h.db, 'scores')).toBe(0); + const row = await h.db.first<{ status: string; reject_reason: string }>('SELECT status, reject_reason FROM runs'); + expect(row).toEqual({ status: 'rejected', reject_reason: reason }); + return h; + } + + it('inflated client score claim', () => rejectedWith((r) => void (r.claimedResult!.score += 100000), 'score_mismatch')); + it('seed that is not the issued seed', () => rejectedWith((r) => void (r.header.seed = 7), 'seed_mismatch')); + it('seed chosen by the client at the issuing stage is useless: replay of another seed fails', async () => { + const h = makeHarness(); + const run = await h.start({ seed: 999 }); + const res = await h.playAndSubmit(run, reference().replay); // replay was recorded for 54321 + expect(res.body.error.reason).toBe('seed_mismatch'); + }); + it('co-op config', () => rejectedWith((r) => void (r.header.config = { ...r.header.config, playerCount: 2 }), 'config_mismatch')); + it('shared-lives config', () => rejectedWith((r) => void (r.header.config = { ...r.header.config, livesMode: 'shared' }), 'config_mismatch')); + it('extra config keys', () => rejectedWith((r) => void ((r.header.config as unknown as Record).godMode = true), 'config_mismatch')); + it('speed handicap config', () => rejectedWith((r) => void (r.header.config = { ...r.header.config, speed: [2, 1] }), 'config_mismatch')); + it('unsupported rules version', () => rejectedWith((r) => void (r.header.rulesVersion = '0.9.0'), 'rules_mismatch')); + it('a run issued under older rules, after the server moved on, is rejected with a clear reason', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + await h.db.run("UPDATE runs SET rules_version = '0.9.0' WHERE id = ?", [run.runId]); + const bot = botRun(REFERENCE_SEED); + bot.replay.header.rulesVersion = '0.9.0'; + const res = await h.playAndSubmit(run, bot.replay); + expect(res.status).toBe(422); + expect(res.body.error.reason).toBe('rules_mismatch'); + expect(await count(h.db, 'scores')).toBe(0); + }); + it('unsupported schema version', () => rejectedWith((r) => void (r.header.schemaVersion = 99), 'invalid_replay')); + it('wrong tick rate', () => rejectedWith((r) => void (r.header.tickRate = 120), 'invalid_replay')); + it('modified input timing (the altered run no longer matches the recording)', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = botRun(REFERENCE_SEED); + (() => { + const r = bot.replay; + const mid = Math.floor(r.inputs.length / 2); + r.inputs[mid]!.tick += 1; + if (r.inputs[mid + 1] && r.inputs[mid]!.tick >= r.inputs[mid + 1]!.tick) r.inputs[mid]!.tick -= 1; + r.inputs[mid]!.input.move = r.inputs[mid]!.input.move > 0 ? -1 : 1; + })(); + const res = await h.playAndSubmit(run, bot.replay); + expect(res.status).toBe(422); + expect(['score_mismatch', 'invalid_replay', 'not_game_over']).toContain(res.body.error.reason); + expect(await count(h.db, 'scores')).toBe(0); + }); + it('reordered ticks', () => rejectedWith((r) => void r.inputs.reverse(), 'invalid_replay')); + it('extra ticks padded after game over', () => rejectedWith((r) => void (r.totalTicks += 10), 'invalid_replay')); + it('input appended after game over', () => + rejectedWith((r) => { + r.totalTicks += 5; + r.inputs.push({ tick: r.totalTicks - 1, input: { rotate: 0, move: 1, shoot: true } }); + }, 'invalid_replay')); + it('abandoned run that never reached game over', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = botRun(REFERENCE_SEED, { maxTicks: 1200 }); + expect(bot.gameOver).toBe(false); + delete (bot.replay as { claimedResult?: unknown }).claimedResult; + const res = await h.playAndSubmit(run, bot.replay); + expect(res.status).toBe(422); + expect(res.body.error.reason).toBe('not_game_over'); + expect(await count(h.db, 'scores')).toBe(0); + }); + it('over-long replay', async () => { + const h = makeHarness({ settings: { maxTicks: 1000 } }); + const run = await h.start({ seed: REFERENCE_SEED }); + const res = await h.playAndSubmit(run, reference().replay); + expect(res.body.error.reason).toBe('too_long'); + }); + it('NaN / out-of-range input values', () => rejectedWith((r) => void (r.inputs[1]!.input.rotate = 50), 'invalid_replay')); + + it('a ten-minute replay cannot arrive seconds after the challenge was issued', async () => { + const h = makeHarness(); + const seed = 4018; // 36,554 ticks = 10.2 minutes + const run = await h.start({ seed }); + const bot = botRun(seed); + h.clock.advance(5000); + const res = await h.submit(run, bot.replay); + expect(res.status).toBe(422); + expect(res.body.error.reason).toBe('too_fast'); + expect(await count(h.db, 'scores')).toBe(0); + }); + + it('the same ten-minute replay is accepted once the full time has really elapsed', async () => { + const h = makeHarness(); + const seed = 4018; + const run = await h.start({ seed }); + const bot = botRun(seed); + h.clock.advance((bot.replay.totalTicks / 60) * 1000 + 1000); + expect((await h.submit(run, bot.replay)).status).toBe(200); + }); + + it('a long pause (wall time >> simulated time) is fine within the expiry window', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + h.clock.advance(40 * 60_000); // 40 min of pauses / tab suspension + expect((await h.submit(run, reference().replay)).status).toBe(200); + }); +}); + +describe('credentials, ownership and expiry', () => { + it('unknown and malformed run ids -> 404', async () => { + const h = makeHarness(); + const bot = reference(); + for (const id of [crypto.randomUUID(), 'not-a-uuid', '../../etc/passwd']) { + const res = await h.call('POST', `/api/v1/runs/${encodeURIComponent(id)}/submit`, { json: { replay: bot.replay }, token: 'x' }); + expect(res.status).toBe(404); + } + }); + + it('missing, wrong and truncated tokens -> 401 and the run stays open', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + for (const token of [null, 'wrong', run.token.slice(0, -1), run.token + 'x', '']) { + const res = await h.playAndSubmit(run, bot.replay, { token }); + expect(res.status).toBe(401); + } + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('issued'); + expect((await h.submit(run, bot.replay)).status).toBe(200); + }); + + it("another player's run cannot be submitted with your token (or theirs, without it)", async () => { + const h = makeHarness(); + const mine = await h.start({ seed: REFERENCE_SEED }); + const theirs = await h.start({ seed: REFERENCE_SEED, ip: '198.51.100.9' }); + const bot = reference(); + h.clock.advance(200_000); + expect((await h.submit(theirs, bot.replay, { token: mine.token })).status).toBe(401); + expect((await h.submit(theirs, bot.replay, { token: null })).status).toBe(401); + expect(await count(h.db, 'scores')).toBe(0); + }); + + it('an expired challenge is refused (410) and never creates a score', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + h.clock.advance(h.settings.runTtlMs + 1); + const res = await h.submit(run, reference().replay); + expect(res.status).toBe(410); + expect(res.body.error.code).toBe('run_expired'); + expect(await count(h.db, 'scores')).toBe(0); + }); +}); + +describe('one-use runs', () => { + it('re-sending the identical body after success is idempotent: same score, no second row', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + const first = await h.playAndSubmit(run, bot.replay, { nickname: 'Dave J' }); + const again = await h.submit(run, bot.replay, { nickname: 'Dave J' }); + expect(again.status).toBe(200); + expect(again.body.replayed).toBe(true); + expect(again.body.score.id).toBe(first.body.score.id); + expect(await count(h.db, 'scores')).toBe(1); + }); + + it('a different body for an accepted run is refused (409) and cannot change the stored score', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + await h.playAndSubmit(run, bot.replay, { nickname: 'Dave J' }); + const other = await h.submit(run, bot.replay, { nickname: 'Someone Else' }); + expect(other.status).toBe(409); + expect(other.body.error.code).toBe('run_already_submitted'); + expect((await h.db.first<{ nickname: string }>('SELECT nickname FROM scores'))!.nickname).toBe('Dave J'); + }); + + it('a rejected run is terminal: a corrected replay cannot be tried again', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bad = reference(); + bad.replay.claimedResult!.score += 1; + expect((await h.playAndSubmit(run, bad.replay)).status).toBe(422); + const retry = await h.submit(run, reference().replay); + expect(retry.status).toBe(409); + expect(retry.body.error.code).toBe('run_rejected'); + expect(await count(h.db, 'scores')).toBe(0); + }); + + it('simultaneous identical submissions create exactly one score', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + h.clock.advance(200_000); + const results = await Promise.all(Array.from({ length: 12 }, () => h.submit(run, bot.replay, { nickname: 'Racer' }))); + const ok = results.filter((r) => r.status === 200); + expect(ok.length).toBeGreaterThanOrEqual(1); + expect(new Set(ok.map((r) => r.body.score.id)).size).toBe(1); + for (const r of results.filter((r) => r.status !== 200)) expect([409]).toContain(r.status); + expect(await count(h.db, 'scores')).toBe(1); + expect(await count(h.db, 'runs', "status = 'accepted'")).toBe(1); + }); + + it('simultaneous DIFFERENT submissions (different nicknames) for one run: exactly one wins', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + h.clock.advance(200_000); + const results = await Promise.all(['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo'].map((n) => h.submit(run, bot.replay, { nickname: n }))); + expect(results.filter((r) => r.status === 200).length).toBe(1); + expect(await count(h.db, 'scores')).toBe(1); + }); + + it('holds across separate database connections (several Worker instances sharing one database)', async () => { + const { mkdtempSync, rmSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'lb-')); + const file = join(dir, 'shared.sqlite'); + const clock = makeClock(); + const instances = Array.from({ length: 4 }, () => makeHarness({ db: openSqliteDb(file), clock })); + try { + const run = await instances[0]!.start({ seed: REFERENCE_SEED }); + const bot = reference(); + clock.advance(200_000); + const results = await Promise.all( + Array.from({ length: 16 }, (_, i) => instances[i % 4]!.submit(run, bot.replay, { nickname: `Inst${i % 4}` })), + ); + expect(results.filter((r) => r.status === 200 && !r.body.replayed).length).toBe(1); + expect(await count(instances[0]!.db, 'scores')).toBe(1); + expect(await count(instances[3]!.db, 'runs', "status = 'accepted'")).toBe(1); + } finally { + for (const i of instances) i.db.close(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('the scores table itself refuses a second score for one run', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + await h.playAndSubmit(run, reference().replay); + await expect( + h.db.run(`INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms) VALUES ('dup', ?, 1, 'Dup Dup', 1, '1.0.0', 1, 1)`, [run.runId]), + ).rejects.toThrow(); + }); +}); + +describe('request size and encoding limits', () => { + it('rejects an oversized body (413) without consuming the run', async () => { + const h = makeHarness({ settings: { maxBodyBytes: 4096 } }); + const run = await h.start({ seed: REFERENCE_SEED }); + const res = await h.submit(run, reference().replay); + expect(res.status).toBe(413); + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('issued'); + }); + + it('refuses a declared Content-Length over the limit before reading', async () => { + const h = makeHarness({ settings: { maxBodyBytes: 1000 } }); + const run = await h.start(); + const res = await h.call('POST', `/api/v1/runs/${run.runId}/submit`, { token: run.token, headers: { 'content-length': '999999' }, body: '{}' }); + expect(res.status).toBe(413); + }); + + it('a gzip bomb stops at the decoded limit', async () => { + const h = makeHarness({ settings: { maxBodyBytes: 1024 * 1024 } }); + const run = await h.start(); + const bomb = gzipSync(Buffer.alloc(32 * 1024 * 1024, 0x20)); // 32 MiB of spaces (32x the limit), ~32 KB compressed + expect(bomb.length).toBeLessThan(h.settings.maxCompressedBytes); + const res = await h.call('POST', `/api/v1/runs/${run.runId}/submit`, { token: run.token, headers: { 'content-encoding': 'gzip' }, body: bomb as unknown as BodyInit }); + expect(res.status).toBe(413); + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('issued'); + }); + + it('rejects an over-limit compressed body', async () => { + const h = makeHarness({ settings: { maxCompressedBytes: 100 } }); + const run = await h.start(); + const res = await h.call('POST', `/api/v1/runs/${run.runId}/submit`, { + token: run.token, + headers: { 'content-encoding': 'gzip' }, + body: gzipSync(Buffer.from(crypto.getRandomValues(new Uint8Array(2000)))) as unknown as BodyInit, // incompressible + }); + expect(res.status).toBe(413); + }); + + it('accepts a legitimate gzip upload', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const res = await h.playAndSubmit(run, reference().replay, { gzip: true }); + expect(res.status).toBe(200); + expect(res.body.score.score).toBe(9114); + }); + + it('truncated gzip and corrupt gzip -> 400, run not consumed', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const full = gzipSync(Buffer.from(JSON.stringify({ replay: reference().replay }))); + for (const body of [full.subarray(0, Math.floor(full.length / 2)), Buffer.from('definitely not gzip')]) { + const res = await h.call('POST', `/api/v1/runs/${run.runId}/submit`, { token: run.token, headers: { 'content-encoding': 'gzip' }, body: body as unknown as BodyInit }); + expect(res.status).toBe(400); + } + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('issued'); + }); + + it('unsupported content-encodings -> 415', async () => { + const h = makeHarness(); + const run = await h.start(); + const res = await h.call('POST', `/api/v1/runs/${run.runId}/submit`, { token: run.token, headers: { 'content-encoding': 'br' }, body: '{}' }); + expect(res.status).toBe(415); + }); + + it('truncated JSON, non-JSON and wrong shapes -> 400 without consuming the run, and a correct retry succeeds', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + const json = JSON.stringify({ replay: bot.replay }); + h.clock.advance(200_000); + for (const rawBody of [json.slice(0, json.length - 40), 'not json', '[]', '{}', '{"replay": 5}', '{"replay": []}', '']) { + const res = await h.submit(run, null, { rawBody }); + expect([400]).toContain(res.status); + } + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('issued'); + expect((await h.submit(run, bot.replay)).status).toBe(200); + }); +}); + +describe('nicknames', () => { + it('invalid nicknames are refused before the run is consumed', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + h.clock.advance(200_000); + for (const nickname of ['ab', 'x'.repeat(17), '', 'a&b c', 'bad"quote', 123, {}, ' ']) { + const res = await h.submit(run, bot.replay, { nickname }); + // Whitespace-only collapses to the default name, everything else is refused. + expect(res.status === 400 || (nickname === ' ' && res.status === 200)).toBe(true); + if (res.status === 200) return; + } + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('issued'); + }); + + it('normalises whitespace and keeps unicode letters', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + const res = await h.playAndSubmit(run, reference().replay, { nickname: ' Élodie B_2 ' }); + expect(res.body.score.nickname).toBe('Élodie B_2'); + }); + + it('defaults to Anonymous', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + expect((await h.playAndSubmit(run, reference().replay)).body.score.nickname).toBe('Anonymous'); + }); + + it('untrusted control metadata is whitelisted, never trusted', async () => { + const h = makeHarness(); + const run = await h.start({ seed: REFERENCE_SEED }); + await h.playAndSubmit(run, reference().replay, { controls: { scheme: "'; DROP TABLE scores;--" } }); + expect((await h.db.first<{ reported_controls: string }>('SELECT reported_controls FROM scores'))!.reported_controls).toBe('unknown'); + }); +}); + +describe('failure handling', () => { + it('a database failure while recording the score returns 503, leaves no score, and the player can retry', async () => { + let fail = true; + const h = makeHarness({ dbWrap: (db) => faultyDb(db, (sql) => fail && /INSERT INTO scores/.test(sql)) }); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + const first = await h.playAndSubmit(run, bot.replay); + expect(first.status).toBe(503); + expect(await count(h.db, 'scores')).toBe(0); + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('issued'); + fail = false; + const retry = await h.submit(run, bot.replay); + expect(retry.status).toBe(200); + expect(await count(h.db, 'scores')).toBe(1); + }); + + it('if even releasing the claim fails, the claim lease lets a later request take over', async () => { + let failScores = true; + const h = makeHarness({ dbWrap: (db) => faultyDb(db, (sql) => (failScores && /INSERT INTO scores/.test(sql)) || (failScores && /SET status = 'issued'/.test(sql))) }); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + expect((await h.playAndSubmit(run, bot.replay)).status).toBe(503); + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('verifying'); + failScores = false; + const early = await h.submit(run, bot.replay); + expect(early.status).toBe(409); + expect(early.body.error.code).toBe('run_in_progress'); + h.clock.advance(h.settings.claimLeaseMs + 1); + expect((await h.submit(run, bot.replay)).status).toBe(200); + expect(await count(h.db, 'scores')).toBe(1); + }); + + it('a database outage when starting a run is reported, not hidden', async () => { + const h = makeHarness({ dbWrap: (db) => faultyDb(db, () => true) }); + const res = await h.call('POST', '/api/v1/runs'); + expect(res.status).toBe(500); + }); + + it('a verifier crash is a rejection, not a retry loop', async () => { + const h = makeHarness(); + h.deps.verify = () => { + throw new Error('boom'); + }; + const run = await h.start({ seed: REFERENCE_SEED }); + const res = await h.playAndSubmit(run, reference().replay); + expect(res.status).toBe(422); + expect((await h.db.first<{ status: string }>('SELECT status FROM runs'))!.status).toBe('rejected'); + }); +}); + +describe('rate limits', () => { + it('limits run starts per client and reports Retry-After', async () => { + const h = makeHarness({ settings: { rate: { ...makeHarness().settings.rate, startPerIp: 3 } } }); + for (let i = 0; i < 3; i++) expect((await h.call('POST', '/api/v1/runs', { ip: '192.0.2.1' })).status).toBe(201); + const blocked = await h.call('POST', '/api/v1/runs', { ip: '192.0.2.1' }); + expect(blocked.status).toBe(429); + expect(Number(blocked.headers.get('retry-after'))).toBeGreaterThan(0); + expect((await h.call('POST', '/api/v1/runs', { ip: '192.0.2.2' })).status).toBe(201); // a different client is unaffected + h.clock.advance(3_600_000); + expect((await h.call('POST', '/api/v1/runs', { ip: '192.0.2.1' })).status).toBe(201); // the window rolled over + }); + + it('a global ceiling bounds total starts regardless of client', async () => { + const h = makeHarness({ settings: { rate: { ...makeHarness().settings.rate, startGlobal: 2 } } }); + expect((await h.call('POST', '/api/v1/runs', { ip: '192.0.2.1' })).status).toBe(201); + expect((await h.call('POST', '/api/v1/runs', { ip: '192.0.2.2' })).status).toBe(201); + expect((await h.call('POST', '/api/v1/runs', { ip: '192.0.2.3' })).status).toBe(429); + }); + + it('limits submissions before any verification work happens', async () => { + const h = makeHarness({ settings: { rate: { ...makeHarness().settings.rate, submitPerIp: 2 } } }); + const run = await h.start({ seed: REFERENCE_SEED }); + const bot = reference(); + h.clock.advance(200_000); + await h.submit(run, bot.replay, { token: 'bad' }); + await h.submit(run, bot.replay, { token: 'bad' }); + const res = await h.submit(run, bot.replay); + expect(res.status).toBe(429); + expect(await count(h.db, 'scores')).toBe(0); + }); + + it('refuses browser origins that are not allow-listed, but serves origin-less callers', async () => { + const h = makeHarness({ settings: { allowedOrigins: ['https://game.example'] } }); + expect((await h.call('POST', '/api/v1/runs', { headers: { origin: 'https://evil.example' } })).status).toBe(403); + const ok = await h.call('POST', '/api/v1/runs', { headers: { origin: 'https://game.example' } }); + expect(ok.status).toBe(201); + expect(ok.headers.get('access-control-allow-origin')).toBe('https://game.example'); + expect((await h.call('POST', '/api/v1/runs', { ip: '1.1.1.1' })).status).toBe(201); + const pre = await h.call('OPTIONS', '/api/v1/runs', { headers: { origin: 'https://evil.example' } }); + expect(pre.status).toBe(403); + }); +}); diff --git a/phaser-asteroids/server/tests/week.test.ts b/phaser-asteroids/server/tests/week.test.ts new file mode 100644 index 0000000..44d994e --- /dev/null +++ b/phaser-asteroids/server/tests/week.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { weekWindow, zonedParts } from '../src/week'; + +const TZ = 'America/Halifax'; +const iso = (ms: number) => new Date(ms).toISOString(); +const hours = (w: { startMs: number; endMs: number }) => (w.endMs - w.startMs) / 3_600_000; + +describe('weekly window (Monday-Sunday, America/Halifax)', () => { + it('a mid-week instant maps to the Monday 00:00 ADT start (UTC-3 in October)', () => { + const w = weekWindow(Date.UTC(2026, 9, 22, 15, 0, 0), TZ); // Thursday + expect(iso(w.startMs)).toBe('2026-10-19T03:00:00.000Z'); + expect(iso(w.endMs)).toBe('2026-10-26T03:00:00.000Z'); + expect(hours(w)).toBe(168); + }); + + it('flips exactly at Halifax Monday midnight, not at UTC midnight', () => { + const lastMomentOfOldWeek = Date.UTC(2026, 9, 26, 2, 59, 59, 999); // Sunday 23:59:59.999 ADT + const firstMomentOfNewWeek = Date.UTC(2026, 9, 26, 3, 0, 0, 0); // Monday 00:00:00.000 ADT + expect(iso(weekWindow(lastMomentOfOldWeek, TZ).startMs)).toBe('2026-10-19T03:00:00.000Z'); + expect(iso(weekWindow(firstMomentOfNewWeek, TZ).startMs)).toBe('2026-10-26T03:00:00.000Z'); + // Sunday evening in Halifax is already Monday in UTC, which must NOT roll the week over. + expect(iso(weekWindow(Date.UTC(2026, 9, 26, 1, 0, 0), TZ).startMs)).toBe('2026-10-19T03:00:00.000Z'); + }); + + it('the week containing the autumn DST change (2026-11-01) is 169 hours long', () => { + const w = weekWindow(Date.UTC(2026, 10, 1, 12, 0, 0), TZ); // Sunday after clocks went back + expect(iso(w.startMs)).toBe('2026-10-26T03:00:00.000Z'); // Monday 00:00 ADT (UTC-3) + expect(iso(w.endMs)).toBe('2026-11-02T04:00:00.000Z'); // Monday 00:00 AST (UTC-4) + expect(hours(w)).toBe(169); + }); + + it('the week containing the spring DST change (2026-03-08) is 167 hours long', () => { + const w = weekWindow(Date.UTC(2026, 2, 9, 12, 0, 0), TZ); + // Monday 2026-03-09 is after the change: week starts that day at 00:00 ADT (UTC-3). + expect(iso(w.startMs)).toBe('2026-03-09T03:00:00.000Z'); + const prior = weekWindow(Date.UTC(2026, 2, 8, 12, 0, 0), TZ); + expect(iso(prior.startMs)).toBe('2026-03-02T04:00:00.000Z'); // Monday 00:00 AST (UTC-4) + expect(iso(prior.endMs)).toBe('2026-03-09T03:00:00.000Z'); + expect(hours(prior)).toBe(167); + }); + + it('crosses the New Year inside a single week (Mon 2026-12-28 to Mon 2027-01-04)', () => { + for (const day of [28, 29, 30, 31]) { + const w = weekWindow(Date.UTC(2026, 11, day, 18, 0, 0), TZ); + expect(iso(w.startMs)).toBe('2026-12-28T04:00:00.000Z'); + expect(iso(w.endMs)).toBe('2027-01-04T04:00:00.000Z'); + } + expect(iso(weekWindow(Date.UTC(2027, 0, 1, 18, 0, 0), TZ).startMs)).toBe('2026-12-28T04:00:00.000Z'); + expect(iso(weekWindow(Date.UTC(2027, 0, 4, 4, 0, 0), TZ).startMs)).toBe('2027-01-04T04:00:00.000Z'); + }); + + it('handles a Sunday and a Monday correctly in the same zone', () => { + expect(zonedParts(Date.UTC(2026, 9, 25, 12, 0, 0), TZ).isoWeekday).toBe(7); + expect(zonedParts(Date.UTC(2026, 9, 26, 12, 0, 0), TZ).isoWeekday).toBe(1); + }); + + it('every instant belongs to exactly one window and windows tile the timeline', () => { + let t = Date.UTC(2026, 0, 1); + const end = Date.UTC(2027, 1, 1); + let prev = weekWindow(t, TZ); + for (; t < end; t += 6 * 3_600_000 + 17_000) { + const w = weekWindow(t, TZ); + expect(t).toBeGreaterThanOrEqual(w.startMs); + expect(t).toBeLessThan(w.endMs); + if (w.startMs !== prev.startMs) expect(w.startMs).toBe(prev.endMs); + prev = w; + } + }); +}); diff --git a/phaser-asteroids/server/tsconfig.json b/phaser-asteroids/server/tsconfig.json new file mode 100644 index 0000000..8cb5e84 --- /dev/null +++ b/phaser-asteroids/server/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": ["node"], + "allowJs": true, + "checkJs": false + }, + "include": ["src", "tests", "testing", "bench", "../src/replay", "../src/core"] +} diff --git a/phaser-asteroids/server/wrangler.bench.toml b/phaser-asteroids/server/wrangler.bench.toml new file mode 100644 index 0000000..fe4e26e --- /dev/null +++ b/phaser-asteroids/server/wrangler.bench.toml @@ -0,0 +1,3 @@ +name = "asteroids-verify-bench" +main = "bench/worker.ts" +compatibility_date = "2026-06-01" diff --git a/phaser-asteroids/server/wrangler.toml b/phaser-asteroids/server/wrangler.toml new file mode 100644 index 0000000..1c53293 --- /dev/null +++ b/phaser-asteroids/server/wrangler.toml @@ -0,0 +1,48 @@ +# Cloudflare Worker + D1 for the Phaser Asteroids ranked leaderboard. See ../docs/leaderboard-backend.md. +# +# NOTHING here deploys anything. `wrangler dev --local` (npm run dev) uses a local workerd + a local SQLite-backed D1 under +# .wrangler/state and never contacts a Cloudflare account. Replay verification needs more than the 10 ms of CPU the Workers +# *Free* plan allows (measured 40-250 ms), so a real deployment needs the Workers *Paid* plan (US$5/month). + +name = "asteroids-leaderboard" +main = "src/worker.ts" +compatibility_date = "2026-06-01" + +# Safety net against a runaway loop becoming a bill: far above a measured worst-case verification, far below the 30 s default. +[limits] +cpu_ms = 5000 + +[triggers] +crons = ["17 7 * * *"] # daily cleanup (scheduled handler in src/worker.ts) + +[[d1_databases]] +binding = "DB" +database_name = "asteroids-leaderboard" +# Local development ignores this id. For deployment, replace it with the id printed by `wrangler d1 create asteroids-leaderboard`. +database_id = "00000000-0000-0000-0000-000000000000" +migrations_dir = "migrations" + +# Local / test defaults. Secrets (ADMIN_TOKEN, IP_HASH_SALT) are NOT set here: locally use .dev.vars (git-ignored), in production +# use `wrangler secret put`. +[vars] +ALLOWED_ORIGINS = "http://localhost:5173,http://127.0.0.1:5173,http://localhost:4173,http://127.0.0.1:4173,http://127.0.0.1:4410" + +# Production: wrangler does not inherit bindings or vars into environments, so everything is repeated. Fill in before deploying: +# npx wrangler deploy --env production +[env.production] +name = "asteroids-leaderboard" + +[env.production.limits] +cpu_ms = 5000 + +[env.production.triggers] +crons = ["17 7 * * *"] + +[[env.production.d1_databases]] +binding = "DB" +database_name = "asteroids-leaderboard" +database_id = "REPLACE_WITH_ID_FROM_wrangler_d1_create" +migrations_dir = "migrations" + +[env.production.vars] +ALLOWED_ORIGINS = "https://djblackett.github.io" diff --git a/phaser-asteroids/src/ranked/api.ts b/phaser-asteroids/src/ranked/api.ts new file mode 100644 index 0000000..0feb1f5 --- /dev/null +++ b/phaser-asteroids/src/ranked/api.ts @@ -0,0 +1,198 @@ +import type { GameConfig } from '../core/gameConfig'; +import { FIXED_TICK_RATE, GAMEPLAY_RULES_VERSION, REPLAY_SCHEMA_VERSION } from '../replay/constants'; +import type { ReplayRecord } from '../replay/types'; +import type { ControlScheme } from './controls'; + +/** + * Browser side of the ranked-run protocol (see docs/leaderboard-backend.md). The server issues the seed and the configuration; + * this module only carries them to the game and carries the finished recording back. Nothing here decides what counts as a score. + */ + +export interface RankedChallenge { + runId: string; + /** Secret that authorises submitting this run. Kept in memory only. */ + token: string; + seed: number; + rulesVersion: string; + schemaVersion: number; + tickRate: number; + config: GameConfig; + issuedAt: string; + expiresAt: string; +} + +export interface VerifiedScore { + id: string; + nickname: string; + score: number; + completedAt: string; + durationSeconds: number; +} + +export type SubmitOutcome = + | { kind: 'accepted'; score: VerifiedScore; ranks: { allTime: number | null; weekly: number | null }; replayed: boolean } + | { kind: 'rejected'; reason: string; message: string } + | { kind: 'failed'; message: string }; + +export class RankedApiError extends Error { + constructor( + readonly code: string, + message: string, + ) { + super(message); + this.name = 'RankedApiError'; + } +} + +type FetchLike = (input: string, init?: RequestInit) => Promise; + +const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]', '::1']); +/** `wrangler dev` default. */ +const LOCAL_API = 'http://127.0.0.1:8787'; + +/** + * Where the leaderboard API lives. Production builds bake it in as VITE_LEADERBOARD_API_URL. On a loopback host (local development, + * the browser tests) `?api=` may point at a local backend, and with nothing configured the local `wrangler dev` address is used. + * Anywhere else a query parameter is ignored: a crafted link cannot redirect a player's run to another server. Null: ranked play is + * not available in this build. + */ +export function resolveApiBase(search: string, hostname: string, configured?: string): string | null { + const clean = (u: string) => u.replace(/\/+$/, ''); + const valid = (u: string | null | undefined): string | null => { + if (!u) return null; + try { + const url = new URL(u); + return url.protocol === 'http:' || url.protocol === 'https:' ? clean(url.origin + url.pathname) : null; + } catch { + return null; + } + }; + if (LOOPBACK.has(hostname)) return valid(new URLSearchParams(search).get('api')) ?? valid(configured) ?? LOCAL_API; + return valid(configured); +} + +/** Ranked play is a developer / test launch path for now: it is requested with `?ranked`. */ +export function rankedRequested(search: string): boolean { + return new URLSearchParams(search).has('ranked'); +} + +/** Mirrors the server's ranked limit (20 simulated minutes at 60 Hz); a longer recording would be refused, so it is not sent. */ +export const RANKED_MAX_TICKS = 20 * 60 * FIXED_TICK_RATE; + +const isObject = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); + +async function json(res: Response): Promise { + try { + return await res.json(); + } catch { + return null; + } +} + +async function withTimeout(fetchFn: FetchLike, url: string, init: RequestInit, ms: number): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), ms); + try { + return await fetchFn(url, { ...init, signal: controller.signal }); + } finally { + clearTimeout(timer); + } +} + +/** Asks the server for a ranked challenge. Throws RankedApiError; the caller must then NOT start a ranked run. */ +export async function requestChallenge(base: string, fetchFn: FetchLike = (u, i) => fetch(u, i)): Promise { + let res: Response; + try { + res = await withTimeout(fetchFn, `${base}/api/v1/runs`, { method: 'POST' }, 10_000); + } catch { + throw new RankedApiError('network', 'The ranked service could not be reached'); + } + const body = await json(res); + if (res.status === 429) throw new RankedApiError('rate_limited', 'Too many ranked runs started; try again later'); + if (res.status !== 201 || !isObject(body)) throw new RankedApiError('unavailable', `The ranked service refused the request (${res.status})`); + + const c = body as unknown as RankedChallenge; + if (typeof c.runId !== 'string' || typeof c.token !== 'string' || !Number.isInteger(c.seed) || c.seed < 0 || c.seed > 0xffffffff) { + throw new RankedApiError('bad_challenge', 'The ranked service sent an invalid challenge'); + } + if (c.rulesVersion !== GAMEPLAY_RULES_VERSION || c.schemaVersion !== REPLAY_SCHEMA_VERSION || c.tickRate !== FIXED_TICK_RATE) { + throw new RankedApiError('update_required', 'This version of the game does not match the ranked service; reload to update'); + } + if (!isObject(c.config) || c.config.playerCount !== 1) throw new RankedApiError('bad_challenge', 'The ranked service sent an unsupported configuration'); + return c; +} + +async function gzip(text: string): Promise { + if (typeof CompressionStream === 'undefined') return null; + try { + const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('gzip')); + return new Uint8Array(await new Response(stream).arrayBuffer()); + } catch { + return null; + } +} + +export interface SubmitOptions { + base: string; + challenge: RankedChallenge; + replay: ReplayRecord; + nickname?: string; + controls: ControlScheme; + fetchFn?: FetchLike; + sleep?: (ms: number) => Promise; + /** Waits between attempts after a network error or a retryable server answer. The server treats a repeated identical body as idempotent. */ + retryDelaysMs?: readonly number[]; +} + +/** + * Sends the finished recording. The server's answer is the only thing that makes a run count; whatever the game itself computed is + * not sent as a score (the replay carries its own claim only so the server can cross-check it). Network errors, 5xx, 429 and + * "still verifying" are retried with the identical body, which the server answers idempotently; definitive refusals are not. + */ +export async function submitRankedRun(opts: SubmitOptions): Promise { + const { base, challenge } = opts; + const fetchFn = opts.fetchFn ?? ((u, i) => fetch(u, i)); + const sleep = opts.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + const delays = opts.retryDelaysMs ?? [1000, 3000, 8000]; + + const text = JSON.stringify({ + replay: opts.replay, + ...(opts.nickname ? { nickname: opts.nickname } : {}), + controls: { scheme: opts.controls }, + }); + const compressed = await gzip(text); + const headers: Record = { Authorization: `Bearer ${challenge.token}`, 'Content-Type': 'application/json' }; + if (compressed) headers['Content-Encoding'] = 'gzip'; + const body = (compressed ?? text) as BodyInit; + const url = `${base}/api/v1/runs/${encodeURIComponent(challenge.runId)}/submit`; + + let lastProblem = 'The ranked service could not be reached'; + for (let attempt = 0; attempt <= delays.length; attempt++) { + if (attempt > 0) await sleep(delays[attempt - 1]!); + let res: Response; + try { + res = await withTimeout(fetchFn, url, { method: 'POST', headers, body }, 30_000); + } catch { + lastProblem = 'The ranked service could not be reached'; + continue; + } + const data = await json(res); + const error = isObject(data) && isObject(data.error) ? data.error : null; + const code = typeof error?.code === 'string' ? error.code : ''; + + if (res.status === 200 && isObject(data) && data.status === 'accepted') { + return { kind: 'accepted', score: data.score as VerifiedScore, ranks: data.ranks as { allTime: number | null; weekly: number | null }, replayed: data.replayed === true }; + } + if (res.status === 422 || code === 'run_rejected') { + const reason = typeof error?.reason === 'string' ? error.reason : 'rejected'; + return { kind: 'rejected', reason, message: 'The server could not verify this score' }; + } + if (res.status === 410) return { kind: 'failed', message: 'This ranked run expired before it was submitted' }; + if (res.status === 429 || res.status >= 500 || code === 'run_in_progress' || code === 'run_busy') { + lastProblem = res.status === 429 ? 'Too many submissions; try again later' : 'The ranked service is busy'; + continue; + } + return { kind: 'failed', message: `The score was not accepted (${code || res.status})` }; + } + return { kind: 'failed', message: lastProblem }; +} diff --git a/phaser-asteroids/src/ranked/controls.ts b/phaser-asteroids/src/ranked/controls.ts new file mode 100644 index 0000000..345a222 --- /dev/null +++ b/phaser-asteroids/src/ranked/controls.ts @@ -0,0 +1,36 @@ +import type { PlayerInput } from '../core/player'; +import type { MovementMode } from '../input/movementMode'; + +/** + * The control scheme reported alongside a ranked run, for later fairness analysis (keyboard vs touch vs pad). It is INFORMATIONAL and + * UNTRUSTED: a modified client can send any value, and the server never uses it to accept, reject or rank a score. + */ +export type ControlScheme = 'keyboard' | 'gamepad' | 'touch-classic' | 'touch-point' | 'touch-assisted' | 'mixed' | 'unknown'; + +const TOUCH_SCHEME: Record = { + classic: 'touch-classic', + pointToFly: 'touch-point', + assisted: 'touch-assisted', +}; + +/** Whether an input is doing anything (a pad or finger that is merely connected does not count as "used"). */ +export function isActiveInput(input: PlayerInput): boolean { + return input.rotate !== 0 || input.move !== 0 || input.shoot || !!input.laser || !!input.boost || !!input.steer; +} + +/** Remembers which sources actually produced input during a run. One source -> that scheme; more than one -> `mixed`. */ +export class ControlTracker { + private readonly used = new Set(); + + observe(sources: { keyboard: PlayerInput; gamepad: PlayerInput; touch: PlayerInput | null }, touchMovement: MovementMode): void { + if (isActiveInput(sources.keyboard)) this.used.add('keyboard'); + if (isActiveInput(sources.gamepad)) this.used.add('gamepad'); + if (sources.touch && isActiveInput(sources.touch)) this.used.add(TOUCH_SCHEME[touchMovement]); + } + + scheme(): ControlScheme { + if (this.used.size === 0) return 'unknown'; + if (this.used.size === 1) return [...this.used][0]!; + return 'mixed'; + } +} diff --git a/phaser-asteroids/src/ranked/env.d.ts b/phaser-asteroids/src/ranked/env.d.ts new file mode 100644 index 0000000..c9d2ce5 --- /dev/null +++ b/phaser-asteroids/src/ranked/env.d.ts @@ -0,0 +1,8 @@ +// The project deliberately has no vite/client types; this declares the one build-time variable the ranked client reads. +interface ImportMetaEnv { + /** Base URL of the leaderboard API baked into a production build, e.g. https://asteroids-leaderboard.example.workers.dev */ + readonly VITE_LEADERBOARD_API_URL?: string; +} +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/phaser-asteroids/src/ranked/localScores.ts b/phaser-asteroids/src/ranked/localScores.ts new file mode 100644 index 0000000..0a262a3 --- /dev/null +++ b/phaser-asteroids/src/ranked/localScores.ts @@ -0,0 +1,73 @@ +/** + * A device-local record of this browser's accepted ranked scores, so a future UI can show "your best" without accounts. It is + * a convenience only: it proves nothing about who played, and clearing site data forgets it. The authoritative entries live on the + * server; these are just their public ids plus the score the server reported. + */ +export interface StorageLike { + getItem(key: string): string | null; + setItem(key: string, value: string): void; +} + +export interface LocalScore { + id: string; + score: number; + at: string; +} + +export const LOCAL_SCORES_KEY = 'asteroids.rankedScores'; +const KEEP = 20; + +export function readLocalScores(storage: StorageLike | undefined = safeStorage()): LocalScore[] { + try { + const parsed: unknown = JSON.parse(storage?.getItem(LOCAL_SCORES_KEY) ?? '[]'); + if (!Array.isArray(parsed)) return []; + return parsed.filter( + (s): s is LocalScore => !!s && typeof s.id === 'string' && Number.isFinite(s.score) && typeof s.at === 'string', + ); + } catch { + return []; + } +} + +export function rememberScore(score: LocalScore, storage: StorageLike | undefined = safeStorage()): void { + try { + const all = readLocalScores(storage).filter((s) => s.id !== score.id); + all.push(score); + all.sort((a, b) => b.score - a.score); + storage?.setItem(LOCAL_SCORES_KEY, JSON.stringify(all.slice(0, KEEP))); + } catch { + /* private mode or blocked storage: the score is still on the server */ + } +} + +export function localBest(storage?: StorageLike): LocalScore | null { + return readLocalScores(storage)[0] ?? null; +} + +function safeStorage(): StorageLike | undefined { + try { + return typeof localStorage === 'undefined' ? undefined : localStorage; + } catch { + return undefined; + } +} + +export const NICKNAME_KEY = 'asteroids.rankedNickname'; + +/** The nickname to send: `?nick=` wins, then whatever was used last. The server validates and normalises it. */ +export function chosenNickname(search: string, storage: StorageLike | undefined = safeStorage()): string | undefined { + const fromUrl = new URLSearchParams(search).get('nick'); + if (fromUrl) { + try { + storage?.setItem(NICKNAME_KEY, fromUrl); + } catch { + /* ignore */ + } + return fromUrl; + } + try { + return storage?.getItem(NICKNAME_KEY) ?? undefined; + } catch { + return undefined; + } +} diff --git a/phaser-asteroids/src/ranked/session.ts b/phaser-asteroids/src/ranked/session.ts new file mode 100644 index 0000000..d78750d --- /dev/null +++ b/phaser-asteroids/src/ranked/session.ts @@ -0,0 +1,106 @@ +import type { RankedChallenge, SubmitOutcome } from './api'; + +export type RankedPhase = 'idle' | 'requesting' | 'ready' | 'playing' | 'submitting' | 'accepted' | 'rejected' | 'failed' | 'abandoned'; + +export interface RankedSnapshot { + phase: RankedPhase; + runId: string | null; + seed: number | null; + /** Server-reported result once accepted; the only score that counts. */ + verifiedScore: number | null; + outcome: SubmitOutcome | null; + message: string; +} + +/** + * Where a ranked run is, for the game-over line and for browser tests. One game per page, so a module singleton is enough. + * Lifecycle: idle -> requesting -> ready (challenge in hand) -> playing -> submitting -> accepted | rejected | failed, + * or abandoned when the player leaves before game over. A casual game never touches it. + */ +class RankedSession { + phase: RankedPhase = 'idle'; + private challenge: RankedChallenge | null = null; + /** The run whose result this session is waiting for; a late answer for any other run is ignored. */ + private currentRunId: string | null = null; + private outcome: SubmitOutcome | null = null; + private message = ''; + + /** The player asked for a ranked run: forget the previous one (a slow answer for it must not overwrite what follows). */ + beginRequest(): void { + this.challenge = null; + this.currentRunId = null; + this.outcome = null; + this.set('requesting'); + } + + /** A challenge was issued: the next GameScene is a ranked run. */ + setChallenge(challenge: RankedChallenge): void { + this.challenge = challenge; + this.outcome = null; + this.message = ''; + this.set('ready'); + } + + /** Consumed by exactly one GameScene: a retry or restart can never reuse (or silently continue) a ranked challenge. */ + takeChallenge(): RankedChallenge | null { + const c = this.challenge; + this.challenge = null; + if (c) { + this.currentRunId = c.runId; + this.set('playing'); + } + return c; + } + + set(phase: RankedPhase, message = ''): void { + this.phase = phase; + this.message = message; + this.publish(); + } + + finish(runId: string, outcome: SubmitOutcome): void { + if (runId !== this.currentRunId) return; + this.outcome = outcome; + if (outcome.kind === 'accepted') this.set('accepted'); + else if (outcome.kind === 'rejected') this.set('rejected', outcome.message); + else this.set('failed', outcome.message); + } + + /** The line shown on the game-over screen. Empty for casual play. */ + statusLine(): string { + switch (this.phase) { + case 'submitting': + return 'RANKED: VERIFYING SCORE...'; + case 'accepted': { + if (this.outcome?.kind !== 'accepted') return ''; + const { score, ranks } = this.outcome; + const place = ranks.weekly ? `#${ranks.weekly} THIS WEEK` : ranks.allTime ? `#${ranks.allTime} ALL-TIME` : 'RECORDED'; + return `VERIFIED ${score.score} ${place}`; + } + case 'rejected': + return `RANKED SCORE NOT RECORDED: ${this.message}`.toUpperCase(); + case 'failed': + return `RANKED SCORE NOT SUBMITTED: ${this.message}`.toUpperCase(); + default: + return ''; + } + } + + snapshot(): RankedSnapshot { + return { + phase: this.phase, + runId: this.currentRunId ?? this.challenge?.runId ?? null, + seed: this.challenge?.seed ?? null, + verifiedScore: this.outcome?.kind === 'accepted' ? this.outcome.score.score : null, + outcome: this.outcome, + message: this.message, + }; + } + + private publish(): void { + if (typeof window === 'undefined') return; + (window as unknown as { __ASTEROIDS_RANKED__?: unknown }).__ASTEROIDS_RANKED__ = { ...this.snapshot(), phase: this.phase }; + } +} + +export const rankedSession = new RankedSession(); diff --git a/phaser-asteroids/src/scenes/GameScene.ts b/phaser-asteroids/src/scenes/GameScene.ts index 84670ca..a9fd0f9 100644 --- a/phaser-asteroids/src/scenes/GameScene.ts +++ b/phaser-asteroids/src/scenes/GameScene.ts @@ -2,6 +2,7 @@ import Phaser from 'phaser'; import { getAudio, type AudioDirector } from '../audio/phaserAudio'; import { SCREEN_HEIGHT, SCREEN_WIDTH } from '../core/constants'; import { GameSim, type SimEvent } from '../core/game'; +import { resolveGameConfig } from '../core/gameConfig'; import { NO_INPUT, type PlayerInput } from '../core/player'; import { seededRng } from '../core/rng'; import { getSetup, simConfigOf } from '../gameSetup'; @@ -20,8 +21,12 @@ import { type MountedDiagnostics, } from '../input/keyDiagnostics'; import { createKeyPressRouter } from '../input/keyPress'; -import { keySchemesFor, type KeyScheme } from '../input/keyboardControls'; +import { keySchemesFor, readPlayerInput, type KeyScheme } from '../input/keyboardControls'; import { readPlayerInputs } from '../input/playerInputs'; +import { RANKED_MAX_TICKS, resolveApiBase, submitRankedRun, type RankedChallenge } from '../ranked/api'; +import { ControlTracker } from '../ranked/controls'; +import { chosenNickname, rememberScore } from '../ranked/localScores'; +import { rankedSession } from '../ranked/session'; import { drawStarfield, drawWorld } from '../render/worldRenderer'; import { FIXED_DT, @@ -133,6 +138,10 @@ export class GameScene extends Phaser.Scene { private verifiedSeed = 0; private fixedRunner: FixedStepRunner | null = null; private replayRecorder: ReplayRecorder | null = null; + // Ranked run (null in casual and in the experimental ?verified mode): issued by the server, submitted once at game over. + private rankedChallenge: RankedChallenge | null = null; + private rankedSubmitted = false; + private controlTracker = new ControlTracker(); constructor() { super(SCENE_GAME); @@ -142,9 +151,18 @@ export class GameScene extends Phaser.Scene { // State lives in init(), not the constructor, so every restart begins clean. The title screen's choices come from the // registry; the simulation (and with it every co-op detail) is always built from scratch. const setup = getSetup(this.registry); - const config = simConfigOf(setup); - - const verifiedInfo = typeof window !== 'undefined' ? parseVerifiedMode(window.location.search) : { verified: false, seed: 0 }; + // A ranked run takes its seed AND configuration from the server's challenge; nothing from the menu or the URL applies. + const challenge = rankedSession.takeChallenge(); + this.rankedChallenge = challenge; + this.rankedSubmitted = false; + this.controlTracker = new ControlTracker(); + const config = challenge ? resolveGameConfig(challenge.config) : simConfigOf(setup); + + const verifiedInfo = challenge + ? { verified: true, seed: challenge.seed } + : typeof window !== 'undefined' + ? parseVerifiedMode(window.location.search) + : { verified: false, seed: 0 }; this.isVerifiedMode = verifiedInfo.verified; this.verifiedSeed = verifiedInfo.seed; @@ -254,6 +272,7 @@ export class GameScene extends Phaser.Scene { if (!this.paused) { runner.update(dt, (tick, fixedDt) => { const rawInputs = sim.isGameOver ? this.schemes.map(() => NO_INPUT) : this.readInputs(); + if (this.rankedChallenge && !sim.isGameOver) this.observeControls(); const p1Input = toPlayerInput(toRecordedInput(rawInputs[0] ?? NO_INPUT)); if (!recorder.isFinalized) { recorder.recordTick(tick, p1Input); @@ -262,6 +281,7 @@ export class GameScene extends Phaser.Scene { if (sim.isGameOver && !recorder.isFinalized) { recorder.markGameOver(sim); } + if (sim.isGameOver) this.beginRankedSubmit(); this.audio.sfx.handle(events); if (this.touchUi) this.haptics.handle(events); this.announce(events, time); @@ -322,6 +342,56 @@ export class GameScene extends Phaser.Scene { if (playing) this.touch.setAbilities(abilityLabels(this.sim.player)); } + /** Ranked only: notes which input sources really drove the ship, for the (untrusted) control-scheme report. */ + private observeControls(): void { + const scheme = this.schemes[0]; + if (!scheme) return; + this.controlTracker.observe( + { + keyboard: readPlayerInput(this.held, scheme), + gamepad: this.pads.command(0, 1), + touch: this.touchUi ? this.touch.command() : null, + }, + getMovement(this).mode, + ); + } + + /** + * Ranked only, once, at game over: sends the recording to the server, which replays it and decides the score. The game never + * posts a score of its own. Failure leaves the (unranked-looking) game over screen alone and just says the score was not recorded. + */ + private beginRankedSubmit(): void { + const challenge = this.rankedChallenge; + const recorder = this.replayRecorder; + if (!challenge || !recorder || this.rankedSubmitted) return; + this.rankedSubmitted = true; + const search = typeof window !== 'undefined' ? window.location.search : ''; + const base = typeof window !== 'undefined' ? resolveApiBase(search, window.location.hostname, import.meta.env.VITE_LEADERBOARD_API_URL) : null; + const replay = recorder.exportReplay(); + rankedSession.set('submitting'); + if (!base) { + rankedSession.finish(challenge.runId, { kind: 'failed', message: 'Ranked play is not available in this build' }); + return; + } + if (replay.totalTicks > RANKED_MAX_TICKS) { + rankedSession.finish(challenge.runId, { kind: 'failed', message: 'This run was longer than the 20 minute ranked limit' }); + return; + } + void submitRankedRun({ base, challenge, replay, nickname: chosenNickname(search), controls: this.controlTracker.scheme() }) + .then((outcome) => { + if (outcome.kind === 'accepted') rememberScore({ id: outcome.score.id, score: outcome.score.score, at: outcome.score.completedAt }); + rankedSession.finish(challenge.runId, outcome); + }) + .catch(() => rankedSession.finish(challenge.runId, { kind: 'failed', message: 'Unexpected error while submitting' })); + } + + /** Leaving a ranked run before game over: its challenge is simply never submitted. */ + private abandonRanked(): void { + if (this.sim.isGameOver) return; + if (this.rankedChallenge) rankedSession.set('abandoned'); + this.replayRecorder?.abandon(); + } + /** One input per player: that player's own keys, merged with the controller assigned to them (if any). */ private readInputs(): PlayerInput[] { return this.readInputsUnguarded().map((input, i) => { @@ -533,13 +603,18 @@ export class GameScene extends Phaser.Scene { } private toMenu(): void { - if (!this.sim.isGameOver) this.replayRecorder?.abandon(); + this.abandonRanked(); if (this.paused || this.sim.isGameOver) this.scene.start(SCENE_START); } private retry(): void { - if (!this.sim.isGameOver) this.replayRecorder?.abandon(); - if (this.sim.isGameOver && this.sim.retryDelay <= 0) this.scene.restart(); + this.abandonRanked(); + if (this.sim.isGameOver && this.sim.retryDelay <= 0) { + // A ranked challenge is single-use: another ranked run must be requested from the title screen, never silently reused or + // downgraded to a casual restart. + if (this.rankedChallenge) this.scene.start(SCENE_START); + else this.scene.restart(); + } } // --- browser lifecycle ----------------------------------------------------- @@ -590,6 +665,7 @@ export class GameScene extends Phaser.Scene { this.audio.music.setGamePaused(false); this.audio.music.setMegaPowerActive(false); + this.abandonRanked(); if (this.isVerifiedMode && typeof window !== 'undefined') { delete (window as unknown as { __ASTEROIDS_REPLAY__?: unknown }).__ASTEROIDS_REPLAY__; } @@ -629,7 +705,14 @@ export class GameScene extends Phaser.Scene { const coop = sim.players.length > 1; this.gameOverOverlay.setLine(0, `Player 1: ${sim.player.score}`, CENTER_Y - 190, COLORS.player1, 30); // Two players: both scores, the team total and why the run ended. (Lines 3-5 stay empty in a one-player game.) - this.gameOverOverlay.setLine(3, coop ? `Player 2: ${sim.player2?.score ?? 0}` : '', CENTER_Y - 150, COLORS.player2, 30); + const rankedLine = this.rankedChallenge ? rankedSession.statusLine() : ''; + this.gameOverOverlay.setLine( + 3, + coop ? `Player 2: ${sim.player2?.score ?? 0}` : rankedLine, + CENTER_Y - 150, + coop ? COLORS.player2 : COLORS.heading, + coop ? 30 : 22, + ); this.gameOverOverlay.setLine(4, coop ? `TEAM TOTAL: ${sim.totalScore}` : '', CENTER_Y - 105, COLORS.white, 26); const reason = sim.gameOverReason === 'shared_lives_exhausted' ? 'THE SHARED LIVES ARE ALL USED UP' : 'BOTH PLAYERS ARE ELIMINATED'; this.gameOverOverlay.setLine(5, coop ? reason : '', CENTER_Y - 65, COLORS.dim, 22); diff --git a/phaser-asteroids/src/scenes/StartScene.ts b/phaser-asteroids/src/scenes/StartScene.ts index 4180da1..f8b671a 100644 --- a/phaser-asteroids/src/scenes/StartScene.ts +++ b/phaser-asteroids/src/scenes/StartScene.ts @@ -1,5 +1,6 @@ import Phaser from 'phaser'; import { getAudio, type AudioDirector } from '../audio/phaserAudio'; +import { SCREEN_HEIGHT, SCREEN_WIDTH } from '../core/constants'; import { defaultRng } from '../core/rng'; import { Starfield } from '../core/starfield'; import { getSetup, setSetup, type GameSetup } from '../gameSetup'; @@ -10,6 +11,8 @@ import { getInputMode, getMovement, getTouchControls } from '../input/gameTouch' import type { GamepadHub } from '../input/gamepadHub'; import type { InputModeController } from '../input/inputMode'; import { createKeyPressRouter } from '../input/keyPress'; +import { RankedApiError, rankedRequested, requestChallenge, resolveApiBase } from '../ranked/api'; +import { rankedSession } from '../ranked/session'; import { drawStarfield } from '../render/worldRenderer'; import type { MenuContext, PageNav } from '../ui/menu/context'; import type { MenuSnapshot } from '../ui/menu/menuController'; @@ -20,6 +23,7 @@ import { buildCoopPage } from '../ui/menu/pages/coop'; import { buildPadLayoutPage } from '../ui/menu/pages/padLayout'; import { buildPowerupGuide } from '../ui/menu/pages/powerups'; import { buildTitlePage } from '../ui/menu/pages/title'; +import { addText, COLORS } from '../ui/text'; import { SCENE_GAME, SCENE_START } from './keys'; /** A second mode switch inside this window is the same touch landing twice (two fingers, a bouncing thumb), not a decision. */ @@ -40,6 +44,8 @@ export class StartScene extends Phaser.Scene { private menu!: MenuView; private starting = false; private switchLockedUntil = 0; + /** One line at the bottom of the title screen, used only when a ranked run was asked for with `?ranked`. */ + private rankedNote: Phaser.GameObjects.Text | null = null; constructor() { super(SCENE_START); @@ -53,6 +59,7 @@ export class StartScene extends Phaser.Scene { create(): void { this.starting = false; this.switchLockedUntil = 0; + this.rankedNote = null; this.setup = getSetup(this.registry); this.audio = getAudio(this); this.audio.startMusicWhenUnlocked(); @@ -78,6 +85,8 @@ export class StartScene extends Phaser.Scene { }; this.menu = new MenuView(this, 10, builders, 'title'); + if (this.rankedWanted()) this.showRankedNote('RANKED MODE: PLAY ASKS THE SERVER FOR A VERIFIED RUN', COLORS.heading); + // Presses meant for the scene we came from (the BACK that opened this menu, a RETRY that was refused) are not ours. this.pads.discardPresses(); this.menu.show(this.inputMode.isTouch ? 'touch' : 'keys'); @@ -211,6 +220,39 @@ export class StartScene extends Phaser.Scene { private start(): void { if (this.starting) return; this.starting = true; - this.scene.start(SCENE_GAME); + if (this.rankedWanted()) void this.startRanked(); + else this.scene.start(SCENE_GAME); + } + + private rankedWanted(): boolean { + return typeof window !== 'undefined' && rankedRequested(window.location.search); + } + + /** + * Ranked play starts only after the server has issued a challenge (seed + configuration). If it cannot be issued the player is told so + * and stays here: a ranked run is never started without one, and a casual game is never started in its place without the player asking. + */ + private async startRanked(): Promise { + rankedSession.beginRequest(); + this.showRankedNote('REQUESTING A RANKED RUN...', COLORS.hint); + try { + const base = resolveApiBase(window.location.search, window.location.hostname, import.meta.env.VITE_LEADERBOARD_API_URL); + if (!base) throw new RankedApiError('unconfigured', 'Ranked play is not available in this build'); + const challenge = await requestChallenge(base); + if (!this.scene.isActive(SCENE_START)) return; + rankedSession.setChallenge(challenge); + this.scene.start(SCENE_GAME); + } catch (e) { + const message = e instanceof RankedApiError ? e.message : 'Unexpected error'; + rankedSession.set('failed', message); + if (!this.scene.isActive(SCENE_START)) return; + this.showRankedNote(`RANKED UNAVAILABLE: ${message.toUpperCase()}. PLAY TO TRY AGAIN.`, '#ff9696'); + this.starting = false; + } + } + + private showRankedNote(text: string, color: string): void { + this.rankedNote ??= addText(this, SCREEN_WIDTH / 2, SCREEN_HEIGHT - 28, '', { size: 18, originX: 0.5, originY: 0.5 }).setDepth(30); + this.rankedNote.setText(text).setColor(color); } } diff --git a/phaser-asteroids/tests/ranked.test.ts b/phaser-asteroids/tests/ranked.test.ts new file mode 100644 index 0000000..7bc1621 --- /dev/null +++ b/phaser-asteroids/tests/ranked.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, it } from 'vitest'; +import { NO_INPUT } from '../src/core/player'; +import { + rankedRequested, + RankedApiError, + requestChallenge, + resolveApiBase, + submitRankedRun, + type RankedChallenge, +} from '../src/ranked/api'; +import { ControlTracker } from '../src/ranked/controls'; +import { chosenNickname, localBest, readLocalScores, rememberScore, type StorageLike } from '../src/ranked/localScores'; +import { rankedSession } from '../src/ranked/session'; +import type { ReplayRecord } from '../src/replay'; + +const challenge: RankedChallenge = { + runId: '11111111-1111-4111-8111-111111111111', + token: 't'.repeat(43), + seed: 123456, + rulesVersion: '1.0.0', + schemaVersion: 1, + tickRate: 60, + config: { playerCount: 1, livesMode: 'independent', friendlyFire: false, speed: [1, 1] }, + issuedAt: '2026-10-22T15:00:00.000Z', + expiresAt: '2026-10-22T16:00:00.000Z', +}; +const replay = { header: {}, inputs: [], totalTicks: 1 } as unknown as ReplayRecord; +const reply = (status: number, body: unknown) => new Response(JSON.stringify(body), { status }); +const accepted = { status: 'accepted', replayed: false, score: { id: 's1', nickname: 'Ace', score: 1250, completedAt: '2026-10-22T15:01:00.000Z', durationSeconds: 25 }, ranks: { allTime: 3, weekly: 1 } }; + +function memory(): StorageLike & { data: Map } { + const data = new Map(); + return { data, getItem: (k) => data.get(k) ?? null, setItem: (k, v) => void data.set(k, v) }; +} + +describe('resolveApiBase', () => { + it('uses the build-time URL on a real host and ignores ?api= there', () => { + expect(resolveApiBase('?api=https://evil.example', 'djblackett.github.io', 'https://lb.example.dev/')).toBe('https://lb.example.dev'); + expect(resolveApiBase('', 'djblackett.github.io', undefined)).toBeNull(); + }); + it('lets a loopback page point at a local backend, defaulting to wrangler dev', () => { + expect(resolveApiBase('?api=http://127.0.0.1:8792/', '127.0.0.1')).toBe('http://127.0.0.1:8792'); + expect(resolveApiBase('', 'localhost')).toBe('http://127.0.0.1:8787'); + }); + it('rejects non-http(s) and malformed URLs', () => { + expect(resolveApiBase('?api=javascript:alert(1)', '127.0.0.1', undefined)).toBe('http://127.0.0.1:8787'); + expect(resolveApiBase('', 'example.com', 'not a url')).toBeNull(); + }); + it('ranked play is only requested explicitly', () => { + expect(rankedRequested('')).toBe(false); + expect(rankedRequested('?debug=1')).toBe(false); + expect(rankedRequested('?ranked=1')).toBe(true); + }); +}); + +describe('requestChallenge', () => { + it('returns the server-issued challenge', async () => { + const c = await requestChallenge('http://x', async () => reply(201, challenge)); + expect(c.seed).toBe(123456); + }); + it('fails (never invents a challenge) when offline, rate limited, or refused', async () => { + await expect(requestChallenge('http://x', async () => Promise.reject(new TypeError('offline')))).rejects.toMatchObject({ code: 'network' }); + await expect(requestChallenge('http://x', async () => reply(429, {}))).rejects.toMatchObject({ code: 'rate_limited' }); + await expect(requestChallenge('http://x', async () => reply(503, {}))).rejects.toMatchObject({ code: 'unavailable' }); + }); + it('refuses a challenge for different rules or an unsupported config', async () => { + await expect(requestChallenge('http://x', async () => reply(201, { ...challenge, rulesVersion: '2.0.0' }))).rejects.toMatchObject({ code: 'update_required' }); + await expect(requestChallenge('http://x', async () => reply(201, { ...challenge, config: { ...challenge.config, playerCount: 2 } }))).rejects.toBeInstanceOf(RankedApiError); + await expect(requestChallenge('http://x', async () => reply(201, { ...challenge, seed: -1 }))).rejects.toMatchObject({ code: 'bad_challenge' }); + }); +}); + +describe('submitRankedRun', () => { + const opts = { base: 'http://x', challenge, replay, controls: 'keyboard' as const, sleep: async () => undefined, retryDelaysMs: [1, 1, 1] }; + + it('sends the token as a bearer credential, gzip-compressed, with the replay and reported controls (no score)', async () => { + let seen: { url: string; init: RequestInit } | undefined; + const out = await submitRankedRun({ ...opts, nickname: 'Ace', fetchFn: async (url, init) => ((seen = { url, init: init! }), reply(200, accepted)) }); + expect(out.kind).toBe('accepted'); + expect(seen!.url).toBe(`http://x/api/v1/runs/${challenge.runId}/submit`); + const headers = seen!.init.headers as Record; + expect(headers.Authorization).toBe(`Bearer ${challenge.token}`); + expect(headers['Content-Encoding']).toBe('gzip'); + const bytes = seen!.init.body as Uint8Array; + const text = await new Response(new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('gzip'))).text(); + const body = JSON.parse(text); + expect(Object.keys(body).sort()).toEqual(['controls', 'nickname', 'replay']); + expect(body.controls).toEqual({ scheme: 'keyboard' }); + }); + + it('retries network errors and "still verifying" with the same body, then succeeds', async () => { + const bodies: unknown[] = []; + let n = 0; + const out = await submitRankedRun({ + ...opts, + fetchFn: async (_u, init) => { + bodies.push(init!.body); + n++; + if (n === 1) throw new TypeError('network down'); + if (n === 2) return reply(409, { error: { code: 'run_in_progress' } }); + if (n === 3) return reply(503, {}); + return reply(200, { ...accepted, replayed: true }); + }, + }); + expect(out).toMatchObject({ kind: 'accepted', replayed: true }); + expect(n).toBe(4); + expect(new Set(bodies.map((b) => (b as Uint8Array).length)).size).toBe(1); + }); + + it('does not retry a definitive rejection', async () => { + let n = 0; + const out = await submitRankedRun({ ...opts, fetchFn: async () => (n++, reply(422, { error: { code: 'replay_rejected', reason: 'score_mismatch' } })) }); + expect(out).toMatchObject({ kind: 'rejected', reason: 'score_mismatch' }); + expect(n).toBe(1); + }); + + it('reports expiry and gives up after the retry budget when the service stays down', async () => { + expect(await submitRankedRun({ ...opts, fetchFn: async () => reply(410, { error: { code: 'run_expired' } }) })).toMatchObject({ kind: 'failed' }); + let n = 0; + const out = await submitRankedRun({ ...opts, fetchFn: async () => (n++, Promise.reject(new TypeError('offline'))) }); + expect(out.kind).toBe('failed'); + expect(n).toBe(4); + }); +}); + +describe('ControlTracker', () => { + const idle = { ...NO_INPUT }; + const press = { ...NO_INPUT, shoot: true }; + it('reports the single source that actually drove the ship', () => { + const t = new ControlTracker(); + t.observe({ keyboard: press, gamepad: idle, touch: null }, 'assisted'); + expect(t.scheme()).toBe('keyboard'); + }); + it('maps touch to the movement mode and ignores idle sources', () => { + for (const [mode, scheme] of [['classic', 'touch-classic'], ['pointToFly', 'touch-point'], ['assisted', 'touch-assisted']] as const) { + const t = new ControlTracker(); + t.observe({ keyboard: idle, gamepad: idle, touch: { ...NO_INPUT, steer: { heading: 90, mode: 'assist' } } }, mode); + expect(t.scheme()).toBe(scheme); + } + }); + it('is mixed when several sources were used, unknown when none', () => { + const t = new ControlTracker(); + expect(t.scheme()).toBe('unknown'); + t.observe({ keyboard: press, gamepad: idle, touch: null }, 'assisted'); + t.observe({ keyboard: idle, gamepad: { ...NO_INPUT, move: 1 }, touch: null }, 'assisted'); + expect(t.scheme()).toBe('mixed'); + }); +}); + +describe('rankedSession', () => { + it('hands a challenge to exactly one game and never reuses it', () => { + rankedSession.setChallenge(challenge); + expect(rankedSession.takeChallenge()?.runId).toBe(challenge.runId); + expect(rankedSession.takeChallenge()).toBeNull(); + }); + it('ignores a late result for a run that is no longer current', () => { + rankedSession.setChallenge(challenge); + rankedSession.takeChallenge(); + rankedSession.beginRequest(); + rankedSession.finish(challenge.runId, { kind: 'accepted', score: accepted.score, ranks: accepted.ranks, replayed: false }); + expect(rankedSession.phase).toBe('requesting'); + }); + it('words the game-over line from the server answer only', () => { + rankedSession.setChallenge(challenge); + rankedSession.takeChallenge(); + rankedSession.set('submitting'); + expect(rankedSession.statusLine()).toContain('VERIFYING'); + rankedSession.finish(challenge.runId, { kind: 'accepted', score: accepted.score, ranks: accepted.ranks, replayed: false }); + expect(rankedSession.statusLine()).toBe('VERIFIED 1250 #1 THIS WEEK'); + rankedSession.beginRequest(); + expect(rankedSession.statusLine()).toBe(''); + }); +}); + +describe('local score memory', () => { + it('keeps this device\'s best scores and survives corrupt or blocked storage', () => { + const s = memory(); + rememberScore({ id: 'a', score: 100, at: 'x' }, s); + rememberScore({ id: 'b', score: 900, at: 'y' }, s); + rememberScore({ id: 'a', score: 100, at: 'x' }, s); + expect(readLocalScores(s).map((r) => r.id)).toEqual(['b', 'a']); + expect(localBest(s)?.score).toBe(900); + s.data.set('asteroids.rankedScores', '{not json'); + expect(readLocalScores(s)).toEqual([]); + expect(() => rememberScore({ id: 'c', score: 1, at: 'z' }, { getItem: () => { throw new Error('blocked'); }, setItem: () => { throw new Error('blocked'); } })).not.toThrow(); + }); + it('remembers the chosen nickname', () => { + const s = memory(); + expect(chosenNickname('?nick=Ace', s)).toBe('Ace'); + expect(chosenNickname('', s)).toBe('Ace'); + }); +}); diff --git a/phaser-asteroids/vite.config.ts b/phaser-asteroids/vite.config.ts index c515c13..4e80493 100644 --- a/phaser-asteroids/vite.config.ts +++ b/phaser-asteroids/vite.config.ts @@ -18,7 +18,7 @@ export default defineConfig({ }, }, test: { - include: ['tests/**/*.test.ts'], + include: ['tests/**/*.test.ts', 'server/tests/**/*.test.ts'], environment: 'node', }, }); From 9a6485f5542b3fda2dc27d20d27decef712844e9 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:05:35 -0300 Subject: [PATCH 2/7] Add ranked result and scores pages, nickname input handling, and associated styles - Implemented `rankedResult.ts` to handle the display of ranked run results, including score submission and feedback. - Created `scores.ts` to display high scores with pagination and filtering options. - Added `nickname.css` for styling the nickname input field, ensuring accessibility and usability. - Developed `nicknameInput.ts` to manage the nickname input field, allowing for proper keyboard handling and focus management. - Introduced tests for ranked input readiness and time limit verification to ensure robust functionality. --- docs/leaderboard-backend.md | 146 ++++- docs/release-preflight.md | 156 ++++++ phaser-asteroids/docs/menus.md | 17 +- phaser-asteroids/index.html | 2 +- phaser-asteroids/package.json | 1 + phaser-asteroids/scripts/lib/rankedStack.mjs | 214 +++++++ phaser-asteroids/scripts/menu.mjs | 8 +- phaser-asteroids/scripts/ranked-browser.mjs | 407 ++++++++------ phaser-asteroids/scripts/ranked-input.mjs | 161 ++++++ phaser-asteroids/scripts/ranked-ui.mjs | 526 ++++++++++++++++++ .../server/migrations/0002_time_limit.sql | 11 + phaser-asteroids/server/src/config.ts | 14 +- phaser-asteroids/server/src/leaderboard.ts | 8 +- phaser-asteroids/server/src/nickname.ts | 33 +- phaser-asteroids/server/src/router.ts | 4 +- phaser-asteroids/server/src/runs.ts | 17 +- phaser-asteroids/server/src/verify.ts | 19 +- .../server/tests/leaderboard.test.ts | 2 +- .../server/tests/timelimit.test.ts | 264 +++++++++ phaser-asteroids/src/input/rankedInput.ts | 7 + phaser-asteroids/src/ranked/api.ts | 318 +++++++++-- phaser-asteroids/src/ranked/localScores.ts | 70 ++- phaser-asteroids/src/ranked/nickname.ts | 47 ++ phaser-asteroids/src/ranked/personalBest.ts | 40 ++ phaser-asteroids/src/ranked/scoresModel.ts | 118 ++++ phaser-asteroids/src/ranked/session.ts | 122 ++-- phaser-asteroids/src/ranked/submission.ts | 166 ++++++ phaser-asteroids/src/replay/recorder.ts | 17 + phaser-asteroids/src/replay/types.ts | 10 + phaser-asteroids/src/replay/verifier.ts | 26 +- phaser-asteroids/src/scenes/GameScene.ts | 296 ++++++++-- phaser-asteroids/src/scenes/StartScene.ts | 173 ++++-- phaser-asteroids/src/ui/menu/pages/common.ts | 2 +- phaser-asteroids/src/ui/menu/pages/ranked.ts | 132 +++++ .../src/ui/menu/pages/rankedResult.ts | 212 +++++++ phaser-asteroids/src/ui/menu/pages/scores.ts | 122 ++++ phaser-asteroids/src/ui/menu/pages/title.ts | 37 +- phaser-asteroids/src/ui/menu/widgets.ts | 71 ++- phaser-asteroids/src/ui/nickname.css | 58 ++ phaser-asteroids/src/ui/nicknameInput.ts | 202 +++++++ phaser-asteroids/tests/ranked.test.ts | 489 +++++++++++++--- phaser-asteroids/tests/rankedInput.test.ts | 37 ++ phaser-asteroids/tests/timeLimit.test.ts | 108 ++++ 43 files changed, 4333 insertions(+), 557 deletions(-) create mode 100644 docs/release-preflight.md create mode 100644 phaser-asteroids/scripts/lib/rankedStack.mjs create mode 100644 phaser-asteroids/scripts/ranked-input.mjs create mode 100644 phaser-asteroids/scripts/ranked-ui.mjs create mode 100644 phaser-asteroids/server/migrations/0002_time_limit.sql create mode 100644 phaser-asteroids/server/tests/timelimit.test.ts create mode 100644 phaser-asteroids/src/input/rankedInput.ts create mode 100644 phaser-asteroids/src/ranked/nickname.ts create mode 100644 phaser-asteroids/src/ranked/personalBest.ts create mode 100644 phaser-asteroids/src/ranked/scoresModel.ts create mode 100644 phaser-asteroids/src/ranked/submission.ts create mode 100644 phaser-asteroids/src/ui/menu/pages/ranked.ts create mode 100644 phaser-asteroids/src/ui/menu/pages/rankedResult.ts create mode 100644 phaser-asteroids/src/ui/menu/pages/scores.ts create mode 100644 phaser-asteroids/src/ui/nickname.css create mode 100644 phaser-asteroids/src/ui/nicknameInput.ts create mode 100644 phaser-asteroids/tests/rankedInput.test.ts create mode 100644 phaser-asteroids/tests/timeLimit.test.ts diff --git a/docs/leaderboard-backend.md b/docs/leaderboard-backend.md index a4a3d5e..1b20e6e 100644 --- a/docs/leaderboard-backend.md +++ b/docs/leaderboard-backend.md @@ -1,6 +1,7 @@ -# Phaser Asteroids — Secure Online Leaderboard Backend (Phase 2) +# Phaser Asteroids — Secure Online Leaderboard (Phase 2 backend, Phase 3 player experience) > **Status:** Implemented and tested locally (Node + real workerd/D1 runtime + real Chromium). **Not deployed.** Nothing in this repository talks to a Cloudflare account. +> Phase 3 (the ranked menu, nickname entry, High Scores, personal best, and the time-limited ending) is described in [§15](#15-the-player-facing-experience-phase-3); the 20-minute limit decision is in [§3](#timing-policy). > **Code:** `phaser-asteroids/server/` (backend), `phaser-asteroids/src/ranked/` (browser client), builds on `phaser-asteroids/src/replay/` (Phase 1, see [deterministic-replay.md](deterministic-replay.md)). The single security rule: **no score enters the public leaderboard unless the server independently reproduces it from a ranked run the server itself issued.** The browser never sends a score; it sends the inputs it played, and the server replays them with the same deterministic engine. @@ -106,11 +107,36 @@ Every arrow is a **single conditional SQL statement or one atomic batch**, so th | --- | --- | --- | | Challenge lifetime | **60 minutes** from issue (`RUN_TTL_SECONDS`, 60 s–24 h) | Covers the longest allowed run plus long pauses | | Minimum elapsed time | simulated duration (`totalTicks / 60`) must be ≤ real time since issue **+ 2 s** | The fixed-step runner never advances more than real time (and not at all while paused), so a legitimate client cannot finish faster than its replay claims. Rejects "10 minutes of play submitted 5 s after issue" (`too_fast`) before any simulation runs | -| Maximum length | **72,000 ticks = 20 simulated minutes** | Bounds CPU and memory | +| Time limit | **72,000 ticks = 20 simulated minutes**, issued with the challenge as `timeLimitTicks` | Bounds CPU and memory. **Reaching it with the ship still alive is a valid, scored ending** (`endReason: "time_limit"`), not a failed submission. See below | | Pause / tab suspension / blur | Allowed | Simulation time stands still while paused, wall time continues; both sides of the inequality stay true. Only the 60-minute window limits how long a player can sit paused | **This does not prove a human played.** A bot can generate a replay offline and simply wait. See §12. +### The 20-minute limit is a valid ending (decision) + +*Problem (found in Phase 2):* a run longer than 72,000 ticks could not be submitted, so a player's best-ever run could silently become unsubmittable. + +*Investigation (numbers measured for this decision):* + +| Question | Result | +| --- | --- | +| Verification cost of a full 72,000-tick run | ~0.5 s of simulation CPU in Node even with an immortal ship at difficulty level 39 (scratch measurement); the Worker's safety net is `cpu_ms = 5000` | +| Worst-case recording size, one input change on **every** tick of 20 minutes (Assisted Flight steering) | 6.9 MiB raw, **0.44 MiB gzipped** (about 15:1). Limits are 8 MiB / 1 MiB, so a full-length run fits with margin | +| How far can play realistically go? | Asteroids get 15 % faster every 30 s without bound, the shipped bot dies within 2-6 minutes on every seed tried, and no run in testing has come near 20 minutes | +| Challenge lifetime | 60 minutes: 20 minutes of play plus 40 minutes of pauses | + +*Decision:* keep the measured 20-minute resource budget and make **reaching it a first-class outcome** instead of raising an arbitrary cap (any finite cap would otherwise recreate the same problem one minute later): + +* The server issues `timeLimitTicks` with every challenge and stores it with the run (`runs.time_limit_ticks`). It is verified against that stored value, so changing the configuration never strands a run that is already in flight. +* The game stops the run at exactly that tick (authoritative simulation ticks, not wall time) and shows a result page: **TIME LIMIT REACHED**. +* The replay's `totalTicks` must equal the limit exactly. A natural game over before it always wins. A replay that stops early without game over is still `not_game_over`; one that runs past it is `too_long`; a game-over replay padded to reach the limit is `invalid_replay`. +* The server simulates exactly that many ticks and scores the simulation **at that tick**. A ship never has to be "killed". Nothing in the body can choose or move the limit, and the recording's own claim (`claimedResult.endReason`) is only cross-checked. +* The ending is stored (`scores.end_reason`, `game_over` or `time_limit`) and returned as `endReason`. +* The limit is told to players before they start (the Ranked Play page) and counted down in the HUD during the last minute. +* Versioning: `claimedResult.endReason` is optional and recordings made before it existed still verify; `verifyReplay` only honours a time limit when a caller passes `timeLimitTicks`. `RANKED_TIME_LIMIT_SECONDS` can only **shorten** the limit (5-1200 s); the CPU, memory and body-size budgets were sized for 1200 s and cannot be raised by configuration. + +*Not covered by a test at full length:* no automated run can stay alive for 72,000 ticks, so the exact-limit rules are tested at a reduced limit (480-1500 ticks, in real Chromium and in the unit tests); the rules are the same code path at every length, and the full-length CPU and body-size figures above are measurements, not a test. + ## 4. Replay submission and verification `POST /api/v1/runs/:id/submit`, `Authorization: Bearer `, body JSON `{ replay, nickname?, controls? }`, optionally `Content-Encoding: gzip`. @@ -135,7 +161,7 @@ Order of work (cheap and fail-fast first): | Compressed request | 1 MiB | `Content-Length` pre-check, then bytes counted while streaming; stream cancelled when exceeded | | Decompressed / plain body | 8 MiB | Same, and the inflate stream is counted and cancelled at the limit (a 32 MiB-of-spaces gzip bomb is refused with 413) | | Encodings | `identity`, `gzip` | Others → 415 | -| Ticks | 72,000 | `too_long` | +| Ticks | 72,000 (the issued time limit) | `too_long`; a run alive at exactly the limit is accepted | | Input changes | ≤ ticks (the replay schema allows at most one change per tick; Phase 1 also caps at 100 k) | Structure validation | | Structure/types | every field type- and range-checked by Phase 1's `validateReplayStructure` | Before simulation | | Simulation work | ≤ 72,000 ticks, bounded entity counts in the game itself | `limits.cpu_ms = 5000` as a backstop | @@ -156,7 +182,7 @@ Reference points: a 10-minute replay is 3.3 MB raw / ~210 KB gzipped, well insid ## 5. Database schema -Migration `server/migrations/0001_init.sql` (applied to D1 with `wrangler d1 migrations apply`): +Migrations `server/migrations/0001_init.sql` and `0002_time_limit.sql` (applied to D1 with `wrangler d1 migrations apply`; 0002 adds `runs.time_limit_ticks` and `scores.end_reason`, see §3): **`runs`** — `id` (PK, UUID), `token_hash`, `seed` (0…2³²−1), `rules_version`, `config_json`, `created_at`, `expires_at`, `status` (`issued|verifying|accepted|rejected`), `claim_token`, `claimed_at`, `replay_hash` (SHA-256 of the submitted body: enables idempotent retries; **not** proof of authenticity), `finished_at`, `score_id`, `reject_reason`, `reject_detail`, `issuer_hash`. CHECK constraints tie `status='accepted'` ⇔ `score_id` set and `status='rejected'` ⇔ `reject_reason` set. @@ -181,6 +207,7 @@ All JSON, all under `/api/v1`. Errors: `{"error":{"code":"…","message":"…", "schemaVersion": 1, "tickRate": 60, "config": { "playerCount": 1, "livesMode": "independent", "friendlyFire": false, "speed": [1, 1] }, + "timeLimitTicks": 72000, "issuedAt": "2026-10-22T15:00:00.000Z", "expiresAt": "2026-10-22T16:00:00.000Z" } @@ -195,7 +222,7 @@ Request body (before optional gzip): `{"replay": {header, inputs, totalTicks, cl { "status": "accepted", "replayed": false, - "score": { "id": "c649cb33-…", "nickname": "Dave J", "score": 9114, "completedAt": "2026-10-22T15:03:11.204Z", "durationSeconds": 127.02 }, + "score": { "id": "c649cb33-…", "nickname": "Dave J", "score": 9114, "completedAt": "2026-10-22T15:03:11.204Z", "durationSeconds": 127.02, "endReason": "game_over" }, "ranks": { "allTime": 3, "weekly": 1 } } ``` @@ -231,10 +258,10 @@ Query: `limit` (1–100, default 10), `offset` (0–1000). Anything else → 400 } ``` ### `GET /scores/:id` → 200 `{ "score": {…}, "ranks": { "allTime": 3, "weekly": 1 } }` (404 if unknown **or hidden**) -### `GET /health` → `{ "ok": true, "rulesVersion": "1.0.0", "schemaVersion": 1, "maxTicks": 72000, "time": "…" }` +### `GET /health` → `{ "ok": true, "rulesVersion": "1.0.0", "schemaVersion": 1, "maxTicks": 72000, "timeLimitSeconds": 1200, "time": "…" }` ### `POST /admin/scores/:id/visibility` — body `{"visible": false, "reason": "offensive"}`, `Authorization: Bearer `. The route does not exist (404) unless `ADMIN_TOKEN` (≥ 16 chars) is configured; never sends CORS headers; failed attempts are rate limited. -Public entries expose only `id, rank, nickname, score, completedAt, durationSeconds`. +Public entries expose only `id, rank, nickname, score, completedAt, durationSeconds, endReason` (`game_over` or `time_limit`). ## 7. Atomic, one-use submission @@ -292,9 +319,9 @@ Assume the attacker reads the JavaScript, edits local state, hand-writes replay 4. **Offensive nicknames** are limited by charset only; there is no word filter. Moderation is after-the-fact (hide). 5. **Denial of service** is bounded, not prevented: a flood of cheap requests still costs request fees, and the global rate limits can be exhausted by an attacker to block legitimate starts/submissions. Consider a Cloudflare WAF rate-limiting rule at the edge (an account setting, not done here). 6. **Rate limiting by IP** is imperfect in both directions (shared NATs, rotating proxies). -7. **In-flight runs lost on deploy** if rules change; a run longer than 20 simulated minutes cannot be submitted (the client reports it; the game does not yet stop the run at the cap). +7. **In-flight runs lost on deploy** if rules change. (A run that reaches 20 simulated minutes is no longer a failure: it ends there and is scored, see §3.) 8. **Memory/CPU limits have been checked on local workerd only**, not on Cloudflare's network. -9. **Only single-player, keyboard-driven ranked play was exercised end-to-end in a browser.** Touch and gamepad metadata are unit-tested (`tests/ranked.test.ts`) but not driven through a ranked browser run. +9. **Browser coverage is emulated, not physical:** keyboard and touch (Assisted Flight, Chromium touch emulation) ranked runs and gamepad *menu* navigation are driven end to end; a controller-flown ranked run and real-phone behaviour are not. 10. **D1 is a single-region primary** and there is no backup beyond D1 Time Travel. ## 13. Local setup and testing @@ -314,15 +341,16 @@ npm run dev # http://127.0.0.1:8787 # Run the game against it (separate terminal, from phaser-asteroids/) npm run dev # http://localhost:5173 -# open http://localhost:5173/?ranked=1&nick=YourName (PLAY now requests a server-issued run) +# open http://localhost:5173/ then RANKED -> START RANKED RUN (the dev shortcut ?ranked=1 also still works) ``` | Command (from `phaser-asteroids/`) | What it proves | Runtime | | --- | --- | --- | | `npm test` | All unit tests, including server (`node:sqlite`, same SQL/migrations) and client | local, mocked clock | -| `npm run test:server` | Only the 108 server tests: lifecycle, forgery, concurrency, limits, leaderboard, weeks, moderation, nicknames, rate limits | local, mocked clock | +| `npm run test:server` | Only the server tests: lifecycle, forgery, concurrency, limits, leaderboard, weeks, moderation, nicknames, rate limits | local, mocked clock | | `npm run test:worker` | 32 HTTP checks against the **real Worker in workerd with a real local D1** and the real clock | local service | -| `npm run test:ranked` | **Chromium → game → Worker → D1 → leaderboard**, plus casual play with the backend down | local service, real browser | +| `npm run test:ranked` | The whole player journey through the real menus: **Chromium → game → Worker → D1 → leaderboard → High Scores → personal best**, plus ranked/casual play with the backend down | local service, real browser | +| `npm run test:ranked:ui` | Time-limited run on a Worker with an 8 s limit, forged-score rejection, skip, lost-response Retry, challenge expiry, paging, empty board, gamepad menu navigation, phone-sized touch + Assisted Flight run, resize/keyboard-field alignment | local services, real browser | | `npm run bench:workerd` | CPU/latency of the verifier in workerd | local service | | `npm run typecheck`, `cd server && npx tsc --noEmit -p tsconfig.json` | Types | — | @@ -344,14 +372,90 @@ Nothing above is a test against production Cloudflare infrastructure. **Rollback:** `npx wrangler rollback --env production` restores the previous Worker version (also available in the dashboard). Migrations are forward-only; 0001 is additive. For data problems, D1 Time Travel: `npx wrangler d1 time-travel restore asteroids-leaderboard --env production --timestamp=`. Removing `VITE_LEADERBOARD_API_URL` from the site build turns ranked play off without touching the backend. -## 15. Future client UI integration +## 15. The player-facing experience (Phase 3) + +Code: `src/ranked/` (API client, submission state machine, personal best, boards model), `src/ui/menu/pages/{ranked,rankedResult,scores}.ts` (pages built from the existing menu kit), `src/ui/nicknameInput.ts` (the one DOM text field), `src/scenes/{StartScene,GameScene}.ts` (integration). Nothing here verifies or ranks anything: every number on screen after a run comes from the server's answer. + +### Flow + +``` +TITLE ── PLAY (casual, unchanged; Space) + ── RANKED (R) ──► RANKED PLAY page: rules, the time limit, your best verified score + │ └ START RANKED RUN ─ POST /runs ─► CONNECTING… ─► play + │ └ (backend down / not configured) "Ranked Play is temporarily unavailable. You can still play normally." + │ TRY AGAIN · PLAY NORMALLY · BACK + ── HIGH SCORES (H) ─► THIS WEEK | ALL TIME, 10 per screen, PREVIOUS / NEXT, BACK +RANKED RUN ── RANKED label beside the clock (a countdown in the last minute) ── pause/resume as normal + └─ game over, or TIME LIMIT REACHED ─► RESULT page: score, name field, SUBMIT SCORE / SKIP + └─ SUBMIT ─► UPLOADING… ─► SERVER IS VERIFYING… ─► SCORE VERIFIED! (weekly + all-time rank) ─► VIEW HIGH SCORES · PLAY AGAIN · MAIN MENU +``` + +* `?ranked=1` still works as a developer shortcut (PLAY then opens the same Ranked Play page and starts the request), but nothing needs it. +* **Ranked is one player.** With two players chosen on the title screen the button reads `RANKED / 1 PLAYER ONLY` and is disabled; the player count is never changed silently. +* **Ranked play starts only after the server issues a challenge.** A failed request leaves the player on the page with a plain message; a casual game is never started in its place unless they choose PLAY NORMALLY. The result page's PLAY AGAIN goes through the same request: a spent challenge is never reused. +* **Leaving a run in progress** needs the pause menu's existing two-press RETURN TO MENU. An abandoned run creates no score. After the result page is open, MAIN MENU / PLAY AGAIN only appear once there is nothing left to submit (accepted, rejected, expired, skipped...), so a score cannot be thrown away by one stray tap; SKIP is an explicit button. +* **Expiry during a long pause** is detected as it happens (against the device clock, shifted by the clock difference measured when the challenge arrived). The pause menu and HUD say `RANKED RUN EXPIRED`, the label changes to `UNRANKED`, and the result page says the run expired instead of attempting a submission that cannot succeed. + +### Submission states (`src/ranked/submission.ts`) + +| State | What the player sees | Leads to | +| --- | --- | --- | +| ready | name field, SUBMIT SCORE (Enter), SKIP; live feedback under the field | uploading, skipped | +| uploading | "UPLOADING YOUR RUN…" (or "CONNECTION TROUBLE. TRYING AGAIN (n)…") | verifying | +| verifying | "THE SERVER IS VERIFYING YOUR SCORE…" (shown when the upload has really finished: XHR `upload.onload`) | any answer | +| accepted | **SCORE VERIFIED!**, the server's score, nickname, weekly and all-time rank, new personal best | — | +| rejected | SCORE NOT VERIFIED, reason code in small print; the run is spent | — | +| network error | "Could not reach the ranked server. Your run is safe." RETRY · SKIP | uploading | +| duplicate | "Already submitted" (the run holds an accepted score under a different submission) | — | +| expired | "Ranked run expired"; nothing was sent | — | +| refused / unavailable | the server refused the request / no API configured | — | + +"Verified" is shown only for a state reached from a `200 accepted`. **Retry semantics:** the request body (replay + nickname + controls) is built once and sent byte-identically on every attempt (the browser test hashes every request). The automatic attempts are bounded (the first try plus two repeats, 1.5 s and 4 s apart); after that nothing happens until the player presses RETRY. Only transport failures, 5xx, 429 and "still verifying" can be retried; a server rejection, expiry or a `run_already_submitted` never is. A response lost after the server accepted the run comes back as `replayed: true` with the original score (tested end to end). The nickname is locked after the first send (a changed name would be a different body and a 409); it reopens only if the server itself says `invalid_nickname`, which does not consume the run. + +### Nickname + +3-16 characters (counted as Unicode code points), must start with a letter or digit, then letters, digits, space and `_ . ! -`; blank means `Anonymous`. The rule lives in one function, `src/ranked/nickname.ts`, which the Worker re-exports, so the field's live feedback and the server cannot disagree (the server's answer remains authoritative). The last **successfully submitted** nickname is remembered in `localStorage` (`asteroids.rankedNickname`) and pre-filled; `?nick=` pre-fills on a development page and stores nothing. Nicknames are drawn as plain canvas text, never HTML. + +**Mobile keyboard.** The field is a real `` laid over its canvas frame: a phone opens its keyboard only for a tap that lands on an input, and you also get IME, paste and screen-reader support. It follows the canvas through resizes and rotation every frame (verified at 667×375, 844×390, 1024×768, 768×1024, 1920×1080 with the typed text kept); while it is focused and the on-screen keyboard has shrunk the visual viewport, it docks just above the keyboard so what is being typed is never hidden; in portrait the "rotate your phone" prompt covers it and the text is kept; Enter / "Done" dismisses the keyboard and submits (if valid); key presses in the field never reach the game (no steering, pausing or retrying while typing); font size is at least 16 px so iOS does not zoom. `interactive-widget=resizes-visual` is set on the viewport meta so browsers behave alike. + +### Personal best (`src/ranked/localScores.ts`, `personalBest.ts`) + +The 20 best **server-accepted** `{id, score, at, nickname}` entries are kept in `localStorage` (`asteroids.rankedScores`); the best across nicknames is the personal best. Only an acceptance adds to it. When a page that shows it opens, `GET /scores/:id` refreshes it (and forgets a score the server no longer lists, e.g. hidden); offline it shows the remembered figure. Clearing site data forgets it, switching device does not carry it. A score id is public and proves nothing: High Scores marks rows whose **id** matches a remembered one with `YOU` (never by nickname). There are no accounts and nothing here is an identity. + +### High Scores (`src/ui/menu/pages/scores.ts`, `scoresModel.ts`) + +THIS WEEK (default) / ALL TIME, ten entries per screen (`limit=10&offset=…`, never a bulk download), PREVIOUS / NEXT, `PAGE n / m`. The week caption (`WEEK OF OCT 19 - OCT 25 (ATLANTIC TIME)`) is formatted from the server's `weekStart`/`weekEnd`/`timeZone`; the browser never computes a week. Switching boards works by touch, mouse, Left/Right on the tabs (keyboard and D-pad), and a slow answer for a board the player has already left is dropped. States: loading, empty ("No ranked scores yet. Be the first!"), network error (TRY AGAIN), not configured ("High scores are not available yet"), ready. + +### Offline, unconfigured and development behaviour + +* **No production API configured** (`VITE_LEADERBOARD_API_URL` unset, non-loopback host): casual play is untouched; Ranked Play says "not available in this build yet"; High Scores says "not available yet"; nothing is requested. +* **Backend unreachable:** a normal game still starts instantly (the browser test turns the Worker off and checks no API call is made by plain PLAY). +* **Local development:** on a loopback host `?api=http://127.0.0.1:PORT` selects a local Worker and the default is `wrangler dev`'s `http://127.0.0.1:8787`. `?api=` is ignored on any other host. +* Intro page limitation: the Ranked Play page states the production limit (20:00); a Worker started with a shorter `RANKED_TIME_LIMIT_SECONDS` (tests only) still shows 20:00 there, while the HUD and result page use the issued value. + +### Mobile and accessibility notes + +Controls are at least 90 game px (≥ 44 CSS px at 667×375 and up; asserted in the browser tests for the title, High Scores and result pages), no page has overlapping or off-screen controls (asserted from the menu geometry), keyboard focus rings are the existing gold frames, the DOM field has an accessible name and a visible focus style, and a polite live region announces results ("Score verified. 24,850 points. Weekly rank 7."). Nothing animates while verifying, so reduced-motion needs no special case. Portrait phones get the existing rotate prompt (the game is landscape-only). + +### Manual acceptance checklist (physical Android phone) — NOT yet performed + +No real device was available to this work; the Android keyboard, `visualViewport` behaviour, fullscreen and haptics on real hardware are **untested**. Please run on a phone against a reachable Worker (for example `wrangler dev --ip 0.0.0.0` plus `npm run preview:lan`, with the phone's origin in `ALLOWED_ORIGINS`): + +1. Open the game: title menu shows PLAY, RANKED, HIGH SCORES, AUDIO, CONTROLS; everything is thumb-sized. +2. HIGH SCORES: switch THIS WEEK / ALL TIME, page with NEXT, BACK. +3. RANKED → read the time limit → START RANKED RUN → game starts only after "CONNECTING…". +4. Fresh install: movement is Assisted Flight; steer, FIRE, LASER, BOOST feel normal; the RANKED label is visible and does not cover anything. +5. Fullscreen button (title/pause) still works; PAUSE → RESUME keeps the run; rotate upright and back. +6. Die (or reach the limit). Result page: tap the name field — keyboard opens, the field stays visible above it, typing works, "Done" dismisses and submits; try a 2-character name and see feedback; dismiss the keyboard by tapping elsewhere and confirm the text is still there. +7. SUBMIT: uploading → verifying → SCORE VERIFIED! with the ranks you expect. Turn on airplane mode before SUBMIT: you get "Could not reach…" and RETRY works after turning it off, without a second score. +8. VIEW HIGH SCORES: your row is marked YOU. +9. Reload the page: RANKED page shows your best verified score. Clear site data: it is gone, the board entry is not. -Everything the UI needs is already exposed by the game and API: +### Known limitations (Phase 3) -* **Start:** `requestChallenge()` / `StartScene.startRanked()` (`src/ranked/api.ts`); replace the `?ranked` dev flag with a menu item. -* **State:** `rankedSession` (`src/ranked/session.ts`) with phases `requesting → playing → submitting → accepted | rejected | failed | abandoned`; mirrored on `window.__ASTEROIDS_RANKED__` for tests. -* **Result:** `outcome.score` and `outcome.ranks` (all-time and weekly rank) after acceptance; the game-over screen already shows one status line. -* **Personal best:** `src/ranked/localScores.ts` keeps accepted `{id, score, at}` on this device; `GET /scores/:id` returns the current rank for each id. -* **Nickname:** `?nick=` / stored value today; add an input and let the server's 400 `invalid_nickname` message drive validation text. -* **Leaderboard screen:** `GET /leaderboard/weekly|all-time` (page with `limit`/`offset`). Render nicknames with text APIs only. Show `weekEnd` as the reset time. -* Handle `failed`/`rejected` by offering "Play again (ranked)" which goes back to the title and requests a *new* challenge, as RETRY already does. +* Real-device behaviour (above) is untested; the on-screen-keyboard docking relies on `visualViewport` and is only exercised in emulation. +* A ranked run at the full 20:00 has not been played in automated tests; the time-limit rules are tested at 8 s (real Chromium + Worker) and 1500 ticks (unit), and full-length cost is a measurement (see §3). +* Gamepad-only players cannot type a nickname without a keyboard (they can SUBMIT with the remembered one, or leave it blank for `Anonymous`); there is no on-screen controller keyboard by design. +* The nickname has no word filter (moderation is after the fact, §12.4). +* Rank text uses the ranks returned at acceptance; the High Scores screen is a snapshot and may be a few seconds stale (`Cache-Control: public, max-age=5`). +* Ranked scores and bots: §12.1 is unchanged. Anyone can generate a valid replay offline for the issued seed. diff --git a/docs/release-preflight.md b/docs/release-preflight.md new file mode 100644 index 0000000..eac24fb --- /dev/null +++ b/docs/release-preflight.md @@ -0,0 +1,156 @@ +# Ranked leaderboard release preflight — 2026-10-22 + +**Decision: suitable for a reviewed feature commit; HOLD deployment.** No critical score-forgery or credential-disclosure defect was found. Resolve the mobile start safeguard below, finish the bounded verification gates, and supply production configuration before a controlled release. Keep the production time limit fixed at 1,200 seconds until the configuration-change defect is fixed. + +This was an audit. No application code, existing tests, configuration, history or cloud resources were changed. No commit, push, merge or deployment was performed. This report and ignored local verification artifacts are the only additions from this task. + +## 1. Repository state + +- Branch: `feature/leaderboard-ui`; HEAD `0963cd4` (`Add ranked leaderboard functionality and related tests`). Previous commits: `ae1eaf8` (nonzero browser replay verification), `63a0a6d` (reject post-game-over replay ticks). +- Initially: **25 modified tracked feature files + 14 untracked feature files = 39 feature paths**, nothing staged. Tracked feature diff: **1,728 insertions / 556 deletions**; that statistic excludes untracked contents. This report adds one further untracked path. +- Five unrelated tracked `tmp/` paths appear deleted, accompanied by access-denied / inconsistent missing-directory warnings. Their actual state could not be established reliably; do not interpret this as authorization to delete or restore them. +- Global `git diff --check` reported no whitespace violations but could not read those five paths. The scoped check over `docs/` and `phaser-asteroids/` passed cleanly. Git also reports routine LF/CRLF conversion warnings. +- Root, frontend and server `node_modules/` directories exist and are ignored; none is tracked. Frontend and server lockfiles are unchanged. Frontend build, dependencies and Worker types are usable. +- No unexpected gameplay-engine, audio, asset, Python, workflow or lockfile changes were found in the feature diff. The viewport adjustment supports the new mobile nickname field. Shared menu changes are limited to the title layout, hint fitting, a text-field widget and a narrower context type. + +## 2. Files reviewed + +All 39 feature paths were inspected, including all 14 new files. Paths below are under `phaser-asteroids/` unless prefixed otherwise; **new files are marked +**. + +| Area | Files | +| --- | --- | +| Documentation / entry | `../docs/leaderboard-backend.md`, `docs/menus.md`, `index.html`, `package.json` | +| Browser verification | `scripts/menu.mjs`, `scripts/ranked-browser.mjs`, **+** `scripts/ranked-ui.mjs`, **+** `scripts/lib/rankedStack.mjs` | +| Backend | `server/src/{config,leaderboard,nickname,router,runs,verify}.ts`, `server/tests/leaderboard.test.ts`, **+** `server/tests/timelimit.test.ts`, **+** `server/migrations/0002_time_limit.sql` | +| Ranked client | `src/ranked/{api,localScores,session}.ts`, **+** `src/ranked/{nickname,personalBest,scoresModel,submission}.ts` | +| Replay / integration | `src/replay/{recorder,types,verifier}.ts`, `src/scenes/{GameScene,StartScene}.ts` | +| Menus / input | `src/ui/menu/pages/{common,title}.ts`, `src/ui/menu/widgets.ts`, **+** `src/ui/menu/pages/{ranked,rankedResult,scores}.ts`, **+** `src/ui/nicknameInput.ts`, **+** `src/ui/nickname.css` | +| Client tests | `tests/ranked.test.ts`, **+** `tests/timeLimit.test.ts` | + +Supporting review covered both ignore files and lockfile status, Wrangler configuration, migration 0001, Worker entry/crypto/router/lifecycle, SQLite harness, menu controller/view, input routing, production debug hooks, Vite configuration, deployment documentation/workflow, browser-suite entry points, and available verification logs/screenshot inventory. The Phase 3 behavior was assessed against the supplied brief and repository documentation; no separate original Phase 3 specification was supplied. + +## 3. Confirmed defects and release gates + +**Mobile release gate — ranked start bypasses the existing touch-off safeguard.** In `src/ui/menu/pages/title.ts:67`, casual PLAY becomes `keysOnly` on a coarse-pointer phone in keyboard mode. The adjacent ranked button (`:82`) and Ranked Play START (`pages/ranked.ts:89`) have no equivalent restriction. `StartScene.ts:314` accepts that start, while `GameScene.ts:241` leaves the touch UI off. A phone without a physical keyboard/controller can therefore tap into a run it cannot steer. This is a confirmed code-path inconsistency; it has not been reproduced on physical hardware in this audit. **Narrow fix:** preserve the input preference and apply the existing pointer-start restriction at every ranked entry/start action, including TRY AGAIN and PLAY NORMALLY, with a clear route back to touch controls. Verify the touch-off path before mobile release. + +**Configuration-change defect — issued time limits are not immutable.** `server/src/verify.ts:78` uses `Math.min(issuedLimit, settings.maxTicks)`. An actual-verifier reproduction produced: + +| Issued limit | Current limit | Submission | Result | +| --- | --- | --- | --- | +| 900 | 72,000 | Alive at 900 ticks | accepted | +| 900 | 600 | Same original 900-tick recording | `too_long` | +| 900 | 600 | Alive at 600 ticks | accepted as `time_limit` | + +This contradicts `docs/leaderboard-backend.md:130` and migration 0002's comment. The existing configuration-change test only covers raising the limit (`server/tests/timelimit.test.ts:186`). **Narrow fix:** distinguish the fixed 72,000-tick resource ceiling from the configurable limit for *new* challenges; verify recorded limits against the fixed ceiling. Add one lowering-limit regression. This does not block the first controlled release if production stays at the default throughout, but it blocks safely changing that setting during active play. + +**Deployment gates:** production D1 ID is a placeholder; secrets must be supplied; the Pages build does not wire `VITE_LEADERBOARD_API_URL` into its environment. Without the latter, ranked play is deliberately unavailable on the published host. These are known setup requirements, not evidence of a broken casual game. Browser/phone gates are listed in sections 8–9. + +## 4. Non-blocking issues to track + +- Production still supports `?debug`, `?keydebug`, `?verified`/`?seed` and publishes replay/session inspection objects (`src/main.ts:26`, `GameScene.ts:195`, `src/ranked/session.ts:122`). There is no enabled god-mode or score-acceptance cheat handler. `?debug` exposes mutable local scene state, including in-memory client objects; TypeScript `private` is not a security boundary. These hooks existed before this diff and cannot bypass server replay verification. Consider development gating separately; browser scripts currently depend on them. +- `src/ranked/api.ts:106` clears its fetch timeout after response headers, before JSON body consumption (`:126`, `:362`). A stalled response body can leave ranked/board loading waiting indefinitely. This is a confirmed timeout-coverage gap, not an observed outage; casual play remains independent. +- Browser harness cleanup kills parent processes without awaiting complete process-tree shutdown (`scripts/lib/rankedStack.mjs:93`, `:137`). Startup failures can also leave the preview child without the normal close handle. Orphan-process/hanging-shutdown risk is plausible, but this audit did not establish it as the cause of the reported keyboard hang. +- Full-length 20-minute verification cost remains measured evidence, not a full-length accepted browser test. Physical mobile keyboard behavior and a controller-flown ranked run remain unverified. +- The intro always says 20:00 even for a deliberately shortened test Worker; this is already documented. Local personal best is device convenience, not an authenticated identity. Bots that produce valid issued-seed replays and wait out elapsed time remain an acknowledged limitation. + +## 5. Security and configuration findings + +| Requirement | Evidence / result | +| --- | --- | +| Server-issued ranked challenge | Worker creates CSPRNG ID/token/seed, stores only the token hash and approved configuration; game consumes a challenge once. Failed requests do not silently start ranked play. | +| Casual cannot post an arbitrary ranked score | Casual has no challenge/submission flow. Submit requires a real run/token and checks issued seed, exact configuration, rules and elapsed time before independent simulation. Merely enabling the experimental replay path grants no credential. | +| Verification cannot be switched off by the client | Production Worker injects no verifier override; test-only dependency injection is internal. Claimed score is cross-checked, never used as the authoritative score. | +| Credential handling | Tokens remain in browser memory and Authorization headers; no raw token is in session snapshots, local storage, leaderboard output or intentional application logs. Public run IDs and replay seeds are not secrets. Debug inspection of the player's own runtime remains possible as above. | +| Nickname injection | Shared charset/normalization rules; canvas text, DOM input `.value` and live-region `.textContent`; no nickname HTML insertion. Parameterized SQL handles storage/moderation. | +| Idempotency / personal best | Prepared bytes are reused for bounded automatic/manual retries; conditional claims, atomic score finalization and UNIQUE(run_id) protect acceptance. Local score/nickname writes occur only after a server acceptance. | +| Casual during outages | Ranked requests are asynchronous; casual simulation/start does not await them. Existing browser journey reports this path working; no new browser run was performed here. | +| Time limit | Server caps work, replays all ticks and accepts an alive ending only at its selected exact limit; padding after natural game over is rejected. Default 72,000-tick enforcement is sound, subject to the configuration-change defect above. | +| Administration | Admin route absent without a token of at least 16 characters; bearer comparison, failed-auth throttling, no admin CORS. No frontend admin secret or admin-client route found. Hide/unhide SQL and unit coverage exist. | +| CORS / production defaults | Explicit allowed origin, no wildcard or credentialed CORS; foreign browser POST origins rejected. Originless scripts are allowed intentionally: CORS is not authentication. Production repeats D1/vars and excludes loopback origins. API query override works only on loopback hosts. | + +`IP_HASH_SALT` silently falls back to a public development value (`server/src/config.ts:105`); setting a random production secret is mandatory for the intended IP privacy. Admin is disabled by default. The API URL is public configuration and must use HTTPS in production; URL validation also permits HTTP for local use. Never put admin or Cloudflare credentials into any `VITE_*` variable. + +## 6. Exclusions and secret scan + +277 tracked/untracked text files were scanned for common private-key/token formats, credential URLs and secret assignments, without printing candidate values. The only assignment match was the explicit test fixture in `server/tests/harness.ts:82`; the tracked `.dev.vars.example` contains recognizable placeholders. No actual credential was identified. This was a working-tree scan, not an exhaustive Git-history or ignored-file secret audit. No actual `.env` or `.dev.vars` file was found at the frontend/server roots. + +Keep dependencies, `dist/`, `.node/`, `.wrangler/`, `.dev.vars`, logs, screenshots, benchmark/reproduction output and local game data excluded. Existing rules cover these paths. **Generic `.env`, `.env.*` and `.dev.vars.*` variants are not currently ignored**: add narrowly scoped rules before using those secret-bearing files, preserving `.dev.vars.example`. + +Exclude these unrelated apparent deletions from feature staging; investigate their access problem separately: + +``` +tmp/test_add_score_sorts_and_limit0/scores.json +tmp/test_get_top_scores_returns_re0/scores.json +tmp/test_is_high_score_checks_thre0/scores.json +tmp/test_load_highscores_returns_e1/scores.json +tmp/test_log_event_writes_json_lin0/game_events.jsonl +``` + +All 14 new feature files have a legitimate role; no disposable script among them was identified. Use explicit paths or patch staging, never an indiscriminate `git add -A` for this tree. + +## 7. Proposed logical commits — none created + +1. **Shared protocol and server time-limited endings:** shared nickname rules/re-export, replay recorder/types/verifier, server changes, migration 0002 and time-limit/public-contract tests. Include the lowering-limit correction here if undertaken. +2. **Ranked player experience:** client API/session/submission/storage/boards, scene integration, menu pages/widgets, nickname field/CSS/viewport, client tests and menu documentation. Include the mobile safeguard correction here. +3. **Acceptance harness and release instructions:** ranked browser scripts/shared stack, menu expectation updates, package script, backend runbook and this report. Incorporate the concrete production setup/rollback corrections below before deployment. + +Review the staged diff after each proposed group and keep every intermediate commit type-correct. Leave the unrelated `tmp/` state outside these commits. + +## 8. Verification evidence and minimal remaining plan + +**Performed now:** `npm test -- --reporter=dot`: **55 files / 1,459 tests passed**, 13.93 seconds. `npm run build`: frontend typecheck + production browser/Node replay builds passed. Separate `node ../node_modules/typescript/bin/tsc --noEmit -p tsconfig.json` from `server/`: passed. One small actual-verifier configuration-change reproduction was run. Logs/build/reproduction modules are ignored under `scripts/.smoke-output/` and `dist/`. + +The first unit attempt failed before tests because sandbox subprocess creation returned EPERM; the permitted retry passed. No browser suite, benchmark sweep, background monitor or cloud command was run. + +**Previous evidence:** the supplied brief reports a working browser → Worker → D1 journey, incomplete menu/touch/gamepad verification, keyboard timing failure plus shutdown hang, smoke laser-cooldown failure, and baseline-reproduced music/pages audio failures. Available `verify*.log` files are older Oct 19 smoke/co-op evidence; Oct 22 screenshots are mixed-age artifacts, not complete final-layout pass logs. Neither proves final Phase 3 regression completion. The baseline audio comparison is reported by the user and was not independently repeated here. + +Run the following independently on an idle machine, building once after any fixes. Commands are from `phaser-asteroids/`; retain a separate log for each. Budgets below are proposed stopping limits, not measured runtimes. Require exit code 0 **and** the final summary; a hanging process is incomplete even if preceding assertions passed. + +| Order | Check | Stop / acceptance rule | +| --- | --- | --- | +| 1 | Address mobile start safeguard; unit/type/build checks only for changed code | Stop on failure. Keep the time limit at 1,200 s or fix/test the limit defect before changing it. | +| 2 | `node scripts/menu.mjs` | One run, 15-minute ceiling; require completed final-layout tour and summary. No rerun loop. | +| 3 | `node scripts/touch.mjs` | One run, 15-minute ceiling; require touch-off recovery, controls, pause/rotation and final summary. Then do section 9 on the S25. | +| 4 | `node scripts/gamepad.mjs` | One run, 10-minute ceiling; require navigation, assignment, disconnect/resume, ability edges and clean exit. | +| 5 | Target the reported keyboard/laser behavior with a short manual check; if automated certification is required, run `node scripts/keyboard.mjs` then `node scripts/smoke.mjs`, separately | At most one run each, 5-minute ceiling each. On the same timing failure, preserve diagnostics and compare that assertion to the baseline once; do not modify gameplay to get green. Stop on another failure or hang and classify it. | +| 6 | After the production API URL is wired into the candidate build, `node scripts/pages-check.mjs` | One run, 5-minute ceiling. Pages path/asset/start errors block publication. If only the known baseline audio assertion fails, document a specific disposition; the current deploy workflow still requires this job to pass. | + +Do not rerun the separate music suite merely to rediscover the reported baseline failure. Combat/co-op and the already working ranked journey do not need routine full reruns for this audit. After a ranked flow or verifier fix, rerun only its affected unit checks and the relevant ranked acceptance script once; the stock ranked UI script uses two local Workers and should be a separate task if needed. + +On timeout, stop and clean up only that run's owned process tree, verify its preview port is released, and record the incomplete result before starting anything else. No parallel browser runners or monitoring loops. Any unexplained functional failure holds release; a timing assertion is not automatically a gameplay bug or an automatic waiver. + +## 9. Manual Galaxy S25 checklist + +Use Chrome with Samsung Keyboard (and the user's usual keyboard if different), both normal and fullscreen landscape. Use the production HTTPS candidate or an explicitly configured LAN build. A LAN hostname ignores `?api=`: bake in a reachable API URL and allow the exact phone-page origin in the Worker; check secure-context-dependent fullscreen/haptics on HTTPS. + +- Fresh profile and saved preferences: PLAY / RANKED / HIGH SCORES readable and tappable, no safe-area or browser-toolbar clipping; Assisted Flight default and saved movement preference preserved. +- Switch touch OFF via the existing confirmation, reload, and verify finger taps cannot start an uncontrollable casual or ranked run. Recover through TOUCH CONTROLS ON. External keyboard/controller can still start correctly. +- Start ranked only after CONNECTING succeeds. Steer + FIRE + LASER + BOOST with multiple fingers; label/countdown do not cover play. Pause/resume, rotate upright/back, app-switch and lock/unlock without stuck inputs or unintended submission. +- Result nickname: tap opens real keyboard; field remains visible; type/paste/edit, spaces/underscores, short/long/invalid names, blank Anonymous, Done, system Back, and tap outside. No typing triggers pause/mute/fire; no lost text on rotation or toolbar changes. +- Submit once and double-tap: one accepted score, correct server score/name/ranks, YOU highlight and personal best after reload. SKIP writes no score and no remembered nickname; PLAY AGAIN gets a fresh challenge. +- Airplane mode before submission: bounded retries, clear failure, manual RETRY after reconnection, exactly one stored score. API unavailable: casual PLAY remains usable. Test a locally shortened expiry/limit separately if needed; never shorten the production limit during active runs. +- Board tabs, paging, back navigation, Android Back, fullscreen exit/re-entry and haptics behave as expected. Record browser/OS/keyboard versions and failures; emulation does not certify these checks. + +## 10. Exact production prerequisites and runbook corrections + +Everything in this section is **for the owner to perform later; none was executed**. Existing `docs/leaderboard-backend.md` §14 covers the broad sequence, but needs the environment-specific and recovery details here. + +1. Have a Cloudflare account with **Workers Paid**, permission to create D1, deploy Workers and set secrets; a Workers subdomain or intended custom domain; and permission to set the GitHub Pages build configuration. Workers Paid currently has a $5 USD/month minimum; review usage charges. [Cloudflare pricing](https://developers.cloudflare.com/workers/platform/pricing/) +2. Use the pinned lockfiles with Node 22.14+ compatible tooling. From `phaser-asteroids/`, `npm ci`; from `server/`, `npm ci`. Authenticate with `npx wrangler login` only when ready to configure the account. Do not copy test secrets into production. +3. From `server/`, `npx wrangler d1 create asteroids-leaderboard`; put its returned ID in **`[[env.production.d1_databases]]`**, keeping `binding = "DB"` and `migrations_dir = "migrations"`. The top-level zero ID is only a local placeholder; it does not configure production. +4. In `[env.production.vars]`, set exact HTTPS browser origins, comma-separated, without a path: `https://djblackett.github.io` plus any actual custom frontend origin. Keep local origins in the local configuration only. Leave `RANKED_TIME_LIMIT_SECONDS` unset (1,200 s), TTL default 3,600 s and the reviewed rate limits unless intentionally changed. Keep `cpu_ms = 5000` and the cleanup cron in production. +5. Set a long random `IP_HASH_SALT` with `npx wrangler secret put IP_HASH_SALT --env production`. For usable moderation, also set a separate random `ADMIN_TOKEN` of at least 16 characters with `npx wrangler secret put ADMIN_TOKEN --env production`. Store these securely outside the frontend/repository; no Cloudflare API credential is needed in browser code. +6. Inspect `npx wrangler d1 migrations list asteroids-leaderboard --env production --remote`, then apply with `npx wrangler d1 migrations apply asteroids-leaderboard --env production --remote`. Confirm **both 0001_init.sql and 0002_time_limit.sql** applied, including `runs.time_limit_ticks` and `scores.end_reason`. Apply schema **before** the new Worker. [D1 migrations](https://developers.cloudflare.com/d1/reference/migrations/) +7. Deploy the Worker with the production environment only when authorized, then check health, allowed/denied-origin preflights and one controlled issued-challenge/accepted-score flow. Health is liveness/configuration only; it does not query D1, so it cannot prove migrations or the binding work. +8. Wire the public HTTPS Worker base URL into the Pages **build step**, for example `env: { VITE_LEADERBOARD_API_URL: "${{ vars.VITE_LEADERBOARD_API_URL }}" }` plus the corresponding repository variable. Merely creating that repository variable does not export it to Vite; `.github/workflows/deploy-gh-pages.yml` currently contains no such mapping. Rebuild, validate the Pages base path and publish only after authorization. This value is public, never a secret. +9. Moderation from a trusted operator terminal, with `ASTEROIDS_ADMIN_TOKEN` already supplied securely and the placeholders replaced: + + ```powershell + Invoke-RestMethod -Method Post -Uri 'https:///api/v1/admin/scores//visibility' -Headers @{ Authorization = "Bearer $env:ASTEROIDS_ADMIN_TOKEN" } -ContentType 'application/json' -Body '{"visible":false,"reason":"offensive"}' + ``` + + Confirm the score disappears from both boards and its public detail returns 404 after the public cache's five-second lifetime. Use `{"visible":true}` to unhide. The existing direct-D1 fallback command at `docs/leaderboard-backend.md:296` needs **`--env production`** added; otherwise it selects the top-level binding/placeholder. Do not run moderation from the frontend or put tokens into URLs/logs. +10. Monitor Worker Metrics CPU and Memory Usage percentiles, request/errors and invocation statuses, especially **Exceeded CPU Time Limits / Exceeded Memory**; compare verification traffic with the 5,000 ms cap and **128 MB isolate limit**. Watch D1 query errors/latency and the existing structured rejection/internal-error events with `npx wrangler tail --env production`. Persisted Workers Logs must be explicitly enabled if required; this Wrangler file has no observability configuration. Use controlled representative uploads and local profiling for memory investigation; local latency is not production CPU measurement. [Metrics](https://developers.cloudflare.com/workers/observability/metrics-and-analytics/), [limits](https://developers.cloudflare.com/workers/platform/limits/), [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/) +11. Recovery: keep the previous frontend artifact and Worker version ID. A previous Worker can be restored with `npx wrangler rollback --env production`; migrations are not undone. A Phase 2 Worker does not issue `timeLimitTicks`, so the new frontend will refuse its challenges: restore a compatible frontend too, or disable ranked by removing the API URL and **rebuilding/republishing** the frontend. On the first deployment there may be no previous Worker version; frontend disablement is the immediate fallback. For data loss/corruption, inspect the restore point and use `npx wrangler d1 time-travel restore asteroids-leaderboard --env production --timestamp=` only after explicit operator review; it restores the whole database, including scores after that point. [Worker rollback](https://developers.cloudflare.com/workers/wrangler/commands/), [D1 Time Travel](https://developers.cloudflare.com/d1/reference/time-travel/) + +The existing deployment page also describes the game as having no backend (`phaser-asteroids/docs/deployment.md:3`); clarify that the static casual game remains standalone while ranked uses this optional Worker. Add migration 0002 and frontend/Worker compatibility to the rollback text. No cloud account access was needed to identify these gaps. diff --git a/phaser-asteroids/docs/menus.md b/phaser-asteroids/docs/menus.md index 002dbcd..714e770 100644 --- a/phaser-asteroids/docs/menus.md +++ b/phaser-asteroids/docs/menus.md @@ -9,8 +9,11 @@ what the pick-ups do; everything that is a setting is one step away.** Gameplay, ``` Title Pause (during a run) ├── PLAY (Space; start the run) ├── RESUME (P / START; continues, cannon kept quiet) +├── RANKED (R; one player) ── RANKED PLAY page, see below ├── 1 PLAYER | 2 PLAYERS (keyboard; 1 / 2) ├── AUDIO ──┐ -├── AUDIO ───────────────┐ ├── CONTROLS ──┤ the same pages as on the title +├── HIGH SCORES (H) ── THIS WEEK | ALL TIME ├── CONTROLS ──┤ the same pages as on the title +├── AUDIO ───────────────┐ │ + ├── CONTROLS ───────────────┤ └── RETURN TO MENU (two presses; Esc goes straight there) ├── CO-OP (two players only) ── TWO-PLAYER OPTIONS └── POWER-UPS card ── POWER-UP GUIDE AUDIO: MUSIC on | off · MUSIC TRACK < > · MUSIC VOLUME - + · SOUND EFFECTS - + @@ -58,6 +61,15 @@ used by the keyboard and the controller alike. (a controller that was found but not given to a player says so in the top-left corner until it joins). - The **FULLSCREEN** pill (DOM, top right, touch mode) is unchanged and kept clear of every button. +## Ranked play and High Scores (leaderboard pass) + +The title screen has a green PLAY and a gold RANKED side by side, and HIGH SCORES in the row with AUDIO and CONTROLS. They are ordinary pages of the same menu kit: + +* `ranked` (RANKED PLAY): the rules in four lines including the time limit, the best verified score on this device, START RANKED RUN, HIGH SCORES, BACK. START asks the server for a challenge ("CONNECTING..."; BACK/Esc cancels); a failure replaces the page's content with a plain message and TRY AGAIN / PLAY NORMALLY / BACK. +* `scores` (HIGH SCORES): board tabs (`MenuChoice`, so Left/Right switch boards on a keyboard or D-pad), ten rows, PREVIOUS / BACK / NEXT. It is also opened from the ranked result page, inside the game scene's own menu view. +* `result` (game scene only, ranked runs): name field, SUBMIT SCORE, SKIP; then the verdict pages. The name field is a new widget, `MenuField`, whose text is a real DOM `` (`src/ui/nicknameInput.ts`). +* With two players chosen RANKED is disabled and says `1 PLAYER ONLY`. Full description, states and tests: `docs/leaderboard-backend.md` section 15. + ## Where each existing setting lives now | Setting | Was | Now | @@ -114,7 +126,7 @@ Without `navigator.vibrate` the TEST VIBRATION button is not offered and the pag | `src/ui/menu/widgets.ts` | Drawn pieces: `MenuButton`, `MenuStepper` (`- bar +`, `< name >`), `MenuChoice` (`[ ON \| OFF ]`), `PageKit` (owns what one page made). | | `src/ui/menu/menuView.ts` | Puts a controller on a scene: builds each page when it opens and destroys it when it closes, forwards the pointer. | | `src/ui/menu/context.ts` | `MenuContext`: what pages read and change (audio, haptics, input mode, movement, pads, setup). Title and pause build the same pages from it. | -| `src/ui/menu/pages/*.ts` | `title`, `audio`, `controls`, `coop`, `powerups`, `padLayout`, `pause`, plus `reference.ts` (key caps and touch icons) and `common.ts`. | +| `src/ui/menu/pages/*.ts` | `title`, `audio`, `controls`, `coop`, `powerups`, `padLayout`, `pause`, `ranked`, `scores`, `rankedResult`, plus `reference.ts` (key caps and touch icons) and `common.ts`. | | `src/ui/menu/controlHelp.ts`, `powerupInfo.ts` | The control reference and power-up text as pure data (unit tested against the real key schemes, `padToInput` and the sim constants). | | `src/scenes/StartScene.ts`, `GameScene.ts` | Own the menu view, route keys and controller buttons, start / resume / leave. | @@ -130,6 +142,7 @@ rebuilt when its content changes (player count, mode, a controller assigned) wit | Power-up text from the constants, the key / pad / touch reference against the real mappings, legend widths | `tests/menuContent.test.ts` | | Haptics default ON, saved OFF kept, junk, blocked storage, nothing written | `tests/haptics.test.ts` | | Browser: hierarchy, keys listed are the keys that work, AUDIO / CONTROLS / CO-OP navigation and persistence, pause submenus keep the run paused, Space / A / held laser and boost never fire on resume, taps never reach the game, 25 + 20 open / close rounds leak nothing, controller navigation, **an automated layout review of every page at 5 phone and 5 desktop sizes**, reduced motion | `npm run test:menu` (`scripts/menu.mjs`, screenshots in `scripts/.smoke-output/menu-*.png`) | +| Browser: ranked / High Scores / result pages with a real Worker and D1 (including gamepad and touch navigation of them) | `npm run test:ranked`, `npm run test:ranked:ui` | | Browser: the touch, keyboard, controller, music and co-op suites drive the new menus through `menuSnapshot()` / `pauseMenuSnapshot()` (the scene's debug hook lists every button's id, label and rectangle) | `npm run test:touch`, `test:input`, `test:gamepad`, `test:music`, `test:coop`, `test:browser`, `test:pages` | ## Known limits diff --git a/phaser-asteroids/index.html b/phaser-asteroids/index.html index fc3e977..1798df2 100644 --- a/phaser-asteroids/index.html +++ b/phaser-asteroids/index.html @@ -2,7 +2,7 @@ - + Asteroids