#!/usr/bin/env node /** * serve.mjs — the production entry point (PLAN.md §6, D48, D56). * * `npm start` runs `applyBrand.mjs` and then this, instead of `dist/server/entry.mjs` * directly. It is a thin wrapper around the adapter's own handler and exists for three * reasons, two of them things `@astrojs/node` gets wrong. * * --------------------------------------------------------------------------------------- * 1. THE ADAPTER SERVES THE WRONG PAGE'S CONTENT-SECURITY-POLICY * --------------------------------------------------------------------------------------- * `@astrojs/node`'s `staticHeaders` writes one policy per prerendered route into * `dist/_headers.json` and looks the right one up per request. The lookup, in * `dist/serve-static.js`, is: * * headersMap.find((header) => header.pathname.includes(baselessPathname)) * * `String.includes` — a SUBSTRING test, not equality, taking the first match. So: * * - `/modules/` matches the record for `/docs/modules/building-a-module`, * - `/architecture/` matches `/docs/architecture/...`, * - and `/`, which is a substring of every path in the file, matches whichever record * happens to be first — here `/404`. * * Every prerendered page was therefore served some other page's policy. Because the * policies are per-page hash lists, that is not a cosmetic mismatch: the browser refused * the page's own stylesheet. `/modules/` and `/architecture/` rendered unstyled sections * with `Refused to apply inline style` in a console, and the homepage only looked fine * because it happens to share a hash with the 404 page. * * Astro's static-header machinery is otherwise exactly what §6 wants, so this replaces the * lookup rather than the mechanism: the same `_headers.json`, matched by pathname * EQUALITY. The workaround is deliberately small and obvious so it can be deleted whole * when the upstream `find` is fixed — the check for that is whether `/modules/` and * `/docs/modules/building-a-module` are served different policies. * * --------------------------------------------------------------------------------------- * 2. THE HEADERS THAT ARE NOT CSP * --------------------------------------------------------------------------------------- * A few security headers have nothing to do with Astro and no other place to live. They * are set here rather than written into an operator's reverse-proxy configuration (D48, * again): the container should be correct on its own, and a proxy someone else configures * is a promise this repository cannot check. * * The two routes that render per request — `/beta` and `/brand/*` — have no entry in * `_headers.json`, because nothing prerendered them. They get `frame-ancestors 'none'` on * its own, which is the one directive a `` CSP cannot express and therefore the one * thing Astro's per-page meta tag leaves them missing. */ import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; const here = path.dirname(fileURLToPath(import.meta.url)); const root = path.join(here, '..'); const port = Number(process.env.PORT ?? 4321); const host = process.env.HOST ?? '0.0.0.0'; /* --------------------------------------------------------------------------------------- The policies, matched exactly --------------------------------------------------------------------------------------- */ const normalise = (pathname) => { const clean = pathname.split('?')[0].split('#')[0]; const trimmed = clean.replace(/\/+$/, ''); return trimmed === '' ? '/' : trimmed; }; const policies = new Map(); const headersFile = path.join(root, 'dist', '_headers.json'); if (fs.existsSync(headersFile)) { for (const record of Object.values(JSON.parse(fs.readFileSync(headersFile, 'utf8')))) { const csp = record.headers?.find((h) => h.key.toLowerCase() === 'content-security-policy'); if (csp) policies.set(normalise(record.pathname), csp.value); } } else { // Not fatal: the site still serves, with the per-page policy Astro also emits. // Loud, because a deployment silently losing its response-header CSP is exactly what §6 // is trying to prevent. console.error( '[serve] dist/_headers.json is missing — pages will be served without a CSP response\n' + ' header. Check that astro.config.mjs still sets `staticHeaders: true`.' ); } const FRAME_ONLY = "frame-ancestors 'none'"; /** * Headers with no page-by-page component. Each is the browser default made explicit, and * each closes something the CSP does not: * * - `X-Content-Type-Options` stops a browser guessing that a .txt is HTML. * - `Referrer-Policy` keeps the path of the page a reader came from out of requests to * other origins — there are none today (D9), and this is what keeps that true if a * link is ever followed off-site. * - `X-Frame-Options` says again, for anything too old to honour `frame-ancestors`. * - `Permissions-Policy` turns off hardware this site has no reason to ask for. A * marketing page requesting a camera should be impossible, not merely unlikely. */ const STATIC_HEADERS = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()', }; /* --------------------------------------------------------------------------------------- The server --------------------------------------------------------------------------------------- */ // The adapter's entry starts its own listener on import unless this is set. process.env.ASTRO_NODE_AUTOSTART = 'disabled'; // `pathToFileURL`, not the bare path: on Windows an absolute path starts with a drive // letter, and Node's ESM loader reads `c:` as an unsupported URL scheme. const { handler } = await import(pathToFileURL(path.join(root, 'dist', 'server', 'entry.mjs')).href); /* --------------------------------------------------------------------------------------- 3. THE FORWARDED HEADERS THE ADAPTER DOES NOT READ --------------------------------------------------------------------------------------- */ /** * Make the request look, to the adapter, like what the browser actually sent. * * `@astrojs/node` builds the URL of every request from the connection and the `Host` * header alone — `astro/app/node`'s `createRequestFromNodeRequest`: * * const isEncrypted = "encrypted" in req.socket && req.socket.encrypted; * const protocol = isEncrypted ? "https" : "http"; * * `x-forwarded-proto` is never consulted on this path. (`security.allowedDomains` does not * help: on this code path it gates only whether `Astro.clientAddress` may come from * `x-forwarded-for`.) * * Behind a proxy that terminates TLS — which is how this site is deployed, and the only * way it is deployed — that is fatal to the one route that accepts a POST. The browser * sends `Origin: https://runicgateway.com`; the container computes `http://runicgateway.com` * because its own socket is plaintext; and Astro's CSRF middleware compares the two for * EQUALITY: * * const isSameOrigin = request.headers.get("origin") === url.origin; * * So every beta signup, from every visitor, is answered `403 Cross-site POST form * submissions are forbidden`. No proxy configuration can fix it — a proxy cannot make this * container's socket encrypted — and nothing else on the site changes, so the symptom is a * form that silently refuses everyone while fifty pages look perfectly healthy. * * Both headers are trusted unconditionally, with no flag to set. The image is meant to be * deployed and work: it publishes on loopback for a proxy to reach, and an operator who has * to discover a `TRUST_PROXY` variable to make the signup work is an operator who ships a * dead form. Trusting them costs nothing here — a cross-site form submission cannot make a * victim's browser send `x-forwarded-proto`, so the CSRF check is exactly as strong as it * was, and the site has no cookie, session or credential to protect in the first place. * * `x-forwarded-host` is handled for the same reason at one remove: most proxies pass `Host` * through untouched, but some rewrite it to the upstream address and put the real name here * instead, which produces the identical mismatch. */ const firstForwarded = (value) => value?.toString().split(',')[0].trim(); const applyForwardedHeaders = (req) => { const proto = firstForwarded(req.headers['x-forwarded-proto']); if (proto === 'https' && !req.socket.encrypted) { // What `"encrypted" in req.socket` reads. Defined on the socket rather than passed // along, because the adapter is given the raw request and looks there itself. Object.defineProperty(req.socket, 'encrypted', { value: true, configurable: true }); } const forwardedHost = firstForwarded(req.headers['x-forwarded-host']); if (forwardedHost && !/[/\\]/.test(forwardedHost)) { req.headers.host = forwardedHost; } }; const server = http.createServer((req, res) => { applyForwardedHeaders(req); const policy = policies.get(normalise(req.url ?? '/')); for (const [key, value] of Object.entries(STATIC_HEADERS)) res.setHeader(key, value); res.setHeader('Content-Security-Policy', policy ?? FRAME_ONLY); /** * The adapter will set its own (wrong) `Content-Security-Policy` from inside the static * handler, overwriting what was just set. Rather than race it, every later attempt to * set that one header is ignored — the correct value is already on the response, and * this request's policy cannot change halfway through serving it. */ const setHeader = res.setHeader.bind(res); res.setHeader = (name, value) => { if (String(name).toLowerCase() === 'content-security-policy') return res; return setHeader(name, value); }; handler(req, res); }); server.listen(port, host, () => { console.log(`[serve] listening on http://${host}:${port} — ${policies.size} prerendered policies`); });