- 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]>
170 lines
6.5 KiB
TypeScript
170 lines
6.5 KiB
TypeScript
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.
|
|
*/
|
|
export type SecurityHeader = { key: string; value: string }
|
|
|
|
export type BuildSecurityHeadersArgs = {
|
|
/**
|
|
* 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[]
|
|
/**
|
|
* Cross-Origin-Opener-Policy. Default 'same-origin' — isolates the browsing
|
|
* context so a malicious page can't hold a window.opener reference (protects
|
|
* against XS-Leaks / Spectre-class attacks). Project-independent, so it's a
|
|
* default. Use 'same-origin-allow-popups' if you open OAuth/payment popups
|
|
* 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
|
|
* modern browsers, but X-Frame-Options is kept for older ones. Set to null
|
|
* to omit (e.g. if you set frame-ancestors in your project CSP).
|
|
*/
|
|
frameOptions?: 'DENY' | 'SAMEORIGIN' | null
|
|
/**
|
|
* Enable HSTS (Strict-Transport-Security). Only takes effect over HTTPS, and
|
|
* tells browsers to force HTTPS for `maxAge` seconds. Default true. Turn OFF
|
|
* in local/dev over plain HTTP, or you may lock the browser to https on
|
|
* localhost. Set the env guard in your next.config (see docs).
|
|
*/
|
|
hsts?: boolean
|
|
/** Add includeSubDomains to HSTS. Default true. */
|
|
hstsIncludeSubDomains?: boolean
|
|
/** HSTS max-age in seconds. Default 63072000 (2 years), the common baseline. */
|
|
hstsMaxAge?: number
|
|
/** Add preload to HSTS (only if you'll submit to the preload list). Default false. */
|
|
hstsPreload?: boolean
|
|
/**
|
|
* Permissions-Policy. Default disables camera, microphone, geolocation. Pass
|
|
* your own string to override, or null to omit.
|
|
*/
|
|
permissionsPolicy?: null | string
|
|
/** Referrer-Policy. Default 'strict-origin-when-cross-origin' (browser default, explicit). */
|
|
referrerPolicy?: null | string
|
|
}
|
|
|
|
/**
|
|
* Builds the generic, project-independent security headers every site should
|
|
* send: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy,
|
|
* 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 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
|
|
* csp: { mode: 'report-only', reportUri: '/api/csp-report', analytics: true },
|
|
* })
|
|
* const nextConfig = {
|
|
* async headers() {
|
|
* return [{ source: '/:path*', headers: securityHeaders }]
|
|
* },
|
|
* }
|
|
*/
|
|
export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): SecurityHeader[] {
|
|
const {
|
|
additional = [],
|
|
coop = 'same-origin',
|
|
csp = false,
|
|
frameOptions = 'DENY',
|
|
hsts = true,
|
|
hstsIncludeSubDomains = true,
|
|
hstsMaxAge = 63072000,
|
|
hstsPreload = false,
|
|
permissionsPolicy = 'camera=(), microphone=(), geolocation=()',
|
|
referrerPolicy = 'strict-origin-when-cross-origin',
|
|
} = args
|
|
|
|
const headers: SecurityHeader[] = []
|
|
|
|
if (hsts) {
|
|
const parts = [`max-age=${hstsMaxAge}`]
|
|
if (hstsIncludeSubDomains) {parts.push('includeSubDomains')}
|
|
if (hstsPreload) {parts.push('preload')}
|
|
headers.push({ key: 'Strict-Transport-Security', value: parts.join('; ') })
|
|
}
|
|
|
|
if (frameOptions) {
|
|
headers.push({ key: 'X-Frame-Options', value: frameOptions })
|
|
}
|
|
|
|
// Prevents MIME-type sniffing — always safe, no project specifics.
|
|
headers.push({ key: 'X-Content-Type-Options', value: 'nosniff' })
|
|
|
|
if (referrerPolicy) {
|
|
headers.push({ key: 'Referrer-Policy', value: referrerPolicy })
|
|
}
|
|
|
|
if (permissionsPolicy) {
|
|
headers.push({ key: 'Permissions-Policy', value: permissionsPolicy })
|
|
}
|
|
|
|
// COOP — isolates the browsing context (XS-Leaks / Spectre protection).
|
|
if (coop) {
|
|
headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop })
|
|
}
|
|
|
|
// Staging / preview (IPAL_NOINDEX=1): keep every response out of search engines.
|
|
if (isSiteNoindex()) {
|
|
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())
|
|
if (i >= 0) {headers[i] = extra}
|
|
else {headers.push(extra)}
|
|
}
|
|
|
|
return headers
|
|
}
|
|
|
|
/**
|
|
* Headers for files served from the upload routes. Media accept `image/*`,
|
|
* which includes SVG — and an SVG opened directly from the site's own origin
|
|
* can run script (stored XSS from any account that can upload). This CSP lets
|
|
* the file display but never execute: no scripts, no plugins, sandboxed.
|
|
* Media on R2 come from another domain and are already isolated; local-disk
|
|
* media (dev, or sites without R2) need this.
|
|
*
|
|
* // next.config.ts — next to the site-wide headers
|
|
* async headers() {
|
|
* return [
|
|
* { source: '/:path*', headers: securityHeaders },
|
|
* ...buildUploadSecurityHeaders(), // default: /api/media/file/*
|
|
* ]
|
|
* }
|
|
*/
|
|
export function buildUploadSecurityHeaders({ collections = ['media'] }: { collections?: string[] } = {}): {
|
|
headers: SecurityHeader[]
|
|
source: string
|
|
}[] {
|
|
const headers: SecurityHeader[] = [
|
|
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
|
|
{ key: 'X-Content-Type-Options', value: 'nosniff' },
|
|
]
|
|
return collections.map((slug) => ({ headers, source: `/api/${slug}/file/:path*` }))
|
|
}
|