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
+20
View File
@@ -208,6 +208,15 @@ once there are more than 20.
Steps and checks: `iapl-upgrade` "→ 1.17.0, e-mail", [email.md](./email.md).
- **Microsoft Graph is deprecated and will be removed in 2.0** (with Payload 4). It works unchanged through 1.x.
To move a site: [email.md](./email.md) "Moving off Microsoft Graph" — when the owner says so, not in passing.
- **Recommended, one line — public pages load with one request instead of two:** in `next.config.ts` change
`withPayload(withSecurityConfig(nextConfig))` to `withSecurityConfig(withPayload(nextConfig))`. Payload's
`withPayload` sends `Accept-CH`, `Critical-CH` and `Vary: Sec-CH-Prefers-Color-Scheme` for every path, and
`Critical-CH` makes Chrome repeat the first document request of every visit; as the outer wrapper,
`withSecurityConfig` keeps the three headers on `/admin/:path*` only. **A site that is not edited behaves exactly
as before** (the inner wrapper cannot see Payload's rule). Another panel address:
`{ adminClientHints: { route: '/its' } }`; the old behaviour on purpose: `{ adminClientHints: false }`.
Check: `curl -sI <site>/pl | grep -i critical-ch` prints nothing, `<site>/admin/login` still prints it.
`iapl-upgrade` "→ 1.17.0, the public pages' first request", [security.md](./security.md) "Client hints".
- **Otherwise nothing.** Recommended after the update: `pnpm exec iapl-skills` (or the project's `ipal:skills` script) and commit —
the skills are named `iapl-*` now; the 16 old `ipal-*` folders are removed by name, a project's own `ipal-…` skill
stays, and the pointer block in `AGENTS.md` is rewritten in place.
@@ -240,6 +249,17 @@ once there are more than 20.
keep their doctor rule ids, so settings in a project's doctor file still match.
### Added
- **Payload's colour-scheme client hints go to the admin only** ([security.md](./security.md) "Client hints").
`withSecurityConfig(withPayload(nextConfig))` — the wrapper **outside** `withPayload` — moves `Accept-CH`,
`Critical-CH` and `Vary: Sec-CH-Prefers-Color-Scheme` from `/:path*` to `/admin/:path*`. Before, every public
page, route handler and static file carried them, and Chrome requested the first page of a visit twice (measured
on the built reference site, both bundlers: 2 document requests → 1; one network round trip less before the
first byte). The panel keeps its light / dark first paint. Option `adminClientHints`: `{ route }` for a changed
`routes.admin`, `{ sources }` for more paths, `false` for the old behaviour. Exports:
`scopeColorSchemeClientHints`, `adminClientHintSources`, `COLOR_SCHEME_CLIENT_HINT`, type
`AdminClientHintsOptions`. Doctor rule `client-hints` (info): the wrapper is inside `withPayload`, or (with
`--url`) the home page still sends `Critical-CH`. The starter and the reference site use the new order; an
existing site changes one line ("Requires project changes").
- **The Intecion Notifications Webservice (IWSN) as the default e-mail transport** ([email.md](./email.md), AGENT.md §7.2).
The admin panel calls it **IWSN**; docs, logs and the doctor use the full name.
`mailAdapter()` now picks per send: Graph when the panel says so and `GRAPH_*` is set → SMTP when the panel has a
+9 -4
View File
@@ -247,7 +247,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 `iapl`; `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"; `iapl({ 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** → *Approve cookies* → **Approve and add**; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookies → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `iapl-consent-check` |
| 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 }` + `generate:importmap` (`TotpRedirectProvider`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **an account without 2FA can only set it up** (`twoFactor.requireSetup`, default: nothing else answers, 72 h from creation or an admin's reset, then blocked until an admin chooses "Reopen setup" on the account) — so set 2FA up right after creating an account; `iapl-doctor --url` must report 0 accounts without 2FA; Postgres/SQLite: migration for `totpSetupFrom`; `IAPL_IP_HEADER` in production | security.md, forms.md | A |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withSecurityConfig(withPayload(nextConfig))` — this order (no `X-Powered-By`; Payload's colour-scheme client hints for `/admin` only, check: `curl -sI localhost:3000/pl \| grep -i critical-ch` → nothing); 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 }` + `generate:importmap` (`TotpRedirectProvider`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **an account without 2FA can only set it up** (`twoFactor.requireSetup`, default: nothing else answers, 72 h from creation or an admin's reset, then blocked until an admin chooses "Reopen setup" on the account) — so set 2FA up right after creating an account; `iapl-doctor --url` must report 0 accounts without 2FA; Postgres/SQLite: migration for `totpSetupFrom`; `IAPL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(iaplEnvRules({ storage: true, ipHeader: true }))`; staging with `IAPL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `iaplEnvRules` | 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 |
@@ -1150,7 +1150,7 @@ 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: `iapl({ lightbox: true })` → Form messages → Image viewer | lightbox.md |
| YouTube without cookies before a click | `<YouTubeEmbed>` (`/client`) | storage.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders` (`csp`), `buildCsp`, `buildCspHeaders`, `buildAdminCsp` / `buildAdminCspHeaders`, `buildUploadSecurityHeaders`, `withSecurityConfig` (hides `X-Powered-By`) | storage.md, security.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders` (`csp`), `buildCsp`, `buildCspHeaders`, `buildAdminCsp` / `buildAdminCspHeaders`, `buildUploadSecurityHeaders`, `withSecurityConfig` (the OUTER wrapper: hides `X-Powered-By`, keeps Payload's `Accept-CH` / `Critical-CH` / `Vary` colour-scheme hints on the admin only; `adminClientHints: { route, sources } \| false`), `scopeColorSchemeClientHints`, `adminClientHintSources`, `COLOR_SCHEME_CLIENT_HINT` | 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); your own sizes: `fluidClamp`, `FLUID_SCALE`, `FLUID_RANGES` | design-tokens.md |
| Brand colours, fonts, radii, motion, dark mode | `tokens.css` + `tailwind.css`, `src/design/tokens.ts` (`defineTokens`, types `TokensInput`, `ColorInput`, `ColorRole`), `pnpm exec iapl-tokens` (`--check`, `--report`, `--warn-only`); building blocks `tokensToCss`, `defaultTokensCss`, `contrastReport` (`ContrastRow`), `contrastRatio`, `parseColor`, `resolveColors`, `IAPL_TOKENS`, `iaplVar`, `IaplTokenName`, `IAPL_BREAKPOINTS`, `COLOR_DEFAULTS`, `STATIC_DEFAULTS`, `FLUID_TOKENS`, `INVERSE_SCOPE`, `LEGACY_DARK_ROLES`, `LIGHT_SELECTOR`, `DARK_SELECTOR`, `INVERSE_SELECTOR`, `RemValue`, `FluidRange` | design-tokens.md |
@@ -1179,8 +1179,12 @@ table from the panel (`<CookieTable>` and the `settings="detailed"` window, scan
requires it (accessibility.md).
**Security:** 2FA enforced (`iapl({ twoFactor: { issuer, plugin:
payloadTotp } })`, never `twoFactor: false` without a client decision). No `X-Powered-By`:
`withPayload(withSecurityConfig(nextConfig))`. CSP in three steps (security.md → "ROLL OUT CSP"):
payloadTotp } })`, never `twoFactor: false` without a client decision). No `X-Powered-By`, and Payload's
colour-scheme client hints (`Accept-CH`, `Critical-CH`, `Vary: Sec-CH-Prefers-Color-Scheme`) only on the admin:
`withSecurityConfig(withPayload(nextConfig))` — **in this order**; inside `withPayload` the wrapper cannot see
Payload's rule and every public page makes Chrome repeat its first request (security.md → "Client hints"; a
changed `routes.admin`: `{ adminClientHints: { route: '/its' } }`). Check: `curl -sI $U/pl | grep -iE
'accept-ch|critical-ch'` → nothing, the same for `$U/admin/login` → both. 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
@@ -1229,6 +1233,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| 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 })` | — |
| Payload's colour-scheme client hints only on `/admin/:path*` (with `withSecurityConfig` outside `withPayload`) | `withSecurityConfig(config, { adminClientHints: false })` | `{ adminClientHints: { route, sources } }`, `scopeColorSchemeClientHints(rules, sources)` |
| 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 |
+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
+1 -1
View File
@@ -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
+4 -2
View File
@@ -683,6 +683,7 @@ Do one item at a time, build, check. Order by importance:
| 73 | **1.17.0 — e-mail: the Intecion mail service is the default transport** — a site with no SMTP server in the panel and no `GRAPH_*` starts sending through the service after the upgrade (an outbound call with its host; a new public route `POST /api/iapl/mail-relay/confirm`; mail from `[email protected]`); a Graph site warns at start | Nothing to run (no schema, migration or import-map change). SMTP site: nothing. Graph site: nothing now — deprecated, move when the owner says. Site with neither: agree it with the owner; `serverURL` = the public address, "Sender address" filled in, the host listed by Intecion; or `iapl({ mail: { relay: false } })` to keep the old behaviour | `iapl-upgrade` "→ 1.17.0, e-mail", AGENT.md §7.2, email.md |
| 74 | **1.17.0 — Postgres** — a Postgres site with many form submissions or "forgot password" requests at the same moment stopped answering (every page waited); after the update `transactionWatchState` shows a reserve, form and account mail arrive a moment after the save | Nothing to run. Default: a fifth of the pool (at least 2) kept free of transactions; form, "forgot password" and "verify" mail sent right after the commit; shorter SMTP time-outs. The old way: `connectionReserve: false`, `forms: { emailsInTransaction: true }`, `mail: { accountMailAfterCommit: false }`. An own e-mail adapter calls `sendAccountMailAfterCommit` first. MongoDB / SQLite: no change | CHANGELOG 1.17.0 "Fixed — Postgres", deployment.md §4.3a, forms.md "When e-mails go out" |
| 75 | **1.17.0 — e-mail: launch day and copies** — a site moves from `<name>.dev.netscale.pl` to its real domain (the real domain must send with no click); or production's database is copied to a development or staging address (it must not mail real people); or the start stops with "`developmentHosts` must be an array of host patterns" | Nothing to run on launch day. A development address matching `iapl({ developmentHosts })` (built in `*.dev.netscale.pl`) or a site with `IAPL_NOINDEX=1` that holds another host's connection sends nothing until an admin presses "Connect again". Other staging hosts: add their pattern to `developmentHosts` (an array of non-empty patterns; `[]` = none). Production never keeps `IAPL_NOINDEX` | `iapl-upgrade` "→ 1.17.0, e-mail", email.md "Staging, copies and several hosts" |
| 76 | **1.17.0 — public pages: Chrome requests the first page of a visit twice** — `curl -sI <site>/pl` shows `Critical-CH: Sec-CH-Prefers-Color-Scheme` (Payload's `withPayload` adds it for every path; only the admin reads the hint); Lighthouse lists the same URL twice under redirects | `next.config.ts`: `withSecurityConfig(withPayload(nextConfig))` — the plugin's wrapper OUTSIDE (was inside). Another panel address: `{ adminClientHints: { route } }`; keep the old behaviour: `{ adminClientHints: false }`. Without the edit nothing changes | `iapl-upgrade` "→ 1.17.0, the public pages' first request", security.md "Client hints" |
After updating the package: `pnpm exec iapl-skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
`node_modules/@intecion/ipal-kit/dist`.
@@ -787,8 +788,9 @@ done until the reference site uses it. Before `npm version`:
(no new name is born with the old spelling).
- [ ] **`pnpm e2e:built` green — required, no release without it.** It builds the reference site with webpack AND with
Turbopack (with the late-staff fixture, `E2E_LATE_STAFF=1`) and runs, on each built site: the account rules of
staff collections the project or a later plugin adds (`e2e/late-staff.spec.ts`), and "no package manifest among
the public files". Unit tests run unminified code and cannot see what a bundle renames or publishes — two
staff collections the project or a later plugin adds (`e2e/late-staff.spec.ts`), "no package manifest among
the public files", and "client hints" (Payload's colour-scheme headers on the admin only; Chrome requests a
public page once). Unit tests run unminified code and cannot see what a bundle renames or publishes — two
defects of the 1.16.7 review lived only in a built site. Needs `reference/.env` (local seeded MongoDB, `E2E_*`
test admin); port from `E2E_BASE_URL`. Afterwards `git status` is clean (the command puts the reference site's
generated types and import map back, also when it fails); rebuild the reference site without the fixture
+1
View File
@@ -101,6 +101,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
| | `env-live` | error | (deep) the project's env rules pass in the real environment |
| security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection |
| | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin |
| | `client-hints` | info | `withSecurityConfig` is the outer wrapper (`withSecurityConfig(withPayload(…))`), so Payload's colour-scheme client hints go to the admin only; live: `/` sends no `Critical-CH: Sec-CH-Prefers-Color-Scheme`. Not reported with `adminClientHints: false` |
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `access-missing` | warning | `iapl` has an `access` option — without it there are no roles and every panel account is an admin |
+53 -5
View File
@@ -2,7 +2,8 @@
Generic HTTP security headers (HSTS, X-Frame-Options, nosniff,
Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy; `X-Robots-Tag` on staging)
as a function for `next.config`, `withSecurityConfig` to hide `X-Powered-By`, and an opt-in
as a function for `next.config`, `withSecurityConfig` to hide `X-Powered-By` and to keep Payload's colour-scheme
client hint headers on the admin panel only, and an opt-in
Content-Security-Policy (`buildCsp`, report-only first, a separate admin policy, optional nonces and a
report collector).
@@ -42,8 +43,9 @@ 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 the admin only, not for every page
export default withSecurityConfig(withPayload(nextConfig))
```
## Options
@@ -83,8 +85,9 @@ advisories) to try. Audits flag it. Where it comes from:
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))`.
`X-Powered-By` entry from `headers()` rules, so both orders hide the header:
`withSecurityConfig(withPayload(nextConfig))` (recommended: the only order that also narrows the client hints,
next section) or `withPayload(withSecurityConfig(nextConfig))` (the order of sites made before 1.17.0).
Turn off: `withSecurityConfig(nextConfig, { hidePoweredBy: false })`, or do not call it. Without the helper,
`poweredByHeader: false` in the config passed to `withPayload` has the same effect.
@@ -95,6 +98,49 @@ Check: `curl -sI https://<DOMAIN>/pl | grep -i x-powered-by` prints nothing. Beh
Keep the software updated as well — hiding the header does not remove the advisories (the minimum safe
Next.js is listed in the agent guide, §4).
## Client hints — the admin only (`withSecurityConfig`)
**The problem.** Payload's `withPayload` adds three response headers for **every** path (`/:path*`):
`Accept-CH: Sec-CH-Prefers-Color-Scheme`, `Critical-CH: Sec-CH-Prefers-Color-Scheme` and
`Vary: Sec-CH-Prefers-Color-Scheme`. The admin panel needs them: with the hint in the request it renders light or
dark on the server, so the panel does not flash on its first paint. A public page does not read the hint, yet
`Critical-CH` tells Chrome to **repeat the first document request of a visit** with the hint added — one wasted
round trip on every first page view (two requests for `/pl` in the server log; about 600 ms in a mobile Lighthouse
run of a client site, where it shows as a repeated navigation under "Avoid multiple page redirects"). Route
handlers and static files also get `Vary: Sec-CH-Prefers-Color-Scheme`, which splits them in a shared cache.
Neither `withPayload` nor the proxy has an option for it, and a proxy cannot remove a header that `next.config` set.
**The fix.** `withSecurityConfig` as the **outer** wrapper moves the three headers to the panel's routes:
```ts
export default withSecurityConfig(withPayload(nextConfig)) // /admin/:path* only (the default)
```
| Option | Default | Role |
|---|---|---|
| `adminClientHints` | `true` | `true`: the hint headers only for `/admin/:path*`. `false`: leave them on every path (the behaviour before 1.17.0) |
| `adminClientHints.route` | `'/admin'` | Payload's `routes.admin` when the panel has another address: `{ route: '/its' }` |
| `adminClientHints.sources` | `[]` | more Next `source` patterns that keep the headers, e.g. `['/preview/:path*']` for a page of your own that reads `Sec-CH-Prefers-Color-Scheme` on the server |
- **The order matters.** Only the outer wrapper sees the rule `withPayload` adds. `withPayload(withSecurityConfig(…))`
— the order of every site made before 1.17.0 — still builds and still hides `X-Powered-By`, but the hints stay on
every path, as before. Swap the two names (one line); nothing else changes. `iapl-doctor` rule `client-hints`
(info) reports the old order, and with `--url` a public page that still sends `Critical-CH`.
- **What is moved.** Only the token `Sec-CH-Prefers-Color-Scheme` in `Accept-CH`, `Critical-CH` and `Vary` of a
site-wide rule (`/:path*`, `/(.*)`). Other tokens stay (another client hint, another `Vary` name), other headers
of the rule stay (CSP, HSTS, …), and a rule you wrote for a narrower source is left alone. `/admin/:path*` gets
the headers exactly as `withPayload` wrote them. Next's own `Vary` for pages (`rsc, next-router-state-tree, …`)
is not touched.
- **The panel works as before**: on its first request Chrome learns the hint from `/admin` and repeats that one
request, the panel paints in the browser's scheme with no flash; a theme chosen in the account (the
`payload-theme` cookie) still wins.
- **Building blocks:** `scopeColorSchemeClientHints(rules, sources?)` (the same narrowing for a `headers()` array
of your own), `adminClientHintSources(route?)`, `COLOR_SCHEME_CLIENT_HINT`.
Check (a production build): `curl -sI localhost:3000/pl | grep -iE 'accept-ch|critical-ch'` prints nothing;
`curl -sI localhost:3000/admin/login | grep -iE 'accept-ch|critical-ch'` prints both. In Chrome, a first visit to a
public page in a fresh profile shows one document request.
## Content-Security-Policy
### Why CSP is opt-in
@@ -1058,6 +1104,8 @@ the full text, as before. The components take the same as props
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; CSP — leave out `csp` (the default);
X-Powered-By hiding — `withSecurityConfig(config, { hidePoweredBy: false })` or do not call it;
client hints for the admin only — `withSecurityConfig(config, { adminClientHints: false })` (hints on every path
again), `{ adminClientHints: { route, sources } }` (another panel address, more paths);
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 })`,
+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))
+3 -2
View File
@@ -9,7 +9,8 @@
* 1. production build with the late-staff fixture (E2E_LATE_STAFF=1, reference/e2e/late-staff-fixture.ts);
* 2. no package manifest under .next/static (checked on disk, before anything is started);
* 3. Playwright against `next start`: e2e/late-staff.spec.ts, e2e/mail-relay.spec.ts (the mail service: the confirm
* route under Next, the state block in the panel's production bundle) and the smoke test "no package.json is published".
* route under Next, the state block in the panel's production bundle) and the smoke tests "no package.json is published"
* and "client hints" (Payload's colour-scheme headers on the admin only; a public page is requested once).
*
* Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local,
* seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup.
@@ -81,7 +82,7 @@ for (const bundler of bundlers) {
process.exit(1)
}
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
run(`${bundler}: the built site — late-staff spec, the mail service and the published-files check`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'smoke', '--grep', 'late staff collection|the mail service|no package.json is published'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
run(`${bundler}: the built site — late-staff spec, the mail service, the published-files check and the client hints`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'smoke', '--grep', 'late staff collection|the mail service|no package.json is published|client hints'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
passed.push(bundler)
}
console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)
+2
View File
@@ -171,6 +171,8 @@ async function main() {
const headers = home.headers
check('GET /pl', home.status === 200, String(home.status))
check('CSP report-only, no X-Powered-By', headers.has('content-security-policy-report-only') && !headers.has('x-powered-by'))
// Payload's colour-scheme client hints belong to the admin only (withSecurityConfig outside withPayload)
check('no Accept-CH / Critical-CH on /pl', !headers.has('accept-ch') && !headers.has('critical-ch'), headers.get('critical-ch') ?? headers.get('accept-ch') ?? '')
const llms = await (await fetch(`http://127.0.0.1:${PORT}/llms.txt`)).text()
check('llms.txt names the site', llms.includes('Release Check'))
+3
View File
@@ -413,6 +413,7 @@ export {
} from './modules/secrets/writeOnly.js'
export type { WriteOnlySecretOptions } from './modules/secrets/writeOnly.js'
export {
adminClientHintSources,
buildAdminCsp,
buildAdminCspHeaders,
buildCsp,
@@ -420,12 +421,14 @@ export {
buildReportingEndpoints,
buildSecurityHeaders,
buildUploadSecurityHeaders,
COLOR_SCHEME_CLIENT_HINT,
createCspNonce,
createCspReportRoute,
CSP_NONCE_HEADER,
cspHeaderKey,
DEFAULT_CSP_REPORT_GROUP,
parseCspReports,
scopeColorSchemeClientHints,
totpAdminPath,
totpRedirectTarget,
UPLOAD_SECURITY_HEADERS,
+22 -1
View File
@@ -45,7 +45,7 @@ export const securityRules: DoctorRule[] = [
check: async (ctx) => {
const out: RuleFinding[] = []
if (!/withSecurityConfig\s*\(|poweredByHeader\s*:\s*false/.test(next(ctx))) {
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withPayload(withSecurityConfig(nextConfig))', message: 'X-Powered-By is not hidden (withSecurityConfig)', severity: 'error' })
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withSecurityConfig(withPayload(nextConfig))', message: 'X-Powered-By is not hidden (withSecurityConfig)', severity: 'error' })
}
if (ctx.live) {
for (const path of ['/', `${ctx.live.adminRoute}/login`]) {
@@ -60,6 +60,27 @@ export const securityRules: DoctorRule[] = [
group: 'security',
source: 'static',
},
{
id: 'client-hints',
check: async (ctx) => {
const out: RuleFinding[] = []
const code = next(ctx)
const kept = /adminClientHints\s*:\s*false/.test(code)
if (!kept && /withPayload\s*\(\s*withSecurityConfig\s*\(/.test(code)) {
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withSecurityConfig(withPayload(nextConfig))', message: "withSecurityConfig is inside withPayload: Payload's colour-scheme client hints go out with every page (Chrome repeats the first request of a visit)", severity: 'info' })
}
if (ctx.live && !kept) {
const res = await ctx.live.fetch('/')
if (/sec-ch-prefers-color-scheme/i.test(res.headers.get('critical-ch') ?? '')) {
out.push({ fix: 'withSecurityConfig(withPayload(nextConfig)) (security.md → Client hints)', message: 'live / sends Critical-CH: Sec-CH-Prefers-Color-Scheme (only the admin needs it)', severity: 'info' })
}
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: 'csp',
check: async (ctx) => {
+2 -2
View File
@@ -15,5 +15,5 @@ export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRo
export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js'
export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js'
export type { TotpRedirectArgs, TotpUser } from './totp/totpRedirect.js'
export { withSecurityConfig } from './withSecurityConfig.js'
export type { WithSecurityConfigOptions } from './withSecurityConfig.js'
export { adminClientHintSources, COLOR_SCHEME_CLIENT_HINT, scopeColorSchemeClientHints, withSecurityConfig } from './withSecurityConfig.js'
export type { AdminClientHintsOptions, WithSecurityConfigOptions } from './withSecurityConfig.js'
+113 -18
View File
@@ -2,13 +2,32 @@
* Minimal structural shape of a Next config — the plugin does not import `next`
* types into this helper; Next's real NextConfig satisfies it at the call site.
*/
type HeaderRule = { headers: { key: string; value: string }[] } & Record<string, unknown>
type Header = { key: string; value: string }
type HeaderRule = { headers: Header[]; source?: string } & Record<string, unknown>
type NextConfigLike = {
headers?: () => HeaderRule[] | Promise<HeaderRule[]>
poweredByHeader?: boolean
}
export type AdminClientHintsOptions = {
/** Payload's `routes.admin`. Default `/admin`. */
route?: string
/**
* More Next `source` patterns that keep the colour-scheme hint headers, besides the panel
* (for example a page of the project that reads `Sec-CH-Prefers-Color-Scheme` on the server).
*/
sources?: string[]
}
export type WithSecurityConfigOptions = {
/**
* Send Payload's colour-scheme client hint headers (`Accept-CH`, `Critical-CH`, `Vary` with
* `Sec-CH-Prefers-Color-Scheme`) for the admin panel only, not for every path. Default true.
* Works only when this wrapper is the OUTER one: `withSecurityConfig(withPayload(nextConfig))`.
* An object sets the panel's route (`route`, default `/admin`) and extra paths (`sources`);
* `false` leaves the headers where withPayload put them (every path).
*/
adminClientHints?: AdminClientHintsOptions | boolean
/**
* Remove `X-Powered-By` (Next's own "Next.js" and the "Next.js, Payload" that
* withPayload adds) — it tells scanners which software to target. Default true;
@@ -17,38 +36,114 @@ export type WithSecurityConfigOptions = {
hidePoweredBy?: boolean
}
/** The client hint Payload's admin reads to pick light or dark before the first paint. */
export const COLOR_SCHEME_CLIENT_HINT = 'Sec-CH-Prefers-Color-Scheme'
const HINT = COLOR_SCHEME_CLIENT_HINT.toLowerCase()
const HINT_HEADERS = new Set(['accept-ch', 'critical-ch', 'vary'])
/** Sources that mean "every path": the shape of the rule withPayload adds. */
const SITE_WIDE = new Set(['/(.*)', '/:path(.*)', '/:path*'])
const tokens = (value: string) => value.split(',').map((t) => t.trim()).filter(Boolean)
/**
* Next config wrapper for the security settings that are not response headers
* the project adds itself. Today: hides `X-Powered-By`.
* Next `source` patterns of the admin panel for a `routes.admin` value: `/admin` → `['/admin/:path*']`
* (`:path*` also matches `/admin` itself). An admin at the root gives `['/:path*']`.
*/
export function adminClientHintSources(route = '/admin'): string[] {
const clean = `/${route}`.replace(/\/+/g, '/').replace(/\/$/, '')
return [`${clean}/:path*`]
}
/**
* Moves the colour-scheme client hint headers of site-wide rules to the given sources.
*
* Where the header comes from: Next sends `X-Powered-By: Next.js` unless
* `poweredByHeader: false`; Payload's withPayload switches Next's off and adds
* `X-Powered-By: Next.js, Payload` through headers() — also unless the config it
* wraps says `poweredByHeader: false`. This helper sets that flag AND drops the
* header from headers() rules, so it works on either side of withPayload:
* Where they come from: Payload's withPayload appends `Accept-CH`, `Critical-CH` and `Vary`, all with the value
* `Sec-CH-Prefers-Color-Scheme`, for `/:path*`. The admin reads the hint to render the right theme on the server.
* A public page does not, yet `Critical-CH` makes Chrome repeat the first document request of a visit, and `Vary`
* splits the page in shared caches.
*
* Only site-wide rules (`/:path*`, `/(.*)`) are narrowed; a rule the project wrote for a narrower source is left
* alone. Other tokens of the three headers (another client hint, another `Vary` name) stay where they were, and
* everything else in the rule (`has`, `missing`, `basePath`, `locale`) is carried over to the new rules.
*/
export function scopeColorSchemeClientHints<R extends HeaderRule>(rules: R[], sources: string[] = adminClientHintSources()): R[] {
const keep = new Set(sources)
const out: R[] = []
const moved: R[] = []
for (const rule of rules) {
if (typeof rule.source !== 'string' || !SITE_WIDE.has(rule.source) || keep.has(rule.source)) {
out.push(rule)
continue
}
const taken: Header[] = []
const left: Header[] = []
for (const header of rule.headers) {
const all = HINT_HEADERS.has(header.key.toLowerCase()) ? tokens(header.value) : []
const rest = all.filter((t) => t.toLowerCase() !== HINT)
if (rest.length === all.length) {
left.push(header)
continue
}
taken.push(header)
if (rest.length) {left.push({ key: header.key, value: rest.join(', ') })}
}
if (!taken.length) {
out.push(rule)
continue
}
if (left.length) {out.push({ ...rule, headers: left })}
// the admin keeps the full original value: what the panel got before the change
for (const source of sources) {moved.push({ ...rule, headers: taken, source })}
}
return [...out, ...moved]
}
/**
* Next config wrapper for the security and delivery settings that are not response headers
* the project adds itself. Hides `X-Powered-By`, and keeps Payload's colour-scheme client hint
* headers on the admin panel only.
*
* Where the headers come from: Next sends `X-Powered-By: Next.js` unless `poweredByHeader: false`;
* Payload's withPayload switches Next's off and adds `X-Powered-By: Next.js, Payload` through
* headers() — also unless the config it wraps says `poweredByHeader: false`. withPayload also
* appends `Accept-CH`, `Critical-CH` and `Vary: Sec-CH-Prefers-Color-Scheme` for every path.
*
* Hiding `X-Powered-By` works on either side of withPayload. Narrowing the client hints needs
* this wrapper OUTSIDE, because only there it sees the rule withPayload adds:
*
* // next.config.ts
* import { withSecurityConfig } from '@intecion/ipal-kit'
* export default withPayload(withSecurityConfig(nextConfig))
* export default withSecurityConfig(withPayload(nextConfig))
*/
export function withSecurityConfig<T extends object>(
config: T,
options: WithSecurityConfigOptions = {},
): { poweredByHeader?: boolean } & T {
const { hidePoweredBy = true } = options
if (!hidePoweredBy) {return config}
const { adminClientHints = true, hidePoweredBy = true } = options
const original = (config as NextConfigLike).headers
const hints = adminClientHints === true ? {} : adminClientHints
if (!hidePoweredBy && !(hints && original)) {return config}
const sources = hints ? [...adminClientHintSources(hints.route), ...(hints.sources ?? [])] : []
return {
...config,
poweredByHeader: false,
...(hidePoweredBy ? { poweredByHeader: false } : {}),
...(original
? {
headers: async () =>
(await original()).map((rule) => ({
...rule,
headers: rule.headers.filter((h) => h.key.toLowerCase() !== 'x-powered-by'),
})),
headers: async () => {
let rules = await original()
if (hints) {rules = scopeColorSchemeClientHints(rules, sources)}
if (hidePoweredBy) {
rules = rules.flatMap((rule) => {
const headers = rule.headers.filter((h) => h.key.toLowerCase() !== 'x-powered-by')
if (headers.length === rule.headers.length) {return [rule]}
// Next refuses a rule with no headers ("`headers` field cannot be empty"): drop one emptied here
return headers.length ? [{ ...rule, headers }] : []
})
}
return rules
},
}
: {}),
}
+30
View File
@@ -493,6 +493,12 @@ describe('security and deep status', () => {
expect(rules(await doctor(root, ['security']))).toContain('csp:info')
expect(rules(await doctor(root, ['csp'], { config: { seen: { 'csp-report-only': '2026-09-01' } } }))).toEqual(['csp:warning'])
})
test('client-hints: withSecurityConfig inside withPayload is reported (info); outside, or kept on purpose, is not', async () => {
const inner = project(next('export default withPayload(\n withSecurityConfig(nextConfig))'))
expect(rules(await doctor(inner, ['client-hints']))).toEqual(['client-hints:info'])
expect(rules(await doctor(project(next('export default withSecurityConfig(withPayload(nextConfig))')), ['client-hints']))).toEqual([])
expect(rules(await doctor(project(next('export default withPayload(withSecurityConfig(nextConfig, { adminClientHints: false }))')), ['client-hints']))).toEqual([])
})
test('deep status: users without TOTP, pending cookies, stale import map, env problems', async () => {
const root = project({ ...base(), 'src/app/(payload)/admin/importMap.js': '', 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }, cookieScanner: { crawl: true }', ...installed('@clocklimited/payload-2fa', '3.0.0') })
const report = await doctor(root, ['2fa', 'cookie-scanner', 'importmap', 'env-live', 'deep-status'], {
@@ -595,6 +601,30 @@ describe('live (--url)', () => {
})
})
describe('live (--url): client hints', () => {
let server: Server
let url = ''
let headers: Record<string, string> = {}
beforeAll(async () => {
server = createServer((_req, res) => res.writeHead(200, headers).end('ok'))
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
url = `http://127.0.0.1:${(server.address() as { port: number }).port}`
})
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))
test('a public page that sends Critical-CH for the colour scheme is reported; without it, or kept on purpose, not', async () => {
const outer = { ...base(), 'next.config.ts': 'export default withSecurityConfig(withPayload(nextConfig))' }
headers = { 'Accept-CH': 'Sec-CH-Prefers-Color-Scheme', 'Critical-CH': 'Sec-CH-Prefers-Color-Scheme' }
expect((await doctor(project(outer), ['client-hints'], { url })).findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([
'info: live / sends Critical-CH: Sec-CH-Prefers-Color-Scheme (only the admin needs it)',
])
const kept = { ...base(), 'next.config.ts': 'export default withSecurityConfig(withPayload(nextConfig), { adminClientHints: false })' }
expect((await doctor(project(kept), ['client-hints'], { url })).findings).toEqual([])
headers = {}
expect((await doctor(project(outer), ['client-hints'], { url })).findings).toEqual([])
})
})
describe('CLI', () => {
const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n<!-- iapl:start -->\n## IAPL 1.14.6 — agent guide\n<!-- iapl:end -->', 'CLAUDE.md': '@AGENTS.md\n' })
const cli = async (args: string[], cwd: string) => {
+98
View File
@@ -7,14 +7,17 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { createProxy } from '../src/modules/i18n/createProxy.js'
import {
adminClientHintSources,
buildAdminCsp,
buildAdminCspHeaders,
buildCsp,
buildCspHeaders,
buildSecurityHeaders,
COLOR_SCHEME_CLIENT_HINT,
createCspNonce,
createCspReportRoute,
parseCspReports,
scopeColorSchemeClientHints,
withSecurityConfig,
} from '../src/modules/security/index.js'
@@ -62,6 +65,101 @@ describe('withSecurityConfig (X-Powered-By)', () => {
})
})
describe('withSecurityConfig (colour-scheme client hints for the admin only)', () => {
type Rule = { headers: { key: string; value: string }[]; source: string } & Record<string, unknown>
const HINT = /sec-ch-prefers-color-scheme/i
const rulesOf = async (c: NextConfig) => (await c.headers!()) as Rule[]
/** Rules that still carry the hint in any header, by source. */
const hinted = (rules: Rule[]) => rules.filter((r) => r.headers.some((h) => HINT.test(h.value))).map((r) => r.source)
const header = (rule: Rule | undefined, key: string) => rule?.headers.find((h) => h.key.toLowerCase() === key)?.value
const own = { headers: [{ key: 'X-Frame-Options', value: 'DENY' }, { key: 'Vary', value: 'Accept' }], source: '/:path*' }
test('real withPayload sends the hints for every path: the problem being fixed', async () => {
expect(hinted(await rulesOf(withPayload({})))).toEqual(['/:path*'])
})
test('outside withPayload: the three headers go to the admin only, nothing else changes', async () => {
const rules = await rulesOf(withSecurityConfig(withPayload({ headers: async () => [own] })))
// FAILS when the hints come back on a public route
expect(hinted(rules)).toEqual(['/admin/:path*'])
const admin = rules.find((r) => r.source === '/admin/:path*')
expect(admin?.headers).toEqual([
{ key: 'Accept-CH', value: COLOR_SCHEME_CLIENT_HINT },
{ key: 'Vary', value: COLOR_SCHEME_CLIENT_HINT },
{ key: 'Critical-CH', value: COLOR_SCHEME_CLIENT_HINT },
])
// the project's own rule is untouched, and no site-wide rule is left with Accept-CH / Critical-CH / an empty Vary
expect(rules[0]).toEqual(own)
const siteWide = rules.filter((r) => r.source === '/:path*').flatMap((r) => r.headers.map((h) => h.key.toLowerCase()))
expect(siteWide).toEqual(['x-frame-options', 'vary'])
expect(rules.flatMap((r) => r.headers).filter((h) => !h.value)).toEqual([])
})
test('no rule is left without headers (Next stops the build on one)', async () => {
// withPayload's rule is hints + X-Powered-By: with both taken out nothing is left of it on /:path*
for (const config of [withSecurityConfig(withPayload({})), withSecurityConfig(withPayload({ headers: async () => [own] })), withSecurityConfig(withPayload({ poweredByHeader: false }))]) {
const rules = await rulesOf(config)
expect(rules.filter((r) => !r.headers.length)).toEqual([])
expect(hinted(rules)).toEqual(['/admin/:path*'])
}
expect((await rulesOf(withSecurityConfig(withPayload({})))).map((r) => r.source)).toEqual(['/admin/:path*'])
})
test('inside withPayload it cannot see the rule: behaviour as before the change (an old site is not broken)', async () => {
const rules = await rulesOf(withPayload(withSecurityConfig({ headers: async () => [own] })))
expect(hinted(rules)).toEqual(['/:path*'])
expect(rules.flatMap((r) => r.headers.map((h) => h.key.toLowerCase()))).not.toContain('x-powered-by')
})
test('route: a changed routes.admin; sources: more paths', async () => {
expect(hinted(await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: { route: '/panel' } })))).toEqual(['/panel/:path*'])
expect(hinted(await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: { route: 'cms/', sources: ['/preview/:path*'] } })))).toEqual(['/cms/:path*', '/preview/:path*'])
expect(adminClientHintSources()).toEqual(['/admin/:path*'])
// an admin at the root: every path IS the admin, the rule stays
expect(adminClientHintSources('/')).toEqual(['/:path*'])
expect(hinted(await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: { route: '/' } })))).toEqual(['/:path*'])
})
test('adminClientHints: false restores the old behaviour; hidePoweredBy is independent', async () => {
const kept = await rulesOf(withSecurityConfig(withPayload({}), { adminClientHints: false }))
expect(hinted(kept)).toEqual(['/:path*'])
expect(kept.flatMap((r) => r.headers.map((h) => h.key))).not.toContain('X-Powered-By')
const both = await rulesOf(withSecurityConfig(withPayload({}), { hidePoweredBy: false }))
expect(hinted(both)).toEqual(['/admin/:path*'])
expect(both.flatMap((r) => r.headers.map((h) => h.key))).toContain('X-Powered-By')
const config = withPayload({})
expect(withSecurityConfig(config, { adminClientHints: false, hidePoweredBy: false })).toBe(config)
})
test('scopeColorSchemeClientHints: other tokens stay, rule options are carried, narrower rules are left alone', () => {
const rules = scopeColorSchemeClientHints([
{ basePath: false, has: [{ type: 'header', key: 'x' }], headers: [
{ key: 'accept-ch', value: 'Sec-CH-UA, sec-ch-prefers-color-scheme' },
{ key: 'Vary', value: 'RSC, Sec-CH-Prefers-Color-Scheme, Accept' },
{ key: 'Critical-CH', value: 'Sec-CH-Prefers-Color-Scheme' },
{ key: 'X-A', value: '1' },
], source: '/(.*)' },
{ headers: [{ key: 'Accept-CH', value: 'Sec-CH-Prefers-Color-Scheme' }], source: '/shop/:path*' },
{ headers: [{ key: 'Vary', value: 'Accept-Encoding' }], source: '/:path*' },
])
expect(rules).toEqual([
{ basePath: false, has: [{ type: 'header', key: 'x' }], headers: [
{ key: 'accept-ch', value: 'Sec-CH-UA' },
{ key: 'Vary', value: 'RSC, Accept' },
{ key: 'X-A', value: '1' },
], source: '/(.*)' },
{ headers: [{ key: 'Accept-CH', value: 'Sec-CH-Prefers-Color-Scheme' }], source: '/shop/:path*' },
{ headers: [{ key: 'Vary', value: 'Accept-Encoding' }], source: '/:path*' },
{ basePath: false, has: [{ type: 'header', key: 'x' }], headers: [
{ key: 'accept-ch', value: 'Sec-CH-UA, sec-ch-prefers-color-scheme' },
{ key: 'Vary', value: 'RSC, Sec-CH-Prefers-Color-Scheme, Accept' },
{ key: 'Critical-CH', value: 'Sec-CH-Prefers-Color-Scheme' },
], source: '/admin/:path*' },
])
expect(header(rules.at(-1) as Rule, 'x-a')).toBeUndefined()
})
})
describe('buildCsp', () => {
test('mode picks the header; report-only first, enforce with one option', () => {
expect(buildCsp({ mode: 'report-only' }).key).toBe('Content-Security-Policy-Report-Only')