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:
co-authored by
Claude Opus 5.5
parent
10da62ea4c
commit
8e10232765
@@ -210,6 +210,13 @@ za Cloudflare. Bez tego klient, który trafi do aplikacji z pominięciem proxy,
|
||||
podstawić dowolny z tych nagłówków. Ta sama opcja `clientIp` jest w `createSearchRoute`
|
||||
i `createMcpRoute`.
|
||||
|
||||
Brak IP (proxy obcina nagłówek, zły `IPAL_IP_HEADER`) **nie** omija limitu: takie żądania
|
||||
dzielą jeden wspólny kubełek `unknown-ip` z limitem ×20 (`UNKNOWN_IP_FACTOR`) — prawdziwi
|
||||
odwiedzający przechodzą, flood bez nagłówka nie. Bez przypięcia nagłówka kolejność
|
||||
`cf-connecting-ip` → `x-real-ip` → XFF zostaje (zmiana na XFF-od-prawej złączyłaby za Cloudflare
|
||||
wszystkich odwiedzających w kubełek węzła brzegowego) — dlatego `IPAL_IP_HEADER` na produkcji
|
||||
jest obowiązkowe (`ipalEnvRules({ ipHeader: true })`).
|
||||
|
||||
Limity domyślnie trzymane są w pamięci, osobno dla każdej instancji. Kilka instancji
|
||||
→ wspólny store (np. Redis) raz przy starcie: `setRateLimitStore({ hit })`
|
||||
(przykład w JSDoc `RateLimitStore`). Gdy store padnie, żądanie przechodzi (log ostrzeżenia).
|
||||
|
||||
@@ -91,6 +91,13 @@ Status zapisuje serwer przy weryfikacji formularza (bez crona), najwyżej raz na
|
||||
przy trwającym błędzie i od razu przy zmianie stanu. Zapis nowych kluczy w panelu
|
||||
czyści status; po następnym wysłaniu formularza pojawi się aktualny.
|
||||
Twardo (fail closed): `submitForm({ …, turnstileOnConfigError: 'reject' })`.
|
||||
Domyślne `allow` jest świadome: `degraded` wywołuje tylko nasza konfiguracja albo awaria
|
||||
Cloudflare — odwiedzający nie może go wymusić, a formularze nie padają razem z Cloudflare.
|
||||
|
||||
**Hostname tokenu (opcjonalnie):** `createSubmitAction({ …, turnstileHostnames: ['www.firma.pl', 'firma.pl'] })`
|
||||
(albo `submitForm` / `verifyTurnstile({ hostnames })`) odrzuca token rozwiązany na innej domenie
|
||||
(`reason: 'turnstile'`, log `token solved on "…"`). Przydatne, gdy widget dopuszcza dowolny hostname.
|
||||
Testowe klucze Cloudflare zwracają `example.com` — w dev zostaw puste.
|
||||
|
||||
Po aktualizacji pluginu: `pnpm payload generate:importmap` (nowe komponenty panelu);
|
||||
Postgres: `pnpm payload migrate:create` (pole `turnstileStatus` w SiteIntegrations).
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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' }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
import {
|
||||
checkRateLimit,
|
||||
clientIp,
|
||||
UNKNOWN_IP_FACTOR,
|
||||
consumeRateLimit,
|
||||
setRateLimitStore,
|
||||
} from '../src/modules/shared/rateLimit.js'
|
||||
@@ -64,8 +65,10 @@ describe('checkRateLimit (in memory)', () => {
|
||||
expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false)
|
||||
})
|
||||
|
||||
test('no key → allowed', () => {
|
||||
expect(checkRateLimit({ key: '', max: 0 })).toBe(true)
|
||||
test('no key → one shared bucket with a roomier limit, not a free pass', () => {
|
||||
const scope = `s-${Math.random()}`
|
||||
for (let i = 0; i < 2 * UNKNOWN_IP_FACTOR; i++) {expect(checkRateLimit({ key: '', max: 2, scope })).toBe(true)}
|
||||
expect(checkRateLimit({ key: '', max: 2, scope })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { UNKNOWN_IP_FACTOR } from '../src/modules/shared/rateLimit.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
@@ -82,6 +83,19 @@ describe('submitForm — Turnstile', () => {
|
||||
expect(create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('turnstileHostnames: a token solved on another host is rejected', async () => {
|
||||
mockSiteverify({ hostname: 'evil.example', success: true })
|
||||
const { create, payload } = fakePayload({ forms, integrations: keys })
|
||||
const base = { data, formId: 'contact', payload, turnstileToken: 'tok' }
|
||||
expect(await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).toEqual({
|
||||
reason: 'turnstile',
|
||||
success: false,
|
||||
})
|
||||
expect(create).not.toHaveBeenCalled()
|
||||
mockSiteverify({ hostname: 'WWW.firma.pl', success: true })
|
||||
expect((await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).success).toBe(true)
|
||||
})
|
||||
|
||||
test('configured + Cloudflare rejects OUR secret → allowed by default, refused with reject', async () => {
|
||||
mockSiteverify({ 'error-codes': ['invalid-input-secret'], success: false })
|
||||
const { payload } = fakePayload({ forms, integrations: keys })
|
||||
@@ -97,6 +111,15 @@ describe('submitForm — Turnstile', () => {
|
||||
describe('submitForm — other gates', () => {
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
test('no client IP is not a free pass — it shares one capped bucket', async () => {
|
||||
const { payload } = fakePayload({ forms })
|
||||
let accepted = 0
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if ((await submitForm({ data, formId: 'contact', maxPerMinute: 1, payload })).success) {accepted++}
|
||||
}
|
||||
expect(accepted).toBe(UNKNOWN_IP_FACTOR)
|
||||
})
|
||||
|
||||
test('rate limit per IP', async () => {
|
||||
const { payload } = fakePayload({ forms })
|
||||
const ip = nextIp()
|
||||
|
||||
Reference in New Issue
Block a user