Files
wikideck/server/game/host.ts
T
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).

## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
  - The server checks ownership, and 40-card eligibility is enforced.
  - Modes: Classic (ranked), Draft and Trending.
  - Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).

PR numbers refer to `claude/wikideck`.

## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
  - The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
  - Bot matches aren't reachable from Play.
  - Card identity pre-bake hasn't been done.
  - The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.

This PR is for Eric to merge.

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

Co-authored-by: Claude <claude@eom.dev>
2026-11-18 18:12:24 +00:00

615 lines
34 KiB
TypeScript
Raw 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. A seat is either an eom.dev
* account (Dex ID token in the create/join body, verified server-side; player id
* `sha256('acct:' + iss + '\n' + sub)`) or, in guest-friendly Edit War modes, a client-held
* secret (only its SHA-256 is stored). Seats act through per-seat bearer tokens. Every
* action must equal one of the engine's legalActions for that seat.
*
* Engines: each mode names its engine (`editwar` or `duel`); the host runs every engine it
* was given. Constructed decks are NFT token ids the player owns, resolved from the chain by
* the ownership port (server/game/ownership.ts) and turned into cards by the engine.
*/
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { modeKey, resolveRuleset, trendBonus, clampPower, requiresAccount, MODE_SCHEMA_VERSION,
type EngineId, type HostIdentity, type ModeDocument, type ModeList, type ModeStats, type LiveCardData } from '../../shared/game/modes.ts';
import type { ChainCard, EnginePort, OwnershipPort, Seat, SeatAccount } 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; }
}
/** The lobby's creator no longer has a valid deck; the lobby was expired. */
class StaleLobby extends GameError { constructor(message: string) { super(409, message); } }
type AnyEngine = EnginePort<any, any, any, any>;
type Player = { id: string; name: string; tokenHash: Buffer; seen: number;
/** Set for account seats: who to resolve the deck for. Never the ID token itself. */
account?: SeatAccount;
/** Constructed modes: the token ids this seat submitted (re-resolved at match start). */
deckIds?: string[] };
type Phase = 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
type Lobby = {
id: string; mode: ModeDocument; rules: unknown; seed: string; createdAt: number;
/** Bumped on every observable change, so unchanged polls (`?v=`) can return 204. */
version: number;
/** Private lobbies are hidden from lists and quick match; joined through the invite code. */
private?: boolean; invite?: string;
/** Rated (Elo) iff the mode is rated and both seats are accounts; decided at join. */
rated?: boolean;
/** Constructed modes: token ids per seat, for the record's references. */
tokens?: [string[], string[]];
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;
/** Per-seat time bank in ms (engines with `bankSeconds`): spent after the turn timer runs out. */
bank?: [number, number];
outcome?: { winner: Seat | null; reason: string }; matchId?: string;
};
type HostedMode = { mode: ModeDocument; rules: unknown; engine: AnyEngine };
export type HostOptions = {
identity: HostIdentity;
modes: ModeDocument[];
/** Engines by id. Every mode's `engine` must be present here. */
engines?: Partial<Record<EngineId, AnyEngine>>;
/** Shorthand for `engines: { editwar: engine }` (Night 1 callers and tests). */
engine?: AnyEngine;
/** Account verification and server-side ownership (#57). Without it, account seats are unavailable. */
ownership?: OwnershipPort;
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; invite?: string; playerId: string };
/** Body of create / join / quick match. `idToken` is a Dex ID token; `deck` is NFT token ids. */
export type SeatRequest = { name?: unknown; secret?: unknown; idToken?: unknown; deck?: unknown; private?: unknown };
const NAME = /^[\p{L}\p{N} _.\-]{1,24}$/u;
const SECRET = /^[A-Za-z0-9_-]{22,128}$/;
const LOBBY_ID = /^[a-f0-9]{24}$/;
const INVITE = /^[A-Za-z0-9_-]{12}$/;
export class ModeHost {
readonly identity: HostIdentity;
private readonly store: MatchStore;
private readonly ownership?: OwnershipPort;
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.store = options.store;
this.ownership = options.ownership;
const engines: Partial<Record<EngineId, AnyEngine>> = { ...(options.engine ? { editwar: options.engine } : {}), ...options.engines };
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}`);
const engine = engines[mode.engine];
if (!engine) throw new Error(`Mode ${mode.id}: engine "${mode.engine}" is not available on this host`);
// Validate rules once at startup with the engine's own parser: a bad mode fails loudly.
const rules = resolveRuleset(engine.defaultRuleset, mode.rules, v => engine.parseRuleset(v));
const loaners = mode.decks.kind === 'starter' || (mode.decks.kind === 'draft' && mode.decks.source === 'preview');
// BRIEF decision 1: duel decks are only cards the players own. No starter, loaner or preview cards.
if (mode.engine === 'duel' && loaners) throw new Error(`Mode ${mode.id}: duel modes use owned cards only (constructed, or a collections draft)`);
if (mode.decks.kind === 'draft' && mode.decks.poolSize < 2 * engine.deckSize(rules)) {
throw new Error(`Mode ${mode.id}: draft poolSize must be at least 2 × deck size`);
}
if (!loaners && !engine.fromChain) throw new Error(`Mode ${mode.id}: engine "${mode.engine}" cannot build cards from owned NFTs`);
if (mode.decks.kind === 'starter') {
// Host-dealt starter decks must be legal under the mode's rules, or the mode is unplayable.
try { engine.validateDeck(rules, 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, engine });
}
}
/** 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' && !l.private)
.slice(0, 50).map(l => ({ lobbyId: l.id, host: l.players[0]!.name, createdAt: l.createdAt,
hostId: l.players[0]!.id, account: !!l.players[0]!.account }));
}
/** Look up a private (or public) waiting lobby by its invite code: what an invite link shows. */
invite(code: string) {
this.sweep();
const l = typeof code === 'string' && INVITE.test(code) ? [...this.lobbies.values()].find(x => x.invite === code) : undefined;
if (!l) throw new GameError(404, 'Invite not found or expired.');
return { lobbyId: l.id, phase: l.phase, open: l.phase === 'waiting', host: this.identity,
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name, engine: l.mode.engine },
createdBy: l.players[0]!.name, createdAt: l.createdAt, accountRequired: requiresAccount(l.mode) };
}
async createLobby(modeId: string, request: SeatRequest): Promise<SeatTicket> {
const h = this.mode(modeId);
this.sweep();
this.checkCapacity(h);
const p = await this.seat(h, request);
if (h.mode.decks.kind === 'constructed') await this.resolveDeck(h, p.player, request.deck);
return this.openLobby(h, p, request.private === true);
}
async join(lobbyId: string, request: SeatRequest): Promise<SeatTicket> {
const l = this.lobby(lobbyId);
this.sweep();
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
const h = this.mode(l.mode.id);
const p = await this.seat(h, request);
const cards = h.mode.decks.kind === 'constructed' ? await this.resolveDeck(h, p.player, request.deck) : undefined;
return this.seatInLobby(l, p, cards);
}
/**
* Quick match: join the oldest open public lobby of this mode that someone else opened,
* else open a new public lobby and wait. No rating window (the ladder is small).
*/
async quickMatch(modeId: string, request: SeatRequest): Promise<SeatTicket & { matched: boolean }> {
const h = this.mode(modeId);
this.sweep();
const p = await this.seat(h, request);
const cards = h.mode.decks.kind === 'constructed' ? await this.resolveDeck(h, p.player, request.deck) : undefined;
const candidates = [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting' && !l.private &&
l.players[0]!.id !== p.player.id).sort((a, b) => a.createdAt - b.createdAt);
for (const l of candidates) {
if (l.phase !== 'waiting') continue;
// A stale lobby (its host's cards moved) is expired and skipped: not the quick-matcher's fault.
try { return { ...await this.seatInLobby(l, p, cards), matched: true }; }
catch (e) { if (e instanceof StaleLobby) continue; throw e; }
}
this.checkCapacity(h);
return { ...this.openLobby(h, p, false), matched: false };
}
/** The lobby's current state version (see `view`). */
version(lobbyId: string): number { return this.lobby(lobbyId).version; }
private checkCapacity(h: HostedMode) {
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 === h.mode.id).length >= h.mode.limits.maxConcurrentMatches) {
throw new GameError(503, 'This mode is at its match limit on this host; try again later.');
}
}
private openLobby(h: HostedMode, p: { player: Player; token: string }, isPrivate: boolean): SeatTicket {
const active = [...this.lobbies.values()].filter(l => l.phase !== 'finished' && l.phase !== 'expired');
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 invite = randomBytes(9).toString('base64url');
const now = this.now();
this.lobbies.set(id, { id, mode: h.mode, rules: h.rules, seed: randomBytes(16).toString('hex'), createdAt: now,
version: 1, private: isPrivate, invite, players: [p.player], phase: 'waiting', actions: [], lastMove: now });
return { lobbyId: id, seat: 0, token: p.token, invite, playerId: p.player.id };
}
/** Seat a prepared player in a waiting lobby and start the draft or match. Synchronous until claimed. */
private async seatInLobby(l: Lobby, p: { player: Player; token: string }, joinerCards?: ChainCard[]): Promise<SeatTicket> {
// Re-check after the caller's awaits: another join may have claimed the lobby meanwhile.
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
if (l.players[0]!.id === p.player.id) throw new GameError(409, 'You cannot play against yourself.');
const h = this.mode(l.mode.id);
// Claim the lobby before any await, so a concurrent join can't also pass the 'waiting' check.
l.phase = 'starting';
l.lastMove = this.now();
const policy = h.mode.decks;
// The creator's cards may have moved since they opened the lobby: resolve them again now,
// at match start, before the joiner is seated (a stale lobby never lists the joiner).
const creatorCards = policy.kind === 'constructed'
? await this.resolveDeck(h, l.players[0]!, l.players[0]!.deckIds).catch(e => {
this.expire(l); throw new StaleLobby(`The lobby host's deck is no longer valid: ${(e as Error).message}`.slice(0, 200)); })
: undefined;
l.players.push(p.player);
l.rated = h.mode.limits.rated && l.players.every(x => x.account);
this.bump(l);
if (policy.kind === 'draft' && policy.source === 'collections') {
const pools = await Promise.all(l.players.map(x => this.ownershipCall(() => this.ownership!.collection(x.account!))))
.catch(e => { this.expire(l); throw e; });
const size = h.engine.deckSize(l.rules);
pools.forEach((c, seat) => { if (c.length < size) { this.expire(l);
throw new GameError(409, `${seat === 0 ? 'The lobby host' : 'You'} own${seat === 0 ? 's' : ''} ${c.length} / ${size} cards: both players must be eligible to draft.`); } });
const cards = seededShuffle([...pools[0]!, ...pools[1]!], `${l.seed}:pool`).slice(0, policy.poolSize)
.map(c => h.engine.fromChain!(l.rules, c));
this.startDraft(l, cards);
} else if (policy.kind === 'draft') this.startDraft(l, h.engine.previewPool(l.rules, `${l.seed}:pool`, policy.poolSize));
else if (policy.kind === 'constructed') {
const decks = [creatorCards!, joinerCards!];
l.tokens = [decks[0]!.map(c => c.tokenId), decks[1]!.map(c => c.tokenId)];
await this.startMatch(l, [decks[0]!.map(c => h.engine.fromChain!(l.rules, c)), decks[1]!.map(c => h.engine.fromChain!(l.rules, c))]);
} else await this.startMatch(l, [h.engine.starterDeck(l.rules, `${l.seed}:0`), h.engine.starterDeck(l.rules, `${l.seed}:1`)]);
return { lobbyId: l.id, seat: 1, token: p.token, invite: l.invite, playerId: p.player.id };
}
/**
* Public status, plus the seat's private view when a valid token is given.
* With `since` equal to the lobby's current version, returns null (the router sends 204).
*/
view(lobbyId: string, token?: string, since?: number) {
const l = this.lobby(lobbyId);
this.sweep();
if (since !== undefined && since === l.version) return null;
const engine = this.mode(l.mode.id).engine;
const seat = token ? this.seatFor(l, token) : null;
const base = { lobbyId: l.id, version: l.version, phase: l.phase, host: this.identity,
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name, engine: l.mode.engine },
players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), seat, matchId: l.matchId ?? null,
rated: l.rated ?? false, private: l.private ?? false, invite: seat === 0 ? l.invite ?? null : undefined,
outcome: l.outcome ?? null };
if (l.phase === 'drafting' && l.draft && seat !== null) {
const d = l.draft;
return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: 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, clock: l.phase === 'playing' ? { turnStartedAt: l.turnStartedAt ?? null, turnMs: this.turnMs(l), bankMs: l.bank ?? null } : null,
state: engine.viewFor(l.state, seat),
legalActions: l.phase === 'playing' ? 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.mode(l.mode.id).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') { this.expire(l); return this.view(lobbyId, token); }
if (l.phase !== 'playing' && l.phase !== 'drafting') throw new GameError(409, 'Nothing to resign.');
const engine = this.mode(l.mode.id).engine;
if (l.phase === 'playing' && l.state !== undefined && engine.concedeAction) {
this.apply(l, seat, 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'),
...(p.account && typeof p.account.sub === 'string' && typeof p.account.issuer === 'string'
? { account: { sub: p.account.sub, issuer: p.account.issuer, name: String(p.account.name ?? p.name) } } : {}),
...(Array.isArray(p.deckIds) ? { deckIds: p.deckIds.map(String).slice(0, 64) } : {}) })),
version: Number.isSafeInteger(raw.version) ? raw.version : 1,
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()) {
const engine = this.hosted.get(l.mode.id)!.engine;
if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) this.expire(l);
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 => engine.legalActions(l.state, s).length > 0);
// Past the turn timer, a lone waiting seat spends its bank before it times out.
const bank = waiting.length === 1 && l.bank ? l.bank[waiting[0]!] : 0;
if (now - (l.turnStartedAt ?? l.lastMove) <= this.turnMs(l) + bank) { /* still on the bank */ }
else if (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') { if (l.bank) l.bank[s] = 0; this.apply(l, s, 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, pool: unknown[]) {
if (l.mode.decks.kind !== 'draft') return;
const size = this.mode(l.mode.id).engine.deckSize(l.rules);
if (pool.length < 2 * size) { this.expire(l); throw new GameError(409, `The draft pool has only ${pool.length} cards; it needs ${2 * size}.`); }
// 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';
this.bump(l);
}
private async takePick(l: Lobby, seat: Seat, index: number) {
const d = l.draft!;
d.taken[index] = seat;
d.turn++;
l.lastMove = this.now();
this.bump(l);
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 engine = this.mode(l.mode.id).engine;
const mapped = await Promise.all(decks.map(d => this.mapDeck(l.mode, d))) as [unknown[], unknown[]];
for (const d of mapped) {
try { engine.validateDeck(l.rules, d); }
catch (e) { this.expire(l); throw new GameError(400, `Deck rejected by the engine: ${(e as Error).message}`.slice(0, 200)); }
}
l.decks = mapped;
l.state = engine.createMatch(l.rules, mapped, l.seed);
l.phase = 'playing';
l.startedAt = l.lastMove = l.turnStartedAt = this.now();
const bankSeconds = engine.bankSeconds?.(l.rules);
if (bankSeconds !== undefined && bankSeconds > 0) l.bank = [bankSeconds * 1000, bankSeconds * 1000];
l.turn = engine.turnOf?.(l.state);
delete l.draft;
this.bump(l);
if (engine.isOver(l.state)) { const r = 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;
const { engine, rules } = this.hosted.get(mode.id)!;
return Promise.all(deck.map(async card => {
const pageId = 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 = engine.applyLive ? engine.applyLive(rules, card, live) : card;
if (mapping.preset === 'trending') {
const bonus = trendBonus(mapping, live.trendPercent);
if (bonus !== 0) mapped = engine.withPower(mapped, clampPower(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) {
const engine = this.mode(l.mode.id).engine;
l.state = engine.applyAction(l.state, seat, action);
l.actions.push({ seat, action });
l.lastMove = this.now();
this.bump(l);
const turn = engine.turnOf?.(l.state);
if (turn !== l.turn) {
// The seat that ended the turn pays any time over the turn timer from its bank.
if (l.bank && l.turnStartedAt !== undefined) {
const over = l.lastMove - l.turnStartedAt - this.turnMs(l);
if (over > 0) l.bank[seat] = Math.max(0, l.bank[seat] - over);
}
l.turn = turn; l.turnStartedAt = l.lastMove;
}
if (engine.isOver(l.state)) { const r = 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.mode(l.mode.id).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();
this.bump(l);
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, engine: l.mode.engine, rated: l.rated ?? false,
seed: l.seed, rules: l.rules,
players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), winner, reason: reason.slice(0, 40),
startedAt: l.startedAt ?? l.createdAt, endedAt: l.lastMove, decks: l.decks, actions: l.actions,
...(l.tokens ? { tokens: l.tokens } : {}) });
}
private bump(l: Lobby) { l.version = (l.version ?? 0) + 1; }
private expire(l: Lobby) {
if (l.phase === 'finished' || l.phase === 'expired') return;
l.phase = 'expired'; l.lastMove = this.now(); this.bump(l);
}
/** Verify the seat: an eom.dev account (ID token) or, where the mode allows guests, a secret. */
private async seat(h: HostedMode, input: SeatRequest): Promise<{ player: Player; token: string }> {
const token = randomBytes(24).toString('base64url');
if (input.idToken !== undefined && input.idToken !== null && input.idToken !== '') {
if (!this.ownership) throw new GameError(503, 'eom.dev accounts are not available on this host.');
const account = await this.ownershipCall(() => this.ownership!.verifyAccount(input.idToken));
const id = createHash('sha256').update(`acct:${account.issuer}\n${account.sub}`).digest('hex');
const name = displayName(account.name || account.username || '') ?? 'Player';
return { player: { id, name, tokenHash: hashToken(token), seen: this.now(),
account: { sub: account.sub, issuer: account.issuer, name } }, token };
}
if (requiresAccount(h.mode)) throw new GameError(401, 'This mode plays with cards you own: log in with your eom.dev account.');
return this.player(input, token);
}
/** Resolve a seat's submitted token ids to owned, confirmed chain cards (#57). */
private async resolveDeck(h: HostedMode, p: Player, tokenIds: unknown): Promise<ChainCard[]> {
if (h.mode.decks.kind !== 'constructed') return [];
if (!this.ownership || !p.account) throw new GameError(401, 'Log in with your eom.dev account to play your own cards.');
const deckSize = h.engine.deckSize(h.rules);
if (!Array.isArray(tokenIds) || tokenIds.length !== deckSize || !tokenIds.every(t => typeof t === 'string' && t.length <= 128)) {
throw new GameError(400, `A deck is exactly ${deckSize} card token ids you own.`);
}
const cards = await this.ownershipCall(() => this.ownership!.resolveDeck(p.account!, tokenIds,
{ deckSize, maxCopiesPerPage: h.engine.copyLimit?.(h.rules) ?? 4, minConfirmations: h.mode.decks.kind === 'constructed' ? h.mode.decks.minConfirmations : 1 }));
// Belt and braces: the ownership layer must hand back exactly the submitted tokens.
if (cards.length !== deckSize || cards.some((c, i) => c.tokenId !== tokenIds[i])) throw new GameError(500, 'Ownership check returned a different deck.');
p.deckIds = [...tokenIds as string[]];
return cards;
}
/** Pass player-facing ownership errors (status 4xx) through; anything else is a 503. */
private async ownershipCall<T>(fn: () => Promise<T>): Promise<T> {
try { return await fn(); }
catch (e) {
if (e instanceof GameError) throw e;
const status = (e as { status?: unknown })?.status;
if (typeof status === 'number' && status >= 400 && status < 500) throw new GameError(status, String((e as Error).message).slice(0, 200));
throw new GameError(503, 'Could not check accounts or ownership right now; try again.');
}
}
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: SeatRequest, token: string): { 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');
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(); }
/** An account display name reduced to the lobby name alphabet; null if nothing is left. */
function displayName(raw: string): string | null {
const cleaned = raw.normalize('NFC').replace(/[^\p{L}\p{N} _.\-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 24).trim();
return NAME.test(cleaned) ? cleaned : null;
}
/** Deterministic Fisher-Yates from a seed (SHA-256 counter stream): replayable draft pools. */
export function seededShuffle<T>(items: T[], seed: string): T[] {
const out = [...items];
let counter = 0, buf = Buffer.alloc(0), off = 0;
const next32 = () => {
if (off + 4 > buf.length) { buf = createHash('sha256').update(`${seed}:${counter++}`).digest(); off = 0; }
const v = buf.readUInt32BE(off); off += 4; return v;
};
for (let i = out.length - 1; i > 0; i--) {
const j = next32() % (i + 1);
[out[i], out[j]] = [out[j]!, out[i]!];
}
return out;
}