From ebf70d49bd3ae834aa2ee2b9ad4ec459c4540ccf Mon Sep 17 00:00:00 2001 From: rasm-its Date: Fri, 16 Oct 2026 02:31:58 +0200 Subject: [PATCH] Consent: withdrawal clears tool cookies, policy version, consent log, cookie scan; form input hardening MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 , merged with the defaults. - Cookie Settings → Policy version: raising it asks every visitor again. - : 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 (/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 --- docs/agent/skills/ipal-consent-check/SKILL.md | 31 +++ .../scripts/cookie-scan.mjs | 176 ++++++++++++++++++ .../scripts/import-cookies.ts | 59 ++++++ docs/consent.md | 22 +++ src/exports/rsc.ts | 2 + src/globals/CookieSettings/fields.ts | 42 +++++ src/index.ts | 7 +- src/modules/consent/ConsentContext.tsx | 31 ++- src/modules/consent/CookieBanner.tsx | 14 +- src/modules/consent/CookieTable.tsx | 61 ++++++ src/modules/consent/client.ts | 3 +- src/modules/consent/consentLog.ts | 110 +++++++++++ src/modules/consent/getConsentTexts.ts | 34 +++- src/modules/consent/index.ts | 7 +- src/modules/consent/storage.ts | 34 +++- src/modules/consent/texts.ts | 2 + src/modules/consent/useConsent.ts | 106 ++++++++--- src/modules/forms/submitForm.ts | 2 +- src/modules/forms/validateSubmission.ts | 67 ++++++- src/plugin.ts | 8 + src/types.ts | 10 +- test/formSecurity.test.ts | 67 +++++++ test/integration.test.ts | 45 +++++ test/seo.test.ts | 11 ++ 24 files changed, 905 insertions(+), 46 deletions(-) create mode 100644 docs/agent/skills/ipal-consent-check/scripts/cookie-scan.mjs create mode 100644 docs/agent/skills/ipal-consent-check/scripts/import-cookies.ts create mode 100644 src/modules/consent/CookieTable.tsx create mode 100644 src/modules/consent/consentLog.ts create mode 100644 test/formSecurity.test.ts diff --git a/docs/agent/skills/ipal-consent-check/SKILL.md b/docs/agent/skills/ipal-consent-check/SKILL.md index 75106d9..6650345 100644 --- a/docs/agent/skills/ipal-consent-check/SKILL.md +++ b/docs/agent/skills/ipal-consent-check/SKILL.md @@ -37,3 +37,34 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je `CookieBanner` z pluginu. Własny baner w projekcie to naruszenie AGENT.md §7. + +## Lista ciasteczek do polityki cookies (cookie-scan) + +Po każdej zmianie narzędzi (nowy piksel, czat, mapa, wideo) i przed oddaniem strony: + +1. Skan działającej strony (bez zgody i po „Akceptuj wszystko”, strona główna + do 10 stron z sitemapy): + ```bash + node .agents/skills/ipal-consent-check/scripts/cookie-scan.mjs http://localhost:3000 --lang pl + ``` + Wynik: `cookie-scan/cookies.json` i `cookie-scan/cookies.md` (tabela). `[ERROR]` = ciasteczko + **nie-niezbędne ustawione przed zgodą** — napraw jak w tabeli wyżej. `[WARNING] unknown` — + ustal dostawcę i cel, wpisz `category` (`necessary|functional|analytics|marketing`) i `purpose` + w `cookies.json`. Nie zgaduj — zapytaj, jeśli nie wiesz. +2. Import do panelu (Cookie Settings → Cookies), każdy język osobno (skan z `--lang en` dla angielskiego): + ```bash + LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json + ``` + Łączy po nazwie, nie nadpisuje zmian redaktora (`OVERWRITE=1` wymusza). Nie usuwa ciasteczek, + których skan nie widział — to robi redaktor w panelu. +3. Strona polityki cookies pokazuje tabelę z panelu — **nie wklejaj listy do treści polityki**: + ```tsx + import { getCookieTable, getConsentTexts } from '@intecion/ipal-kit' + import { CookieTable } from '@intecion/ipal-kit/rsc' + const rows = await getCookieTable({ payload, locale }) + + ``` + Tabela bez stylów (`classNames` per element). Blok w panelu typu „Cookie table” na stronie + polityki to dobre miejsce — wtedy redaktor decyduje, gdzie się pojawi. + +Czas życia: Chrome skraca każde ciasteczko do maks. 400 dni (13 mies.) — skan pokazuje to, co +realnie zostaje w przeglądarce. `ipal-a11y` i inne klucze localStorage są wymienione osobno. diff --git a/docs/agent/skills/ipal-consent-check/scripts/cookie-scan.mjs b/docs/agent/skills/ipal-consent-check/scripts/cookie-scan.mjs new file mode 100644 index 0000000..4eed3b5 --- /dev/null +++ b/docs/agent/skills/ipal-consent-check/scripts/cookie-scan.mjs @@ -0,0 +1,176 @@ +#!/usr/bin/env node +// ipal cookie-scan — lists every cookie (and localStorage key) a running site sets, for the cookie policy. +// node cookie-scan.mjs [--pages 10] [--lang pl|en] [--out cookie-scan] [--wait 3000] +// Two fresh browser profiles: before any decision, and after "Accept all" (data-ipal="accept"). +// Pages: the base URL + up to --pages URLs from /sitemap.xml. +// Writes /cookies.json (import into the panel: import-cookies.ts) and /cookies.md (table). +// Needs Playwright: pnpm add -D playwright && pnpm exec playwright install chromium +// Exit code: 0 = ok, 1 = non-necessary cookies set BEFORE consent, 2 = setup problem. +import { mkdirSync, writeFileSync } from 'node:fs' +import path from 'node:path' + +const args = process.argv.slice(2) +if (!args[0] || args.includes('--help') || args.includes('-h')) { + console.log('Usage: cookie-scan.mjs [--pages N] [--lang pl|en] [--out dir] [--wait ms]') + process.exit(args[0] ? 0 : 2) +} +const opt = (name, def) => { + const i = args.indexOf(`--${name}`) + return i >= 0 ? args[i + 1] : def +} +const base = args[0].replace(/\/$/, '') +const MAX = Number(opt('pages', 10)) || 10 +const LANG = opt('lang', 'pl') === 'en' ? 'en' : 'pl' +const OUT = opt('out', 'cookie-scan') +const WAIT = Number(opt('wait', 3000)) || 3000 + +let pw +for (const mod of ['playwright', 'playwright-core', '@playwright/test']) { + try { pw = await import(mod); break } catch { /* next */ } +} +if (!pw) { + console.error('cookie-scan: Playwright not found. Install: pnpm add -D playwright && pnpm exec playwright install chromium') + process.exit(2) +} +const { chromium } = pw.default ?? pw + +// Known cookies → provider, consent category, purpose. `*` = prefix. +const T = (pl, en) => ({ en, pl }) +const CATALOG = [ + ['cookie-consent', 'this site', 'necessary', T('Zapamiętuje Twoją decyzję w sprawie plików cookies.', 'Stores your cookie consent decision.')], + ['NEXT_LOCALE', 'this site', 'functional', T('Zapamiętuje wybrany język strony.', 'Remembers the selected site language.')], + ['payload-token', 'this site', 'necessary', T('Sesja zalogowanego redaktora (panel administracyjny).', 'Logged-in editor session (admin panel).')], + ['__cf_bm', 'Cloudflare', 'necessary', T('Ochrona przed botami.', 'Bot protection.')], + ['_cfuvid', 'Cloudflare', 'necessary', T('Ochrona przed nadużyciami i limit zapytań.', 'Abuse protection and rate limiting.')], + ['cf_clearance', 'Cloudflare', 'necessary', T('Potwierdzenie przejścia weryfikacji Cloudflare.', 'Proof of passing a Cloudflare challenge.')], + ['_ga', 'Google', 'analytics', T('Google Analytics: rozróżnia użytkowników w statystykach.', 'Google Analytics: distinguishes users in statistics.')], + ['_ga_*', 'Google', 'analytics', T('Google Analytics: stan sesji w statystykach.', 'Google Analytics: session state for statistics.')], + ['_gid', 'Google', 'analytics', T('Google Analytics: rozróżnia użytkowników (24 h).', 'Google Analytics: distinguishes users (24 h).')], + ['_gat*', 'Google', 'analytics', T('Google Analytics: ogranicza liczbę zapytań.', 'Google Analytics: throttles request rate.')], + ['_gcl_*', 'Google', 'marketing', T('Google Ads: przypisanie konwersji do reklam.', 'Google Ads: attributes conversions to ads.')], + ['_fbp', 'Meta', 'marketing', T('Meta Pixel: pomiar i dopasowanie reklam.', 'Meta Pixel: ad measurement and targeting.')], + ['_fbc', 'Meta', 'marketing', T('Meta Pixel: zapamiętuje kliknięcie w reklamę.', 'Meta Pixel: stores the ad click.')], + ['_clck', 'Microsoft Clarity', 'analytics', T('Clarity: identyfikator użytkownika w analizie zachowań.', 'Clarity: user id for behaviour analytics.')], + ['_clsk', 'Microsoft Clarity', 'analytics', T('Clarity: łączy odsłony w jedną sesję.', 'Clarity: joins page views into a session.')], + ['CLID', 'Microsoft Clarity', 'analytics', T('Clarity: identyfikator użytkownika.', 'Clarity: user id.')], + ['MUID', 'Microsoft', 'marketing', T('Microsoft: identyfikator przeglądarki dla reklam.', 'Microsoft: browser id for advertising.')], + ['_uetsid', 'Microsoft Ads', 'marketing', T('Microsoft Ads: pomiar konwersji (sesja).', 'Microsoft Ads: conversion tracking (session).')], + ['_uetvid', 'Microsoft Ads', 'marketing', T('Microsoft Ads: pomiar konwersji (użytkownik).', 'Microsoft Ads: conversion tracking (user).')], + ['li_fat_id', 'LinkedIn', 'marketing', T('LinkedIn Insight: przypisanie konwersji.', 'LinkedIn Insight: conversion attribution.')], + ['lidc', 'LinkedIn', 'marketing', T('LinkedIn: wybór centrum danych.', 'LinkedIn: data-center routing.')], + ['bcookie', 'LinkedIn', 'marketing', T('LinkedIn: identyfikator przeglądarki.', 'LinkedIn: browser id.')], + ['bscookie', 'LinkedIn', 'marketing', T('LinkedIn: bezpieczny identyfikator przeglądarki.', 'LinkedIn: secure browser id.')], + ['UserMatchHistory', 'LinkedIn', 'marketing', T('LinkedIn Ads: synchronizacja identyfikatorów.', 'LinkedIn Ads: id sync.')], + ['AnalyticsSyncHistory', 'LinkedIn', 'marketing', T('LinkedIn: synchronizacja z analityką.', 'LinkedIn: analytics sync.')], + ['_ttp', 'TikTok', 'marketing', T('TikTok Pixel: pomiar reklam.', 'TikTok Pixel: ad measurement.')], + ['_tt_enable_cookie', 'TikTok', 'marketing', T('TikTok Pixel: sprawdza obsługę cookies.', 'TikTok Pixel: cookie support check.')], + ['_hj*', 'Hotjar', 'analytics', T('Hotjar: analiza zachowań użytkowników.', 'Hotjar: behaviour analytics.')], + ['YSC', 'YouTube', 'marketing', T('YouTube: statystyki odtworzeń osadzonych filmów.', 'YouTube: embedded video statistics.')], + ['VISITOR_INFO1_LIVE', 'YouTube', 'marketing', T('YouTube: szacuje przepustowość, preferencje odtwarzacza.', 'YouTube: bandwidth estimate, player preferences.')], + ['VISITOR_PRIVACY_METADATA', 'YouTube', 'marketing', T('YouTube: stan zgody użytkownika.', 'YouTube: user consent state.')], +] +const match = (name) => + CATALOG.find(([pattern]) => (pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern)) + +const human = (expires) => { + if (!expires || expires < 0) {return LANG === 'pl' ? 'sesja' : 'session'} + const days = Math.round((expires * 1000 - Date.now()) / 86_400_000) + if (days < 1) { + const h = Math.max(1, Math.round((expires * 1000 - Date.now()) / 3_600_000)) + return LANG === 'pl' ? `${h} godz.` : `${h} h` + } + if (days < 60) {return LANG === 'pl' ? `${days} dni` : `${days} days`} + const months = Math.round(days / 30) + if (months < 24) {return LANG === 'pl' ? `${months} mies.` : `${months} months`} + const years = Math.round(days / 365) + return LANG === 'pl' ? `${years} ${years < 5 ? 'lata' : 'lat'}` : `${years} years` +} + +// Pages to visit +const pages = [base] +try { + const xml = await (await fetch(`${base}/sitemap.xml`)).text() + for (const m of xml.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)) { + if (pages.length > MAX) {break} + if (!pages.includes(m[1])) {pages.push(m[1])} + } +} catch { /* no sitemap — base only */ } + +let browser +try { + browser = await chromium.launch() +} catch (err) { + console.error(`cookie-scan: cannot start Chromium — run: pnpm exec playwright install chromium\n${err.message?.split('\n')[0] ?? err}`) + process.exit(2) +} +const host = new URL(base).hostname.replace(/^www\./, '') + +async function visit(accept) { + const ctx = await browser.newContext() + const page = await ctx.newPage() + const storage = new Set() + try { + for (const [i, url] of pages.entries()) { + await page.goto(url, { waitUntil: 'networkidle', timeout: 30_000 }).catch(() => {}) + if (accept && i === 0) { + const btn = page.locator('[data-ipal="accept"]') + if (await btn.count()) {await btn.first().click().catch(() => {})} + } + await page.waitForTimeout(WAIT) + for (const k of await page.evaluate(() => Object.keys(localStorage)).catch(() => [])) {storage.add(k)} + } + return { cookies: await ctx.cookies(), storage: [...storage] } + } finally { + await ctx.close() + } +} + +const before = await visit(false) +const after = await visit(true) +await browser.close() + +const beforeNames = new Set(before.cookies.map((c) => c.name)) +const seen = new Map() +for (const c of [...before.cookies, ...after.cookies]) { + if (seen.has(c.name)) {continue} + const known = match(c.name) + const firstParty = c.domain.replace(/^\./, '').endsWith(host) + seen.set(c.name, { + category: known?.[2] ?? 'unknown', + domain: c.domain.replace(/^\./, ''), + duration: human(c.expires), + firstParty, + name: c.name, + provider: known ? (known[1] === 'this site' ? (LANG === 'pl' ? 'ta strona' : 'this site') : known[1]) : firstParty ? (LANG === 'pl' ? 'ta strona' : 'this site') : c.domain.replace(/^\./, ''), + purpose: known?.[3][LANG] ?? '', + setBeforeConsent: beforeNames.has(c.name), + }) +} +const ORDER = ['necessary', 'functional', 'analytics', 'marketing', 'unknown'] +const cookies = [...seen.values()].sort((a, b) => ORDER.indexOf(a.category) - ORDER.indexOf(b.category) || a.name.localeCompare(b.name)) + +mkdirSync(OUT, { recursive: true }) +writeFileSync(path.join(OUT, 'cookies.json'), JSON.stringify({ base, cookies, lang: LANG, localStorage: after.storage, pages, scannedAt: new Date().toISOString() }, null, 2)) +const head = LANG === 'pl' + ? '| Nazwa | Dostawca | Kategoria | Cel | Czas przechowywania |\n|---|---|---|---|---|' + : '| Name | Provider | Category | Purpose | Duration |\n|---|---|---|---|---|' +const rows = cookies.map((c) => `| \`${c.name}\` | ${c.provider} | ${c.category} | ${c.purpose || '—'} | ${c.duration} |`) +writeFileSync(path.join(OUT, 'cookies.md'), `${head}\n${rows.join('\n')}\n`) + +let errors = 0 +console.log(`cookie-scan — ${base} (${pages.length} page(s))`) +const early = cookies.filter((c) => c.setBeforeConsent && c.category !== 'necessary') +if (early.length) { + errors += early.length + console.log(`\n[ERROR] set BEFORE consent and not necessary (${early.length}) — GDPR: gate it (ConsentScript / Analytics) or classify it as necessary if it truly is`) + for (const c of early) {console.log(` ${c.name} (${c.domain}, ${c.category})`)} +} +const unknown = cookies.filter((c) => c.category === 'unknown') +if (unknown.length) { + console.log(`\n[WARNING] unknown cookies (${unknown.length}) — find the provider and purpose, set the category in cookies.json before importing`) + for (const c of unknown) {console.log(` ${c.name} (${c.domain})`)} +} +if (after.storage.length) {console.log(`\nlocalStorage keys (mention in the policy if they hold personal data): ${after.storage.join(', ')}`)} +console.log(`\n${cookies.length} cookie(s) → ${path.join(OUT, 'cookies.json')}, ${path.join(OUT, 'cookies.md')}`) +console.log(`Import into the panel: LOCALE=${LANG} pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts ${path.join(OUT, 'cookies.json')}`) +process.exit(errors ? 1 : 0) diff --git a/docs/agent/skills/ipal-consent-check/scripts/import-cookies.ts b/docs/agent/skills/ipal-consent-check/scripts/import-cookies.ts new file mode 100644 index 0000000..295c37d --- /dev/null +++ b/docs/agent/skills/ipal-consent-check/scripts/import-cookies.ts @@ -0,0 +1,59 @@ +/** + * Imports a cookie-scan result into Cookie Settings → Cookies (panel), so the + * cookie policy page () lists what the site really sets. + * + * LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json + * # second language: scan again with --lang en, then import with LOCALE=en + * # (rows are matched by cookie name; only purpose/duration are localized) + * + * Merges by cookie name: an editor's own purpose/duration/provider are kept + * unless OVERWRITE=1. Cookies no longer seen are kept too (remove them in the + * panel) — a scan of a few pages can miss cookies set elsewhere. `unknown` + * category rows are skipped: classify them in cookies.json first. + */ +import config from '@payload-config' +import { readFileSync } from 'node:fs' +import { getPayload } from 'payload' + +type Scanned = { category: string; duration?: string; name: string; provider?: string; purpose?: string } +type Row = { category?: string; duration?: null | string; id?: string; name?: string; provider?: null | string; purpose?: null | string } + +// `payload run` forwards positional args but not --flags — options come from env. +const file = process.argv.slice(2).find((a) => a.endsWith('.json')) +const locale = process.env.LOCALE +const overwrite = process.env.OVERWRITE === '1' +if (!file || !locale) { + console.error('Usage: LOCALE= [OVERWRITE=1] pnpm payload run import-cookies.ts ') + process.exit(2) +} + +const scan = JSON.parse(readFileSync(file, 'utf8')) as { cookies: Scanned[] } +const payload = await getPayload({ config }) +const current = (await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, locale: locale as never })) as { cookies?: Row[] } +const rows: Row[] = [...(current.cookies ?? [])] + +let added = 0 +let updated = 0 +let skipped = 0 +for (const c of scan.cookies) { + if (c.category === 'unknown') { + skipped++ + continue + } + const existing = rows.find((r) => r.name === c.name) + if (!existing) { + rows.push({ category: c.category, duration: c.duration, name: c.name, provider: c.provider, purpose: c.purpose }) + added++ + continue + } + const pick = (mine: null | string | undefined, theirs?: string) => (overwrite || !mine ? (theirs ?? mine) : mine) + existing.provider = pick(existing.provider, c.provider) + existing.purpose = pick(existing.purpose, c.purpose) + existing.duration = pick(existing.duration, c.duration) + if (overwrite) {existing.category = c.category} + updated++ +} + +await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: rows } as never, locale: locale as never }) +console.log(`Cookie Settings (${locale}): ${added} added, ${updated} updated, ${skipped} unknown skipped. Review them in the panel.`) +process.exit(0) diff --git a/docs/consent.md b/docs/consent.md index e1b019f..dfba8e1 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -204,3 +204,25 @@ chcesz zachować sprzątanie locale (albo zaimportuj `LOCALE_COOKIE_NAME` i doda > Mechanizm zgody dla locale jest opisany też od strony i18n: > [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo). + +## Wersja polityki, wycofanie zgody, rejestr zgód, tabela ciasteczek (1.10) + +- **Ponowna zgoda po zmianie polityki:** Cookie Settings → *Policy version* (sidebar). Podnieś o 1 + po dodaniu narzędzia albo zmianie polityki — każdy odwiedzający zobaczy baner ponownie. + `getConsentTexts` przekazuje wersję do `` automatycznie. +- **Wycofanie zgody kasuje ciasteczka narzędzi** (`_ga`, `_ga_*`, `_gid`, `_fbp`, `_gcl_*`, Clarity, + LinkedIn, TikTok, Hotjar…) — także na domenie nadrzędnej (`.klient.pl`), gdzie zapisuje je GA. + Własne ciasteczka projektu: `` (dopisywane do + listy domyślnej, `*` = prefiks). +- **Równy wybór:** `` — „Odrzuć” wygląda jak „Akceptuj wszystko” + (wymóg UODO/EDPB: odmowa równie łatwa jak zgoda). Domyślnie wyłączone, żeby nie zmieniać wyglądu + istniejących stron; **w nowych projektach włączaj**. +- **Rejestr zgód (dowód zgody, art. 7 ust. 1 RODO):** `ipalKit({ consentLog: true })` + + ``. Zapisuje losowy identyfikator (ten sam co w + ciasteczku), wybory, wersję polityki i czas — **bez IP i user-agenta**. Kolekcja *Consent records* + (tylko admin), automatyczne czyszczenie po `retentionDays` (domyślnie 1095). Postgres: `migrate:create`. +- **Tabela ciasteczek** dla strony polityki: Cookie Settings → *Cookies* (wypełniana skanem, + skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `` z `/rsc`. +- Ciasteczko zgody ma `Secure` na HTTPS. +- Global Privacy Control nie jest potrzebny: w UE wszystko poza niezbędnymi i tak jest domyślnie + wyłączone do czasu zgody. diff --git a/src/exports/rsc.ts b/src/exports/rsc.ts index 9e46c90..6e1cecb 100644 --- a/src/exports/rsc.ts +++ b/src/exports/rsc.ts @@ -12,6 +12,8 @@ export type { EnhanceProps, RenderBlocksProps, } from '../modules/blocks/index.js' +export { CookieTable } from '../modules/consent/CookieTable.js' +export type { CookieTableLabels } from '../modules/consent/CookieTable.js' export { RenderRichText } from '../modules/richtext/index.js' export type { RenderRichTextProps } from '../modules/richtext/index.js' export { JsonLdGraph } from '../modules/seo/index.js' diff --git a/src/globals/CookieSettings/fields.ts b/src/globals/CookieSettings/fields.ts index d554781..8c39e70 100644 --- a/src/globals/CookieSettings/fields.ts +++ b/src/globals/CookieSettings/fields.ts @@ -9,6 +9,19 @@ import { CONSENT_CATEGORIES } from '../../modules/consent/categories.js' * truth. Only the link's visible text lives here (privacyLinkLabel). */ export const cookieSettingsFields: Field[] = [ + { + name: 'policyVersion', + type: 'number', + admin: { + description: + 'Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.', + position: 'sidebar', + step: 1, + }, + defaultValue: 1, + min: 1, + required: true, + }, { name: 'message', type: 'textarea', @@ -65,4 +78,33 @@ export const cookieSettingsFields: Field[] = [ { name: 'description', type: 'textarea', localized: true }, ], }, + { + name: 'cookies', + type: 'array', + admin: { + description: + 'Cookies the site uses — shown on the cookie policy page (). Fill it from a scan: ipal-consent-check → cookie-scan.', + initCollapsed: true, + }, + fields: [ + { + type: 'row', + fields: [ + { name: 'name', type: 'text', admin: { width: '40%' }, required: true }, + { name: 'provider', type: 'text', admin: { description: 'e.g. Google, this site', width: '30%' } }, + { + name: 'category', + type: 'select', + admin: { width: '30%' }, + defaultValue: 'necessary', + options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })), + required: true, + }, + ], + }, + { name: 'purpose', type: 'textarea', localized: true }, + { name: 'duration', type: 'text', admin: { description: 'e.g. "2 years", "session"' }, localized: true }, + ], + labels: { plural: 'Cookies', singular: 'Cookie' }, + }, ] diff --git a/src/index.ts b/src/index.ts index 80d591b..97e262e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,19 +21,24 @@ export type { AnalyticsConfig } from './modules/analytics/index.js' export { getAnalyticsConfig } from './modules/analytics/index.js' export { ACCEPT_ALL_CONSENT, + buildConsentLogCollection, + buildConsentLogEndpoint, CONSENT_CATEGORIES, CONSENT_COOKIE, + CONSENT_LOG_SLUG, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, + getCookieTable, parseConsent, + readConsentRecord, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent, } from './modules/consent/index.js' -export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js' +export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js' export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js' export { archiveFieldName, diff --git a/src/modules/consent/ConsentContext.tsx b/src/modules/consent/ConsentContext.tsx index 1cbb62d..c4d180d 100644 --- a/src/modules/consent/ConsentContext.tsx +++ b/src/modules/consent/ConsentContext.tsx @@ -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(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 {children} } diff --git a/src/modules/consent/CookieBanner.tsx b/src/modules/consent/CookieBanner.tsx index 00589af..efec62f 100644 --- a/src/modules/consent/CookieBanner.tsx +++ b/src/modules/consent/CookieBanner.tsx @@ -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 -