diff --git a/.github/workflows/README.md b/.github/workflows/README.md
index b80bb7b..1989cc1 100644
--- a/.github/workflows/README.md
+++ b/.github/workflows/README.md
@@ -2,15 +2,28 @@
## deploy-gh-pages.yml
-Builds the Phaser game in `phaser-asteroids/` and publishes it as the GitHub Pages site,
-. It is the only workflow that deploys to Pages.
+Builds the Phaser game in `phaser-asteroids/`, deploys and verifies its production Cloudflare Worker,
+then publishes the already-built GitHub Pages site, .
+It is the only release workflow; both deployments use the same commit.
-- **Push to `main`** touching `phaser-asteroids/**` (or this workflow): validate, then deploy.
+- **Push to `main`** touching `phaser-asteroids/**` (or this workflow): validate, deploy Worker, verify health/versions, then deploy Pages.
- **Pull request:** validate only.
- **Manual run:** Actions → "Deploy to GitHub Pages" → Run workflow. Deploys only from `main`.
-Validation (blocks deployment): `npm ci`, typecheck, unit tests, production build, and a headless-Chrome check of the build
-(`phaser-asteroids/scripts/pages-check.mjs`).
+Validation (blocks deployment): `npm ci`, typecheck, unit tests (including server tests), production build,
+headless-Chrome check (`phaser-asteroids/scripts/pages-check.mjs`), locked server install and server typecheck,
+and mocked tests of the production health gate. Full browser suites remain optional.
+
+Set the repository Actions **secret** `CLOUDFLARE_API_TOKEN` to a token with **Editor access only to the existing
+`asteroids-leaderboard` Worker** in account `620de0810a6cf29710d9fedb3a966d6f`. No D1 access is needed just to deploy
+the existing binding. The account ID is already in `wrangler.toml`. Never use a Global API Key.
+Exact token setup, verification, manual release and recovery instructions are in the
+[deployment guide](../../phaser-asteroids/docs/deployment.md#one-time-setup-repository-owner).
+
+The whole release is serialized without cancelling active runs. Stale commits fail before Worker deployment.
+Worker deploy/health failures block Pages. If Pages fails after the Worker succeeds, the Worker remains updated;
+rerun **all jobs on current main** (or revert on main to restore both). Do not rerun only Pages.
+Production D1 migrations are explicit manual operations, never part of this workflow.
The build requires the repository Actions variable `VITE_LEADERBOARD_API_URL` (public HTTPS Worker origin, without `/api/v1`) and fails before building if it is missing or empty. The production value is `https://asteroids-leaderboard.davejandrea.workers.dev`. Backend `IP_HASH_SALT` and `ADMIN_TOKEN` are Cloudflare secrets and must never enter the frontend build; see [the backend deployment guide](../../docs/leaderboard-backend.md#14-production-setup-and-deployment).
diff --git a/.github/workflows/deploy-gh-pages.yml b/.github/workflows/deploy-gh-pages.yml
index 7f789ec..841b15c 100644
--- a/.github/workflows/deploy-gh-pages.yml
+++ b/.github/workflows/deploy-gh-pages.yml
@@ -1,6 +1,6 @@
name: Deploy to GitHub Pages
-# Publishes the Phaser 4 port in phaser-asteroids/ as the whole GitHub Pages site, at the repository root:
+# Releases the production Worker, verifies compatibility, then publishes the Phaser 4 port to GitHub Pages:
# https://djblackett.github.io/asteroids-bootdev/
#
# Pull requests only run the validation job. Nothing is deployed unless the run is on `main`; a manual run from
@@ -26,6 +26,12 @@ on:
permissions:
contents: read
+# Hold the release lock through validation, Worker deployment/verification AND Pages publication.
+# PRs and non-main manual runs have separate groups. Never cancel a release halfway through.
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: false
+
jobs:
# Blocks deployment: typecheck, unit tests, production build, and a real-browser check of that build served
# at the Pages URL path (/asteroids-bootdev/) and at "/". The larger browser suites run separately (browser-suites.yml).
@@ -33,6 +39,8 @@ jobs:
name: Phaser - validate and build
runs-on: ubuntu-latest
timeout-minutes: 15
+ outputs:
+ artifact_name: phaser-site-${{ github.run_attempt }}
defaults:
run:
working-directory: phaser-asteroids
@@ -75,36 +83,111 @@ jobs:
google-chrome --version
node scripts/pages-check.mjs
+ # npm test above already includes server/tests; do not run the same suite twice.
+ - name: Install locked server dependencies and typecheck
+ run: |
+ npm ci --prefix server
+ npm --prefix server run typecheck
+
+ - name: Test production health verification (mock HTTP only)
+ run: node --test scripts/production-health.test.mjs
+
- name: Upload build for deployment
if: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
uses: actions/upload-artifact@v7
with:
- name: phaser-site
+ # Preserve earlier attempts' artifacts and avoid immutable-name conflicts on reruns.
+ name: phaser-site-${{ github.run_attempt }}
path: phaser-asteroids/dist
if-no-files-found: error
retention-days: 7
+ worker:
+ name: Deploy and verify production Worker
+ needs: phaser
+ if: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ release_attempt: ${{ steps.verification.outputs.release_attempt }}
+ defaults:
+ run:
+ working-directory: phaser-asteroids/server
+ steps:
+ - name: Checkout the validated commit
+ uses: actions/checkout@v7
+ with:
+ ref: ${{ github.sha }}
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v7
+ with:
+ node-version: 22
+ cache: npm
+ cache-dependency-path: phaser-asteroids/server/package-lock.json
+
+ - name: Install locked Wrangler dependency
+ run: npm ci
+
+ - name: Download the validated build (includes shared replay versions)
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.phaser.outputs.artifact_name }}
+ path: phaser-asteroids/dist
+
+ # Concurrency does not guarantee commit order. Reject old queued runs and old reruns.
+ # Once this passes, finish BOTH deployments even if main advances while releasing.
+ - name: Refuse a stale release
+ run: |
+ latest=$(git ls-remote --exit-code origin refs/heads/main | cut -f1)
+ if [ "$latest" != "$GITHUB_SHA" ]; then
+ echo "::error::This commit is no longer main. Run the release workflow on current main instead."
+ exit 1
+ fi
+
+ - name: Deploy the existing production Worker
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ run: |
+ if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
+ echo "::error::Set the repository Actions secret CLOUDFLARE_API_TOKEN before releasing."
+ exit 1
+ fi
+ npx wrangler deploy --env production
+
+ - name: Verify production health and replay compatibility
+ id: verification
+ run: |
+ node ../scripts/production-health.mjs
+ echo "release_attempt=$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"
+
deploy:
name: Deploy to GitHub Pages
- needs: phaser
+ needs: [phaser, worker]
if: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
pages: write # publish to Pages
id-token: write # prove to Pages that the deployment comes from this workflow
- # Deployments are serialised and never cancelled half-way, so overlapping pushes cannot corrupt publication.
- concurrency:
- group: pages
- cancel-in-progress: false
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
+ # A rerun of only Pages would otherwise reuse a prior attempt's successful Worker job.
+ - name: Require Worker verification in this release attempt
+ env:
+ WORKER_ATTEMPT: ${{ needs.worker.outputs.release_attempt }}
+ run: |
+ if [ "$WORKER_ATTEMPT" != "$GITHUB_RUN_ATTEMPT" ]; then
+ echo "::error::Re-run all jobs so the Worker and health gate run in this attempt before Pages."
+ exit 1
+ fi
+
- name: Download the build
uses: actions/download-artifact@v8
with:
- name: phaser-site
+ name: ${{ needs.phaser.outputs.artifact_name }}
path: site
- name: Check the assembled site
@@ -120,8 +203,11 @@ jobs:
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v5
with:
+ name: github-pages-${{ github.run_attempt }}
path: site
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v5
+ with:
+ artifact_name: github-pages-${{ github.run_attempt }}
diff --git a/docs/leaderboard-backend.md b/docs/leaderboard-backend.md
index 9f4371f..8164b89 100644
--- a/docs/leaderboard-backend.md
+++ b/docs/leaderboard-backend.md
@@ -1,6 +1,6 @@
# Phaser Asteroids — Secure Online Leaderboard (Phase 2 backend, Phase 3 player experience)
-> **Status:** Production Worker deployed with approval and verified on 2026-10-22 at **https://asteroids-leaderboard.davejandrea.workers.dev**. Production D1 has both migrations applied and both Worker secrets are configured. Frontend GitHub Actions wiring is prepared but has not been published.
+> **Status:** Production Worker deployed with approval and verified on 2026-10-22 at **https://asteroids-leaderboard.davejandrea.workers.dev**. Production D1 has both migrations applied and both Worker secrets are configured. The coordinated Worker + Pages release workflow is prepared for review; see the [deployment guide](../phaser-asteroids/docs/deployment.md) for required CI credentials and recovery.
> 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)).
@@ -399,13 +399,34 @@ Set-Clipboard -Value ''
On other platforms, use a password manager and Wrangler's `--secrets-file` with a protected, temporary JSON or dotenv file. For later secret rotation, `wrangler secret put IP_HASH_SALT --env production` and `wrangler secret put ADMIN_TOKEN --env production` prompt without putting values in shell history. **These commands create a new deployment**, so use them only after deployment is approved. Changing the IP salt resets per-IP rate-limit identities; changing the admin token invalidates the old moderation credential. Do not rotate either accidentally.
-### GitHub Pages build wiring (prepared only)
+### Coordinated GitHub Actions release
-`.github/workflows/deploy-gh-pages.yml` supplies `${{ vars.VITE_LEADERBOARD_API_URL }}` to the existing production build step. For the separately approved frontend release, set the **repository Actions variable** `VITE_LEADERBOARD_API_URL` to `https://asteroids-leaderboard.davejandrea.workers.dev`, without `/api/v1`. The repository variable was not changed during backend deployment. This is a public URL, not a secret. Use a repository variable because the build job does not run in the `github-pages` environment. `IP_HASH_SALT` and `ADMIN_TOKEN` belong only in Cloudflare Worker secrets.
+`.github/workflows/deploy-gh-pages.yml` validates and builds the frontend (including server unit tests), typechecks the
+server, deploys the existing Worker with locked Wrangler, verifies public health against the shared rules/schema
+versions in that build, then publishes the same frontend artifact. Worker deploy/verification failure blocks Pages.
+Releases are serialized through both deployments and stale commits are rejected. PRs only validate.
-Publishing the frontend is a separate release from backend setup. The GitHub Actions build fails if `VITE_LEADERBOARD_API_URL` is missing or empty, preventing publication with Ranked Play disabled. This guard applies only to the workflow; ordinary local builds can still omit the variable. The opt-in LAN config still selects its same-origin local proxy even when a production build URL exists.
+Before merging/enabling this workflow, set the **repository Actions secret** `CLOUDFLARE_API_TOKEN` to a token with
+Editor access scoped to this existing Worker, as detailed in the
+[one-time setup](../phaser-asteroids/docs/deployment.md#one-time-setup-repository-owner). Deploying the existing D1
+binding requires no D1 data permission. The account ID is already configured in `wrangler.toml`. Code-only deployments
+preserve the existing Cloudflare-managed `IP_HASH_SALT` and `ADMIN_TOKEN`; neither secret belongs in GitHub or Vite.
-### General deployment checklist
+Set the **repository Actions variable** `VITE_LEADERBOARD_API_URL` to
+`https://asteroids-leaderboard.davejandrea.workers.dev`, without `/api/v1`. This public URL is supplied to the existing
+production build, which fails if it is missing or empty. Use a repository variable because the build job does not use
+the `github-pages` environment. Ordinary local builds may omit it; the opt-in LAN config still selects its local proxy.
+
+No production migrations are run by CI. V1/V2 score history needs no new migration. Schema changes are separately
+reviewed, controlled operations; keep migration credentials out of the release workflow. Existing scores and the
+`env.production.DB` binding are preserved. For verification, partial releases, manual fallback and rollback, use the
+[release/recovery guide](../phaser-asteroids/docs/deployment.md#rolling-back). These changes do not configure repository
+settings, commit, push or publish anything by themselves.
+
+### Initial provisioning reference (already completed; not a release checklist)
+
+Do not repeat database creation, first-deployment secret upload or migrations for a routine release. Use the
+coordinated workflow above. The following records initial provisioning for a new installation only.
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`.
@@ -419,7 +440,11 @@ Publishing the frontend is a separate release from backend setup. The GitHub Act
**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.
+**Rollback:** Prefer reverting the change on `main` so the workflow restores both frontend and Worker together.
+For an urgent Worker-only rollback after a partial release, first stop competing releases and confirm the version
+matches the currently published client; see the [recovery procedure](../phaser-asteroids/docs/deployment.md#rolling-back).
+Code rollback does not require D1 restore or migration changes. Removing `VITE_LEADERBOARD_API_URL` from a local build
+disables ranked play, but the Actions production build deliberately rejects an empty value.
## 15. The player-facing experience (Phase 3)
diff --git a/phaser-asteroids/docs/deployment.md b/phaser-asteroids/docs/deployment.md
index af9c92a..3dd780c 100644
--- a/phaser-asteroids/docs/deployment.md
+++ b/phaser-asteroids/docs/deployment.md
@@ -1,7 +1,7 @@
# Deploying to GitHub Pages
-The Phaser game is a static site (`npm run build` → `phaser-asteroids/dist/`): no server, no backend, nothing to
-install for players. GitHub Actions builds it and publishes it as the repository's GitHub Pages site.
+The Phaser game is a static site (`npm run build` → `phaser-asteroids/dist/`), with a separate Cloudflare Worker + D1
+for ranked play. GitHub Actions validates both, deploys and checks the Worker, then publishes the built site to Pages.
**URL:**
@@ -15,7 +15,7 @@ game; `BUILD_WEB.md` and `pygbag` still work locally if you want it).
| Trigger | What runs |
| --- | --- |
-| Push to `main` that changes `phaser-asteroids/**` or the workflow file | Validate, then deploy |
+| Push to `main` that changes `phaser-asteroids/**` or the workflow file | Validate, deploy Worker, verify compatibility, then publish Pages |
| Pull request to `main` | Validate only. No Pages permissions are used, nothing is published. |
| Manual run (**Actions → Deploy to GitHub Pages → Run workflow**) | Validate; deploys only when run on `main` |
@@ -26,15 +26,41 @@ Changes to the Python game or to root docs do not deploy.
as the site root at `/asteroids-bootdev/` (the Pages URL path) **and** at `/` (a custom domain), and checks: no console or
page errors, no HTTP errors, all 10 start-up audio files load from under that path, the two extra soundtracks are *not* requested at start-up but load from under it when picked (and a saved choice plays after a reload), nothing is requested outside it, the title screen
renders in WebGL, a one-player game starts with the music playing, `?keydebug` loads, and the Gamepad API is available.
-It fails (it is never skipped) if Chrome is missing. The deploy job then publishes that same `dist/` (it is passed on as an
-artifact, not rebuilt).
+It fails (it is never skipped) if Chrome is missing. `npm test` includes `server/tests`, so those focused server tests
+are already a release gate. After the browser check, the job installs locked server dependencies, runs the separate
+server typecheck, and runs mocked tests of the production health gate.
+
+The `worker` job depends on successful validation, checks out that run's exact commit, installs the server's locked
+Wrangler, and downloads that same build. Immediately before deploying, it checks the current `main` SHA; stale queued
+runs and old reruns fail without deploying. It runs `npx wrangler deploy --env production` from
+`phaser-asteroids/server`, using the existing account, Worker, D1 binding and Cloudflare-managed secrets.
+
+Next, `scripts/production-health.mjs` makes only a read-only GET to
+. It requires HTTP success, `ok: true`, and exact
+`rulesVersion` / `schemaVersion` matches with `GAMEPLAY_RULES_VERSION` / `REPLAY_SCHEMA_VERSION` exported by the
+build's `dist/node/index.js`. These come from shared `src/replay/constants.ts`; there is no separate CI version.
+Exact schema equality follows the existing replay compatibility policy. It attempts at most five requests, each
+with a 10-second timeout, waiting five seconds between failures. Logs show expected versions and failure reasons.
+It never creates challenges or scores. This checks Worker compatibility, not D1 connectivity; an optional read-only
+`GET /api/v1/leaderboard/all-time?limit=1` can confirm the database separately.
+
+The `deploy` job requires both `phaser` and `worker` to succeed, then publishes the same `dist/` artifact without
+rebuilding. A Worker deployment or health failure prevents frontend publication. The Worker deploys on every release,
+including frontend-only changes. Pull requests and manual runs from other branches validate only and receive no token.
**Do not block deployment:** the larger browser suites (smoke, keyboard, combat, co-op, simulated-gamepad). Run them
from **Actions → Phaser browser suites → Run workflow**, or locally (`npm run test:browser`, `test:input`, `test:combat`,
`test:coop`, `test:gamepad`; Chrome or Edge required).
-The deploy job uses the `github-pages` environment and a `pages` concurrency group that never cancels a running
-deployment, so overlapping pushes are serialised. Only that job has `pages: write` / `id-token: write`.
+Workflow-level concurrency serializes the entire release on `main`, with `cancel-in-progress: false`. The lock covers
+validation through Worker verification and Pages publication; other branches and PRs use separate groups. GitHub may
+replace a pending run when another arrives and does not guarantee commit order, hence the stale-SHA check. Once the
+Worker deployment starts, the run finishes both deployments even if `main` advances; the newer release waits.
+An old run cannot overwrite a newer successful release. Pages also requires the Worker's successful health check
+to come from the current run attempt, blocking a Pages-only rerun that would reuse an old Worker result. Use
+**Re-run all jobs** so the Worker and health gate execute again under the same lock. Avoid manual deployments while Actions is releasing.
+The Pages job retains the `github-pages` environment and is the only job with `pages: write` / `id-token: write`.
+Build and Pages artifact names include the run attempt, so retries keep previous artifacts without upload-name conflicts.
> The workflow deliberately has no path filter on `pull_request`. If you ever mark it a *required* status check, a
> path-filtered workflow would leave PRs that don't touch those paths waiting forever.
@@ -44,19 +70,48 @@ deployment, so overlapping pushes are serialised. Only that job has `pages: writ
1. **Settings → Pages → Build and deployment → Source: GitHub Actions.** (The repository already publishes from an
Actions workflow, so this is probably set; confirm it.)
2. **Settings → Environments → github-pages**: if *Deployment branches* is restricted, `main` must be allowed.
-3. Push to `main` (touching `phaser-asteroids/**` or the workflow), or run the workflow manually on `main`.
-
-The first successful deployment **replaces** the existing Python (pygbag) site completely.
+3. In Cloudflare's dashboard, open **Account API tokens → Create Token** for account
+ `620de0810a6cf29710d9fedb3a966d6f`. Create a custom token for GitHub Actions. Under Workers permissions choose
+ **Editor**, scoped to the existing Worker **asteroids-leaderboard**, not all Workers. Do not select Admin.
+ [Cloudflare's current Workers permission guide](https://developers.cloudflare.com/workers/authorization/workers/)
+ specifies Editor for deploying an existing Worker and says existing D1 bindings need no separate D1 permissions.
+ This Worker uses `workers.dev`, so no zone/routes permission is required. Do not grant D1 Edit, KV, R2, account-wide
+ Workers access or use a Global API Key. Keep any separate migration credential out of this release workflow.
+4. **Repository Settings → Secrets and variables → Actions → Secrets → New repository secret**:
+ name `CLOUDFLARE_API_TOKEN`, value the token. It is supplied only to the Worker deploy step. The production account ID
+ is already in `server/wrangler.toml`, so no `CLOUDFLARE_ACCOUNT_ID` secret or variable is needed. Missing credentials
+ fail explicitly; there is no login fallback. Do not add `IP_HASH_SALT` or `ADMIN_TOKEN` to GitHub: the existing
+ Cloudflare secrets remain attached on code-only deployments. Do not run the first-deployment secret helper again.
+5. Under **Actions → Variables**, set the repository variable `VITE_LEADERBOARD_API_URL` to
+ `https://asteroids-leaderboard.davejandrea.workers.dev` (no `/api/v1`). This public URL is the only backend value
+ supplied to Vite. It is a repository variable because validation does not use the `github-pages` environment.
+6. Before the initial merge, wait for any runs of the previous workflow to finish (it locked only Pages).
+ Review and merge the workflow changes only when ready to enable releases. A qualifying push to `main`, including
+ the merge containing this workflow, automatically releases both services. There is no additional enable switch.
+ Without the token, validation may succeed but Worker deployment fails and Pages stays unchanged. Do not merge
+ merely to test deployment; configure the credentials and review the implementation first.
+
+Production Worker, secrets and D1 already exist. Do not recreate them or reapply schema migrations for routine releases.
## Finding the deployment URL
The `Deploy to GitHub Pages` job summary and the run's **github-pages** environment link show it; so does
**Settings → Pages**. History is under the repository's **Deployments** (right-hand sidebar).
+To verify a release, confirm all three jobs succeeded for the intended commit. The Worker job logs its Cloudflare
+deployment/version ID and the health gate's expected and observed versions. Open the health URL above and the Pages
+site; hard refresh if assets are cached. No production scores are submitted by automation.
+
## Troubleshooting a failed deployment
-- **Which job failed?** `Phaser - validate and build`: a real problem; run the same commands locally (`npm ci`,
- `npm run typecheck`, `npm test`, `npm run test:pages`). `Deploy to GitHub Pages`: see below.
+- **Which job failed?** `Phaser - validate and build`: run the same commands locally (`npm ci`,
+ `npm run typecheck`, `npm test`, `npm run test:pages`, then server install/typecheck).
+- **Worker deploy fails:** check the missing-secret diagnostic or Wrangler's permission/configuration error. Do not
+ broaden the token to Admin or D1 Edit as a workaround. Check its account and Worker scope. Pages is blocked.
+- **Health gate fails:** logs show HTTP, JSON, network or version errors. Check Cloudflare's deployed version and the
+ shared versions in this commit. After fixing the issue, run all jobs on current `main`. Pages is blocked; a successful
+ Worker upload may already have changed production even if this step fails. See recovery below.
+- **Stale release rejected:** run the workflow on current `main`; rerunning the old commit will keep failing.
- **`Get Pages site failed` / `HttpError: Not Found` in Configure Pages:** Pages isn't enabled with Source set to GitHub Actions.
- **`Deployment request failed … 404` or environment protection rules:** *Settings → Environments → github-pages* doesn't allow the branch.
- **Browser check fails only in CI:** open the step log; the failing check names the URL. A Chrome start-up error
@@ -97,12 +152,70 @@ GitHub Pages is HTTPS, a secure context, which the Gamepad API requires.
## Rolling back
-Pages keeps no history of its own; roll back by redeploying a known-good commit:
-
-- **Fastest:** **Actions → Deploy to GitHub Pages**, open the last good *successful* run on `main`, **Re-run all jobs**. That
- rebuilds from that run's commit and publishes it. (A re-run keeps that run's commit, not today's `main`.)
-- **Durable:** `git revert ` and push to `main`; the workflow deploys the reverted tree.
-- To take the site down entirely: **Settings → Pages → Unpublish site**.
+If Worker deployment/verification fails, Pages remains at its prior version. Wrangler failures can happen after an
+upload, so inspect Cloudflare before assuming the Worker is unchanged. If the Worker succeeds but Pages fails,
+**the new Worker stays live and the old frontend stays published**; there is no automatic rollback. Ranked play may
+temporarily reject mismatched clients. Casual play remains available. An older browser session can also retain old
+rules after a successful release; refreshing loads the new client, and a run in progress across a rules update may
+be rejected. This workflow does not introduce multi-version verification.
+
+- **Recover forward:** fix credentials, Pages settings or the underlying failure. If the failed commit is still `main`,
+ choose **Re-run all jobs** on its run; otherwise **Run workflow** on current `main`. This redeploys and rechecks the
+ Worker before Pages, even if the first Worker deployment succeeded. Do not choose only the failed Pages job.
+- **Restore previous behavior:** revert the bad change(s) onto `main` and push after review. The resulting new commit
+ releases both the known-good Worker code and frontend. An old successful run is deliberately rejected by the stale
+ check; do not use it to roll back just one service.
+- **Urgent partial-release recovery:** after disabling the workflow and waiting for any active release to finish, an
+ operator can use `npx wrangler rollback --env production` from `phaser-asteroids/server` (or the Cloudflare dashboard)
+ to restore the known-good Worker version matching the currently published frontend. Confirm the chosen version and
+ its health response. Then prepare a matching revert on `main` before re-enabling releases. No D1 restore is needed
+ for a code rollback. To take the frontend down entirely: **Settings → Pages → Unpublish site**.
+
+## Manual release when Actions is unavailable
+
+Disable the release workflow and wait for any active run to finish before deploying manually. Use a clean checkout
+of one reviewed commit for both services, with Node 22 and Chrome/Edge installed. Set the public
+`VITE_LEADERBOARD_API_URL` environment variable as above, then from `phaser-asteroids/` run:
+
+```sh
+npm ci
+npm run typecheck
+npm test
+npm run build
+node scripts/pages-check.mjs
+npm ci --prefix server
+npm --prefix server run typecheck
+node --test scripts/production-health.test.mjs
+cd server
+# Authenticate locally with wrangler login, or a securely injected scoped CLOUDFLARE_API_TOKEN.
+npx wrangler deploy --env production
+node ../scripts/production-health.mjs
+```
+
+Stop if any command fails. Preserve the resulting `dist/`; publish exactly that directory only after health succeeds.
+GitHub Pages currently uses Actions as its publishing source, so a complete Pages release cannot use this workflow
+during an Actions outage. Branch-based Pages publishing also uses GitHub's build/deployment infrastructure and may
+be affected by the same outage. Prefer leaving the current release in place until Actions recovers. If branch publishing
+is available and a release is urgent, temporarily
+set **Settings → Pages → Source → Deploy from a branch**, choose a dedicated publishing branch and `/(root)`, and
+publish this same `dist/` at that branch's root, including an empty `.nojekyll`. This is an explicit operator action;
+do not copy source files, credentials or local server state into that branch. Verify both URLs, then switch Pages
+back to **GitHub Actions** and re-enable the workflow when service recovers. Before any later release, ensure `main`
+contains the intended code for both services. Do not race a manual release against Actions.
+
+## Production D1 migrations
+
+Routine releases never run `wrangler d1 migrations apply`, create databases, reset data or change bindings. Existing
+V1/V2 score history requires no migration; scores remain in the same production database. Schema changes need a
+separate reviewed operation with a migration-capable credential and a recovery plan. Only when explicitly intended,
+from `phaser-asteroids/server`, run:
+
+```sh
+npx wrangler d1 migrations apply asteroids-leaderboard --env production --remote
+```
+
+Coordinate schema compatibility before the code release. The CI token deliberately has no D1 data permissions.
+Do not restore/reset D1 to recover from a failed code deployment.
## Trying a branch on a phone before it is published
diff --git a/phaser-asteroids/scripts/production-health.mjs b/phaser-asteroids/scripts/production-health.mjs
new file mode 100644
index 0000000..8c5e3ff
--- /dev/null
+++ b/phaser-asteroids/scripts/production-health.mjs
@@ -0,0 +1,38 @@
+// Read-only release gate. Versions come from the SAME built artifact that Pages will publish.
+import { setTimeout } from 'node:timers/promises';
+import { pathToFileURL } from 'node:url';
+import { GAMEPLAY_RULES_VERSION, REPLAY_SCHEMA_VERSION } from '../dist/node/index.js';
+
+const HEALTH_URL = 'https://asteroids-leaderboard.davejandrea.workers.dev/api/v1/health';
+
+export async function verifyProductionHealth(fetchImpl = fetch, wait = setTimeout) {
+ console.log(`Expected rules=${GAMEPLAY_RULES_VERSION}, schema=${REPLAY_SCHEMA_VERSION}`);
+ for (let attempt = 1; attempt <= 5; attempt++) {
+ try {
+ const response = await fetchImpl(HEALTH_URL, {
+ signal: AbortSignal.timeout(10_000),
+ cache: 'no-store',
+ redirect: 'error',
+ });
+ if (!response.ok) throw new Error(`Health returned HTTP ${response.status}`);
+ const health = await response.json();
+ // Exact schema equality is the compatibility policy used by the replay validator.
+ if (health?.ok !== true || health.rulesVersion !== GAMEPLAY_RULES_VERSION || health.schemaVersion !== REPLAY_SCHEMA_VERSION) {
+ throw new Error(`Incompatible health: ok=${JSON.stringify(health?.ok)}, rules=${JSON.stringify(health?.rulesVersion)}, schema=${JSON.stringify(health?.schemaVersion)}`);
+ }
+ console.log(`Production Worker healthy: rules=${health.rulesVersion}, schema=${health.schemaVersion}`);
+ return;
+ } catch (error) {
+ console.error(`Health attempt ${attempt}/5 failed: ${error.message}`);
+ if (attempt === 5) throw new Error('Production Worker verification failed; do not publish the frontend.');
+ await wait(5_000);
+ }
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ verifyProductionHealth().catch((error) => {
+ console.error(error.message);
+ process.exitCode = 1;
+ });
+}
diff --git a/phaser-asteroids/scripts/production-health.test.mjs b/phaser-asteroids/scripts/production-health.test.mjs
new file mode 100644
index 0000000..86b51eb
--- /dev/null
+++ b/phaser-asteroids/scripts/production-health.test.mjs
@@ -0,0 +1,54 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { GAMEPLAY_RULES_VERSION, REPLAY_SCHEMA_VERSION } from '../dist/node/index.js';
+import { verifyProductionHealth } from './production-health.mjs';
+
+const healthy = { ok: true, rulesVersion: GAMEPLAY_RULES_VERSION, schemaVersion: REPLAY_SCHEMA_VERSION };
+
+test('accepts matching production versions with a read-only unauthenticated request', async () => {
+ await verifyProductionHealth(async (url, options) => {
+ assert.equal(url, 'https://asteroids-leaderboard.davejandrea.workers.dev/api/v1/health');
+ assert.equal(options.method, undefined); // fetch defaults to GET
+ assert.equal(options.headers, undefined);
+ assert.equal(options.cache, 'no-store');
+ assert.equal(options.redirect, 'error');
+ assert.ok(options.signal instanceof AbortSignal);
+ return Response.json(healthy);
+ });
+});
+
+test('retries propagation failures, then accepts a compatible Worker', async () => {
+ let calls = 0;
+ const waits = [];
+ await verifyProductionHealth(async () => {
+ calls++;
+ if (calls === 1) throw new Error('network unavailable');
+ if (calls === 2) return Response.json({ ...healthy, rulesVersion: 'previous-version' });
+ return Response.json(healthy);
+ }, async (ms) => waits.push(ms));
+ assert.equal(calls, 3);
+ assert.deepEqual(waits, [5_000, 5_000]);
+});
+
+for (const [name, response] of [
+ ['HTTP failure', () => new Response('unavailable', { status: 503 })],
+ ['invalid JSON', () => new Response('not JSON')],
+ ['null body', () => Response.json(null)],
+ ['ok false', () => Response.json({ ...healthy, ok: false })],
+ ['truthy ok', () => Response.json({ ...healthy, ok: 'true' })],
+ ['wrong rules', () => Response.json({ ...healthy, rulesVersion: 'previous-version' })],
+ ['wrong schema', () => Response.json({ ...healthy, schemaVersion: REPLAY_SCHEMA_VERSION + 1 })],
+ ['missing schema', () => Response.json({ ok: true, rulesVersion: GAMEPLAY_RULES_VERSION })],
+ ['network timeout', () => { throw new Error('request timed out'); }],
+]) {
+ test(`blocks publication after five attempts: ${name}`, async () => {
+ let calls = 0;
+ let waits = 0;
+ await assert.rejects(verifyProductionHealth(async () => {
+ calls++;
+ return response();
+ }, async () => { waits++; }), /verification failed; do not publish/);
+ assert.equal(calls, 5);
+ assert.equal(waits, 4);
+ });
+}
diff --git a/phaser-asteroids/server/README.md b/phaser-asteroids/server/README.md
index d6269d3..4827800 100644
--- a/phaser-asteroids/server/README.md
+++ b/phaser-asteroids/server/README.md
@@ -16,6 +16,14 @@ Layout: `src/` portable service (+ `worker.ts`/`d1.ts` Cloudflare glue), `migrat
Local secrets go in `.dev.vars` (git-ignored); copy `.dev.vars.example`.
-Production is deployed at **https://asteroids-leaderboard.davejandrea.workers.dev** using the existing account and the separate `env.production.DB` binding in `wrangler.toml`. Both migrations and production secrets are configured; health, both D1-backed leaderboards and live logs were verified on 2026-10-22. GitHub Pages frontend publication remains a separate release. On Windows, `./scripts/production-secrets.ps1 -Action Check` validates the encrypted local secret backup and `-Action DryRun` compiles without publishing. Only `-Action Deploy` publishes and attaches `IP_HASH_SALT` and `ADMIN_TOKEN`. See the full guide's production section before deploying. Never put backend secrets in Vite or GitHub Actions variables.
+Production is deployed at **https://asteroids-leaderboard.davejandrea.workers.dev** using the existing account and the
+separate `env.production.DB` binding in `wrangler.toml`. Both migrations and production secrets are configured.
+The [coordinated release workflow](../docs/deployment.md) validates both services, deploys this Worker, checks health
+and shared replay versions, then publishes Pages from the same commit. Configure the scoped `CLOUDFLARE_API_TOKEN`
+repository secret before merging/enabling it. CI never runs production migrations or reuploads backend secrets.
+Code-only `npx wrangler deploy --env production` preserves Cloudflare's existing `IP_HASH_SALT` and `ADMIN_TOKEN`.
+On Windows, `./scripts/production-secrets.ps1 -Action Check` validates the encrypted local secret backup and
+`-Action DryRun` compiles without publishing. The helper's `Deploy` action attaches secrets for initial setup;
+do not use it for ordinary CI releases or rotate secrets accidentally. Never put backend secrets in Vite or GitHub variables.
Physical Android ranked testing: [`../../docs/android-lan-testing.md`](../../docs/android-lan-testing.md). Opt-in `migrate:lan` / `dev:lan` use separate local D1 state, loopback port 8788 and disabled admin routes. The frontend LAN proxy is the only phone-facing listener.