M1 (4): forms.turnstileOnConfigError — a form with files is refused while Turnstile cannot check

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 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:12 +01:00
co-authored by Claude Fable 5.2
parent 42fdad8c2d
commit 463fd5d664
7 changed files with 170 additions and 9 deletions
+2
View File
@@ -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
*
+1
View File
@@ -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'
}
@@ -220,7 +220,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
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)}
+38 -8
View File
@@ -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<TurnstileFormKind, TurnstileOnConfigError> = { 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<SubmitFormArgs, 'ip' | 'maxPerMinute' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileOnConfigError, turnstileToken }))
}: { turnstileKind?: TurnstileFormKind } & Pick<SubmitFormArgs, 'ip' | 'maxPerMinute' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
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<SubmitFormArgs, 'ip' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
}: { turnstileKind?: TurnstileFormKind } & Pick<SubmitFormArgs, 'ip' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
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
+14
View File
@@ -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
}
+5
View File
@@ -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 ---
+108
View File
@@ -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<string, unknown>, 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<string, unknown> = 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<string, unknown>) =>
((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' })
})
})