Files
wikideck/docs/game/HOSTING.md
T
claudeanderic 4f7a8a7c74 Night 1: Edit War card game, eom.dev accounts, peer-hosted modes, Android and iOS apps (#22)
Overnight build by 17 Claude agents (2026-11-16 22:45 → 01:30 EST), coordinated in [claude/wikideck milestone 63](https://gitea.eom.dev/claude/wikideck/milestone/63). **For Eric's review. Do not merge without it.** The full write-up is in `docs/night/REPORT.md`.

**What's in it** (38 reviewed PRs, squash-merged into `night/2026-11-16`):
- **Edit War:**
  - a 3-lane, 6-turn card game built on what WikiDeck cards actually hold
  - a pure, deterministic, off-chain rules engine (`shared/game/`, with the API in `docs/game/ENGINE_API.md`); rules are data and v1.1 is the default
  - a mobile-first Play UI with a lobby, deck builder, four loaner starter decks, a match against the AI, results and a tutorial
  - a landing page (fixes #3)
- **Design and balance:** `docs/game/DESIGN.md`, `CARD_DATA.md` (236 sampled articles) and `BALANCE.md` (bot simulations). Starter pairings went from 23–77% on v1 to roughly even on v1.1.
- **eom.dev accounts:** Dex OIDC with PKCE, plus off-chain wallet linking, where the client builds the message it signs (`server/account/`, `src/auth/`).
- **Peer-hosted game modes:** modes are JSON data, never code. Node API at `/api/game/*`, with host credit and leaderboards. Three example modes (`shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`).
- **Mobile:** Capacitor 7 Android app (a debug APK played a full match against the AI in the emulator), and an iOS project waiting on Xcode (`docs/night/ANDROID.md`, `docs/night/IOS.md`).
- **Testnet tooling:** `deploy/night/` (LAN-only, 3 nodes) and an optional `WIKIDECK_USER_AGENT` (the default is unchanged).

**Not touched:** consensus and protocol (`server/chain.ts`, `shared/protocol.ts`, `server/testnet/{consensus,ledger,…}.ts`, `native/`), the live deployment and mainnet. Matches run off-chain and never move or burn NFTs.

**Checks:** the final integration gate passed in `node:24-alpine`: `npm test` 241/242 with 0 fail (1 skipped), and `npm run build` passes. The repo needs Node 24, because Node 20 fails 12 tests falsely.

**Decisions for Eric** (see REPORT.md, Known issues and Next steps):
1. whether the live node should set `WIKIDECK_USER_AGENT`
2. the Xcode licence, which you should accept yourself
3. #49 in the fork, a bot change held after the freeze
4. on-chain host rewards (proposal only, in HOSTING.md)

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: WikiDeck/wikideck#22

Co-authored-by: Claude <claude@eom.dev>
2026-11-17 17:40:58 +00:00

17 KiB
Raw Blame History

Hosting WikiDeck game modes

Anyone running a WikiDeck node can host their own game modes: their own twist on the rules, played with WikiDeck cards on their node, with visible credit for hosting them. Hosting a popular mode is the night-1 incentive to run a peer.

  • Schema and validator: shared/game/modes.ts
  • Node API: server/game/ (mounted at /api/game by server/testnet/http.ts)
  • Example modes: server/game/modes/*.json (shipped in the node image)
  • Tests: tests/modes-*.test.ts

Everything here is off-chain. Hosting a mode never touches blocks, transfers, trades, validation or NFT ownership. A match never moves or burns a card.

1. Modes are data, never code

A mode is a JSON document, at most 8 KiB:

{
  "schema": "wikideck.mode/1",
  "id": "trending",
  "version": 1,
  "name": "Trending",
  "description": "Live Wikipedia pageview trends power cards up or down.",
  "tags": ["live-data"],
  "rules": { "trendUp": 25, "trendDown": -25 },
  "cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true },
  "decks": { "kind": "starter" },
  "limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 }
}
Field Meaning
id, version Lowercase slug and a version integer. Bump version whenever the rules change, so old match records and leaderboards stay attributable (<origin>#<id>@<version>).
name, description, tags Plain text only: no control characters or < >.
rules Overrides on top of the engine's DEFAULT_RULESET (see docs/game/ENGINE_API.md). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict parseRuleset, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys).
cards A card-mapping preset from a fixed list. standard leaves cards as dealt. live freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's trendUp/trendDown) at match start. trending does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers.
decks starter (everyone gets a seeded starter deck), draft (snake draft from a host-seeded pool of preview cards) or constructed (bring your own; see "Not yet" below).
limits Concurrency and lobby expiry for this mode on this host. turnSeconds only applies to engines without their own turn timer; with tonight's engine, the ruleset's turnSeconds (plus 5 s network grace) is the timer.

The schema is strict: unknown fields are rejected, as are prototype keys (__proto__, constructor, prototype) anywhere in the document, nesting deeper than two levels inside rules, more than 48 rule keys, and oversized strings and arrays. A peer never evaluates, imports or runs anything another peer sends. Nothing in a mode can name a file, a URL, a script or a function.

2. Running your own modes

Configure modes with environment variables on your node:

Variable Default Meaning
WIKIDECK_MODES classic Comma list of built-in ids (classic, trending, draft) and/or paths to .json files. none hosts nothing (the node still lists its peers' modes).
WIKIDECK_MODES_DIR unset A directory: every *.json in it is loaded as a mode.
WIKIDECK_GAME_OPERATOR your origin's host The name shown as "Hosted by …".
WIKIDECK_GAME_NOTE unset A short note shown next to your name, e.g. "EU, best effort".
WIKIDECK_GAME_PEERS WIKIDECK_PEERS Peer origins whose modes to list. Use the peers' public origins, because players open the peer's own site to play there.
WIKIDECK_GAME_TREND_INTERVAL_MS 20000 Background trend warm-up pace for trending modes (minimum 15000).
PUBLIC_ORIGIN http://127.0.0.1:$PORT Your node's identity as a host.

At most 16 modes per node. A bad mode file stops the node at startup with a readable error, because rules are validated once with the engine's parser when the node starts.

Example for the night-1 testnet (three nodes, different modes):

# node-a: the base rules plus Trending
WIKIDECK_MODES: classic,trending
WIKIDECK_GAME_OPERATOR: Testnet A
WIKIDECK_GAME_PEERS: http://192.168.1.32:3102,http://192.168.1.32:3103
# node-b: the draft
WIKIDECK_MODES: draft
WIKIDECK_GAME_OPERATOR: Testnet B
# node-c: everything, including a custom file
WIKIDECK_MODES: classic,trending,draft,/app/data/modes/blitz.json

Writing a new mode

Start from server/game/modes/classic.json, change id, name and description, then override rules. Some ideas within tonight's rules:

  • Blitz: "rules": { "turns": 4, "energyByTurn": [3, 4, 5, 6] }
  • On-topic: "rules": { "onTopicBonus": [0, 2, 2, 3, 3, 4, 4], "trendUp": 10, "trendDown": -10 }
  • Slow play: "rules": { "turns": 6, "turnSeconds": 40 } (the engine caps turns × turnSeconds at 240)
  • Big decks: "rules": { "deckSize": 16, "maxLoaners": 16 } with "decks": { "kind": "draft", "poolSize": 40 }. Starter decks are 12 cards, so a non-draft mode with another deck size is rejected at startup.

Check that a mode parses with npm test (the built-in modes are tested), or load it on a local node: it fails at startup if the engine rejects it.

3. The node API

Everything is under /api/game, behind the node's existing /api admission budget and global rate limit, plus stricter per-route limits.

Method Path What it does
GET /modes Publish: this node's host identity, total matches hosted, and each mode with live stats (players online, open lobbies, live matches, matches played, distinct players).
GET /network/modes Discover: this node's list plus each configured peer's list, fetched as data.
GET /hosts/leaderboard Hosts ranked by matches hosted (this node plus peers).
GET /modes/:id/leaderboard Per-mode player leaderboard (wins, losses, draws).
GET /modes/:id/lobbies Open lobbies waiting for an opponent.
POST /modes/:id/lobbies Create a lobby: { name, secret } → { lobbyId, seat: 0, token }.
POST /lobbies/:lobby/join Join: { name, secret } → { lobbyId, seat: 1, token }. The match (or draft) starts.
GET /lobbies/:lobby Status. With Authorization: Bearer <token>: your PlayerView and your legalActions.
POST /lobbies/:lobby/pick Draft pick: { index }.
POST /lobbies/:lobby/actions Play: { action }, which must equal one of your legalActions.
POST /lobbies/:lobby/resign Resign (or cancel a waiting lobby).
GET /matches/:matchId A finished match record: seed, both decks, the full action log and the result.

Players. The browser generates a random secret once and keeps it in local storage. The host only ever stores and shows sha256("wikideck-player:" + secret) as the player id, so a leaderboard name can't be claimed by someone else who uses the same display name. Each seat also gets a fresh bearer token per lobby; only its hash is kept. When eom.dev accounts land (#7), the player id can come from the account instead.

Playing on a peer's mode. The browser's CSP keeps API calls same-origin, so the lobby shows peer modes with "Hosted by …" and links to the peer's own site to play there. No node proxies another node's matches.

Restarts

Live lobbies, drafts and matches survive a node restart. The node saves them to $WIKIDECK_DATA_DIR/game/live.json every 15 s and on SIGTERM/SIGINT, and restores them on start. Player tokens keep working, and turn and draft timers restart from the moment the node is back. A lobby is dropped instead of restored if its mode is no longer hosted with the same version and rules, so a match never continues under different rules. A hard crash can lose up to 15 s of moves.

4. Credit for hosts

Every mode shows "Hosted by <operator>" (with the node's origin), its player counts, its own leaderboard, and the node's total matches hosted. /hosts/leaderboard ranks nodes by matches hosted.

Tonight these numbers are informational: each node reports its own counts. See section 6 for how they could become rewards without trusting the host's word.

5. Security notes

Limits

Limit Value
Mode document 8 KiB; 48 rule keys; rule nesting depth 2; strings ≤ 64 chars inside rules
Modes per node / per peer response 16
Peer /api/game/modes response 192 KiB, read with a streaming byte cap; 3 s timeout; no redirects; cached 30 s; at most one refresh in flight
Peers at most 16, operator-configured origins only (HTTPS, or HTTP with WIKIDECK_ALLOW_PRIVATE_PEERS=1)
Lobbies + matches in memory 512 per node; maxConcurrentMatches per mode; 3 per player
Match length engine bounds (turns ≤ 12, turns × turnSeconds ≤ 240 s) plus a hard 2,000-action cap
Rate limits per IP 240/min reads and plays, 60/min lobby create/join/resign, 30/min peer-discovery routes (on top of the node-wide 300/min /api limit and the RPC admission budget)
Request body the node's 68 KB JSON limit
Wikipedia lookups (trending) background only: one page per 20 s by default (WIKIDECK_GAME_TREND_INTERVAL_MS, minimum 15 s), at most 256 queued, never per request

Mode validation

A mode is rejected at node startup, never handed to the engine half-checked, if:

  • it fails the mode schema (section 1), or
  • the merged ruleset fails the engine's strict parseRuleset, or
  • it fails the host-side checks in server/game/engine-binding.ts: distinctStats requires topicCount 3; every portalReveal turn ≤ turns; energyByTurn has an entry per turn; turns × turnSeconds ≤ 240; powerByCost has 7 entries; no keyword whose hidden information viewFor doesn't mask yet (obscure) is enabled; or
  • its deck policy can't produce legal decks (starter decks illegal under its rules, or a draft pool smaller than 2 × deckSize).

Wikipedia load (verifyStats)

Our Wikipedia egress is shared and rate-limited, so tonight the host makes no Wikipedia requests in any request or match path:

  • Hosted decks are loaners (starter or drafted), so there are no owned-card stats to verify, and verifyStats never triggers a fetch.
  • When owned decks arrive, verification must use the DESIGN §1.10 immutable cache keyed by (pageId, revisionId, snapshotMonth), with check: 'unchecked' and uncheckedCostCap as the normal path when the cache is cold, not a per-card fetch.
  • trending reads only the background-warmed trend cache (see "Not yet").

Cheating

  • The client is never trusted. Each action must deep-equal one of the engine's legalActions for the token's seat, so you can't act for the other seat, play cards you don't hold, overspend energy or act after the match ends.
  • Hidden information stays on the host. Each seat only ever receives viewFor(state, seat); the opponent's hand and staged plays never leave the server. Spectators see status only.
  • Seeds are the host's. The host picks a random seed when the lobby opens, so players can't grind for a favourable shuffle. The engine hashes it to 32 bits: fine against players, but not a secret worth relying on against a host.
  • Stalling: when a seat runs out of turn time, the host applies the engine's timeout action (auto-commit). After afkTurns idle timeouts the engine forfeits that seat. Timeouts are in the action log, so they replay. A stalled draft pick is made automatically.
  • Sybils and win-trading: anyone can make a new player id, and two ids controlled by the same person can feed each other wins. Tonight's leaderboards are for fun. Accounts (#7) or wallet-signed identities would raise the cost.
  • Card input. The host builds every deck from shipped engine data (starter decks and the loaner pool). It never accepts cards, check values or pinned stats from client JSON.
  • Card stats. Card numbers come from the engine's card mapping. Minted stats are self-reported by the minter (see council-critic in #3); a mode can only pick a mapping preset, not supply numbers.

What a malicious host can and can't do

Hosted PvP trusts the host. The host holds both players' hidden plans (hands and queued plays) and relays them; it decides the seed; and it would be the one to mark card stats as checked or unchecked (DESIGN §1.10). Nothing tonight lets players verify a match while it's being played. So a host is trusted for the matches it hosts, and only those. Play on hosts you trust, and treat leaderboards on any other host as that host's claims.

A malicious host can:

  • lie about its stats, its matches hosted and its leaderboards;
  • rig its own matches: pick seeds, peek at hands, or ignore the rules;
  • drop or stall your match, or record a false result.

A malicious host can't:

  • touch your cards: matches are off-chain, and the host never receives a key or signature;
  • run code on other nodes: its modes are inert data, validated with hard limits;
  • make other nodes fetch anything except its own /api/game/modes, or make them fetch it in a way that slows them down (byte cap, timeout, cache, single flight);
  • publish modes under another node's origin: discovery pins the origin it actually fetched;
  • see your player secret: it only receives it once, over its own origin, and stores the hash. Use a different secret per host if you don't trust a host (the UI can derive one per origin).

Audit trail. Every finished match record publishes the seed, both decks and the full action log, so anyone can re-run it with the engine's replay(ruleset, decks, seed, actions) and check the result. A host that lies about a result can be caught; a host that peeked at hands can't.

6. Proposal: on-chain host rewards (not tonight)

Rewarding hosts on-chain is a protocol change, so it's out of scope for night 1. This is a proposal for later, to be reviewed like any consensus change.

Goal: pay hosts for matches real players actually played, without trusting the host's count.

  1. Signed match results. Both players sign the final result (matchId, <origin>#<id>@<version>, seed hash, action-log hash, winner) with their wallet keys. The host signs too. A result needs all three signatures, so a host can't invent matches or results alone, and players can't deny a match they played.
  2. Replayable evidence. The record keeps the seed, decks and action log. Anyone can replay it with the pinned engine version to check the result. Disputes are settled by replay, not by vote.
  3. Batched claims. Once per epoch, a host submits one transaction committing a Merkle root of its signed results. A new hostClaim transaction type would carry the root and a count. This is the protocol change: a new transaction type, its validation and its reward rule.
  4. Rewards that resist farming. A host's reward per epoch grows with the number of distinct paired wallets (not matches), each wallet counts toward at most one host per epoch, wallets must hold at least one minted card older than N blocks, and the total is a small, capped share of block rewards. That makes sybil farms cost real mining work.
  5. Challenges. For a window after a claim, anyone can post a replay that contradicts a committed result, or proof that a wallet was double-counted. A successful challenge voids the host's claim for that epoch.

Open questions: who pays (a share of block rewards versus a fee from players), how to stop colluding players and hosts from farming one another, and whether the engine version must be pinned in consensus.

Not yet

  • constructed decks of owned NFTs: the policy exists, but tonight the host deals starter decks for it. Playing with your own cards needs a wallet-signed ownership proof for the lobby (and then the engine's cardFromStats). That's a follow-up once accounts and wallet linking (#7) settle.
  • trending never calls Wikipedia when a match starts. The node warms a cache-only trend store in the background, one page every 20 s (configurable, never faster than 15 s), through its existing enrichment cache (6 h TTL), starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This keeps load on the shared, rate-limited Wikipedia egress tiny: a few dozen pages per 6 hours per node.
  • Spectating and rematches.
  • Separate game RPC budget. /api/game sits behind the node's global /api admission budget (WIKIDECK_RPC_REQUESTS_PER_SECOND, 10 writes/s node-wide), so a flood of game traffic can delay chain RPC (and the reverse). At human speed this is fine. The fix is to give game routes their own RpcBudget, which means mounting them ahead of the shared budget in server/testnet/http.ts: a change to that shared file, so it's proposed in #6 rather than made tonight.