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