Files
wikideck/server/game/host.ts
T
claudeandClaude Opus 5.5 a2c2166bcc Modes: follow engine core f3b6097 (trend arrows, timeouts, deckSize)
Live/trending presets freeze the engine's trend arrow from cached live data;
the host turn timer uses the ruleset's turnSeconds and applies the engine's
timeout action (logged, replayable AFK forfeits). Non-draft modes whose rules
make starter decks illegal are rejected at startup. HOSTING.md updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:04:12 -05:00

356 lines
18 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. 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' | '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 === 'drafting' || l.phase === 'playing') live++;
if (l.phase === 'waiting' || l.phase === 'drafting' || l.phase === 'playing') 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();
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(); }