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
+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()