Files
ipal-kit/reference/e2e/smoke.spec.ts
T
Radosław SmolińskiandClaude Fable 5.2 0c61ac231b Security: staff checks only for staff collections; 2FA covers what the plugin adds
Staff check (userMeetsRole): the 'no roles field = every account passes'
rule applied to the account's own collection, so an account of a second
auth collection (customers) passed every staff check. It now applies only
to staff collections: the panel's login collection plus the new
access.staffCollections. The injected auth collection uses the new
adminOrSelfIn(slug), so an account of another collection with the same
numeric id is not 'self'.

2FA: @clocklimited/payload-2fa wraps the collections and globals present
when it runs; ipalKit's own globals and collections were added later and
stayed unwrapped, so a password without the TOTP code opened them over
REST and GraphQL. ipal-kit now has its own second-factor check
(secondFactorPassed / requireSecondFactor): applied to every collection
and global at the end of ipalKit, again in onInit for entities added by
plugins listed after it, and inside userMeetsRole and the endpoints that
take a project access function. It fails closed: an unrecognised user
shape is refused, and startup stops when the injected 2FA plugin lacks
the parts the check reads (twoFactor.guard: false opts out).

Tests through real HTTP requests (REST and GraphQL) against Payload's
route handlers, plus the reference smoke test. Docs, agent guide, skills
and the reference skills copy updated; changelog entry without a version.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:31:55 +01:00

253 lines
14 KiB
TypeScript

import { expect, type Page, test } from '@playwright/test'
import { attachmentOf, startSmtpSink } from './smtp-sink'
import { totp } from './totp'
/**
* Smoke tests of the reference site — every convention a client site must keep working after a plugin release.
* Run against a built, seeded site (playwright.config.ts). Both languages where it applies.
*/
const LOCALES = [
{ blog: '/pl/blog', code: 'pl', contact: '/pl/kontakt', home: '/pl', showcase: '/pl/bloki' },
{ blog: '/en/blog', code: 'en', contact: '/en/contact', home: '/en', showcase: '/en/blocks' },
]
async function rejectCookies(page: Page) {
const reject = page.getByRole('button', { name: /^(Odrzuć|Reject)$/ })
if (await reject.isVisible().catch(() => false)) {await reject.click()}
}
test('/ redirects to the default locale', async ({ request }) => {
const res = await request.get('/', { maxRedirects: 0 })
expect([307, 308]).toContain(res.status())
expect(res.headers().location).toMatch(/\/pl$/)
})
for (const l of LOCALES) {
test(`${l.code}: home renders with one h1, no console errors, both themes`, async ({ page }) => {
const errors: string[] = []
page.on('console', (m) => m.type() === 'error' && errors.push(m.text()))
await page.goto(l.home)
await expect(page.locator('h1')).toHaveCount(1)
await expect(page.locator('[data-ipal-block="hero"]')).toBeVisible()
await rejectCookies(page)
await page.getByRole('switch').first().click()
await expect(page.locator('html')).toHaveAttribute('data-theme', /dark|light/)
expect(errors, errors.join('\n')).toEqual([])
})
test(`${l.code}: the showcase renders every library block, also on the inverse surface`, async ({ page }) => {
await page.goto(l.showcase)
const slugs = await page.locator('[data-ipal-block]').evaluateAll((els) => [...new Set(els.map((e) => (e as HTMLElement).dataset.ipalBlock))])
expect(slugs.length).toBeGreaterThanOrEqual(15)
expect(await page.locator('[data-ipal-block][data-surface="inverse"]').count()).toBeGreaterThanOrEqual(15)
await expect(page.locator('meta[name="robots"]')).toHaveAttribute('content', /noindex/)
})
test(`${l.code}: the blog archive lists entries that open`, async ({ page }) => {
await page.goto(l.blog)
const first = page.locator('[data-ipal-block="entryList"] :is(h2, h3) a').first() // card titles: h2 when the list has no heading, else h3
await expect(first).toBeVisible()
await first.click()
await expect(page.locator('h1')).toHaveCount(1)
})
test(`${l.code}: the contact form sends`, async ({ page }) => {
await page.goto(l.contact)
await rejectCookies(page)
const form = page.locator('form[data-ipal="form"]').first()
await form.locator('input[name="name"]').fill('Test Smoke')
await form.locator('input[name="email"]').fill('[email protected]')
await form.locator('textarea[name="message"]').fill('Smoke test message.')
await form.locator('input[name="consent"]').check()
// Turnstile (test keys) puts its token in a hidden input once solved — submitting earlier is a turnstile failure
await expect(form.locator('input[name="cf-turnstile-response"]')).not.toHaveValue('', { timeout: 15_000 })
await form.locator('button[type="submit"]').click()
await expect(page.locator('[data-ipal="form-success"]')).toBeVisible({ timeout: 15_000 })
})
}
// Files on forms (forms: { attachments: true }): e-mailed to the studio, never stored. A real browser, the real
// endpoint and a local mail sink — the file must arrive as an attachment of the staff e-mail only.
test.describe('the quote form sends a file by e-mail', () => {
const PDF = Buffer.concat([Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), Buffer.alloc(200_000, 0x20)])
let sink: Awaited<ReturnType<typeof startSmtpSink>>
test.beforeAll(async () => {
sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
})
test.afterAll(async () => {
await sink.close()
})
async function fillQuote(page: Page) {
await page.goto('/en/quote')
await rejectCookies(page)
const form = page.locator('form[data-ipal="form"]').first()
await form.locator('input[name="name"]').fill('Test Smoke')
await form.locator('input[name="email"]').fill('[email protected]')
await form.locator('button[type="submit"]').click() // Next
await form.locator('input[name="scope"][value="building"]').check()
await form.locator('input[name="area"][value="s"]').check()
await form.locator('input[name="consent"]').check()
return form
}
test('a wrong file is refused at the field; a PDF arrives attached to the staff e-mail, not the customer one', async ({ page }) => {
const form = await fillQuote(page)
const input = form.locator('input[type="file"][name="attachment"]')
await expect(input).toHaveAttribute('accept', /\.pdf/)
// a type the field does not accept: the message shows at once, by the field
await input.setInputFiles({ buffer: Buffer.from('MZ'), mimeType: 'application/octet-stream', name: 'plan.exe' })
await expect(form.locator('[id$="attachment-error"]')).toContainText('The file "plan.exe" is in a format we do not accept. Choose one of: PDF, JPG, PNG.')
// keyboard: the Remove button is a real button — focus it and press Enter
await form.getByRole('button', { name: /Remove plan\.exe/ }).focus()
await page.keyboard.press('Enter')
await expect(form.locator('[data-ipal="form-files"] li')).toHaveCount(0)
// a program renamed to .pdf passes the browser check and is stopped by the server (content, not name)
await input.setInputFiles({ buffer: Buffer.concat([Buffer.from('MZ\x90\x00'), Buffer.alloc(2000)]), mimeType: 'application/pdf', name: 'plan.pdf' })
const token = form.locator('input[name="cf-turnstile-response"]')
await expect(token).not.toHaveValue('', { timeout: 15_000 })
await form.locator('button[type="submit"]').click()
// the message is at the File field, names the file, says why and what to do; nothing the visitor typed is lost
const problem = form.locator('[id$="attachment-error"]')
await expect(problem).toContainText('The file "plan.pdf" was refused', { timeout: 15_000 })
await expect(problem).toContainText('Choose another file (PDF, JPG, PNG). You can also send the form without the file.')
await expect(input).toHaveAttribute('aria-invalid', 'true')
await expect(form.locator('input[name="scope"][value="building"]')).toBeChecked()
await expect(form.locator('input[name="consent"]')).toBeChecked()
await form.getByRole('button', { name: 'Back' }).click()
await expect(form.locator('input[name="name"]')).toHaveValue('Test Smoke')
await expect(form.locator('input[name="email"]')).toHaveValue('[email protected]')
await form.locator('button[type="submit"]').click() // Next
expect(sink.messages).toHaveLength(0)
// the real file (the field takes several: remove the refused one first)
await form.getByRole('button', { name: /Remove plan\.pdf/ }).click()
await input.setInputFiles({ buffer: PDF, mimeType: 'application/pdf', name: 'Floor plan (ground).pdf' })
await expect(form.locator('[data-ipal="form-files"] li')).toContainText('Floor plan (ground).pdf')
// After a refusal the spam check renews itself (a token is single-use). The test keys always give the same
// dummy token, so there is nothing to watch for: submit until the request goes out.
let status = 0
await expect(async () => {
const posted = page.waitForResponse((r) => r.url().includes('/api/ipal/forms/submit') && r.request().method() === 'POST', { timeout: 3000 })
await form.locator('button[type="submit"]').click()
status = (await posted).status()
}).toPass({ timeout: 25_000 })
expect(status).toBe(200)
await expect(page.locator('[data-ipal="form-success"]')).toBeVisible({ timeout: 15_000 })
await expect.poll(() => sink.messages.length, { timeout: 15_000 }).toBe(2)
const staff = sink.messages.find((m) => !m.to.join().includes('[email protected]'))!
const customer = sink.messages.find((m) => m.to.join().includes('[email protected]'))!
const attached = attachmentOf(staff.data, 'Floor plan (ground).pdf')
expect(attached && Buffer.compare(attached, PDF)).toBe(0)
const text = (raw: string) => raw.replace(/=\n/g, '') // undo quoted-printable soft line breaks
expect(text(staff.data)).toContain('not checked for viruses')
expect(customer.data).not.toContain('Content-Disposition: attachment')
expect(text(customer.data)).toContain('Floor plan (ground).pdf') // the name in the summary, never the file
})
})
test('every sitemap URL answers 200 with a title, canonical, hreflang and JSON-LD', async ({ page, request }) => {
const xml = await (await request.get('/sitemap.xml')).text()
const urls = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname)
expect(urls.length).toBeGreaterThan(20)
for (const path of urls) {
const res = await page.goto(path)
expect(res?.status(), path).toBe(200)
await expect(page, path).toHaveTitle(/\S/)
expect(await page.locator('link[rel="canonical"]').count(), path).toBe(1)
expect(await page.locator('link[hreflang]').count(), path).toBeGreaterThanOrEqual(2)
expect(await page.locator('script[type="application/ld+json"]').count(), path).toBeGreaterThan(0)
}
})
test('SEO and GEO routes respond', async ({ request }) => {
const robots = await (await request.get('/robots.txt')).text()
expect(robots).toContain('Sitemap:')
expect(robots).toMatch(/Disallow: \/admin/)
expect(await (await request.get('/llms.txt')).text()).toContain('Example Studio')
expect((await request.get('/llms-full.txt')).status()).toBe(200)
expect(await (await request.get('/md/pl')).text()).toMatch(/^#|\n#/)
expect((await request.get('/api/health')).status()).toBe(200)
const mcp = await request.post('/api/mcp', { data: { id: 1, jsonrpc: '2.0', method: 'tools/list' } })
expect(await mcp.text()).toContain('get_page')
})
test('security headers: CSP enforced, no X-Powered-By', async ({ request }) => {
const headers = (await request.get('/pl')).headers()
expect(headers['content-security-policy']).toBeTruthy()
expect(headers['x-frame-options']).toBe('DENY')
expect(headers['x-powered-by']).toBeUndefined()
})
test('a missing page is a 404 with the panel 404 content', async ({ page }) => {
const res = await page.goto('/pl/nie-ma-takiej-strony')
expect(res?.status()).toBe(404)
await expect(page.getByRole('heading', { level: 1 })).toBeVisible()
})
test('consent: reject sets no analytics, the choice is logged', async ({ page }) => {
const logged = page.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
await page.goto('/pl')
await page.getByRole('button', { name: 'Odrzuć' }).click()
expect((await logged).status()).toBe(201)
const cookies = await page.context().cookies()
expect(cookies.some((c) => /^_ga/.test(c.name))).toBe(false)
expect(cookies.some((c) => c.name === 'cookie-consent')).toBe(true)
})
test('admin: sign in through 2FA, agency credit, panel link preview', async ({ page, request }) => {
const head = await (await request.get('/admin/login')).text()
expect(head).toMatch(/noindex/)
expect(head).toMatch(/og:site_name/)
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
await page.goto('/admin/login')
await page.fill('#field-email', email!)
await page.fill('#field-password', password!)
await page.click('.form-submit button')
await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' })
if (page.url().includes('verify-totp')) {
// six one-digit inputs: type the code into the first, focus moves on by itself
const firstDigit = page.getByRole('textbox').first()
await firstDigit.click()
await page.keyboard.type(totp(secret!))
}
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
await expect(page.getByText(/Intecion/).first()).toBeVisible()
})
// 2FA covers what the plugin adds, over the API too (REST and GraphQL): a correct password without the code
// from the authenticator app opens neither the settings nor visitors' data; the code does.
test('API: a staff password without the 2FA code opens nothing; with the code it does', async ({ playwright, baseURL }) => {
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
const api = await playwright.request.newContext({ baseURL }) // its own cookie jar
const login = await api.post('/api/users/login', { data: { email, password } })
expect(login.status()).toBe(200)
const guarded = ['/api/globals/site-integrations', '/api/form-submissions', '/api/consent-records', '/api/users', '/api/globals/site-settings', '/api/forms']
for (const path of guarded) {
const res = await api.get(path)
expect(res.status(), `${path} without the code`).toBe(403)
expect(await res.text()).not.toContain('e2e-sink') // the SMTP password create-test-admin.ts stored
}
expect((await api.post('/api/globals/site-settings', { data: {} })).status()).toBe(403)
expect((await api.post('/api/ipal/test-email', { data: { to: '[email protected]' } })).status()).toBe(403)
const query = '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }'
const before = await (await api.post('/api/graphql', { data: { query } })).json()
expect(before.errors?.length).toBeGreaterThan(0)
expect(JSON.stringify(before)).not.toContain('e2e-sink')
const verify = await api.post('/api/verify-totp', { data: { token: totp(secret!) } })
expect((await verify.json()).ok).toBe(true)
for (const path of guarded) {expect((await api.get(path)).status(), `${path} with the code`).toBe(200)}
const after = await (await api.post('/api/graphql', { data: { query } })).json()
expect(after.errors).toBeUndefined()
expect(after.data.SiteIntegration.smtpPassword).toBe('e2e-sink')
await api.dispose()
})