# 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 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: no X-Powered-By (Next's and Payload's) export default withPayload(withSecurityConfig(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), or on a development host — the site's address (`serverUrl`, default `NEXT_PUBLIC_SERVER_URL`) matches `developmentHosts` (default `['*.dev.netscale.pl']`, Intecion's development domain) — `X-Robots-Tag: noindex, nofollow` is added to every response. `next.config` runs before the plugin, so a project that changed `iapl({ developmentHosts })` passes the same list: `buildSecurityHeaders({ developmentHosts: [...] })`; `developmentHosts: false` or `IAPL_NOINDEX=0` leaves the header out. **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 work: `withPayload(withSecurityConfig(nextConfig))` (recommended) or `withSecurityConfig(withPayload(nextConfig))`. 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). ## 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 `