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:
@@ -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