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:
2026-10-16 02:31:58 +02:00
co-authored by Claude Opus 5.5
parent c9a50abc33
commit ebf70d49bd
24 changed files with 905 additions and 46 deletions
@@ -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 })
<CookieTable rows={rows} categories={texts.categories} labels={/* nagłówki kolumn z panelu */} />
```
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.
@@ -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 <baseUrl> [--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 <out>/cookies.json (import into the panel: import-cookies.ts) and <out>/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 <baseUrl> [--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(/<loc>\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)
@@ -0,0 +1,59 @@
/**
* Imports a cookie-scan result into Cookie Settings → Cookies (panel), so the
* cookie policy page (<CookieTable>) 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=<code> [OVERWRITE=1] pnpm payload run import-cookies.ts <cookies.json>')
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)
+22
View File
@@ -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 `<ConsentProvider texts>` 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: `<ConsentProvider cookieMap={{ marketing: ['_my*'] }}>` (dopisywane do
listy domyślnej, `*` = prefiks).
- **Równy wybór:** `<CookieBanner equalChoice />` — „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 })` +
`<ConsentProvider logEndpoint="/api/ipal/consent">`. 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` + `<CookieTable>` 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.
+2
View File
@@ -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'
+42
View File
@@ -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 (<CookieTable>). 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' },
},
]
+6 -1
View File
@@ -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,
+29 -2
View File
@@ -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>
}
+12 -2
View File
@@ -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">
+61
View File
@@ -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>
)
}
+2 -1
View File
@@ -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'
+110
View File
@@ -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',
}
}
+33 -1
View File
@@ -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 []
}
}
+6 -1
View File
@@ -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'
+26 -8
View File
@@ -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
}
+2
View File
@@ -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
}
+81 -25
View File
@@ -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 }
}
+1 -1
View File
@@ -61,7 +61,7 @@ export type SubmitFailure =
/** The offending field's name, when one field is at fault. */
field?: string
/** What was wrong with it. */
kind?: 'required' | 'too_long' | 'unknown_fields'
kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
reason: 'validation'
success: false
}
+64 -3
View File
@@ -5,6 +5,8 @@ type FormField = {
blockType?: string
label?: string
name?: string
/** select / radio choices defined in the panel. */
options?: { value?: unknown }[] | null
required?: boolean | null
}
@@ -24,7 +26,7 @@ export type FormValidationResult =
| {
/** Offending field, when a single field is at fault. */
field?: string
kind: 'required' | 'too_long' | 'unknown_fields'
kind: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
ok: false
reason: 'invalid'
}
@@ -47,6 +49,60 @@ const CAPTCHA_KEYS = new Set(['cf-turnstile-response', 'g-recaptcha-response'])
/** Hard ceiling on a single field's length, independent of the form config. */
const MAX_FIELD_LENGTH = 5000
/**
* ONE address, nothing else. The form-builder can send a confirmation to
* `{{email}}`, so a value like "[email protected], [email protected]" or one with a line break would
* turn the site into a spam relay (and CR/LF into header injection). Commas,
* semicolons, whitespace and angle brackets are rejected outright.
*/
const EMAIL = /^[^\s@,;<>"()[\]\\]+@[^\s"(),;<>@[\\\]][^\s"(),.;<>@[\\\]]*\.[^\s"(),;<>@[\\\]]{2,}$/
const MAX_EMAIL_LENGTH = 254
// Control characters except tab and line breaks (U+0000–U+001F, U+007F), plus
// bidi overrides that can disguise text in the admin panel and e-mails.
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u0008\v\f\u000E-\u001F\u007F\u202A-\u202E\u2066-\u2069]/g
type Checked = { error?: 'invalid_format'; value?: unknown }
/**
* Type-checks one value against its field's block type, as defined in the
* panel, and normalizes it. Anything not a plain value for that type is
* rejected — a hand-crafted request can't smuggle objects, extra recipients or
* values outside a select's options.
*/
function checkValue(field: FormField, value: unknown): Checked {
if (value === undefined || value === null || value === '') {return { value }}
switch (field.blockType) {
case 'checkbox':
return typeof value === 'boolean' ? { value } : { error: 'invalid_format' }
case 'email': {
if (typeof value !== 'string') {return { error: 'invalid_format' }}
const email = value.trim()
return email.length <= MAX_EMAIL_LENGTH && EMAIL.test(email) ? { value: email } : { error: 'invalid_format' }
}
case 'number': {
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
return Number.isFinite(n) ? { value: n } : { error: 'invalid_format' }
}
case 'radio':
case 'select': {
if (typeof value !== 'string' && typeof value !== 'number') {return { error: 'invalid_format' }}
const allowed = (field.options ?? []).map((o) => String(o?.value))
// No options configured → nothing to compare against; still a plain value.
return allowed.length === 0 || allowed.includes(String(value)) ? { value } : { error: 'invalid_format' }
}
case 'textarea':
return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' }
default:
// text, country, state and custom blocks: one line of plain text.
if (typeof value === 'number') {return { value }}
return typeof value === 'string'
? { value: value.replace(CONTROL, '').replace(/[\r\n]+/g, ' ') }
: { error: 'invalid_format' }
}
}
/**
* Default name for a GDPR consent field. A checkbox with this name is treated
* as a consent gate: it MUST be checked for the submission to go through,
@@ -116,10 +172,15 @@ export async function validateSubmission(
return { field: field.name, kind: 'too_long', ok: false, reason: 'invalid' }
}
const checked = field.name === consentFieldName ? { value } : checkValue(field, value)
if (checked.error) {
return { field: field.name, kind: checked.error, ok: false, reason: 'invalid' }
}
// Only carry through keys that belong to the form — unknown keys from a
// hand-crafted request are dropped, not stored.
if (value !== undefined) {
cleaned[field.name] = value
if (checked.value !== undefined) {
cleaned[field.name] = checked.value
}
}
+8
View File
@@ -7,6 +7,7 @@ import { buildNotifications } from './globals/Notifications/index.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -220,6 +221,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]
// --- consent log: proof of consent (opt-in) ---
if (options.consentLog) {
const logOptions = options.consentLog === true ? {} : options.consentLog
config.collections = [...(config.collections ?? []), buildConsentLogCollection()]
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
// --- IndexNow: submit published URLs (opt-in) ---
if (options.indexNow) {
const pagesSlug = options.pages?.slug ?? 'pages'
+9 -1
View File
@@ -42,6 +42,15 @@ export type IpalOptions = {
*/
adminRoute?: string
/** Internationalization — locales, default locale, fallback behavior */
/**
* Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records`
* collection and POST /api/ipal/consent. Pass `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Stores a random id, choices, policy version and time — no personal data.
* `true` or `{ retentionDays }` (default 1095). Default off.
*/
consentLog?: { retentionDays?: number } | boolean
/**
* Collections whose entries live under an archive page — blog posts, case
* studies, anything with a listing. Adds an "archive page" assignment per
@@ -61,7 +70,6 @@ export type IpalOptions = {
i18n: I18nConfig
/** Internationalization — locales, default locale, fallback behavior */
/**
* IndexNow (seo/indexNow.ts): on publish, submit the page's URLs in every
* language to Bing & co. (feeds ChatGPT Search / Copilot). Adds the hook to the
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, test } from 'vitest'
import { validateSubmission } from '../src/modules/forms/validateSubmission.js'
import { fakePayload } from './helpers.js'
const forms = {
f: {
fields: [
{ name: 'name', blockType: 'text' },
{ name: 'email', blockType: 'email' },
{ name: 'topic', blockType: 'select', options: [{ value: 'offer' }, { value: 'support' }] },
{ name: 'count', blockType: 'number' },
{ name: 'message', blockType: 'textarea' },
{ name: 'agree', blockType: 'checkbox' },
],
},
}
const { payload } = fakePayload({ forms })
const check = (data: Record<string, unknown>) => validateSubmission(payload, 'f', data)
describe('form validation — injection and abuse', () => {
test.each([
['[email protected], [email protected]'],
['[email protected];[email protected]'],
['[email protected]\r\nBcc: [email protected]'],
['Name <[email protected]>'],
['not-an-email'],
[`${'a'.repeat(250)}@x.pl`],
])('email %j is rejected — no extra recipients or headers', async (email) => {
expect(await check({ email })).toMatchObject({ field: 'email', kind: 'invalid_format', ok: false })
})
test('a valid email is trimmed and kept', async () => {
expect(await check({ email: ' [email protected] ' })).toMatchObject({
cleaned: { email: '[email protected]' },
ok: true,
})
})
test('select accepts only values configured in the panel', async () => {
expect(await check({ topic: 'offer' })).toMatchObject({ ok: true })
expect(await check({ topic: '<script>alert(1)</script>' })).toMatchObject({ field: 'topic', kind: 'invalid_format' })
})
test('objects, arrays and wrong types are rejected', async () => {
expect(await check({ name: { $gt: '' } })).toMatchObject({ field: 'name', kind: 'invalid_format' })
expect(await check({ message: ['a', 'b'] })).toMatchObject({ field: 'message', kind: 'invalid_format' })
expect(await check({ count: '12abc' })).toMatchObject({ field: 'count', kind: 'invalid_format' })
expect(await check({ agree: 'true' })).toMatchObject({ field: 'agree', kind: 'invalid_format' })
})
test('control and bidi characters are stripped; single-line text loses line breaks', async () => {
const res = await check({ name: 'Jan\r\nKowalski\u0007', message: 'Dzień\u0000 dobry‮\nlinia 2' })
expect(res).toMatchObject({ cleaned: { name: 'Jan Kowalski', message: 'Dzień dobry\nlinia 2' }, ok: true })
})
test('HTML is stored as text (the renderer and e-mails escape it)', async () => {
expect(await check({ message: '<img src=x onerror=alert(1)>' })).toMatchObject({
cleaned: { message: '<img src=x onerror=alert(1)>' },
ok: true,
})
})
test('numbers are normalized', async () => {
expect(await check({ count: ' 42 ' })).toMatchObject({ cleaned: { count: 42 }, ok: true })
})
})
+45
View File
@@ -12,6 +12,8 @@ import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { getCookieTable } from '../src/modules/consent/getConsentTexts.js'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { ipalKit } from '../src/plugin.js'
@@ -42,6 +44,7 @@ beforeAll(async () => {
plugins: [
ipalKit({
access: { authCollection: 'users' },
consentLog: true,
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
@@ -174,3 +177,45 @@ describe('getPageJsonLd', () => {
expect(await h.getPageJsonLd('pl', ['nie-ma'])).toEqual([])
})
})
describe('consent log', () => {
const post = (body: unknown, ip = '10.6.0.1') =>
buildConsentLogEndpoint().handler({
headers: new Headers({ 'x-real-ip': ip }),
json: async () => body,
payload,
} as never) as Promise<Response>
const state = { analytics: true, functional: false, marketing: false, necessary: true }
test('stores id, choices and version only', async () => {
const res = await post({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state, version: 2 })
expect(res.status).toBe(201)
const { docs } = await payload.find({ collection: 'consent-records' as never, where: { consentId: { equals: 'a1b2c3d4e5f6a7b8c9d0e1f2' } } })
const rec = docs[0] as unknown as Record<string, unknown>
expect(rec).toMatchObject({ choices: state, version: 2 })
expect(Object.keys(rec).filter((k) => /ip|agent|email/i.test(k))).toEqual([])
})
test('rejects malformed records', async () => {
for (const bad of [{}, { id: 'x', state, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state: { analytics: 'yes' }, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state, version: 0 }]) {
expect((await post(bad, '10.6.0.2')).status).toBe(400)
}
})
test('the collection is not writable or readable anonymously', async () => {
await expect(payload.find({ collection: 'consent-records' as never, overrideAccess: false })).rejects.toThrow()
})
})
describe('cookie table', () => {
test('rows from Cookie Settings in the requested language', async () => {
await payload.updateGlobal({
slug: 'cookie-settings' as never,
data: { cookies: [{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' }, { name: ' ' }] } as never,
locale: 'pl' as never,
})
expect(await getCookieTable({ locale: 'pl', payload })).toEqual([
{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' },
])
})
})
+11
View File
@@ -202,3 +202,14 @@ describe('buildCsp — googleMaps', () => {
expect(buildCsp().value).toContain('https://fonts.gstatic.com')
})
})
describe('consent storage — version and id', () => {
test('a consent from another policy version is ignored; id round-trips', async () => {
const { readConsentRecord, serializeConsent } = await import('../src/modules/consent/storage.js')
const state = { analytics: true, functional: true, marketing: false, necessary: true }
const raw = serializeConsent(state, 2, 'abc123')
expect(readConsentRecord(raw, 2)).toMatchObject({ id: 'abc123', state, version: 2 })
expect(readConsentRecord(raw, 3)).toBeNull()
expect(readConsentRecord(raw)).toBeNull() // default version 1
})
})