|
| 1 | +/** |
| 2 | + * Content-Security-Policy + hardening headers for the web UI (#657). |
| 3 | + * |
| 4 | + * Defense-in-depth: the JWT lives in localStorage (the EventSource header |
| 5 | + * limitation drove the `?token=` design), so a CSP contains any future XSS by |
| 6 | + * locking down where injected JS can send data. connect-src is built from the |
| 7 | + * SAME build-time env the app uses for its API/WS calls, so it matches the |
| 8 | + * real backend without hardcoding a deploy URL. |
| 9 | + * |
| 10 | + * Required by next.config.js (CommonJS) — keep this file dependency-free. |
| 11 | + */ |
| 12 | + |
| 13 | +const DEFAULT_WS_URL = 'ws://localhost:8000'; |
| 14 | +const AVATAR_HOST = 'https://avatars.githubusercontent.com'; |
| 15 | + |
| 16 | +/** |
| 17 | + * Closed allow-list of origins the browser may talk to. 'self' covers the |
| 18 | + * same-origin REST/SSE traffic (NEXT_PUBLIC_API_URL defaults to '' = proxied); |
| 19 | + * the WebSocket hooks dial NEXT_PUBLIC_WS_URL (or the localhost default). |
| 20 | + */ |
| 21 | +function buildConnectSrc({ apiUrl, wsUrl } = {}) { |
| 22 | + const sources = new Set(["'self'"]); |
| 23 | + if (apiUrl) sources.add(apiUrl); |
| 24 | + sources.add(wsUrl || DEFAULT_WS_URL); |
| 25 | + return Array.from(sources).join(' '); |
| 26 | +} |
| 27 | + |
| 28 | +function buildCsp(env = process.env) { |
| 29 | + const connectSrc = buildConnectSrc({ |
| 30 | + apiUrl: env.NEXT_PUBLIC_API_URL, |
| 31 | + wsUrl: env.NEXT_PUBLIC_WS_URL, |
| 32 | + }); |
| 33 | + return [ |
| 34 | + "default-src 'self'", |
| 35 | + // ponytail: 'unsafe-inline'/'unsafe-eval' are required by the Next.js App |
| 36 | + // Router without a per-request nonce middleware (a much larger change). |
| 37 | + // Exfil containment comes from connect-src/img-src/object-src below — not |
| 38 | + // script-src — so the token can't be POSTed/GET'd to an attacker origin. |
| 39 | + "script-src 'self' 'unsafe-inline' 'unsafe-eval'", |
| 40 | + "style-src 'self' 'unsafe-inline'", |
| 41 | + `img-src 'self' data: blob: ${AVATAR_HOST}`, |
| 42 | + "font-src 'self' data:", |
| 43 | + `connect-src ${connectSrc}`, |
| 44 | + "object-src 'none'", |
| 45 | + "base-uri 'self'", |
| 46 | + "frame-ancestors 'none'", |
| 47 | + "form-action 'self'", |
| 48 | + ].join('; '); |
| 49 | +} |
| 50 | + |
| 51 | +function securityHeaders(env = process.env) { |
| 52 | + return [ |
| 53 | + { key: 'Content-Security-Policy', value: buildCsp(env) }, |
| 54 | + { key: 'X-Content-Type-Options', value: 'nosniff' }, |
| 55 | + { key: 'X-Frame-Options', value: 'DENY' }, |
| 56 | + { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, |
| 57 | + ]; |
| 58 | +} |
| 59 | + |
| 60 | +module.exports = { buildCsp, buildConnectSrc, securityHeaders }; |
0 commit comments