import type { SecurityHeader } from './buildSecurityHeaders.js' export type CspDirective = | 'base-uri' | 'child-src' | 'connect-src' | 'default-src' | 'font-src' | 'form-action' | 'frame-ancestors' | 'frame-src' | 'img-src' | 'manifest-src' | 'media-src' | 'object-src' | 'script-src' | 'style-src' | 'worker-src' /** Sources per directive. Any directive name is accepted (also ones not in CspDirective). */ export type CspSources = Partial> export type BuildCspArgs = { /** Google Analytics / GTM — adds googletagmanager + google-analytics (+ Google Signals hosts). */ analytics?: boolean /** Microsoft Clarity (plugin's loadClarity). */ clarity?: boolean /** * Development mode: adds 'unsafe-eval' to script-src (React / Next dev tooling * needs it; production does not). Default `process.env.NODE_ENV === 'development'`. */ dev?: boolean /** Extra sources per directive, merged with the built-ins. */ extra?: CspSources /** Google Maps — embeds (iframe) and the Maps JavaScript API, full domain set. Google Fonts are allowed by default. */ googleMaps?: boolean /** LinkedIn Insight Tag (plugin's loadLinkedIn). */ linkedIn?: boolean /** Meta (Facebook) Pixel (plugin's loadMetaPixel / ConsentScript with fbevents.js). */ metaPixel?: boolean /** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */ mode?: 'enforce' | 'report-only' /** * Per-request nonce (from the proxy — createProxy `csp`, or createCspNonce). * Adds `'nonce-…'` to script-src and, with `strictDynamic` (default on with a * nonce), `'strict-dynamic'`: scripts the nonced Next bootstrap loads are * trusted, so host lists and 'unsafe-inline' stop mattering in CSP3 browsers * (both stay as a fallback for old ones). Needs dynamic rendering — see docs. */ nonce?: string /** * Replace a directive completely (`null` drops it). Applied after everything * else — the escape hatch when a built-in source does not fit the project. */ override?: Partial> /** Media/R2 public URL (from R2_PUBLIC_URL) — added to img-src and media-src. */ r2Url?: string /** Reporting API group name for `report-to` (and the Reporting-Endpoints header). Default 'csp-endpoint'. */ reportGroup?: string /** * Where browsers send violation reports, e.g. '/api/csp-report' * (createCspReportRoute) or a third-party collector URL. Adds `report-uri` * and `report-to`; buildCspHeaders also returns the Reporting-Endpoints header. */ reportUri?: string /** With a nonce: add 'strict-dynamic'. Default true. */ strictDynamic?: boolean /** TikTok Pixel (plugin's loadTikTok). */ tiktok?: boolean /** Cloudflare Turnstile — adds challenges.cloudflare.com to script/frame/connect. */ turnstile?: boolean /** YouTube embeds — adds youtube to frame-src. */ youtube?: boolean } export const DEFAULT_CSP_REPORT_GROUP = 'csp-endpoint' /** Header name for the mode — the request header Next reads the nonce from is the same. */ export function cspHeaderKey(mode: BuildCspArgs['mode'] = 'enforce'): string { return mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy' } /** * Builds a Content-Security-Policy string with the hard OWASP/Lighthouse-required * directives baked in, and opt-in sources for common third parties. Solves the * real risk of hand-writing raw CSP per project and forgetting `base-uri 'self'` * or `object-src 'none'`. * * CSP still lives in the project (it lists the project's own domains), but this * helper standardizes the skeleton so every project's CSP has the same hardened * base — you only flip flags for what the project actually loads. * * Returns { key, value } ready for buildSecurityHeaders `additional` * (or pass the args as buildSecurityHeaders `csp`, which also adds Reporting-Endpoints): * * import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit' * const csp = buildCsp({ * mode: 'report-only', // start here; switch to 'enforce' when clean * r2Url: process.env.R2_PUBLIC_URL, * turnstile: true, analytics: true, * }) * const headers = buildSecurityHeaders({ hsts: prod, additional: [csp] }) * * Deploy CSP carefully: start with mode:'report-only', check the console for * violations across the whole site (forms/Turnstile, gallery/R2, embeds), add * missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md. */ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } { const { analytics, clarity, dev = process.env.NODE_ENV === 'development', extra = {}, googleMaps, linkedIn, metaPixel, mode = 'enforce', nonce, override = {}, r2Url, reportGroup = DEFAULT_CSP_REPORT_GROUP, reportUri, strictDynamic = true, tiktok, turnstile, youtube, } = args const src: Record = { 'connect-src': ["'self'"], 'default-src': ["'self'"], 'font-src': ["'self'", 'https://fonts.gstatic.com', 'data:'], 'form-action': ["'self'"], 'frame-src': [], 'img-src': ["'self'", 'data:', 'blob:'], 'media-src': [], // video/audio sources — filled via r2Url / extra // Without a nonce: 'unsafe-inline' is required — Next streams its RSC payload // in inline