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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
771dda1c6f
commit
ff4c595b91
@@ -1,22 +1,8 @@
|
||||
export type BuildCspArgs = {
|
||||
/** Google Analytics / GTM — adds googletagmanager + google-analytics. */
|
||||
analytics?: boolean
|
||||
/** Extra sources per directive, merged with the built-ins. */
|
||||
extra?: Partial<Record<CspDirective, string[]>>
|
||||
/** Google Maps — embeds (iframe) and the Maps JavaScript API, full domain set. Google Fonts are allowed by default. */
|
||||
googleMaps?: boolean
|
||||
/** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */
|
||||
mode?: 'enforce' | 'report-only'
|
||||
/** Media/R2 public URL (from R2_PUBLIC_URL) — added to img-src. */
|
||||
r2Url?: string
|
||||
/** Cloudflare Turnstile — adds challenges.cloudflare.com to script/frame/connect. */
|
||||
turnstile?: boolean
|
||||
/** YouTube embeds — adds youtube to frame-src. */
|
||||
youtube?: boolean
|
||||
}
|
||||
import type { SecurityHeader } from './buildSecurityHeaders.js'
|
||||
|
||||
type CspDirective =
|
||||
export type CspDirective =
|
||||
| 'base-uri'
|
||||
| 'child-src'
|
||||
| 'connect-src'
|
||||
| 'default-src'
|
||||
| 'font-src'
|
||||
@@ -24,12 +10,76 @@ type CspDirective =
|
||||
| '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
|
||||
@@ -40,7 +90,8 @@ type CspDirective =
|
||||
* 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`:
|
||||
* 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({
|
||||
@@ -55,29 +106,61 @@ type CspDirective =
|
||||
* missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md.
|
||||
*/
|
||||
export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } {
|
||||
const { analytics, extra = {}, googleMaps, mode = 'enforce', r2Url, turnstile, youtube } = args
|
||||
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<CspDirective, string[]> = {
|
||||
'default-src': ["'self'"],
|
||||
// 'unsafe-inline' is hard to avoid with Next/analytics; 'unsafe-eval' is NOT
|
||||
// added by default (weakens CSP) — add via extra only if a library needs it.
|
||||
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 extra when needed
|
||||
'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 extra when needed
|
||||
'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)}
|
||||
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')
|
||||
@@ -89,9 +172,42 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
|
||||
// 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')
|
||||
src['img-src'].push('https://*.google-analytics.com', '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) {
|
||||
@@ -111,15 +227,92 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
|
||||
}
|
||||
|
||||
// Merge caller extras.
|
||||
for (const [dir, values] of Object.entries(extra) as Array<[CspDirective, string[]]>) {
|
||||
for (const [dir, values] of Object.entries(extra)) {
|
||||
if (values && values.length) {src[dir] = [...(src[dir] ?? []), ...values]}
|
||||
}
|
||||
|
||||
const value = (Object.entries(src) as Array<[CspDirective, string[]]>)
|
||||
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('; ')
|
||||
|
||||
const key = mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'
|
||||
return { key, value }
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user