Merge claude/consent-banner-first-paint-154f9f: the cookie banner is part of the first render
Conflicts in the docs only, both sides kept: changelog lines, AGENT.md checklist rows 12 (banner) and 13 (wrapper order), the two iapl-upgrade blocks, PROGRAMISTA rows 76 (client hints) and 77 (banner, renumbered from 76). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -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 `<CookieBanner>` 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 — `<SiteProviders 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: `<CookieBanner firstPaint={false} />`.
|
||||
`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
|
||||
|
||||
+2
-1
@@ -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`; `<MediaPreconnect/>`; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `<Media>` 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 `<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` |
|
||||
| 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; 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 `<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`; `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 | `<SiteProviders banner={<CookieBanner …/>}>`, `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 <page> \| 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 | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — 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 | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
|
||||
|
||||
@@ -38,6 +38,18 @@ before analytics or marketing consent — check the project's choice in "Project
|
||||
5. Banner not found (`data-ipal="banner"`) → `<CookieBanner/>` 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 `<SiteProviders>`. 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.
|
||||
|
||||
|
||||
@@ -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 `<SiteProviders nonce>` (console: the inline script was refused); a custom `classNames.root` is fine | consent.md → "First paint"; check: `curl -s <page> \| 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 |
|
||||
|
||||
|
||||
@@ -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<ConsentTexts>`; pass to `ConsentProvider texts`. |
|
||||
| `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Server: Cookies → Cookie list rows in one language → `Promise<CookieTableRow[]>` (does not throw) — for `CookieTable`. |
|
||||
|
||||
@@ -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={<CookieBanner firstPaint={false} />}`; 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`
|
||||
|
||||
@@ -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 })`): `<SiteProviders nonce={nonce}>` must be set (it already is where the theme
|
||||
script works); by hand: `<ConsentProvider nonce>`. 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: `<CookieBanner firstPaint={false} />`.
|
||||
**Check:** `curl -s <page> | 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:**
|
||||
|
||||
+81
-4
@@ -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: `<SiteProviders nonce={nonce}>` passes it on (a site that already passes `nonce` for the
|
||||
theme script is done); by hand: `<ConsentProvider nonce={nonce}>` or `<CookieBanner nonce={nonce}>`.
|
||||
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:** `<CookieBanner firstPaint={false} />` — 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
|
||||
<SiteProviders shell={shell} consentCookie={consentCookie}>… // by hand: <ConsentProvider cookieValue={consentCookie}>
|
||||
```
|
||||
|
||||
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 `<script>` as its next sibling; `useConsentContext()` gives `hydrated` (false in the
|
||||
server render and while hydrating) and `serverRead`.
|
||||
|
||||
## Overriding the look (Level 2)
|
||||
|
||||
The default Tailwind classes can be overridden with `classNames`:
|
||||
@@ -292,7 +368,8 @@ Texts from the panel (**Cookies**, per language) — empty field = the element i
|
||||
New fields in the global = a migration in projects on Postgres/SQLite (`payload migrate:create`); MongoDB unchanged.
|
||||
|
||||
The elements also have stable `data-ipal` handles for CSS and e2e tests (used by
|
||||
`iapl-consent-check`): `banner`, `cookie-button` and the buttons `settings`, `reject`,
|
||||
`iapl-consent-check`): `banner` (while it waits for the first-paint script it carries `hidden`; a button clicked before hydration:
|
||||
`data-ipal-pending`; live: `data-ipal-ready`), `banner-script`, `cookie-button` and the buttons `settings`, `reject`,
|
||||
`accept`, `back`, `save`; in modal mode also `consent-overlay`, `consent-dialog`, `close`; in detailed mode
|
||||
additionally `category-<category>` (card) and `cookies` (expandable list).
|
||||
|
||||
|
||||
@@ -684,6 +684,7 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 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" |
|
||||
| 77 | **1.17.0 — cookie banner at first paint** — the banner appeared seconds after the page (after hydration) and was the LCP element on text pages; or after the update an e2e test finds a hidden `[data-ipal="banner"]` for a returning visitor; or with a nonce CSP the console reports a refused inline script | Nothing to run: the banner is now in the server HTML and an inline script shows or hides it before the first paint; pages stay static; consent, tags and the log are unchanged. Remove a project "mounted" wrapper around the banner. Nonce CSP: `<SiteProviders nonce>`. Tailwind 3 with a `classNames.root` that sets `display`: `[data-ipal="banner"][hidden] { display: none !important }`. Old behaviour: `<CookieBanner firstPaint={false} />`; exact HTML on a dynamic site: `consentCookie` | `iapl-upgrade` "→ 1.17.0, cookie banner at first paint", consent.md "First paint" |
|
||||
|
||||
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`.
|
||||
|
||||
+3
-1
@@ -157,11 +157,12 @@ It does not mount `AlternateLinksProvider` (i18n.md) — add it yourself if you
|
||||
| `logEndpoint` | — | consent log endpoint (`consentLog`) |
|
||||
| `banner` | `<CookieBanner />` | your own banner or `false` |
|
||||
| `cookieButton` | `<CookieButton />` | your own button or `false` |
|
||||
| `consentCookie` | — | optional server read of the consent cookie (`(await cookies()).get(CONSENT_COOKIE)?.value ?? null`): exact HTML, but the pages become dynamic. Left out (default): pages stay static and the banner decides before the first paint with an inline script — consent.md → "First paint" |
|
||||
| `analytics` | on | extra `<Analytics>` props or `false` = no tags |
|
||||
| `cookieMap` | — | extra cookies per category to clean up after consent is withdrawn |
|
||||
| `jsonLd` | `[]` | extra JSON-LD nodes |
|
||||
| `lightbox` | off | `true` / `{ texts, classNames, icons, loop, unstyled }` → one `<LightboxProvider>` for the site; texts from `shell.lightboxTexts` (Form messages → Image viewer) — lightbox.md |
|
||||
| `nonce` | — | CSP nonce (`(await headers()).get('x-nonce')` with `createProxy({ csp })`) for the theme script and the analytics tags — security.md |
|
||||
| `nonce` | — | CSP nonce (`(await headers()).get('x-nonce')` with `createProxy({ csp })`) for the theme script, the cookie banner's first-paint script and the analytics tags — security.md |
|
||||
| `preconnect` | `true` | `<link rel=preconnect>` to the media origin |
|
||||
| `stats` | off | `true`/props → `<PageStats>` (stats.md) |
|
||||
| `theme` | `false` | `<ThemeScript>` before the first paint (theme.md) |
|
||||
@@ -174,6 +175,7 @@ It does not mount `AlternateLinksProvider` (i18n.md) — add it yourself if you
|
||||
of the same name in `src/lib/content.ts` (e.g. your own `generateStaticParams` with entries).
|
||||
- `createPageRoute`: your own view through `render`, your own 404/redirect through `onMissing`, extra block props through `blockProps`, JSON-LD through `jsonLd`.
|
||||
- `SiteProviders`: `lightbox` is off by default; for `renderImage` / `renderDialog` (functions) mount `<LightboxProvider>` yourself in a client component instead (lightbox.md).
|
||||
- The cookie banner is in the server HTML and painted with the page (1.17.0; it used to appear after hydration and could be the LCP element). Off: `banner={<CookieBanner firstPaint={false} />}`; server-exact HTML on a dynamic site: `consentCookie` (consent.md → "First paint").
|
||||
- `SiteProviders`: `banner`, `cookieButton`, `analytics` accept your own element or `false`; `analytics={{ consentMode: 'basic' }}` = no request to Google before consent (default `'advanced'`: the tag loads with every signal `denied`).
|
||||
- Search engines from the panel: `robots` instead of `getRobots` ignores it; your own robots: `buildRobots({ ...robotsOptionsFrom(settings), … })`; drop the verification tags: `const { verification, ...meta } = await generatePageMetadata(…)`.
|
||||
- Construction filter in Markdown / MCP: `markdown: { isPathVisible: () => true }`, `mcp: { isPathVisible: () => true }`; in the sitemap and llms.txt: `underConstructionSeo: false`.
|
||||
|
||||
+2
-1
@@ -224,7 +224,7 @@ export const proxy = createProxy(i18nConfig, {
|
||||
// app/(frontend)/[locale]/layout.tsx
|
||||
import { headers } from 'next/headers'
|
||||
const nonce = (await headers()).get('x-nonce') // CSP_NONCE_HEADER
|
||||
<SiteProviders shell={shell} theme nonce={nonce}>… // ThemeScript + GA4/GTM tag get the nonce
|
||||
<SiteProviders shell={shell} theme nonce={nonce}>… // ThemeScript, the banner's first-paint script + GA4/GTM tag get the nonce
|
||||
```
|
||||
|
||||
Costs and rules:
|
||||
@@ -236,6 +236,7 @@ Costs and rules:
|
||||
- Your own proxy: `createCspNonce()` + `buildCsp({ nonce })`, set the policy on the request headers
|
||||
(`NextResponse.next({ request: { headers } })`) and on the response, like `createProxy` does.
|
||||
- `ConsentScript nonce`, `ThemeScript nonce`, `Analytics nonce` exist for policies without `'strict-dynamic'`.
|
||||
- The cookie banner's first-paint script (consent.md → "First paint") is inline, so under a nonce policy it needs the nonce with or without `'strict-dynamic'`: `SiteProviders nonce` passes it (`ConsentProvider nonce` / `CookieBanner nonce` by hand). Refused, the banner appears after hydration.
|
||||
|
||||
### Payload admin — its own, looser policy
|
||||
|
||||
|
||||
@@ -38,6 +38,18 @@ before analytics or marketing consent — check the project's choice in "Project
|
||||
5. Banner not found (`data-ipal="banner"`) → `<CookieBanner/>` 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 `<SiteProviders>`. 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.
|
||||
|
||||
|
||||
@@ -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 `<SiteProviders nonce>` (console: the inline script was refused); a custom `classNames.root` is fine | consent.md → "First paint"; check: `curl -s <page> \| 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 |
|
||||
|
||||
|
||||
@@ -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<ConsentTexts>`; pass to `ConsentProvider texts`. |
|
||||
| `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Server: Cookies → Cookie list rows in one language → `Promise<CookieTableRow[]>` (does not throw) — for `CookieTable`. |
|
||||
|
||||
@@ -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={<CookieBanner firstPaint={false} />}`; 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`
|
||||
|
||||
@@ -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 })`): `<SiteProviders nonce={nonce}>` must be set (it already is where the theme
|
||||
script works); by hand: `<ConsentProvider nonce>`. 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: `<CookieBanner firstPaint={false} />`.
|
||||
**Check:** `curl -s <page> | 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:**
|
||||
|
||||
@@ -290,6 +290,101 @@ test('consent: reject sets no analytics, the choice is logged', async ({ page })
|
||||
expect(cookies.some((c) => c.name === 'cookie-consent')).toBe(true)
|
||||
})
|
||||
|
||||
// The banner is part of the first render (consent.md → "First paint"): in the static HTML, shown or kept hidden by
|
||||
// an inline script before the browser paints, live after hydration.
|
||||
const watchBanner = () => {
|
||||
const w = window as unknown as { __bannerFrames: number }
|
||||
w.__bannerFrames = 0
|
||||
const tick = () => {
|
||||
const b = document.querySelector<HTMLElement>('[data-ipal="banner"]')
|
||||
if (b && getComputedStyle(b).display !== 'none' && b.getBoundingClientRect().height > 0) {w.__bannerFrames++}
|
||||
requestAnimationFrame(tick)
|
||||
}
|
||||
requestAnimationFrame(tick)
|
||||
}
|
||||
const isAppScript = (url: URL) => url.pathname.startsWith('/_next/static/') && url.pathname.endsWith('.js')
|
||||
|
||||
for (const l of LOCALES) {
|
||||
test(`${l.code}: consent banner is in the static HTML and painted before the page hydrates`, async ({ page, request }) => {
|
||||
const res = await request.get(l.home)
|
||||
const html = await res.text()
|
||||
expect(html).toMatch(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
|
||||
expect(html).toMatch(/<\/div><script[^>]*data-ipal="banner-script"/)
|
||||
// the page is still a static one: the banner did not make it depend on a cookie
|
||||
expect(res.headers()['cache-control']).toMatch(/s-maxage=\d+/)
|
||||
expect(res.headers()['set-cookie']).toBeUndefined()
|
||||
const withCookie = await request.get(l.home, { headers: { cookie: 'cookie-consent=anything' } })
|
||||
expect((await withCookie.text()).includes('data-ipal="banner"')).toBe(true)
|
||||
|
||||
// no application script at all: nothing hydrates, the inline script alone decides
|
||||
await page.route(isAppScript, (route) => route.abort())
|
||||
await page.goto(l.home)
|
||||
const banner = page.locator('[data-ipal="banner"]')
|
||||
await expect(banner).toBeVisible()
|
||||
await expect(banner.getByRole('button', { name: /^(Odrzuć|Reject)$/ })).toBeVisible()
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
|
||||
})
|
||||
}
|
||||
|
||||
test('consent: a returning visitor never sees the banner, an old policy version asks again; no console errors', async ({ context, page }) => {
|
||||
const errors: string[] = []
|
||||
page.on('console', (m) => {
|
||||
if (m.type() === 'error' || /hydrat/i.test(m.text())) {errors.push(m.text())}
|
||||
})
|
||||
page.on('pageerror', (e) => errors.push(String(e)))
|
||||
await page.goto('/pl')
|
||||
await page.getByRole('button', { name: 'Odrzuć' }).click()
|
||||
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
||||
const stored = (await context.cookies()).find((c) => c.name === 'cookie-consent')!
|
||||
|
||||
await page.addInitScript(watchBanner)
|
||||
for (const path of ['/pl', '/en', '/pl/regulamin']) {
|
||||
await page.goto(path)
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
||||
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
||||
expect(await page.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames), `${path}: frames with the banner shown`).toBe(0)
|
||||
}
|
||||
// without the application scripts too: the inline script hides it before the first paint
|
||||
const bare = await context.newPage()
|
||||
await bare.addInitScript(watchBanner)
|
||||
await bare.route(isAppScript, (route) => route.abort())
|
||||
await bare.goto('/pl')
|
||||
await bare.waitForTimeout(500)
|
||||
expect(await bare.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames)).toBe(0)
|
||||
await bare.close()
|
||||
|
||||
// the same decision under another policy version: asked again, from the first paint
|
||||
const record = JSON.parse(decodeURIComponent(stored.value)) as { version: number }
|
||||
await context.addCookies([{ ...stored, value: encodeURIComponent(JSON.stringify({ ...record, version: record.version + 1 })) }])
|
||||
await page.goto('/pl')
|
||||
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
|
||||
expect(errors).toEqual([])
|
||||
})
|
||||
|
||||
test('consent: a click on the banner before the page has hydrated is not lost', async ({ context, page }) => {
|
||||
let release: () => void = () => {}
|
||||
const held = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
await page.route(isAppScript, async (route) => {
|
||||
await held
|
||||
await route.continue()
|
||||
})
|
||||
await page.goto('/pl', { waitUntil: 'commit' })
|
||||
const reject = page.locator('[data-ipal="reject"]')
|
||||
await expect(reject).toBeVisible()
|
||||
await reject.click()
|
||||
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(false) // the script itself stores nothing
|
||||
const logged = page.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
|
||||
release()
|
||||
expect((await logged).status()).toBe(201)
|
||||
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
||||
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
||||
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(true)
|
||||
})
|
||||
|
||||
test('admin: sign in through 2FA, agency credit, panel link preview', async ({ page, request }) => {
|
||||
const head = await (await request.get('/admin/login')).text()
|
||||
expect(head).toMatch(/noindex/)
|
||||
|
||||
+2
-1
@@ -82,6 +82,7 @@ export {
|
||||
CONSENT_LOG_SLUG,
|
||||
CONSENT_MAX_AGE,
|
||||
CONSENT_VERSION,
|
||||
consentBannerScript,
|
||||
consentCategoryOptions,
|
||||
consentFallback,
|
||||
DEFAULT_CONSENT,
|
||||
@@ -94,7 +95,7 @@ export {
|
||||
setDefaultConsent,
|
||||
updateConsent,
|
||||
} from './modules/consent/index.js'
|
||||
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentStorage, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
|
||||
export type { ConsentBannerScriptOptions, ConsentCategory, ConsentLogOptions, ConsentState, ConsentStorage, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
|
||||
// Cookie scanner — review list, scan, declarations, Open Cookie Database lookup (docs/cookie-scanner.md).
|
||||
export {
|
||||
addCookieScannerTabs,
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { ConsentCookieMap } from './useConsent.js'
|
||||
|
||||
import { useConsent } from './useConsent.js'
|
||||
|
||||
type ConsentContextValue = { texts: ConsentTexts } & ReturnType<typeof useConsent>
|
||||
type ConsentContextValue = { nonce?: string; texts: ConsentTexts } & ReturnType<typeof useConsent>
|
||||
|
||||
const ConsentContext = createContext<ConsentContextValue | null>(null)
|
||||
|
||||
@@ -14,18 +14,28 @@ type ConsentProviderProps = {
|
||||
children: ReactNode
|
||||
/** Extra cookies per category to delete when consent is withdrawn — merged with the built-in list. */
|
||||
cookieMap?: ConsentCookieMap
|
||||
/**
|
||||
* Optional server read: the consent cookie's raw value from this request
|
||||
* (`(await cookies()).get(CONSENT_COOKIE)?.value ?? null`). The HTML then has no banner for a visitor who already
|
||||
* decided — and the page is dynamic (no static / ISR copy). Leave out to keep pages static (the default): the
|
||||
* banner is in the HTML for everyone and an inline script decides before the first paint.
|
||||
*/
|
||||
cookieValue?: null | string
|
||||
/**
|
||||
* Consent log endpoint (createConsentLogEndpoint, e.g. '/api/ipal/consent'):
|
||||
* every decision is POSTed — random id, choices, policy version, no personal
|
||||
* data — so the site can demonstrate consent (GDPR Art. 7(1)). Off when omitted.
|
||||
*/
|
||||
logEndpoint?: string
|
||||
/** CSP nonce for the banner's first-paint script (a nonce policy: `(await headers()).get('x-nonce')`). */
|
||||
nonce?: null | string
|
||||
texts: ConsentTexts
|
||||
}
|
||||
|
||||
export function ConsentProvider({ children, cookieMap, logEndpoint, texts }: ConsentProviderProps) {
|
||||
export function ConsentProvider({ children, cookieMap, cookieValue, logEndpoint, nonce, texts }: ConsentProviderProps) {
|
||||
const consent = useConsent({
|
||||
cookieMap,
|
||||
cookieValue,
|
||||
onDecision: logEndpoint
|
||||
? (record) => {
|
||||
void fetch(logEndpoint, {
|
||||
@@ -38,7 +48,7 @@ export function ConsentProvider({ children, cookieMap, logEndpoint, texts }: Con
|
||||
: undefined,
|
||||
version: texts.version,
|
||||
})
|
||||
return <ConsentContext value={{ ...consent, texts }}>{children}</ConsentContext>
|
||||
return <ConsentContext value={{ ...consent, nonce: nonce ?? undefined, texts }}>{children}</ConsentContext>
|
||||
}
|
||||
|
||||
export function useConsentContext(): ConsentContextValue {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
|
||||
import { useConsentContext } from './ConsentContext.js'
|
||||
import { useIsMounted } from './useIsMounted.js'
|
||||
import { BANNER_PENDING_ATTRIBUTE, BANNER_READY_ATTRIBUTE, consentBannerScript } from './firstPaint.js'
|
||||
|
||||
/** A button on the banner (first level). */
|
||||
export type CookieBannerAction = 'accept' | 'reject' | 'settings'
|
||||
@@ -177,8 +177,19 @@ type CookieBannerProps = {
|
||||
* keeps the existing look; recommended true.
|
||||
*/
|
||||
equalChoice?: boolean
|
||||
/**
|
||||
* Render the banner on the server, so it is part of the first paint instead of appearing after hydration (where it
|
||||
* often becomes the page's LCP element). Default true. On a static page the HTML is the same for every visitor:
|
||||
* the banner is there with `hidden`, and an inline script right after it (consentBannerScript) shows it, or keeps
|
||||
* it hidden for a visitor with a current decision, before the browser paints. With a server-read cookie
|
||||
* (<ConsentProvider cookieValue>) the HTML is exact and there is no script. `false` = as before 1.17.0: nothing
|
||||
* until the page has hydrated.
|
||||
*/
|
||||
firstPaint?: boolean
|
||||
/** Cookie icon next to the banner text and the settings title. Default true. */
|
||||
icon?: boolean
|
||||
/** CSP nonce for the first-paint script. Default: the one given to <ConsentProvider> / <SiteProviders>. */
|
||||
nonce?: string
|
||||
/** Banner buttons, in this order. Default ['settings', 'reject', 'accept']. */
|
||||
order?: CookieBannerAction[]
|
||||
/**
|
||||
@@ -201,16 +212,18 @@ export function CookieBanner({
|
||||
classNames,
|
||||
controls = 'checkbox',
|
||||
equalChoice = false,
|
||||
firstPaint = true,
|
||||
icon = true,
|
||||
nonce,
|
||||
order = DEFAULT_ORDER,
|
||||
settings = 'inline',
|
||||
settingsActions = DEFAULT_SETTINGS_ACTIONS,
|
||||
}: CookieBannerProps = {}) {
|
||||
const isMounted = useIsMounted()
|
||||
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
|
||||
const { acceptAll, decided, hydrated, nonce: contextNonce, rejectAll, savePreferences, serverRead, state, texts } = useConsentContext()
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
|
||||
const closeRef = useRef<HTMLButtonElement>(null)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const modal = settings !== 'inline'
|
||||
const detailed = settings === 'detailed'
|
||||
|
||||
@@ -229,11 +242,29 @@ export function CookieBanner({
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [modal, showSettings])
|
||||
|
||||
// Render nothing until mounted — avoids the React 19 hydration mismatch that
|
||||
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
|
||||
// needed now.
|
||||
if (!isMounted) {return null}
|
||||
// A banner that came with the server HTML can be clicked before this component is live: the first-paint script
|
||||
// noted the button, carry the click out now (once) and take over.
|
||||
useEffect(() => {
|
||||
const el = rootRef.current
|
||||
if (!el || el.hasAttribute(BANNER_READY_ATTRIBUTE)) {return}
|
||||
const pending = el.getAttribute(BANNER_PENDING_ATTRIBUTE)
|
||||
el.removeAttribute(BANNER_PENDING_ATTRIBUTE)
|
||||
el.setAttribute(BANNER_READY_ATTRIBUTE, '')
|
||||
if (pending === 'accept') {acceptAll()}
|
||||
else if (pending === 'reject') {rejectAll()}
|
||||
else if (pending === 'settings') {setShowSettings(true)}
|
||||
// once, when the server-rendered banner becomes live
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// firstPaint={false}: nothing in the server HTML, the banner appears once the page has hydrated (before 1.17.0).
|
||||
if (!firstPaint && !hydrated) {return null}
|
||||
// While hydrating `decided` is the server's value, so this matches the server HTML; the browser's own value
|
||||
// follows before the next paint (useConsent).
|
||||
if (decided) {return null}
|
||||
// The HTML every visitor gets (static page, nothing read on the server): hidden until the script after it, or
|
||||
// hydration, has looked at the cookie.
|
||||
const undecidedHtml = !hydrated && !serverRead
|
||||
|
||||
const cn = (slot: keyof CookieBannerClassNames) => classNames?.[slot] ?? defaults[slot]
|
||||
const primary = cn('primaryButton')
|
||||
@@ -423,7 +454,9 @@ export function CookieBanner({
|
||||
}
|
||||
|
||||
return (
|
||||
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" data-nosnippet role="dialog">
|
||||
<>
|
||||
{/* suppressHydrationWarning: the script below changes `hidden` / `style` before React hydrates, on purpose */}
|
||||
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" data-nosnippet hidden={undecidedHtml || undefined} ref={rootRef} role="dialog" suppressHydrationWarning>
|
||||
<div className={cn('body')}>
|
||||
{!showSettings ? (
|
||||
<div className={cn('content')}>
|
||||
@@ -452,5 +485,16 @@ export function CookieBanner({
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* Only in the server HTML (gone with the first client render): a script React creates in the browser never runs.
|
||||
suppressHydrationWarning: browsers hide the nonce attribute from the DOM. */}
|
||||
{undecidedHtml ? (
|
||||
<script
|
||||
dangerouslySetInnerHTML={{ __html: consentBannerScript({ version: texts.version }) }}
|
||||
data-ipal="banner-script"
|
||||
nonce={nonce ?? contextNonce}
|
||||
suppressHydrationWarning
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Cookie } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { useConsentContext } from './ConsentContext.js'
|
||||
import { useIsMounted } from './useIsMounted.js'
|
||||
|
||||
/** Elements the button moves up for, so it never covers footer links. */
|
||||
export const COOKIE_BUTTON_AVOID = 'footer, [role="contentinfo"]'
|
||||
@@ -34,13 +33,11 @@ export type CookieButtonProps = {
|
||||
* view the button moves up by the visible part of it, so footer links stay free.
|
||||
*/
|
||||
export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'left' }: CookieButtonProps = {}) {
|
||||
const isMounted = useIsMounted()
|
||||
const { decided, reopen, texts } = useConsentContext()
|
||||
const lift = useLiftAbove(avoid, isMounted && decided)
|
||||
const lift = useLiftAbove(avoid, decided)
|
||||
|
||||
// Render nothing until mounted — prevents hydration mismatch (no project
|
||||
// ConsentWrapper workaround needed).
|
||||
if (!isMounted) {return null}
|
||||
// `decided` is the server's value while hydrating (no decision on a static page, so nothing is rendered — or the
|
||||
// cookie the server read, <ConsentProvider cookieValue>, and then the button is in the HTML), the browser's after.
|
||||
if (!decided) {return null}
|
||||
|
||||
const cls =
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { CONSENT_COOKIE, readConsentRecord } from './storage.js'
|
||||
|
||||
/**
|
||||
* The stored consent decision as an external store (React `useSyncExternalStore`).
|
||||
*
|
||||
* Why a store and not state filled in an effect: with a store React hydrates with the server's value and switches to
|
||||
* the browser's own before the browser paints, so the banner and the button can be part of the server HTML with no
|
||||
* hydration mismatch and no frame of the wrong one. One decision per document: every <ConsentProvider> on a page
|
||||
* reads the same value.
|
||||
*/
|
||||
export type ConsentRecord = NonNullable<ReturnType<typeof readConsentRecord>>
|
||||
|
||||
const listeners = new Set<() => void>()
|
||||
/** The value last written in this document — still the decision when the browser refuses to keep the cookie. */
|
||||
let written: string | undefined
|
||||
let cache: { key: string; record: ConsentRecord | null } | undefined
|
||||
|
||||
/** Raw value of the consent cookie in this browser (first cookie of that name), undefined when there is none. */
|
||||
export function readConsentCookie(): string | undefined {
|
||||
if (typeof document === 'undefined') {return undefined}
|
||||
return document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
|
||||
?.split('=')[1]
|
||||
}
|
||||
|
||||
/** The current decision under `version`, or null. The same object until the stored value changes. */
|
||||
export function getConsentSnapshot(version: number): ConsentRecord | null {
|
||||
const raw = readConsentCookie()
|
||||
const key = `${version}\n${raw ?? ''}\n${written ?? ''}`
|
||||
if (cache?.key !== key) {
|
||||
cache = { key, record: readConsentRecord(raw, version) ?? readConsentRecord(written, version) }
|
||||
}
|
||||
return cache.record
|
||||
}
|
||||
|
||||
export function subscribeConsent(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the cookie (`value` already serialized, `attributes` like `;path=/;max-age=…`) and tells every reader. */
|
||||
export function writeConsentCookie(value: string, attributes: string): void {
|
||||
document.cookie = `${CONSENT_COOKIE}=${value}${attributes}`
|
||||
written = value
|
||||
for (const listener of listeners) {listener()}
|
||||
}
|
||||
|
||||
/** Tests only: forget what this document wrote. */
|
||||
export function resetConsentStore(): void {
|
||||
written = undefined
|
||||
cache = undefined
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { CONSENT_COOKIE, CONSENT_VERSION } from './storage.js'
|
||||
|
||||
/** Set by the first-paint script: the `data-ipal` action of a button clicked before hydration. */
|
||||
export const BANNER_PENDING_ATTRIBUTE = 'data-ipal-pending'
|
||||
/** Set by <CookieBanner> once it handles clicks itself. */
|
||||
export const BANNER_READY_ATTRIBUTE = 'data-ipal-ready'
|
||||
|
||||
export type ConsentBannerScriptOptions = {
|
||||
/** Name of the consent cookie. Default CONSENT_COOKIE (`cookie-consent`). */
|
||||
cookieName?: string
|
||||
/** Policy version the stored decision must carry (ConsentTexts.version). Default CONSENT_VERSION. */
|
||||
version?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The script <CookieBanner> puts right after its own markup, so the banner is decided BEFORE the first paint on a
|
||||
* page that is the same HTML for every visitor (static / ISR, CDN-cached).
|
||||
*
|
||||
* The server renders the banner with the `hidden` attribute. This script — a classic inline script, so it runs while
|
||||
* the HTML is parsed — looks at the element just before it and at the consent cookie:
|
||||
* - no stored decision under this policy version (no cookie, unreadable, foreign, another version) → `hidden` is
|
||||
* removed: the banner is part of the first paint;
|
||||
* - a current decision → `display: none` on the element, until React takes it out after hydration.
|
||||
*
|
||||
* It decides exactly as readConsentRecord does (first cookie of that name, URI-decoded JSON, `version` equal), reads
|
||||
* nothing else, stores nothing, loads nothing. The banner can be clicked before React has hydrated the page; the
|
||||
* script notes the clicked button (`data-ipal-pending` on the banner) and <CookieBanner> carries the click out once
|
||||
* it is live, so an early "Accept" or "Reject" is not lost. Without JavaScript, or when a CSP refuses the script, the banner stays
|
||||
* hidden until hydration: the behaviour before this script existed.
|
||||
*
|
||||
* Exported for a project that renders its own banner: put `hidden` and `suppressHydrationWarning` on the banner's
|
||||
* root, and this script in a `<script>` (with the nonce) as its next sibling.
|
||||
*/
|
||||
export function consentBannerScript({ cookieName = CONSENT_COOKIE, version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
|
||||
// JSON string literal, safe inside <script>: no `</script>`, no line separators
|
||||
const name = JSON.stringify(`${cookieName}=`)
|
||||
.replace(/</g, '\\u003c')
|
||||
.split(String.fromCharCode(0x2028)).join('\\u2028')
|
||||
.split(String.fromCharCode(0x2029)).join('\\u2029')
|
||||
const v = Number.isFinite(version) ? Number(version) : CONSENT_VERSION
|
||||
return (
|
||||
`(function(){try{var s=document.currentScript,b=s&&s.previousElementSibling;if(!b){return}` +
|
||||
`var n=${name},d=false,c=document.cookie?document.cookie.split("; "):[];` +
|
||||
`for(var i=0;i<c.length;i++){if(c[i].indexOf(n)===0){try{d=JSON.parse(decodeURIComponent(c[i].split("=")[1])).version===${v}}catch(e){}break}}` +
|
||||
`if(d){b.style.display="none"}else{b.removeAttribute("hidden");` +
|
||||
// a click on a banner button before the page has hydrated is kept for <CookieBanner> 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){}})()`
|
||||
)
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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<Record<ConsentCategory, string[]>>
|
||||
|
||||
@@ -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<ConsentState>(DEFAULT_CONSENT)
|
||||
const [decided, setDecided] = useState(false)
|
||||
const [consentId, setConsentId] = useState<string | undefined>(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)
|
||||
// <CookieButton> 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 }
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -23,6 +23,12 @@ export type SiteProvidersProps = {
|
||||
/** The cookie banner. Default `<CookieBanner />`; 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 `<CookieButton />`; 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
|
||||
/** <link rel=preconnect> 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 ? <ThemeScript {...shell.theme} nonce={nonce ?? undefined} /> : null}
|
||||
{preconnect ? <MediaPreconnect /> : null}
|
||||
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
|
||||
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
|
||||
<ConsentProvider cookieMap={cookieMap} cookieValue={consentCookie} logEndpoint={logEndpoint} nonce={nonce} texts={shell.consent}>
|
||||
<TurnstileProvider siteKey={shell.turnstileSiteKey}>
|
||||
{lightbox ? (
|
||||
<LightboxProvider texts={shell.lightboxTexts} {...(lightbox === true ? {} : lightbox)}>
|
||||
|
||||
@@ -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<typeof vi.spyOn>
|
||||
/** Scripts the code under test adds to <head> (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<HTMLElement>('[data-ipal="banner"]')
|
||||
const button = () => container.querySelector<HTMLElement>('[data-ipal="cookie-button"]')
|
||||
const scriptEl = () => container.querySelector<HTMLScriptElement>('[data-ipal="banner-script"]')
|
||||
const click = (name: string) => act(() => container.querySelector<HTMLElement>(`[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 = /<script[^>]*data-ipal="banner-script"[^>]*>(?<code>.*?)<\/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<typeof load>) => 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(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
|
||||
expect(html).toContain(CONSENT_FALLBACK.message.slice(0, 40))
|
||||
expect(html).toMatch(/<\/div><script[^>]*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('<script')
|
||||
expect(html).toContain('data-ipal="cookie-button"')
|
||||
})
|
||||
|
||||
test.each([
|
||||
['no cookie', null],
|
||||
['another policy version', stored(ACCEPT, 2)],
|
||||
['malformed', '%7Bnot-json'],
|
||||
['foreign content', encodeURIComponent('yes')],
|
||||
])('server-read cookie, %s: the banner is in the HTML, shown, without a script', (_label, cookieValue) => {
|
||||
const html = renderToString(tree({ cookieValue }))
|
||||
expect(html).toContain('data-ipal="banner"')
|
||||
expect(html).not.toMatch(/data-ipal="banner"[^>]*hidden/)
|
||||
expect(html).not.toContain('<script')
|
||||
expect(html).not.toContain('data-ipal="cookie-button"')
|
||||
})
|
||||
|
||||
test('firstPaint={false}: nothing in the HTML, as before 1.17.0', () => {
|
||||
const html = renderToString(tree({ banner: { firstPaint: false } }))
|
||||
expect(html).not.toContain('data-ipal="banner"')
|
||||
expect(html).not.toContain('<script')
|
||||
})
|
||||
|
||||
test('nonce: from the provider, or the banner prop', () => {
|
||||
expect(renderToString(tree({ nonce: 'n-1' }))).toMatch(/<script[^>]*nonce="n-1"/)
|
||||
expect(renderToString(tree({ banner: { nonce: 'n-2' }, nonce: 'n-1' }))).toMatch(/<script[^>]*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(/<script[^>]*data-ipal="banner-script"[^>]*nonce="n-3"|<script[^>]*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<string, string> }
|
||||
// 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 <script>, reads and writes nothing else', () => {
|
||||
const script = consentBannerScript({ cookieName: '</script><script>alert(1)//', version: Number.NaN })
|
||||
expect(script).not.toContain('</script')
|
||||
expect(script).toContain('.version===1')
|
||||
const plain = consentBannerScript({ version: 3 })
|
||||
expect(plain).not.toMatch(/localStorage|sessionStorage|fetch|XMLHttpRequest|createElement|dataLayer|src=|cookie\s*=[^=]/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hydration', () => {
|
||||
test('first visit: visible before hydration, no hydration warning, the script leaves the tree', () => {
|
||||
const r = load()
|
||||
expect(visibleBeforeHydration(r)).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
expect(banner()!.hasAttribute('hidden')).toBe(false)
|
||||
expect(scriptEl()).toBeNull()
|
||||
expect(button()).toBeNull()
|
||||
})
|
||||
|
||||
test('returning visitor: never visible, no hydration warning, the button after hydration', () => {
|
||||
setConsentCookie(stored(REJECT))
|
||||
const r = load()
|
||||
expect(r.html).toContain('data-ipal="banner"') // static HTML: the same for everyone
|
||||
expect(r.beforeHydration).toEqual({ display: 'none', hidden: true })
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['policy version raised', stored(ACCEPT, 2)],
|
||||
['malformed cookie', '%7Bnope'],
|
||||
['foreign cookie', 'accepted'],
|
||||
])('%s: the banner asks again, from the first paint', (_label, value) => {
|
||||
setConsentCookie(value)
|
||||
const r = load()
|
||||
expect(visibleBeforeHydration(r)).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
expect(button()).toBeNull()
|
||||
})
|
||||
|
||||
test('script refused (CSP without the nonce) or no JavaScript: hidden until hydration, then as before', () => {
|
||||
const first = load({ blocked: true })
|
||||
expect(first.beforeHydration).toEqual({ display: '', hidden: true }) // what a no-JS visitor keeps seeing: no banner
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()!.hasAttribute('hidden')).toBe(false)
|
||||
act(() => root!.unmount())
|
||||
setConsentCookie(stored(REJECT))
|
||||
const back = load({ blocked: true })
|
||||
expect(back.beforeHydration.hidden).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
})
|
||||
|
||||
test('server-read cookie: the HTML is already right, no warning either way', () => {
|
||||
setConsentCookie(stored(REJECT))
|
||||
const decided = load({ serverCookie: stored(REJECT) })
|
||||
expect(decided.html).not.toContain('data-ipal="banner"')
|
||||
expect(decided.html).toContain('data-ipal="cookie-button"')
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
act(() => root!.unmount())
|
||||
clearCookies()
|
||||
const fresh = load({ serverCookie: null })
|
||||
expect(visibleBeforeHydration(fresh)).toBe(true)
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['accept', ACCEPT],
|
||||
['reject', REJECT],
|
||||
])('a click on "%s" before hydration is carried out once the page is live', (action, state) => {
|
||||
const fetchMock = vi.fn((_url: string, _init: { body: string }) => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const node = tree({ logEndpoint: '/api/ipal/consent' })
|
||||
const html = renderToString(node)
|
||||
container.innerHTML = html
|
||||
runInlineScript(html)
|
||||
container.querySelector<HTMLElement>(`[data-ipal="${action}"]`)!.click() // nothing is listening but the script
|
||||
expect(banner()!.getAttribute('data-ipal-pending')).toBe(action)
|
||||
expect(liveCookies()).toEqual([]) // no decision is stored by the script itself
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).toBeNull()
|
||||
expect(readConsentRecord(storedRaw(), 3)!.state).toEqual(state)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('early click on "settings" opens the settings; a click on the text or the link decides nothing', () => {
|
||||
const node = tree()
|
||||
const html = renderToString(node)
|
||||
container.innerHTML = html
|
||||
runInlineScript(html)
|
||||
banner()!.querySelector('p')!.click()
|
||||
expect(banner()!.hasAttribute('data-ipal-pending')).toBe(false)
|
||||
container.querySelector<HTMLElement>('[data-ipal="settings"]')!.click()
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(liveCookies()).toEqual([])
|
||||
expect(container.querySelector('#ipal-consent-title')).not.toBeNull()
|
||||
// live now: a click is handled by React alone, the script's listener stays out of it
|
||||
click('back')
|
||||
click('reject')
|
||||
expect(banner()).toBeNull()
|
||||
})
|
||||
|
||||
test('firstPaint={false}: appears with hydration, no warning', () => {
|
||||
const r = load({ banner: { firstPaint: false } })
|
||||
expect(r.html).not.toContain('data-ipal="banner"')
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(banner()).not.toBeNull()
|
||||
})
|
||||
|
||||
test('control: this harness does report a real hydration mismatch', () => {
|
||||
const node = tree()
|
||||
container.innerHTML = renderToString(node).replace('>page<', '>another page<')
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node, { onRecoverableError: (e) => console.error(e) })
|
||||
})
|
||||
expect(errors).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('decisions, reopening and withdrawal work as before', () => {
|
||||
const consentCookie = () => readConsentRecord(storedRaw(), 3)
|
||||
|
||||
test('reject → the button → the banner again → accept; the id stays, each decision is logged', () => {
|
||||
const fetchMock = vi.fn((_url: string, _init: { body: string }) => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
load({ logEndpoint: '/api/ipal/consent' })
|
||||
click('reject')
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
const first = consentCookie()!
|
||||
expect(first.state).toEqual(REJECT)
|
||||
expect(first.version).toBe(3)
|
||||
expect(first.id).toMatch(/^[0-9a-f]{24}$/)
|
||||
expect(Number.isNaN(Date.parse(first.timestamp))).toBe(false)
|
||||
|
||||
click('cookie-button')
|
||||
expect(banner()).not.toBeNull()
|
||||
expect(banner()!.hasAttribute('hidden')).toBe(false)
|
||||
expect(scriptEl()).toBeNull() // a banner made in the browser carries no script
|
||||
expect(button()).toBeNull()
|
||||
click('accept')
|
||||
expect(consentCookie()!.state).toEqual(ACCEPT)
|
||||
expect(consentCookie()!.id).toBe(first.id)
|
||||
|
||||
// the consent log: one POST per decision, the same body as before
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
const calls = fetchMock.mock.calls.map(([url, init]) => ({ ...(init as object), body: JSON.parse(init.body) as unknown, url }))
|
||||
expect(calls[0]).toEqual({ body: { id: first.id, state: REJECT, version: 3 }, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST', url: '/api/ipal/consent' })
|
||||
expect(calls[1].body).toEqual({ id: first.id, state: ACCEPT, version: 3 })
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('nothing is logged or written by rendering, hydrating or the script', () => {
|
||||
const fetchMock = vi.fn(() => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
load({ logEndpoint: '/api/ipal/consent' })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(liveCookies()).toEqual([])
|
||||
})
|
||||
|
||||
test('withdrawal: analytics cookies go, Google gets the update', () => {
|
||||
setConsentCookie(stored(ACCEPT))
|
||||
document.cookie = '_ga=GA1.1.1;path=/'
|
||||
document.cookie = '_ga_ABC=1;path=/'
|
||||
load()
|
||||
click('cookie-button')
|
||||
click('reject')
|
||||
expect(liveCookies().filter((c) => c.startsWith('_ga'))).toEqual([])
|
||||
expect(consentCookie()!.state).toEqual(REJECT)
|
||||
const update = [...(window.dataLayer as ArrayLike<unknown>[])].map((a) => Array.from(a)).find((a) => a[1] === 'update')!
|
||||
expect(update[2]).toMatchObject({ ad_storage: 'denied', analytics_storage: 'denied' })
|
||||
})
|
||||
|
||||
test('settings in the detailed window: choose a category, save', () => {
|
||||
load({ banner: { controls: 'switch', settings: 'detailed' } })
|
||||
click('settings')
|
||||
expect(container.querySelector('[data-ipal="consent-dialog"]')).not.toBeNull()
|
||||
act(() => container.querySelector<HTMLElement>('[data-ipal="category-analytics"] [role="switch"]')!.click())
|
||||
click('save')
|
||||
expect(consentCookie()!.state).toEqual({ ...REJECT, analytics: true })
|
||||
expect(banner()).toBeNull()
|
||||
})
|
||||
|
||||
test('a browser that refuses the cookie: the decision still holds for this page view', () => {
|
||||
load()
|
||||
Object.defineProperty(document, 'cookie', { configurable: true, get: () => '', set: () => {} })
|
||||
try {
|
||||
click('accept')
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
} finally {
|
||||
delete (document as { cookie?: string }).cookie
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('tags: nothing earlier than before', () => {
|
||||
const pixels = { clarityProjectId: 'clar', consentMode: 'basic', gtmContainerId: 'GTM-TEST', metaPixelId: '123' }
|
||||
const layer = () => [...((window.dataLayer ?? []))].map((entry) => (Object.prototype.toString.call(entry) === '[object Arguments]' ? Array.from(entry as ArrayLike<unknown>) : entry))
|
||||
|
||||
test('the server HTML holds one script, the banner one, and it names no tag', () => {
|
||||
const html = renderToString(tree({ analytics: pixels }))
|
||||
expect(html.match(/<script/g)).toHaveLength(1)
|
||||
expect(html).not.toMatch(/googletagmanager|facebook|clarity|GTM-TEST/)
|
||||
})
|
||||
|
||||
test('no decision: showing the banner at first paint loads no tag; Consent Mode default is all denied', () => {
|
||||
load({ analytics: pixels })
|
||||
expect(injected).toEqual([])
|
||||
expect(layer()).toEqual([['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied', wait_for_update: 500 })]])
|
||||
expect((window as { fbq?: unknown }).fbq).toBeUndefined()
|
||||
})
|
||||
|
||||
test('rejected earlier: still no tag after hydration', () => {
|
||||
setConsentCookie(stored(REJECT))
|
||||
load({ analytics: pixels })
|
||||
expect(injected).toEqual([])
|
||||
})
|
||||
|
||||
test('accepting in the banner: the default came first, then the update, then the tags', () => {
|
||||
load({ analytics: pixels })
|
||||
click('accept')
|
||||
const entries = layer()
|
||||
expect((entries[0] as unknown[]).slice(0, 2)).toEqual(['consent', 'default'])
|
||||
expect((entries[1] as unknown[]).slice(0, 2)).toEqual(['consent', 'update'])
|
||||
expect(entries[2]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(injected).toEqual(expect.arrayContaining(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST', 'https://connect.facebook.net/en_US/fbevents.js']))
|
||||
})
|
||||
|
||||
test('accepted earlier: Consent Mode default (the stored choice) is pushed before the Google tag starts', () => {
|
||||
setConsentCookie(stored(ACCEPT))
|
||||
load({ analytics: pixels })
|
||||
const entries = layer()
|
||||
expect(entries[0]).toEqual(['consent', 'default', expect.objectContaining({ ad_storage: 'granted', analytics_storage: 'granted' })])
|
||||
expect(entries.findIndex((e) => (e as { event?: string }).event === 'gtm.js')).toBeGreaterThan(0)
|
||||
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
|
||||
})
|
||||
|
||||
test("'advanced' (default): the Google tag loads before a decision as before, after the denied default", () => {
|
||||
load({ analytics: { gtmContainerId: 'GTM-TEST', metaPixelId: '123' } })
|
||||
const entries = layer()
|
||||
expect(entries[0]).toEqual(['consent', 'default', expect.objectContaining({ analytics_storage: 'denied' })])
|
||||
expect(entries[1]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(injected).toEqual(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST']) // no Meta Pixel without consent
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user