Files
Radosław SmolińskiandClaude Opus 5.5 f5c53e4523 Consent compliance: docs, agent guide, skills, changelog, shared behaviour spec, browser check, reference e2e
- docs/consent.md: compliance defaults, Global Privacy Control, withdrawal, consent log on by default and the SQL
  migration; no more "UODO requirement" or "GPC not needed". docs/analytics.md: what Consent Mode advanced sends.
- docs/consent-behaviour-spec.md: the behaviour IAPL and IAWL share, with the 13-item test list.
- CHANGELOG 1.17.0: the SQL migration first, a before → after table for an existing site.
- AGENT.md, iapl-setup / iapl-upgrade / iapl-reference / iapl-consent-check, PROGRAMISTA item 78; reference skills copy.
- iapl-consent-check: Global Privacy Control, equal prominence and withdrawal runs; Google asset warnings.
- Reference site uses the new defaults; e2e for GPC, a stale grant, equal prominence, withdrawal; e2e:built runs every
  consent test in both bundlers. YouTubeEmbed warns in development without a poster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:48:19 +01:00

215 lines
13 KiB
JavaScript

#!/usr/bin/env node
// iapl-consent-check — proves in a real browser that tracking waits for consent (GDPR).
// node consent-check.mjs <pageUrl> [--wait 4000]
// Five runs, each in a fresh browser profile:
// 1. no decision → no third-party pixels, no tracking cookies, Google only with "denied" signals;
// "Reject" as prominent as "Accept all" (same size, same look or no weaker contrast)
// 2. accept all → configured tags start (reported, so you can confirm they're the right ones)
// 3. reject all → same as 1, also after a reload
// 4. Global Privacy Control (Sec-GPC: 1 + navigator.globalPrivacyControl) → no banner (IAPL 1.17.0 default),
// no tracker request at all, Google included
// 5. accept, then withdraw (cookie button → reject) → the tracking cookies are gone
// Needs Playwright: pnpm add -D playwright && pnpm exec playwright install chromium
// Exit code: 0 = compliant, 1 = violations, 2 = setup problem.
const args = process.argv.slice(2)
if (!args[0] || args.includes('--help') || args.includes('-h')) {
console.log('Usage: consent-check.mjs <pageUrl> [--wait ms]')
process.exit(args[0] ? 0 : 2)
}
const url = args[0]
const waitIdx = args.indexOf('--wait')
const WAIT = waitIdx >= 0 ? Number(args[waitIdx + 1]) || 4000 : 4000
let pw
for (const mod of ['playwright', 'playwright-core', '@playwright/test']) {
try { pw = await import(mod); break } catch { /* next */ }
}
if (!pw) {
console.error('iapl-consent-check: Playwright not found. Install: pnpm add -D playwright && pnpm exec playwright install chromium')
process.exit(2)
}
const { chromium } = pw.default ?? pw
// Non-Google vendors have no Consent Mode → ANY request before consent is a violation.
const PIXELS = [
['Meta Pixel', /connect\.facebook\.net|facebook\.com\/tr/],
['Microsoft Clarity', /clarity\.ms/],
['LinkedIn Insight', /snap\.licdn\.com|px\.ads\.linkedin\.com/],
['TikTok Pixel', /analytics\.tiktok\.com/],
['DoubleClick / Google Ads', /doubleclick\.net|googleadservices\.com/],
['Hotjar', /hotjar\.com/],
]
// Embeds that set cookies — should wait for consent or use a privacy mode.
const EMBEDS = [
['YouTube (cookie mode)', /youtube\.com\/embed/],
['Google Maps embed', /google\.com\/maps\/embed/],
]
// Requests to Google before any choice that are not tracking tags: a warning (the visitor's IP reaches Google).
const THIRD_PARTY_ASSETS = [
['YouTube thumbnail (i.ytimg.com) — upload a poster', /i\.ytimg\.com/],
['Google Fonts — self-host (next/font)', /fonts\.googleapis\.com|fonts\.gstatic\.com/],
['Google Maps API', /maps\.googleapis\.com/],
]
const GOOGLE_COLLECT = /google-analytics\.com\/(g\/)?collect|analytics\.google\.com\/g\/collect/
const GOOGLE_TAG = /googletagmanager\.com\/(gtm|gtag)/
const TRACKING_COOKIES = /^(_ga|_gid|_gat|_gcl_|_fbp|_fbc|_clck|_clsk|_ttp|li_|lidc|bcookie|_hj)/
// gcs=G1{ad}{analytics}: '1' = granted. Before consent both must not be '1'.
const consentGranted = (u) => {
const gcs = new URL(u).searchParams.get('gcs')
return gcs ? /^G1.?1|^G11/.test(gcs) : null
}
const browser = await chromium.launch()
/** Computed look of the banner's accept / reject buttons and the banner surface (run 1). */
const buttonLook = (page) => page.evaluate(() => {
const props = ['fontSize', 'fontWeight', 'paddingTop', 'paddingLeft', 'borderTopLeftRadius', 'height', 'backgroundColor', 'color', 'borderTopColor', 'borderTopWidth']
const pick = (el) => {
if (!el) return null
const cs = getComputedStyle(el)
const out = { tag: el.tagName }
for (const p of props) out[p] = p === 'height' ? String(Math.round(el.getBoundingClientRect().height)) : cs[p]
return out
}
const banner = document.querySelector('[data-ipal="banner"]')
return { accept: pick(document.querySelector('[data-ipal="banner"] [data-ipal="accept"]')), reject: pick(document.querySelector('[data-ipal="banner"] [data-ipal="reject"]')), surface: banner ? getComputedStyle(banner).backgroundColor : null }
})
const run = async (label, action, { gpc = false, withdraw = false } = {}) => {
const ctx = await browser.newContext(gpc ? { extraHTTPHeaders: { 'Sec-GPC': '1' } } : {})
if (gpc) await ctx.addInitScript(() => Object.defineProperty(Navigator.prototype, 'globalPrivacyControl', { configurable: true, get: () => true }))
const page = await ctx.newPage()
const requests = []
page.on('request', (r) => requests.push(r.url()))
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
} catch (e) {
console.error(`iapl-consent-check: cannot open ${url} (${e.message.split('\n')[0]})`)
const gpcRun = await run('4. Global Privacy Control')
if (gpcRun.bannerVisible) warnings.push('4. Global Privacy Control: the banner is shown (gpc="ask", gpc={false} or IAPL before 1.17.0) — the default honours the signal without a banner')
inspect(gpcRun, true)
if (gpcRun.requests.some((u) => GOOGLE_TAG.test(u) || GOOGLE_COLLECT.test(u))) violations.push('4. Global Privacy Control: the Google tag loaded although the browser asks not to share data and nothing was granted')
const withdrawn = await run('5. accept, then withdraw', 'accept', { withdraw: true })
if (withdrawn.withdrawn?.missing) warnings.push('5. withdraw: no [data-ipal="cookie-button"] to reopen the settings — is <CookieButton/> rendered?')
else if (withdrawn.withdrawn) {
const left = withdrawn.withdrawn.after.filter((c) => TRACKING_COOKIES.test(c))
for (const c of left) violations.push(`5. withdraw: tracking cookie "${c}" still set after "Reject" (add it to <ConsentProvider cookieMap> or the panel's cookie list)`)
}
await browser.close()
process.exit(2)
}
await page.waitForTimeout(WAIT)
await page.mouse.wheel(0, 2000) // some tags wait for interaction (Analytics defer)
await page.waitForTimeout(500)
const banner = (await page.locator('[data-ipal="banner"]').count()) > 0
const bannerVisible = banner && (await page.locator('[data-ipal="banner"]').first().isVisible())
const look = action ? null : await buttonLook(page)
let clicked = null
if (action) {
const btn = page.locator(`[data-ipal="${action}"]`)
if ((await btn.count()) > 0) {
const before = requests.length
await btn.first().click()
await page.waitForTimeout(WAIT)
clicked = before
if (action === 'reject') {
await page.reload({ waitUntil: 'domcontentloaded' })
await page.waitForTimeout(WAIT)
}
} else clicked = -1
}
let withdrawn = null
if (withdraw && clicked !== -1) {
const before = (await ctx.cookies()).map((c) => c.name)
const reopen = page.locator('[data-ipal="cookie-button"]')
if ((await reopen.count()) > 0) {
await reopen.first().click()
await page.locator('[data-ipal="banner"] [data-ipal="reject"]').first().click()
await page.waitForTimeout(1000)
withdrawn = { after: (await ctx.cookies()).map((c) => c.name), before }
} else withdrawn = { missing: true }
}
const cookies = (await ctx.cookies()).map((c) => c.name)
await ctx.close()
return { label, requests, cookies, banner, bannerVisible, clicked, look, withdrawn }
}
/** WCAG contrast of two computed colours (rgb/rgba strings); null when one is transparent. */
const rgb = (c) => { const m = /rgba?\(([^)]+)\)/.exec(c ?? ''); if (!m) return null; const p = m[1].split(',').map(Number); return p.length > 3 && p[3] === 0 ? null : p.slice(0, 3) }
const lum = ([r, g, b]) => { const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 }; return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b) }
const contrast = (a, b) => { const x = rgb(a), y = rgb(b); if (!x || !y) return null; const [l1, l2] = [lum(x), lum(y)].sort((m, n) => n - m); return (l1 + 0.05) / (l2 + 0.05) }
const violations = []
const warnings = []
const info = []
const inspect = (r, mustBeQuiet) => {
const pixelHits = PIXELS.filter(([, re]) => r.requests.some((u) => re.test(u))).map(([n]) => n)
const embedHits = EMBEDS.filter(([, re]) => r.requests.some((u) => re.test(u))).map(([n]) => n)
const trackingCookies = r.cookies.filter((c) => TRACKING_COOKIES.test(c))
const collects = r.requests.filter((u) => GOOGLE_COLLECT.test(u))
const grantedCollects = collects.filter((u) => consentGranted(u) === true)
if (mustBeQuiet) {
for (const p of pixelHits) violations.push(`${r.label}: ${p} loaded without consent`)
for (const c of trackingCookies) violations.push(`${r.label}: tracking cookie "${c}" set without consent`)
if (grantedCollects.length) violations.push(`${r.label}: Google Analytics hit with consent GRANTED (gcs) before a decision`)
const noSignal = collects.filter((u) => consentGranted(u) === null)
if (noSignal.length) warnings.push(`${r.label}: Google Analytics hit without Consent Mode signal (gcs) — setDefaultConsent must run before the tag`)
for (const e of embedHits) warnings.push(`${r.label}: ${e} loaded before consent — gate it (ConsentScript) or use youtube-nocookie / click-to-load`)
for (const [n, re] of THIRD_PARTY_ASSETS) if (r.requests.some((u) => re.test(u))) warnings.push(`${r.label}: ${n} — a request to Google before any choice`)
}
return { pixelHits, trackingCookies, google: r.requests.some((u) => GOOGLE_TAG.test(u) || GOOGLE_COLLECT.test(u)) }
}
const first = await run('1. no decision')
if (!first.banner) warnings.push('1. no decision: cookie banner [data-ipal="banner"] not found — is <CookieBanner/> rendered? Older IAPL versions lack data-ipal attributes on buttons.')
const s1 = inspect(first, true)
// Equal prominence (docs/consent-behaviour-spec.md §5): same element and size; same look, or "Reject" no weaker.
if (first.look?.accept && !first.look.reject) violations.push('1. no decision: no "Reject" button on the first layer')
else if (first.look?.accept && first.look.reject) {
const { accept: a, reject: j, surface } = first.look
const size = ['tag', 'fontSize', 'fontWeight', 'paddingTop', 'paddingLeft', 'borderTopLeftRadius', 'height'].filter((p) => a[p] !== j[p])
if (size.length) violations.push(`1. no decision: "Reject" is not as prominent as "Accept all" (differs in ${size.join(', ')})`)
const colours = ['backgroundColor', 'color', 'borderTopColor', 'borderTopWidth'].filter((p) => a[p] !== j[p])
if (colours.length) {
const textJ = contrast(j.color, rgb(j.backgroundColor) ? j.backgroundColor : surface)
const edge = (b) => contrast(rgb(b.backgroundColor) ? b.backgroundColor : b.borderTopColor, surface) ?? 1
if ((textJ !== null && textJ < 4.5) || edge(j) < edge(a)) violations.push(`1. no decision: "Reject" looks weaker than "Accept all" (${colours.join(', ')} differ and its contrast is lower)`)
}
}
const accepted = await run('2. accept all', 'accept')
if (accepted.clicked === -1) warnings.push('2. accept: button [data-ipal="accept"] not found — skipped')
const afterAccept = { ...accepted, requests: accepted.clicked > 0 ? accepted.requests.slice(accepted.clicked) : accepted.requests }
const s2 = inspect(afterAccept, false)
if (!accepted.cookies.includes('cookie-consent') && accepted.clicked >= 0) warnings.push('2. accept: consent cookie "cookie-consent" not stored')
const rejected = await run('3. reject all (+ reload)', 'reject')
if (rejected.clicked === -1) warnings.push('3. reject: button [data-ipal="reject"] not found — skipped')
else inspect({ ...rejected, requests: rejected.requests.slice(rejected.clicked ?? 0) }, true)
const gpcRun = await run('4. Global Privacy Control')
if (gpcRun.bannerVisible) warnings.push('4. Global Privacy Control: the banner is shown (gpc="ask", gpc={false} or IAPL before 1.17.0) — the default honours the signal without a banner')
inspect(gpcRun, true)
if (gpcRun.requests.some((u) => GOOGLE_TAG.test(u) || GOOGLE_COLLECT.test(u))) violations.push('4. Global Privacy Control: the Google tag loaded although the browser asks not to share data and nothing was granted')
const withdrawn = await run('5. accept, then withdraw', 'accept', { withdraw: true })
if (withdrawn.withdrawn?.missing) warnings.push('5. withdraw: no [data-ipal="cookie-button"] to reopen the settings — is <CookieButton/> rendered?')
else if (withdrawn.withdrawn) {
const left = withdrawn.withdrawn.after.filter((c) => TRACKING_COOKIES.test(c))
for (const c of left) violations.push(`5. withdraw: tracking cookie "${c}" still set after "Reject" (add it to <ConsentProvider cookieMap> or the panel's cookie list)`)
}
await browser.close()
info.push(`before consent: Google tag ${s1.google ? 'loaded (Consent Mode, OK if gcs denied)' : 'not loaded'}`)
info.push(`after accept: ${s2.pixelHits.length ? s2.pixelHits.join(', ') : 'no third-party pixels'}${s2.google ? ' + Google' : ''}; cookies: ${accepted.cookies.filter((c) => TRACKING_COOKIES.test(c)).join(', ') || 'none'}`)
console.log(`iapl-consent-check — ${url}`)
for (const v of violations) console.log(`[ERROR] ${v}`)
for (const w of warnings) console.log(`[WARNING] ${w}`)
for (const i of info) console.log(` · ${i}`)
console.log(`iapl-consent-check: ${violations.length} violation(s), ${warnings.length} warning(s)`)
process.exit(violations.length ? 1 : 0)