Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
metrics to quantitatively produce better games. which games are played the mo… #46
Check · Review · Land · Live done — Landed and live in production.
The app now counts plays per game and ranks the games on a new /stats/ page, most played first. bun test passes (197 tests). I did not run tsc (the repo has no tsconfig) or start the app by hand.
shipped production is serving it deploy ab54f53
1 earlier comment · 1 event
The app now counts plays per game and ranks the games on a new /stats/ page, most played first. bun test passes (197 tests). I did not run tsc (the repo has no tsconfig) or start the app by hand.
The issue body was empty and its title was cut off after "which games are played the mo…". I read it as "which games are played the most", so I built play counts. Say if you meant something else.
What changed
- Reporting: each game page sends three anonymous events to
POST /api/play. They are the page opening, the first tap or key press (counted as a play), and the seconds the page stayed visible after that. - Where it lives: the code is in
shell.js, so every game is covered without editing any of them. - Validation: the endpoint accepts only same-origin requests, known game ids and known events. Seconds must be a whole number from 1 to 3600, and the body is capped at 256 bytes.
- Storage:
stats.mjskeeps only totals per game, with no ids or cookies. It writesplays.jsonunderFORGE_APP_DATA, or keeps counts in memory if that is unset. - Reading it:
- /stats/ shows plays, opens, play rate (plays per open) and average seconds per play. It runs no script, sets a strict Content-Security-Policy, and is linked from the home footer.
- /api/stats returns the same rows as JSON.
- The README has a new Plays section.
- Tests:
stats.test.mjs,serve.test.mjsandshell.test.mjscover counting, persistence, escaping, origin refusal, bad input and the client sending its events.
What I chose not to do
- Finished rounds: I don't count them yet, because every game ends in its own way and each would need a hook.
- Per-day counts: I kept only totals.
- SQLite: I used plain JSON instead of
bun:sqlite, becauseserve.mjsis documented to run on Node too and totals don't need a database. - Security headers on game pages: I added no Content-Security-Policy to them, since I didn't want to risk breaking the existing games.
To try it: run bun serve.mjs, open a game and tap, then visit /stats/.
🤖 Generated with Claude Code
The shape is right: one small stats.mjs, totals only, no cookies, a script-free /stats/ page with a strict CSP, linked from the home footer. On the preview, /stats/, /api/stats and the 403 for a foreign Origin all work. There is no tty in forge.json, so the terminal door does not apply here.
Fix first: the numbers can be faked by anyone with curl, and they are meant to decide which games to build. The Origin check stops browser CSRF, but Origin is a header the client writes. On the preview I sent curl -X POST -H 'origin: <preview>' -d '{"game":"balote","event":"play"}' five times. All five returned 204, and /api/stats now shows balote with 1 open, 5 plays and a play rate of 100%, because the clamp hides the impossible ratio. A loop can push any game to #1 in seconds. Please:
- Rate-limit
POST /api/playwith a key taken fromreq.socket.remoteAddress(never a client header) and a fixed-size bucket map, plus a global ceiling of accepted events per game per minute so a proxy that shares one address cannot flood it either. Answer 429 when the limit is hit, and add a test for it. - Keep the counts consistent in
record: refuse aplaywhen it would makeplay > open, and refusetimewhen it would makeseconds > play * 3600. Then a forged stream cannot produce a ratio a real one never could, and you can drop theMath.min(1, …)that hides the problem today. Test both refusals instats.test.mjs.
Other changes, all needed this round:
- The body cap counts decoded characters, not bytes read (
raw += chunk; raw.length > 256). Countchunk.lengthon the Buffers, collect them, and decode once at the end. - The client's
timeevent has no test.laponvisibilitychange/pagehide, the resume after the page is visible again, the 3600 s clamp and the rule against sending under 1 s could all break andshell.test.mjswould stay green. Add a test that driveslisteners.visibilitychangewithdocument.hiddentoggled and a stubbedDate.now, and asserts the{event:'time', seconds}that is sent. serve.mjstakes the countable ids and titles fromshell.jswith a regex. If a futureGAMESentry is written in a different shape, it is silently left uncounted and every POST for it gets a 400. Add a serve test asserting that/api/statslists exactly the idsPixelPlaysexposes, asserve.test.mjsalready does for theindex.htmlfallback list. Without it, the next game added cannot be tracked and nothing fails.timer ??= setTimeout(flush, 1000).unref?.() ?? timeris hard to read and depends onunref()returning the timer. Write it as two plain statements. Also flush onSIGTERMso a redeploy does not drop the last second of counts.- In the README Plays section, say what the limits are (rate limit, consistency rules) rather than only "same-origin only", which reads as stronger protection than an Origin check gives.
All seven points are addressed and pushed. bun test passes (205 tests).
- Rate limit:
limits.mjsis a small fixed-window limiter with a bounded key table.POST /api/playallows 60 events a minute perreq.socket.remoteAddressand 600 a minute per game, and answers 429 withretry-afterwhen either is hit. A full key table refuses new keys until windows expire.
- Tests: limits.test.mjs covers the limiter. serve.test.mjs has an HTTP test that a fast client gets 429.
- Not tested: there is no test of the per-game ceiling through HTTP, because the per-address limit trips first from a single test client. It is only unit-tested in the limiter.
- Consistent counts:
recordnow refuses aplaythat would makeplay > open. It also refusestimethat would makeseconds > play * 3600. I dropped theMath.min(1, …).stats.test.mjstests both refusals. - Body cap: the 256 limit now counts Buffer bytes. The body is collected and decoded once at the end, and a test with multi-byte characters gets 413.
- Client time events:
shell.test.mjsnow drivesvisibilitychangewithdocument.hiddentoggled and a stubbedDate.now. It asserts:
- nothing is sent before a play;
- the first hide sends 12 s;
- a repeated hide sends nothing more;
- the resume works;
- under 1 s is skipped;
- the clamp sends 3600 s;
- pagehide sends the remainder.
- Id parity: a
serve.test.mjstest asserts/api/statslists exactly the ids thatPixelPlays.GAMESexposes. I kept the regex rather than restructuring, so a differently shapedGAMESentry now fails that test instead of going uncounted. - Timer and shutdown: the timer is now two plain statements.
serve.mjsflushes on SIGTERM and SIGINT before exiting. - README: the Plays section now describes the Origin check as limited and states the rate limits and consistency rules. It also says that slow inflation within those bounds is still possible, so the numbers are a guide rather than proof.
The limits narrow what a script can do but do not close the gap. Someone patient can still push a game up within them. The per-address limit may also be shared if the forge proxy puts every visitor on one socket address. In that case the 60-a-minute limit applies to all visitors together.
🤖 Generated with Claude Code
All seven earlier asks are met:
- Rate limit: met.
limits.mjskeys onreq.socket.remoteAddress(60/min) and on the game (600/min), answers 429 with retry-after, and its key table is bounded. It has unit tests and an HTTP test. - Consistent totals: met. A play is refused without an open ahead of it, and time is refused beyond
play * 3600. Both are tested. - Body cap: met. It sums Buffer bytes and decodes once, and the multi-byte test gets 413.
lapand visibility: met. The hide, resume, under-a-second, clamp and pagehide paths are all driven inshell.test.mjs.- Id parity: met.
/api/statsids are asserted equal toPixelPlays.GAMES. - Timer: met. It is two plain statements, and the counts flush on SIGTERM/SIGINT.
- README: met. It states the limits honestly.
On the preview: the home footer links stats/, and /stats/ answers 200 with CSP default-src 'none', nosniff and no-referrer. A same-origin POST to /api/play gets 204 and shows up on the page; a cross-origin POST gets 403. The app has no tty, so there is no terminal door to match.
Non-blocking: the preview's /api/stats shows balote at open 1, play 5, playRate 500. That data was saved under the earlier head, before the consistency rule, and the loader in createStats reads it back without the rule. Clamping on load (play <= open, seconds <= play * 3600) would make the README's claim hold for old files too. Production starts with no file, so this does not block landing.
The app now counts plays per game and ranks the games on a new
/stats/page, most played first.bun testpasses (197 tests). I did not runtsc(the repo has no tsconfig) or start the app by hand.The issue body was empty and its title was cut off after "which games are played the mo…". I read it as "which games are played the most", so I built play counts. Say if you meant something else.
What changed
POST /api/play. They are the page opening, the first tap or key press (counted as a play), and the seconds the page stayed visible after that.shell.js, so every game is covered without editing any of them.stats.mjskeeps only totals per game, with no ids or cookies. It writesplays.jsonunderFORGE_APP_DATA, or keeps counts in memory if that is unset.-
/stats/shows plays, opens, play rate (plays per open) and average seconds per play. It runs no script, sets a strict Content-Security-Policy, and is linked from the home footer. -/api/statsreturns the same rows as JSON. - The README has a new Plays section.stats.test.mjs,serve.test.mjsandshell.test.mjscover counting, persistence, escaping, origin refusal, bad input and the client sending its events.What I chose not to do
bun:sqlite, becauseserve.mjsis documented to run on Node too and totals don't need a database.To try it: run
bun serve.mjs, open a game and tap, then visit/stats/.🤖 Generated with Claude Code
Closes #43