On by default with whiteLabel. The login screen and the 2FA screens get the look through AdminLogo and SafeTotpView, which every site already has in its import map: an upgrade needs no edit. allScreens adds one provider (SignInLook) for forgot / reset password, first user and logout; a production start leaves it out when the import map on disk lacks it. Logo and name come from Site settings: no new field, no migration. Language links through GET /api/ipal/admin-language (Payload's own cookie, back to an admin path only). Options: accent, logoMadeFor, languages, svgLogo; whiteLabel.brandAccess 'admin'. The 2FA code boxes get names for screen readers. Reference site and starter: allScreens on. Docs, agent guide, skills, tests. Co-Authored-By: Claude Fable 5.2 <[email protected]>
557 lines
32 KiB
TypeScript
557 lines
32 KiB
TypeScript
import { expect, type Page, test } from '@playwright/test'
|
|
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
import { createServer, request as httpRequest } from 'node:http'
|
|
import path from 'node:path'
|
|
|
|
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')
|
|
})
|
|
|
|
// A bundler turns a file that server code names relative to its own module into an ASSET. Turbopack published the
|
|
// plugin's whole package.json that way (dependency lists, scripts, the registry address) under /_next/static/media/.
|
|
test('no package.json is published: nothing under .next/static holds one, and the obvious addresses answer 404', async ({ request }) => {
|
|
const statics = path.resolve('.next/static')
|
|
const walk = (dir: string): string[] => (existsSync(dir) ? readdirSync(dir).flatMap((name) => {
|
|
const file = path.join(dir, name)
|
|
return statSync(file).isDirectory() ? walk(file) : [file]
|
|
}) : [])
|
|
const files = walk(statics)
|
|
expect(files.length, 'the built site\'s .next/static (run from the site folder)').toBeGreaterThan(0)
|
|
// by name, and by content (a manifest of a package: its dependency lists)
|
|
const manifests = files.filter((file) => /package[^/]*\.json$/.test(file) || (file.endsWith('.json') && /"(?:devDependencies|peerDependencies|publishConfig)"\s*:/.test(readFileSync(file, 'utf8'))))
|
|
expect(manifests.map((file) => path.relative(statics, file))).toEqual([])
|
|
for (const address of ['/package.json', '/_next/package.json', '/_next/static/package.json', '/_next/static/media/package.json']) {
|
|
expect((await request.get(address)).status(), address).toBe(404)
|
|
}
|
|
})
|
|
|
|
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.describe('client hints: Payload\'s colour-scheme headers go to the admin only', () => {
|
|
const HINT = /sec-ch-prefers-color-scheme/i
|
|
|
|
test('no public page, route handler or static file carries them; the admin does', async ({ request }) => {
|
|
const home = await request.get('/pl')
|
|
const asset = (await home.text()).match(/\/_next\/static\/[^"'\\ ]+\.(?:js|css)/)?.[0]
|
|
expect(asset, 'a static file linked from /pl').toBeTruthy()
|
|
// FAILS when withPayload's site-wide rule is back (withSecurityConfig inside withPayload, or the option off)
|
|
for (const path of ['/pl', '/en', '/pl/kontakt', '/en/contact', '/pl/blog', '/api/health', '/robots.txt', '/sitemap.xml', '/llms.txt', asset!]) {
|
|
const res = await request.get(path)
|
|
const headers = res.headers()
|
|
expect(res.status(), path).toBe(200)
|
|
expect(headers['accept-ch'], `${path}: Accept-CH`).toBeUndefined()
|
|
expect(headers['critical-ch'], `${path}: Critical-CH`).toBeUndefined()
|
|
expect(headers.vary ?? '', `${path}: Vary`).not.toMatch(HINT)
|
|
}
|
|
for (const path of ['/admin', '/admin/login']) {
|
|
const headers = (await request.get(path, { maxRedirects: 0 })).headers()
|
|
expect(headers['accept-ch'], `${path}: Accept-CH`).toMatch(HINT)
|
|
expect(headers['critical-ch'], `${path}: Critical-CH`).toMatch(HINT)
|
|
}
|
|
})
|
|
|
|
test('Chrome asks for a public page once; the admin still gets the hint and renders the browser\'s scheme', async ({ baseURL, browser, request }) => {
|
|
// A counting proxy in front of the site: what the SERVER receives. Chrome repeats a document request inside
|
|
// its network stack when the answer names a critical hint it did not send; the page never sees that.
|
|
const documents: { hint?: string; url: string }[] = []
|
|
const site = new URL(baseURL!)
|
|
const proxy = createServer((req, res) => {
|
|
if (req.headers['sec-fetch-dest'] === 'document') {documents.push({ hint: req.headers['sec-ch-prefers-color-scheme'] as string | undefined, url: req.url! })}
|
|
const upstream = httpRequest({ headers: req.headers, host: site.hostname, method: req.method, path: req.url, port: site.port }, (r) => {
|
|
res.writeHead(r.statusCode!, r.headers)
|
|
r.pipe(res)
|
|
})
|
|
upstream.on('error', () => res.destroy())
|
|
req.pipe(upstream)
|
|
})
|
|
await new Promise<void>((resolve) => proxy.listen(0, '127.0.0.1', resolve))
|
|
const origin = `http://localhost:${(proxy.address() as { port: number }).port}`
|
|
try {
|
|
for (const path of ['/pl', '/en/contact']) {
|
|
const context = await browser.newContext() // a fresh profile: a first visit
|
|
documents.length = 0
|
|
await (await context.newPage()).goto(origin + path)
|
|
expect(documents, `${path}: one document request, no hint asked for`).toEqual([{ hint: undefined, url: path }])
|
|
await context.close()
|
|
}
|
|
// The panel: its first request teaches Chrome the hint, the repeated one carries it — as before the change.
|
|
// (Chrome's network stack sends the system's scheme; Playwright's colorScheme emulation does not reach it.)
|
|
const context = await browser.newContext()
|
|
const page = await context.newPage()
|
|
documents.length = 0
|
|
const response = await page.goto(`${origin}/admin/login`)
|
|
expect(documents).toEqual([{ hint: undefined, url: '/admin/login' }, { hint: expect.stringMatching(/^(dark|light)$/), url: '/admin/login' }])
|
|
const sent = documents[1]!.hint!
|
|
// the theme is in the server's HTML: the first paint is already right (no flash)
|
|
expect(await response!.text()).toMatch(new RegExp(`<html[^>]*data-theme="${sent}"`))
|
|
await expect(page.locator('html')).toHaveAttribute('data-theme', sent)
|
|
await context.close()
|
|
// and the server renders whichever scheme the hint names
|
|
for (const scheme of ['dark', 'light']) {
|
|
const html = await (await request.get('/admin/login', { headers: { 'Sec-CH-Prefers-Color-Scheme': scheme } })).text()
|
|
expect(html, scheme).toMatch(new RegExp(`<html[^>]*data-theme="${scheme}"`))
|
|
}
|
|
} finally {
|
|
proxy.close()
|
|
}
|
|
})
|
|
})
|
|
|
|
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)
|
|
})
|
|
|
|
// The banner is part of the first render (consent.md → "First paint"): in the static HTML, shown or kept hidden by
|
|
// an inline script before the browser paints, live after hydration.
|
|
const watchBanner = () => {
|
|
const w = window as unknown as { __bannerFrames: number }
|
|
w.__bannerFrames = 0
|
|
const tick = () => {
|
|
const b = document.querySelector<HTMLElement>('[data-ipal="banner"]')
|
|
if (b && getComputedStyle(b).display !== 'none' && b.getBoundingClientRect().height > 0) {w.__bannerFrames++}
|
|
requestAnimationFrame(tick)
|
|
}
|
|
requestAnimationFrame(tick)
|
|
}
|
|
const isAppScript = (url: URL) => url.pathname.startsWith('/_next/static/') && url.pathname.endsWith('.js')
|
|
|
|
for (const l of LOCALES) {
|
|
test(`${l.code}: consent banner is in the static HTML and painted before the page hydrates`, async ({ page, request }) => {
|
|
const res = await request.get(l.home)
|
|
const html = await res.text()
|
|
expect(html).toMatch(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
|
|
expect(html).toMatch(/<\/div><script[^>]*data-ipal="banner-script"/)
|
|
// the page is still a static one: the banner did not make it depend on a cookie
|
|
expect(res.headers()['cache-control']).toMatch(/s-maxage=\d+/)
|
|
expect(res.headers()['set-cookie']).toBeUndefined()
|
|
const withCookie = await request.get(l.home, { headers: { cookie: 'cookie-consent=anything' } })
|
|
expect((await withCookie.text()).includes('data-ipal="banner"')).toBe(true)
|
|
|
|
// no application script at all: nothing hydrates, the inline script alone decides
|
|
await page.route(isAppScript, (route) => route.abort())
|
|
await page.goto(l.home)
|
|
const banner = page.locator('[data-ipal="banner"]')
|
|
await expect(banner).toBeVisible()
|
|
await expect(banner.getByRole('button', { name: /^(Odrzuć|Reject)$/ })).toBeVisible()
|
|
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
|
|
})
|
|
}
|
|
|
|
test('consent: a returning visitor never sees the banner, an old policy version asks again; no console errors', async ({ context, page }) => {
|
|
const errors: string[] = []
|
|
page.on('console', (m) => {
|
|
if (m.type() === 'error' || /hydrat/i.test(m.text())) {errors.push(m.text())}
|
|
})
|
|
page.on('pageerror', (e) => errors.push(String(e)))
|
|
await page.goto('/pl')
|
|
await page.getByRole('button', { name: 'Odrzuć' }).click()
|
|
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
|
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
|
const stored = (await context.cookies()).find((c) => c.name === 'cookie-consent')!
|
|
|
|
await page.addInitScript(watchBanner)
|
|
for (const path of ['/pl', '/en', '/pl/regulamin']) {
|
|
await page.goto(path)
|
|
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
|
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
|
expect(await page.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames), `${path}: frames with the banner shown`).toBe(0)
|
|
}
|
|
// without the application scripts too: the inline script hides it before the first paint
|
|
const bare = await context.newPage()
|
|
await bare.addInitScript(watchBanner)
|
|
await bare.route(isAppScript, (route) => route.abort())
|
|
await bare.goto('/pl')
|
|
await bare.waitForTimeout(500)
|
|
expect(await bare.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames)).toBe(0)
|
|
await bare.close()
|
|
|
|
// the same decision under another policy version: asked again, from the first paint
|
|
const record = JSON.parse(decodeURIComponent(stored.value)) as { version: number }
|
|
await context.addCookies([{ ...stored, value: encodeURIComponent(JSON.stringify({ ...record, version: record.version + 1 })) }])
|
|
await page.goto('/pl')
|
|
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
|
|
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
|
|
expect(errors).toEqual([])
|
|
})
|
|
|
|
test('consent: a click on the banner before the page has hydrated is not lost', async ({ context, page }) => {
|
|
let release: () => void = () => {}
|
|
const held = new Promise<void>((resolve) => {
|
|
release = resolve
|
|
})
|
|
await page.route(isAppScript, async (route) => {
|
|
await held
|
|
await route.continue()
|
|
})
|
|
await page.goto('/pl', { waitUntil: 'commit' })
|
|
const reject = page.locator('[data-ipal="reject"]')
|
|
await expect(reject).toBeVisible()
|
|
await reject.click()
|
|
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(false) // the script itself stores nothing
|
|
const logged = page.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
|
|
release()
|
|
expect((await logged).status()).toBe(201)
|
|
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
|
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
|
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(true)
|
|
})
|
|
|
|
// Consent compliance (1.17.0, docs/consent-behaviour-spec.md): Global Privacy Control, equal prominence, withdrawal.
|
|
const withGpc = async (browser: import('@playwright/test').Browser, baseURL?: string) => {
|
|
const context = await browser.newContext({ baseURL, extraHTTPHeaders: { 'Sec-GPC': '1' } })
|
|
await context.addInitScript(() => Object.defineProperty(Navigator.prototype, 'globalPrivacyControl', { configurable: true, get: () => true }))
|
|
return context
|
|
}
|
|
const consentRecord = async (context: import('@playwright/test').BrowserContext) => {
|
|
const c = (await context.cookies()).find((x) => x.name === 'cookie-consent')
|
|
return c ? (JSON.parse(decodeURIComponent(c.value)) as { gpc?: boolean; id: string; state: Record<string, boolean>; version: number }) : null
|
|
}
|
|
|
|
test('consent: Global Privacy Control — no banner from the first paint, nothing stored, the same static HTML; opting in from the button wins', async ({ baseURL, browser, request }) => {
|
|
const plain = await request.get('/pl')
|
|
const signalled = await request.get('/pl', { headers: { 'Sec-GPC': '1' } })
|
|
// the server never renders differently for the signal: one static page, no Vary on it
|
|
const strip = (html: string) => html.replace(/ nonce="[^"]*"/g, '')
|
|
expect(strip(await signalled.text())).toBe(strip(await plain.text()))
|
|
expect(signalled.headers()['cache-control']).toMatch(/s-maxage=\d+/)
|
|
expect(signalled.headers().vary ?? '').not.toMatch(/sec-gpc/i)
|
|
|
|
const context = await withGpc(browser, baseURL)
|
|
const page = await context.newPage()
|
|
const errors: string[] = []
|
|
page.on('console', (m) => m.type() === 'error' && errors.push(m.text()))
|
|
const trackers: string[] = []
|
|
page.on('request', (r) => /googletagmanager|google-analytics|facebook|clarity\.ms|licdn|tiktok|doubleclick/.test(r.url()) && trackers.push(r.url()))
|
|
await page.addInitScript(watchBanner)
|
|
await page.goto('/pl')
|
|
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
|
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
|
expect(await page.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames)).toBe(0)
|
|
expect(await consentRecord(context)).toBeNull()
|
|
expect(trackers).toEqual([])
|
|
|
|
// the visitor opens the settings: the line about the signal; "Accept all" there is their own choice for this site
|
|
await page.locator('[data-ipal="cookie-button"]').click()
|
|
await expect(page.locator('[data-ipal="gpc-notice"]').first()).toContainText('Global Privacy Control')
|
|
const logged = page.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
|
|
await page.locator('[data-ipal="banner"] [data-ipal="accept"]').click()
|
|
expect((await logged).status()).toBe(201)
|
|
expect(await consentRecord(context)).toMatchObject({ gpc: true, state: { analytics: true, marketing: true } })
|
|
await page.goto('/en')
|
|
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
|
|
expect((await consentRecord(context))!.state.analytics).toBe(true)
|
|
expect(errors).toEqual([])
|
|
await context.close()
|
|
})
|
|
|
|
test('consent: the signal appears after an "Accept" made without it — analytics and marketing go off, the cookies with them', async ({ baseURL, browser, context, page }) => {
|
|
await page.goto('/pl')
|
|
await page.locator('[data-ipal="banner"] [data-ipal="accept"]').click()
|
|
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
|
|
const record = (await consentRecord(context))!
|
|
expect(record).toMatchObject({ gpc: false, state: { analytics: true, marketing: true } })
|
|
const consent = (await context.cookies()).find((c) => c.name === 'cookie-consent')!
|
|
|
|
const gpc = await withGpc(browser, baseURL)
|
|
const host = new URL(baseURL!).hostname
|
|
await gpc.addCookies([{ ...consent }, { domain: host, name: '_ga', path: '/', value: 'GA1.1.1' }, { domain: host, name: '_fbp', path: '/', value: 'fb.1' }])
|
|
const p = await gpc.newPage()
|
|
const logged = p.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
|
|
await p.goto('/pl')
|
|
expect((await logged).status()).toBe(201)
|
|
const after = (await consentRecord(gpc))!
|
|
expect(after).toMatchObject({ gpc: true, id: record.id, state: { analytics: false, functional: true, marketing: false } })
|
|
const names = (await gpc.cookies()).map((c) => c.name)
|
|
expect(names).not.toContain('_ga')
|
|
expect(names).not.toContain('_fbp')
|
|
await expect(p.locator('[data-ipal="banner"]')).toHaveCount(0)
|
|
await gpc.close()
|
|
})
|
|
|
|
for (const l of LOCALES) {
|
|
test(`${l.code}: consent — "Reject" is as prominent as "Accept all" (same element, size and look)`, async ({ page }) => {
|
|
for (const size of [{ height: 640, width: 360 }, { height: 800, width: 1280 }]) {
|
|
await page.setViewportSize(size)
|
|
await page.goto(l.home)
|
|
const look = await page.evaluate(() => {
|
|
const pick = (sel: string) => {
|
|
const el = document.querySelector<HTMLElement>(sel)!
|
|
const cs = getComputedStyle(el)
|
|
const r = el.getBoundingClientRect()
|
|
return { bg: cs.backgroundColor, color: cs.color, fontSize: cs.fontSize, fontWeight: cs.fontWeight, height: Math.round(r.height), padding: cs.padding, radius: cs.borderRadius, tag: el.tagName, visible: r.bottom <= innerHeight && r.top >= 0 }
|
|
}
|
|
return { accept: pick('[data-ipal="banner"] [data-ipal="accept"]'), reject: pick('[data-ipal="banner"] [data-ipal="reject"]') }
|
|
})
|
|
expect(look.reject, `${size.width}px`).toEqual(look.accept)
|
|
expect(look.reject.tag).toBe('BUTTON')
|
|
expect(look.reject.visible).toBe(true)
|
|
}
|
|
})
|
|
}
|
|
|
|
test('consent: withdrawal — reopen, reject: analytics cookies and listed storage keys go, the record says so', async ({ context, page }) => {
|
|
await page.goto('/pl')
|
|
await page.locator('[data-ipal="banner"] [data-ipal="accept"]').click()
|
|
const host = new URL(page.url()).hostname
|
|
await context.addCookies([{ domain: host, name: '_ga', path: '/', value: 'GA1.1.1' }, { domain: host, name: '_ga_TEST', path: '/', value: '1' }])
|
|
await page.reload()
|
|
await page.locator('[data-ipal="cookie-button"]').click()
|
|
const logged = page.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
|
|
await page.locator('[data-ipal="banner"] [data-ipal="reject"]').click()
|
|
expect((await logged).status()).toBe(201)
|
|
const names = (await context.cookies()).map((c) => c.name)
|
|
expect(names.filter((n) => n.startsWith('_ga'))).toEqual([])
|
|
expect((await consentRecord(context))!.state).toMatchObject({ analytics: false, functional: false, marketing: false })
|
|
})
|
|
|
|
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()
|
|
// the sign-in panel belongs to the sign-in screens: inside the panel it is not shown
|
|
await expect(page.locator('.iapl-signin')).toBeHidden()
|
|
})
|
|
|
|
// 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')
|
|
// Its own cookie jar. Payload takes the login cookie only from the site's own origin (csrf), so say where we are:
|
|
// without `Origin` these requests would count as anonymous and prove nothing.
|
|
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
|
|
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()
|
|
// the secret is stored (create-test-admin.ts) and never returned, also to a fully signed-in admin
|
|
expect(after.data.SiteIntegration.smtpPassword).toBe('********')
|
|
expect(JSON.stringify(after)).not.toContain('e2e-sink')
|
|
// …and it stays with the server it was saved for: moving the server without typing the password again is refused
|
|
const moved = await api.post('/api/globals/site-integrations', { data: { smtpHost: 'elsewhere.example.com' } })
|
|
expect(moved.status()).toBe(400)
|
|
expect(await moved.text()).toMatch(/Enter the password again|Wpisz hasło ponownie/)
|
|
await api.dispose()
|
|
})
|