Rate limit: no IP shares a capped bucket; optional Turnstile hostname check

A request without a usable client IP used to skip every limiter. It now
counts against one shared 'unknown-ip' bucket at 20x the limit. submitForm,
createSubmitAction and verifyTurnstile accept turnstileHostnames/hostnames
to reject tokens solved on another domain.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 16:59:51 +02:00
co-authored by Claude Opus 5.5
parent 10da62ea4c
commit 8e10232765
8 changed files with 86 additions and 14 deletions
+3 -1
View File
@@ -21,7 +21,7 @@ type CreateSubmitActionArgs = {
headers: () => Headers | Promise<Headers>
/** Honeypot field name. Default HONEYPOT_FIELD. */
honeypotField?: string
} & Pick<SubmitFormArgs, 'consentFieldName' | 'maxPerMinute' | 'turnstileOnConfigError'>
} & Pick<SubmitFormArgs, 'consentFieldName' | 'maxPerMinute' | 'turnstileHostnames' | 'turnstileOnConfigError'>
export type SubmitActionResult = {
field?: string
@@ -55,6 +55,7 @@ export function createSubmitAction({
headers,
honeypotField = HONEYPOT_FIELD,
maxPerMinute,
turnstileHostnames,
turnstileOnConfigError,
}: CreateSubmitActionArgs) {
return async function sendForm(
@@ -78,6 +79,7 @@ export function createSubmitAction({
locale,
maxPerMinute,
payload,
turnstileHostnames,
turnstileOnConfigError,
turnstileToken: typeof turnstileToken === 'string' ? turnstileToken.trim() || undefined : undefined,
})
+6 -2
View File
@@ -27,6 +27,8 @@ export type SubmitFormArgs = {
*/
maxPerMinute?: number
payload: BasePayload
/** Hostnames a Turnstile token must come from (see verifyTurnstile `hostnames`). Unset = not checked. */
turnstileHostnames?: string[]
/**
* Turnstile can't be verified because of OUR side (missing/wrong secret,
* Cloudflare unreachable): 'allow' (default) accepts the submission and shows
@@ -101,11 +103,13 @@ export async function submitForm({
locale,
maxPerMinute = 5,
payload,
turnstileHostnames,
turnstileOnConfigError = 'allow',
turnstileToken,
}: SubmitFormArgs): Promise<SubmitFormResult> {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
if (maxPerMinute > 0 && ip) {
// 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 }
}
@@ -117,7 +121,7 @@ export async function submitForm({
if ((await getTurnstileConfig(payload)).enabled) {
const ok =
Boolean(turnstileToken) &&
(await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! }))
(await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! }))
if (!ok) {
return { reason: 'turnstile', success: false }
}