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 }
}
+23 -9
View File
@@ -69,6 +69,20 @@ export type RateLimitArgs = {
type CheckArgs = { cost?: number } & RateLimitArgs
/**
* Requests with no usable client IP (a proxy that strips the header, a
* misconfigured IPAL_IP_HEADER) share one bucket with a roomier limit. Letting
* them through unlimited meant a client that simply omits the header walked
* past every limiter; one shared bucket keeps real visitors flowing while
* capping the flood.
*/
export const UNKNOWN_IP_KEY = 'unknown-ip'
export const UNKNOWN_IP_FACTOR = 20
function resolveKey(key: string, max: number): { key: string; max: number } {
return key ? { key, max } : { key: UNKNOWN_IP_KEY, max: max * UNKNOWN_IP_FACTOR }
}
function hitMemory(id: string, cost: number, windowMs: number): Bucket {
const now = Date.now()
sweep(now)
@@ -87,11 +101,11 @@ function hitMemory(id: string, cost: number, windowMs: number): Bucket {
* backwards compatibility; the plugin's own routes use consumeRateLimit.
*
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) is allowed through — better to accept a
* submission than to block everyone behind a proxy that strips the header.
* rejected. A missing key (no IP) counts against one shared bucket with
* UNKNOWN_IP_FACTOR × max.
*/
export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean {
if (!key) {return true}
export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean {
const { key, max } = resolveKey(rawKey, rawMax)
const id = `${scope}:${key}`
const current = buckets.get(id)
const used = current && current.resetAt > Date.now() ? current.count : 0
@@ -108,12 +122,12 @@ export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowM
*/
export async function consumeRateLimit({
cost = 1,
key,
max = 5,
key: rawKey,
max: rawMax = 5,
scope = 'form',
windowMs = 60_000,
}: CheckArgs): Promise<{ ok: boolean; retryAfter: number }> {
if (!key) {return { ok: true, retryAfter: 0 }}
const { key, max } = resolveKey(rawKey, rawMax)
const id = `${scope}:${key}`
let bucket: Bucket
@@ -164,8 +178,8 @@ export type ClientIpOptions = {
* and walk past the rate limit; each proxy appends the address it saw, so the
* rightmost entries are the trustworthy ones.
*
* Empty string when nothing usable is present — the limiter then lets the
* request through.
* Empty string when nothing usable is present — the limiter then counts it in
* the shared UNKNOWN_IP_KEY bucket.
*/
let warnedUnpinned = false
+12
View File
@@ -19,6 +19,13 @@ type IntegrationsWithTurnstile = {
}
type VerifyTurnstileArgs = {
/**
* Hostnames the token must have been solved on (siteverify's `hostname`), e.g.
* ['www.example.com', 'example.com']. Unset = not checked. Guards against a
* token solved on another site that shares the widget (a sitekey allowing any
* hostname). Cloudflare's test keys report 'example.com' — leave unset in dev.
*/
hostnames?: string[]
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
ip?: string
/**
@@ -73,6 +80,7 @@ const PLUGIN_ERRORS: Record<string, string> = {
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/
export async function checkTurnstile({
hostnames,
ip,
payload,
sendRemoteIp = false,
@@ -112,6 +120,10 @@ export async function checkTurnstile({
if (typeof data?.success !== 'boolean') {return degraded('bad-response')}
if (data.success) {
if (hostnames?.length && !hostnames.some((h) => h.toLowerCase() === data.hostname?.toLowerCase())) {
console.warn(`[ipal] Turnstile rejected: token solved on "${data.hostname ?? '?'}", expected ${hostnames.join(', ')}`)
return { code: 'hostname-mismatch', outcome: 'reject' }
}
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' })
return { outcome: 'pass' }
}