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]>
174 lines
9.2 KiB
TypeScript
174 lines
9.2 KiB
TypeScript
/**
|
|
* 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 { iapl } 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: [
|
|
iapl({
|
|
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({ audience: 'all', 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)
|
|
// No crawl problem left; only the approval reminder remains (drafts from the first crawl wait).
|
|
expect(await CookieCrawlAlert({ approval: false, audience: 'all', payload })).toBeNull()
|
|
expect(await CookieCrawlAlert({ audience: 'all', crawl: false, payload })).not.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({ audience: 'all', payload })).not.toBeNull()
|
|
})
|
|
})
|