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

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

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

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

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

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

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

397 lines
20 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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;
}
/**
* Live lobbies and matches as JSON, so a restart (e.g. a redeploy) doesn't lose games.
* Only the host's own data dir ever holds this; token hashes, never tokens, are stored.
*/
snapshot(): string {
const live = [...this.lobbies.values()].filter(l => l.phase === 'waiting' || l.phase === 'drafting' || l.phase === 'playing');
return JSON.stringify({ schema: 'wikideck-live-lobbies/1', savedAt: this.now(), lobbies: live.map(l => ({
...l, mode: { id: l.mode.id, version: l.mode.version },
players: l.players.map(p => ({ ...p, tokenHash: p.tokenHash.toString('hex') })) })) });
}
/**
* Restore a snapshot written by `snapshot()`. Lobbies whose mode is no longer hosted with the
* same version and rules are dropped. Timers restart from now, so nobody times out because
* the node was down. Returns how many lobbies were restored.
*/
restore(json: string): number {
const data = JSON.parse(json) as { schema?: string; lobbies?: any[] };
if (data.schema !== 'wikideck-live-lobbies/1' || !Array.isArray(data.lobbies)) return 0;
const now = this.now();
let restored = 0;
for (const raw of data.lobbies.slice(0, this.maxLobbies)) {
const h = this.hosted.get(raw?.mode?.id);
if (!h || h.mode.version !== raw.mode.version || JSON.stringify(h.rules) !== JSON.stringify(raw.rules)) continue;
if (typeof raw.id !== 'string' || !LOBBY_ID.test(raw.id) || this.lobbies.has(raw.id)) continue;
if (!['waiting', 'drafting', 'playing'].includes(raw.phase) || !Array.isArray(raw.players) || raw.players.length < 1 || raw.players.length > 2) continue;
const lobby: Lobby = { ...raw, mode: h.mode, rules: h.rules,
players: raw.players.map((p: any) => ({ id: String(p.id), name: String(p.name), seen: now, tokenHash: Buffer.from(String(p.tokenHash), 'hex') })),
lastMove: now, createdAt: raw.phase === 'waiting' ? now : raw.createdAt, turnStartedAt: now };
if (lobby.players.some(p => p.tokenHash.length !== 32)) continue;
if (lobby.draft && lobby.mode.decks.kind === 'draft') lobby.draft.deadline = now + lobby.mode.decks.pickSeconds * 1000;
if (lobby.phase === 'playing' && (lobby.state === undefined || !lobby.decks)) continue;
if (lobby.phase === 'drafting' && !lobby.draft) continue;
this.lobbies.set(lobby.id, lobby);
restored++;
}
return restored;
}
/** 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(); }