Skip to content
Merged
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
8 changes: 8 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,11 @@ This project employs the following security practices:
- CodeQL static analysis on pushes and pull requests to `main`, plus weekly scheduled scans
- OpenSSF Scorecard monitoring
- HTML sanitization via DOMPurify
- A strict Content-Security-Policy delivered via `<meta http-equiv>`; inline scripts are allowed by SHA-256 hash rather than `'unsafe-inline'`, and `connect-src` is limited to the Hacker News APIs

### Accepted GitHub Pages constraints

GitHub Pages serves static files and cannot set HTTP response headers, which limits a few defenses to what a `<meta>` CSP can express:

- No clickjacking protection. `frame-ancestors` is ignored when a CSP is delivered via `<meta>`, and `X-Frame-Options` cannot be sent, so the site can be embedded in a frame.
- No CSP violation reporting. `report-to`/`report-uri` require a response header and a collection endpoint, neither of which is available; the build instead fails if any executable inline script in the built HTML lacks a CSP hash, and the e2e suite asserts the deployed policy is violation-free.
69 changes: 69 additions & 0 deletions e2e/csp.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { test, expect, type Page } from '@playwright/test';
import { setupApiMocks } from './fixtures/api-mocks';

/**
* Guards the build-time meta CSP (htmlMetaCsp() in vite.config.js), exercised
* via `vite preview` of the production build. The CSP has no functional
* footprint — a missing CSP or a dropped script hash leaves the app fully usable
* — so these assertions are the only thing that catches a silent regression.
*/

/** Capture securitypolicyviolation events before any page script runs. */
async function collectCspViolations(page: Page) {
await page.addInitScript(() => {
(window as unknown as { __csp: string[] }).__csp = [];
document.addEventListener('securitypolicyviolation', (e) => {
(window as unknown as { __csp: string[] }).__csp.push(
`${e.effectiveDirective || e.violatedDirective} :: ${e.blockedURI}`,
);
});
});
}

const readViolations = (page: Page) =>
page.evaluate(() => (window as unknown as { __csp: string[] }).__csp);

test.describe('Content-Security-Policy', () => {
test.beforeEach(async ({ page }) => {
await collectCspViolations(page);
await setupApiMocks(page);
});

test('ships exactly one enforced meta CSP', async ({ page }) => {
await page.goto('/', { waitUntil: 'networkidle' });

const meta = page.locator('meta[http-equiv="Content-Security-Policy"]');
await expect(meta).toHaveCount(1);

const content = (await meta.getAttribute('content')) ?? '';
// Core hardening directives must be present and must not regress to unsafe values.
expect(content).toContain("default-src 'self'");
expect(content).toContain("object-src 'none'");
expect(content).toContain("base-uri 'self'");
expect(content).toMatch(/script-src 'self'[^;]*'sha256-/);
expect(content).not.toContain("script-src 'self' 'unsafe-inline'");
// Assert connect-src endpoints by string: the violation checks below can't
// see the WebSocket path because page.routeWebSocket replaces window.WebSocket
// with a shim that never opens a native socket, so the browser never evaluates
// connect-src for wss://. Deleting wss:// would ship green yet break production.
expect(content).toContain('https://hn.algolia.com');
expect(content).toContain('wss://*.firebaseio.com');
});

test('raises no violations on load (Algolia-backed homepage)', async ({ page }) => {
await page.goto('/', { waitUntil: 'networkidle' });
await expect(page.locator('#root')).not.toBeEmpty();
expect(await readViolations(page)).toEqual([]);
});

test('raises no violations navigating to a Firebase-backed section', async ({ page }) => {
await page.goto('/#/best', { waitUntil: 'networkidle' });
// /#/best reads over wss://<shard>.firebaseio.com. Assert the data rendered
// (layout-agnostic: title is in the DOM for both list and swipe) so the wss
// connection is actually exercised; a blocked wss:// would raise a violation.
await expect(page.locator('#root')).toContainText('The Art of Finishing Projects', {
timeout: 10_000,
});
expect(await readViolations(page)).toEqual([]);
});
});
8 changes: 7 additions & 1 deletion src/api/hnSdk.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { getApps, initializeApp } from 'firebase/app';
import { get, getDatabase, ref } from 'firebase/database';
import { forceWebSockets, get, getDatabase, ref } from 'firebase/database';
import type { FirebaseItem, UserProfile } from '../types';

const APP_NAME = 'hn-sdk';

// Pin RTDB to WebSockets. Its long-poll fallback is <script> injection to
// *.firebaseio.com/.lp, which our script-src blocks — so it's already dead under
// the CSP and dropping it only removes failed requests + console errors. Must
// run before the first connection opens.
forceWebSockets();

function getDb() {
const existing = getApps().find(app => app.name === APP_NAME);
const app = existing
Expand Down
142 changes: 141 additions & 1 deletion vite.config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,152 @@
/// <reference types="vitest/config" />
import { fileURLToPath } from 'node:url'
import { createHash } from 'node:crypto'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'

// Build-time CSP as a <meta http-equiv> — GitHub Pages can't set response
// headers. Build-only so dev HMR (inline scripts + ws://) keeps working.
// script-src avoids 'unsafe-inline' by hashing executable inline scripts from
// the FINAL html (order: 'post') so hashes can't drift; inert blocks like
// <script type="application/ld+json"> aren't governed by script-src, so skip them.
function htmlMetaCsp() {
const SELF = "'self'"
const sha256 = (content) =>
`'sha256-${createHash('sha256').update(content, 'utf8').digest('base64')}'`

// script-src governs only scripts the browser executes (classic/module): an
// absent/empty type, "module", or an exact case-insensitive match for a
// JavaScript MIME type essence string. A parameterized type like
// "text/javascript;charset=utf-8" is NOT a match, so the browser treats it as
// inert data and we must not hash it. The essence list (incl. legacy aliases)
// is verified to execute across Chromium/Firefox/WebKit; inert blocks like
// <script type="application/ld+json"> don't.
const JS_MIME_ESSENCE = new Set([
'application/ecmascript', 'application/javascript',
'application/x-ecmascript', 'application/x-javascript',
'text/ecmascript', 'text/javascript',
'text/javascript1.0', 'text/javascript1.1', 'text/javascript1.2',
'text/javascript1.3', 'text/javascript1.4', 'text/javascript1.5',
'text/jscript', 'text/livescript',
'text/x-ecmascript', 'text/x-javascript',
])
const isExecutableType = (type) => {
const t = type.trim().toLowerCase()
return t === '' || t === 'module' || JS_MIME_ESSENCE.has(t)
}
const typeOfTag = (attrs) => {
const m = /\stype\s*=\s*["']?([^"'\s>]+)/i.exec(attrs)
return m ? m[1] : ''
}

return {
name: 'html-meta-csp',
apply: 'build',
transformIndexHtml: {
order: 'post',
async handler(html) {
// \ssrc= lookahead skips external <script src=...>; the jsdom check
// below backstops its blind spot (inline script with " src=" in an attr).
const inlineScript = /<script(?![^>]*\ssrc=)([^>]*)>([\s\S]*?)<\/script>/gi
const scriptHashes = []
let match
while ((match = inlineScript.exec(html)) !== null) {
if (isExecutableType(typeOfTag(match[1]))) {
scriptHashes.push(sha256(match[2]))
}
}

const csp = [
`default-src ${SELF}`,
`base-uri ${SELF}`,
`object-src 'none'`,
`frame-src 'none'`,
`script-src ${SELF} ${scriptHashes.join(' ')}`,
// unsafe-inline for styles only: React inline styles + dynamic CSS
// vars can't be practically hashed.
`style-src ${SELF} 'unsafe-inline'`,
`img-src ${SELF} data:`,
`font-src ${SELF}`,
// Algolia REST (https) + Firebase RTDB (wss only — forceWebSockets()
// means no https/long-poll to firebaseio, and https doesn't relax to
// wss). The wildcard covers RTDB's dynamically-assigned shard hosts.
`connect-src ${SELF} https://hn.algolia.com wss://*.firebaseio.com`,
`manifest-src ${SELF}`,
`worker-src ${SELF}`,
`form-action ${SELF}`,
// No upgrade-insecure-requests: all endpoints are already https/wss,
// and WebKit upgrades even http://localhost, breaking the preview e2e.
// No frame-ancestors: ignored in a <meta> CSP (see SECURITY.md).
].join('; ')

const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}" />`
// After <meta charset> so it stays in the first 1024 bytes and the CSP
// precedes the inline scripts it governs.
const out = html.replace(
/(<meta charset=["'][^"']*["']\s*\/?>)/i,
`$1\n ${meta}`
)
if (out === html) {
throw new Error('[html-meta-csp] <meta charset> anchor not found — CSP was not injected')
}

await assertEveryInlineScriptHashed(out, csp, sha256, isExecutableType)
return out
},
},
}
}

// Backstop: re-parse the final html with jsdom (not the extraction regex) and
// fail the build if any executable inline script lacks a hash — catches the
// regex's blind spot and any future plugin that injects unhashed scripts.
async function assertEveryInlineScriptHashed(out, csp, sha256, isExecutableType) {
const { JSDOM } = await import('jsdom')
const { document } = new JSDOM(out).window
for (const el of document.querySelectorAll('script')) {
if (el.hasAttribute('src')) continue
if (!isExecutableType(el.getAttribute('type') ?? '')) continue
const hash = sha256(el.textContent ?? '')
if (!csp.includes(hash)) {
throw new Error(
`[html-meta-csp] executable inline <script> is not allow-listed by the CSP (${hash}). ` +
`The src= extraction regex likely skipped it — fix the script or the regex.`,
)
}
}
}

// RFC 9116 security.txt emitted at build time so the required Expires stays
// fresh (+6mo, under the RFC's <1yr) and can't silently go stale. Pages serves
// the dot-directory because the Actions artifact deploy skips Jekyll.
function wellKnownSecurityTxt() {
const REPO = 'https://github.com/hackertok/hackertok.github.io'
const SITE = 'https://hackertok.github.io'
return {
name: 'well-known-security-txt',
apply: 'build',
generateBundle() {
const expires = new Date()
expires.setUTCMonth(expires.getUTCMonth() + 6)
expires.setUTCMilliseconds(0)
const source = [
'# HackerTok security contact (RFC 9116). Expires regenerated each build.',
`Contact: ${REPO}/security/advisories/new`,
`Expires: ${expires.toISOString().replace('.000Z', 'Z')}`,
`Policy: ${REPO}/blob/main/SECURITY.md`,
`Canonical: ${SITE}/.well-known/security.txt`,
'Preferred-Languages: en',
'',
].join('\n')
this.emitFile({ type: 'asset', fileName: '.well-known/security.txt', source })
},
}
}

// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
plugins: [react(), tailwindcss(), htmlMetaCsp(), wellKnownSecurityTxt()],
base: '/',
resolve: {
// Mirrors tsconfig.json paths and components.json aliases so `@/...`
Expand Down