diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8b4a52f..404d76f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -228,6 +228,22 @@ once there are more than 20. upgrade. Run `pnpm exec iapl-skills` and commit in the same change as the version bump. ### Changed +- **The cookie banner is part of the first render** ([consent.md → First paint](./consent.md#first-paint-the-banner-is-part-of-the-first-render-1170)). + Until now `` rendered nothing until the page had hydrated, so on a first visit its text appeared late + and on a text page became the LCP element (reference site, mobile profile, 4x CPU, slow 4G: page painted at 1.0 s, + banner and LCP at 2.7 s; now banner and LCP at 1.0 s; CLS unchanged). The banner is now in the server HTML with + `hidden`, followed by one small inline script that, before the browser paints, shows it (no decision, an older + Policy version, an unreadable cookie) or keeps it hidden (current decision). **An existing site gets this by + updating, with no edit; public pages stay static / ISR.** Nothing about consent changes: no tag loads earlier, the + Consent Mode default is still pushed first, the cookie, the consent log and withdrawal are as before. A click on a + banner button before hydration is carried out once the page is live. + **What an existing site may notice:** the page's HTML is about 3 kB larger, 1.2 kB gzipped (the banner's markup and the script; the detailed cookie + list is not in it); `[data-ipal="banner"]` exists in the DOM (hidden) for a returning visitor until hydration — a + project e2e test that counts the element right after load should assert `toBeHidden()`; with a **nonce CSP** the + script needs the nonce — `` passes it (without it the banner appears after hydration, as + before); with **Tailwind 3** and a `classNames.root` that sets `display`, add + `[data-ipal="banner"][hidden] { display: none !important }`. Old behaviour: ``. + `CookieButton` and `useConsent` read the decision through a store (`useSyncExternalStore`) instead of an effect. - **New names beside the old ones** (the old ones are deprecated and go in 2.0): `iapl()` for `ipalKit()`, `IaplOptions`, `iaplEnvRules`, `IaplEnvFeatures`, `iaplT`, `iaplVar`, `IAPL_TOKENS`, `IAPL_BREAKPOINTS`, `IaplTokenName`, `IaplGlobalSlug`; commands `iapl`, `iapl-doctor`, `iapl-skills`, `iapl-tokens`, @@ -260,6 +276,10 @@ once there are more than 20. `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"). +- Consent, first paint: `CookieBanner` props `firstPaint` (default `true`) and `nonce`; `ConsentProvider` props `nonce` + and `cookieValue`, `SiteProviders` prop `consentCookie` (optional server read of the consent cookie: no banner in the + HTML of a visitor who decided, at the price of dynamic pages); `consentBannerScript({ version, cookieName })` from the + root for a project's own banner; `useConsent` / `useConsentContext` also return `hydrated` and `serverRead`. - **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 4c3ed8b..fb34444 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -246,7 +246,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2. | 9 | **Media / R2 / speed** | `Media` with `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + field; **always** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` in `.env.example`; ``; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `` via `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S | | 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` | +| 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; the banner is in the server HTML and painted with the page — pages stay static, an inline script decides before the first paint; with a nonce CSP pass `nonce` to `SiteProviders`; never wrap the banner in a "mounted" guard or `dynamic(…, { ssr: false })`, never read the consent cookie in the layout unless the site is dynamic anyway: `consentCookie`, consent.md → "First paint"); 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`; `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 | @@ -1160,6 +1160,7 @@ project → **plugin gap**, not a copy. | Need | Use | Doc | |---|---|---| | Banner, settings, cookie button | `}>`, `CookieButton`, `useConsent` | consent.md | +| Banner at first paint (not after hydration; LCP) | built in: `CookieBanner firstPaint` (default on), `SiteProviders nonce` under a nonce CSP; off: `firstPaint={false}`; server-exact HTML on a dynamic site: `SiteProviders consentCookie` / `ConsentProvider cookieValue`; your own banner: `consentBannerScript`. Check: `curl -s \| grep -c 'data-ipal="banner-script"'` → 1 and the response still has `s-maxage` | consent.md → "First paint" | | Settings window: in the bar / small / large with cookie details | `` — do not build your own window or cookie list | consent.md → "Large window with details" | | A consent-dependent script | `ConsentScript` | consent.md | | Cookie table on the policy page | `` (`/rsc`), `getCookieTable` | consent.md | diff --git a/docs/agent/skills/iapl-consent-check/SKILL.md b/docs/agent/skills/iapl-consent-check/SKILL.md index fa75eb3..9ba0caf 100644 --- a/docs/agent/skills/iapl-consent-check/SKILL.md +++ b/docs/agent/skills/iapl-consent-check/SKILL.md @@ -38,6 +38,18 @@ before analytics or marketing consent — check the project's choice in "Project 5. Banner not found (`data-ipal="banner"`) → `` is not rendered, or an older IAPL version without `data-ipal` attributes on the buttons → **iapl-upgrade**. +6. Banner at first paint (1.17.0, consent.md → "First paint"): the banner is in the server HTML and an inline + script shows or hides it before the browser paints; pages stay static. + ```bash + curl -s http://localhost:3000/pl | grep -c 'data-ipal="banner-script"' # 1 + curl -sI http://localhost:3000/pl | grep -i cache-control # still s-maxage=… (static / ISR) + ``` + `0` → `firstPaint={false}`, a custom banner, or a wrapper that renders the banner only after mount + (remove it). Under a nonce CSP the browser console must not report the inline script as refused: pass + `nonce` to ``. A visitor who decided must never see the banner on reload; one whose + decision is from an older Policy version must see it at once. A click on a button before hydration + counts (the checks above click as soon as the button is visible). + The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's `CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7. diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index a068095..064c5f3 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -89,6 +89,8 @@ through this procedure. Ask only when you are missing something you cannot get y | canonical / sitemap with localhost | `NEXT_PUBLIC_SERVER_URL` not set in the build | set it in the build env (not only at runtime) | | `/admin`, `/_next` → 500 or a loop | the proxy matcher is not a literal | inline matcher in `proxy.ts` | | hydration mismatch on the banner | reading cookie/`window` during render | consent only through `CookieBanner`/`useConsentContext`; `Date`, `Math.random` outside render | +| banner appears late (after hydration), is the LCP element | `firstPaint={false}`; IAPL older than 1.17.0; a nonce CSP without `` (console: the inline script was refused); a custom `classNames.root` is fine | consent.md → "First paint"; check: `curl -s \| grep -c 'data-ipal="banner-script"'` → 1 | +| banner flashes for a visitor who already decided | the first-paint script was refused (nonce) and `classNames.root` sets `display` over `[hidden]` (Tailwind 3) | pass the nonce; add `[data-ipal="banner"][hidden] { display: none !important }` | | images do not load (R2) | media domain missing in `images.remotePatterns` / wrong `R2_PUBLIC_URL`; without `R2_PUBLIC_URL`: Media has no `access.read: () => true` → 403 on `/api/media/file/…` | `next.config.ts` + env, or Media access (storage.md) | | 404 page without styles/nav | `not-found.tsx` outside `[locale]` without a layout | pages.md — `not-found` example | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 8a1556d..f5f5429 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -161,14 +161,15 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant | Export | Import from | What it does / when | |---|---|---| -| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint? }` — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. | -| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`; colours from `--ipal-*` CSS vars. Do not write your own banner. | +| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint?, nonce?, cookieValue? }` (`nonce`: CSP nonce for the banner's first-paint script; `cookieValue`: optional server-read consent cookie → exact HTML, dynamic pages) — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. | +| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`, `firstPaint` (default `true`: in the server HTML, decided before the first paint by an inline script; pages stay static), `nonce`; colours from `--ipal-*` CSS vars. Do not write your own banner. | | `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Props `className`, `side` (`'left' \| 'right'`), `avoid` (selector it lifts above, default `COOKIE_BUTTON_AVOID` = footer; `false`). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. | | `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Default footer selector; pixels the footer covers at the bottom of the screen (how far the button moves up) | | `TOTP_TEXTS`, `TOTP_VIEW_TITLE` | `@intecion/ipal-kit` | en/pl texts of the 2FA screens (`totpPlugin:*`, merged by `twoFactor`) and their tab title | | `ConsentScript` | `@intecion/ipal-kit/client` | Loads an external script (`src` or `code`) only after consent for `category` — for vendors without Consent Mode (chat, Plausible etc.). Inside `ConsentProvider`. | | `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: cookie table for the cookie policy page — `{ rows, labels?, locale?, categories?, caption?, classNames?, storageColumn?, storageTypes? }`; `rows` from `getCookieTable()`; a **Type** column when a row is local / session storage (`storageColumn: 'auto' \| boolean`). | -| `useConsent(options?)` | `@intecion/ipal-kit/client` | Low-level consent state hook → `{ state, decided, consentId, acceptAll, rejectAll, savePreferences, reopen }`. Usually use `ConsentProvider` + `useConsentContext` (the provider calls it itself). | +| `useConsent(options?)` | `@intecion/ipal-kit/client` | Low-level consent state hook → `{ state, decided, consentId, hydrated, serverRead, acceptAll, rejectAll, savePreferences, reopen }` (options: `cookieMap`, `version`, `onDecision`, `cookieValue`). Usually use `ConsentProvider` + `useConsentContext` (the provider calls it itself). | +| `consentBannerScript({ version?, cookieName? })` | `@intecion/ipal-kit` | The inline script `CookieBanner` puts after its markup: before the first paint it removes `hidden` from the banner (no current decision) or sets `display: none` (current decision), and keeps a click made before hydration. For a project's own banner; reads only the consent cookie. Options type: `ConsentBannerScriptOptions`. consent.md → "First paint". | | `useConsentContext()` | `@intecion/ipal-kit/client` | Hook: the `useConsent` value + `texts` from `ConsentProvider` — for your own consent-dependent UI (e.g. `state.marketing`). Throws outside the provider. | | `getConsentTexts({ payload, config, locale?, privacyPolicy?, settingsSlug? })` | `@intecion/ipal-kit` | Server: banner texts from the CookieSettings global (EN fallback per field) + privacy policy link from the system pages → `Promise`; pass to `ConsentProvider texts`. | | `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Server: Cookies → Cookie list rows in one language → `Promise` (does not throw) — for `CookieTable`. | diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index 2428736..958395a 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -452,6 +452,7 @@ and `rel="alternate" type="text/markdown"`; `/pl/nie-ma-takiej` → 404 with con - `createPageRoute`: `render` (your own view, e.g. an archive), `onMissing: 'redirectHome'`, `jsonLd: false`, `homeAlias: false`, `layoutField`; a fully custom page on `resolveRoute` (pages.md). `generateStaticParams` covers **only the pages collection, up to 1000 per language** — the scope is currently fixed (entries → ISR). +- The cookie banner is in the server HTML and painted with the page; pages stay static (consent.md → "First paint"). Do not wrap it in a "mounted" guard. Off: `banner={}`; nonce CSP: `nonce` on `SiteProviders`; a dynamic site may pass `consentCookie` for server-exact HTML. - `SiteProviders`: `banner={false}` / your own, `cookieButton={false}`, `analytics={false}` / `{{ defer: true }}`, `preconnect={false}`, `jsonLd={[…]}` (adds), `cookieMap`, `theme`, `stats`; `JsonLdGraph` and `TurnstileProvider` currently always (Turnstile turns itself off without keys). A fully custom layout: providers from `/client` diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index f3082a0..0a913e8 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -566,6 +566,20 @@ PROGRAMISTA §6, item 76; security.md "Client hints") — one line, recommended **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, cookie banner at first paint (CHANGELOG 1.17.0 "Changed"; PROGRAMISTA §6, item 77; consent.md → "First paint") — nothing is required:** +The banner is now in the server HTML and painted with the page (it appeared after hydration and could be the LCP +element). Pages stay static; consent, tags, the cookie and the consent log are unchanged. +1. Remove a project wrapper that delays the banner (`ConsentWrapper`, a "mounted" guard, `dynamic(…, { ssr: false })`) + — it undoes the improvement. +2. Nonce CSP (`createProxy({ csp })`): `` must be set (it already is where the theme + script works); by hand: ``. Without it the banner appears after hydration, as before. +3. Tailwind 3, or CSS of your own, with `classNames.root` that sets `display`: add + `[data-ipal="banner"][hidden] { display: none !important }`. +4. E2E tests of the project that expect **no** `[data-ipal="banner"]` element before a decision is read (e.g. + `toHaveCount(0)` right after `goto` for a returning visitor) must wait for hydration or assert `toBeHidden()`. +5. Keep the old behaviour: ``. +**Check:** `curl -s | grep -c 'data-ipal="banner-script"'` → 1; the response still carries `s-maxage`; first +visit: the banner is there before the page's scripts have loaded; after a decision and a reload: never shown. **→ 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:** diff --git a/docs/consent.md b/docs/consent.md index cfcda48..1c0ce94 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -82,9 +82,11 @@ export default async function Layout({ children, params }) { `ConsentProvider` — props: `texts` (required, `ConsentTexts` from `getConsentTexts`), `cookieMap` (extra cookies to delete on withdrawal), `logEndpoint` -(consent log). `CookieBanner` does not render after a decision, `CookieButton` — -the opposite (it shows only after a decision and reopens the banner); both -render only after mounting on the client. +(consent log), `nonce` (CSP nonce for the banner's first-paint script), `cookieValue` (optional +server-read cookie — [First paint](#first-paint-the-banner-is-part-of-the-first-render-1170)). +`CookieBanner` does not render after a decision, `CookieButton` — +the opposite (it shows only after a decision and reopens the banner). Since 1.17.0 the banner is in +the server HTML and painted with the page, not after hydration (next section). Built-in banner texts follow the page language: `consentFallback(locale)` → `CONSENT_FALLBACK_PL` on `pl`, `CONSENT_FALLBACK` (English) otherwise; panel values always win. Category names for your own selects: @@ -99,6 +101,8 @@ takes `locale` and optional `labels`; defaults: `COOKIE_TABLE_LABELS` (`@intecio |---|---|---| | `classNames` | — | slots (table below) — a given one replaces the default | | `equalChoice` | `false` | "Reject" styled as the primary button | +| `firstPaint` | `true` | banner in the server HTML, decided before the first paint; `false` = nothing until the page has hydrated (as before 1.17.0) | +| `nonce` | provider's | CSP nonce for the first-paint script; default: the one given to `ConsentProvider` / `SiteProviders` | | `icon` | `true` | cookie icon | | `order` | `['settings', 'reject', 'accept']` | banner buttons | | `settings` | `'inline'` | `'inline' \| 'modal' \| 'detailed'` | @@ -112,6 +116,78 @@ moves up by its visible part (`bottomOverlap`), so it never covers footer links. `--ipal-cookie-button-offset` (from the bottom, default `1rem`), `--ipal-cookie-button-inset` (from the side, default `1rem`); z-index `--ipal-z-header`. Type `CookieButtonProps`. +## First paint: the banner is part of the first render (1.17.0) + +Before 1.17.0 the banner rendered nothing until React had hydrated the page and an effect had read the +cookie. On a first visit its text appeared seconds after the page (measured on the reference site, +mobile profile with 4x CPU and slow 4G: page painted at 1.0 s, banner at 2.7 s) and on a text page it +became the **LCP element**. Now it is in the HTML and painted with the page (banner at 1.0 s, LCP 1.0 s). +An existing site gets this by updating: no edit, pages stay static. + +**How (default, pages stay static / ISR / CDN-cached).** The HTML is the same for every visitor, so it +cannot know the visitor's cookie. The server renders the banner with the `hidden` attribute and, right +after it, one small inline script (`consentBannerScript`, about 0.6 kB). The script runs while the HTML is +parsed, before the browser paints: + +| Visitor | Before the first paint | After hydration | +|---|---|---| +| no decision; decision under an older **Policy version**; unreadable or foreign `cookie-consent` | `hidden` removed → banner painted with the page | the same element becomes live (no re-render, no shift: the bar is `position: fixed`) | +| current decision | `display: none` on the banner → never painted | React removes it; `CookieButton` appears | +| JavaScript off, or a CSP refused the script | banner stays hidden | with JS: appears after hydration, as before 1.17.0; without JS: no banner (and no tag: every tag is loaded by JS) | + +The script decides exactly as `readConsentRecord` does, reads only the consent cookie, stores nothing and +loads nothing. A click on a banner button **before** hydration is not lost: the script notes the button +(`data-ipal-pending`), and the banner carries the click out when it becomes live (the decision, the cookie +and the consent log entry are made then, by the same code as any click). There is no hydration warning: +React hydrates with "no decision" (what the server rendered) and switches to the browser's own value +before the next paint (`useSyncExternalStore`). + +What does **not** change: what counts as consent, when tags load (nothing earlier), the Consent Mode +default (still pushed first), the cookie (`cookie-consent`, `{ id, state, timestamp, version }`), the +consent log, withdrawal, `CookieButton`, the settings window in all three modes, texts per language. + +**CSP.** With the header-only policy (`buildSecurityHeaders`, `'unsafe-inline'` for scripts — what +static pages need anyway) nothing is to be done. With a nonce policy (`createProxy({ csp })`) the script +needs the nonce: `` passes it on (a site that already passes `nonce` for the +theme script is done); by hand: `` or ``. +Without the nonce the script is refused and the banner appears after hydration, as before. + +**Your own `classNames.root`.** The banner is hidden with the `hidden` attribute. Tailwind 4 makes +`[hidden]` win over every utility; with Tailwind 3 (or other CSS) a root class that sets `display` +(`flex`, `grid`) overrides it: add `[data-ipal="banner"][hidden] { display: none !important }` to the +site's CSS. + +**Turn it off:** `` — nothing in the HTML, the banner appears after +hydration (before 1.17.0). + +**Option: read the cookie on the server (exact HTML, dynamic pages).** Pass the request's cookie and the +server render already knows the decision — no banner in the HTML for a visitor who decided (the +`CookieButton` instead), the banner without `hidden` and without a script for one who has not: + +```tsx +import { CONSENT_COOKIE } from '@intecion/ipal-kit' +import { cookies } from 'next/headers' + +const consentCookie = (await cookies()).get(CONSENT_COOKIE)?.value ?? null // null = read, none sent +… // by hand: +``` + +The price: `cookies()` makes every page under that layout **dynamic** — rendered per request, no static +or ISR copy, and a CDN must not share one HTML between visitors. Choose it only for a site that is +dynamic anyway (a nonce CSP, signed-in pages). `undefined` (the prop left out) = static mode. + +| | Static (default) | Server read (`consentCookie`) | +|---|---|---| +| Public pages | static / ISR, one HTML for all, CDN-cacheable | dynamic, per request | +| Banner in the HTML of a visitor who decided | yes, hidden before paint | no | +| Inline script | one (needs the nonce under a nonce CSP) | none | +| Banner at first paint for a new visitor | yes | yes | + +**Your own banner** (AGENT.md §7 says: don't; when you must): `consentBannerScript({ version })` from +`@intecion/ipal-kit` (options: `ConsentBannerScriptOptions` — `version`, `cookieName`) is the same script — put `hidden` and `suppressHydrationWarning` on your banner's root and +the script in a ``, no line separators + const name = JSON.stringify(`${cookieName}=`) + .replace(/ to carry out + `b.addEventListener("click",function(e){if(b.hasAttribute("${BANNER_READY_ATTRIBUTE}")){return}` + + `var t=e.target,a=t&&t.closest?t.closest("[data-ipal]"):null;if(a&&a!==b){b.setAttribute("${BANNER_PENDING_ATTRIBUTE}",a.getAttribute("data-ipal"))}})}` + + `}catch(e){}})()` + ) +} diff --git a/src/modules/consent/index.ts b/src/modules/consent/index.ts index 05064e3..b544cd6 100644 --- a/src/modules/consent/index.ts +++ b/src/modules/consent/index.ts @@ -11,6 +11,8 @@ export type { ConsentCategory, ConsentState } from './categories.js' export { CONSENT_CATEGORY_LABELS, consentCategoryOptions } from './categoryLabels.js' export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './consentLog.js' export type { ConsentLogOptions } from './consentLog.js' +export { consentBannerScript } from './firstPaint.js' +export type { ConsentBannerScriptOptions } from './firstPaint.js' export { CONSENT_FALLBACK, CONSENT_FALLBACK_PL, consentFallback, getConsentTexts, getCookieTable } from './getConsentTexts.js' export type { CookieTableRow } from './getConsentTexts.js' export { setDefaultConsent, updateConsent } from './googleConsent.js' diff --git a/src/modules/consent/useConsent.ts b/src/modules/consent/useConsent.ts index 4d41269..73b8329 100644 --- a/src/modules/consent/useConsent.ts +++ b/src/modules/consent/useConsent.ts @@ -1,12 +1,13 @@ 'use client' -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useMemo, useState, useSyncExternalStore } from 'react' import type { ConsentCategory, ConsentState } from './categories.js' import { LOCALE_COOKIE_NAME } from '../i18n/index.js' import { ACCEPT_ALL_CONSENT, DEFAULT_CONSENT, REJECT_ALL_CONSENT } from './categories.js' +import { getConsentSnapshot, subscribeConsent, writeConsentCookie } from './consentStore.js' import { updateConsent } from './googleConsent.js' -import { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js' +import { CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js' export type ConsentCookieMap = Partial> @@ -52,6 +53,13 @@ function deleteCookie(name: string) { type UseConsentOptions = { /** Extra cookies per category to delete on withdrawal — merged with DEFAULT_COOKIE_MAP. */ cookieMap?: ConsentCookieMap + /** + * The consent cookie's raw value READ ON THE SERVER for this request (`null` = the request had none). Given, the + * server render already knows the decision: no banner in the HTML for a visitor who decided, the button instead. + * Reading a cookie makes the page dynamic (no static / ISR HTML, no shared CDN copy) — leave it out to keep pages + * static; the banner then decides before the first paint with a small inline script (consentBannerScript). + */ + cookieValue?: null | string /** * Called after every decision with the consent id and choices — e.g. POST to * the consent log (createConsentLogEndpoint). Never blocks the banner. @@ -61,10 +69,14 @@ type UseConsentOptions = { version?: number } +const noSubscription = () => () => {} +const isClient = () => true +const isServer = () => false + export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) { // Backwards compatible: the old signature took the cookie map directly. const opts: UseConsentOptions = - 'cookieMap' in options || 'version' in options || 'onDecision' in options + 'cookieMap' in options || 'version' in options || 'onDecision' in options || 'cookieValue' in options ? (options) : { cookieMap: options as ConsentCookieMap } const version = opts.version ?? CONSENT_VERSION @@ -73,22 +85,25 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) { const cookieMap = useMemo(() => mergeCookieMaps(opts.cookieMap), [cookieMapKey]) const { onDecision } = opts - const [state, setState] = useState(DEFAULT_CONSENT) - const [decided, setDecided] = useState(false) - const [consentId, setConsentId] = useState(undefined) - - useEffect(() => { - const raw = document.cookie - .split('; ') - .find((c) => c.startsWith(`${CONSENT_COOKIE}=`)) - ?.split('=')[1] - const record = readConsentRecord(raw, version) - if (record) { - setState(record.state) - setDecided(true) - setConsentId(record.id) - } - }, [version]) + // The decision lives in the cookie, read through a store: during the server render and hydration React uses the + // server's value (none, or the cookie the server read), then the browser's own before the next paint. + const serverRead = opts.cookieValue !== undefined + const serverRecord = useMemo( + () => (serverRead ? readConsentRecord(opts.cookieValue ?? undefined, version) : null), + [serverRead, opts.cookieValue, version], + ) + const record = useSyncExternalStore( + subscribeConsent, + () => getConsentSnapshot(version), + () => serverRecord, + ) + /** False in the server render and while hydrating, true from the first client render on. */ + const hydrated = useSyncExternalStore(noSubscription, isClient, isServer) + // reopens the banner over a stored decision; the next decision closes it again. + const [reopened, setReopened] = useState(false) + const state = record?.state ?? DEFAULT_CONSENT + const decided = record !== null && !reopened + const consentId = record?.id const persist = useCallback( (next: ConsentState) => { @@ -104,10 +119,8 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) { const id = consentId ?? newConsentId() const secure = location.protocol === 'https:' ? ';secure' : '' - document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next, version, id)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}` - setState(next) - setDecided(true) - setConsentId(id) + writeConsentCookie(serializeConsent(next, version, id), `;path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`) + setReopened(false) // Tell Google right away. Tags are already on the page holding whatever // defaults Analytics set at load; without this update they keep them for // the rest of the session and never write their cookies — the banner would @@ -129,7 +142,7 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) { persist({ ...DEFAULT_CONSENT, ...choices, necessary: true }), [persist], ) - const reopen = useCallback(() => setDecided(false), []) + const reopen = useCallback(() => setReopened(true), []) - return { acceptAll, consentId, decided, rejectAll, reopen, savePreferences, state } + return { acceptAll, consentId, decided, hydrated, rejectAll, reopen, savePreferences, serverRead, state } } diff --git a/src/modules/consent/useIsMounted.ts b/src/modules/consent/useIsMounted.ts deleted file mode 100644 index c5519cd..0000000 --- a/src/modules/consent/useIsMounted.ts +++ /dev/null @@ -1,17 +0,0 @@ -'use client' -import { useEffect, useState } from 'react' - -/** - * Returns true only after the component has mounted on the client. Used to gate - * consent UI (CookieBanner, CookieButton) so it renders nothing during SSR / - * first paint — preventing the React 19 / Next hydration mismatch that projects - * were working around with their own setTimeout-based ConsentWrapper. Built into - * the components now, so no project wrapper is needed. - */ -export function useIsMounted(): boolean { - const [mounted, setMounted] = useState(false) - useEffect(() => { - setMounted(true) - }, []) - return mounted -} diff --git a/src/modules/frontend/SiteProviders.tsx b/src/modules/frontend/SiteProviders.tsx index ccfadf3..a83f5a8 100644 --- a/src/modules/frontend/SiteProviders.tsx +++ b/src/modules/frontend/SiteProviders.tsx @@ -23,6 +23,12 @@ export type SiteProvidersProps = { /** The cookie banner. Default ``; pass your own configured one (`equalChoice`, classNames) or `false`. */ banner?: false | ReactNode children: ReactNode + /** + * Optional server read of the consent cookie: `(await cookies()).get(CONSENT_COOKIE)?.value ?? null`. The HTML + * then has no banner for a visitor who already decided, and the page becomes dynamic (no static / ISR copy). + * Leave out (default) to keep pages static: the banner decides before the first paint with an inline script. + */ + consentCookie?: null | string /** The "cookie settings" button. Default ``; your own or `false`. */ cookieButton?: false | ReactNode /** Extra cookies per category to delete when consent is withdrawn. */ @@ -41,8 +47,9 @@ export type SiteProvidersProps = { logEndpoint?: string /** * CSP nonce for a nonce-based policy (createProxy `csp`): read it in the layout - * with `(await headers()).get('x-nonce')`. Goes on the theme script and on the - * analytics tags the plugin injects (GTM passes it on to its own tags). + * with `(await headers()).get('x-nonce')`. Goes on the theme script, the cookie + * banner's first-paint script and the analytics tags the plugin injects (GTM + * passes it on to its own tags). */ nonce?: null | string /** to the media origin (R2_PUBLIC_URL). Default true. */ @@ -82,6 +89,7 @@ export function SiteProviders({ analytics, banner, children, + consentCookie, cookieButton, cookieMap, jsonLd = [], @@ -98,7 +106,7 @@ export function SiteProviders({ {theme ? : null} {preconnect ? : null} - + {lightbox ? ( diff --git a/test/consentFirstPaint.test.ts b/test/consentFirstPaint.test.ts new file mode 100644 index 0000000..4aea97b --- /dev/null +++ b/test/consentFirstPaint.test.ts @@ -0,0 +1,484 @@ +// @vitest-environment happy-dom +/** + * The cookie banner is part of the first render (1.17.0): in the server HTML, decided before the first paint, with + * no hydration mismatch — and nothing about consent itself changes: no tag earlier, Consent Mode default first, the + * consent log and the stored cookie as before. + */ +import { act, createElement, type ReactElement } from 'react' +import { hydrateRoot, type Root } from 'react-dom/client' +import { renderToString } from 'react-dom/server' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' + +import type { ConsentState } from '../src/modules/consent/categories.js' + +import { Analytics } from '../src/modules/analytics/Analytics.js' +import { ConsentProvider } from '../src/modules/consent/ConsentContext.js' +import { resetConsentStore } from '../src/modules/consent/consentStore.js' +import { CookieBanner } from '../src/modules/consent/CookieBanner.js' +import { CookieButton } from '../src/modules/consent/CookieButton.js' +import { consentBannerScript } from '../src/modules/consent/firstPaint.js' +import { CONSENT_FALLBACK, CONSENT_FALLBACK_PL } from '../src/modules/consent/getConsentTexts.js' +import { CONSENT_COOKIE, readConsentRecord, serializeConsent } from '../src/modules/consent/storage.js' +import { SiteProviders } from '../src/modules/frontend/SiteProviders.js' + +const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const ACCEPT: ConsentState = { analytics: true, functional: true, marketing: true, necessary: true } +const REJECT: ConsentState = { analytics: false, functional: false, marketing: false, necessary: true } +const texts = { ...CONSENT_FALLBACK, version: 3 } +const stored = (state: ConsentState, version = 3) => serializeConsent(state, version, 'id-1') + +type TreeOptions = { analytics?: object; banner?: object; cookieValue?: null | string; logEndpoint?: string; nonce?: string; texts?: object } +const tree = (o: TreeOptions = {}) => + h( + ConsentProvider, + { cookieValue: o.cookieValue, logEndpoint: o.logEndpoint, nonce: o.nonce, texts: o.texts ?? texts }, + h('main', null, 'page'), + h(CookieBanner, o.banner ?? {}), + h(CookieButton), + o.analytics ? h(Analytics, o.analytics) : null, + ) + +const clearCookies = () => { + for (const c of document.cookie.split('; ')) { + const name = c.split('=')[0] + if (name) {document.cookie = `${name}=;path=/;max-age=0`} + } +} +/** Cookies that hold a value (happy-dom keeps a just-expired cookie, emptied, until the second is over). */ +const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1]) +const storedRaw = () => liveCookies().find((c) => c.startsWith(`${CONSENT_COOKIE}=`))?.split('=')[1] +const setConsentCookie = (value: string) => { + document.cookie = `${CONSENT_COOKIE}=${value};path=/` +} + +let container: HTMLDivElement +let root: Root | undefined +let errors: ReturnType +/** Scripts the code under test adds to (never really loaded). */ +let injected: string[] + +beforeEach(() => { + clearCookies() + resetConsentStore() + delete (window as { dataLayer?: unknown[] }).dataLayer + delete (window as { fbq?: unknown }).fbq + delete (window as { _fbq?: unknown })._fbq + container = document.createElement('div') + document.body.appendChild(container) + errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + injected = [] + vi.spyOn(document.head, 'appendChild').mockImplementation((node) => { + injected.push((node as HTMLScriptElement).src || 'inline') + return node + }) +}) + +afterEach(() => { + if (root) {act(() => root!.unmount())} + root = undefined + container.remove() + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +const banner = () => container.querySelector('[data-ipal="banner"]') +const button = () => container.querySelector('[data-ipal="cookie-button"]') +const scriptEl = () => container.querySelector('[data-ipal="banner-script"]') +const click = (name: string) => act(() => container.querySelector(`[data-ipal="${name}"]`)!.click()) + +/** What the browser does while parsing: run the inline script with itself as document.currentScript. */ +function runInlineScript(html: string) { + const el = scriptEl() + // happy-dom gives no text for a script that came in through innerHTML: take it from the HTML itself + const code = /]*data-ipal="banner-script"[^>]*>(?.*?)<\/script>/s.exec(html)?.groups?.code + if (!el || !code) {return} + // eslint-disable-next-line @typescript-eslint/no-implied-eval + new Function('document', code)({ + get cookie() { + return document.cookie + }, + currentScript: el, + }) +} + +/** Server HTML into the page, the inline script as the parser would run it, then hydration. */ +function load(o: { blocked?: boolean; serverCookie?: null | string } & TreeOptions = {}) { + const node = tree({ ...o, cookieValue: o.serverCookie }) + // renderToString never reads document.cookie (the store's server snapshot): see 'the same HTML for every visitor' + container.innerHTML = renderToString(node) + const html = renderToString(node) + if (!o.blocked) {runInlineScript(html)} + const beforeHydration = { display: banner()?.style.display, hidden: banner()?.hasAttribute('hidden') } + act(() => { + root = hydrateRoot(container, node) + }) + return { beforeHydration, html } +} +const visibleBeforeHydration = (r: ReturnType) => r.beforeHydration.hidden === false && r.beforeHydration.display !== 'none' + +describe('server render', () => { + test('static page: the banner is in the HTML, hidden, with its script right after it; no button', () => { + const html = renderToString(tree()) + expect(html).toMatch(/]*data-ipal="banner"[^>]*hidden=""/) + expect(html).toContain(CONSENT_FALLBACK.message.slice(0, 40)) + expect(html).toMatch(/<\/div>]*data-ipal="banner-script"[^>]*>\(function/) + expect(html).toContain('.version===3') + expect(html).not.toContain('data-ipal="cookie-button"') + // the same HTML for every visitor: nothing in it depends on a cookie + setConsentCookie(stored(ACCEPT)) + resetConsentStore() + expect(renderToString(tree())).toBe(html) + }) + + test('the page language decides the text', () => { + const html = renderToString(tree({ texts: { ...CONSENT_FALLBACK_PL, version: 3 } })) + expect(html).toContain('Używamy plików cookies') + expect(html).toContain('Akceptuj wszystkie') + }) + + test('server-read cookie with a current decision: no banner, no script, the button is in the HTML', () => { + const html = renderToString(tree({ cookieValue: stored(REJECT) })) + expect(html).not.toContain('data-ipal="banner"') + expect(html).not.toContain(' { + const html = renderToString(tree({ cookieValue })) + expect(html).toContain('data-ipal="banner"') + expect(html).not.toMatch(/data-ipal="banner"[^>]*hidden/) + expect(html).not.toContain(' { + const html = renderToString(tree({ banner: { firstPaint: false } })) + expect(html).not.toContain('data-ipal="banner"') + expect(html).not.toContain(' { + expect(renderToString(tree({ nonce: 'n-1' }))).toMatch(/]*nonce="n-1"/) + expect(renderToString(tree({ banner: { nonce: 'n-2' }, nonce: 'n-1' }))).toMatch(/]*nonce="n-2"/) + }) + + test('SiteProviders passes its nonce and the optional server-read cookie', () => { + const shell = { analytics: {}, consent: texts, jsonLd: [], lightboxTexts: {}, theme: {}, turnstileSiteKey: undefined } + const site = (props: object) => renderToString(h(SiteProviders, { analytics: false, preconnect: false, shell, ...props }, h('main', null, 'page'))) + expect(site({ nonce: 'n-3' })).toMatch(/]*data-ipal="banner-script"[^>]*nonce="n-3"|]*nonce="n-3"[^>]*data-ipal="banner-script"/) + const decided = site({ consentCookie: stored(REJECT) }) + expect(decided).not.toContain('data-ipal="banner"') + expect(decided).toContain('data-ipal="cookie-button"') + expect(site({ consentCookie: null })).not.toMatch(/data-ipal="banner"[^>]*hidden/) + }) +}) + +describe('the first-paint script decides as readConsentRecord does', () => { + const run = (cookie: string, version = 3) => { + const b = { removeAttribute: (n: string) => void b.removed.push(n), removed: [] as string[], style: {} as Record } + // eslint-disable-next-line @typescript-eslint/no-implied-eval + new Function('document', consentBannerScript({ version }))({ cookie, currentScript: { previousElementSibling: b } }) + return b.style.display === 'none' ? 'hidden' : b.removed.includes('hidden') ? 'shown' : 'untouched' + } + const raw = (cookie: string) => + cookie + .split('; ') + .find((c) => c.startsWith(`${CONSENT_COOKIE}=`)) + ?.split('=')[1] + + test.each([ + ['no cookie at all', ''], + ['other cookies only', 'a=1; theme=dark'], + ['a current decision', `a=1; ${CONSENT_COOKIE}=${stored(REJECT)}; b=2`], + ['a current decision, accept', `${CONSENT_COOKIE}=${stored(ACCEPT)}`], + ['an older policy version', `${CONSENT_COOKIE}=${stored(ACCEPT, 2)}`], + ['a newer policy version', `${CONSENT_COOKIE}=${stored(ACCEPT, 4)}`], + ['version as a string', `${CONSENT_COOKIE}=${encodeURIComponent(JSON.stringify({ state: ACCEPT, version: '3' }))}`], + ['malformed JSON', `${CONSENT_COOKIE}=%7Bnope`], + ['malformed encoding', `${CONSENT_COOKIE}=%E0%A4%A`], + ['empty value', `${CONSENT_COOKIE}=`], + ['JSON null', `${CONSENT_COOKIE}=null`], + ['a foreign value', `${CONSENT_COOKIE}=accepted`], + ['a cookie whose name only ends the same', `x-${CONSENT_COOKIE}=${stored(ACCEPT)}`], + ['a cookie whose name only starts the same', `${CONSENT_COOKIE}-old=${stored(ACCEPT)}`], + ['no state in the record (read as all refused)', `${CONSENT_COOKIE}=${encodeURIComponent(JSON.stringify({ version: 3 }))}`], + ['two cookies of the name: the first counts', `${CONSENT_COOKIE}=bad; ${CONSENT_COOKIE}=${stored(ACCEPT)}`], + ])('%s', (_label, cookie) => { + const decided = readConsentRecord(raw(cookie), 3) !== null + expect(run(cookie)).toBe(decided ? 'hidden' : 'shown') + }) + + test('default version 1; no banner element next to the script: nothing happens, nothing throws', () => { + expect(consentBannerScript()).toContain('.version===1') + expect(run(`${CONSENT_COOKIE}=${serializeConsent(REJECT)}`, 1)).toBe('hidden') + // eslint-disable-next-line @typescript-eslint/no-implied-eval + expect(() => new Function('document', consentBannerScript())({ cookie: '', currentScript: null })).not.toThrow() + }) + + test('cannot close its own