Files
ipal-kit/dist/modules/forms/submitForm.js
T
2026-10-15 15:53:32 +02:00

99 lines
3.4 KiB
JavaScript

import 'server-only';
import { verifyTurnstile } from '../turnstile/index.js';
import { validateSubmission } from './validateSubmission.js';
import { checkRateLimit } from './rateLimit.js';
/**
* 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({ payload, formId, data, turnstileToken, ip, maxPerMinute = 5, consentFieldName, turnstileOnConfigError = 'allow' }) {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
if (maxPerMinute > 0 && ip) {
if (!checkRateLimit({
key: ip,
max: maxPerMinute
})) {
return {
success: false,
reason: 'rate_limited'
};
}
}
// 2. Turnstile — verify when a token is supplied; reject on failure.
if (turnstileToken !== undefined) {
const ok = await verifyTurnstile({
token: turnstileToken,
payload,
ip,
onConfigError: turnstileOnConfigError
});
if (!ok) {
return {
success: false,
reason: 'turnstile'
};
}
}
// 3. Validate against the form's schema. A public endpoint can't trust the
// shape of `data` — drop unknown keys, enforce required, cap length.
const validation = await validateSubmission(payload, formId, data, consentFieldName);
if (!validation.ok) {
if (validation.reason === 'not_found') {
return {
success: false,
reason: 'not_found'
};
}
if (validation.reason === 'consent') {
return {
success: false,
reason: 'consent',
field: validation.field
};
}
return {
success: false,
reason: 'validation',
...validation.field ? {
field: validation.field
} : {},
...validation.kind ? {
kind: validation.kind
} : {}
};
}
// 4. Persist (form-builder shape: submissionData array). Triggers the email
// hook. Only validated, known fields are stored.
try {
const submission = await payload.create({
collection: 'form-submissions',
data: {
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value])=>({
field,
value: value == null ? '' : String(value)
}))
}
});
return {
success: true,
submissionId: submission.id
};
} catch (err) {
payload.logger.error(`[ipal] Form submission failed: ${err.message}`);
return {
success: false,
reason: 'error'
};
}
}
//# sourceMappingURL=submitForm.js.map