forked from WikiDeck/wikideck
94 lines
4.4 KiB
TypeScript
94 lines
4.4 KiB
TypeScript
/**
|
|
* Discover the modes of explicitly configured peers. No discovery service, no gossip:
|
|
* the operator lists peer origins (WIKIDECK_GAME_PEERS, else WIKIDECK_PEERS). Each peer's
|
|
* GET /api/game/modes is fetched with a timeout, a byte cap and no redirects, then parsed
|
|
* strictly as data. The fetched origin replaces whatever origin the peer claims.
|
|
*/
|
|
import { parseModeList, MAX_MODE_LIST_BYTES, type ModeList } from '../../shared/game/modes.ts';
|
|
|
|
export type PeerModes = { origin: string; ok: boolean; error?: string; fetchedAt: number; rejected?: number; list?: ModeList };
|
|
export type Fetcher = (url: string, init: { signal: AbortSignal; redirect: 'error'; headers: Record<string, string> }) => Promise<Response>;
|
|
|
|
export function parsePeerOrigins(raw: string | undefined, allowPrivate: boolean): string[] {
|
|
const out = new Set<string>();
|
|
for (const text of (raw ?? '').split(',').map(s => s.trim()).filter(Boolean)) {
|
|
if (text.length > 256 || !/^https?:\/\/[^/?#\\@\s]+\/?$/i.test(text)) throw new Error(`Invalid game peer origin: ${text.slice(0, 80)}`);
|
|
const url = new URL(text);
|
|
if (url.protocol !== 'https:' && !(allowPrivate && url.protocol === 'http:')) throw new Error('Game peers must be HTTPS (or HTTP with WIKIDECK_ALLOW_PRIVATE_PEERS=1)');
|
|
out.add(url.origin);
|
|
}
|
|
if (out.size > 16) throw new Error('At most 16 game peers');
|
|
return [...out];
|
|
}
|
|
|
|
export class ModeDiscovery {
|
|
private readonly peers: string[];
|
|
private readonly fetcher: Fetcher;
|
|
private readonly ttlMs: number;
|
|
private readonly timeoutMs: number;
|
|
private readonly cache = new Map<string, PeerModes>();
|
|
private inflight: Promise<PeerModes[]> | null = null;
|
|
private readonly now: () => number;
|
|
|
|
constructor(options: { peers: string[]; fetcher?: Fetcher; ttlMs?: number; timeoutMs?: number; now?: () => number }) {
|
|
this.peers = options.peers;
|
|
this.fetcher = options.fetcher ?? ((url, init) => fetch(url, init));
|
|
this.ttlMs = options.ttlMs ?? 30_000;
|
|
this.timeoutMs = options.timeoutMs ?? 3_000;
|
|
this.now = options.now ?? Date.now;
|
|
}
|
|
|
|
/** Cached peer results; refreshes stale entries at most once concurrently. */
|
|
async all(): Promise<PeerModes[]> {
|
|
const now = this.now();
|
|
const stale = this.peers.some(p => { const c = this.cache.get(p); return !c || now - c.fetchedAt > this.ttlMs; });
|
|
if (stale) {
|
|
this.inflight ??= Promise.all(this.peers.map(p => this.fetchPeer(p))).finally(() => { this.inflight = null; });
|
|
await this.inflight;
|
|
}
|
|
return this.peers.map(p => this.cache.get(p)!).filter(Boolean);
|
|
}
|
|
|
|
private async fetchPeer(origin: string): Promise<PeerModes> {
|
|
const fetchedAt = this.now();
|
|
let result: PeerModes;
|
|
try {
|
|
const signal = AbortSignal.timeout(this.timeoutMs);
|
|
const res = await this.fetcher(`${origin}/api/game/modes`, { signal, redirect: 'error', headers: { accept: 'application/json' } });
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
const body = await readCapped(res, MAX_MODE_LIST_BYTES);
|
|
const { list, rejected } = parseModeList(body);
|
|
// The peer may claim any operator name, but not any origin: we know where we fetched it.
|
|
result = { origin, ok: true, fetchedAt, rejected, list: { ...list, host: { ...list.host, origin } } };
|
|
} catch (e) {
|
|
const previous = this.cache.get(origin);
|
|
result = { origin, ok: false, error: describe(e), fetchedAt, ...(previous?.list ? { list: previous.list } : {}) };
|
|
}
|
|
this.cache.set(origin, result);
|
|
return result;
|
|
}
|
|
}
|
|
|
|
async function readCapped(res: Response, max: number): Promise<string> {
|
|
const declared = Number(res.headers.get('content-length') ?? 0);
|
|
if (declared > max) throw new Error('Mode list too large');
|
|
if (!res.body) return '';
|
|
const reader = res.body.getReader();
|
|
const chunks: Uint8Array[] = [];
|
|
let total = 0;
|
|
for (;;) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
total += value.byteLength;
|
|
if (total > max) { await reader.cancel(); throw new Error('Mode list too large'); }
|
|
chunks.push(value);
|
|
}
|
|
return new TextDecoder().decode(Buffer.concat(chunks));
|
|
}
|
|
|
|
function describe(e: unknown): string {
|
|
const m = e instanceof Error ? e.message : String(e);
|
|
return (m.includes('too large') ? 'response too large' : m.includes('abort') || m.includes('timeout') ? 'timeout'
|
|
: /^HTTP \d+$/.test(m) ? m : e instanceof SyntaxError ? 'invalid JSON' : 'invalid or unreachable').slice(0, 80);
|
|
}
|