import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import { credentialMatches, createCredentialToken, hashCredentialToken, InMemorySeatCredentialStore, type MatchCredentialRecord, type SeatCredentialStore, } from "./credentials.js"; import { createEconomancyMatch, InMemoryMatchStore, persistEconomancyMatch, restoreEconomancyMatch, type EconomancyMatchSession, type MatchStore, } from "@instlang/economancy-host"; import type { MatchCommandEnvelope, MatchCommandResult, MatchEvent, PlayerMatchView, PublicMatchView, } from "@instlang/economancy-protocol"; const maxBodyBytes = 1_048_576; export interface CreateMatchRequest { readonly matchId: unknown; readonly players: unknown; readonly player?: unknown; } export interface MatchViewResponse { readonly view: PublicMatchView | PlayerMatchView; } export interface CreateMatchResponse extends MatchViewResponse { readonly player: string; readonly inviteToken: string; readonly hostToken: string; readonly seatToken: string; } export interface JoinMatchRequest { readonly player: unknown; readonly inviteToken: unknown; } export interface JoinMatchResponse { readonly matchId: string; readonly player: string; readonly seatToken: string; readonly view: PlayerMatchView; } export interface MatchEventsResponse { readonly matchId: string; readonly events: readonly MatchEvent[]; } export interface EconomancyMatchServiceOptions { readonly store?: MatchStore; readonly credentials?: SeatCredentialStore; } export class MatchNotFoundError extends Error { public constructor() { super("match_not_found"); } } export class MatchAlreadyExistsError extends Error { public constructor() { super("match_already_exists"); } } export class MatchCredentialsMissingError extends Error { public constructor() { super("match_credentials_missing"); } } export class AuthenticationRequiredError extends Error { public constructor() { super("seat_token_required"); } } export class AuthenticationInvalidError extends Error { public constructor() { super("seat_token_invalid"); } } export class AuthenticationActorMismatchError extends Error { public constructor() { super("seat_actor_mismatch"); } } /** Coordinates authoritative sessions with a durable or in-memory MatchStore. */ export class EconomancyMatchService { private readonly store: MatchStore; private readonly credentials: SeatCredentialStore; private readonly sessions = new Map(); public constructor(options: EconomancyMatchServiceOptions = {}) { this.store = options.store ?? new InMemoryMatchStore(); this.credentials = options.credentials ?? new InMemorySeatCredentialStore(); } public async createMatch(request: CreateMatchRequest): Promise { if (typeof request.matchId !== "string") throw new Error("match_identity_invalid"); if (this.sessions.has(request.matchId) || await this.store.load(request.matchId) !== undefined) { throw new MatchAlreadyExistsError(); } const created = createEconomancyMatch(request.matchId, request.players); if (created.kind !== "accepted") throw new Error(created.reason); const player = request.player === undefined ? created.session.players[0]! : request.player; if (typeof player !== "string" || !created.session.players.includes(player)) throw new Error("seat_player_invalid"); const inviteToken = createCredentialToken(); const hostToken = createCredentialToken(); const seatToken = createCredentialToken(); await this.credentials.save(created.session.matchId, { matchId: created.session.matchId, inviteTokenHash: hashCredentialToken(inviteToken), hostTokenHash: hashCredentialToken(hostToken), seats: [{ player, tokenHash: hashCredentialToken(seatToken) }], }); await this.save(created.session); this.sessions.set(created.session.matchId, created.session); return { view: created.session.getPlayerView(player)!, player, inviteToken, hostToken, seatToken }; } public async getView(matchId: string, seatToken: string | undefined): Promise { const session = await this.requireSession(matchId); const record = await this.requireCredentialRecord(matchId); if (seatToken === undefined) throw new AuthenticationRequiredError(); const player = this.playerForSeatToken(record, seatToken); const view = session.getPlayerView(player); if (view === undefined) throw new MatchNotFoundError(); return { view }; } public async joinMatch(matchId: string, request: JoinMatchRequest): Promise { const session = await this.requireSession(matchId); if (typeof request.player !== "string" || !session.players.includes(request.player)) throw new Error("seat_player_invalid"); if (typeof request.inviteToken !== "string" || request.inviteToken.length < 20) throw new AuthenticationInvalidError(); const record = await this.requireCredentialRecord(matchId); if (!credentialMatches(request.inviteToken, record.inviteTokenHash)) throw new AuthenticationInvalidError(); const seatToken = createCredentialToken(); const next: MatchCredentialRecord = { ...record, seats: [...record.seats.filter((seat) => seat.player !== request.player), { player: request.player, tokenHash: hashCredentialToken(seatToken) }], }; await this.credentials.save(matchId, next); return { matchId, player: request.player, seatToken, view: session.getPlayerView(request.player)! }; } public async dispatch(matchId: string, envelope: MatchCommandEnvelope, seatToken: string | undefined): Promise { const session = await this.requireSession(matchId); const record = await this.requireCredentialRecord(matchId); if (seatToken === undefined) throw new AuthenticationRequiredError(); if (envelope.command.kind === "advance_income") { if (!credentialMatches(seatToken, record.hostTokenHash)) throw new AuthenticationInvalidError(); } else { const actor = record.seats.find((seat) => credentialMatches(seatToken, seat.tokenHash))?.player; if (actor === undefined) throw new AuthenticationInvalidError(); if (actor !== envelope.actor) throw new AuthenticationActorMismatchError(); } const result = await session.dispatch(envelope); if (result.kind === "accepted") await this.save(session); return result; } public async getEvents(matchId: string, sequenceExclusive: number): Promise { const session = await this.requireSession(matchId); return { matchId, events: session.getEventsSince(sequenceExclusive) }; } private async requireSession(matchId: string): Promise { const cached = this.sessions.get(matchId); if (cached !== undefined) return cached; const serialized = await this.store.load(matchId); if (serialized === undefined) throw new MatchNotFoundError(); const restored = await restoreEconomancyMatch(serialized); if (restored.kind !== "accepted") throw new Error("match_restore_failed:" + restored.reason); if (restored.session.matchId !== matchId) throw new Error("match_store_match_id_mismatch"); this.sessions.set(matchId, restored.session); return restored.session; } private async requireCredentialRecord(matchId: string): Promise { const record = await this.credentials.load(matchId); if (record === undefined) throw new MatchCredentialsMissingError(); return record; } private playerForSeatToken(record: MatchCredentialRecord, seatToken: string): string { const player = record.seats.find((seat) => credentialMatches(seatToken, seat.tokenHash))?.player; if (player === undefined) throw new AuthenticationInvalidError(); return player; } private async save(session: EconomancyMatchSession): Promise { const persisted = persistEconomancyMatch(session); if (persisted.kind !== "accepted") throw new Error(persisted.reason); await this.store.save(session.matchId, persisted.serialized); } } export function createEconomancyHttpServer(service: EconomancyMatchService): Server { return createServer((request, response) => { void handleEconomancyRequest(service, request, response).catch((error: unknown) => { const message = error instanceof Error ? error.message : "server_error"; sendJson(response, statusForError(error, message), { error: message }); }); }); } export async function handleEconomancyRequest(service: EconomancyMatchService, request: IncomingMessage, response: ServerResponse): Promise { setCorsHeaders(response); if (request.method === "OPTIONS") { response.writeHead(204); response.end(); return; } const url = new URL(request.url ?? "/", "http://localhost"); const parts = url.pathname.split("/").filter(Boolean); if (request.method === "POST" && parts.length === 1 && parts[0] === "matches") { const body = await readJson(request); const created = await service.createMatch(body as CreateMatchRequest); sendJson(response, 201, created); return; } if (parts[0] !== "matches" || parts[1] === undefined || parts.length > 3) { sendJson(response, 404, { error: "route_not_found" }); return; } const matchId = decodeURIComponent(parts[1]); if (request.method === "POST" && parts[2] === "join") { const body = await readJson(request); const joined = await service.joinMatch(matchId, body as JoinMatchRequest); sendJson(response, 200, joined); return; } if (request.method === "GET" && parts.length === 2) { const result = await service.getView(matchId, authorizationToken(request)); sendJson(response, 200, result); return; } if (request.method === "GET" && parts[2] === "events") { const sequenceExclusive = parseSequence(url.searchParams.get("since")); const result = await service.getEvents(matchId, sequenceExclusive); sendJson(response, 200, result); return; } if (request.method === "POST" && parts[2] === "commands") { const body = await readJson(request); const result = await service.dispatch(matchId, body as MatchCommandEnvelope, authorizationToken(request)); sendJson(response, 200, result); return; } sendJson(response, 404, { error: "route_not_found" }); } function parseSequence(value: string | null): number { if (value === null || value === "") return -1; const sequence = Number(value); if (!Number.isSafeInteger(sequence) || sequence < -1) throw new Error("events_sequence_invalid"); return sequence; } async function readJson(request: IncomingMessage): Promise { const chunks: Buffer[] = []; let size = 0; for await (const chunk of request) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); size += buffer.byteLength; if (size > maxBodyBytes) throw new Error("request_body_too_large"); chunks.push(buffer); } const text = Buffer.concat(chunks).toString("utf8"); try { return JSON.parse(text) as unknown; } catch { throw new Error("request_json_invalid"); } } function setCorsHeaders(response: ServerResponse): void { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "content-type, authorization"); response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS"); } function sendJson(response: ServerResponse, status: number, body: unknown): void { const serialized = JSON.stringify(body); response.statusCode = status; response.setHeader("content-type", "application/json; charset=utf-8"); response.setHeader("content-length", Buffer.byteLength(serialized)); response.end(serialized); } function statusForError(error: unknown, message: string): number { if (error instanceof MatchNotFoundError) return 404; if (error instanceof MatchAlreadyExistsError || error instanceof MatchCredentialsMissingError) return 409; if (error instanceof AuthenticationRequiredError || error instanceof AuthenticationInvalidError) return 401; if (error instanceof AuthenticationActorMismatchError) return 403; if (/^(request_|events_sequence_invalid|match_identity_invalid|match_players_invalid|seat_|command_)/.test(message)) return 400; return 500; } function authorizationToken(request: IncomingMessage): string | undefined { const header = request.headers?.authorization; if (typeof header !== "string" || !header.startsWith("Bearer ")) return undefined; const token = header.slice("Bearer ".length).trim(); return token === "" ? undefined : token; }