Cookie scanner, phase 1: declarations, database lookup, review list

ipalKit({ cookieScanner }) (opt-in) adds the cookie-review collection, a
"Scan cookies" box above its list and GET/POST /api/ipal/cookie-scan. A scan
lists the cookies of every integration the project switches on (consent,
admin login, locale, stats, GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok,
Turnstile), the project's own declarations, and extra names looked up in the
bundled Open Cookie Database, as drafts. Editors accept (→ Cookie Settings →
Cookies, every locale, only empty text filled), edit or reject. A rescan never
deletes, never changes status and never overwrites edited text.

Everything is overridable (access, collectionOverrides, integrations,
declarations, databaseCategories, labels, syncAccepted) and the building
blocks are exported. Admin labels in en + pl. Docs: cookie-scanner.md,
consent.md, AGENT.md, ipal-reference, ipal-consent-check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-27 14:55:20 +01:00
co-authored by Claude Opus 5.5
parent ab45cf48be
commit a0545b6716
26 changed files with 2168 additions and 7 deletions
+174
View File
@@ -0,0 +1,174 @@
/**
* Cookie scanner through a REAL Payload (SQLite in memory, two locales): scan →
* drafts → editor edits → rescan keeps the edits → accept → Cookie Settings.
*/
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js'
import { runCookieScan } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
const SLUG = 'cookie-review' as never
const plugin = { localeCount: 2, stats: true }
const declarations = [
{ name: 'yt-*', category: 'marketing' as const, purpose: { en: 'YouTube embed', pl: 'Film YouTube' }, retention: '6 months', setBeforeConsent: false, vendor: 'Google' },
]
type Entry = {
category?: string
id: number
key: string
listed?: boolean
name: string
purpose?: Record<string, string> | string
source: string
status: string
vendor?: string
}
let payload: Payload
const all = async () => (await payload.find({ collection: SLUG, depth: 0, limit: 100, locale: 'all' as never })).docs as unknown as Entry[]
const byName = async (name: string) => (await all()).find((e) => e.name === name)!
const cookieList = async (locale: string) =>
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as {
cookies?: { category: string; duration?: null | string; name: string; provider?: null | string; purpose?: null | string }[]
}).cookies ?? []
beforeAll(async () => {
const config = buildConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
cookieScanner: { declarations },
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
stats: true,
twoFactor: false,
}),
],
secret: 'cookie-scanner-test-secret',
telemetry: false,
})
payload = await getPayload({ config })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-ABC123DEF4' } as never })
// An editor's own row, already published before the first scan.
await payload.updateGlobal({
slug: 'cookie-settings' as never,
data: { cookies: [{ name: '_ga', category: 'analytics', provider: 'Google', purpose: 'Tekst redaktora' }] } as never,
locale: 'pl' as never,
})
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('cookie scanner against a real Payload', () => {
test('a scan writes drafts in every locale and publishes nothing', async () => {
const { enabled, summary } = await runCookieScan({ names: ['_hjSessionUser_42', 'mystery'], options: { declarations }, payload, plugin })
expect(enabled.map((i) => i.key)).toEqual(['consent', 'admin', 'locale', 'stats', 'ga4'])
expect(summary).toMatchObject({ unknown: 1, updated: 0 })
const entries = await all()
expect(entries.every((e) => e.status === 'draft')).toBe(true)
expect(entries.map((e) => e.name).sort()).toEqual(
['NEXT_LOCALE', '_ga', '_ga_*', '_hjSessionUser_*', 'cookie-consent', 'ipal_vid', 'mystery', 'payload-token', 'yt-*'].sort(),
)
expect((await byName('ipal_vid')).purpose).toMatchObject({ en: expect.stringContaining('Built-in statistics'), pl: expect.stringContaining('Wbudowane') })
expect(await byName('_ga')).toMatchObject({ listed: true, source: 'integration' })
expect(await byName('mystery')).toMatchObject({ source: 'unknown' })
expect((await cookieList('pl')).map((c) => c.name)).toEqual(['_ga']) // nothing published
})
test('a rescan keeps what an editor changed, adds nothing twice, deletes nothing', async () => {
const vid = await byName('ipal_vid')
await payload.update({ id: vid.id, collection: SLUG, data: { purpose: 'Mój opis', vendor: 'Nasza strona' } as never, locale: 'pl' as never })
const before = (await all()).length
const { summary } = await runCookieScan({ options: { declarations }, payload, plugin })
expect(summary.created).toBe(0)
const after = await byName('ipal_vid')
expect(after.purpose).toMatchObject({ en: expect.stringContaining('Built-in statistics'), pl: 'Mój opis' })
expect(after.vendor).toBe('Nasza strona')
expect((await all()).length).toBe(before) // names not passed again are kept
})
test('accepting adds the cookie to Cookie Settings in every locale', async () => {
const vid = await byName('ipal_vid')
const saved = (await payload.update({ id: vid.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never })) as unknown as Entry
expect(saved.purpose).toBe('Mój opis') // the editor's save still answers in their locale
const pl = (await cookieList('pl')).find((c) => c.name === 'ipal_vid')
const en = (await cookieList('en')).find((c) => c.name === 'ipal_vid')
expect(pl).toMatchObject({ category: 'analytics', duration: '6 mies.', provider: 'Nasza strona', purpose: 'Mój opis' })
expect(en?.purpose).toContain('Built-in statistics')
expect((await byName('ipal_vid')).listed).toBe(true)
})
test('accepting an existing row fills only empty text, never the editor’s', async () => {
const ga = await byName('_ga')
await payload.update({ id: ga.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never })
const pl = (await cookieList('pl')).filter((c) => c.name === '_ga')
expect(pl).toHaveLength(1)
expect(pl[0]).toMatchObject({ duration: '2 lata', provider: 'Google', purpose: 'Tekst redaktora' })
expect((await cookieList('en')).find((c) => c.name === '_ga')?.purpose).toContain('Google Analytics')
})
test('an entry without a category cannot be accepted', async () => {
const mystery = await byName('mystery')
await expect(
payload.update({ id: mystery.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never }),
).rejects.toThrow()
})
test('rejecting keeps the entry; a rescan never changes its status', async () => {
const yt = await byName('yt-*')
await payload.update({ id: yt.id, collection: SLUG, data: { status: 'rejected' } as never, locale: 'pl' as never })
await runCookieScan({ options: { declarations }, payload, plugin })
expect((await byName('yt-*')).status).toBe('rejected')
expect((await byName('ipal_vid')).status).toBe('accepted')
expect((await cookieList('pl')).some((c) => c.name === 'yt-*')).toBe(false)
})
test('the endpoint: editors scan, visitors and plain users get 403', async () => {
const [get, post] = buildCookieScanEndpoints({ declarations }, plugin)
const call = (endpoint: typeof get, user: unknown, body: unknown = {}) =>
endpoint.handler({ json: async () => body, payload, user } as never) as Promise<Response>
expect((await call(post, null)).status).toBe(403)
expect((await call(post, { collection: 'users', roles: ['user'] })).status).toBe(403)
const editor = { collection: 'users', roles: ['editor'] }
const listed = (await (await call(get, editor)).json()) as { integrations: { key: string }[] }
expect(listed.integrations.map((i) => i.key)).toContain('ga4')
const res = await call(post, editor, { names: ['_fbp'] })
expect(res.status).toBe(200)
expect(((await res.json()) as { summary: { created: number } }).summary.created).toBe(1)
expect(await byName('_fbp')).toMatchObject({ source: 'integration', status: 'draft' })
})
test('custom access option replaces the editor check', async () => {
const [, post] = buildCookieScanEndpoints({ access: () => false }, plugin)
const res = (await post.handler({ json: async () => ({}), payload, user: { collection: 'users', roles: ['admin'] } } as never))
expect(res.status).toBe(403)
})
})