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]>
207 lines
12 KiB
TypeScript
207 lines
12 KiB
TypeScript
/**
|
|
* One approval for everything a scan found, through a REAL Payload (SQLite,
|
|
* pl + en): scan → approval list → "Approve and add" → Cookie banner → Cookies,
|
|
* the cookie policy table and the banner's detailed window.
|
|
*/
|
|
import type { Config, 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 type { I18nConfig } from '../src/modules/i18n/types.js'
|
|
|
|
import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConsentTexts.js'
|
|
import { approveCookies, buildCookieApprovalEndpoints, loadCookieApproval } from '../src/modules/consent/scanner/approval.js'
|
|
import { nextChange, runCookieScan } from '../src/modules/consent/scanner/scan.js'
|
|
import { sameCookie } from '../src/modules/consent/scanner/sync.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 i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
|
|
const youtube = (purpose = { en: 'YouTube embed', pl: 'Film YouTube' }) => ({
|
|
name: 'yt-*',
|
|
category: 'marketing' as const,
|
|
purpose,
|
|
retention: { en: '6 months', pl: '6 mies.' },
|
|
setBeforeConsent: false,
|
|
vendor: 'Google',
|
|
})
|
|
|
|
type Row = { category: string; duration?: null | string; name: string; provider?: null | string; purpose?: null | string }
|
|
type Entry = { category?: null | string; change?: null | string; id: number; name: string; needsDescription?: boolean; status: string }
|
|
|
|
let payload: Payload
|
|
const list = async (locale: string) =>
|
|
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as { cookies?: Row[] }).cookies ?? []
|
|
const entry = async (name: string) =>
|
|
(await payload.find({ collection: SLUG, depth: 0, where: { name: { equals: name } } })).docs[0] as unknown as Entry
|
|
|
|
beforeAll(async () => {
|
|
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: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n, stats: true, twoFactor: false })],
|
|
secret: 'cookie-approval-test-secret',
|
|
telemetry: false,
|
|
}),
|
|
})
|
|
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-ABC123DEF4' } as never })
|
|
// A row an editor wrote by hand, before any scan: a concrete name the scan knows as `_ga_*`.
|
|
await payload.updateGlobal({
|
|
slug: 'cookie-settings' as never,
|
|
data: { cookies: [{ name: '_ga_XYZ123', category: 'analytics', provider: 'Google', purpose: 'Tekst redaktora' }] } as never,
|
|
locale: 'pl' as never,
|
|
})
|
|
}, 60_000)
|
|
|
|
afterAll(async () => {
|
|
await payload?.destroy()
|
|
})
|
|
|
|
describe('cookie approval — pure rules', () => {
|
|
test('markers: new, changed, found again, rejected left alone', () => {
|
|
expect(nextChange(undefined, true)).toBe('new')
|
|
expect(nextChange({ change: null, status: 'accepted' }, true)).toBe('changed')
|
|
expect(nextChange({ change: 'new', status: 'draft' }, true)).toBe('new')
|
|
expect(nextChange({ change: 'gone', status: 'accepted' }, false)).toBeNull()
|
|
expect(nextChange({ change: null, status: 'accepted' }, false)).toBeNull()
|
|
expect(nextChange({ change: null, status: 'rejected' }, true)).toBeNull()
|
|
})
|
|
|
|
test('the same cookie: equal names or a pattern covering the other', () => {
|
|
expect(sameCookie('_ga_*', '_ga_XYZ123')).toBe(true)
|
|
expect(sameCookie('_ga_XYZ123', '_ga_*')).toBe(true)
|
|
expect(sameCookie('_ga', '_ga_XYZ123')).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('cookie approval against a real Payload', () => {
|
|
test('a scan adds nothing to the cookie banner; the approval list groups what it found', async () => {
|
|
await runCookieScan({ names: ['mystery_cookie'], options: { declarations: [youtube()] }, payload, plugin })
|
|
expect((await list('pl')).map((r) => r.name)).toEqual(['_ga_XYZ123']) // nothing added before approval
|
|
|
|
const { gone, pending } = await loadCookieApproval({ locale: 'en', payload })
|
|
expect(gone).toEqual([])
|
|
const names = pending.map((p) => p.name)
|
|
for (const n of ['_ga', '_ga_*', 'cookie-consent', 'ipal_vid', 'NEXT_LOCALE', 'yt-*', 'mystery_cookie']) {expect(names).toContain(n)}
|
|
expect(pending.find((p) => p.name === 'ipal_vid')).toMatchObject({ category: 'analytics', change: 'new', purpose: expect.stringContaining('Built-in statistics'), unknown: false })
|
|
expect(pending.find((p) => p.name === 'mystery_cookie')).toMatchObject({ category: null, unknown: true })
|
|
// In Polish when the admin reads Polish.
|
|
const pl = await loadCookieApproval({ locale: 'pl', payload })
|
|
expect(pl.pending.find((p) => p.name === 'ipal_vid')?.purpose).toContain('Wbudowane statystyki')
|
|
})
|
|
|
|
test('approving adds the ticked cookies everywhere they are listed — once, without touching editor text', async () => {
|
|
const yt = await entry('yt-*')
|
|
const ids = (await loadCookieApproval({ locale: 'pl', payload })).pending.filter((p) => p.id !== yt.id).map((p) => p.id)
|
|
const result = await approveCookies({ ids, payload })
|
|
expect(result).toMatchObject({ filled: 1, needsDescription: 1 })
|
|
|
|
const pl = await list('pl')
|
|
const en = await list('en')
|
|
// Cookie banner → Cookies, in every locale, with the plugin's texts.
|
|
expect(pl.find((r) => r.name === 'ipal_vid')).toMatchObject({ category: 'analytics', duration: '6 mies.', purpose: expect.stringContaining('Wbudowane') })
|
|
expect(en.find((r) => r.name === 'ipal_vid')?.purpose).toContain('Built-in statistics')
|
|
// `_ga_*` is the editor's `_ga_XYZ123`: no second row, their text and category kept, only empty text filled.
|
|
expect(pl.filter((r) => sameCookie(r.name, '_ga_*'))).toHaveLength(1)
|
|
expect(pl.find((r) => r.name === '_ga_XYZ123')).toMatchObject({ category: 'analytics', duration: '2 lata', purpose: 'Tekst redaktora' })
|
|
// Unknown: a category that needs consent, flagged "needs description".
|
|
expect(pl.find((r) => r.name === 'mystery_cookie')?.category).toBe('marketing')
|
|
expect(await entry('mystery_cookie')).toMatchObject({ category: 'marketing', change: null, needsDescription: true, status: 'accepted' })
|
|
// Unticked: still waiting, not in the list.
|
|
expect(await entry('yt-*')).toMatchObject({ status: 'draft' })
|
|
expect(pl.some((r) => r.name === 'yt-*')).toBe(false)
|
|
|
|
// The cookie policy table and the banner's detailed window read the same list.
|
|
expect((await getCookieTable({ locale: 'en', payload })).map((r) => r.name)).toContain('ipal_vid')
|
|
const texts = await getConsentTexts({ config: i18n, locale: 'pl', payload, privacyPolicy: false })
|
|
expect(texts.cookies?.map((r) => r.name)).toContain('ipal_vid')
|
|
})
|
|
|
|
test('writing a purpose clears "needs description"', async () => {
|
|
const mystery = await entry('mystery_cookie')
|
|
await payload.update({ id: mystery.id, collection: SLUG, data: { purpose: 'Czat na stronie' } as never, locale: 'pl' as never })
|
|
expect((await entry('mystery_cookie')).needsDescription).toBe(false)
|
|
})
|
|
|
|
test('a changed suggestion asks again; approving never overwrites the cookie banner text', async () => {
|
|
await approveCookies({ payload }) // yt-* too
|
|
const before = (await list('pl')).find((r) => r.name === 'yt-*')!
|
|
await runCookieScan({ options: { declarations: [youtube({ en: 'YouTube player', pl: 'Odtwarzacz YouTube' })] }, payload, plugin })
|
|
const { pending } = await loadCookieApproval({ locale: 'pl', payload })
|
|
expect(pending.map((p) => [p.name, p.change])).toEqual([['yt-*', 'changed']])
|
|
await approveCookies({ payload })
|
|
expect((await list('pl')).find((r) => r.name === 'yt-*')?.purpose).toBe(before.purpose)
|
|
expect((await loadCookieApproval({ locale: 'pl', payload })).pending).toEqual([])
|
|
})
|
|
|
|
test('a cookie no longer found is only flagged: nothing is deleted', async () => {
|
|
const rows = (await list('pl')).length
|
|
const entries = (await payload.count({ collection: SLUG })).totalDocs
|
|
const { summary } = await runCookieScan({ options: { declarations: [] }, payload, plugin })
|
|
expect(summary.gone).toBe(1)
|
|
const { gone, pending } = await loadCookieApproval({ locale: 'pl', payload })
|
|
expect(gone.map((g) => g.name)).toEqual(['yt-*'])
|
|
expect(pending).toEqual([])
|
|
expect((await list('pl')).length).toBe(rows)
|
|
expect((await payload.count({ collection: SLUG })).totalDocs).toBe(entries)
|
|
// Found again → the flag goes away.
|
|
await runCookieScan({ options: { declarations: [youtube({ en: 'YouTube player', pl: 'Odtwarzacz YouTube' })] }, payload, plugin })
|
|
expect((await entry('yt-*')).change).toBeNull()
|
|
})
|
|
|
|
test('the endpoint: editors only; approves what it is given', async () => {
|
|
const [get, post] = buildCookieApprovalEndpoints({})
|
|
const call = (e: typeof get, user: unknown, body: unknown = {}) =>
|
|
e.handler({ json: async () => body, payload, query: { locale: 'en' }, user } as never) as Promise<Response>
|
|
expect((await call(get, null)).status).toBe(403)
|
|
expect((await call(post, { collection: 'users', roles: ['user'] })).status).toBe(403)
|
|
await runCookieScan({ names: ['late_cookie'], payload, plugin })
|
|
const editor = { collection: 'users', roles: ['editor'] }
|
|
const listed = (await (await call(get, editor)).json()) as { pending: { id: number; name: string }[] }
|
|
expect(listed.pending.map((p) => p.name)).toEqual(['late_cookie'])
|
|
const res = (await (await call(post, editor, { ids: [listed.pending[0].id] })).json()) as { result: { added: number } }
|
|
expect(res.result.added).toBe(1)
|
|
})
|
|
})
|
|
|
|
describe('cookie approval — optional', () => {
|
|
const config = (cookieScanner: unknown) =>
|
|
iapl({ cookieScanner: cookieScanner as never, i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
|
|
|
|
test('on by default: the view, its endpoint and the dashboard reminder', async () => {
|
|
const c = await config(true)
|
|
expect(c.admin?.components?.views?.ipalCookieApproval).toMatchObject({ path: '/cookie-approval' })
|
|
expect(c.endpoints?.some((e) => e.path === '/ipal/cookie-approval')).toBe(true)
|
|
expect(c.admin?.components?.beforeDashboard).toEqual(
|
|
expect.arrayContaining([expect.objectContaining({ path: '@intecion/ipal-kit/admin#CookieCrawlAlert' })]),
|
|
)
|
|
})
|
|
|
|
test('approval: false keeps per-entry review only', async () => {
|
|
const c = await config({ approval: false })
|
|
expect(c.admin?.components?.views?.ipalCookieApproval).toBeUndefined()
|
|
expect(c.endpoints?.some((e) => e.path === '/ipal/cookie-approval')).toBe(false)
|
|
expect((c.admin?.components?.beforeDashboard ?? []).some((x) => JSON.stringify(x).includes('CookieCrawlAlert'))).toBe(false)
|
|
})
|
|
|
|
test('own category for unknown cookies; no dashboard reminder', async () => {
|
|
const c = await config({ approval: { dashboard: false, unknownCategory: 'analytics' } })
|
|
expect(JSON.stringify(c.admin?.components?.views?.ipalCookieApproval)).toContain('"unknownCategory":"analytics"')
|
|
expect((c.admin?.components?.beforeDashboard ?? []).some((x) => JSON.stringify(x).includes('CookieCrawlAlert'))).toBe(false)
|
|
})
|
|
})
|