Files
ipal-kit/src/modules/security/buildCsp.ts
T
Radosław SmolińskiandClaude Opus 5.5 ff4c595b91 Security: hide X-Powered-By, CSP report-only with reports, admin policy and nonces
- withSecurityConfig: poweredByHeader false + strips X-Powered-By from headers()
  (Next's and withPayload's), works on either side of withPayload
- buildSecurityHeaders({ csp }): CSP + Reporting-Endpoints; mode switches
  report-only → enforce
- buildCsp: reportUri/reportGroup, nonce + strict-dynamic, dev unsafe-eval,
  metaPixel/linkedIn/tiktok/clarity flags, media-src for R2, override
- buildAdminCsp(Headers): looser policy for Payload admin (Monaco CDN, blob workers)
- createCspReportRoute + parseCspReports: report collector for both formats
- createProxy({ csp }) + createCspNonce: per-request nonce, x-nonce header;
  SiteProviders/ThemeScript/Analytics/ConsentScript accept nonce
- docs: security.md, AGENT.md, ipal-setup/reference/upgrade; ipal-audit checks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 21:28:11 +01:00

319 lines
13 KiB
TypeScript

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<Record<({} & string) | CspDirective, string[]>>
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<Record<({} & string) | CspDirective, null | string[]>>
/** 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<string, string[]> = {
'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 <script> tags that differ per page and per render, so neither a
// static header nor hashes can list them. With a nonce it is only a CSP2
// fallback (CSP3 browsers ignore it once a nonce is present).
// 'unsafe-eval' is NOT added in production (weakens CSP) — `dev` adds it.
'script-src': ["'self'", "'unsafe-inline'"],
// Styles: React/Next and the plugin set inline style attributes (positions,
// CSS variables) and next/font + experimental.inlineCss emit <style> tags —
// attributes cannot carry a nonce, so 'unsafe-inline' stays for style-src.
'style-src': ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
'worker-src': [], // web workers — filled via googleMaps / extra
// HARD defaults (OWASP/Lighthouse) — always on, no reason to omit:
'base-uri': ["'self'"], // block <base> hijacking
'frame-ancestors': ["'none'"], // clickjacking protection (replaces X-Frame-Options)
'object-src': ["'none'"], // block <object>/<embed> (Flash-era attack surface)
}
if (nonce) {
src['script-src'].unshift(`'nonce-${nonce}'`, ...(strictDynamic ? ["'strict-dynamic'"] : []))
}
if (dev) {src['script-src'].push("'unsafe-eval'")}
// Site-relative R2_PUBLIC_URL ('/media', dev) is same-origin — already covered by 'self'.
if (r2Url && /^https?:\/\//i.test(r2Url)) {
src['img-src'].push(r2Url)
src['media-src'].push("'self'", r2Url)
}
if (turnstile) {
src['script-src'].push('https://challenges.cloudflare.com')
src['frame-src'].push('https://challenges.cloudflare.com')
src['connect-src'].push('https://challenges.cloudflare.com')
}
if (analytics) {
// Google's GA4/GTM CSP set. Wildcards are required: GA4 sends EU hits to
// region1.google-analytics.com and some to *.analytics.google.com — allowing
// only www.google-analytics.com blocks every hit ("data collection not active").
// doubleclick + www.google.com: Google Signals / Ads conversion pings.
src['script-src'].push('https://*.googletagmanager.com')
src['connect-src'].push(
'https://*.google-analytics.com',
'https://*.analytics.google.com',
'https://*.googletagmanager.com',
'https://*.g.doubleclick.net',
'https://www.google.com',
)
src['img-src'].push('https://*.google-analytics.com', 'https://*.googletagmanager.com', 'https://*.g.doubleclick.net', 'https://www.google.com')
}
if (metaPixel) {
src['script-src'].push('https://connect.facebook.net')
src['connect-src'].push('https://www.facebook.com', 'https://connect.facebook.net')
src['img-src'].push('https://www.facebook.com')
src['frame-src'].push('https://www.facebook.com')
}
if (linkedIn) {
src['script-src'].push('https://snap.licdn.com')
src['connect-src'].push('https://px.ads.linkedin.com', 'https://px4.ads.linkedin.com', 'https://www.linkedin.com')
src['img-src'].push('https://px.ads.linkedin.com', 'https://px4.ads.linkedin.com', 'https://www.linkedin.com')
}
if (tiktok) {
src['script-src'].push('https://analytics.tiktok.com')
src['connect-src'].push('https://analytics.tiktok.com')
src['img-src'].push('https://analytics.tiktok.com')
}
if (clarity) {
// The tag loads from www.clarity.ms, then scripts.clarity.ms; data goes to *.clarity.ms.
src['script-src'].push('https://*.clarity.ms')
src['connect-src'].push('https://*.clarity.ms')
src['img-src'].push('https://*.clarity.ms', 'https://c.bing.com')
}
if (youtube) {
src['frame-src'].push('https://www.youtube.com', 'https://www.youtube-nocookie.com')
src['img-src'].push('https://i.ytimg.com') // YouTubeEmbed poster
}
if (googleMaps) {
// Embeds (iframe) and the Maps JavaScript API — the domain set from Google's
// CSP guide for Maps JS (tiles, markers, Street View images, fonts, workers).
const g = ['https://*.googleapis.com', 'https://*.gstatic.com', 'https://*.google.com', 'https://*.ggpht.com', 'https://*.googleusercontent.com']
src['frame-src'].push('https://www.google.com', 'https://maps.google.com', 'https://*.google.com')
src['script-src'].push(...g)
src['img-src'].push(...g)
src['connect-src'].push('https://*.googleapis.com', 'https://*.google.com', 'https://*.gstatic.com', 'data:', 'blob:')
src['worker-src'].push('blob:')
}
// Merge caller extras.
for (const [dir, values] of Object.entries(extra)) {
if (values && values.length) {src[dir] = [...(src[dir] ?? []), ...values]}
}
if (reportUri) {
src['report-uri'] = [reportUri]
src['report-to'] = [reportGroup]
}
// Replace whole directives last.
for (const [dir, values] of Object.entries(override)) {
if (values === null) {delete src[dir]}
else if (values) {src[dir] = values}
}
const value = Object.entries(src)
.filter(([, values]) => values.length > 0)
.map(([dir, values]) => `${dir} ${[...new Set(values)].join(' ')}`)
.join('; ')
return { key: cspHeaderKey(mode), value }
}
/**
* The CSP header plus, with `reportUri`, the Reporting-Endpoints header that
* `report-to` points at (Chrome/Edge use report-to; Firefox/Safari still use
* report-uri — the policy carries both).
*/
export function buildCspHeaders(args: BuildCspArgs = {}): SecurityHeader[] {
const headers: SecurityHeader[] = [buildCsp(args)]
if (args.reportUri) {headers.push(buildReportingEndpoints(args.reportUri, args.reportGroup))}
return headers
}
/** `Reporting-Endpoints: <group>="<url>"` — the target of CSP `report-to`. */
export function buildReportingEndpoints(url: string, group: string = DEFAULT_CSP_REPORT_GROUP): SecurityHeader {
return { key: 'Reporting-Endpoints', value: `${group}="${url}"` }
}
export type BuildAdminCspArgs = Pick<
BuildCspArgs,
'dev' | 'extra' | 'mode' | 'override' | 'r2Url' | 'reportGroup' | 'reportUri'
>
/**
* A separate, looser policy for Payload's admin (`/admin/:path*`). The admin is
* a large client app the project does not control: it needs inline scripts and
* styles, loads the Monaco code editor (code/JSON fields) from cdn.jsdelivr.net
* with blob: workers, and frames the site itself for Live Preview. The hard
* rules (base-uri, object-src, form-action) stay.
*
* async headers() {
* return [
* { source: '/:path*', headers: securityHeaders },
* { source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only' }) },
* ]
* }
*
* Next applies the last matching rule for the same header key, so the admin
* rule must come after the site-wide one.
*/
export function buildAdminCsp(args: BuildAdminCspArgs = {}): { key: string; value: string } {
const monaco = 'https://cdn.jsdelivr.net'
const adminExtra: CspSources = {
'connect-src': [monaco],
'font-src': [monaco],
'frame-src': ["'self'"], // Live Preview iframe
'img-src': ['https:'], // avatars, external upload previews
'script-src': [monaco],
'style-src': [monaco],
'worker-src': ["'self'", 'blob:'],
}
for (const [dir, values] of Object.entries(args.extra ?? {})) {
if (values) {adminExtra[dir] = [...(adminExtra[dir] ?? []), ...values]}
}
return buildCsp({
...args,
extra: adminExtra,
// Admin is never framed by another origin; Live Preview frames the SITE, not the admin.
override: { 'frame-ancestors': ["'self'"], ...args.override },
})
}
/** buildAdminCsp plus Reporting-Endpoints (with `reportUri`). */
export function buildAdminCspHeaders(args: BuildAdminCspArgs = {}): SecurityHeader[] {
const headers: SecurityHeader[] = [buildAdminCsp(args)]
if (args.reportUri) {headers.push(buildReportingEndpoints(args.reportUri, args.reportGroup))}
return headers
}