diff --git a/docs/dev/consent-compliance-proposal.md b/docs/dev/consent-compliance-proposal.md index 23a236c..466559e 100644 --- a/docs/dev/consent-compliance-proposal.md +++ b/docs/dev/consent-compliance-proposal.md @@ -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: diff --git a/src/exports/client.ts b/src/exports/client.ts index 86097ce..e8bedb0 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -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' diff --git a/src/index.ts b/src/index.ts index 0ddfd94..7d5502c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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, diff --git a/src/modules/analytics/Analytics.tsx b/src/modules/analytics/Analytics.tsx index b6e595b..ab7247b 100644 --- a/src/modules/analytics/Analytics.tsx +++ b/src/modules/analytics/Analytics.tsx @@ -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[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, diff --git a/src/modules/analytics/pixels.ts b/src/modules/analytics/pixels.ts index 3d46bcb..2fdf99d 100644 --- a/src/modules/analytics/pixels.ts +++ b/src/modules/analytics/pixels.ts @@ -13,6 +13,8 @@ * Microsoft Clarity → analytics */ +import { clarityConsent } from '../consent/vendorConsent.js' + type Win = Record & 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[]) { diff --git a/src/modules/analytics/shouldLoadGoogle.ts b/src/modules/analytics/shouldLoadGoogle.ts index b31a411..2c44cea 100644 --- a/src/modules/analytics/shouldLoadGoogle.ts +++ b/src/modules/analytics/shouldLoadGoogle.ts @@ -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) } diff --git a/src/modules/consent/ConsentContext.tsx b/src/modules/consent/ConsentContext.tsx index c3be4a8..c123c7a 100644 --- a/src/modules/consent/ConsentContext.tsx +++ b/src/modules/consent/ConsentContext.tsx @@ -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 + * ( 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 {children} diff --git a/src/modules/consent/CookieBanner.tsx b/src/modules/consent/CookieBanner.tsx index 6c0a705..db4e979 100644 --- a/src/modules/consent/CookieBanner.tsx +++ b/src/modules/consent/CookieBanner.tsx @@ -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 = { 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 / . */ 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>(state) const closeRef = useRef(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] 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({ )} {texts.settingsDescription &&

{texts.settingsDescription}

} + {gpc && texts.gpcNotice ?

{texts.gpcNotice}

: null}
    {CONSENT_CATEGORIES.map((cat) => detailed ? ( @@ -476,6 +492,7 @@ export function CookieBanner({ )}

    + {gpc && texts.gpcNotice ?

    {texts.gpcNotice}

    : null}
    {order.map(button)}
    @@ -489,7 +506,7 @@ export function CookieBanner({ suppressHydrationWarning: browsers hide the nonce attribute from the DOM. */} {undecidedHtml ? ( `, no line separators const name = JSON.stringify(`${cookieName}=`) .replace(/ to carry out `b.addEventListener("click",function(e){if(b.hasAttribute("${BANNER_READY_ATTRIBUTE}")){return}` + diff --git a/src/modules/consent/getConsentTexts.ts b/src/modules/consent/getConsentTexts.ts index e91e650..4cab004 100644 --- a/src/modules/consent/getConsentTexts.ts +++ b/src/modules/consent/getConsentTexts.ts @@ -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, diff --git a/src/modules/consent/googleConsent.ts b/src/modules/consent/googleConsent.ts index d6c04d7..6786e86 100644 --- a/src/modules/consent/googleConsent.ts +++ b/src/modules/consent/googleConsent.ts @@ -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. */ diff --git a/src/modules/consent/gpc.ts b/src/modules/consent/gpc.ts new file mode 100644 index 0000000..c36e2f6 --- /dev/null +++ b/src/modules/consent/gpc.ts @@ -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": "" }`). 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' } }) +} diff --git a/src/modules/consent/index.ts b/src/modules/consent/index.ts index b544cd6..b0521e9 100644 --- a/src/modules/consent/index.ts +++ b/src/modules/consent/index.ts @@ -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, diff --git a/src/modules/consent/storage.ts b/src/modules/consent/storage.ts index 15ba720..47aec01 100644 --- a/src/modules/consent/storage.ts +++ b/src/modules/consent/storage.ts @@ -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 } diff --git a/src/modules/consent/texts.ts b/src/modules/consent/texts.ts index 11f96d9..7a8ed2c 100644 --- a/src/modules/consent/texts.ts +++ b/src/modules/consent/texts.ts @@ -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 diff --git a/src/modules/consent/useConsent.ts b/src/modules/consent/useConsent.ts index 73b8329..dcfa058 100644 --- a/src/modules/consent/useConsent.ts +++ b/src/modules/consent/useConsent.ts @@ -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> @@ -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). + * 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) // 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) + 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 } } diff --git a/src/modules/consent/vendorConsent.ts b/src/modules/consent/vendorConsent.ts new file mode 100644 index 0000000..ad5e5a0 --- /dev/null +++ b/src/modules/consent/vendorConsent.ts @@ -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): { ad_Storage: string; analytics_Storage: string } { + return { ad_Storage: granted(state.marketing), analytics_Storage: granted(state.analytics) } +} diff --git a/src/modules/doctor/rules/consent.ts b/src/modules/doctor/rules/consent.ts new file mode 100644 index 0000000..406e948 --- /dev/null +++ b/src/modules/doctor/rules/consent.ts @@ -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 `` 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 ", 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 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 (SiteProviders does it by itself)', message: ' 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', + }, +] diff --git a/src/modules/doctor/run.ts b/src/modules/doctor/run.ts index 31b9f50..5ef7baf 100644 --- a/src/modules/doctor/run.ts +++ b/src/modules/doctor/run.ts @@ -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, diff --git a/src/modules/frontend/SiteProviders.tsx b/src/modules/frontend/SiteProviders.tsx index a83f5a8..db08fa7 100644 --- a/src/modules/frontend/SiteProviders.tsx +++ b/src/modules/frontend/SiteProviders.tsx @@ -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 ; `false` = no analytics tags at all. */ analytics?: false | Omit - /** The cookie banner. Default ``; pass your own configured one (`equalChoice`, classNames) or `false`. */ + /** The cookie banner. Default ``; 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 | undefined)[] /** @@ -43,8 +49,13 @@ export type SiteProvidersProps = { * yourself in a client component. */ lightbox?: boolean | Omit - /** 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) * - * }> + * }> *
    {children}