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
+2 -1
View File
@@ -31,7 +31,8 @@ pnpm e2e:built # webpack, then Turbopack: build with the late-staff fixtu
```
It checks the account rules of a staff collection that a plugin listed after iapl adds or copies
(`e2e/late-staff-fixture.ts`, on only with `E2E_LATE_STAFF=1`; `e2e/late-staff.spec.ts`) and that no package manifest
is among the public files. Unit tests run unminified code and cannot see what a bundle renames or publishes.
is among the public files, and that Payload's colour-scheme client hints go to the admin only (a public page is
requested once). Unit tests run unminified code and cannot see what a bundle renames or publishes.
Without `E2E_LATE_STAFF=1` the fixture adds nothing and the spec is skipped. Rebuild with `pnpm build` afterwards.
## What is where
+71
View File
@@ -1,5 +1,6 @@
import { expect, type Page, test } from '@playwright/test'
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
import { createServer, request as httpRequest } from 'node:http'
import path from 'node:path'
import { attachmentOf, startSmtpSink } from './smtp-sink'
@@ -203,6 +204,76 @@ test('security headers: CSP enforced, no X-Powered-By', async ({ request }) => {
expect(headers['x-powered-by']).toBeUndefined()
})
test.describe('client hints: Payload\'s colour-scheme headers go to the admin only', () => {
const HINT = /sec-ch-prefers-color-scheme/i
test('no public page, route handler or static file carries them; the admin does', async ({ request }) => {
const home = await request.get('/pl')
const asset = (await home.text()).match(/\/_next\/static\/[^"'\\ ]+\.(?:js|css)/)?.[0]
expect(asset, 'a static file linked from /pl').toBeTruthy()
// FAILS when withPayload's site-wide rule is back (withSecurityConfig inside withPayload, or the option off)
for (const path of ['/pl', '/en', '/pl/kontakt', '/en/contact', '/pl/blog', '/api/health', '/robots.txt', '/sitemap.xml', '/llms.txt', asset!]) {
const res = await request.get(path)
const headers = res.headers()
expect(res.status(), path).toBe(200)
expect(headers['accept-ch'], `${path}: Accept-CH`).toBeUndefined()
expect(headers['critical-ch'], `${path}: Critical-CH`).toBeUndefined()
expect(headers.vary ?? '', `${path}: Vary`).not.toMatch(HINT)
}
for (const path of ['/admin', '/admin/login']) {
const headers = (await request.get(path, { maxRedirects: 0 })).headers()
expect(headers['accept-ch'], `${path}: Accept-CH`).toMatch(HINT)
expect(headers['critical-ch'], `${path}: Critical-CH`).toMatch(HINT)
}
})
test('Chrome asks for a public page once; the admin still gets the hint and renders the browser\'s scheme', async ({ baseURL, browser, request }) => {
// A counting proxy in front of the site: what the SERVER receives. Chrome repeats a document request inside
// its network stack when the answer names a critical hint it did not send; the page never sees that.
const documents: { hint?: string; url: string }[] = []
const site = new URL(baseURL!)
const proxy = createServer((req, res) => {
if (req.headers['sec-fetch-dest'] === 'document') {documents.push({ hint: req.headers['sec-ch-prefers-color-scheme'] as string | undefined, url: req.url! })}
const upstream = httpRequest({ headers: req.headers, host: site.hostname, method: req.method, path: req.url, port: site.port }, (r) => {
res.writeHead(r.statusCode!, r.headers)
r.pipe(res)
})
upstream.on('error', () => res.destroy())
req.pipe(upstream)
})
await new Promise<void>((resolve) => proxy.listen(0, '127.0.0.1', resolve))
const origin = `http://localhost:${(proxy.address() as { port: number }).port}`
try {
for (const path of ['/pl', '/en/contact']) {
const context = await browser.newContext() // a fresh profile: a first visit
documents.length = 0
await (await context.newPage()).goto(origin + path)
expect(documents, `${path}: one document request, no hint asked for`).toEqual([{ hint: undefined, url: path }])
await context.close()
}
// The panel: its first request teaches Chrome the hint, the repeated one carries it — as before the change.
// (Chrome's network stack sends the system's scheme; Playwright's colorScheme emulation does not reach it.)
const context = await browser.newContext()
const page = await context.newPage()
documents.length = 0
const response = await page.goto(`${origin}/admin/login`)
expect(documents).toEqual([{ hint: undefined, url: '/admin/login' }, { hint: expect.stringMatching(/^(dark|light)$/), url: '/admin/login' }])
const sent = documents[1]!.hint!
// the theme is in the server's HTML: the first paint is already right (no flash)
expect(await response!.text()).toMatch(new RegExp(`<html[^>]*data-theme="${sent}"`))
await expect(page.locator('html')).toHaveAttribute('data-theme', sent)
await context.close()
// and the server renders whichever scheme the hint names
for (const scheme of ['dark', 'light']) {
const html = await (await request.get('/admin/login', { headers: { 'Sec-CH-Prefers-Color-Scheme': scheme } })).text()
expect(html, scheme).toMatch(new RegExp(`<html[^>]*data-theme="${scheme}"`))
}
} finally {
proxy.close()
}
})
})
test('a missing page is a 404 with the panel 404 content', async ({ page }) => {
const res = await page.goto('/pl/nie-ma-takiej-strony')
expect(res?.status()).toBe(404)
+3 -2
View File
@@ -57,5 +57,6 @@ const nextConfig: NextConfig = {
},
}
// withSecurityConfig: no X-Powered-By (Next's and Payload's)
export default withPayload(withSecurityConfig(nextConfig))
// 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, so a public page is requested once (security.md)
export default withSecurityConfig(withPayload(nextConfig))