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
+16 -5
View File
@@ -109,7 +109,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2.
| 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<SiteProviders>` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → the editor accepts; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookie banner → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
@@ -146,7 +146,7 @@ In the project's `AGENTS.md`, under "Project decisions", one line with the item
ipal-audit-skip: mcp, llms-full — the client does not want to share content with AI agents (email 2026-03-02)
```
Keys: `llms`, `llms-full`, `markdown`, `mcp`, `jsonld`, `r2`, `turnstile`,
`analytics`, `twofactor`, `aibots`, `forms-seed` (`audit.sh` understands only these). Without this line a missing item is an error.
`analytics`, `twofactor`, `aibots`, `forms-seed`, `csp` (`audit.sh` understands only these). Without this line a missing item is an error.
---
@@ -937,7 +937,8 @@ project → **plugin gap**, not a copy.
| Image / video in `<Media>` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md |
| Enlarge an image (card, gallery, product, rich text) | `<SiteProviders lightbox>` + `<LightboxTrigger group image={lightboxImage(media, { size })}>` (`/client`), `RenderRichText lightbox`, `useLightbox`; labels: `ipalKit({ lightbox: true })` → Form messages → Image viewer | lightbox.md |
| YouTube without cookies before a click | `<YouTubeEmbed>` (`/client`) | storage.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders`, `buildCsp`, `buildUploadSecurityHeaders` | storage.md, security.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders` (`csp`), `buildCsp`, `buildCspHeaders`, `buildAdminCsp` / `buildAdminCspHeaders`, `buildUploadSecurityHeaders`, `withSecurityConfig` (hides `X-Powered-By`) | storage.md, security.md |
| CSP reports, nonces | `createCspReportRoute` (`parseCspReports`, type `CspViolation`), `createProxy({ csp })` + `<SiteProviders nonce>` (dynamic pages only), `createCspNonce`, `CSP_NONCE_HEADER`, `buildReportingEndpoints`, `cspHeaderKey`, `DEFAULT_CSP_REPORT_GROUP`; types `BuildAdminCspArgs`, `CspDirective`, `CspSources`, `CreateCspReportRouteArgs`, `WithSecurityConfigOptions` | security.md |
| Fluid typography and spacing | `fluid.css` / `fluid-wide.css` (`--ipal-*` variables) | PROGRAMISTA §2.5 |
**Consent, analytics, operations**
@@ -962,8 +963,16 @@ table from the panel (`<CookieTable>` and the `settings="detailed"` window, scan
requires it (accessibility.md).
**Security:** 2FA enforced (`ipalKit({ twoFactor: { issuer, plugin:
payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: first
`report-only`, then `enforce`; no Trusted Types (they break Turnstile/GA).
payloadTotp } })`, never `twoFactor: false` without a client decision). No `X-Powered-By`:
`withPayload(withSecurityConfig(nextConfig))`. CSP in three steps (security.md → "ROLL OUT CSP"):
(1) `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', <flags for what the
site loads> } })`, the admin rule `{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode:
'report-only', reportUri }) }` AFTER the site-wide one, and `export const POST = createCspReportRoute()` in
`src/app/api/csp-report/route.ts`; (2) deploy, read the console and the `[csp]` lines in the Coolify logs,
add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both places. Check:
`curl -sI $U/pl | grep -iE 'content-security|x-powered-by'`. ISR/SSG sites keep the header policy (with
`'unsafe-inline'` — Next's inline RSC scripts cannot be hashed); nonces (`createProxy({ csp })` +
`<SiteProviders nonce>`) only on sites whose pages already render per request. No Trusted Types (they break Turnstile/GA).
### 7.1 Newer defaults — turn off / override (the plugin helps, never limits)
@@ -983,6 +992,8 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
| Consent Mode `advanced` | `consentMode: 'basic'` | your own `<Analytics>` props (`SiteProviders analytics={false}`) |
| Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` |
| No `X-Powered-By` (with `withSecurityConfig`) | `withSecurityConfig(config, { hidePoweredBy: false })` | — |
| CSP off until `buildSecurityHeaders({ csp })`; then hard rules, `'unsafe-eval'` only in dev | leave out `csp` | `buildCsp({ extra, override, strictDynamic, dev })`, `buildAdminCsp({ extra, override })`, `createCspReportRoute({ onReport, maxBytes })`, your own string via `additional` |
| Construction mode hides pages in Markdown, MCP | `markdown: { isPathVisible: () => true }`, `mcp: { isPathVisible: () => true }` | `isPathVisible`, `isPathVisibleIn(mode, path)`, `pathOf(url)`, type `PathVisibility` |
| Construction mode filters the sitemap and llms.txt | `underConstructionSeo: false` | `include` / `getIncludedPaths` in the low-level builders |
| `getSettings` at `depth: 1` | — | `createContentHelpers({ settingsDepth: 2 })` (every request pays) |
+10 -1
View File
@@ -1,6 +1,6 @@
---
name: ipal-audit
description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env, security headers, X-Powered-By, CSP), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
---
# ipal-audit
@@ -38,5 +38,14 @@ in AGENT.md §0b). Never add that line yourself just to make the audit pass.
google-analytics / googletagmanager (except Consent Mode), facebook.net,
clarity.ms, licdn, tiktok.
- **Content**: fallbacks contain no client data (`|| 'Firma X'`).
- **Response headers** (on a running build — `pnpm build && pnpm start`, or the deployed domain):
```bash
U=http://localhost:3000
for p in /pl /admin /api/health; do echo "== $p"; curl -sI "$U$p" | grep -iE 'x-powered-by|content-security-policy'; done
```
`x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). No
`content-security-policy` / `content-security-policy-report-only` on `/pl` and `/admin` → WARNING (CSP not
rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`).
Then open `/pl` and `/admin` in the browser: CSP lines in the console = missing sources (flags / `extra`).
Do not say "done" until the full audit (without `--quick`) has no errors.
@@ -261,6 +261,8 @@ if [ -n "$APP" ]; then
need ERROR '' "health route" "src/app/api/health/route.ts → export { healthRoute as GET } from '@/lib/content'" 'healthRoute|createHealthRoute' src/app
need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts
need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js
need WARNING '' "X-Powered-By hidden" "next.config.ts → export default withPayload(withSecurityConfig(nextConfig)) — Next and withPayload send X-Powered-By: Next.js, Payload (security.md)" 'withSecurityConfig|poweredByHeader: *false' next.config.ts next.config.mjs next.config.js
need WARNING csp "Content-Security-Policy" "next.config.ts → buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } }) + buildAdminCspHeaders on /admin/:path*, then 'enforce' (security.md → ROLL OUT CSP)" "csp: *\\{|csp,|buildCsp|Content-Security-Policy" next.config.ts next.config.mjs next.config.js src/proxy.ts proxy.ts
# Consent, analytics, Turnstile (layout)
need ERROR '' "cookie consent" "<SiteProviders> (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app
need ERROR analytics "analytics" "<SiteProviders> (loads Analytics) or <Analytics> inside ConsentProvider" 'SiteProviders|<Analytics' src/app
+2 -2
View File
@@ -139,8 +139,8 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| proxy | `src/proxy.ts` | `export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })` + `export const config = { matcher: ['/((?!api\|admin\|_next\|.*\\..*).*)'] }` (a literal!) | `curl -sI $U/` → `/pl`; `curl -s -H 'Accept: text/markdown' $U/pl` → Markdown | i18n.md, PROGRAMISTA §2.6 |
| proxy (Next 15 / custom) | `middleware`/`proxy.ts` | `createLocaleMiddleware({ config, … })` (`/next/middleware` or the main entry) | as above | i18n.md |
| env validation | `src/instrumentation.ts` | `if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` from `@intecion/ipal-kit/env` | remove a variable → startup fails with the list of missing ones | env.md |
| Next config | `next.config.ts` | `withPayload({ images: buildImagesConfig(), htmlLimitedBots: /Googlebot\|Bingbot…/i, headers: async () => [{ source: '/:path*', headers: buildSecurityHeaders({ hsts }) }, ...buildUploadSecurityHeaders()] })` | `curl -sI $U/pl \| grep -i 'x-content-type\|strict-transport'` | security.md, storage.md, PROGRAMISTA §2.9 |
| CSP | `next.config.ts` | `buildCsp({ mode: 'report-only', … })` → later `enforce` | browser console without violations | security.md |
| Next config | `next.config.ts` | `withPayload(withSecurityConfig({ images: buildImagesConfig(), htmlLimitedBots: /Googlebot\|Bingbot…/i, headers: async () => [{ source: '/:path*', headers: buildSecurityHeaders({ hsts, csp }) }, { source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, ...buildUploadSecurityHeaders()] }))` | `curl -sI $U/pl \| grep -iE 'x-content-type\|strict-transport\|x-powered-by'` (no `x-powered-by`) | security.md, storage.md, PROGRAMISTA §2.9 |
| CSP | `next.config.ts`, `src/app/api/csp-report/route.ts` | `csp = { mode: 'report-only', reportUri: '/api/csp-report', r2Url, <flags> }` in `buildSecurityHeaders` + `buildAdminCspHeaders`; route `export const POST = createCspReportRoute()`; after clean reports `mode: 'enforce'` | `curl -sI $U/pl \| grep -i content-security-policy-report-only`; browser console and `[csp]` log lines without violations | security.md |
| data / routes | `src/lib/content.ts` | `export const { … } = createContentHelpers({ config, content, i18n: i18nConfig, baseUrl, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName } })` | `pnpm tsc --noEmit` | frontend.md, PROGRAMISTA §2.7 |
| layout | `app/(frontend)/[locale]/layout.tsx` | `const shell = await getSiteShell(locale)`; `<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />} theme stats>` | HTML: `<script type="application/ld+json">` (WebSite+Organization), cookie banner | frontend.md, consent.md |
| theme | layout | `<SiteProviders theme>` (or `<ThemeScript {...shell.theme} />` from `/rsc`), `<html suppressHydrationWarning>`; switcher `<ThemeSwitcher>` (`/client`) | `data-theme` on `<html>` before hydration | theme.md |
@@ -240,7 +240,7 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | ready `[[...slug]]` catch-all page → `{ Page, generateMetadata, generateStaticParams }` (blocks, slug history redirects, JSON-LD, under-construction mode); does not paginate `?page=` |
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended) |
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | 404 content in one language — called from a server action for the lazy `createNotFoundPage({ load })` (pages.md) |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); does not mount `AlternateLinksProvider` |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); `nonce` (from `x-nonce`) goes on the theme script and the GA4/GTM tag; does not mount `AlternateLinksProvider` |
Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders` and the returned `@/lib/content` keys: `node_modules/@intecion/ipal-kit/docs/frontend.md`.
@@ -279,7 +279,7 @@ Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders
| `negotiateLocale({ config, cookieLocale, acceptLanguage })` | `@intecion/ipal-kit` | language choice: cookie → Accept-Language → default |
| `matchAcceptLanguage(header, config)` | `@intecion/ipal-kit` | matches the `Accept-Language` header to the configured languages |
| `LOCALE_COOKIE_NAME` | `@intecion/ipal-kit` | constant `'NEXT_LOCALE'` — cookie with the chosen language (functional, saved only with consent) |
| `createProxy(i18nConfig, { NextResponse, markdown?, exposeHeaders?, consentCategory?, cookieName?, policyVersion? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | recommended `proxy.ts`: language negotiation, redirect `/` → `/{locale}`, cookie with consent, `x-locale`/`x-pathname` headers, optional Markdown routes |
| `createProxy(i18nConfig, { NextResponse, markdown?, exposeHeaders?, consentCategory?, cookieName?, policyVersion?, csp? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | recommended `proxy.ts`: language negotiation, redirect `/` → `/{locale}`, cookie with consent, `x-locale`/`x-pathname` headers, optional Markdown routes; `csp` (buildCsp args) = a nonce CSP per request + `x-nonce` for `<SiteProviders nonce>` (dynamic pages only, security.md) |
| `createLocaleMiddleware({ config, cookieName?, policyVersion? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | lower level: a `req → LocaleMiddlewareResult` function for your own proxy. The locale cookie is saved only with `functional` consent (`consentCategory: 'necessary'` = always), read under the version the consent was stored with; `policyVersion` pins one version |
| `DEFAULT_PROXY_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | alias of `DEFAULT_MIDDLEWARE_MATCHER` for `createProxy`; paste the value into `config.matcher` as a literal |
| `DEFAULT_MIDDLEWARE_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | array `['/((?!api\|admin\|_next\|.*\\..*).*)']` (excludes `api`, `admin`, `_next`, files); paste into `config.matcher` as a literal — Next reads the matcher statically |
@@ -508,11 +508,18 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `buildSecurityHeaders({ hsts?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. Add CSP via `additional`. |
| `buildCsp({ mode?, r2Url?, turnstile?, analytics?, googleMaps?, youtube?, extra? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src` etc.) + sources for the enabled integrations; put it into `additional`. Start with `mode: 'report-only'`. |
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
| `buildAdminCsp(args)` / `buildAdminCspHeaders(args)` | `@intecion/ipal-kit` | Looser policy for Payload's admin: Monaco from `cdn.jsdelivr.net`, `blob:` workers, `https:` images, Live Preview `frame-src 'self'`, `frame-ancestors 'self'`. Rule `{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode, reportUri }) }` AFTER the site-wide rule. |
| `createCspReportRoute({ onReport?, maxBytes? })` | `@intecion/ipal-kit` | `POST` handler for `reportUri` (`src/app/api/csp-report/route.ts`): both report formats, body cap 16 KB, always `204`; default sink = one `[csp] …` `console.warn` line per violation (Coolify logs). |
| `parseCspReports(body)` | `@intecion/ipal-kit` | Normalises a report body (`csp-report` object or Reporting API array) to `CspViolation[]` — for your own collector. |
| `buildReportingEndpoints(url, group?)`, `cspHeaderKey(mode?)`, `DEFAULT_CSP_REPORT_GROUP` | `@intecion/ipal-kit` | Building blocks: the `Reporting-Endpoints` header, the header name for a mode, the default `report-to` group (`'csp-endpoint'`). |
| `createCspNonce()`, `CSP_NONCE_HEADER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | A per-request nonce and the request header (`x-nonce`) `createProxy({ csp })` passes it in — for your own proxy. Nonces make pages dynamic (no ISR). |
| `buildUploadSecurityHeaders({ collections? })` | `@intecion/ipal-kit` | `headers()` entries for `/api/<upload>/file/*` (`media` by default): files from disk are displayed, never executed (sandbox). Needed for media without R2. |
**Types:** `BuildCspArgs`, `BuildSecurityHeadersArgs` — builder options; `SecurityHeader` — `{ key, value }` in the Next.js shape.
**Types:** `BuildCspArgs`, `BuildAdminCspArgs`, `BuildSecurityHeadersArgs`, `WithSecurityConfigOptions`, `CreateCspReportRouteArgs` — builder options; `CspDirective`, `CspSources` — directive names / sources per directive; `CspViolation` — one normalised report; `SecurityHeader` — `{ key, value }` in the Next.js shape.
## SEO (`seo`) — details: `node_modules/@intecion/ipal-kit/docs/seo.md`
+25 -8
View File
@@ -326,23 +326,36 @@ and `rel="alternate" type="text/markdown"`; `/pl/nie-ma-takiej` → 404 with con
| `src/app/robots.ts` | `export { getRobots as default } from '@/lib/content'` + `force-dynamic` (AI crawler policy from Site settings → Search engines; `robots` = code only) |
| `src/app/manifest.ts` | `export { manifest as default } from '@/lib/content'` + `force-dynamic` |
| `src/app/api/health/route.ts` | `export { healthRoute as GET } from '@/lib/content'` + `force-dynamic` |
| `src/app/api/csp-report/route.ts` | `import { createCspReportRoute } from '@intecion/ipal-kit'` + `export const POST = createCspReportRoute()` (CSP violation reports → `[csp]` lines in the logs) |
```ts
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import { buildCsp, buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders } from '@intecion/ipal-kit'
import {
buildAdminCspHeaders, buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders, withSecurityConfig,
} from '@intecion/ipal-kit'
const csp = buildCsp({ mode: 'report-only', r2Url: process.env.R2_PUBLIC_URL, turnstile: true, analytics: true })
const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production', additional: [csp] })
// CSP step 1: report-only. After the reports are clean (security.md → "ROLL OUT CSP"): mode 'enforce'.
const csp = { mode: 'report-only', reportUri: '/api/csp-report', r2Url: process.env.R2_PUBLIC_URL } as const
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
// flags for what the site loads: analytics, metaPixel, linkedIn, tiktok, clarity, turnstile, youtube, googleMaps
csp: { ...csp, turnstile: true, analytics: true },
})
export default withPayload({
// withSecurityConfig: no X-Powered-By (Next's and Payload's)
export default withPayload(withSecurityConfig({
images: { ...buildImagesConfig() },
htmlLimitedBots:
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
async headers() {
return [{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]
return [
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, // after the site-wide rule
...buildUploadSecurityHeaders(),
]
},
})
}))
```
```ts
// src/instrumentation.ts — import from /env (the root pulls in Payload → Edge/Turbopack crash)
@@ -362,13 +375,17 @@ export function register() {
the "XML Sitemap" style; `curl -s localhost:3000/robots.txt` → `Sitemap:`, `Disallow: /admin`, AI bots (GPTBot,
ClaudeBot…) with `Allow` (a policy picked in Site settings → Search engines → AI assistants shows up after a reload);
`curl -sI localhost:3000/sitemap.xml | grep -i cache-control` → `s-maxage=3600`; `/manifest.webmanifest` → JSON with the name from Site settings; `/api/health` → `200`
(`503` without a database); `curl -sI localhost:3000/pl | grep -i 'x-frame-options\|content-security-policy-report-only'`;
(`503` without a database); `curl -sI localhost:3000/pl | grep -iE 'x-frame-options|content-security-policy-report-only|reporting-endpoints|x-powered-by'`
→ the first three, NO `x-powered-by`; `/pl` and `/admin` in the browser → no `[Report Only]` CSP lines in the console
(each one → a flag or `extra`, see security.md); `curl -si -X POST localhost:3000/api/csp-report -H 'content-type: application/csp-report' -d '{"csp-report":{}}' | head -1` → `204`;
an empty `PAYLOAD_SECRET` in `.env` → `pnpm dev` exits with a list of missing variables (restore it).
**Turn off / override.** `robots`: `aiBots: 'block-training' | 'disallow' | false` (only on a client decision →
`ipal-audit-skip: aibots`), `adminRoute: false` (hidden panel), `extraDisallow`; `sitemapStyle: false` (raw XML)
or your own text; `buildSecurityHeaders({ frameOptions, coop, hsts, additional })` — an `additional` entry with the same key
overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `extra`), after a clean console `mode: 'enforce'`;
overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `metaPixel`, `linkedIn`, …), `extra`, `override`, no `csp`
= no policy; after clean reports `mode: 'enforce'` (site and admin); nonces only for pages that already render per request
(`createProxy({ csp })` + `<SiteProviders nonce>`); `withSecurityConfig(config, { hidePoweredBy: false })` keeps `X-Powered-By`;
`buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules
(`ipalEnvRules(…).filter(…)`). Staging: `IPAL_NOINDEX=1` (also stops IndexNow). Search engines: `robots` instead of
`getRobots` ignores the panel; `ipalKit({ searchSettings: false })` removes the tab; per-bot exceptions in code:
+16
View File
@@ -112,6 +112,22 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
Nothing else to change: the statistics tab title, the cookie scanner's integration names and the maintenance
notice's close button follow the language by themselves.
**→ the release after 1.14.0 (X-Powered-By, CSP; security.md):**
1. **Hide `X-Powered-By`** — `next.config.ts`: `export default withPayload(withSecurityConfig(nextConfig))`
(import `withSecurityConfig` from `@intecion/ipal-kit`); remove a hand-written `poweredByHeader: false` or a header
override if the project had one. **Check:** `curl -sI localhost:3000/pl | grep -i x-powered-by` → nothing (also on
`/admin` and `/api/health`).
2. **CSP, report-only first** — no CSP yet, or a hand-written one → `buildSecurityHeaders({ csp: { mode: 'report-only',
reportUri: '/api/csp-report', r2Url: process.env.R2_PUBLIC_URL, <flags for what the site loads> } })`, the admin rule
`{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' }) }`
after the site-wide one, and `src/app/api/csp-report/route.ts` = `export const POST = createCspReportRoute()`.
Flags: what the panel's Site integrations and the code load (analytics, metaPixel, linkedIn, tiktok, clarity,
turnstile, youtube, googleMaps); anything else → `extra`. **Check:** `curl -sI localhost:3000/pl | grep -iE
'content-security-policy-report-only|reporting-endpoints'`; the main pages and `/admin` in a browser, accept the
cookie banner → no `[Report Only]` lines in the console. Deploy.
3. **Enforce later** — after a few days of clean `[csp]` lines in the Coolify logs: `mode: 'enforce'` in both places,
redeploy, check the pages again. Record the date in `AGENTS.md` → "Project decisions".
## 2. Inventory (no code changes)
For **every** item in the PROGRAMISTA §6 table show evidence (grep / file) of whether
it applies to the project. Run the **ipal-audit** skill (`--quick`) and attach the result.
+190 -105
View File
@@ -2,15 +2,16 @@
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`. CSP is DELIBERATELY
left out — it depends on the project's domains, so it stays in the project.
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. CSP
(Content-Security-Policy) needs to know the domains of a specific project (where
scripts, images, fonts and analytics load from), so it cannot be generic —
it stays in the project and is added through `additional`.
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
@@ -21,23 +22,28 @@ application (including `/admin` and static files), and the proxy skips those rou
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import type { NextConfig } from 'next'
import { buildSecurityHeaders } from '@intecion/ipal-kit'
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: process.env.NODE_ENV === 'production', // IMPORTANT: off in dev (http)
additional: [
// the project's CSP — it knows its own domains:
// { key: 'Content-Security-Policy', value: "default-src 'self'; ..." },
],
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 }]
return [
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders({ ...csp, r2Url: process.env.R2_PUBLIC_URL }) },
...buildUploadSecurityHeaders(),
]
},
}
export default withPayload(nextConfig)
// withSecurityConfig: no X-Powered-By (Next's and Payload's)
export default withPayload(withSecurityConfig(nextConfig))
```
## Options
@@ -52,7 +58,8 @@ export default withPayload(nextConfig)
| `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 |
| `additional` | `[]` | extra headers (e.g. CSP); the same key overrides |
| `csp` | `false` | `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`) |
| `additional` | `[]` | extra headers; the same key overrides (also the `csp` ones) |
With `IPAL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response.
@@ -65,133 +72,204 @@ domain. Wire it alongside: `[{ source: '/:path*', headers: securityHeaders }, ..
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'`.
## Overriding and CSP
## X-Powered-By — hide it (`withSecurityConfig`)
`additional` with the same key OVERRIDES the default (e.g. change X-Frame-Options
to SAMEORIGIN). A new key (like CSP) is added. CSP always goes through `additional` —
the plugin does not generate it, because it depends on the project.
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:
### Why CSP stays in the project (not the plugin)
- **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://<DOMAIN>/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 mechanism (`additional`),
and the project supplies a CSP that fits it.
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)
Instead of writing a raw CSP in every project (risk of forgetting base-uri,
object-src), use `buildCsp` — it has hard OWASP/Lighthouse rules built in, and you
turn on only the flags for what the project loads:
```ts
// next.config.ts
import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit'
import { buildCsp } from '@intecion/ipal-kit'
const csp = buildCsp({
mode: 'report-only', // start here; 'enforce' once the console is clean
r2Url: process.env.R2_PUBLIC_URL, // R2 media → img-src
turnstile: true, // challenges.cloudflare.com → script/frame/connect
analytics: true, // GTM + GA
youtube: true, // youtube → frame-src
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'] }, // extra sources
})
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
additional: [csp],
// 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'; …" }
```
**Hard rules built in** (always on, impossible to forget): `base-uri 'self'`,
`object-src 'none'`, `frame-ancestors 'none'`. These are the ones Lighthouse/OWASP
require and that are easy to miss when writing CSP by hand.
`buildCspHeaders(args)` returns `[csp, Reporting-Endpoints]` (the second only with `reportUri`);
`buildSecurityHeaders({ csp: args })` does the same inside the site-wide list.
Base sources: `default-src 'self'`, `form-action 'self'`, `script-src 'self' 'unsafe-inline'`
(Next / analytics), `style-src 'self' 'unsafe-inline' https://fonts.googleapis.com`. `r2Url` goes into
`img-src` only as an absolute address (`https://…`); `youtube` also adds `i.ytimg.com` (the
`YouTubeEmbed` poster); `googleMaps` adds `*.googleapis.com`, `*.gstatic.com`, `*.google.com`, `*.ggpht.com`,
`*.googleusercontent.com` (iframe and Maps JS).
**Hard rules built in** (always on unless you `override` them): `base-uri 'self'`,
`object-src 'none'`, `frame-ancestors 'none'`, `form-action 'self'`.
`buildCsp` does NOT add `'unsafe-eval'` (it weakens CSP) — add it through `extra` only
if a library requires it. `mode` defaults to `'enforce'` (`Content-Security-Policy`);
`'report-only'` gives `…-Report-Only` — start with it when rolling out.
**What each flag allows** — the plugin's own components need exactly these:
CSP is still "in the project" (you pick the flags for what you load), but the skeleton
comes from the plugin — every project has the same hardened foundation.
| 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'` |
### Building CSP by hand (if you need full control)
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.
Read the media domain from `R2_PUBLIC_URL` (env), do not hard-code it. Match the other
sources to what the project actually loads:
**Why `'unsafe-inline'` stays without a nonce.** Next streams the page's RSC payload in inline
`<script>` tags (`self.__next_f.push(…)`) that differ per page and per render — a static header cannot
list their hashes, and static/ISR HTML cannot carry a per-request nonce. So a header-only CSP keeps
`'unsafe-inline'` in `script-src`; it still blocks every script from a host you did not list, `<object>`,
`<base>` hijacking, framing and form posts to other sites. `style-src 'unsafe-inline'` stays in every mode:
React, Next and the plugin set inline `style` attributes, which a nonce cannot cover. `buildCsp` never adds
`'unsafe-eval'` in production.
### Nonces (stricter; dynamic pages only)
Next adds a per-request nonce to its own scripts when the request carries a CSP header with
`'nonce-…'` (enforcing or report-only). `createProxy(i18nConfig, { NextResponse, csp: { … } })` does it:
a fresh nonce per request, the policy on the request (for Next) and the response, and the nonce as the
`x-nonce` request header. The policy then gets `'nonce-…' 'strict-dynamic'`: scripts the nonced Next
bootstrap loads (the plugin's analytics, pixels, Turnstile) are trusted, and CSP3 browsers ignore the
host list and `'unsafe-inline'` (both stay as a fallback for old browsers). `strictDynamic: false`
keeps host-based checks.
```ts
// next.config.ts
const r2Url = process.env.R2_PUBLIC_URL || ''
const csp = [
"default-src 'self'",
// scripts: self + Turnstile (Cloudflare) + analytics (GTM/GA if you use them)
"script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://*.googletagmanager.com",
// styles: self + inline (Tailwind) + Google Fonts
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
// images: self + R2 media (from env!) + data:
`img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com ${r2Url}`.trim(),
"font-src 'self' https://fonts.gstatic.com data:",
// GA4: wildcards are required — EU traffic goes to region1.google-analytics.com
"connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com",
// frames: Turnstile (captcha widget)
"frame-src https://challenges.cloudflare.com",
"form-action 'self'",
"frame-ancestors 'none'", // replaces X-Frame-Options in modern browsers
].join('; ')
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
additional: [{ key: 'Content-Security-Policy', value: csp }],
// proxy.ts
export const proxy = createProxy(i18nConfig, {
NextResponse, markdown: true,
csp: { mode: 'report-only', reportUri: '/api/csp-report', analytics: true, r2Url: process.env.R2_PUBLIC_URL },
})
// app/(frontend)/[locale]/layout.tsx
import { headers } from 'next/headers'
const nonce = (await headers()).get('x-nonce') // CSP_NONCE_HEADER
<SiteProviders shell={shell} theme nonce={nonce}>… // ThemeScript + GA4/GTM tag get the nonce
```
Match the sources to the project: Google Maps (`https://maps.googleapis.com`,
`https://*.google.com`), other embeds, other analytics. Anything you do not list
will be blocked.
Costs and rules:
- Reading `headers()` makes every page under the proxy matcher **dynamic** — no ISR, no static HTML, a
render per request. That is why nonces are opt-in; ISR sites keep the header-only policy.
- The proxy matcher skips `/api`, `/admin`, `/_next` and files — those keep the `next.config` headers. Do
NOT also send the site CSP from `next.config` for the frontend paths (two policies = both apply); keep
only the admin rule and `buildUploadSecurityHeaders` there.
- Your own proxy: `createCspNonce()` + `buildCsp({ nonce })`, set the policy on the request headers
(`NextResponse.next({ request: { headers } })`) and on the response, like `createProxy` does.
- `ConsentScript nonce`, `ThemeScript nonce`, `Analytics nonce` exist for policies without `'strict-dynamic'`.
### Payload admin — its own, looser policy
The admin (`/admin`, or your `adminRoute`) is a large client app the project does not control: inline
scripts and styles, the Monaco code editor loaded from `cdn.jsdelivr.net` with `blob:` workers, image
previews from any `https:` host, and the Live Preview iframe (`frame-src 'self'`). `buildAdminCsp(args)` /
`buildAdminCspHeaders(args)` give that policy with the same hard rules, `frame-ancestors 'self'`, and the
same `mode`, `reportUri`, `extra`, `override`. Put its rule AFTER the site-wide one — Next uses the
last matching rule for the same header key:
```ts
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' }) },
```
With a custom `adminRoute` (e.g. `/its`), use that path in `source`.
### Collecting reports
`createCspReportRoute({ onReport?, maxBytes = 16384 })` — a `POST` handler for `reportUri`. It accepts
both formats (`application/csp-report` from `report-uri`, `application/reports+json` from `report-to`),
caps the body, always answers `204`, and by default logs one `console.warn` line per violation:
`[csp] report script-src-elem blocked=https://x.example/a.js page=https://site/pl`. Read them in the
Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more.
```ts
// app/api/csp-report/route.ts (a fixed route wins over Payload's /api/[...slug])
import { createCspReportRoute } from '@intecion/ipal-kit'
export const POST = createCspReportRoute()
```
Third-party option: point `reportUri` at a collector (report-uri.com, Sentry's security endpoint,
uriports) and skip the route. `parseCspReports(body)` normalises both formats for your own handler.
### ROLL OUT CSP CAREFULLY — Report-Only first
A CSP that is too strict **breaks the site** (blocks scripts/styles/images). NEVER deploy
an enforcing CSP blindly. The safe method:
1. **Reporting first** — use the key `Content-Security-Policy-Report-Only`
(not `Content-Security-Policy`). The browser REPORTS violations in the console
but does NOT block — the site works as usual.
```ts
additional: [{ key: 'Content-Security-Policy-Report-Only', value: csp }]
```
2. **Open the site** → DevTools → Console → look for "Content Security Policy"
violations. Each violation = a missing domain. Add it to the matching CSP
directive.
3. **Go through the whole site** — home page, forms (Turnstile!),
gallery (R2 images), pages with maps/embeds. Collect every violation.
4. **Only when the console is clean** → change the key to `Content-Security-Policy`
(enforcing). Now CSP protects without breaking anything.
1. **Report-only** — `mode: 'report-only'` with `reportUri`. The browser REPORTS violations (console +
the report route) but does NOT block — the site works as usual. Deploy it.
2. **Read the reports** — DevTools → Console ("Content Security Policy" / "[Report Only]") on every page
type, and the `[csp]` lines in the Coolify logs (real visitors, other browsers). Go through the whole
site — home page, forms (Turnstile!), gallery (R2 images), embeds, cookie banner accept (analytics and
pixels load only after consent), the admin. Give it a few days of real traffic.
3. **Fix each violation** — a missing host of yours → the matching flag or `extra`; noise from browser
extensions (`chrome-extension://`, `moz-extension://`) → ignore.
4. **Enforce** — when the reports are clean, change `mode: 'report-only'` to `mode: 'enforce'` (site and
admin). Keep `reportUri`: enforced violations keep being reported. Check the pages once more.
### Building CSP by hand (if you need full control)
Pass your own string through `additional` (same key overrides `csp`):
```ts
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
additional: [{ key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'; base-uri 'self'; object-src 'none'; …" }],
})
```
Read the media domain from `R2_PUBLIC_URL` (env), do not hard-code it. Anything you do not list will be
blocked once enforced.
### Checking headers in production
```bash
# check which headers actually go out:
curl -sI https://<DOMAIN>/pl | grep -i "strict-transport\|content-type-options\|referrer\|content-security\|x-frame"
curl -sI https://<DOMAIN>/pl | grep -iE "strict-transport|content-type-options|referrer|content-security|reporting-endpoints|x-frame|x-powered-by"
```
If HSTS/nosniff/Referrer are there but CSP is missing → add CSP (above). If ALL of them
are missing despite buildSecurityHeaders in the config → check that `headers()` is
wired and that Cloudflare (if it sits in front of the app) does not filter headers.
Expected: HSTS, nosniff, Referrer, `content-security-policy-report-only` (or `content-security-policy`
after enforcing), and NO `x-powered-by`. If ALL of them are missing despite buildSecurityHeaders in the
config → check that `headers()` is wired and that Cloudflare (if it sits in front of the app) does not
filter headers.
> Cloudflare note: if CF sits in front of the app, it may override/filter
> Cloudflare / Coolify note: if CF sits in front of the app, it may override/filter
> headers. Then set them in CF as well (Transform Rules → Modify Response Header),
> or make sure CF passes the origin's headers through.
> or make sure CF passes the origin's headers through. Coolify's proxy passes the app's headers
> through unchanged; a header middleware added in the app's "Custom labels" can add or drop them.
## COOP (Cross-Origin-Opener-Policy) — on by default
@@ -370,10 +448,17 @@ data access, not just the UI.
## Turn off, override, extend
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; 2FA — `twoFactor: false` (discouraged).
- **Override:** `additional` (the same key overrides the plugin's header), `buildCsp({ extra })`, `mode`;
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; CSP — leave out `csp` (the default);
X-Powered-By hiding — `withSecurityConfig(config, { hidePoweredBy: false })` or do not call it;
2FA — `twoFactor: false` (discouraged).
- **Override:** `additional` (the same key overrides the plugin's header and the `csp` ones),
`buildCsp({ extra, override, mode, strictDynamic })`, `buildAdminCsp({ extra, override })`,
`createCspReportRoute({ onReport, maxBytes })`;
2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`;
access — `access.authAccess`, `access.firstUserAdmin`, `globalOverrides` ([access.md](./access.md)).
- **Extend:** `buildCsp`, `buildUploadSecurityHeaders({ collections })` for your own upload collections.
- **Check:** `curl -sI https://domain/ | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security"`;
- **Extend:** `buildCsp` / `buildCspHeaders` / `buildReportingEndpoints` / `cspHeaderKey` /
`parseCspReports` / `createCspNonce` (`CSP_NONCE_HEADER`, `DEFAULT_CSP_REPORT_GROUP`) for your own proxy
or collector; `buildUploadSecurityHeaders({ collections })` for your own upload collections.
- **Check:** `curl -sI https://domain/pl | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security|x-powered-by"`
(no `x-powered-by`; `content-security-policy-report-only` while rolling out);
on staging also `x-robots-tag`; startup with a wrong `twoFactor.collectionSlug` fails with `[ipal] twoFactor…`.