Every language filled (fillEmptyLocales, default on): text saved in one language goes to every language where the same field is still empty, never over a language's own text. Applies to the cookie list (purpose, duration) and the cookie review (purpose, duration). Scanner and approval writes give a language without its own text the default language's text. Building blocks: buildFillEmptyLocalesGlobalHook / CollectionHook, fillEmptyLocales, withFillLocales. One Cookies entry (cookieScanner.adminLayout, default combined): the Cookie banner global is now labelled Cookies and gets Review and approve (scan box and approval list inline) and Site check tabs, built from ui fields. Cookie review and Cookie check leave the navigation (admin.group false) but keep their pages, data and API. This is presentation only: no schema change and no migration, only generate:importmap. adminLayout separate keeps the old layout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
177 lines
8.4 KiB
TypeScript
177 lines
8.4 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 { 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' })
|
||
// 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)
|
||
})
|
||
})
|