Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions docs/leaderboard-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,17 +251,19 @@ Query: `limit` (1–100, default 10), `offset` (0–1000). Anything else → 400

```json
{
"scope": "weekly", "rulesVersion": "1.0.0",
"scope": "weekly", "rulesVersion": "1.1.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 } ]
"entries": [ { "id": "c649cb33-…", "rank": 1, "nickname": "Dave J", "score": 13959, "rulesVersion": "1.1.0", "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, "timeLimitSeconds": 1200, "time": "…" }`
### `POST /admin/scores/:id/visibility` — body `{"visible": false, "reason": "offensive"}`, `Authorization: Bearer <ADMIN_TOKEN>`. 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, endReason` (`game_over` or `time_limit`).
Public entries expose only `id, rank, nickname, score, rulesVersion, completedAt, durationSeconds, endReason` (`game_over` or `time_limit`).
`rulesVersion` on an entry is the stored rules version for that score, also included in score-detail and accepted-submission responses.
The page-level `rulesVersion` remains the server's current gameplay rules; all-time entries can belong to different versions.

## 7. Atomic, one-use submission

Expand All @@ -276,17 +278,27 @@ Tested: 12 simultaneous identical submissions and 5 simultaneous *different* one
## 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.
* Public display support is defined separately in `src/ranked/scoringEras.ts`: `1.0.0` = **V1**, `1.1.0` = **V2**. These are deliberate scoring eras, not software release numbers. Compatible technical versions can be explicitly added to an existing era; introduce a new era only for substantial scoring/difficulty changes. Unknown versions receive no invented label and are excluded from public boards.
* 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.
* **All-time:** all visible scores > 0 across explicitly supported scoring eras (V1 and V2). Every row displays its era, with a note that scores from different versions may not be directly comparable.
* **Weekly:** visible scores > 0 from the current scoring era only (V2 for current rules `1.1.0`), 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 unsupported-version entries are excluded; ranks of lower entries shift when an entry is hidden. Pages, totals, score details and post-submission ranks use the same eligibility rules.
* Zero-score runs are accepted (the run is finished, one-use) but never listed.

Historical personal bests remain valid across eras, including when their weekly rank is null. This device's remembered score IDs
and highlights are preserved. Stored rules metadata is refreshed from score detail and cached for offline labels; legacy cached
records with no version show `VERSION UNKNOWN` until refreshed. Visible unknown-version score details retain their raw version
and have null ranks. No dates or current-version defaults are used to guess an era.

The existing `scores.rules_version` column and indexes support these reads. No data rewrite, reset or migration is required.
After review and approval, the coordinated CI release on `main` deploys the Worker read/rank/API changes, verifies its health,
then publishes the frontend labels and personal-best handling. PR validation does not deploy either component.
The extra API field is additive; replay schema and gameplay rules remain unchanged. This does not enable V1 replay verification.

## 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.
Expand Down
3 changes: 3 additions & 0 deletions phaser-asteroids/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ and runs only those suites. After changing test scripts alone, `npm run test:fea
can reuse that build. Rebuild after source or asset changes. See [focused testing and timings](docs/test-performance.md).
Minor cosmetic UI edits use the existing Vite server and only relevant focused checks; two minutes is the ceiling.

`npm run test:feature -- history` checks the V1/V2 boards, labels, legacy personal bests and a verified V2 submission
against a temporary local Worker/D1 database and Chromium. It does not access production data.

For physical Android ranked testing against local Worker/D1, use the opt-in [LAN startup and S25 checklist](../docs/android-lan-testing.md).

Requires Node.js 20.19+ or 22.12+ (Vite 8's requirement; developed on Node 22.14).
Expand Down
2 changes: 2 additions & 0 deletions phaser-asteroids/docs/gameplay-experiment-a.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Historical record of the approved A baseline. Experiment B now adds explosions on top of these settings;
see `gameplay-experiment-b.md` for current behavior and the combined ranked reference result.
The historical ranking policy below has since been replaced: ALL TIME now supports labeled V1/V2 scores,
while THIS WEEK uses the current era. See `../../docs/leaderboard-backend.md` for that policy.

Rules `1.1.0`, replay schema still `1`. Initial values:

Expand Down
3 changes: 2 additions & 1 deletion phaser-asteroids/docs/test-performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ It stops at the first failed suite. Each child command has a ten-minute limit; e
Longer legacy suites can still use their existing commands. Run from `phaser-asteroids/`.

Available names: `smoke`, `keyboard`, `combat`, `coop`, `gamepad`, `touch`, `music`, `menu`,
`mobile-entry`, `pages`, `replay`, `ranked`, `ranked-ui`, `ranked-input`, `worker`.
`mobile-entry`, `pages`, `replay`, `ranked`, `ranked-ui`, `ranked-input`, `history`, `worker`.
Use `history` for the V1/V2 board, label and personal-best regression against an isolated local Worker/D1.
For a mobile-entry feature, select `mobile-entry`; this already covers PLAY, PRACTICE, touch readiness,
error paths and desktop entry. It is unnecessary for a cosmetic label edit.

Expand Down
114 changes: 114 additions & 0 deletions phaser-asteroids/scripts/historical-leaderboard.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Focused regression: production build + real local Worker/D1 + Chromium. No production data or services are used.
// Run after building: node scripts/historical-leaderboard.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { settleTitleInput } from './lib/menuWaits.mjs';
import { clickItem, menuItems, openTitle, rankedState, requireBuild, sceneTexts, sleep, startGameAndBrowser, WorkerStack } from './lib/rankedStack.mjs';

const GAME_PORT = Number(process.env.HISTORY_GAME_PORT ?? 4420);
const worker = new WorkerStack({ port: Number(process.env.HISTORY_API_PORT ?? 8798), gamePort: GAME_PORT, vars: { RANKED_TIME_LIMIT_SECONDS: '8' } });
const caption = 'SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE.';
const id = (i) => `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`;
const api = async (path) => {
const res = await fetch(`${worker.API}/api/v1${path}`);
assert.equal(res.status, 200);
return res.json();
};
async function waitText(page, scene, text) {
await page.waitForFunction(([key, expected]) => {
const walk = (list) => list.some((o) => o.visible && (o.type === 'Container' ? walk(o.list) : o.type === 'Text' && o.text === expected));
return walk(window.__game.scene.getScene(key).children.list);
}, [scene, text], { timeout: 15000 });
}
async function allTime(page) {
const zone = (await menuItems(page)).items.find((i) => i.id === 'scope').zones.find((z) => z.name === 'ALL TIME');
const point = await page.evaluate(([x, y]) => {
const c = document.querySelector('canvas').getBoundingClientRect();
return { x: c.left + x * c.width / 1280, y: c.top + y * c.height / 720 };
}, [zone.x + zone.w / 2, zone.y + zone.h / 2]);
await page.mouse.click(point.x, point.y);
await waitText(page, 'StartScene', 'Past Week');
}

requireBuild();
let game;
process.on('exit', () => worker.cleanup());
try {
const migration = worker.migrate();
assert.ok(migration.ok, migration.output);
await worker.start();
const now = Date.now();
const rows = [
['Old Champ_99!', 20000, '1.0.0', now, 'visible'], // historical rules, inside the current week
['Current Pilot', 1000, '1.1.0', now, 'visible'],
['Past Week', 30000, '1.1.0', now - 9 * 86400000, 'visible'],
['Hidden Pilot', 99999, '1.0.0', now, 'hidden'],
['Unknown Pilot', 99998, '9.0.0', now, 'visible'],
['Zero Pilot', 0, '1.0.0', now, 'visible'],
];
assert.ok(worker.exec(rows.map(([name, score, version, at, visibility], i) => {
const run = id(i + 100);
return `INSERT INTO runs (id, token_hash, seed, rules_version, config_json, created_at, expires_at, status, finished_at, score_id)
VALUES ('${run}', 'x', 1, '${version}', '{}', ${at - 60000}, ${at + 3600000}, 'accepted', ${at}, '${id(i)}');
INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms, visibility)
VALUES ('${id(i)}', '${run}', ${score}, '${name}', ${at}, '${version}', 3600, 60000, '${visibility}');`;
}).join('\n')));
const board = await api('/leaderboard/all-time');
assert.equal(board.total, 3);
assert.deepEqual(board.entries.map((e) => [e.id, e.rank, e.rulesVersion]), [[id(2), 1, '1.1.0'], [id(0), 2, '1.0.0'], [id(1), 3, '1.1.0']]);
const weekly = await api('/leaderboard/weekly');
assert.equal(weekly.total, 1);
assert.equal(weekly.entries[0].id, id(1));
assert.deepEqual((await api(`/scores/${id(0)}`)).ranks, { allTime: 2, weekly: null });
console.log('PASS real Worker: mixed-era ordering, counts, exclusions and historical detail ranks');

game = await startGameAndBrowser(GAME_PORT);
const context = await game.browser.newContext({ viewport: { width: 1280, height: 720 } });
await context.addInitScript((best) => localStorage.setItem('asteroids.rankedScores', JSON.stringify([best])), {
id: id(0), score: 20000, at: new Date(now).toISOString(), nickname: 'Old Champ_99!', // legacy cache: no rulesVersion
});
const page = await openTitle(context, game.GAME, { api: worker.API });
await clickItem(page, 'scores');
await waitText(page, 'StartScene', 'Current Pilot');
const bestLine = 'YOUR BEST VERIFIED SCORE: 20,000 V1 (Old Champ_99!)';
await waitText(page, 'StartScene', bestLine);
let texts = await sceneTexts(page, 'StartScene');
assert.ok(!texts.includes('Old Champ_99!') && texts.includes('V2'));
await allTime(page);
texts = await sceneTexts(page, 'StartScene');
assert.ok(texts.includes(caption) && texts.includes('V1') && texts.includes('V2') && texts.includes('YOU'));
const cached = await page.evaluate(() => JSON.parse(localStorage.getItem('asteroids.rankedScores')));
assert.equal(cached[0].rulesVersion, '1.0.0');
fs.mkdirSync('scripts/.smoke-output', { recursive: true });
await page.screenshot({ path: 'scripts/.smoke-output/historical-leaderboard-desktop.png' });
await page.setViewportSize({ width: 844, height: 390 });
await page.screenshot({ path: 'scripts/.smoke-output/historical-leaderboard-phone.png' });
console.log('PASS browser: weekly/current era, mixed labels, comparison note, YOU highlight and legacy personal-best refresh');

await page.setViewportSize({ width: 1280, height: 720 });
await settleTitleInput(page);
await page.keyboard.press('Escape');
await page.waitForFunction(() => window.__game.scene.getScene('StartScene').menuSnapshot()?.page === 'title');
await settleTitleInput(page);
await clickItem(page, 'ranked');
await page.waitForFunction(() => window.__game.scene.getScene('StartScene').menuSnapshot()?.page === 'ranked');
await settleTitleInput(page);
await clickItem(page, 'start');
await page.waitForFunction(() => window.__game.scene.getScene('GameScene').resultMenuSnapshot()?.page === 'result', null, { timeout: 30000 });
await sleep(900); // the result menu ignores input briefly after the run ends
await page.locator('.nick-input').fill('New Pilot');
await clickItem(page, 'submit', 'result');
await waitText(page, 'GameScene', 'SCORE VERIFIED!');
texts = await sceneTexts(page, 'GameScene');
assert.ok(texts.includes('V2') && texts.includes('YOUR BEST: 20,000 V1') && !texts.includes('NEW PERSONAL BEST!'));
const accepted = (await rankedState(page)).outcome;
assert.equal(accepted.score.rulesVersion, '1.1.0');
assert.deepEqual((await api(`/scores/${accepted.score.id}`)).ranks, accepted.ranks);
assert.equal((await page.evaluate(() => JSON.parse(localStorage.getItem('asteroids.rankedScores'))))[0].id, id(0));
assert.deepEqual(page.problems, []);
console.log('PASS verified V2 submission: result labels, historical personal best and consistent server ranks');
await context.close();
} finally {
await game?.close();
worker.cleanup();
}
2 changes: 1 addition & 1 deletion phaser-asteroids/scripts/ranked-browser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ try {
const allTime = scopeZones.find((z) => z.name === 'ALL TIME');
const cp = await page.evaluate(([x, y]) => { const c = document.querySelector('canvas').getBoundingClientRect(); return { x: c.left + (x * c.width) / 1280, y: c.top + (y * c.height) / 720 }; }, [allTime.x + allTime.w / 2, allTime.y + allTime.h / 2]);
await page.mouse.click(cp.x, cp.y);
await waitText(page, 'GameScene', /^BEST VERIFIED SCORES OF ALL TIME$/);
await waitText(page, 'GameScene', /^SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE\.$/);
await waitText(page, 'GameScene', new RegExp(`^${NICK}$`));
check('switching to ALL TIME shows the same entry', true);
check('the player\'s best verified score is shown under the table', (await sceneTexts(page, 'GameScene')).some((t) => t.startsWith('YOUR BEST VERIFIED SCORE:')));
Expand Down
6 changes: 3 additions & 3 deletions phaser-asteroids/scripts/ranked-ui.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ti
await waitText(page, 'StartScene', /^Old 4$/);
texts = await sceneTexts(page, 'StartScene');
check('ALL TIME includes last week\'s scores and ranks them above (24 scores = 3 pages)', texts.includes('Old 4') && texts.includes('PAGE 1 / 3') && texts.indexOf('Old 4') < texts.indexOf('Week 01'));
check('...with a caption that is not a week', texts.includes('BEST VERIFIED SCORES OF ALL TIME') && !texts.some((t) => t.startsWith('WEEK OF')));
check('...with a caption that is not a week', texts.includes('SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE.') && !texts.some((t) => t.startsWith('WEEK OF')));
await page.keyboard.press('Escape');
await ctx.close();
}
Expand Down Expand Up @@ -195,7 +195,7 @@ INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ti
await tap(BTN.UP);
check('D-pad Up reaches the board tabs', (await focus()) === 'scope', await focus());
await tap(BTN.RIGHT);
await waitText(page, 'StartScene', /^BEST VERIFIED SCORES OF ALL TIME$/);
await waitText(page, 'StartScene', /^SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE\.$/);
check('D-pad Right switches THIS WEEK to ALL TIME', true);
await tap(BTN.LEFT);
await waitText(page, 'StartScene', /^WEEK OF /);
Expand Down Expand Up @@ -455,7 +455,7 @@ INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ti
const k = scale;
const c = await centre('canvas');
await finger.tap(c.left + (tab.x + tab.w / 2) * k, c.top + (tab.y + tab.h / 2) * k);
await waitText(page, 'StartScene', /^BEST VERIFIED SCORES OF ALL TIME$/);
await waitText(page, 'StartScene', /^SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE\.$/);
check('a finger switches THIS WEEK / ALL TIME', true);
await tapItem('back', 'title');
await tapItem('ranked', 'title');
Expand Down
1 change: 1 addition & 0 deletions phaser-asteroids/scripts/test-feature.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const suites = {
'mobile-entry': 'scripts/mobile-entry.mjs', pages: 'scripts/pages-check.mjs',
replay: 'scripts/replay-browser.mjs', ranked: 'scripts/ranked-browser.mjs',
'ranked-ui': 'scripts/ranked-ui.mjs', 'ranked-input': 'scripts/ranked-input.mjs',
history: 'scripts/historical-leaderboard.mjs',
worker: 'server/scripts/worker-e2e.mjs',
};
const args = process.argv.slice(2).filter((arg) => arg !== '--');
Expand Down
Loading
Loading