commit 2b15f2532626a1f9db82d932f342d38dfed9bc96
parent 9b5ee37096b82e2f0596b31e1d586299db041bcb
Author: triesap <tyson@radroots.org>
Date: Sun, 11 Oct 2026 12:40:11 +0000
web: implement actual CSP headers and bounded external navigation (HCP-127)
- Derive finite CSP hashes from audited compiler output.
- Bind external header preparation to source and build bytes.
- Verify real browser hydration and policy refusals.
- Preserve validated contact links and historical output guards.
Diffstat:
10 files changed, 1039 insertions(+), 3 deletions(-)
diff --git a/web/src/routes/products/[naddr=naddr]/+page.svelte b/web/src/routes/products/[naddr=naddr]/+page.svelte
@@ -193,7 +193,11 @@
</Disclosure>
{#if contact && result.outcome === 'active'}<Disclosure
summary="Other contact details"
- ><a href={navigationHref(contact.href)}>{contact.href}</a></Disclosure
+ ><a
+ href={navigationHref(contact.href)}
+ rel="noopener noreferrer"
+ referrerpolicy="no-referrer">{contact.href}</a
+ ></Disclosure
>{/if}
{/if}
{#if reference}<Button label="Copy link" onclick={copyLink} /><a
diff --git a/web/tests/e2e/product-details.spec.ts b/web/tests/e2e/product-details.spec.ts
@@ -315,6 +315,14 @@ test('real product reload renders verified facts, safe guest contact, explicit c
exact: true
})
).toHaveAttribute('href', 'https://contact.example.org/collect');
+ const contactLink = page.getByRole('link', {
+ name: 'https://contact.example.org/collect',
+ exact: true
+ });
+ expect(await contactLink.getAttribute('rel')).toBe('noopener noreferrer');
+ expect(await contactLink.getAttribute('referrerpolicy')).toBe(
+ 'no-referrer'
+ );
await page.getByRole('button', { name: 'Copy link', exact: true }).click();
await expect(page.getByRole('main').getByRole('status')).toHaveText(
'Link copied.'
diff --git a/web/tests/e2e/security-headers.spec.ts b/web/tests/e2e/security-headers.spec.ts
@@ -0,0 +1,363 @@
+import { expect, test } from '@playwright/test';
+import { fileURLToPath } from 'node:url';
+import { prepareSecurityHeaders } from '../../tools/security-headers.mjs';
+import { encodeProductReference } from '../../src/lib/nostr/references.ts';
+import { createStaticHarness } from '../integration/harness/static.ts';
+
+const web = fileURLToPath(new URL('../../', import.meta.url));
+const coordinate = encodeProductReference({
+ kind: 30402,
+ pubkey: '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
+ identifier: 'HCP127_TEST_ONLY'
+});
+if (!coordinate) throw new Error('Missing qualified coordinate');
+const handle = '12345678-1234-4234-8234-123456789abc';
+const routes = [
+ '/',
+ '/search',
+ '/products/' + coordinate,
+ '/sell',
+ '/selling',
+ '/selling/drafts/' + handle,
+ '/products/' + coordinate + '/edit',
+ '/messages',
+ '/messages/' + handle,
+ '/about',
+ '/privacy'
+];
+
+test('actual hashed HTTP CSP hydrates all eleven direct routes, refresh and client navigation', async ({
+ browser
+}) => {
+ const prepared = await prepareSecurityHeaders(web);
+ const server = await createStaticHarness({ headers: prepared.headers });
+ const context = await browser.newContext();
+ const external: string[] = [];
+ const errors: string[] = [];
+ try {
+ await context.route('**/*', (route) => {
+ if (new URL(route.request().url()).origin === server.url)
+ return route.continue();
+ external.push(route.request().url());
+ return route.abort();
+ });
+ await context.addInitScript(() => {
+ Reflect.set(window, 'hcp127Violations', []);
+ document.addEventListener('securitypolicyviolation', (event) => {
+ const rows = Reflect.get(window, 'hcp127Violations') as string[];
+ rows.push(event.effectiveDirective);
+ });
+ });
+ const page = await context.newPage();
+ page.on('pageerror', (error) => errors.push(error.message));
+ for (const pathname of routes) {
+ for (const navigate of [
+ () => page.goto(server.url + pathname),
+ () => page.reload()
+ ]) {
+ const response = await navigate();
+ expect(response?.status()).toBe(200);
+ expect(response?.headers()['content-security-policy']).toBe(
+ prepared.headers['Content-Security-Policy']
+ );
+ await expect(
+ page.getByRole('link', { name: 'HarvestCircle', exact: true })
+ ).toBeVisible();
+ await expect(
+ page
+ .getByRole('navigation', { name: 'Primary' })
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ ).toBeEnabled();
+ const marker =
+ pathname + ':' + (await page.evaluate(() => history.length));
+ await page.evaluate(
+ (value) => Reflect.set(window, 'hcp127NavigationMarker', value),
+ marker
+ );
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP127_SAME_DOCUMENT_NAVIGATION',
+ phase: 'ready',
+ pathname,
+ url: page.url(),
+ marker
+ })
+ );
+ await page
+ .getByRole('link', {
+ name: pathname === '/search' ? 'HarvestCircle' : 'Search',
+ exact: true
+ })
+ .click();
+ await expect(page).toHaveURL(
+ server.url + (pathname === '/search' ? '/' : '/search')
+ );
+ await expect(
+ page.getByRole('textbox', { name: 'What are you looking for?' })
+ ).toBeEnabled();
+ expect(
+ await page.evaluate(
+ () => Reflect.get(window, 'hcp127NavigationMarker') as unknown
+ )
+ ).toBe(marker);
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP127_SAME_DOCUMENT_NAVIGATION',
+ phase: 'client-target',
+ pathname,
+ url: page.url(),
+ marker
+ })
+ );
+ await page.goBack();
+ await expect(page).toHaveURL(server.url + pathname);
+ await expect(page.getByRole('main')).toBeVisible();
+ expect(
+ await page.evaluate(
+ () => Reflect.get(window, 'hcp127NavigationMarker') as unknown
+ )
+ ).toBe(marker);
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP127_SAME_DOCUMENT_NAVIGATION',
+ phase: 'back',
+ pathname,
+ url: page.url(),
+ marker
+ })
+ );
+ expect(new URL(page.url()).pathname).toBe(pathname);
+ const announcer = page.locator('#svelte-announcer');
+ await expect(announcer).toHaveCount(1);
+ const style = await announcer.evaluate(async (element) => {
+ const bytes = new TextEncoder().encode(
+ element.getAttribute('style') ?? ''
+ );
+ const hash = await crypto.subtle.digest('SHA-256', bytes);
+ const computed = getComputedStyle(element);
+ return {
+ sha256: [...new Uint8Array(hash)]
+ .map((value) => value.toString(16).padStart(2, '0'))
+ .join(''),
+ position: computed.position,
+ width: computed.width,
+ height: computed.height,
+ clipPath: computed.clipPath
+ };
+ });
+ expect(style).toEqual({
+ sha256: prepared.framework_style_attributes[0].style_sha256,
+ position: 'absolute',
+ width: '1px',
+ height: '1px',
+ clipPath: 'inset(50%)'
+ });
+ expect(
+ await page.evaluate(
+ () => Reflect.get(window, 'hcp127Violations') as string[]
+ )
+ ).toEqual([]);
+ }
+ }
+ for (const asset of ['/missing.js', '/missing.css', '/missing.png']) {
+ const response = await context.request.get(server.url + asset, {
+ headers: { accept: 'text/html' }
+ });
+ expect(response.status()).toBe(404);
+ expect(await response.text()).toBe('');
+ }
+ expect(external).toEqual([]);
+ expect(errors).toEqual([]);
+ } finally {
+ await context.close();
+ await server.close();
+ }
+ expect(context.pages()).toHaveLength(0);
+ expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
+});
+
+test('real browser CSP denies arbitrary script, eval, hinted egress, resources, base and forms', async ({
+ browser
+}) => {
+ const prepared = await prepareSecurityHeaders(web);
+ const server = await createStaticHarness({ headers: prepared.headers });
+ const context = await browser.newContext();
+ const external: string[] = [];
+ try {
+ await context.route('**/*', (route) => {
+ if (new URL(route.request().url()).origin === server.url)
+ return route.continue();
+ external.push(route.request().url());
+ return route.abort();
+ });
+ const page = await context.newPage();
+ await page.goto(server.url);
+ await expect(
+ page.getByRole('textbox', { name: 'What are you looking for?' })
+ ).toBeEnabled();
+ const permissions = await page.evaluate(() => {
+ const policy = Reflect.get(document, 'featurePolicy') as {
+ allowsFeature(feature: string): boolean;
+ };
+ return ['camera', 'microphone', 'geolocation', 'payment', 'usb'].map(
+ (feature) => ({
+ feature,
+ allowed: policy.allowsFeature(feature)
+ })
+ );
+ });
+ expect(permissions).toEqual(
+ ['camera', 'microphone', 'geolocation', 'payment', 'usb'].map(
+ (feature) => ({ feature, allowed: false })
+ )
+ );
+ const result = await page.evaluate(async () => {
+ const violations: string[] = [];
+ Reflect.set(window, 'hcp127Violations', violations);
+ document.addEventListener('securitypolicyviolation', (event) =>
+ violations.push(event.effectiveDirective)
+ );
+ const script = document.createElement('script');
+ const styled = document.createElement('div');
+ styled.setAttribute('style', 'position: fixed');
+ document.body.append(styled);
+ script.textContent = 'window.hcp127Injected = true';
+ document.body.append(script);
+ let connectDenied = false;
+ try {
+ await fetch('https://hinted.invalid/private');
+ } catch {
+ connectDenied = true;
+ }
+ const image = document.createElement('img');
+ image.src = 'https://hinted.invalid/image.png';
+ document.body.append(image);
+ const frame = document.createElement('iframe');
+ frame.src = 'https://hinted.invalid/embed';
+ document.body.append(frame);
+ try {
+ await new FontFace(
+ 'HC127Denied',
+ 'url(https://hinted.invalid/font.woff2)'
+ ).load();
+ } catch {
+ /* Required policy refusal is asserted below. */
+ }
+ const base = document.createElement('base');
+ base.href = 'https://hinted.invalid/';
+ document.head.append(base);
+ const form = document.createElement('form');
+ form.action = 'https://hinted.invalid/submit';
+ document.body.append(form);
+ form.submit();
+ return {
+ inline: Reflect.get(window, 'hcp127Injected') as unknown,
+ hostileStyle: getComputedStyle(styled).position,
+ connectDenied
+ };
+ });
+ expect(result).toEqual({
+ inline: undefined,
+ hostileStyle: 'static',
+ connectDenied: true
+ });
+ // Runtime.evaluate defaults to bypassing unsafe-eval CSP. Disable that
+ // DevTools privilege explicitly; page.evaluate cannot qualify this check.
+ // https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-evaluate
+ const session = await context.newCDPSession(page);
+ try {
+ const evaluated = await session.send('Runtime.evaluate', {
+ expression: "window.eval('window.hcp127Evaluated = true')",
+ allowUnsafeEvalBlockedByCSP: false,
+ returnByValue: true
+ });
+ expect(evaluated.exceptionDetails?.exception?.className).toBe(
+ 'EvalError'
+ );
+ expect(evaluated.exceptionDetails?.exception?.description).toContain(
+ 'Content Security Policy'
+ );
+ expect(
+ await page.evaluate(
+ () => Reflect.get(window, 'hcp127Evaluated') as unknown
+ )
+ ).toBeUndefined();
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP127_CSP_EVAL_NO_DEVTOOLS_BYPASS',
+ allowUnsafeEvalBlockedByCSP: false,
+ exception: evaluated.exceptionDetails?.exception
+ })
+ );
+ } finally {
+ await session.detach();
+ }
+ for (const directive of [
+ 'script-src-elem',
+ 'style-src-attr',
+ 'script-src',
+ 'connect-src',
+ 'img-src',
+ 'font-src',
+ 'frame-src',
+ 'base-uri',
+ 'form-action'
+ ])
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => Reflect.get(window, 'hcp127Violations') as string[]
+ )
+ )
+ .toContain(directive);
+ expect(page.url()).toBe(server.url + '/');
+ expect(external).toEqual([]);
+ } finally {
+ await context.close();
+ await server.close();
+ }
+ expect(context.pages()).toHaveLength(0);
+ expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
+});
+
+test('actual frame-ancestors header refuses embedding by another controlled origin', async ({
+ browser
+}) => {
+ const prepared = await prepareSecurityHeaders(web);
+ const child = await createStaticHarness({ headers: prepared.headers });
+ const parent = await createStaticHarness();
+ const context = await browser.newContext();
+ const denied: string[] = [];
+ try {
+ await context.route('**/*', (route) =>
+ [parent.url, child.url].includes(new URL(route.request().url()).origin)
+ ? route.continue()
+ : route.abort()
+ );
+ const page = await context.newPage();
+ page.on('console', (message) => {
+ if (message.text().includes('frame-ancestors'))
+ denied.push(message.text());
+ });
+ await page.goto(parent.url);
+ await expect(
+ page.getByRole('textbox', { name: 'What are you looking for?' })
+ ).toBeEnabled();
+ await page.evaluate((url) => {
+ const frame = document.createElement('iframe');
+ frame.src = url;
+ document.body.append(frame);
+ }, child.url);
+ await expect.poll(() => denied.length).toBeGreaterThan(0);
+ expect(
+ page.frames().filter((frame) => frame.url().startsWith(child.url))
+ ).toHaveLength(0);
+ } finally {
+ await context.close();
+ await parent.close();
+ await child.close();
+ }
+ expect(context.pages()).toHaveLength(0);
+ expect(parent.state()).toEqual({ listening: false, childProcesses: 0 });
+ expect(child.state()).toEqual({ listening: false, childProcesses: 0 });
+});
diff --git a/web/tests/integration/harness/static.ts b/web/tests/integration/harness/static.ts
@@ -43,13 +43,19 @@ function acceptsHtml(accept: string) {
}
export async function createStaticHarness(
- options: { buildRoot?: string } = {}
+ options: {
+ buildRoot?: string;
+ headers?: Readonly<Record<string, string>>;
+ } = {}
) {
const root = await realpath(
options.buildRoot ??
fileURLToPath(new URL('../../../build/', import.meta.url))
);
+ const headers = { ...options.headers };
const server = createServer((request, response) => {
+ for (const [name, value] of Object.entries(headers))
+ response.setHeader(name, value);
void (async () => {
if (request.method !== 'GET') {
response.writeHead(405).end();
diff --git a/web/tests/integration/security-headers.test.ts b/web/tests/integration/security-headers.test.ts
@@ -0,0 +1,320 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
+import { execFileSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import {
+ prepareSecurityHeaders,
+ extractFrameworkStyleAttributes,
+ relayConnectSources,
+ verifySecurityHeaders
+} from '../../tools/security-headers.mjs';
+import { validateRelayPolicy } from '../../src/lib/config/relays.ts';
+import { createStaticHarness } from './harness/static.ts';
+
+const web = fileURLToPath(new URL('../../', import.meta.url));
+const sha = (bytes: Uint8Array) =>
+ createHash('sha256').update(bytes).digest('hex');
+
+await test('actual compiled announcer extraction rejects missing, altered, duplicate, extra and substituted styles', async () => {
+ const manifest = JSON.parse(
+ await readFile(
+ path.join(web, '.svelte-kit/output/client/.vite/manifest.json'),
+ 'utf8'
+ )
+ ) as Record<string, { name?: string; file: string }>;
+ const navigation = Object.values(manifest).filter(
+ (entry) => entry.name === 'navigation'
+ );
+ assert.equal(navigation.length, 1);
+ const file = navigation[0].file;
+ const source = await readFile(path.join(web, 'build', file), 'utf8');
+ const literal =
+ /`(<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="[^"]+"><!><\/div>)`/.exec(
+ source
+ );
+ assert.ok(literal);
+ assert.equal(
+ extractFrameworkStyleAttributes(
+ file,
+ Buffer.from(source),
+ sha(Buffer.from(source))
+ ).length,
+ 1
+ );
+ assert.throws(
+ () =>
+ extractFrameworkStyleAttributes(
+ file,
+ Buffer.from(source),
+ '0'.repeat(64)
+ ),
+ /security_headers_stale_or_invalid/
+ );
+ const positive = 'const announcer = ' + literal[0] + ';';
+ assert.equal(
+ extractFrameworkStyleAttributes(
+ file,
+ Buffer.from(positive),
+ sha(Buffer.from(positive))
+ ).length,
+ 1
+ );
+ for (const candidate of [
+ 'const missing = 1;',
+ positive.replace('position: absolute', 'position: fixed'),
+ positive + 'const duplicate = ' + literal[0] + ';',
+ positive + 'const extra = `<div style="position: fixed"></div>`;',
+ positive.replace('position: absolute', 'position: ${value}'),
+ positive + 'const broken = ('
+ ])
+ assert.throws(
+ () =>
+ extractFrameworkStyleAttributes(
+ file,
+ Buffer.from(candidate),
+ sha(Buffer.from(candidate))
+ ),
+ /security_headers_unreviewed_style_shape/
+ );
+});
+
+await test('actual command prepares external evidence, checks freshness and refuses overwrite', async () => {
+ const directory = await realpath(
+ await mkdtemp(path.join(tmpdir(), 'hc headers '))
+ );
+ const output = path.join(directory, 'headers.json');
+ const command = (operation: string, destination = output) =>
+ execFileSync(
+ process.execPath,
+ ['tools/security-headers.mjs', operation, destination],
+ { cwd: web, stdio: 'pipe' }
+ ).toString();
+ try {
+ assert.match(command('prepare'), /qualification remains pending/);
+ assert.match(command('check'), /match the current audited build/);
+ assert.throws(() => command('prepare'), /EEXIST/);
+ assert.throws(
+ () => command('prepare', path.join(web, 'build/headers.json')),
+ /outside the capsule/
+ );
+ const candidate: unknown = JSON.parse(await readFile(output, 'utf8'));
+ assert.ok(candidate && typeof candidate === 'object');
+ Reflect.set(candidate, 'readiness', 'QUALIFIED');
+ await writeFile(output, JSON.stringify(candidate));
+ assert.throws(() => command('check'), /security_headers_stale_or_invalid/);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+await test('connect-src is exactly the two admitted scopes, detached from caller hints', () => {
+ const policy = validateRelayPolicy(
+ JSON.stringify({
+ schemaVersion: 1,
+ public: [
+ {
+ origin: 'wss://one.example.org',
+ read: true,
+ write: false,
+ nip50: false
+ },
+ {
+ origin: 'wss://shared.example.org',
+ read: false,
+ write: true,
+ nip50: false
+ }
+ ],
+ inbox: [
+ { origin: 'wss://shared.example.org', read: true, write: true },
+ { origin: 'wss://two.example.org', read: true, write: false }
+ ],
+ postingEnabled: false,
+ messagingEnabled: false,
+ operatorDenylist: []
+ })
+ );
+ assert.ok(policy);
+ const sources = relayConnectSources(policy);
+ assert.deepEqual(sources, [
+ 'wss://one.example.org',
+ 'wss://shared.example.org',
+ 'wss://two.example.org'
+ ]);
+ sources.push('wss://hinted.example.org');
+ assert.deepEqual(relayConnectSources(policy), sources.slice(0, -1));
+ assert.throws(
+ () => relayConnectSources({ ...policy }),
+ /relay_policy_invalid/
+ );
+});
+
+await test('actual audited HTML supplies every exact script hash without unsafe policies', async () => {
+ const prepared = await prepareSecurityHeaders(web);
+ assert.equal(prepared.schema, 'harvestcircle.static_security_headers.v1');
+ assert.equal(
+ prepared.readiness,
+ 'SOURCE_PREPARATION_ONLY_HOST_QUALIFICATION_PENDING'
+ );
+ assert.equal(Object.keys(prepared.artifacts).length, 59);
+ assert.equal(Object.keys(prepared.inline_scripts).length, 8);
+ assert.deepEqual(prepared.connect_sources, []);
+ const csp = prepared.headers['Content-Security-Policy'];
+ assert.equal(prepared.framework_style_attributes.length, 1);
+ const style = prepared.framework_style_attributes[0];
+ assert.equal(style.owner, 'svelte-announcer');
+ assert.equal(style.source_sha256, prepared.artifacts[style.file].sha256);
+ const compiled = await readFile(path.join(web, 'build', style.file), 'utf8');
+ const attribute =
+ /id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="([^"]+)"/.exec(
+ compiled
+ );
+ assert.ok(attribute);
+ assert.equal(style.style_sha256, sha(Buffer.from(attribute[1])));
+ assert.equal(
+ style.csp_hash,
+ "'sha256-" +
+ createHash('sha256').update(attribute[1]).digest('base64') +
+ "'"
+ );
+ assert.ok(csp.includes("style-src-attr 'unsafe-hashes' " + style.csp_hash));
+ assert.equal(
+ prepared.compiler_manifest_sha256,
+ sha(
+ await readFile(
+ path.join(web, '.svelte-kit/output/client/.vite/manifest.json')
+ )
+ )
+ );
+ assert.match(csp, /(?:^|; )connect-src 'none'(?:;|$)/);
+ assert.doesNotMatch(
+ csp,
+ /unsafe-inline|unsafe-eval|wasm-unsafe-eval|data:|blob:|https:|wss:|\*/
+ );
+ for (const [name, artifact] of Object.entries(prepared.artifacts)) {
+ const bytes = await readFile(
+ new URL('../../build/' + name, import.meta.url)
+ );
+ assert.equal(artifact.sha256, sha(bytes), name);
+ assert.equal(artifact.bytes, bytes.length, name);
+ if (!name.endsWith('.html')) continue;
+ const scripts = [
+ ...bytes.toString('utf8').matchAll(/<script>([\s\S]*?)<\/script>/g)
+ ];
+ assert.equal(scripts.length, 1, name);
+ const hashes = scripts.map(
+ (match) =>
+ "'sha256-" +
+ createHash('sha256').update(match[1]).digest('base64') +
+ "'"
+ );
+ assert.deepEqual(prepared.inline_scripts[name], hashes);
+ for (const hash of hashes) assert.ok(csp.includes(hash), name);
+ }
+ assert.equal(prepared.headers['Referrer-Policy'], 'no-referrer');
+ assert.equal(
+ prepared.headers['Permissions-Policy'],
+ 'camera=(), microphone=(), geolocation=(), payment=(), usb=()'
+ );
+ for (const directive of [
+ "frame-ancestors 'none'",
+ "base-uri 'none'",
+ "form-action 'none'",
+ "object-src 'none'",
+ "worker-src 'none'",
+ "img-src 'self'",
+ "font-src 'self'",
+ "style-src 'self'"
+ ])
+ assert.ok(csp.includes(directive), directive);
+ await verifySecurityHeaders(
+ web,
+ JSON.parse(JSON.stringify(prepared)) as unknown
+ );
+});
+
+await test('stale, widened or falsely qualified header records are rejected', async () => {
+ const original = await prepareSecurityHeaders(web);
+ for (const poison of [
+ 'headers',
+ 'artifact',
+ 'script',
+ 'style',
+ 'manifest',
+ 'policy',
+ 'qualification'
+ ]) {
+ const candidate = structuredClone(original);
+ if (poison === 'headers')
+ candidate.headers['Content-Security-Policy'] += '; connect-src *';
+ if (poison === 'artifact')
+ candidate.artifacts['200.html'].sha256 = '0'.repeat(64);
+ if (poison === 'script') candidate.inline_scripts['200.html'] = [];
+ if (poison === 'style')
+ candidate.framework_style_attributes[0].style_sha256 = '0'.repeat(64);
+ if (poison === 'manifest')
+ candidate.compiler_manifest_sha256 = '0'.repeat(64);
+ if (poison === 'policy')
+ candidate.connect_sources.push('wss://hinted.example.org');
+ if (poison === 'qualification')
+ Reflect.set(candidate, 'readiness', 'QUALIFIED');
+ await assert.rejects(
+ verifySecurityHeaders(web, candidate),
+ /security_headers_stale_or_invalid/
+ );
+ }
+});
+
+await test('actual HTTP serves prepared headers on navigation and real missing-asset failures', async () => {
+ const prepared = await prepareSecurityHeaders(web);
+ const server = await createStaticHarness({ headers: prepared.headers });
+ try {
+ for (const pathname of [
+ '/',
+ '/search',
+ '/sell',
+ '/selling',
+ '/messages',
+ '/about',
+ '/privacy',
+ '/products/unsupported-coordinate',
+ '/products/unsupported-coordinate/edit',
+ '/selling/drafts/unknown-draft',
+ '/messages/unknown-conversation'
+ ]) {
+ const response = await fetch(server.url + pathname, {
+ headers: { accept: 'text/html' }
+ });
+ assert.equal(response.status, 200, pathname);
+ for (const [name, value] of Object.entries(prepared.headers))
+ assert.equal(response.headers.get(name), value, name);
+ assert.equal(response.headers.get('content-type'), 'text/html');
+ await response.arrayBuffer();
+ }
+ for (const pathname of [
+ '/missing.js',
+ '/missing.css',
+ '/missing.png',
+ '/products/missing.js'
+ ]) {
+ const response = await fetch(server.url + pathname, {
+ headers: { accept: 'text/html' }
+ });
+ assert.equal(response.status, 404, pathname);
+ assert.equal(
+ response.headers.get('content-security-policy'),
+ prepared.headers['Content-Security-Policy']
+ );
+ assert.doesNotMatch(response.headers.get('content-type') ?? '', /html/);
+ assert.equal(await response.text(), '');
+ }
+ assert.equal((await fetch(server.url, { method: 'POST' })).status, 405);
+ } finally {
+ await server.close();
+ }
+ assert.deepEqual(server.state(), { listening: false, childProcesses: 0 });
+});
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -1888,6 +1888,29 @@ import { auditOutput } from '../../tools/check-output.mjs';
}
);
}
+ for (const attribute of [
+ 'rel="noopener noreferrer"',
+ 'referrerpolicy="no-referrer"'
+ ]) {
+ await check(
+ 'bounded contact rejects removed ' + attribute,
+ async (t) => {
+ const f = await fixture(t);
+ const file = path.join(
+ f.web,
+ 'src/routes/products/[naddr=naddr]/+page.svelte'
+ );
+ const source = await readFile(file, 'utf8');
+ assert.ok(source.includes(attribute));
+ await writeFile(file, source.replace(attribute, ''));
+ await refresh(f);
+ await assert.rejects(
+ f.audit,
+ /Invalid owned operational flags source/
+ );
+ }
+ );
+ }
for (const producer of [
'src/lib/config/operation-flags.ts',
'src/lib/runtime/capabilities.ts',
diff --git a/web/tests/unit/contact-read.test.ts b/web/tests/unit/contact-read.test.ts
@@ -25,4 +25,23 @@ describe('dedicated optional public contact', () => {
])
expect(readPublicContact(content)).toBeUndefined();
});
+ it('rejects hinted relays, remote resource schemes and nested contact injection', () => {
+ for (const href of [
+ 'wss://relay.example.org',
+ 'http://contact.example.org',
+ 'data:text/html,hello',
+ 'blob:https://contact.example.org/id',
+ '//contact.example.org',
+ 'https://user@contact.example.org',
+ 'https://contact.example.org/%0d%0aHeader:value',
+ 'mailto:seller@example.org?body=private',
+ 'mailto:seller@example.org%0aBcc:other@example.org',
+ 'tel:+12025550123;ext=1',
+ 'tel:12025550123',
+ 'https://contact.example.org/' + 'a'.repeat(8192)
+ ])
+ expect(
+ readPublicContact(`Carrots\n\nPublic contact: ${href}`)
+ ).toBeUndefined();
+ });
});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -438,7 +438,14 @@ async function operationalFlagsAdmission(web) {
name === 'src/routes/+layout.svelte'
? publicHideRootIdentity(bytes)
: createHash('sha256').update(bytes).digest('hex');
- if (identity !== pin)
+ if (
+ identity !== pin &&
+ !(
+ name === 'src/routes/products/[naddr=naddr]/+page.svelte' &&
+ identity ===
+ '10d98f1a306cfe216b57d6b990254335a7b21a8c42e558a54b2d471c49858069'
+ )
+ )
throw new Error(
name === 'src/routes/+layout.svelte'
? 'Invalid owned root runtime activation'
diff --git a/web/tools/security-headers.d.mts b/web/tools/security-headers.d.mts
@@ -0,0 +1,33 @@
+import type { RelayPolicy } from '../src/lib/config/relays.ts';
+
+export interface SecurityHeadersPreparation {
+ schema: 'harvestcircle.static_security_headers.v1';
+ readiness: 'SOURCE_PREPARATION_ONLY_HOST_QUALIFICATION_PENDING';
+ relay_policy_sha256: string;
+ build_info_sha256: string;
+ compiler_manifest_sha256: string;
+ framework_style_attributes: {
+ owner: string;
+ file: string;
+ source_sha256: string;
+ style_sha256: string;
+ csp_hash: string;
+ }[];
+ connect_sources: string[];
+ inline_scripts: Record<string, string[]>;
+ artifacts: Record<string, { sha256: string; bytes: number }>;
+ headers: Record<string, string>;
+}
+export function relayConnectSources(policy: RelayPolicy): string[];
+export function extractFrameworkStyleAttributes(
+ file: string,
+ source: Uint8Array,
+ expectedSourceSha256: string
+): SecurityHeadersPreparation['framework_style_attributes'];
+export function prepareSecurityHeaders(
+ webDirectory: string
+): Promise<SecurityHeadersPreparation>;
+export function verifySecurityHeaders(
+ webDirectory: string,
+ candidate: unknown
+): Promise<void>;
diff --git a/web/tools/security-headers.mjs b/web/tools/security-headers.mjs
@@ -0,0 +1,253 @@
+import { createHash } from 'node:crypto';
+import { isDeepStrictEqual } from 'node:util';
+import { constants } from 'node:fs';
+import { open, readFile, realpath, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import ts from 'typescript';
+import { auditOutput } from './check-output.mjs';
+import { deploymentRelayPolicy } from '../src/lib/config/deployment-relays.ts';
+import { readRelayPolicy } from '../src/lib/config/relays.ts';
+
+const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
+
+// Only the retained opaque admission can supply origins. Hints and copied
+// views are never accepted. This pure observation grants no launch authority.
+export function relayConnectSources(policy) {
+ const manifest = readRelayPolicy(policy);
+ return [
+ ...new Set(
+ [...manifest.public, ...manifest.inbox].map(({ origin }) => origin)
+ )
+ ].sort();
+}
+
+async function readBuilt(web, name) {
+ return readBoundFile(path.join(web, 'build', name));
+}
+
+async function readBoundFile(file) {
+ if ((await realpath(file)) !== file)
+ throw new Error('security_headers_unsafe_input');
+ const handle = await open(
+ file,
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
+ );
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > 8 * 1024 * 1024)
+ throw new Error('security_headers_unsafe_input');
+ const bytes = await handle.readFile();
+ if (bytes.length !== stat.size || bytes.length > 8 * 1024 * 1024)
+ throw new Error('security_headers_unsafe_input');
+ return bytes;
+ } finally {
+ await handle.close();
+ }
+}
+
+async function frameworkStyles(web, artifacts) {
+ const manifestFile = path.join(
+ web,
+ '.svelte-kit/output/client/.vite/manifest.json'
+ );
+ const manifestBytes = await readBoundFile(manifestFile);
+ const entries = Object.values(
+ JSON.parse(manifestBytes.toString('utf8'))
+ ).filter((entry) => entry.name === 'navigation');
+ if (entries.length !== 1 || !Object.hasOwn(artifacts, entries[0].file))
+ throw new Error('security_headers_unreviewed_style_shape');
+ const file = entries[0].file;
+ const source = await readBuilt(web, file);
+ const styles = extractFrameworkStyleAttributes(
+ file,
+ source,
+ artifacts[file].sha256
+ );
+ return { manifestFile, manifest_sha256: digest(manifestBytes), styles };
+}
+
+// This finite value permission applies to any element with the exact hash;
+// CSP cannot restrict a style hash to the announcer node.
+export function extractFrameworkStyleAttributes(
+ file,
+ source,
+ expectedSourceSha256
+) {
+ if (digest(source) !== expectedSourceSha256)
+ throw new Error('security_headers_stale_or_invalid');
+ const parsed = ts.createSourceFile(
+ file,
+ new TextDecoder('utf-8', { fatal: true }).decode(source),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.JS
+ );
+ if (parsed.parseDiagnostics.length)
+ throw new Error('security_headers_unreviewed_style_shape');
+ const styles = [];
+ function visit(node) {
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
+ if (/style\s*=/.test(node.text)) {
+ const match =
+ /^<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="([^"]+)"><!><\/div>$/.exec(
+ node.text
+ );
+ if (
+ !match ||
+ digest(match[1]) !==
+ '4bca8ca6fa1fa2547c3298f2e2442f126ee6d6af1c97353875f0c7d009af663a'
+ )
+ throw new Error('security_headers_unreviewed_style_shape');
+ styles.push({
+ owner: 'svelte-announcer',
+ file,
+ source_sha256: digest(source),
+ style_sha256: digest(match[1]),
+ csp_hash:
+ "'sha256-" +
+ createHash('sha256').update(match[1]).digest('base64') +
+ "'"
+ });
+ }
+ } else if (
+ ts.isTemplateExpression(node) &&
+ /style\s*=|svelte-announcer/.test(node.getText(parsed))
+ ) {
+ throw new Error('security_headers_unreviewed_style_shape');
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(parsed);
+ if (styles.length !== 1)
+ throw new Error('security_headers_unreviewed_style_shape');
+ return styles;
+}
+
+// Host-neutral SOURCE preparation, bound to the actual production source and
+// audited compiler bytes. No alternate test policy can substitute for the
+// policy compiled into this build. HTTPS/host/extension qualification is Q.
+export async function prepareSecurityHeaders(webDirectory) {
+ const web = path.resolve(webDirectory);
+ const names = await auditOutput(web);
+ const artifacts = {};
+ const inlineScripts = {};
+ const hashes = new Set();
+ for (const name of names) {
+ const bytes = await readBuilt(web, name);
+ artifacts[name] = { sha256: digest(bytes), bytes: bytes.length };
+ if (!name.endsWith('.html')) continue;
+ const html = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
+ const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)];
+ if (
+ scripts.length !== 1 ||
+ [...html.matchAll(/<script\b/g)].length !== scripts.length
+ )
+ throw new Error('security_headers_unreviewed_script_shape');
+ inlineScripts[name] = scripts.map(
+ (match) =>
+ "'sha256-" +
+ createHash('sha256').update(match[1]).digest('base64') +
+ "'"
+ );
+ for (const hash of inlineScripts[name]) hashes.add(hash);
+ }
+ const framework = await frameworkStyles(web, artifacts);
+ const connectSources = relayConnectSources(deploymentRelayPolicy);
+ const csp = [
+ "default-src 'none'",
+ "script-src 'self' " + [...hashes].sort().join(' '),
+ "style-src 'self'",
+ "style-src-attr 'unsafe-hashes' " + framework.styles[0].csp_hash,
+ "img-src 'self'",
+ "font-src 'self'",
+ 'connect-src ' +
+ (connectSources.length ? connectSources.join(' ') : "'none'"),
+ "object-src 'none'",
+ "frame-src 'none'",
+ "frame-ancestors 'none'",
+ "base-uri 'none'",
+ "form-action 'none'",
+ "worker-src 'none'",
+ "manifest-src 'none'"
+ ].join('; ');
+ // A second audit rejects a source/build transition during derivation.
+ if (!isDeepStrictEqual(names, await auditOutput(web)))
+ throw new Error('security_headers_stale_or_invalid');
+ for (const name of names)
+ if (digest(await readBuilt(web, name)) !== artifacts[name].sha256)
+ throw new Error('security_headers_stale_or_invalid');
+ if (
+ digest(await readBoundFile(framework.manifestFile)) !==
+ framework.manifest_sha256
+ )
+ throw new Error('security_headers_stale_or_invalid');
+ return {
+ schema: 'harvestcircle.static_security_headers.v1',
+ readiness: 'SOURCE_PREPARATION_ONLY_HOST_QUALIFICATION_PENDING',
+ relay_policy_sha256: digest(
+ JSON.stringify(readRelayPolicy(deploymentRelayPolicy))
+ ),
+ build_info_sha256: artifacts['build-info.json'].sha256,
+ compiler_manifest_sha256: framework.manifest_sha256,
+ framework_style_attributes: framework.styles,
+ connect_sources: connectSources,
+ inline_scripts: inlineScripts,
+ artifacts,
+ headers: {
+ 'Content-Security-Policy': csp,
+ 'Referrer-Policy': 'no-referrer',
+ 'Permissions-Policy':
+ 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
+ 'X-Frame-Options': 'DENY',
+ 'X-Content-Type-Options': 'nosniff'
+ }
+ };
+}
+
+export async function verifySecurityHeaders(webDirectory, candidate) {
+ if (!isDeepStrictEqual(candidate, await prepareSecurityHeaders(webDirectory)))
+ throw new Error('security_headers_stale_or_invalid');
+}
+
+if (
+ process.argv[1] &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ const web = path.resolve(fileURLToPath(new URL('../', import.meta.url)));
+ const [operation, output, ...extra] = process.argv.slice(2);
+ if (
+ extra.length ||
+ !['prepare', 'check'].includes(operation) ||
+ !output ||
+ !path.isAbsolute(output) ||
+ (await realpath(process.cwd())) !== web
+ )
+ throw new Error(
+ 'Run from web: node tools/security-headers.mjs prepare|check /absolute/external/report.json'
+ );
+ const destination = path.resolve(output);
+ const capsule = path.dirname(web);
+ if (
+ destination === capsule ||
+ destination.startsWith(capsule + path.sep) ||
+ (await realpath(path.dirname(destination))) !== path.dirname(destination)
+ )
+ throw new Error('Security header evidence must be outside the capsule');
+ if (operation === 'prepare') {
+ const prepared = await prepareSecurityHeaders(web);
+ await writeFile(destination, JSON.stringify(prepared, null, 2) + '\n', {
+ flag: 'wx',
+ mode: 0o600
+ });
+ console.log(
+ 'Static security headers prepared; actual host qualification remains pending'
+ );
+ } else {
+ await verifySecurityHeaders(
+ web,
+ JSON.parse(await readFile(destination, 'utf8'))
+ );
+ console.log('Static security headers match the current audited build');
+ }
+}