quill/oracle Public Public: anyone can read this; nobody can change it.
workbenchthis machine
Files f5bda0fa490dc51bf72b54ac9776717cf7b1ae79
| 1 | /** |
| 2 | * oracle — the door. The security floor, the body caps and the table of |
| 3 | * paths live here; the mind is in `oracle.ts`, the ledger in `db.ts` and |
| 4 | * every page in `pages.ts`. |
| 5 | * |
| 6 | * The ledger is a SQLite file under FORGE_APP_DATA. Production and each |
| 7 | * preview get their own directory, so a preview starts with a copy of |
| 8 | * production's verdicts and never writes back to them. |
| 9 | */ |
| 10 | |
| 11 | import { join } from "node:path"; |
| 12 | import * as ledger from "./db.ts"; |
| 13 | import { isOutcome } from "./oracle.ts"; |
| 14 | import { homePage, ledgerPage, notFoundPage, verdictPage } from "./pages.ts"; |
| 15 | |
| 16 | const db = ledger.open(); |
| 17 | |
| 18 | const chrome = { |
| 19 | env: process.env.FORGE_APP_ENV ?? "local", |
| 20 | pull: process.env.FORGE_APP_PULL, |
| 21 | commit: (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7), |
| 22 | ssh: process.env.FORGE_APP_SSH, |
| 23 | }; |
| 24 | |
| 25 | // The security floor every response stands on. Scripts and styles come from |
| 26 | // this origin (inline styles allowed, inline scripts not), nothing frames us, |
| 27 | // browsers never guess a content type, and referrers stay on this site. |
| 28 | // The app's public address is what the forge told us, never the socket's. |
| 29 | const publicOrigin = new URL(process.env.FORGE_APP_URL ?? "http://localhost").origin; |
| 30 | |
| 31 | const SECURITY = { |
| 32 | "content-security-policy": |
| 33 | "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", |
| 34 | "x-content-type-options": "nosniff", |
| 35 | "referrer-policy": "strict-origin-when-cross-origin", |
| 36 | "permissions-policy": "camera=(), microphone=(), geolocation=()", |
| 37 | // Once served over https, always: browsers remember for a year. |
| 38 | ...(publicOrigin.startsWith("https:") |
| 39 | ? { "strict-transport-security": "max-age=31536000" } |
| 40 | : {}), |
| 41 | }; |
| 42 | const html = (body: string, status = 200): Response => |
| 43 | new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", ...SECURITY } }); |
| 44 | |
| 45 | // A browser on another site can make a person's browser POST here; it cannot |
| 46 | // make that request look same-origin. Browsers say where a request came from |
| 47 | // (Sec-Fetch-Site, or Origin); a request that names another site is refused. |
| 48 | const sameOrigin = (request: Request): boolean => { |
| 49 | const site = request.headers.get("sec-fetch-site"); |
| 50 | if (site !== null) return site === "same-origin" || site === "none"; |
| 51 | const origin = request.headers.get("origin"); |
| 52 | return origin === null || origin === publicOrigin; |
| 53 | }; |
| 54 | |
| 55 | // A request body is read up to a cap and no further, counting the bytes as |
| 56 | // they arrive. A declared Content-Length is a claim: a chunked request has |
| 57 | // none, and a lie is free. Undefined means "too large" — refuse it. Past the |
| 58 | // cap the rest is drained and dropped so the connection stays usable for |
| 59 | // the next request; past eight times the cap it is cut off instead. |
| 60 | const BODY_MAX = 64 * 1024; |
| 61 | async function readBody(request: Request, max = BODY_MAX): Promise<Uint8Array | undefined> { |
| 62 | const reader = request.body?.getReader(); |
| 63 | if (reader === undefined) return new Uint8Array(); |
| 64 | const parts: Uint8Array[] = []; |
| 65 | let size = 0; |
| 66 | for (;;) { |
| 67 | const { done, value } = await reader.read(); |
| 68 | if (done) break; |
| 69 | size += value.byteLength; |
| 70 | if (size > max) { |
| 71 | for (;;) { |
| 72 | const next = await reader.read(); |
| 73 | if (next.done) return undefined; |
| 74 | size += next.value.byteLength; |
| 75 | if (size > max * 8) { |
| 76 | await reader.cancel(); |
| 77 | return undefined; |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | parts.push(value); |
| 82 | } |
| 83 | const body = new Uint8Array(size); |
| 84 | let at = 0; |
| 85 | for (const part of parts) { |
| 86 | body.set(part, at); |
| 87 | at += part.byteLength; |
| 88 | } |
| 89 | return body; |
| 90 | } |
| 91 | |
| 92 | // The form fields of a capped body, decoded the way the browser sent them |
| 93 | // (a plain form or a multipart one), by handing the bytes back to a Request. |
| 94 | async function readForm(request: Request): Promise<FormData | undefined> { |
| 95 | const body = await readBody(request); |
| 96 | if (body === undefined) return undefined; |
| 97 | return new Request(request.url, { |
| 98 | method: "POST", |
| 99 | headers: { "content-type": request.headers.get("content-type") ?? "" }, |
| 100 | body, |
| 101 | }).formData(); |
| 102 | } |
| 103 | |
| 104 | export const server = Bun.serve({ |
| 105 | port: Number(process.env.PORT ?? 8080), |
| 106 | hostname: process.env.HOST ?? "127.0.0.1", |
| 107 | async fetch(request) { |
| 108 | const url = new URL(request.url); |
| 109 | if (request.method === "POST" && !sameOrigin(request)) |
| 110 | return new Response("forbidden", { status: 403 }); |
| 111 | |
| 112 | // Ask. An empty question is not a question; the same question is not a |
| 113 | // new one, which `ledger.ask` enforces in one statement. |
| 114 | if (request.method === "POST" && url.pathname === "/ask") { |
| 115 | const form = await readForm(request); |
| 116 | if (form === undefined) |
| 117 | return new Response("too large", { status: 413, headers: SECURITY }); |
| 118 | const question = String(form.get("question") ?? "").trim(); |
| 119 | if (question === "") return Response.redirect("/", 303); |
| 120 | const row = ledger.ask(db, question); |
| 121 | return Response.redirect(`/v/${row.id}`, 303); |
| 122 | } |
| 123 | |
| 124 | // Score a verdict. Only the three words count; anything else is a |
| 125 | // client inventing states for the ledger to hold. |
| 126 | const judging = url.pathname.match(/^\/v\/(\d{1,15})\/judge$/); |
| 127 | if (request.method === "POST" && judging) { |
| 128 | const form = await readForm(request); |
| 129 | if (form === undefined) |
| 130 | return new Response("too large", { status: 413, headers: SECURITY }); |
| 131 | const outcome = String(form.get("outcome") ?? ""); |
| 132 | const id = Number(judging[1]); |
| 133 | if (!isOutcome(outcome) || ledger.get(db, id) === null) |
| 134 | return html(notFoundPage(chrome), 404); |
| 135 | ledger.judge(db, id, outcome); |
| 136 | return Response.redirect(`/v/${id}`, 303); |
| 137 | } |
| 138 | |
| 139 | const reading = request.method === "GET" || request.method === "HEAD"; |
| 140 | |
| 141 | if (reading && url.pathname === "/") { |
| 142 | const full = html(homePage(chrome, ledger.recent(db), ledger.scored(db))); |
| 143 | return request.method === "HEAD" |
| 144 | ? new Response(null, { status: full.status, headers: full.headers }) |
| 145 | : full; |
| 146 | } |
| 147 | |
| 148 | const permalink = url.pathname.match(/^\/v\/(\d{1,15})$/); |
| 149 | if (reading && permalink) { |
| 150 | const row = ledger.get(db, Number(permalink[1])); |
| 151 | return row === null |
| 152 | ? html(notFoundPage(chrome), 404) |
| 153 | : html(verdictPage(chrome, row)); |
| 154 | } |
| 155 | |
| 156 | if (reading && url.pathname === "/ledger") { |
| 157 | const show = url.searchParams.get("show") ?? "all"; |
| 158 | const filter = ledger.isFilter(show) ? show : "all"; |
| 159 | return html(ledgerPage(chrome, ledger.ledger(db, filter), filter)); |
| 160 | } |
| 161 | |
| 162 | // Files under ./static are served as they are, cached for a year: name |
| 163 | // them by content (app.3f2a9c.js) and a change is a new name, never a |
| 164 | // stale cache. The path is confined to the directory. |
| 165 | if (reading && url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { |
| 166 | const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1))); |
| 167 | if (await file.exists()) |
| 168 | return new Response(file, { |
| 169 | headers: { "cache-control": "public, max-age=31536000, immutable", ...SECURITY }, |
| 170 | }); |
| 171 | } |
| 172 | |
| 173 | return html(notFoundPage(chrome), 404); |
| 174 | }, |
| 175 | // A bug answers with the floor and nothing else: never the runtime's own |
| 176 | // error page, which carries source and paths, and never without the |
| 177 | // headers. The detail goes to the log, where it belongs. |
| 178 | error(error) { |
| 179 | console.error(error); |
| 180 | return html("<h1>Something went wrong</h1>", 500); |
| 181 | }, |
| 182 | }); |
| 183 | |
| 184 | console.log( |
| 185 | `the oracle is listening on http://${server.hostname}:${server.port} (${chrome.env})`, |
| 186 | ); |