// @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 beforeEach(() => { clearCookies() resetConsentStore() localStorage.clear() sessionStorage.clear() setGpc(undefined) for (const key of ['dataLayer', 'fbq', '_fbq', 'clarity', 'ttq']) {delete (window as unknown as Record)[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('[data-ipal="banner"]') const button = () => container.querySelector('[data-ipal="cookie-button"]') const click = (name: string) => act(() => container.querySelector(`[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('[data-ipal="banner-script"]') const code = /]*data-ipal="banner-script"[^>]*>(?.*?)<\/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) : 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 = { addEventListener() {}, removeAttribute: (n: string) => void b.removed.push(n), removed: [] as string[], style: {} as Record } // 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({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', gpc: true, 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 = { id: 'a1b2c3d4e5f6a7b8c9d0e1f2', gpc: true, state: REJECT, version: 1 } const call = (ip: string) => (endpoint.handler as (r: PayloadRequest) => Promise)( 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('limits: body size and version', () => { let ipN = 30 const site = (policyVersion: (() => number) | number = 3) => ({ create: vi.fn(async ({ data }: { data: object }) => ({ id: 1, ...data })), db: { deleteMany: vi.fn(async () => {}) }, findGlobal: vi.fn(async () => ({ policyVersion: typeof policyVersion === 'function' ? policyVersion() : policyVersion })), logger: { error: vi.fn() }, }) const send = (payload: object, init: { body?: BodyInit; headers?: Record }) => (buildConsentLogEndpoint().handler as (r: PayloadRequest) => Promise)( Object.assign(new Request('http://acme.pl/api/ipal/consent', { duplex: 'half', method: 'POST', ...init, headers: { 'content-type': 'application/json', 'x-real-ip': `203.0.113.${ipN++}`, ...init.headers } } as RequestInit), { payload }) as unknown as PayloadRequest, ) const decision = (version: number, extra: object = {}) => JSON.stringify({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state: REJECT, version, ...extra }) test('a body over 4 KiB is refused with 413 and never parsed: by content-length, and by the stream without one', async () => { const payload = site() const parse = vi.spyOn(JSON, 'parse') const big = decision(1, { pad: 'x'.repeat(20 * 1024 * 1024) }) expect((await send(payload, { body: big })).status).toBe(413) // no length declared (a chunked stream): read only up to the cap let pulled = 0 const stream = new ReadableStream({ pull(controller) { pulled++ if (pulled > 10_000) {controller.close(); return} controller.enqueue(new Uint8Array(1024).fill(32)) }, }) expect((await send(payload, { body: stream })).status).toBe(413) expect(pulled).toBeLessThan(10) // a false, small content-length does not let a large body through expect((await send(payload, { body: big, headers: { 'content-length': '100' } })).status).toBe(413) expect(parse.mock.calls.filter(([text]) => typeof text === 'string' && text.length > 4096)).toEqual([]) expect(payload.create).not.toHaveBeenCalled() parse.mockRestore() }) test('a normal decision passes; just under the cap passes', async () => { const payload = site() expect((await send(payload, { body: decision(3) })).status).toBe(201) const near = decision(3, { pad: 'x'.repeat(4096 - decision(3, { pad: '' }).length) }) expect(near.length).toBe(4096) expect((await send(payload, { body: near })).status).toBe(201) }) test('version: from 1 to the policy version; above it 400; an editor\'s fresh raise is read again', async () => { let current = 3 const payload = site(() => current) expect((await send(payload, { body: decision(1) })).status).toBe(201) // a page rendered before a raise expect((await send(payload, { body: decision(3) })).status).toBe(201) expect((await send(payload, { body: decision(99) })).status).toBe(400) expect((await send(payload, { body: decision(0) })).status).toBe(400) current = 4 // the editor raises it; the cache still says 3 expect((await send(payload, { body: decision(4) })).status).toBe(201) expect((await send(payload, { body: decision(5) })).status).toBe(400) }) }) }) 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) => { 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': { name: 'acmepl-web', dependencies: { '@intecion/ipal-kit': '^1.17.0' } }, ...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) => (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 withPlugins({ plugins: [iapl({ i18n${opts} })] })` }) test('Postgres, consent log on, no migration creating consent_records → warning (every 1.17.0 consent check is); 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:warning/)]) 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 = `}>{children}` 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': '{children}' })).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': '', 'src/payload.config.ts': 'iapl({ cookieScanner: { crawl: true } })', }) expect(out).toEqual([expect.stringMatching(/^consent-banner:warning: 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() })