From ff4c595b918a217f33b7b5b69f2bbf9c56a8e845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 27 Oct 2026 21:28:11 +0100 Subject: [PATCH] Security: hide X-Powered-By, CSP report-only with reports, admin policy and nonces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - withSecurityConfig: poweredByHeader false + strips X-Powered-By from headers() (Next's and withPayload's), works on either side of withPayload - buildSecurityHeaders({ csp }): CSP + Reporting-Endpoints; mode switches report-only → enforce - buildCsp: reportUri/reportGroup, nonce + strict-dynamic, dev unsafe-eval, metaPixel/linkedIn/tiktok/clarity flags, media-src for R2, override - buildAdminCsp(Headers): looser policy for Payload admin (Monaco CDN, blob workers) - createCspReportRoute + parseCspReports: report collector for both formats - createProxy({ csp }) + createCspNonce: per-request nonce, x-nonce header; SiteProviders/ThemeScript/Analytics/ConsentScript accept nonce - docs: security.md, AGENT.md, ipal-setup/reference/upgrade; ipal-audit checks Co-Authored-By: Claude Opus 5.5 --- docs/agent/AGENT.md | 21 +- docs/agent/skills/ipal-audit/SKILL.md | 11 +- docs/agent/skills/ipal-audit/scripts/audit.sh | 2 + docs/agent/skills/ipal-reference/SKILL.md | 4 +- .../skills/ipal-reference/resources/api.md | 17 +- docs/agent/skills/ipal-setup/SKILL.md | 33 +- docs/agent/skills/ipal-upgrade/SKILL.md | 16 + docs/security.md | 295 +++++++++++------- src/exports/next-middleware.ts | 1 + src/index.ts | 28 +- src/modules/analytics/Analytics.tsx | 13 +- src/modules/consent/ConsentScript.tsx | 10 +- src/modules/frontend/SiteProviders.tsx | 11 +- src/modules/i18n/createProxy.ts | 31 +- src/modules/security/buildCsp.ts | 257 +++++++++++++-- src/modules/security/buildSecurityHeaders.ts | 30 +- src/modules/security/createCspReportRoute.ts | 121 +++++++ src/modules/security/cspNonce.ts | 10 + src/modules/security/index.ts | 19 +- src/modules/security/withSecurityConfig.ts | 55 ++++ src/modules/theme/ThemeScript.tsx | 10 +- test/security.test.ts | 250 +++++++++++++++ 22 files changed, 1059 insertions(+), 186 deletions(-) create mode 100644 src/modules/security/createCspReportRoute.ts create mode 100644 src/modules/security/cspNonce.ts create mode 100644 src/modules/security/withSecurityConfig.ts create mode 100644 test/security.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index d7a5bdd..1f0e40f 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -109,7 +109,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2. | 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `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"; `ipalKit({ 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** → the editor accepts; or cookie-scan → import) — feeds `` on the policy page **and** the lists in the `detailed` window; Cookie banner → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` | -| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` in production | security.md, forms.md | A | +| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }`; `IPAL_IP_HEADER` in production | security.md, forms.md | A | | 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A | | 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P | | 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P | @@ -146,7 +146,7 @@ In the project's `AGENTS.md`, under "Project decisions", one line with the item ipal-audit-skip: mcp, llms-full — the client does not want to share content with AI agents (email 2026-03-02) ``` Keys: `llms`, `llms-full`, `markdown`, `mcp`, `jsonld`, `r2`, `turnstile`, -`analytics`, `twofactor`, `aibots`, `forms-seed` (`audit.sh` understands only these). Without this line a missing item is an error. +`analytics`, `twofactor`, `aibots`, `forms-seed`, `csp` (`audit.sh` understands only these). Without this line a missing item is an error. --- @@ -937,7 +937,8 @@ project → **plugin gap**, not a copy. | Image / video in `` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md | | Enlarge an image (card, gallery, product, rich text) | `` + `` (`/client`), `RenderRichText lightbox`, `useLightbox`; labels: `ipalKit({ lightbox: true })` → Form messages → Image viewer | lightbox.md | | YouTube without cookies before a click | `` (`/client`) | storage.md | -| `next.config` | `buildImagesConfig`, `buildSecurityHeaders`, `buildCsp`, `buildUploadSecurityHeaders` | storage.md, security.md | +| `next.config` | `buildImagesConfig`, `buildSecurityHeaders` (`csp`), `buildCsp`, `buildCspHeaders`, `buildAdminCsp` / `buildAdminCspHeaders`, `buildUploadSecurityHeaders`, `withSecurityConfig` (hides `X-Powered-By`) | storage.md, security.md | +| CSP reports, nonces | `createCspReportRoute` (`parseCspReports`, type `CspViolation`), `createProxy({ csp })` + `` (dynamic pages only), `createCspNonce`, `CSP_NONCE_HEADER`, `buildReportingEndpoints`, `cspHeaderKey`, `DEFAULT_CSP_REPORT_GROUP`; types `BuildAdminCspArgs`, `CspDirective`, `CspSources`, `CreateCspReportRouteArgs`, `WithSecurityConfigOptions` | security.md | | Fluid typography and spacing | `fluid.css` / `fluid-wide.css` (`--ipal-*` variables) | PROGRAMISTA §2.5 | **Consent, analytics, operations** @@ -962,8 +963,16 @@ table from the panel (`` and the `settings="detailed"` window, scan requires it (accessibility.md). **Security:** 2FA enforced (`ipalKit({ twoFactor: { issuer, plugin: -payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: first -`report-only`, then `enforce`; no Trusted Types (they break Turnstile/GA). +payloadTotp } })`, never `twoFactor: false` without a client decision). No `X-Powered-By`: +`withPayload(withSecurityConfig(nextConfig))`. CSP in three steps (security.md → "ROLL OUT CSP"): +(1) `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', } })`, the admin rule `{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: +'report-only', reportUri }) }` AFTER the site-wide one, and `export const POST = createCspReportRoute()` in +`src/app/api/csp-report/route.ts`; (2) deploy, read the console and the `[csp]` lines in the Coolify logs, +add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both places. Check: +`curl -sI $U/pl | grep -iE 'content-security|x-powered-by'`. ISR/SSG sites keep the header policy (with +`'unsafe-inline'` — Next's inline RSC scripts cannot be hashed); nonces (`createProxy({ csp })` + +``) only on sites whose pages already render per request. No Trusted Types (they break Turnstile/GA). ### 7.1 Newer defaults — turn off / override (the plugin helps, never limits) @@ -983,6 +992,8 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir | Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev | | Consent Mode `advanced` | `consentMode: 'basic'` | your own `` props (`SiteProviders analytics={false}`) | | Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` | +| No `X-Powered-By` (with `withSecurityConfig`) | `withSecurityConfig(config, { hidePoweredBy: false })` | — | +| CSP off until `buildSecurityHeaders({ csp })`; then hard rules, `'unsafe-eval'` only in dev | leave out `csp` | `buildCsp({ extra, override, strictDynamic, dev })`, `buildAdminCsp({ extra, override })`, `createCspReportRoute({ onReport, maxBytes })`, your own string via `additional` | | Construction mode hides pages in Markdown, MCP | `markdown: { isPathVisible: () => true }`, `mcp: { isPathVisible: () => true }` | `isPathVisible`, `isPathVisibleIn(mode, path)`, `pathOf(url)`, type `PathVisibility` | | Construction mode filters the sitemap and llms.txt | `underConstructionSeo: false` | `include` / `getIncludedPaths` in the low-level builders | | `getSettings` at `depth: 1` | — | `createContentHelpers({ settingsDepth: 2 })` (every request pays) | diff --git a/docs/agent/skills/ipal-audit/SKILL.md b/docs/agent/skills/ipal-audit/SKILL.md index b360e17..5493147 100644 --- a/docs/agent/skills/ipal-audit/SKILL.md +++ b/docs/agent/skills/ipal-audit/SKILL.md @@ -1,6 +1,6 @@ --- name: ipal-audit -description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project. +description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env, security headers, X-Powered-By, CSP), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project. --- # ipal-audit @@ -38,5 +38,14 @@ in AGENT.md §0b). Never add that line yourself just to make the audit pass. google-analytics / googletagmanager (except Consent Mode), facebook.net, clarity.ms, licdn, tiktok. - **Content**: fallbacks contain no client data (`|| 'Firma X'`). +- **Response headers** (on a running build — `pnpm build && pnpm start`, or the deployed domain): + ```bash + U=http://localhost:3000 + for p in /pl /admin /api/health; do echo "== $p"; curl -sI "$U$p" | grep -iE 'x-powered-by|content-security-policy'; done + ``` + `x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). No + `content-security-policy` / `content-security-policy-report-only` on `/pl` and `/admin` → WARNING (CSP not + rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`). + Then open `/pl` and `/admin` in the browser: CSP lines in the console = missing sources (flags / `extra`). Do not say "done" until the full audit (without `--quick`) has no errors. diff --git a/docs/agent/skills/ipal-audit/scripts/audit.sh b/docs/agent/skills/ipal-audit/scripts/audit.sh index 1fa2ba1..6c103b3 100644 --- a/docs/agent/skills/ipal-audit/scripts/audit.sh +++ b/docs/agent/skills/ipal-audit/scripts/audit.sh @@ -261,6 +261,8 @@ if [ -n "$APP" ]; then need ERROR '' "health route" "src/app/api/health/route.ts → export { healthRoute as GET } from '@/lib/content'" 'healthRoute|createHealthRoute' src/app need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js + need WARNING '' "X-Powered-By hidden" "next.config.ts → export default withPayload(withSecurityConfig(nextConfig)) — Next and withPayload send X-Powered-By: Next.js, Payload (security.md)" 'withSecurityConfig|poweredByHeader: *false' next.config.ts next.config.mjs next.config.js + need WARNING csp "Content-Security-Policy" "next.config.ts → buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } }) + buildAdminCspHeaders on /admin/:path*, then 'enforce' (security.md → ROLL OUT CSP)" "csp: *\\{|csp,|buildCsp|Content-Security-Policy" next.config.ts next.config.mjs next.config.js src/proxy.ts proxy.ts # Consent, analytics, Turnstile (layout) need ERROR '' "cookie consent" " (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app need ERROR analytics "analytics" " (loads Analytics) or inside ConsentProvider" 'SiteProviders| [{ source: '/:path*', headers: buildSecurityHeaders({ hsts }) }, ...buildUploadSecurityHeaders()] })` | `curl -sI $U/pl \| grep -i 'x-content-type\|strict-transport'` | security.md, storage.md, PROGRAMISTA §2.9 | -| CSP | `next.config.ts` | `buildCsp({ mode: 'report-only', … })` → later `enforce` | browser console without violations | security.md | +| Next config | `next.config.ts` | `withPayload(withSecurityConfig({ images: buildImagesConfig(), htmlLimitedBots: /Googlebot\|Bingbot…/i, headers: async () => [{ source: '/:path*', headers: buildSecurityHeaders({ hsts, csp }) }, { source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, ...buildUploadSecurityHeaders()] }))` | `curl -sI $U/pl \| grep -iE 'x-content-type\|strict-transport\|x-powered-by'` (no `x-powered-by`) | security.md, storage.md, PROGRAMISTA §2.9 | +| CSP | `next.config.ts`, `src/app/api/csp-report/route.ts` | `csp = { mode: 'report-only', reportUri: '/api/csp-report', r2Url, }` 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: `