Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
4 changes: 4 additions & 0 deletions apps/web/public/_headers
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/*
Content-Security-Policy: frame-ancestors 'none'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
37 changes: 37 additions & 0 deletions apps/web/src/lib/security-headers.test.ts
Original file line number Diff line number Diff line change
@@ -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}`);
}
});
20 changes: 20 additions & 0 deletions apps/web/src/lib/security-headers.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, string>> = {
"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<Record<string, string>> = SECURITY_HEADERS): string {
const lines = Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`);
return `/*\n${lines.join("\n")}\n`;
}
6 changes: 6 additions & 0 deletions apps/web/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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,
},
});
32 changes: 32 additions & 0 deletions docs/web-security-headers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!-- SPDX-License-Identifier: MIT -->

# 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`.
2 changes: 1 addition & 1 deletion services/drand-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
85 changes: 85 additions & 0 deletions services/drand-tools/src/quicknet.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>, 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("<html><body>blocked</body></html>", { "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("<html></html>", { "content-type": "text/html" }, 503);
await assert.rejects(getChainInfo(), /info HTTP 503/);
});
38 changes: 36 additions & 2 deletions services/drand-tools/src/quicknet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(res: Response, endpoint: string): Promise<T> {
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<ChainInfo> {
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<ChainInfo>(res, "info");
}

export async function getBeacon(round: number | "latest"): Promise<Beacon> {
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<Beacon>(res, `beacon ${round}`);
}

export function roundAt(info: ChainInfo, unixSeconds: number): number {
Expand Down