Files
wikideck/server/game/router.ts
claudeandClaude Opus 5.5 adc78409fe host-pvp: multi-engine host, owned-deck seats, invites, quick match, Elo, ?v= polling (#56)
- Mode schema wikideck.mode/2: required `engine` (editwar | duel); Night 1
  wikideck.mode/1 documents are rejected with a clear message. Deck policies:
  constructed (owned NFT token ids, minConfirmations), starter (Edit War only),
  draft with source preview (Edit War only) or collections. limits.rated and
  limits.accountsOnly.
- ModeHost runs every engine it is given, chosen per mode. Duel modes refuse
  loaner policies at startup (BRIEF decision 1).
- Seats: eom.dev account via Dex ID token (body or JWT bearer on seat-creating
  routes), player id sha256('acct:'+iss+'\n'+sub); guests only in Edit War.
- Constructed decks resolved through an injected OwnershipPort (#57), cards built
  by the engine's fromChain; creator's deck re-resolved at join.
- Private lobbies + invite codes (GET /invites/:code, POST /invites/:code/join),
  quick match (POST /modes/:id/quick), lobby state version with 204 on ?v=.
- Elo (1200, K 24) per mode for rated account-vs-account matches, recomputed
  from matches.jsonl; records carry engine, rated, tokens. /modes/:id/ladder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:27:37 -05: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) };
}