fable/val Public Public: anyone can read this; nobody can change it.
forked from benjivers/val
workbenchthis machine
Files 9437cb3d70375fd62d025a6905df31145f578113
| 1 | /** |
| 2 | * val — the door. Routing, sessions, sockets and the security floor; the |
| 3 | * game itself is in src/match.ts and the live one in src/arena.ts. |
| 4 | * |
| 5 | * A seat belongs to a session cookie, so the same browser gets the same |
| 6 | * player back across a reload, and a socket is only ever given a seat the |
| 7 | * server chose. |
| 8 | */ |
| 9 | |
| 10 | import { createHash, randomUUID } from "node:crypto"; |
| 11 | import { join } from "node:path"; |
| 12 | import { AGENTS, SLOTS } from "./abilities.ts"; |
| 13 | import { attach, command, findPlayer, match, release, snapshot, startArena, takeSeat, type Command } from "./arena.ts"; |
| 14 | import { recentResults } from "./db.ts"; |
| 15 | import { gridRows, TILE } from "./map.ts"; |
| 16 | import { gamePage } from "./pages/game.ts"; |
| 17 | |
| 18 | const env = process.env.FORGE_APP_ENV ?? "local"; |
| 19 | const pull = process.env.FORGE_APP_PULL; |
| 20 | const commit = (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7); |
| 21 | const where = env === "preview" ? `preview of pull #${pull ?? "?"}` : env; |
| 22 | |
| 23 | // The security floor every response stands on. Scripts and styles come from |
| 24 | // this origin (inline styles allowed, inline scripts not), nothing frames us, |
| 25 | // browsers never guess a content type, and referrers stay on this site. |
| 26 | // The app's public address is what the forge told us, never the socket's. |
| 27 | const publicOrigin = new URL(process.env.FORGE_APP_URL ?? "http://localhost").origin; |
| 28 | |
| 29 | const SECURITY = { |
| 30 | "content-security-policy": |
| 31 | "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", |
| 32 | "x-content-type-options": "nosniff", |
| 33 | "referrer-policy": "strict-origin-when-cross-origin", |
| 34 | "permissions-policy": "camera=(), microphone=(), geolocation=()", |
| 35 | // Once served over https, always: browsers remember for a year. |
| 36 | ...(publicOrigin.startsWith("https:") |
| 37 | ? { "strict-transport-security": "max-age=31536000" } |
| 38 | : {}), |
| 39 | }; |
| 40 | const html = (body: string, status = 200, extra: Record<string, string> = {}): Response => |
| 41 | new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", ...SECURITY, ...extra } }); |
| 42 | |
| 43 | // A browser on another site can make a person's browser POST here; it cannot |
| 44 | // make that request look same-origin. Browsers say where a request came from |
| 45 | // (Sec-Fetch-Site, or Origin); a request that names another site is refused. |
| 46 | // The address the forge published is the one that counts, but a browser |
| 47 | // reaching the app by another name (localhost, an IP, a tunnel) sends that |
| 48 | // host in both the URL and the Origin — a cross-site request never can. |
| 49 | const sameOrigin = (request: Request): boolean => { |
| 50 | const site = request.headers.get("sec-fetch-site"); |
| 51 | if (site !== null) return site === "same-origin" || site === "none"; |
| 52 | const origin = request.headers.get("origin"); |
| 53 | return origin === null || origin === publicOrigin || origin === new URL(request.url).origin; |
| 54 | }; |
| 55 | |
| 56 | // A request body is read up to a cap and no further, counting the bytes as |
| 57 | // they arrive. A declared Content-Length is a claim: a chunked request has |
| 58 | // none, and a lie is free. Undefined means "too large" — refuse it. Past the |
| 59 | // cap the rest is drained and dropped so the connection stays usable for |
| 60 | // the next request; past eight times the cap it is cut off instead. |
| 61 | const BODY_MAX = 64 * 1024; |
| 62 | async function readBody(request: Request, max = BODY_MAX): Promise<Uint8Array | undefined> { |
| 63 | const reader = request.body?.getReader(); |
| 64 | if (reader === undefined) return new Uint8Array(); |
| 65 | const parts: Uint8Array[] = []; |
| 66 | let size = 0; |
| 67 | for (;;) { |
| 68 | const { done, value } = await reader.read(); |
| 69 | if (done) break; |
| 70 | size += value.byteLength; |
| 71 | if (size > max) { |
| 72 | for (;;) { |
| 73 | const next = await reader.read(); |
| 74 | if (next.done) return undefined; |
| 75 | size += next.value.byteLength; |
| 76 | if (size > max * 8) { |
| 77 | await reader.cancel(); |
| 78 | return undefined; |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | parts.push(value); |
| 83 | } |
| 84 | const body = new Uint8Array(size); |
| 85 | let at = 0; |
| 86 | for (const part of parts) { |
| 87 | body.set(part, at); |
| 88 | at += part.byteLength; |
| 89 | } |
| 90 | return body; |
| 91 | } |
| 92 | |
| 93 | // The form fields of a capped body, decoded the way the browser sent them |
| 94 | // (a plain form or a multipart one), by handing the bytes back to a Request. |
| 95 | async function readForm(request: Request): Promise<FormData | undefined> { |
| 96 | const body = await readBody(request); |
| 97 | if (body === undefined) return undefined; |
| 98 | return new Request(request.url, { |
| 99 | method: "POST", |
| 100 | headers: { "content-type": request.headers.get("content-type") ?? "" }, |
| 101 | body, |
| 102 | }).formData(); |
| 103 | } |
| 104 | |
| 105 | // ------------------------------------------------------------- the client |
| 106 | |
| 107 | // The client is a handful of small modules under static/ — the renderer, the |
| 108 | // map, the crosshair, the ray maths — bundled into one file at start-up so a |
| 109 | // browser makes one request and the maths can still be imported by the tests. |
| 110 | // It is named by its content: a change is a new URL, so a year-long cache is |
| 111 | // never stale. |
| 112 | const built = await Bun.build({ |
| 113 | entrypoints: [join(import.meta.dir, "..", "static", "val.js")], |
| 114 | target: "browser", |
| 115 | }); |
| 116 | if (!built.success) throw new AggregateError(built.logs, "the client would not build"); |
| 117 | const scriptBody = await built.outputs[0]!.text(); |
| 118 | const scriptHash = createHash("sha256").update(scriptBody).digest("hex").slice(0, 10); |
| 119 | const scriptUrl = `/static/val.${scriptHash}.js`; |
| 120 | |
| 121 | // ------------------------------------------------------------- sessions |
| 122 | |
| 123 | const cookies = (request: Request): Record<string, string> => { |
| 124 | const out: Record<string, string> = {}; |
| 125 | for (const part of (request.headers.get("cookie") ?? "").split(";")) { |
| 126 | const at = part.indexOf("="); |
| 127 | if (at < 1) continue; |
| 128 | out[part.slice(0, at).trim()] = decodeURIComponent(part.slice(at + 1).trim()); |
| 129 | } |
| 130 | return out; |
| 131 | }; |
| 132 | |
| 133 | const SESSION = "val_session"; |
| 134 | const NAME = "val_name"; |
| 135 | |
| 136 | /** A name is one line of plain text, sixteen characters, nothing clever. */ |
| 137 | const cleanName = (raw: unknown): string => { |
| 138 | const text = String(raw ?? "") |
| 139 | .replace(/[\u0000-\u001f\u007f<>"'\\]/g, "") |
| 140 | .trim() |
| 141 | .slice(0, 16); |
| 142 | return text.length >= 1 ? text : ""; |
| 143 | }; |
| 144 | |
| 145 | const setCookie = (name: string, value: string, httpOnly: boolean): string => |
| 146 | `${name}=${encodeURIComponent(value)}; Path=/; SameSite=Lax; Max-Age=604800${httpOnly ? "; HttpOnly" : ""}${publicOrigin.startsWith("https:") ? "; Secure" : ""}`; |
| 147 | |
| 148 | type SocketData = { session: string; playerId: string }; |
| 149 | |
| 150 | // ---------------------------------------------------------------- routing |
| 151 | |
| 152 | export const server = Bun.serve<SocketData, Record<string, never>>({ |
| 153 | port: Number(process.env.PORT ?? 8080), |
| 154 | hostname: process.env.HOST ?? "127.0.0.1", |
| 155 | async fetch(request, self) { |
| 156 | const url = new URL(request.url); |
| 157 | const jar = cookies(request); |
| 158 | const session = jar[SESSION] ?? randomUUID(); |
| 159 | const fresh = jar[SESSION] === undefined; |
| 160 | |
| 161 | if (request.method === "POST" && !sameOrigin(request)) |
| 162 | return new Response("forbidden", { status: 403, headers: SECURITY }); |
| 163 | |
| 164 | if (request.method === "POST" && url.pathname === "/join") { |
| 165 | const form = await readForm(request); |
| 166 | if (form === undefined) return new Response("too large", { status: 413, headers: SECURITY }); |
| 167 | const name = cleanName(form.get("name")); |
| 168 | const headers = new Headers({ location: "/", ...SECURITY }); |
| 169 | headers.append("set-cookie", setCookie(SESSION, session, true)); |
| 170 | if (name) { |
| 171 | headers.append("set-cookie", setCookie(NAME, name, false)); |
| 172 | takeSeat(session, name); |
| 173 | } |
| 174 | return new Response(null, { status: 303, headers }); |
| 175 | } |
| 176 | |
| 177 | // The socket: one seat per session, taken from a bot where it stands. |
| 178 | if (url.pathname === "/ws") { |
| 179 | if (!sameOrigin(request)) return new Response("forbidden", { status: 403, headers: SECURITY }); |
| 180 | const name = cleanName(jar[NAME]) || `Guest-${session.slice(0, 4)}`; |
| 181 | const player = takeSeat(session, name); |
| 182 | if (!player) return new Response("no seats", { status: 503, headers: SECURITY }); |
| 183 | const upgraded = self.upgrade(request, { data: { session, playerId: player.id } }); |
| 184 | return upgraded ? undefined : new Response("expected a websocket", { status: 426, headers: SECURITY }); |
| 185 | } |
| 186 | |
| 187 | if (url.pathname === "/" && (request.method === "GET" || request.method === "HEAD")) { |
| 188 | const body = gamePage({ |
| 189 | state: match(), |
| 190 | script: scriptUrl, |
| 191 | name: cleanName(jar[NAME]), |
| 192 | env: where, |
| 193 | commit, |
| 194 | ssh: process.env.FORGE_APP_SSH, |
| 195 | results: recentResults(3), |
| 196 | }); |
| 197 | const response = html(body, 200, fresh ? { "set-cookie": setCookie(SESSION, session, true) } : {}); |
| 198 | return request.method === "HEAD" |
| 199 | ? new Response(null, { status: response.status, headers: response.headers }) |
| 200 | : response; |
| 201 | } |
| 202 | |
| 203 | // The agents and their kits: what every ability does, its price and its |
| 204 | // charges, so the buy panel can label itself. The same table the server |
| 205 | // plays by, and no secret in it. |
| 206 | if (url.pathname === "/agents.json" && (request.method === "GET" || request.method === "HEAD")) |
| 207 | return Response.json( |
| 208 | { |
| 209 | agents: AGENTS.map((a) => ({ |
| 210 | id: a.id, |
| 211 | name: a.name, |
| 212 | role: a.role, |
| 213 | blurb: a.blurb, |
| 214 | abilities: Object.fromEntries( |
| 215 | SLOTS.map((slot) => { |
| 216 | const ability = a.abilities[slot]; |
| 217 | return [ |
| 218 | slot, |
| 219 | { |
| 220 | name: ability.name, |
| 221 | cost: ability.cost, |
| 222 | charges: ability.charges, |
| 223 | cooldown: ability.cooldown, |
| 224 | points: ability.points, |
| 225 | text: ability.text, |
| 226 | }, |
| 227 | ]; |
| 228 | }), |
| 229 | ), |
| 230 | })), |
| 231 | }, |
| 232 | { headers: { "cache-control": "public, max-age=300", ...SECURITY } }, |
| 233 | ); |
| 234 | |
| 235 | // The map is the same for everybody and changes only when the code does. |
| 236 | if (url.pathname === "/map.json" && (request.method === "GET" || request.method === "HEAD")) |
| 237 | return Response.json( |
| 238 | { rows: gridRows(), tile: TILE }, |
| 239 | { headers: { "cache-control": "public, max-age=300", ...SECURITY } }, |
| 240 | ); |
| 241 | |
| 242 | if (url.pathname === scriptUrl) |
| 243 | return new Response(scriptBody, { |
| 244 | headers: { |
| 245 | "content-type": "text/javascript; charset=utf-8", |
| 246 | "cache-control": "public, max-age=31536000, immutable", |
| 247 | ...SECURITY, |
| 248 | }, |
| 249 | }); |
| 250 | |
| 251 | // Files under ./static are served as they are, cached for a year: name |
| 252 | // them by content and a change is a new name, never a stale cache. The |
| 253 | // path is confined to the directory. |
| 254 | if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { |
| 255 | const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1))); |
| 256 | if (await file.exists()) |
| 257 | return new Response(file, { |
| 258 | headers: { "cache-control": "public, max-age=31536000, immutable", ...SECURITY }, |
| 259 | }); |
| 260 | } |
| 261 | return new Response("not found", { status: 404, headers: SECURITY }); |
| 262 | }, |
| 263 | |
| 264 | websocket: { |
| 265 | maxPayloadLength: 4 * 1024, |
| 266 | open(socket) { |
| 267 | const { session, playerId } = socket.data; |
| 268 | attach(session, playerId, (data) => socket.send(data)); |
| 269 | socket.send(snapshot(playerId)); |
| 270 | }, |
| 271 | message(socket, raw) { |
| 272 | // Anything a client sends is a claim: it is parsed, bounded and given |
| 273 | // to the arena, which decides what it is allowed to mean. |
| 274 | if (typeof raw !== "string" || raw.length > 4096) return; |
| 275 | let parsed: unknown; |
| 276 | try { |
| 277 | parsed = JSON.parse(raw); |
| 278 | } catch { |
| 279 | return; |
| 280 | } |
| 281 | if (typeof parsed !== "object" || parsed === null) return; |
| 282 | command(socket.data.playerId, parsed as Command); |
| 283 | }, |
| 284 | close(socket) { |
| 285 | release(socket.data.session); |
| 286 | }, |
| 287 | }, |
| 288 | |
| 289 | // A bug answers with the floor and nothing else: never the runtime's own |
| 290 | // error page, which carries source and paths, and never without the |
| 291 | // headers. The detail goes to the log, where it belongs. |
| 292 | error(error) { |
| 293 | console.error(error); |
| 294 | return html("<h1>Something went wrong</h1>", 500); |
| 295 | }, |
| 296 | }); |
| 297 | |
| 298 | startArena(); |
| 299 | |
| 300 | console.log(`val listening on http://${server.hostname}:${server.port} (${env})`); |
| 301 | export { findPlayer }; |