Files
ipal-kit/test/seed.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 4bb9c663fd Cookie scanner, phase 2: browser crawl through a shared scanner service
cookieScanner.crawl (opt-in) adds "Crawl site" to the Cookie review box. The
site asks the shared scanner service (services/cookie-crawler: Node +
Playwright, Dockerfile, deployed once on Coolify) to crawl its sitemap pages
twice, with no consent and after "Accept all". The service posts cookies,
storage keys and third-party hosts back to POST /api/ipal/cookie-crawl/results
(bearer token, running job only). No browser in the site.

Findings land as drafts through the same merge rules. Anything stored before
consent that is not necessary, and tracker requests before consent, are
violations, flagged on the review entries from the latest crawl only. The
cookie-crawl global keeps the latest result (no history). A dashboard warning
(CookieCrawlAlert) and an opt-in e-mail through the project's mail adapter
follow a crawl with violations or new unknown cookies. Scheduled crawls: a
Coolify scheduled task with the token. ipalEnvRules({ cookieCrawl: true }).

Also: the six older real-Payload tests no longer leave an orphaned
payload generate:types process (typescript.autoGenerate: false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:14:01 +01:00

293 lines
14 KiB
TypeScript

import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { createSeeder, editedSinceSeed, isLocalDatabase, seedHash } from '../src/exports/seed.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
const flush = () => new Promise((r) => setTimeout(r, 0))
describe('isLocalDatabase', () => {
test.each([
['file:./dev.db', true],
['file::memory:', true],
['./payload.sqlite', true],
['postgres://u:p@localhost:5432/app', true],
['postgres://u:[email protected]/app', true],
['postgres://u:p@[::1]:5432/app', true],
['postgres:///app', true],
['postgres://u:p@x/app?host=/var/run/postgresql', true],
['postgres://u:p@db:5432/app', false],
['mongodb+srv://u:[email protected]/app', false],
['mongodb://a:1,b:2/app', false],
['', false],
[undefined, false],
])('%s → %s', (url, local) => {
expect(isLocalDatabase(url, { localHosts: [] })).toBe(local)
})
test('extra local hosts (option or SEED_LOCAL_HOSTS)', () => {
expect(isLocalDatabase('postgres://u:p@db:5432/app', { localHosts: ['db'] })).toBe(true)
vi.stubEnv('SEED_LOCAL_HOSTS', 'db, postgres')
expect(isLocalDatabase('postgres://u:p@postgres:5432/app')).toBe(true)
vi.unstubAllEnvs()
})
})
describe('editedSinceSeed / seedHash', () => {
const at = (s: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, s)).toISOString()
test('timestamps: inside the window = untouched, later = edited', () => {
expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(5) }, hashField: false })).toBeNull()
expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(500) }, hashField: false })).toMatch(/updated 500s after creation/)
expect(editedSinceSeed({ doc: { createdAt: at(0), updatedAt: at(500) }, hashField: false, untouchedSeconds: 600 })).toBeNull()
expect(editedSinceSeed({ doc: {}, hashField: false })).toBe('no createdAt/updatedAt')
})
test('a stored hash decides over timestamps', () => {
const doc = { createdAt: at(0), seedHash: seedHash({ a: 1 }), updatedAt: at(9000) }
expect(editedSinceSeed({ currentHash: seedHash({ a: 1 }), doc })).toBeNull()
expect(editedSinceSeed({ currentHash: seedHash({ a: 2 }), doc })).toBe('seedHash differs')
})
test('seedHash ignores key order, row ids and nulls', () => {
// eslint-disable-next-line perfectionist/sort-objects -- key order is what this checks
expect(seedHash({ a: 1, b: [{ id: 'x', t: 'q' }], c: null })).toBe(seedHash({ b: [{ t: 'q' }], a: 1 }))
expect(seedHash({ a: 1 })).not.toBe(seedHash({ a: 2 }))
})
})
/** createSeeder against a real (SQLite) Payload with pl/en and localization.fallback on. */
describe('createSeeder', () => {
let payload: Payload
const lines: string[] = []
const log = (line: string) => {
lines.push(line)
}
const seeder = (opts: Parameters<typeof createSeeder>[1] = {}) => createSeeder(payload, { dryRun: false, log, update: false, ...opts })
beforeAll(async () => {
vi.stubEnv('DATABASE_URI', 'file::memory:')
const config = buildConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{
name: 'rows',
type: 'array',
fields: [
{ name: 'text', type: 'text', localized: true },
{ name: 'page', type: 'relationship', relationTo: 'pages' },
],
},
],
versions: { drafts: true },
},
{
slug: 'posts',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', localized: true },
{ name: 'seedHash', type: 'text', admin: { hidden: true } },
],
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
globals: [
{
slug: 'header',
fields: [
{ name: 'tagline', type: 'text', localized: true },
{ name: 'phone', type: 'text' },
{ name: 'links', type: 'array', fields: [{ name: 'label', type: 'text', localized: true }] },
],
},
],
localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] },
plugins: [ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'seed-test-secret',
telemetry: false,
typescript: { autoGenerate: false }, // no orphaned `payload generate:types` child
})
payload = await getPayload({ config })
}, 60_000)
afterEach(() => {
lines.length = 0
vi.restoreAllMocks()
vi.unstubAllEnvs()
vi.stubEnv('DATABASE_URI', 'file::memory:')
})
afterAll(async () => {
vi.unstubAllEnvs()
await payload?.destroy()
})
const readPage = (id: number | string, locale: 'en' | 'pl') =>
payload.findByID({ id, collection: 'pages', depth: 0, draft: true, fallbackLocale: false as never, locale })
test('creates missing pages in every locale, resolves $page links, keeps row ids, then skips', async () => {
const PAGES = [
{
slug: { en: 'home', pl: 'start' },
rows: [{ page: { $page: 'kontakt' }, text: { en: 'Write to us', pl: 'Napisz do nas' } }, { text: { en: 'Second', pl: 'Drugi' } }],
title: { en: 'Home', pl: 'Strona główna' },
},
{ slug: { en: 'contact', pl: 'kontakt' }, title: { en: 'Contact', pl: 'Kontakt' } },
]
const seed = seeder()
const results = await seed.upsertBySlug('pages', PAGES)
expect(results.map((r) => r.status)).toEqual(['create', 'create'])
const [home, contact] = results
const pl = await readPage(home.id!, 'pl')
const en = await readPage(home.id!, 'en')
expect(pl.title).toBe('Strona główna')
expect(en.title).toBe('Home')
expect(en.slug).toBe('home')
expect((pl.rows as { id: string }[]).map((r) => r.id)).toEqual((en.rows as { id: string }[]).map((r) => r.id))
expect((pl.rows as { text: string }[])[0].text).toBe('Napisz do nas')
expect((en.rows as { page: unknown; text: string }[])[0]).toMatchObject({ page: contact.id, text: 'Write to us' })
const again = seeder()
expect((await again.upsertBySlug('pages', PAGES)).map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)'])
expect(again.summary()).toEqual({ created: 0, errors: 0, skipped: 2, skippedEdited: 0, updated: 0 })
expect(lines.join('\n')).toMatch(/skip \(exists\)\s+pages "start"/)
})
test('fallbackLocale: false — a locale missing from the seed is not filled with the default text', async () => {
const r = await seeder().upsertBySlug('pages', { slug: { pl: 'tylko-pl' }, title: { pl: 'Tylko po polsku' } })
const en = await readPage(r.id!, 'en')
expect(en.title ?? null).toBeNull()
})
test('dry run writes nothing and reports the plan', async () => {
const seed = seeder({ dryRun: true })
const r = await seed.upsertBySlug('pages', { slug: { pl: 'nowa' }, rows: [{ page: { $page: 'nowa' } }], title: { pl: 'Nowa' } })
expect(r.status).toBe('create')
expect((await payload.find({ collection: 'pages', where: { slug: { equals: 'nowa' } } })).totalDocs).toBe(0)
expect(seed.summary().created).toBe(1)
expect(lines.join('\n')).toMatch(/DRY RUN/)
})
test('update: untouched records are updated, records edited since seeding are skipped', async () => {
const first = await seeder().upsertBySlug('pages', { slug: { pl: 'oferta' }, title: { en: 'Offer', pl: 'Oferta' } })
const edited = await seeder().upsertBySlug('pages', { slug: { pl: 'o-nas' }, title: { pl: 'O nas' } })
// An editor saves "o-nas" 10 minutes after it was created.
vi.useFakeTimers({ now: Date.now() + 600_000, toFake: ['Date'] })
await payload.update({ id: edited.id!, collection: 'pages', data: { title: 'O nas — poprawione' }, locale: 'pl' })
vi.useRealTimers()
const seed = seeder({ update: true })
const up = await seed.upsertBySlug('pages', [
{ slug: { pl: 'oferta' }, title: { en: 'Our offer', pl: 'Nasza oferta' } },
{ slug: { pl: 'o-nas' }, title: { pl: 'O nas (seed)' } },
])
expect(up.map((r) => r.status)).toEqual(['update', 'skip (edited)'])
expect(up[1].note).toMatch(/after creation/)
expect((await readPage(first.id!, 'en')).title).toBe('Our offer')
expect((await readPage(edited.id!, 'pl')).title).toBe('O nas — poprawione')
expect(seed.summary()).toMatchObject({ skippedEdited: 1, updated: 1 })
})
test('hash field: repeated updates while untouched; an editor change is detected', async () => {
const created = await seeder().upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post', pl: 'Wpis' } })
vi.useFakeTimers({ now: Date.now() + 600_000, toFake: ['Date'] })
// Timestamps alone would call this edited — the stored hash says it is untouched.
expect((await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 2', pl: 'Wpis 2' } })).status).toBe('update')
expect((await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 3', pl: 'Wpis 3' } })).status).toBe('update')
await payload.update({ id: created.id!, collection: 'posts', data: { title: 'Changed by an editor' }, locale: 'en' })
const r = await seeder({ update: true }).upsertBySlug('posts', { slug: { pl: 'wpis' }, title: { en: 'Post 4', pl: 'Wpis 4' } })
vi.useRealTimers()
expect(r).toMatchObject({ note: 'seedHash differs', status: 'skip (edited)' })
expect((await payload.findByID({ id: created.id!, collection: 'posts', locale: 'en' })).title).toBe('Changed by an editor')
})
test('upsertBy matches a natural key', async () => {
expect((await seeder().upsertBy('posts', { title: 'Formularz' }, { slug: 'formularz', title: 'Formularz' })).status).toBe('create')
expect((await seeder().upsertBy('posts', { title: 'Formularz' }, { slug: 'x', title: 'Formularz' })).status).toBe('skip (exists)')
})
test('fillGlobal fills only empty fields, in every locale', async () => {
await payload.updateGlobal({ slug: 'header', data: { phone: '+48 600 000 000' } })
const seed = seeder()
const r = await seed.fillGlobal('header', {
links: [{ label: { en: 'Contact', pl: 'Kontakt' } }],
phone: '+48 111 111 111',
tagline: { en: 'Hello', pl: 'Cześć' },
})
expect(r.status).toBe('create')
expect(r.note).toBe('empty fields filled: links, tagline')
const pl = await payload.findGlobal({ slug: 'header', fallbackLocale: false as never, locale: 'pl' })
const en = await payload.findGlobal({ slug: 'header', fallbackLocale: false as never, locale: 'en' })
expect(pl.phone).toBe('+48 600 000 000')
expect(pl.tagline).toBe('Cześć')
expect(en.tagline).toBe('Hello')
expect((en.links as { id: string; label: string }[])[0]).toMatchObject({ id: (pl.links as { id: string }[])[0].id, label: 'Contact' })
expect((await seeder().fillGlobal('header', { tagline: { pl: 'Inne' } })).status).toBe('skip (exists)')
})
test('production guard: update refused on production or a non-local database unless IPAL_SEED_ALLOW_PROD_UPDATE=1', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => seeder({ update: true })).toThrow(/update refused: NODE_ENV=production[\s\S]*Back up the database/)
expect(() => seeder()).not.toThrow() // create-only is always allowed
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
expect(seeder({ update: true }).update).toBe(true)
expect(lines.join('\n')).toMatch(/Did you back it up/)
vi.unstubAllEnvs()
vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app')
expect(() => seeder({ update: true })).toThrow(/the database is not local/)
expect(() => seeder({ guard: { localHosts: ['db'] }, update: true })).not.toThrow()
expect(() => seeder({ guard: false, update: true })).not.toThrow()
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
expect(() => seeder({ force: true, update: true })).toThrow(/force refused/)
})
test('env defaults: SEED_DRY_RUN, SEED_UPDATE', () => {
vi.stubEnv('SEED_DRY_RUN', '1')
vi.stubEnv('SEED_UPDATE', '1')
const s = createSeeder(payload, { log })
expect(s.dryRun).toBe(true)
expect(s.update).toBe(true)
})
test('seed writes skip IndexNow; a normal save still pings', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 }))
vi.stubEnv('NODE_ENV', 'production')
vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1')
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl')
vi.stubEnv('INDEXNOW_KEY', 'k123')
const seed = seeder({ update: true })
await seed.upsertBySlug('pages', [
{ slug: { en: 'news', pl: 'aktualnosci' }, _status: 'published', title: { en: 'News', pl: 'Aktualności' } },
{ slug: { pl: 'oferta' }, _status: 'published', title: { pl: 'Oferta po aktualizacji' } },
])
await seed.fillGlobal('header', { phone: '+48 1' })
await flush()
await flush()
expect(fetchSpy).not.toHaveBeenCalled()
const page = await payload.create({ collection: 'pages', data: { slug: 'zwykla', _status: 'published', title: 'Zwykła' }, locale: 'pl' })
await flush()
await flush()
expect(fetchSpy).toHaveBeenCalled()
expect(page.id).toBeDefined()
})
})