From 9143c132a31cc5d11fded798c4f65bc697904ef0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 11:55:26 +0100 Subject: [PATCH] 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 --- docs/CHANGELOG.md | 20 +++ docs/agent/AGENT.md | 13 +- docs/agent/skills/iapl-audit/SKILL.md | 6 +- docs/agent/skills/iapl-audit/scripts/audit.sh | 2 +- docs/agent/skills/iapl-reference/SKILL.md | 2 +- .../skills/iapl-reference/resources/api.md | 3 +- docs/agent/skills/iapl-setup/SKILL.md | 9 +- docs/agent/skills/iapl-upgrade/SKILL.md | 21 ++- docs/dev/PROGRAMISTA.md | 6 +- docs/doctor.md | 1 + docs/security.md | 58 +++++++- reference/.agents/skills/iapl-audit/SKILL.md | 6 +- .../skills/iapl-audit/scripts/audit.sh | 2 +- .../.agents/skills/iapl-reference/SKILL.md | 2 +- .../skills/iapl-reference/resources/api.md | 3 +- reference/.agents/skills/iapl-setup/SKILL.md | 9 +- .../.agents/skills/iapl-upgrade/SKILL.md | 21 ++- reference/README.md | 3 +- reference/e2e/smoke.spec.ts | 71 ++++++++++ reference/next.config.ts | 5 +- scripts/e2e-built.mjs | 5 +- scripts/starter-gate.mjs | 2 + src/index.ts | 3 + src/modules/doctor/rules/security.ts | 23 ++- src/modules/security/index.ts | 4 +- src/modules/security/withSecurityConfig.ts | 131 +++++++++++++++--- test/doctor.test.ts | 30 ++++ test/security.test.ts | 98 +++++++++++++ 28 files changed, 500 insertions(+), 59 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 94a952f..8b4a52f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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 /pl | grep -i critical-ch` prints nothing, `/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 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 2039b7d..4c3ed8b 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -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 `` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `iapl`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P | | 11 | **Turnstile** | `` 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'` (`` — 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) + `}>` (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 `` 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 `` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md | | Enlarge an image (card, gallery, product, rich text) | `` + `` (`/client`), `RenderRichText lightbox`, `useLightbox`; labels: `iapl({ lightbox: true })` → Form messages → Image viewer | lightbox.md | | YouTube without cookies before a click | `` (`/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 })` + `` (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 (`` 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', } })`, 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 `` 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 | diff --git a/docs/agent/skills/iapl-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md index 015a7f8..f4eef8c 100644 --- a/docs/agent/skills/iapl-audit/SKILL.md +++ b/docs/agent/skills/iapl-audit/SKILL.md @@ -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`). diff --git a/docs/agent/skills/iapl-audit/scripts/audit.sh b/docs/agent/skills/iapl-audit/scripts/audit.sh index d95976a..fd2f3e8 100644 --- a/docs/agent/skills/iapl-audit/scripts/audit.sh +++ b/docs/agent/skills/iapl-audit/scripts/audit.sh @@ -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" " (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 187cdde..11ab28a 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -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 `_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, }` 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)`; `} theme stats>` | HTML: `