diff --git a/docs/digest-activation-runbook.md b/docs/digest-activation-runbook.md new file mode 100644 index 0000000..affe97d --- /dev/null +++ b/docs/digest-activation-runbook.md @@ -0,0 +1,311 @@ +# Hull & Havoc moderation digest: production activation runbook + +Prepared 2026-11-12 on `release/hull-and-havoc-rc`. **Nothing here has been run against production.** Every step marked *PRODUCTION WRITE*, *DNS*, *SECRET* or *LIVE EMAIL* needs your explicit authorization at the time you run it. The D1 blocks (``) were rehearsed against a local stand-in database; see [Rehearsal evidence](#rehearsal-evidence). + +What the digest is and how it behaves: [leaderboard-moderation.md#daily-moderation-digest](leaderboard-moderation.md#daily-moderation-digest). This runbook only activates it. + +## Dependencies and order + +| # | Step | Kind | Depends on | +| --- | --- | --- | --- | +| 1 | Confirm the `privacy@davidandrea.ca` mailbox | Owner, Google Workspace | | +| 2 | Resend account, sending subdomain, DNS records | DNS (Cloudflare), no MX change at the root | | +| 3 | Sending-only API key | Credential | 2 verified | +| 4-8 | D1 bookmark, export, verify, apply **0005**, verify | PRODUCTION WRITE (D1 only) | none of 1-3; can run any time | +| 9 | Set `MODERATION_DIGEST_FROM`, release through `main` | Release (Worker **and GitHub Pages**) | 2, 4-8, **privacy-policy approval** (see below) | +| 10 | Controlled delivery test | LIVE EMAIL (one) | 3 | +| 11 | `wrangler secret put RESEND_API_KEY` | SECRET | 9, 10 | +| 12 | Post-activation verification | Read-only | 11 plus the next 07:17 UTC cron | + +**Release coupling.** Pushing or merging to `main` runs `.github/workflows/deploy-gh-pages.yml`, which deploys the Worker *and* republishes GitHub Pages. This release candidate also contains the public privacy page (`phaser-asteroids/public/privacy/`) and the Hull & Havoc branding, so step 9 **publishes the privacy policy**. Do step 9 only after you approve the policy. To activate the digest earlier, release a server-only change (only `phaser-asteroids/server/**`) to `main` separately. That is a different release, and it needs its own review. + +**Safe orders.** The Worker code is safe on a database without 0005: unconfigured, it logs `disabled` and touches no digest table. Configured without the table, it logs `error` and cleanup still runs. 0005 is additive, and the current Worker `c2aef78f` ignores it. So 4-8 may come before or after 9. The order above (schema first) avoids any `error` run. + +## 1. Mailbox (owner, no repository change) + +Confirm in the Google Workspace admin console that `privacy@davidandrea.ca` is a mailbox, alias or group that you monitor. Do not change MX, SPF, DKIM or DMARC on `davidandrea.ca`; Google Workspace keeps receiving mail as now. + +## 2. Resend sending subdomain (DNS in Cloudflare) + +Use a **subdomain**, so the root domain's Google Workspace records stay untouched. Suggested name: `notify.davidandrea.ca` (any unused name works; it then appears in `MODERATION_DIGEST_FROM`). + +1. Sign in to Resend. Go to **Domains > Add domain** and enter the subdomain. Pick the region closest to you; it only affects the return-path host. +2. Resend lists the DNS records to add. **Copy the values from the Resend dashboard; do not type them from memory or from this page.** They are normally: + - a DKIM **TXT** record at `resend._domainkey.`; + - an **MX** record and an SPF **TXT** record on the bounce host `send.`. The MX sits on that host only, not on `davidandrea.ca`, so inbound mail at the root is unaffected; + - optionally a DMARC **TXT** record at `_dmarc.`. Without one, the subdomain inherits the root domain's DMARC policy, which is fine. +3. In the Cloudflare dashboard, open **davidandrea.ca > DNS > Records** and add each record exactly as shown, as **DNS only** (grey cloud; TXT and MX cannot be proxied anyway). Before saving, check that no record targets the bare `davidandrea.ca` name or edits an existing MX/TXT record there. If the Resend wizard offers to configure Cloudflare automatically, that is acceptable only if its preview lists the same subdomain-only records. +4. Wait for Resend to show the domain as **Verified**. STOP here until it does. + +Sender for step 9: `Hull & Havoc ` (replace `notify` with your subdomain). The digest's validator accepts `Name
` with a name of at most 80 characters and no quotes or angle brackets. + +## 3. API key (credential) + +1. In Resend, go to **API Keys > Create API key**. Permission **Sending access**, restricted to the verified subdomain. Name it something like `hull-and-havoc-worker-digest`. +2. The key is shown once. Keep it only in your password manager until step 10. Never paste it into a file in the repository, `wrangler.toml`, `.dev.vars` that you might commit, a GitHub Actions variable, a command-line argument or a chat. The Worker never logs it, and its error text is redacted. +3. If it is ever exposed, revoke it in Resend and create a new one. Step 11 replaces the Worker copy. + +## 4-8. D1: backup, then apply 0005 (PRODUCTION WRITE in step 7 only) + +Run in a fresh, interactive **PowerShell** window (not CI, not Git Bash), logged in with `npx wrangler login` on account `620de0810a6cf29710d9fedb3a966d6f`. Check out the commit you will release, so the migration file matches what ships. + +### Setup (no production access) + +Edit the value, then run: + + +```powershell +Set-Location 'C:\Users\davej\dev\asteroids-bootdev\phaser-asteroids\server' +$BackupDir = $null # REQUIRED: existing protected directory outside the repository, at most 100 characters, e.g. 'C:\Users\davej\OrbitalRelease\digest' +``` + +Helper definitions (they only define functions and constants): + + +```powershell +$ErrorActionPreference = 'Stop' +$env:WRANGLER_SEND_METRICS = 'false' +$D1 = 'asteroids-leaderboard' +$AccountId = '620de0810a6cf29710d9fedb3a966d6f' +$ProdDbId = 'cf4833f7-5fc9-45ca-a767-750df108f1e9' +$ExpectedWorkerVersion = 'c2aef78f-ec27-4118-bd2c-a13f59b7313b' # active since Stage 2 (2026-11-04); STOP if it differs +$PublicBase = 'https://asteroids-leaderboard.davejandrea.workers.dev' +$WranglerJs = Join-Path $PWD 'node_modules\wrangler\bin\wrangler.js' +$Ledger0004 = '0001_init.sql,0002_time_limit.sql,0003_reports.sql,0004_moderation_workflow.sql' +$Ledger0005 = $Ledger0004 + ',0005_moderation_digest.sql' +$CountsSql = "SELECT (SELECT COUNT(*) FROM scores) AS scores, (SELECT COUNT(*) FROM scores WHERE visibility = 'hidden') AS hidden_scores, (SELECT COUNT(*) FROM runs) AS runs, (SELECT COUNT(*) FROM score_reports) AS reports, (SELECT COUNT(*) FROM moderation_audit) AS audit, (SELECT COUNT(*) FROM d1_migrations) AS migrations" +$ScoresSql = 'SELECT * FROM scores ORDER BY id' +$DigestColumns = 'day,status,attempts,claimed_at,subject,body,expired,provider_id,error,updated_at' + +function Assert-Digest([bool]$Ok, [string]$Message) { if (-not $Ok) { throw "STOP: $Message" } } +function Invoke-Wrangler { + & node $WranglerJs @args + if ($LASTEXITCODE -ne 0) { throw "STOP: wrangler $($args[0..2] -join ' ') exited $LASTEXITCODE" } +} +function Get-WranglerJson { + $out = & node $WranglerJs @args --json + if ($LASTEXITCODE -ne 0) { throw "STOP: wrangler $($args[0..2] -join ' ') exited $LASTEXITCODE" } + ($out -join "`n") | ConvertFrom-Json +} +# Read-only production query: fails if D1 reports any write. One statement, one line (newlines break the Windows argument). +function Invoke-ProdQuery([string]$Sql) { + $r = @(Get-WranglerJson d1 execute $D1 --env production --remote --command $Sql) + Assert-Digest (-not ($r | Where-Object { $_.meta.rows_written -or $_.meta.changed_db })) 'a read-only check reported a write' + Write-Output -NoEnumerate @($r[0].results) +} +function Invoke-LocalQuery([string]$State, [string]$Sql) { + $r = @(Get-WranglerJson d1 execute $D1 --local --persist-to $State --command $Sql) + Write-Output -NoEnumerate @($r[0].results) +} +function ConvertTo-Canonical($Value) { ConvertTo-Json -InputObject $Value -Depth 6 -Compress } +function Save-Record { $Record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $RecordFile -Encoding utf8 } +function Test-Ledger([scriptblock]$Q, [string]$Expected) { ((& $Q 'SELECT name FROM d1_migrations ORDER BY id').name -join ',') -eq $Expected } +function Test-Migration0005([scriptblock]$Q) { + Assert-Digest (Test-Ledger $Q $Ledger0005) 'ledger is not exactly 0001-0005' + $cols = ((& $Q 'PRAGMA table_info(moderation_digests)') | ForEach-Object { $_.name }) -join ',' + Assert-Digest ($cols -eq $DigestColumns) "moderation_digests columns are [$cols]" + $ddl = (& $Q "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'moderation_digests'")[0].sql + Assert-Digest ($ddl -match 'superseded' -and $ddl -match 'WITHOUT ROWID') 'moderation_digests status constraint' + Assert-Digest ((& $Q 'SELECT COUNT(*) AS n FROM moderation_digests')[0].n -eq 0) 'moderation_digests is not empty' + Assert-Digest ((& $Q 'PRAGMA foreign_key_check').Count -eq 0) 'foreign-key errors' +} +function Test-PublicReads { + $health = Invoke-RestMethod -Uri "$PublicBase/api/v1/health" + $all = Invoke-RestMethod -Uri "$PublicBase/api/v1/leaderboard/all-time?limit=1&offset=0" + Assert-Digest ($all.total -ge 1 -and @($all.entries).Count -eq 1) 'public board did not return entries' + [ordered]@{ utc = [DateTime]::UtcNow.ToString('o'); rules = $health.rulesVersion; allTimeTotal = $all.total } +} +$ProdQ = { param($Sql) Invoke-ProdQuery $Sql } +``` + +Session guards. EXPECT: `SETUP OK` and the record path. + + +```powershell +Assert-Digest (-not $env:CI) 'CI is set, so Wrangler would auto-confirm prompts; use a fresh interactive PowerShell' +Assert-Digest (Test-Path -LiteralPath .\wrangler.toml) 'run from phaser-asteroids\server' +Assert-Digest ((& node $WranglerJs --version) -eq '4.151.3') 'Wrangler is not the locked 4.151.3' +Assert-Digest ([bool]$BackupDir -and (Test-Path -LiteralPath $BackupDir -PathType Container)) 'set $BackupDir to an existing protected directory' +$BackupDir = (Resolve-Path -LiteralPath $BackupDir).Path.TrimEnd('\') +$RepoRoot = (Resolve-Path -LiteralPath (git rev-parse --show-toplevel)).Path.TrimEnd('\') +Assert-Digest (-not ($BackupDir + '\').StartsWith($RepoRoot + '\', [StringComparison]::OrdinalIgnoreCase)) '$BackupDir is inside the Git repository' +Assert-Digest ($BackupDir.Length -le 100) '$BackupDir is too long for local D1 copies' +Assert-Digest (-not (git status --porcelain -- migrations)) 'migrations/ differs from the checked-out commit' +$Files = (Get-ChildItem -LiteralPath migrations -Filter '*.sql' | Sort-Object Name).Name -join ',' +Assert-Digest ($Files -eq $Ledger0005) "migrations/ holds [$Files]; expected exactly 0001-0005" +$Stamp = [DateTime]::UtcNow.ToString('yyyyMMdd-HHmmss') +$RecordFile = Join-Path $BackupDir "digest-record-$Stamp.json" +$ExportFile = Join-Path $BackupDir "prod-d1-pre0005-$Stamp.sql" +$VerifyState = Join-Path $BackupDir "verify-$Stamp" +$DressState = Join-Path $BackupDir "dress-$Stamp" +$Record = [ordered]@{ stage = 'digest-0005'; startedUtc = [DateTime]::UtcNow.ToString('o'); gitHead = (git rev-parse HEAD); sha256_0005 = (Get-FileHash -LiteralPath migrations\0005_moderation_digest.sql).Hash } +Save-Record +"SETUP OK. Record: $RecordFile" +``` + +### Step 4: confirm account, database, Worker and ledger (read-only) + +EXPECT: `STEP 4 OK`. STOP on another account, database or active version, or on any ledger other than exactly 0001-0004. Do not use `d1 migrations list` here; it writes (`CREATE TABLE IF NOT EXISTS`). + + +```powershell +$Who = Get-WranglerJson whoami +Assert-Digest ($Who.loggedIn -and (@($Who.accounts.id) -contains $AccountId)) "not logged in to account $AccountId" +$Info = Get-WranglerJson d1 info $D1 --env production +Assert-Digest ($Info.uuid -eq $ProdDbId) "--env production resolves to database $($Info.uuid)" +$Deploy = Get-WranglerJson deployments status --env production +Assert-Digest (@($Deploy.versions).Count -eq 1 -and $Deploy.versions[0].version_id -eq $ExpectedWorkerVersion -and $Deploy.versions[0].percentage -eq 100) 'active Worker is not 100% the expected version' +Assert-Digest (Test-Ledger $ProdQ $Ledger0004) 'production ledger is not exactly 0001-0004' +Assert-Digest ((Invoke-ProdQuery "SELECT name FROM sqlite_master WHERE name = 'moderation_digests'").Count -eq 0) 'moderation_digests exists without a ledger entry' +Assert-Digest ((Invoke-ProdQuery 'PRAGMA foreign_key_check').Count -eq 0) 'foreign-key errors before migration' +$Record.before = [ordered]@{ utc = [DateTime]::UtcNow.ToString('o'); workerVersion = $ExpectedWorkerVersion; counts = (Invoke-ProdQuery $CountsSql)[0]; publicReads = Test-PublicReads } +Save-Record +$Record.before.counts | Format-List +'STEP 4 OK' +``` + +### Step 5: bookmark and export (read-only) + +Records a Time Travel restore point, then exports production to a private file outside Git (D1 may briefly pause other queries during the export). EXPECT: `STEP 5 OK`, a bookmark and the export's SHA-256. Never commit, upload or attach the export. + + +```powershell +$Bookmark = Get-WranglerJson d1 time-travel info $D1 --env production +Assert-Digest ([bool]$Bookmark.bookmark) 'Time Travel returned no bookmark' +$Record.restore = [ordered]@{ capturedUtc = [DateTime]::UtcNow.ToString('o'); before0005Bookmark = $Bookmark.bookmark } +Save-Record +"Restore point before 0005: $($Bookmark.bookmark)" +Assert-Digest (-not (Test-Path -LiteralPath $ExportFile)) 'export file already exists' +Invoke-Wrangler d1 export $D1 --env production --remote --output $ExportFile | Out-Null # Out-Null hides the one-hour signed URL +$ExportSql = [IO.File]::ReadAllText((Resolve-Path -LiteralPath $ExportFile)) +foreach ($t in 'scores', 'runs', 'score_reports', 'moderation_audit', 'd1_migrations') { Assert-Digest ($ExportSql -match "CREATE TABLE[^(]*\b$t\b") "export has no CREATE TABLE for $t" } +Assert-Digest ($ExportSql -notmatch 'CREATE TABLE[^(]*\bmoderation_digests\b') 'export already contains moderation_digests' +$Record.export = [ordered]@{ file = $ExportFile; bytes = (Get-Item -LiteralPath $ExportFile).Length; sha256 = (Get-FileHash -LiteralPath $ExportFile).Hash } +Save-Record +$Record.export | Format-List +'STEP 5 OK' +``` + +### Step 6: prove the export restores, and dress-rehearse 0005 on it (local only) + +Imports the export into two isolated local databases inside `$BackupDir`, then applies 0005 to the second. Wrangler asks to confirm applying 1 migration **locally**: answer `y`. EXPECT: `STEP 6 OK`. On a count mismatch (a score was submitted after the export), delete this attempt's export and copies and restart at step 5. On any other failure, STOP. + + +```powershell +Invoke-Wrangler d1 execute $D1 --local --persist-to $VerifyState --file $ExportFile | Out-Null +$VerifyQ = { param($Sql) Invoke-LocalQuery $VerifyState $Sql } +Assert-Digest (Test-Ledger $VerifyQ $Ledger0004) 'imported ledger is not 0001-0004' +Assert-Digest ((ConvertTo-Canonical (Invoke-LocalQuery $VerifyState $CountsSql)[0]) -ceq (ConvertTo-Canonical (Invoke-ProdQuery $CountsSql)[0])) 'imported counts differ from production now (restart at step 5)' +$BackupScores = ConvertTo-Canonical (Invoke-LocalQuery $VerifyState $ScoresSql) +Assert-Digest ($BackupScores -ceq (ConvertTo-Canonical (Invoke-ProdQuery $ScoresSql))) 'imported scores differ from production' +Invoke-Wrangler d1 execute $D1 --local --persist-to $DressState --file $ExportFile | Out-Null +Invoke-Wrangler d1 migrations apply $D1 --local --persist-to $DressState +$DressQ = { param($Sql) Invoke-LocalQuery $DressState $Sql } +Test-Migration0005 $DressQ +Assert-Digest ((ConvertTo-Canonical (Invoke-LocalQuery $DressState $ScoresSql)) -ceq $BackupScores) 'dress rehearsal changed score rows' +$Record.backupVerified = [ordered]@{ utc = [DateTime]::UtcNow.ToString('o'); dressRehearsal0005 = 'ok' } +Save-Record +'STEP 6 OK' +``` + +### Step 7: apply 0005 (PRODUCTION WRITE) + +Records a fresh restore point, then applies. With the ledger at 0001-0004 and `migrations/` holding exactly 0001-0005 (both checked above), the only pending file is 0005. When Wrangler asks *About to apply 1 migration(s)*, answer `y` **only if its table lists `0005_moderation_digest.sql` alone**. Otherwise answer `n` (nothing is applied) and STOP. + + +```powershell +$Pre = Get-WranglerJson d1 time-travel info $D1 --env production +Assert-Digest ([bool]$Pre.bookmark) 'no pre-migration bookmark' +$Record.restore.pre0005Utc = [DateTime]::UtcNow.ToString('o'); $Record.restore.pre0005Bookmark = $Pre.bookmark +Save-Record +"Restore point immediately before 0005: $($Pre.bookmark)" +Invoke-Wrangler d1 migrations apply $D1 --env production --remote +``` + +### Step 8: verify 0005 and data preservation (read-only) + +EXPECT: `STEP 8 OK`. Scores submitted since the export are allowed; every backed-up score row must be unchanged. + + +```powershell +Test-Migration0005 $ProdQ +$Now = @{}; foreach ($row in (Invoke-ProdQuery $ScoresSql)) { $Now[$row.id] = ConvertTo-Canonical $row } +$Changed = @((Invoke-LocalQuery $VerifyState $ScoresSql) | Where-Object { $Now[$_.id] -cne (ConvertTo-Canonical $_) }).Count +Assert-Digest ($Changed -eq 0) "$Changed backed-up score rows missing or changed" +$Deploy = Get-WranglerJson deployments status --env production +Assert-Digest ($Deploy.versions[0].version_id -eq $ExpectedWorkerVersion) 'active Worker changed during the migration' +$Post = Get-WranglerJson d1 time-travel info $D1 --env production +$Record.after0005 = [ordered]@{ utc = [DateTime]::UtcNow.ToString('o'); counts = (Invoke-ProdQuery $CountsSql)[0]; publicReads = Test-PublicReads; after0005Bookmark = $Post.bookmark } +Save-Record +"STEP 8 OK. Record: $RecordFile" +``` + +**If a D1 step stops:** steps 4-6 change nothing in production; fix the cause and restart from setup. If step 7 fails, Wrangler rolls back the failing file and does not record it (documented behavior; rehearsed locally only for 0004), so rerun step 4's ledger check read-only and STOP. If step 8 fails after a recorded 0005, do not drop or edit anything: the table is additive and the current Worker ignores it. Investigate read-only. A Time Travel restore would discard every score submitted after the bookmark, so do not use it for a digest problem. + +## 9. Configure the sender and release (needs policy approval) + +1. **Done 2026-11-12 on `feature/privacy-play-ux`.** On the release branch, in `phaser-asteroids/server/wrangler.toml` under `[env.production.vars]`, replace the commented line with your verified sender: + `MODERATION_DIGEST_FROM = "Hull & Havoc "` + `MODERATION_DIGEST_TO` (`privacy@davidandrea.ca`) and `MODERATION_DASHBOARD_URL` are already set. Commit. +2. Run the local verification listed in [play-release-validation.md](play-release-validation.md#release-candidate-hull--havoc-2026-11-12) on that commit, including `npx wrangler deploy --env production --dry-run` from `phaser-asteroids/server`. +3. With policy approval, merge to `main` by pull request and push (the only step that triggers CI). CI validates, deploys the Worker, checks `/api/v1/health` and publishes Pages. +4. Verify (read-only): `npx wrangler deployments status --env production` shows one new version at 100%; the public board and `/admin` load; `https://djblackett.github.io/asteroids-bootdev/privacy/` loads in a private window. The digest is still disabled (no key), so `SELECT COUNT(*) FROM moderation_digests` stays 0 after the next cron. + +## 10. Controlled delivery test (LIVE EMAIL: exactly one) + +Proves the key, sender and mailbox, independently of the Worker (the Worker's request is covered by `npm run test:worker` against a local mock provider). It sends one fixed message with no player data and touches no database. + +**Timing:** run it after 07:17 UTC, or before setting the secret in step 11. Its idempotency key has its own prefix, so it cannot collide with a daily digest key in any case. + +```powershell +Set-Location 'C:\Users\davej\dev\asteroids-bootdev\phaser-asteroids\server' +$k = Read-Host 'Resend API key (input hidden)' -AsSecureString +$env:RESEND_API_KEY = [Net.NetworkCredential]::new('', $k).Password +$env:MODERATION_DIGEST_FROM = 'Hull & Havoc ' # your verified sender +$env:MODERATION_DIGEST_TO = 'privacy@davidandrea.ca' +node scripts/digest-delivery-test.mjs # dry run: prints the request, sends nothing +node scripts/digest-delivery-test.mjs --confirm-one-live-email # sends one email +Remove-Item Env:RESEND_API_KEY, Env:MODERATION_DIGEST_FROM, Env:MODERATION_DIGEST_TO; Remove-Variable k +``` + +EXPECT `{"status":"sent","id":"..."}` and the message in the mailbox (check spam; mark it *not spam*). On `timeout`, check the Resend dashboard's email log before retrying, because the message may have been accepted. On `http_403`/`http_422`, the domain or sender is not verified: fix it in step 2 and retry. + +## 11. Enable the digest (SECRET) + +```powershell +Set-Location 'C:\Users\davej\dev\asteroids-bootdev\phaser-asteroids\server' +npx wrangler secret put RESEND_API_KEY --env production # paste at the hidden prompt; never as an argument +npx wrangler secret list --env production # names only: ADMIN_TOKEN, IP_HASH_SALT, RESEND_API_KEY +``` + +This creates a new Worker version with the same code. Do not add `RESEND_API_KEY` to `secrets.required` or to GitHub. The next 07:17 UTC cron sends a digest only if the **Needs review** queue is not empty or open reports expired. Do not create production reports to trigger one. + +## 12. Post-activation verification (read-only) + +After the next 07:17 UTC cron: + +1. **Ledger** (the reliable record, because Workers Logs are not enabled for this Worker): + `npx wrangler d1 execute asteroids-leaderboard --env production --remote --command "SELECT day, status, attempts, expired, error FROM moderation_digests ORDER BY day DESC LIMIT 5"` + - No rows: nothing needed review (correct, no email). + - `sent`: delivered to Resend; confirm the mailbox. + - `failed` with `http_401`/`http_403`/`http_422`: key or sender problem; it retries once a day. Fix the key or domain. + - `failed` with `timeout`/`http_5xx`: provider trouble. The next day's digest carries any expiry counts and marks the row `superseded`. +2. **Invocation health:** Cloudflare dashboard **Workers > asteroids-leaderboard > Metrics** shows the daily invocation with 0 errors. A digest problem never fails the cron, so errors there mean cleanup failed. +3. **Live log, if needed:** run `npx wrangler tail --env production --format json` around 07:17 UTC and look for `{"evt":"moderation_digest","status":...}`. It shows status and provider error names only, never the key. +4. **Duplicates:** at most one email per UTC day. More than one with the same date is a defect; disable it (below) and report it. + +## Rollback and recovery + +| Problem | Action | Effect | +| --- | --- | --- | +| Unwanted, wrong or duplicate emails | `npx wrangler secret delete RESEND_API_KEY --env production` | Digest `disabled` from the next cron; new Worker version, same code. Cleanup unaffected. | +| Key exposed | Revoke it in Resend, create a new one, repeat step 11 | Old key stops working immediately. | +| Worker regression unrelated to the digest | `npx wrangler rollback --env production` (e.g. `c2aef78f-ec27-4118-bd2c-a13f59b7313b`) | That version ignores `moderation_digests`; schema-compatible. Pages is not rolled back by this. | +| Sender domain problems | Remove the subdomain records in Cloudflare DNS | No effect on `davidandrea.ca` inbound mail. | +| 0005 itself | Leave the table. It is additive and holds counts only; ledger rows are pruned after 30 days. | Dropping it is unnecessary. If ever needed, that is a separately reviewed migration, not a manual edit. | + +D1 Time Travel restore is **not** a digest recovery tool: it rewinds the whole database and discards scores submitted after the bookmark. + +## Rehearsal evidence + +See [play-release-validation.md](play-release-validation.md#release-candidate-hull--havoc-2026-11-12). diff --git a/docs/leaderboard-backend.md b/docs/leaderboard-backend.md index fa1d4f3..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 @@ -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 da29d8b..5cd6791 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 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. ## Assessment of the previous implementation @@ -19,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 @@ -52,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. @@ -64,30 +66,125 @@ 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. 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. -## Google Play UGC review +## Daily moderation digest + +Implemented 2026-11-12 on `feature/moderation-digest`, integrated (with the expiry carry-forward below) on `release/hull-and-havoc-rc`; **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. + +**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: + +- Empty queue and nothing expired: no email. +- Otherwise one email, subject `Hull & Havoc — 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 `Hull & Havoc — 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: hull-and-havoc-moderation-digest-YYYY-MM-DD`. Resend keeps keys for 24 hours, which covers every attempt of one UTC day, so a timeout whose request the provider actually accepted is deduplicated rather than sent twice. +- *Not exactly-once.* The D1 row is the reliable local guard; the provider key is the second layer. If every attempt of a day ends ambiguously (timeout, Worker killed mid-send), whether that day's email arrived is unknown. The digest never resends that day under a new key. +- *Outages across days.* An undelivered day (failed, or `sending` past its 10-minute lease) is not retried after its day ends. The next day's digest is composed from the live queue, and it **carries the undelivered days' expired-report counts** (column `expired`), because those reports are already deleted. The earlier rows become `superseded`, so nothing stays pending. An expiry notice is therefore repeated rather than lost when an earlier email did arrive after all. +- *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 the provider key prevents a second delivery within a day. +- *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. In the unusual case of a second invocation on a day whose first cleanup had failed, reports deleted after that day's email was sent are logged as `expiredNotAnnounced` rather than emailed. + +**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, `Hull & Havoc ` (set in `[env.production.vars]` 2026-11-12; `notify.davidandrea.ca` is verified in Resend). | +| `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:** follow the ordered [digest activation runbook](digest-activation-runbook.md) (D1 backup, staged 0005, Resend subdomain DNS, sending-only key, Worker configuration, authorized delivery test, verification, rollback). Every production step there needs separate authorization. + +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. -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. +**Not covered by tests:** real Resend delivery and its idempotency behaviour, 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. Regression tests pin the cleanup-then-digest ordering (a report expiring in the same run's cleanup, empty remaining queue) and the cross-day carry-forward. -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. +## Report retention and review policy -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. +**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 on the expiry day no longer loses the notice: the count is carried to the next day's digest. It is lost only if the digest cannot claim a ledger row at all for 30 days (ledger rows are pruned after 30 days), or in the `expiredNotAnnounced` edge case above. Workers Logs are not enabled for this Worker, so the cron log is visible only live (`wrangler tail`). +- 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 | **Explicit (2026-11-12, `feature/privacy-play-ux`):** the only submit control is **ACCEPT RULES & SUBMIT** (Enter on a keyboard is its labelled shortcut; the phone keyboard's Done key no longer submits), with a one-line rules summary and a LEADERBOARD RULES button beside it. Asked on every submission; client-only, no stored consent 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 | Done (see above) | +| | 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 the explicit, per-submission ACCEPT RULES & SUBMIT control is sufficient without a stored record of acceptance | +| | 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 +**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-data-inventory.md b/docs/play-data-inventory.md index 5ac80aa..beff8d2 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 @@ -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/play-release-validation.md b/docs/play-release-validation.md index 950aa74..dfaa3c3 100644 --- a/docs/play-release-validation.md +++ b/docs/play-release-validation.md @@ -2,6 +2,68 @@ 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. +## Release candidate: Hull & Havoc (2026-11-12) + +Branch `release/hull-and-havoc-rc` (local only; nothing pushed, deployed, migrated or emailed). Mocked/loopback email only. + +| Check | Result | +| --- | --- | +| Vitest (full) | **71 files / 1,705 tests passed** (incl. digest 25, delivery-test script 3, branding 3, privacy page 5, Android release guards) | +| Typecheck | frontend `tsc --noEmit` and server `tsc -p server/tsconfig.json`: pass | +| Production build | `npm run build`: pass; `dist/privacy/index.html` emitted; no Resend/digest strings in the client bundle | +| Android build guards | `node --test scripts/build-android.test.mjs`: 8/8 | +| Frozen rules | `rules-guard.mjs main`: 0 changes under `server/rules`; guard tests 4/4. No diff under `src/core`, `src/replay`, `src/game`, `src/scenes` vs `main` | +| Real Worker + D1 (workerd) | `server/scripts/worker-e2e.mjs`: **39/39**, incl. one digest for two same-day crons, key `hull-and-havoc-moderation-digest-YYYY-MM-DD` | +| D1 migration rehearsal | `test:release:migrations`: **43/43**, incl. additive 0005 after 0004 and the historical Worker on the 0005 schema | +| Runbook D1 blocks | [digest-activation-runbook.md](digest-activation-runbook.md) setup and steps 4-8 run verbatim against a local stand-in (only `--env production --remote` rewritten; account calls stubbed; invalid API token); all OK; step 4 correctly STOPs once 0005 is applied | +| Moderation dashboard (Chromium) | `test:moderation:admin`: **28/28** | +| Menus incl. privacy pages | `scripts/menu.mjs`: **127/127**; `HULL & HAVOC` title fits at every tested size | +| GitHub Pages subpath | `scripts/pages-check.mjs`: **35/35**, incl. `/asteroids-bootdev/privacy/` (200, heading, contact, favicon, no off-site requests, back link, no sideways scroll at 360 px) | +| Worker production dry-run | `wrangler deploy --env production --dry-run`: 151.57 KiB; bindings `DB`, `ALLOWED_ORIGINS`, `MODERATION_DIGEST_TO`, `MODERATION_DASHBOARD_URL`; no sender or key (digest stays disabled) | +| Android unsigned release | `bundleRelease assembleRelease lintRelease -PallowUnsignedRelease=true`: success. Inspector `-Unsigned`: PASS (no `.so`, no server verifier, package/SDK/debuggable/permissions), WARN draft privacy text (expected). `aapt2`: package `ca.davidandrea.spacearcade` 1.0 (1), label **Hull & Havoc**. APK `ED631C99…EF8F14`, AAB `87A2C243…EF272` | +| Sideload copy (local debug key) | `hull-and-havoc-1.0-sideload-debugkey.apk`, `08348538…C35E24`, v2/v3 verified, 16 KB aligned. Not uploadable | + +**Not run:** gameplay browser suites (`ranked-ui`, `ranked`, `touch`, `keyboard`, `combat`, `coop`, `gamepad`, `replay:browser`), because no gameplay code changed. No signed build, no device install, no real Resend delivery, no production read or write. + +### Google Play: focused check of this candidate + +Established by inspection or test: +- Package `ca.davidandrea.spacearcade`, version 1.0 (1), rules 1.2.0 frozen; launcher label Hull & Havoc; permissions INTERNET and VIBRATE only (the digest added none). +- Privacy URL `https://djblackett.github.io/asteroids-bootdev/privacy/` is used consistently in the page, the offline screens and the Play guide. It is **not live** until a release to `main`. +- Draft gate: the policy was approved 2026-11-12 and the offline screen no longer carries `DRAFT PRIVACY POLICY - REVIEW PENDING`. The signed-mode inspector still lists both markers and refuses any build that reintroduces one. Upload-key procedure (`ASTEROIDS_UPLOAD_*`, signed-mode inspector) unchanged. +- Reporting, blocking and the `/admin` workflow pass their suites. Gameplay requests do not depend on email. + +Unresolved interpretation (not established; see [UGC readiness](leaderboard-moderation.md#google-play-ugc-readiness-rechecked-2026-11-12)): +- **Rules acceptance:** submit-as-acceptance with the rules one tap away. Play asks users to accept terms before creating UGC; whether an implicit "by submitting" suffices is a reviewer judgment. The conservative option is an explicit "Accept rules & submit" label (client-only change, not made here). +- **Blocking without accounts:** name-based device-local blocking; names are shared and changeable. +- **Ongoing moderation:** depends on activating the digest and on your actual response time, not on code. +- **Data safety:** the inventory supports the rows (name, app activity, IP-derived identifier, deletion by email). Internal-only testing is exempt; answers must be final before closed/open/production tracks. + +## 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). + ## 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. @@ -100,6 +162,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..09c74d2 100644 --- a/docs/privacy-policy-draft.md +++ b/docs/privacy-policy-draft.md @@ -1,12 +1,14 @@ -# 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. The draft describes the changes in this checkout; reporting and erasure are not yet deployed. +**Not approved for publication or distribution.** Provider retention and mailbox handling require review. The final name is Hull & Havoc. The public contact is confirmed (below); filling it in does not approve this text. Package: `ca.davidandrea.spacearcade`. Proposed effective date: set on approval. -Operator: **David Andrea** (confirmed 2026-11-04). Privacy, security and removal contact: **[PUBLIC EMAIL PENDING]**. +**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). -**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. +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`). -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. +**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. + +Hull & Havoc is a game without user accounts, advertising or analytics SDKs. You can play Practice without uploading gameplay or submitting a score. Menus may contact the online service to retrieve public scores and refresh scores previously saved on your device. Ranked play requests a server-issued challenge. If you choose to submit your result, the game sends your nickname, gameplay replay (changes in movement, aiming and action controls), game/rules versions, configuration, timing, claimed result and control category. We use this to independently verify scores, operate the leaderboard and prevent cheating or abuse. Full replay submissions are processed in memory; we retain a hash of the submission, verified score and associated run metadata rather than the full replay. @@ -14,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. Once activated (not yet deployed), 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. @@ -28,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. +Before submitting, you choose **Accept rules & submit**, which accepts public display and these rules; you can skip instead. 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. The operator reviews reports and flagged scores when they need attention; the leaderboard is not monitored continuously, and a report can expire after 30 days before review. 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. +**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. +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. It shows the proposed public URL; the link only resolves after the page is released. 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..e1d75a2 --- /dev/null +++ b/docs/privacy-policy-publication.md @@ -0,0 +1,124 @@ +# Hull & Havoc privacy policy: publication record + +Prepared 2026-11-12 on branch `feature/privacy-policy-page`; integrated into `release/hull-and-havoc-rc` the same day; wording and in-game access revised on `feature/privacy-play-ux` (see [Review remediation](#review-remediation-2026-11-12)). **Approved by the owner 2026-11-12; not yet published.** The approval commit sets the date and removes the in-game DRAFT line (see [Approval record](#approval-record-2026-11-12)). The page goes public when that commit reaches `main`. + +- 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` (approved copy; the DRAFT line is replaced by a plain `PRIVACY POLICY` heading. The inspector's marker list is kept, so a reintroduced draft is still refused; it 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 on the release candidate but 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 still says "Last updated 12 November 2026" (the preparation date; source edits do not change it). Follow the [date procedure](#approval-and-publication-date-procedure). +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 + +Merged into `release/hull-and-havoc-rc` after the digest commits, without conflicts. The offline screen's retention line about provider logs was aligned with the page ("Cloudflare logs and backups follow their own retention periods"); the DRAFT marker is unchanged. + +## Additional wording for your review (release-candidate check, 2026-11-12) + +7. ~~Review commitment~~: **resolved in wording** (A below). Still yours to decide: whether to publish a review target (for example "within a few days of a report"); none is stated. +8. ~~"Kept indefinitely by default"~~: **purpose added** (D below). Still yours: whether EU/UK users need more (see item 5). +9. ~~Rules acceptance~~: **explicit control implemented** (below). Still yours: whether it is enough for Play without a stored acceptance record. +10. **Operator identity.** The page names "David Andrea" as operator and gives no postal address. Play does not require an address in the policy, but Play's developer account may display one; keep the names consistent. + +## Review remediation (2026-11-12) + +Branch `feature/privacy-play-ux` from `release/hull-and-havoc-rc` (`d06ad4c`). Client-only; no Worker, D1, migration, digest, gameplay, scoring, replay or Android-identity change. The policy is still **not approved** and the DRAFT gate is unchanged. + +### Exact wording changes + +| | Public page (`public/privacy/index.html`) | Offline screens (`privacy.ts`) | +| --- | --- | --- | +| A. Moderation | "Reports are private and are reviewed by the operator." → "Reports are private and go only to the operator." plus a new paragraph: "A person (the operator) reviews reports and flagged scores when they need attention. The leaderboard is not monitored continuously or in real time, so there can be a delay before anything is reviewed, and a report can reach its 30-day retention limit before it has been looked at. Sending a report does not automatically hide or remove anything; only the operator can change an entry." Screening sentence now says names are screened "before a score is accepted". | Rules page: "Reports go privately to the operator for review; they do not auto-hide scores." → "Names are screened automatically. Reports are private and never auto-hide; / the operator reviews them when needed, not continuously or instantly." The two blocking lines were merged into "Block hides that name on this device only; it cannot follow name changes." | +| B. Practice | Summary: "without uploading anything" → "without uploading gameplay or submitting a score". The *Playing without going online* paragraph (menus may still contact the service) is unchanged. | "Practice does not upload gameplay." → "Practice uploads no gameplay and submits no score. Menus may fetch public scores." | +| C. Requests | Heading "Removal requests, appeals and questions" → "Your requests: removal, access, correction and questions", with a list: removal; what information we hold / a copy; correction where inaccurate and applicable; appeal; how long information is kept or how it is used. New limits: "Because there are no accounts and nicknames are not unique, we can only find entries from the details you give us, and we may not be able to confirm that an entry is yours. We may ask for more context before acting, so that we do not disclose, change or remove someone else's entry, and we may be unable to complete a request if we cannot reasonably identify the information." | "Email to ask for removal, access, correction, an appeal, or how data is used:" and "With no accounts and shared nicknames we may not be able to tell which / entries are yours, so we may ask for context or be unable to act." | +| D. Retention | Scores row adds: "We keep verified scores and the run records linked to them to preserve the leaderboard's history and integrity, and so that results can be checked again later." No retention period changed; no claim that every field is needed forever. | "…no automatic expiry, even if hidden, / to keep the leaderboard's history and let results be checked later." | +| Rules | "By submitting a score you accept…" → "Before a score is submitted, the game shows a summary of these rules with a link to the full text, and you submit by choosing **Accept rules & submit**. Doing so means you accept public display of the entry and these rules. You can always skip submitting instead." | "Before each submission you choose ACCEPT RULES & SUBMIT: that accepts / these rules and the public display of your nickname and score." | + +Unchanged (pinned by `tests/privacyPage.test.ts`): Cloudflare infrastructure, salted IP hash, in-memory replay verification, report contents and 30-day retention, device-local blocking, provider backups/logs, public fields, operator and contact, name, package ID, date. The review draft `privacy-policy-draft.md` received the matching rules/review/Practice sentences and now marks the digest as not yet deployed. + +### Full policy in the game + +- Every offline privacy page has **VIEW FULL POLICY** between BACK and NEXT. It opens `PRIVACY_POLICY_URL` (`https://djblackett.github.io/asteroids-bootdev/privacy/`, defined once in `privacy.ts`; a test checks every copy of the address in the code and these docs). The summary pages still work without a network. +- Browser: `window.open(url, '_blank')`, then the new tab's `opener` is cleared. If the browser blocks it, the page says so and shows the address. +- Android app: a plain navigation. Capacitor's WebView hands any URL outside the app's own host to the system browser (Android `ACTION_VIEW`) and cancels the load, so the game page stays (verified in `@capacitor/android`'s `Bridge.launchIntent`). No plugin, dependency, permission or native change. Capacitor cannot report "no browser installed", so the page always shows the address and "needs internet" after the tap. +- Code: `src/platform/openExternal.ts` (https only), `src/ui/menu/pages/privacy.ts`. + +### Rules acceptance + +- The result page's submit button is now **ACCEPT RULES & SUBMIT** (keyboard hint ENTER), beside SKIP. Beneath it: "SUBMITTING MAKES YOUR NICKNAME AND SCORE PUBLIC." and a one-line rules summary ("RULES: NO HATEFUL, SEXUAL, THREATENING OR HARASSING NAMES, IMPERSONATION OR PERSONAL INFO."). **LEADERBOARD RULES** opens the full rules page directly; BACK returns with the typed name kept. **PRIVACY** opens page 1. +- On touch screens the phone keyboard's Done key now only closes the keyboard; it no longer submits. On a keyboard, Enter remains the labelled shortcut of the accept button. Controllers press the same button. +- Asked on every submission, so nothing is stored: no consent table, no local flag, no API change. Practice and Skip need no acceptance. +- Code: `src/ui/menu/pages/rankedResult.ts`, one callback in `src/scenes/GameScene.ts`. + +### Tests (this branch) + +All local; the policy site was stubbed in the browser tests, and no production data or real email was involved. + +| Check | Result | +| --- | --- | +| Focused unit tests (`privacyPage`, `openExternal`, `androidRelease`, `branding`) | 31/31 (privacy page 13: wording A-D, rules, unchanged facts, page length, one canonical URL) | +| Full Vitest | 72 files / 1,718 tests passed | +| Frontend typecheck + production build | pass | +| Android build guards | 8/8 | +| Menus (`scripts/menu.mjs`) | 139/139, incl. 12 new: VIEW FULL POLICY on all 4 pages; mouse, Enter, phone tap and controller (D-pad + A) open the canonical URL in a new tab with no opener link; blocked tab shows the address; layout review of every privacy page at 5 phone + 5 desktop sizes | +| Ranked result UI (`scripts/ranked-ui.mjs`, local Worker + D1) | 106/106, incl. 7 new: ACCEPT RULES & SUBMIT with ENTER hint, rules summary, LEADERBOARD RULES → rules page → BACK keeps the name with nothing sent, phone Done key sends nothing, touch submission still verified; 44 CSS px and overlap checks at phone sizes | +| GitHub Pages subpath (`scripts/pages-check.mjs`) | 35/35 | +| Client bundle | no Resend/digest/admin-secret strings; the DRAFT marker is present, so the signed-release inspector still refuses it | + +**Untested:** the Android hand-off on a real device or emulator (verified from the Capacitor source and a unit test only), a phone with no browser installed, real screen readers, and a physical controller (simulated `navigator.getGamepads`). + +### Approval and publication-date procedure + +1. Do not change the "Last updated" date while the text is under review. It records when the text was prepared. +2. On the day you approve, in **one commit**: set both the visible date and `