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
20 changes: 20 additions & 0 deletions .github/workflows/deploy-gh-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
# Full history: the frozen-rules guard below compares this commit with the base it would merge into.
fetch-depth: 0

- name: Set up Node.js
uses: actions/setup-node@v7
Expand All @@ -62,9 +65,22 @@ jobs:
- name: Typecheck
run: npm run typecheck

# Includes server/tests/rulesCompat.test.ts, the release compatibility gate: every rules version a distributed Android build
# plays is still registered, frozen engines match their pinned hashes, and the reference replays still give the recorded results
# (an unversioned gameplay change fails here). See phaser-asteroids/server/rules/README.md.
- name: Unit tests
run: npm test

# A frozen engine may be added but never edited, and dropped only after its support period. The unit tests above check files
# against their pinned hashes; this checks the hashes and release records themselves were not rewritten.
- name: Frozen replay engines guard
env:
BASE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || github.event.before }}
run: |
node --test scripts/rules-guard.test.mjs
if [ -z "$BASE" ] || [ "$BASE" = "0000000000000000000000000000000000000000" ]; then BASE=origin/main; fi
node scripts/rules-guard.mjs "$BASE"

- name: Build (typecheck + vite build)
env:
# Public Worker origin; set this repository Actions variable after backend verification.
Expand Down Expand Up @@ -92,6 +108,10 @@ jobs:
- name: Test production health verification (mock HTTP only)
run: node --test scripts/production-health.test.mjs

# Includes the check that the Android versionCode is recorded in server/rules/released.json with the rules it plays.
- name: Test the Android build checks (no Android SDK needed)
run: node --test scripts/build-android.test.mjs

- name: Upload build for deployment
if: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
uses: actions/upload-artifact@v7
Expand Down
19 changes: 12 additions & 7 deletions docs/leaderboard-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,11 @@ Indexes: partial board index `(rules_version, score DESC, completed_at ASC, id A

All JSON, all under `/api/v1`. Errors: `{"error":{"code":"…","message":"…", …}}`.

### `POST /runs` → 201
### `POST /runs?rules=1.2.0&schema=1` → 201

The query names the rules and replay schema the client plays (clients since 2026-11 always send it; it keeps the request CORS-simple).
A version the Worker supports is issued as asked; anything else, or no query, gets the current version. Anything in the body is ignored.
See [`phaser-asteroids/server/rules/README.md`](../phaser-asteroids/server/rules/README.md).

```json
{
Expand Down Expand Up @@ -258,7 +262,8 @@ 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, "timeLimitSeconds": 1200, "time": "…" }`
### `GET /health` → `{ "ok": true, "rulesVersion": "1.2.0", "schemaVersion": 1, "supportedRules": ["1.2.0"], "maxTicks": 72000, "timeLimitSeconds": 1200, "time": "…" }`
`rulesVersion` / `schemaVersion` are what a request without `?rules=` is issued; `supportedRules` lists every version this deployment verifies.
### `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, rulesVersion, completedAt, durationSeconds, endReason` (`game_over` or `time_limit`).
Expand All @@ -277,10 +282,10 @@ 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.
* `GAMEPLAY_RULES_VERSION` (`src/replay/constants.ts`) must change whenever physics, spawning, collision or scoring changes. The server verifies several versions side by side: each one is a frozen build of the engine in `phaser-asteroids/server/rules/<version>/`, registered in `server/src/engines.ts`, and chosen by the version stored with the run when it was issued. The replay header must match that version. The unit tests fail if gameplay changes without a bump (reference replays), and CI refuses to drop a version a distributed Android build still plays. Bump procedure, deployment order and retirement policy: [`phaser-asteroids/server/rules/README.md`](../phaser-asteroids/server/rules/README.md).
* 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).
* A rules bump deploys a Worker that verifies the old and the new version, so runs issued before the deploy still verify. Only retiring a version (after its support period) makes its remaining runs fail with `rules_mismatch`.

## 9. Weekly / all-time definitions

Expand All @@ -301,7 +306,7 @@ The extra API field is additive; replay schema and gameplay rules remain unchang

## 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.
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. The global submission budget is spent only after the run token has been checked (and the run is still open), so unauthenticated junk, which the per-client bucket still limits, cannot use it up for everyone. 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`.

Expand Down Expand Up @@ -374,7 +379,7 @@ Nothing above is a test against production Cloudflare infrastructure.

The existing Cloudflare account is `620de0810a6cf29710d9fedb3a966d6f`. Production D1 `asteroids-leaderboard` is `cf4833f7-5fc9-45ca-a767-750df108f1e9` (ENAM). These identifiers are public configuration, not credentials. The `DB` binding in `env.production` points to this database; `0001_init.sql` and `0002_time_limit.sql` are applied remotely. Immediately before the approved deployment, Cloudflare confirmed that the Worker did not exist, so no existing Worker was overwritten.

Production retains the 5,000 ms CPU cap, daily `17 7 * * *` UTC housekeeping, 20-minute ranked limit and `https://djblackett.github.io` CORS origin (origins have no repository path). Both secrets are declared required for production deployments. The API uses HTTPS on `workers.dev`; version preview URLs are disabled. GitHub Pages continues to host the game. The default D1 placeholder, local origins, `dev:lan`, `migrate:lan`, LAN proxy and `.wrangler/state-lan` remain separate from production.
Production retains the 5,000 ms CPU cap, daily `17 7 * * *` UTC housekeeping, 20-minute ranked limit and the `https://djblackett.github.io` and `https://spacearcade.davidandrea.ca` (Android app, see `phaser-asteroids/docs/android.md`) CORS origins (origins have no repository path). Both secrets are declared required for production deployments. The API uses HTTPS on `workers.dev`; version preview URLs are disabled. GitHub Pages continues to host the game. The default D1 placeholder, local origins, `dev:lan`, `migrate:lan`, LAN proxy and `.wrangler/state-lan` remain separate from production.

Preparation validation passed: frontend and backend typechecks, frontend production build, all 127 backend unit tests, all 32 real local Worker/D1 integration checks, production deployment dry-run with both secret bindings, and the existing LAN Chromium smoke test (ranked game, accepted replay, both boards and persistence after reload). The dry-run artifacts contain neither secret and no temporary plaintext upload file remains.

Expand Down Expand Up @@ -442,7 +447,7 @@ coordinated workflow above. The following records initial provisioning for a new

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).
3. Set `ALLOWED_ORIGINS` in `[env.production.vars]` (default `https://djblackett.github.io,https://spacearcade.davidandrea.ca`, the second being the Android app's origin; include a custom domain if used).
4. `npx wrangler d1 migrations apply asteroids-leaderboard --env production --remote`
5. Prepare `IP_HASH_SALT` and `ADMIN_TOKEN` securely as above. Obtain approval before any command that publishes the Worker, including `secret put`.
6. First deployment: use the helper's `Deploy` action above (or `npx wrangler deploy --env production --secrets-file <protected-file>`). Later code-only deployments preserve existing secrets. Note the `*.workers.dev` URL (or attach a custom domain).
Expand Down
2 changes: 1 addition & 1 deletion docs/release-preflight.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ Everything in this section is **for the owner to perform later; none was execute
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.
4. In `[env.production.vars]`, set exact HTTPS browser origins, comma-separated, without a path: `https://djblackett.github.io`, `https://spacearcade.davidandrea.ca` (the Android app; `server.hostname` in `phaser-asteroids/capacitor.config.ts`), 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.
Expand Down
6 changes: 6 additions & 0 deletions phaser-asteroids/.env.android
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Loaded ONLY by `vite build --mode android` (npm run build:android). Browser builds and GitHub Pages never read this file.
#
# The Android app talks to the production leaderboard Worker, always. scripts/build-android.mjs refuses to build if this is missing,
# not https, a loopback / private address, or contradicted by a different VITE_LEADERBOARD_API_URL in the shell environment, and
# checks afterwards that this exact origin is in the bundle. Public value (it ships inside every web build anyway).
VITE_LEADERBOARD_API_URL=https://asteroids-leaderboard.davejandrea.workers.dev
1 change: 1 addition & 0 deletions phaser-asteroids/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
node_modules/
dist/
dist-android/
*.log
scripts/.smoke-output/
.node/
Expand Down
13 changes: 13 additions & 0 deletions phaser-asteroids/android/.idea/deviceManager.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion phaser-asteroids/android/app/capacitor.build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ android {

apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {

implementation project(':capacitor-app')

}

Expand Down
3 changes: 3 additions & 0 deletions phaser-asteroids/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:screenOrientation="sensorLandscape"
android:exported="true">

<intent-filter>
Expand All @@ -38,4 +39,6 @@
<!-- Permissions -->

<uses-permission android:name="android.permission.INTERNET" />
<!-- navigator.vibrate (src/haptics) is silently ignored by WebView without it. A normal permission: no prompt. -->
<uses-permission android:name="android.permission.VIBRATE" />
</manifest>
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
package ca.davidandrea.spacearcade;

import android.os.Bundle;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import com.getcapacitor.BridgeActivity;

public class MainActivity extends BridgeActivity {}
public class MainActivity extends BridgeActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Capacitor's SystemBars plugin hides the bars (capacitor.config.ts) but has no option for how they come back. Without this a
// swipe from the edge mid-game brings them back for good and shrinks the playfield; with it they slide in over the game and
// hide again by themselves (the usual "immersive" behaviour for games).
WindowInsetsControllerCompat controller = WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
controller.setSystemBarsBehavior(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
}
}
3 changes: 3 additions & 0 deletions phaser-asteroids/android/app/src/main/res/values/styles.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
<!-- Black behind the game: SystemBars colours any inset band (camera cutout) with the window background, which is white in
the light theme otherwise. -->
<item name="android:windowBackground">@android:color/black</item>
</style>


Expand Down
3 changes: 3 additions & 0 deletions phaser-asteroids/android/capacitor.settings.gradle
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')

include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
26 changes: 25 additions & 1 deletion phaser-asteroids/capacitor.config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,33 @@
import type { CapacitorConfig } from '@capacitor/cli';

/**
* The Android app (see docs/android.md). The web game inside it is the normal build, made by `npm run build:android` into its own
* folder: the server-only replay verifier in dist/node is never packaged, and the production leaderboard URL is required.
*/
const config: CapacitorConfig = {
appId: 'ca.davidandrea.spacearcade',
appName: 'phaser-asteroids',
webDir: 'dist'
webDir: 'dist-android',
server: {
// The app's page is https://spacearcade.davidandrea.ca/ (served from the APK, never fetched from the internet). This is the Origin the
// leaderboard Worker sees, so it is listed in ALLOWED_ORIGINS (server/wrangler.toml). It is not `localhost`, so the game never
// treats the app as a development machine (src/ranked/api.ts). Changing it later would also lose saved settings and local scores,
// because localStorage belongs to the origin.
hostname: 'spacearcade.davidandrea.ca',
androidScheme: 'https',
},
plugins: {
// Capacitor 8's built-in system bars: hidden for the whole session (the game is landscape and fullscreen), light icons when the
// user swipes them in, and the real safe-area insets written to the page as --safe-area-inset-* (index.html, src/ui/touch.css).
SystemBars: {
hidden: true,
style: 'DARK',
insetsHandling: 'css',
// index.html's viewport has viewport-fit=cover. Without the hint the plugin assumes it does not until the page has rendered, and
// until then pads the WebView natively by the insets: an off-centre, smaller game at start, then one resize.
initialViewportFitValueHint: 'cover',
},
},
};

export default config;
Loading
Loading