/** * End-to-end through a REAL Payload (SQLite in memory): plugin config → form * built in the "panel" (Local API) → submitForm → stored submission. Catches * what unit tests with a fake payload can't: schema, access control, hooks. */ 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 { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js' import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConsentTexts.js' import { submitForm } from '../src/modules/forms/submitForm.js' import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' import { createPageRoute } from '../src/modules/frontend/pageRoute.js' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) let payload: Payload let configPromise: Parameters[0]['config'] let formId: string beforeAll(async () => { const config = buildTestConfig({ collections: [ // Open sign-up, the risky setup the roles field guard exists for. { slug: 'users', access: { create: () => true }, auth: true, fields: [] }, { slug: 'pages', fields: [ { name: 'title', type: 'text' }, { name: 'slug', type: 'text', index: true, localized: true }, ], }, // SiteSettings' logo/favicon upload fields point here. { 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' }, consentLog: true, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false, }), ], secret: 'integration-test-secret', telemetry: false, }) configPromise = config payload = await getPayload({ config }) const form = await payload.create({ collection: 'forms' as never, data: { confirmationMessage: { root: { type: 'root', children: [ { type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Dziękujemy', version: 1 }], direction: null, format: '', indent: 0, version: 1, }, ], direction: null, format: '', indent: 0, version: 1, }, }, fields: [ { name: 'name', blockType: 'text', label: 'Imię', required: true }, { name: 'consent', blockType: 'checkbox', label: 'Zgoda' }, ], title: 'Kontakt', } as never, }) formId = String(form.id) }, 60_000) afterAll(async () => { await payload?.destroy() }) describe('forms against a real Payload', () => { test('a valid submission is stored with only the form fields', async () => { const result = await submitForm({ data: { name: 'Ala', consent: true }, formId, ip: '10.7.0.1', payload }) expect(result.success).toBe(true) if (!result.success) {return} const stored = (await payload.findByID({ id: result.submissionId, collection: 'form-submissions' as never, depth: 0, })) as unknown as { form: number | string; submissionData: { field: string; value: string }[] } expect(String(stored.form)).toBe(formId) expect(stored.submissionData.map(({ field, value }) => ({ field, value }))).toEqual([ { field: 'name', value: 'Ala' }, { field: 'consent', value: 'true' }, ]) }) test('the gates hold: consent, required, unknown keys', async () => { const send = (data: Record) => submitForm({ data, formId, ip: '10.7.0.2', maxPerMinute: 0, payload }) expect(await send({ name: 'Ala', consent: false })).toMatchObject({ reason: 'consent' }) expect(await send({ consent: true })).toMatchObject({ field: 'name', reason: 'validation' }) expect(await send({ name: 'Ala', consent: true, role: 'admin' })).toMatchObject({ kind: 'unknown_fields' }) }) test('step-by-step form with a checkbox group, radio and date: built in the panel, stored readable', async () => { const multi = await payload.create({ collection: 'forms' as never, data: { confirmationType: 'redirect', fields: [ { name: 'name', blockType: 'text', label: 'Imię', required: true }, { blockType: 'step', title: 'Szczegóły' }, { name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona', value: 'www' }, { label: 'SEO', value: 'seo' }], required: true }, { name: 'size', blockType: 'radio', label: 'Wielkość', options: [{ label: 'Mała', value: 's' }, { label: 'Duża', value: 'l' }] }, { name: 'deadline', blockType: 'date', label: 'Termin' }, ], redirect: { url: '/dziekujemy' }, title: 'Wycena', } as never, }) const result = await submitForm({ data: { name: 'Ala', deadline: '2026-12-01', services: ['www', 'seo'], size: 'l' }, formId: String(multi.id), ip: '10.7.0.9', payload, }) expect(result).toMatchObject({ success: true }) if (!result.success) {return} const stored = (await payload.findByID({ id: result.submissionId, collection: 'form-submissions' as never, depth: 0 })) as unknown as { submissionData: { field: string; value: string }[] } expect(stored.submissionData.map(({ field, value }) => [field, value])).toEqual([ ['name', 'Ala'], ['services', 'www, seo'], ['size', 'l'], ['deadline', '2026-12-01'], ]) }) test('REST/anonymous creation of submissions is closed (only submitForm writes)', async () => { await expect( payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [] } as never, overrideAccess: false, }), ).rejects.toThrow() }) test('open sign-up cannot self-assign admin — roles fall back to the default', async () => { const user = (await payload.create({ collection: 'users', data: { email: 'a@acme.pl', password: 'Passw0rd!x-long', roles: ['admin'] } as never, overrideAccess: false, })) as unknown as { roles: string[] } expect(user.roles).toEqual(['user']) }) test('seed / Local API with overrideAccess can still create an admin', async () => { const admin = (await payload.create({ collection: 'users', data: { email: 'root@acme.pl', password: 'Passw0rd!x-long', roles: ['admin'] } as never, })) as unknown as { roles: string[] } expect(admin.roles).toEqual(['admin']) }) }) describe('generatePageMetadata — markdownAlternate', () => { const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const test('advertises the Markdown version of an indexable page', async () => { await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', title: 'O nas' } as never }) const on = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, markdownAlternate: true }) const meta = await on.generatePageMetadata('pl', ['o-nas']) expect(meta.alternates?.canonical).toBe('https://acme.pl/o-nas') expect(meta.alternates?.types).toEqual({ 'text/markdown': '/md/o-nas' }) const off = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) expect((await off.generatePageMetadata('pl', ['o-nas'])).alternates?.types).toBeUndefined() }) }) describe('getPageJsonLd', () => { const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const test('WebPage + breadcrumbs from the real route, FAQ when mapped, no @context per node', async () => { await payload.create({ collection: 'pages' as never, data: { slug: 'kontakt', title: 'Kontakt' } as never }) const h = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) const nodes = await h.getPageJsonLd('pl', ['kontakt'], { faq: () => [{ answer: 'Tak.', question: 'Czy dojeżdżacie?' }, { answer: '', question: 'puste' }], pageType: () => 'ContactPage', }) expect(nodes.map((n) => n['@type'])).toEqual(['ContactPage', 'BreadcrumbList', 'FAQPage']) expect(nodes[0]).toMatchObject({ name: 'Kontakt', '@id': 'https://acme.pl/kontakt', inLanguage: 'pl' }) expect(nodes.every((n) => !('@context' in n))).toBe(true) expect((nodes[2] as { mainEntity: unknown[] }).mainEntity).toHaveLength(1) expect(await h.getPageJsonLd('pl', ['nie-ma'])).toEqual([]) }) }) describe('one-call helpers — layout, page, GEO routes', () => { const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const const h = () => createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, mcp: { serverName: 'acme-site' } }) test('getSiteShell: consent, analytics, Turnstile, form texts and site JSON-LD in one call', async () => { await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Acme' } as never }) const shell = await h().getSiteShell('pl') expect(shell.turnstileSiteKey).toBeNull() expect(shell.consent.buttons.acceptAll).toEqual(expect.any(String)) // a Polish page gets the Polish defaults while the panel is empty expect(shell.formTexts).toMatchObject({ next: 'Dalej', stepOf: 'Krok {current} z {total}' }) expect(shell.lightboxTexts).toMatchObject({ close: 'Zamknij', counter: '{current} / {total}' }) expect(shell.jsonLd.map((n) => n['@type'])).toEqual(['WebSite', 'Organization']) expect(shell.jsonLd.every((n) => !('@context' in n))).toBe(true) const custom = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, siteJsonLd: false }) expect((await custom.getSiteShell('pl')).jsonLd).toEqual([]) }) test('createPageRoute: renders a page with its JSON-LD, 404s an unknown slug', async () => { await payload.create({ collection: 'pages' as never, data: { slug: 'uslugi', title: 'Usługi' } as never }) const notFound = vi.fn(() => { throw new Error('NEXT_NOT_FOUND') }) as unknown as () => never const permanentRedirect = vi.fn() as unknown as (url: string) => never const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect }) const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } } expect(JSON.stringify(el.props.children[0])).toContain('Usługi') // Blocks get the locale and whether they are the first section (the page's h1). const blocksEl = el.props.children[1] as { props: { enhanceProps: (a: { allBlocks: never[]; block: never; index: number }) => Record } } expect(blocksEl.props.enhanceProps({ allBlocks: [], block: {} as never, index: 0 })).toMatchObject({ isFirst: true, locale: 'pl' }) expect(blocksEl.props.enhanceProps({ allBlocks: [], block: {} as never, index: 1 }).isFirst).toBe(false) // …and whether a block before them shows an image (the LCP image of a list under a page header without one). const hero = { blockType: 'hero', media: { height: 1, mimeType: 'image/jpeg', url: '/a.jpg', width: 1 } } expect(blocksEl.props.enhanceProps({ allBlocks: [{ blockType: 'hero' }, {}] as never[], block: {} as never, index: 1 }).firstImage).toBe(true) expect(blocksEl.props.enhanceProps({ allBlocks: [hero, {}] as never[], block: {} as never, index: 1 }).firstImage).toBe(false) await expect(route.Page({ params: Promise.resolve({ slug: ['nie-ma'] }) })).rejects.toThrow('NEXT_NOT_FOUND') expect((await route.generateMetadata({ params: Promise.resolve({ slug: ['uslugi'] }) })).alternates?.canonical).toBe('https://acme.pl/uslugi') }) test('route handlers answer without per-file configuration', async () => { const helpers = h() const llms = await helpers.llmsRoute() expect(llms.status).toBe(200) expect(await llms.text()).toContain('https://acme.pl/uslugi') expect((await helpers.healthRoute()).status).toBe(200) expect((await helpers.indexNowKeyRoute()).status).toBe(404) // no key configured const mcp = await helpers.mcpPOST( new Request('https://acme.pl/api/mcp', { body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'initialize' }), headers: { 'content-type': 'application/json' }, method: 'POST' }), ) expect(JSON.stringify(await mcp.json())).toContain('acme-site') const md = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'], locale: 'pl' }) }) expect(md.status).toBe(200) }) test('single-language Markdown: app/md/[[...slug]] (no locale param) and the [locale] route both serve the page', async () => { const helpers = h() const noLocale = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'] }) }) expect(noLocale.status).toBe(200) const plain = await noLocale.text() expect(plain).toContain('url: https://acme.pl/uslugi') expect(plain).toContain('locale: pl') // [locale] route on a one-language site: "/md/uslugi" arrives as locale "uslugi" const asLocale = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ locale: 'uslugi' }) }) expect(asLocale.status).toBe(200) const body = await asLocale.text() expect(body).toContain('# Usługi') expect(body).toContain('url: https://acme.pl/uslugi') expect(body).toContain('locale: pl') }) }) describe('consent log', () => { // a real Request, as Payload passes one (the endpoint reads the body stream with a cap) const post = (body: unknown, ip = '10.6.0.1') => buildConsentLogEndpoint().handler( Object.assign(new Request('http://localhost/api/ipal/consent', { body: JSON.stringify(body), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' }), { payload }) as never, ) as Promise const state = { analytics: true, functional: false, marketing: false, necessary: true } test('stores id, choices and version only', async () => { // the site's policy version is 1 (Cookie settings not changed): a decision carries 1 at most (1.17.0) const res = await post({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state, version: 1 }) expect(res.status).toBe(201) const { docs } = await payload.find({ collection: 'consent-records' as never, where: { consentId: { equals: 'a1b2c3d4e5f6a7b8c9d0e1f2' } } }) const rec = docs[0] as unknown as Record expect(rec).toMatchObject({ choices: state, version: 1 }) expect(Object.keys(rec).filter((k) => /ip|agent|email/i.test(k))).toEqual([]) }) test('rejects malformed records', async () => { for (const bad of [{}, { id: 'x', state, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state: { analytics: 'yes' }, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state, version: 0 }, { id: 'a1b2c3d4e5f6a7b8', state, version: 2 }]) { expect((await post(bad, '10.6.0.2')).status).toBe(400) } }) test('the collection is not writable or readable anonymously', async () => { await expect(payload.find({ collection: 'consent-records' as never, overrideAccess: false })).rejects.toThrow() }) }) describe('consent texts', () => { const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const test('optional banner copy is omitted when empty and passed through when set', async () => { const empty = await getConsentTexts({ config, locale: 'pl', payload, privacyPolicy: false }) expect(empty.eyebrow).toBeUndefined() expect(empty.title).toBeUndefined() expect(empty.settingsDescription).toBeUndefined() expect(empty.alwaysActiveLabel).toBeUndefined() expect(empty.buttons.close).toBe('Zamknij') // Polish default on a Polish page expect((await getConsentTexts({ config, locale: 'en', payload, privacyPolicy: false })).buttons.close).toBe('Close') await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { alwaysActiveLabel: 'Zawsze aktywne', buttons: { close: 'Zamknij' }, eyebrow: 'Prywatność i cookies', settingsDescription: 'Możesz zmienić wybór w dowolnym momencie.', title: 'Szanujemy Twoją prywatność', } as never, locale: 'pl' as never, }) const texts = await getConsentTexts({ config, locale: 'pl', payload, privacyPolicy: false }) expect(texts).toMatchObject({ alwaysActiveLabel: 'Zawsze aktywne', buttons: { close: 'Zamknij' }, eyebrow: 'Prywatność i cookies', settingsDescription: 'Możesz zmienić wybór w dowolnym momencie.', title: 'Szanujemy Twoją prywatność', }) }) }) describe('cookie table', () => { test('rows from Cookie Settings in the requested language', async () => { await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki' }, { name: ' ' }] } as never, locale: 'pl' as never, }) expect(await getCookieTable({ locale: 'pl', payload })).toEqual([ { name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki', storage: 'cookie' }, ]) // the same rows feed the detailed settings window, with the page language's default labels until the panel has them const texts = await getConsentTexts({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, locale: 'pl', payload, privacyPolicy: false }) expect(texts.cookies).toEqual([{ name: '_ga', category: 'analytics', duration: '2 lata', provider: 'Google', purpose: 'Statystyki', storage: 'cookie' }]) expect(texts.details).toEqual({ cookies: 'Używane cookies', duration: 'Okres', provider: 'Dostawca', purpose: 'Cel', storage: 'Rodzaj', storageTypes: { cookie: 'Plik cookie', localStorage: 'Pamięć lokalna', sessionStorage: 'Pamięć sesji' }, }) await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { detailLabels: { cookies: 'Używane ciasteczka', duration: 'Czas', provider: 'Dostawca', purpose: 'Cel' } } as never, locale: 'pl' as never, }) expect((await getConsentTexts({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, locale: 'pl', payload, privacyPolicy: false })).details).toEqual({ cookies: 'Używane ciasteczka', duration: 'Czas', provider: 'Dostawca', purpose: 'Cel', storage: 'Rodzaj', storageTypes: { cookie: 'Plik cookie', localStorage: 'Pamięć lokalna', sessionStorage: 'Pamięć sesji' }, }) }) }) describe('forms access', () => { test('anonymous REST read of a form hides its e-mail recipients; submissions are staff-only', async () => { await payload.update({ id: formId, collection: 'forms' as never, data: { emails: [{ emailTo: 'biuro@acme.pl', subject: 'Nowe zgłoszenie' }] } as never, }) const anon = (await payload.findByID({ id: formId, collection: 'forms' as never, overrideAccess: false })) as Record expect(anon.fields).toBeDefined() expect(JSON.stringify(anon.emails ?? [])).not.toContain('biuro@acme.pl') const user = (await payload.create({ collection: 'users', data: { email: 'plain@acme.pl', password: 'Passw0rd!x-long' } as never, })) as unknown as Record await expect( payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }), ).rejects.toThrow() const editor = { ...user, collection: 'users', roles: ['editor'] } expect((await payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: editor as never })).totalDocs).toBeGreaterThan(0) }) })