import Fastify from 'fastify' import cors from '@fastify/cors' import { AuthError, closeDatabase, connectDatabase, registerAccountRoutes, } from './accounts.js' import { CardsUnavailableError, findCardByName, getCard, matchesCardFilters, searchCards, } from './cards.js' import { compileImplementation, deleteOverride, getImplementation, implementationIndex, invalidateImplementationIndex, readOverride, writeOverride, type ImplementationStatus, } from './effects/implementations.js' import { PseudoParseError } from './effects/pseudo.js' import { translateCard, TranslationError } from './effects/translate.js' import { importDeckText } from './game/commander.js' import { cardArt, cardImage, playmatImage, scryfallArtUrl, scryfallImageUrl } from './images.js' import { MatchError, createMatch, getMatchView, joinMatch, leaveMatch, listMatches, performAction, setDeck, setPlaymat, startMatch, subscribe, type ActionPayload, type DeckSubmission, type MatchView, type PlaymatSubmission, } from './game/rooms.js' const app = Fastify({ logger: true }) const STATUS_FILTERS = new Set([ 'supported', 'partial', 'unsupported', 'needs-work', 'manual', 'all', ]) const COLOR_FILTERS = new Set(['W', 'U', 'B', 'R', 'G', 'C', 'M']) const TYPE_FILTERS = new Set([ 'artifact', 'battle', 'creature', 'enchantment', 'instant', 'kindred', 'land', 'planeswalker', 'sorcery', 'legendary', ]) const RARITY_FILTERS = new Set(['common', 'uncommon', 'rare', 'mythic', 'special', 'bonus']) function parseCmc(value: string | undefined): number | undefined | null { if (value === undefined || value === '') return undefined const parsed = Number(value) return Number.isFinite(parsed) && parsed >= 0 ? parsed : null } // Dev servers move to another port when 3000 is taken, and localhost/127.0.0.1 // are the same machine. CORS_ORIGIN lists any additional production origins. const LOCAL_ORIGIN = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/ const configuredOrigins = process.env.CORS_ORIGIN?.split(',') .map(origin => origin.trim()) .filter(Boolean) function isAllowedOrigin(origin: string | undefined): boolean { if (!origin || LOCAL_ORIGIN.test(origin)) return true return configuredOrigins?.includes(origin) ?? false } await app.register(cors, { origin: (origin, callback) => callback(null, isAllowedOrigin(origin)), // @fastify/cors defaults to GET,HEAD,POST; decks and preferences are saved with PUT. methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'], }) app.setErrorHandler((error, request, reply) => { if (error instanceof CardsUnavailableError) { return reply.code(503).send({ error: error.message }) } if (error instanceof PseudoParseError) { return reply.code(400).send({ error: error.message, line: error.line }) } if (error instanceof TranslationError || error instanceof MatchError || error instanceof AuthError) { return reply.code(error.status).send({ error: error.message }) } request.log.error(error) return reply.code(500).send({ error: 'Internal server error' }) }) registerAccountRoutes(app) app.get('/health', async () => ({ status: 'ok', service: 'commander-api' })) app.get<{ Querystring: { q?: string limit?: string offset?: string status?: string format?: string color?: string type?: string rarity?: string cmcMin?: string cmcMax?: string } }>( '/cards', async (request, reply) => { const { q = '', limit, offset, status = 'all' } = request.query if (!STATUS_FILTERS.has(status as ImplementationStatus | 'needs-work' | 'manual' | 'all')) { return reply.code(400).send({ error: `Unknown status filter: ${status}` }) } const format = request.query.format?.trim().toLowerCase() || undefined if (format && !/^[a-z][a-z0-9_]{0,31}$/.test(format)) { return reply.code(400).send({ error: `Invalid format filter: ${format}` }) } const color = request.query.color?.trim().toUpperCase() || undefined if (color && !COLOR_FILTERS.has(color)) { return reply.code(400).send({ error: `Unknown color filter: ${color}` }) } const type = request.query.type?.trim().toLowerCase() || undefined if (type && !TYPE_FILTERS.has(type)) { return reply.code(400).send({ error: `Unknown type filter: ${type}` }) } const rarity = request.query.rarity?.trim().toLowerCase() || undefined if (rarity && !RARITY_FILTERS.has(rarity)) { return reply.code(400).send({ error: `Unknown rarity filter: ${rarity}` }) } const cmcMin = parseCmc(request.query.cmcMin) const cmcMax = parseCmc(request.query.cmcMax) if (cmcMin === null || cmcMax === null) { return reply.code(400).send({ error: 'Mana value filters must be non-negative numbers' }) } const parsedLimit = Number.parseInt(limit ?? '50', 10) const pageSize = Number.isFinite(parsedLimit) ? Math.min(Math.max(parsedLimit, 1), 200) : 50 const parsedOffset = Number.parseInt(offset ?? '0', 10) const start = Number.isFinite(parsedOffset) ? Math.max(parsedOffset, 0) : 0 const index = await implementationIndex() const result = searchCards(q, pageSize, start, card => { const summary = index.get(card.oracle_id) if (status === 'manual' && !summary?.manual) return false if (status === 'needs-work' && summary?.status === 'supported') return false if (status !== 'all' && status !== 'manual' && status !== 'needs-work' && summary?.status !== status) { return false } return matchesCardFilters(card, { format, color, type, rarity, cmcMin, cmcMax }) }) return { total: result.total, cards: result.cards.map(card => ({ ...card, implementation: index.get(card.oracle_id) ?? null, })), } }, ) app.get('/stats', async () => { const index = await implementationIndex() const stats = { supported: 0, partial: 0, unsupported: 0, manual: 0 } for (const summary of index.values()) { stats[summary.status]++ if (summary.manual) stats.manual++ } return stats }) app.get<{ Params: { id: string } }>('/cards/:id', async (request, reply) => { const card = getCard(request.params.id) if (!card) return reply.code(404).send({ error: 'Card not found' }) return card }) /** Only fetch art from Scryfall's image host, never an arbitrary URL from the data file. */ app.get<{ Params: { id: string } }>('/cards/:id/image', async (request, reply) => { const card = getCard(request.params.id) if (!card) return reply.code(404).send({ error: 'Card not found' }) const source = scryfallImageUrl(card.image_uri) if (!source) return reply.code(404).send({ error: 'Card image not available' }) try { const image = await cardImage(card.oracle_id, source) return reply .header('Cache-Control', 'public, max-age=31536000, immutable') .type('image/jpeg') .send(image) } catch (error) { request.log.warn({ err: error, card: card.oracle_id }, 'Card image download failed') return reply.code(502).send({ error: 'Card image unavailable' }) } }) app.get<{ Params: { id: string } }>('/cards/:id/art', async (request, reply) => { const card = getCard(request.params.id) if (!card) return reply.code(404).send({ error: 'Card not found' }) const source = scryfallArtUrl(card.image_uri) if (!source) return reply.code(404).send({ error: 'Card art not available' }) try { const image = await cardArt(card.oracle_id, source) return reply .header('Cache-Control', 'public, max-age=31536000, immutable') .type('image/jpeg') .send(image) } catch (error) { request.log.warn({ err: error, card: card.oracle_id }, 'Card art download failed') return reply.code(502).send({ error: 'Card art unavailable' }) } }) app.get<{ Params: { id: string } }>('/cards/:id/implementation', async (request, reply) => { const card = getCard(request.params.id) if (!card) return reply.code(404).send({ error: 'Card not found' }) return { card, ...(await getImplementation(card)) } }) app.put<{ Params: { id: string }; Body: { source?: unknown } }>( '/cards/:id/implementation', async (request, reply) => { const card = getCard(request.params.id) if (!card) return reply.code(404).send({ error: 'Card not found' }) const source = request.body?.source if (typeof source !== 'string') { return reply.code(400).send({ error: 'Body must be JSON with a "source" string' }) } if (source.length > 1_000_000) { return reply.code(413).send({ error: 'Implementation is too large' }) } // Validate before touching the existing file, so a typo cannot lose work. compileImplementation(card, source) await writeOverride(card.oracle_id, source) invalidateImplementationIndex() return { card, ...(await getImplementation(card)) } }, ) app.post<{ Params: { id: string } }>('/cards/:id/translate', async (request, reply) => { const card = getCard(request.params.id) if (!card) return reply.code(404).send({ error: 'Card not found' }) return { source: await translateCard(card) } }) app.delete<{ Params: { id: string } }>('/cards/:id/implementation', async (request, reply) => { const card = getCard(request.params.id) if (!card) return reply.code(404).send({ error: 'Card not found' }) await deleteOverride(card.oracle_id) invalidateImplementationIndex() return { card, ...(await getImplementation(card)) } }) // Kept for scripts and debugging: a card has an override even if nobody asked // for the whole implementation payload. app.get<{ Params: { id: string } }>('/cards/:id/override', async (request, reply) => { const override = await readOverride(request.params.id) if (!override) return reply.code(404).send({ error: 'No manual implementation' }) return override }) // --------------------------------------------------------------------------- // Decks and Commander games // --------------------------------------------------------------------------- app.post<{ Body: { text?: unknown } }>('/decks/import', async (request, reply) => { const text = request.body?.text if (typeof text !== 'string') { return reply.code(400).send({ error: 'Body must be JSON with a "text" string' }) } if (text.length > 200_000) { return reply.code(413).send({ error: 'Decklist is too large' }) } return importDeckText(text) }) app.post<{ Body: { names?: unknown } }>('/cards/resolve', async (request, reply) => { const names = request.body?.names if (!Array.isArray(names) || names.some(name => typeof name !== 'string')) { return reply.code(400).send({ error: 'Body must be JSON with a "names" string array' }) } return { cards: names.slice(0, 100).map(name => findCardByName(String(name)) ?? null) } }) app.get('/games', async () => ({ games: listMatches() })) /** A stale or invalid browser preference must never block creating or joining a game. */ async function applyPlaymat( match: { matchId: string; token: string }, playmat: PlaymatSubmission | undefined, ): Promise { if (!playmat) return try { await setPlaymat(match.matchId, match.token, playmat) } catch (error) { if (!(error instanceof MatchError)) throw error } } app.post<{ Body: { name?: unknown; deck?: DeckSubmission; maxPlayers?: unknown; playmat?: PlaymatSubmission } }>( '/games', { bodyLimit: 4_500_000 }, async (request, reply) => { try { const match = createMatch(request.body?.name, request.body?.deck, request.body?.maxPlayers) await applyPlaymat(match, request.body?.playmat) return match } catch (error) { if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message }) throw error } }, ) app.post<{ Params: { id: string } Body: { name?: unknown; deck?: DeckSubmission; playmat?: PlaymatSubmission } }>( '/games/:id/join', { bodyLimit: 4_500_000 }, async (request, reply) => { try { const match = joinMatch(request.params.id, request.body?.name, request.body?.deck) await applyPlaymat(match, request.body?.playmat) return match } catch (error) { if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message }) throw error } }, ) app.post<{ Params: { id: string }; Body: { token?: string } }>( '/games/:id/leave', async (request, reply) => { leaveMatch(request.params.id, request.body?.token) return { ok: true } }, ) app.post<{ Params: { id: string }; Body: { token?: string } }>( '/games/:id/start', async (request, reply) => { startMatch(request.params.id, request.body?.token) return { ok: true } }, ) app.post<{ Params: { id: string }; Body: { token?: string; action?: ActionPayload } }>( '/games/:id/actions', async (request, reply) => { if (!request.body?.action) { return reply.code(400).send({ error: 'Body must include an action' }) } performAction(request.params.id, request.body.token, request.body.action) return { ok: true } }, ) app.post<{ Params: { id: string }; Body: { token?: string; deck?: DeckSubmission } }>( '/games/:id/deck', async (request, reply) => { setDeck(request.params.id, request.body?.token, request.body?.deck) return { ok: true } }, ) app.post<{ Params: { id: string }; Body: { token?: string; playmat?: PlaymatSubmission } }>( '/games/:id/playmat', { bodyLimit: 4_500_000 }, async (request, reply) => { try { const playmat = await setPlaymat(request.params.id, request.body?.token, request.body?.playmat) return { playmat } } catch (error) { if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message }) throw error } }, ) app.get<{ Params: { id: string } }>('/playmats/:id', async (request, reply) => { const image = await playmatImage(request.params.id) if (!image) return reply.code(404).send({ error: 'Playmat not found' }) return reply .header('Cache-Control', 'public, max-age=31536000, immutable') .header('X-Content-Type-Options', 'nosniff') .type('image/jpeg') .send(image) }) app.get<{ Params: { id: string }; Querystring: { token?: string } }>( '/games/:id/state', async request => getMatchView(request.params.id, request.query.token), ) app.get<{ Params: { id: string }; Querystring: { token?: string } }>( '/games/:id/events', (request, reply) => { const token = request.query.token // Validate before hijacking so errors keep their status codes. getMatchView(request.params.id, token) const origin = request.headers.origin const allowOrigin = origin && isAllowedOrigin(origin) ? origin : configuredOrigins?.[0] ?? 'http://localhost:3000' reply.hijack() reply.raw.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no', 'Access-Control-Allow-Origin': allowOrigin, Vary: 'Origin', }) reply.raw.write(': connected\n\n') const send = (state: MatchView): void => { reply.raw.write(`data: ${JSON.stringify(state)}\n\n`) } const unsubscribe = subscribe(request.params.id, token, send) const ping = setInterval(() => reply.raw.write(': ping\n\n'), 25_000) request.raw.on('close', () => { clearInterval(ping) unsubscribe() }) }, ) await connectDatabase() for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.on(signal, async () => { await app.close() await closeDatabase() process.exit(0) }) } await app.listen({ port: Number(process.env.PORT ?? 4000), host: '0.0.0.0', })