WIP: form attachments (e-mail only) — core, endpoint, Graph large upload
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0ba0014ed5
commit
6003b3d7d7
+230
-53
@@ -2,12 +2,26 @@ import 'server-only'
|
||||
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.js'
|
||||
import type { FormValidationResult } from './validateSubmission.js'
|
||||
|
||||
import { mailAttachmentLimit } from '../email/attachmentLimit.js'
|
||||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||||
import { verifyTurnstile } from '../turnstile/verify.js'
|
||||
import { getFormAttachments } from './attachments/config.js'
|
||||
import { canCarryFiles, FORM_FILES_CONTEXT, type FormFileDelivery } from './attachments/delivery.js'
|
||||
import { checkBufferedFiles, createFileGate } from './attachments/fileGate.js'
|
||||
import { formatFileSize } from './attachments/fileTypes.js'
|
||||
import { consumeRateLimit } from './rateLimit.js'
|
||||
import { validateSubmission } from './validateSubmission.js'
|
||||
|
||||
export type SubmitFormArgs = {
|
||||
/**
|
||||
* A key the browser makes per submit attempt (16–64 letters, digits, `-`, `_`).
|
||||
* A second request with the same key returns the first outcome and sends no
|
||||
* e-mail again. Stored only with `forms.attachments`.
|
||||
*/
|
||||
attemptKey?: string
|
||||
/**
|
||||
* Name of the GDPR consent checkbox. A field with this name must be checked
|
||||
* for the submission to succeed (enforced server-side). Defaults to
|
||||
@@ -16,6 +30,11 @@ export type SubmitFormArgs = {
|
||||
consentFieldName?: string
|
||||
/** Submitted field data — shape matches the form's fields. */
|
||||
data: Record<string, unknown>
|
||||
/**
|
||||
* Files by File-field key, as whole buffers — for a project's own transfer
|
||||
* path (needs `forms.attachments`). Checked like any upload and e-mailed, never stored.
|
||||
*/
|
||||
files?: Record<string, { data: Uint8Array; name: string }[]>
|
||||
/** Form-builder form ID this submission belongs to. */
|
||||
formId: string
|
||||
/** Client IP — used for Turnstile and rate limiting. */
|
||||
@@ -59,18 +78,35 @@ export type SubmitFormArgs = {
|
||||
* at fault (absent for whole-payload problems like unknown keys)
|
||||
* - `not_found` — no form with this id
|
||||
* - `consent` — a required GDPR consent checkbox was left unchecked
|
||||
* - `delivery` — the attached file could not be sent by e-mail
|
||||
* - `error` — persistence failed unexpectedly
|
||||
*/
|
||||
export type SubmitFailure =
|
||||
| {
|
||||
/** The offending field's name, when one field is at fault. */
|
||||
field?: string
|
||||
/** The refused file's name (file_too_large, file_type). */
|
||||
file?: string
|
||||
/** What was wrong with it. */
|
||||
kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
|
||||
kind?: 'file_count' | 'file_too_large' | 'file_type' | 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
|
||||
/** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */
|
||||
label?: string
|
||||
/** The limit behind file_too_large (MB) or file_count (files). */
|
||||
max?: number
|
||||
reason: 'validation'
|
||||
success: false
|
||||
/** Accepted types, "PDF, DOCX" (file_type). */
|
||||
types?: string
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* The file could not be handed to the mail server (or the form has no
|
||||
* e-mail that may carry it). The file is gone — the visitor must send it
|
||||
* again. `submissionId`: the stored attempt, marked "Not sent".
|
||||
*/
|
||||
reason: 'delivery'
|
||||
submissionId?: number | string
|
||||
success: false
|
||||
}
|
||||
| {
|
||||
field?: string
|
||||
@@ -85,96 +121,237 @@ export type SubmitFailure =
|
||||
|
||||
export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
|
||||
|
||||
/**
|
||||
* Handles a form submission end to end: rate limit, verify Turnstile, validate
|
||||
* against the form's own schema, then store.
|
||||
*
|
||||
* The order is cost-ascending on purpose — the cheapest checks reject first, so
|
||||
* a flood never reaches Turnstile's network call or the database.
|
||||
*
|
||||
* Emails aren't sent here. The form-builder sends whatever an editor configured
|
||||
* under the form's "Emails" tab (form-submissions hook → payload.sendEmail),
|
||||
* which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.
|
||||
*
|
||||
* server-only: touches the Turnstile secret.
|
||||
*/
|
||||
export async function submitForm({
|
||||
consentFieldName,
|
||||
data,
|
||||
formId,
|
||||
/** Rate limit, then Turnstile — the two gates that need nothing but the request. `null` = passed. */
|
||||
export async function passSubmitGates({
|
||||
ip,
|
||||
locale,
|
||||
maxPerMinute = 5,
|
||||
payload,
|
||||
turnstileHostnames,
|
||||
turnstileOnConfigError = 'allow',
|
||||
turnstileToken,
|
||||
}: SubmitFormArgs): Promise<SubmitFormResult> {
|
||||
// 1. Rate limit — cheapest gate, drops a flood before any real work.
|
||||
// No IP → the limiter's shared "unknown" bucket, never a free pass.
|
||||
if (maxPerMinute > 0) {
|
||||
if (!(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) {
|
||||
return { reason: 'rate_limited', success: false }
|
||||
}
|
||||
}
|
||||
}: Pick<SubmitFormArgs, 'ip' | 'maxPerMinute' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
|
||||
return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileOnConfigError, turnstileToken }))
|
||||
}
|
||||
|
||||
// 2. Turnstile — decided by the SERVER's config, never by whether the client
|
||||
// sent a token: configured → a token is required and verified (a bot can't
|
||||
// opt out by omitting it); not configured → skipped, the widget isn't shown.
|
||||
/** 1. Rate limit — cheapest gate, drops a flood before any real work. No IP → the shared "unknown" bucket, never a free pass. */
|
||||
export async function passRateLimit({ ip, maxPerMinute = 5 }: Pick<SubmitFormArgs, 'ip' | 'maxPerMinute'>): Promise<null | SubmitFailure> {
|
||||
if (maxPerMinute > 0 && !(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) {
|
||||
return { reason: 'rate_limited', success: false }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Turnstile — decided by the SERVER's config, never by whether the client
|
||||
* sent a token: configured → a token is required and verified (a bot can't opt
|
||||
* out by omitting it); not configured → skipped, the widget isn't shown.
|
||||
*/
|
||||
export async function passTurnstile({
|
||||
ip,
|
||||
payload,
|
||||
turnstileHostnames,
|
||||
turnstileOnConfigError = 'allow',
|
||||
turnstileToken,
|
||||
}: Pick<SubmitFormArgs, 'ip' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
|
||||
if ((await getTurnstileConfig(payload)).enabled) {
|
||||
const ok =
|
||||
Boolean(turnstileToken) &&
|
||||
(await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! }))
|
||||
if (!ok) {
|
||||
return { reason: 'turnstile', success: false }
|
||||
}
|
||||
if (!ok) {return { reason: 'turnstile', success: false }}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 3. Validate against the form's schema. A public endpoint can't trust the
|
||||
// shape of `data` — drop unknown keys, enforce required, cap length.
|
||||
type ValidSubmission = Extract<FormValidationResult, { ok: true }>
|
||||
|
||||
/**
|
||||
* 3. Validate against the form's schema. A public endpoint can't trust the
|
||||
* shape of `data` — drop unknown keys, enforce required, cap length, enforce consent.
|
||||
*/
|
||||
export async function validateSubmitFields({
|
||||
consentFieldName,
|
||||
data,
|
||||
formId,
|
||||
locale,
|
||||
payload,
|
||||
}: Pick<SubmitFormArgs, 'consentFieldName' | 'data' | 'formId' | 'locale' | 'payload'>): Promise<{ failure: SubmitFailure } | { validation: ValidSubmission }> {
|
||||
// Explicit argument → ipalKit({ forms: { consentFieldName } }) → 'consent'.
|
||||
const configured = (payload.config?.custom as { ipal?: { consentFieldName?: unknown } } | undefined)?.ipal?.consentFieldName
|
||||
const consentField = consentFieldName ?? (typeof configured === 'string' && configured ? configured : undefined)
|
||||
const validation = await validateSubmission(payload, formId, data, consentField)
|
||||
if (!validation.ok) {
|
||||
if (validation.reason === 'not_found') {
|
||||
return { reason: 'not_found', success: false }
|
||||
}
|
||||
if (validation.reason === 'consent') {
|
||||
return { field: validation.field, reason: 'consent', success: false }
|
||||
}
|
||||
const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined
|
||||
return {
|
||||
if (validation.ok) {return { validation }}
|
||||
if (validation.reason === 'not_found') {return { failure: { reason: 'not_found', success: false } }}
|
||||
if (validation.reason === 'consent') {return { failure: { field: validation.field, reason: 'consent', success: false } }}
|
||||
const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined
|
||||
return {
|
||||
failure: {
|
||||
reason: 'validation',
|
||||
success: false,
|
||||
...(validation.field ? { field: validation.field } : {}),
|
||||
...(validation.kind ? { kind: validation.kind } : {}),
|
||||
...(label ? { label } : {}),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Persist (form-builder shape: submissionData array). Triggers the email
|
||||
// hook. Only validated, known fields are stored.
|
||||
/** A refused file as a submit failure, with the field's label for the message. */
|
||||
export async function fileFailure(payload: BasePayload, formId: string, failure: FormFileFailure, locale?: string): Promise<SubmitFailure> {
|
||||
if (failure.kind === 'unknown_fields') {return { kind: 'unknown_fields', reason: 'validation', success: false }}
|
||||
const label = await fieldLabel(payload, formId, failure.field, locale)
|
||||
return {
|
||||
field: failure.field,
|
||||
kind: failure.kind,
|
||||
reason: 'validation',
|
||||
success: false,
|
||||
...(failure.file ? { file: failure.file } : {}),
|
||||
...(label ? { label } : {}),
|
||||
...(failure.max !== undefined ? { max: failure.max } : {}),
|
||||
...(failure.types ? { types: failure.types } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
const ATTEMPT_KEY = /^[\w-]{16,64}$/
|
||||
|
||||
/** A usable attempt key, or undefined. */
|
||||
export const cleanAttemptKey = (key: unknown): string | undefined => (typeof key === 'string' && ATTEMPT_KEY.test(key) ? key : undefined)
|
||||
|
||||
/**
|
||||
* The outcome of an earlier request with this attempt key, when one was stored —
|
||||
* a repeated request (double click, a proxy or browser resend) gets the first
|
||||
* answer and sends nothing again. Only with `forms.attachments` (the field exists then).
|
||||
*/
|
||||
export async function findSubmitAttempt(payload: BasePayload, attemptKey: string | undefined): Promise<null | SubmitFormResult> {
|
||||
if (!attemptKey || !getFormAttachments(payload)) {return null}
|
||||
try {
|
||||
const found = await payload.find({
|
||||
collection: 'form-submissions',
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
where: { attemptKey: { equals: attemptKey } },
|
||||
} as never)
|
||||
const doc = found.docs[0] as { filesDelivery?: string; id: number | string } | undefined
|
||||
if (!doc) {return null}
|
||||
return doc.filesDelivery === 'failed' ? { reason: 'delivery', submissionId: doc.id, success: false } : { submissionId: doc.id, success: true }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Persist (form-builder shape: submissionData array). Triggers the e-mail
|
||||
* hook. Only validated, known fields are stored.
|
||||
*
|
||||
* Files are NOT stored. They ride in the request context to the e-mail hook
|
||||
* (attachments/delivery), which attaches them to the company e-mail; the
|
||||
* submission keeps their name, type and size and whether the mail server took them.
|
||||
*/
|
||||
export async function storeSubmission({
|
||||
attemptKey,
|
||||
files = [],
|
||||
formId,
|
||||
locale,
|
||||
payload,
|
||||
validation,
|
||||
}: {
|
||||
attemptKey?: string
|
||||
/** Files that passed the file gate. */
|
||||
files?: AcceptedFormFile[]
|
||||
validation: ValidSubmission
|
||||
} & Pick<SubmitFormArgs, 'formId' | 'locale' | 'payload'>): Promise<SubmitFormResult> {
|
||||
const attachments = getFormAttachments(payload)
|
||||
const delivery: FormFileDelivery | undefined = files.length ? { files } : undefined
|
||||
const text = (value: unknown) =>
|
||||
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
|
||||
value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string)
|
||||
// Rows in the form's field order; a File field's row is "CV.pdf (2.1 MB)".
|
||||
const rows: { field: string; value: string }[] = []
|
||||
for (const field of validation.form.fields ?? []) {
|
||||
if (typeof field.name !== 'string') {continue}
|
||||
if (field.name in validation.cleaned) {rows.push({ field: field.name, value: text(validation.cleaned[field.name]) })}
|
||||
const own = files.filter((f) => f.field === field.name)
|
||||
if (own.length) {rows.push({ field: field.name, value: own.map((f) => `${f.name} (${formatFileSize(f.size)})`).join(', ') })}
|
||||
}
|
||||
try {
|
||||
const submission = await payload.create({
|
||||
collection: 'form-submissions',
|
||||
...(locale ? { locale: locale as never } : {}),
|
||||
...(delivery ? { context: { [FORM_FILES_CONTEXT]: delivery } } : {}),
|
||||
data: {
|
||||
form: formId,
|
||||
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
|
||||
field,
|
||||
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
|
||||
value: value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
|
||||
})),
|
||||
submissionData: rows,
|
||||
...(attachments && attemptKey ? { attemptKey } : {}),
|
||||
// "Not sent" until the mail server has taken the message — a crash in between must not read as sent.
|
||||
...(delivery ? { filesDelivery: 'failed', submissionFiles: files.map((f) => ({ name: f.name, type: f.type, field: f.field, size: f.size })) } : {}),
|
||||
} as never,
|
||||
})
|
||||
return { submissionId: submission.id, success: true }
|
||||
if (!delivery) {return { submissionId: submission.id, success: true }}
|
||||
|
||||
const result = delivery.result ?? { note: 'No e-mail was sent for this form.', state: 'failed' as const }
|
||||
try {
|
||||
await payload.update({
|
||||
id: submission.id,
|
||||
collection: 'form-submissions',
|
||||
data: { filesDelivery: result.state, filesDeliveryNote: result.note ?? '' } as never,
|
||||
depth: 0,
|
||||
})
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`)
|
||||
}
|
||||
return result.state === 'sent' ? { submissionId: submission.id, success: true } : { reason: 'delivery', submissionId: submission.id, success: false }
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
|
||||
return { reason: 'error', success: false }
|
||||
} finally {
|
||||
// The buffers are not needed past this point — drop the references now.
|
||||
if (delivery) {delivery.files = []}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a form submission end to end: rate limit, verify Turnstile, validate
|
||||
* against the form's own schema, check the files, then store and e-mail.
|
||||
*
|
||||
* The order is cost-ascending on purpose — the cheapest checks reject first, so
|
||||
* a flood never reaches Turnstile's network call or the database.
|
||||
*
|
||||
* Emails aren't composed here. The form-builder sends whatever an editor
|
||||
* configured under the form's "Emails" tab (form-submissions hook →
|
||||
* payload.sendEmail), over the configured email adapter (mailAdapter).
|
||||
*
|
||||
* `files` (whole buffers) is for a project's own transfer path; panel forms
|
||||
* send files to the streaming endpoint (attachments/endpoint), which runs
|
||||
* these same stages around the read.
|
||||
*
|
||||
* server-only: touches the Turnstile secret.
|
||||
*/
|
||||
export async function submitForm(args: SubmitFormArgs): Promise<SubmitFormResult> {
|
||||
const { attemptKey: rawKey, files, formId, locale, payload } = args
|
||||
const blocked = await passSubmitGates(args)
|
||||
if (blocked) {return blocked}
|
||||
|
||||
const checked = await validateSubmitFields(args)
|
||||
if ('failure' in checked) {return checked.failure}
|
||||
const { validation } = checked
|
||||
|
||||
const attemptKey = cleanAttemptKey(rawKey)
|
||||
const repeated = await findSubmitAttempt(payload, attemptKey)
|
||||
if (repeated) {return repeated}
|
||||
|
||||
const hasFiles = Object.values(files ?? {}).some((list) => list.length > 0)
|
||||
const attachments = getFormAttachments(payload)
|
||||
if (!attachments || (!hasFiles && validation.fileFields.length === 0)) {
|
||||
// A file without the feature (or without a File field) is an unknown field.
|
||||
if (hasFiles) {return { kind: 'unknown_fields', reason: 'validation', success: false }}
|
||||
return storeSubmission({ attemptKey, formId, locale, payload, validation })
|
||||
}
|
||||
|
||||
if (hasFiles && !canCarryFiles(validation.form)) {return { reason: 'delivery', success: false }}
|
||||
const gate = createFileGate({ fields: validation.fileFields, options: attachments, transportMaxBytes: await mailAttachmentLimit(payload) })
|
||||
const refused = await checkBufferedFiles(gate, files ?? {})
|
||||
if (refused) {return fileFailure(payload, formId, refused, locale)}
|
||||
return storeSubmission({ attemptKey, files: gate.accepted, formId, locale, payload, validation })
|
||||
}
|
||||
|
||||
/**
|
||||
* The label of one form field in the page's language, so a message names the
|
||||
* field the way the visitor sees it ("E-mail address", not "email"). Only read
|
||||
|
||||
Reference in New Issue
Block a user