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
+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'),
})),
}
: {}),
}
}