From 463fd5d664d197fa5e208a930d05a5ff3d46b493 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 22:13:16 +0100 Subject: [PATCH] =?UTF-8?q?M1=20(4):=20forms.turnstileOnConfigError=20?= =?UTF-8?q?=E2=80=94=20a=20form=20with=20files=20is=20refused=20while=20Tu?= =?UTF-8?q?rnstile=20cannot=20check?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While Turnstile is degraded (wrong or missing secret, Cloudflare down) a text form is still accepted, as before; a submission to the file endpoint is refused by default. forms.turnstileOnConfigError sets it for every form or per kind ('allow' | 'reject' | { text, files }); a value at a call site still wins. Nothing changes when Turnstile is off. The gates and the resolver are exported from the server entry. Co-Authored-By: Claude Fable 5.2 --- src/exports/server.ts | 2 + src/modules/forms/attachments/config.ts | 1 + .../forms/attachments/submitHandler.ts | 3 +- src/modules/forms/submitForm.ts | 46 ++++++-- src/modules/forms/types.ts | 14 +++ src/plugin.ts | 5 + test/m1Turnstile.test.ts | 108 ++++++++++++++++++ 7 files changed, 170 insertions(+), 9 deletions(-) create mode 100644 test/m1Turnstile.test.ts diff --git a/src/exports/server.ts b/src/exports/server.ts index 6a5652a..915cef9 100644 --- a/src/exports/server.ts +++ b/src/exports/server.ts @@ -4,6 +4,8 @@ export { createSubmitAction, splitFormFiles } from '../modules/forms/createSubmi export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js' export { submitForm } from '../modules/forms/index.js' export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js' +export { passSubmitGates, passTurnstile, resolveTurnstileOnConfigError, TURNSTILE_ON_CONFIG_ERROR_DEFAULT } from '../modules/forms/submitForm.js' +export type { TurnstileFormKind, TurnstileOnConfigError, TurnstileOnConfigErrorOption } from '../modules/forms/submitForm.js' /** * Entry point: ipal-kit/server * diff --git a/src/modules/forms/attachments/config.ts b/src/modules/forms/attachments/config.ts index 7a5af65..fc384ed 100644 --- a/src/modules/forms/attachments/config.ts +++ b/src/modules/forms/attachments/config.ts @@ -84,6 +84,7 @@ export type FormSubmitEndpointOptions = { */ timeoutMs?: number turnstileHostnames?: string[] + /** While Turnstile cannot check: unset = `forms.turnstileOnConfigError`, else `'reject'` (this endpoint carries files). */ turnstileOnConfigError?: 'allow' | 'reject' } diff --git a/src/modules/forms/attachments/submitHandler.ts b/src/modules/forms/attachments/submitHandler.ts index 5ab249d..35f4e56 100644 --- a/src/modules/forms/attachments/submitHandler.ts +++ b/src/modules/forms/attachments/submitHandler.ts @@ -220,7 +220,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise { const { [honeypot]: _honeypot, ...answers } = data const token = fields._token?.trim() || undefined - const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token }) + // a form that can carry files: while Turnstile cannot check, refused by default (forms.turnstileOnConfigError) + const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileKind: 'files', turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token }) if (settled) {return} if (blocked) {return stop(blocked)} diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 01fb9d4..3365771 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -51,8 +51,10 @@ export type SubmitFormArgs = { turnstileHostnames?: string[] /** * Turnstile can't be verified because of OUR side (missing/wrong secret, - * Cloudflare unreachable): 'allow' (default) accepts the submission and shows - * the problem in the panel; 'reject' refuses it. + * Cloudflare unreachable): 'allow' accepts the submission and shows the + * problem in the panel; 'reject' refuses it. Unset = the plugin option + * `forms.turnstileOnConfigError`, else the default for the kind of form + * (text: 'allow'; a form with files: 'reject'). */ turnstileOnConfigError?: 'allow' | 'reject' /** @@ -128,16 +130,42 @@ export type SubmitFailure = export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure +/** What a form does while Turnstile cannot check (wrong or missing secret, Cloudflare down). */ +export type TurnstileOnConfigError = 'allow' | 'reject' +/** Which kind of form asks: one that only carries text, or one that can carry files (the file endpoint). */ +export type TurnstileFormKind = 'files' | 'text' +/** `forms.turnstileOnConfigError`: one answer for every form, or one per kind. */ +export type TurnstileOnConfigErrorOption = { files?: TurnstileOnConfigError; text?: TurnstileOnConfigError } | TurnstileOnConfigError + +/** Defaults: a text form keeps working (the enquiry matters more than spam); a form with files does not. */ +export const TURNSTILE_ON_CONFIG_ERROR_DEFAULT: Record = { files: 'reject', text: 'allow' } + +/** + * The policy for one submission: the value given at the call site, else the plugin option + * `forms.turnstileOnConfigError` (one value, or per kind), else the default for the kind. + */ +export function resolveTurnstileOnConfigError( + payload: { config?: { custom?: unknown } } | null | undefined, + kind: TurnstileFormKind = 'text', + explicit?: TurnstileOnConfigError, +): TurnstileOnConfigError { + if (explicit === 'allow' || explicit === 'reject') {return explicit} + const option = (payload?.config?.custom as { ipal?: { forms?: { turnstileOnConfigError?: TurnstileOnConfigErrorOption } } } | undefined)?.ipal?.forms?.turnstileOnConfigError + const fromOption = typeof option === 'string' ? option : option?.[kind] + return fromOption === 'allow' || fromOption === 'reject' ? fromOption : TURNSTILE_ON_CONFIG_ERROR_DEFAULT[kind] +} + /** Rate limit, then Turnstile — the two gates that need nothing but the request. `null` = passed. */ export async function passSubmitGates({ ip, maxPerMinute = 5, payload, turnstileHostnames, - turnstileOnConfigError = 'allow', + turnstileKind, + turnstileOnConfigError, turnstileToken, -}: Pick): Promise { - return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileOnConfigError, turnstileToken })) +}: { turnstileKind?: TurnstileFormKind } & Pick): Promise { + return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileKind, turnstileOnConfigError, turnstileToken })) } /** 1. Rate limit — cheapest gate, drops a flood before any real work. No IP → the shared "unknown" bucket, never a free pass. */ @@ -157,13 +185,15 @@ export async function passTurnstile({ ip, payload, turnstileHostnames, - turnstileOnConfigError = 'allow', + turnstileKind = 'text', + turnstileOnConfigError, turnstileToken, -}: Pick): Promise { +}: { turnstileKind?: TurnstileFormKind } & Pick): Promise { if ((await getTurnstileConfig(payload)).enabled) { + const onConfigError = resolveTurnstileOnConfigError(payload, turnstileKind, turnstileOnConfigError) const ok = Boolean(turnstileToken) && - (await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! })) + (await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError, payload, token: turnstileToken! })) if (!ok) {return { reason: 'turnstile', success: false }} } return null diff --git a/src/modules/forms/types.ts b/src/modules/forms/types.ts index 24c372e..4080a29 100644 --- a/src/modules/forms/types.ts +++ b/src/modules/forms/types.ts @@ -2,6 +2,7 @@ import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types' import type { Block, CollectionConfig, Field } from 'payload' import type { FormAttachmentsOption } from './attachments/config.js' +import type { TurnstileOnConfigErrorOption } from './submitForm.js' /** * Receives the collection's default fields and returns the final list — add, @@ -93,4 +94,17 @@ export type FormsOption = { formSubmissionOverrides?: FormsCollectionOverrides /** Collections a form can redirect to (e.g. ['pages']). */ redirectRelationships?: string[] + /** + * What a form does while Turnstile CANNOT check — the secret is missing or + * wrong, Cloudflare is down (the "degraded" state, shown in Site + * integrations and by ipal-doctor). Default: a text form is accepted + * (`'allow'`: an enquiry matters more than spam), a form that can carry + * files — the file endpoint — is refused (`'reject'`: an accepted bot + * submission would put an attachment into a mailbox). + * One value for every form, or one per kind: + * `'reject'`, `'allow'`, `{ text: 'allow', files: 'allow' }`. + * A value passed at a call site (`createSubmitAction`, `attachments.submit`) + * still wins. Not involved when Turnstile is off (no keys). docs/turnstile.md. + */ + turnstileOnConfigError?: TurnstileOnConfigErrorOption } diff --git a/src/plugin.ts b/src/plugin.ts index 681ab6d..6b7a962 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -587,6 +587,11 @@ export const ipalKit = (options: IpalOptions): Plugin => { if (options.forms.consentFieldName) { config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, consentFieldName: options.forms.consentFieldName } } } + // what a form does while Turnstile cannot check — read by passTurnstile when the call site gives none + if (options.forms.turnstileOnConfigError) { + const ipal = (config.custom?.ipal ?? {}) as { forms?: object } + config.custom = { ...config.custom, ipal: { ...ipal, forms: { ...ipal.forms, turnstileOnConfigError: options.forms.turnstileOnConfigError } } } + } } // --- globals --- diff --git a/test/m1Turnstile.test.ts b/test/m1Turnstile.test.ts new file mode 100644 index 0000000..b2daa7a --- /dev/null +++ b/test/m1Turnstile.test.ts @@ -0,0 +1,108 @@ +/** + * M1: what a form does while Turnstile cannot check (forms.turnstileOnConfigError). + * Cloudflare is the mocked `fetch`; the rest is the real gate code. + */ +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { passTurnstile, resolveTurnstileOnConfigError, TURNSTILE_ON_CONFIG_ERROR_DEFAULT } from '../src/modules/forms/submitForm.js' +import { ipalKit } from '../src/plugin.js' + +vi.mock('server-only', () => ({})) + +type Option = 'allow' | 'reject' | { files?: 'allow' | 'reject'; text?: 'allow' | 'reject' } | undefined +const payloadWith = (integrations: Record, option?: Option) => ({ + config: { custom: { ipal: { forms: option ? { turnstileOnConfigError: option } : {} } }, globals: [{ slug: 'site-integrations' }] }, + findGlobal: async () => integrations, + logger: { error: () => undefined, info: () => undefined, warn: () => undefined }, + updateGlobal: async () => ({}), +}) +const KEYS = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' } +const cloudflare = (body: unknown, status = 200) => vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(body), { status }))) +const gate = (kind: 'files' | 'text' | undefined, option?: Option, explicit?: 'allow' | 'reject', integrations: Record = KEYS, token: string | undefined = 'token') => + passTurnstile({ ip: '1.2.3.4', payload: payloadWith(integrations, option) as never, turnstileKind: kind, turnstileOnConfigError: explicit, turnstileToken: token }) +const REFUSED = { reason: 'turnstile', success: false } + +afterEach(() => { + vi.unstubAllGlobals() + vi.unstubAllEnvs() + vi.restoreAllMocks() +}) + +describe('forms.turnstileOnConfigError', () => { + test('the policy: call site, then the plugin option, then the default for the kind', () => { + expect(TURNSTILE_ON_CONFIG_ERROR_DEFAULT).toEqual({ files: 'reject', text: 'allow' }) + const p = (option?: Option) => payloadWith(KEYS, option) + expect(resolveTurnstileOnConfigError(p(), 'text')).toBe('allow') + expect(resolveTurnstileOnConfigError(p(), 'files')).toBe('reject') + expect(resolveTurnstileOnConfigError(p(), undefined)).toBe('allow') // a caller that says nothing is a text form, as before + expect(resolveTurnstileOnConfigError(p('reject'), 'text')).toBe('reject') + expect(resolveTurnstileOnConfigError(p('allow'), 'files')).toBe('allow') + expect(resolveTurnstileOnConfigError(p({ files: 'allow' }), 'files')).toBe('allow') + expect(resolveTurnstileOnConfigError(p({ files: 'allow' }), 'text')).toBe('allow') + expect(resolveTurnstileOnConfigError(p({ text: 'reject' }), 'files')).toBe('reject') + expect(resolveTurnstileOnConfigError(p('reject'), 'text', 'allow')).toBe('allow') // the call site wins + expect(resolveTurnstileOnConfigError(p('allow'), 'files', 'reject')).toBe('reject') + expect(resolveTurnstileOnConfigError(p('nonsense' as never), 'files')).toBe('reject') // an unknown value never loosens + expect(resolveTurnstileOnConfigError(null, 'files')).toBe('reject') + }) + + test.each([ + ['Cloudflare rejects the secret', { 'error-codes': ['invalid-input-secret'], success: false }, 200], + ['Cloudflare answers 500', {}, 500], + ['an answer nobody understands', { hello: 1 }, 200], + ])('%s: a text form is accepted, a form with files is refused', async (_name, body, status) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + cloudflare(body, status) + expect(await gate('text')).toBeNull() + expect(await gate(undefined)).toBeNull() + expect(await gate('files')).toEqual(REFUSED) + }) + + test('the network fails: the same', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNRESET') })) + expect(await gate('text')).toBeNull() + expect(await gate('files')).toEqual(REFUSED) + }) + + test('the plugin option and the call site change it, each way', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + cloudflare({ 'error-codes': ['invalid-input-secret'], success: false }) + expect(await gate('text', 'reject')).toEqual(REFUSED) + expect(await gate('files', 'allow')).toBeNull() + expect(await gate('files', { files: 'allow' })).toBeNull() + expect(await gate('text', { files: 'allow' })).toBeNull() + expect(await gate('files', undefined, 'allow')).toBeNull() + expect(await gate('text', 'allow', 'reject')).toEqual(REFUSED) + }) + + test('not touched by the policy: a valid token passes, a bad token and a missing token are refused, for both kinds', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + cloudflare({ success: true }) + expect(await gate('text')).toBeNull() + expect(await gate('files')).toBeNull() + cloudflare({ 'error-codes': ['invalid-input-response'], success: false }) + expect(await gate('text', 'allow')).toEqual(REFUSED) + expect(await gate('files', 'allow')).toEqual(REFUSED) + expect(await gate('files', 'allow', undefined, KEYS, undefined)).toEqual(REFUSED) + }) + + test('Turnstile off (no keys): nothing is checked, forms with files included', async () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + vi.stubEnv('TURNSTILE_SECRET_KEY', '') + vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', '') + expect(await gate('files', undefined, undefined, {}, undefined)).toBeNull() + expect(await gate('text', 'reject', undefined, {}, undefined)).toBeNull() + expect(fetchMock).not.toHaveBeenCalled() + }) + + test('ipalKit carries the option to where the gate reads it', async () => { + const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } + const build = async (forms: Record) => + ((await ipalKit({ forms, i18n, twoFactor: false } as never)({ collections: [], secret: 'x' } as never)).custom as { ipal?: { forms?: { turnstileOnConfigError?: unknown } } }).ipal?.forms?.turnstileOnConfigError + expect(await build({})).toBeUndefined() + expect(await build({ turnstileOnConfigError: 'reject' })).toBe('reject') + expect(await build({ turnstileOnConfigError: { files: 'allow' } })).toEqual({ files: 'allow' }) + }) +})