From a1e97009c91083ef5304429220c3ead3f4dbbf6f Mon Sep 17 00:00:00 2001 From: sojetunde8 <287985093+sojetunde8@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:15:39 +0100 Subject: [PATCH] Reject non-JSON Drand responses and send clickjacking and nosniff headers from the web app - drand-tools validates the response Content-Type (application/json with an optional charset) before parsing chain info and beacons, and fails with one stable error category (#663) - the web app sends Content-Security-Policy frame-ancestors 'none', X-Frame-Options DENY and X-Content-Type-Options nosniff from the Vite dev and preview servers and ships them in public/_headers; docs/web-security-headers.md says where they are configured, and a test keeps the places in step (#665) Closes #663 Closes #665 --- apps/web/package.json | 2 +- apps/web/public/_headers | 4 ++ apps/web/src/lib/security-headers.test.ts | 37 ++++++++++ apps/web/src/lib/security-headers.ts | 20 ++++++ apps/web/vite.config.ts | 6 ++ docs/web-security-headers.md | 32 +++++++++ services/drand-tools/package.json | 2 +- services/drand-tools/src/quicknet.test.ts | 85 +++++++++++++++++++++++ services/drand-tools/src/quicknet.ts | 38 +++++++++- 9 files changed, 222 insertions(+), 4 deletions(-) create mode 100644 apps/web/public/_headers create mode 100644 apps/web/src/lib/security-headers.test.ts create mode 100644 apps/web/src/lib/security-headers.ts create mode 100644 docs/web-security-headers.md create mode 100644 services/drand-tools/src/quicknet.test.ts diff --git a/apps/web/package.json b/apps/web/package.json index cb5d76a7..8c146b3b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -13,7 +13,7 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "test": "node --import tsx --test src/demo/trace-health-check.test.ts src/lib/config.test.ts src/lib/hex.test.ts src/lib/chain.test.ts src/dashboard/fixture-health-check.test.ts src/lib/round-status.test.ts src/components/dashboard/RoundStatusCard.test.tsx src/hooks/useDashboardData.test.ts src/lib/countdown.test.ts src/lib/transaction-status.test.ts src/lib/reduced-motion.test.ts src/passkey-session.test.ts && node --experimental-test-module-mocks --import tsx --test src/hooks/useRoundSession.reveal.test.tsx src/hooks/useRoundSession.refresh.test.tsx src/hooks/useLiveRound.test.tsx", + "test": "node --import tsx --test src/demo/trace-health-check.test.ts src/lib/config.test.ts src/lib/hex.test.ts src/lib/chain.test.ts src/dashboard/fixture-health-check.test.ts src/lib/round-status.test.ts src/components/dashboard/RoundStatusCard.test.tsx src/hooks/useDashboardData.test.ts src/lib/countdown.test.ts src/lib/transaction-status.test.ts src/lib/reduced-motion.test.ts src/lib/security-headers.test.ts src/passkey-session.test.ts && node --experimental-test-module-mocks --import tsx --test src/hooks/useRoundSession.reveal.test.tsx src/hooks/useRoundSession.refresh.test.tsx src/hooks/useLiveRound.test.tsx", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { diff --git a/apps/web/public/_headers b/apps/web/public/_headers new file mode 100644 index 00000000..c0220b37 --- /dev/null +++ b/apps/web/public/_headers @@ -0,0 +1,4 @@ +/* + Content-Security-Policy: frame-ancestors 'none' + X-Frame-Options: DENY + X-Content-Type-Options: nosniff diff --git a/apps/web/src/lib/security-headers.test.ts b/apps/web/src/lib/security-headers.test.ts new file mode 100644 index 00000000..ff7d2654 --- /dev/null +++ b/apps/web/src/lib/security-headers.test.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 Sub Rosa contributors +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { SECURITY_HEADERS, renderHeadersFile } from "./security-headers"; + +const webRoot = fileURLToPath(new URL("../../", import.meta.url)); + +test("denies framing by any other origin", () => { + assert.equal(SECURITY_HEADERS["Content-Security-Policy"], "frame-ancestors 'none'"); + assert.equal(SECURITY_HEADERS["X-Frame-Options"], "DENY"); +}); + +test("turns MIME sniffing off", () => { + assert.equal(SECURITY_HEADERS["X-Content-Type-Options"], "nosniff"); +}); + +test("the static-host _headers file matches the shared constant", () => { + const shipped = readFileSync(`${webRoot}public/_headers`, "utf8"); + assert.equal(shipped, renderHeadersFile()); +}); + +test("the Vite dev and preview servers send the same headers", () => { + const config = readFileSync(`${webRoot}vite.config.ts`, "utf8"); + assert.match(config, /from "\.\/src\/lib\/security-headers"/); + assert.match(config, /server:\s*{[^}]*headers: SECURITY_HEADERS/s); + assert.match(config, /preview:\s*{[^}]*headers: SECURITY_HEADERS/s); +}); + +test("the deployment doc says where the headers are configured", () => { + const doc = readFileSync(`${webRoot}../../docs/web-security-headers.md`, "utf8"); + for (const place of ["public/_headers", "vite.config.ts", "src/lib/security-headers.ts"]) { + assert.ok(doc.includes(place), `doc should mention ${place}`); + } +}); diff --git a/apps/web/src/lib/security-headers.ts b/apps/web/src/lib/security-headers.ts new file mode 100644 index 00000000..c4d038cf --- /dev/null +++ b/apps/web/src/lib/security-headers.ts @@ -0,0 +1,20 @@ +// Copyright (c) 2026 Sub Rosa contributors + +/// Response headers every deployment of the web app must send so the auction +/// interface cannot be framed by another origin and browsers do not sniff +/// content types. The same values are served by the Vite dev and preview servers +/// (`vite.config.ts`) and shipped to static hosts in `public/_headers`; +/// `security-headers.test.ts` keeps all three in step. See +/// `docs/web-security-headers.md`. +export const SECURITY_HEADERS: Readonly> = { + "Content-Security-Policy": "frame-ancestors 'none'", + "X-Frame-Options": "DENY", + "X-Content-Type-Options": "nosniff", +}; + +/// Render `SECURITY_HEADERS` in the `_headers` file format used by Netlify and +/// Cloudflare Pages: one path rule, then one indented `Name: value` per line. +export function renderHeadersFile(headers: Readonly> = SECURITY_HEADERS): string { + const lines = Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`); + return `/*\n${lines.join("\n")}\n`; +} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index acea4eb5..b09be29a 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -4,6 +4,8 @@ import inject from "@rollup/plugin-inject"; import { createRequire } from "node:module"; import { defineConfig } from "vite"; +import { SECURITY_HEADERS } from "./src/lib/security-headers"; + const require = createRequire(import.meta.url); export default defineConfig({ @@ -36,9 +38,13 @@ export default defineConfig({ include: ["buffer", "crypto-browserify", "stream-browserify", "process/browser", "events"], }, server: { + headers: SECURITY_HEADERS, port: 5173, fs: { allow: ["..", "../..", "../../..", "../../../.."], }, }, + preview: { + headers: SECURITY_HEADERS, + }, }); diff --git a/docs/web-security-headers.md b/docs/web-security-headers.md new file mode 100644 index 00000000..dbfd619a --- /dev/null +++ b/docs/web-security-headers.md @@ -0,0 +1,32 @@ + + +# Web app security headers + +The auction interface must not be framed by another origin (clickjacking) and +must not be served with MIME sniffing enabled. Every response from the web app +carries: + +| Header | Value | Why | +| --- | --- | --- | +| `Content-Security-Policy` | `frame-ancestors 'none'` | No origin may embed the app in a frame | +| `X-Frame-Options` | `DENY` | The same denial for browsers that ignore `frame-ancestors` | +| `X-Content-Type-Options` | `nosniff` | The browser must trust the declared content type | + +## Where they are configured + +- `apps/web/src/lib/security-headers.ts` is the single source of truth (the + `SECURITY_HEADERS` constant). +- `apps/web/vite.config.ts` sends them from the Vite dev server (`server.headers`) + and the preview server (`preview.headers`). +- `apps/web/public/_headers` ships with the build output (`dist/_headers`) and is + read by Netlify and Cloudflare Pages. + +Hosts that do not read `_headers` (nginx, Caddy, S3 or CloudFront, Vercel) need +the same three headers set in their own configuration; copy them from the table +above. A CDN or proxy in front of the app must not strip or override them. + +## Keeping them in step + +`apps/web/src/lib/security-headers.test.ts` fails when `public/_headers` no longer +matches `SECURITY_HEADERS`, when the Vite config stops using it, or when this page +stops naming the files above. Run it with `pnpm --filter @sub-rosa/web test`. diff --git a/services/drand-tools/package.json b/services/drand-tools/package.json index b0c1d6f1..0a101713 100644 --- a/services/drand-tools/package.json +++ b/services/drand-tools/package.json @@ -11,7 +11,7 @@ }, "scripts": { "validate": "tsx src/index.ts", - "test": "node --import tsx --test src/encode.test.ts src/parity.test.ts", + "test": "node --import tsx --test src/encode.test.ts src/parity.test.ts src/quicknet.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { diff --git a/services/drand-tools/src/quicknet.test.ts b/services/drand-tools/src/quicknet.test.ts new file mode 100644 index 00000000..4b2aa9ae --- /dev/null +++ b/services/drand-tools/src/quicknet.test.ts @@ -0,0 +1,85 @@ +// Copyright (c) 2026 Sub Rosa contributors +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; + +import { DrandResponseError, NON_JSON_RESPONSE, getBeacon, getChainInfo } from "./quicknet.js"; + +const realFetch = globalThis.fetch; + +function respond(body: string, headers: Record, status = 200) { + globalThis.fetch = (async () => new Response(body, { status, headers })) as typeof fetch; +} + +afterEach(() => { + globalThis.fetch = realFetch; +}); + +const INFO = { + public_key: "ab".repeat(96), + period: 3, + genesis_time: 1692803367, + hash: "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971", + schemeID: "bls-unchained-g1-rfc9380", +}; +const BEACON = { round: 7, randomness: "cd".repeat(32), signature: "ef".repeat(48) }; + +test("accepts application/json", async () => { + respond(JSON.stringify(INFO), { "content-type": "application/json" }); + assert.deepEqual(await getChainInfo(), INFO); +}); + +test("accepts application/json with a charset parameter, in any case", async () => { + respond(JSON.stringify(BEACON), { "content-type": "application/json; charset=utf-8" }); + assert.deepEqual(await getBeacon(7), BEACON); + respond(JSON.stringify(BEACON), { "content-type": "Application/JSON;charset=UTF-8" }); + assert.deepEqual(await getBeacon(7), BEACON); +}); + +for (const [label, contentType] of [ + ["HTML", "text/html; charset=utf-8"], + ["plain text", "text/plain"], + ["text/json", "text/json"], + ["a JSON-looking prefix", "application/jsonp"], +] as const) { + test(`rejects a 200 response served as ${label}, for chain info and beacons`, async () => { + respond("blocked", { "content-type": contentType }); + await assert.rejects(getChainInfo(), (err: unknown) => { + assert.ok(err instanceof DrandResponseError); + assert.equal(err.category, NON_JSON_RESPONSE); + assert.equal(err.contentType, contentType); + return true; + }); + await assert.rejects(getBeacon("latest"), (err: unknown) => { + assert.ok(err instanceof DrandResponseError); + assert.equal(err.category, NON_JSON_RESPONSE); + return true; + }); + }); +} + +test("rejects a response with no content-type", async () => { + globalThis.fetch = (async () => { + const res = new Response(JSON.stringify(INFO), { status: 200 }); + res.headers.delete("content-type"); + return res; + }) as typeof fetch; + await assert.rejects(getChainInfo(), (err: unknown) => { + assert.ok(err instanceof DrandResponseError); + assert.equal(err.contentType, null); + return true; + }); +}); + +test("uses the same category when a JSON content-type carries a broken body", async () => { + respond("{not json", { "content-type": "application/json" }); + await assert.rejects(getBeacon(1), (err: unknown) => { + assert.ok(err instanceof DrandResponseError); + assert.equal(err.category, NON_JSON_RESPONSE); + return true; + }); +}); + +test("a non-success status keeps its HTTP error", async () => { + respond("", { "content-type": "text/html" }, 503); + await assert.rejects(getChainInfo(), /info HTTP 503/); +}); diff --git a/services/drand-tools/src/quicknet.ts b/services/drand-tools/src/quicknet.ts index 768a4c52..6ddf6c8f 100644 --- a/services/drand-tools/src/quicknet.ts +++ b/services/drand-tools/src/quicknet.ts @@ -21,16 +21,50 @@ export interface Beacon { signature: string; // compressed G1, hex (48 bytes) } +/// The one stable category every "this did not come back as JSON" failure uses, +/// so callers can match on it instead of on message text. +export const NON_JSON_RESPONSE = "non-json-response"; + +export class DrandResponseError extends Error { + readonly category = NON_JSON_RESPONSE; + constructor( + readonly endpoint: string, + readonly contentType: string | null, + detail: string, + ) { + super(`${endpoint} returned a non-JSON response (${detail})`); + this.name = "DrandResponseError"; + } +} + +/// `application/json`, optionally followed by parameters such as a charset. +const JSON_MEDIA_TYPE = /^application\/json\s*(;.*)?$/i; + +/// Parse a success response as JSON, but only when the server says it is JSON. +/// An intermediary that answers 200 with an HTML error page would otherwise +/// surface as an opaque `Unexpected token '<'` parse error. +async function readJson(res: Response, endpoint: string): Promise { + const contentType = res.headers.get("content-type"); + if (contentType === null || !JSON_MEDIA_TYPE.test(contentType.trim())) { + throw new DrandResponseError(endpoint, contentType, `content-type ${contentType ?? "missing"}`); + } + try { + return (await res.json()) as T; + } catch { + throw new DrandResponseError(endpoint, contentType, "body is not valid JSON"); + } +} + export async function getChainInfo(): Promise { const res = await fetch(`${API}/${QUICKNET_HASH}/info`); if (!res.ok) throw new Error(`info HTTP ${res.status}`); - return (await res.json()) as ChainInfo; + return readJson(res, "info"); } export async function getBeacon(round: number | "latest"): Promise { const res = await fetch(`${API}/${QUICKNET_HASH}/public/${round}`); if (!res.ok) throw new Error(`beacon ${round} HTTP ${res.status}`); - return (await res.json()) as Beacon; + return readJson(res, `beacon ${round}`); } export function roundAt(info: ChainInfo, unixSeconds: number): number {