Replaced by an explicit list of forms only (ten exported names, runtime env names, project file names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are not touched. package.json keeps the five old bin names beside the five new ones. The old names stop working in this commit and come back as aliases in the next; docs follow. Co-Authored-By: Claude Fable 5.2 <[email protected]>
214 lines
11 KiB
TypeScript
214 lines
11 KiB
TypeScript
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 { iapl } 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) =>
|
|
iapl({
|
|
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' }),
|
|
])
|
|
// No accept → cookie list hook; only the hook that fills empty locales (fillEmptyLocales).
|
|
expect(review?.hooks?.afterChange).toHaveLength(1)
|
|
expect(config.endpoints?.filter((e) => e.path === '/ipal/cookie-scan').map((e) => e.method).sort()).toEqual(['get', 'post'])
|
|
})
|
|
})
|