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:
Radosław Smoliński
2026-10-27 21:28:11 +01:00
co-authored by Claude Opus 5.5
parent 771dda1c6f
commit ff4c595b91
22 changed files with 1059 additions and 186 deletions
+1
View File
@@ -10,3 +10,4 @@
export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/createProxy.js'
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/localeMiddleware.js'
export type { LocaleMiddlewareResult } from '../modules/i18n/localeMiddleware.js'
export { createCspNonce, CSP_NONCE_HEADER } from '../modules/security/cspNonce.js'
+25 -3
View File
@@ -254,9 +254,31 @@ export { buildTableOfContentsField, extractHeadings, headingText } from './modul
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './modules/richtext/headings.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/lexicalToMarkdown.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export {
buildAdminCsp,
buildAdminCspHeaders,
buildCsp,
buildCspHeaders,
buildReportingEndpoints,
buildSecurityHeaders,
buildUploadSecurityHeaders,
createCspNonce,
createCspReportRoute,
CSP_NONCE_HEADER,
cspHeaderKey,
DEFAULT_CSP_REPORT_GROUP,
parseCspReports,
withSecurityConfig,
} from './modules/security/index.js'
export type {
BuildAdminCspArgs,
BuildCspArgs,
CreateCspReportRouteArgs,
CspDirective,
CspSources,
CspViolation,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
+9 -4
View File
@@ -32,11 +32,13 @@ function readConsent(version: number | undefined) {
return parseConsent(raw, version) ?? DEFAULT_CONSENT
}
function injectScript(src: string) {
function injectScript(src: string, nonce?: string) {
if (document.querySelector(`script[src="${src}"]`)) {return}
const s = document.createElement('script')
s.src = src
s.async = true
// GTM reads its own script's nonce and passes it to Custom HTML tags.
if (nonce) {s.nonce = nonce}
document.head.appendChild(s)
}
@@ -68,6 +70,8 @@ export type AnalyticsProps = {
defer?: boolean
/** Fallback delay after window `load`, in ms. Default 3500. */
deferTimeoutMs?: number
/** CSP nonce (nonce-based policy) — set on the GA4 / GTM script tag. */
nonce?: string
} & AnalyticsConfig
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
@@ -135,6 +139,7 @@ export function Analytics(props: AnalyticsProps) {
gtmContainerId,
linkedInPartnerId,
metaPixelId,
nonce,
tiktokPixelId,
} = props
@@ -162,13 +167,13 @@ export function Analytics(props: AnalyticsProps) {
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
injectScript(GTM_SCRIPT(gtmContainerId))
injectScript(GTM_SCRIPT(gtmContainerId), nonce)
} else if (ga4MeasurementId) {
injectScript(GA4_SCRIPT(ga4MeasurementId))
injectScript(GA4_SCRIPT(ga4MeasurementId), nonce)
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [googleAllowed, ga4MeasurementId, gtmContainerId])
}, [googleAllowed, ga4MeasurementId, gtmContainerId, nonce])
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
+9 -1
View File
@@ -25,6 +25,11 @@ type ConsentScriptProps = {
defer?: boolean
/** Stable id used to dedupe — the script is injected at most once. */
id?: string
/**
* CSP nonce for both the external and the inline script. Only needed with a
* nonce policy WITHOUT 'strict-dynamic' (with it, scripts the app adds are trusted).
*/
nonce?: string
/** External script URL. Injected only once the category is granted. */
src?: string
}
@@ -60,6 +65,7 @@ export function ConsentScript({
category,
code,
defer,
nonce,
src,
}: ConsentScriptProps) {
const { state } = useConsentContext()
@@ -82,6 +88,7 @@ export function ConsentScript({
if (!code) {return}
const inline = document.createElement('script')
if (dedupeId) {inline.id = `${dedupeId}-inline`}
if (nonce) {inline.nonce = nonce}
inline.textContent = code
document.head.appendChild(inline)
}
@@ -92,6 +99,7 @@ export function ConsentScript({
if (dedupeId) {el.id = dedupeId}
if (asyncAttr) {el.async = true}
if (defer) {el.defer = true}
if (nonce) {el.nonce = nonce}
if (attributes) {for (const [k, v] of Object.entries(attributes)) {el.setAttribute(k, v)}}
// eslint-disable-next-line @eslint-react/web-api/no-leaked-event-listener -- one-shot, and the script is never unloaded (see below)
el.addEventListener('load', runInline, { once: true })
@@ -102,7 +110,7 @@ export function ConsentScript({
// Deliberately no removal on cleanup: a loaded third-party script can't be
// meaningfully unloaded. Withdrawal is handled by not re-injecting (and, for
// vendors that support it, Consent Mode). See the component doc.
}, [granted, src, code, id, attributes, asyncAttr, defer])
}, [granted, src, code, id, attributes, asyncAttr, defer, nonce])
return null
}
+9 -2
View File
@@ -39,6 +39,12 @@ export type SiteProvidersProps = {
lightbox?: boolean | Omit<LightboxProviderProps, 'children' | 'renderDialog' | 'renderImage'>
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
logEndpoint?: string
/**
* CSP nonce for a nonce-based policy (createProxy `csp`): read it in the layout
* with `(await headers()).get('x-nonce')`. Goes on the theme script and on the
* analytics tags the plugin injects (GTM passes it on to its own tags).
*/
nonce?: null | string
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
preconnect?: boolean
/** getSiteShell(locale) from lib/content. */
@@ -81,6 +87,7 @@ export function SiteProviders({
jsonLd = [],
lightbox = false,
logEndpoint,
nonce,
preconnect = true,
shell,
stats = false,
@@ -88,7 +95,7 @@ export function SiteProviders({
}: SiteProvidersProps) {
return (
<>
{theme ? <ThemeScript {...shell.theme} /> : null}
{theme ? <ThemeScript {...shell.theme} nonce={nonce ?? undefined} /> : null}
{preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
@@ -103,7 +110,7 @@ export function SiteProviders({
</TurnstileProvider>
{banner === undefined ? <CookieBanner /> : banner || null}
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
{analytics === false ? null : <Analytics {...shell.analytics} nonce={nonce ?? undefined} {...analytics} />}
{stats ? <PageStats {...(stats === true ? {} : stats)} /> : null}
</ConsentProvider>
</>
+30 -1
View File
@@ -1,6 +1,9 @@
import type { BuildCspArgs } from '../security/buildCsp.js'
import type { I18nConfig } from './types.js'
import { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from '../content/markdownNegotiation.js'
import { buildCsp, buildReportingEndpoints } from '../security/buildCsp.js'
import { createCspNonce, CSP_NONCE_HEADER } from '../security/cspNonce.js'
import { isValidLocale } from './helpers.js'
import { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'
@@ -23,6 +26,8 @@ type ProxyRequest = {
type ProxyResponse = {
cookies: { set: (name: string, value: string, opts?: Record<string, unknown>) => void }
/** Needed for `csp`; Next's NextResponse has it. */
headers?: Headers
}
/**
@@ -40,6 +45,16 @@ type CreateProxyOptions = {
consentCategory?: 'functional' | 'necessary'
consentCookieName?: string
cookieName?: string
/**
* Content-Security-Policy with a per-request nonce (buildCsp args, no `nonce`).
* The proxy creates the nonce, puts the policy on the request (Next reads the
* nonce from it and adds it to its own scripts) and on the response, and
* exposes the nonce as the `x-nonce` request header for <SiteProviders nonce>.
* Nonces need dynamic rendering: every page under the matcher renders per
* request (no ISR / static HTML). Static sites keep the header-only CSP from
* buildSecurityHeaders `csp` instead. Default off.
*/
csp?: Omit<BuildCspArgs, 'nonce'>
/** Expose x-locale / x-pathname request headers to RSC. Default true. */
exposeHeaders?: boolean
/**
@@ -72,7 +87,7 @@ export function createProxy(
config: I18nConfig,
deps: { NextResponse: NextResponseLike } & CreateProxyOptions,
): (request: ProxyRequest) => ProxyResponse {
const { exposeHeaders = true, markdown, NextResponse, ...mwOptions } = deps
const { csp, exposeHeaders = true, markdown, NextResponse, ...mwOptions } = deps
const run = createLocaleMiddleware({ config, ...mwOptions })
const mdPrefix = markdown ? (typeof markdown === 'string' ? markdown : MARKDOWN_PREFIX).replace(/\/$/, '') : null
@@ -92,6 +107,12 @@ export function createProxy(
const result = run(request)
const requestHeaders = new Headers(request.headers)
const nonce = csp ? createCspNonce() : undefined
const policy = csp ? buildCsp({ ...csp, nonce }) : null
if (policy && nonce) {
requestHeaders.set(policy.key, policy.value)
requestHeaders.set(CSP_NONCE_HEADER, nonce)
}
if (exposeHeaders) {
const seg = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = isValidLocale(seg, config) ? seg : config.defaultLocale
@@ -104,6 +125,14 @@ export function createProxy(
? NextResponse.redirect(new URL(result.location, request.url))
: NextResponse.next({ request: { headers: requestHeaders } })
if (policy) {
response.headers?.set(policy.key, policy.value)
if (csp?.reportUri) {
const re = buildReportingEndpoints(csp.reportUri, csp.reportGroup)
response.headers?.set(re.key, re.value)
}
}
if (result.cookie) {
response.cookies.set(result.cookie.name, result.cookie.value, {
path: '/',
+225 -32
View File
@@ -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
}
+19 -11
View File
@@ -1,4 +1,7 @@
import type { BuildCspArgs } from './buildCsp.js'
import { isSiteNoindex } from '../seo/siteNoindex.js'
import { buildCspHeaders } from './buildCsp.js'
/**
* A single HTTP header, in the shape Next.js next.config headers() expects.
@@ -7,10 +10,8 @@ export type SecurityHeader = { key: string; value: string }
export type BuildSecurityHeadersArgs = {
/**
* Extra headers to append or override. Same-key entries replace the default,
* so you can e.g. add your project's Content-Security-Policy here — CSP is
* intentionally NOT a default because it depends on the project's own
* domains (scripts, images, fonts, analytics). Keep CSP in your project.
* Extra headers to append or override. Same-key entries replace the default
* (and the `csp` headers), so a hand-written Content-Security-Policy fits here too.
*/
additional?: SecurityHeader[]
/**
@@ -21,6 +22,13 @@ export type BuildSecurityHeadersArgs = {
* that need window.opener; false to omit.
*/
coop?: 'same-origin' | 'same-origin-allow-popups' | false
/**
* Content-Security-Policy from buildCsp args — off by default, because a CSP
* lists the project's own domains. With `reportUri` the Reporting-Endpoints
* header is added too. Roll-out: `mode: 'report-only'` first, read the
* reports, then `mode: 'enforce'` (the only change). See docs/security.md.
*/
csp?: BuildCspArgs | false
/**
* X-Frame-Options value. 'DENY' (default) blocks all framing; 'SAMEORIGIN'
* allows same-origin framing. Note: CSP frame-ancestors supersedes this in
@@ -56,19 +64,16 @@ export type BuildSecurityHeadersArgs = {
* Permissions-Policy. These are identical across projects, so the plugin owns
* the boilerplate; the client spreads the result into next.config's headers().
*
* Content-Security-Policy is deliberately excluded: a useful CSP enumerates the
* exact domains a project loads from (its CDN, analytics, embeds), so it can't
* be generic without being either too loose (useless) or too strict (breaks the
* site). Add your project's CSP via `additional`.
* Content-Security-Policy is opt-in: a useful CSP enumerates the exact domains
* a project loads from (its CDN, analytics, embeds), so the project turns on the
* buildCsp flags it needs through `csp` (or passes its own via `additional`).
*
* @example
* // next.config.ts
* import { buildSecurityHeaders } from '@intecion/ipal-kit'
* const securityHeaders = buildSecurityHeaders({
* hsts: process.env.NODE_ENV === 'production', // off in dev over http
* additional: [
* { key: 'Content-Security-Policy', value: "default-src 'self'; ..." },
* ],
* csp: { mode: 'report-only', reportUri: '/api/csp-report', analytics: true },
* })
* const nextConfig = {
* async headers() {
@@ -80,6 +85,7 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
const {
additional = [],
coop = 'same-origin',
csp = false,
frameOptions = 'DENY',
hsts = true,
hstsIncludeSubDomains = true,
@@ -123,6 +129,8 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' })
}
if (csp) {headers.push(...buildCspHeaders(csp))}
// Merge additional: same-key entries override the defaults above.
for (const extra of additional) {
const i = headers.findIndex((h) => h.key.toLowerCase() === extra.key.toLowerCase())
@@ -0,0 +1,121 @@
/** One CSP violation, normalised from either report format. */
export type CspViolation = {
blockedUri?: string
disposition?: string
documentUri?: string
effectiveDirective?: string
lineNumber?: number
originalPolicy?: string
sample?: string
sourceFile?: string
}
export type CreateCspReportRouteArgs = {
/** Largest accepted body in bytes; bigger requests get 413. Default 16 KB. */
maxBytes?: number
/**
* What to do with each violation. Default: one `console.warn` line per
* violation (Coolify keeps container logs — read them there). Plug in
* payload.logger, Sentry or a database write here.
*/
onReport?: (violation: CspViolation) => Promise<void> | void
}
type Raw = Record<string, unknown>
const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)
function fromLegacy(r: Raw): CspViolation {
// report-uri: { "csp-report": { "document-uri", "violated-directive", … } }
return {
blockedUri: str(r['blocked-uri']),
disposition: str(r['disposition']),
documentUri: str(r['document-uri']),
effectiveDirective: str(r['effective-directive']) ?? str(r['violated-directive']),
lineNumber: typeof r['line-number'] === 'number' ? r['line-number'] : undefined,
originalPolicy: str(r['original-policy']),
sample: str(r['script-sample']),
sourceFile: str(r['source-file']),
}
}
function fromReportingApi(b: Raw): CspViolation {
// report-to: [{ type: 'csp-violation', body: { documentURL, effectiveDirective, … } }]
return {
blockedUri: str(b.blockedURL),
disposition: str(b.disposition),
documentUri: str(b.documentURL),
effectiveDirective: str(b.effectiveDirective),
lineNumber: typeof b.lineNumber === 'number' ? b.lineNumber : undefined,
originalPolicy: str(b.originalPolicy),
sample: str(b.sample),
sourceFile: str(b.sourceFile),
}
}
/** Parses a report body in either format (report-uri JSON or Reporting API array). */
export function parseCspReports(body: unknown): CspViolation[] {
if (Array.isArray(body)) {
return body
.filter((r): r is Raw => !!r && typeof r === 'object' && (r as Raw).type === 'csp-violation')
.map((r) => fromReportingApi(((r.body ?? {}) as Raw)))
}
if (body && typeof body === 'object' && 'csp-report' in body) {
const inner = (body as Raw)['csp-report']
return inner && typeof inner === 'object' ? [fromLegacy(inner as Raw)] : []
}
return []
}
/**
* A small collector for CSP violation reports — the `reportUri` target while
* the policy runs in report-only mode. Accepts both formats browsers send
* (`application/csp-report` from report-uri, `application/reports+json` from
* report-to), caps the body size, always answers 204, and never stores
* anything itself: by default each violation is one `console.warn` line.
*
* // app/api/csp-report/route.ts (outside Payload's /api/[...slug] — a fixed route wins)
* import { createCspReportRoute } from '@intecion/ipal-kit'
* export const POST = createCspReportRoute()
*
* Third-party alternative: point `reportUri` at report-uri.com, Sentry
* (security endpoint) or similar, and skip this route.
*/
export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise<Response> {
const {
maxBytes = 16 * 1024,
onReport = (v: CspViolation) => {
console.warn(
`[csp] ${v.disposition ?? 'report'} ${v.effectiveDirective ?? '?'} blocked=${v.blockedUri ?? '?'} page=${v.documentUri ?? '?'}${v.sourceFile ? ` src=${v.sourceFile}:${v.lineNumber ?? ''}` : ''}`,
)
},
} = args
return async (request: Request) => {
const length = Number(request.headers.get('content-length') ?? 0)
if (length > maxBytes) {return new Response(null, { status: 413 })}
let text: string
try {
text = await request.text()
} catch {
return new Response(null, { status: 400 })
}
if (text.length > maxBytes) {return new Response(null, { status: 413 })}
let body: unknown
try {
body = JSON.parse(text)
} catch {
return new Response(null, { status: 400 })
}
for (const violation of parseCspReports(body).slice(0, 50)) {
try {
await onReport(violation)
} catch {
// a failing sink must not turn reports into errors in the browser
}
}
return new Response(null, { status: 204 })
}
}
+10
View File
@@ -0,0 +1,10 @@
/** Request header the proxy uses to hand the nonce to server components. */
export const CSP_NONCE_HEADER = 'x-nonce'
/**
* A fresh per-request nonce (base64 of a random UUID, 128 bits of randomness).
* Works in the Edge and Node runtimes (Web Crypto + btoa are globals in both).
*/
export function createCspNonce(): string {
return btoa(crypto.randomUUID())
}
+16 -3
View File
@@ -1,4 +1,17 @@
export { buildCsp } from './buildCsp.js'
export type { BuildCspArgs } from './buildCsp.js'
export {
buildAdminCsp,
buildAdminCspHeaders,
buildCsp,
buildCspHeaders,
buildReportingEndpoints,
cspHeaderKey,
DEFAULT_CSP_REPORT_GROUP,
} from './buildCsp.js'
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader, } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js'
export { withSecurityConfig } from './withSecurityConfig.js'
export type { WithSecurityConfigOptions } from './withSecurityConfig.js'
@@ -0,0 +1,55 @@
/**
* Minimal structural shape of a Next config — the plugin does not import `next`
* types into this helper; Next's real NextConfig satisfies it at the call site.
*/
type HeaderRule = { headers: { key: string; value: string }[] } & Record<string, unknown>
type NextConfigLike = {
headers?: () => HeaderRule[] | Promise<HeaderRule[]>
poweredByHeader?: boolean
}
export type WithSecurityConfigOptions = {
/**
* Remove `X-Powered-By` (Next's own "Next.js" and the "Next.js, Payload" that
* withPayload adds) — it tells scanners which software to target. Default true;
* `false` leaves the config's poweredByHeader as it is.
*/
hidePoweredBy?: boolean
}
/**
* Next config wrapper for the security settings that are not response headers
* the project adds itself. Today: hides `X-Powered-By`.
*
* Where the header comes from: Next sends `X-Powered-By: Next.js` unless
* `poweredByHeader: false`; Payload's withPayload switches Next's off and adds
* `X-Powered-By: Next.js, Payload` through headers() — also unless the config it
* wraps says `poweredByHeader: false`. This helper sets that flag AND drops the
* header from headers() rules, so it works on either side of withPayload:
*
* // next.config.ts
* import { withSecurityConfig } from '@intecion/ipal-kit'
* export default withPayload(withSecurityConfig(nextConfig))
*/
export function withSecurityConfig<T extends object>(
config: T,
options: WithSecurityConfigOptions = {},
): { poweredByHeader?: boolean } & T {
const { hidePoweredBy = true } = options
if (!hidePoweredBy) {return config}
const original = (config as NextConfigLike).headers
return {
...config,
poweredByHeader: false,
...(original
? {
headers: async () =>
(await original()).map((rule) => ({
...rule,
headers: rule.headers.filter((h) => h.key.toLowerCase() !== 'x-powered-by'),
})),
}
: {}),
}
}
+7 -3
View File
@@ -2,7 +2,10 @@ import type { ThemeConfig } from './theme.js'
import { themeScript } from './theme.js'
export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
export type ThemeScriptProps = {
/** CSP nonce (createProxy `csp` → `x-nonce` header) — needed when the policy uses nonces. */
nonce?: string
} & Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
/**
* Sets the theme on <html> BEFORE anything is painted — no flash of the light
@@ -12,6 +15,7 @@ export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaul
* const shell = await getSiteShell(locale)
* <html lang={locale} suppressHydrationWarning><body><ThemeScript {...shell.theme} />…
*/
export function ThemeScript({ allowToggle = false, defaultTheme = null }: ThemeScriptProps) {
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} />
export function ThemeScript({ allowToggle = false, defaultTheme = null, nonce }: ThemeScriptProps) {
// suppressHydrationWarning: browsers hide the nonce attribute from the DOM (nonce hiding).
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} nonce={nonce} suppressHydrationWarning />
}