Consent compliance: Global Privacy Control honoured, equal choice by default, withdrawal that stops running tools, consent log on by default
- GPC (gpc.ts): read in the browser before the first paint (consentBannerScript) and in the consent store; pages stay static. 'honour' (default): no banner, analytics and marketing off, no request to Google or a pixel; an explicit choice on the site wins; a grant made without the signal gives way when it appears. 'ask' and false as opt-outs. - equalChoice defaults to true; a development warning when the banner has no 'reject'. - Withdrawal: Meta / TikTok / Clarity told at once, listed localStorage / sessionStorage keys removed. - Clarity gets consentv2 when it loads; ads_data_redaction with the Consent Mode default. - consentLog on by default (consentLog: false turns it off); SiteProviders posts to it by itself; a missing SQL table answers 503 with one log line. - Default banner text: one sentence on changing the choice and browser settings; the GPC line (PL / EN). - Doctor: consent-log-migration, consent-banner rules. - Stats: Sec-GPC over a choice made without it keeps the visitor id out. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
41771fd51a
commit
99036eb70c
@@ -491,7 +491,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
|
||||
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
|
||||
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
|
||||
const hooks = async (options: Record<string, unknown>) =>
|
||||
(await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, (c.hooks?.beforeOperation ?? []).filter(ruleHook).length])
|
||||
(await iapl({ access: { authCollection: 'users' }, consentLog: false, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, (c.hooks?.beforeOperation ?? []).filter(ruleHook).length])
|
||||
expect(await hooks({})).toEqual([['customers', 0], ['users', 1]])
|
||||
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 0], ['users', 0]])
|
||||
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
// @vitest-environment happy-dom
|
||||
/**
|
||||
* Consent compliance (1.17.0): Global Privacy Control honoured before the first paint on a static page, "Reject" as
|
||||
* prominent as "Accept all" by default, a withdrawal that stops the tools already running and clears their storage,
|
||||
* Clarity's consent signal, the consent log on by default and failing soft without its table, and the doctor rules
|
||||
* that report a weaker setup. docs/consent.md and docs/consent-behaviour-spec.md describe each.
|
||||
*/
|
||||
import type { Config, PayloadRequest } from 'payload'
|
||||
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { act, createElement, type ReactElement } from 'react'
|
||||
import { hydrateRoot, type Root } from 'react-dom/client'
|
||||
import { renderToString } from 'react-dom/server'
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { ConsentState } from '../src/modules/consent/categories.js'
|
||||
import type { I18nConfig } from '../src/modules/i18n/index.js'
|
||||
|
||||
import { Analytics } from '../src/modules/analytics/Analytics.js'
|
||||
import { loadClarity } from '../src/modules/analytics/pixels.js'
|
||||
import { shouldLoadGoogle } from '../src/modules/analytics/shouldLoadGoogle.js'
|
||||
import { ConsentProvider } from '../src/modules/consent/ConsentContext.js'
|
||||
import { buildConsentLogEndpoint, isMissingTableError } from '../src/modules/consent/consentLog.js'
|
||||
import { resetConsentStore } from '../src/modules/consent/consentStore.js'
|
||||
import { CookieBanner } from '../src/modules/consent/CookieBanner.js'
|
||||
import { CookieButton } from '../src/modules/consent/CookieButton.js'
|
||||
import { consentBannerScript } from '../src/modules/consent/firstPaint.js'
|
||||
import { CONSENT_FALLBACK, CONSENT_FALLBACK_PL } from '../src/modules/consent/getConsentTexts.js'
|
||||
import { gpcFromHeaders, gpcWellKnown, resolveConsent } from '../src/modules/consent/gpc.js'
|
||||
import { CONSENT_COOKIE, readConsentRecord, serializeConsent } from '../src/modules/consent/storage.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
import { SiteProviders } from '../src/modules/frontend/SiteProviders.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
|
||||
const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement
|
||||
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const ACCEPT: ConsentState = { analytics: true, functional: true, marketing: true, necessary: true }
|
||||
const REJECT: ConsentState = { analytics: false, functional: false, marketing: false, necessary: true }
|
||||
const texts = {
|
||||
...CONSENT_FALLBACK,
|
||||
cookies: [
|
||||
{ name: 'chat_session', category: 'marketing' as const, storage: 'localStorage' as const },
|
||||
{ name: 'vid_*', category: 'analytics' as const, storage: 'sessionStorage' as const },
|
||||
{ name: 'theme', category: 'necessary' as const, storage: 'localStorage' as const },
|
||||
],
|
||||
version: 3,
|
||||
}
|
||||
const stored = (state: ConsentState, gpc?: boolean) => serializeConsent(state, 3, 'a1b2c3d4e5f6a7b8c9d0e1f2', gpc)
|
||||
|
||||
type Tree = { analytics?: object; banner?: object; gpc?: 'ask' | 'honour' | false; logEndpoint?: string }
|
||||
const tree = (o: Tree = {}) =>
|
||||
h(
|
||||
ConsentProvider,
|
||||
{ gpc: o.gpc, logEndpoint: o.logEndpoint, texts },
|
||||
h('main', null, 'page'),
|
||||
h(CookieBanner, o.banner ?? {}),
|
||||
h(CookieButton),
|
||||
o.analytics ? h(Analytics, o.analytics) : null,
|
||||
)
|
||||
|
||||
const setGpc = (on: boolean | undefined) => {
|
||||
if (on === undefined) {delete (navigator as { globalPrivacyControl?: boolean }).globalPrivacyControl}
|
||||
else {Object.defineProperty(navigator, 'globalPrivacyControl', { configurable: true, value: on })}
|
||||
}
|
||||
const clearCookies = () => {
|
||||
for (const c of document.cookie.split('; ')) {
|
||||
const name = c.split('=')[0]
|
||||
if (name) {document.cookie = `${name}=;path=/;max-age=0`}
|
||||
}
|
||||
}
|
||||
const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1])
|
||||
const storedRecord = () => readConsentRecord(liveCookies().find((c) => c.startsWith(`${CONSENT_COOKIE}=`))?.split('=')[1], 3)
|
||||
const setConsentCookie = (value: string) => {
|
||||
document.cookie = `${CONSENT_COOKIE}=${value};path=/`
|
||||
}
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root | undefined
|
||||
let injected: string[]
|
||||
let errors: ReturnType<typeof vi.spyOn>
|
||||
|
||||
beforeEach(() => {
|
||||
clearCookies()
|
||||
resetConsentStore()
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
setGpc(undefined)
|
||||
for (const key of ['dataLayer', 'fbq', '_fbq', 'clarity', 'ttq']) {delete (window as unknown as Record<string, unknown>)[key]}
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
errors = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
injected = []
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation((node) => {
|
||||
injected.push((node as HTMLScriptElement).src || 'inline')
|
||||
return node
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {act(() => root!.unmount())}
|
||||
root = undefined
|
||||
container.remove()
|
||||
setGpc(undefined)
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const banner = () => container.querySelector<HTMLElement>('[data-ipal="banner"]')
|
||||
const button = () => container.querySelector<HTMLElement>('[data-ipal="cookie-button"]')
|
||||
const click = (name: string) => act(() => container.querySelector<HTMLElement>(`[data-ipal="${name}"]`)!.click())
|
||||
|
||||
/** Server HTML, the inline script as the parser runs it (with the real `navigator`), then hydration. */
|
||||
function load(o: Tree = {}) {
|
||||
const node = tree(o)
|
||||
const html = renderToString(node)
|
||||
container.innerHTML = html
|
||||
const el = container.querySelector<HTMLScriptElement>('[data-ipal="banner-script"]')
|
||||
const code = /<script[^>]*data-ipal="banner-script"[^>]*>(?<code>.*?)<\/script>/s.exec(html)?.groups?.code
|
||||
if (el && code) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
new Function('document', code)({ get cookie() { return document.cookie }, currentScript: el })
|
||||
}
|
||||
const shownBeforeHydration = banner() !== null && !banner()!.hasAttribute('hidden') && banner()!.style.display !== 'none'
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
return { html, shownBeforeHydration }
|
||||
}
|
||||
const layer = () => [...(window.dataLayer ?? [])].map((e) => (Object.prototype.toString.call(e) === '[object Arguments]' ? Array.from(e as ArrayLike<unknown>) : e))
|
||||
|
||||
describe('resolveConsent: Global Privacy Control × stored choice × mode', () => {
|
||||
const rec = (state: ConsentState, gpc?: boolean) => ({ ...(gpc === undefined ? {} : { gpc }), state })
|
||||
test.each([
|
||||
// [label, record, signal, mode, decided, analytics, marketing, stale, gpc]
|
||||
['no choice, no signal', null, false, 'honour', false, false, false, false, false],
|
||||
['no choice, signal, honour → no banner, off', null, true, 'honour', true, false, false, false, true],
|
||||
['no choice, signal, ask → banner', null, true, 'ask', false, false, false, false, true],
|
||||
['no choice, signal, ignored', null, true, false, false, false, false, false, false],
|
||||
['grant made WITH the signal stands', rec(ACCEPT, true), true, 'honour', true, true, true, false, true],
|
||||
['grant made WITHOUT the signal gives way', rec(ACCEPT, false), true, 'honour', true, false, false, true, true],
|
||||
['…also in ask mode', rec(ACCEPT, false), true, 'ask', true, false, false, true, true],
|
||||
['…not when the signal is ignored', rec(ACCEPT, false), true, false, true, true, true, false, false],
|
||||
['a record from before 1.17.0 (no gpc field) stands', rec(ACCEPT), true, 'honour', true, true, true, false, true],
|
||||
['a refusal made without the signal: nothing to change', rec(REJECT, false), true, 'honour', true, false, false, false, true],
|
||||
['the absence of the signal is never consent', rec(REJECT, true), false, 'honour', true, false, false, false, false],
|
||||
] as const)('%s', (_l, record, signal, mode, decided, analytics, marketing, stale, gpc) => {
|
||||
const r = resolveConsent(record, signal, mode)
|
||||
expect([r.decided, r.state.analytics, r.state.marketing, r.stale, r.gpc]).toEqual([decided, analytics, marketing, stale, gpc])
|
||||
})
|
||||
|
||||
test('functional is not the signal\'s business: a functional grant made without it stays', () => {
|
||||
expect(resolveConsent(rec({ ...ACCEPT }, false), true).state.functional).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the stored record', () => {
|
||||
test('gpc goes in and comes out; a non-boolean value is dropped; records without it still read', () => {
|
||||
expect(readConsentRecord(stored(ACCEPT, true), 3)!.gpc).toBe(true)
|
||||
expect(readConsentRecord(stored(ACCEPT, false), 3)!.gpc).toBe(false)
|
||||
expect(readConsentRecord(stored(ACCEPT), 3)!).not.toHaveProperty('gpc')
|
||||
const odd = encodeURIComponent(JSON.stringify({ gpc: 'yes', state: ACCEPT, timestamp: 'x', version: 3 }))
|
||||
expect(readConsentRecord(odd, 3)!).not.toHaveProperty('gpc')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the first-paint script and Global Privacy Control', () => {
|
||||
const run = (o: { cookie?: string; gpc?: 'ask' | 'honour' | false; signal?: boolean }) => {
|
||||
setGpc(o.signal)
|
||||
const b = { removeAttribute: (n: string) => void b.removed.push(n), removed: [] as string[], style: {} as Record<string, string>, addEventListener() {} }
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
new Function('document', consentBannerScript({ gpc: o.gpc, version: 3 }))({ cookie: o.cookie ?? '', currentScript: { previousElementSibling: b } })
|
||||
return b.style.display === 'none' ? 'hidden' : b.removed.includes('hidden') ? 'shown' : 'untouched'
|
||||
}
|
||||
test.each([
|
||||
['signal, honour (default)', { signal: true }, 'hidden'],
|
||||
['signal, ask', { gpc: 'ask' as const, signal: true }, 'shown'],
|
||||
['signal, ignored', { gpc: false as const, signal: true }, 'shown'],
|
||||
['no signal (false)', { signal: false }, 'shown'],
|
||||
['no support (undefined)', {}, 'shown'],
|
||||
['signal and a current choice', { cookie: `${CONSENT_COOKIE}=${stored(REJECT)}`, signal: true }, 'hidden'],
|
||||
])('%s → %s', (_l, o, want) => expect(run(o)).toBe(want))
|
||||
})
|
||||
|
||||
describe('honour (default): a browser with Global Privacy Control', () => {
|
||||
test('no banner before or after hydration, the button instead; the same page HTML as without the signal', () => {
|
||||
const plain = renderToString(tree())
|
||||
setGpc(true)
|
||||
const r = load()
|
||||
expect(r.html).toBe(plain)
|
||||
expect(r.shownBeforeHydration).toBe(false)
|
||||
expect(banner()).toBeNull()
|
||||
expect(button()).not.toBeNull()
|
||||
expect(liveCookies()).toEqual([]) // nothing stored for a visitor who only sends the signal
|
||||
})
|
||||
|
||||
test('advanced mode: nothing reaches Google or a pixel; the Consent Mode default is all denied', () => {
|
||||
setGpc(true)
|
||||
load({ analytics: { clarityProjectId: 'clar', gtmContainerId: 'GTM-TEST', metaPixelId: '123' } })
|
||||
expect(injected).toEqual([])
|
||||
expect(layer()[0]).toEqual(['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied' })])
|
||||
expect(layer().some((e) => (e as { event?: string }).event === 'gtm.js')).toBe(false)
|
||||
})
|
||||
|
||||
test('the settings window says the signal is honoured; an explicit grant there wins and is stored with gpc: true', () => {
|
||||
const fetchMock = vi.fn((_u: string, _i: { body: string }) => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
setGpc(true)
|
||||
load({ analytics: { gtmContainerId: 'GTM-TEST', metaPixelId: '123' }, logEndpoint: '/api/ipal/consent' })
|
||||
click('cookie-button')
|
||||
expect(container.querySelector('[data-ipal="gpc-notice"]')?.textContent).toBe(CONSENT_FALLBACK.gpcNotice)
|
||||
click('accept')
|
||||
expect(storedRecord()).toMatchObject({ gpc: true, state: ACCEPT })
|
||||
expect(injected).toEqual(expect.arrayContaining(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST', 'https://connect.facebook.net/en_US/fbevents.js']))
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({ gpc: true, state: ACCEPT })
|
||||
})
|
||||
|
||||
test('next page view with that grant: kept (made with the signal on)', () => {
|
||||
setConsentCookie(stored(ACCEPT, true))
|
||||
setGpc(true)
|
||||
load({ analytics: { gtmContainerId: 'GTM-TEST' } })
|
||||
expect(storedRecord()!.state).toEqual(ACCEPT)
|
||||
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the signal appears after a grant made without it', () => {
|
||||
test('analytics and marketing go off without asking: cookies deleted, Google told, record rewritten and logged', () => {
|
||||
const fetchMock = vi.fn((_u: string, _i: { body: string }) => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
setConsentCookie(stored(ACCEPT, false))
|
||||
document.cookie = '_ga=GA1.1.1;path=/'
|
||||
document.cookie = '_fbp=fb.1;path=/'
|
||||
setGpc(true)
|
||||
load({ analytics: { gtmContainerId: 'GTM-TEST', metaPixelId: '123' }, logEndpoint: '/api/ipal/consent' })
|
||||
expect(banner()).toBeNull()
|
||||
expect(storedRecord()).toMatchObject({ gpc: true, id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state: { ...ACCEPT, analytics: false, marketing: false } })
|
||||
expect(liveCookies().filter((c) => /^_ga|^_fbp/.test(c))).toEqual([])
|
||||
expect(layer()[0]).toEqual(['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied', functionality_storage: 'granted' })])
|
||||
expect(injected).toEqual([])
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({ gpc: true, state: { analytics: false, marketing: false } })
|
||||
})
|
||||
|
||||
test('a record from before 1.17.0 stands (we cannot know which came first)', () => {
|
||||
setConsentCookie(stored(ACCEPT))
|
||||
setGpc(true)
|
||||
load({ analytics: { gtmContainerId: 'GTM-TEST' } })
|
||||
expect(storedRecord()!.state).toEqual(ACCEPT)
|
||||
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
|
||||
})
|
||||
|
||||
test("gpc={false}: the signal is ignored, the grant stands", () => {
|
||||
setConsentCookie(stored(ACCEPT, false))
|
||||
setGpc(true)
|
||||
load({ gpc: false })
|
||||
expect(storedRecord()!.state).toEqual(ACCEPT)
|
||||
})
|
||||
})
|
||||
|
||||
describe("gpc='ask'", () => {
|
||||
test('the banner is shown with the notice; nothing reaches Google until a choice', () => {
|
||||
setGpc(true)
|
||||
const r = load({ analytics: { gtmContainerId: 'GTM-TEST' }, gpc: 'ask' })
|
||||
expect(r.shownBeforeHydration).toBe(true)
|
||||
expect(container.querySelector('[data-ipal="gpc-notice"]')).not.toBeNull()
|
||||
expect(injected).toEqual([])
|
||||
click('accept')
|
||||
expect(storedRecord()).toMatchObject({ gpc: true, state: ACCEPT })
|
||||
expect(injected).toContain('https://www.googletagmanager.com/gtm.js?id=GTM-TEST')
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldLoadGoogle', () => {
|
||||
test.each([
|
||||
['advanced', false, REJECT, true],
|
||||
['advanced', true, REJECT, false],
|
||||
['advanced', true, { ...REJECT, analytics: true }, true],
|
||||
['basic', false, REJECT, false],
|
||||
['basic', true, { ...REJECT, marketing: true }, true],
|
||||
] as const)('%s, gpc %s', (consentMode, gpc, state, want) => {
|
||||
expect(shouldLoadGoogle({ consentMode, gpc, ready: true, state })).toBe(want)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withdrawal stops what already runs', () => {
|
||||
test('pixels get their revoke call, Clarity stops, listed storage keys go; necessary keys stay', () => {
|
||||
setConsentCookie(stored(ACCEPT, false))
|
||||
localStorage.setItem('chat_session', 'x')
|
||||
localStorage.setItem('theme', 'dark')
|
||||
sessionStorage.setItem('vid_1', 'y')
|
||||
const fbq = vi.fn()
|
||||
const clarity = vi.fn()
|
||||
const revokeConsent = vi.fn()
|
||||
Object.assign(window, { clarity, fbq, ttq: { grantConsent: vi.fn(), revokeConsent } })
|
||||
load()
|
||||
click('cookie-button')
|
||||
click('reject')
|
||||
expect(fbq).toHaveBeenCalledWith('consent', 'revoke')
|
||||
expect(revokeConsent).toHaveBeenCalled()
|
||||
expect(clarity).toHaveBeenCalledWith('consent', false)
|
||||
expect(localStorage.getItem('chat_session')).toBeNull()
|
||||
expect(sessionStorage.getItem('vid_1')).toBeNull()
|
||||
expect(localStorage.getItem('theme')).toBe('dark')
|
||||
})
|
||||
|
||||
test('granting marketing again on the same page: the pixel is told to grant', () => {
|
||||
setConsentCookie(stored(REJECT, false))
|
||||
const fbq = vi.fn()
|
||||
Object.assign(window, { fbq })
|
||||
load()
|
||||
click('cookie-button')
|
||||
click('accept')
|
||||
expect(fbq).toHaveBeenCalledWith('consent', 'grant')
|
||||
})
|
||||
|
||||
test('Clarity gets its consent signal when it loads (EEA visits need one)', () => {
|
||||
loadClarity('clar', { analytics: true, marketing: false })
|
||||
const queue = (window as unknown as { clarity: { q: unknown[][] } }).clarity.q
|
||||
expect(queue[0]).toEqual(['consentv2', { ad_Storage: 'denied', analytics_Storage: 'granted' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('equal choice by default', () => {
|
||||
const classOf = (html: string, action: string) => new RegExp(`class="([^"]*)" data-ipal="${action}"`).exec(html)?.[1]
|
||||
test('"Reject" looks like "Accept all"; equalChoice={false} restores the secondary look', () => {
|
||||
const html = renderToString(tree())
|
||||
expect(classOf(html, 'reject')).toBe(classOf(html, 'accept'))
|
||||
const old = renderToString(tree({ banner: { equalChoice: false } }))
|
||||
expect(classOf(old, 'reject')).not.toBe(classOf(old, 'accept'))
|
||||
})
|
||||
|
||||
test('an order without "reject" warns while developing', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
load({ banner: { order: ['settings', 'accept'] } })
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining("has no 'reject'"))
|
||||
})
|
||||
})
|
||||
|
||||
describe('default texts', () => {
|
||||
test('the extra sentence (change the choice; browser settings) and the GPC line, in both languages', () => {
|
||||
expect(CONSENT_FALLBACK.message).toContain('set cookie rules in your browser')
|
||||
expect(CONSENT_FALLBACK_PL.message).toContain('w przeglądarce')
|
||||
expect(CONSENT_FALLBACK_PL.gpcNotice).toContain('Global Privacy Control')
|
||||
})
|
||||
})
|
||||
|
||||
describe('server side', () => {
|
||||
test('gpcFromHeaders: only the exact value 1', () => {
|
||||
expect(gpcFromHeaders(new Headers({ 'sec-gpc': '1' }))).toBe(true)
|
||||
expect(gpcFromHeaders(new Headers({ 'sec-gpc': '0' }))).toBe(false)
|
||||
expect(gpcFromHeaders(new Headers())).toBe(false)
|
||||
expect(gpcFromHeaders(null)).toBe(false)
|
||||
})
|
||||
|
||||
test('gpcWellKnown answers the site statement', async () => {
|
||||
const res = gpcWellKnown({ lastUpdate: '2026-11-26' })()
|
||||
expect(await res.json()).toEqual({ gpc: true, lastUpdate: '2026-11-26' })
|
||||
})
|
||||
|
||||
test('SiteProviders posts to the shell\'s consent log endpoint by default; logEndpoint={false} turns it off', () => {
|
||||
const fetchMock = vi.fn((_u: string, _i: object) => Promise.resolve(new Response(null)))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const shell = { analytics: {}, consent: texts, consentLogEndpoint: '/api/ipal/consent', jsonLd: [], lightboxTexts: {}, theme: {}, turnstileSiteKey: null }
|
||||
for (const [props, want] of [[{}, 1], [{ logEndpoint: false }, 0]] as const) {
|
||||
fetchMock.mockClear()
|
||||
clearCookies()
|
||||
resetConsentStore()
|
||||
const node = h(SiteProviders, { analytics: false, preconnect: false, shell, ...props }, h('main', null, 'page'))
|
||||
container.innerHTML = renderToString(node)
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
click('reject')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(want)
|
||||
if (want) {expect(fetchMock.mock.calls[0][0]).toBe('/api/ipal/consent')}
|
||||
act(() => root!.unmount())
|
||||
root = undefined
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('consent log: on by default, fails soft without its table', () => {
|
||||
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
|
||||
const base = () => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config
|
||||
|
||||
test('no option → the collection and the endpoint; consentLog: false → neither', async () => {
|
||||
const on = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base())
|
||||
expect(on.collections!.map((c) => c.slug)).toContain('consent-records')
|
||||
expect(on.endpoints!.some((e) => e.path === '/ipal/consent' && e.method === 'post')).toBe(true)
|
||||
const off = await iapl({ access: { authCollection: 'users' }, consentLog: false, i18n, twoFactor: false })(base())
|
||||
expect(off.collections!.map((c) => c.slug)).not.toContain('consent-records')
|
||||
expect((off.endpoints ?? []).some((e) => e.path === '/ipal/consent')).toBe(false)
|
||||
})
|
||||
|
||||
test.each([
|
||||
['postgres', new Error('relation "consent_records" does not exist')],
|
||||
['postgres, schema', Object.assign(new Error('Failed query'), { cause: { message: 'relation "public.consent_records" does not exist' } })],
|
||||
['sqlite', new Error('SQLITE_ERROR: no such table: consent_records')],
|
||||
])('missing table (%s) is recognised', (_l, err) => expect(isMissingTableError(err)).toBe(true))
|
||||
|
||||
test('another error is not taken for a missing table', () => {
|
||||
expect(isMissingTableError(new Error('relation "users" does not exist'))).toBe(false)
|
||||
expect(isMissingTableError(new Error('connection refused'))).toBe(false)
|
||||
})
|
||||
|
||||
test('a missing table: 503, one log line for many requests, never a throw', async () => {
|
||||
const logger = { error: vi.fn() }
|
||||
const payload = { create: vi.fn(async () => { throw new Error('relation "consent_records" does not exist') }), db: { deleteMany: vi.fn(async () => {}) }, logger }
|
||||
const endpoint = buildConsentLogEndpoint()
|
||||
const body = { gpc: true, id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state: REJECT, version: 1 }
|
||||
const call = (ip: string) =>
|
||||
(endpoint.handler as (r: PayloadRequest) => Promise<Response>)(
|
||||
Object.assign(new Request('http://acme.pl/api/ipal/consent', { body: JSON.stringify(body), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' }), { payload }) as unknown as PayloadRequest,
|
||||
)
|
||||
expect((await call('203.0.113.10')).status).toBe(503)
|
||||
expect((await call('203.0.113.11')).status).toBe(503)
|
||||
const lines = logger.error.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('consent-records table does not exist'))
|
||||
expect(lines.length).toBeLessThanOrEqual(1)
|
||||
expect(payload.create).toHaveBeenCalledTimes(2)
|
||||
// the body's gpc never reaches the record (the shape is unchanged)
|
||||
expect(Object.keys((payload.create.mock.calls[0] as unknown as [{ data: object }])[0].data).sort()).toEqual(['choices', 'consentId', 'version'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('doctor: consent rules', () => {
|
||||
const packageRoot = path.resolve(import.meta.dirname, '..')
|
||||
let dirs: string[] = []
|
||||
afterEach(() => {
|
||||
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
|
||||
dirs = []
|
||||
})
|
||||
const project = (files: Record<string, object | string>) => {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'iapl-consent-'))
|
||||
dirs.push(root)
|
||||
const all = {
|
||||
'node_modules/@intecion/ipal-kit/package.json': { name: '@intecion/ipal-kit', version: '1.17.0' },
|
||||
'package.json': { dependencies: { '@intecion/ipal-kit': '^1.17.0' }, name: 'acmepl-web' },
|
||||
...files,
|
||||
}
|
||||
for (const [rel, content] of Object.entries(all)) {
|
||||
const file = path.join(root, rel)
|
||||
mkdirSync(path.dirname(file), { recursive: true })
|
||||
writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content))
|
||||
}
|
||||
return root
|
||||
}
|
||||
const findings = async (files: Record<string, object | string>) =>
|
||||
(await runDoctor({ offline: true, only: ['consent'], packageRoot, root: project(files), today: '2026-11-26', writeSeen: false })).findings.map((f) => `${f.rule}:${f.severity}:${f.message.slice(0, 60)}`)
|
||||
const pg = { 'node_modules/@payloadcms/db-postgres/package.json': { name: '@payloadcms/db-postgres', version: '3.70.0' } }
|
||||
const config = (opts = '') => ({ 'src/payload.config.ts': `export default buildConfig({ plugins: [iapl({ i18n${opts} })] })` })
|
||||
|
||||
test('Postgres, consent log on, no migration creating consent_records → error; with one, or consentLog: false → nothing', async () => {
|
||||
expect(await findings({ ...pg, ...config(), 'src/migrations/20260101_init.ts': 'create table "users"' })).toEqual([expect.stringMatching(/^consent-log-migration:error/)])
|
||||
expect(await findings({ ...pg, ...config(), 'src/migrations/20261126_consent.ts': 'CREATE TABLE "consent_records"' })).toEqual([])
|
||||
expect(await findings({ ...pg, ...config(', consentLog: false'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
|
||||
expect(await findings({ ...config() })).toEqual([]) // MongoDB: no table, nothing to migrate
|
||||
})
|
||||
|
||||
test('the banner\'s defaults switched off are reported', async () => {
|
||||
const layout = `<SiteProviders shell={shell} gpc={false} cookieButton={false} banner={<CookieBanner equalChoice={false} order={['settings', 'accept']} />}>{children}</SiteProviders>`
|
||||
const out = await findings({ ...config(), 'src/app/(frontend)/[locale]/layout.tsx': layout })
|
||||
expect(out.map((f) => f.split(':').slice(0, 2).join(':')).sort()).toEqual(['consent-banner:warning', 'consent-banner:warning', 'consent-banner:warning', 'consent-banner:warning'])
|
||||
})
|
||||
|
||||
test('the defaults as shipped: nothing to report', async () => {
|
||||
expect(await findings({ ...config(), 'src/app/(frontend)/[locale]/layout.tsx': '<SiteProviders shell={shell}>{children}</SiteProviders>' })).toEqual([])
|
||||
})
|
||||
|
||||
test('a hand-wired ConsentProvider without logEndpoint while the log is on; the crawl judging another Consent Mode', async () => {
|
||||
const out = await findings({
|
||||
'src/app/(frontend)/[locale]/layout.tsx': '<ConsentProvider texts={t}><Analytics consentMode="basic" /></ConsentProvider>',
|
||||
'src/payload.config.ts': 'iapl({ cookieScanner: { crawl: true } })',
|
||||
})
|
||||
expect(out).toEqual([expect.stringMatching(/^consent-banner:warning:<ConsentProvider> without logEndpoint/), expect.stringMatching(/^consent-banner:warning:the layout runs Consent Mode 'basic'/)])
|
||||
})
|
||||
})
|
||||
|
||||
test('no console error in this file\'s renders', () => {
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -30,11 +30,11 @@ const REJECT: ConsentState = { analytics: false, functional: false, marketing: f
|
||||
const texts = { ...CONSENT_FALLBACK, version: 3 }
|
||||
const stored = (state: ConsentState, version = 3) => serializeConsent(state, version, 'id-1')
|
||||
|
||||
type TreeOptions = { analytics?: object; banner?: object; cookieValue?: null | string; logEndpoint?: string; nonce?: string; texts?: object }
|
||||
type TreeOptions = { analytics?: object; banner?: object; cookieValue?: null | string; gpc?: 'ask' | 'honour' | false; logEndpoint?: string; nonce?: string; texts?: object }
|
||||
const tree = (o: TreeOptions = {}) =>
|
||||
h(
|
||||
ConsentProvider,
|
||||
{ cookieValue: o.cookieValue, logEndpoint: o.logEndpoint, nonce: o.nonce, texts: o.texts ?? texts },
|
||||
{ cookieValue: o.cookieValue, gpc: o.gpc, logEndpoint: o.logEndpoint, nonce: o.nonce, texts: o.texts ?? texts },
|
||||
h('main', null, 'page'),
|
||||
h(CookieBanner, o.banner ?? {}),
|
||||
h(CookieButton),
|
||||
@@ -151,12 +151,18 @@ describe('server render', () => {
|
||||
['another policy version', stored(ACCEPT, 2)],
|
||||
['malformed', '%7Bnot-json'],
|
||||
['foreign content', encodeURIComponent('yes')],
|
||||
])('server-read cookie, %s: the banner is in the HTML, shown, without a script', (_label, cookieValue) => {
|
||||
])('server-read cookie, %s: the banner is in the HTML; Global Privacy Control is the browser\'s, so its script decides (gpc={false}: shown, no script)', (_label, cookieValue) => {
|
||||
// the server cannot know Global Privacy Control (a browser signal): with 'honour' the script decides that part
|
||||
const html = renderToString(tree({ cookieValue }))
|
||||
expect(html).toContain('data-ipal="banner"')
|
||||
expect(html).not.toMatch(/data-ipal="banner"[^>]*hidden/)
|
||||
expect(html).not.toContain('<script')
|
||||
expect(html).toMatch(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
|
||||
expect(html).toContain('data-ipal="banner-script"')
|
||||
expect(html).toContain('navigator.globalPrivacyControl===true')
|
||||
expect(html).not.toContain('data-ipal="cookie-button"')
|
||||
// the signal ignored: as before GPC, shown with no script
|
||||
const off = renderToString(tree({ cookieValue, gpc: false }))
|
||||
expect(off).toContain('data-ipal="banner"')
|
||||
expect(off).not.toMatch(/data-ipal="banner"[^>]*hidden/)
|
||||
expect(off).not.toContain('<script')
|
||||
})
|
||||
|
||||
test('firstPaint={false}: nothing in the HTML, as before 1.17.0', () => {
|
||||
@@ -177,7 +183,8 @@ describe('server render', () => {
|
||||
const decided = site({ consentCookie: stored(REJECT) })
|
||||
expect(decided).not.toContain('data-ipal="banner"')
|
||||
expect(decided).toContain('data-ipal="cookie-button"')
|
||||
expect(site({ consentCookie: null })).not.toMatch(/data-ipal="banner"[^>]*hidden/)
|
||||
expect(site({ consentCookie: null })).toContain('data-ipal="banner-script"')
|
||||
expect(site({ consentCookie: null, gpc: false })).not.toMatch(/data-ipal="banner"[^>]*hidden/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -383,8 +390,9 @@ describe('decisions, reopening and withdrawal work as before', () => {
|
||||
// the consent log: one POST per decision, the same body as before
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
const calls = fetchMock.mock.calls.map(([url, init]) => ({ ...(init as object), body: JSON.parse(init.body) as unknown, url }))
|
||||
expect(calls[0]).toEqual({ body: { id: first.id, state: REJECT, version: 3 }, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST', url: '/api/ipal/consent' })
|
||||
expect(calls[1].body).toEqual({ id: first.id, state: ACCEPT, version: 3 })
|
||||
// 1.17.0: `gpc` (the browser's Global Privacy Control at the time) joins the body; the record's shape is unchanged
|
||||
expect(calls[0]).toEqual({ body: { gpc: false, id: first.id, state: REJECT, version: 3 }, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST', url: '/api/ipal/consent' })
|
||||
expect(calls[1].body).toEqual({ gpc: false, id: first.id, state: ACCEPT, version: 3 })
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -445,7 +453,7 @@ describe('tags: nothing earlier than before', () => {
|
||||
test('no decision: showing the banner at first paint loads no tag; Consent Mode default is all denied', () => {
|
||||
load({ analytics: pixels })
|
||||
expect(injected).toEqual([])
|
||||
expect(layer()).toEqual([['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied', wait_for_update: 500 })]])
|
||||
expect(layer()).toEqual([['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'denied', wait_for_update: 500 })], ['set', 'ads_data_redaction', true]])
|
||||
expect((window as { fbq?: unknown }).fbq).toBeUndefined()
|
||||
})
|
||||
|
||||
@@ -460,8 +468,9 @@ describe('tags: nothing earlier than before', () => {
|
||||
click('accept')
|
||||
const entries = layer()
|
||||
expect((entries[0] as unknown[]).slice(0, 2)).toEqual(['consent', 'default'])
|
||||
expect((entries[1] as unknown[]).slice(0, 2)).toEqual(['consent', 'update'])
|
||||
expect(entries[2]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(entries[1]).toEqual(['set', 'ads_data_redaction', true])
|
||||
expect((entries[2] as unknown[]).slice(0, 2)).toEqual(['consent', 'update'])
|
||||
expect(entries[3]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(injected).toEqual(expect.arrayContaining(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST', 'https://connect.facebook.net/en_US/fbevents.js']))
|
||||
})
|
||||
|
||||
@@ -478,7 +487,8 @@ describe('tags: nothing earlier than before', () => {
|
||||
load({ analytics: { gtmContainerId: 'GTM-TEST', metaPixelId: '123' } })
|
||||
const entries = layer()
|
||||
expect(entries[0]).toEqual(['consent', 'default', expect.objectContaining({ analytics_storage: 'denied' })])
|
||||
expect(entries[1]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(entries[1]).toEqual(['set', 'ads_data_redaction', true])
|
||||
expect(entries[2]).toMatchObject({ event: 'gtm.js' })
|
||||
expect(injected).toEqual(['https://www.googletagmanager.com/gtm.js?id=GTM-TEST']) // no Meta Pixel without consent
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user