/** * val — the door. Routing, sessions, sockets and the security floor; the * game itself is in src/match.ts and the live one in src/arena.ts. * * A seat belongs to a session cookie, so the same browser gets the same * player back across a reload, and a socket is only ever given a seat the * server chose. */ import { createHash, randomUUID } from "node:crypto"; import { join } from "node:path"; import { AGENTS, SLOTS } from "./abilities.ts"; import { addressCapped, attach, command, findPlayer, match, release, snapshot, startArena, takeSeat, unwatch, watch, type Command, } from "./arena.ts"; import { recentResults } from "./db.ts"; import { gridRows, TILE } from "./map.ts"; import { gamePage } from "./pages/game.ts"; const env = process.env.FORGE_APP_ENV ?? "local"; const pull = process.env.FORGE_APP_PULL; const commit = (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7); const where = env === "preview" ? `preview of pull #${pull ?? "?"}` : env; // The security floor every response stands on. Scripts and styles come from // this origin (inline styles allowed, inline scripts not), nothing frames us, // browsers never guess a content type, and referrers stay on this site. // The app's public address is what the forge told us, never the socket's. const publicOrigin = new URL(process.env.FORGE_APP_URL ?? "http://localhost").origin; const SECURITY = { "content-security-policy": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", "x-content-type-options": "nosniff", "referrer-policy": "strict-origin-when-cross-origin", "permissions-policy": "camera=(), microphone=(), geolocation=()", // Once served over https, always: browsers remember for a year. ...(publicOrigin.startsWith("https:") ? { "strict-transport-security": "max-age=31536000" } : {}), }; const html = (body: string, status = 200, extra: Record = {}): Response => new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", ...SECURITY, ...extra } }); // A browser on another site can make a person's browser POST here; it cannot // make that request look same-origin. Browsers say where a request came from // (Sec-Fetch-Site, or Origin); a request that names another site is refused. // The address the forge published is the one that counts, but a browser // reaching the app by another name (localhost, an IP, a tunnel) sends that // host in both the URL and the Origin — a cross-site request never can. const sameOrigin = (request: Request): boolean => { const site = request.headers.get("sec-fetch-site"); if (site !== null) return site === "same-origin" || site === "none"; const origin = request.headers.get("origin"); return origin === null || origin === publicOrigin || origin === new URL(request.url).origin; }; // A request body is read up to a cap and no further, counting the bytes as // they arrive. A declared Content-Length is a claim: a chunked request has // none, and a lie is free. Undefined means "too large" — refuse it. Past the // cap the rest is drained and dropped so the connection stays usable for // the next request; past eight times the cap it is cut off instead. const BODY_MAX = 64 * 1024; async function readBody(request: Request, max = BODY_MAX): Promise { const reader = request.body?.getReader(); if (reader === undefined) return new Uint8Array(); const parts: Uint8Array[] = []; let size = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > max) { for (;;) { const next = await reader.read(); if (next.done) return undefined; size += next.value.byteLength; if (size > max * 8) { await reader.cancel(); return undefined; } } } parts.push(value); } const body = new Uint8Array(size); let at = 0; for (const part of parts) { body.set(part, at); at += part.byteLength; } return body; } // The form fields of a capped body, decoded the way the browser sent them // (a plain form or a multipart one), by handing the bytes back to a Request. async function readForm(request: Request): Promise { const body = await readBody(request); if (body === undefined) return undefined; return new Request(request.url, { method: "POST", headers: { "content-type": request.headers.get("content-type") ?? "" }, body, }).formData(); } // ------------------------------------------------------------- the client // The client is a handful of small modules under static/ — the renderer, the // map, the crosshair, the ray maths — bundled into one file at start-up so a // browser makes one request and the maths can still be imported by the tests. // It is named by its content: a change is a new URL, so a year-long cache is // never stale. const built = await Bun.build({ entrypoints: [join(import.meta.dir, "..", "static", "val.js")], target: "browser", }); if (!built.success) throw new AggregateError(built.logs, "the client would not build"); const scriptBody = await built.outputs[0]!.text(); const scriptHash = createHash("sha256").update(scriptBody).digest("hex").slice(0, 10); const scriptUrl = `/static/val.${scriptHash}.js`; // ------------------------------------------------------------- sessions const cookies = (request: Request): Record => { const out: Record = {}; for (const part of (request.headers.get("cookie") ?? "").split(";")) { const at = part.indexOf("="); if (at < 1) continue; out[part.slice(0, at).trim()] = decodeURIComponent(part.slice(at + 1).trim()); } return out; }; const SESSION = "val_session"; const NAME = "val_name"; /** A name is one line of plain text, sixteen characters, nothing clever. */ const cleanName = (raw: unknown): string => { const text = String(raw ?? "") .replace(/[\u0000-\u001f\u007f<>"'\\]/g, "") .trim() .slice(0, 16); return text.length >= 1 ? text : ""; }; const setCookie = (name: string, value: string, httpOnly: boolean): string => `${name}=${encodeURIComponent(value)}; Path=/; SameSite=Lax; Max-Age=604800${httpOnly ? "; HttpOnly" : ""}${publicOrigin.startsWith("https:") ? "; Secure" : ""}`; type SocketData = { session: string; playerId: string; address: string; token: string; spectator: boolean }; // ---------------------------------------------------------------- routing export const server = Bun.serve>({ port: Number(process.env.PORT ?? 8080), hostname: process.env.HOST ?? "127.0.0.1", async fetch(request, self) { const url = new URL(request.url); const jar = cookies(request); const session = jar[SESSION] ?? randomUUID(); const fresh = jar[SESSION] === undefined; // A cookie costs one HTTP request, so it names a browser, not a person — // the address is the one thing here a single machine cannot mint a // second one of, which is what a playing seat is actually rationed by. const address = self?.requestIP?.(request)?.address ?? ""; if (request.method === "POST" && !sameOrigin(request)) return new Response("forbidden", { status: 403, headers: SECURITY }); if (request.method === "POST" && url.pathname === "/join") { const form = await readForm(request); if (form === undefined) return new Response("too large", { status: 413, headers: SECURITY }); const name = cleanName(form.get("name")); const headers = new Headers({ location: "/", ...SECURITY }); headers.append("set-cookie", setCookie(SESSION, session, true)); if (name) { headers.append("set-cookie", setCookie(NAME, name, false)); takeSeat(address, session, name); } return new Response(null, { status: 303, headers }); } // The socket: one playing seat per address, taken from a bot where it // stands. A connection with no session the page minted, or one whose // address already plays under a different session, gets no seat at all — // it watches instead, with a view built for no side, rather than being // handed the vision a seat would otherwise give it on top of the one it // already has. if (url.pathname === "/ws") { if (!sameOrigin(request)) return new Response("forbidden", { status: 403, headers: SECURITY }); const token = randomUUID(); if (fresh || addressCapped(address, session)) { const upgraded = self.upgrade(request, { data: { session, playerId: "", address, token, spectator: true } }); return upgraded ? undefined : new Response("expected a websocket", { status: 426, headers: SECURITY }); } const name = cleanName(jar[NAME]) || `Guest-${session.slice(0, 4)}`; const player = takeSeat(address, session, name); if (!player) return new Response("no seats", { status: 503, headers: SECURITY }); const upgraded = self.upgrade(request, { data: { session, playerId: player.id, address, token, spectator: false } }); return upgraded ? undefined : new Response("expected a websocket", { status: 426, headers: SECURITY }); } if (url.pathname === "/" && (request.method === "GET" || request.method === "HEAD")) { const body = gamePage({ state: match(), script: scriptUrl, name: cleanName(jar[NAME]), env: where, commit, ssh: process.env.FORGE_APP_SSH, results: recentResults(3), }); const response = html(body, 200, fresh ? { "set-cookie": setCookie(SESSION, session, true) } : {}); return request.method === "HEAD" ? new Response(null, { status: response.status, headers: response.headers }) : response; } // The agents and their kits: what every ability does, its price and its // charges, so the buy panel can label itself. The same table the server // plays by, and no secret in it. if (url.pathname === "/agents.json" && (request.method === "GET" || request.method === "HEAD")) return Response.json( { agents: AGENTS.map((a) => ({ id: a.id, name: a.name, role: a.role, blurb: a.blurb, abilities: Object.fromEntries( SLOTS.map((slot) => { const ability = a.abilities[slot]; return [ slot, { name: ability.name, cost: ability.cost, charges: ability.charges, cooldown: ability.cooldown, points: ability.points, text: ability.text, }, ]; }), ), })), }, { headers: { "cache-control": "public, max-age=300", ...SECURITY } }, ); // The map is the same for everybody and changes only when the code does. if (url.pathname === "/map.json" && (request.method === "GET" || request.method === "HEAD")) return Response.json( { rows: gridRows(), tile: TILE }, { headers: { "cache-control": "public, max-age=300", ...SECURITY } }, ); if (url.pathname === scriptUrl) return new Response(scriptBody, { headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=31536000, immutable", ...SECURITY, }, }); // Files under ./static are served as they are, cached for a year: name // them by content and a change is a new name, never a stale cache. The // path is confined to the directory. if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1))); if (await file.exists()) return new Response(file, { headers: { "cache-control": "public, max-age=31536000, immutable", ...SECURITY }, }); } return new Response("not found", { status: 404, headers: SECURITY }); }, websocket: { maxPayloadLength: 4 * 1024, open(socket) { const { session, playerId, address, token, spectator } = socket.data; if (spectator) return void watch(token, (data) => socket.send(data)); attach(session, playerId, address, token, (data) => socket.send(data)); socket.send(snapshot(playerId)); }, message(socket, raw) { if (socket.data.spectator) return; // a watcher has no seat to drive // Anything a client sends is a claim: it is parsed, bounded and given // to the arena, which decides what it is allowed to mean. if (typeof raw !== "string" || raw.length > 4096) return; let parsed: unknown; try { parsed = JSON.parse(raw); } catch { return; } if (typeof parsed !== "object" || parsed === null) return; command(socket.data.playerId, parsed as Command); }, close(socket) { if (socket.data.spectator) return void unwatch(socket.data.token); release(socket.data.session, socket.data.token); }, }, // A bug answers with the floor and nothing else: never the runtime's own // error page, which carries source and paths, and never without the // headers. The detail goes to the log, where it belongs. error(error) { console.error(error); return html("

Something went wrong

", 500); }, }); startArena(); console.log(`val listening on http://${server.hostname}:${server.port} (${env})`); export { findPlayer };