Payload's colour-scheme client hints go to the admin only: withSecurityConfig outside withPayload

withPayload adds Accept-CH, Critical-CH and Vary: Sec-CH-Prefers-Color-Scheme for /:path*; Critical-CH makes
Chrome repeat the first document request of a visit to a public page. As the outer wrapper, withSecurityConfig
moves the three headers to /admin/:path* (adminClientHints: { route, sources } | false). Inside withPayload
nothing changes, so an unedited site behaves as before. Exports scopeColorSchemeClientHints,
adminClientHintSources, COLOR_SCHEME_CLIENT_HINT; doctor rule client-hints (info); reference site and starter
use the new order; e2e:built and the starter gate check it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 11:55:26 +01:00
co-authored by Claude Fable 5.2
parent 2f6a81acbf
commit 9143c132a3
28 changed files with 500 additions and 59 deletions
+4 -2
View File
@@ -60,9 +60,11 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
- **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
for p in /pl /admin /api/health; do echo "== $p"; curl -sI "$U$p" | grep -iE 'x-powered-by|content-security-policy|critical-ch'; done
```
`x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). No
`x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). `critical-ch` on `/pl` or
`/api/health` → INFO: Chrome repeats the first request of every visit; make `withSecurityConfig` the outer wrapper,
`withSecurityConfig(withPayload(nextConfig))` (security.md → "Client hints"); on `/admin` it belongs. 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`).
@@ -296,7 +296,7 @@ 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(iaplEnvRules({...})) 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 '' "X-Powered-By hidden" "next.config.ts → export default withSecurityConfig(withPayload(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
@@ -178,7 +178,7 @@ Mandatory set: AGENT.md §0b, skill **iapl-setup**; checks: **iapl-audit**, **ia
| 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(iaplEnvRules({ storage: true, ipHeader: true, databaseName: true }))` from `@intecion/ipal-kit/env` | remove a variable → startup fails with the list of missing ones; a database not named `<domain>_prod`/`_dev` → a warning | env.md, deployment.md §4.2a |
| 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 |
| Next config | `next.config.ts` | `withSecurityConfig(withPayload({ 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\|critical-ch'` (no `x-powered-by`, no `critical-ch`: Payload's colour-scheme hints go to `/admin` only) | 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 |
@@ -601,7 +601,8 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IAPL_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. |
| `withSecurityConfig(nextConfig, { hidePoweredBy?, adminClientHints? })` | `@intecion/ipal-kit` | Next config wrapper, used OUTSIDE withPayload: `withSecurityConfig(withPayload(nextConfig))`. `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"; either order; `hidePoweredBy: false` = no change). Moves withPayload's `Accept-CH` / `Critical-CH` / `Vary: Sec-CH-Prefers-Color-Scheme` from `/:path*` to `/admin/:path*` (outer order only; a public page no longer makes Chrome repeat its first request). `adminClientHints: { route?: '/admin', sources?: string[] }` = another `routes.admin` / more paths; `false` = every path, as before 1.17.0. |
| `scopeColorSchemeClientHints(rules, sources?)` · `adminClientHintSources(route?)` · `COLOR_SCHEME_CLIENT_HINT` | `@intecion/ipal-kit` | The narrowing as building blocks: takes a Next `headers()` array, returns it with the colour-scheme token of `Accept-CH` / `Critical-CH` / `Vary` moved from site-wide rules (`/:path*`, `/(.*)`) to `sources` (default `['/admin/:path*']`); other tokens, headers and narrower rules are kept. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. |
| `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `iapl` runs after the 2FA factory; for a project that registers the 2FA package itself. |
+6 -3
View File
@@ -485,8 +485,9 @@ const securityHeaders = buildSecurityHeaders({
csp: { ...csp, turnstile: true, analytics: true },
})
// withSecurityConfig: no X-Powered-By (Next's and Payload's)
export default withPayload(withSecurityConfig({
// 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 /admin only — inside withPayload it cannot narrow them
export default withSecurityConfig(withPayload({
images: { ...buildImagesConfig() },
htmlLimitedBots:
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
@@ -518,7 +519,8 @@ the "XML Sitemap" style; `curl -s localhost:3000/robots.txt` → `Sitemap:`, `Di
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 -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
→ the first three, NO `x-powered-by`; `curl -sI localhost:3000/pl | grep -iE 'accept-ch|critical-ch'` → nothing (a production build;
the same for `/admin/login` → both — otherwise `withSecurityConfig` is not the outer wrapper); `/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).
@@ -528,6 +530,7 @@ or your own text; `buildSecurityHeaders({ frameOptions, coop, hsts, additional }
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`;
`withSecurityConfig(config, { adminClientHints: false })` leaves Payload's colour-scheme hints on every path, `{ adminClientHints: { route: '/its', sources: ['/preview/:path*'] } }` = a changed `routes.admin` / more paths;
`buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules
(`iaplEnvRules(…).filter(…)`). Staging: `IAPL_NOINDEX=1` (also stops IndexNow). Search engines: `robots` instead of
`getRobots` ignores the panel; `iapl({ searchSettings: false })` removes the tab; per-bot exceptions in code:
+18 -3
View File
@@ -146,8 +146,9 @@ panel opens and a document saves.
as a workaround can drop it.
**→ 1.14.1 (PROGRAMISTA §6, item 50; X-Powered-By, CSP; security.md) — nothing required, recommended in this order:**
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
1. **Hide `X-Powered-By`** — `next.config.ts`: `export default withSecurityConfig(withPayload(nextConfig))`
(import `withSecurityConfig` from `@intecion/ipal-kit`; from 1.17.0 the wrapper goes OUTSIDE — "→ 1.17.0, the public
pages' first request"); 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',
@@ -549,9 +550,23 @@ ipal-kit"). **Do not rename anything in the project unless the owner asks.**
different values). `pnpm exec iapl-doctor` rule `legacy-names` (info) lists what is left.
5. **Never on an existing site:** `storageNames: 'iapl'` or `visitorCookie`. They are for sites made with 1.17.0 or
later; on a live site they reset visitors' statistics history and the 2FA attempt counts, and change the cookie list.
**Check:** `pnpm exec iapl-doctor` shows no new error or warning (new rules: `legacy-names`, `storage-names`); the site
**Check:** `pnpm exec iapl-doctor` shows no new error or warning (new rules: `legacy-names`, `storage-names`, `client-hints` — the last one is the next block); the site
builds; the panel opens; the old commands (`pnpm exec ipal-doctor`) still run.
**→ 1.17.0, the public pages' first request (Payload's colour-scheme client hints for the admin only; CHANGELOG 1.17.0;
PROGRAMISTA §6, item 76; security.md "Client hints") — one line, recommended on every site:**
1. `next.config.ts`: swap the two wrappers — `export default withPayload(withSecurityConfig(nextConfig))` becomes
`export default withSecurityConfig(withPayload(nextConfig))`. Nothing else changes; `X-Powered-By` stays hidden.
Without the swap the site works exactly as before (Payload sends `Accept-CH` / `Critical-CH` /
`Vary: Sec-CH-Prefers-Color-Scheme` for every path, and Chrome repeats the first request of every visit).
2. The panel is not at `/admin` (`routes.admin`): `withSecurityConfig(withPayload(nextConfig), { adminClientHints: { route: '/its' } })`.
3. A page of the project's own that reads `Sec-CH-Prefers-Color-Scheme` on the server (rare:
`grep -rn "Sec-CH-Prefers-Color-Scheme" src`): add its path — `{ adminClientHints: { sources: ['/that/:path*'] } }`,
or keep the old behaviour with `{ adminClientHints: false }`.
**Check** (a production build, `pnpm build && pnpm start`): `curl -sI localhost:3000/pl | grep -iE 'accept-ch|critical-ch'` →
nothing; `curl -sI localhost:3000/admin/login | grep -iE 'accept-ch|critical-ch'` → both; the panel opens in the browser's
light / dark scheme with no flash; `pnpm exec iapl-doctor` has no `client-hints` finding.
**→ 1.17.0, e-mail (the Intecion mail service (IWSN in the panel) is the default transport; Microsoft Graph deprecated; CHANGELOG 1.17.0;
PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; read which case the site is:**
1. **Every site:** no schema change, no migration, no import-map change. `pnpm payload generate:types` gives a small diff