Consent: withdrawal clears tool cookies, policy version, consent log, cookie scan; form input hardening
Consent (GDPR)
- Withdrawing consent now deletes GA/Meta/Ads/Clarity/LinkedIn/TikTok/Hotjar
cookies (prefix patterns) on the host AND parent domains — previously only
the locale cookie was removed and _ga & co. stayed. Projects extend the list
via <ConsentProvider cookieMap>, merged with the defaults.
- Cookie Settings → Policy version: raising it asks every visitor again.
- <CookieBanner equalChoice>: Reject styled like Accept (UODO/EDPB), opt-in.
- Opt-in consent log (ipalKit({ consentLog: true }) + logEndpoint): random id,
choices, version, time — no IP/UA; admin-only collection, retention purge.
- Cookie Settings → Cookies + getCookieTable + unstyled <CookieTable> (/rsc).
- Consent cookie gets Secure on HTTPS; consent id stored with the decision.
- ipal-consent-check: cookie-scan.mjs (before/after consent, known-tool
catalog PL/EN, flags non-necessary cookies set before consent) and
import-cookies.ts into the panel (idempotent, keeps editor edits).
Forms
- Server-side type checks per field from the panel definition: email = one
address (blocks "a@x, b@y" recipient injection into {{email}} confirmations
and CR/LF header injection), select/radio only configured options, numbers,
booleans; objects/arrays rejected; control and bidi characters stripped.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
import { createContext, type ReactNode, use } from 'react'
|
||||
|
||||
import type { ConsentTexts } from './texts.js'
|
||||
import type { ConsentCookieMap } from './useConsent.js'
|
||||
|
||||
import { useConsent } from './useConsent.js'
|
||||
|
||||
@@ -9,8 +10,34 @@ type ConsentContextValue = { texts: ConsentTexts } & ReturnType<typeof useConsen
|
||||
|
||||
const ConsentContext = createContext<ConsentContextValue | null>(null)
|
||||
|
||||
export function ConsentProvider({ children, texts }: { children: ReactNode; texts: ConsentTexts }) {
|
||||
const consent = useConsent()
|
||||
type ConsentProviderProps = {
|
||||
children: ReactNode
|
||||
/** Extra cookies per category to delete when consent is withdrawn — merged with the built-in list. */
|
||||
cookieMap?: ConsentCookieMap
|
||||
/**
|
||||
* Consent log endpoint (createConsentLogEndpoint, e.g. '/api/ipal/consent'):
|
||||
* every decision is POSTed — random id, choices, policy version, no personal
|
||||
* data — so the site can demonstrate consent (GDPR Art. 7(1)). Off when omitted.
|
||||
*/
|
||||
logEndpoint?: string
|
||||
texts: ConsentTexts
|
||||
}
|
||||
|
||||
export function ConsentProvider({ children, cookieMap, logEndpoint, texts }: ConsentProviderProps) {
|
||||
const consent = useConsent({
|
||||
cookieMap,
|
||||
onDecision: logEndpoint
|
||||
? (record) => {
|
||||
void fetch(logEndpoint, {
|
||||
body: JSON.stringify(record),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
keepalive: true,
|
||||
method: 'POST',
|
||||
}).catch(() => {})
|
||||
}
|
||||
: undefined,
|
||||
version: texts.version,
|
||||
})
|
||||
return <ConsentContext value={{ ...consent, texts }}>{children}</ConsentContext>
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,17 @@ const strongText =
|
||||
const mutedText =
|
||||
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
|
||||
|
||||
export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNames } = {}) {
|
||||
type CookieBannerProps = {
|
||||
classNames?: CookieBannerClassNames
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
equalChoice?: boolean
|
||||
}
|
||||
|
||||
export function CookieBanner({ classNames, equalChoice = false }: CookieBannerProps = {}) {
|
||||
const isMounted = useIsMounted()
|
||||
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
@@ -104,7 +114,7 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
|
||||
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
|
||||
{texts.buttons.settings}
|
||||
</button>
|
||||
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
|
||||
<button className={equalChoice ? primaryClass : secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
|
||||
{texts.buttons.reject}
|
||||
</button>
|
||||
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { CookieTableRow } from './getConsentTexts.js'
|
||||
import type { ConsentTexts } from './texts.js'
|
||||
|
||||
export type CookieTableLabels = {
|
||||
category: string
|
||||
duration: string
|
||||
name: string
|
||||
provider: string
|
||||
purpose: string
|
||||
}
|
||||
|
||||
type CookieTableProps = {
|
||||
/** Optional caption above the table. */
|
||||
caption?: string
|
||||
/** Category names — pass `texts.categories` from getConsentTexts so they match the banner. */
|
||||
categories?: ConsentTexts['categories']
|
||||
/** Classes per element; nothing is styled by default. */
|
||||
classNames?: Partial<Record<'caption' | 'table' | 'td' | 'th' | 'tr', string>>
|
||||
/** Column headings in the page's language — from the project (panel field or page content). */
|
||||
labels: CookieTableLabels
|
||||
/** From getCookieTable({ payload, locale }) — Cookie Settings → Cookies. */
|
||||
rows: CookieTableRow[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The cookie list for the cookie-policy page, straight from the panel — no copy
|
||||
* pasted into the policy text, so it can't go stale. Plain semantic <table>,
|
||||
* unstyled: classNames per element, or style it from the page's CSS. Server
|
||||
* component (no state).
|
||||
*
|
||||
* const rows = await getCookieTable({ payload, locale })
|
||||
* <CookieTable rows={rows} labels={…from the panel…} categories={texts.categories} />
|
||||
*/
|
||||
export function CookieTable({ caption, categories, classNames = {}, labels, rows }: CookieTableProps) {
|
||||
if (rows.length === 0) {return null}
|
||||
return (
|
||||
<table className={classNames.table}>
|
||||
{caption ? <caption className={classNames.caption}>{caption}</caption> : null}
|
||||
<thead>
|
||||
<tr className={classNames.tr}>
|
||||
<th className={classNames.th} scope="col">{labels.name}</th>
|
||||
<th className={classNames.th} scope="col">{labels.provider}</th>
|
||||
<th className={classNames.th} scope="col">{labels.category}</th>
|
||||
<th className={classNames.th} scope="col">{labels.purpose}</th>
|
||||
<th className={classNames.th} scope="col">{labels.duration}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr className={classNames.tr} key={`${row.category}:${row.name}`}>
|
||||
<td className={classNames.td}><code>{row.name}</code></td>
|
||||
<td className={classNames.td}>{row.provider ?? ''}</td>
|
||||
<td className={classNames.td}>{categories?.[row.category]?.title ?? row.category}</td>
|
||||
<td className={classNames.td}>{row.purpose ?? ''}</td>
|
||||
<td className={classNames.td}>{row.duration ?? ''}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@@ -5,4 +5,5 @@ export { CookieBanner } from './CookieBanner.js'
|
||||
export type { CookieBannerClassNames } from './CookieBanner.js'
|
||||
export { CookieButton } from './CookieButton.js'
|
||||
// Client-only consent exports — hook, provider, and UI components.
|
||||
export { useConsent } from './useConsent.js'
|
||||
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
|
||||
export type { ConsentCookieMap } from './useConsent.js'
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { isAdmin } from '../access/predicates.js'
|
||||
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
|
||||
import { CONSENT_CATEGORIES } from './categories.js'
|
||||
|
||||
/**
|
||||
* Consent log — proof of consent (GDPR Art. 7(1): the controller must be able
|
||||
* to demonstrate it). Each banner decision is stored as: random consent id (the
|
||||
* same one kept in the visitor's cookie), the choices, the policy version and
|
||||
* 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: `ipalKit({ 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.
|
||||
*/
|
||||
|
||||
export const CONSENT_LOG_SLUG = 'consent-records'
|
||||
|
||||
export type ConsentLogOptions = {
|
||||
/** Days a record is kept. Default 1095 (3 years). */
|
||||
retentionDays?: number
|
||||
}
|
||||
|
||||
export function buildConsentLogCollection(): CollectionConfig {
|
||||
return {
|
||||
slug: CONSENT_LOG_SLUG,
|
||||
access: {
|
||||
// Written only by the endpoint (Local API); read and pruned by admins.
|
||||
create: () => false,
|
||||
delete: ({ req: { user } }) => isAdmin(user),
|
||||
read: ({ req: { user } }) => isAdmin(user),
|
||||
update: () => false,
|
||||
},
|
||||
admin: {
|
||||
defaultColumns: ['consentId', 'version', 'createdAt'],
|
||||
description: 'Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.',
|
||||
group: 'Settings',
|
||||
useAsTitle: 'consentId',
|
||||
},
|
||||
fields: [
|
||||
{ name: 'consentId', type: 'text', index: true, required: true },
|
||||
{ name: 'version', type: 'number', required: true },
|
||||
{
|
||||
name: 'choices',
|
||||
type: 'group',
|
||||
fields: CONSENT_CATEGORIES.map((c) => ({ name: c, type: 'checkbox' as const })),
|
||||
},
|
||||
],
|
||||
labels: { plural: 'Consent records', singular: 'Consent record' },
|
||||
timestamps: true,
|
||||
}
|
||||
}
|
||||
|
||||
let lastPurge = 0
|
||||
|
||||
export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint {
|
||||
return {
|
||||
handler: async (req: PayloadRequest) => {
|
||||
const limit = await consumeRateLimit({ key: clientIp(req as unknown as Request), max: 20, scope: 'consent' })
|
||||
if (!limit.ok) {return Response.json({ ok: false }, { status: 429 })}
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await (req as unknown as Request).json()
|
||||
} catch {
|
||||
return Response.json({ ok: false }, { status: 400 })
|
||||
}
|
||||
const b = body as { id?: unknown; state?: Record<string, unknown>; version?: unknown }
|
||||
const valid =
|
||||
typeof b.id === 'string' &&
|
||||
/^[0-9a-f]{16,64}$/.test(b.id) &&
|
||||
typeof b.version === 'number' &&
|
||||
Number.isInteger(b.version) &&
|
||||
b.version >= 1 &&
|
||||
b.state !== null &&
|
||||
typeof b.state === 'object' &&
|
||||
CONSENT_CATEGORIES.every((c) => typeof b.state![c] === 'boolean')
|
||||
if (!valid) {return Response.json({ ok: false }, { status: 400 })}
|
||||
|
||||
try {
|
||||
await req.payload.create({
|
||||
collection: CONSENT_LOG_SLUG as never,
|
||||
data: {
|
||||
choices: Object.fromEntries(CONSENT_CATEGORIES.map((c) => [c, b.state![c] === true])),
|
||||
consentId: b.id,
|
||||
version: b.version,
|
||||
} as never,
|
||||
overrideAccess: true,
|
||||
})
|
||||
const now = Date.now()
|
||||
if (now - lastPurge > 24 * 60 * 60 * 1000) {
|
||||
lastPurge = now
|
||||
await req.payload.delete({
|
||||
collection: CONSENT_LOG_SLUG as never,
|
||||
overrideAccess: true,
|
||||
where: { createdAt: { less_than: new Date(now - retentionDays * 86_400_000).toISOString() } },
|
||||
})
|
||||
}
|
||||
return Response.json({ ok: true }, { status: 201 })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return Response.json({ ok: false }, { status: 500 })
|
||||
}
|
||||
},
|
||||
method: 'post',
|
||||
path: '/ipal/consent',
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import type { ConsentTexts } from './texts.js'
|
||||
import { resolveLocalized } from '../i18n/resolveLocalized.js'
|
||||
import { getSystemPagePath } from '../pages/index.js'
|
||||
import { getGlobal } from '../payload/index.js'
|
||||
import { CONSENT_CATEGORIES } from './categories.js'
|
||||
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
|
||||
|
||||
/** English fallback used when the global has no value for a field. */
|
||||
const FALLBACK: ConsentTexts = {
|
||||
@@ -39,7 +39,9 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
|
||||
type CookieSettingsData = {
|
||||
buttons?: null | Partial<ConsentTexts['buttons']>
|
||||
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
|
||||
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
|
||||
message?: null | string
|
||||
policyVersion?: null | number
|
||||
privacyLinkLabel?: null | string
|
||||
settingsTitle?: null | string
|
||||
}
|
||||
@@ -141,5 +143,35 @@ export async function getConsentTexts({
|
||||
message: g.message || FALLBACK.message,
|
||||
privacyLink,
|
||||
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
|
||||
...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export type CookieTableRow = {
|
||||
category: ConsentCategory
|
||||
duration?: string
|
||||
name: string
|
||||
provider?: string
|
||||
purpose?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows of Cookie Settings → Cookies in one language, for the cookie policy page
|
||||
* (<CookieTable rows={…}>). Server-side; never throws (empty list).
|
||||
*/
|
||||
export async function getCookieTable({ locale, payload }: { locale?: string; payload: BasePayload }): Promise<CookieTableRow[]> {
|
||||
try {
|
||||
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
|
||||
return (g.cookies ?? [])
|
||||
.filter((c) => typeof c.name === 'string' && c.name.trim())
|
||||
.map((c) => ({
|
||||
name: c.name!.trim(),
|
||||
category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary',
|
||||
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
|
||||
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
|
||||
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,13 +8,18 @@ export {
|
||||
REJECT_ALL_CONSENT,
|
||||
} from './categories.js'
|
||||
export type { ConsentCategory, ConsentState } from './categories.js'
|
||||
export { getConsentTexts } from './getConsentTexts.js'
|
||||
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './consentLog.js'
|
||||
export type { ConsentLogOptions } from './consentLog.js'
|
||||
export { getConsentTexts, getCookieTable } from './getConsentTexts.js'
|
||||
export type { CookieTableRow } from './getConsentTexts.js'
|
||||
export { setDefaultConsent, updateConsent } from './googleConsent.js'
|
||||
export {
|
||||
CONSENT_COOKIE,
|
||||
CONSENT_MAX_AGE,
|
||||
CONSENT_VERSION,
|
||||
newConsentId,
|
||||
parseConsent,
|
||||
readConsentRecord,
|
||||
serializeConsent,
|
||||
} from './storage.js'
|
||||
export type { ConsentTexts } from './texts.js'
|
||||
|
||||
@@ -3,41 +3,59 @@ import type { ConsentState } from './categories.js'
|
||||
import { CONSENT_CATEGORIES, DEFAULT_CONSENT } from './categories.js'
|
||||
|
||||
/**
|
||||
* Consent persistence in a cookie. Stored with a version so we can invalidate
|
||||
* old consents when the policy changes, and a timestamp (GDPR: consent must be
|
||||
* dated). Readable both client-side (banner) and server-side (script gating).
|
||||
* Consent persistence in a cookie. Stored with a version so old consents can be
|
||||
* invalidated when the policy changes (Cookie Settings → Policy version in the
|
||||
* panel), a timestamp (GDPR: consent must be dated) and a random id that links
|
||||
* the visitor's choice to the optional server-side consent record. Readable both
|
||||
* client-side (banner) and server-side (script gating, proxy).
|
||||
*/
|
||||
export const CONSENT_COOKIE = 'cookie-consent'
|
||||
/** Default policy version — the panel's Cookie Settings → Policy version overrides it. */
|
||||
export const CONSENT_VERSION = 1
|
||||
export const CONSENT_MAX_AGE = 60 * 60 * 24 * 180 // 180 days
|
||||
|
||||
type StoredConsent = {
|
||||
/** Random id of this decision (no personal data) — matches the consent record. */
|
||||
id?: string
|
||||
state: ConsentState
|
||||
timestamp: string
|
||||
version: number
|
||||
}
|
||||
|
||||
export function serializeConsent(state: ConsentState): string {
|
||||
/** Random id for a consent decision. */
|
||||
export function newConsentId(): string {
|
||||
const bytes = new Uint8Array(12)
|
||||
globalThis.crypto.getRandomValues(bytes)
|
||||
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
export function serializeConsent(state: ConsentState, version: number = CONSENT_VERSION, id?: string): string {
|
||||
const payload: StoredConsent = {
|
||||
...(id ? { id } : {}),
|
||||
state,
|
||||
timestamp: new Date().toISOString(),
|
||||
version: CONSENT_VERSION,
|
||||
version,
|
||||
}
|
||||
return encodeURIComponent(JSON.stringify(payload))
|
||||
}
|
||||
|
||||
export function parseConsent(raw: string | undefined): ConsentState | null {
|
||||
/** Full stored record (id, timestamp, version) — null when missing, unreadable or from another policy version. */
|
||||
export function readConsentRecord(raw: string | undefined, version: number = CONSENT_VERSION): ({ state: ConsentState } & StoredConsent) | null {
|
||||
if (!raw) {return null}
|
||||
try {
|
||||
const parsed = JSON.parse(decodeURIComponent(raw)) as StoredConsent
|
||||
if (parsed.version !== CONSENT_VERSION) {return null}
|
||||
if (parsed.version !== version) {return null}
|
||||
const state = { ...DEFAULT_CONSENT }
|
||||
for (const cat of CONSENT_CATEGORIES) {
|
||||
if (typeof parsed.state?.[cat] === 'boolean') {state[cat] = parsed.state[cat]}
|
||||
}
|
||||
state.necessary = true
|
||||
return state
|
||||
return { ...parsed, state }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function parseConsent(raw: string | undefined, version: number = CONSENT_VERSION): ConsentState | null {
|
||||
return readConsentRecord(raw, version)?.state ?? null
|
||||
}
|
||||
|
||||
@@ -13,4 +13,6 @@ export type ConsentTexts = {
|
||||
/** null = no privacy-policy link shown */
|
||||
privacyLink: { href: string; label: string } | null
|
||||
settingsTitle: string
|
||||
/** Policy version from the panel — a stored consent from another version asks again. */
|
||||
version?: number
|
||||
}
|
||||
|
||||
@@ -1,69 +1,125 @@
|
||||
'use client'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
|
||||
import type { ConsentCategory, ConsentState } from './categories.js'
|
||||
|
||||
import { LOCALE_COOKIE_NAME } from '../i18n/index.js'
|
||||
import { ACCEPT_ALL_CONSENT, DEFAULT_CONSENT, REJECT_ALL_CONSENT } from './categories.js'
|
||||
import { updateConsent } from './googleConsent.js'
|
||||
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent, serializeConsent } from './storage.js'
|
||||
import { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js'
|
||||
|
||||
export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
|
||||
|
||||
/**
|
||||
* Cookies to delete when consent for a category is withdrawn. Keyed by
|
||||
* category. The plugin knows about its own functional cookie (locale); clients
|
||||
* can extend this via the `cookieMap` arg to useConsent if they set their own.
|
||||
* Cookies deleted when consent for a category is withdrawn (GDPR: withdrawing
|
||||
* must stop the processing). `name*` matches a prefix (`_ga_*` → _ga_ABC123).
|
||||
* Covers the plugin's own functional cookie and the tools Analytics can load;
|
||||
* projects add theirs through <ConsentProvider cookieMap> (merged, not replaced).
|
||||
*/
|
||||
const DEFAULT_COOKIE_MAP: Partial<Record<ConsentCategory, string[]>> = {
|
||||
export const DEFAULT_COOKIE_MAP: ConsentCookieMap = {
|
||||
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*'],
|
||||
functional: [LOCALE_COOKIE_NAME],
|
||||
marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'],
|
||||
}
|
||||
|
||||
/** Expire a cookie now, across the whole site. */
|
||||
function mergeCookieMaps(extra?: ConsentCookieMap): ConsentCookieMap {
|
||||
if (!extra) {return DEFAULT_COOKIE_MAP}
|
||||
const out: ConsentCookieMap = { ...DEFAULT_COOKIE_MAP }
|
||||
for (const [cat, names] of Object.entries(extra) as [ConsentCategory, string[]][]) {
|
||||
out[cat] = [...new Set([...(out[cat] ?? []), ...names])]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 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)
|
||||
}
|
||||
|
||||
/**
|
||||
* Expire a cookie on this host AND every parent domain — GA, Meta and others
|
||||
* set theirs on the registrable domain (.acme.pl), which a host-only delete
|
||||
* leaves behind.
|
||||
*/
|
||||
function deleteCookie(name: string) {
|
||||
document.cookie = `${name}=;path=/;max-age=0;samesite=lax`
|
||||
const parts = location.hostname.split('.')
|
||||
const domains = [''] // host-only
|
||||
for (let i = 0; i < parts.length - 1; i++) {domains.push(`;domain=.${parts.slice(i).join('.')}`)}
|
||||
for (const domain of domains) {document.cookie = `${name}=;path=/;max-age=0;samesite=lax${domain}`}
|
||||
}
|
||||
|
||||
export function useConsent(
|
||||
cookieMap: Partial<Record<ConsentCategory, string[]>> = DEFAULT_COOKIE_MAP,
|
||||
) {
|
||||
type UseConsentOptions = {
|
||||
/** Extra cookies per category to delete on withdrawal — merged with DEFAULT_COOKIE_MAP. */
|
||||
cookieMap?: ConsentCookieMap
|
||||
/**
|
||||
* Called after every decision with the consent id and choices — e.g. POST to
|
||||
* the consent log (createConsentLogEndpoint). Never blocks the banner.
|
||||
*/
|
||||
onDecision?: (record: { id: string; state: ConsentState; version: number }) => void
|
||||
/** Policy version from the panel (Cookie Settings). A stored consent from another version asks again. */
|
||||
version?: number
|
||||
}
|
||||
|
||||
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
|
||||
? (options)
|
||||
: { 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 { onDecision } = opts
|
||||
|
||||
const [state, setState] = useState<ConsentState>(DEFAULT_CONSENT)
|
||||
const [decided, setDecided] = useState(false)
|
||||
const [consentId, setConsentId] = useState<string | undefined>(undefined)
|
||||
|
||||
useEffect(() => {
|
||||
const raw = document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
|
||||
?.split('=')[1]
|
||||
const parsed = parseConsent(raw)
|
||||
if (parsed) {
|
||||
setState(parsed)
|
||||
const record = readConsentRecord(raw, version)
|
||||
if (record) {
|
||||
setState(record.state)
|
||||
setDecided(true)
|
||||
setConsentId(record.id)
|
||||
}
|
||||
}, [])
|
||||
}, [version])
|
||||
|
||||
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,
|
||||
// so a functional cookie (e.g. locale) written under consent has to go when
|
||||
// that consent is revoked. Uses the current `state` as the previous value.
|
||||
// cookies tied to it. GDPR: withdrawing consent must stop the processing.
|
||||
for (const cat of Object.keys(cookieMap) as ConsentCategory[]) {
|
||||
const wasGranted = state[cat] === true
|
||||
const nowDenied = next[cat] !== true
|
||||
if (wasGranted && nowDenied) {
|
||||
for (const name of cookieMap[cat] ?? []) {deleteCookie(name)}
|
||||
if (state[cat] === true && next[cat] !== true) {
|
||||
for (const pattern of cookieMap[cat] ?? []) {
|
||||
for (const name of matchingCookies(pattern)) {deleteCookie(name)}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax`
|
||||
const id = consentId ?? newConsentId()
|
||||
const secure = location.protocol === 'https:' ? ';secure' : ''
|
||||
document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next, version, id)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`
|
||||
setState(next)
|
||||
setDecided(true)
|
||||
setConsentId(id)
|
||||
// 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 })
|
||||
} catch {
|
||||
// a logging hook must never break the banner
|
||||
}
|
||||
},
|
||||
[state, cookieMap],
|
||||
[state, consentId, version, onDecision, cookieMap],
|
||||
)
|
||||
|
||||
const acceptAll = useCallback(() => persist(ACCEPT_ALL_CONSENT), [persist])
|
||||
@@ -75,5 +131,5 @@ export function useConsent(
|
||||
)
|
||||
const reopen = useCallback(() => setDecided(false), [])
|
||||
|
||||
return { acceptAll, decided, rejectAll, reopen, savePreferences, state }
|
||||
return { acceptAll, consentId, decided, rejectAll, reopen, savePreferences, state }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user