// Shared submit handler for any runtime with Request, Response and fetch. export interface CoreFormsConfig { upstream?: string; // https://cms.example.com/wp-json/core-forms/v1 formId?: string; // 123 apiKey?: string; // cf_... allowedOrigins?: string; // https://www.example.com,https://example.com } const MAX_BYTES = 16 * 1024; function fail(status: number, message: string): Response { return new Response(JSON.stringify({ message }), { status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, }); } export async function submitToCoreForms( request: Request, config: CoreFormsConfig, ): Promise { if (request.method !== 'POST') return fail(405, 'Method not allowed.'); const { upstream, formId, apiKey, allowedOrigins } = config; if (!upstream || !formId || !apiKey || !allowedOrigins) { return fail(503, 'The form proxy is not configured.'); } const origins = allowedOrigins.split(',').map((item) => item.trim()).filter(Boolean); if (!origins.includes(request.headers.get('origin') ?? '')) { return fail(403, 'This origin is not allowed.'); } // A soft signal that drops the laziest scripts. A captcha does the real work. const userAgent = request.headers.get('user-agent') ?? ''; if (!/mozilla|safari|chrome|firefox/i.test(userAgent)) { return fail(403, 'Submission blocked.'); } if (Number(request.headers.get('content-length') ?? 0) > MAX_BYTES) { return fail(413, 'Submission too large.'); } const body = await request.arrayBuffer(); if (body.byteLength > MAX_BYTES) return fail(413, 'Submission too large.'); const type = request.headers.get('content-type') ?? ''; let payload: unknown; try { if (type.includes('application/json')) { payload = JSON.parse(new TextDecoder().decode(body)); } else { // Accept text fields from a normal HTML form post as well. const form = await new Response(body, { headers: { 'Content-Type': type } }).formData(); const fields = new Map(); form.forEach((value, name) => { if (typeof value !== 'string') return; const previous = fields.get(name); fields.set(name, previous === undefined ? value : ([] as string[]).concat(previous, value)); }); payload = Object.fromEntries(fields); } } catch { return fail(400, 'Could not read the submission.'); } if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { return fail(400, 'Send the fields as a JSON object.'); } const isPlain = (value: unknown) => value === null || typeof value !== 'object'; for (const value of Object.values(payload)) { if (!(Array.isArray(value) ? value.every(isPlain) : isPlain(value))) { return fail(400, 'Send text, numbers or lists only.'); } } // Always submit to the configured form, whatever the browser sent. (payload as Record).id = formId; let response: Response; let result: string; try { response = await fetch( `${upstream.replace(/\/$/, '')}/forms/${encodeURIComponent(formId)}/submit`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Core-Forms-Key': apiKey, 'User-Agent': userAgent, }, body: JSON.stringify(payload), redirect: 'manual', signal: AbortSignal.timeout(15000), }, ); result = await response.text(); } catch { return fail(502, 'The form server could not be reached.'); } // A redirect, firewall page or PHP error is not a form response. if (!(response.headers.get('content-type') ?? '').includes('application/json')) { return fail(502, 'The form server returned an unexpected response.'); } return new Response(result, { status: response.status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, }); }