Merge claude/cookie-scanner-eef8a8: cookie scanner phases 1 and 2

cookieScanner option: cookie-review collection, Scan cookies (declarations +
bundled Open Cookie Database), opt-in browser crawl through
services/cookie-crawler with the cookie-crawl global and dashboard alert.

Overlap with claude/test-no-typegen, resolved here: one test-config fix.
- the six real-Payload tests keep buildTestConfig and drop the branch's
  duplicate typescript: { autoGenerate: false } lines;
- cookieScannerIntegration and cookieCrawlIntegration use buildTestConfig
  instead of buildConfig + their own flag (testConfig.test.ts guard passes).
This commit is contained in:
Radosław Smoliński
2026-10-27 15:26:44 +01:00
54 changed files with 6925 additions and 7 deletions
+171
View File
@@ -0,0 +1,171 @@
/**
* Phase 2 end to end: a REAL Payload (SQLite, pl + en) and a REAL Chromium crawl
* (services/cookie-crawler) of a small local test site. Only the HTTP hop
* between site and service is short-circuited (that hop: cookieCrawler.test.ts).
*/
import type { Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { chromium } from '@playwright/test'
import { createServer } from 'node:http'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { crawlSite } from '../services/cookie-crawler/crawl.mjs'
import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js'
import { buildCookieCrawlEndpoints } from '../src/modules/consent/scanner/crawl/endpoints.js'
import { COOKIE_SCAN_LABELS } from '../src/modules/consent/scanner/labels.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
type CrawlDoc = { status: string; summary: { pages: number; violations: number }; violations: { name: string }[] }
const TOKEN = 't'.repeat(32)
const editor = { collection: 'users', email: '[email protected]', roles: ['editor'] }
// The test site: `sid` (declared necessary) and `_fbp` + a tracker request before consent;
// `_ga` and a localStorage key only after "Accept all".
const PAGE = (body: string) => `<!doctype html><html><body>${body}</body></html>`
const site: Server = createServer((req, res) => {
if (req.url === '/sitemap.xml') {
res.writeHead(200, { 'Content-Type': 'application/xml' })
res.end(`<urlset><url><loc>${siteUrl}/about</loc></url></urlset>`)
return
}
res.writeHead(200, { 'Content-Type': 'text/html', 'Set-Cookie': 'sid=1; Path=/' })
res.end(
req.url === '/about'
? PAGE('<p>About</p>')
: PAGE(`<script>document.cookie='_fbp=fb.1; path=/'</script>
<img src="http://tracker.invalid/p.gif" alt="">
<button data-ipal="accept" onclick="document.cookie='_ga=GA1; path=/';localStorage.setItem('ipal-theme','dark')">Accept all</button>`),
)
})
let siteUrl = ''
let payload: Payload
const crawlOptions = () => ({ serviceUrl: 'http://crawler.test', siteUrl, token: TOKEN, trackerHosts: (d: string[]) => [...d, 'tracker.invalid'] })
const declarations = [{ name: 'sid', category: 'necessary' as const, purpose: 'Session', retention: 'Session', setBeforeConsent: true, vendor: 'This site' }]
beforeAll(async () => {
await new Promise<void>((r) => site.listen(0, '127.0.0.1', r))
siteUrl = `http://127.0.0.1:${(site.address() as AddressInfo).port}`
payload = await getPayload({
config: buildTestConfig({
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: { crawl: crawlOptions(), declarations },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
twoFactor: false,
}),
],
secret: 'cookie-crawl-test-secret',
telemetry: false,
}),
})
}, 60_000)
afterAll(async () => {
await payload?.destroy()
await new Promise<void>((r) => site.close(() => r()))
})
describe('cookie crawl — panel button → service → results', () => {
const started: Record<string, unknown>[] = []
const fetchImpl = vi.fn(async (_url: Request | string | URL, init?: RequestInit) => {
started.push(JSON.parse(init?.body as string))
return new Response('{}', { status: 202 })
}) as unknown as typeof fetch
const endpoints = () =>
buildCookieCrawlEndpoints({ fetchImpl, labels: COOKIE_SCAN_LABELS, options: { crawl: crawlOptions(), declarations }, plugin: { localeCount: 2, stats: false } })
const call = (i: number, { body = {}, token, user = null }: { body?: unknown; token?: string; user?: unknown } = {}) =>
endpoints()[i].handler({
headers: new Headers(token ? { authorization: `Bearer ${token}` } : {}),
json: async () => body,
payload,
user,
} as never) as Promise<Response>
const review = async (name: string, storage = 'cookie') =>
(await payload.find({ collection: 'cookie-review' as never, depth: 0, where: { key: { equals: `${storage}:${name}` } } })).docs[0] as unknown as Record<string, unknown>
test('visitors cannot start a crawl; an editor can; a second start while running is refused', async () => {
expect((await call(1)).status).toBe(403)
expect((await call(1, { user: { ...editor, roles: ['user'] } })).status).toBe(403)
expect((await call(1, { user: editor })).status).toBe(202)
expect(started[0]).toMatchObject({ callbackUrl: `${siteUrl}/api/ipal/cookie-crawl/results`, maxPages: 20, siteUrl })
expect((await call(1, { user: editor })).status).toBe(409)
const status = (await (await call(0, { user: editor })).json()) as Record<string, unknown>
expect(status).toMatchObject({ configured: true, status: 'running' })
})
test('results need the token and the running job id', async () => {
const jobId = started[0].jobId as string
expect((await call(2, { body: { jobId, observations: [], ok: true, pages: [], requests: [] } })).status).toBe(401)
expect((await call(2, { body: { jobId: 'a'.repeat(32), observations: [], ok: true, pages: [], requests: [] }, token: TOKEN })).status).toBe(409)
})
test('a real browser crawl lands as drafts with violations, a dashboard warning and an e-mail', async () => {
await payload.updateGlobal({ slug: 'cookie-crawl' as never, data: { notifyEmails: '[email protected]' } as never })
const sendEmail = vi.spyOn(payload, 'sendEmail').mockResolvedValue(undefined as never)
const result = await crawlSite({ chromium, maxPages: 5, siteUrl, waitMs: 300 })
expect(result.accepted).toBe(true)
expect(result.pages).toEqual(['/', '/about'])
const res = await call(2, { body: { ...result, jobId: started[0].jobId }, token: TOKEN })
expect(res.status).toBe(200)
expect(await review('sid')).toMatchObject({ seenBeforeConsent: true, status: 'draft', violation: false })
expect(await review('_fbp')).toMatchObject({ category: 'marketing', seenBeforeConsent: true, violation: true })
expect(await review('_ga')).toMatchObject({ seenBeforeConsent: false, status: 'draft', violation: false })
expect(await review('ipal-theme', 'localStorage')).toMatchObject({ source: 'unknown', status: 'draft' })
const crawl = (await payload.findGlobal({ slug: 'cookie-crawl' as never })) as unknown as CrawlDoc
expect(crawl.status).toBe('done')
expect(crawl.summary).toMatchObject({ pages: 2, violations: 2 })
expect(crawl.violations.map((v: { name: string }) => v.name).sort()).toEqual(['_fbp', 'tracker.invalid'])
expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({ subject: expect.stringContaining('2'), to: ['[email protected]'] }))
expect(await CookieCrawlAlert({ payload })).not.toBeNull()
sendEmail.mockRestore()
}, 60_000)
test('only the latest crawl counts: a clean crawl clears the flags; status and entries stay', async () => {
const fbp = await review('_fbp')
await payload.update({ id: fbp.id as number, collection: 'cookie-review' as never, data: { status: 'rejected' } as never })
const before = (await payload.count({ collection: 'cookie-review' as never })).totalDocs
expect((await call(1, { token: TOKEN })).status).toBe(202) // a scheduled task authenticates with the token
const jobId = started.at(-1)!.jobId
const clean = { accepted: true, jobId, observations: [{ name: 'sid', after: true, before: true, pages: ['/'], storage: 'cookie' }], ok: true, pages: ['/'], requests: [] }
expect((await call(2, { body: clean, token: TOKEN })).status).toBe(200)
expect(await review('_fbp')).toMatchObject({ seenBeforeConsent: false, status: 'rejected', violation: false })
expect((await payload.count({ collection: 'cookie-review' as never })).totalDocs).toBe(before)
const crawl = (await payload.findGlobal({ slug: 'cookie-crawl' as never })) as unknown as CrawlDoc
expect(crawl.summary.violations).toBe(0)
expect(await CookieCrawlAlert({ payload })).toBeNull()
})
test('a failed crawl is reported and the next one may start', async () => {
expect((await call(1, { user: editor })).status).toBe(202)
const jobId = started.at(-1)!.jobId
expect((await call(2, { body: { error: 'site down', jobId, ok: false }, token: TOKEN })).status).toBe(200)
const status = (await (await call(0, { user: editor })).json()) as Record<string, unknown>
expect(status).toMatchObject({ error: 'site down', status: 'failed' })
expect(await CookieCrawlAlert({ payload })).not.toBeNull()
})
})
+193
View File
@@ -0,0 +1,193 @@
import type { AddressInfo } from 'node:net'
/**
* The scanner service (services/cookie-crawler) without a browser, and the
* site side's pure pieces: wire format, violations, token check, config.
*/
import type { BasePayload } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { checkCrawlRequest, discoverPages, isFirstParty, mergeRuns, parseSites } from '../services/cookie-crawler/lib.mjs'
import { createCrawlerServer } from '../services/cookie-crawler/server.mjs'
import { resolveCrawlConfig } from '../src/modules/consent/scanner/crawl/config.js'
import { bearerMatches } from '../src/modules/consent/scanner/crawl/endpoints.js'
import { parseCrawlResult } from '../src/modules/consent/scanner/crawl/result.js'
import { findCrawlViolations } from '../src/modules/consent/scanner/crawl/violations.js'
const TOKEN = 'a'.repeat(32)
const JOB = 'f'.repeat(32)
const sites = parseSites(`acme.pl=${TOKEN}, shop.example.com=${'b'.repeat(32)},short.pl=123`)
describe('crawler service — request checks', () => {
test('sites: host=token pairs, www dropped, short tokens refused', () => {
expect(sites).toEqual([
{ host: 'acme.pl', token: TOKEN },
{ host: 'shop.example.com', token: 'b'.repeat(32) },
])
})
const body = { callbackUrl: 'https://www.acme.pl/api/ipal/cookie-crawl/results', jobId: JOB, siteUrl: 'https://www.acme.pl' }
const check = (b: object, authorization = `Bearer ${TOKEN}`, allowHttp = false) => checkCrawlRequest({ allowHttp, authorization, body: b, sites })
test('a listed site with its own token passes', () => {
expect(check(body)).toBeNull()
})
test('refuses other sites, other tokens, foreign callbacks, http, bad job ids', () => {
expect(check({ ...body, callbackUrl: 'https://evil.com/x', siteUrl: 'https://evil.com' })).toBe('site_not_allowed')
expect(check(body, `Bearer ${'b'.repeat(32)}`)).toBe('unauthorized') // shop's token cannot crawl acme
expect(check(body, '')).toBe('unauthorized')
expect(check({ ...body, callbackUrl: 'https://evil.com/collect' })).toBe('callback_not_on_site')
expect(check({ ...body, callbackUrl: 'http://acme.pl/x', siteUrl: 'http://acme.pl' })).toBe('https_only')
expect(check({ ...body, callbackUrl: 'http://acme.pl/x', siteUrl: 'http://acme.pl' }, `Bearer ${TOKEN}`, true)).toBeNull()
expect(check({ ...body, jobId: '../etc' })).toBe('bad_job_id')
expect(check(null as never)).toBe('bad_request')
})
})
describe('crawler service — pages and runs', () => {
test('pages from the sitemap index: same origin only, capped', async () => {
const files: Record<string, string> = {
'https://acme.pl/sitemap.xml': '<sitemapindex><sitemap><loc>https://acme.pl/sitemap-pages.xml</loc></sitemap></sitemapindex>',
'https://acme.pl/sitemap-pages.xml': '<urlset><url><loc>https://acme.pl/pl</loc></url><url><loc>https://evil.com/x</loc></url><url><loc>https://acme.pl/en</loc></url><url><loc>https://acme.pl/de</loc></url></urlset>',
}
const fakeFetch = vi.fn(async (url: string) => new Response(files[url] ?? '', { status: files[url] ? 200 : 404 }))
expect(await discoverPages('https://acme.pl/', 2, fakeFetch as unknown as typeof fetch)).toEqual(['https://acme.pl/', 'https://acme.pl/pl', 'https://acme.pl/en'])
const offline = vi.fn(async () => { throw new Error('down') })
expect(await discoverPages('https://acme.pl/', 5, offline as unknown as typeof fetch)).toEqual(['https://acme.pl/'])
})
test('first party includes subdomains', () => {
expect(isFirstParty('www.acme.pl', 'acme.pl')).toBe(true)
expect(isFirstParty('cdn.acme.pl', 'acme.pl')).toBe(true)
expect(isFirstParty('notacme.pl', 'acme.pl')).toBe(false)
})
test('two runs merge into before/after flags with the first pages', () => {
const { observations, requests } = mergeRuns(
{ cookies: [{ name: 'sid', domain: '.acme.pl', page: '/' }], requests: [{ host: 'connect.facebook.net', page: '/' }], storage: [] },
{
cookies: [{ name: 'sid', domain: 'acme.pl', page: '/' }, { name: '_ga', domain: '.acme.pl', page: '/' }, { name: '_ga', domain: '.acme.pl', page: '/en' }],
requests: [],
storage: [{ name: 'ipal-theme', page: '/', storage: 'localStorage' }],
},
)
expect(observations).toEqual([
{ name: 'sid', after: true, before: true, domain: 'acme.pl', pages: ['/'], storage: 'cookie' },
{ name: '_ga', after: true, before: false, domain: 'acme.pl', pages: ['/', '/en'], storage: 'cookie' },
{ name: 'ipal-theme', after: true, before: false, pages: ['/'], storage: 'localStorage' },
])
expect(requests).toEqual([{ after: false, before: true, host: 'connect.facebook.net', pages: ['/'] }])
})
})
describe('crawler service — HTTP', () => {
let close: (() => Promise<void>) | undefined
afterEach(async () => {
await close?.()
close = undefined
})
async function start(crawl: (job: unknown) => Promise<unknown>, extra: Record<string, unknown> = {}) {
const delivered: { auth: null | string; body: Record<string, unknown>; url: string }[] = []
const fetchImpl = vi.fn(async (url: string, init: RequestInit) => {
delivered.push({ auth: new Headers(init.headers).get('authorization'), body: JSON.parse(init.body as string), url })
return new Response('{}', { status: 200 })
})
const server = createCrawlerServer({ allowHttp: true, crawl, deliveryDelays: [0], fetchImpl: fetchImpl as unknown as typeof fetch, log: () => {}, sites, ...extra }) as { whenIdle: () => Promise<void> } & ReturnType<typeof createCrawlerServer>
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
close = () => new Promise<void>((r) => server.close(() => r()))
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
const post = (body: unknown, token = TOKEN) =>
fetch(`${base}/crawl`, { body: JSON.stringify(body), headers: { Authorization: `Bearer ${token}` }, method: 'POST' })
return { base, delivered, post, server }
}
const job = { callbackUrl: 'https://acme.pl/api/ipal/cookie-crawl/results', jobId: JOB, siteUrl: 'https://acme.pl' }
test('202, crawl in the background, result posted back with the site token', async () => {
const crawl = vi.fn(async () => ({ accepted: true, observations: [], ok: true, pages: ['/'], requests: [] }))
const { base, delivered, post, server } = await start(crawl)
expect((await fetch(`${base}/health`)).status).toBe(200)
const res = await post(job)
expect(res.status).toBe(202)
await server.whenIdle()
expect(crawl).toHaveBeenCalledWith(expect.objectContaining({ maxPages: 20, siteUrl: 'https://acme.pl' }))
expect(delivered).toEqual([{ auth: `Bearer ${TOKEN}`, body: expect.objectContaining({ jobId: JOB, ok: true }), url: job.callbackUrl }])
})
test('401 for a wrong token, 404 elsewhere, a crash or timeout is reported as ok:false', async () => {
const { base, delivered, post, server } = await start(() => new Promise(() => {}), { jobTimeoutMs: 50 })
expect((await post(job, 'x'.repeat(32))).status).toBe(401)
expect((await fetch(`${base}/nope`)).status).toBe(404)
expect((await post(job)).status).toBe(202)
await server.whenIdle()
expect(delivered[0].body).toMatchObject({ error: expect.stringContaining('longer than 50 ms'), jobId: JOB, ok: false })
})
test('a full queue answers 429', async () => {
const { post } = await start(() => new Promise(() => {}), { jobTimeoutMs: 60_000, queueMax: 1 })
expect((await post(job)).status).toBe(202) // running
expect((await post(job)).status).toBe(202) // queued
expect((await post(job)).status).toBe(429)
})
})
describe('crawl — site side', () => {
test('the wire format is validated, junk dropped', () => {
expect(parseCrawlResult({ jobId: 'nope', ok: true })).toBeNull()
expect(parseCrawlResult({ error: 'boom', jobId: JOB, ok: false })).toEqual({ error: 'boom', jobId: JOB, ok: false })
const r = parseCrawlResult({
jobId: JOB,
observations: [
{ name: '_ga', after: true, before: true, domain: '.Acme.pl', pages: ['/'], storage: 'cookie' },
{ name: 'bad name', storage: 'cookie' },
{ name: 'x', storage: 'indexedDB' },
],
ok: true,
pages: ['/', 3],
requests: [{ before: true, host: 'connect.facebook.net' }, { host: 'not a host' }],
})
expect(r).toEqual({
accepted: true,
jobId: JOB,
observations: [{ name: '_ga', after: true, before: true, domain: 'acme.pl', pages: ['/'], storage: 'cookie' }],
ok: true,
pages: ['/'],
requests: [{ after: false, before: true, host: 'connect.facebook.net', pages: [] }],
})
})
test('violations: stored before consent and not necessary; tracker hosts; Google only in basic mode', () => {
const o = (name: string, before: boolean) => ({ name, after: true, before, pages: ['/'], storage: 'cookie' as const })
const categories: Record<string, null | string> = { _fbp: 'marketing', 'cookie-consent': 'necessary', mystery: null }
const args = {
categoryOf: (x: { name: string }) => categories[x.name],
observations: [o('cookie-consent', true), o('_fbp', true), o('mystery', true), o('_ga', false)],
requests: [
{ after: true, before: true, host: 'connect.facebook.net', pages: ['/'] },
{ after: true, before: true, host: 'www.googletagmanager.com', pages: ['/'] },
{ after: true, before: false, host: 'px.ads.linkedin.com', pages: ['/'] },
],
}
expect(findCrawlViolations(args).map((v) => v.name)).toEqual(['_fbp', 'mystery', 'connect.facebook.net'])
expect(findCrawlViolations({ ...args, consentMode: 'basic' }).map((v) => v.name)).toContain('www.googletagmanager.com')
expect(findCrawlViolations({ ...args, trackerHosts: [] }).map((v) => v.kind)).toEqual(['cookie', 'cookie'])
})
test('bearer token: constant-time match, nothing without a token', () => {
expect(bearerMatches(`Bearer ${TOKEN}`, TOKEN)).toBe(true)
expect(bearerMatches(`Bearer ${TOKEN}x`, TOKEN)).toBe(false)
expect(bearerMatches(TOKEN, TOKEN)).toBe(false)
expect(bearerMatches(`Bearer ${TOKEN}`, null)).toBe(false)
})
test('config: options, then env, then Payload serverURL; short tokens are not a token', () => {
const payload = { config: { serverURL: 'https://acme.pl/' } } as unknown as BasePayload
vi.stubEnv('IPAL_COOKIE_SCAN_URL', 'https://crawler.intecion.net/')
vi.stubEnv('IPAL_COOKIE_SCAN_TOKEN', 'short')
const c = resolveCrawlConfig({ maxPages: 500 }, payload)
expect(c).toMatchObject({ maxPages: 100, serviceUrl: 'https://crawler.intecion.net', siteUrl: 'https://acme.pl', token: null })
expect(resolveCrawlConfig({ token: TOKEN, trackerHosts: (d) => [...d, 'chat.example'] }, payload).trackerHosts).toContain('chat.example')
vi.unstubAllEnvs()
})
})
+212
View File
@@ -0,0 +1,212 @@
import type { BasePayload, Config } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import type { CookieScanContext } from '../src/modules/consent/scanner/types.js'
import { indexCookieDatabase, loadCookieDatabase, lookupCookie } from '../src/modules/consent/scanner/cookieDatabase.js'
import { OPEN_COOKIE_DATABASE_SOURCE } from '../src/modules/consent/scanner/data/openCookieDatabase.js'
import { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from '../src/modules/consent/scanner/integrations.js'
import { COOKIE_SCAN_LABELS, labelFor, labelRecord, mergeCookieScanLabels } from '../src/modules/consent/scanner/labels.js'
import { mergeCookieReview, suggestionFor, textFor } from '../src/modules/consent/scanner/merge.js'
import { collectCookieFindings, parseCookieNames } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
const ctx = (integrations: Record<string, unknown> = {}, plugin: Partial<CookieScanContext['plugin']> = {}): CookieScanContext => ({
integrations,
payload: {
config: { cookiePrefix: 'payload' },
findGlobal: vi.fn(async () => integrations),
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
} as unknown as BasePayload,
plugin: { localeCount: 1, stats: false, ...plugin },
})
describe('cookie scanner — names', () => {
test('a trailing * is a prefix, anything else exact', () => {
expect(cookieNameMatches('_ga_*', '_ga_ABC123')).toBe(true)
expect(cookieNameMatches('_ga_*', '_ga')).toBe(false)
expect(cookieNameMatches('_ga', '_ga')).toBe(true)
expect(cookieNameMatches('_ga', '_gat')).toBe(false)
})
test('names from the panel: trimmed, unique, invalid dropped, capped', () => {
expect(parseCookieNames(' _ga \n\n_fbp\n_ga\nbad name\na;b\nx=y')).toEqual(['_ga', '_fbp'])
expect(parseCookieNames(['a', 1, null, 'b'])).toEqual(['a', 'b'])
expect(parseCookieNames(undefined)).toEqual([])
expect(parseCookieNames(Array.from({ length: 500 }, (_, i) => `c${i}`))).toHaveLength(200)
})
})
describe('cookie scanner — Open Cookie Database', () => {
test('the bundled copy names its source, license and commit', () => {
expect(OPEN_COOKIE_DATABASE_SOURCE.license).toBe('Apache-2.0')
expect(OPEN_COOKIE_DATABASE_SOURCE.commit).toMatch(/^[0-9a-f]{40}$/)
})
test('exact names, wildcard prefixes, third-party domains', async () => {
const db = await loadCookieDatabase()
expect(lookupCookie(db, '_ga')).toMatchObject({ name: '_ga', category: 'analytics', source: 'database', vendor: 'Google' })
const gac = lookupCookie(db, '_gac_UA-123')
expect(gac?.name).toBe('_gac_*') // one entry per pattern, not per site-specific suffix
expect(lookupCookie(db, '_fbp')).toMatchObject({ category: 'marketing', domain: 'facebook.com' })
expect(lookupCookie(db, 'no-such-cookie-xyz')).toBeNull()
})
test('categories map to consent categories, and the map is overridable', () => {
const db = indexCookieDatabase([
['sess', 'App', 'Functional', '', 'Session', 'session', 'Acme', 0],
['pref', 'App', 'Personalization', '', 'Prefs', '1 year', 'Acme', 0],
['pre_', 'App', 'Security', '', 'Guard', '1 day', 'Acme', 1],
['pre_long_', 'App', 'Marketing', '', 'Ads', '1 day', 'Acme', 1],
])
// Functional is never mapped to necessary by default — an unchecked lookup must not skip consent
expect(lookupCookie(db, 'sess')?.category).toBe('functional')
expect(lookupCookie(db, 'pref')?.category).toBe('functional')
expect(lookupCookie(db, 'sess', { Functional: 'necessary' })?.category).toBe('necessary')
// the longest prefix wins
expect(lookupCookie(db, 'pre_long_1')?.category).toBe('marketing')
expect(lookupCookie(db, 'pre_1')?.category).toBe('necessary')
})
})
describe('cookie scanner — findings', () => {
test('only integrations the project switches on', async () => {
const { enabled, findings } = await collectCookieFindings({ ctx: ctx({ ga4MeasurementId: 'G-ABC123DEF4' }), database: false })
expect(enabled.map((i) => i.key)).toEqual(['consent', 'admin', 'ga4'])
expect(findings.map((f) => f.name)).toEqual(['cookie-consent', 'payload-token', '_ga', '_ga_*'])
expect(findings.every((f) => f.source === 'integration')).toBe(true)
})
test('stats, languages, pixels and Turnstile follow the project config', async () => {
const on = await collectCookieFindings({
ctx: ctx(
{ clarityProjectId: 'abcdefghij', metaPixelId: '1234567890123456', turnstileSecretKey: 's', turnstileSiteKey: 'k' },
{ localeCount: 2, stats: true },
),
database: false,
})
const names = on.findings.map((f) => f.name)
for (const n of ['ipal_vid', 'NEXT_LOCALE', '_fbp', '_fbc', '_clck', 'cf_clearance']) {expect(names).toContain(n)}
expect(names).not.toContain('_ttp')
// an invalid ID counts as off
const bad = await collectCookieFindings({ ctx: ctx({ metaPixelId: 'nope' }), database: false })
expect(bad.findings.map((f) => f.name)).not.toContain('_fbp')
})
test('every built-in declaration has text in English and Polish and a sane category', () => {
for (const integration of DEFAULT_COOKIE_INTEGRATIONS) {
const list = typeof integration.declarations === 'function' ? integration.declarations(ctx()) : integration.declarations
for (const d of list) {
expect(typeof d.purpose === 'object' && d.purpose.en && d.purpose.pl, `${d.name} purpose`).toBeTruthy()
expect(typeof d.retention === 'object' && d.retention.en && d.retention.pl, `${d.name} retention`).toBeTruthy()
// only necessary cookies may be set before consent
if (d.setBeforeConsent) {expect(d.category, d.name).toBe('necessary')}
}
}
})
test('project declarations, then built-ins, then the database, then unknown', async () => {
const { findings } = await collectCookieFindings({
ctx: ctx(),
declarations: [{ name: 'yt-*', category: 'marketing', purpose: 'YouTube embed', retention: '6 months', setBeforeConsent: false, vendor: 'Google' }],
names: ['yt-player', '_fbp', '_hjSessionUser_123', 'totally_unknown', 'cookie-consent'],
})
const by = Object.fromEntries(findings.map((f) => [f.name, f]))
expect(by['yt-*'].source).toBe('project')
expect(by['yt-player']).toBeUndefined() // covered by the project's pattern
expect(by._fbp).toMatchObject({ source: 'integration', sourceDetail: 'Meta Pixel' }) // built-in text even with the pixel off
expect(by['_hjSessionUser_*']).toMatchObject({ category: 'functional', source: 'database' }) // filed as Functional upstream — asks for consent
expect(by.totally_unknown).toEqual({ name: 'totally_unknown', source: 'unknown', storage: 'cookie' })
expect(findings.filter((f) => f.name === 'cookie-consent')).toHaveLength(1)
})
test('a failing isEnabled counts as off and is logged', async () => {
const c = ctx()
const { enabled } = await collectCookieFindings({
ctx: c,
database: false,
integrations: [{ declarations: [], isEnabled: () => { throw new Error('boom') }, key: 'x', label: 'X' }],
})
expect(enabled).toEqual([])
expect(c.payload.logger.warn).toHaveBeenCalled()
})
})
describe('cookie scanner — merging a rescan', () => {
const next = suggestionFor(
{ name: '_ga', category: 'analytics', purpose: { en: 'New EN', pl: 'Nowy PL' }, retention: '2 years', source: 'integration', storage: 'cookie', vendor: 'Google' },
['pl', 'en'],
)
test('text per locale: own language, English, first', () => {
expect(textFor({ en: 'E', pl: 'P' }, 'pl')).toBe('P')
expect(textFor({ en: 'E', pl: 'P' }, 'de')).toBe('E')
expect(textFor({ fr: 'F' }, 'de')).toBe('F')
expect(textFor('same', 'pl')).toBe('same')
expect(next.retention).toEqual({ en: '2 years', pl: '2 years' })
})
test('empty and untouched values follow the scan', () => {
const previous = { category: 'analytics' as const, purpose: { en: 'Old EN', pl: 'Stary PL' }, vendor: 'Google' }
const { changed, values } = mergeCookieReview({ ...previous, retention: {} }, previous, next)
expect(changed).toBe(true)
expect(values.purpose).toEqual({ en: 'New EN', pl: 'Nowy PL' })
expect(values.retention).toEqual({ en: '2 years', pl: '2 years' })
})
test('text an editor changed is never overwritten — per locale and per field', () => {
const previous = { category: 'analytics' as const, purpose: { en: 'Old EN', pl: 'Stary PL' }, vendor: 'Google' }
const current = { category: 'marketing' as const, purpose: { en: 'Old EN', pl: 'Mój tekst' }, vendor: 'Google LLC' }
const { values } = mergeCookieReview(current, previous, next)
expect(values.purpose).toEqual({ en: 'New EN', pl: 'Mój tekst' })
expect(values.vendor).toBe('Google LLC')
expect(values.category).toBe('marketing')
})
test('same suggestion again → nothing changes', () => {
expect(mergeCookieReview(next, next, next).changed).toBe(false)
})
test('a missing suggestion never clears a value', () => {
const { changed, values } = mergeCookieReview({ vendor: 'Mine' }, undefined, {})
expect(changed).toBe(false)
expect(values.vendor).toBe('Mine')
})
})
describe('cookie scanner — labels and config', () => {
test('English and Polish for every label; projects add languages and change text', () => {
expect(Object.keys(COOKIE_SCAN_LABELS.pl).sort()).toEqual(Object.keys(COOKIE_SCAN_LABELS.en).sort())
const labels = mergeCookieScanLabels({ de: { scanButton: 'Cookies scannen' }, pl: { scanButton: 'Skanuj' } })
expect(labelRecord(labels, 'scanButton')).toEqual({ de: 'Cookies scannen', en: 'Scan cookies', pl: 'Skanuj' })
expect(labels.de.status).toBe('Status') // missing keys fall back to English
expect(labelFor(labels, 'fr', 'scanButton')).toBe('Scan cookies')
})
const run = async (cookieScanner?: unknown) =>
ipalKit({
cookieScanner: cookieScanner as never,
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
})({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
test('off by default: no collection, no endpoint', async () => {
const config = await run()
expect(config.collections?.some((c) => c.slug === 'cookie-review')).toBe(false)
expect(config.endpoints?.some((e) => e.path === '/ipal/cookie-scan')).toBe(false)
})
test('on: collection with the scan button, GET + POST endpoint; overrides win', async () => {
const config = await run({ collectionOverrides: { admin: { group: 'Privacy' } }, syncAccepted: false })
const review = config.collections?.find((c) => c.slug === 'cookie-review')
expect(review?.admin?.group).toBe('Privacy')
expect(review?.admin?.components?.beforeListTable).toEqual([
expect.objectContaining({ path: '@intecion/ipal-kit/admin#CookieScanButton' }),
])
expect(review?.hooks?.afterChange).toEqual([])
expect(config.endpoints?.filter((e) => e.path === '/ipal/cookie-scan').map((e) => e.method).sort()).toEqual(['get', 'post'])
})
})
+175
View File
@@ -0,0 +1,175 @@
/**
* 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 { 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'
import { buildTestConfig } from './helpers.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 = buildTestConfig({
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)
})
})
+3
View File
@@ -236,6 +236,9 @@ describe('agent guide covers the whole plugin', () => {
...typeKeys('src/modules/access/types.ts', 'AccessOption'),
...typeKeys('src/modules/content/types.ts', 'ContentCollectionOption'),
...typeKeys('src/modules/content/types.ts', 'ContentOption'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieScannerOptions'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieCrawlOptions'),
...typeKeys('src/modules/env/ipalEnvRules.ts', 'IpalEnvFeatures'),
...typeKeys('src/modules/forms/types.ts', 'FormsOption'),
...typeKeys('src/modules/i18n/types.ts', 'I18nConfig'),
...typeKeys('src/modules/i18n/types.ts', 'LocaleDefinition'),