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]>
178 lines
8.5 KiB
TypeScript
178 lines
8.5 KiB
TypeScript
/**
|
||
* 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 { iapl } 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: [
|
||
iapl({
|
||
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 })
|
||
// Site Settings allow the theme switch by default, so its localStorage key is declared too.
|
||
expect(enabled.map((i) => i.key)).toEqual(['consent', 'theme', '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', 'theme', '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' })
|
||
// The editor wrote Polish only; saving filled the empty English text from it (fillEmptyLocales) — the scan keeps it.
|
||
expect((await cookieList('en')).find((c) => c.name === '_ga')?.purpose).toBe('Tekst redaktora')
|
||
})
|
||
|
||
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)
|
||
})
|
||
})
|