Files
wikideck/server/game/router.ts
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: WikiDeck/wikideck#23

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

92 lines
5.8 KiB
TypeScript

/**
* /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))));
// Same body; entries carry `rating` (Elo, null if unrated) plus W/L.
r.get('/modes/:modeId/ladder', reads, wrap(req => host.leaderboard(String(req.params.modeId))));
r.get('/modes/:modeId/lobbies', reads, wrap(req => ({ lobbies: host.openLobbies(String(req.params.modeId)) })));
// Seat bodies: `{name, secret}` for guests (Edit War only), or `{idToken}` for an eom.dev account
// (the Dex ID token travels in the body: Authorization carries seat tokens). Constructed
// modes add `deck: tokenId[]`; `private: true` hides the lobby (join it by invite code).
const seat = (req: Request) => {
const b = body(req);
// Also accept the Dex ID token as `Authorization: Bearer <jwt>` on seat-creating routes: a
// JWT (three dot-separated parts) can never match the seat-token format above.
const m = /^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.exec(req.get('authorization') ?? '');
return { name: b.name, secret: b.secret, idToken: b.idToken ?? m?.[1], deck: b.deck, private: b.private };
};
r.post('/modes/:modeId/lobbies', writes, wrap(async (req, res) => {
const ticket = await host.createLobby(String(req.params.modeId), seat(req));
res.status(201);
return ticket;
}));
// Quick match: join the oldest open public lobby, else open one (`matched: false`) and poll it.
r.post('/modes/:modeId/quick', writes, wrap(req => host.quickMatch(String(req.params.modeId), seat(req))));
r.post('/lobbies/:lobbyId/join', writes, wrap(req => host.join(String(req.params.lobbyId), seat(req))));
// Invite links (/play/invite/<code> in the SPA) resolve here, then join by lobby id or code.
r.get('/invites/:code', reads, wrap(req => host.invite(String(req.params.code))));
r.post('/invites/:code/join', writes, wrap(req => host.join(host.invite(String(req.params.code)).lobbyId, seat(req))));
// Polling: `?v=<version>` from the last response returns 204 while nothing changed.
r.get('/lobbies/:lobbyId', plays, wrap((req, res) => {
const raw = typeof req.query.v === 'string' ? req.query.v : undefined;
const since = raw !== undefined && /^\d{1,15}$/.test(raw) ? Number(raw) : undefined;
const out = host.view(String(req.params.lobbyId), bearer(req) || undefined, since);
if (out === null) { res.status(204).end(); return; }
return out;
}));
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) };
}