Consent compliance: Global Privacy Control honoured, equal choice by default, withdrawal that stops running tools, consent log on by default

- GPC (gpc.ts): read in the browser before the first paint (consentBannerScript) and in the consent store; pages stay
  static. 'honour' (default): no banner, analytics and marketing off, no request to Google or a pixel; an explicit
  choice on the site wins; a grant made without the signal gives way when it appears. 'ask' and false as opt-outs.
- equalChoice defaults to true; a development warning when the banner has no 'reject'.
- Withdrawal: Meta / TikTok / Clarity told at once, listed localStorage / sessionStorage keys removed.
- Clarity gets consentv2 when it loads; ads_data_redaction with the Consent Mode default.
- consentLog on by default (consentLog: false turns it off); SiteProviders posts to it by itself; a missing SQL table
  answers 503 with one log line.
- Default banner text: one sentence on changing the choice and browser settings; the GPC line (PL / EN).
- Doctor: consent-log-migration, consent-banner rules.
- Stats: Sec-GPC over a choice made without it keeps the visitor id out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 13:38:39 +01:00
co-authored by Claude Opus 5.5
parent 41771fd51a
commit 99036eb70c
31 changed files with 1130 additions and 120 deletions
+6 -8
View File
@@ -157,10 +157,9 @@ settings window, opened from the cookie button, the visitor switches categories
informed choice. In `'ask'` mode "Accept all" works as usual and the record carries `gpc: true`.
**What the visitor sees.** Mode `'honour'`: no banner; the cookie button; in the settings window, above the
categories, one line (PL / EN defaults in code, overridable through `texts`): *"Twoja przeglądarka wysyła sygnał
Global Privacy Control. Analityka i marketing są wyłączone. Możesz je włączyć dla tej witryny poniżej."* / *"Your
browser sends a Global Privacy Control signal. Analytics and marketing are off. You can turn them on for this site
below."* The same line appears in the banner in `'ask'` mode.
categories, one line (PL / EN defaults in code, overridable through `texts`): *"Your browser sends a Global Privacy
Control signal. Analytics and marketing are off. You can turn them on for this site below."* (Polish default in
`getConsentTexts.ts`) The same line appears in the banner in `'ask'` mode.
**What the consent log records.** In 1.17.0 nothing changes in the log's shape (a new field is a column, §6). The
cookie record carries `gpc`; the request to the log may carry it and the endpoint ignores it. A later release that
@@ -250,9 +249,8 @@ class.
**F. Default text** (the fallback used when the panel field is empty). Opt-out: the editor's own text in the panel
always wins.
- Visitor: before → "…You can accept all, reject non-essential, or choose which to allow." After → the same plus:
"You can change your choice at any time with the cookie button, and set cookie rules in your browser too." (PL:
"Wybór można zmienić w każdej chwili przyciskiem cookies, a zasady dla plików cookies ustawić także w
przeglądarce.")
"You can change your choice at any time with the cookie button, and set cookie rules in your browser too." (Polish
default in `getConsentTexts.ts`)
- A site with its own text in the panel keeps it; doctor (deep mode) notes when that text has no such sentence.
- Analytics: none. Schema: none (constants in code, no new panel field).
@@ -487,7 +485,7 @@ sets the crawl's mode too.
- UODO Biuletyn, "Problematyka ochrony danych osobowych a pliki cookies", 2025-03-31:
https://nowybiuletyn.uodo.gov.pl/problematyka-ochrony-danych-osobowych-a-pliki-cookies/
- WSA Warszawa, II SA/Wa 3993/21 (consent through browser settings), as reported:
https://www.prawo.pl/biznes/zgoda-na-cookies-udzielona-przez-ustawienie-przegladarki,512328.html
`https://www.prawo.pl/biznes/zgoda-na-cookies-udzielona-przez-ustawienie-przegladarki,512328.html`
**EU**
- EDPB, Report of the Cookie Banner Taskforce, 2023-01-17:
+3
View File
@@ -20,11 +20,14 @@ export { shouldLoadGoogle } from '../modules/analytics/shouldLoadGoogle.js'
*/
export {
bottomOverlap,
clarityConsent,
ConsentProvider,
ConsentScript,
COOKIE_BUTTON_AVOID,
CookieBanner,
CookieButton,
readEffectiveConsent,
signalVendors,
useConsent,
useConsentContext,
} from '../modules/consent/client.js'
+8 -1
View File
@@ -79,6 +79,7 @@ export {
CONSENT_COOKIE,
CONSENT_FALLBACK,
CONSENT_FALLBACK_PL,
CONSENT_LOG_PATH,
CONSENT_LOG_SLUG,
CONSENT_MAX_AGE,
CONSENT_VERSION,
@@ -88,14 +89,20 @@ export {
DEFAULT_CONSENT,
getConsentTexts,
getCookieTable,
GPC_CATEGORIES,
GPC_HEADER,
gpcFromHeaders,
gpcFromNavigator,
gpcWellKnown,
parseConsent,
readConsentRecord,
REJECT_ALL_CONSENT,
resolveConsent,
serializeConsent,
setDefaultConsent,
updateConsent,
} from './modules/consent/index.js'
export type { ConsentBannerScriptOptions, ConsentCategory, ConsentLogOptions, ConsentState, ConsentStorage, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export type { ConsentBannerScriptOptions, ConsentCategory, ConsentLogOptions, ConsentState, ConsentStorage, ConsentTexts, CookieTableRow, GpcMode, ResolvedConsent } from './modules/consent/index.js'
// Cookie scanner — review list, scan, declarations, Open Cookie Database lookup (docs/cookie-scanner.md).
export {
addCookieScannerTabs,
+19 -19
View File
@@ -4,8 +4,9 @@ import { useEffect, useRef, useState } from 'react'
import type { AnalyticsConfig } from './types.js'
import { useConsentContext } from '../consent/client.js'
import { readEffectiveConsent } from '../consent/consentStore.js'
import { gtag } from '../consent/googleConsent.js'
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'
import { CONSENT_VERSION, DEFAULT_CONSENT, setDefaultConsent } from '../consent/index.js'
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
import { shouldLoadGoogle } from './shouldLoadGoogle.js'
@@ -19,17 +20,13 @@ const GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=$
const GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`
/**
* Reads the current consent state from cookie, or defaults if none. `version`
* must be the panel's policy version — the same one useConsent checks — or a
* valid consent under any version other than 1 reads as "all denied".
* What is in effect in this browser now: the stored choice under the panel's policy version (the same one
* useConsent checks) with Global Privacy Control applied. Read live, not from React state, because these effects
* also run while the page hydrates, when React still holds the server's "no decision".
*/
function readConsent(version: number | undefined) {
if (typeof document === 'undefined') {return DEFAULT_CONSENT}
const raw = document.cookie
.split('; ')
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
?.split('=')[1]
return parseConsent(raw, version) ?? DEFAULT_CONSENT
function readConsent(version: number | undefined, gpc: Parameters<typeof readEffectiveConsent>[1]) {
if (typeof document === 'undefined') {return { gpc: false, state: DEFAULT_CONSENT }}
return readEffectiveConsent(version ?? CONSENT_VERSION, gpc)
}
function injectScript(src: string, nonce?: string) {
@@ -144,7 +141,7 @@ export function Analytics(props: AnalyticsProps) {
} = props
// Live consent state — drives the non-Google pixels.
const { state, texts } = useConsentContext()
const { gpc, gpcMode, state, texts } = useConsentContext()
const ready = useDeferredReady(defer, deferTimeoutMs)
const defaultConsentSet = useRef(false)
@@ -154,16 +151,19 @@ export function Analytics(props: AnalyticsProps) {
useEffect(() => {
if (defaultConsentSet.current) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
setDefaultConsent(readConsent(texts.version))
setDefaultConsent(readConsent(texts.version, gpcMode).state)
defaultConsentSet.current = true
}, [ga4MeasurementId, gtmContainerId, texts.version])
}, [ga4MeasurementId, gtmContainerId, texts.version, gpcMode])
// --- Google: load once `ready` (and, in 'basic' mode, once consented);
// Consent Mode handles what the tag may store ---
const googleAllowed = shouldLoadGoogle({ consentMode, ready, state })
// --- Google: load once `ready` (and, in 'basic' mode or under Global Privacy
// Control, once consented); Consent Mode handles what the tag may store ---
const googleAllowed = shouldLoadGoogle({ consentMode, gpc, ready, state })
useEffect(() => {
if (!googleAllowed) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
// Checked again against the browser's live value: while hydrating, React's `gpc` / `state` are the server's.
const live = readConsent(texts.version, gpcMode)
if (!shouldLoadGoogle({ consentMode, gpc: live.gpc, ready: true, state: live.state })) {return}
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
@@ -173,7 +173,7 @@ export function Analytics(props: AnalyticsProps) {
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [googleAllowed, ga4MeasurementId, gtmContainerId, nonce])
}, [googleAllowed, ga4MeasurementId, gtmContainerId, nonce, consentMode, gpcMode, texts.version])
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
@@ -185,7 +185,7 @@ export function Analytics(props: AnalyticsProps) {
if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}
if (tiktokPixelId) {loadTikTok(tiktokPixelId)}
}
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId, state)}
}, [
ready,
state.marketing,
+13 -2
View File
@@ -13,6 +13,8 @@
* Microsoft Clarity → analytics
*/
import { clarityConsent } from '../consent/vendorConsent.js'
type Win = Record<string, any> & typeof window
/** Meta (Facebook) Pixel — fires PageView on load. */
@@ -40,14 +42,20 @@ export function loadMetaPixel(id: string): void {
w.fbq('track', 'PageView')
}
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */
export function loadClarity(id: string): void {
/**
* Microsoft Clarity — heatmaps / session recordings (analytics category). Sends Clarity's consent signal
* (`consentv2`) right away: since 31 October 2025 Clarity needs one for visits from the EEA, the UK and Switzerland,
* or it runs without cookies (every page view a new visitor). `consent` = the state the tag was loaded under
* (analytics granted; `ad_Storage` follows marketing). Later changes reach it through signalVendors.
*/
export function loadClarity(id: string, consent: { analytics: boolean; marketing: boolean } = { analytics: true, marketing: false }): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.clarity) {return}
w.clarity = function (...a: unknown[]) {
;(w.clarity.q = w.clarity.q || []).push(a)
}
w.clarity('consentv2', clarityConsent(consent))
const s = document.createElement('script')
s.async = true
s.src = `https://www.clarity.ms/tag/${id}`
@@ -94,6 +102,9 @@ export function loadTikTok(id: string): void {
'group',
'enableCookie',
'disableCookie',
'holdConsent',
'revokeConsent',
'grantConsent',
]
ttq.setAndDefer = function (t: any, e: string) {
t[e] = function (...args: unknown[]) {
+9 -2
View File
@@ -7,17 +7,24 @@
/**
* Whether the Google tag may load now. Pure, so the consent rule is testable
* without a DOM: 'basic' waits for an analytics or marketing grant, 'advanced'
* relies on the Consent Mode default and loads as soon as `ready`.
* relies on the Consent Mode default and loads as soon as `ready` — except
* while Global Privacy Control applies (`gpc`) and nothing is granted: then it
* waits like 'basic', so a visitor whose browser asks not to share data sends
* nothing to Google before choosing otherwise.
*/
export function shouldLoadGoogle({
consentMode,
gpc = false,
ready,
state,
}: {
consentMode: 'advanced' | 'basic'
/** Global Privacy Control applies (the browser sends it and the site honours it). */
gpc?: boolean
ready: boolean
state: { analytics?: boolean; marketing?: boolean }
}): boolean {
if (!ready) {return false}
return consentMode === 'advanced' || Boolean(state.analytics || state.marketing)
const granted = Boolean(state.analytics || state.marketing)
return granted || (consentMode === 'advanced' && !gpc)
}
+42 -5
View File
@@ -1,6 +1,8 @@
'use client'
import { createContext, type ReactNode, use } from 'react'
import { createContext, type ReactNode, use, useMemo } from 'react'
import type { ConsentCategory } from './categories.js'
import type { GpcMode } from './gpc.js'
import type { ConsentTexts } from './texts.js'
import type { ConsentCookieMap } from './useConsent.js'
@@ -22,20 +24,54 @@ type ConsentProviderProps = {
*/
cookieValue?: null | string
/**
* Consent log endpoint (createConsentLogEndpoint, e.g. '/api/ipal/consent'):
* Global Privacy Control: `'honour'` (default) — a browser that sends the signal gets no banner, analytics and
* marketing stay off and nothing is sent to a tracker until the visitor opts in from the cookie button; `'ask'` —
* the banner is shown, nothing is sent until a choice; `false` — the signal is ignored. A choice made on the site
* wins over the signal. See docs/consent.md → Global Privacy Control.
*/
gpc?: GpcMode
/**
* Consent log endpoint (`iapl({ consentLog })`, on by default: '/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.
* data — so the site can demonstrate consent (GDPR Art. 7(1)). Off when omitted
* (<SiteProviders> fills it in from the site shell).
*/
logEndpoint?: string
/** Days a choice is kept before the banner asks again. Default 180. */
maxAgeDays?: number
/** 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, cookieValue, logEndpoint, nonce, texts }: ConsentProviderProps) {
/**
* The panel's cookie list (Cookie Settings → Cookies) per category, split into cookie names and browser-storage keys:
* withdrawing a category removes them too, next to the built-in list (DEFAULT_COOKIE_MAP) and `cookieMap`.
*/
function listedPerCategory(rows: ConsentTexts['cookies']): { cookies: ConsentCookieMap; storage: ConsentCookieMap } {
const cookies: ConsentCookieMap = {}
const storage: ConsentCookieMap = {}
for (const row of rows ?? []) {
if (row.category === 'necessary' || !row.name) {continue}
const target = row.storage === 'localStorage' || row.storage === 'sessionStorage' ? storage : cookies
;(target[row.category as ConsentCategory] ??= []).push(row.name)
}
return { cookies, storage }
}
export function ConsentProvider({ children, cookieMap, cookieValue, gpc, logEndpoint, maxAgeDays, nonce, texts }: ConsentProviderProps) {
const listKey = JSON.stringify(texts.cookies ?? null)
const listed = useMemo(() => listedPerCategory(texts.cookies), [listKey])
const mergedCookies = useMemo(() => {
const out: ConsentCookieMap = { ...listed.cookies }
for (const [cat, names] of Object.entries(cookieMap ?? {}) as [ConsentCategory, string[]][]) {out[cat] = [...(out[cat] ?? []), ...names]}
return out
}, [listed, JSON.stringify(cookieMap ?? null)])
const consent = useConsent({
cookieMap,
cookieMap: mergedCookies,
cookieValue,
gpc,
maxAgeDays,
onDecision: logEndpoint
? (record) => {
void fetch(logEndpoint, {
@@ -46,6 +82,7 @@ export function ConsentProvider({ children, cookieMap, cookieValue, logEndpoint,
}).catch(() => {})
}
: undefined,
storageMap: listed.storage,
version: texts.version,
})
return <ConsentContext value={{ ...consent, nonce: nonce ?? undefined, texts }}>{children}</ConsentContext>
+26 -9
View File
@@ -60,6 +60,8 @@ export type CookieBannerClassNames = {
dialog?: string
/** Small label above the banner title (CookieSettings → eyebrow). */
eyebrow?: string
/** The line saying the browser's Global Privacy Control was honoured (banner and settings view). */
gpcNotice?: string
/** Cookie icon next to the banner text and the settings title. */
icon?: string
/** Privacy-policy link inside the message. */
@@ -143,6 +145,7 @@ const defaults: Required<CookieBannerClassNames> = {
cookiesToggle: `inline-flex cursor-pointer select-none items-center gap-1 text-xs font-medium ${accent} hover:underline [&::-webkit-details-marker]:hidden`,
dialog: `relative max-h-[90vh] w-full max-w-2xl overflow-y-auto ${radius} border p-6 shadow-2xl ${surface} ${border}`,
eyebrow: `mb-1 text-xs font-semibold uppercase tracking-wider ${accent}`,
gpcNotice: `text-xs ${mutedText}`,
icon: `h-6 w-6 shrink-0 ${accent}`,
link: `${accent} underline hover:no-underline`,
message: `text-justify text-sm ${bodyText}`,
@@ -172,9 +175,9 @@ type CookieBannerProps = {
/** Category controls: native checkboxes (default) or accessible switches (role="switch"). */
controls?: 'checkbox' | 'switch'
/**
* Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO,
* EDPB) expect refusing to be as easy and visible as accepting. Default false
* keeps the existing look; recommended true.
* Style "Reject" like "Accept all" (primary). EU data-protection authorities (EDPB Cookie Banner Taskforce, 2023;
* repeated by UODO) expect refusing to be as easy and as visible as accepting. Default true since 1.17.0;
* `false` styles "Reject" as the secondary button (before 1.17.0) — iapl-doctor then warns.
*/
equalChoice?: boolean
/**
@@ -190,7 +193,10 @@ type CookieBannerProps = {
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']. */
/**
* Banner buttons, in this order. Default ['settings', 'reject', 'accept']. Keep 'reject': refusing must be possible
* on the first layer (a development warning and iapl-doctor say so when it is missing).
*/
order?: CookieBannerAction[]
/**
* Where category settings open:
@@ -211,7 +217,7 @@ const DEFAULT_SETTINGS_ACTIONS: CookieSettingsAction[] = ['back', 'save']
export function CookieBanner({
classNames,
controls = 'checkbox',
equalChoice = false,
equalChoice = true,
firstPaint = true,
icon = true,
nonce,
@@ -219,7 +225,7 @@ export function CookieBanner({
settings = 'inline',
settingsActions = DEFAULT_SETTINGS_ACTIONS,
}: CookieBannerProps = {}) {
const { acceptAll, decided, hydrated, nonce: contextNonce, rejectAll, savePreferences, serverRead, state, texts } = useConsentContext()
const { acceptAll, decided, gpc, gpcMode, 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)
@@ -242,6 +248,14 @@ export function CookieBanner({
return () => document.removeEventListener('keydown', onKey)
}, [modal, showSettings])
// Refusing must be possible on the first layer (EDPB Cookie Banner Taskforce): say so while developing.
const noReject = !order.includes('reject')
useEffect(() => {
if (noReject && process.env.NODE_ENV !== 'production') {
console.warn("[iapl] <CookieBanner order> has no 'reject': visitors cannot refuse on the first layer (docs/consent.md → Equal choice)")
}
}, [noReject])
// 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(() => {
@@ -263,8 +277,9 @@ export function CookieBanner({
// 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
// hydration, has looked at the cookie. With a server-read cookie and no decision the server still cannot know
// Global Privacy Control (a browser signal), so with `gpc: 'honour'` the script decides that part too.
const undecidedHtml = !hydrated && (!serverRead || gpcMode === 'honour')
const cn = (slot: keyof CookieBannerClassNames) => classNames?.[slot] ?? defaults[slot]
const primary = cn('primaryButton')
@@ -415,6 +430,7 @@ export function CookieBanner({
)}
</div>
{texts.settingsDescription && <p className={cn('settingsDescription')}>{texts.settingsDescription}</p>}
{gpc && texts.gpcNotice ? <p className={cn('gpcNotice')} data-ipal="gpc-notice">{texts.gpcNotice}</p> : null}
<ul className={cn('categories')}>
{CONSENT_CATEGORIES.map((cat) =>
detailed ? (
@@ -476,6 +492,7 @@ export function CookieBanner({
</>
)}
</p>
{gpc && texts.gpcNotice ? <p className={cn('gpcNotice')} data-ipal="gpc-notice">{texts.gpcNotice}</p> : null}
</div>
</div>
<div className={cn('actions')}>{order.map(button)}</div>
@@ -489,7 +506,7 @@ export function CookieBanner({
suppressHydrationWarning: browsers hide the nonce attribute from the DOM. */}
{undecidedHtml ? (
<script
dangerouslySetInnerHTML={{ __html: consentBannerScript({ version: texts.version }) }}
dangerouslySetInnerHTML={{ __html: consentBannerScript({ gpc: gpcMode, version: texts.version }) }}
data-ipal="banner-script"
nonce={nonce ?? contextNonce}
suppressHydrationWarning
+2
View File
@@ -8,3 +8,5 @@ export type { CookieButtonProps } from './CookieButton.js'
// Client-only consent exports — hook, provider, and UI components.
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
export type { ConsentCookieMap } from './useConsent.js'
export { readEffectiveConsent } from './consentStore.js'
export { clarityConsent, signalVendors } from './vendorConsent.js'
+27 -5
View File
@@ -15,12 +15,22 @@ import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
* the time. NO IP address, user agent or other personal data — the id alone
* links a record to the browser that holds the cookie.
*
* Opt-in: `iapl({ consentLog: true })` adds the collection and the endpoint
* POST /api/ipal/consent; the layout passes `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Records older than `retentionDays` (default 3 years) are purged automatically.
* On by default since 1.17.0 (`iapl({ consentLog: false })` turns it off): adds the collection and the endpoint
* POST /api/ipal/consent. <SiteProviders> posts there by itself (the site shell knows the path); a layout with its
* own <ConsentProvider> passes `logEndpoint="/api/ipal/consent"`. Postgres / SQLite: the collection is a table, so
* the deploy that brings it needs a migration — until it exists a write answers 503 and logs one line; the page and
* the banner never notice. Records older than `retentionDays` (default 3 years) are purged automatically.
*/
export const CONSENT_LOG_SLUG = 'consent-records'
/** The endpoint's path under the API route (`/api` + this). */
export const CONSENT_LOG_PATH = '/ipal/consent'
/** A database error that means the collection's table is not there (a SQL project without the migration). */
export function isMissingTableError(err: unknown): boolean {
const text = err instanceof Error ? `${err.message} ${(err as { cause?: { message?: string } }).cause?.message ?? ''}` : String(err)
return /relation "?[\w.]*consent_records"? does not exist|no such table:? *"?[\w.]*consent_records|consent_records.*does(?: not|n't) exist/i.test(text)
}
export type ConsentLogOptions = {
/**
@@ -72,6 +82,8 @@ export function buildConsentLogCollection(): CollectionConfig {
}
const purge = createDailyPurge(CONSENT_LOG_SLUG)
/** The missing-table line is logged once per process, not on every visitor's click. */
let missingTableLogged = false
export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint {
return {
@@ -85,7 +97,8 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti
} catch {
return Response.json({ ok: false }, { status: 400 })
}
const b = body as { id?: unknown; state?: Record<string, unknown>; version?: unknown }
// `gpc` (Global Privacy Control at the time of the choice) may come with the body; the record does not store it.
const b = body as { gpc?: unknown; id?: unknown; state?: Record<string, unknown>; version?: unknown }
const valid =
typeof b.id === 'string' &&
/^[0-9a-f]{16,64}$/.test(b.id) &&
@@ -110,11 +123,20 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti
purge(req.payload, { createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() } })
return Response.json({ ok: true }, { status: 201 })
} catch (err) {
if (isMissingTableError(err)) {
if (!missingTableLogged) {
missingTableLogged = true
req.payload.logger.error(
"[iapl] consent log: the consent-records table does not exist — create and apply a migration (pnpm payload migrate:create consent-log, commit, migrate at container start) or set iapl({ consentLog: false }). Banner choices are not recorded until then; the site works.",
)
}
return Response.json({ ok: false }, { status: 503 })
}
req.payload.logger.error(`[iapl] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: '/ipal/consent',
path: CONSENT_LOG_PATH,
}
}
+10
View File
@@ -1,3 +1,4 @@
import { gpcFromNavigator, type GpcMode, resolveConsent, type ResolvedConsent } from './gpc.js'
import { CONSENT_COOKIE, readConsentRecord } from './storage.js'
/**
@@ -34,6 +35,15 @@ export function getConsentSnapshot(version: number): ConsentRecord | null {
return cache.record
}
/**
* What is in effect right now in this browser — the stored decision under `version` with Global Privacy Control
* applied (gpc.ts). Read straight from the cookie and `navigator`, not from React state, so an effect that runs
* during hydration (when React still holds the server's "no decision") sees the browser's real value.
*/
export function readEffectiveConsent(version: number, gpc: GpcMode = 'honour'): ResolvedConsent {
return resolveConsent(getConsentSnapshot(version), gpcFromNavigator(), gpc)
}
export function subscribeConsent(listener: () => void): () => void {
listeners.add(listener)
return () => {
+10 -2
View File
@@ -8,6 +8,11 @@ export const BANNER_READY_ATTRIBUTE = 'data-ipal-ready'
export type ConsentBannerScriptOptions = {
/** Name of the consent cookie. Default CONSENT_COOKIE (`cookie-consent`). */
cookieName?: string
/**
* Global Privacy Control mode (gpc.ts). With `'honour'` (default) a browser that sends the signal
* (`navigator.globalPrivacyControl === true`) counts as decided: the banner stays hidden, as React will keep it.
*/
gpc?: 'ask' | 'honour' | false
/** Policy version the stored decision must carry (ConsentTexts.version). Default CONSENT_VERSION. */
version?: number
}
@@ -20,7 +25,8 @@ export type ConsentBannerScriptOptions = {
* 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.
* - a current decision, or Global Privacy Control honoured (`gpc: 'honour'`) → `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
@@ -31,7 +37,7 @@ export type ConsentBannerScriptOptions = {
* 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 {
export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
// JSON string literal, safe inside <script>: no `</script>`, no line separators
const name = JSON.stringify(`${cookieName}=`)
.replace(/</g, '\\u003c')
@@ -42,6 +48,8 @@ export function consentBannerScript({ cookieName = CONSENT_COOKIE, version = CON
`(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}}` +
// Global Privacy Control honoured: no banner, the same decision React makes (resolveConsent)
(gpc === 'honour' ? `if(!d&&navigator.globalPrivacyControl===true){d=true}` : '') +
`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}` +
+7 -2
View File
@@ -36,8 +36,10 @@ export const CONSENT_FALLBACK: ConsentTexts = {
storage: 'Type',
storageTypes: { cookie: 'Cookie', localStorage: 'Local storage', sessionStorage: 'Session storage' },
},
gpcNotice:
'Your browser sends a Global Privacy Control signal. Analytics and marketing are off. You can turn them on for this site here.',
message:
'We use cookies to run the site, analyze traffic, and improve your experience. You can accept all, reject non-essential, or choose which to allow.',
'We use cookies to run the site, analyze traffic, and improve your experience. You can accept all, reject non-essential, or choose which to allow. You can change your choice at any time with the cookie button, and set cookie rules in your browser too.',
privacyLink: null,
settingsTitle: 'Cookie settings',
}
@@ -69,8 +71,10 @@ export const CONSENT_FALLBACK_PL: ConsentTexts = {
storage: 'Rodzaj',
storageTypes: { cookie: 'Plik cookie', localStorage: 'Pamięć lokalna', sessionStorage: 'Pamięć sesji' },
},
gpcNotice:
'Twoja przeglądarka wysyła sygnał Global Privacy Control. Analityka i marketing są wyłączone. Możesz je włączyć dla tej witryny tutaj.',
message:
'Używamy plików cookies, aby witryna działała, aby analizować ruch i ulepszać witrynę. Można zaakceptować wszystkie, odrzucić te, które nie są niezbędne, lub wybrać je samodzielnie.',
'Używamy plików cookies, aby witryna działała, aby analizować ruch i ulepszać witrynę. Można zaakceptować wszystkie, odrzucić te, które nie są niezbędne, lub wybrać je samodzielnie. Wybór można zmienić w każdej chwili przyciskiem cookies, a zasady dla plików cookies ustawić także w przeglądarce.',
privacyLink: null,
settingsTitle: 'Ustawienia cookies',
}
@@ -209,6 +213,7 @@ export async function getConsentTexts({
storage: g.detailLabels?.storage?.trim() || FALLBACK.details!.storage,
storageTypes: FALLBACK.details!.storageTypes,
},
gpcNotice: FALLBACK.gpcNotice,
message: g.message || FALLBACK.message,
privacyLink,
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
+5 -1
View File
@@ -41,12 +41,16 @@ export function gtag(..._args: unknown[]) {
window.dataLayer.push(arguments)
}
/** Sets the default consent state (call before Google tags load). */
/**
* Sets the default consent state (call before Google tags load). Also `ads_data_redaction`: while `ad_storage` is
* denied, Google Ads and Floodlight requests carry no ad-click identifiers (it does nothing once marketing is granted).
*/
export function setDefaultConsent(state: ConsentState) {
gtag('consent', 'default', {
...toSignals(state),
wait_for_update: 500, // ms to wait for an update before firing
})
gtag('set', 'ads_data_redaction', true)
}
/** Updates consent after the user decides. */
+86
View File
@@ -0,0 +1,86 @@
import type { ConsentState } from './categories.js'
import { DEFAULT_CONSENT } from './categories.js'
/**
* Global Privacy Control (https://www.w3.org/TR/gpc/): a browser setting that says "do not sell or share my data".
* The browser sends `Sec-GPC: 1` with its requests and exposes `navigator.globalPrivacyControl === true`.
*
* In the EU optional categories are already off until the visitor opts in, so the signal is read as a REFUSAL of
* the categories that share data with third parties — analytics and marketing — that the visitor did not have to
* click. A choice the visitor makes on this site while the signal is on is specific to the site and wins.
*
* - `'honour'` (default): with the signal and no stored choice there is no banner, analytics and marketing stay off
* and no tag that sends data loads (also not the Google tag in Consent Mode `advanced`). The cookie button opens
* the settings, where the visitor can still opt in.
* - `'ask'`: the banner is shown as usual; until a choice nothing is sent to any tracker, Google included.
* - `false`: the signal is ignored (before 1.17.0).
*
* A choice stored WITHOUT the signal (`gpc: false` in the record) that granted analytics or marketing gives way when
* the signal appears: both go off, their cookies are deleted and the record is rewritten (the visitor can grant
* again). Records from before 1.17.0 carry no `gpc` field and stand until they expire or the visitor changes them.
* The absence of the signal is never consent.
*/
export type GpcMode = 'ask' | 'honour' | false
/** The categories the signal refuses: the ones that share data with third parties. */
export const GPC_CATEGORIES = ['analytics', 'marketing'] as const
/** `Sec-GPC` request header (only the exact value `1` is a signal). */
export const GPC_HEADER = 'sec-gpc'
/** True when the browser sends the GPC signal (`navigator.globalPrivacyControl === true`). False on the server. */
export function gpcFromNavigator(): boolean {
if (typeof navigator === 'undefined') {return false}
return (navigator as { globalPrivacyControl?: unknown }).globalPrivacyControl === true
}
/**
* True when a request carries `Sec-GPC: 1`. For endpoints and pages that are already per visitor — reading the
* header while rendering a static page makes it dynamic, and a cached page that differs by it needs
* `Vary: Sec-GPC` (or `private`). The plugin never renders a page differently for the signal.
*/
export function gpcFromHeaders(headers: { get(name: string): null | string } | Headers | null | undefined): boolean {
return headers?.get(GPC_HEADER)?.trim() === '1'
}
type StoredLike = { gpc?: boolean; state: ConsentState } | null
export type ResolvedConsent = {
/** No banner needed: a stored choice, or the signal honoured. */
decided: boolean
/** The signal is present and the mode reads it. */
gpc: boolean
/** A stored choice made without the signal granted analytics or marketing: the hook rewrites it. */
stale: boolean
/** The categories in effect. */
state: ConsentState
}
/** What is in effect for a stored choice (or none), the signal and the mode. Pure. */
export function resolveConsent(record: StoredLike, signal: boolean, mode: GpcMode = 'honour'): ResolvedConsent {
const active = mode !== false && signal
if (!active) {return { decided: record !== null, gpc: false, stale: false, state: record?.state ?? DEFAULT_CONSENT }}
if (record) {
const grants = GPC_CATEGORIES.some((cat) => record.state[cat])
if (record.gpc === false && grants) {
return { decided: true, gpc: true, stale: true, state: { ...record.state, analytics: false, marketing: false } }
}
return { decided: true, gpc: true, stale: false, state: record.state }
}
return { decided: mode === 'honour', gpc: true, stale: false, state: DEFAULT_CONSENT }
}
/**
* Route handler for `/.well-known/gpc.json` — the site's statement that it honours the signal
* (`{ "gpc": true, "lastUpdate": "<date>" }`). Optional, public: put it in `app/.well-known/gpc.json/route.ts`:
*
* import { gpcWellKnown } from '@intecion/ipal-kit'
* export const GET = gpcWellKnown({ lastUpdate: '2026-11-26' })
*
* The proxy's matcher must let the path through (most skip paths with a dot — then nothing is needed).
*/
export function gpcWellKnown({ lastUpdate }: { lastUpdate: string }): () => Response {
const date = /^\d{4}-\d{2}-\d{2}/.test(lastUpdate) ? lastUpdate : new Date().toISOString().slice(0, 10)
return () => Response.json({ gpc: true, lastUpdate: date }, { headers: { 'cache-control': 'public, max-age=86400' } })
}
+3 -1
View File
@@ -9,13 +9,15 @@ export {
} from './categories.js'
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 { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_PATH, 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'
export { GPC_CATEGORIES, GPC_HEADER, gpcFromHeaders, gpcFromNavigator, gpcWellKnown, resolveConsent } from './gpc.js'
export type { GpcMode, ResolvedConsent } from './gpc.js'
export {
CONSENT_COOKIE,
CONSENT_MAX_AGE,
+9 -2
View File
@@ -15,6 +15,11 @@ export const CONSENT_VERSION = 1
export const CONSENT_MAX_AGE = 60 * 60 * 24 * 180 // 180 days
type StoredConsent = {
/**
* Was the browser sending Global Privacy Control when this choice was made? Absent in records written before
* 1.17.0. A record made WITHOUT the signal (`false`) gives way to the signal once it appears (gpc.ts).
*/
gpc?: boolean
/** Random id of this decision (no personal data) — matches the consent record. */
id?: string
state: ConsentState
@@ -29,8 +34,9 @@ export function newConsentId(): string {
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
}
export function serializeConsent(state: ConsentState, version: number = CONSENT_VERSION, id?: string): string {
export function serializeConsent(state: ConsentState, version: number = CONSENT_VERSION, id?: string, gpc?: boolean): string {
const payload: StoredConsent = {
...(typeof gpc === 'boolean' ? { gpc } : {}),
...(id ? { id } : {}),
state,
timestamp: new Date().toISOString(),
@@ -50,7 +56,8 @@ export function readConsentRecord(raw: string | undefined, version: number = CON
if (typeof parsed.state?.[cat] === 'boolean') {state[cat] = parsed.state[cat]}
}
state.necessary = true
return { ...parsed, state }
const { gpc, ...rest } = parsed
return { ...rest, ...(typeof gpc === 'boolean' ? { gpc } : {}), state }
} catch {
return null
}
+5
View File
@@ -36,6 +36,11 @@ export type ConsentTexts = {
}
/** Small label above the banner title (e.g. "Privacy & cookies"). Empty = not shown. */
eyebrow?: string
/**
* Shown when the browser's Global Privacy Control is honoured (settings window; banner in `gpc: 'ask'`).
* getConsentTexts fills it in the page's language; empty = not shown.
*/
gpcNotice?: string
message: string
/** null = no privacy-policy link shown */
privacyLink: { href: string; label: string } | null
+95 -28
View File
@@ -1,5 +1,5 @@
'use client'
import { useCallback, useMemo, useState, useSyncExternalStore } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import type { ConsentCategory, ConsentState } from './categories.js'
@@ -7,7 +7,9 @@ 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 { gpcFromNavigator, type GpcMode, resolveConsent } from './gpc.js'
import { CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js'
import { signalVendors } from './vendorConsent.js'
export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
@@ -23,19 +25,39 @@ export const DEFAULT_COOKIE_MAP: ConsentCookieMap = {
marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'],
}
function mergeCookieMaps(extra?: ConsentCookieMap): ConsentCookieMap {
if (!extra) {return DEFAULT_COOKIE_MAP}
const out: ConsentCookieMap = { ...DEFAULT_COOKIE_MAP }
function mergeCookieMaps(base: ConsentCookieMap, extra?: ConsentCookieMap): ConsentCookieMap {
if (!extra) {return base}
const out: ConsentCookieMap = { ...base }
for (const [cat, names] of Object.entries(extra) as [ConsentCategory, string[]][]) {
if (cat === 'necessary') {continue}
out[cat] = [...new Set([...(out[cat] ?? []), ...names])]
}
return out
}
const matches = (names: string[], pattern: string) =>
pattern.endsWith('*') ? names.filter((n) => n.startsWith(pattern.slice(0, -1))) : names.filter((n) => n === pattern)
/** Names of cookies currently set that match a pattern (`name` or prefix `name*`). */
function matchingCookies(pattern: string): string[] {
const names = document.cookie.split('; ').map((c) => c.split('=')[0]).filter(Boolean)
return pattern.endsWith('*') ? names.filter((n) => n.startsWith(pattern.slice(0, -1))) : names.filter((n) => n === pattern)
return matches(document.cookie.split('; ').map((c) => c.split('=')[0]).filter(Boolean), pattern)
}
/** Removes the keys matching `pattern` from localStorage and sessionStorage (blocked storage is skipped). */
function deleteStorageKeys(pattern: string) {
for (const area of ['localStorage', 'sessionStorage'] as const) {
try {
const store = window[area]
const keys: string[] = []
for (let i = 0; i < store.length; i++) {
const key = store.key(i)
if (key !== null) {keys.push(key)}
}
for (const key of matches(keys, pattern)) {store.removeItem(key)}
} catch {
// storage blocked (private mode, sandbox): nothing to remove
}
}
}
/**
@@ -60,11 +82,21 @@ type UseConsentOptions = {
* static; the banner then decides before the first paint with a small inline script (consentBannerScript).
*/
cookieValue?: null | string
/** Global Privacy Control (gpc.ts): `'honour'` (default), `'ask'` or `false` (ignored). */
gpc?: GpcMode
/** Days a choice (grant or refusal) is kept before the banner asks again. Default 180. */
maxAgeDays?: number
/**
* Called after every decision with the consent id and choices — e.g. POST to
* the consent log (createConsentLogEndpoint). Never blocks the banner.
* the consent log (createConsentLogEndpoint). Never blocks the banner. `gpc`: whether the browser sent Global
* Privacy Control when the choice was made (also on the automatic rewrite when the signal appears).
*/
onDecision?: (record: { id: string; state: ConsentState; version: number }) => void
onDecision?: (record: { gpc: boolean; id: string; state: ConsentState; version: number }) => void
/**
* localStorage / sessionStorage keys per category, removed when consent for it is withdrawn (`name*` = prefix).
* <ConsentProvider> fills it from the panel's cookie list (entries of type Local / Session storage).
*/
storageMap?: ConsentCookieMap
/** Policy version from the panel (Cookie Settings). A stored consent from another version asks again. */
version?: number
}
@@ -76,14 +108,20 @@ 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 || 'cookieValue' in options
? (options)
['cookieMap', 'cookieValue', 'gpc', 'maxAgeDays', 'onDecision', 'storageMap', 'version'].some((key) => key in options)
? (options as UseConsentOptions)
: { cookieMap: options as ConsentCookieMap }
const version = opts.version ?? CONSENT_VERSION
// Merge once per distinct map (props may pass a new object each render).
const cookieMapKey = JSON.stringify(opts.cookieMap ?? null)
const cookieMap = useMemo(() => mergeCookieMaps(opts.cookieMap), [cookieMapKey])
const cookieMap = useMemo(() => mergeCookieMaps(DEFAULT_COOKIE_MAP, opts.cookieMap), [cookieMapKey])
const storageKey = JSON.stringify(opts.storageMap ?? null)
const storageMap = useMemo(() => mergeCookieMaps({}, opts.storageMap), [storageKey])
const { onDecision } = opts
const gpcMode: GpcMode = opts.gpc === undefined ? 'honour' : opts.gpc
const maxAge = opts.maxAgeDays !== undefined && Number.isFinite(opts.maxAgeDays) && opts.maxAgeDays > 0
? Math.round(opts.maxAgeDays * 86_400)
: CONSENT_MAX_AGE
// 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.
@@ -99,42 +137,71 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) {
)
/** False in the server render and while hydrating, true from the first client render on. */
const hydrated = useSyncExternalStore(noSubscription, isClient, isServer)
/** Global Privacy Control from the browser; the server never knows it (pages stay the same for every visitor). */
const signal = useSyncExternalStore(noSubscription, gpcFromNavigator, 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 resolved = resolveConsent(record, signal, gpcMode)
const state = resolved.state
const decided = resolved.decided && !reopened
const consentId = record?.id
const persist = useCallback(
(next: ConsentState) => {
// Withdrawal cleanup: for any category flipping true → false, delete the
// cookies tied to it. GDPR: withdrawing consent must stop the processing.
for (const cat of Object.keys(cookieMap) as ConsentCategory[]) {
if (state[cat] === true && next[cat] !== true) {
for (const pattern of cookieMap[cat] ?? []) {
for (const name of matchingCookies(pattern)) {deleteCookie(name)}
}
/** Withdrawal: for every category going from on to off, delete its cookies and storage keys, tell the tools. */
const withdraw = useCallback(
(prev: ConsentState, next: ConsentState) => {
for (const cat of Object.keys(prev) as ConsentCategory[]) {
if (cat === 'necessary' || prev[cat] !== true || next[cat] === true) {continue}
for (const pattern of cookieMap[cat] ?? []) {
for (const name of matchingCookies(pattern)) {deleteCookie(name)}
}
for (const pattern of storageMap[cat] ?? []) {deleteStorageKeys(pattern)}
}
signalVendors(prev, next)
},
[cookieMap, storageMap],
)
const id = consentId ?? newConsentId()
const write = useCallback(
(prev: ConsentState, next: ConsentState, id: string, gpc: boolean) => {
// GDPR: withdrawing consent must stop the processing.
withdraw(prev, next)
const secure = location.protocol === 'https:' ? ';secure' : ''
writeConsentCookie(serializeConsent(next, version, id), `;path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`)
setReopened(false)
writeConsentCookie(serializeConsent(next, version, id, gpc), `;path=/;max-age=${maxAge};samesite=lax${secure}`)
// 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
// look like it worked while nothing changed.
updateConsent(next)
try {
onDecision?.({ id, state: next, version })
onDecision?.({ gpc, id, state: next, version })
} catch {
// a logging hook must never break the banner
}
},
[state, consentId, version, onDecision, cookieMap],
[withdraw, version, maxAge, onDecision],
)
const persist = useCallback(
(next: ConsentState) => {
// `gpc`: the signal as the browser sends it, whatever the mode — a fact about when the choice was made.
write(record?.state ?? DEFAULT_CONSENT, next, consentId ?? newConsentId(), gpcFromNavigator())
setReopened(false)
},
[write, record, consentId],
)
// The signal appeared after a choice made without it that granted analytics or marketing: both go off now, their
// cookies with them, and the record says so (gpc: true). Once per stored record.
const rewritten = useRef<null | string>(null)
const staleKey = resolved.stale && record ? `${record.id ?? ''}|${record.timestamp}` : null
useEffect(() => {
if (!staleKey || !record || rewritten.current === staleKey) {return}
rewritten.current = staleKey
write(record.state, resolved.state, record.id ?? newConsentId(), true)
// runs for a stale record only; `write` reads everything else it needs
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [staleKey])
const acceptAll = useCallback(() => persist(ACCEPT_ALL_CONSENT), [persist])
const rejectAll = useCallback(() => persist(REJECT_ALL_CONSENT), [persist])
const savePreferences = useCallback(
@@ -144,5 +211,5 @@ export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) {
)
const reopen = useCallback(() => setReopened(true), [])
return { acceptAll, consentId, decided, hydrated, rejectAll, reopen, savePreferences, serverRead, state }
return { acceptAll, consentId, decided, gpc: resolved.gpc, gpcMode, hydrated, rejectAll, reopen, savePreferences, serverRead, state }
}
+41
View File
@@ -0,0 +1,41 @@
import type { ConsentState } from './categories.js'
/* eslint-disable @typescript-eslint/no-explicit-any -- vendor globals (fbq, clarity, ttq) are untyped */
const granted = (on: boolean) => (on ? 'granted' : 'denied')
/**
* Tells the tools that are already running on this page about a change of consent, so a withdrawal stops them at
* once rather than at the next page load. Only tools that have a call for it, and only when they are loaded:
*
* - Microsoft Clarity (analytics): `clarity('consentv2', …)`; analytics off → `clarity('consent', false)`, which
* erases its cookies and stops it.
* - Meta Pixel (marketing): `fbq('consent', 'revoke' | 'grant')`.
* - TikTok Pixel (marketing): `ttq.revokeConsent()` / `ttq.grantConsent()`.
*
* Google tags get the Consent Mode update separately (googleConsent.ts). LinkedIn Insight has no such call: it stops
* with the next page load. Never throws.
*/
export function signalVendors(prev: ConsentState, next: ConsentState): void {
if (typeof window === 'undefined') {return}
const w = window as any
try {
if (prev.marketing !== next.marketing) {
if (typeof w.fbq === 'function') {w.fbq('consent', next.marketing ? 'grant' : 'revoke')}
const ttq = w.ttq
const call = next.marketing ? ttq?.grantConsent : ttq?.revokeConsent
if (typeof call === 'function') {call.call(ttq)}
}
if (typeof w.clarity === 'function' && (prev.analytics !== next.analytics || prev.marketing !== next.marketing)) {
if (next.analytics) {w.clarity('consentv2', clarityConsent(next))}
else {w.clarity('consent', false)}
}
} catch {
// a vendor's call must never break the banner
}
}
/** Clarity's consent API v2 for a state (`ad_Storage` follows marketing, `analytics_Storage` analytics). */
export function clarityConsent(state: Pick<ConsentState, 'analytics' | 'marketing'>): { ad_Storage: string; analytics_Storage: string } {
return { ad_Storage: granted(state.marketing), analytics_Storage: granted(state.analytics) }
}
+134
View File
@@ -0,0 +1,134 @@
import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { configFile } from '../project.js'
import { lt, stripComments } from '../util.js'
const cfg = (ctx: DoctorContext) => stripComments(ctx.read(configFile(ctx) ?? ''))
const SQL_ADAPTERS = ['@payloadcms/db-postgres', '@payloadcms/db-vercel-postgres', '@payloadcms/db-sqlite', '@payloadcms/db-d1-sqlite']
/** The consent log is on unless the config says `consentLog: false` (the default since 1.17.0). */
const consentLogOn = (ctx: DoctorContext) => {
const code = cfg(ctx)
if (/\bconsentLog\s*:\s*false\b/.test(code)) {return false}
const v = ctx.pluginVersion
// Before 1.17.0 it was opt-in.
return v && lt(v, '1.17.0') ? /\bconsentLog\s*:\s*(?:true|\{)/.test(code) : true
}
/** .tsx files of the site (app/ and components/), comments stripped — where the layout wires the banner. */
function siteFiles(ctx: DoctorContext): Array<{ code: string; file: string }> {
const files: string[] = []
const walk = (dir: string, depth: number) => {
for (const name of ctx.list(dir)) {
if (files.length >= 600 || name === 'node_modules' || name.startsWith('.') || name === '(payload)') {continue}
if (/\.tsx$/.test(name)) {files.push(`${dir}/${name}`)}
else if (!name.includes('.') || /^\(.*\)$|^\[.*\]$/.test(name)) {if (depth < 8) {walk(`${dir}/${name}`, depth + 1)}}
}
}
walk(`${ctx.src}app`, 0)
walk(`${ctx.src}components`, 0)
return files.map((file) => ({ code: stripComments(ctx.read(file)), file }))
}
/** The props of every `<Tag …>` in a file, up to its closing `>` / `/>` at the top level (props may hold JSX). */
function tagProps(code: string, tag: string): string[] {
const out: string[] = []
const re = new RegExp(`<${tag}\\b`, 'g')
for (let m = re.exec(code); m; m = re.exec(code)) {
let depth = 0
let i = m.index + m[0].length
for (; i < code.length; i++) {
const ch = code[i]
if (ch === '{') {depth++}
else if (ch === '}') {depth--}
else if (ch === '>' && depth === 0) {break}
}
out.push(code.slice(m.index + m[0].length, i))
}
return out
}
export const consentRules: DoctorRule[] = [
{
// Postgres / SQLite: the consent log (on by default since 1.17.0) is a table. Without a migration that creates
// it, every banner choice answers 503 and nothing is recorded (the site keeps working).
id: 'consent-log-migration',
check: (ctx) => {
if (!SQL_ADAPTERS.some((name) => ctx.installed(name)) || !consentLogOn(ctx)) {return []}
const dirs = [`${ctx.src}migrations`, 'migrations'].filter((dir) => ctx.exists(dir))
const files = dirs.flatMap((dir) => ctx.list(dir).filter((name) => /\.(?:ts|js|mjs|sql|json)$/.test(name)).map((name) => `${dir}/${name}`))
if (files.some((file) => /consent_records/.test(ctx.read(file)))) {return []}
return [{
file: configFile(ctx) ?? undefined,
fix: "pnpm payload migrate:create consent-log, commit it, and have it applied when the new container starts (prodMigrations, or `pnpm payload migrate && pnpm start`) — or iapl({ consentLog: false })",
message: files.length
? 'no migration creates the consent log table `consent_records` (the consent log is on by default since 1.17.0): banner choices are not recorded in production'
: 'a SQL database and no migrations folder: the consent log table `consent_records` (on by default since 1.17.0) must be created by a migration, or choices are not recorded',
severity: files.length ? 'error' : 'warning',
}]
},
docs: 'docs/consent.md#consent-log-details-consentlog',
group: 'consent',
source: 'static',
},
{
// The banner's compliant defaults (1.17.0) switched off in the layout: allowed, reported.
id: 'consent-banner',
check: (ctx) => {
const out: RuleFinding[] = []
const files = siteFiles(ctx)
const logOn = consentLogOn(ctx)
const anyReopen = files.some(({ code }) => /\breopen\b/.test(code))
let layoutMode: 'advanced' | 'basic' | null = null
for (const { code, file } of files) {
for (const props of tagProps(code, 'CookieBanner')) {
if (/\bequalChoice\s*=\s*\{\s*false\s*\}/.test(props)) {
out.push({ file, fix: 'remove equalChoice={false} (the default since 1.17.0 styles "Reject" like "Accept all")', message: '"Reject" is styled weaker than "Accept all" (equalChoice={false}); EU authorities expect refusing to be as easy and as visible as accepting', severity: 'warning' })
}
const order = props.match(/\border\s*=\s*\{\s*\[([^\]]*)\]/)?.[1]
if (order !== undefined && !/['"]reject['"]/.test(order)) {
out.push({ file, fix: "keep 'reject' in <CookieBanner order>", message: 'the banner has no "Reject" button on the first layer (order without \'reject\')', severity: 'warning' })
}
}
for (const tag of ['SiteProviders', 'ConsentProvider']) {
for (const props of tagProps(code, tag)) {
if (/\bgpc\s*=\s*\{\s*false\s*\}/.test(props)) {
out.push({ file, fix: 'remove gpc={false} (default: honour Global Privacy Control), or record the reason in iapl-doctor.json', message: `<${tag} gpc={false}>: the browser's Global Privacy Control signal is ignored`, severity: 'warning' })
}
if (/\bgpc\s*=\s*(?:"ask"|'ask'|\{\s*['"]ask['"]\s*\})/.test(props)) {
out.push({ file, message: `<${tag} gpc="ask">: visitors with Global Privacy Control still see the banner (nothing is sent before a choice)`, severity: 'info' })
}
if (tag === 'SiteProviders' && /\bcookieButton\s*=\s*\{\s*false\s*\}/.test(props) && !anyReopen) {
out.push({ file, fix: 'keep <CookieButton /> or call useConsentContext().reopen from a link in the footer', message: 'no way to reopen the cookie settings (cookieButton={false} and no `reopen` anywhere): withdrawing consent must be as easy as giving it', severity: 'warning' })
}
if (logOn && /\blogEndpoint\s*=\s*\{\s*false\s*\}/.test(props)) {
out.push({ file, message: `<${tag} logEndpoint={false}> while the consent log is on: banner choices are not recorded`, severity: 'info' })
}
if (tag === 'ConsentProvider' && logOn && !/\blogEndpoint\b/.test(props)) {
out.push({ file, fix: 'logEndpoint="/api/ipal/consent" on <ConsentProvider> (SiteProviders does it by itself)', message: '<ConsentProvider> without logEndpoint: the consent log is on but this layout never posts to it', severity: 'warning' })
}
const mode = props.match(/\bconsentMode\s*:\s*['"](advanced|basic)['"]/)?.[1] as 'advanced' | 'basic' | undefined
if (mode) {layoutMode = mode}
}
}
const analyticsMode = tagProps(code, 'Analytics').map((p) => p.match(/\bconsentMode\s*=\s*(?:"|'|\{\s*['"])(advanced|basic)/)?.[1]).find(Boolean) as 'advanced' | 'basic' | undefined
if (analyticsMode) {layoutMode = analyticsMode}
}
// The crawl judges Google's requests by its own consentMode: it must match the layout's.
const code = cfg(ctx)
if (/cookieScanner\s*:\s*\{[\s\S]*?\bcrawl\s*:\s*(?!false)/.test(code)) {
const crawlMode = code.match(/\bcrawl\s*:\s*\{[^}]*\bconsentMode\s*:\s*['"](advanced|basic)['"]/)?.[1] ?? 'advanced'
const site = layoutMode ?? 'advanced'
if (crawlMode !== site) {
out.push({ file: configFile(ctx) ?? undefined, fix: `cookieScanner: { crawl: { consentMode: '${site}' } }`, message: `the layout runs Consent Mode '${site}' but the cookie crawl judges Google's requests as '${crawlMode}'`, severity: 'warning' })
}
}
return out
},
docs: 'docs/consent.md',
group: 'consent',
source: 'static',
},
]
+2
View File
@@ -8,6 +8,7 @@ import { readEnv } from '../shared/envName.js'
import { createDoctorContext, doctorConfigFile, type DoctorContext, loadDoctorConfig } from './project.js'
import { agentRules } from './rules/agents.js'
import { blockRules } from './rules/blocks.js'
import { consentRules } from './rules/consent.js'
import { envRules } from './rules/env.js'
import { layoutRules } from './rules/layout.js'
import { legacyRules } from './rules/legacy.js'
@@ -34,6 +35,7 @@ export const doctorRules: DoctorRule[] = [
...layoutRules,
...envRules,
...securityRules,
...consentRules,
...mailRules,
...agentRules,
...legacyRules,
+26 -5
View File
@@ -1,6 +1,7 @@
import type { ReactNode } from 'react'
import type { AnalyticsProps } from '../analytics/Analytics.js'
import type { GpcMode } from '../consent/gpc.js'
import type { ConsentCookieMap } from '../consent/useConsent.js'
import type { LightboxProviderProps } from '../lightbox/LightboxProvider.js'
import type { PageStatsProps } from '../stats/PageStats.js'
@@ -20,7 +21,7 @@ import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
export type SiteProvidersProps = {
/** `defer` etc. for <Analytics>; `false` = no analytics tags at all. */
analytics?: false | Omit<AnalyticsProps, keyof SiteShell['analytics']>
/** The cookie banner. Default `<CookieBanner />`; pass your own configured one (`equalChoice`, classNames) or `false`. */
/** The cookie banner. Default `<CookieBanner />`; pass your own configured one (`settings`, classNames) or `false`. */
banner?: false | ReactNode
children: ReactNode
/**
@@ -33,6 +34,11 @@ export type SiteProvidersProps = {
cookieButton?: false | ReactNode
/** Extra cookies per category to delete when consent is withdrawn. */
cookieMap?: ConsentCookieMap
/**
* Global Privacy Control: `'honour'` (default), `'ask'` or `false`. See ConsentProvider `gpc` and
* docs/consent.md → Global Privacy Control.
*/
gpc?: GpcMode
/** More site-wide JSON-LD nodes next to shell.jsonLd (e.g. buildNavigationJsonLd). */
jsonLd?: (null | Record<string, unknown> | undefined)[]
/**
@@ -43,8 +49,13 @@ export type SiteProvidersProps = {
* yourself in a client component.
*/
lightbox?: boolean | Omit<LightboxProviderProps, 'children' | 'renderDialog' | 'renderImage'>
/** Consent log endpoint, e.g. '/api/ipal/consent' (iapl consentLog: true). */
logEndpoint?: string
/**
* Consent log endpoint. Default: the site shell's (`shell.consentLogEndpoint`, '/api/ipal/consent' whenever the
* plugin's consent log is on — the default since 1.17.0). `false` = decisions are not posted.
*/
logEndpoint?: false | string
/** Days a choice is kept before the banner asks again. Default 180. */
maxAgeDays?: number
/**
* 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, the cookie
@@ -77,7 +88,7 @@ export type SiteProvidersProps = {
*
* const shell = await getSiteShell(locale)
* <body>
* <SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
* <SiteProviders shell={shell} banner={<CookieBanner settings="detailed" />}>
* <Header … /><main>{children}</main><Footer … />
* </SiteProviders>
* </body>
@@ -92,9 +103,11 @@ export function SiteProviders({
consentCookie,
cookieButton,
cookieMap,
gpc,
jsonLd = [],
lightbox = false,
logEndpoint,
maxAgeDays,
nonce,
preconnect = true,
shell,
@@ -106,7 +119,15 @@ export function SiteProviders({
{theme ? <ThemeScript {...shell.theme} nonce={nonce ?? undefined} /> : null}
{preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} cookieValue={consentCookie} logEndpoint={logEndpoint} nonce={nonce} texts={shell.consent}>
<ConsentProvider
cookieMap={cookieMap}
cookieValue={consentCookie}
gpc={gpc}
logEndpoint={logEndpoint === false ? undefined : (logEndpoint ?? shell.consentLogEndpoint ?? undefined)}
maxAgeDays={maxAgeDays}
nonce={nonce}
texts={shell.consent}
>
<TurnstileProvider siteKey={shell.turnstileSiteKey}>
{lightbox ? (
<LightboxProvider texts={shell.lightboxTexts} {...(lightbox === true ? {} : lightbox)}>
@@ -16,6 +16,7 @@ import type { FormNotificationTexts } from '../notifications/types.js'
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapRouteOptions, SitemapStyleOptions } from '../seo/index.js'
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
import { CONSENT_LOG_PATH } from '../consent/consentLog.js'
import { getConsentTexts } from '../consent/getConsentTexts.js'
import { isPathAllowed, isPathVisibleIn } from '../construction/logic.js'
import { pathOf } from '../construction/visibility.js'
@@ -829,6 +830,7 @@ export function createContentHelpers({
return {
analytics,
consent,
consentLogEndpoint: consentLogEndpointOf(payload.config),
formTexts: notifications.form,
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
lightboxTexts: notifications.lightbox,
@@ -909,6 +911,12 @@ export function createContentHelpers({
export type SiteShell = {
analytics: AnalyticsConfig
consent: ConsentTexts
/**
* Where the cookie banner posts each decision (the consent log): '/api/ipal/consent' (with the config's API
* route) while the plugin's consent log is on — the default — or null with `consentLog: false`. Optional so a
* hand-built shell keeps compiling. <SiteProviders> uses it unless `logEndpoint` is given.
*/
consentLogEndpoint?: null | string
formTexts: FormNotificationTexts
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
jsonLd: Record<string, unknown>[]
@@ -921,3 +929,10 @@ export type SiteShell = {
}
export type ContentHelpers = ReturnType<typeof createContentHelpers>
/** The consent log's public path when the plugin added its endpoint (consentLog on), else null. */
function consentLogEndpointOf(config: { endpoints?: unknown; routes?: { api?: string } }): null | string {
const endpoints = Array.isArray(config.endpoints) ? (config.endpoints as Array<{ method?: string; path?: string }>) : []
if (!endpoints.some((e) => e.path === CONSENT_LOG_PATH && e.method === 'post')) {return null}
return `${(config.routes?.api ?? '/api').replace(/\/+$/, '')}${CONSENT_LOG_PATH}`
}
+6 -5
View File
@@ -5,7 +5,8 @@ import { useEffect, useRef } from 'react'
import { usePathname } from 'next/navigation.js'
import { useConsentContext } from '../consent/ConsentContext.js'
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent } from '../consent/storage.js'
import { readEffectiveConsent } from '../consent/consentStore.js'
import { CONSENT_MAX_AGE, CONSENT_VERSION } from '../consent/storage.js'
import { VISITOR_COOKIE } from './visitorCookie.js'
// Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP).
@@ -56,7 +57,7 @@ export type PageStatsProps = {
*/
export function PageStats({ endpoint = '/api/ipal/hit', locale, visitorCookie = VISITOR_COOKIE }: PageStatsProps) {
const pathname = usePathname()
const { texts } = useConsentContext()
const { gpcMode, texts } = useConsentContext()
const firstHit = useRef(true)
useEffect(() => {
@@ -66,9 +67,9 @@ export function PageStats({ endpoint = '/api/ipal/hit', locale, visitorCookie =
if (firstHit.current && document.referrer) {body.r = document.referrer}
firstHit.current = false
if (locale) {body.l = locale}
// The cookie, not context state: on a full page load this effect runs before
// useConsent has read the cookie, so state would still say "no consent".
if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId(visitorCookie)}
// The cookie (with Global Privacy Control applied), not context state: on a full page load this effect runs
// while React still holds the server's "no consent".
if (readEffectiveConsent(texts.version ?? CONSENT_VERSION, gpcMode).state.analytics) {body.v = ensureVisitorId(visitorCookie)}
const json = JSON.stringify(body)
if (!navigator.sendBeacon?.(endpoint, new Blob([json], { type: 'application/json' }))) {
+6 -3
View File
@@ -2,7 +2,8 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
import { CONSENT_COOKIE, CONSENT_VERSION, parseConsent } from '../consent/storage.js'
import { gpcFromHeaders, resolveConsent } from '../consent/gpc.js'
import { CONSENT_COOKIE, CONSENT_VERSION, readConsentRecord } from '../consent/storage.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { STATS_SLUG } from './collection.js'
@@ -72,8 +73,10 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
const host = headers.get('host') ?? ''
let visitorId: string | undefined
if (typeof body.v === 'string' && VISITOR_ID_PATTERN.test(body.v)) {
const consent = parseConsent(readCookie(headers.get('cookie'), CONSENT_COOKIE), await policyVersion(req))
if (consent?.analytics) {visitorId = body.v}
const record = readConsentRecord(readCookie(headers.get('cookie'), CONSENT_COOKIE), await policyVersion(req))
// Global Privacy Control (Sec-GPC: 1) over a choice made WITHOUT it: the browser rewrites that choice with
// analytics off (gpc.ts); until it has, the server does not take the id either.
if (record && resolveConsent(record, gpcFromHeaders(headers)).state.analytics) {visitorId = body.v}
}
const now = new Date()
+3 -3
View File
@@ -778,9 +778,9 @@ export const iapl = (options: IaplOptions): Plugin => {
config.endpoints = [...(config.endpoints ?? []), buildDoctorEndpoint(options.doctor ?? {})]
}
// --- consent log: proof of consent (opt-in) ---
if (options.consentLog) {
const logOptions = options.consentLog === true ? {} : options.consentLog
// --- consent log: proof of consent (on by default since 1.17.0; `consentLog: false` turns it off) ---
if (options.consentLog !== false) {
const logOptions = options.consentLog === true || options.consentLog === undefined ? {} : options.consentLog
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)]
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
+5 -3
View File
@@ -90,9 +90,11 @@ export type IaplOptions = {
/** Internationalization — locales, default locale, fallback behavior */
/**
* Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records`
* collection and POST /api/ipal/consent. Pass `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Stores a random id, choices, policy version and time — no personal data.
* `true` or `{ retentionDays, collectionOverrides }` (default 1095 days). Default off.
* collection and POST /api/ipal/consent. <SiteProviders> posts there by itself; a layout with its own
* `<ConsentProvider>` passes `logEndpoint="/api/ipal/consent"`.
* Stores a random id, choices, policy version and time — no IP, no user agent.
* `{ retentionDays, collectionOverrides }` (default 1095 days). **On by default since 1.17.0**; `false` turns it
* off. Postgres / SQLite: a new table — create and apply a migration in the same deploy (docs/consent.md).
*/
consentLog?: boolean | ConsentLogOptions
+1 -1
View File
@@ -491,7 +491,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
const hooks = async (options: Record<string, unknown>) =>
(await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, (c.hooks?.beforeOperation ?? []).filter(ruleHook).length])
(await iapl({ access: { authCollection: 'users' }, consentLog: false, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, (c.hooks?.beforeOperation ?? []).filter(ruleHook).length])
expect(await hooks({})).toEqual([['customers', 0], ['users', 1]])
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 0], ['users', 0]])
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
+483
View File
@@ -0,0 +1,483 @@
// @vitest-environment happy-dom
/**
* Consent compliance (1.17.0): Global Privacy Control honoured before the first paint on a static page, "Reject" as
* prominent as "Accept all" by default, a withdrawal that stops the tools already running and clears their storage,
* Clarity's consent signal, the consent log on by default and failing soft without its table, and the doctor rules
* that report a weaker setup. docs/consent.md and docs/consent-behaviour-spec.md describe each.
*/
import type { Config, PayloadRequest } from 'payload'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
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 type { I18nConfig } from '../src/modules/i18n/index.js'
import { Analytics } from '../src/modules/analytics/Analytics.js'
import { loadClarity } from '../src/modules/analytics/pixels.js'
import { shouldLoadGoogle } from '../src/modules/analytics/shouldLoadGoogle.js'
import { ConsentProvider } from '../src/modules/consent/ConsentContext.js'
import { buildConsentLogEndpoint, isMissingTableError } from '../src/modules/consent/consentLog.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 { gpcFromHeaders, gpcWellKnown, resolveConsent } from '../src/modules/consent/gpc.js'
import { CONSENT_COOKIE, readConsentRecord, serializeConsent } from '../src/modules/consent/storage.js'
import { runDoctor } from '../src/modules/doctor/run.js'
import { SiteProviders } from '../src/modules/frontend/SiteProviders.js'
import { iapl } from '../src/plugin.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,
cookies: [
{ name: 'chat_session', category: 'marketing' as const, storage: 'localStorage' as const },
{ name: 'vid_*', category: 'analytics' as const, storage: 'sessionStorage' as const },
{ name: 'theme', category: 'necessary' as const, storage: 'localStorage' as const },
],
version: 3,
}
const stored = (state: ConsentState, gpc?: boolean) => serializeConsent(state, 3, 'a1b2c3d4e5f6a7b8c9d0e1f2', gpc)
type Tree = { analytics?: object; banner?: object; gpc?: 'ask' | 'honour' | false; logEndpoint?: string }
const tree = (o: Tree = {}) =>
h(
ConsentProvider,
{ gpc: o.gpc, logEndpoint: o.logEndpoint, texts },
h('main', null, 'page'),
h(CookieBanner, o.banner ?? {}),
h(CookieButton),
o.analytics ? h(Analytics, o.analytics) : null,
)
const setGpc = (on: boolean | undefined) => {
if (on === undefined) {delete (navigator as { globalPrivacyControl?: boolean }).globalPrivacyControl}
else {Object.defineProperty(navigator, 'globalPrivacyControl', { configurable: true, value: on })}
}
const clearCookies = () => {
for (const c of document.cookie.split('; ')) {
const name = c.split('=')[0]
if (name) {document.cookie = `${name}=;path=/;max-age=0`}
}
}
const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1])
const storedRecord = () => readConsentRecord(liveCookies().find((c) => c.startsWith(`${CONSENT_COOKIE}=`))?.split('=')[1], 3)
const setConsentCookie = (value: string) => {
document.cookie = `${CONSENT_COOKIE}=${value};path=/`
}
let container: HTMLDivElement
let root: Root | undefined
let injected: string[]
let errors: ReturnType<typeof vi.spyOn>
beforeEach(() => {
clearCookies()
resetConsentStore()
localStorage.clear()
sessionStorage.clear()
setGpc(undefined)
for (const key of ['dataLayer', 'fbq', '_fbq', 'clarity', 'ttq']) {delete (window as unknown as Record<string, unknown>)[key]}
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()
setGpc(undefined)
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
const banner = () => container.querySelector<HTMLElement>('[data-ipal="banner"]')
const button = () => container.querySelector<HTMLElement>('[data-ipal="cookie-button"]')
const click = (name: string) => act(() => container.querySelector<HTMLElement>(`[data-ipal="${name}"]`)!.click())
/** Server HTML, the inline script as the parser runs it (with the real `navigator`), then hydration. */
function load(o: Tree = {}) {
const node = tree(o)
const html = renderToString(node)
container.innerHTML = html
const el = container.querySelector<HTMLScriptElement>('[data-ipal="banner-script"]')
const code = /<script[^>]*data-ipal="banner-script"[^>]*>(?<code>.*?)<\/script>/s.exec(html)?.groups?.code
if (el && code) {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
new Function('document', code)({ get cookie() { return document.cookie }, currentScript: el })
}
const shownBeforeHydration = banner() !== null && !banner()!.hasAttribute('hidden') && banner()!.style.display !== 'none'
act(() => {
root = hydrateRoot(container, node)
})
return { html, shownBeforeHydration }
}
const layer = () => [...(window.dataLayer ?? [])].map((e) => (Object.prototype.toString.call(e) === '[object Arguments]' ? Array.from(e as ArrayLike<unknown>) : e))
describe('resolveConsent: Global Privacy Control × stored choice × mode', () => {
const rec = (state: ConsentState, gpc?: boolean) => ({ ...(gpc === undefined ? {} : { gpc }), state })
test.each([
// [label, record, signal, mode, decided, analytics, marketing, stale, gpc]
['no choice, no signal', null, false, 'honour', false, false, false, false, false],
['no choice, signal, honour → no banner, off', null, true, 'honour', true, false, false, false, true],
['no choice, signal, ask → banner', null, true, 'ask', false, false, false, false, true],
['no choice, signal, ignored', null, true, false, false, false, false, false, false],
['grant made WITH the signal stands', rec(ACCEPT, true), true, 'honour', true, true, true, false, true],
['grant made WITHOUT the signal gives way', rec(ACCEPT, false), true, 'honour', true, false, false, true, true],
['…also in ask mode', rec(ACCEPT, false), true, 'ask', true, false, false, true, true],
['…not when the signal is ignored', rec(ACCEPT, false), true, false, true, true, true, false, false],
['a record from before 1.17.0 (no gpc field) stands', rec(ACCEPT), true, 'honour', true, true, true, false, true],
['a refusal made without the signal: nothing to change', rec(REJECT, false), true, 'honour', true, false, false, false, true],
['the absence of the signal is never consent', rec(REJECT, true), false, 'honour', true, false, false, false, false],
] as const)('%s', (_l, record, signal, mode, decided, analytics, marketing, stale, gpc) => {
const r = resolveConsent(record, signal, mode)
expect([r.decided, r.state.analytics, r.state.marketing, r.stale, r.gpc]).toEqual([decided, analytics, marketing, stale, gpc])
})
test('functional is not the signal\'s business: a functional grant made without it stays', () => {
expect(resolveConsent(rec({ ...ACCEPT }, false), true).state.functional).toBe(true)
})
})
describe('the stored record', () => {
test('gpc goes in and comes out; a non-boolean value is dropped; records without it still read', () => {
expect(readConsentRecord(stored(ACCEPT, true), 3)!.gpc).toBe(true)
expect(readConsentRecord(stored(ACCEPT, false), 3)!.gpc).toBe(false)
expect(readConsentRecord(stored(ACCEPT), 3)!).not.toHaveProperty('gpc')
const odd = encodeURIComponent(JSON.stringify({ gpc: 'yes', state: ACCEPT, timestamp: 'x', version: 3 }))
expect(readConsentRecord(odd, 3)!).not.toHaveProperty('gpc')
})
})
describe('the first-paint script and Global Privacy Control', () => {
const run = (o: { cookie?: string; gpc?: 'ask' | 'honour' | false; signal?: boolean }) => {
setGpc(o.signal)
const b = { removeAttribute: (n: string) => void b.removed.push(n), removed: [] as string[], style: {} as Record<string, string>, addEventListener() {} }
// eslint-disable-next-line @typescript-eslint/no-implied-eval
new Function('document', consentBannerScript({ gpc: o.gpc, version: 3 }))({ cookie: o.cookie ?? '', currentScript: { previousElementSibling: b } })
return b.style.display === 'none' ? 'hidden' : b.removed.includes('hidden') ? 'shown' : 'untouched'
}
test.each([
['signal, honour (default)', { signal: true }, 'hidden'],
['signal, ask', { gpc: 'ask' as const, signal: true }, 'shown'],
['signal, ignored', { gpc: false as const, signal: true }, 'shown'],
['no signal (false)', { signal: false }, 'shown'],
['no support (undefined)', {}, 'shown'],
['signal and a current choice', { cookie: `${CONSENT_COOKIE}=${stored(REJECT)}`, signal: true }, 'hidden'],
])('%s → %s', (_l, o, want) => expect(run(o)).toBe(want))
})
describe('honour (default): a browser with Global Privacy Control', () => {
test('no banner before or after hydration, the button instead; the same page HTML as without the signal', () => {
const plain = renderToString(tree())
setGpc(true)
const r = load()
expect(r.html).toBe(plain)
expect(r.shownBeforeHydration).toBe(false)
expect(banner()).toBeNull()
expect(button()).not.toBeNull()
expect(liveCookies()).toEqual([]) // nothing stored for a visitor who only sends the signal
})
test('advanced mode: nothing reaches Google or a pixel; the Consent Mode default is all denied', () => {
setGpc(true)
load({ analytics: { clarityProjectId: 'clar', gtmContainerId: 'GTM-TEST', metaPixelId: '123' } })
expect(injected).toEqual([])
expect(layer()[0]).toEqual(['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied' })])
expect(layer().some((e) => (e as { event?: string }).event === 'gtm.js')).toBe(false)
})
test('the settings window says the signal is honoured; an explicit grant there wins and is stored with gpc: true', () => {
const fetchMock = vi.fn((_u: string, _i: { body: string }) => Promise.resolve(new Response(null)))
vi.stubGlobal('fetch', fetchMock)
setGpc(true)
load({ analytics: { gtmContainerId: 'GTM-TEST', metaPixelId: '123' }, logEndpoint: '/api/ipal/consent' })
click('cookie-button')
expect(container.querySelector('[data-ipal="gpc-notice"]')?.textContent).toBe(CONSENT_FALLBACK.gpcNotice)
click('accept')
expect(storedRecord()).toMatchObject({ gpc: true, state: ACCEPT })
expect(injected).toEqual(expect.arrayContaining(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST', 'https://connect.facebook.net/en_US/fbevents.js']))
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({ gpc: true, state: ACCEPT })
})
test('next page view with that grant: kept (made with the signal on)', () => {
setConsentCookie(stored(ACCEPT, true))
setGpc(true)
load({ analytics: { gtmContainerId: 'GTM-TEST' } })
expect(storedRecord()!.state).toEqual(ACCEPT)
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
})
})
describe('the signal appears after a grant made without it', () => {
test('analytics and marketing go off without asking: cookies deleted, Google told, record rewritten and logged', () => {
const fetchMock = vi.fn((_u: string, _i: { body: string }) => Promise.resolve(new Response(null)))
vi.stubGlobal('fetch', fetchMock)
setConsentCookie(stored(ACCEPT, false))
document.cookie = '_ga=GA1.1.1;path=/'
document.cookie = '_fbp=fb.1;path=/'
setGpc(true)
load({ analytics: { gtmContainerId: 'GTM-TEST', metaPixelId: '123' }, logEndpoint: '/api/ipal/consent' })
expect(banner()).toBeNull()
expect(storedRecord()).toMatchObject({ gpc: true, id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state: { ...ACCEPT, analytics: false, marketing: false } })
expect(liveCookies().filter((c) => /^_ga|^_fbp/.test(c))).toEqual([])
expect(layer()[0]).toEqual(['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied', functionality_storage: 'granted' })])
expect(injected).toEqual([])
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({ gpc: true, state: { analytics: false, marketing: false } })
})
test('a record from before 1.17.0 stands (we cannot know which came first)', () => {
setConsentCookie(stored(ACCEPT))
setGpc(true)
load({ analytics: { gtmContainerId: 'GTM-TEST' } })
expect(storedRecord()!.state).toEqual(ACCEPT)
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
})
test("gpc={false}: the signal is ignored, the grant stands", () => {
setConsentCookie(stored(ACCEPT, false))
setGpc(true)
load({ gpc: false })
expect(storedRecord()!.state).toEqual(ACCEPT)
})
})
describe("gpc='ask'", () => {
test('the banner is shown with the notice; nothing reaches Google until a choice', () => {
setGpc(true)
const r = load({ analytics: { gtmContainerId: 'GTM-TEST' }, gpc: 'ask' })
expect(r.shownBeforeHydration).toBe(true)
expect(container.querySelector('[data-ipal="gpc-notice"]')).not.toBeNull()
expect(injected).toEqual([])
click('accept')
expect(storedRecord()).toMatchObject({ gpc: true, state: ACCEPT })
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
})
})
describe('shouldLoadGoogle', () => {
test.each([
['advanced', false, REJECT, true],
['advanced', true, REJECT, false],
['advanced', true, { ...REJECT, analytics: true }, true],
['basic', false, REJECT, false],
['basic', true, { ...REJECT, marketing: true }, true],
] as const)('%s, gpc %s', (consentMode, gpc, state, want) => {
expect(shouldLoadGoogle({ consentMode, gpc, ready: true, state })).toBe(want)
})
})
describe('withdrawal stops what already runs', () => {
test('pixels get their revoke call, Clarity stops, listed storage keys go; necessary keys stay', () => {
setConsentCookie(stored(ACCEPT, false))
localStorage.setItem('chat_session', 'x')
localStorage.setItem('theme', 'dark')
sessionStorage.setItem('vid_1', 'y')
const fbq = vi.fn()
const clarity = vi.fn()
const revokeConsent = vi.fn()
Object.assign(window, { clarity, fbq, ttq: { grantConsent: vi.fn(), revokeConsent } })
load()
click('cookie-button')
click('reject')
expect(fbq).toHaveBeenCalledWith('consent', 'revoke')
expect(revokeConsent).toHaveBeenCalled()
expect(clarity).toHaveBeenCalledWith('consent', false)
expect(localStorage.getItem('chat_session')).toBeNull()
expect(sessionStorage.getItem('vid_1')).toBeNull()
expect(localStorage.getItem('theme')).toBe('dark')
})
test('granting marketing again on the same page: the pixel is told to grant', () => {
setConsentCookie(stored(REJECT, false))
const fbq = vi.fn()
Object.assign(window, { fbq })
load()
click('cookie-button')
click('accept')
expect(fbq).toHaveBeenCalledWith('consent', 'grant')
})
test('Clarity gets its consent signal when it loads (EEA visits need one)', () => {
loadClarity('clar', { analytics: true, marketing: false })
const queue = (window as unknown as { clarity: { q: unknown[][] } }).clarity.q
expect(queue[0]).toEqual(['consentv2', { ad_Storage: 'denied', analytics_Storage: 'granted' }])
})
})
describe('equal choice by default', () => {
const classOf = (html: string, action: string) => new RegExp(`class="([^"]*)" data-ipal="${action}"`).exec(html)?.[1]
test('"Reject" looks like "Accept all"; equalChoice={false} restores the secondary look', () => {
const html = renderToString(tree())
expect(classOf(html, 'reject')).toBe(classOf(html, 'accept'))
const old = renderToString(tree({ banner: { equalChoice: false } }))
expect(classOf(old, 'reject')).not.toBe(classOf(old, 'accept'))
})
test('an order without "reject" warns while developing', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
load({ banner: { order: ['settings', 'accept'] } })
expect(warn).toHaveBeenCalledWith(expect.stringContaining("has no 'reject'"))
})
})
describe('default texts', () => {
test('the extra sentence (change the choice; browser settings) and the GPC line, in both languages', () => {
expect(CONSENT_FALLBACK.message).toContain('set cookie rules in your browser')
expect(CONSENT_FALLBACK_PL.message).toContain('w przeglądarce')
expect(CONSENT_FALLBACK_PL.gpcNotice).toContain('Global Privacy Control')
})
})
describe('server side', () => {
test('gpcFromHeaders: only the exact value 1', () => {
expect(gpcFromHeaders(new Headers({ 'sec-gpc': '1' }))).toBe(true)
expect(gpcFromHeaders(new Headers({ 'sec-gpc': '0' }))).toBe(false)
expect(gpcFromHeaders(new Headers())).toBe(false)
expect(gpcFromHeaders(null)).toBe(false)
})
test('gpcWellKnown answers the site statement', async () => {
const res = gpcWellKnown({ lastUpdate: '2026-11-26' })()
expect(await res.json()).toEqual({ gpc: true, lastUpdate: '2026-11-26' })
})
test('SiteProviders posts to the shell\'s consent log endpoint by default; logEndpoint={false} turns it off', () => {
const fetchMock = vi.fn((_u: string, _i: object) => Promise.resolve(new Response(null)))
vi.stubGlobal('fetch', fetchMock)
const shell = { analytics: {}, consent: texts, consentLogEndpoint: '/api/ipal/consent', jsonLd: [], lightboxTexts: {}, theme: {}, turnstileSiteKey: null }
for (const [props, want] of [[{}, 1], [{ logEndpoint: false }, 0]] as const) {
fetchMock.mockClear()
clearCookies()
resetConsentStore()
const node = h(SiteProviders, { analytics: false, preconnect: false, shell, ...props }, h('main', null, 'page'))
container.innerHTML = renderToString(node)
act(() => {
root = hydrateRoot(container, node)
})
click('reject')
expect(fetchMock).toHaveBeenCalledTimes(want)
if (want) {expect(fetchMock.mock.calls[0][0]).toBe('/api/ipal/consent')}
act(() => root!.unmount())
root = undefined
}
})
})
describe('consent log: on by default, fails soft without its table', () => {
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
const base = () => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config
test('no option → the collection and the endpoint; consentLog: false → neither', async () => {
const on = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base())
expect(on.collections!.map((c) => c.slug)).toContain('consent-records')
expect(on.endpoints!.some((e) => e.path === '/ipal/consent' && e.method === 'post')).toBe(true)
const off = await iapl({ access: { authCollection: 'users' }, consentLog: false, i18n, twoFactor: false })(base())
expect(off.collections!.map((c) => c.slug)).not.toContain('consent-records')
expect((off.endpoints ?? []).some((e) => e.path === '/ipal/consent')).toBe(false)
})
test.each([
['postgres', new Error('relation "consent_records" does not exist')],
['postgres, schema', Object.assign(new Error('Failed query'), { cause: { message: 'relation "public.consent_records" does not exist' } })],
['sqlite', new Error('SQLITE_ERROR: no such table: consent_records')],
])('missing table (%s) is recognised', (_l, err) => expect(isMissingTableError(err)).toBe(true))
test('another error is not taken for a missing table', () => {
expect(isMissingTableError(new Error('relation "users" does not exist'))).toBe(false)
expect(isMissingTableError(new Error('connection refused'))).toBe(false)
})
test('a missing table: 503, one log line for many requests, never a throw', async () => {
const logger = { error: vi.fn() }
const payload = { create: vi.fn(async () => { throw new Error('relation "consent_records" does not exist') }), db: { deleteMany: vi.fn(async () => {}) }, logger }
const endpoint = buildConsentLogEndpoint()
const body = { gpc: true, id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state: REJECT, version: 1 }
const call = (ip: string) =>
(endpoint.handler as (r: PayloadRequest) => Promise<Response>)(
Object.assign(new Request('http://acme.pl/api/ipal/consent', { body: JSON.stringify(body), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' }), { payload }) as unknown as PayloadRequest,
)
expect((await call('203.0.113.10')).status).toBe(503)
expect((await call('203.0.113.11')).status).toBe(503)
const lines = logger.error.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('consent-records table does not exist'))
expect(lines.length).toBeLessThanOrEqual(1)
expect(payload.create).toHaveBeenCalledTimes(2)
// the body's gpc never reaches the record (the shape is unchanged)
expect(Object.keys((payload.create.mock.calls[0] as unknown as [{ data: object }])[0].data).sort()).toEqual(['choices', 'consentId', 'version'])
})
})
describe('doctor: consent rules', () => {
const packageRoot = path.resolve(import.meta.dirname, '..')
let dirs: string[] = []
afterEach(() => {
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
dirs = []
})
const project = (files: Record<string, object | string>) => {
const root = mkdtempSync(path.join(tmpdir(), 'iapl-consent-'))
dirs.push(root)
const all = {
'node_modules/@intecion/ipal-kit/package.json': { name: '@intecion/ipal-kit', version: '1.17.0' },
'package.json': { dependencies: { '@intecion/ipal-kit': '^1.17.0' }, name: 'acmepl-web' },
...files,
}
for (const [rel, content] of Object.entries(all)) {
const file = path.join(root, rel)
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content))
}
return root
}
const findings = async (files: Record<string, object | string>) =>
(await runDoctor({ offline: true, only: ['consent'], packageRoot, root: project(files), today: '2026-11-26', writeSeen: false })).findings.map((f) => `${f.rule}:${f.severity}:${f.message.slice(0, 60)}`)
const pg = { 'node_modules/@payloadcms/db-postgres/package.json': { name: '@payloadcms/db-postgres', version: '3.70.0' } }
const config = (opts = '') => ({ 'src/payload.config.ts': `export default buildConfig({ plugins: [iapl({ i18n${opts} })] })` })
test('Postgres, consent log on, no migration creating consent_records → error; with one, or consentLog: false → nothing', async () => {
expect(await findings({ ...pg, ...config(), 'src/migrations/20260101_init.ts': 'create table "users"' })).toEqual([expect.stringMatching(/^consent-log-migration:error/)])
expect(await findings({ ...pg, ...config(), 'src/migrations/20261126_consent.ts': 'CREATE TABLE "consent_records"' })).toEqual([])
expect(await findings({ ...pg, ...config(', consentLog: false'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
expect(await findings({ ...config() })).toEqual([]) // MongoDB: no table, nothing to migrate
})
test('the banner\'s defaults switched off are reported', async () => {
const layout = `<SiteProviders shell={shell} gpc={false} cookieButton={false} banner={<CookieBanner equalChoice={false} order={['settings', 'accept']} />}>{children}</SiteProviders>`
const out = await findings({ ...config(), 'src/app/(frontend)/[locale]/layout.tsx': layout })
expect(out.map((f) => f.split(':').slice(0, 2).join(':')).sort()).toEqual(['consent-banner:warning', 'consent-banner:warning', 'consent-banner:warning', 'consent-banner:warning'])
})
test('the defaults as shipped: nothing to report', async () => {
expect(await findings({ ...config(), 'src/app/(frontend)/[locale]/layout.tsx': '<SiteProviders shell={shell}>{children}</SiteProviders>' })).toEqual([])
})
test('a hand-wired ConsentProvider without logEndpoint while the log is on; the crawl judging another Consent Mode', async () => {
const out = await findings({
'src/app/(frontend)/[locale]/layout.tsx': '<ConsentProvider texts={t}><Analytics consentMode="basic" /></ConsentProvider>',
'src/payload.config.ts': 'iapl({ cookieScanner: { crawl: true } })',
})
expect(out).toEqual([expect.stringMatching(/^consent-banner:warning:<ConsentProvider> without logEndpoint/), expect.stringMatching(/^consent-banner:warning:the layout runs Consent Mode 'basic'/)])
})
})
test('no console error in this file\'s renders', () => {
expect(errors).not.toHaveBeenCalled()
})
+23 -13
View File
@@ -30,11 +30,11 @@ const REJECT: ConsentState = { analytics: false, functional: false, marketing: f
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 }
type TreeOptions = { analytics?: object; banner?: object; cookieValue?: null | string; gpc?: 'ask' | 'honour' | false; 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 },
{ cookieValue: o.cookieValue, gpc: o.gpc, logEndpoint: o.logEndpoint, nonce: o.nonce, texts: o.texts ?? texts },
h('main', null, 'page'),
h(CookieBanner, o.banner ?? {}),
h(CookieButton),
@@ -151,12 +151,18 @@ describe('server render', () => {
['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) => {
])('server-read cookie, %s: the banner is in the HTML; Global Privacy Control is the browser\'s, so its script decides (gpc={false}: shown, no script)', (_label, cookieValue) => {
// the server cannot know Global Privacy Control (a browser signal): with 'honour' the script decides that part
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).toMatch(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
expect(html).toContain('data-ipal="banner-script"')
expect(html).toContain('navigator.globalPrivacyControl===true')
expect(html).not.toContain('data-ipal="cookie-button"')
// the signal ignored: as before GPC, shown with no script
const off = renderToString(tree({ cookieValue, gpc: false }))
expect(off).toContain('data-ipal="banner"')
expect(off).not.toMatch(/data-ipal="banner"[^>]*hidden/)
expect(off).not.toContain('<script')
})
test('firstPaint={false}: nothing in the HTML, as before 1.17.0', () => {
@@ -177,7 +183,8 @@ describe('server render', () => {
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/)
expect(site({ consentCookie: null })).toContain('data-ipal="banner-script"')
expect(site({ consentCookie: null, gpc: false })).not.toMatch(/data-ipal="banner"[^>]*hidden/)
})
})
@@ -383,8 +390,9 @@ describe('decisions, reopening and withdrawal work as before', () => {
// 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 })
// 1.17.0: `gpc` (the browser's Global Privacy Control at the time) joins the body; the record's shape is unchanged
expect(calls[0]).toEqual({ body: { gpc: false, 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({ gpc: false, id: first.id, state: ACCEPT, version: 3 })
expect(errors).not.toHaveBeenCalled()
})
@@ -445,7 +453,7 @@ describe('tags: nothing earlier than before', () => {
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(layer()).toEqual([['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied', wait_for_update: 500 })], ['set', 'ads_data_redaction', true]])
expect((window as { fbq?: unknown }).fbq).toBeUndefined()
})
@@ -460,8 +468,9 @@ describe('tags: nothing earlier than before', () => {
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(entries[1]).toEqual(['set', 'ads_data_redaction', true])
expect((entries[2] as unknown[]).slice(0, 2)).toEqual(['consent', 'update'])
expect(entries[3]).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']))
})
@@ -478,7 +487,8 @@ describe('tags: nothing earlier than before', () => {
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(entries[1]).toEqual(['set', 'ads_data_redaction', true])
expect(entries[2]).toMatchObject({ event: 'gtm.js' })
expect(injected).toEqual(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST']) // no Meta Pixel without consent
})
})