From 387debc88cb40a38598e2c3cd73c72eea18ae008 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Fri, 13 Nov 2026 16:34:34 +0100 Subject: [PATCH] =?UTF-8?q?WIP:=20reference=20site=20=E2=80=94=20File=20fi?= =?UTF-8?q?eld=20on=20the=20quote=20form,=20mail=20sink=20smoke=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- reference/.env.example | 2 + reference/e2e/create-test-admin.ts | 13 +++- reference/e2e/smoke.spec.ts | 67 +++++++++++++++++++ reference/e2e/smtp-sink.ts | 64 ++++++++++++++++++ reference/src/components/forms/formClasses.ts | 5 ++ reference/src/payload.config.ts | 7 +- reference/src/seed/demo.ts | 4 +- reference/src/seed/forms.ts | 12 ++++ 8 files changed, 170 insertions(+), 4 deletions(-) create mode 100644 reference/e2e/smtp-sink.ts diff --git a/reference/.env.example b/reference/.env.example index 6a1e7c2..0936964 100644 --- a/reference/.env.example +++ b/reference/.env.example @@ -56,4 +56,6 @@ INDEXNOW_KEY= E2E_ADMIN_EMAIL=e2e-admin@example.com E2E_ADMIN_PASSWORD=e2e-RC2nC29eKC8HJHfg E2E_TOTP_SECRET=JPURUZNWYTZX2L42MT4SS7736WWNQWBL +# Port of the mail sink the smoke tests start (e2e/smtp-sink.ts); create-test-admin.ts points e-mail sending at it +E2E_SMTP_PORT=2526 # @starter:endif diff --git a/reference/e2e/create-test-admin.ts b/reference/e2e/create-test-admin.ts index ff5b59f..7907b60 100644 --- a/reference/e2e/create-test-admin.ts +++ b/reference/e2e/create-test-admin.ts @@ -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: 'site@example-studio.test', 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) diff --git a/reference/e2e/smoke.spec.ts b/reference/e2e/smoke.spec.ts index c5cc42e..68eff56 100644 --- a/reference/e2e/smoke.spec.ts +++ b/reference/e2e/smoke.spec.ts @@ -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> + 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('smoke@example.com') + 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('smoke@example.com'))! + const customer = sink.messages.find((m) => m.to.join().includes('smoke@example.com'))! + 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>/g)].map((m) => new URL(m[1]).pathname) diff --git a/reference/e2e/smtp-sink.ts b/reference/e2e/smtp-sink.ts new file mode 100644 index 0000000..2a067c3 --- /dev/null +++ b/reference/e2e/smtp-sink.ts @@ -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; 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 .') + } 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') +} diff --git a/reference/src/components/forms/formClasses.ts b/reference/src/components/forms/formClasses.ts index 06b923c..f381a10 100644 --- a/reference/src/components/forms/formClasses.ts +++ b/reference/src/components/forms/formClasses.ts @@ -17,6 +17,11 @@ export const formClasses: BuilderFormClassNames = { fields: 'grid grid-cols-12 gap-4', form: 'grid gap-6', formError: 'rounded-control bg-danger-surface p-3 text-danger', + file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong', + fileItem: 'flex flex-wrap items-center gap-2', + fileList: 'mt-2 grid gap-1 text-sm', + fileRemove: 'underline underline-offset-2', + help: 'mt-1 text-sm text-fg-muted', input: control, label: 'mb-1 block font-medium text-fg-strong', legend: 'mb-1 font-medium text-fg-strong', diff --git a/reference/src/payload.config.ts b/reference/src/payload.config.ts index b1869dd..ea30d28 100644 --- a/reference/src/payload.config.ts +++ b/reference/src/payload.config.ts @@ -69,7 +69,12 @@ export default buildConfig({ // @starter:endif ], }, - forms: { redirectRelationships: ['pages'], emailLayout: true }, + // @starter:if demo + // attachments: the Quote form takes floor plans and photos — e-mailed to the studio, never stored (forms.md "Files") + forms: { attachments: true, emailLayout: true, redirectRelationships: ['pages'] }, + // @starter:else + //: forms: { redirectRelationships: ['pages'], emailLayout: true }, // files on forms: add `attachments: true` (forms.md "Files") + // @starter:endif // @starter:if twoFactor twoFactor: { issuer: 'Example Studio', plugin: payloadTotp }, // @starter:else diff --git a/reference/src/seed/demo.ts b/reference/src/seed/demo.ts index 93b057e..d048623 100644 --- a/reference/src/seed/demo.ts +++ b/reference/src/seed/demo.ts @@ -240,8 +240,8 @@ export async function seedDemoPages(seed: Seeder, media: Record) { blockType: 'richText', content: rich( - ['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, wspomnij o nich w formularzu — poprosimy o pliki w odpowiedzi. Wycena jest bezpłatna i do niczego nie zobowiązuje.'], - ['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, mention them in the form — we will ask for the files in our reply. The quote is free and commits you to nothing.'], + ['Wycena obejmuje zakres prac, podział na etapy, harmonogram i warunki płatności. Im więcej wiemy na starcie, tym dokładniejsza będzie: podaj lokalizację, przybliżoną powierzchnię, rodzaj budynku albo wnętrza i planowany termin rozpoczęcia. Jeśli masz rzuty, zdjęcia, mapę do celów projektowych albo wypis z planu miejscowego, dołącz je w formularzu (PDF, JPG lub PNG). Wycena jest bezpłatna i do niczego nie zobowiązuje.'], + ['The quote covers the scope of work, the stages, the schedule and the payment terms. The more we know at the start, the more precise it is: tell us the location, the rough floor area, the type of building or interior and when you plan to start. If you have floor plans, photos, a survey map or an extract from the local plan, attach them in the form (PDF, JPG or PNG). The quote is free and commits you to nothing.'], ), variant: 'narrow', }, diff --git a/reference/src/seed/forms.ts b/reference/src/seed/forms.ts index 6428092..99ee940 100644 --- a/reference/src/seed/forms.ts +++ b/reference/src/seed/forms.ts @@ -84,6 +84,18 @@ export async function seedForms(seed: Seeder, notifyTo: string) { required: true, }, { blockType: 'date', label: tx('Planowany start', 'Planned start'), name: 'start' }, + // @starter:if demo + // A File field (forms: { attachments: true }): sent with the notification to the studio, never stored on the site. + { + allowedTypes: ['pdf', 'jpg', 'png'], + blockType: 'file', + help: tx('Rzuty, zdjęcia lub mapa: PDF, JPG lub PNG, razem do 10 MB.', 'Floor plans, photos or a map: PDF, JPG or PNG, up to 10 MB together.'), + label: tx('Załączniki (opcjonalnie)', 'Attachments (optional)'), + maxFiles: 3, + maxSizeMB: 10, + name: 'attachment', + }, + // @starter:endif { blockType: 'message', message: rich(tx('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.', 'We use your data only to prepare the quote.')) }, consent, ],