import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; export interface SeatCredential { readonly player: string; readonly tokenHash: string; } export interface MatchCredentialRecord { readonly matchId: string; readonly inviteTokenHash: string; readonly hostTokenHash: string; readonly seats: readonly SeatCredential[]; } export interface SeatCredentialStore { load(matchId: string): Promise; save(matchId: string, record: MatchCredentialRecord): Promise; } export class InMemorySeatCredentialStore implements SeatCredentialStore { private readonly records = new Map(); public async load(matchId: string): Promise { const record = this.records.get(matchId); return record === undefined ? undefined : cloneRecord(record); } public async save(matchId: string, record: MatchCredentialRecord): Promise { validateRecord(matchId, record); this.records.set(matchId, cloneRecord(record)); } } export class JsonFileSeatCredentialStore implements SeatCredentialStore { public constructor(private readonly directory: string) {} public async load(matchId: string): Promise { const path = this.pathFor(matchId); try { const serialized = await readFile(path, "utf8"); const parsed = JSON.parse(serialized) as unknown; if (!isCredentialRecord(parsed, matchId)) throw new Error("seat_credential_record_invalid"); return cloneRecord(parsed); } catch (error) { if (isNodeError(error) && error.code === "ENOENT") return undefined; if (error instanceof SyntaxError) throw new Error("seat_credential_record_json_invalid", { cause: error }); throw error; } } public async save(matchId: string, record: MatchCredentialRecord): Promise { validateRecord(matchId, record); const path = this.pathFor(matchId); await mkdir(dirname(path), { recursive: true }); const temporaryPath = `${path}.${randomUUID()}.tmp`; await writeFile(temporaryPath, JSON.stringify(record), { encoding: "utf8" }); await rename(temporaryPath, path); } private pathFor(matchId: string): string { if (!validIdentifier(matchId)) throw new Error("seat_credential_match_id_invalid"); return join(this.directory, `${matchId}.json`); } } export function createCredentialToken(): string { return randomBytes(32).toString("base64url"); } export function hashCredentialToken(token: string): string { return createHash("sha256").update(token, "utf8").digest("hex"); } export function credentialMatches(token: string, expectedHash: string): boolean { const actual = Buffer.from(hashCredentialToken(token), "hex"); const expected = Buffer.from(expectedHash, "hex"); return actual.length === expected.length && timingSafeEqual(actual, expected); } function cloneRecord(record: MatchCredentialRecord): MatchCredentialRecord { return { matchId: record.matchId, inviteTokenHash: record.inviteTokenHash, hostTokenHash: record.hostTokenHash, seats: record.seats.map((seat) => ({ player: seat.player, tokenHash: seat.tokenHash })), }; } function validateRecord(matchId: string, record: MatchCredentialRecord): void { if (!isCredentialRecord(record, matchId)) throw new Error("seat_credential_record_invalid"); } function isCredentialRecord(value: unknown, matchId: string): value is MatchCredentialRecord { if (!validIdentifier(matchId) || value === null || typeof value !== "object" || Array.isArray(value)) return false; const record = value as { matchId?: unknown; inviteTokenHash?: unknown; hostTokenHash?: unknown; seats?: unknown }; if (record.matchId !== matchId || !validHash(record.inviteTokenHash) || !validHash(record.hostTokenHash) || !Array.isArray(record.seats)) return false; const players = new Set(); return record.seats.every((value) => { if (value === null || typeof value !== "object" || Array.isArray(value)) return false; const seat = value as { player?: unknown; tokenHash?: unknown }; if (!validIdentifier(seat.player) || !validHash(seat.tokenHash) || players.has(seat.player)) return false; players.add(seat.player); return true; }); } function validHash(value: unknown): value is string { return typeof value === "string" && /^[0-9a-f]{64}$/.test(value); } function validIdentifier(value: unknown): value is string { return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value); } function isNodeError(value: unknown): value is NodeJS.ErrnoException { return value instanceof Error && "code" in value; }