71 lines
4.2 KiB
TypeScript
71 lines
4.2 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))));
|
|
r.get('/modes/:modeId/lobbies', reads, wrap(req => ({ lobbies: host.openLobbies(String(req.params.modeId)) })));
|
|
r.post('/modes/:modeId/lobbies', writes, wrap((req, res) => {
|
|
const b = body(req);
|
|
res.status(201);
|
|
return host.createLobby(String(req.params.modeId), { name: b.name, secret: b.secret });
|
|
}));
|
|
r.post('/lobbies/:lobbyId/join', writes, wrap(req => {
|
|
const b = body(req);
|
|
return host.join(String(req.params.lobbyId), { name: b.name, secret: b.secret });
|
|
}));
|
|
r.get('/lobbies/:lobbyId', plays, wrap(req => host.view(String(req.params.lobbyId), bearer(req) || undefined)));
|
|
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) };
|
|
}
|