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:
co-authored by
Claude Opus 5.5
parent
41771fd51a
commit
99036eb70c
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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}` +
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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' } })
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
Reference in New Issue
Block a user