WIP: reference site — File field on the quote form, mail sink smoke test

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:34:34 +01:00
co-authored by Claude Fable 5.2
parent b7fb1b0e31
commit 387debc88c
8 changed files with 170 additions and 4 deletions
+12 -1
View File
@@ -3,7 +3,8 @@
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md).
* never create users (docs/seeding.md). It also points e-mail sending at the tests' local mail sink
* (E2E_SMTP_PORT, default 2526).
*/
import config from '@payload-config'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
@@ -23,4 +24,14 @@ if (found.docs[0]) {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
await payload.updateGlobal({
slug: 'site-integrations',
data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
overrideAccess: true,
})
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
process.exit(0)
+67
View File
@@ -1,5 +1,6 @@
import { expect, type Page, test } from '@playwright/test'
import { attachmentOf, startSmtpSink } from './smtp-sink'
import { totp } from './totp'
/**
@@ -66,6 +67,72 @@ for (const l of LOCALES) {
})
}
// 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('plan.exe')
// 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' })
await expect(form.locator('input[name="cf-turnstile-response"]')).not.toHaveValue('', { timeout: 15_000 })
await form.locator('button[type="submit"]').click()
await expect(form.locator('[id$="attachment-error"]')).toContainText('not an accepted file type', { timeout: 15_000 })
expect(sink.messages).toHaveLength(0)
// the real file
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')
await expect(form.locator('input[name="cf-turnstile-response"]')).not.toHaveValue('', { timeout: 15_000 })
const posted = page.waitForResponse((r) => r.url().includes('/api/ipal/forms/submit') && r.request().method() === 'POST')
await form.locator('button[type="submit"]').click()
expect((await posted).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)
+64
View File
@@ -0,0 +1,64 @@
import { createServer, type Server } from 'node:net'
export type SinkMessage = { data: string; to: string[] }
/**
* A mail sink for the smoke tests: just enough SMTP for nodemailer to log in and deliver. It keeps every
* message in memory, so a test can read what the site really sent (recipients, attachments).
* e2e/create-test-admin.ts points Site integrations → E-mail sending at it (127.0.0.1:E2E_SMTP_PORT).
*/
export function startSmtpSink(port: number): Promise<{ close: () => Promise<void>; messages: SinkMessage[] }> {
const messages: SinkMessage[] = []
const server: Server = createServer((socket) => {
const mail: SinkMessage = { data: '', to: [] }
let inData = false
let buffer = ''
const reply = (line: string) => socket.write(`${line}\r\n`)
reply('220 localhost ESMTP smoke-sink')
socket.on('error', () => undefined)
socket.on('data', (chunk) => {
buffer += chunk.toString('latin1')
let index: number
while ((index = buffer.indexOf('\r\n')) >= 0) {
const line = buffer.slice(0, index)
buffer = buffer.slice(index + 2)
if (inData) {
if (line === '.') {
inData = false
messages.push({ ...mail, to: [...mail.to] })
reply('250 2.0.0 Ok: queued')
} else {
mail.data += `${line}\n`
}
continue
}
const command = line.toUpperCase()
if (command.startsWith('EHLO')) {socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')}
else if (command.startsWith('AUTH PLAIN')) {reply('235 2.7.0 Authentication successful')}
else if (command.startsWith('MAIL FROM:')) {reply('250 2.1.0 Ok')}
else if (command.startsWith('RCPT TO:')) {
mail.to.push(line.slice(8).trim())
reply('250 2.1.5 Ok')
} else if (command === 'DATA') {
inData = true
reply('354 End data with <CR><LF>.<CR><LF>')
} else if (command === 'QUIT') {
reply('221 2.0.0 Bye')
socket.end()
} else {reply('502 5.5.2 Command not recognized')}
}
})
})
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => resolve({ close: () => new Promise((done) => server.close(() => done())), messages }))
})
}
/** The decoded bytes of the attachment named `filename` in a raw message, or null. */
export function attachmentOf(raw: string, filename: string): Buffer | null {
const at = raw.indexOf(`filename=${filename}`) >= 0 ? raw.indexOf(`filename=${filename}`) : raw.indexOf(`filename="${filename}"`)
if (at < 0) {return null}
const body = raw.slice(raw.indexOf('\n\n', at) + 2)
return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64')
}