/** * lanternfall — the door. The rules are in `game.ts`, the dungeon in * `dungeon.ts` (pure), what happened in `db.ts`; here there is a table of * paths and a cookie. * * A delver belongs to one opaque HttpOnly cookie. It names nobody: the name * on the gravestone is derived from the cookie, which is also why a dead * delver's successor is somebody new rather than the same person again. */ import { randomBytes } from "node:crypto"; import { join } from "node:path"; import * as store from "./db.ts"; import { act, delverFor, isAction, viewFor } from "./game.ts"; import { endPage, gamePage, notFoundPage } from "./pages.ts"; const db = store.open(); const chrome = { env: process.env.FORGE_APP_ENV ?? "local", pull: process.env.FORGE_APP_PULL, commit: (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7), ssh: process.env.FORGE_APP_SSH, }; const HAND = "delver"; function handOf(request: Request): string | undefined { for (const part of (request.headers.get("cookie") ?? "").split(";")) { const [name, ...rest] = part.trim().split("="); if (name === HAND) { const value = rest.join("="); if (/^[a-f0-9]{32}$/.test(value)) return value; } } return undefined; } const newHand = (): string => randomBytes(16).toString("hex"); const handCookie = (hand: string): string => `${HAND}=${hand}; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax${ publicOrigin.startsWith("https:") ? "; Secure" : "" }`; // 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; // The security floor every response stands on. The one addition to the // scaffold's: script-src is still 'self', and the page's only script is a // file under /static — there is no inline script anywhere. const SECURITY: Record = { "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=()", ...(publicOrigin.startsWith("https:") ? { "strict-transport-security": "max-age=31536000" } : {}), }; const html = (body: string, status = 200): Response => new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", ...SECURITY } }); // 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. 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; }; // 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(); } /** Everything the screen needs for one delver, in one place. */ function screen(hand: string): string { const delver = delverFor(db, hand); const now = store.turn(db); return gamePage( chrome, delver, viewFor(db, delver), store.cacheState(db, delver.depth, now), store.heard(db, delver.id), store.recentGraves(db), store.topScores(db), store.countSeen(db), ); } export const server = Bun.serve({ port: Number(process.env.PORT ?? 8080), hostname: process.env.HOST ?? "127.0.0.1", async fetch(request) { const url = new URL(request.url); if (request.method === "POST" && !sameOrigin(request)) return new Response("forbidden", { status: 403 }); if (request.method === "POST" && url.pathname === "/act") { const form = await readForm(request); if (form === undefined) return new Response("too large", { status: 413, headers: SECURITY }); const hand = handOf(request) ?? newHand(); const headers = new Headers({ "set-cookie": handCookie(hand), ...SECURITY }); const wanted = String(form.get("action") ?? ""); if (!isAction(wanted)) { headers.set("location", "/"); return new Response(null, { status: 303, headers }); } const result = act(db, hand, wanted); // A run that ended gets its own page once; the next action sends // somebody new down. headers.set("location", result.died ? "/died" : result.climbedOut ? "/out" : "/"); return new Response(null, { status: 303, headers }); } const reading = request.method === "GET" || request.method === "HEAD"; if (reading && url.pathname === "/") { const seen = handOf(request); const hand = seen ?? newHand(); const full = html(screen(hand)); const headers = new Headers(full.headers); if (seen === undefined) headers.set("set-cookie", handCookie(hand)); return request.method === "HEAD" ? new Response(null, { status: full.status, headers }) : new Response(await full.text(), { status: full.status, headers }); } if (reading && (url.pathname === "/died" || url.pathname === "/out")) { const hand = handOf(request); const last = hand === undefined ? null : store.lastDelver(db, hand); if (last === null || last.state === "delving") return Response.redirect("/", 303); return html( endPage(chrome, last, last.state === "returned", store.heard(db, last.id)), ); } if (reading && 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 html(notFoundPage(chrome), 404); }, error(error) { console.error(error); return html("

Something went wrong

", 500); }, }); console.log( `lanternfall is open on http://${server.hostname}:${server.port} (${chrome.env}), turn ${store.turn(db)}`, );