Published on 6 min read
Anti-cheat leaderboards: the server replays the game
How Hamlet Guard verifies leaderboards: a deterministic simulation, replays made of seed and commands, re-simulation on GitHub Actions with a minimal DB role.
Related project: Hamlet Guard
A leaderboard in a web game is only as trustworthy as its scores. In the browser, a score is a number the client sends to the server, and anyone with developer tools can send whatever number they like. For Hamlet Guard, the pixel-art tower defense game I am building, I decided not to trust the number but the game: the server replays the match and accepts the score only if the result comes out identical.
The constraint that shaped the architecture
Replaying a match costs CPU. In the design notes I measured 17 to 37 ms per won match in Node, on a development PC, using the greedy bot from the balance tests. The free Cloudflare Workers plan gives each request 10 ms of CPU, so running the check inside the Worker would require a paid plan. I chose to stay on the free tier and move the verification to GitHub Actions, asynchronously. The player does not wait: the score reaches the server as pending and is judged later.
A simulation that always gives the same result
For the re-simulation to mean anything, packages/sim must be deterministic: the same seed and the same commands must produce the same state at every tick, on any JavaScript engine. The package is headless, with no Pixi, React or DOM, and the monorepo's ESLint config enforces it. The real problem is math. Math.sin, Math.exp or Math.pow are not guaranteed to return the same bits across engines, and Math.random or Date.now cannot be replayed at all. So the engine bans them:
// eslint.config.js (excerpt, simplified)
const NON_DETERMINISTIC_MATH = ['random', 'sin', 'cos', 'atan2', 'exp', 'log', 'pow'].map(
(property) => ({
object: 'Math',
property,
message: 'Non deterministico tra motori JS: vietato in packages/sim (usa Math.sqrt o tabelle).',
}),
);
Gameplay values are integers: gold, lives, damage, costs, score and ticks. Positions, speeds and distances stay floats, because movement along a path is continuous. So determinism does not come from "everything is an integer". It comes from two choices: only using operations that IEEE 754 rounds identically everywhere (addition, multiplication, division, square root), and hashing the exact bits of every float, so a difference in the last bit changes the hash. The random generator, mulberry32, also uses only 32-bit integer operations and starts from the match seed. The world state lives in an ECS, bitECS 0.4: components are typed arrays (Float64Array, Int32Array) created for each simulation, so two matches never share memory.
The replay: seed, commands and checkpoints
A replay does not store the game state, only what is needed to recreate it: the seed, the level, the content and simulation versions, the difficulty, the chosen skills, and the list of commands with the tick where each one was applied. Every 300 ticks, which is every 10 seconds at 30 Hz, the session records a checkpoint with the FNV-1a hash of the state:
advance(): void {
if (state.status !== 'playing') { pending.length = 0; return; }
for (const command of pending) applyAndRecord(state, replay, command);
pending.length = 0;
step(state);
replay.endTick = state.tick;
if (state.tick % CHECKPOINT_INTERVAL_TICKS === 0 || state.status !== 'playing') {
replay.checkpoints.push({ tick: state.tick, hash: hashState(state) });
}
}
A rejected command changes nothing and is not recorded, so a replay cannot be padded with useless taps. During re-simulation the server recomputes every hash. At the first checkpoint that differs, the replay is rejected as diverged, together with the tick where the two histories split.
The verifier
The Worker receives POST /api/scores, checks only the shape of the payload (it does not import the simulation, to stay light), stores the score as pending and answers 202. In the background, through waitUntil, it asks GitHub to start the verify-scores.yml workflow: at most once every two minutes and 30 times a day. The workflow also runs every night. The dispatch counter lives in the database, because it has to hold across every Worker instance at once.
The verification script runs a sequence of checks: known content, known level, simulation version, legal skills, agreement with the checkpoints, a won match, and a score equal to the one claimed. Every rejection carries a stored reason. That lets me tell a game bug from an attempt to cheat, and to judge scores again when a new content version arrives.
The workflow writes to the database with a dedicated role, td_verifier, which has the minimum privileges it needs:
REVOKE ALL ON scores, remote_config, saves, season_content FROM td_verifier;
REVOKE ALL (status, reason, verified_at) ON scores FROM td_verifier;
GRANT SELECT ON scores, remote_config, saves TO td_verifier;
-- Write access: the outcome only. No DELETE, no INSERT, no UPDATE of score or other columns.
GRANT UPDATE (status, reason, verified_at) ON scores TO td_verifier;
If someone obtained this role's password, they could read a few tables and change the outcome of a verification. They still could not invent a score or delete one.
The test that guards determinism
The most important test does not check a function. It checks that a result stays stable. For a fixed seed and a fixed list of commands, determinism.test.ts expects one exact finalHash. If a change alters the simulation's behaviour, the test fails. When the change is intended, I update the value and bump SIM_VERSION, now 7. Old replays are then rejected as stale_sim rather than judged under rules that did not exist when they were played.
What ends up on the board
Verifying a score is not enough: the board also has to define what counts. Only wins make it onto the board, and each player's best verified score stands, separately for each level, difficulty and simulation version. The board belongs to the current season. When a season closes, its board stays archived and the new one starts from zero. Ties go to whoever got there first.
Content versions share one board, because a balance tweak should not wipe it out. The simulation version does split the boards, because it changes what a replay means: a score earned under different rules cannot be compared.
What I would do differently
The cloud save, which the verifier reads to check owned skills, is written by the client. A cheater has to forge it too, and the check cannot stop that. I treat it as a known limit, not a guarantee. I would also like to run the golden tests in real browsers, not only in Node, because that is where engine differences show up. And deferred verification means a score waits until the workflow runs: fine for a beta, not for a live tournament.
You can try Hamlet Guard at hamletguard.it.
- anti-cheat
- deterministic simulation
- Cloudflare Workers
- GitHub Actions
- TypeScript
Have a similar project? Let's talk
If you're facing a similar challenge, get in touch and I'll tell you how I would approach it.
Let's talk