# PEPE RUN backend security audit: `backend/protocol`, `backend/admission`, `backend/store`, `backend/runtime` Audited source: https://github.com/identity-md-launches/goal-3502-build-audit-deploy-pepe at commit `6083f1b5db4c14344351876ca9d2d057b768ad85`. Every `file:line` below refers to that commit. I also read `game/engine.mjs` and `src/RunArcade.sol` / `src/RunVerifier.sol` where the four packages depend on them. I did not audit the contracts themselves; that belongs to a separate item. ## Summary **Existing tests.** They all pass on Node v24.21.0: - `node --test` over the protocol, store, migration and admission suites: 34/34. - `node backend/runtime/check.mjs`: 10/10. - `backend/protocol/check.mjs` was not run, because its Foundry step needs `forge` plus solc 0.8.26 (see Not checked). I wrote six proof-of-concept scripts in a scratch folder (`poc1`–`poc5` plus a worker); their outputs are quoted in the table. The scratch folder is not delivered. **What holds up:** - **SQL.** Every statement is parameterised. The only interpolation is `PRAGMA user_version=${v}`, where `v` is the migration loop counter (`backend/store/index.mjs:62`). - **No reuse of an entry, no second seed.** - On chain, `nonceUsed` blocks reuse (`src/RunArcade.sol:175-177`). - In the store, `sessions.entry_key` is UNIQUE (`backend/store/migrations/001.sql:21`). - In the runtime, `runs`/`seeds` are keyed by `entry_id`, and a different derivation fails with `SEED_RESELECTION` (`backend/runtime/index.mjs:58-59,91-95`). - **Input handling.** Inputs cannot be reordered, backdated or replayed. Sequences must be contiguous, a late input is moved to the current server tick, and duplicates are no-ops (`backend/runtime/index.mjs:168-176`). - **The clock.** It is wall-clock driven, so a client cannot slow the game (`backend/runtime/index.mjs:216`). - **Snapshot fields.** Snapshots contain no secret field (`backend/runtime/index.mjs:314-322`, `backend/protocol/evidence.mjs:27-37`). Error messages carry codes or key names, not seed values. - **Session tokens.** They are random UUIDs (`backend/runtime/index.mjs:97,339`) and cannot be forged. - **Week calendar.** It matches the contract: - Anchor 331200 = `1970-01-04T20:00:00Z`, a Sunday (computed). - Cutoffs are 1800 s and 300 s before the end (`backend/protocol/schedule.mjs:6-8`, `src/RunArcade.sol:24-26`). - **secp256k1 recovery is correct for Ethereum signatures.** - Wycheproof `ecdsa_secp256k1_sha256`: 166/168 valid vectors recover the published key, and 0/87 invalid vectors are accepted. - The 2 misses are tcId 350 and 471. In both, k·G has an x-coordinate ≥ n, which needs a recovery id of 2 or 3. Ethereum's v ∈ {27,28} cannot express that either. - 200/200 OpenSSL-generated signatures recover correctly, and malformed signatures (r=0, s=0, high s, r=n, v=29) are rejected. **What does not hold up:** 1. **Course foresight (F1).** The engine seed is only 32 bits, and the course comes straight from mulberry32 of that seed. A paying client watched 8 on-screen obstacles, brute-forced the seed in 46 s on 4 threads, and predicted every later obstacle exactly. 2. **Nothing stops a bot (F2).** A script driving the snapshot API is scored like a human. Because speed depends only on distance, every run that survives to the 2-hour cap would score the same distance, and the tie goes to the lowest `entryId`. 3. **An operator can pick the winner (F3), and nothing downstream would notice.** An operator with database write access can fabricate inputs for a real entry. An operator holding both score keys can sign any distance. Either one can withhold attestations from rival runs. The replay verifier only replays what the operator's database exports, and the contract checks signatures, not replays. 4. **Paid entries can be lost through no fault of the player (F4, F5).** This happens when finality arrives after 19:55, or when the server crashes after the player has already used their one reconnect. 5. **Secrets in plaintext (F6).** Seed secrets and live bearer tokens are stored unencrypted. 6. **Resource exhaustion.** Unauthenticated challenge creation and 43–48 ms unthrottled signature recovery allow disk and CPU exhaustion (F7, F8). The HTTP API, chain indexer, replay verifier service, settlement keeper, seed-custody adapter and runtime wallet-session adapter do not exist yet. Their required interfaces are listed under F14 and in What to do next. ## Findings Severity reflects impact on a real-money weekly jackpot. | id | severity | where (file and line) | what goes wrong | proof | fix | |---|---|---|---|---|---| | F1 | High | `backend/protocol/hashing.mjs:124` (`seed = Number(BigInt(mix) & 0xffffffffn)`); `game/engine.mjs:84-90,140-173,176-181` (mulberry32 seeded directly with the seed, two draws per obstacle); `backend/runtime/index.mjs:320` (snapshot returns every visible obstacle's exact `xMm`, `kind`, `id`) | The 256-bit secret/blockhash mix is cut to 32 bits and fed into a non-cryptographic PRNG. Each visible obstacle's kind and exact position reveals ≈6–7 bits (kind roll plus gap ticks, inverted from the next obstacle's position). After ~5–8 obstacles the seed is unique, and the whole course beyond the 800 px view is known for the rest of the run. | `poc1-seed-from-snapshots.mjs` drove a real `PaidRuntime` using only `snapshot()`. At 113 m it had 8 obstacles; the 2^32 search took 46.1 s on 4 threads and returned one candidate, `2913378132`, equal to the seed in `runtime.sqlite`. It predicted 55 off-screen obstacles in the next 1 km; the next 4 revealed by the server matched exactly (0 mismatches). | Derive obstacle *i* from a keyed PRF over the full 256-bit `mix` (e.g. `keccak256(mix, i)`), never from a 32-bit state. That changes `rulesVersion`/`rulesHash` and `RunVerifier.deriveSeed`'s `uint32` return (`src/RunVerifier.sol:102`), so do it before deployment. Also send only the obstacles actually on the client's screen. Even then, exact positions keep leaking gap information, which is only safe once the generator is a PRF. | | F2 | High (design) | `backend/runtime/index.mjs:35,190-195,203` (anomaly counters are evidence only); `backend/runtime/README.md:51` ("They never change the score"); `backend/runtime/index.mjs:21` (2 h cap); `game/engine.mjs:277-280` (distance step depends only on distance); `backend/protocol/schedule.mjs:37-43` and `src/RunArcade.sol:259-262` (tie → lower `entryId`) | A script playing from snapshots is accepted like a human, and the replay verifier only confirms that the inputs reproduce the distance. Speed is a pure function of distance, so every run that survives to `maxRunTicks` reaches the same distance. A tie at the cap is won by the earliest entry of the week. | `poc1` used a naive scripted jumper (no human) that covered 113 m on the live runtime with every input accepted. I did not test whether a better bot survives to the cap (see Not checked). | This is a product/legal decision: no code change can prove a human played. Options: disclose that automated play cannot be excluded; make ties at the cap split or roll over instead of going to the lowest `entryId`; add review or manual dispute holds for top scores before settlement (needs a contract challenge window, F3). Do not present the anomaly counters as anti-cheat. | | F3 | High | `src/RunArcade.sol:255` (`ADMISSION_AUTHORITY` is also the score authority); `src/RunArcade.sol:241-266` (no replay data checked); `src/RunArcade.sol:272-274` (settle allowed as soon as the week ends); `backend/runtime/index.mjs:354-364` (the verifier gets the operator's `exportEvidence`); `backend/store/README.md:86` ("this library is not a sandbox against its own operators") | **Operator with store DB write:** can rewrite `inputs`/`checkpoint` of a confederate's real entry, for example with a perfect input plan computed offline from the seed (F6). The verifier replays exactly what it is given and signs; the contract accepts it. **Operator with the admission/score key plus the replay-verifier key:** signs any `distanceMeters` for any on-chain entry. **Either one:** can withhold attestations of a rival's higher score; nothing on chain or in the store forces every finished run to be attested. Publishing the seed after the week does not help, because settlement is immediate. **What is caught:** fake entries. `submitScore` requires an on-chain `Entry` with a matching wallet/epoch/royal/seedCommitment/rulesHash (`src/RunArcade.sol:247-253`), and admissions still cost tokens (`src/RunArcade.sol:209`), so neither DB edits nor the admission key can grant free entries or lives. | Code reading of the cited lines; no PoC needed. The contract checks only the two signatures and entry metadata. | (a) Run the replay verifier as a separate party with its own copy of the input stream: inputs mirrored to it live, or hash-chained per batch and countersigned. (b) Separate the online admission hot key from the score-authority key in the contract. (c) Publish every terminal run's replay digest and, after the run, the seed evidence and inputs, so anyone can re-run them. (d) Add a challenge window between the week end and `settle()`. (e) Publish the list of finished sessions so withheld attestations are visible. | | F4 | Medium | `backend/admission/index.mjs:83` (`minFinalityWindowS = 90`), `:131-132`; `backend/runtime/index.mjs:79-84` (`ENTRY_CLOSED` after 19:55; seed needs finalized `entryBlock+2`); `backend/store/index.mjs:114` (purchase must be finalized) | A game quote is issued up to 90 s before 19:30. Ethereum blocks take about 15 minutes to finalize (ethereum.org), so a late purchase becomes playable around 19:43–19:45 with ~10 minutes before the 19:55 stop. If finality is delayed past 19:55 the entry can never start, and the contract has no refund path. | `poc4`: the quote was issued at cutoff − 95 s with expiry at cutoff − 90 s. `poc2` (F4): entry bought at 19:28:25, seed block finalized after 19:55:00, `start()` → `ENTRY_CLOSED`. | Set `minFinalityWindowS` to at least ~30 min plus `minPlayWindowS`, or move the contract's entry cutoff earlier. Disclose the shortened play window for late purchases. Decide (legal/product) what happens to an entry finalized after 19:55. | | F5 | Medium | `backend/store/index.mjs:205` (`reconnect_used` → `expired/second_disconnect`); `backend/runtime/index.mjs:388-396` (`recover()` disconnects every live run); `backend/store/index.mjs:336-340` (`isEligible` admits only `finished`); `backend/runtime/index.mjs:239,245` (`sweep()` runs outside the per-session `try` inside a `setInterval`) | A server crash or restart counts as the player's disconnect. If the player already used their one reconnect, the run ends `expired` and is not eligible, even though the fault was the server's. Also, any exception from `store.expireDue()`, such as `SQLITE_BUSY` after the 5 s timeout, escapes the timer callback and kills the process, which triggers this path for every live run. | `poc2` (F3 output): disconnect → reconnect → simulated crash → `recover()` gives `expired`, reason `second_disconnect`, `isEligible=false`. | Give server recovery its own reconnect allowance, separate from the client's. Wrap `tickAll` in `try/catch`. Decide and document whether `expired` runs rank with their checkpointed distance. | | F6 | Medium | `backend/admission/store.mjs:30` and `backend/admission/index.mjs:158-163` (`seed_secret` stored in plaintext); `backend/runtime/index.mjs:58,93` (`seeds.evidence` holds the secret, mix and seed in plaintext); `backend/runtime/index.mjs:59,97` (`runs.token` bearer token in plaintext) | Anyone who can read the admission DB can open every commitment. Once `entryBlock+2` is finalized, they know the seed and the full course *before* the player starts, and can leak it to a confederate. Anyone who can read the runtime DB can take over live runs: the stored token is the live credential until the first reconnect, and it has no wallet binding or expiry. | `poc4` (F6): `seed_secret` read from `admission_quotes` recomputes the signed `seedCommitment` (true). `poc2` (F6): input sent with the token read from `runs.token` → `accepted [{"seq":1,"tick":1}]`. | Envelope-encrypt seed secrets with a KMS key held by a separate seed-custody service that releases a secret only when it derives the seed for `start`. Store only a hash of the token and bind it to the authenticated wallet session with a TTL. Restrict and audit DB access. | | F7 | Medium | `backend/admission/index.mjs:106-115` (rate bucket `sha256(wallet|origin)`, where the wallet is attacker-chosen and no proof is required); `backend/admission/store.mjs:56-62,48-55` (challenges and rate windows are never deleted) | Anyone can create unlimited durable challenge rows by changing the `wallet` field. The per-wallet limit (8/h) is bypassed and the disk grows without bound. | `poc4` (F7): 3000/3000 challenges accepted from one client with random wallets, 2.5 ms each; 3000 challenge rows and 3000 rate rows, 5.4 MB DB+WAL. | Add per-IP and global limits in the HTTP API, cap open challenges, and periodically delete expired challenges and rate windows. Optionally, ask for the wallet only at sign time and bind it then. | | F8 | Medium | `backend/admission/secp256k1.mjs:26-40,45-65` (affine BigInt arithmetic with a modular inverse per point add); `backend/admission/index.mjs:140-152` (no rate limit on `requestAdmission`; the signature is recovered before the nonce hash is checked) | Each forged call costs one full recovery (~45 ms of CPU). About 20 requests/s saturate a core, and a failed attempt does not burn the challenge. | `poc3`: `recoverAddress` takes 43.3 ms per call. `poc4` (F8): 30 forged `requestAdmission` calls on one challenge took 48.4 ms each and all returned `WALLET_SIGNATURE_MISMATCH`; the challenge still worked afterwards. | Check `nonce_hash` and challenge state before doing any curve math. Rate-limit per challenge and per IP, and expire a challenge after N bad signatures. Use an audited constant-structure library such as `@noble/curves`, vendored like `noble-hashes`, with projective coordinates. | | F9 | Low | `backend/admission/secp256k1.mjs:75-84` (`signDigestForTestOnly`: `k = z + d`) | The nonce is a public function of the key, so a single signature reveals the private key. It is exported from a production module, one import away from misuse. | `poc3`: private key recovered from one signature via `d = z(1−s)/(s−r) mod n` → `true`. | Move it to `backend/admission/test/` and forbid importing it from non-test code (lint rule). | | F10 | Low | `backend/store/index.mjs:193-227`; `backend/runtime/index.mjs:286-294,325,339` | The client can freeze the course once per run, for up to the 15 s grace window, at a moment it chooses (for example just before a hard section). Simulation is suspended while disconnected and re-anchored on reconnect. | `poc2` (F2): tick 120 before the disconnect, still 120 after 14 s offline; grace deadline 14 992 ms. | Keep simulating during a disconnect (the run continues and may die), or shorten the grace window and disclose it. If the pause stays, record it in the evidence and the terms. | | F11 | Low | `backend/store/index.mjs:103,189-190` (every checkpoint stores an idempotency receipt containing the full session view with engine state); `backend/store/README.md:84` (never deleted); `backend/runtime/index.mjs:46,134` (`#sessions` never pruned) | The disk grows ~2.6 kB per checkpoint at 2 checkpoints/s: ~37 MB per 2 h run, forever. Memory also grows with every run the process has served. | `poc2` (F5): 13 receipts, 33 866 B, 2 605 B per checkpoint, extrapolated to ~37.5 MB per 2 h run. | Make checkpoint receipts minimal (tick, seq, state hash), since idempotency already follows from tick/seq. Plan archival. Evict terminal sessions from `#sessions`. | | F12 | Low | `backend/admission/index.mjs:138` (skin quote expiry `now + quoteTtlS` with no week-end cap); `src/RunArcade.sol:172-173` (`a.epoch != currentEpoch` → revert) | A skin quote issued shortly before Sunday 20:00 stays valid into the next week, and its transaction reverts `WrongEpoch`. The buyer wastes gas. | `poc4` (F12): quote at end − 30 s had `admission.epoch=2969` and expiry 90 s after the week end. | Cap every quote's expiry at `epochWindow(epoch).end − margin`. | | F13 | Low | `backend/protocol/schedule.mjs:8,24`; `src/RunArcade.sol:254` (`ScoreAfterClose`); `backend/runtime/index.mjs:21,230` | Runs forced to end at 19:55 must be replayed (up to 2 h of ticks), doubly signed and included on chain before 20:00. Scores that miss the window are lost, and the keeper has no slack. | Analysis of the cited lines; not executed. | Measure replay time for a 2 h run. Either end runs earlier or let the contract accept receipts for runs that ended before `finalCheckpoint` during a short post-week window before `settle()` (contract change). | | F14 | Info | `backend/protocol/schemas.mjs:12,21-22` vs `backend/runtime/index.mjs:135-136,167`; `backend/protocol/schemas.mjs:2` (validator has no `maxItems`/`maxLength`) | The published JSON schemas do not match the runtime. `inputBatchRequest` events require `{seq,tick,action}`, but the runtime takes `{seq,action,clientTick}`. `sessionOpenResponse` requires `entryId`/`seedStatus` and forbids the runtime's `token`, `royal`, `epoch`, `tickRate`, `cutoffAtMs`, `limits`. The validator accepts arrays of any length. | `poc5`: runtime input shape → `rejected: $.events[0].tick required`; runtime `start()` result → `rejected: $.entryId required`; a 200 000-event batch → `valid` (209 ms). | Align the schemas with the runtime before writing the HTTP API. Add `maxItems: 16` and string length limits, and cap the HTTP body size before parsing. | | F15 | Info | `backend/admission/secp256k1.mjs:37,57` | `multiply(N, R)` reduces k mod N to 0 and always returns `null`, so the "subgroup" check never rejects anything. It is harmless (secp256k1 has cofactor 1) but misleading. | Code reading; Wycheproof and OpenSSL results in the Summary. | Remove it, or replace the module with an audited library (F8). | | F16 | Info | `backend/runtime/index.mjs:64,216` | The runtime uses `Date.now()` without a monotonic guard (only the store clamps its own clock, `backend/store/index.mjs:77-81`). A backward NTP step freezes all runs; a forward step makes them catch up at 12 ticks per loop. | Code reading. | Drive ticks from `performance.now()` anchored once to wall time, and alarm on clock steps. | ### Operator capabilities and what catches them | actor and access | can do | caught by replay verifier? | caught by contracts? | |---|---|---|---| | Admission DB read | learn every seed after `entryBlock+2` finality, before play (F6); tell a confederate the course | no | no | | Runtime/store DB read | take over live runs with the stored token (F6); read seeds | no | no | | Store DB write | invent inputs or checkpoints for a real entry (F3); register fake purchases | inputs: no (it replays what it is given); fake purchase: n/a | fake purchase: **yes** (`src/RunArcade.sol:247-253`); invented inputs: no | | Admission/score key (`ADMISSION_AUTHORITY`) | sign admissions (the wallet still pays: `src/RunArcade.sol:171,209`); provide half of every score signature | — | free entries: **yes** (payment required); a score alone: **yes** (also needs `REPLAY_VERIFIER`) | | Both score keys | record any distance for any real entry; pick the winner | no | no (only entry metadata is checked) | | Any signer | withhold attestations from rivals | no | no | | Owner | change prices, fees, wallet or winner | — | not assessed here (contract item) | ## What to do next | # | action | |---|---| | 1 | Replace the 32-bit mulberry32 course generator with a PRF over the full 256-bit `mix` (F1), and update `RULES_VERSION`, `rulesHash`, `RunVerifier.deriveSeed` and the vectors before any deployment. | | 2 | Make the replay verifier actually independent: it must receive inputs directly or as countersigned hash-chained batches, not from the operator's `exportEvidence` (F3). Use a separate score key in the contract, not `ADMISSION_AUTHORITY`. | | 3 | Add a challenge window between the week end and `settle()`, and publish every finished run's digest, inputs and seed evidence so anyone can replay them (F3, F2, F13). | | 4 | Get the requester's decision on automated play and on ties at the 2 h cap, and disclose it in the terms (F2). | | 5 | Encrypt seed secrets in a separate KMS-backed custody service, and store only token hashes bound to a wallet session with a TTL (F6). | | 6 | Raise `minFinalityWindowS` to cover ~15-minute finality plus play time, and define what happens to entries finalized after 19:55 (F4). | | 7 | Stop server recovery from consuming the player's reconnect, and wrap `tickAll` in `try/catch` (F5). | | 8 | Check the nonce before curve math, rate-limit `requestChallenge`/`requestAdmission` per IP and per challenge, purge expired rows, and move to an audited secp256k1 library (F7, F8, F15). | | 9 | Move `signDigestForTestOnly` into `test/` (F9). | | 10 | Fix the schemas to match the runtime, with size limits (F14). Then build the **HTTP/WebSocket API** on them: SIWE login → session credential for `admission.authenticate`; `start/input/snapshot/disconnect/reconnect/finish/result` (`backend/runtime/README.md:28-39`); per-IP limits; body cap ≤ 2048 B for input. | | 11 | Build the **chain indexer** to: read `EntryPurchased`/`AdmissionConsumed` (`src/RunArcade.sol:66-67`) at `finalized`; call `store.registerPurchase` (`backend/store/index.mjs:108-130`) and `admission.recordAdmissionUse` (`backend/admission/index.mjs:201-207`); serve `resolveEntry` with `entryBlock`, `seedCommitment` and `royal` taken from `entryOf(entryId)` on chain (not from the DB); call `markReorg` on orphaning. | | 12 | Build the **replay verifier** to: take the evidence; check `verifySeedEvidence` and the on-chain commitment; replay inputs through `game/engine.mjs` with the runtime's tick semantics (`backend/protocol/inputs.mjs:15-46`); recompute the store digest as `replayHash` (`docs/protocol.md:21`); sign the EIP-712 v2 `Score` with `distanceMeters = floor(distanceMm/1000)`; then call `store.recordAttestation`. | | 13 | Build the **settlement keeper** with a durable outbox to: call `submitScore` before `epochEnd` for every accepted run, `settle()` after the end, and re-check `isEligible` and canonical status just before submitting (`backend/store/README.md:74`). | | 14 | Plan for growth: minimal checkpoint receipts, eviction of terminal sessions, and a capacity/archival plan (F11). Cap skin quote expiry at the week end (F12). Use a monotonic tick clock (F16). | ## Not checked - **Contracts.** I read only the lines cited. `backend/protocol/check.mjs`'s Foundry step (`forge test` with solc 0.8.26) was not run, so the on-chain/off-chain vector equality and the owner powers are not verified here. - **Bot reach.** I did not test whether a competent bot survives to the 2 h cap, or whether every generated course is survivable. My PoC bot died in level 1. - **Real infrastructure.** No real Ethereum RPC, finality feed, reorg, KMS/HSM signer, evidence provider or network transport exists to test. F4's timing relies on the "about 15 minutes" finality figure from ethereum.org, not on a measurement. - **Vendored hashing library.** I did not compare `backend/protocol/vendor/noble-hashes-1.8.0` byte-for-byte with the upstream release. - **Load and concurrency.** Load beyond `backend/runtime/check.mjs`'s own capacity runs was not tested. Concurrency across more than two processes was covered only by the existing tests. - **Front end.** The web client (`web/`) has no paid mode yet, so client-side leakage was not assessed. - **Legal.** Eligibility, intellectual-property rights and licences were not examined. This report invents no address, price, licence or approval.