diff --git a/SECURITY.md b/SECURITY.md index 2247dca..9bb4896 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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 ``; 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 `` CSP can express: + +- No clickjacking protection. `frame-ancestors` is ignored when a CSP is delivered via ``, 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. diff --git a/e2e/csp.spec.ts b/e2e/csp.spec.ts new file mode 100644 index 0000000..18d5a4a --- /dev/null +++ b/e2e/csp.spec.ts @@ -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://.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([]); + }); +}); diff --git a/src/api/hnSdk.ts b/src/api/hnSdk.ts index 95329f9..873bb24 100644 --- a/src/api/hnSdk.ts +++ b/src/api/hnSdk.ts @@ -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