Night 1: peer-hosted game modes, with schema, node API, host credit and 3 example modes (#22)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 05:05:38 +00:00
co-authored by Claude Opus 5.5
parent 6bd2dab74b
commit 4a4941c6ff
19 changed files with 1973 additions and 0 deletions
+257
View File
@@ -0,0 +1,257 @@
# 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:
```json
{
"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):
```yaml
# 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.
## 4. Credit for hosts
Every mode shows **"Hosted by &lt;operator&gt;"** (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.
+55
View File
@@ -0,0 +1,55 @@
/**
* Operator configuration for hosted modes. Everything comes from the operator's own
* environment and files; nothing here is learned from peers.
*
* WIKIDECK_MODES comma list of built-in mode ids and/or JSON file paths
* (default "classic"; "none" hosts nothing but still discovers)
* WIKIDECK_MODES_DIR optional directory: every *.json in it is a mode
* WIKIDECK_GAME_OPERATOR name shown as "Hosted by ..." (default: the origin's host name)
* WIKIDECK_GAME_NOTE optional short note shown with the host
* WIKIDECK_GAME_PEERS peer origins whose modes to list (default: WIKIDECK_PEERS)
* PUBLIC_ORIGIN this node's public origin (the host identity)
*/
import { readFileSync, readdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { HostIdentitySchema, MAX_MODES_PER_NODE, parseModeJson, type HostIdentity, type ModeDocument } from '../../shared/game/modes.ts';
import { parsePeerOrigins } from './discovery.ts';
export const BUILTIN_MODES_DIR = fileURLToPath(new URL('./modes/', import.meta.url));
export const BUILTIN_MODE_IDS = ['classic', 'trending', 'draft'] as const;
export function loadModes(env: NodeJS.ProcessEnv = process.env): ModeDocument[] {
const modes: ModeDocument[] = [];
const spec = (env.WIKIDECK_MODES ?? 'classic').trim();
if (spec !== 'none') for (const item of spec.split(',').map(s => s.trim()).filter(Boolean)) {
if ((BUILTIN_MODE_IDS as readonly string[]).includes(item)) modes.push(readMode(join(BUILTIN_MODES_DIR, `${item}.json`)));
else if (item.endsWith('.json')) modes.push(readMode(resolve(item)));
else throw new Error(`WIKIDECK_MODES: unknown built-in mode "${item.slice(0, 40)}" (use ${BUILTIN_MODE_IDS.join(', ')} or a .json path)`);
}
if (env.WIKIDECK_MODES_DIR) {
const dir = resolve(env.WIKIDECK_MODES_DIR);
for (const f of readdirSync(dir).filter(f => f.endsWith('.json')).sort()) modes.push(readMode(join(dir, f)));
}
if (modes.length > MAX_MODES_PER_NODE) throw new Error(`At most ${MAX_MODES_PER_NODE} modes per node`);
const ids = new Set<string>();
for (const m of modes) { if (ids.has(m.id)) throw new Error(`Duplicate mode id ${m.id}`); ids.add(m.id); }
return modes;
}
function readMode(path: string): ModeDocument {
try { return parseModeJson(readFileSync(path, 'utf8')); }
catch (e) { throw new Error(`Invalid mode file ${path}: ${(e as Error).message.slice(0, 300)}`); }
}
export function hostIdentity(env: NodeJS.ProcessEnv = process.env): HostIdentity {
const origin = new URL(env.PUBLIC_ORIGIN ?? `http://127.0.0.1:${env.PORT ?? 3001}`).origin;
return HostIdentitySchema.parse({ origin, operator: (env.WIKIDECK_GAME_OPERATOR ?? new URL(origin).host).slice(0, 48),
...(env.WIKIDECK_GAME_NOTE ? { note: env.WIKIDECK_GAME_NOTE.slice(0, 120) } : {}) });
}
export function gamePeers(env: NodeJS.ProcessEnv = process.env): string[] {
const self = hostIdentity(env).origin;
return parsePeerOrigins(env.WIKIDECK_GAME_PEERS ?? env.WIKIDECK_PEERS, env.WIKIDECK_ALLOW_PRIVATE_PEERS === '1')
.filter(o => o !== self);
}
+93
View File
@@ -0,0 +1,93 @@
/**
* Discover the modes of explicitly configured peers. No discovery service, no gossip:
* the operator lists peer origins (WIKIDECK_GAME_PEERS, else WIKIDECK_PEERS). Each peer's
* GET /api/game/modes is fetched with a timeout, a byte cap and no redirects, then parsed
* strictly as data. The fetched origin replaces whatever origin the peer claims.
*/
import { parseModeList, MAX_MODE_LIST_BYTES, type ModeList } from '../../shared/game/modes.ts';
export type PeerModes = { origin: string; ok: boolean; error?: string; fetchedAt: number; rejected?: number; list?: ModeList };
export type Fetcher = (url: string, init: { signal: AbortSignal; redirect: 'error'; headers: Record<string, string> }) => Promise<Response>;
export function parsePeerOrigins(raw: string | undefined, allowPrivate: boolean): string[] {
const out = new Set<string>();
for (const text of (raw ?? '').split(',').map(s => s.trim()).filter(Boolean)) {
if (text.length > 256 || !/^https?:\/\/[^/?#\\@\s]+\/?$/i.test(text)) throw new Error(`Invalid game peer origin: ${text.slice(0, 80)}`);
const url = new URL(text);
if (url.protocol !== 'https:' && !(allowPrivate && url.protocol === 'http:')) throw new Error('Game peers must be HTTPS (or HTTP with WIKIDECK_ALLOW_PRIVATE_PEERS=1)');
out.add(url.origin);
}
if (out.size > 16) throw new Error('At most 16 game peers');
return [...out];
}
export class ModeDiscovery {
private readonly peers: string[];
private readonly fetcher: Fetcher;
private readonly ttlMs: number;
private readonly timeoutMs: number;
private readonly cache = new Map<string, PeerModes>();
private inflight: Promise<PeerModes[]> | null = null;
private readonly now: () => number;
constructor(options: { peers: string[]; fetcher?: Fetcher; ttlMs?: number; timeoutMs?: number; now?: () => number }) {
this.peers = options.peers;
this.fetcher = options.fetcher ?? ((url, init) => fetch(url, init));
this.ttlMs = options.ttlMs ?? 30_000;
this.timeoutMs = options.timeoutMs ?? 3_000;
this.now = options.now ?? Date.now;
}
/** Cached peer results; refreshes stale entries at most once concurrently. */
async all(): Promise<PeerModes[]> {
const now = this.now();
const stale = this.peers.some(p => { const c = this.cache.get(p); return !c || now - c.fetchedAt > this.ttlMs; });
if (stale) {
this.inflight ??= Promise.all(this.peers.map(p => this.fetchPeer(p))).finally(() => { this.inflight = null; });
await this.inflight;
}
return this.peers.map(p => this.cache.get(p)!).filter(Boolean);
}
private async fetchPeer(origin: string): Promise<PeerModes> {
const fetchedAt = this.now();
let result: PeerModes;
try {
const signal = AbortSignal.timeout(this.timeoutMs);
const res = await this.fetcher(`${origin}/api/game/modes`, { signal, redirect: 'error', headers: { accept: 'application/json' } });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await readCapped(res, MAX_MODE_LIST_BYTES);
const { list, rejected } = parseModeList(body);
// The peer may claim any operator name, but not any origin: we know where we fetched it.
result = { origin, ok: true, fetchedAt, rejected, list: { ...list, host: { ...list.host, origin } } };
} catch (e) {
const previous = this.cache.get(origin);
result = { origin, ok: false, error: describe(e), fetchedAt, ...(previous?.list ? { list: previous.list } : {}) };
}
this.cache.set(origin, result);
return result;
}
}
async function readCapped(res: Response, max: number): Promise<string> {
const declared = Number(res.headers.get('content-length') ?? 0);
if (declared > max) throw new Error('Mode list too large');
if (!res.body) return '';
const reader = res.body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > max) { await reader.cancel(); throw new Error('Mode list too large'); }
chunks.push(value);
}
return new TextDecoder().decode(Buffer.concat(chunks));
}
function describe(e: unknown): string {
const m = e instanceof Error ? e.message : String(e);
return (m.includes('too large') ? 'response too large' : m.includes('abort') || m.includes('timeout') ? 'timeout'
: /^HTTP \d+$/.test(m) ? m : e instanceof SyntaxError ? 'invalid JSON' : 'invalid or unreachable').slice(0, 80);
}
+74
View File
@@ -0,0 +1,74 @@
/** Binds the mode host to the real engine through its public API (shared/game/index.ts). */
import { DEFAULT_RULESET, parseRuleset, starterDeck, loanerCard, STARTER_POOL, validateDeck, createMatch,
legalActions, applyAction, isOver, result, viewFor, Rng,
type Action, type GameCard, type MatchState, type Ruleset } from '../../shared/game/index.ts';
import type { EnginePort, Seat } from './engine-port.ts';
/**
* Deterministic pool of loaner (non-NFT) cards for draft modes: seeded shuffles of the
* starter pool, one copy per round, never exceeding the ruleset's per-page copy limit.
*/
export function previewPool(rules: Ruleset, seed: string, size: number): GameCard[] {
const rng = Rng.fromSeed(`draft-pool:${seed}`);
const pool: GameCard[] = [];
for (let copy = 0; pool.length < size && copy < rules.maxCopiesPerPage; copy++) {
for (const spec of rng.shuffle(STARTER_POOL)) { if (pool.length >= size) break; pool.push(loanerCard(spec, copy)); }
}
return pool;
}
/**
* The engine's strict parseRuleset, plus host-side checks that keep a hosted mode playable
* (requested in review on #6). Anything that fails is rejected at startup, never passed on.
*/
export const UNSAFE_KEYWORDS: readonly string[] = ['obscure'];
export function parseModeRuleset(value: unknown): Ruleset {
const rules = parseRuleset(value);
const problems: string[] = [];
if (rules.distinctStats && rules.topicCount !== 3) problems.push('distinctStats requires topicCount 3');
if (rules.portalReveal.some(turn => turn > rules.turns)) problems.push('every portalReveal turn must be ≤ turns');
if (rules.energyByTurn.length < rules.turns) problems.push('energyByTurn needs one entry per turn');
if (rules.turns * rules.turnSeconds > 240) problems.push('turns × turnSeconds must be ≤ 240');
if (rules.powerByCost.length !== 7) problems.push('powerByCost needs 7 entries');
// Keywords whose hidden information viewFor doesn't mask yet would leak cards to the opponent (#6, #27).
for (const id of UNSAFE_KEYWORDS) if ((rules.keywordsEnabled as readonly string[]).includes(id)) problems.push(`keyword "${id}" is not hostable yet (viewFor does not mask it)`);
if (problems.length) throw new Error(`Invalid mode rules: ${problems.join('; ')}`);
return rules;
}
export const engineBinding: EnginePort<Ruleset, GameCard, MatchState, Action> = {
defaultRuleset: DEFAULT_RULESET,
parseRuleset: parseModeRuleset,
deckSize: rules => rules.deckSize,
starterDeck: (_rules, seed) => starterDeck(seed),
previewPool,
validateDeck: (rules, cards) => {
const problems = validateDeck(rules, cards);
if (problems.length) throw new Error(problems.slice(0, 3).join('; '));
},
cardPower: card => card.power,
withPower: (card, power) => ({ ...card, power: Math.min(30, Math.max(0, power)) }),
cardPageId: card => card.pageId,
cardSummary: card => ({ cardId: card.cardId, title: card.title, pageId: card.pageId, faction: card.faction,
cost: card.cost, power: card.power, home: card.home, trend: card.trend, keyword: card.keyword }),
createMatch: (rules, decks, seed) => createMatch(rules, decks, seed),
legalActions: (state, seat) => legalActions(state, seat),
applyAction: (state, seat: Seat, action) => {
if (action.player !== seat) throw new Error('Action for the wrong seat');
return applyAction(state, action);
},
concedeAction: seat => ({ type: 'concede', player: seat }),
timeoutAction: seat => ({ type: 'timeout', player: seat }),
turnSeconds: rules => rules.turnSeconds,
turnOf: state => state.turn,
// DESIGN §1.6: the live trend arrow, frozen at match start, using the ruleset's thresholds.
applyLive: (rules, card, live) => {
const t = live.trendPercent;
const trend = t === null || !Number.isFinite(t) ? 0 : t >= rules.trendUp ? 1 : t <= rules.trendDown ? -1 : 0;
return { ...card, trend };
},
isOver,
result: state => { const r = result(state); return { winner: r?.winner ?? null, reason: r?.reason ?? 'complete' }; },
viewFor: (state, seat) => viewFor(state, seat),
};
+43
View File
@@ -0,0 +1,43 @@
/**
* The slice of the engine API (docs/game/ENGINE_API.md) the mode host uses.
* The host is engine-agnostic behind this port: the real binding lives in engine-binding.ts,
* tests use a tiny stub. Card and state values are opaque to the host.
*/
export type Seat = 0 | 1;
export type MatchOutcome = { winner: Seat | null; reason?: string };
export interface EnginePort<Rules = unknown, Card = unknown, State = unknown, Action = unknown> {
readonly defaultRuleset: Rules;
/** Strict engine-side validation of a merged ruleset. Throws on anything invalid. */
parseRuleset(value: unknown): Rules;
deckSize(rules: Rules): number;
starterDeck(rules: Rules, seed: string): Card[];
/** Deterministic pool of non-NFT preview cards, for draft modes. */
previewPool(rules: Rules, seed: string, size: number): Card[];
/** Throws if the deck is not legal under the rules. */
validateDeck(rules: Rules, cards: Card[]): void;
cardPower(card: Card): number;
withPower(card: Card, power: number): Card;
/** Wikipedia page id of a card, if it has one (for live/trending mappings). */
cardPageId(card: Card): number | null;
/** Public, JSON-safe summary shown in a draft pool. */
cardSummary(card: Card): unknown;
createMatch(rules: Rules, decks: [Card[], Card[]], seed: string): State;
legalActions(state: State, seat: Seat): Action[];
applyAction(state: State, seat: Seat, action: Action): State;
/** Optional engine-level concede, so a resignation is part of the replayable action log. */
concedeAction?(seat: Seat): Action;
/** Optional host-only timeout action, applied when a seat runs out of turn time. */
timeoutAction?(seat: Seat): Action;
/** Optional per-turn time limit from the ruleset, in seconds. */
turnSeconds?(rules: Rules): number;
/** Optional current turn number, so the host can time turns rather than actions. */
turnOf?(state: State): number;
/** Optional: freeze live data onto a card at match start (e.g. a trend arrow). */
applyLive?(rules: Rules, card: Card, live: { trendPercent: number | null }): Card;
isOver(state: State): boolean;
result(state: State): MatchOutcome;
/** What one seat may see (hides the opponent's hand and staged plays). */
viewFor(state: State, seat: Seat): unknown;
}
+357
View File
@@ -0,0 +1,357 @@
/**
* Hosts lobbies and matches for this node's modes, with the deterministic engine.
* All state is off-chain and in memory; finished matches go to the MatchStore.
*
* Trust model: the host is authoritative for its own matches. Players are identified by a
* client-held secret (only its SHA-256 is stored or shown) and act through per-seat bearer
* tokens. Every action must equal one of the engine's legalActions for that seat.
*/
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { modeKey, resolveRuleset, trendBonus, clampPower, MODE_SCHEMA_VERSION,
type HostIdentity, type ModeDocument, type ModeList, type ModeStats, type LiveCardData } from '../../shared/game/modes.ts';
import type { EnginePort, Seat } from './engine-port.ts';
import { MatchStore, type MatchRecord } from './store.ts';
export class GameError extends Error {
readonly status: number;
constructor(status: number, message: string) { super(message); this.status = status; }
}
type Player = { id: string; name: string; tokenHash: Buffer; seen: number };
type Phase = 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
type Lobby = {
id: string; mode: ModeDocument; rules: unknown; seed: string; createdAt: number;
players: Player[]; phase: Phase;
draft?: { pool: unknown[]; taken: (Seat | null)[]; order: Seat[]; turn: number; deadline: number };
decks?: [unknown[], unknown[]];
state?: unknown; actions: { seat: Seat; action: unknown }[]; startedAt?: number; lastMove: number; turnStartedAt?: number; turn?: number;
outcome?: { winner: Seat | null; reason: string }; matchId?: string;
};
type HostedMode = { mode: ModeDocument; rules: unknown };
export type HostOptions = {
identity: HostIdentity;
modes: ModeDocument[];
engine: EnginePort<any, any, any, any>;
store: MatchStore;
/** Optional live Wikipedia trend lookup for `trending` modes. Failures mean "no bonus". */
liveData?: (pageId: number) => Promise<LiveCardData | null>;
now?: () => number;
/** Node-wide cap on lobbies + matches in memory across all modes. */
maxLobbies?: number;
};
export type SeatTicket = { lobbyId: string; seat: Seat; token: string };
const NAME = /^[\p{L}\p{N} _.\-]{1,24}$/u;
const SECRET = /^[A-Za-z0-9_-]{22,128}$/;
const LOBBY_ID = /^[a-f0-9]{24}$/;
export class ModeHost {
readonly identity: HostIdentity;
private readonly engine: EnginePort<any, any, any, any>;
private readonly store: MatchStore;
private readonly hosted = new Map<string, HostedMode>();
private readonly lobbies = new Map<string, Lobby>();
private readonly liveData?: HostOptions['liveData'];
private readonly now: () => number;
private readonly maxLobbies: number;
constructor(options: HostOptions) {
this.identity = options.identity;
this.engine = options.engine;
this.store = options.store;
this.liveData = options.liveData;
this.now = options.now ?? Date.now;
this.maxLobbies = options.maxLobbies ?? 512;
for (const mode of options.modes) {
if (this.hosted.has(mode.id)) throw new Error(`Duplicate mode id ${mode.id}`);
// Validate rules once at startup with the engine's own parser: a bad mode fails loudly.
const rules = resolveRuleset(this.engine.defaultRuleset, mode.rules, v => this.engine.parseRuleset(v));
if (mode.decks.kind === 'draft' && mode.decks.poolSize < 2 * this.engine.deckSize(rules)) {
throw new Error(`Mode ${mode.id}: draft poolSize must be at least 2 × deck size`);
}
if (mode.decks.kind !== 'draft') {
// Host-dealt starter decks must be legal under the mode's rules, or the mode is unplayable.
try { this.engine.validateDeck(rules, this.engine.starterDeck(rules, 'startup-check')); }
catch (e) { throw new Error(`Mode ${mode.id}: starter decks are illegal under its rules (${(e as Error).message.slice(0, 120)}); use a draft deck policy`); }
}
this.hosted.set(mode.id, { mode, rules });
}
}
/** Body of GET /api/game/modes. */
list(): ModeList {
return { schema: MODE_SCHEMA_VERSION, host: this.identity, matchesHosted: this.store.total,
modes: [...this.hosted.values()].map(h => ({ mode: h.mode, stats: this.stats(h.mode.id) })) };
}
stats(modeId: string): ModeStats {
let online = 0, open = 0, live = 0;
for (const l of this.lobbies.values()) {
if (l.mode.id !== modeId) continue;
if (l.phase === 'waiting') open++;
if (l.phase === 'starting' || l.phase === 'drafting' || l.phase === 'playing') live++;
if (l.phase !== 'finished' && l.phase !== 'expired') online += l.players.length;
}
return { playersOnline: online, openLobbies: open, liveMatches: live,
matchesPlayed: this.store.modeMatches(modeId), distinctPlayers: this.store.modePlayers(modeId) };
}
leaderboard(modeId: string) {
const h = this.mode(modeId);
return { host: this.identity, mode: { id: h.mode.id, version: h.mode.version, name: h.mode.name },
key: modeKey(this.identity.origin, h.mode), entries: this.store.leaderboard(modeId) };
}
openLobbies(modeId: string) {
this.mode(modeId);
return [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting')
.slice(0, 50).map(l => ({ lobbyId: l.id, host: l.players[0]!.name, createdAt: l.createdAt }));
}
createLobby(modeId: string, player: { name: unknown; secret: unknown }): SeatTicket {
const h = this.mode(modeId);
this.sweep();
const active = [...this.lobbies.values()].filter(l => l.phase !== 'finished' && l.phase !== 'expired');
if (active.length >= this.maxLobbies) throw new GameError(503, 'This host is full; try again later.');
if (active.filter(l => l.mode.id === modeId).length >= h.mode.limits.maxConcurrentMatches) {
throw new GameError(503, 'This mode is at its match limit on this host; try again later.');
}
const p = this.player(player);
if (active.filter(l => l.players.some(x => x.id === p.player.id)).length >= 3) {
throw new GameError(429, 'Too many open lobbies or matches for this player.');
}
const id = randomBytes(12).toString('hex');
const now = this.now();
this.lobbies.set(id, { id, mode: h.mode, rules: h.rules, seed: randomBytes(16).toString('hex'), createdAt: now,
players: [p.player], phase: 'waiting', actions: [], lastMove: now });
return { lobbyId: id, seat: 0, token: p.token };
}
async join(lobbyId: string, player: { name: unknown; secret: unknown }): Promise<SeatTicket> {
const l = this.lobby(lobbyId);
this.sweep();
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
const p = this.player(player);
if (l.players[0]!.id === p.player.id) throw new GameError(409, 'You cannot play against yourself.');
l.players.push(p.player);
l.lastMove = this.now();
// Claim the lobby before any await, so a concurrent join can't also pass the 'waiting' check.
l.phase = 'starting';
if (l.mode.decks.kind === 'draft') this.startDraft(l);
else await this.startMatch(l, [this.engine.starterDeck(l.rules, `${l.seed}:0`), this.engine.starterDeck(l.rules, `${l.seed}:1`)]);
return { lobbyId: l.id, seat: 1, token: p.token };
}
/** Public status, plus the seat's private view when a valid token is given. */
view(lobbyId: string, token?: string) {
const l = this.lobby(lobbyId);
this.sweep();
const seat = token ? this.seatFor(l, token) : null;
const base = { lobbyId: l.id, phase: l.phase, host: this.identity,
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name },
players: l.players.map(p => ({ id: p.id, name: p.name })), seat, matchId: l.matchId ?? null,
outcome: l.outcome ?? null };
if (l.phase === 'drafting' && l.draft) {
const d = l.draft;
return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: this.engine.cardSummary(c), takenBy: d.taken[i] })),
toPick: d.order[d.turn] ?? null, deadline: d.deadline } };
}
if ((l.phase === 'playing' || l.phase === 'finished') && l.state !== undefined && seat !== null) {
return { ...base, state: this.engine.viewFor(l.state, seat),
legalActions: l.phase === 'playing' ? this.engine.legalActions(l.state, seat) : [] };
}
return base;
}
async pick(lobbyId: string, token: string, index: unknown) {
const l = this.lobby(lobbyId);
const seat = this.requireSeat(l, token);
this.sweep();
if (l.phase !== 'drafting' || !l.draft) throw new GameError(409, 'Not drafting.');
if (l.draft.order[l.draft.turn] !== seat) throw new GameError(409, 'Not your pick.');
if (typeof index !== 'number' || !Number.isInteger(index) || index < 0 || index >= l.draft.pool.length ||
l.draft.taken[index] !== null) throw new GameError(400, 'Invalid pick.');
await this.takePick(l, seat, index);
return this.view(lobbyId, token);
}
async act(lobbyId: string, token: string, action: unknown) {
const l = this.lobby(lobbyId);
const seat = this.requireSeat(l, token);
this.sweep();
if (l.phase !== 'playing' || l.state === undefined) throw new GameError(409, 'No match in progress.');
// The host never trusts a client action: it must be one of the engine's legal actions.
const legal = this.engine.legalActions(l.state, seat);
const chosen = legal.find(a => isDeepStrictEqual(a, action));
if (chosen === undefined) throw new GameError(400, 'Illegal action.');
this.apply(l, seat, chosen);
l.players[seat]!.seen = l.lastMove;
return this.view(lobbyId, token);
}
resign(lobbyId: string, token: string) {
const l = this.lobby(lobbyId);
const seat = this.requireSeat(l, token);
if (l.phase === 'waiting') { l.phase = 'expired'; return this.view(lobbyId, token); }
if (l.phase !== 'playing' && l.phase !== 'drafting') throw new GameError(409, 'Nothing to resign.');
if (l.phase === 'playing' && l.state !== undefined && this.engine.concedeAction) {
this.apply(l, seat, this.engine.concedeAction(seat), 'resign');
if ((l.phase as Phase) === 'finished') return this.view(lobbyId, token);
}
this.finish(l, seat === 0 ? 1 : 0, 'resign');
return this.view(lobbyId, token);
}
matchRecord(matchId: string): MatchRecord {
if (!/^[a-f0-9]{32}$/.test(matchId)) throw new GameError(400, 'Invalid match id.');
const r = this.store.get(matchId);
if (!r) throw new GameError(404, 'Match not found on this host.');
return r;
}
/** Expire idle lobbies, auto-pick stalled drafts, forfeit stalled matches, drop old lobbies. */
sweep(): void {
const now = this.now();
for (const l of this.lobbies.values()) {
if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) l.phase = 'expired';
else if (l.phase === 'drafting' && l.draft && now > l.draft.deadline) {
// Auto-pick the first free card for whoever is stalling; synchronous, no live data.
const idx = l.draft.taken.indexOf(null);
if (idx >= 0) void this.takePick(l, l.draft.order[l.draft.turn]!, idx).catch(() => { l.phase = 'expired'; });
} else if (l.phase === 'playing' && l.state !== undefined && now - (l.turnStartedAt ?? l.lastMove) > this.turnMs(l)) {
const waiting = ([0, 1] as Seat[]).filter(s => this.engine.legalActions(l.state, s).length > 0);
if (this.engine.timeoutAction) {
// The engine decides what a timeout means (auto-commit, AFK forfeit); it is logged and replayable.
for (const s of waiting) if (l.phase === 'playing') this.apply(l, s, this.engine.timeoutAction(s));
l.turnStartedAt = now;
} else if (waiting.length === 1) this.finish(l, waiting[0] === 0 ? 1 : 0, 'timeout');
else this.finish(l, null, 'abandoned');
}
if ((l.phase === 'finished' || l.phase === 'expired') && now - l.lastMove > 10 * 60_000) this.lobbies.delete(l.id);
}
}
private startDraft(l: Lobby) {
if (l.mode.decks.kind !== 'draft') return;
const size = this.engine.deckSize(l.rules);
const pool = this.engine.previewPool(l.rules, `${l.seed}:pool`, l.mode.decks.poolSize);
if (pool.length < 2 * size) throw new GameError(500, 'Engine returned a short draft pool.');
// Snake order 0,1,1,0,0,1,... with a seed-chosen first picker.
const first: Seat = parseInt(l.seed.slice(0, 2), 16) % 2 === 0 ? 0 : 1;
const order: Seat[] = [];
for (let i = 0; i < 2 * size; i++) order.push(((Math.floor((i + 1) / 2) % 2 === 0 ? first : 1 - first)) as Seat);
l.draft = { pool, taken: pool.map(() => null), order, turn: 0, deadline: this.now() + l.mode.decks.pickSeconds * 1000 };
l.phase = 'drafting';
}
private async takePick(l: Lobby, seat: Seat, index: number) {
const d = l.draft!;
d.taken[index] = seat;
d.turn++;
l.lastMove = this.now();
if (l.mode.decks.kind === 'draft') d.deadline = this.now() + l.mode.decks.pickSeconds * 1000;
if (d.turn >= d.order.length) {
const decks: [unknown[], unknown[]] = [[], []];
d.taken.forEach((s, i) => { if (s !== null) decks[s].push(d.pool[i]); });
await this.startMatch(l, decks);
}
}
private async startMatch(l: Lobby, decks: [unknown[], unknown[]]) {
const mapped = await Promise.all(decks.map(d => this.mapDeck(l.mode, d))) as [unknown[], unknown[]];
for (const d of mapped) {
try { this.engine.validateDeck(l.rules, d); }
catch (e) { l.phase = 'expired'; throw new GameError(400, `Deck rejected by the engine: ${(e as Error).message}`.slice(0, 200)); }
}
l.decks = mapped;
l.state = this.engine.createMatch(l.rules, mapped, l.seed);
l.phase = 'playing';
l.startedAt = l.lastMove = l.turnStartedAt = this.now();
l.turn = this.engine.turnOf?.(l.state);
delete l.draft;
if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, r.reason ?? 'complete'); }
}
/** Apply the mode's card-mapping preset. Bonus data is looked up once, before the match. */
private async mapDeck(mode: ModeDocument, deck: unknown[]): Promise<unknown[]> {
const mapping = mode.cards;
if (mapping.preset === 'standard' || !this.liveData) return deck;
return Promise.all(deck.map(async card => {
const pageId = this.engine.cardPageId(card);
if (pageId === null) return card;
const live = await this.liveData!(pageId).catch(() => null);
if (!live) return card;
// `live` and `trending`: freeze the live trend arrow onto the card (engine rules decide its effect).
let mapped = this.engine.applyLive ? this.engine.applyLive(this.hosted.get(mode.id)!.rules, card, live) : card;
if (mapping.preset === 'trending') {
const bonus = trendBonus(mapping, live.trendPercent);
if (bonus !== 0) mapped = this.engine.withPower(mapped, clampPower(this.engine.cardPower(mapped) + bonus));
}
return mapped;
}));
}
/** Apply an action already known to be legal (or host-issued), log it, and settle the match if over. */
private apply(l: Lobby, seat: Seat, action: unknown, reason?: string) {
l.state = this.engine.applyAction(l.state, seat, action);
l.actions.push({ seat, action });
l.lastMove = this.now();
const turn = this.engine.turnOf?.(l.state);
if (turn !== l.turn) { l.turn = turn; l.turnStartedAt = l.lastMove; }
if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, reason ?? r.reason ?? 'complete'); }
else if (l.actions.length >= 2000) this.finish(l, null, 'action-limit');
}
/** Turn timer: the engine's own per-turn limit plus a little network grace, else the mode's limit. */
private turnMs(l: Lobby): number {
const engineSeconds = this.engine.turnSeconds?.(l.rules);
return engineSeconds !== undefined ? (engineSeconds + 5) * 1000 : l.mode.limits.turnSeconds * 1000;
}
private finish(l: Lobby, winner: Seat | null, reason: string) {
if (l.phase === 'finished' || l.phase === 'expired') return;
l.phase = 'finished';
l.outcome = { winner, reason };
l.lastMove = this.now();
if (!l.decks || l.players.length !== 2) return; // Resigned during draft: no match record.
const matchId = randomBytes(16).toString('hex');
l.matchId = matchId;
this.store.add({ matchId, modeId: l.mode.id, modeVersion: l.mode.version, seed: l.seed, rules: l.rules,
players: l.players.map(p => ({ id: p.id, name: p.name })), winner, reason: reason.slice(0, 40),
startedAt: l.startedAt ?? l.createdAt, endedAt: l.lastMove, decks: l.decks, actions: l.actions });
}
private mode(modeId: string): HostedMode {
const h = typeof modeId === 'string' ? this.hosted.get(modeId) : undefined;
if (!h) throw new GameError(404, 'Mode not hosted here.');
return h;
}
private lobby(lobbyId: string): Lobby {
const l = typeof lobbyId === 'string' && LOBBY_ID.test(lobbyId) ? this.lobbies.get(lobbyId) : undefined;
if (!l) throw new GameError(404, 'Lobby not found.');
return l;
}
private player(input: { name: unknown; secret: unknown }): { player: Player; token: string } {
const name = typeof input.name === 'string' ? input.name.trim() : '';
if (!NAME.test(name)) throw new GameError(400, 'Name must be 1-24 letters, digits, spaces, _ . or -');
if (typeof input.secret !== 'string' || !SECRET.test(input.secret)) throw new GameError(400, 'Invalid player secret.');
const id = createHash('sha256').update(`wikideck-player:${input.secret}`).digest('hex');
const token = randomBytes(24).toString('base64url');
return { player: { id, name, tokenHash: hashToken(token), seen: this.now() }, token };
}
private seatFor(l: Lobby, token: string): Seat | null {
const h = hashToken(token);
const i = l.players.findIndex(p => timingSafeEqual(p.tokenHash, h));
return i === 0 || i === 1 ? i : null;
}
private requireSeat(l: Lobby, token: string): Seat {
const s = typeof token === 'string' ? this.seatFor(l, token) : null;
if (s === null) throw new GameError(403, 'Not a player in this lobby.');
return s;
}
}
function hashToken(token: string): Buffer { return createHash('sha256').update(token).digest(); }
+45
View File
@@ -0,0 +1,45 @@
/**
* Entry point for the game-modes API. server/testnet/http.ts mounts it with one line:
* app.use('/api/game', await (await import('../game/index.ts')).gameRouter({ dataDir, enrichment: wikipediaEnrichment }));
*/
import { join } from 'node:path';
import type express from 'express';
import { loadModes, hostIdentity, gamePeers } from './config.ts';
import { ModeDiscovery } from './discovery.ts';
import { ModeHost } from './host.ts';
import { createGameRouter } from './router.ts';
import { MatchStore } from './store.ts';
import type { EnginePort } from './engine-port.ts';
import { TrendCache } from './trends.ts';
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean }): Promise<express.Router> {
const env = options.env ?? process.env;
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
const modes = loadModes(env);
// Trends come from a slowly warmed, cache-only store: never a Wikipedia call per match.
let trends: TrendCache | undefined;
if (options.enrichment && modes.some(m => m.cards.preset === 'trending')) {
const enrichment = options.enrichment;
// Wikipedia egress is shared and rate-limited: default one page per 20 s (≥ 15 s enforced).
const interval = Number(env.WIKIDECK_GAME_TREND_INTERVAL_MS ?? 20_000);
if (!Number.isSafeInteger(interval) || interval < 15_000 || interval > 3_600_000) throw new Error('WIKIDECK_GAME_TREND_INTERVAL_MS must be 15000..3600000');
trends = new TrendCache(pageId => enrichment.get(pageId), { intervalMs: interval });
for (const card of engine.starterDeck(engine.defaultRuleset, 'trend-warmup')) {
const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id);
}
for (const card of engine.previewPool(engine.defaultRuleset, 'trend-warmup', 64)) {
const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id);
}
if (options.warmTrends !== false) trends.start();
}
const host = new ModeHost({ identity: hostIdentity(env), modes, engine,
store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null),
liveData: trends ? async pageId => trends!.get(pageId) : undefined });
const discovery = new ModeDiscovery({ peers: gamePeers(env) });
const timer = setInterval(() => host.sweep(), 5_000);
timer.unref();
return createGameRouter(host, discovery);
}
+12
View File
@@ -0,0 +1,12 @@
{
"schema": "wikideck.mode/1",
"id": "classic",
"version": 1,
"name": "Classic",
"description": "The base WikiDeck rules with starter decks. Cards use their at-mint snapshot stats.",
"tags": ["base", "starter"],
"rules": {},
"cards": { "preset": "standard" },
"decks": { "kind": "starter" },
"limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 }
}
+28
View File
@@ -0,0 +1,28 @@
{
"schema": "wikideck.mode/1",
"id": "draft",
"version": 1,
"name": "Snake Draft",
"description": "Both players snake-draft 10-card decks from one shared, host-seeded pool of 30 preview cards, then play the base rules with a 4-card opening hand. Nobody brings cards, so everyone starts even.",
"tags": [
"draft",
"no-collection"
],
"rules": {
"deckSize": 10,
"openingHand": 4
},
"cards": {
"preset": "standard"
},
"decks": {
"kind": "draft",
"poolSize": 30,
"pickSeconds": 30
},
"limits": {
"maxConcurrentMatches": 16,
"turnSeconds": 90,
"lobbyMinutes": 15
}
}
+29
View File
@@ -0,0 +1,29 @@
{
"schema": "wikideck.mode/1",
"id": "trending",
"version": 1,
"name": "Trending",
"description": "Live Wikipedia pageview trends matter both ways: cards get the live trend arrow (up at +25%, down at -25%, where the base rules ignore falls), plus +1 power per 25% rise and -1 per 25% fall, capped at 3 either way.",
"tags": [
"live-data",
"starter"
],
"rules": {
"trendUp": 25,
"trendDown": -25
},
"cards": {
"preset": "trending",
"percentPerPoint": 25,
"maxBonus": 3,
"penalise": true
},
"decks": {
"kind": "starter"
},
"limits": {
"maxConcurrentMatches": 32,
"turnSeconds": 90,
"lobbyMinutes": 15
}
}
+70
View File
@@ -0,0 +1,70 @@
/**
* /api/game routes: publish, discover and host modes. Additive; nothing here reads or writes
* the ledger. Mounted by server/testnet/http.ts via server/game/index.ts.
*/
import express, { type Request, type Response, type NextFunction } from 'express';
import rateLimit from 'express-rate-limit';
import type { ModeHost } from './host.ts';
import { GameError } from './host.ts';
import type { ModeDiscovery } from './discovery.ts';
const limiter = (limit: number) => rateLimit({ windowMs: 60_000, limit, standardHeaders: 'draft-8', legacyHeaders: false });
export function createGameRouter(host: ModeHost, discovery: ModeDiscovery): express.Router {
const r = express.Router();
const reads = limiter(240), writes = limiter(60), plays = limiter(240), network = limiter(30);
const wrap = (fn: (req: Request, res: Response) => unknown) => async (req: Request, res: Response, next: NextFunction) => {
try { const out = await fn(req, res); if (!res.headersSent) res.json(out); } catch (e) { next(e); }
};
const bearer = (req: Request) => {
const h = req.get('authorization') ?? '';
return /^Bearer [A-Za-z0-9_-]{16,64}$/.test(h) ? h.slice(7) : '';
};
const body = (req: Request) => (req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}) as Record<string, unknown>;
// Publish: this node's modes, host identity, stats.
r.get('/modes', reads, wrap(() => host.list()));
// Discover: this node plus every configured peer, as data. The browser opens a peer's own
// site to play there (CSP keeps API calls same-origin).
r.get('/network/modes', network, wrap(async () => {
const peers = await discovery.all();
return { self: host.list(), peers: peers.map(p => ({ origin: p.origin, ok: p.ok, error: p.error ?? null,
fetchedAt: p.fetchedAt, rejectedModes: p.rejected ?? 0, list: p.list ?? null })) };
}));
// Host leaderboard: matches hosted per node (self-reported by peers; see HOSTING.md).
r.get('/hosts/leaderboard', network, wrap(async () => {
const self = host.list();
const rows = [{ ...summary(self), self: true, reachable: true }];
for (const p of await discovery.all()) if (p.list) rows.push({ ...summary(p.list), self: false, reachable: p.ok });
rows.sort((a, b) => b.matchesHosted - a.matchesHosted || a.origin.localeCompare(b.origin));
return { hosts: rows };
}));
r.get('/modes/:modeId/leaderboard', reads, wrap(req => host.leaderboard(String(req.params.modeId))));
r.get('/modes/:modeId/lobbies', reads, wrap(req => ({ lobbies: host.openLobbies(String(req.params.modeId)) })));
r.post('/modes/:modeId/lobbies', writes, wrap((req, res) => {
const b = body(req);
res.status(201);
return host.createLobby(String(req.params.modeId), { name: b.name, secret: b.secret });
}));
r.post('/lobbies/:lobbyId/join', writes, wrap(req => {
const b = body(req);
return host.join(String(req.params.lobbyId), { name: b.name, secret: b.secret });
}));
r.get('/lobbies/:lobbyId', plays, wrap(req => host.view(String(req.params.lobbyId), bearer(req) || undefined)));
r.post('/lobbies/:lobbyId/pick', plays, wrap(req => host.pick(String(req.params.lobbyId), bearer(req), body(req).index)));
r.post('/lobbies/:lobbyId/actions', plays, wrap(req => host.act(String(req.params.lobbyId), bearer(req), body(req).action)));
r.post('/lobbies/:lobbyId/resign', writes, wrap(req => host.resign(String(req.params.lobbyId), bearer(req))));
// Finished match records: seed, decks and action log, so anyone can replay and audit them.
r.get('/matches/:matchId', reads, wrap(req => host.matchRecord(String(req.params.matchId))));
r.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {
if (err instanceof GameError) { res.status(err.status).json({ error: err.message }); return; }
next(err);
});
return r;
}
function summary(list: { host: { origin: string; operator: string }; matchesHosted: number; modes: { stats: { playersOnline: number; distinctPlayers: number } }[] }) {
return { origin: list.host.origin, operator: list.host.operator, matchesHosted: list.matchesHosted,
modes: list.modes.length, playersOnline: list.modes.reduce((n, m) => n + m.stats.playersOnline, 0) };
}
+87
View File
@@ -0,0 +1,87 @@
/**
* Off-chain match records for this node: an append-only JSON-lines file plus in-memory
* aggregates (leaderboards, host totals). Nothing here touches the ledger.
*/
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { z } from 'zod';
export const MatchRecordSchema = z.object({
matchId: z.string().regex(/^[a-f0-9]{32}$/),
modeId: z.string().max(40),
modeVersion: z.number().int(),
/** Host-chosen seed. Together with decks and actions it lets anyone replay the match. */
seed: z.string().max(128),
/** The resolved ruleset the match ran under (mode overrides already applied). */
rules: z.unknown(),
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24) }).strict()).length(2),
winner: z.union([z.literal(0), z.literal(1), z.null()]),
reason: z.string().max(40),
startedAt: z.number().int(),
endedAt: z.number().int(),
decks: z.array(z.array(z.unknown()).max(64)).length(2),
actions: z.array(z.object({ seat: z.union([z.literal(0), z.literal(1)]), action: z.unknown() }).strict()).max(2000),
}).strict();
export type MatchRecord = z.infer<typeof MatchRecordSchema>;
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number };
type ModeAgg = { matches: number; players: Map<string, LeaderboardEntry> };
const KEEP_RECENT = 500;
export class MatchStore {
private readonly file: string | null;
private readonly modes = new Map<string, ModeAgg>();
private readonly recent = new Map<string, MatchRecord>();
private readonly allPlayers = new Set<string>();
total = 0;
/** `directory` null keeps records in memory only (tests). */
constructor(directory: string | null) {
this.file = directory ? join(directory, 'matches.jsonl') : null;
if (!directory || !this.file) return;
mkdirSync(directory, { recursive: true, mode: 0o700 });
if (!existsSync(this.file)) return;
for (const line of readFileSync(this.file, 'utf8').split('\n')) {
if (!line.trim()) continue;
const parsed = MatchRecordSchema.safeParse(safeJson(line));
if (parsed.success) this.index(parsed.data); // A torn last line after a crash is skipped.
}
}
add(record: MatchRecord): void {
const valid = MatchRecordSchema.parse(record);
if (this.file) appendFileSync(this.file, JSON.stringify(valid) + '\n', { mode: 0o600 });
this.index(valid);
}
get(matchId: string): MatchRecord | undefined { return this.recent.get(matchId); }
modeMatches(modeId: string): number { return this.modes.get(modeId)?.matches ?? 0; }
modePlayers(modeId: string): number { return this.modes.get(modeId)?.players.size ?? 0; }
distinctPlayers(): number { return this.allPlayers.size; }
leaderboard(modeId: string, limit = 20): LeaderboardEntry[] {
const players = [...(this.modes.get(modeId)?.players.values() ?? [])];
return players.sort((a, b) => b.wins - a.wins || a.losses - b.losses || b.played - a.played ||
a.playerId.localeCompare(b.playerId)).slice(0, limit).map(p => ({ ...p }));
}
private index(r: MatchRecord): void {
this.total++;
const agg = this.modes.get(r.modeId) ?? { matches: 0, players: new Map() };
this.modes.set(r.modeId, agg);
agg.matches++;
r.players.forEach((p, seat) => {
this.allPlayers.add(p.id);
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0 };
e.name = p.name; e.played++;
if (r.winner === null) e.draws++; else if (r.winner === seat) e.wins++; else e.losses++;
agg.players.set(p.id, e);
});
this.recent.set(r.matchId, r);
if (this.recent.size > KEEP_RECENT) this.recent.delete(this.recent.keys().next().value!);
}
}
function safeJson(line: string): unknown { try { return JSON.parse(line); } catch { return null; } }
+58
View File
@@ -0,0 +1,58 @@
/**
* Live pageview trends for `trending` modes, read from cache only at match time.
* Wikipedia egress is shared and rate-limited, so lookups never happen in a request path:
* unknown pages are queued and fetched one at a time, slowly, through the node's existing
* enrichment cache. Until a page is warm, its cards simply get no trend bonus.
*/
import type { LiveCardData } from '../../shared/game/modes.ts';
type Source = (pageId: number) => Promise<{ pageviews: { trendPercent: number | null } }>;
export class TrendCache {
private readonly values = new Map<number, { trend: number | null; at: number }>();
private readonly queue: number[] = [];
private readonly queued = new Set<number>();
private timer: ReturnType<typeof setInterval> | undefined;
private busy = false;
private readonly source: Source;
private readonly options: { intervalMs?: number; ttlMs?: number; maxEntries?: number; now?: () => number };
constructor(source: Source, options: { intervalMs?: number; ttlMs?: number; maxEntries?: number; now?: () => number } = {}) {
this.source = source; this.options = options;
}
/** Cache-only lookup; schedules a background fetch when missing or stale. */
get(pageId: number): LiveCardData | null {
const v = this.values.get(pageId);
const now = (this.options.now ?? Date.now)();
if (!v || now - v.at > (this.options.ttlMs ?? 6 * 3600_000)) this.enqueue(pageId);
return v ? { trendPercent: v.trend } : null;
}
enqueue(pageId: number): void {
if (!Number.isSafeInteger(pageId) || pageId <= 0 || this.queued.has(pageId) || this.queue.length >= 256) return;
this.queued.add(pageId); this.queue.push(pageId);
}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.step(), this.options.intervalMs ?? 20_000);
this.timer.unref();
}
stop(): void { if (this.timer) clearInterval(this.timer); this.timer = undefined; }
/** Fetch at most one page. Exposed for tests. */
async step(): Promise<void> {
if (this.busy) return;
const pageId = this.queue.shift();
if (pageId === undefined) return;
this.busy = true;
try {
const data = await this.source(pageId);
const trend = data.pageviews.trendPercent;
this.values.set(pageId, { trend: typeof trend === 'number' && Number.isFinite(trend) ? trend : null, at: (this.options.now ?? Date.now)() });
while (this.values.size > (this.options.maxEntries ?? 512)) this.values.delete(this.values.keys().next().value!);
} catch { /* Leave it cold; it is re-queued on a later lookup. */ }
finally { this.queued.delete(pageId); this.busy = false; }
}
}
+1
View File
@@ -151,6 +151,7 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{
res.status(202).json({id,status:'pending'});
});
app.use('/api/account',createAccountRouter({dataDir}));
app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment}));
app.use(['/api','/p2p'],(_req,res)=>{res.status(404).json({error:'Unknown testnet endpoint'});});
app.use(express.static(resolve(root,'dist')));
app.get('/{*path}',(_req,res)=>res.sendFile(resolve(root,'dist/index.html')));
+230
View File
@@ -0,0 +1,230 @@
/**
* Peer-hosted game modes: a mode is DATA, never code.
*
* A mode is a small JSON document: base-rule overrides (applied on top of the engine's
* default `Ruleset` and re-validated by the engine's own ruleset parser), a card-mapping
* preset chosen from a fixed list, a deck policy, limits, and display text.
* A peer never executes, evals or imports anything another peer sends; it only parses
* this schema with hard size limits. See docs/game/HOSTING.md.
*
* No I/O here: shared by the server (host + discovery) and the browser (lobby).
*/
import { z } from 'zod';
export const MODE_SCHEMA_VERSION = 'wikideck.mode/1' as const;
/** Upper bound on the JSON size of one mode document, before parsing. */
export const MAX_MODE_BYTES = 8 * 1024;
/** Upper bound on modes one node may publish (and that discovery accepts from one peer). */
export const MAX_MODES_PER_NODE = 16;
/** Upper bound on the JSON size of a whole /api/game/modes response read from a peer. */
export const MAX_MODE_LIST_BYTES = 192 * 1024;
const slug = z.string().regex(/^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$/, 'lowercase slug, 3-40 chars');
/** Plain display text: no control characters, no angle brackets (rendered as text anyway). */
const text = (max: number) => z.string().trim().min(1).max(max)
.refine(s => !/[\u0000-\u001f\u007f<>]/.test(s), 'plain text only');
/**
* Rule overrides: a shallow-ish, bounded JSON object of numbers, booleans, short strings and
* short arrays of those. Its *meaning* is decided by the engine's ruleset schema, which runs
* after the merge (see `resolveRuleset`). This schema only guarantees it is small and inert.
*/
const scalar = z.union([z.number().finite(), z.boolean(), z.string().max(64)]);
const leaf = z.union([scalar, z.array(scalar).max(32)]);
const level2 = z.record(z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,39}$/), leaf)
.refine(o => Object.keys(o).length <= 32, 'too many keys');
export const RuleOverridesSchema = z.record(z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,39}$/),
z.union([leaf, level2])).refine(o => Object.keys(o).length <= 48, 'too many rule overrides');
export type RuleOverrides = z.infer<typeof RuleOverridesSchema>;
/**
* How Wikipedia data becomes card numbers in this mode. A fixed list of presets implemented
* in this file; a mode only picks one and tunes bounded parameters.
* - `standard`: the engine's default mapping from the immutable at-mint snapshot.
* - `live`: the same mapping, but from live current values when available.
* - `trending`: standard, plus a power bonus/penalty from live `pageviews.trendPercent`.
*/
export const CardMappingSchema = z.discriminatedUnion('preset', [
z.object({ preset: z.literal('standard') }).strict(),
z.object({ preset: z.literal('live') }).strict(),
z.object({ preset: z.literal('trending'),
/** Trend percent per +1 power (e.g. 25 → +25% trend gives +1). */
percentPerPoint: z.number().int().min(5).max(500).default(25),
/** Clamp on the bonus, in either direction. */
maxBonus: z.number().int().min(0).max(5).default(3),
/** Whether falling trends reduce power (never below 0). */
penalise: z.boolean().default(true),
}).strict(),
]);
export type CardMapping = z.infer<typeof CardMappingSchema>;
/** Where match decks come from. Matches never move or burn NFTs, whatever the policy. */
export const DeckPolicySchema = z.discriminatedUnion('kind', [
/** Each player brings a deck (starter deck or own cards, validated by the engine). */
z.object({ kind: z.literal('constructed'), allowStarter: z.boolean().default(true) }).strict(),
/** Host-seeded starter decks only: everyone gets the engine's `starterDeck(seed)`. */
z.object({ kind: z.literal('starter') }).strict(),
/** Snake draft from a host-seeded pool of non-NFT preview cards. */
z.object({ kind: z.literal('draft'),
/** Cards in the shared pool; must be at least 2 × the ruleset's deck size. */
poolSize: z.number().int().min(8).max(64).default(30),
/** Seconds per pick before the host auto-picks the first card. */
pickSeconds: z.number().int().min(5).max(120).default(30),
}).strict(),
]);
export type DeckPolicy = z.infer<typeof DeckPolicySchema>;
export const ModeLimitsSchema = z.object({
/** Concurrent open lobbies + live matches this mode may hold on the host. */
maxConcurrentMatches: z.number().int().min(1).max(256).default(32),
/** Seconds a player may take for one action before forfeiting the turn/match. */
turnSeconds: z.number().int().min(10).max(600).default(90),
/** Lobbies with no opponent expire after this many minutes. */
lobbyMinutes: z.number().int().min(1).max(120).default(15),
}).strict();
export type ModeLimits = z.infer<typeof ModeLimitsSchema>;
/** The mode document an operator writes (and peers publish). */
export const ModeSchema = z.object({
schema: z.literal(MODE_SCHEMA_VERSION),
id: slug,
/** Monotonic integer; bump when the rules change so old match records stay attributable. */
version: z.number().int().min(1).max(1_000_000),
name: text(48),
description: text(400),
tags: z.array(slug).max(5).default([]),
/** Overrides on top of the engine's DEFAULT_RULESET. */
rules: RuleOverridesSchema.default({}),
cards: CardMappingSchema.default({ preset: 'standard' }),
decks: DeckPolicySchema.default({ kind: 'constructed', allowStarter: true }),
limits: ModeLimitsSchema.default({ maxConcurrentMatches: 32, turnSeconds: 90, lobbyMinutes: 15 }),
}).strict();
export type ModeDocument = z.infer<typeof ModeSchema>;
export type ModeInput = z.input<typeof ModeSchema>;
/**
* The host's identity, configured by the node operator (never taken from a mode file).
* Discovery overwrites `origin` with the URL it actually fetched, so a peer can't
* publish modes in another node's name.
*/
export const HostIdentitySchema = z.object({
origin: z.string().url().max(256),
operator: text(48),
/** Optional short note, e.g. "EU, best effort". */
note: text(120).optional(),
}).strict();
export type HostIdentity = z.infer<typeof HostIdentitySchema>;
export const ModeStatsSchema = z.object({
playersOnline: z.number().int().min(0).max(1_000_000),
openLobbies: z.number().int().min(0).max(1_000_000),
liveMatches: z.number().int().min(0).max(1_000_000),
matchesPlayed: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
distinctPlayers: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
}).strict();
export type ModeStats = z.infer<typeof ModeStatsSchema>;
/** One entry of GET /api/game/modes. */
export const PublishedModeSchema = z.object({ mode: ModeSchema, stats: ModeStatsSchema }).strict();
export type PublishedMode = z.infer<typeof PublishedModeSchema>;
/** Body of GET /api/game/modes. */
export const ModeListSchema = z.object({
schema: z.literal(MODE_SCHEMA_VERSION),
host: HostIdentitySchema,
/** Total matches this node has hosted, across all its modes and versions. */
matchesHosted: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
modes: z.array(PublishedModeSchema).max(MAX_MODES_PER_NODE),
}).strict();
export type ModeList = z.infer<typeof ModeListSchema>;
/** Parse untrusted mode JSON text with a byte limit before JSON.parse. */
export function parseModeJson(json: string): ModeDocument {
if (byteLength(json) > MAX_MODE_BYTES) throw new Error(`Mode document exceeds ${MAX_MODE_BYTES} bytes`);
return parseMode(JSON.parse(json));
}
export function parseMode(value: unknown): ModeDocument {
assertInertKeys(value);
const mode = ModeSchema.parse(value);
if (byteLength(JSON.stringify(mode)) > MAX_MODE_BYTES) throw new Error(`Mode document exceeds ${MAX_MODE_BYTES} bytes`);
return mode;
}
/** Parse an untrusted peer's mode list. Invalid individual modes are dropped, not fatal. */
export function parseModeList(json: string): { list: ModeList; rejected: number } {
if (byteLength(json) > MAX_MODE_LIST_BYTES) throw new Error('Mode list too large');
const raw = z.object({ modes: z.array(z.unknown()).max(MAX_MODES_PER_NODE) }).passthrough().parse(JSON.parse(json));
let rejected = 0;
const modes: PublishedMode[] = [];
for (const entry of raw.modes) {
const parsed = hasForbiddenKeys(entry) ? null : PublishedModeSchema.safeParse(entry);
if (parsed?.success && byteLength(JSON.stringify(parsed.data.mode)) <= MAX_MODE_BYTES) modes.push(parsed.data);
else rejected++;
}
return { list: ModeListSchema.parse({ ...raw, modes }), rejected };
}
/** Stable key for a mode on a host: `<origin>#<id>@<version>`. */
export function modeKey(origin: string, mode: Pick<ModeDocument, 'id' | 'version'>): string {
return `${origin}#${mode.id}@${mode.version}`;
}
const BLOCKED_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
/**
* Merge overrides onto the engine's base ruleset, then validate with the engine's parser.
* Objects merge one level deep; arrays and scalars replace. Unknown keys are left for the
* engine parser to reject (it is strict), so a mode can never smuggle in unchecked rules.
*/
export function resolveRuleset<R>(base: R, overrides: RuleOverrides, parse: (value: unknown) => R): R {
const merged: Record<string, unknown> = structuredClone(base) as Record<string, unknown>;
for (const [key, value] of Object.entries(overrides)) {
if (BLOCKED_KEYS.has(key)) throw new Error('Forbidden rule key');
const current = merged[key];
if (isPlainObject(value) && isPlainObject(current)) {
const inner: Record<string, unknown> = { ...current };
for (const [k, v] of Object.entries(value)) {
if (BLOCKED_KEYS.has(k)) throw new Error('Forbidden rule key');
inner[k] = v;
}
merged[key] = inner;
} else merged[key] = value;
}
return parse(merged);
}
/** Live Wikipedia trend data a card mapping may read (subset of PageEnrichment). */
export type LiveCardData = { trendPercent: number | null };
/**
* Apply the mode's card-mapping preset to a card's base power. Pure and bounded.
* `standard`/`live` differ only in which stats the caller fed the engine's card builder.
*/
export function mappedPower(basePower: number, mapping: CardMapping, live?: LiveCardData): number {
if (mapping.preset !== 'trending') return basePower;
return basePower + trendBonus(mapping, live?.trendPercent ?? null);
}
export function trendBonus(mapping: Extract<CardMapping, { preset: 'trending' }>, trendPercent: number | null): number {
if (trendPercent === null || !Number.isFinite(trendPercent)) return 0;
let bonus = Math.trunc(trendPercent / mapping.percentPerPoint);
if (!mapping.penalise) bonus = Math.max(0, bonus);
return Math.max(-mapping.maxBonus, Math.min(mapping.maxBonus, bonus));
}
/** Clamp a mapped power the same way regardless of preset: never negative. */
export function clampPower(power: number): number { return Math.max(0, Math.round(power)); }
/** Reject prototype-polluting keys anywhere (zod's record() does not check them reliably). */
function hasForbiddenKeys(value: unknown, depth = 0): boolean {
if (depth > 8 || typeof value !== 'object' || value === null) return depth > 8;
for (const key of Object.keys(value)) {
if (BLOCKED_KEYS.has(key)) return true;
if (hasForbiddenKeys((value as Record<string, unknown>)[key], depth + 1)) return true;
}
return false;
}
function assertInertKeys(value: unknown): void {
if (hasForbiddenKeys(value)) throw new Error('Forbidden key in mode document');
}
function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
function byteLength(s: string): number { return new TextEncoder().encode(s).length; }
+209
View File
@@ -0,0 +1,209 @@
// End to end over HTTP with the real engine: publish, discover, host all three example modes.
import test from 'node:test';
import assert from 'node:assert/strict';
import express from 'express';
import type { AddressInfo } from 'node:net';
import { gameRouter } from '../server/game/index.ts';
import { previewPool } from '../server/game/engine-binding.ts';
import { DEFAULT_RULESET, STARTER_POOL, replay, parseRuleset } from '../shared/game/index.ts';
import { parseMode, resolveRuleset, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
import { ModeListSchema } from '../shared/game/modes.ts';
async function serve(env: NodeJS.ProcessEnv, enrichment?: any) {
const app = express();
app.use(express.json({ limit: '68kb' }));
app.use('/api/game', await gameRouter({ dataDir: null, env, enrichment }));
app.use((err: Error, _q: express.Request, res: express.Response, _n: express.NextFunction) => res.status(400).json({ error: err.message }));
const server = app.listen(0, '127.0.0.1');
await new Promise(r => server.once('listening', r));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
return { base, close: () => new Promise(r => server.close(r)) };
}
const call = async (base: string, path: string, body?: unknown, token?: string) => {
const res = await fetch(base + path, { method: body === undefined ? 'GET' : 'POST',
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body) });
return { status: res.status, json: await res.json() as any };
};
const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' };
const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' };
async function playToEnd(base: string, lobby: string, tokens: string[]) {
for (let i = 0; i < 400; i++) {
let moved = false;
for (const t of tokens) {
const v = (await call(base, `/api/game/lobbies/${lobby}`, undefined, t)).json;
if (v.phase !== 'playing') return v;
// Play the first card if possible, else end the turn.
const a = v.legalActions.find((x: any) => x.type === 'play') ?? v.legalActions.find((x: any) => x.type === 'commit');
if (a) { const r = await call(base, `/api/game/lobbies/${lobby}/actions`, { action: a }, t); assert.equal(r.status, 200, JSON.stringify(r.json)); moved = true; }
}
if (!moved) break;
}
return (await call(base, `/api/game/lobbies/${lobby}`, undefined, tokens[0])).json;
}
test('modes api: three example modes over HTTP with the real engine', { timeout: 60_000 }, async () => {
const node = await serve({ WIKIDECK_MODES: 'classic,trending,draft', PUBLIC_ORIGIN: 'http://127.0.0.1:3101',
WIKIDECK_GAME_OPERATOR: 'Node A', WIKIDECK_GAME_PEERS: '' },
{ get: async (pageId: number) => ({ pageviews: { trendPercent: pageId % 3 === 0 ? 80 : -30 } }) });
try {
const list = (await call(node.base, '/api/game/modes')).json;
ModeListSchema.parse(list);
assert.deepEqual(list.modes.map((m: any) => m.mode.id), ['classic', 'trending', 'draft']);
assert.equal(list.host.operator, 'Node A');
for (const id of ['classic', 'trending']) {
const a = await call(node.base, `/api/game/modes/${id}/lobbies`, alice);
assert.equal(a.status, 201);
const b = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/join`, bob);
assert.equal(b.status, 200, JSON.stringify(b.json));
const peek = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`)).json;
assert.equal(peek.state, undefined);
const wrongSeat = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`, undefined, a.json.token)).json.legalActions[0];
const cheat = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/actions`, { action: { ...wrongSeat, player: 1 } }, a.json.token);
assert.equal(cheat.status, 400, 'cannot act for the other seat');
const end = await playToEnd(node.base, a.json.lobbyId, [a.json.token, b.json.token]);
assert.equal(end.phase, 'finished', JSON.stringify(end).slice(0, 300));
const rec = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
assert.equal(rec.modeId, id);
assert.equal(rec.decks[0].length, 12);
}
// Draft: 20 snake picks, 10-card decks.
const a = (await call(node.base, '/api/game/modes/draft/lobbies', alice)).json;
const b = (await call(node.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
const tokens = [a.token, b.token];
let picks = 0;
for (;;) {
const v = (await call(node.base, `/api/game/lobbies/${a.lobbyId}`, undefined, a.token)).json;
if (v.phase !== 'drafting') { assert.equal(v.phase, 'playing'); break; }
const free = v.draft.pool.find((c: any) => c.takenBy === null);
const r = await call(node.base, `/api/game/lobbies/${a.lobbyId}/pick`, { index: free.index }, tokens[v.draft.toPick]);
assert.equal(r.status, 200, JSON.stringify(r.json));
picks++;
}
assert.equal(picks, 20);
const end = await playToEnd(node.base, a.lobbyId, tokens);
assert.equal(end.phase, 'finished');
const record = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
assert.equal(record.decks[1].length, 10);
// Anyone can audit a match: replaying the published record reproduces the result.
const replayed = replay(record.rules, record.decks, record.seed, record.actions.map((a: any) => a.action));
assert.equal(replayed.phase, 'over');
assert.equal(replayed.result?.winner ?? null, record.winner);
const after = (await call(node.base, '/api/game/modes')).json;
assert.equal(after.matchesHosted, 3);
const board = (await call(node.base, '/api/game/modes/draft/leaderboard')).json;
assert.equal(board.entries.length, 2);
assert.equal((await call(node.base, '/api/game/modes/nope/leaderboard')).status, 404);
assert.equal((await call(node.base, '/api/game/lobbies/zzz')).status, 404);
} finally { await node.close(); }
});
test('modes api: a node lists its peers\' modes and ranks hosts by matches hosted', { timeout: 30_000 }, async () => {
const peerB = await serve({ WIKIDECK_MODES: 'draft,classic', PUBLIC_ORIGIN: 'http://b.invalid', WIKIDECK_GAME_OPERATOR: 'Node B' });
const nodeA = await serve({ WIKIDECK_MODES: 'classic', PUBLIC_ORIGIN: 'http://a.invalid', WIKIDECK_GAME_OPERATOR: 'Node A',
WIKIDECK_GAME_PEERS: `${peerB.base},http://127.0.0.1:1`, WIKIDECK_ALLOW_PRIVATE_PEERS: '1' });
try {
// One match on B so it leads the host leaderboard.
const a = (await call(peerB.base, '/api/game/modes/draft/lobbies', alice)).json;
const b = (await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/resign`, {}, b.token); // during the draft: not a match
const c = (await call(peerB.base, '/api/game/modes/classic/lobbies', alice)).json;
const d = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/join`, bob)).json;
assert.equal((await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/resign`, {}, d.token)).json.outcome.winner, 0);
const resigned = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}`, undefined, c.token)).json;
const rec = (await call(peerB.base, `/api/game/matches/${resigned.matchId}`)).json;
assert.equal(replay(rec.rules, rec.decks, rec.seed, rec.actions.map((x: any) => x.action)).result?.winner, 0, 'resign replays as concede');
const net = (await call(nodeA.base, '/api/game/network/modes')).json;
assert.equal(net.self.host.operator, 'Node A');
assert.equal(net.peers.length, 2);
assert.equal(net.peers[0].ok, true);
assert.equal(net.peers[0].list.host.origin, peerB.base, 'origin pinned to the fetched peer');
assert.equal(net.peers[0].list.modes[0].mode.id, 'draft');
assert.equal(net.peers[1].ok, false);
const hosts = (await call(nodeA.base, '/api/game/hosts/leaderboard')).json.hosts;
assert.deepEqual(hosts.map((h: any) => [h.operator, h.matchesHosted]), [['Node B', 1], ['Node A', 0]]);
} finally { await nodeA.close(); await peerB.close(); }
});
test('modes api: draft preview pool is deterministic and deck-legal', () => {
const p1 = previewPool(DEFAULT_RULESET, 'seed', 30), p2 = previewPool(DEFAULT_RULESET, 'seed', 30);
assert.deepEqual(p1, p2);
assert.equal(p1.length, 30);
assert.equal(new Set(p1.map(c => c.cardId)).size, 30);
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.maxCopiesPerPage);
});
test('modes api: the rule examples in HOSTING.md are valid modes', () => {
for (const rules of [
{ turns: 4, energyByTurn: [3, 4, 5, 6] },
{ onTopicBonus: [0, 2, 2, 3, 3, 4, 4], trendUp: 10, trendDown: -10 },
{ deckSize: 16, maxCopiesPerPage: 2, maxLoaners: 16 },
{ turns: 6, turnSeconds: 40 },
]) {
const m = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'doc-example', version: 1, name: 'x', description: 'x', rules });
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, m.rules, parseRuleset), JSON.stringify(rules));
}
});
test('modes api: mode rules that make starter decks illegal fail at startup; live trend arrows follow the ruleset', async () => {
const { ModeHost } = await import('../server/game/host.ts');
const { MatchStore } = await import('../server/game/store.ts');
const { engineBinding } = await import('../server/game/engine-binding.ts');
const big = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'big', version: 1, name: 'Big', description: 'x',
decks: { kind: 'starter' }, rules: { deckSize: 16, maxLoaners: 16 } });
assert.throws(() => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [big], engine: engineBinding,
store: new MatchStore(null) }), /starter decks are illegal/);
const card = engineBinding.starterDeck(DEFAULT_RULESET, 's')[0]!;
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 30 }).trend, 1);
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: DEFAULT_RULESET.trendDown - 1 }).trend, -1);
assert.equal(engineBinding.applyLive!({ ...DEFAULT_RULESET, trendDown: -25 }, card, { trendPercent: -30 }).trend, -1);
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 5 }).trend, 0);
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: null }).trend, 0);
assert.equal(engineBinding.withPower(card, 99).power, 30, 'power stays within engine bounds');
});
test('modes api: turn timer applies the engine timeout action; AFK forfeits are replayable', async () => {
const { ModeHost } = await import('../server/game/host.ts');
const { MatchStore } = await import('../server/game/store.ts');
const { engineBinding } = await import('../server/game/engine-binding.ts');
let now = 0;
const classic = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } });
const host = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [classic], engine: engineBinding,
store: new MatchStore(null), now: () => now });
const a = host.createLobby('classic', alice);
const b = await host.join(a.lobbyId, bob);
// Bob plays normally; Alice never acts.
for (let turn = 0; turn < 6; turn++) {
const v = host.view(a.lobbyId, b.token) as any;
if (v.phase !== 'playing') break;
await host.act(a.lobbyId, b.token, { type: 'commit', player: 1 });
now += (DEFAULT_RULESET.turnSeconds + 6) * 1000; host.sweep();
}
const end = host.view(a.lobbyId, a.token) as any;
assert.equal(end.phase, 'finished');
assert.deepEqual(end.outcome, { winner: 1, reason: 'afk' });
const rec = host.matchRecord(end.matchId);
assert.ok(rec.actions.some(x => (x.action as any).type === 'timeout'));
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner, 1);
});
test('modes api: mode rules are checked beyond the engine schema and rejected, not passed on', async () => {
const { parseModeRuleset } = await import('../server/game/engine-binding.ts');
const bad = [
{ turns: 2, energyByTurn: [1, 2] }, // portalReveal has a turn > 2
{ distinctStats: true, topicCount: 2, portalReveal: [1, 2] },
{ turns: 12, turnSeconds: 25, energyByTurn: Array(12).fill(3), portalReveal: [1, 2, 3] },
{ powerByCost: [0, 1, 2] },
{ mulligan: true },
{ keywordParams: { notAKeyword: { amount: 1 } } },
{ keywordsEnabled: [...DEFAULT_RULESET.keywordsEnabled, 'obscure'] },
];
for (const rules of bad) assert.throws(() => resolveRuleset(DEFAULT_RULESET, rules as any, parseModeRuleset), JSON.stringify(rules));
assert.throws(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'obscure'] }, parseModeRuleset), /not hostable/);
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'edition', 'wildcard'] }, parseModeRuleset));
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, {}, parseModeRuleset));
});
+196
View File
@@ -0,0 +1,196 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { parseMode, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
import { ModeHost, GameError } from '../server/game/host.ts';
import { MatchStore } from '../server/game/store.ts';
import { ModeDiscovery } from '../server/game/discovery.ts';
import { stubEngine } from './modes-stub-engine.ts';
const mode = (over: object = {}) => parseMode({ schema: MODE_SCHEMA_VERSION, id: 'stub', version: 1, name: 'Stub',
description: 'Stub mode.', decks: { kind: 'starter' }, ...over });
const identity = { origin: 'http://node-a.test', operator: 'Alice' };
const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' };
const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' };
function playOut(host: ModeHost, lobbyId: string, tokens: string[]) {
for (let guard = 0; guard < 50; guard++) {
const v0 = host.view(lobbyId, tokens[0]) as any;
if (v0.phase !== 'playing') return v0;
for (const t of tokens) {
const v = host.view(lobbyId, t) as any;
if (v.legalActions?.length) void host.act(lobbyId, t, v.legalActions[0]);
}
}
throw new Error('did not finish');
}
test('modes host: lobby → match → record → leaderboard and host credit', async () => {
let now = 1_000_000;
const store = new MatchStore(null);
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store, now: () => now });
const a = host.createLobby('stub', alice);
assert.equal(host.list().modes[0]!.stats.openLobbies, 1);
assert.deepEqual(host.openLobbies('stub').map(l => l.host), ['Alice']);
const b = await host.join(a.lobbyId, bob);
assert.equal(b.seat, 1);
assert.equal((host.view(a.lobbyId) as any).state, undefined, 'spectators see no private state');
const end = playOut(host, a.lobbyId, [a.token, b.token]);
assert.equal(end.phase, 'finished');
const list = host.list();
assert.equal(list.matchesHosted, 1);
assert.equal(list.host.operator, 'Alice');
assert.equal(list.modes[0]!.stats.matchesPlayed, 1);
assert.equal(list.modes[0]!.stats.distinctPlayers, 2);
const board = host.leaderboard('stub');
assert.equal(board.entries.length, 2);
assert.equal(board.key, 'http://node-a.test#stub@1');
const rec = host.matchRecord(end.matchId);
assert.equal(rec.actions.length, 6);
assert.equal(rec.players[0]!.name, 'Alice');
assert.ok(!JSON.stringify(rec).includes(alice.secret), 'secrets are never stored');
});
test('modes host: actions must be legal and from the right seat', async () => {
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store: new MatchStore(null) });
const a = host.createLobby('stub', alice);
const b = await host.join(a.lobbyId, bob);
await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 99 }), /Illegal/);
await assert.rejects(host.act(a.lobbyId, 'not-a-token-xxxxxxxxxxxx', { type: 'play', card: 0 }), /Not a player/);
await host.act(a.lobbyId, a.token, { type: 'play', card: 0 });
await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 0 }), /Illegal/, 'no double play');
await host.act(a.lobbyId, b.token, { card: 1, type: 'play' }); // key order doesn't matter
await assert.rejects(host.join(a.lobbyId, { name: 'Eve', secret: 'eve-secret-0123456789abcdefgh' }), /no longer open/);
assert.throws(() => host.createLobby('stub', { name: '<script>', secret: alice.secret }), GameError);
assert.throws(() => host.createLobby('stub', { name: 'Al', secret: 'short' }), GameError);
assert.throws(() => host.createLobby('nope', alice), /not hosted/);
});
test('modes host: limits, expiry and turn timeouts', async () => {
let now = 0;
const host = new ModeHost({ identity, modes: [mode({ limits: { maxConcurrentMatches: 2, turnSeconds: 10, lobbyMinutes: 1 } })],
engine: stubEngine, store: new MatchStore(null), now: () => now });
const l1 = host.createLobby('stub', alice);
host.createLobby('stub', bob);
assert.throws(() => host.createLobby('stub', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' }), /match limit/);
now += 61_000; host.sweep();
assert.equal((host.view(l1.lobbyId) as any).phase, 'expired');
const l3 = host.createLobby('stub', alice);
const t3 = await host.join(l3.lobbyId, bob);
await host.act(l3.lobbyId, l3.token, { type: 'play', card: 0 }); // Bob now owes a move
now += 11_000; host.sweep();
const v = host.view(l3.lobbyId, t3.token) as any;
assert.deepEqual(v.outcome, { winner: 0, reason: 'timeout' });
assert.equal(host.list().matchesHosted, 1);
});
test('modes host: snake draft builds both decks from one pool', async () => {
const host = new ModeHost({ identity, modes: [mode({ decks: { kind: 'draft', poolSize: 8, pickSeconds: 10 } })],
engine: stubEngine, store: new MatchStore(null) });
const a = host.createLobby('stub', alice);
const b = await host.join(a.lobbyId, bob);
const tok = [a.token, b.token];
const order: number[] = [];
for (;;) {
const v = host.view(a.lobbyId, a.token) as any;
if (v.phase !== 'drafting') break;
order.push(v.draft.toPick);
const free = v.draft.pool.find((c: any) => c.takenBy === null).index;
await assert.rejects(host.pick(a.lobbyId, tok[1 - v.draft.toPick]!, free), /Not your pick/);
await host.pick(a.lobbyId, tok[v.draft.toPick]!, free);
}
assert.equal(order.length, 8);
assert.deepEqual(order.slice(0, 4), [order[0], 1 - order[0]!, 1 - order[0]!, order[0]], 'snake order');
assert.equal((host.view(a.lobbyId, a.token) as any).phase, 'playing');
assert.throws(() => new ModeHost({ identity, modes: [mode({ decks: { kind: 'draft', poolSize: 8 }, rules: { deckSize: 5 } })],
engine: stubEngine, store: new MatchStore(null) }), /poolSize/);
});
test('modes host: trending mapping adjusts power from live trends, once, bounded', async () => {
const seen: number[] = [];
const host = new ModeHost({ identity, modes: [mode({ cards: { preset: 'trending', percentPerPoint: 10, maxBonus: 2 } })],
engine: stubEngine, store: new MatchStore(null),
liveData: async pageId => { seen.push(pageId); return { trendPercent: pageId % 2 ? 1000 : -1000 }; } });
const a = host.createLobby('stub', alice);
const b = await host.join(a.lobbyId, bob);
const base = stubEngine.starterDeck(stubEngine.defaultRuleset, 'x');
const hand = (host.view(a.lobbyId, a.token) as any).state.hand;
assert.equal(seen.length, 8);
for (const c of hand) assert.ok(c.power >= 0 && c.power <= 11);
void b; void base;
});
test('modes host: bad rules fail at startup, via the engine parser', () => {
assert.throws(() => new ModeHost({ identity, modes: [mode({ rules: { turns: 99 } })], engine: stubEngine, store: new MatchStore(null) }));
assert.throws(() => new ModeHost({ identity, modes: [mode(), mode()], engine: stubEngine, store: new MatchStore(null) }), /Duplicate/);
});
test('modes store: records persist and rebuild aggregates; torn lines are skipped', async () => {
const dir = mkdtempSync(join(tmpdir(), 'modes-store-'));
try {
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store: new MatchStore(dir) });
const a = host.createLobby('stub', alice);
const b = await host.join(a.lobbyId, bob);
playOut(host, a.lobbyId, [a.token, b.token]);
const file = join(dir, 'matches.jsonl');
const { appendFileSync } = await import('node:fs');
appendFileSync(file, '{"torn":');
const reopened = new MatchStore(dir);
assert.equal(reopened.total, 1);
assert.equal(reopened.leaderboard('stub').length, 2);
assert.ok(readFileSync(file, 'utf8').includes('"modeId":"stub"'));
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('modes discovery: peers are fetched as data, origin is pinned, failures are contained', async () => {
const good = { schema: MODE_SCHEMA_VERSION, host: { origin: 'https://evil.example', operator: 'Bob' }, matchesHosted: 7,
modes: [{ mode: mode(), stats: { playersOnline: 1, openLobbies: 1, liveMatches: 0, matchesPlayed: 7, distinctPlayers: 3 } }] };
let calls = 0, now = 0;
const fetcher = async (url: string) => {
calls++;
if (url.startsWith('http://b.test')) return new Response(JSON.stringify(good), { status: 200 });
if (url.startsWith('http://c.test')) return new Response('x'.repeat(400_000), { status: 200 });
throw new Error('connect ECONNREFUSED');
};
const d = new ModeDiscovery({ peers: ['http://b.test', 'http://c.test', 'http://d.test'], fetcher, now: () => now, ttlMs: 1000 });
const peers = await d.all();
assert.equal(peers[0]!.ok, true);
assert.equal(peers[0]!.list!.host.origin, 'http://b.test', 'claimed origin replaced by the fetched one');
assert.equal(peers[1]!.ok, false);
assert.equal(peers[1]!.error, 'response too large');
assert.equal(peers[2]!.error, 'invalid or unreachable');
await d.all();
assert.equal(calls, 3, 'cached within ttl');
now = 5000; await d.all();
assert.equal(calls, 6);
});
test('modes trends: cache-only at match time, warmed one page at a time', async () => {
const { TrendCache } = await import('../server/game/trends.ts');
const calls: number[] = [];
let now = 0;
const t = new TrendCache(async id => { calls.push(id); if (id === 2) throw new Error('rate limited'); return { pageviews: { trendPercent: id * 10 } }; },
{ now: () => now, ttlMs: 1000 });
assert.equal(t.get(1), null, 'cold page: no bonus, no fetch in the request path');
assert.equal(t.get(2), null);
t.get(1);
assert.deepEqual(calls, []);
await t.step(); await t.step();
assert.deepEqual(calls, [1, 2], 'one fetch per step, deduplicated');
assert.deepEqual(t.get(1), { trendPercent: 10 });
assert.equal(t.get(2), null, 'failure stays cold');
now = 5000; t.get(1); await t.step(); await t.step();
assert.deepEqual(calls, [1, 2, 2, 1], 'stale entries are refreshed in the background');
});
test('modes host: two concurrent joins cannot both take the second seat', async () => {
const slow = { ...stubEngine };
const host = new ModeHost({ identity, modes: [mode({ cards: { preset: 'trending' } })], engine: slow, store: new MatchStore(null),
liveData: async () => { await new Promise(r => setTimeout(r, 20)); return { trendPercent: 0 }; } });
const a = host.createLobby('stub', alice);
const results = await Promise.allSettled([host.join(a.lobbyId, bob), host.join(a.lobbyId, { name: 'Eve', secret: 'eve-secret-0123456789abcdefgh' })]);
assert.equal(results.filter(r => r.status === 'fulfilled').length, 1);
assert.equal((host.view(a.lobbyId) as any).players.length, 2);
});
+85
View File
@@ -0,0 +1,85 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { parseMode, parseModeJson, parseModeList, resolveRuleset, trendBonus, mappedPower,
MAX_MODE_BYTES, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
import { BUILTIN_MODES_DIR, BUILTIN_MODE_IDS, loadModes } from '../server/game/config.ts';
import { parsePeerOrigins } from '../server/game/discovery.ts';
import { stubEngine } from './modes-stub-engine.ts';
import { engineBinding } from '../server/game/engine-binding.ts';
const base = { schema: MODE_SCHEMA_VERSION, id: 'my-mode', version: 1, name: 'My mode', description: 'A test mode.' };
test('modes: minimal document gets safe defaults', () => {
const m = parseMode(base);
assert.deepEqual(m.cards, { preset: 'standard' });
assert.equal(m.decks.kind, 'constructed');
assert.equal(m.limits.maxConcurrentMatches, 32);
assert.deepEqual(m.rules, {});
});
test('modes: built-in example modes parse and resolve against the engine ruleset', () => {
for (const id of BUILTIN_MODE_IDS) {
const m = parseModeJson(readFileSync(`${BUILTIN_MODES_DIR}${id}.json`, 'utf8'));
assert.equal(m.id, id);
assert.doesNotThrow(() => resolveRuleset(engineBinding.defaultRuleset, m.rules, engineBinding.parseRuleset));
}
assert.deepEqual(loadModes({ WIKIDECK_MODES: 'classic,draft' }).map(m => m.id), ['classic', 'draft']);
assert.deepEqual(loadModes({ WIKIDECK_MODES: 'none' }), []);
assert.throws(() => loadModes({ WIKIDECK_MODES: 'classic,classic' }), /Duplicate/);
assert.throws(() => loadModes({ WIKIDECK_MODES: '../../etc/passwd' }), /unknown built-in/);
});
test('modes: schema rejects code, markup, unknown fields and oversize documents', () => {
assert.throws(() => parseMode({ ...base, script: 'alert(1)' }));
assert.throws(() => parseMode({ ...base, name: '<img src=x onerror=alert(1)>' }));
assert.throws(() => parseMode({ ...base, id: 'Bad Id' }));
assert.throws(() => parseMode({ ...base, cards: { preset: 'eval', code: 'x' } }));
assert.throws(() => parseMode({ ...base, cards: { preset: 'trending', maxBonus: 99 } }));
assert.throws(() => parseMode({ ...base, limits: { maxConcurrentMatches: 100000 } }));
assert.throws(() => parseMode({ ...base, rules: { deep: { deeper: { deepest: 1 } } } }));
assert.throws(() => parseModeJson(JSON.stringify(base).replace('}', ',"rules":{"__proto__":{"turns":1}}}')));
assert.throws(() => resolveRuleset(stubEngine.defaultRuleset, JSON.parse('{"__proto__":{"turns":1}}'), stubEngine.parseRuleset));
assert.throws(() => parseModeJson(JSON.stringify({ ...base, description: 'x'.repeat(MAX_MODE_BYTES) })), /exceeds|too_big|400/);
const many = Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`k${i}`, i]));
assert.throws(() => parseMode({ ...base, rules: many }));
});
test('modes: rule overrides merge one level deep and the engine parser has the final say', () => {
const r = resolveRuleset(stubEngine.defaultRuleset, { turns: 5, scoring: { tieBreak: 'first' } }, stubEngine.parseRuleset);
assert.deepEqual(r, { deckSize: 4, turns: 5, scoring: { tieBreak: 'first' } });
assert.throws(() => resolveRuleset(stubEngine.defaultRuleset, { turns: 500 }, stubEngine.parseRuleset));
assert.throws(() => resolveRuleset(stubEngine.defaultRuleset, { unknownRule: 1 }, stubEngine.parseRuleset));
assert.deepEqual(stubEngine.defaultRuleset.scoring, { tieBreak: 'draw' }, 'base ruleset is not mutated');
});
test('modes: trending bonus is bounded, optional and symmetric', () => {
const t = parseMode({ ...base, cards: { preset: 'trending' } }).cards;
assert.equal(t.preset, 'trending');
if (t.preset !== 'trending') return;
assert.equal(trendBonus(t, 60), 2);
assert.equal(trendBonus(t, 1000), 3);
assert.equal(trendBonus(t, -1000), -3);
assert.equal(trendBonus(t, null), 0);
assert.equal(trendBonus(t, Number.NaN), 0);
assert.equal(trendBonus({ ...t, penalise: false }, -80), 0);
assert.equal(mappedPower(4, { preset: 'standard' }, { trendPercent: 500 }), 4);
});
test('modes: peer lists drop invalid modes instead of failing, and are size capped', () => {
const good = { mode: parseMode(base), stats: { playersOnline: 0, openLobbies: 0, liveMatches: 0, matchesPlayed: 3, distinctPlayers: 2 } };
const body = { schema: MODE_SCHEMA_VERSION, host: { origin: 'http://a.example', operator: 'A' }, matchesHosted: 3,
modes: [good, { mode: { ...base, id: 'X' }, stats: good.stats }] };
const { list, rejected } = parseModeList(JSON.stringify(body));
assert.equal(list.modes.length, 1);
assert.equal(rejected, 1);
assert.throws(() => parseModeList(' '.repeat(300 * 1024)), /too large/);
});
test('modes: game peers are operator-configured origins only', () => {
assert.deepEqual(parsePeerOrigins('https://a.example, https://a.example/,https://b.example', false), ['https://a.example', 'https://b.example']);
assert.throws(() => parsePeerOrigins('http://a.example', false));
assert.deepEqual(parsePeerOrigins('http://node-b:3001', true), ['http://node-b:3001']);
assert.throws(() => parsePeerOrigins('https://a.example/api', false));
assert.throws(() => parsePeerOrigins('https://user@a.example', false));
});
+44
View File
@@ -0,0 +1,44 @@
// A tiny deterministic stand-in for the real engine, implementing the EnginePort used by
// server/game. Each turn both seats play one card; after `turns` turns, higher total power wins.
import { z } from 'zod';
import type { EnginePort, Seat } from '../server/game/engine-port.ts';
export type StubCard = { id: string; pageId: number | null; power: number };
type Rules = { deckSize: number; turns: number; scoring: { tieBreak: 'draw' | 'first' } };
type State = { rules: Rules; turn: number; hands: StubCard[][]; staged: (number | null)[]; totals: number[] };
const RulesSchema = z.object({ deckSize: z.number().int().min(2).max(20), turns: z.number().int().min(1).max(10),
scoring: z.object({ tieBreak: z.enum(['draw', 'first']) }).strict() }).strict();
function rng(seed: string) { let h = 2166136261; for (const c of seed) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
return () => { h ^= h << 13; h ^= h >>> 17; h ^= h << 5; return (h >>> 0) / 2 ** 32; }; }
const pool = (seed: string, n: number) => { const r = rng(seed);
return Array.from({ length: n }, (_, i) => ({ id: `${seed}-${i}`, pageId: 1000 + i, power: 1 + Math.floor(r() * 9) })); };
export const stubEngine: EnginePort<Rules, StubCard, State, { type: 'play'; card: number }> = {
defaultRuleset: { deckSize: 4, turns: 3, scoring: { tieBreak: 'draw' } },
parseRuleset: v => RulesSchema.parse(v),
deckSize: r => r.deckSize,
starterDeck: (r, seed) => pool(seed, r.deckSize),
previewPool: (_r, seed, n) => pool(seed, n),
validateDeck: (r, cards) => { if (cards.length !== r.deckSize) throw new Error('wrong deck size');
for (const c of cards) if (!Number.isInteger(c.power) || c.power < 0 || c.power > 20) throw new Error('bad card'); },
cardPower: c => c.power,
withPower: (c, power) => ({ ...c, power }),
cardPageId: c => c.pageId,
cardSummary: c => ({ id: c.id, power: c.power }),
createMatch: (rules, decks) => ({ rules, turn: 0, hands: decks.map(d => d.map(c => ({ ...c }))), staged: [null, null], totals: [0, 0] }),
legalActions: (s, seat) => s.turn >= s.rules.turns || s.staged[seat] !== null ? [] :
s.hands[seat]!.map((_, card) => ({ type: 'play' as const, card })),
applyAction: (s, seat, a) => {
const n: State = structuredClone(s);
n.staged[seat] = a.card;
if (n.staged[0] !== null && n.staged[1] !== null) {
for (const p of [0, 1] as Seat[]) { const [c] = n.hands[p]!.splice(n.staged[p]!, 1); n.totals[p]! += c!.power; }
n.staged = [null, null]; n.turn++;
}
return n;
},
isOver: s => s.turn >= s.rules.turns,
result: s => ({ winner: s.totals[0]! > s.totals[1]! ? 0 : s.totals[1]! > s.totals[0]! ? 1 : s.rules.scoring.tieBreak === 'first' ? 0 : null }),
viewFor: (s, seat) => ({ turn: s.turn, hand: s.hands[seat], opponentCards: s.hands[1 - seat]!.length, totals: s.totals, staged: s.staged[seat] }),
};