# security Generic HTTP security headers (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy; `X-Robots-Tag` on staging) as a function for `next.config`, `withSecurityConfig` to hide `X-Powered-By` and to keep Payload's colour-scheme client hint headers on the admin panel only, and an opt-in Content-Security-Policy (`buildCsp`, report-only first, a separate admin policy, optional nonces and a report collector). ## Rule Headers that are IDENTICAL across projects are provided once by the plugin and are on by default. CSP (Content-Security-Policy) needs to know the domains of a specific project (where scripts, images, fonts and analytics load from), so it is OFF until the project turns on the `buildCsp` flags for what it loads — through `buildSecurityHeaders({ csp })`, or its own policy through `additional`. ## Usage — next.config.ts Wire the headers in `next.config`, NOT in the proxy — they must cover the WHOLE application (including `/admin` and static files), and the proxy skips those routes. ```ts // next.config.ts import { withPayload } from '@payloadcms/next/withPayload' import type { NextConfig } from 'next' import { buildAdminCspHeaders, buildSecurityHeaders, buildUploadSecurityHeaders, withSecurityConfig } from '@intecion/ipal-kit' const prod = process.env.NODE_ENV === 'production' const csp = { mode: 'report-only', reportUri: '/api/csp-report' } as const // later: mode 'enforce' const securityHeaders = buildSecurityHeaders({ hsts: prod, // IMPORTANT: off in dev (http) csp: { ...csp, r2Url: process.env.R2_PUBLIC_URL, analytics: true, turnstile: true }, }) const nextConfig: NextConfig = { async headers() { return [ { source: '/:path*', headers: securityHeaders }, { source: '/admin/:path*', headers: buildAdminCspHeaders({ ...csp, r2Url: process.env.R2_PUBLIC_URL }) }, ...buildUploadSecurityHeaders(), ] }, } // withSecurityConfig OUTSIDE withPayload: no X-Powered-By (Next's and Payload's), and Payload's colour-scheme // client hints (Accept-CH, Critical-CH, Vary) for the admin only, not for every page export default withSecurityConfig(withPayload(nextConfig)) ``` ## Options | Option | Default | Role | |---|---|---| | `hsts` | `true` | Strict-Transport-Security (force HTTPS) | | `hstsMaxAge` | `63072000` (2 years) | HSTS max-age in seconds | | `hstsIncludeSubDomains` | `true` | HSTS on subdomains | | `hstsPreload` | `false` | preload (only if you submit to the list) | | `frameOptions` | `'DENY'` | X-Frame-Options (anti-clickjacking); `null` = no header | | `referrerPolicy` | `'strict-origin-when-cross-origin'` | Referrer-Policy; `null` = no header | | `permissionsPolicy` | blocks camera/mic/geolocation | Permissions-Policy; your own string, or `null` = no header | | `coop` | `'same-origin'` | Cross-Origin-Opener-Policy; `'same-origin-allow-popups'`, or `false` = no header | | `csp` | `false` | `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`) | | `additional` | `[]` | extra headers; the same key overrides (also the `csp` ones) | With `IAPL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response. **A value the browser would not understand fails at start (1.17.1).** `hsts`, `hstsIncludeSubDomains` and `hstsPreload` take `true` / `false`, `hstsMaxAge` a number of seconds, `frameOptions` `'DENY'` / `'SAMEORIGIN'` / `null`, `coop` a COOP value or `false`, `referrerPolicy` / `permissionsPolicy` a header value or `null`. Before, `hsts: null` dropped HSTS and `hstsMaxAge: 'abc'` or `frameOptions: 'false'` sent a header the browser ignores. `buildCsp` the same way: `dev` and `strictDynamic` are booleans (`dev: 'false'` used to add `'unsafe-eval'` in production), `mode` is `'enforce'` / `'report-only'`, and every `extra` / `override` value is an array of sources (a string was spread into single characters — a lone `*` among them is a wildcard). ## Switches are read strictly (1.17.1) A JavaScript config is not type-checked. A plugin option whose nonsense value used to switch a protection off, widen who sees something, or switch an opt-in feature (a public endpoint) on, now stops the start with a message naming the option — like `twoFactor.requireSetup.windowHours` since 1.16.6. Real values work as before. | Option | Refused now | What it did before | |---|---|---| | `accounts` | `0`, `''`, anything not `false` / an object | `0` or `''` dropped every account rule | | `cookieScanner`, `stats`, `consentLog`, `adminMeta`, `whiteLabel`, `forms.attachments`, `cookieScanner.crawl`, `mail.relay` | a string, a number, `null` | `'false'` switched an opt-in feature on (or was ignored) | | `indexNow`, `lightbox`, `enabled`, `twoFactor.allowCollectionMismatch` | anything but `true` / `false` | `'false'` meant on — for the mismatch: panel users without 2FA | | `consentLog.retentionDays` | not a number above 0 | `null`, `0` or a negative number purged every proof of consent daily | | `adminMeta.robots.index` / `.follow` | anything but `true` / `false` | `'false'`, `0` or `null` took the noindex off the panel | | `dashboardAlerts.integrations` / `.cookies` | a name outside `'admin' / 'editor' / 'all'` (`'editor' / 'all'`) | an unknown name showed the details to every staff account | | `mail.relay.accountMail.windowMinutes`, `mail.relay.confirmRateLimit.windowMs` | not a number above 0 | a window of 0 is a limit that never fills | | `mail.relay.accountMail.perAddress` / `.perVisitor`, `confirmRateLimit.max` | not a number of at least 1 | — | | `forms.attachments.submit.maxPerMinute`, `.timeoutMs`, `.idleTimeoutMs` | not a number of at least 0 (`0` = off, as documented) | `'off'`, `null` or `{}` turned the limit off | | `storageNames` | anything but `'ipal'` / `'iapl'` | an unknown name meant `'ipal'` | | seed `guard` (`createSeeder`) | `0`, `''`; `allowFull` / `allowProdUpdate` / `production` not booleans | `guard: 0` dropped the production guard; `allowFull: 'false'` allowed a full seed | Role names are strict too: `requireRole`, `requireRoleField` and `readPublished` throw on a name outside `ROLE_HIERARCHY`, and `hasMinimumRole` / `userMeetsRole` answer `false` for one (before, every staff account met it). **Uploads:** `buildUploadSecurityHeaders({ collections = ['media'] })` returns `headers()` rules for `/api//file/*` (sandbox, no scripts) — an SVG from local disk cannot run a script on the site's domain. Wire it alongside: `[{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]`. ## TRAP — HSTS in dev HSTS over HTTP on localhost can lock the browser into HTTPS for localhost. ALWAYS turn it off in dev: `hsts: process.env.NODE_ENV === 'production'`. ## X-Powered-By — hide it (`withSecurityConfig`) A response header `X-Powered-By: Next.js, Payload` tells scanners which software (and which known advisories) to try. Audits flag it. Where it comes from: - **Next.js** sends `X-Powered-By: Next.js` unless the config says `poweredByHeader: false`. - **Payload's `withPayload`** switches Next's header off and adds its own `X-Powered-By: Next.js, Payload` for `/:path*` through `headers()` — also unless the config it wraps says `poweredByHeader: false`. Payload's REST/GraphQL handlers add nothing of their own. `withSecurityConfig(nextConfig, { hidePoweredBy = true })` sets `poweredByHeader: false` AND drops any `X-Powered-By` entry from `headers()` rules, so both orders hide the header: `withSecurityConfig(withPayload(nextConfig))` (recommended: the only order that also narrows the client hints, next section) or `withPayload(withSecurityConfig(nextConfig))` (the order of sites made before 1.17.0). Turn off: `withSecurityConfig(nextConfig, { hidePoweredBy: false })`, or do not call it. Without the helper, `poweredByHeader: false` in the config passed to `withPayload` has the same effect. Check: `curl -sI https:///pl | grep -i x-powered-by` prints nothing. Behind Coolify the proxy (Traefik or Caddy) adds no `X-Powered-By`; if the header comes back in production, look for a "Custom labels" header middleware in the Coolify app, or a Cloudflare Transform Rule. Keep the software updated as well — hiding the header does not remove the advisories (the minimum safe Next.js is listed in the agent guide, §4). ## Client hints — the admin only (`withSecurityConfig`) **The problem.** Payload's `withPayload` adds three response headers for **every** path (`/:path*`): `Accept-CH: Sec-CH-Prefers-Color-Scheme`, `Critical-CH: Sec-CH-Prefers-Color-Scheme` and `Vary: Sec-CH-Prefers-Color-Scheme`. The admin panel needs them: with the hint in the request it renders light or dark on the server, so the panel does not flash on its first paint. A public page does not read the hint, yet `Critical-CH` tells Chrome to **repeat the first document request of a visit** with the hint added — one wasted round trip on every first page view (two requests for `/pl` in the server log; about 600 ms in a mobile Lighthouse run of a client site, where it shows as a repeated navigation under "Avoid multiple page redirects"). Route handlers and static files also get `Vary: Sec-CH-Prefers-Color-Scheme`, which splits them in a shared cache. Neither `withPayload` nor the proxy has an option for it, and a proxy cannot remove a header that `next.config` set. **The fix.** `withSecurityConfig` as the **outer** wrapper moves the three headers to the panel's routes: ```ts export default withSecurityConfig(withPayload(nextConfig)) // /admin/:path* only (the default) ``` | Option | Default | Role | |---|---|---| | `adminClientHints` | `true` | `true`: the hint headers only for `/admin/:path*`. `false`: leave them on every path (the behaviour before 1.17.0) | | `adminClientHints.route` | `'/admin'` | Payload's `routes.admin` when the panel has another address: `{ route: '/its' }` | | `adminClientHints.sources` | `[]` | more Next `source` patterns that keep the headers, e.g. `['/preview/:path*']` for a page of your own that reads `Sec-CH-Prefers-Color-Scheme` on the server | - **The order matters.** Only the outer wrapper sees the rule `withPayload` adds. `withPayload(withSecurityConfig(…))` — the order of every site made before 1.17.0 — still builds and still hides `X-Powered-By`, but the hints stay on every path, as before. Swap the two names (one line); nothing else changes. `iapl-doctor` rule `client-hints` (info) reports the old order, and with `--url` a public page that still sends `Critical-CH`. - **What is moved.** Only the token `Sec-CH-Prefers-Color-Scheme` in `Accept-CH`, `Critical-CH` and `Vary` of a site-wide rule (`/:path*`, `/(.*)`). Other tokens stay (another client hint, another `Vary` name), other headers of the rule stay (CSP, HSTS, …), and a rule you wrote for a narrower source is left alone. `/admin/:path*` gets the headers exactly as `withPayload` wrote them. Next's own `Vary` for pages (`rsc, next-router-state-tree, …`) is not touched. - **The panel works as before**: on its first request Chrome learns the hint from `/admin` and repeats that one request, the panel paints in the browser's scheme with no flash; a theme chosen in the account (the `payload-theme` cookie) still wins. - **Building blocks:** `scopeColorSchemeClientHints(rules, sources?)` (the same narrowing for a `headers()` array of your own), `adminClientHintSources(route?)`, `COLOR_SCHEME_CLIENT_HINT`. Check (a production build): `curl -sI localhost:3000/pl | grep -iE 'accept-ch|critical-ch'` prints nothing; `curl -sI localhost:3000/admin/login | grep -iE 'accept-ch|critical-ch'` prints both. In Chrome, a first visit to a public page in a fresh profile shows one document request. ## Content-Security-Policy ### Why CSP is opt-in HSTS, nosniff and Referrer-Policy are IDENTICAL for every project → the plugin generates them. CSP lists the SPECIFIC domains the project loads from (its R2, analytics, Turnstile, fonts). A generic CSP would be either too loose (`*` = useless) or would break the site. So the plugin provides the hardened skeleton and one flag per integration it ships (`buildCsp`), and the project turns on what it uses. ### buildCsp — CSP generator (recommended over writing it by hand) ```ts import { buildCsp } from '@intecion/ipal-kit' const csp = buildCsp({ mode: 'report-only', // start here; 'enforce' once the reports are clean reportUri: '/api/csp-report', // where browsers send violations (createCspReportRoute) r2Url: process.env.R2_PUBLIC_URL, // R2 media → img-src, media-src turnstile: true, // Cloudflare Turnstile analytics: true, // GA4 / GTM metaPixel: true, linkedIn: true, tiktok: true, clarity: true, // the pixels the plugin loads youtube: true, // YouTubeEmbed googleMaps: true, // Google Maps // extra: { 'script-src': ['https://other-script.example'] }, // add sources to any directive // override: { 'frame-ancestors': ["'self'"], 'style-src': null }, // replace / drop a directive }) // → { key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'; …" } ``` `buildCspHeaders(args)` returns `[csp, Reporting-Endpoints]` (the second only with `reportUri`); `buildSecurityHeaders({ csp: args })` does the same inside the site-wide list. **Hard rules built in** (always on unless you `override` them): `base-uri 'self'`, `object-src 'none'`, `frame-ancestors 'none'`, `form-action 'self'`. **What each flag allows** — the plugin's own components need exactly these: | Flag | Plugin part | Sources | |---|---|---| | (always) | Next, Tailwind, next/font, `ThemeScript`, `JsonLdGraph`, consent banner, lightbox, `MediaPreconnect` | `'self'`, `'unsafe-inline'` (script, style), `data:`/`blob:` images, Google Fonts | | `r2Url` | media on R2 | the URL → `img-src`, `media-src` (a site-relative `/media` is already `'self'`) | | `analytics` | `Analytics` GA4 / GTM | `script-src *.googletagmanager.com`; `connect-src`/`img-src` `*.google-analytics.com`, `*.analytics.google.com`, `*.googletagmanager.com`, `*.g.doubleclick.net`, `www.google.com` | | `metaPixel` | `loadMetaPixel`, fbevents via `ConsentScript` | `connect.facebook.net` (script, connect), `www.facebook.com` (connect, img, frame) | | `linkedIn` | `loadLinkedIn` | `snap.licdn.com` (script); `px.ads.linkedin.com`, `px4.ads.linkedin.com`, `www.linkedin.com` (connect, img) | | `tiktok` | `loadTikTok` | `analytics.tiktok.com` (script, connect, img) | | `clarity` | `loadClarity` | `*.clarity.ms` (script, connect, img), `c.bing.com` (img) | | `turnstile` | `Turnstile` | `challenges.cloudflare.com` (script, frame, connect) | | `youtube` | `YouTubeEmbed` | `www.youtube.com`, `www.youtube-nocookie.com` (frame), `i.ytimg.com` (img) | | `googleMaps` | Maps iframe / Maps JS | `*.googleapis.com`, `*.gstatic.com`, `*.google.com`, `*.ggpht.com`, `*.googleusercontent.com`, `blob:` workers | | `dev` | `next dev` | `'unsafe-eval'` (React dev tooling). Default `process.env.NODE_ENV === 'development'` | Plausible or another script through `ConsentScript` → add its host with `extra`. GTM tags you add in the GTM panel (Hotjar, Ads…) load their own hosts → add them with `extra` as the reports show them. **Why `'unsafe-inline'` stays without a nonce.** Next streams the page's RSC payload in inline `