From 8a55e73a47f36080b0f8752c3468b80dfb1c3f68 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 12 Nov 2026 02:57:18 -0400 Subject: [PATCH 01/14] docs: update moderation and release documentation with production deployment details --- docs/leaderboard-moderation.md | 2 ++ docs/play-release-validation.md | 4 +++ docs/release-preflight.md | 26 +++++++++++++++++++- phaser-asteroids/android/app/build.gradle | 5 ++++ phaser-asteroids/docs/google-play-release.md | 2 +- 5 files changed, 37 insertions(+), 2 deletions(-) diff --git a/docs/leaderboard-moderation.md b/docs/leaderboard-moderation.md index da29d8b..447ac2e 100644 --- a/docs/leaderboard-moderation.md +++ b/docs/leaderboard-moderation.md @@ -88,6 +88,8 @@ Still requires interpretation/external evidence: whether submit-as-acceptance is ## Verification +**Live since 2026-11-04 18:32 UTC** (Worker version `c2aef78f`; [Stage 2 record](release-preflight.md#stage-2-production-worker-deployment-2026-11-04)). Production `/admin` is reachable at the Worker origin. Authenticated read-only checks show an empty queue and audit log. No production moderation decision has been made yet. The initial review of existing names (workflow step 2) is still to do. + Production preparation at committed HEAD `f540caf` is documented in the [release preflight/runbook](release-preflight.md): staged migration commands, backup/recovery, historical-client compatibility, configuration checklist and stop/go gates. The earlier implementation-pass statements above are historical; this follow-up verified the code is committed and ran only local mutation tests plus a public production health GET. No production migration/deployment/backup/restore was performed. See [release validation](play-release-validation.md) for results. Reproduce from `phaser-asteroids`: full Vitest, server typecheck, production build, `test:worker`, `test:ranked:ui`, `test:menu`, and `test:moderation:admin`. The last runs real Chromium against a disposable local Worker/D1 and covers login, report review, name replacement/restoration, hide/restore, resolution/reopening, history, erasure, unrelated-row preservation, lock/reload and responsive layout. Screenshots are under ignored `scripts/.smoke-output/moderation-admin-*.png`. Nothing in these tests targets production. diff --git a/docs/play-release-validation.md b/docs/play-release-validation.md index 950aa74..7d034e6 100644 --- a/docs/play-release-validation.md +++ b/docs/play-release-validation.md @@ -2,6 +2,10 @@ Prepared on `dev`, base HEAD `c1871a92c6f2a99bbac6f8dc8885691804826737`, plus the uncommitted privacy/release changes. No push, merge, deployment, production data mutation, key generation, signing or Play publication. Pre-existing Android Studio `.idea` changes and inaccessible tracked `tmp/` deletions were left alone. The Gradle settings typo seen initially was already corrected in the working tree before this task's Android edits. +## Backend release — 2026-11-04 (Stage 2) + +The moderation Worker is live: merge `8569834` (tree identical to `549729f`), Actions run 41887905781, Cloudflare version `c2aef78f-ec27-4118-bd2c-a13f59b7313b` at 100% on D1 0001-0004. Pre-deploy local results at `549729f` matched the table below (1,667 unit, 40/40 migrations/historical client, 33/33 worker-e2e, 28/28 admin, 99/99 ranked UI, 127/127 menu). Live public (31/31) and admin read-only (19/19) checks passed. Details and remaining gates: [Stage 2 record](release-preflight.md#stage-2-production-worker-deployment-2026-11-04). Android old-device testing is still outstanding (0 ADB devices). + ## Production preparation verification — 2026-11-04 Audited `dev` at `f540cafb2da864d3d3da52619910f062acfff9c3`. The moderation implementation is committed (`91c349c`, then `f540caf`); this pass adds local tests/docs. No commit/push/merge, production backup/export/restore/migration/deployment, credentials changes, score writes or Play upload. Five existing root `tmp/` deletions were preserved. See the [current release preflight](release-preflight.md) for readiness, compatibility findings, configuration uncertainties and exact approval-only production commands. Earlier sections below are historical snapshots. diff --git a/docs/release-preflight.md b/docs/release-preflight.md index 45b39db..93da244 100644 --- a/docs/release-preflight.md +++ b/docs/release-preflight.md @@ -1,6 +1,6 @@ # Orbital Impact production release preflight and runbook -Audit: 2026-11-04. **Blocked for production release pending external gates.** **[Stage 1](#stage-1-production-d1-backup-and-migrations) (production D1 backup + migrations 0003/0004) is prepared and locally rehearsed, awaiting explicit operator authorization.** Local preparation is verified; production backup/export/restore, migrations, deployment, credentials changes and Play upload were not performed. This replaces the historical 2026-10-22 preflight. See [operator workflow](leaderboard-moderation.md), [test evidence](play-release-validation.md), [data inventory](play-data-inventory.md), [policy draft](privacy-policy-draft.md) and [Android signing/build/Play instructions](../phaser-asteroids/docs/google-play-release.md). +Audit: 2026-11-04. **Backend released; Android/Play still blocked pending external gates.** [Stage 1](#stage-1-production-result-2026-11-04) (production D1 backup + migrations 0003/0004) executed 2026-11-04 18:04-18:06 UTC. [Stage 2](#stage-2-production-worker-deployment-2026-11-04) (moderation Worker via main CI) executed 2026-11-04 18:30-18:33 UTC and verified. No restore, credentials change, production moderation write or Play upload was performed. Sections below that describe Stage 1/2 as pending are the pre-execution plan, kept for reference. This replaces the historical 2026-10-22 preflight. See [operator workflow](leaderboard-moderation.md), [test evidence](play-release-validation.md), [data inventory](play-data-inventory.md), [policy draft](privacy-policy-draft.md) and [Android signing/build/Play instructions](../phaser-asteroids/docs/google-play-release.md). ## Release identity and assessment @@ -466,6 +466,30 @@ Remove-Item -LiteralPath $RolloutDir -Recurse -Force # staged copies of commit - **Guards:** setup refused a backup directory inside the repository and a session with `CI` set. A first attempt from a deep scratch path failed inside workerd on the local D1 path, which is why setup now enforces the 100-character limit on `$BackupDir`. - **Not provable locally:** the real remote export format (for example whether it emits `_cf_KV`, or DDL text that differs from `sqlite_master`), remote atomicity of a failed migration, export/restore permissions, and Time Travel restore. Steps 4-5 test the first on real data before any write. The others stay inferred. +### Stage 1 production result (2026-11-04) + +Executed with operator authorization 18:04:20-18:06:01 UTC from `549729f`, through the blocks above. Step 4 output was URL-redacted, and the step 6/8 interactive `y` check was replaced by an automated exactly-one-pending-file assertion. All steps passed. Ledger 0001-0004 (0003 at 18:05:23, 0004 at 18:05:36). 41 scores (0 hidden), 44 runs (41 accepted). Every backed-up score and accepted run unchanged, FK check empty, Worker `004624cd` unchanged at 100% throughout. The record JSON (all three bookmarks, counts, hashes), the SHA-256-verified export and two local D1 copies are in the protected release directory outside Git (`stage1-record-20261104-180420.json`). The export hash was re-verified before Stage 2. + +## Stage 2: production Worker deployment (2026-11-04) + +Executed with operator authorization. Evidence: protected release directory, `stage2\stage2-record-20261104.json` (no secrets). + +| Item | Result | +| --- | --- | +| Release content | **Verified:** `origin/main..dev` = `91c349c`, `f540caf`, `1a6eb98`, `946d845`, `549729f` (the last two docs-only despite the `549729f` message). `phaser-asteroids/` identical between `1a6eb98` and `549729f`. No change to `wrangler.toml`, workflows, `server/rules` or gameplay/scoring code. Client changes limited to privacy/report/block UI and `cache: 'no-store'` reads. Android changes are signing/backup config, not built by CI. | +| Pre-deploy production state (read-only) | **Verified:** account/D1 `cf4833f7-…`, ledger 0001-0004, 0004 schema checks, FK empty, 41/44/41, all Stage 1 backup rows unchanged, `004624cd` 100%, no workflow running. | +| Local verification at `549729f` (clean detached worktree) | **Verified:** `npm ci` (both), unit 67 files / 1,667 tests, both typechecks, build, android-build 8/8, node tests, rules guard (0 changes since `c1871a9`), `test:release:migrations` 40/40 (historical client/Worker), `worker-e2e` 33/33, `moderation-admin` 28/28, `ranked-ui` 99/99, `menu` 127/127, production dry-run 140.51 KiB with `DB`. Built client has no admin token/salt value, admin routes or admin code; the only `Bearer` is the existing run-challenge header. | +| Merge | `main` fast-forwarded to `532f8fb`, then `git merge --no-ff dev` gave **`85698345c0760c02055036e241d7b8ca4137abcb`**, tree `175aa8cd…` identical to `549729f`. Pushed 18:30:51 UTC (one push, one run). | +| GitHub Actions | **Run [41887905781](https://github.com/djblackett/asteroids-bootdev/actions/runs/41887905781)**, attempt 1, success: validate 18:30:59-18:32:13, Worker (stale guard, `wrangler deploy --env production`, production-health) 18:32:16-18:32:35, Pages 18:32:39-18:33:12. | +| Cloudflare | Deployment `e4ea95c8-9e6f-4cb6-9741-d9e99a706230` (18:32:30 UTC), version **`c2aef78f-ec27-4118-bd2c-a13f59b7313b` at 100%**. Bindings `DB`=`cf4833f7-…`, `ALLOWED_ORIGINS`, secrets `ADMIN_TOKEN`/`IP_HASH_SALT` (names only). Cron `17 7 * * *` unchanged. Rollback target `004624cd` still listed; not used. | +| Public API (31/31) | **Verified:** health unchanged (rules 1.2.0, schema 1, supported [1.2.0], maxTicks 72000, 1200 s). Both boards 200 with unchanged top-level and entry fields; all 41 all-time and the weekly entries identical to the pre-deploy snapshot (ids, ranks, names, scores); paging OK; all 41 details 200 with public shape; unknown id 404. **`Cache-Control: no-store`** on boards and details, no `CF-Cache-Status`. CORS unchanged: both origins echoed, preflight headers identical, foreign preflight 403. No moderation-only fields in public bodies. No score or report was submitted. | +| Admin (19/19) | **Verified:** `GET /admin` 200 HTML, nonce CSP (`default-src 'none'`, `connect-src 'self'`, `frame-ancestors 'none'`), per-response nonce, inline-only assets, no external resources, no-store, `X-Frame-Options: DENY`, no-referrer, no CORS. Foreign `Origin` → 403 `origin_not_allowed` (writes nothing). **One** unauthenticated request → generic 401 (wrote the single `admin-fail` counter row). Authenticated GETs with the DPAPI-backed token (memory only, never printed): queue 200 no-store with 0 entries (no reports, no integrity flags), all-entries 41 visible / none renamed, hidden view empty, audit empty, per-entry history empty, no hashes/tokens exposed, GET on moderate route 405. No moderation mutation sent. The console's empty-state rendering was not driven in a live browser; it is covered by `moderation-admin` locally. | +| D1 after deploy (read-only) | **Verified:** ledger 0001-0004, 41/0/44/41, reports 0, audit 0, FK empty, Stage 1 backup rows unchanged. `rate_limits` = 1 (the `admin-fail` row above). | +| Logs/health | **Verified:** `wrangler tail` during sample reads: 11 events, all 200/`ok`, 0 exceptions. Analytics since 18:00 UTC: `004624cd` 79 requests / 0 errors, `c2aef78f` 79 / 0. **Limitation:** no Workers observability/Logpush configured, so there is no retained log history; the new scheduled handler (with report pruning) first runs 2026-11-05 07:17 UTC and was not observed. | +| GitHub Pages | Published the same build. **Note:** the public web game now shows the bundled Privacy screen marked `DRAFT PRIVACY POLICY - REVIEW PENDING` with `[PRIVACY CONTACT PENDING]`. | + +Remaining after Stage 2: confirm the first cron run with reports pruning (check analytics or tail around 07:17 UTC); replace the draft privacy text and contact (now visible on the web build); old-device Android compatibility (no ADB device was available); all Play/signing/policy gates in [section 4](#4-android-and-play). Worker rollback: `rollback 004624cd-b03e-4c2e-8bfc-1e8abb29ef9e` is schema-compatible, but it removes reports, admin and `no-store`. + ## Deployment sequence Production commands below are **instructions for a separately approved operator rollout**. None ran except the recorded public health GET and local compilation. Execute stages separately, check native exit codes and save evidence. Do not paste this whole document as a script. diff --git a/phaser-asteroids/android/app/build.gradle b/phaser-asteroids/android/app/build.gradle index 3e90e86..0d0bef0 100644 --- a/phaser-asteroids/android/app/build.gradle +++ b/phaser-asteroids/android/app/build.gradle @@ -74,6 +74,11 @@ tasks.configureEach { task -> if (task.name in ['preReleaseBuild', 'validateSigningRelease']) { task.doFirst { if (!hasUploadSigning && providers.gradleProperty('allowUnsignedRelease').orNull != 'true') { + + + + + throw new GradleException('Release signing is missing. Set ASTEROIDS_UPLOAD_* or use -PallowUnsignedRelease=true for audit-only unsigned output.') } } diff --git a/phaser-asteroids/docs/google-play-release.md b/phaser-asteroids/docs/google-play-release.md index 14a5115..9531b3d 100644 --- a/phaser-asteroids/docs/google-play-release.md +++ b/phaser-asteroids/docs/google-play-release.md @@ -7,7 +7,7 @@ Prepared 2026-11-03 on `dev`. **Local preparation only; nothing was published or Use the [production release preflight](../../docs/release-preflight.md) for the audited commit, staged 0003/0004 migration commands, backup/recovery and installed-client report. The main GitHub workflow deploys the Worker automatically and does not check schema; complete the authorized migration gates before triggering it. Latest local evidence is in [release validation](../../docs/play-release-validation.md); unsigned artifact success does not establish device, signing or Play readiness. - Approve `../../docs/privacy-policy-draft.md`, public contact, provider retention and target ages/content rating. Operator is David Andrea (confirmed 2026-11-04); choosing the public contact address is intentionally deferred and must be revisited before distribution. Replace bundled contact placeholders in `src/ui/menu/pages/privacy.ts`; synchronize policy text. Host the approved policy separately and provide its public URL to Play Console. Do not distribute a draft policy. -- Pending migrations 0003 and 0004 and the reviewed Worker changes must eventually be deployed by an authorized operator before testers rely on reporting. This task does not authorize that deployment. Existing ranked requests are unchanged; production moderation availability has not been verified in this follow-up. Deploy the backend first: the updated app adds the suspicious_score report reason, while old report reasons remain supported. +- **Done 2026-11-04:** migrations 0003/0004 (Stage 1) and the moderation Worker (Stage 2, version `c2aef78f`) are in production; see the [Stage 2 record](../../docs/release-preflight.md#stage-2-production-worker-deployment-2026-11-04). Historical note: pending migrations 0003 and 0004 and the reviewed Worker changes must eventually be deployed by an authorized operator before testers rely on reporting. This task does not authorize that deployment. Existing ranked requests are unchanged; production moderation availability has not been verified in this follow-up. Deploy the backend first: the updated app adds the suspicious_score report reason, while old report reasons remain supported. - Establish report review coverage and the removal process in `../../docs/leaderboard-moderation.md`. Confirm production CORS still permits `https://spacearcade.davidandrea.ca` and `https://djblackett.github.io`. Do not loosen origins or expose admin credentials in the app. - Install Node/npm matching the lockfile/toolchain (validated here with Node 26.13.0/npm 11.20.0), JDK 21, Android SDK 36 and Build Tools 36.1.0. Use the committed Gradle wrapper 8.14.3 and AGP 8.13.0. `JAVA_HOME` selects JDK 21; check user Gradle properties/Android Studio settings do not override it. Do not commit local machine paths. Java source compatibility remains 17. From 4c0af25f31de42b7c0446abaa33a10fa61a1db4a Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:38:49 -0400 Subject: [PATCH 02/14] fix(android): guard signed release inspection; drop stray blank lines - build.gradle: remove the five blank lines 8a55e73 added inside the unsigned-release guard (file is byte-identical to before that commit). - inspect-android-release.ps1: both modes refuse a debuggable APK and report the version; without -Unsigned it now requires verified APK (apksigner) and AAB (jarsigner) signatures, refuses the Android debug certificate, and refuses bundled draft privacy text, listing every problem before failing. -Unsigned only warns about the draft text. New -ApkPath/-AabPath to inspect copies. - androidRelease.test.ts: the inspector's marker list must cover every upper-case draft marker still in src/ui/menu/pages/privacy.ts. No gameplay, rules, server or packaged web change. Co-Authored-By: Claude Opus 5.5 --- phaser-asteroids/android/app/build.gradle | 5 -- .../scripts/inspect-android-release.ps1 | 56 +++++++++++++++++-- phaser-asteroids/tests/androidRelease.test.ts | 18 ++++++ 3 files changed, 69 insertions(+), 10 deletions(-) diff --git a/phaser-asteroids/android/app/build.gradle b/phaser-asteroids/android/app/build.gradle index 0d0bef0..3e90e86 100644 --- a/phaser-asteroids/android/app/build.gradle +++ b/phaser-asteroids/android/app/build.gradle @@ -74,11 +74,6 @@ tasks.configureEach { task -> if (task.name in ['preReleaseBuild', 'validateSigningRelease']) { task.doFirst { if (!hasUploadSigning && providers.gradleProperty('allowUnsignedRelease').orNull != 'true') { - - - - - throw new GradleException('Release signing is missing. Set ASTEROIDS_UPLOAD_* or use -PallowUnsignedRelease=true for audit-only unsigned output.') } } diff --git a/phaser-asteroids/scripts/inspect-android-release.ps1 b/phaser-asteroids/scripts/inspect-android-release.ps1 index 89ef196..4588e48 100644 --- a/phaser-asteroids/scripts/inspect-android-release.ps1 +++ b/phaser-asteroids/scripts/inspect-android-release.ps1 @@ -1,17 +1,27 @@ param( [string]$SdkRoot = "$env:LOCALAPPDATA/Android/Sdk", [string]$BuildTools = '36.1.0', - [switch]$Unsigned + [switch]$Unsigned, + # Override the artifact paths (default: Gradle's release outputs). Used to check copies, and to test this script's refusals. + [string]$ApkPath, + [string]$AabPath ) $ErrorActionPreference = 'Stop' $projectRoot = Split-Path -Parent $PSScriptRoot $apkName = if ($Unsigned) { 'app-release-unsigned.apk' } else { 'app-release.apk' } -$apkPath = Join-Path $projectRoot "android/app/build/outputs/apk/release/$apkName" -$aabPath = Join-Path $projectRoot 'android/app/build/outputs/bundle/release/app-release.aab' -$aaptPath = Join-Path $SdkRoot "build-tools/$BuildTools/aapt2.exe" +$apkPath = if ($ApkPath) { $ApkPath } else { Join-Path $projectRoot "android/app/build/outputs/apk/release/$apkName" } +$aabPath = if ($AabPath) { $AabPath } else { Join-Path $projectRoot 'android/app/build/outputs/bundle/release/app-release.aab' } +$buildToolsDir = Join-Path $SdkRoot "build-tools/$BuildTools" +$aaptPath = Join-Path $buildToolsDir 'aapt2.exe' if (-not (Test-Path -LiteralPath $aaptPath)) { throw "Install Android build tools $BuildTools or pass -BuildTools." } +# Text that only the unapproved review copy of the bundled privacy policy contains (src/ui/menu/pages/privacy.ts). A signed artifact +# is meant for testers or Play, and must not ship a draft policy (docs/privacy-policy-draft.md). tests/androidRelease.test.ts keeps +# this list in step with the source while the draft remains. +$draftPolicyMarkers = @('[PRIVACY CONTACT PENDING]', 'DRAFT PRIVACY POLICY - REVIEW PENDING') + Add-Type -AssemblyName System.IO.Compression.FileSystem +$draftFindings = @() foreach ($artifactPath in @($apkPath, $aabPath)) { if (-not (Test-Path -LiteralPath $artifactPath)) { throw "Missing artifact: $artifactPath" } $archive = [IO.Compression.ZipFile]::OpenRead($artifactPath) @@ -20,6 +30,15 @@ foreach ($artifactPath in @($apkPath, $aabPath)) { if ($nativeEntries.Count) { throw "Native libraries present in $artifactPath. Perform ELF and ZIP 16 KB alignment checks before release: $($nativeEntries.FullName -join ', ')" } if (@($archive.Entries | Where-Object { $_.FullName -match 'assets/public/node/' }).Count) { throw 'Server verifier was packaged.' } Write-Output "PASS no native .so libraries or server verifier: $artifactPath" + $scripts = @($archive.Entries | Where-Object { $_.FullName -match '(^|/)assets/public/assets/[^/]+\.js$' }) + if (-not $scripts.Count) { throw "No bundled game scripts found in $artifactPath" } + foreach ($entry in $scripts) { + $reader = New-Object IO.StreamReader($entry.Open()) + try { $text = $reader.ReadToEnd() } finally { $reader.Dispose() } + foreach ($marker in $draftPolicyMarkers) { + if ($text.Contains($marker)) { $draftFindings += "$marker in $(Split-Path -Leaf $artifactPath):$($entry.FullName)" } + } + } } finally { $archive.Dispose() } $digest = (Get-FileHash -LiteralPath $artifactPath -Algorithm SHA256).Hash Write-Output "SHA256 $digest $artifactPath" @@ -29,6 +48,7 @@ if ($LASTEXITCODE) { throw 'aapt2 badging failed' } $badging | Where-Object { $_ -match '^package:|^sdkVersion:|^targetSdkVersion:' } | ForEach-Object { Write-Output "$_" } if (-not ($badging -match "name='ca.davidandrea.spacearcade'")) { throw 'Wrong package ID' } if (-not ($badging -match "targetSdkVersion:'36'")) { throw 'Review target SDK requirement (expected 36)' } +if ($badging -match '^application-debuggable') { throw 'APK is debuggable: release artifacts must come from the release build type' } $permissions = & $aaptPath dump permissions $apkPath if ($LASTEXITCODE) { throw 'aapt2 permissions failed' } $permissions @@ -36,4 +56,30 @@ $unexpected = @($permissions | Select-String "uses-permission.*name='([^']+)'" | $_ -notin @('android.permission.INTERNET', 'android.permission.VIBRATE', 'ca.davidandrea.spacearcade.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION') }) if ($unexpected.Count) { throw "Unexpected permissions: $($unexpected -join ', ')" } -Write-Output 'PASS package, SDK and permission audit. Still test the Play-delivered app on a 16 KB device/emulator.' +Write-Output 'PASS package, SDK, debuggable and permission audit.' + +if ($Unsigned) { + foreach ($finding in $draftFindings) { Write-Output "WARN draft privacy text bundled (allowed only for unsigned audit/test builds): $finding" } + Write-Output 'Unsigned audit only: no signature or certificate was checked. Not uploadable.' +} else { + # Signed artifacts: a real (non-debug) signature on both, and no draft policy. Every problem is reported before failing. + $problems = @() + $apksigner = Join-Path $buildToolsDir 'apksigner.bat' + $apkCerts = & $apksigner verify --print-certs $apkPath 2>&1 + if ($LASTEXITCODE) { $problems += "APK signature does not verify: $(($apkCerts | Select-Object -First 2) -join ' ')" } + $apkCerts | Where-Object { $_ -match 'certificate (DN|SHA-256 digest)' } | ForEach-Object { Write-Output "APK $_" } + if ($apkCerts -match 'CN=Android Debug') { $problems += 'APK is signed with the Android debug key, not the upload key' } + $jarsigner = if ($env:JAVA_HOME -and (Test-Path -LiteralPath (Join-Path $env:JAVA_HOME 'bin/jarsigner.exe'))) { Join-Path $env:JAVA_HOME 'bin/jarsigner.exe' } else { (Get-Command jarsigner -ErrorAction SilentlyContinue).Source } + if (-not $jarsigner) { + $problems += 'jarsigner not found: set JAVA_HOME to JDK 21 to verify the AAB signature' + } else { + $aabCerts = & $jarsigner -verify -verbose -certs $aabPath 2>&1 + if ($LASTEXITCODE -or -not ($aabCerts -match '^jar verified\.')) { $problems += "AAB is unsigned or its signature does not verify: $(($aabCerts | Where-Object { $_ -match '\S' } | Select-Object -Last 1))" } + if ($aabCerts -match 'CN=Android Debug') { $problems += 'AAB is signed with the Android debug key, not the upload key' } + } + foreach ($finding in $draftFindings) { $problems += "draft privacy policy bundled; approve the policy and contact first (docs/privacy-policy-draft.md): $finding" } + if ($problems.Count) { throw "Signed release inspection failed:`n - $($problems -join "`n - ")" } + Write-Output 'PASS APK and AAB signatures verify, neither uses the Android debug key, and no draft privacy text is bundled.' + Write-Output 'Compare the printed certificate digest with the registered upload certificate.' +} +Write-Output 'Still test the Play-delivered app on a 16 KB device/emulator.' diff --git a/phaser-asteroids/tests/androidRelease.test.ts b/phaser-asteroids/tests/androidRelease.test.ts index dd9247b..30e3657 100644 --- a/phaser-asteroids/tests/androidRelease.test.ts +++ b/phaser-asteroids/tests/androidRelease.test.ts @@ -55,6 +55,24 @@ describe('Android app configuration', () => { expect(read('index.html')).toMatch(/ { + // scripts/inspect-android-release.ps1 refuses signed artifacts that contain the review copy. If the draft wording changes while it + // is still a draft, the inspector's list must change with it, or a draft could pass as approved. + const inspector = read('scripts/inspect-android-release.ps1'); + const listed = [...(inspector.match(/\$draftPolicyMarkers = @\(([^)]*)\)/)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]); + expect(listed.length).toBeGreaterThan(0); + // Read as text: importing the menu page would pull in Phaser. Every quoted literal with an upper-case review marker counts. + const draftLines = [...read('src/ui/menu/pages/privacy.ts').matchAll(/'((?:[^'\\\n]|\\.)*)'/g)].map((m) => m[1]).filter((line) => /PENDING|DRAFT/.test(line)); + for (const line of draftLines) expect(listed, `inspector does not refuse "${line}"`).toContain(line); + }); + + it('the release inspector refuses debuggable output and checks signatures outside -Unsigned', () => { + const inspector = read('scripts/inspect-android-release.ps1'); + expect(inspector).toContain("'^application-debuggable'"); + expect(inspector).toContain('apksigner.bat'); + expect(inspector).toContain('CN=Android Debug'); + }); + it('the manifest locks landscape and allows vibration', () => { const manifest = read('android/app/src/main/AndroidManifest.xml'); expect(manifest).toContain('android:screenOrientation="sensorLandscape"'); From 5db17fb6b44bd2817e3f415c09751dfaa75ed99e Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:38:50 -0400 Subject: [PATCH 03/14] docs: current release status and phone test checklist - release-preflight: new "Current status (2026-11-12)" section separating verified items, confirmed internal-testing blockers and manual gates; older Stage 1/2 and blocker text marked as dated records. - Record read-only cron evidence: one successful 07:00 UTC invocation per day 2026-11-05..12 with 0 errors since c2aef78f, prune effects in D1. - Privacy draft, data inventory, backend, moderation, validation, Android and Play docs: stop describing reporting/moderation/erasure as undeployed; the policy text and contact remain unapproved drafts. - New phaser-asteroids/docs/phone-test-checklist.md (absorbs the old android.md device checklist): sideload build, install commands and sections for install, orientation, touch, audio, offline, ranked, retry, report/block/privacy and existing-install compatibility. Co-Authored-By: Claude Opus 5.5 --- docs/leaderboard-backend.md | 2 +- docs/leaderboard-moderation.md | 8 +- docs/play-data-inventory.md | 2 +- docs/play-release-validation.md | 23 ++- docs/privacy-policy-draft.md | 4 +- docs/release-preflight.md | 33 +++- phaser-asteroids/docs/android.md | 28 +--- phaser-asteroids/docs/google-play-release.md | 4 +- phaser-asteroids/docs/phone-test-checklist.md | 152 ++++++++++++++++++ 9 files changed, 224 insertions(+), 32 deletions(-) create mode 100644 phaser-asteroids/docs/phone-test-checklist.md diff --git a/docs/leaderboard-backend.md b/docs/leaderboard-backend.md index fa1d4f3..d6c75a2 100644 --- a/docs/leaderboard-backend.md +++ b/docs/leaderboard-backend.md @@ -310,7 +310,7 @@ One-use run ids; CSPRNG tokens and seeds; expiry; atomic state transitions; per- Minimal logging (no IPs, nicknames or tokens): `run_rejected`, `verifier_threw`, `submit_failed`, `unhandled`, `prune`. -Moderation: use the Worker-origin `/admin` console or the authenticated APIs in the [moderation operator guide](leaderboard-moderation.md). Pending migrations 0003/0004 add private reports, reversible display names and transactional audit records. Avoid direct SQL moderation: it bypasses revision guards and audit history. Public boards/details now use `Cache-Control: no-store`. +Moderation: use the Worker-origin `/admin` console or the authenticated APIs in the [moderation operator guide](leaderboard-moderation.md). Migrations 0003/0004 (applied in production 2026-11-04) add private reports, reversible display names and transactional audit records. Avoid direct SQL moderation: it bypasses revision guards and audit history. Public boards/details now use `Cache-Control: no-store`. ## 11. What an attacker can and cannot do diff --git a/docs/leaderboard-moderation.md b/docs/leaderboard-moderation.md index 447ac2e..b4a3b25 100644 --- a/docs/leaderboard-moderation.md +++ b/docs/leaderboard-moderation.md @@ -1,5 +1,7 @@ # Leaderboard moderation: audit and operator guide +**Current status (2026-11-12):** live in production since 2026-11-04 (see [Verification](#verification)). The deployment checklist under [Erasure, cache consistency and release configuration](#erasure-cache-consistency-and-release-configuration) is complete except where marked open. The remaining operator tasks are the initial review of existing names, review coverage, and the public removal contact. The rest of this page records the implementation pass as written at the time. + Audited and extended on 2026-11-04 on `dev`, starting at `91c349c` (`add moderation tooling`). Local implementation and tests only. No production deployment, production data changes, credentials changes, commits or pushes were performed. Existing inaccessible root `tmp/` deletions were left alone. ## Assessment of the previous implementation @@ -70,10 +72,10 @@ After approving a request, use **Erase score and linked records**, typing the fu Public boards/details and admin responses now send `Cache-Control: no-store`; current frontend reads also bypass browser HTTP caching. No Cache API is used. Existing old-client caches may remain fresh for their former five-second lifetime during rollout. Already displayed screens, offline local records, downloaded copies and screenshots cannot be recalled. Refresh/reopen fetches current server state; there is no push removal from an already open screen. -Before a separately authorized production release: +Before a separately authorized production release (status as of 2026-11-12 in brackets): -- Back up/rehearse the migration against a disposable copy and review provider restore/retention practices. Apply pending 0003 **and 0004** to the correct `env.production` D1 before deploying this Worker. Do not deploy the code against an unmigrated database. This task ran migrations only with `--local`. -- Preserve existing `ADMIN_TOKEN`, `IP_HASH_SALT`, origin allowlist and frozen engines. No new secret/service/dependency is needed. Verify administration is enabled, the 07:17 UTC cleanup cron runs, and report review is assigned. Confirm HTTPS to the actual Worker origin. Protect that origin and D1 access through existing account controls. +- [**Done 2026-11-04**: backup verified, 0003/0004 applied before the Worker.] Back up/rehearse the migration against a disposable copy and review provider restore/retention practices. Apply pending 0003 **and 0004** to the correct `env.production` D1 before deploying this Worker. Do not deploy the code against an unmigrated database. This task ran migrations only with `--local`. [Provider retention review still open.] +- [**Done**: secrets and origins preserved, administration enabled, cron verified indirectly 2026-11-12. **Open**: report review assignment.] Preserve existing `ADMIN_TOKEN`, `IP_HASH_SALT`, origin allowlist and frozen engines. No new secret/service/dependency is needed. Verify administration is enabled, the 07:17 UTC cleanup cron runs, and report review is assigned. Confirm HTTPS to the actual Worker origin. Protect that origin and D1 access through existing account controls. - Verify Cloudflare Cache Rules do not override `no-store` for `/api/v1/*` or `/admin`. Purge any previously forced edge caches at deployment if such a rule existed; this source checkout cannot verify dashboard rules. Do not promise instant removal from old copies. - Review Cloudflare observability, logs, D1 Time Travel and exports separately. SQL erasure does not erase provider backups/logs. Reapply approved erasures before serving a restored database. - Deploy backend before the updated app (new report reason requires it). Rebuild/sync Android assets and test a Play-delivered build. Old challenge/submission/board/detail shapes, default rules and frozen verifier remain unchanged; old report reasons and legacy admin APIs remain supported. diff --git a/docs/play-data-inventory.md b/docs/play-data-inventory.md index 5ac80aa..4be6305 100644 --- a/docs/play-data-inventory.md +++ b/docs/play-data-inventory.md @@ -1,6 +1,6 @@ # Android privacy inventory and proposed Data safety answers -Audit date: 2026-11-03; moderation follow-up 2026-11-04. Branch: `dev`. Scope: Capacitor Android application, browser code shared with it, Cloudflare Worker and D1 schema. Root Python game's scores/logging are not packaged in the Android game. No cloud account settings or production data were read or modified. Reporting, erasure and the extended moderation workflow below are implemented locally, not deployed. See [moderation audit and operator guide](leaderboard-moderation.md). +Audit date: 2026-11-03; moderation follow-up 2026-11-04. Branch: `dev`. Scope: Capacitor Android application, browser code shared with it, Cloudflare Worker and D1 schema. Root Python game's scores/logging are not packaged in the Android game. No cloud account settings or production data were read or modified. Reporting, erasure and the extended moderation workflow below were implemented locally at audit time and **have been live in production since 2026-11-04** (Worker `c2aef78f`, D1 migrations 0001-0004; see the [Stage 2 record](release-preflight.md#stage-2-production-worker-deployment-2026-11-04)). The proposed answers below are still unconfirmed against provider settings. See [moderation audit and operator guide](leaderboard-moderation.md). ## Confirmed data flows diff --git a/docs/play-release-validation.md b/docs/play-release-validation.md index 7d034e6..5016a4a 100644 --- a/docs/play-release-validation.md +++ b/docs/play-release-validation.md @@ -2,6 +2,27 @@ Prepared on `dev`, base HEAD `c1871a92c6f2a99bbac6f8dc8885691804826737`, plus the uncommitted privacy/release changes. No push, merge, deployment, production data mutation, key generation, signing or Play publication. Pre-existing Android Studio `.idea` changes and inaccessible tracked `tmp/` deletions were left alone. The Gradle settings typo seen initially was already corrected in the working tree before this task's Android edits. +## Device-test preparation — 2026-11-12 + +Branch `release/android-device-prep`; packaged sources unchanged from `f1a031a` (`dev` after a no-file-change merge of `main`). No push, deploy, production write, key generation or Play upload. Production access was SELECT-only D1 (`rows_written: 0`) plus Cloudflare analytics and deployment-status reads. + +| Check (from phaser-asteroids, PowerShell, JDK 21.0.5) | Result | +| --- | --- | +| `npx vitest run --maxWorkers=4` | **Passed:** 67 files / 1,669 tests (1,667 + 2 new inspector/draft-marker tests) | +| `npm run typecheck --prefix server`, `npm run test:android-build`, rules-guard/production-health tests, `node scripts/rules-guard.mjs main` | **Passed:** typecheck; 8/8; 19/19; 0 released-rules changes | +| `npm run android:sync` | **Passed:** 1.0 (1) plays frozen rules 1.2.0/schema 1; production HTTPS origin baked in | +| `gradlew :app:bundleRelease :app:assembleRelease :app:lintRelease -PallowUnsignedRelease=true` | **Passed:** BUILD SUCCESSFUL; lint 0 errors / 14 warnings (same categories as before) | +| `inspect-android-release.ps1 -Unsigned` | **Passed**, with WARN for the bundled draft privacy text. AAB `8CC0A4F8…EFB2`, APK `284F84C1…D01C`: byte-identical to 2026-11-04 | +| Inspector refusals (new) | **Verified:** signed mode on the debug-key APK + unsigned AAB lists debug key, unsigned AAB and 4 draft-marker findings; debug APK refused as debuggable; missing `app-release.apk` refused | +| Sideload APK (release APK re-signed with local debug key) | **Built:** `apk/sideload/orbital-impact-1.0-sideload-debugkey.apk`, SHA-256 `11FEB5AB…E592`, v2/v3 verified, 16 KB zip-aligned. Not uploadable | +| `gradlew :app:assembleDebug` | **Passed:** `apk/debug/app-debug.apk` `E49AC998…6093` (diagnostic only) | +| Production cron (read-only) | **Verified indirectly:** daily 07:00 UTC invocation 8/8 days, 0 errors since deploy; prune effects visible in D1. See [current status](release-preflight.md#current-status-2026-11-12) | +| ADB devices | **Not stable:** Samsung SM-S901E appeared once via a local bridge, then `offline`. Nothing installed | +| Browser suites (ranked UI, menu, worker-e2e, moderation admin, migrations) | **Not re-run:** no change to their inputs since the 2026-11-04 passes at `549729f` | +| Physical device, 16 KB runtime, signed AAB, Play-delivered install | **Not run:** require a device, an upload key and Console access | + +Tooling note: from the Bash tool, whose working directory had a lowercase drive letter (`c:\`), every Vitest file failed with `Cannot read properties of undefined (reading 'config')`. Running from a `C:\` working directory passed. This was an environment artifact, not a test failure. + ## Backend release — 2026-11-04 (Stage 2) The moderation Worker is live: merge `8569834` (tree identical to `549729f`), Actions run 41887905781, Cloudflare version `c2aef78f-ec27-4118-bd2c-a13f59b7313b` at 100% on D1 0001-0004. Pre-deploy local results at `549729f` matched the table below (1,667 unit, 40/40 migrations/historical client, 33/33 worker-e2e, 28/28 admin, 99/99 ranked UI, 127/127 menu). Live public (31/31) and admin read-only (19/19) checks passed. Details and remaining gates: [Stage 2 record](release-preflight.md#stage-2-production-worker-deployment-2026-11-04). Android old-device testing is still outstanding (0 ADB devices). @@ -104,6 +125,6 @@ Toolchain: Node 26.13.0, npm 11.20.0, JDK 21.0.5, Gradle 8.14.3, AGP 8.13.0. Ins 1. Operator confirmed as David Andrea on 2026-11-04. Public privacy/security/removal/moderation mailbox intentionally deferred at David's request; return to this before distribution. Choose the address and mailbox handling/retention, final game name and effective date. Replace bundled contact placeholders and approve the public policy before distribution. Hosting proposal is in [the draft](privacy-policy-draft.md); nothing is hosted by this task. 2. Verify Cloudflare logging, request fields/location processing, security logs, backup/recovery/export retention, processing role and regions. Finalize [Data safety answers](play-data-inventory.md) using those facts. Accepted/hidden scores currently have no automatic expiry; do not promise otherwise. 3. Assign moderation coverage and review [nickname-blocking limitations](leaderboard-moderation.md) against Play's user-blocking requirement. No account or stable user identity was added. -4. Separately authorize/report the Worker migration and deployment before enabling reports for testers; implement the removal mailbox process. The new erasure route exists locally and is tested, but is not live in production. +4. ~~Separately authorize/report the Worker migration and deployment before enabling reports for testers.~~ **Done 2026-11-04** (Stage 1/2): reporting, moderation and the erasure route are live in production. Still open: implement the removal mailbox process (depends on item 1). 5. Human creates/protects the upload key or supplies an existing one; build and inspect signed artifacts and verify certificate fingerprints. Confirm Play has not already consumed version code 1; increment and append the release registry record if needed. 6. Test a Play-delivered build on a 16 KB emulator/device and Samsung/representative devices, including tablet/window behavior and backup/device transfer. No `.so` files makes ELF alignment inapplicable to the bundled app; it does not replace runtime testing. Complete the [internal-testing procedure](../phaser-asteroids/docs/google-play-release.md), target ages/content rating and branding pass before promotion. diff --git a/docs/privacy-policy-draft.md b/docs/privacy-policy-draft.md index d9fa974..6b6b29f 100644 --- a/docs/privacy-policy-draft.md +++ b/docs/privacy-policy-draft.md @@ -1,6 +1,8 @@ # Asteroids privacy policy — review draft -**Not approved for publication or distribution.** Public contact, provider retention and final game name require review. Package: `ca.davidandrea.spacearcade`. Proposed effective date: set on approval. The draft describes the changes in this checkout; reporting and erasure are not yet deployed. +**Not approved for publication or distribution.** Public contact, provider retention and final game name require review. Package: `ca.davidandrea.spacearcade`. Proposed effective date: set on approval. + +**Deployment status (2026-11-12):** the reporting, operator moderation (name replacement, hide/restore, report resolution, audit history) and erasure functions this draft describes have been live in the production leaderboard service since 2026-11-04 (Worker version `c2aef78f`; [Stage 2 record](release-preflight.md#stage-2-production-worker-deployment-2026-11-04)). The policy text itself is **still an unapproved draft**: the public web build and any test APK show the bundled Privacy screen marked `DRAFT PRIVACY POLICY - REVIEW PENDING` with `[PRIVACY CONTACT PENDING]`. Deployment of these features does not approve this text, the contact, or the retention statements below. Operator: **David Andrea** (confirmed 2026-11-04). Privacy, security and removal contact: **[PUBLIC EMAIL PENDING]**. diff --git a/docs/release-preflight.md b/docs/release-preflight.md index 93da244..6d4f49a 100644 --- a/docs/release-preflight.md +++ b/docs/release-preflight.md @@ -1,6 +1,31 @@ # Orbital Impact production release preflight and runbook -Audit: 2026-11-04. **Backend released; Android/Play still blocked pending external gates.** [Stage 1](#stage-1-production-result-2026-11-04) (production D1 backup + migrations 0003/0004) executed 2026-11-04 18:04-18:06 UTC. [Stage 2](#stage-2-production-worker-deployment-2026-11-04) (moderation Worker via main CI) executed 2026-11-04 18:30-18:33 UTC and verified. No restore, credentials change, production moderation write or Play upload was performed. Sections below that describe Stage 1/2 as pending are the pre-execution plan, kept for reference. This replaces the historical 2026-10-22 preflight. See [operator workflow](leaderboard-moderation.md), [test evidence](play-release-validation.md), [data inventory](play-data-inventory.md), [policy draft](privacy-policy-draft.md) and [Android signing/build/Play instructions](../phaser-asteroids/docs/google-play-release.md). +Audit: 2026-11-04. **Backend released; Android/Play still blocked pending external gates.** [Stage 1](#stage-1-production-result-2026-11-04) (production D1 backup + migrations 0003/0004) executed 2026-11-04 18:04-18:06 UTC. [Stage 2](#stage-2-production-worker-deployment-2026-11-04) (moderation Worker via main CI) executed 2026-11-04 18:30-18:33 UTC and verified. No restore, credentials change, production moderation write or Play upload was performed. **Present requirements are in [Current status](#current-status-2026-11-12) below.** Every later section is a dated record: where it describes Stage 1/2, migrations or the Worker deployment as pending, that is the pre-execution plan, kept for reference and for future migrations. This replaces the historical 2026-10-22 preflight. See [operator workflow](leaderboard-moderation.md), [test evidence](play-release-validation.md), [data inventory](play-data-inventory.md), [policy draft](privacy-policy-draft.md) and [Android signing/build/Play instructions](../phaser-asteroids/docs/google-play-release.md). + +## Current status (2026-11-12) + +Branch `release/android-device-prep` (from `dev` after merging `main`'s Stage 2 merge `8569834` back into `dev`; that merge changed no files). Nothing was pushed, deployed or uploaded. + +### Satisfied or verified + +- **Backend:** D1 ledger 0001-0004 and Worker `c2aef78f` (100%, sole version since 2026-11-04 18:32 UTC). Re-checked read-only on 2026-11-12 (`rows_written: 0`): 43 scores (0 hidden; 2 new accepted scores since Stage 2), 43 runs (all accepted), 0 reports, 0 audit rows. +- **Daily cron:** previously unobserved; **now verified indirectly.** Cloudflare request analytics show exactly one invocation of `c2aef78f` in the 07:00 UTC hour on each day from 2026-11-05 through 2026-11-12 (8/8), all `success`, and **0 errors on any invocation since deployment**. D1 shows the cleanup's effects: the 3 issued runs and the `admin-fail` counter present after Stage 2 are gone, and only the scheduled handler deletes such rows (erasure removes accepted runs only; the audit log is empty). Limits: the dedicated `workersInvocationsScheduled` dataset returned no rows, so the cron trigger name is inferred from timing; report pruning ran over 0 reports, so it deleted nothing observable. +- **Android identity and build:** package `ca.davidandrea.spacearcade`, `1.0`/code `1`, rules `1.2.0`/schema `1` recorded in `server/rules/released.json`, target/compile 36, min 24. Permissions INTERNET, VIBRATE and the signature-only AndroidX receiver; backup and cleartext disabled; release not debuggable; no `.so` files. Unsigned release AAB/APK rebuilt on 2026-11-12 are **byte-identical** to the 2026-11-04 audit artifacts (`8CC0A4F8…`, `284F84C1…`). Release tasks still refuse to run without upload signing unless the audit flag is set. No ads/analytics SDKs; no accounts, so account deletion is not applicable. +- **Guards added 2026-11-12:** without `-Unsigned`, `scripts/inspect-android-release.ps1` refuses debug-key or unsigned artifacts and bundled draft privacy text; both modes refuse debuggable APKs. Covered by `tests/androidRelease.test.ts`. + +### Confirmed blockers for internal testing + +1. **Privacy policy and contact:** `[PUBLIC EMAIL PENDING]` / `[PRIVACY CONTACT PENDING]` remain in the draft and the bundled app text, which is marked as a draft (and public on GitHub Pages). An approved hosted policy URL is needed for Play Console. Owner decision; nothing has been chosen or approved. +2. **Signing:** no upload key exists in this environment; Play App Signing is not enrolled; no signed AAB exists. Confirm in Console that version code 1 is unused. +3. **Physical device:** not yet tested. A sideload build and [checklist](../phaser-asteroids/docs/phone-test-checklist.md) are ready. ADB saw a Samsung SM-S901E only briefly over a local bridge (then `offline`), so nothing was installed or queried. +4. **Play Console setup:** app record, app name (launcher still `phaser-asteroids`), icon/splash/listing assets, and the declarations Console lists as outstanding (privacy policy URL, ads, content rating, target audience, app access). Data safety is exempt for internal-only testing. + +### Requires manual verification or an owner decision + +- Moderation coverage: the initial review of existing names ([workflow step 2](leaderboard-moderation.md#daily-solo-administrator-workflow)) is still to do. Decide whether nickname-only blocking and submit-as-acceptance satisfy Play UGC for an accountless app. +- Provider retention (Workers logs/observability, Time Travel window, export copies) for the privacy text. +- A 16 KB-page device or emulator, a Play-delivered install/update, and a tablet/large screen. +- Existing installs: no build has been distributed (`distributed: null`), so the only possible prior installs are developer builds signed with the same local debug key. See checklist section 9. ## Release identity and assessment @@ -79,7 +104,7 @@ Neither migration has a down migration. Schema rollback discards new moderation ## Stage 1: production D1 backup and migrations -**Status: prepared and rehearsed locally on 2026-11-04 ([evidence](#stage-1-local-rehearsal-evidence)). Not executed. Requires explicit operator authorization.** Stage 1 writes only to the production D1 (0003, then 0004) and to a protected local directory. It never deploys, rolls back or reconfigures the Worker. The deployed Worker `004624cd` serves throughout. Deploying the updated Worker is Stage 2, a separate approval. +**Executed 2026-11-04 ([result](#stage-1-production-result-2026-11-04)).** The status line that follows is the pre-execution record: *prepared and rehearsed locally on 2026-11-04 ([evidence](#stage-1-local-rehearsal-evidence)). Not executed. Requires explicit operator authorization.* Stage 1 writes only to the production D1 (0003, then 0004) and to a protected local directory. It never deploys, rolls back or reconfigures the Worker. The deployed Worker `004624cd` serves throughout. Deploying the updated Worker is Stage 2, a separate approval. ### Before you start @@ -492,7 +517,7 @@ Remaining after Stage 2: confirm the first cron run with reports pruning (check ## Deployment sequence -Production commands below are **instructions for a separately approved operator rollout**. None ran except the recorded public health GET and local compilation. Execute stages separately, check native exit codes and save evidence. Do not paste this whole document as a script. +Production commands below are **instructions for a separately approved operator rollout**. For this release, steps 1-3 were carried out on 2026-11-04 through Stage 1 and Stage 2 (records above). The sequence stays as the template for future backend releases. Execute stages separately, check native exit codes and save evidence. Do not paste this whole document as a script. ### 1. Pre-deployment @@ -561,7 +586,7 @@ Run full submission/moderation in the isolated suites or separately provisioned Use the [existing build/signing procedure](../phaser-asteroids/docs/google-play-release.md). Rebuild/sync after approved text edits; Gradle alone does not rebuild the game. Verify package `ca.davidandrea.spacearcade`, native `1.0` / code `1`, frozen rules `1.2.0` / schema `1`, release registry and `.env.android` HTTPS endpoint. Determine next unused code from Console, preserve distributed records, record final AAB hash/certificate. No ID/branding/version changed here. -Prioritized remaining blockers: +Prioritized remaining blockers (as of 2026-11-04 before Stage 1; superseded by [Current status](#current-status-2026-11-12), where item 2's backup, migrations, deployment and cron are resolved): 1. **Blocked / human policy:** `[PUBLIC EMAIL PENDING]`, approved public policy URL/text, provider/correspondence retention, moderation coverage/appeals/erasure process, audience/rating and interpretation of name-based blocking/submit acceptance. Reporting/local blocking source does not establish Play compliance. No accounts: account-deletion UI is **Not applicable**; operational data-removal contact remains required. 2. **Requires manual verification / Cloudflare:** backup, actual pending migrations and authorized backend deployment, cache/CORS/admin/cron/logging/incident owner. Backend before app: suspicious_score requires updated Worker. diff --git a/phaser-asteroids/docs/android.md b/phaser-asteroids/docs/android.md index 236ba32..f3b8764 100644 --- a/phaser-asteroids/docs/android.md +++ b/phaser-asteroids/docs/android.md @@ -4,7 +4,8 @@ The Android app is the unchanged web game inside Capacitor 8. All native behavio Browsers and GitHub Pages never take any of these paths. Status: implemented and unit/browser tested on the desktop. **Not yet tried on a phone**: see the -[device checklist](#device-checklist). Nothing has been deployed or published. +[phone test checklist](phone-test-checklist.md). The leaderboard backend it uses is deployed (Worker `c2aef78f`, 2026-11-04); the app +itself has not been published. ## Building @@ -33,15 +34,16 @@ cd android && ./gradlew assembleDebug # Set JAVA_HOME to JDK 21 first At runtime, [`resolveApiBase`](../src/ranked/api.ts) ignores `?api=` and the `wrangler dev` fallback whenever the page runs inside the app. So an installed app can only reach the configured production Worker, or report "not available". -Release items not done yet: the app name (still `phaser-asteroids`), `versionCode` / `versionName`, release signing, an AAB build, -and the launcher icon and splash artwork. +Release items not done yet: the app name (still `phaser-asteroids`), the launcher icon and splash artwork, an upload key and a signed +AAB. Version `1.0` / code `1`, the signing configuration and unsigned AAB/APK builds exist; see +[google-play-release.md](google-play-release.md). ## How each concern is handled | Concern | Where | What | |---|---|---| | App origin | [`capacitor.config.ts`](../capacitor.config.ts) | `server.hostname = spacearcade.davidandrea.ca`, `androidScheme = https`. The page origin (and the `Origin` header the Worker sees) is `https://spacearcade.davidandrea.ca`. Nothing is fetched from that domain: Capacitor serves the bundled files under that name. It is not `localhost`, so development-only rules never apply. **Do not change it after release**: `localStorage` (settings, nickname, local scores) belongs to the origin. | -| CORS | [`server/wrangler.toml`](../server/wrangler.toml) | Production `ALLOWED_ORIGINS` now also lists `https://spacearcade.davidandrea.ca`. **This only takes effect after the Worker is deployed.** Merging to `main` deploys it through CI. Until then ranked play and the boards in the app fail with `origin_not_allowed`, and practice still works. | +| CORS | [`server/wrangler.toml`](../server/wrangler.toml) | Production `ALLOWED_ORIGINS` now also lists `https://spacearcade.davidandrea.ca`. Deployed: production echoes this origin (verified 2026-11-04). If it were ever removed, ranked play and the boards in the app would fail with `origin_not_allowed`, and practice would still work. | | Android Back | [`src/platform/nativeBack.ts`](../src/platform/nativeBack.ts), [`nativeApp.ts`](../src/platform/nativeApp.ts) | `@capacitor/app`'s `backButton` event goes to the handler the current scene registered, which uses the same logic as Escape. **Title menu:** `MenuController.back()` closes the open page; on the root page the app is minimized. **A run:** `GameScene.goBack()` pauses, closes a pause page, resumes, or leaves a finished run. Back never leaves the app from a run in progress, and never throws away an unsubmitted ranked score. | | Pause / resume | `nativeApp.ts` | The app's `pause` / `resume` events are replayed as window `blur` / `focus`, which the existing listeners already handle. The run auto-pauses, music falls silent, held keys and touches are released, controllers go neutral, and vibration stops. WebView usually fires these itself; the native events are a backup. On resume the system bars are hidden again. | | Fullscreen | `capacitor.config.ts` (`SystemBars.hidden`), [`MainActivity.java`](../android/app/src/main/java/ca/davidandrea/spacearcade/MainActivity.java), [`fullscreen.ts`](../src/input/fullscreen.ts) | Capacitor 8's built-in SystemBars plugin hides the status and navigation bars. One native line sets "transient bars by swipe", which SystemBars has no option for: an edge swipe shows the bars over the game for a moment instead of bringing them back for good. The in-game FULLSCREEN button is hidden in the app, because Capacitor's WebView immediately ends Fullscreen API requests. | @@ -114,19 +116,5 @@ player installs an update from the store. That can mean days of review, or never ## Device checklist -Use a phone, plus a tablet or foldable for orientation. Use `chrome://inspect` on the PC for the WebView console and network. - -| # | Check | Expected | -|---|---|---| -| 1 | Cold start | Landscape, no status or navigation bar, no FULLSCREEN button on the title or pause screens, music starts. | -| 2 | Swipe from a screen edge mid-run | The bars appear over the game and hide again by themselves; the playfield does not resize. With gesture navigation, check how many swipes a Back gesture takes. | -| 3 | Back: playing → pause page → pause root → game over → title sub-page → title root | Pause, close page, resume, title, close page, app goes to the background. Back during a ranked run's result page never discards the score. | -| 4 | Home, recent apps, a phone call, the screen turned off mid-run | The game is paused on return, music is silent while away, no stuck controls, bars still hidden. | -| 5 | Notch or punch-hole camera, in both landscape directions | Touch controls and HUD clear the cutout; the band is black. The playfield stays in the same place, centred on the screen, when the phone is turned 180°. | -| 6 | Portrait on a large screen (orientation lock ignored) | Rotate prompt, run paused. | -| 7 | HAPTICS ON → TEST VIBRATION, then boost / laser / damage in a run | Felt. Also try with Samsung Silent mode. | -| 8 | Ranked end to end (after the Worker with the new `ALLOWED_ORIGINS` is deployed) | Challenge issued, run verified, rank shown. Turn on airplane mode during upload: retry works with the same submission. | -| 9 | Airplane mode from a cold start | Practice plays; RANKED and SCORES say unavailable, without a crash. | -| 10 | Nickname entry on the result page | The keyboard does not cover the field; Back with the keyboard open only closes the keyboard. | -| 11 | Bluetooth controller and keyboard | Work as in the browser. | -| 12 | 10-minute session | Smooth at 90/120 Hz, no unusual battery drain or heat. | +Moved to [phone-test-checklist.md](phone-test-checklist.md) (2026-11-12), which merges the twelve checks that were here with +install steps, ranked/retry/reporting checks and existing-install compatibility. diff --git a/phaser-asteroids/docs/google-play-release.md b/phaser-asteroids/docs/google-play-release.md index 9531b3d..a7637a9 100644 --- a/phaser-asteroids/docs/google-play-release.md +++ b/phaser-asteroids/docs/google-play-release.md @@ -7,7 +7,7 @@ Prepared 2026-11-03 on `dev`. **Local preparation only; nothing was published or Use the [production release preflight](../../docs/release-preflight.md) for the audited commit, staged 0003/0004 migration commands, backup/recovery and installed-client report. The main GitHub workflow deploys the Worker automatically and does not check schema; complete the authorized migration gates before triggering it. Latest local evidence is in [release validation](../../docs/play-release-validation.md); unsigned artifact success does not establish device, signing or Play readiness. - Approve `../../docs/privacy-policy-draft.md`, public contact, provider retention and target ages/content rating. Operator is David Andrea (confirmed 2026-11-04); choosing the public contact address is intentionally deferred and must be revisited before distribution. Replace bundled contact placeholders in `src/ui/menu/pages/privacy.ts`; synchronize policy text. Host the approved policy separately and provide its public URL to Play Console. Do not distribute a draft policy. -- **Done 2026-11-04:** migrations 0003/0004 (Stage 1) and the moderation Worker (Stage 2, version `c2aef78f`) are in production; see the [Stage 2 record](../../docs/release-preflight.md#stage-2-production-worker-deployment-2026-11-04). Historical note: pending migrations 0003 and 0004 and the reviewed Worker changes must eventually be deployed by an authorized operator before testers rely on reporting. This task does not authorize that deployment. Existing ranked requests are unchanged; production moderation availability has not been verified in this follow-up. Deploy the backend first: the updated app adds the suspicious_score report reason, while old report reasons remain supported. +- **Done 2026-11-04:** migrations 0003/0004 (Stage 1) and the moderation Worker (Stage 2, version `c2aef78f`) are in production and were verified (public 31/31, admin read-only 19/19); see the [Stage 2 record](../../docs/release-preflight.md#stage-2-production-worker-deployment-2026-11-04). The backend therefore already supports the app's suspicious_score report reason. The daily cleanup cron has run successfully every day since (verified read-only 2026-11-12; see the [current status](../../docs/release-preflight.md#current-status-2026-11-12)). For any later backend change, the backend still deploys before the app. - Establish report review coverage and the removal process in `../../docs/leaderboard-moderation.md`. Confirm production CORS still permits `https://spacearcade.davidandrea.ca` and `https://djblackett.github.io`. Do not loosen origins or expose admin credentials in the app. - Install Node/npm matching the lockfile/toolchain (validated here with Node 26.13.0/npm 11.20.0), JDK 21, Android SDK 36 and Build Tools 36.1.0. Use the committed Gradle wrapper 8.14.3 and AGP 8.13.0. `JAVA_HOME` selects JDK 21; check user Gradle properties/Android Studio settings do not override it. Do not commit local machine paths. Java source compatibility remains 17. @@ -72,6 +72,8 @@ Check every command's exit code before continuing (PowerShell does not automatic For verification **without signing credentials**, run the inspector with `-Unsigned` and use the same Gradle command with `-PallowUnsignedRelease=true`. That produces `android/app/build/outputs/bundle/release/app-release.aab` and `outputs/apk/release/app-release-unsigned.apk`, which must not be uploaded as a signed release. Build type remains release (WebView debugging disabled). The actual signed AAB has the same path; copy approved artifacts to a protected release archive and record SHA-256, source revision/dirty diff, lockfile hashes, tool versions, native versions and rules/schema. Inspect the artifact you will upload, not an earlier unsigned one. Verify signed AAB certificate with JDK `jarsigner -verify -verbose -certs `; compare fingerprint to the registered upload certificate. Use SDK `apksigner verify --print-certs ` for signed APKs. Do not print passwords. +Without `-Unsigned`, the inspector (since 2026-11-12) also requires both signatures to verify, refuses the Android debug certificate, refuses a debuggable APK in either mode, and refuses any bundled draft privacy marker (`[PRIVACY CONTACT PENDING]`, `DRAFT PRIVACY POLICY - REVIEW PENDING`); it lists every problem before failing. `-Unsigned` reports the markers as warnings. `-ApkPath`/`-AabPath` inspect copies. For phone testing before signing exists, follow the [phone test checklist](phone-test-checklist.md): it re-signs a copy of the unsigned release APK with the local debug key for sideloading only. + ## Manifest, SDK and memory-page checks Source targets/compiles API 36, min API 24; this satisfies the [current new-app API requirement](https://support.google.com/googleplay/android-developer/answer/11926878?hl=en) checked on 2026-11-03. Release is landscape; backup and cleartext disabled; launcher exported, FileProvider private. Inspect merged release manifest and lint report under `android/app/build/`, then run the artifact inspector. Expected permissions are INTERNET, VIBRATE and the generated signature-only AndroidX dynamic-receiver permission, with no advertising ID, location, microphone/camera or storage access. Confirm `debuggable` is false in release output. Test minimum-supported and current Android behavior, landscape, safe areas and Back on real hardware. diff --git a/phaser-asteroids/docs/phone-test-checklist.md b/phaser-asteroids/docs/phone-test-checklist.md new file mode 100644 index 0000000..2ab9037 --- /dev/null +++ b/phaser-asteroids/docs/phone-test-checklist.md @@ -0,0 +1,152 @@ +# Phone test checklist (sideload build) + +Prepared 2026-11-12 on `release/android-device-prep`. Replaces the earlier device checklist in [android.md](android.md#device-checklist). +This is a **local test build, not a release**: it is signed with this PC's Android debug key, carries the draft privacy text, and +cannot be uploaded to Play. Record results in the "Result" column and keep notes with the device model and Android version. + +## The build + +| | | +| --- | --- | +| **Install this** | `phaser-asteroids/android/app/build/outputs/apk/sideload/orbital-impact-1.0-sideload-debugkey.apk` | +| SHA-256 | `11FEB5AB4A3B7BDCD84FF291D7A22FE96A1B0AAA664FA5F95B2AD298692FE592` | +| What it is | The **release** build type (not debuggable, WebView debugging off) from the unsigned `app-release-unsigned.apk` (SHA-256 `284F84C1…FBD01C`, byte-identical to the 2026-11-04 audit APK), re-signed with `~/.android/debug.keystore` (`CN=Android Debug`, cert SHA-256 `884e8e7b…442f74`). v2+v3 signatures, 16 KB zip alignment verified. | +| Identity | `ca.davidandrea.spacearcade`, versionName `1.0`, versionCode `1`, min SDK 24, target 36. Permissions: INTERNET, VIBRATE, AndroidX dynamic-receiver (signature-only). | +| Gameplay | Frozen rules `1.2.0`, replay schema `1` (recorded in `server/rules/released.json`); production health reports supported `[1.2.0]`. | +| Backend | Production Worker `https://asteroids-leaderboard.davejandrea.workers.dev` (version `c2aef78f`). There is no test backend in this build. | +| Optional diagnostic build | `android/app/build/outputs/apk/debug/app-debug.apk` (SHA-256 `E49AC998…56093`): debuggable, so `chrome://inspect` on the PC shows the WebView console and network. Same package and same debug key, so `adb install -r` swaps between the two **without losing local data**. Use it only to diagnose a failure seen with the release build. | + +Rebuild (from `phaser-asteroids`, PowerShell, JDK 21): + +```powershell +$env:JAVA_HOME = 'C:\Program Files\Eclipse Adoptium\jdk-21.0.5.11-hotspot' +npm run android:sync +Push-Location android; .\gradlew.bat :app:assembleRelease -PallowUnsignedRelease=true --no-daemon --console=plain; Pop-Location +.\scripts\inspect-android-release.ps1 -Unsigned # expect PASS lines plus WARN for the draft privacy text +$bt = "$env:LOCALAPPDATA\Android\Sdk\build-tools\36.1.0" +New-Item -ItemType Directory -Force android\app\build\outputs\apk\sideload | Out-Null +# Debug keystore's public default password; this is not the upload key and must never sign a Play artifact. +& "$bt\apksigner.bat" sign --ks "$env:USERPROFILE\.android\debug.keystore" --ks-pass pass:android --ks-key-alias androiddebugkey --key-pass pass:android ` + --out android\app\build\outputs\apk\sideload\orbital-impact-1.0-sideload-debugkey.apk android\app\build\outputs\apk\release\app-release-unsigned.apk +``` + +The signed-release inspector (no `-Unsigned`) refuses this APK: debug key, plus draft privacy text. That is intended. + +## Before you start + +- **Ranked tests write to production.** A submitted score is a real public entry on both boards; a report is a real private report row. + Use a nickname you are content to have public (or Anonymous). As operator you can hide or erase test entries afterwards from the + Worker's `/admin` console, which also exercises the moderation workflow. Practice, boards and privacy screens write nothing. +- **Later Play installs:** a Play-signed build cannot update this debug-key install. Before installing from Play you must uninstall, + which deletes local settings, nickname, local bests and blocked names (server scores remain). + +## 1. Installation and first launch + +1. Phone: Settings > About phone > Software information > tap Build number 7 times; Developer options > USB debugging on. +2. Connect by **USB cable** and accept the RSA prompt. `adb devices -l` must show the phone as `device` (not `offline`/`unauthorized`). +3. Check for an existing install first: + `adb shell dumpsys package ca.davidandrea.spacearcade | findstr /i "versionCode versionName lastUpdateTime"` +4. Install: `adb install -r "C:\Users\davej\dev\asteroids-bootdev\phaser-asteroids\android\app\build\outputs\apk\sideload\orbital-impact-1.0-sideload-debugkey.apk"` + - `INSTALL_FAILED_UPDATE_INCOMPATIBLE` means an install signed with a different key exists. Note its version, then decide whether + to uninstall (loses its local data). Do not uninstall just to get past the error if you want section 9's evidence. +5. If several devices are attached, add `-s ` from `adb devices`. Useful while testing: `adb logcat -v time *:E chromium:I Capacitor:V`. + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 1.1 | Install command | `Success` | | +| 1.2 | Launcher | Icon present; label is currently `phaser-asteroids` (final name/icon deferred) | | +| 1.3 | Cold start | Splash, then title in landscape; no status/navigation bar; no FULLSCREEN button; music starts | | +| 1.4 | Force-stop and relaunch | Same; settings retained | | + +## 2. Orientation, safe areas and navigation + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 2.1 | Rotate the phone 180° in both landscape directions, at title and mid-run | Follows the sensor; the playfield stays centred; HUD and touch controls clear the camera cutout; any band is black | | +| 2.2 | Hold in portrait | Stays landscape (phones honour the lock). On a tablet/foldable ≥ 600 dp: rotate prompt, run paused | | +| 2.3 | Edge swipe mid-run | Bars appear over the game and hide again by themselves; playfield does not resize | | +| 2.4 | Back: in run → pause page → pause root → game over → title sub-page → title root | Pause, close page, resume, title, close page, app goes to background. Back never discards an unsubmitted ranked result | | +| 2.5 | Gesture navigation vs 3-button navigation (if switchable) | Back works in both; note how many swipes a Back gesture takes | | + +## 3. Touch controls and responsiveness + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 3.1 | Each control layout/movement mode offered in Controls | Rotate/thrust/fire/laser/boost respond immediately; no stuck input after lifting fingers | | +| 3.2 | Multi-touch: steer while firing and boosting | All register together | | +| 3.3 | 10-minute session | Smooth at the display's refresh rate (60/90/120 Hz); no stutter, unusual heat or battery drain | | +| 3.4 | Bluetooth controller and keyboard (if available) | Work as in the browser; menus navigable | | + +## 4. Audio, vibration and interruptions + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 4.1 | Music and effects; volume keys | Audible; volume keys change media volume | | +| 4.2 | HAPTICS ON → TEST VIBRATION, then boost/laser/damage in a run | Felt; also with Samsung Silent/Vibrate mode | | +| 4.3 | Home, recents, screen off, incoming call or alarm mid-run | On return the run is paused, music silent while away, no stuck controls, bars still hidden | | +| 4.4 | Headphones / Bluetooth audio connect and disconnect mid-run | No crash; audio routes sensibly | | + +## 5. Offline Practice + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 5.1 | Airplane mode, then cold start | Title loads; Practice plays fully | | +| 5.2 | RANKED and HIGH SCORES while offline | Clear "unavailable" message; no crash or endless spinner | | +| 5.3 | Privacy pages offline | All 4 pages readable (bundled) | | + +## 6. Ranked challenge, submission and leaderboards (writes to production) + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 6.1 | Start RANKED online | Challenge issued; run starts | | +| 6.2 | Finish; result page; Privacy / Leaderboard Rules link next to Submit | Rules readable; Back returns to the result without losing it | | +| 6.3 | Nickname entry | Keyboard does not cover the field; Back with keyboard open only closes it | | +| 6.4 | Submit | Verified; rank shown; entry appears on weekly and all-time boards and its detail page | | +| 6.5 | A name the server rejects (`invalid_nickname`), then correct it or choose Anonymous | Clear message; corrected submission accepted; run not lost | | +| 6.6 | Board paging; personal bests | Pages load; your accepted score listed locally | | + +## 7. Submission retry after interrupted connectivity + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 7.1 | Finish a ranked run, enable airplane mode, press Submit | Failure message with retry; result kept | | +| 7.2 | Disable airplane mode, retry | Accepted once; exactly one new board entry (no duplicate) | | +| 7.3 | Airplane mode **during** upload (toggle right after Submit) | Retry returns the same result; no duplicate | | +| 7.4 | Background the app on the result page for > 1 hour, then submit | Expired-run message, not a crash (challenge TTL is 1 hour) | | + +## 8. Reporting, blocking and privacy screens + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 8.1 | PRIVACY menu: all 4 pages, NEXT/BACK | Readable at phone size; shows the **draft** marker and `[PRIVACY CONTACT PENDING]` (expected until the policy is approved) | | +| 8.2 | HIGH SCORES > REPORT / BLOCK > Report your own test entry (writes a private report) | Success message (note what a second report of the same entry shows; the server keeps one report per entry and network); the entry appears in `/admin` Needs review | | +| 8.3 | Block that nickname | Entries with that name replaced on this device; survives app restart | | +| 8.4 | Unblock | Entries return | | +| 8.5 | Operator: hide or rename the test entry in `/admin`, then refresh the board in the app | Change visible on next refresh (no-store) | | + +## 9. Existing-install compatibility + +No historical signed release exists (versionCode 1 has never been distributed). The only possible earlier installs are developer builds +signed with this PC's debug key, which this APK can update in place. + +| # | Check | Expected | Result | +| --- | --- | --- | --- | +| 9.1 | Step 1.3 found an earlier build: record its versionCode/lastUpdateTime, then `adb install -r` | Updates without uninstalling | | +| 9.2 | After the update | Settings, last nickname, local bests and blocked names are kept (same origin `https://spacearcade.davidandrea.ca`) | | +| 9.3 | Ranked on the updated install | As section 6 | | +| 9.4 | Signature-mismatch error instead | Record the installed build's provenance; this is the case a Play-signed build will hit (uninstall required) | | + +## Already covered by automation (2026-11-12, do not repeat by hand) + +- Unit: 67 files / 1,669 tests (includes Back routing, lifecycle replay as blur/focus, plugin failures, Android config agreement, + draft-marker guard). Android build guard 8/8; rules/health guards 19/19; rules guard: 0 changes to released rules since `main`. +- `android:sync`: production HTTPS origin baked in, frozen rules recorded, no server verifier packaged. +- Gradle `bundleRelease assembleRelease lintRelease` (unsigned audit flag): success; lint 0 errors / 14 known warnings + (icons/unused resources/orientation). +- Inspector: package, target 36, not debuggable, only expected permissions, no `.so` libraries (16 KB ELF alignment not applicable). +- Earlier desktop Chromium suites (2026-11-04 at `549729f`, unchanged packaged sources): ranked UI 99/99 (touch submission, + retry, expiry, reporting/blocking), menu 127/127 (privacy layouts at phone sizes), worker-e2e 33/33, moderation admin 28/28. + +Automation cannot show real WebView rendering, touch latency, audio focus, vibration, cutouts, system gestures, OEM lifecycle +behaviour or 16 KB-page runtime. Those are the checks above. A 16 KB device/emulator and a Play-delivered install remain separate +gates (see [google-play-release.md](google-play-release.md)). From 0ebef431136722686e6333eca12896f74cc01410 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:23:23 -0400 Subject: [PATCH 04/14] fix(test): restore frontend typecheck broken by 4c0af25 The draft-marker test passed a possibly undefined capture group to toContain's message, which tsc rejects. npm run build (and every suite that builds first, e.g. test:worker) failed at the typecheck step. Co-Authored-By: Claude Opus 5.5 --- phaser-asteroids/tests/androidRelease.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phaser-asteroids/tests/androidRelease.test.ts b/phaser-asteroids/tests/androidRelease.test.ts index 30e3657..6e0e756 100644 --- a/phaser-asteroids/tests/androidRelease.test.ts +++ b/phaser-asteroids/tests/androidRelease.test.ts @@ -62,7 +62,7 @@ describe('Android app configuration', () => { const listed = [...(inspector.match(/\$draftPolicyMarkers = @\(([^)]*)\)/)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]); expect(listed.length).toBeGreaterThan(0); // Read as text: importing the menu page would pull in Phaser. Every quoted literal with an upper-case review marker counts. - const draftLines = [...read('src/ui/menu/pages/privacy.ts').matchAll(/'((?:[^'\\\n]|\\.)*)'/g)].map((m) => m[1]).filter((line) => /PENDING|DRAFT/.test(line)); + const draftLines = [...read('src/ui/menu/pages/privacy.ts').matchAll(/'((?:[^'\\\n]|\\.)*)'/g)].map((m) => m[1]!).filter((line) => /PENDING|DRAFT/.test(line)); for (const line of draftLines) expect(listed, `inspector does not refuse "${line}"`).toContain(line); }); From 9813dd55b3424bd80e130eff2d0eaef87b94735f Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:40:12 -0400 Subject: [PATCH 05/14] feat(server): daily moderation email digest on the existing cron After the unchanged daily cleanup, the scheduled handler sends one short email when the console's Needs review queue is not empty (or open reports just expired unreviewed). It carries counts by reason, integrity flags, expiring/expired report counts and the /admin link; no names, score IDs, reporter/IP hashes or replay data. It never changes moderation state. - Delivery via Resend's HTTPS API with fetch (no new dependency). Disabled until RESEND_API_KEY, MODERATION_DIGEST_FROM/TO and MODERATION_DASHBOARD_URL are all set; disabled path touches no table. - Migration 0005 (additive) adds moderation_digests: one atomically claimed row per UTC day of scheduledTime, storing the text so every retry resends the same payload under one Idempotency-Key. 3 claims a day, one immediate retry for transient errors, 10-minute lease for abandoned sends, permanent errors wait for the next day. - Digest errors are caught (API key redacted); cleanup always runs first and a cleanup failure still fails the invocation. - pruneReports keeps the 30-day rule and now reports how many deleted reports were still open. - Production vars: recipient privacy@davidandrea.ca and the console URL only. Sender and API key are not configured. Tests: digest.test.ts (19), workerd e2e with a loopback mock provider, and an additive-0005 stage in the release migration rehearsal. Co-Authored-By: Claude Opus 5.5 --- .../scripts/release-migration-check.mjs | 9 + phaser-asteroids/server/.dev.vars.example | 6 + .../migrations/0005_moderation_digest.sql | 15 + .../server/scripts/worker-e2e.mjs | 41 +- phaser-asteroids/server/src/config.ts | 8 +- phaser-asteroids/server/src/digest.ts | 259 +++++++++++++ phaser-asteroids/server/src/moderation.ts | 19 +- phaser-asteroids/server/src/scheduled.ts | 38 ++ phaser-asteroids/server/src/worker.ts | 18 +- phaser-asteroids/server/tests/digest.test.ts | 359 ++++++++++++++++++ .../server/tests/moderation.test.ts | 4 +- phaser-asteroids/server/wrangler.toml | 6 + 12 files changed, 761 insertions(+), 21 deletions(-) create mode 100644 phaser-asteroids/server/migrations/0005_moderation_digest.sql create mode 100644 phaser-asteroids/server/src/digest.ts create mode 100644 phaser-asteroids/server/src/scheduled.ts create mode 100644 phaser-asteroids/server/tests/digest.test.ts diff --git a/phaser-asteroids/scripts/release-migration-check.mjs b/phaser-asteroids/scripts/release-migration-check.mjs index 2c7252b..1fe34e5 100644 --- a/phaser-asteroids/scripts/release-migration-check.mjs +++ b/phaser-asteroids/scripts/release-migration-check.mjs @@ -165,6 +165,15 @@ try { check('actual linked run deleted and unrelated run preserved', query(`SELECT * FROM runs WHERE id='run-${target}'`).length === 0 && JSON.stringify(query(`SELECT * FROM runs WHERE id='run-${ids[2]}'`)) === JSON.stringify(otherRun)); check('final foreign-key integrity and complete migration ledger', query('PRAGMA foreign_key_check').length === 0 && query('SELECT name FROM d1_migrations').length === 4); await stop(); + // 0005 (moderation digest ledger) is additive: stage it alone on the used 0004 database; no existing row may change. + const tables0004 = () => JSON.stringify(['scores', 'runs', 'score_reports', 'moderation_audit', 'rate_limits'].map(t => query(`SELECT * FROM ${t} ORDER BY 1, 2`))); + const before0005 = tables0004(); + stage('0005_moderation_digest.sql'); + check('additive 0005 applies after 0004 and changes no existing row', migrate().ok && tables0004() === before0005 && query('SELECT COUNT(*) AS n FROM moderation_digests')[0].n === 0); + check('ledger records exactly 0001-0005 with valid foreign keys', query('PRAGMA foreign_key_check').length === 0 && JSON.stringify(query('SELECT name FROM d1_migrations ORDER BY id').map(r => r.name.slice(0, 4))) === '["0001","0002","0003","0004","0005"]'); + await start(old); + check('historical Worker still serves boards on the 0005 schema', (await client.fetchLeaderboard(base, 'all-time', { limit: 10, offset: 0 }, legacyFetch)).total >= 1); + await stop(); const exportFile = path.join(temp, 'recovery.sql'); const exported = cli(current, ['d1', 'export', 'asteroids-leaderboard', '--local', '--output', exportFile]); assert.ok(exported.ok, exported.output); diff --git a/phaser-asteroids/server/.dev.vars.example b/phaser-asteroids/server/.dev.vars.example index 013e0fa..cc1b3d8 100644 --- a/phaser-asteroids/server/.dev.vars.example +++ b/phaser-asteroids/server/.dev.vars.example @@ -3,3 +3,9 @@ ADMIN_TOKEN=change-me-to-a-long-random-string # Salt for hashing client IPs into rate-limit buckets. IP_HASH_SALT=change-me-too +# Optional daily moderation digest (see ../../docs/leaderboard-moderation.md#daily-moderation-digest). Leave unset locally: +# it is disabled unless all four are present. Never use a real recipient or production key in local testing. +# RESEND_API_KEY= +# MODERATION_DIGEST_FROM=Orbital Impact +# MODERATION_DIGEST_TO=operator@example.test +# MODERATION_DASHBOARD_URL=http://127.0.0.1:8787/admin diff --git a/phaser-asteroids/server/migrations/0005_moderation_digest.sql b/phaser-asteroids/server/migrations/0005_moderation_digest.sql new file mode 100644 index 0000000..ce6793d --- /dev/null +++ b/phaser-asteroids/server/migrations/0005_moderation_digest.sql @@ -0,0 +1,15 @@ +-- One row per UTC day on which a moderation digest was due. It makes the daily email idempotent across cron retries and +-- duplicate invocations, and keeps the exact text so a retry resends the identical payload under the same provider +-- idempotency key. Contents are aggregate counts and the console URL only: no names, score IDs, reporter or IP hashes. +-- Additive: no existing table changes. Rows older than 30 days are removed by the digest itself. +CREATE TABLE moderation_digests ( + day TEXT PRIMARY KEY, + status TEXT NOT NULL CHECK (status IN ('sending', 'sent', 'failed')), + attempts INTEGER NOT NULL, + claimed_at INTEGER NOT NULL, + subject TEXT NOT NULL, + body TEXT NOT NULL, + provider_id TEXT, + error TEXT, + updated_at INTEGER NOT NULL +) WITHOUT ROWID; diff --git a/phaser-asteroids/server/scripts/worker-e2e.mjs b/phaser-asteroids/server/scripts/worker-e2e.mjs index 735fd4e..107e795 100644 --- a/phaser-asteroids/server/scripts/worker-e2e.mjs +++ b/phaser-asteroids/server/scripts/worker-e2e.mjs @@ -8,6 +8,7 @@ // 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 http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; @@ -37,16 +38,33 @@ const migrate = spawnSync(process.execPath, [wranglerBin, 'd1', 'migrations', 'a 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. +// 2. A local stand-in for the email provider (Resend's POST /emails contract). The digest never leaves this machine. +const MAIL_PORT = PORT + 1; +const mail = []; +const mailServer = http.createServer((req, res) => { + let raw = ''; + req.on('data', (d) => (raw += d)); + req.on('end', () => { + mail.push({ method: req.method, url: req.url, headers: req.headers, body: raw }); + res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ id: `e2e-msg-${mail.length}` })); + }); +}); +await new Promise((resolve) => mailServer.listen(MAIL_PORT, '127.0.0.1', resolve)); +const DIGEST_VARS = [ + 'RESEND_API_KEY:re_e2e_local_only', 'MODERATION_DIGEST_FROM:Orbital Impact ', 'MODERATION_DIGEST_TO:operator@digest.test', + `MODERATION_DASHBOARD_URL:${BASE}/admin`, `RESEND_API_URL:http://127.0.0.1:${MAIL_PORT}/emails`, +].flatMap((v) => ['--var', v]); + +// 3. 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'], + [wranglerBin, 'dev', '--local', '--port', String(PORT), '--persist-to', persist, '--test-scheduled', '--var', `ADMIN_TOKEN:${ADMIN}`, '--var', 'IP_HASH_SALT:e2e-salt', ...DIGEST_VARS], { 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(); +const stop = () => { worker.kill(); mailServer.close(); }; process.on('exit', stop); async function waitReady() { @@ -198,8 +216,25 @@ try { 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); + // --- daily cron: cleanup + moderation digest (real D1 claim/upsert, real Worker fetch to the local mock provider) -------------- + const reportedId = accepted[0].json.score.id; + const reported = await api('POST', `/api/v1/scores/${reportedId}/report`, { body: '{"reason":"offensive"}', headers: { 'content-type': 'application/json' } }); + check('a player report is accepted', reported.status === 200, `status=${reported.status}`); const cron = await fetch(`${BASE}/__scheduled?cron=17+7+*+*+*`); check('scheduled cleanup handler runs', cron.status === 200, `status=${cron.status}`); + const cronAgain = await fetch(`${BASE}/__scheduled?cron=17+7+*+*+*`); + check('a repeated cron invocation on the same day also succeeds', cronAgain.status === 200, `status=${cronAgain.status}`); + for (let i = 0; i < 25 && !(log.includes('"status":"skipped"') && mail.length); i++) await sleep(200); + check('moderation digest: exactly one email for two cron runs on one day', mail.length === 1, `emails=${mail.length}`); + const digest = mail[0] ? JSON.parse(mail[0].body) : {}; + check('digest request: bearer key, daily idempotency key, recipient and short aggregate text', + mail[0]?.method === 'POST' && mail[0].url === '/emails' && mail[0].headers.authorization === 'Bearer re_e2e_local_only' + && /^orbital-impact-moderation-digest-\d{4}-\d{2}-\d{2}$/.test(mail[0].headers['idempotency-key'] ?? '') + && JSON.stringify(digest.to) === '["operator@digest.test"]' && digest.subject === 'Orbital Impact — 1 moderation item awaiting review' + && digest.text?.includes('Offensive name: 1') && digest.text.includes(`Review: ${BASE}/admin`), + JSON.stringify({ subject: digest.subject, key: mail[0]?.headers['idempotency-key'] })); + check('digest contains no nickname, score ID or credential', !!digest.text && !/E2E Pilot|Hide Me/.test(digest.text) && !digest.text.includes(reportedId) && !mail[0].body.includes(ADMIN)); + check('worker logged sent, then skipped, and cleanup both times', log.includes('"evt":"moderation_digest","status":"sent"') && log.includes('"evt":"moderation_digest","status":"skipped"') && (log.match(/"evt":"prune"/g) ?? []).length >= 2); // --- rate limiting (last: it exhausts this client's start budget) --------------------------------------------------------- let limited = null; diff --git a/phaser-asteroids/server/src/config.ts b/phaser-asteroids/server/src/config.ts index 11c4a35..7165467 100644 --- a/phaser-asteroids/server/src/config.ts +++ b/phaser-asteroids/server/src/config.ts @@ -1,6 +1,7 @@ import type { GameConfig } from '../../src/core/gameConfig'; import { FIXED_TICK_RATE, GAMEPLAY_RULES_VERSION } from '../../src/replay/constants'; import type { D1Like } from './d1'; +import type { DigestEnv } from './digest'; /** * The only gameplay configuration a ranked run may use: the classic one-player game. The server issues it with every @@ -17,8 +18,11 @@ export const RANKED_CONFIG: Readonly = Object.freeze({ export const RANKED_RULES_VERSION = GAMEPLAY_RULES_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 { +/** + * Bindings and variables the Worker receives (see wrangler.toml). Everything except `DB` is optional so local runs need no setup. + * The moderation digest settings (RESEND_API_KEY, MODERATION_DIGEST_*) are declared in digest.ts. + */ +export interface Env extends DigestEnv { 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; diff --git a/phaser-asteroids/server/src/digest.ts b/phaser-asteroids/server/src/digest.ts new file mode 100644 index 0000000..9f34065 --- /dev/null +++ b/phaser-asteroids/server/src/digest.ts @@ -0,0 +1,259 @@ +import type { Db } from './db'; +import { QUEUE_SQL, REPORT_RETENTION_MS, SUSPICIOUS_SQL } from './moderation'; + +/** + * Daily moderation digest: one short email to the operator, only on days when the console's "Needs review" queue is not empty + * (or open reports reached the 30-day retention limit unreviewed). It reads the queue and never changes moderation state: nothing + * is hidden, renamed, deleted or resolved here. Runs from the existing daily cron after cleanup (see scheduled.ts). + * + * Delivery: Resend's HTTPS API through plain fetch (no SDK). Disabled until every setting below is present; see + * ../../docs/leaderboard-moderation.md#daily-moderation-digest for the operator setup. + * + * Duplicates: `moderation_digests` (migration 0005) holds one row per UTC day of the cron's scheduled time. A day is claimed + * atomically, at most MAX_ATTEMPTS_PER_DAY times, and every attempt resends the stored text under the same Idempotency-Key, so + * a cron retry, a duplicate invocation or an ambiguous timeout cannot produce a second email (Resend keeps keys for 24 hours). + * A failure is retried by the next day's run if items remain, so an outage costs at most a few API calls per day. + */ +export interface DigestEnv { + /** Resend API key (secret: `wrangler secret put RESEND_API_KEY --env production`). Unset: the digest is disabled. */ + RESEND_API_KEY?: string; + /** Sender on a domain verified in Resend, e.g. `Orbital Impact `. */ + MODERATION_DIGEST_FROM?: string; + /** Recipient (one address). */ + MODERATION_DIGEST_TO?: string; + /** Link to the operator console, e.g. `https:///admin`. */ + MODERATION_DASHBOARD_URL?: string; + /** Override for local integration tests only: an https URL or a loopback http URL. Default RESEND_API_URL. */ + RESEND_API_URL?: string; +} + +export interface DigestConfig { + apiKey: string; + apiUrl: string; + from: string; + to: string; + dashboardUrl: string; +} + +export const RESEND_API_URL = 'https://api.resend.com/emails'; +/** Claims per UTC day, including takeovers of an abandoned send. Each claim makes at most two HTTP requests. */ +export const MAX_ATTEMPTS_PER_DAY = 3; +/** A claim this old with no recorded outcome is treated as abandoned (the Worker died mid-send) and can be retried. */ +export const SEND_LEASE_MS = 10 * 60_000; +export const SEND_TIMEOUT_MS = 10_000; +export const RETRY_DELAY_MS = 2_000; +/** Digest ledger rows hold counts only; they are kept a month for troubleshooting. */ +export const DIGEST_ROW_RETENTION_MS = 30 * 86_400_000; +/** Open reports this close to the retention limit are called out as expiring. */ +export const EXPIRY_WARNING_MS = 7 * 86_400_000; + +const ADDRESS = /^[^\s@<>"',;]+@[^\s@<>"',;]+\.[^\s@<>"',;]+$/; + +function validSender(value: string): boolean { + const named = /^([^<>"\r\n]{1,80}) <([^<>]+)>$/.exec(value); + return ADDRESS.test(named ? named[2]! : value); +} + +function validUrl(value: string): boolean { + try { + const url = new URL(value); + return url.protocol === 'https:' || (url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)); + } catch { + return false; + } +} + +/** Never returns or logs a setting's value; only which names are missing or invalid. */ +export function loadDigestConfig(env: DigestEnv): { ok: true; config: DigestConfig } | { ok: false; reason: string } { + const get = (name: keyof DigestEnv) => env[name]?.trim() ?? ''; + const required = ['RESEND_API_KEY', 'MODERATION_DIGEST_FROM', 'MODERATION_DIGEST_TO', 'MODERATION_DASHBOARD_URL'] as const; + const missing = required.filter((name) => !get(name)); + if (missing.length === required.length) return { ok: false, reason: 'not_configured' }; + if (missing.length) return { ok: false, reason: `incomplete:${missing.join(',')}` }; + const apiUrl = get('RESEND_API_URL') || RESEND_API_URL; + const invalid = [ + ...(validSender(get('MODERATION_DIGEST_FROM')) ? [] : ['MODERATION_DIGEST_FROM']), + ...(ADDRESS.test(get('MODERATION_DIGEST_TO')) ? [] : ['MODERATION_DIGEST_TO']), + ...(validUrl(get('MODERATION_DASHBOARD_URL')) ? [] : ['MODERATION_DASHBOARD_URL']), + ...(validUrl(apiUrl) ? [] : ['RESEND_API_URL']), + ]; + if (invalid.length) return { ok: false, reason: `invalid:${invalid.join(',')}` }; + return { + ok: true, + config: { apiKey: get('RESEND_API_KEY'), apiUrl, from: get('MODERATION_DIGEST_FROM'), to: get('MODERATION_DIGEST_TO'), dashboardUrl: get('MODERATION_DASHBOARD_URL') }, + }; +} + +export const REPORT_REASON_LABELS = [ + ['offensive', 'Offensive name'], + ['personal_info', 'Personal information'], + ['suspicious_score', 'Suspected cheating'], + ['other', 'Other'], +] as const; + +export interface QueueSummary { + /** Entries in the console's "Needs review" view: open reports and/or an unreviewed integrity flag. */ + entries: number; + reportedEntries: number; + openReports: Record; + /** Entries with an unreviewed integrity flag. */ + flaggedEntries: number; + /** Open reports that reach the retention limit within EXPIRY_WARNING_MS. */ + expiringSoon: number; +} + +export async function queueSummary(db: Db, now: number): Promise { + const row = await db.first<{ entries: number; reportedEntries: number; flaggedEntries: number; expiringSoon: number }>( + `SELECT (SELECT COUNT(*) FROM scores s WHERE ${QUEUE_SQL}) AS entries, + (SELECT COUNT(DISTINCT score_id) FROM score_reports WHERE status = 'open') AS reportedEntries, + (SELECT COUNT(*) FROM scores s WHERE ${SUSPICIOUS_SQL} AND s.suspicion_reviewed = 0) AS flaggedEntries, + (SELECT COUNT(*) FROM score_reports WHERE status = 'open' AND created_at < ?) AS expiringSoon`, + [now - (REPORT_RETENTION_MS - EXPIRY_WARNING_MS)], + ); + const reasons = await db.all<{ reason: string; n: number }>("SELECT reason, COUNT(*) AS n FROM score_reports WHERE status = 'open' GROUP BY reason"); + return { + entries: row?.entries ?? 0, + reportedEntries: row?.reportedEntries ?? 0, + flaggedEntries: row?.flaggedEntries ?? 0, + expiringSoon: row?.expiringSoon ?? 0, + openReports: Object.fromEntries(reasons.map((r) => [r.reason, r.n])), + }; +} + +const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`; + +/** Aggregate counts and the console link only. Returns null when nothing needs attention (no email). */ +export function composeDigest(day: string, s: QueueSummary, expiredUnresolved: number, dashboardUrl: string): { subject: string; text: string } | null { + if (s.entries === 0 && expiredUnresolved === 0) return null; + const subject = s.entries > 0 + ? `Orbital Impact — ${plural(s.entries, 'moderation item', 'moderation items')} awaiting review` + : `Orbital Impact — ${plural(expiredUnresolved, 'unreviewed report', 'unreviewed reports')} expired`; + const totalReports = Object.values(s.openReports).reduce((a, b) => a + b, 0); + const lines = [`Orbital Impact moderation digest for ${day} (UTC)`, '', `Needs review: ${plural(s.entries, 'entry', 'entries')}`]; + if (totalReports) { + lines.push(`- Open player reports: ${totalReports} on ${plural(s.reportedEntries, 'entry', 'entries')}`); + for (const [reason, label] of REPORT_REASON_LABELS) if (s.openReports[reason]) lines.push(` ${label}: ${s.openReports[reason]}`); + for (const [reason, n] of Object.entries(s.openReports)) { + if (!REPORT_REASON_LABELS.some(([known]) => known === reason)) lines.push(` Other (${reason.replace(/[^a-z_]/g, '').slice(0, 30)}): ${n}`); + } + } + if (s.flaggedEntries) lines.push(`- Unreviewed integrity flags: ${s.flaggedEntries}`); + if (s.expiringSoon) lines.push('', `Expiring: ${plural(s.expiringSoon, 'open report reaches', 'open reports reach')} the 30-day retention limit within 7 days and will then be deleted unreviewed.`); + if (expiredUnresolved) lines.push('', `Expired: ${plural(expiredUnresolved, 'open report', 'open reports')} reached the 30-day limit and ${expiredUnresolved === 1 ? 'was' : 'were'} deleted without review. The entries themselves are unchanged.`); + lines.push('', `Review: ${dashboardUrl}`, '', 'Nothing was hidden, renamed or deleted automatically. This digest is sent at most once a day while items remain open.'); + return { subject, text: lines.join('\n') + '\n' }; +} + +export type SendResult = { ok: true; id: string | null } | { ok: false; retryable: boolean; error: string }; +export type Sender = (message: { subject: string; text: string }, idempotencyKey: string) => Promise; + +/** Resend over fetch. Errors are reduced to a status and provider error name; response messages and secrets are never surfaced. */ +export function resendSender(config: DigestConfig, fetchImpl: typeof fetch = fetch, timeoutMs = SEND_TIMEOUT_MS): Sender { + return async (message, idempotencyKey) => { + let res: Response; + try { + res = await fetchImpl(config.apiUrl, { + method: 'POST', + headers: { + Authorization: `Bearer ${config.apiKey}`, + 'Content-Type': 'application/json', + 'Idempotency-Key': idempotencyKey, + 'User-Agent': 'orbital-impact-moderation-digest', + }, + body: JSON.stringify({ from: config.from, to: [config.to], subject: message.subject, text: message.text }), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (e) { + const name = e instanceof Error ? e.name : ''; + return { ok: false, retryable: true, error: name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network_error' }; + } + type Body = { id?: unknown; name?: unknown } | null; + const data: Body = await res.json().then((v) => (v && typeof v === 'object' ? v as Body : null), () => null); + if (res.ok) return { ok: true, id: typeof data?.id === 'string' ? data.id.slice(0, 100) : null }; + const name = typeof data?.name === 'string' ? data.name.replace(/[^a-z0-9_]/gi, '').slice(0, 60) : ''; + // 409 concurrent_idempotent_requests: another attempt with this key is still in flight; safe to retry. Other 4xx + // (bad key, unverified sender, payload mismatch) need operator action, so they are not retried the same day. + const retryable = res.status === 408 || res.status === 429 || res.status >= 500 || name === 'concurrent_idempotent_requests'; + return { ok: false, retryable, error: `http_${res.status}${name ? `:${name}` : ''}` }; + }; +} + +export type DigestOutcome = + | { status: 'disabled'; reason: string } + | { status: 'empty' } + | { status: 'skipped'; day: string } + | { status: 'sent'; day: string; entries: number; attempt: number } + | { status: 'failed'; day: string; entries: number; attempt: number; error: string; retryable: boolean } + | { status: 'error'; error: string }; + +export interface DigestDeps { + db: Db; + env: DigestEnv; + now: number; + /** The cron event's scheduled time: retries of one event fall on the same day key. */ + scheduledTime: number; + /** Open reports the cleanup that just ran deleted at the retention limit. */ + expiredUnresolved: number; + send?: Sender; + fetch?: typeof fetch; + sleep?: (ms: number) => Promise; +} + +const day = (t: number) => new Date(t).toISOString().slice(0, 10); + +/** Never throws: a digest problem must not fail the scheduled cleanup it runs after. */ +export async function runModerationDigest(deps: DigestDeps): Promise { + try { + return await digest(deps); + } catch (e) { + const key = deps.env.RESEND_API_KEY?.trim(); + const message = key ? String(e).split(key).join('[redacted]') : String(e); + return { status: 'error', error: message.slice(0, 200) }; + } +} + +async function digest({ db, env, now, scheduledTime, expiredUnresolved, ...opts }: DigestDeps): Promise { + const loaded = loadDigestConfig(env); + if (!loaded.ok) return { status: 'disabled', reason: loaded.reason }; + const config = loaded.config; + const today = day(scheduledTime); + await db.run('DELETE FROM moderation_digests WHERE day < ?', [day(now - DIGEST_ROW_RETENTION_MS)]); + + const summary = await queueSummary(db, now); + const message = composeDigest(today, summary, expiredUnresolved, config.dashboardUrl); + if (!message) return { status: 'empty' }; + + // Claim the day. A conflicting row is taken over only after a failure or an abandoned send, and never beyond the daily cap. + // The stored subject/body are kept, so every attempt for a day sends an identical payload under one idempotency key. + const claim = await db.first<{ subject: string; body: string; attempts: number }>( + `INSERT INTO moderation_digests (day, status, attempts, claimed_at, subject, body, updated_at) VALUES (?, 'sending', 1, ?, ?, ?, ?) + ON CONFLICT (day) DO UPDATE SET status = 'sending', attempts = moderation_digests.attempts + 1, claimed_at = excluded.claimed_at, + updated_at = excluded.updated_at, error = NULL + WHERE (moderation_digests.status = 'failed' OR (moderation_digests.status = 'sending' AND moderation_digests.claimed_at < ?)) + AND moderation_digests.attempts < ? + RETURNING subject, body, attempts`, + [today, now, message.subject, message.text, now, now - SEND_LEASE_MS, MAX_ATTEMPTS_PER_DAY], + ); + if (!claim) return { status: 'skipped', day: today }; + + const send = opts.send ?? resendSender(config, opts.fetch); + const sleep = opts.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const key = `orbital-impact-moderation-digest-${today}`; + const payload = { subject: claim.subject, text: claim.body }; + let result = await send(payload, key); + if (!result.ok && result.retryable) { + await sleep(RETRY_DELAY_MS); + result = await send(payload, key); + } + if (result.ok) { + await db.run("UPDATE moderation_digests SET status = 'sent', provider_id = ?, error = NULL, updated_at = ? WHERE day = ?", [result.id, now, today]); + return { status: 'sent', day: today, entries: summary.entries, attempt: claim.attempts }; + } + // A non-retryable error exhausts today's attempts; tomorrow's run tries again if items remain. + await db.run( + `UPDATE moderation_digests SET status = 'failed', error = ?, updated_at = ?, + attempts = CASE WHEN ? = 1 THEN attempts ELSE MAX(attempts, ?) END WHERE day = ?`, + [result.error, now, result.retryable ? 1 : 0, MAX_ATTEMPTS_PER_DAY, today], + ); + return { status: 'failed', day: today, entries: summary.entries, attempt: claim.attempts, error: result.error, retryable: result.retryable }; +} diff --git a/phaser-asteroids/server/src/moderation.ts b/phaser-asteroids/server/src/moderation.ts index 8b05918..1007eb9 100644 --- a/phaser-asteroids/server/src/moderation.ts +++ b/phaser-asteroids/server/src/moderation.ts @@ -24,8 +24,18 @@ export async function reportScore(db: Db, scoreId: string, reporterHash: string, } } -export async function pruneReports(db: Db, now: number): Promise { - return (await db.run('DELETE FROM score_reports WHERE created_at < ?', [now - 30 * 86_400_000])).changes; +/** Published retention for reports: deleted by the daily cleanup once older than this, open or resolved. */ +export const REPORT_RETENTION_MS = 30 * 86_400_000; + +/** + * Daily retention cleanup. `unresolved` counts the deleted reports that were still open, so expiry without review is announced + * in the moderation digest instead of passing silently. The retention period itself is unchanged. + */ +export async function pruneReports(db: Db, now: number): Promise<{ deleted: number; unresolved: number }> { + const cutoff = now - REPORT_RETENTION_MS; + const open = await db.first<{ n: number }>("SELECT COUNT(*) AS n FROM score_reports WHERE created_at < ? AND status = 'open'", [cutoff]); + const deleted = (await db.run('DELETE FROM score_reports WHERE created_at < ?', [cutoff])).changes; + return { deleted, unresolved: Math.min(open?.n ?? 0, deleted) }; } /** Operator-only erasure: atomic, scores before their FK parent; related reports cascade. */ @@ -116,9 +126,12 @@ export async function setScoreVisibility(db: Db, id: string, visible: boolean, r return true; } +/** The console's "Needs review" view (alias `s` = scores). The daily digest counts exactly these entries. */ +export const QUEUE_SQL = `(EXISTS (SELECT 1 FROM score_reports r WHERE r.score_id = s.id AND r.status = 'open') OR (${SUSPICIOUS_SQL} AND s.suspicion_reviewed = 0))`; + export async function adminScores(db: Db, filter: string, before: number | null, id: string | null) { const filters: Record = { - queue: `(EXISTS (SELECT 1 FROM score_reports r WHERE r.score_id = s.id AND r.status = 'open') OR (${SUSPICIOUS_SQL} AND s.suspicion_reviewed = 0))`, + queue: QUEUE_SQL, hidden: "s.visibility = 'hidden'", all: '1=1', }; if (!Object.hasOwn(filters, filter)) throw new ApiError(400, 'invalid_filter', 'Choose queue, hidden or all'); diff --git a/phaser-asteroids/server/src/scheduled.ts b/phaser-asteroids/server/src/scheduled.ts new file mode 100644 index 0000000..66177f0 --- /dev/null +++ b/phaser-asteroids/server/src/scheduled.ts @@ -0,0 +1,38 @@ +import { loadSettings, type Env } from './config'; +import type { Db } from './db'; +import { runModerationDigest, type DigestOutcome, type Sender } from './digest'; +import { pruneReports } from './moderation'; +import { pruneRateLimits } from './ratelimit'; +import { pruneStaleRuns } from './runs'; + +export interface ScheduledOptions { + send?: Sender; + fetch?: typeof fetch; + sleep?: (ms: number) => Promise; + log?: (entry: Record) => void; +} + +/** + * The daily cron (wrangler.toml). Housekeeping first, exactly as before; then the moderation digest, which never throws. A cleanup + * failure still fails the invocation (after the digest has had its chance), so it remains visible in the Cron Events history. + */ +export async function runScheduled(db: Db, env: Omit, now: number, scheduledTime: number, opts: ScheduledOptions = {}): Promise { + const log = opts.log ?? ((entry) => console.log(JSON.stringify(entry))); + const settings = loadSettings(env); + let cleanupError: unknown = null; + let expiredUnresolved = 0; + try { + const runs = await pruneStaleRuns(db, now); + const limits = await pruneRateLimits(db, now, settings.rate.windowMs); + const reports = await pruneReports(db, now); + expiredUnresolved = reports.unresolved; + log({ evt: 'prune', ...runs, rateLimitRows: limits, reportRows: reports.deleted, unresolvedReportRows: reports.unresolved }); + } catch (e) { + cleanupError = e; + log({ evt: 'prune_failed', error: String(e).slice(0, 200) }); + } + const digest = await runModerationDigest({ db, env, now, scheduledTime, expiredUnresolved, send: opts.send, fetch: opts.fetch, sleep: opts.sleep }); + log({ evt: 'moderation_digest', ...digest }); + if (cleanupError) throw cleanupError; + return digest; +} diff --git a/phaser-asteroids/server/src/worker.ts b/phaser-asteroids/server/src/worker.ts index 8d233bf..5ea1ae2 100644 --- a/phaser-asteroids/server/src/worker.ts +++ b/phaser-asteroids/server/src/worker.ts @@ -1,9 +1,7 @@ import { loadSettings, type Env } from './config'; import { d1Db } from './d1'; -import { pruneRateLimits } from './ratelimit'; import { handleRequest } from './router'; -import { pruneStaleRuns } from './runs'; -import { pruneReports } from './moderation'; +import { runScheduled } from './scheduled'; /** Cloudflare Worker entry: wires the D1 binding and environment variables into the portable service. */ export default { @@ -11,14 +9,12 @@ export default { 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); + /** + * Daily cron (wrangler.toml): drops abandoned runs, old rejected runs, stale rate-limit counters and expired reports, then sends + * the moderation digest if it is configured and something needs review (see scheduled.ts / digest.ts). + */ + async scheduled(event: { scheduledTime?: number } | undefined, env: Env): Promise { const now = Date.now(); - const runs = await pruneStaleRuns(db, now); - const limits = await pruneRateLimits(db, now, settings.rate.windowMs); - const reports = await pruneReports(db, now); - console.log(JSON.stringify({ evt: 'prune', ...runs, rateLimitRows: limits, reportRows: reports })); + await runScheduled(d1Db(env.DB), env, now, event?.scheduledTime ?? now); }, }; diff --git a/phaser-asteroids/server/tests/digest.test.ts b/phaser-asteroids/server/tests/digest.test.ts new file mode 100644 index 0000000..b2fa139 --- /dev/null +++ b/phaser-asteroids/server/tests/digest.test.ts @@ -0,0 +1,359 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + MAX_ATTEMPTS_PER_DAY, RESEND_API_URL, SEND_LEASE_MS, loadDigestConfig, resendSender, + type DigestConfig, type SendResult, type Sender, +} from '../src/digest'; +import type { Db } from '../src/db'; +import { runScheduled } from '../src/scheduled'; +import { faultyDb } from '../testing/sqliteDb'; +import { count, insertScore, makeHarness, type Harness } from './harness'; + +// Every delivery here goes to an in-memory mock. Addresses use the reserved .test TLD; nothing contacts a real provider. +const DAY = 86_400_000; +const API_KEY = 're_test_DO_NOT_LEAK_0123456789'; +const ENV = { + RESEND_API_KEY: API_KEY, + MODERATION_DIGEST_FROM: 'Orbital Impact ', + MODERATION_DIGEST_TO: 'operator@digest.test', + MODERATION_DASHBOARD_URL: 'https://worker.test/admin', + IP_HASH_SALT: 'test-salt', +}; + +interface Sent { subject: string; text: string; key: string } + +function mockSender(script: SendResult[] = []): { sent: Sent[]; send: Sender } { + const sent: Sent[] = []; + return { + sent, + send: async (message, key) => { + sent.push({ ...message, key }); + return script.shift() ?? { ok: true, id: `msg-${sent.length}` }; + }, + }; +} + +describe('daily moderation digest', () => { + let h: Harness; + let logs: Array>; + beforeEach(() => { h = makeHarness(); logs = []; }); + afterEach(() => h.db.close()); + + /** A public entry with plausible kill counts, so it carries no integrity flag. */ + const cleanScore = async (nickname = 'Pilot') => { + const id = await insertScore(h.db, { score: 1000, nickname, completedAt: h.clock.now() }); + await h.db.run('UPDATE scores SET asteroids_destroyed = 20 WHERE id = ?', [id]); + return id; + }; + /** insertScore leaves kill counts at 0, so any positive score exceeds the frozen 1.2.0 bound and is flagged. */ + const flaggedScore = () => insertScore(h.db, { score: 5000, nickname: 'Flagged', completedAt: h.clock.now() }); + const report = async (id: string, reason: string, ip = '203.0.113.20') => { + const res = await h.call('POST', `/api/v1/scores/${id}/report`, { ip, json: { reason } }); + expect(res.status).toBe(200); + }; + const resolve = async (id: string) => { + const { moderation_revision: revision } = (await h.db.first<{ moderation_revision: number }>('SELECT moderation_revision FROM scores WHERE id = ?', [id]))!; + const res = await h.call('POST', `/api/v1/admin/scores/${id}/moderate`, { token: h.settings.adminToken!, json: { action: 'resolve', category: 'offensive', revision } }); + expect(res.status).toBe(200); + }; + const run = (send: Sender, opts: { env?: Record; scheduledTime?: number; db?: Db } = {}) => + runScheduled(opts.db ?? h.db, opts.env ?? ENV, h.clock.now(), opts.scheduledTime ?? h.clock.now(), { send, sleep: async () => {}, log: (e) => logs.push(e) }); + + it('sends nothing when the queue is empty', async () => { + await cleanScore(); + const mail = mockSender(); + expect(await run(mail.send)).toEqual({ status: 'empty' }); + expect(mail.sent).toHaveLength(0); + expect(await count(h.db, 'moderation_digests')).toBe(0); + }); + + it('one report produces one short digest with the dashboard link', async () => { + await report(await cleanScore(), 'offensive'); + const mail = mockSender(); + expect(await run(mail.send)).toMatchObject({ status: 'sent', day: '2026-10-22', entries: 1, attempt: 1 }); + expect(mail.sent).toHaveLength(1); + const [email] = mail.sent; + expect(email!.subject).toBe('Orbital Impact — 1 moderation item awaiting review'); + expect(email!.text).toContain('Needs review: 1 entry'); + expect(email!.text).toContain('Open player reports: 1 on 1 entry'); + expect(email!.text).toContain('Offensive name: 1'); + expect(email!.text).toContain('Review: https://worker.test/admin'); + expect(email!.text).toContain('Nothing was hidden, renamed or deleted automatically.'); + expect(email!.text.split('\n').length).toBeLessThan(15); + expect(email!.key).toBe('orbital-impact-moderation-digest-2026-10-22'); + expect(await h.db.first('SELECT status, attempts, provider_id FROM moderation_digests')).toEqual({ status: 'sent', attempts: 1, provider_id: 'msg-1' }); + }); + + it('multiple reports produce one digest with correct counts by category', async () => { + const a = await cleanScore('A'); + const b = await cleanScore('B'); + await cleanScore('C'); + await report(a, 'offensive', '203.0.113.1'); + await report(a, 'offensive', '203.0.113.2'); + await report(b, 'personal_info', '203.0.113.3'); + await report(b, 'other', '203.0.113.4'); + const mail = mockSender(); + await run(mail.send); + expect(mail.sent).toHaveLength(1); + expect(mail.sent[0]!.subject).toBe('Orbital Impact — 2 moderation items awaiting review'); + const text = mail.sent[0]!.text; + expect(text).toContain('Needs review: 2 entries'); + expect(text).toContain('Open player reports: 4 on 2 entries'); + expect(text).toContain('Offensive name: 2'); + expect(text).toContain('Personal information: 1'); + expect(text).toContain('Other: 1'); + expect(text).not.toContain('Suspected cheating'); + expect(text).not.toContain('integrity flags'); + }); + + it('includes unreviewed integrity flags, counts an entry once, and drops flags once reviewed', async () => { + const flagged = await flaggedScore(); + const both = await flaggedScore(); + await report(both, 'suspicious_score'); + const mail = mockSender(); + await run(mail.send); + expect(mail.sent[0]!.subject).toBe('Orbital Impact — 2 moderation items awaiting review'); + expect(mail.sent[0]!.text).toContain('Unreviewed integrity flags: 2'); + expect(mail.sent[0]!.text).toContain('Suspected cheating: 1'); + await resolve(flagged); + await resolve(both); + h.clock.advance(DAY); + expect(await run(mail.send)).toEqual({ status: 'empty' }); + expect(mail.sent).toHaveLength(1); + }); + + it('repeated or retried cron invocations on one day send a single email', async () => { + await report(await cleanScore(), 'offensive'); + const mail = mockSender(); + const scheduledTime = h.clock.now(); + await run(mail.send, { scheduledTime }); + for (let i = 0; i < 3; i++) { + h.clock.advance(SEND_LEASE_MS * 2); + expect(await run(mail.send, { scheduledTime })).toEqual({ status: 'skipped', day: '2026-10-22' }); + } + // A different invocation the same UTC day (e.g. a manual trigger) is also covered by the day key. + expect((await run(mail.send, { scheduledTime: scheduledTime + 3_600_000 })).status).toBe('skipped'); + expect(mail.sent).toHaveLength(1); + }); + + it('repeats once a day while items remain, picks up new reports and stops when the queue is clear', async () => { + const first = await cleanScore('First'); + await report(first, 'offensive'); + const mail = mockSender(); + await run(mail.send); + const second = await cleanScore('Second'); + await report(second, 'personal_info'); + expect((await run(mail.send)).status).toBe('skipped'); // same day: new report waits for tomorrow + h.clock.advance(DAY); + await run(mail.send); + expect(mail.sent).toHaveLength(2); + expect(mail.sent[1]!.subject).toBe('Orbital Impact — 2 moderation items awaiting review'); + expect(mail.sent[1]!.text).toContain('Personal information: 1'); + await resolve(first); + h.clock.advance(DAY); + await run(mail.send); + expect(mail.sent[2]!.subject).toBe('Orbital Impact — 1 moderation item awaiting review'); + expect(mail.sent[2]!.text).not.toContain('Offensive name'); + await resolve(second); + h.clock.advance(DAY); + expect(await run(mail.send)).toEqual({ status: 'empty' }); + expect(mail.sent).toHaveLength(3); + }); + + it('retries transient failures with one idempotency key and identical payload, within a daily cap', async () => { + await report(await cleanScore(), 'offensive'); + const outage: SendResult = { ok: false, retryable: true, error: 'http_503' }; + const mail = mockSender(Array(2 * MAX_ATTEMPTS_PER_DAY).fill(outage)); + expect(await run(mail.send)).toMatchObject({ status: 'failed', attempt: 1, error: 'http_503', retryable: true }); + expect(mail.sent).toHaveLength(2); // one immediate retry + await report(await cleanScore('Later'), 'other'); // counts change, but a retry resends the stored text + for (let attempt = 2; attempt <= MAX_ATTEMPTS_PER_DAY; attempt++) expect(await run(mail.send)).toMatchObject({ status: 'failed', attempt }); + expect(await run(mail.send)).toMatchObject({ status: 'skipped' }); + expect(mail.sent).toHaveLength(2 * MAX_ATTEMPTS_PER_DAY); + expect(new Set(mail.sent.map((m) => m.key)).size).toBe(1); + expect(new Set(mail.sent.map((m) => m.text)).size).toBe(1); + expect(await h.db.first('SELECT status, attempts, error FROM moderation_digests')).toEqual({ status: 'failed', attempts: MAX_ATTEMPTS_PER_DAY, error: 'http_503' }); + // The next day's run starts fresh with current counts once the provider recovers. + h.clock.advance(DAY); + expect(await run(mail.send)).toMatchObject({ status: 'sent', day: '2026-10-23' }); + expect(mail.sent.at(-1)!.subject).toBe('Orbital Impact — 2 moderation items awaiting review'); + }); + + it('does not retry a permanent provider error the same day, and tries again the next day', async () => { + await report(await cleanScore(), 'offensive'); + const mail = mockSender([{ ok: false, retryable: false, error: 'http_403:validation_error' }]); + expect(await run(mail.send)).toMatchObject({ status: 'failed', retryable: false }); + expect(await run(mail.send)).toMatchObject({ status: 'skipped' }); + expect(mail.sent).toHaveLength(1); + h.clock.advance(DAY); + expect((await run(mail.send)).status).toBe('sent'); + }); + + it('takes over an abandoned send only after its lease, with the same key', async () => { + await report(await cleanScore(), 'offensive'); + await h.db.run(`INSERT INTO moderation_digests (day, status, attempts, claimed_at, subject, body, updated_at) + VALUES ('2026-10-22', 'sending', 1, ?, 'stored subject', 'stored body', ?)`, [h.clock.now(), h.clock.now()]); + const mail = mockSender(); + expect((await run(mail.send)).status).toBe('skipped'); + h.clock.advance(SEND_LEASE_MS + 1); + expect(await run(mail.send)).toMatchObject({ status: 'sent', attempt: 2 }); + expect(mail.sent).toEqual([{ subject: 'stored subject', text: 'stored body', key: 'orbital-impact-moderation-digest-2026-10-22' }]); + }); + + it('cleanup still runs when delivery throws or the digest ledger is unusable', async () => { + const id = await cleanScore(); + await report(id, 'offensive'); + await h.db.run("INSERT INTO rate_limits (bucket, window_start, count) VALUES ('old', ?, 1)", [h.clock.now() - 10 * 3_600_000]); + const throwing: Sender = async () => { throw new Error(`boom ${API_KEY}`); }; + const outcome = await run(throwing); + expect(outcome).toEqual({ status: 'error', error: 'Error: boom [redacted]' }); + expect(JSON.stringify(logs)).not.toContain(API_KEY); + expect(await count(h.db, 'rate_limits', "bucket = 'old'")).toBe(0); + expect(logs[0]).toMatchObject({ evt: 'prune', rateLimitRows: 1 }); + + h.db.exec('DROP TABLE moderation_digests'); + await h.db.run("INSERT INTO rate_limits (bucket, window_start, count) VALUES ('old', ?, 1)", [h.clock.now() - 10 * 3_600_000]); + await expect(run(mockSender().send)).resolves.toMatchObject({ status: 'error' }); + expect(await count(h.db, 'rate_limits', "bucket = 'old'")).toBe(0); + }); + + it('a cleanup failure still lets the digest run, then fails the invocation', async () => { + await report(await cleanScore(), 'offensive'); + const mail = mockSender(); + const db = faultyDb(h.db, (sql) => sql.startsWith('DELETE FROM rate_limits')); + await expect(run(mail.send, { db })).rejects.toThrow('simulated database failure'); + expect(mail.sent).toHaveLength(1); + expect(logs.map((l) => l.evt)).toEqual(['prune_failed', 'moderation_digest']); + }); + + it('warns before reports expire and announces open reports deleted at the retention limit', async () => { + const id = await cleanScore(); + await report(id, 'offensive', '203.0.113.1'); + await report(await cleanScore('Resolved'), 'other', '203.0.113.2'); + await resolve((await h.db.first<{ id: string }>("SELECT id FROM scores WHERE nickname = 'Resolved'"))!.id); + const mail = mockSender(); + h.clock.advance(24 * DAY); + await run(mail.send); + expect(mail.sent[0]!.text).toContain('Expiring: 1 open report reaches the 30-day retention limit within 7 days'); + h.clock.advance(7 * DAY); + expect(await run(mail.send)).toMatchObject({ status: 'sent' }); + expect(logs.at(-2)).toMatchObject({ evt: 'prune', reportRows: 2, unresolvedReportRows: 1 }); + expect(mail.sent[1]!.subject).toBe('Orbital Impact — 1 unreviewed report expired'); + expect(mail.sent[1]!.text).toContain('Expired: 1 open report reached the 30-day limit and was deleted without review.'); + expect(mail.sent[1]!.text).toContain('Needs review: 0 entries'); + // Retention itself is unchanged: both reports are gone, and the following day is quiet. + expect(await count(h.db, 'score_reports')).toBe(0); + h.clock.advance(DAY); + expect(await run(mail.send)).toEqual({ status: 'empty' }); + }); + + it('expired reports that were already resolved do not trigger an email', async () => { + const id = await cleanScore(); + await report(id, 'offensive'); + await resolve(id); + h.clock.advance(31 * DAY); + const mail = mockSender(); + expect(await run(mail.send)).toEqual({ status: 'empty' }); + }); + + it('puts no credentials, names, identifiers or reporter data in the email or logs', async () => { + const id = await cleanScore('SecretNick'); + await report(id, 'personal_info', '198.51.100.77'); + const flagged = await flaggedScore(); + const mail = mockSender(); + await run(mail.send); + const reporterHash = (await h.db.first<{ reporter_hash: string }>('SELECT reporter_hash FROM score_reports'))!.reporter_hash; + const { issuer_hash: issuerHash } = (await h.db.first<{ issuer_hash: string | null }>('SELECT issuer_hash FROM runs LIMIT 1'))!; + const output = JSON.stringify(mail.sent) + JSON.stringify(logs); + for (const secret of [API_KEY, reporterHash, 'SecretNick', 'Flagged', id, flagged, '198.51.100.77', 'test-salt', h.settings.adminToken!, ENV.MODERATION_DIGEST_TO]) { + expect(output, secret).not.toContain(secret); + } + if (issuerHash) expect(output).not.toContain(issuerHash); + expect(JSON.stringify(await h.db.all('SELECT * FROM moderation_digests'))).not.toContain(reporterHash); + }); + + it('is disabled, without touching the digest ledger, until fully and validly configured', async () => { + await report(await cleanScore(), 'offensive'); + h.db.exec('DROP TABLE moderation_digests'); // proves the disabled path never queries it (i.e. safe before migration 0005) + const mail = mockSender(); + expect(await run(mail.send, { env: { IP_HASH_SALT: 'x' } })).toEqual({ status: 'disabled', reason: 'not_configured' }); + const { MODERATION_DIGEST_FROM: _omit, ...partial } = ENV; + expect(await run(mail.send, { env: partial })).toEqual({ status: 'disabled', reason: 'incomplete:MODERATION_DIGEST_FROM' }); + expect(await run(mail.send, { env: { ...ENV, MODERATION_DIGEST_TO: 'a@b.test, c@d.test', MODERATION_DASHBOARD_URL: 'http://worker.test/admin' } })) + .toEqual({ status: 'disabled', reason: 'invalid:MODERATION_DIGEST_TO,MODERATION_DASHBOARD_URL' }); + expect(mail.sent).toHaveLength(0); + expect(JSON.stringify(logs)).not.toContain(API_KEY); + }); + + it('leaves scores, leaderboards and moderation state unchanged', async () => { + const id = await cleanScore(); + await report(id, 'offensive'); + await flaggedScore(); + const snapshot = async () => JSON.stringify([ + await h.db.all('SELECT * FROM scores ORDER BY id'), + await h.db.all('SELECT score_id, reason, status, created_at FROM score_reports ORDER BY score_id'), + await h.db.all('SELECT * FROM moderation_audit'), + (await h.call('GET', '/api/v1/leaderboard/all-time')).body, + (await h.call('GET', '/api/v1/leaderboard/weekly')).body, + ]); + const before = await snapshot(); + await run(mockSender().send); + await run(mockSender([{ ok: false, retryable: true, error: 'timeout' }]).send); + expect(await snapshot()).toBe(before); + }); +}); + +describe('Resend delivery adapter', () => { + const config: DigestConfig = { apiKey: API_KEY, apiUrl: RESEND_API_URL, from: ENV.MODERATION_DIGEST_FROM, to: ENV.MODERATION_DIGEST_TO, dashboardUrl: ENV.MODERATION_DASHBOARD_URL }; + const respond = (status: number, body: unknown) => async () => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + + it('posts one plain-text email with bearer auth and the idempotency key', async () => { + let seen: { url: string; init: RequestInit } | null = null; + const fetchMock = (async (url: string, init: RequestInit) => { + seen = { url, init }; + return new Response('{"id":"49a3999c-0ce1-4ea6-ab68-afcd6dc2e794"}', { status: 200 }); + }) as unknown as typeof fetch; + const result = await resendSender(config, fetchMock)({ subject: 'S', text: 'T' }, 'key-1'); + expect(result).toEqual({ ok: true, id: '49a3999c-0ce1-4ea6-ab68-afcd6dc2e794' }); + expect(seen!.url).toBe('https://api.resend.com/emails'); + const headers = seen!.init.headers as Record; + expect(headers.Authorization).toBe(`Bearer ${API_KEY}`); + expect(headers['Idempotency-Key']).toBe('key-1'); + expect(seen!.init.signal).toBeInstanceOf(AbortSignal); + expect(JSON.parse(seen!.init.body as string)).toEqual({ from: ENV.MODERATION_DIGEST_FROM, to: [ENV.MODERATION_DIGEST_TO], subject: 'S', text: 'T' }); + }); + + it('classifies provider errors without echoing their messages', async () => { + const cases: Array<[number, unknown, boolean]> = [ + [500, { name: 'internal_server_error', message: 'x' }, true], + [429, { name: 'rate_limit_exceeded' }, true], + [409, { name: 'concurrent_idempotent_requests' }, true], + [409, { name: 'invalid_idempotent_request' }, false], + [401, { name: 'missing_api_key' }, false], + [422, { name: 'validation_error', message: `The ${ENV.MODERATION_DIGEST_TO} domain is not verified ${API_KEY}` }, false], + ]; + for (const [status, body, retryable] of cases) { + const result = await resendSender(config, respond(status, body) as unknown as typeof fetch)({ subject: 'S', text: 'T' }, 'k'); + expect(result).toEqual({ ok: false, retryable, error: `http_${status}:${(body as { name: string }).name}` }); + } + const html = await resendSender(config, (async () => new Response('bad gateway', { status: 502 })) as unknown as typeof fetch)({ subject: 'S', text: 'T' }, 'k'); + expect(html).toEqual({ ok: false, retryable: true, error: 'http_502' }); + }); + + it('treats network errors and timeouts as retryable', async () => { + const offline = (async () => { throw new TypeError(`fetch failed ${API_KEY}`); }) as unknown as typeof fetch; + expect(await resendSender(config, offline)({ subject: 'S', text: 'T' }, 'k')).toEqual({ ok: false, retryable: true, error: 'network_error' }); + const hanging = ((_url: string, init: RequestInit) => new Promise((_resolve, reject) => { + init.signal!.addEventListener('abort', () => reject(init.signal!.reason)); + })) as unknown as typeof fetch; + expect(await resendSender(config, hanging, 20)({ subject: 'S', text: 'T' }, 'k')).toEqual({ ok: false, retryable: true, error: 'timeout' }); + }); + + it('validates configuration and only allows https or loopback endpoints', () => { + expect(loadDigestConfig(ENV)).toMatchObject({ ok: true, config: { apiUrl: RESEND_API_URL, to: 'operator@digest.test' } }); + expect(loadDigestConfig({ ...ENV, MODERATION_DIGEST_FROM: 'moderation@digest.test' }).ok).toBe(true); + expect(loadDigestConfig({ ...ENV, RESEND_API_URL: 'http://127.0.0.1:9999/emails' }).ok).toBe(true); + expect(loadDigestConfig({ ...ENV, RESEND_API_URL: 'http://mail.example/emails' })).toEqual({ ok: false, reason: 'invalid:RESEND_API_URL' }); + expect(loadDigestConfig({ ...ENV, MODERATION_DIGEST_FROM: 'Orbital ' })).toEqual({ ok: false, reason: 'invalid:MODERATION_DIGEST_FROM' }); + expect(loadDigestConfig({ ...ENV, RESEND_API_KEY: ' ' })).toEqual({ ok: false, reason: 'incomplete:RESEND_API_KEY' }); + }); +}); diff --git a/phaser-asteroids/server/tests/moderation.test.ts b/phaser-asteroids/server/tests/moderation.test.ts index 3498713..6e667b7 100644 --- a/phaser-asteroids/server/tests/moderation.test.ts +++ b/phaser-asteroids/server/tests/moderation.test.ts @@ -49,9 +49,9 @@ describe('private leaderboard moderation and erasure', () => { await report(id); h.clock.advance(29 * 86_400_000); await report(id); - expect(await pruneReports(h.db, h.clock.now())).toBe(0); + expect(await pruneReports(h.db, h.clock.now())).toEqual({ deleted: 0, unresolved: 0 }); h.clock.advance(2 * 86_400_000); - expect(await pruneReports(h.db, h.clock.now())).toBe(1); + expect(await pruneReports(h.db, h.clock.now())).toEqual({ deleted: 1, unresolved: 1 }); }); it('requires admin authorization, preserves hide/unhide, then atomically erases score, run and reports', async () => { diff --git a/phaser-asteroids/server/wrangler.toml b/phaser-asteroids/server/wrangler.toml index 9799a75..87c2ff9 100644 --- a/phaser-asteroids/server/wrangler.toml +++ b/phaser-asteroids/server/wrangler.toml @@ -54,3 +54,9 @@ migrations_dir = "migrations" [env.production.vars] # GitHub Pages, and the Android app (its page origin is set by server.hostname in ../capacitor.config.ts; see ../docs/android.md). ALLOWED_ORIGINS = "https://djblackett.github.io,https://spacearcade.davidandrea.ca" +# Daily moderation digest (src/digest.ts; ../../docs/leaderboard-moderation.md#daily-moderation-digest). It stays disabled until +# MODERATION_DIGEST_FROM (a sender on a domain verified in Resend) is set here and RESEND_API_KEY is set with +# `wrangler secret put RESEND_API_KEY --env production`. Do not add RESEND_API_KEY to the required secrets above. +MODERATION_DIGEST_TO = "privacy@davidandrea.ca" +MODERATION_DASHBOARD_URL = "https://asteroids-leaderboard.davejandrea.workers.dev/admin" +# MODERATION_DIGEST_FROM = "Orbital Impact <...@your-verified-domain>" From 5d720ce6bd7f302aafe199574eb8f91b39e575b3 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:40:12 -0400 Subject: [PATCH 06/14] docs: confirm privacy contact, score retention policy, digest and UGC readiness - Public privacy/security/removal/appeal contact privacy@davidandrea.ca in the in-game Privacy screen, the policy draft, Play release notes and the operator guide. The DRAFT marker stays: the policy is still unapproved and the signed-release inspector keeps refusing it. - Draft states the confirmed default: verified scores are kept indefinitely, subject to moderation, removal requests and later storage policy. - Operator guide: digest behaviour, configuration and activation steps; report retention analysis with options A-D for an owner decision; Google Play UGC readiness rechecked 2026-11-12 (not established). - Data inventory, release preflight, backend doc and README pointers. Co-Authored-By: Claude Opus 5.5 --- docs/leaderboard-backend.md | 2 +- docs/leaderboard-moderation.md | 116 ++++++++++++++++-- docs/play-data-inventory.md | 3 +- docs/privacy-policy-draft.md | 18 +-- docs/release-preflight.md | 5 +- phaser-asteroids/docs/google-play-release.md | 4 +- phaser-asteroids/docs/phone-test-checklist.md | 2 +- phaser-asteroids/server/README.md | 2 +- phaser-asteroids/src/ui/menu/pages/privacy.ts | 10 +- 9 files changed, 131 insertions(+), 31 deletions(-) diff --git a/docs/leaderboard-backend.md b/docs/leaderboard-backend.md index d6c75a2..b4b0e7b 100644 --- a/docs/leaderboard-backend.md +++ b/docs/leaderboard-backend.md @@ -190,7 +190,7 @@ Migrations `server/migrations/0001_init.sql` and `0002_time_limit.sql` (applied **`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. +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, reports after 30 days. Accepted runs are kept. The same cron then sends the optional [moderation digest](leaderboard-moderation.md#daily-moderation-digest) (migration 0005; disabled unless configured). ## 6. API contracts diff --git a/docs/leaderboard-moderation.md b/docs/leaderboard-moderation.md index b4a3b25..91a2133 100644 --- a/docs/leaderboard-moderation.md +++ b/docs/leaderboard-moderation.md @@ -1,6 +1,6 @@ # Leaderboard moderation: audit and operator guide -**Current status (2026-11-12):** live in production since 2026-11-04 (see [Verification](#verification)). The deployment checklist under [Erasure, cache consistency and release configuration](#erasure-cache-consistency-and-release-configuration) is complete except where marked open. The remaining operator tasks are the initial review of existing names, review coverage, and the public removal contact. The rest of this page records the implementation pass as written at the time. +**Current status (2026-11-12):** live in production since 2026-11-04 (see [Verification](#verification)). The deployment checklist under [Erasure, cache consistency and release configuration](#erasure-cache-consistency-and-release-configuration) is complete except where marked open. The public removal/privacy contact is **privacy@davidandrea.ca** (confirmed 2026-11-12). A [daily moderation digest](#daily-moderation-digest) is implemented and tested locally on `feature/moderation-digest` but **not deployed or configured**: it needs migration 0005, a Resend sender domain and API key. The remaining operator tasks are the initial review of existing names, digest activation, and the [policy decisions](#report-retention-and-review-policy) listed below. The rest of this page records the implementation pass as written at the time. Audited and extended on 2026-11-04 on `dev`, starting at `91c349c` (`add moderation tooling`). Local implementation and tests only. No production deployment, production data changes, credentials changes, commits or pushes were performed. Existing inaccessible root `tmp/` deletions were left alone. @@ -21,13 +21,13 @@ Audited and extended on 2026-11-04 on `dev`, starting at `91c349c` (`add moderat ## Daily solo-administrator workflow 1. Open **the Worker's own HTTPS origin + `/admin`**, not the game's origin. Use a trusted browser/device and obtain the existing `ADMIN_TOKEN` from the protected secret store. Enter it in the password field. Do not put it in URLs, shell history, Vite variables, screenshots or the player application. -2. The **Needs review** view lists reported entries and unreviewed integrity flags, 50 at a time. Review all pages routinely (recommended daily while testing; establish sustainable coverage before release). **All entries**, **Hidden entries**, and exact score-ID lookup support proactive review, appeals and restoration. Do an initial review of existing names: the new filter does not rewrite historical data. +2. The **Needs review** view lists reported entries and unreviewed integrity flags, 50 at a time. Once the [daily digest](#daily-moderation-digest) is active, open it when the digest arrives and work through every page; no email means the view is empty. Until then, check it routinely. **All entries**, **Hidden entries**, and exact score-ID lookup support proactive review, appeals and restoration. Do an initial review of existing names: the new filter does not rewrite historical data. 3. Open **Reports / decision history**. The console shows grouped reasons/counts, timestamps, original/current names, rules, score, duration and kill counts. It never reveals reporter/issuer IP hashes, run tokens or full submissions. Reports describe allegations; multiple reports are not proof. 4. Choose the decision category. For an offensive name on a legitimate run, use **Replace name** (default Anonymous). The original nickname remains private in D1; score/rank inputs stay unchanged. Use **Hide** when the entry itself needs removal from public view. Use **Restore score** and **Restore original name** independently after review. Original-name restoration intentionally permits reversal of a false positive and can republish offensive content; review before confirming. 5. **Resolve reports / flag** closes the current complaints and acknowledges the integrity flag. Name/visibility changes do not silently resolve reports. **Reopen review** reverses resolution. New reports or changed open-report categories advance the revision; a stale decision fails with 409 and requires Refresh. Identical repeats do not invalidate a snapshot, and the same reporter cannot reopen an already resolved report. A different reporter can submit a new complaint. 6. The **Audit log** pages through every decision, including anonymized erasures. Per-entry history shows the newest 100. Lock when finished. The token is only held in tab memory, cleared on reload/navigation/lock and after 15 minutes without console actions. The shell is public when enabled, but contains no private data or credentials. CSP, text-only DOM rendering, no third-party resources, no framing and no referrer forwarding protect the console. -This is usable for a solo operator without routine SQL. There are **no notifications, automatic review staffing, multiple-admin identities, or appeal messaging**. The shared admin secret identifies the authorized operator role, not an individually authenticated staff member. Use the external support/removal contact for appeals. Direct privileged D1 changes bypass the application audit and should be exceptional. The log is not cryptographically tamper-proof against a database administrator. +This is usable for a solo operator without routine SQL. The [daily digest](#daily-moderation-digest), once configured, is the only notification. There is **no automatic review staffing, multiple-admin identities, or appeal messaging**. The shared admin secret identifies the authorized operator role, not an individually authenticated staff member. Appeals and removal requests go to **privacy@davidandrea.ca** (shown in the in-game Privacy screen); record the outcome in the console with the `appeal` category. Direct privileged D1 changes bypass the application audit and should be exceptional. The log is not cryptographically tamper-proof against a database administrator. ## Data and reversible decisions @@ -54,7 +54,7 @@ All administrative endpoints and the console are absent when `ADMIN_TOKEN` is un This is deliberately incomplete: it cannot reliably detect all languages, homoglyphs, contextual harassment, disguised personal details or every evasion. Do not describe it as comprehensive profanity/PII detection. Keep human review and in-app reports. Old installed clients retain their local character-only feedback and receive the authoritative server error when submitting. No new client field, rules version, replay schema or consent protocol is required. -Reports accept only `offensive`, `personal_info`, `suspicious_score` or `other`, with a 4 KiB decoded body limit, public-score existence/visibility check, configured origin check, 10 attempts/IP/hour and 1,000 globally/hour. One record per score/salted-IP hash; repeat reports never extend the original 30-day lifetime. Daily cron deletes old open **and resolved** reports. Never use expiry as the review schedule. Rate limits bound writes, not determined distributed abuse: rotating IPs can exhaust the global report budget; shared networks can share limits/deduplication. There is no identity or ownership proof in a report. Reports never directly affect ranking or visibility. +Reports accept only `offensive`, `personal_info`, `suspicious_score` or `other`, with a 4 KiB decoded body limit, public-score existence/visibility check, configured origin check, 10 attempts/IP/hour and 1,000 globally/hour. One record per score/salted-IP hash; repeat reports never extend the original 30-day lifetime. Daily cron deletes old open **and resolved** reports. Never use expiry as the review schedule. The cleanup now counts open reports it deletes, and the digest warns 7 days ahead and announces any that expire unreviewed (see [Report retention and review policy](#report-retention-and-review-policy)). Rate limits bound writes, not determined distributed abuse: rotating IPs can exhaust the global report budget; shared networks can share limits/deduplication. There is no identity or ownership proof in a report. Reports never directly affect ranking or visibility. Device-local blocks remain case-insensitive nickname blocks, with unblock and personal-best name suppression. Shared names affect unrelated people, and changing a nickname evades a block. No stable player identity was added. @@ -66,7 +66,7 @@ Flags are computed for existing and new rows when reading the private queue. The ## Erasure, cache consistency and release configuration -Establish the public mailbox, review responsibility, ownership/context checks and correspondence retention before release. A nickname or public score ID is not ownership proof; shared IPs are not ownership proof either. Ask for minimal contextual evidence and never bulk-delete all records sharing a name or network. No identity documents are needed by this workflow. +The public mailbox is **privacy@davidandrea.ca** (confirmed 2026-11-12; it is delivered by the domain's Google Workspace MX). Still establish review responsibility, ownership/context checks and correspondence retention before release. A nickname or public score ID is not ownership proof; shared IPs are not ownership proof either. Ask for minimal contextual evidence and never bulk-delete all records sharing a name or network. No identity documents are needed by this workflow. After approving a request, use **Erase score and linked records**, typing the full ID to confirm. One transaction writes the deletion event, deletes the score and its actual accepted run, cascades reports and nulls related audit score IDs. Original/override names and token/submission/IP hashes in the linked run disappear. Other scores/runs remain. The retained audit contains only anonymous decision metadata and cannot identify which erased score to remove from a restored backup. Maintain a separately protected, minimal erasure ledger of approved IDs for backup restoration, with a reviewed retention process; do not copy deleted names or IP hashes into it. @@ -80,13 +80,111 @@ Before a separately authorized production release (status as of 2026-11-12 in br - Review Cloudflare observability, logs, D1 Time Travel and exports separately. SQL erasure does not erase provider backups/logs. Reapply approved erasures before serving a restored database. - Deploy backend before the updated app (new report reason requires it). Rebuild/sync Android assets and test a Play-delivered build. Old challenge/submission/board/detail shapes, default rules and frozen verifier remain unchanged; old report reasons and legacy admin APIs remain supported. -## Google Play UGC review +## Daily moderation digest -The [current Play UGC policy](https://support.google.com/googleplay/android-developer/answer/9876937?hl=en), checked 2026-11-04, calls for acceptance before upload, prohibited-content rules, ongoing moderation, and in-app reporting/blocking appropriate to public UGC. Implementation is not proof of Play approval. +Implemented 2026-11-12 on local branch `feature/moderation-digest`; **not deployed, not configured, no live email sent.** Code: `server/src/digest.ts` (queue summary, email text, Resend adapter, daily claim) and `server/src/scheduled.ts` (cron order). Migration `0005_moderation_digest.sql` adds one table. -Demonstrable locally: rules/disclosure beside Submit and in Privacy/Rules; the Submit action is presented as acceptance; prohibited-name rules; in-app reporting and nickname blocking; server screening; authenticated review and corrective actions. There is no in-app monetization encouraging abusive content. +**Behaviour.** The existing daily cron (`17 7 * * *`, 03:17/04:17 Halifax) first runs the unchanged cleanup, then the digest. The digest counts the console's **Needs review** view (the same SQL), so the total matches what `/admin` shows: -Still requires interpretation/external evidence: whether submit-as-acceptance is sufficient for this UX and historical installed builds; whether blocking a mutable, shared nickname satisfies user blocking without accounts; target ages/content rating and any applicable child-safety obligations; actual timely moderation, deployed availability, support contact, published privacy policy and provider handling. There is no server-side acceptance receipt. No incidental-sexual-content exception or Families compliance is claimed. Confirm the accountless interpretation with Play review/support; if rejected, reassess identity or freeform names explicitly rather than silently asserting compliance. +- Empty queue and nothing expired: no email. +- Otherwise one email, subject `Orbital Impact — N moderation items awaiting review` (N = entries in Needs review), containing open reports by reason, entries with reports, unreviewed integrity flags, open reports within 7 days of the 30-day limit, open reports the cleanup just deleted unreviewed, and the console link. +- If the queue is empty but open reports expired that day, the subject is `Orbital Impact — N unreviewed reports expired`. +- It repeats once per UTC day while anything stays open and stops when the queue is clear. + +It contains **no nicknames, score IDs, reporter or IP hashes, tokens or replay data**, and it never hides, renames, resolves, deletes or bans anything. + +**Duplicates and failures.** + +- *One email per day.* One `moderation_digests` row per UTC day of the cron's `scheduledTime` is claimed atomically. Cloudflare retries, duplicate invocations and manual triggers on the same day are skipped (verified in Vitest and real workerd/D1). +- *Identical retries.* The day's text is stored on first claim, and every attempt resends it with `Idempotency-Key: orbital-impact-moderation-digest-YYYY-MM-DD`. Resend keeps keys for 24 hours, so a timeout whose request actually succeeded cannot produce a second email. +- *Retry limits.* Transient errors (timeout after 10 s, network, 408/429/5xx, concurrent-idempotency 409) get one immediate retry. A later invocation the same day can retry, up to 3 claims per day; a send abandoned mid-flight is taken over after 10 minutes. Permanent errors (401/403/422, payload-mismatch 409) are not retried that day. Either way the next day's run tries again if items remain, so an outage costs at most 6 API calls a day and never more than one delivered email. +- *Isolation.* Digest errors are caught and logged as `{"evt":"moderation_digest","status":...}` with a status/provider error name only; the API key is redacted from any error text. They never stop the cleanup, and the digest does not run on request paths, so gameplay is unaffected. A cleanup failure still lets the digest run, then fails the invocation as before. Ledger rows (counts only) are deleted after 30 days. + +**Configuration** (all four required; any missing means `disabled`, which touches no digest table): + +| Name | Kind | Value | +| --- | --- | --- | +| `RESEND_API_KEY` | secret | Resend API key, *sending access* restricted to the sender domain. Never in Git, `wrangler.toml`, Vite or CI variables. Not added to `secrets.required`, so deploys still work without it. | +| `MODERATION_DIGEST_FROM` | var | Sender on a Resend-verified domain, e.g. `Orbital Impact `. **Not yet chosen**; commented out in `wrangler.toml`. | +| `MODERATION_DIGEST_TO` | var | `privacy@davidandrea.ca` (set in `[env.production.vars]`). | +| `MODERATION_DASHBOARD_URL` | var | `https://asteroids-leaderboard.davejandrea.workers.dev/admin` (set). | + +`RESEND_API_URL` exists only for the local integration test (https or loopback http only). No other dependency, permission or service was added. + +**Why Resend.** `davidandrea.ca` uses Cloudflare DNS but Google Workspace MX (public DNS, checked 2026-11-12), so Cloudflare Email Routing's `send_email` binding is not available without moving mail routing. A plain HTTPS API call needs no SDK. No Resend account, domain or key exists in this repository or was verified. + +**Activation (owner, each step separately approved):** + +1. Confirm `privacy@davidandrea.ca` exists in Google Workspace (mailbox, alias or group) and is monitored. +2. In Resend, add a sending subdomain (recommended, so the root SPF/DMARC used by Google Workspace stays untouched) and add the DNS records Resend shows in the Cloudflare DNS dashboard. Wait for verification. Create a sending-only API key for that domain. +3. Back up/bookmark production D1 as in the [release runbook](release-preflight.md), then apply **0005** with the runbook's staged-migration procedure (stage only 0005; first confirm with a read-only `SELECT name FROM d1_migrations` that 0001-0004 are recorded and nothing else is pending). It is additive and the current Worker ignores the table. Confirm the ledger lists 0001-0005. +4. Set `MODERATION_DIGEST_FROM` in `[env.production.vars]`, commit, and release through the normal `main` workflow. Without the key the digest logs `disabled` (verify the next cron log). +5. `npx wrangler secret put RESEND_API_KEY --env production` and paste the key at the prompt (never as an argument). This creates a new Worker version with the same code. The next cron with pending items sends the first digest. +6. Optional live check, only if you authorize it: send a test from the Resend dashboard to the recipient, or wait for a real item. Do not create production reports for testing. + +Deploying the code before 0005 is safe: it stays disabled until configured, and if enabled without the table it logs `error` and cleanup continues. Rollback: delete the secret (`wrangler secret delete RESEND_API_KEY --env production`) or roll the Worker back; the table can stay. + +**Not covered by tests:** real Resend delivery, domain verification, Cloudflare's production cron retry behaviour, and mailbox delivery/spam filtering. Tests use an in-process mock sender and a loopback mock HTTP provider under real workerd. + +## Report retention and review policy + +**Finding.** Reports are deleted 30 days after creation, open or not (published in the draft policy and the in-game screen). Before the digest, nothing told the operator a report existed, so an unresolved complaint could expire without ever being seen. The cleanup also logged only a total. + +**Implemented (narrow, no retention change):** + +- The digest includes a new report in the next day's email and every day after until it is resolved, so it appears about 29 times before expiry. +- Reports in their last 7 days are called out as expiring. +- The cleanup now counts open reports it deletes (`unresolvedReportRows` in the cron log), and the digest announces them, even when the queue is otherwise empty. + +The 30-day limit, the deletion of resolved reports, and the reporter data kept are unchanged. + +**Residual gaps:** + +- Until the digest is configured, expiry is as silent as before. +- A delivery failure lasting the whole 30 days, or one on the expiry day itself, loses that day's expiry notice. The count stays in the Worker log for the provider's log retention. +- The expiry notice gives counts, not which entries (by design). The entries themselves remain public and reviewable in **All entries**. +- If the cleanup cron fails, reports outlive 30 days until it next succeeds (already disclosed as dependent on the job). + +**Options (owner decision; A is what is implemented and matches the published text):** + +| Option | Effect | Needs | +| --- | --- | --- | +| A. Keep 30 days for all reports, rely on daily digest + 7-day warning + expiry notice | No policy change | Digest activation; a review-time commitment | +| B. Keep unresolved reports past 30 days (e.g. to 60/90) until reviewed | No complaint lost to delay; keeps reporter IP hashes longer | Policy/in-app text change, small code change | +| C. At 30 days, drop the reporter hash but keep an anonymous "unresolved" marker (entry, reason, date) until reviewed | Keeps the review signal without reporter data | Migration, code, policy text ("de-identified after 30 days") | +| D. Additionally delete resolved reports sooner (e.g. 7 days after resolution) | Less retention | Small code change; shortening the text is low-risk | + +Recommendation: A now. Choose C if digests prove unreliable in practice. Do not adopt B or C silently: the published retention text must change first. + +## Google Play UGC readiness (rechecked 2026-11-12) + +The [current Play UGC policy](https://support.google.com/googleplay/android-developer/answer/9876937?hl=en) (fetched 2026-11-12) requires users to accept terms/user policy before creating UGC, defined and prohibited objectionable content, "an in-app system for reporting and blocking objectionable UGC and users", and moderation that is "robust, effective, and ongoing". It names apps that "continually fail to address user complaints" as violations. It sets **no response time** and no account requirement. Blocking is called for in apps with one-to-one interaction and in public UGC apps. Implementation is not proof of Play approval; **compliance has not been established.** + +| | Item | Status | +| --- | --- | --- | +| 1. Implemented | Prohibited-content rules | In-game LEADERBOARD RULES page and the draft policy's rules section | +| | Acceptance before submission | Rules/disclosure beside Submit; "By submitting a score you accept these rules". Submit-as-acceptance, no separate control or server receipt | +| | Automatic nickname screening | Server, before a run is claimed; narrow English whole-token denylist; not comprehensive | +| | In-app reporting | HIGH SCORES > REPORT / BLOCK, fixed reasons, rate-limited, never auto-hides | +| | Blocking | Device-local nickname block/unblock (no accounts) | +| | Review and corrective actions | `/admin`: replace name, hide/restore, resolve/reopen, erase; audited, revision-guarded | +| | Removal and appeals | Contact `privacy@davidandrea.ca` in-game and in the draft; erasure procedure above | +| | Operational response | Daily digest **implemented but not active**; becomes the response trigger once configured | +| 2. Small engineering changes | Activate the digest | Configuration only (above) | +| | Explicit acceptance | An "Accept rules & submit" label or a one-time checkbox before the first ranked submission; client-only, no server change | +| | Appeal wording | Done: the contact line now says "removal, appeal, privacy or security" | +| 3. Owner policy decisions | Review commitment | E.g. queue cleared within 2-3 days of a digest, with cover while away | +| | Report retention | Option A-D above | +| | Acceptance | Whether submit-as-acceptance is enough, or add the explicit control | +| | Mailbox | Handling and retention of removal/appeal correspondence | +| | Audience and rating | Target ages and content-rating answers (the questionnaire asks about user interaction/UGC) | +| | Policy approval | Approve and host the policy; the contact being filled in does not approve it | +| 4. Uncertain | Blocking without accounts | Whether name-based blocking satisfies "blocking ... users": names are shared and changeable | +| | Ongoing moderation | Whether "robust, effective, and ongoing" is met depends on actual responsiveness, not on code | +| | Screening coverage | Non-English, homoglyph and contextual abuse | +| | Earlier exposure | Web builds already exposed the draft screen without a contact | + +No incidental-sexual-content exception or Families compliance is claimed. If Play review rejects the accountless interpretation, reassess preset names or identity explicitly rather than asserting compliance. ## Verification diff --git a/docs/play-data-inventory.md b/docs/play-data-inventory.md index 4be6305..beff8d2 100644 --- a/docs/play-data-inventory.md +++ b/docs/play-data-inventory.md @@ -15,6 +15,7 @@ Audit date: 2026-11-03; moderation follow-up 2026-11-04. Branch: `dev`. Scope: C | Abuse counters | Start, submit, failed-admin and new report per-IP buckets; global buckets; hour start and count | Delete window starts older than 2 hours at daily cleanup; effective retention roughly 2–26 hours, longer if cleanup fails | `server/src/ratelimit.ts`, `worker.ts` | | Reports (new) | POST `/scores/:id/report`: score ID, fixed reason (offensive/personal_info/suspicious_score/other), open/resolved status, salted reporter-IP hash, creation time | Private queue; one row per entry/hash. Repeats can update an open reason, not creation time; a resolved complaint cannot be reopened by the same reporter. Purged after 30 days at daily cron, or cascade on score erasure. IP rate 10/hour, global 1,000/hour | migrations 0003/0004, `moderation.ts`, `router.ts` | | Moderation decisions (new) | Admin-only fixed action/category, time, score link, prior revision/visibility/name-override presence, open-report count. Acknowledgement flag on scores for derived rules-specific anomalies | No automatic audit expiry; erasure nulls the score link. No names, replacement text, reporter identifiers, IPs or tokens copied into the audit. Original/override names remain with the score until erasure. One shared operator credential, no new staff profiles | migration 0004, `moderation.ts`, `adminUi.ts` | +| Operator digest (implemented 2026-11-12, not deployed) | Daily cron sends the operator one email via Resend (HTTPS API) when the moderation queue is not empty: aggregate counts by report reason, integrity-flag count, expiring/expired report counts and the console URL. Recipient `privacy@davidandrea.ca` | No nickname, score ID, reporter/IP hash, token or replay leaves the Worker. `moderation_digests` (migration 0005) keeps that text and delivery status per day for 30 days. Resend's own retention of sent mail is unverified. Player data is not shared with Resend; it processes operator email only | `server/src/digest.ts`, `scheduled.ts`, migration 0005 | | Network/request metadata | All API requests reach Cloudflare; headers include user agent, origin, URL/path, bearer token on submission, encoding/type. TLS and infrastructure necessarily process connection data. Leaderboard requests expose interest in an entry/page | Cloudflare-side retention/configuration unknown. Worker never reads `request.cf` country/location data; GET boards/details do not write application DB. Board/detail/admin responses use no-store; current clients also bypass HTTP caches. Previously cached five-second responses may outlive a rollout briefly; no explicit Cache API put | `src/ranked/api.ts`, `server/src/router.ts` | | Application logs | Worker emits event names, run IDs, rejection codes, requested rules, URL path, exception strings, aggregate cleanup counts | No explicit IP, nickname, replay or token logging. Exceptions/paths can contain unexpected input; not a guarantee of zero personal data. Cloudflare observability/tails/log destinations need verification | `server/src/router.ts`, `runs.ts`, `worker.ts` | | Local preferences | `asteroids.musicMuted`, `musicVolume`, `sfxVolume`, `musicTrack`, `inputMode`, `touchMovement` (legacy `touchSteering` read), `haptics` | LocalStorage under the app origin; no timed expiry or upload of preferences as such. Chosen control category/recorded movement still transmitted on ranked submission | `src/audio/audioConfig.ts`, `audioSettings.ts`, `src/input/inputMode.ts`, `movementMode.ts`, `src/haptics/hapticSettings.ts` | @@ -43,7 +44,7 @@ Answer **Yes** to collection. Proposed types and purposes below cover this versi | App activity / App interactions | Review, alongside Other actions | No tap/page analytics. Normal endpoint/request logs might expose interactions; confirm provider logging before deciding | | Diagnostics | Provider verification required | No crash/diagnostic SDK in app; operational Worker errors/request logs may qualify depending on actual captured fields/use. Do not select Analytics just because operational metadata exists | | Approximate location | No application geolocation; provider verification required | Worker does not infer location. If configured Cloudflare processing/logging uses IP-derived location on our behalf, disclose that use | -| Email address | No in-app field; reassess once support mailbox workflow is chosen | Voluntary external email contact is distinct from Android API collection; describe correspondence handling honestly | +| Email address | No in-app field. Public contact `privacy@davidandrea.ca` (confirmed 2026-11-12); reassess once the mailbox workflow is documented | Voluntary external email contact is distinct from Android API collection; describe correspondence handling honestly | | Other UGC | Review only for residual content not already classified as Name | Nicknames already belong in Name; report reason is fixed selection, no free text | No app collection found of photos, user audio, contacts, files/documents, health, finances, messages, installed apps, searches, browsing history or precise location. Audio assets are bundled music, not recordings of players. diff --git a/docs/privacy-policy-draft.md b/docs/privacy-policy-draft.md index 6b6b29f..b9273ef 100644 --- a/docs/privacy-policy-draft.md +++ b/docs/privacy-policy-draft.md @@ -1,12 +1,12 @@ # Asteroids privacy policy — review draft -**Not approved for publication or distribution.** Public contact, provider retention and final game name require review. Package: `ca.davidandrea.spacearcade`. Proposed effective date: set on approval. +**Not approved for publication or distribution.** Provider retention, mailbox handling and final game name require review. The public contact is confirmed (below); filling it in does not approve this text. Package: `ca.davidandrea.spacearcade`. Proposed effective date: set on approval. -**Deployment status (2026-11-12):** the reporting, operator moderation (name replacement, hide/restore, report resolution, audit history) and erasure functions this draft describes have been live in the production leaderboard service since 2026-11-04 (Worker version `c2aef78f`; [Stage 2 record](release-preflight.md#stage-2-production-worker-deployment-2026-11-04)). The policy text itself is **still an unapproved draft**: the public web build and any test APK show the bundled Privacy screen marked `DRAFT PRIVACY POLICY - REVIEW PENDING` with `[PRIVACY CONTACT PENDING]`. Deployment of these features does not approve this text, the contact, or the retention statements below. +**Deployment status (2026-11-12):** the reporting, operator moderation (name replacement, hide/restore, report resolution, audit history) and erasure functions this draft describes have been live in the production leaderboard service since 2026-11-04 (Worker version `c2aef78f`; [Stage 2 record](release-preflight.md#stage-2-production-worker-deployment-2026-11-04)). The policy text itself is **still an unapproved draft**: the public web build and any test APK show the bundled Privacy screen marked `DRAFT PRIVACY POLICY - REVIEW PENDING` (deployed builds still show `[PRIVACY CONTACT PENDING]` until rebuilt from a commit that has the confirmed address). Deployment of these features does not approve this text or the retention statements below. A daily operator email digest of pending moderation items is implemented but not yet deployed; see [the operator guide](leaderboard-moderation.md#daily-moderation-digest). -Operator: **David Andrea** (confirmed 2026-11-04). Privacy, security and removal contact: **[PUBLIC EMAIL PENDING]**. +Operator: **David Andrea** (confirmed 2026-11-04). Privacy, security, removal, appeal and moderation contact: **privacy@davidandrea.ca** (confirmed 2026-11-12; also in `phaser-asteroids/src/ui/menu/pages/privacy.ts`). -**Deferred follow-up — 2026-11-04:** David will choose the public address for privacy, security, leaderboard removal and moderation requests later. Keep the contact placeholders until that decision is made, then update this draft and `phaser-asteroids/src/ui/menu/pages/privacy.ts`. Confirm mailbox handling and retention before distribution; no address has been selected or invented. +**Policy decision — 2026-11-12:** verified leaderboard scores are retained indefinitely by default, subject to moderation, legitimate removal requests and any later reasonable storage policy. No automatic deletion of low or old scores is planned. Before distribution, still confirm how the mailbox and its correspondence are handled and retained. Asteroids is a game without user accounts, advertising or analytics SDKs. You can play Practice without uploading gameplay. Menus may contact the online service to retrieve public scores and refresh scores previously saved on your device. @@ -16,13 +16,13 @@ Submitting a score makes its nickname, score, completion date, simulated duratio Cloudflare hosts our API and D1 database and processes network requests, including IP addresses and ordinary request metadata. Our application database stores a salted hash derived from an IP address for rate limiting and abuse handling, rather than the raw IP address. Hashes are pseudonymous, not guaranteed anonymous. Cloudflare may process technical data to operate and secure its services. We do not sell your data or use it for advertising. Review Cloudflare's [privacy policy](https://www.cloudflare.com/privacypolicy/). -Accepted leaderboard entries and linked run records have no automatic deletion date, including entries hidden by moderators. Daily cleanup deletes abandoned challenges more than one day after their expiry, rejected runs more than 30 days after rejection, and request counters whose hourly window started more than two hours ago. Expiry of a challenge (normally one hour) limits submission; it is not immediate deletion. Cleanup depends on the scheduled job running successfully. +Verified leaderboard entries and linked run records are kept indefinitely by default: they have no automatic deletion date, including entries hidden by moderators. An entry can be removed through moderation or a removal request, and we may adopt a different storage period in a later version of this policy. Daily cleanup deletes abandoned challenges more than one day after their expiry, rejected runs more than 30 days after rejection, and request counters whose hourly window started more than two hours ago. Expiry of a challenge (normally one hour) limits submission; it is not immediate deletion. Cleanup depends on the scheduled job running successfully. -Reports contain the reported score identifier, a selected reason, a salted IP hash, a timestamp and review status. They are private to the operator and used for moderation. Reports are deleted after 30 days by daily cleanup, or when the associated score is erased. Moderation decisions retain a fixed action/category, time, score link and prior moderation state without copying names or reporter identifiers. These records have no automatic expiry; erasure removes their link to the deleted score. **Provider-retention review pending:** D1 recovery history and Cloudflare logs can retain information separately from the live database. Confirm the account's actual settings, recovery period, exports and other provider retention before publishing this paragraph. Do not promise immediate removal from backups. +Reports contain the reported score identifier, a selected reason, a salted IP hash, a timestamp and review status. They are private to the operator and used for moderation. Reports are deleted after 30 days by daily cleanup, or when the associated score is erased. The operator receives a daily email summary while reports or flagged scores await review; it contains only counts and a link to the moderation console, not nicknames, report sources or other player data. Moderation decisions retain a fixed action/category, time, score link and prior moderation state without copying names or reporter identifiers. These records have no automatic expiry; erasure removes their link to the deleted score. **Provider-retention review pending:** D1 recovery history and Cloudflare logs can retain information separately from the live database. Confirm the account's actual settings, recovery period, exports and other provider retention before publishing this paragraph. Do not promise immediate removal from backups. The game stores audio, input, movement and vibration preferences, the last accepted nickname, up to 20 accepted scores with identifiers, and blocked nicknames locally on your device. There is no timed expiry. Clear the app's storage in Android settings (or site data in a browser) to remove this local data. This does not remove server records. Android backup is disabled in the manifest; device-transfer behavior may depend on the device vendor. -For removal of a leaderboard entry or associated run data, or for privacy or security questions, email **[PUBLIC EMAIL PENDING]** with the score identifier if available, nickname, score and approximate date. We may ask for context to avoid deleting someone else's entry. There is no account or account-deletion flow. Removal is handled by the operator; hiding a score is not erasure. Short-lived abuse counters and provider-controlled records follow their respective retention. Requests sent by email also disclose your email address and any information you include; use only the information necessary for the request. **Before publication, specify how the chosen mailbox provider and request correspondence are handled and retained.** +For removal of a leaderboard entry or associated run data, to appeal a moderation decision, or for privacy or security questions, email **privacy@davidandrea.ca** with the score identifier if available, nickname, score and approximate date. We may ask for context to avoid deleting someone else's entry. There is no account or account-deletion flow. Removal is handled by the operator; hiding a score is not erasure. Short-lived abuse counters and provider-controlled records follow their respective retention. Requests sent by email also disclose your email address and any information you include; use only the information necessary for the request. **Before publication, specify how the chosen mailbox provider and request correspondence are handled and retained.** From High Scores, choose Report / Block to report an abusive nickname or hide entries using that nickname on your device. Nicknames are not unique accounts: blocking also hides other people using the same name and cannot follow someone who changes names. @@ -30,10 +30,10 @@ App-to-service traffic uses HTTPS. Administration requires a secret credential. ## Leaderboard rules -By submitting, you accept public display and these rules. Do not use hateful, sexual, threatening or harassing nicknames, impersonate others, or expose personal information. We may replace displayed nicknames, hide or remove entries that violate these rules. A replacement keeps the verified score intact; the original name remains private until the entry is erased. Reports are reviewed by the operator; submitting a report does not automatically remove an entry. +By submitting, you accept public display and these rules. Do not use hateful, sexual, threatening or harassing nicknames, impersonate others, or expose personal information. We may replace displayed nicknames, hide or remove entries that violate these rules. A replacement keeps the verified score intact; the original name remains private until the entry is erased. Reports are reviewed by the operator; submitting a report does not automatically remove an entry. To request removal of your own entry or appeal a decision, email privacy@davidandrea.ca. ## Hosting proposal (not deployed) After review, publish an HTML policy at an operator-controlled, stable HTTPS URL such as `https://davidandrea.ca/spacearcade/privacy/` (proposed path only; ownership and hosting not verified). A separately reviewed static page on the existing GitHub Pages site is an alternative. The URL must work without login, geo restrictions or downloading a PDF. Keep the operator/contact and app identity consistent with Play Console. Do not place the draft in `public/` or a deployment workflow: normal web builds must not accidentally publish it. -The game now includes an offline, paginated PRIVACY menu plus Privacy / Leaderboard Rules before score submission. Before distribution, replace review placeholders and keep its text synchronized with the approved public policy. A remote policy link can be added after its URL is approved; offline access remains useful on phones. +The game now includes an offline, paginated PRIVACY menu plus Privacy / Leaderboard Rules before score submission. Its contact placeholder was replaced with privacy@davidandrea.ca on 2026-11-12; its `DRAFT PRIVACY POLICY - REVIEW PENDING` marker stays (and the signed-release inspector refuses it) until this policy is approved. Keep its text synchronized with the approved public policy. A remote policy link can be added after its URL is approved; offline access remains useful on phones. diff --git a/docs/release-preflight.md b/docs/release-preflight.md index 6d4f49a..e205364 100644 --- a/docs/release-preflight.md +++ b/docs/release-preflight.md @@ -15,14 +15,15 @@ Branch `release/android-device-prep` (from `dev` after merging `main`'s Stage 2 ### Confirmed blockers for internal testing -1. **Privacy policy and contact:** `[PUBLIC EMAIL PENDING]` / `[PRIVACY CONTACT PENDING]` remain in the draft and the bundled app text, which is marked as a draft (and public on GitHub Pages). An approved hosted policy URL is needed for Play Console. Owner decision; nothing has been chosen or approved. +1. **Privacy policy:** the contact is now **privacy@davidandrea.ca** (confirmed 2026-11-12; draft and bundled text updated on `feature/moderation-digest`, not yet built or deployed, so GitHub Pages still shows the placeholder). The text is still a draft and the bundled screen keeps its `DRAFT PRIVACY POLICY - REVIEW PENDING` marker. An approved hosted policy URL is needed for Play Console. Approval remains an owner decision. 2. **Signing:** no upload key exists in this environment; Play App Signing is not enrolled; no signed AAB exists. Confirm in Console that version code 1 is unused. 3. **Physical device:** not yet tested. A sideload build and [checklist](../phaser-asteroids/docs/phone-test-checklist.md) are ready. ADB saw a Samsung SM-S901E only briefly over a local bridge (then `offline`), so nothing was installed or queried. 4. **Play Console setup:** app record, app name (launcher still `phaser-asteroids`), icon/splash/listing assets, and the declarations Console lists as outstanding (privacy policy URL, ads, content rating, target audience, app access). Data safety is exempt for internal-only testing. ### Requires manual verification or an owner decision -- Moderation coverage: the initial review of existing names ([workflow step 2](leaderboard-moderation.md#daily-solo-administrator-workflow)) is still to do. Decide whether nickname-only blocking and submit-as-acceptance satisfy Play UGC for an accountless app. +- Moderation coverage: the initial review of existing names ([workflow step 2](leaderboard-moderation.md#daily-solo-administrator-workflow)) is still to do. Decide whether nickname-only blocking and submit-as-acceptance satisfy Play UGC for an accountless app ([readiness assessment](leaderboard-moderation.md#google-play-ugc-readiness-rechecked-2026-11-12)). +- **Daily moderation digest** (implemented and tested locally on `feature/moderation-digest`, 2026-11-12): needs migration **0005** applied to production D1 (additive, staged like 0003/0004), a Resend-verified sender (`MODERATION_DIGEST_FROM`) and the `RESEND_API_KEY` secret. Disabled and harmless until then; deploying the code before 0005 is safe. See [activation](leaderboard-moderation.md#daily-moderation-digest). Report-retention options A-D await an owner decision ([policy](leaderboard-moderation.md#report-retention-and-review-policy)). - Provider retention (Workers logs/observability, Time Travel window, export copies) for the privacy text. - A 16 KB-page device or emulator, a Play-delivered install/update, and a tablet/large screen. - Existing installs: no build has been distributed (`distributed: null`), so the only possible prior installs are developer builds signed with the same local debug key. See checklist section 9. diff --git a/phaser-asteroids/docs/google-play-release.md b/phaser-asteroids/docs/google-play-release.md index a7637a9..7dc4420 100644 --- a/phaser-asteroids/docs/google-play-release.md +++ b/phaser-asteroids/docs/google-play-release.md @@ -6,9 +6,9 @@ Prepared 2026-11-03 on `dev`. **Local preparation only; nothing was published or Use the [production release preflight](../../docs/release-preflight.md) for the audited commit, staged 0003/0004 migration commands, backup/recovery and installed-client report. The main GitHub workflow deploys the Worker automatically and does not check schema; complete the authorized migration gates before triggering it. Latest local evidence is in [release validation](../../docs/play-release-validation.md); unsigned artifact success does not establish device, signing or Play readiness. -- Approve `../../docs/privacy-policy-draft.md`, public contact, provider retention and target ages/content rating. Operator is David Andrea (confirmed 2026-11-04); choosing the public contact address is intentionally deferred and must be revisited before distribution. Replace bundled contact placeholders in `src/ui/menu/pages/privacy.ts`; synchronize policy text. Host the approved policy separately and provide its public URL to Play Console. Do not distribute a draft policy. +- Approve `../../docs/privacy-policy-draft.md`, public contact, provider retention and target ages/content rating. Operator is David Andrea (confirmed 2026-11-04); public contact **privacy@davidandrea.ca** (confirmed 2026-11-12, now in `src/ui/menu/pages/privacy.ts` and the draft). The bundled `DRAFT PRIVACY POLICY - REVIEW PENDING` marker stays until the policy is approved; the signed-release inspector refuses it. Synchronize the policy text on approval. Host the approved policy separately and provide its public URL to Play Console. Do not distribute a draft policy. - **Done 2026-11-04:** migrations 0003/0004 (Stage 1) and the moderation Worker (Stage 2, version `c2aef78f`) are in production and were verified (public 31/31, admin read-only 19/19); see the [Stage 2 record](../../docs/release-preflight.md#stage-2-production-worker-deployment-2026-11-04). The backend therefore already supports the app's suspicious_score report reason. The daily cleanup cron has run successfully every day since (verified read-only 2026-11-12; see the [current status](../../docs/release-preflight.md#current-status-2026-11-12)). For any later backend change, the backend still deploys before the app. -- Establish report review coverage and the removal process in `../../docs/leaderboard-moderation.md`. Confirm production CORS still permits `https://spacearcade.davidandrea.ca` and `https://djblackett.github.io`. Do not loosen origins or expose admin credentials in the app. +- Establish report review coverage and the removal process in `../../docs/leaderboard-moderation.md`, and activate the [daily moderation digest](../../docs/leaderboard-moderation.md#daily-moderation-digest) (migration 0005, Resend sender and key) so review does not depend on checking the console. UGC readiness is assessed in the same guide; it is not established. Confirm production CORS still permits `https://spacearcade.davidandrea.ca` and `https://djblackett.github.io`. Do not loosen origins or expose admin credentials in the app. - Install Node/npm matching the lockfile/toolchain (validated here with Node 26.13.0/npm 11.20.0), JDK 21, Android SDK 36 and Build Tools 36.1.0. Use the committed Gradle wrapper 8.14.3 and AGP 8.13.0. `JAVA_HOME` selects JDK 21; check user Gradle properties/Android Studio settings do not override it. Do not commit local machine paths. Java source compatibility remains 17. ## Version management diff --git a/phaser-asteroids/docs/phone-test-checklist.md b/phaser-asteroids/docs/phone-test-checklist.md index 2ab9037..93d5b1d 100644 --- a/phaser-asteroids/docs/phone-test-checklist.md +++ b/phaser-asteroids/docs/phone-test-checklist.md @@ -118,7 +118,7 @@ The signed-release inspector (no `-Unsigned`) refuses this APK: debug key, plus | # | Check | Expected | Result | | --- | --- | --- | --- | -| 8.1 | PRIVACY menu: all 4 pages, NEXT/BACK | Readable at phone size; shows the **draft** marker and `[PRIVACY CONTACT PENDING]` (expected until the policy is approved) | | +| 8.1 | PRIVACY menu: all 4 pages, NEXT/BACK | Readable at phone size; shows the **draft** marker (expected until the policy is approved) and the contact `privacy@davidandrea.ca` | | | 8.2 | HIGH SCORES > REPORT / BLOCK > Report your own test entry (writes a private report) | Success message (note what a second report of the same entry shows; the server keeps one report per entry and network); the entry appears in `/admin` Needs review | | | 8.3 | Block that nickname | Entries with that name replaced on this device; survives app restart | | | 8.4 | Unblock | Entries return | | diff --git a/phaser-asteroids/server/README.md b/phaser-asteroids/server/README.md index b974cf8..e47f1a1 100644 --- a/phaser-asteroids/server/README.md +++ b/phaser-asteroids/server/README.md @@ -28,4 +28,4 @@ do not use it for ordinary CI releases or rotate secrets accidentally. Never put 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. -Moderation: see the [audit and operator guide](../../docs/leaderboard-moderation.md). The same-origin `/admin` console uses the existing admin secret in tab memory. Migrations 0003 and 0004 are prerequisites. `npm run test:moderation:admin` from `phaser-asteroids` exercises the workflow in Chromium against disposable local D1. +Moderation: see the [audit and operator guide](../../docs/leaderboard-moderation.md). The same-origin `/admin` console uses the existing admin secret in tab memory. Migrations 0003 and 0004 are prerequisites. The optional daily email digest needs 0005 plus `RESEND_API_KEY` and `MODERATION_DIGEST_FROM` (see the guide's *Daily moderation digest*); unconfigured, it does nothing. `npm run test:moderation:admin` from `phaser-asteroids` exercises the workflow in Chromium against disposable local D1. diff --git a/phaser-asteroids/src/ui/menu/pages/privacy.ts b/phaser-asteroids/src/ui/menu/pages/privacy.ts index 67a6915..2dcfd61 100644 --- a/phaser-asteroids/src/ui/menu/pages/privacy.ts +++ b/phaser-asteroids/src/ui/menu/pages/privacy.ts @@ -3,9 +3,9 @@ import type { PageBuilder } from '../menuView'; import { MenuButton, MIN_TARGET } from '../widgets'; import { CENTER_X, pageTitle } from './common'; -// Review copy, bundled offline. Operator confirmed 2026-11-04. Public contact -// intentionally deferred by David; replace the contact and review status before distribution. -export const PRIVACY_CONTACT = '[PRIVACY CONTACT PENDING]'; +// Review copy, bundled offline. Operator confirmed 2026-11-04; public contact confirmed 2026-11-12. The policy text is still +// awaiting approval: keep the DRAFT marker (the signed-release inspector refuses it) until docs/privacy-policy-draft.md is approved. +export const PRIVACY_CONTACT = 'privacy@davidandrea.ca'; export const PRIVACY_PAGES = [ [ 'DRAFT PRIVACY POLICY - REVIEW PENDING', @@ -22,7 +22,7 @@ export const PRIVACY_PAGES = [ 'Cloudflare processes requests, including your IP and request metadata.', 'We store a salted IP hash for abuse prevention, not the raw IP.', 'Full replays are processed in memory; only their submission hash is kept.', - 'Accepted scores and linked run data have no automatic expiry, even if hidden.', + 'Verified scores and linked run data have no automatic expiry, even if hidden.', 'Daily cleanup removes abandoned runs 1 day after expiry and', 'rejected runs after 30 days; old hourly counters after 2 hours.', 'Reports (entry, reason, IP hash) expire after 30 days at daily cleanup.', @@ -33,7 +33,7 @@ export const PRIVACY_PAGES = [ 'Settings, last nickname, up to 20 accepted scores and blocked names', 'stay in local storage. Clear app storage to remove them from this device.', 'This does not remove server entries. No sale of data or ad tracking.', - 'For removal, privacy or security requests, contact:', + 'For removal, appeal, privacy or security requests, email:', PRIVACY_CONTACT, 'Include the score ID, nickname, score and date. Do not send passwords.', 'We may ask for context to prevent removal of someone else\'s score.', From b7385e84614751c5f41f945624fa286b529a9f25 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:48:37 -0400 Subject: [PATCH 07/14] docs(privacy): Hull & Havoc public privacy page for GitHub Pages (unpublished) Add phaser-asteroids/public/privacy/index.html (standalone, no scripts or third-party resources), point the offline privacy screens at it, extend pages-check and add a content guard test. Record facts, open questions and publish steps in docs/privacy-policy-publication.md. Package ID unchanged; the offline DRAFT marker stays until approval. Co-Authored-By: Claude Sonnet 5.5 --- docs/privacy-policy-draft.md | 4 +- docs/privacy-policy-publication.md | 46 ++++++ phaser-asteroids/docs/google-play-release.md | 2 +- phaser-asteroids/public/privacy/index.html | 149 ++++++++++++++++++ phaser-asteroids/scripts/pages-check.mjs | 18 +++ phaser-asteroids/src/ui/menu/pages/privacy.ts | 13 +- phaser-asteroids/tests/privacyPage.test.ts | 47 ++++++ 7 files changed, 270 insertions(+), 9 deletions(-) create mode 100644 docs/privacy-policy-publication.md create mode 100644 phaser-asteroids/public/privacy/index.html create mode 100644 phaser-asteroids/tests/privacyPage.test.ts diff --git a/docs/privacy-policy-draft.md b/docs/privacy-policy-draft.md index 6b6b29f..11afabf 100644 --- a/docs/privacy-policy-draft.md +++ b/docs/privacy-policy-draft.md @@ -1,4 +1,4 @@ -# Asteroids privacy policy — review draft +# Hull & Havoc privacy policy — review draft **Not approved for publication or distribution.** Public contact, provider retention and final game name require review. Package: `ca.davidandrea.spacearcade`. Proposed effective date: set on approval. @@ -34,6 +34,6 @@ By submitting, you accept public display and these rules. Do not use hateful, se ## Hosting proposal (not deployed) -After review, publish an HTML policy at an operator-controlled, stable HTTPS URL such as `https://davidandrea.ca/spacearcade/privacy/` (proposed path only; ownership and hosting not verified). A separately reviewed static page on the existing GitHub Pages site is an alternative. The URL must work without login, geo restrictions or downloading a PDF. Keep the operator/contact and app identity consistent with Play Console. Do not place the draft in `public/` or a deployment workflow: normal web builds must not accidentally publish it. +**Decision (2026-11-12):** host the policy on the existing GitHub Pages site at `https://djblackett.github.io/asteroids-bootdev/privacy/`. The page is prepared, unpublished, at `phaser-asteroids/public/privacy/index.html`; its facts, open questions and the publish steps are in [privacy-policy-publication.md](privacy-policy-publication.md). Final name: **Hull & Havoc** (Android package ID unchanged). The URL must work without login, geo restrictions or downloading a PDF. Keep the operator/contact and app identity consistent with Play Console. The page now lives in `public/`, so merging it to `main` publishes it on the next release run: merge only after approval. The game now includes an offline, paginated PRIVACY menu plus Privacy / Leaderboard Rules before score submission. Before distribution, replace review placeholders and keep its text synchronized with the approved public policy. A remote policy link can be added after its URL is approved; offline access remains useful on phones. diff --git a/docs/privacy-policy-publication.md b/docs/privacy-policy-publication.md new file mode 100644 index 0000000..c420368 --- /dev/null +++ b/docs/privacy-policy-publication.md @@ -0,0 +1,46 @@ +# Hull & Havoc privacy policy: publication record + +Prepared 2026-11-12 on branch `feature/privacy-policy-page`. **Not published. Not approved.** Nothing was pushed, merged, deployed or uploaded. + +- Public page source: `phaser-asteroids/public/privacy/index.html` (standalone, no scripts or third-party resources; Vite copies `public/` unchanged to `dist/privacy/index.html`). +- Proposed URL: `https://djblackett.github.io/asteroids-bootdev/privacy/` +- Contact: `privacy@davidandrea.ca`. Name: Hull & Havoc. Package ID: `ca.davidandrea.spacearcade` (unchanged). +- Offline copy: `phaser-asteroids/src/ui/menu/pages/privacy.ts` (still carries the `DRAFT PRIVACY POLICY - REVIEW PENDING` marker, so the signed-release inspector keeps refusing it; it now also shows the URL above). +- Guards: `tests/privacyPage.test.ts` (content, no placeholders/secrets/external resources) and `scripts/pages-check.mjs` check 4 (served at `/asteroids-bootdev/privacy/` and `/privacy/`). + +## Fact check (page statement → evidence) + +| Statement | Evidence | +| --- | --- | +| Retention: abandoned challenges 1 day after expiry, rejected runs 30 days, counters >2 h, reports 30 days | `server/src/runs.ts` (`pruneStaleRuns`), `moderation.ts` (`pruneReports`), `ratelimit.ts`; cron `17 7 * * *` in `wrangler.toml`; production cron success verified 2026-11-12 per release docs | +| Scores kept indefinitely | Owner decision 2026-11-12; no delete path for accepted scores in the cron | +| Nickname screening is a short English word list | `server/src/nickname.ts` | +| Public fields; private fields | `docs/play-data-inventory.md`, `server/src/leaderboard.ts` | +| Hash is salted SHA-256 prefix, same salt, links entries | `server/src/router.ts`, `config.ts` per inventory | +| Local storage contents; backup disabled | inventory; Android manifest/`data_extraction_rules.xml` | +| Reports: fixed reason, no free text, IP hash, private | `migrations 0003/0004`, `moderation.ts` | +| Moderation actions, audit without names | migration 0004, `moderation.ts` | +| Moderation features live in production | Stage 2 record in `release-preflight.md` (Worker `c2aef78f`, 2026-11-04) | + +**Deliberately not in the page:** the daily moderation digest. It is uncommitted work on `feature/moderation-digest`, not deployed (`MODERATION_DIGEST_FROM` and the Resend key are unset), so it is not described as operating. It sends the operator counts only, no player data; add a line only if you want to name the email provider. + +## Unresolved: need your decision before publishing + +1. **Mailbox handling.** The page says correspondence stays in the email provider's mailbox with no fixed deletion period. Confirm that is true and acceptable, or set a period. +2. **Provider retention.** The page makes no Cloudflare retention promise. Optionally verify D1 Time Travel and Workers Logs settings for this account (see the inventory) and state real periods. +3. **Effective date.** The page says "Last updated 12 November 2026". Change the date (and the `datetime` attribute) on the day you approve. +4. **Audience / children.** No age statement is made because the target audience and content rating are undecided. Play will require this, and the policy may need a matching sentence. +5. **Legal rights text.** No jurisdiction-specific rights (Canada/PIPEDA, EU/UK GDPR, CCPA) or response times are stated. Decide whether your location and audience need them. +6. **Google Play.** Not checked against live Console requirements (offline session). Confirm the Data safety answers, that the URL is public and non-PDF, and that the policy identifies the developer/app name as shown in the listing. Rebuild the APK and remove the offline DRAFT marker (privacy.ts and `inspect-android-release.ps1` markers) only after approval. + +## Merge notes + +`docs/privacy-policy-draft.md`, `privacy.ts` and `google-play-release.md` also have uncommitted edits in the main worktree (`feature/moderation-digest`). `privacy.ts` here already contains the same contact/wording edits, so they should merge cleanly. Merge the digest branch first, then this one. + +## Publishing (after your explicit approval) + +1. Review `public/privacy/index.html`; resolve the questions above; update the date. +2. Remove nothing from the offline screens yet unless approving for distribution; if approving, drop the DRAFT marker in `privacy.ts` and the matching marker in `scripts/inspect-android-release.ps1` plus `tests/androidRelease.test.ts` expectations. +3. Open a PR into `main`. CI validates (typecheck, tests, build, `pages-check`). +4. Merge. The workflow deploys the Worker first, then GitHub Pages, so follow the release preflight (migrations/secrets) before merging. +5. Open the URL in a private window. Enter it in Play Console. diff --git a/phaser-asteroids/docs/google-play-release.md b/phaser-asteroids/docs/google-play-release.md index a7637a9..44a85c3 100644 --- a/phaser-asteroids/docs/google-play-release.md +++ b/phaser-asteroids/docs/google-play-release.md @@ -82,7 +82,7 @@ The inspector checks APK and AAB for **all** `.so` files, not merely direct proj ## Internal testing (manual, after approval) -1. Recheck Console's outstanding setup requirements. Choose app identity, target audience/content rating, ads declaration (no ads), privacy URL and proposed Data safety answers from the inventory. Apps exclusively on internal testing currently have a Data safety form exemption; prepare accurate answers before closed/open/production tracks. +1. Recheck Console's outstanding setup requirements. Choose app identity, target audience/content rating, ads declaration (no ads), privacy URL and proposed Data safety answers from the inventory. Game name **Hull & Havoc**, Android package ID unchanged (`ca.davidandrea.spacearcade`), privacy contact `privacy@davidandrea.ca`, proposed privacy-policy URL `https://djblackett.github.io/asteroids-bootdev/privacy/` (not live until approved and released; see [privacy-policy-publication.md](../../docs/privacy-policy-publication.md)). The policy page supports the Data safety rows in the inventory (name, app activity, IP-derived identifier, deletion requests) but approval by Google Play is not established by it. Apps exclusively on internal testing currently have a Data safety form exemption; prepare accurate answers before closed/open/production tracks. 2. Under Test and release > Testing > Internal testing, create a release, enroll Play App Signing and upload the **signed** AAB for `ca.davidandrea.spacearcade`. Confirm code/name, upload certificate, supported devices, target SDK, permissions, 16 KB status and pre-launch diagnostics. Resolve errors; do not ignore policy warnings. Add an internal tester list (up to 100) and release notes. Publishing/rolling out is a separate authorized human action; it was not done here. 3. Send the opt-in URL only to intended testers. A sideloaded debug APK with this package ID cannot normally be upgraded by a Play-signed app: uninstall the debug build first if signatures differ (loses its local data; server scores remain). 4. Install from Play using an enrolled Google account, confirm the delivered version, then test fresh install and update paths. Check fullscreen/rotation/Back, audio/vibration, offline Practice, ranked challenge/submission/retry, nickname input and Skip, weekly/all-time pages, Privacy/Rules return navigation, report success/failure/rate limiting and block/unblock persistence. Use harmless test nicknames. Ranked tests against production create real scores; obtain explicit authorization before doing that. Prefer a separately authorized test backend if production data must remain untouched. diff --git a/phaser-asteroids/public/privacy/index.html b/phaser-asteroids/public/privacy/index.html new file mode 100644 index 0000000..36fc32a --- /dev/null +++ b/phaser-asteroids/public/privacy/index.html @@ -0,0 +1,149 @@ + + + + + + + + Hull & Havoc — Privacy Policy + + + + +
+

← Back to the game

+

Hull & Havoc — Privacy Policy

+

Last updated:

+

Operator: David Andrea · Contact: privacy@davidandrea.ca

+ +
+

The short version

+
    +
  • Hull & Havoc has no accounts, no advertising and no analytics or tracking libraries.
  • +
  • You can play Practice without uploading anything. Ranked play and the online leaderboard are optional.
  • +
  • If you submit a ranked score, your nickname and score become public on the leaderboard.
  • +
  • To check that a score is genuine, the game sends the server a record of your controls for that run. The server keeps the result, not the full recording.
  • +
  • We keep a scrambled (hashed) version of your IP address to limit abuse. We do not store the raw address in our own database.
  • +
  • To ask for a leaderboard entry to be removed, or to ask any privacy question, email privacy@davidandrea.ca.
  • +
+
+ +

About this policy

+

This policy covers the Hull & Havoc game (Android package ca.davidandrea.spacearcade) and its web version, together with the online leaderboard service they use. The game is run by David Andrea, who is the person responsible for the information described here.

+ +

Playing without going online

+

Practice mode does not upload your gameplay. The game may still contact the leaderboard service in the background, for example to show public scores or to refresh scores you previously saved on your device, so Practice is not a promise that no network requests are made.

+ +

Ranked play and score submission

+

Starting a ranked run asks the server for a challenge. If you then choose to submit your result, the game sends:

+
    +
  • the nickname you chose (or none, which is shown as “Anonymous”);
  • +
  • a replay of the run, meaning the changes in your movement, aiming and action controls over time;
  • +
  • game and rules versions, game configuration, timing, and the result the game claims;
  • +
  • the type of controls you used (for example keyboard, gamepad or touch). This is informational and does not affect your rank.
  • +
+

The server replays your inputs itself to confirm the score. The full replay is processed in memory and is not stored. We keep the verified result and details of the run, plus a fingerprint (hash) of the submission that is used to detect duplicates and problems.

+

You can skip submitting at any time.

+ +

What is public

+

When a score is accepted, the leaderboard shows its nickname, score, completion date, simulated duration, rules version, ending reason and a score identifier. Please choose a nickname that does not reveal personal information. Other people can see and copy public entries, and we cannot remove copies that others make.

+

Other details of a run, such as control type, kill counts and moderation notes, are kept private.

+ +

IP addresses and Cloudflare

+

The leaderboard runs on Cloudflare (a Worker and a database). Like any online service, Cloudflare processes network requests, which include your IP address and ordinary request details such as your browser or device type and the address requested. Cloudflare may use this technical data to run and secure its own service. See Cloudflare’s privacy policy.

+

Our own database does not store your raw IP address. Instead it stores a salted hash derived from it, used to rate-limit requests and handle abuse. The same secret salt is used each time, so entries from the same address can be linked to each other. A hash is pseudonymous, not guaranteed anonymous. A hash is stored with ranked challenges and with reports.

+

We do not sell your data and we do not use it for advertising.

+ +

Information stored on your device

+

The game keeps these in local storage on your device: audio, input, movement and vibration settings; your most recent accepted nickname; up to 20 of your accepted scores (with their identifiers); and the list of nicknames you have blocked. None of it expires on its own. To remove it, clear the app’s storage in Android settings, or clear site data in your browser. This does not remove anything stored on the server. Android backup is turned off for the app; whether data moves with a device-to-device transfer can depend on the phone maker.

+

If you play the web version, the page and its files are delivered by GitHub Pages, which, like any web host, receives standard request information. This privacy page is hosted there too. The Android app includes its game files and does not download them from GitHub.

+ +

How long we keep information

+
+ + + + + + + + + + + + + +
Retention on the leaderboard service
InformationHow long
Verified leaderboard entries and their linked run recordsKept indefinitely by default, including entries that moderators have hidden. They have no automatic deletion date. An entry can be removed through moderation or on request, and we may adopt a different storage period in a later version of this policy.
Unfinished ranked challengesA challenge normally expires after one hour. A daily cleanup deletes unfinished challenges more than one day after they expire.
Rejected submissionsDeleted by the daily cleanup more than 30 days after rejection.
Request counters used for rate limitingDeleted by the daily cleanup once their hourly window began more than two hours earlier.
Reports about nicknames or scoresDeleted by the daily cleanup after 30 days, or earlier if the reported entry is erased.
Moderation decision recordsNo automatic expiry. If the related entry is erased, the record is kept without its link to that entry.
+
+

The cleanup runs once a day and depends on that scheduled job running successfully, so deletion can occur somewhat later than the times above.

+

Backups and logs. Cloudflare may keep logs and database recovery history for its own periods, separately from the live database. Removing something from the live database does not instantly remove it from those provider records, and we do not control how long they are kept. When we erase a leaderboard entry we do not promise immediate removal from backups or logs.

+ +

Nicknames, reports and moderation

+

Nicknames are screened automatically against a short list of unacceptable English words. This is a first-pass filter only, not a guarantee that every unsuitable name is caught.

+

From the High Scores menu, choose Report / Block to report a nickname or score. A report records the reported entry, a reason you choose from a fixed list, a salted hash of your IP address, the time, and whether it has been reviewed. You cannot type free text into a report. Reports are private and are reviewed by the operator. Sending a report does not automatically hide or remove anything.

+

The operator can replace a displayed nickname, hide or restore an entry, or remove it if it breaks the rules below. When a name is replaced, the verified score stays and the original name remains private until the entry is erased. Scores with unusual patterns may also be flagged for human review. Decisions are recorded as a fixed action and category, a time and a link to the entry, without copying names or reporter details.

+

Blocking only works on your own device: it hides entries that use that nickname for you. Nicknames are not accounts, so blocking also hides other people who use the same name and cannot follow someone who changes names.

+ +

Leaderboard rules

+

By submitting a score you accept public display of the entry and these rules. Do not use hateful, sexual, threatening or harassing nicknames, impersonate other people, or reveal personal information about anyone. We may replace names, and hide or remove entries that break these rules.

+ +

Removal requests, appeals and questions

+

There are no accounts, so there is nothing to log into or delete. To have a leaderboard entry or its run data removed, to appeal a moderation decision, or to ask anything about privacy or security, email privacy@davidandrea.ca. Please include the score identifier if you have it, plus the nickname, score and approximate date. We may ask for more context so that we do not remove someone else’s entry. Hiding an entry is not the same as erasing it, and removal is done by the operator.

+

Please send only the information needed for your request, and never a password. Your email address and anything you write are visible to us, and your message stays in the mailbox of our email provider. We have not set a fixed deletion period for correspondence and will keep it only as long as needed to handle your request and any follow-up.

+ +

Security

+

Traffic between the game and the leaderboard uses HTTPS. Administration of the service requires a secret credential. No system for transmitting or storing data can be guaranteed to be completely secure.

+ +

Changes to this policy

+

If our practices change, we will update this page and its “Last updated” date. The shorter privacy screens inside the game are a summary of this policy and may not include every detail; if they differ, this page is the fuller version.

+ + +
+ + diff --git a/phaser-asteroids/scripts/pages-check.mjs b/phaser-asteroids/scripts/pages-check.mjs index 0974aa9..13ac44e 100644 --- a/phaser-asteroids/scripts/pages-check.mjs +++ b/phaser-asteroids/scripts/pages-check.mjs @@ -228,6 +228,24 @@ async function checkMount(mount) { check(`${label} ?keydebug loads and shows its panel, with no errors`, panel && problems.length === 0, problems.join(' | ')); await page.close(); } + // 4. The static privacy policy (public/privacy/index.html) is served under the mount, loads without errors or off-site requests, and its + // "back to the game" link resolves to the game at the same mount. + { + const { page, problems, ok } = await open(); + const external = []; + page.on('request', (r) => { if (!r.url().startsWith(origin) && !r.url().startsWith('data:')) external.push(r.url()); }); + const res = await page.goto(url('privacy/')); + const heading = await page.locator('h1').textContent(); + const contact = await page.locator('main a[href="mailto:privacy@davidandrea.ca"]').count(); + const back = await page.locator('a', { hasText: 'Back to the game' }).evaluate((a) => a.href); + check(`${label} /privacy/ is served (200) with its heading and the privacy contact`, res?.status() === 200 && heading === 'Hull & Havoc — Privacy Policy' && contact > 0, `${res?.status()} ${heading} ${contact}`); + check(`${label} /privacy/ loads its favicon from the base path, with no errors and no off-site requests`, ok.has(`${mount}favicon.png`) && problems.length === 0 && external.length === 0, [...problems, ...external].join(' | ')); + check(`${label} /privacy/ links back to the game at the same mount`, back === url(''), back); + await page.setViewportSize({ width: 360, height: 640 }); + const phoneOverflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth); + check(`${label} /privacy/ does not scroll sideways at phone width (360px)`, !phoneOverflow); + await page.close(); + } check(`${label} nothing was requested outside the base path`, stray.length === 0, [...new Set(stray)].join(', ')); const redirect = mount === '/' ? null : await fetch(`${origin}${mount.slice(0, -1)}`, { redirect: 'manual' }); if (redirect) check(`${label} the path without a trailing slash redirects to it`, redirect.status === 301 && redirect.headers.get('location') === mount, `${redirect.status} ${redirect.headers.get('location')}`); diff --git a/phaser-asteroids/src/ui/menu/pages/privacy.ts b/phaser-asteroids/src/ui/menu/pages/privacy.ts index 67a6915..2c9da62 100644 --- a/phaser-asteroids/src/ui/menu/pages/privacy.ts +++ b/phaser-asteroids/src/ui/menu/pages/privacy.ts @@ -3,26 +3,27 @@ import type { PageBuilder } from '../menuView'; import { MenuButton, MIN_TARGET } from '../widgets'; import { CENTER_X, pageTitle } from './common'; -// Review copy, bundled offline. Operator confirmed 2026-11-04. Public contact -// intentionally deferred by David; replace the contact and review status before distribution. -export const PRIVACY_CONTACT = '[PRIVACY CONTACT PENDING]'; +// Review copy, bundled offline. Operator confirmed 2026-11-04; public contact confirmed 2026-11-12. The policy text is still +// awaiting approval: keep the DRAFT marker (the signed-release inspector refuses it) until docs/privacy-policy-draft.md is approved. +export const PRIVACY_CONTACT = 'privacy@davidandrea.ca'; export const PRIVACY_PAGES = [ [ 'DRAFT PRIVACY POLICY - REVIEW PENDING', - 'Asteroids / ca.davidandrea.spacearcade', + 'Hull & Havoc / ca.davidandrea.spacearcade', 'Operator: David Andrea. No accounts, ads or analytics SDKs.', 'Ranked play sends game inputs, versions, timing and control type', 'to Cloudflare to verify scores and prevent abuse.', 'Submitting publishes your nickname, score, date, duration and rules version.', 'Use a nickname without personal information. Submission is optional.', 'Practice does not upload gameplay. Menus may fetch public scores.', + 'Full policy: https://djblackett.github.io/asteroids-bootdev/privacy/', ], [ 'STORAGE AND RETENTION', 'Cloudflare processes requests, including your IP and request metadata.', 'We store a salted IP hash for abuse prevention, not the raw IP.', 'Full replays are processed in memory; only their submission hash is kept.', - 'Accepted scores and linked run data have no automatic expiry, even if hidden.', + 'Verified scores and linked run data have no automatic expiry, even if hidden.', 'Daily cleanup removes abandoned runs 1 day after expiry and', 'rejected runs after 30 days; old hourly counters after 2 hours.', 'Reports (entry, reason, IP hash) expire after 30 days at daily cleanup.', @@ -33,7 +34,7 @@ export const PRIVACY_PAGES = [ 'Settings, last nickname, up to 20 accepted scores and blocked names', 'stay in local storage. Clear app storage to remove them from this device.', 'This does not remove server entries. No sale of data or ad tracking.', - 'For removal, privacy or security requests, contact:', + 'For removal, appeal, privacy or security requests, email:', PRIVACY_CONTACT, 'Include the score ID, nickname, score and date. Do not send passwords.', 'We may ask for context to prevent removal of someone else\'s score.', diff --git a/phaser-asteroids/tests/privacyPage.test.ts b/phaser-asteroids/tests/privacyPage.test.ts new file mode 100644 index 0000000..6d03165 --- /dev/null +++ b/phaser-asteroids/tests/privacyPage.test.ts @@ -0,0 +1,47 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { PRIVACY_PAGES } from '../src/ui/menu/pages/privacy'; + +/** The public privacy page is a plain static file in public/, copied unchanged into the build. These checks keep it self-contained and finished. */ +const page = new TextDecoder().decode(readFileSync(resolve(import.meta.dirname, '..', 'public/privacy/index.html'))); +const text = page.replace(//g, '').replace(/<[^>]+>/g, ' '); + +describe('public privacy page (public/privacy/index.html)', () => { + it('names the game, the contact and the unchanged Android package', () => { + expect(page).toContain('Hull & Havoc — Privacy Policy'); + expect(page).toContain('

Hull & Havoc — Privacy Policy

'); + expect(page).toContain('mailto:privacy@davidandrea.ca'); + expect(page).toContain('ca.davidandrea.spacearcade'); + expect(page).toMatch(/