From daa0f21242b1cd6be032c1636a9f43a74a0e4851 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:09:47 +0000 Subject: [PATCH 1/3] fix(web): apply an in-process rate limit when the firewall cannot answer --- apps/web/__tests__/unit/rate-limit.test.ts | 226 ++++++++++++++++++++- apps/web/lib/rate-limit.ts | 169 ++++++++++++--- docs/saml-sso.md | 2 +- 3 files changed, 368 insertions(+), 29 deletions(-) diff --git a/apps/web/__tests__/unit/rate-limit.test.ts b/apps/web/__tests__/unit/rate-limit.test.ts index 18ad525272c..425dca17a99 100644 --- a/apps/web/__tests__/unit/rate-limit.test.ts +++ b/apps/web/__tests__/unit/rate-limit.test.ts @@ -1,8 +1,38 @@ -import { describe, expect, it } from "vitest"; -import { firewallRequestHeaders } from "@/lib/rate-limit"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + checkRateLimit: vi.fn(), + headers: vi.fn(), +})); + +vi.mock("@vercel/firewall", () => ({ checkRateLimit: mocks.checkRateLimit })); +vi.mock("next/headers", () => ({ headers: mocks.headers })); + +const loadRateLimit = async () => { + vi.resetModules(); + return import("@/lib/rate-limit"); +}; + +const callTimes = async (count: number, call: () => Promise) => { + const results: boolean[] = []; + for (let index = 0; index < count; index++) results.push(await call()); + return results; +}; + +beforeEach(() => { + mocks.checkRateLimit.mockReset(); + mocks.headers.mockReset().mockResolvedValue(new Headers()); + vi.spyOn(console, "warn").mockImplementation(() => {}); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.useRealTimers(); +}); describe("firewallRequestHeaders", () => { - it("forwards only host and client IP headers", () => { + it("forwards only host and client IP headers", async () => { + const { firewallRequestHeaders } = await loadRateLimit(); const forwarded = firewallRequestHeaders( new Headers({ host: "cap.so", @@ -22,3 +52,193 @@ describe("firewallRequestHeaders", () => { expect(forwarded.get("cookie")).toBeNull(); }); }); + +describe("isRateLimited outside production", () => { + it("applies the rule's in-process limit per key without calling the firewall", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const send = (key: string) => + isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key }); + + expect(await callTimes(5, () => send("email-a"))).toEqual( + Array(5).fill(false), + ); + expect(await send("email-a")).toBe(true); + expect(await send("email-b")).toBe(false); + expect(mocks.checkRateLimit).not.toHaveBeenCalled(); + }); + + it("keeps separate buckets per rule for the same key", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + await callTimes(5, () => + isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "shared" }), + ); + + expect( + await isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "shared" }), + ).toBe(true); + expect( + await isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_VERIFY, { key: "shared" }), + ).toBe(false); + }); + + it("allows requests again once the window has passed", async () => { + vi.useFakeTimers(); + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const verify = () => + isRateLimited(RATE_LIMIT_IDS.MOBILE_VIDEO_PASSWORD, { key: "user-1" }); + + await callTimes(10, verify); + expect(await verify()).toBe(true); + + vi.advanceTimersByTime(10 * 60_000); + expect(await verify()).toBe(false); + }); + + it("keys on x-real-ip, then the first x-forwarded-for entry", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const fromHeaders = (init: Record) => + isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT, { + headers: new Headers(init), + }); + + await callTimes(10, () => + fromHeaders({ + "x-real-ip": "203.0.113.1", + "x-forwarded-for": "198.51.100.9", + }), + ); + expect(await fromHeaders({ "x-real-ip": "203.0.113.1" })).toBe(true); + expect(await fromHeaders({ "x-forwarded-for": "198.51.100.9" })).toBe( + false, + ); + + await callTimes(9, () => + fromHeaders({ "x-forwarded-for": "198.51.100.9, 10.0.0.1" }), + ); + expect(await fromHeaders({ "x-forwarded-for": "198.51.100.9" })).toBe(true); + expect(await fromHeaders({ "x-forwarded-for": "10.0.0.1" })).toBe(false); + }); + + it("reads App Router headers when none are passed", async () => { + mocks.headers.mockResolvedValue(new Headers({ "x-real-ip": "192.0.2.4" })); + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + + await callTimes(10, () => + isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT), + ); + expect(await isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT)).toBe(true); + expect( + await isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT, { + headers: new Headers({ "x-real-ip": "192.0.2.5" }), + }), + ).toBe(false); + }); + + it("shares one larger bucket when there is no key and no client address", async () => { + mocks.headers.mockRejectedValue(new Error("outside a request scope")); + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const anonymous = () => isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT); + + expect(await callTimes(100, anonymous)).toEqual(Array(100).fill(false)); + expect(await anonymous()).toBe(true); + }); + + it("uses a default limit for rule ids without a configured one", async () => { + const { isRateLimited } = await loadRateLimit(); + const call = () => isRateLimited("rl_unlisted_rule", { key: "k" }); + + expect(await callTimes(60, call)).toEqual(Array(60).fill(false)); + expect(await call()).toBe(true); + }); + + it("evicts the oldest buckets instead of growing without bound", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const send = (key: string) => + isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key }); + + await callTimes(5, () => send("oldest")); + expect(await send("oldest")).toBe(true); + + for (let index = 0; index < 10_000; index++) await send(`filler-${index}`); + + expect(await send("oldest")).toBe(false); + }); + + it("accepts very long keys", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const longKey = "x".repeat(100_000); + + await callTimes(5, () => + isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: longKey }), + ); + expect( + await isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: longKey }), + ).toBe(true); + expect( + await isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { + key: `${longKey}y`, + }), + ).toBe(false); + }); +}); + +describe("isRateLimited in production", () => { + beforeEach(() => { + vi.stubEnv("NODE_ENV", "production"); + }); + + it("follows the firewall when its rule answers", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + mocks.checkRateLimit.mockResolvedValue({ rateLimited: false }); + + expect( + await callTimes(20, () => + isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "email" }), + ), + ).toEqual(Array(20).fill(false)); + + mocks.checkRateLimit.mockResolvedValueOnce({ rateLimited: true }); + expect( + await isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "other" }), + ).toBe(true); + + mocks.checkRateLimit.mockResolvedValueOnce({ + rateLimited: true, + error: "blocked", + }); + expect( + await isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "third" }), + ).toBe(true); + expect(mocks.checkRateLimit).toHaveBeenLastCalledWith( + RATE_LIMIT_IDS.AUTH_OTP_SEND, + expect.objectContaining({ rateLimitKey: "third" }), + ); + }); + + it("falls back to the in-process limit when the firewall rule is missing", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + mocks.checkRateLimit.mockResolvedValue({ + rateLimited: false, + error: "not-found", + }); + const send = () => + isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "email" }); + + expect(await callTimes(5, send)).toEqual(Array(5).fill(false)); + expect(await send()).toBe(true); + }); + + it("falls back to the in-process limit when the firewall check throws", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + mocks.checkRateLimit.mockRejectedValue( + new Error("Could not determine rate limit key."), + ); + const verify = () => + isRateLimited(RATE_LIMIT_IDS.MOBILE_VIDEO_PASSWORD, { + headers: new Headers({ "x-forwarded-for": "198.51.100.7" }), + }); + + expect(await callTimes(10, verify)).toEqual(Array(10).fill(false)); + await expect(verify()).resolves.toBe(true); + }); +}); diff --git a/apps/web/lib/rate-limit.ts b/apps/web/lib/rate-limit.ts index 1bbea8b315b..667602cfd3e 100644 --- a/apps/web/lib/rate-limit.ts +++ b/apps/web/lib/rate-limit.ts @@ -18,25 +18,20 @@ export function firewallRequestHeaders(source: Headers): Headers { } /** - * Best-effort per-key rate limiting backed by the Vercel Firewall. + * Per-key rate limiting backed by the Vercel Firewall, with an in-process + * fallback. * - * IMPORTANT: each `ruleId` passed here must also be configured as a Rate Limit - * rule in the Vercel Firewall dashboard (Firewall → Rate Limiting) with a - * `@vercel/firewall` rule condition whose ID matches `ruleId`, plus the desired - * window / limit / action. An ID that has no matching dashboard rule fails - * OPEN (`checkRateLimit` returns `{ rateLimited: false, error: "not-found" }`), - * so this helper never breaks self-hosted deploys that lack the firewall — but - * it also provides no protection until the rule exists. - * - * Mirrors the existing pattern in `actions/collections/password.ts` and - * `actions/send-download-link.ts`: - * - only enforced in production, - * - best-effort (any error → not limited) so a firewall/IP-header outage can - * never take down the underlying feature. + * Each `ruleId` should also exist as a Rate Limit rule in the Vercel Firewall + * dashboard with a `@vercel/firewall` condition matching the id. When the + * firewall answers (allowed, limited or blocked) its decision is final. When it + * cannot answer (non-production, rule not configured, missing client address + * or any firewall error) the request is counted against a fixed-window limit + * kept in this process (`FALLBACK_RATE_LIMITS`). That fallback is per instance, + * so it is a backstop, not a replacement for the dashboard rule. * * @param ruleId Stable rule id, also configured in the Vercel Firewall. * @param opts.key Optional bucket key (e.g. per-email / per-user). Defaults to - * the caller IP (the firewall's default behaviour). + * the caller IP. * @param opts.headers Optional request headers (required inside Hono handlers * where `next/headers` is unavailable; defaults to the App * Router request headers). @@ -46,29 +41,66 @@ export async function isRateLimited( ruleId: string, opts?: { key?: string; headers?: Headers }, ): Promise { - if (process.env.NODE_ENV !== "production") return false; - try { const headersList = firewallRequestHeaders( - opts?.headers ?? (await nextHeaders()), + opts?.headers ?? (await appRouterHeaders()), + ); + const firewallDecision = await checkFirewallRateLimit( + ruleId, + headersList, + opts?.key, ); + if (firewallDecision !== undefined) return firewallDecision; + + return await isLocallyRateLimited( + ruleId, + opts?.key || clientAddress(headersList), + ); + } catch (error) { + console.warn(`Rate limit check failed for "${ruleId}":`, error); + return false; + } +} + +async function appRouterHeaders(): Promise { + try { + return new Headers(await nextHeaders()); + } catch { + return new Headers(); + } +} + +async function checkFirewallRateLimit( + ruleId: string, + headersList: Headers, + key: string | undefined, +): Promise { + if (process.env.NODE_ENV !== "production") return undefined; + + try { const request = new Request("https://cap.so/api/rate-limit", { method: "POST", headers: headersList, }); - - const { rateLimited } = await checkRateLimit(ruleId, { + const result = await checkRateLimit(ruleId, { request, - ...(opts?.key ? { rateLimitKey: opts.key } : {}), + ...(key ? { rateLimitKey: key } : {}), }); - - return rateLimited; + return result.error === "not-found" ? undefined : result.rateLimited; } catch (error) { console.warn(`Rate limit check failed for "${ruleId}":`, error); - return false; + return undefined; } } +function clientAddress(headersList: Headers): string | undefined { + return ( + headersList.get("x-real-ip")?.trim() || + headersList.get("x-forwarded-for")?.split(",")[0]?.trim() || + undefined + ); +} + /** * Canonical Vercel Firewall rate-limit rule ids introduced by the security * hardening pass. Each MUST be created in the Vercel Firewall dashboard for the @@ -91,7 +123,7 @@ export const RATE_LIMIT_IDS = { MESSENGER_MESSAGE: "rl_messenger_message", /** Unauthed analytics view tracking (Tinybird ingest + notifications). Suggested: 60 / 1m per IP. */ ANALYTICS_TRACK: "rl_analytics_track", - /** Unauthed guest checkout (Stripe object/cost abuse). Suggested: 10 / 10m per IP. */ + /** Unauthed guest checkout (Stripe object/cost abuse). Suggested: 20 / 10m per IP. */ GUEST_CHECKOUT: "rl_guest_checkout", /** Unauthed desktop log → Discord forwarding (spam). Suggested: 10 / 1m per IP. */ DESKTOP_LOGS: "rl_desktop_logs", @@ -99,4 +131,91 @@ export const RATE_LIMIT_IDS = { MOBILE_VIDEO_PASSWORD: "rl_mobile_video_password", /** Unauthed docs Ask AI questions (Anthropic cost). Suggested: 10 / 1m per IP. */ DOCS_ASK: "rl_docs_ask", + AUTH_SSO_START: "rl_auth_sso_start", + MCP_CLIENT_REGISTRATION: "rl_mcp_client_registration", } as const; + +type FallbackRateLimit = { limit: number; windowMs: number }; + +const MINUTE_MS = 60_000; + +const FALLBACK_RATE_LIMITS: Record = { + [RATE_LIMIT_IDS.AGENT_TOKEN_EXCHANGE]: { limit: 120, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.AGENT_AUTHORIZATION]: { limit: 10, windowMs: 10 * MINUTE_MS }, + [RATE_LIMIT_IDS.AGENT_UNLOCK]: { limit: 30, windowMs: 10 * MINUTE_MS }, + [RATE_LIMIT_IDS.AGENT_LOOM_IMPORT]: { limit: 20, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.AUTH_OTP_VERIFY]: { limit: 10, windowMs: 10 * MINUTE_MS }, + [RATE_LIMIT_IDS.AUTH_OTP_SEND]: { limit: 5, windowMs: 10 * MINUTE_MS }, + [RATE_LIMIT_IDS.LOOM_DOWNLOAD]: { limit: 10, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT]: { limit: 10, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.MESSENGER_MESSAGE]: { limit: 20, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.ANALYTICS_TRACK]: { limit: 60, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.GUEST_CHECKOUT]: { limit: 20, windowMs: 10 * MINUTE_MS }, + [RATE_LIMIT_IDS.DESKTOP_LOGS]: { limit: 10, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.MOBILE_VIDEO_PASSWORD]: { + limit: 10, + windowMs: 10 * MINUTE_MS, + }, + [RATE_LIMIT_IDS.DOCS_ASK]: { limit: 10, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.AUTH_SSO_START]: { limit: 100, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.MCP_CLIENT_REGISTRATION]: { limit: 60, windowMs: MINUTE_MS }, +}; + +const DEFAULT_FALLBACK_RATE_LIMIT: FallbackRateLimit = { + limit: 60, + windowMs: MINUTE_MS, +}; + +// Without a key or client address every caller shares one bucket (a proxy +// that forwards no client IP), so that bucket gets a multiple of the +// per-client limit to avoid locking out a whole self-hosted deploy. +const ANONYMOUS_LIMIT_MULTIPLIER = 10; +const MAX_LOCAL_BUCKETS = 10_000; +const MAX_PLAIN_BUCKET_KEY_LENGTH = 256; + +const localBuckets = new Map(); + +async function isLocallyRateLimited( + ruleId: string, + clientKey: string | undefined, +): Promise { + const rule = FALLBACK_RATE_LIMITS[ruleId] ?? DEFAULT_FALLBACK_RATE_LIMIT; + const limit = clientKey + ? rule.limit + : rule.limit * ANONYMOUS_LIMIT_MULTIPLIER; + const bucketKey = clientKey + ? `${ruleId}|key|${await compactBucketKey(clientKey)}` + : `${ruleId}|anonymous`; + const now = Date.now(); + + const bucket = localBuckets.get(bucketKey); + if (bucket && bucket.resetAt > now) { + bucket.count += 1; + return bucket.count > limit; + } + + localBuckets.delete(bucketKey); + reserveLocalBucket(now); + localBuckets.set(bucketKey, { count: 1, resetAt: now + rule.windowMs }); + return limit < 1; +} + +function reserveLocalBucket(now: number) { + if (localBuckets.size < MAX_LOCAL_BUCKETS) return; + for (const [key, bucket] of localBuckets) { + if (bucket.resetAt <= now) localBuckets.delete(key); + } + for (const key of localBuckets.keys()) { + if (localBuckets.size < MAX_LOCAL_BUCKETS) return; + localBuckets.delete(key); + } +} + +async function compactBucketKey(key: string): Promise { + if (key.length <= MAX_PLAIN_BUCKET_KEY_LENGTH) return key; + const digest = await globalThis.crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(key), + ); + return `sha256:${Buffer.from(digest).toString("hex")}`; +} diff --git a/docs/saml-sso.md b/docs/saml-sso.md index 7b02fed06ab..5e0704ca177 100644 --- a/docs/saml-sso.md +++ b/docs/saml-sso.md @@ -37,7 +37,7 @@ Configure WorkOS redirect settings for the same environment: Cap supplies organization-scoped Admin Portal return and success URLs. API-generated links are short-lived bearer capabilities and should be opened immediately, never stored or logged. Use an HTTPS preview origin for a full Admin Portal test. -Configure the Vercel Firewall SDK rule `rl_auth_sso_start`, for example 20 attempts per minute per IP. The shared rate-limit helper is best-effort and fails open when the rule is missing or the firewall is unavailable; merely deploying the rule ID does not enable rate limiting. Self-hosted deployments should provide equivalent perimeter protection. +Configure the Vercel Firewall SDK rule `rl_auth_sso_start`, for example 20 attempts per minute per IP. When the rule is missing or the firewall is unavailable (including self-hosted deployments), the shared rate-limit helper falls back to an in-process limit of 100 attempts per minute per IP for each server instance. Self-hosted deployments should still provide perimeter protection. ## Billing and recovery From addd2807a969a5726fccd52ecd4f4475489ec502 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:20:49 +0000 Subject: [PATCH 2/3] fix(web): cap keyless fallback requests off Vercel and bound bucket sweeps --- apps/web/__tests__/unit/rate-limit.test.ts | 37 ++++++++++++ apps/web/lib/rate-limit.ts | 67 ++++++++++++++++------ 2 files changed, 85 insertions(+), 19 deletions(-) diff --git a/apps/web/__tests__/unit/rate-limit.test.ts b/apps/web/__tests__/unit/rate-limit.test.ts index 425dca17a99..18c1c663162 100644 --- a/apps/web/__tests__/unit/rate-limit.test.ts +++ b/apps/web/__tests__/unit/rate-limit.test.ts @@ -134,6 +134,43 @@ describe("isRateLimited outside production", () => { ).toBe(false); }); + it("caps keyless requests from rotating addresses off Vercel", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const fromAddress = (ip: string) => + isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT, { + headers: new Headers({ "x-forwarded-for": ip }), + }); + + for (let index = 0; index < 100; index++) { + expect(await fromAddress(`198.51.100.${index}`)).toBe(false); + } + expect(await fromAddress("203.0.113.250")).toBe(true); + }); + + it("does not let one limited address use up the shared bucket", async () => { + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const fromAddress = (ip: string) => + isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT, { + headers: new Headers({ "x-real-ip": ip }), + }); + + await callTimes(500, () => fromAddress("203.0.113.9")); + expect(await fromAddress("203.0.113.10")).toBe(false); + }); + + it("trusts client addresses on Vercel", async () => { + vi.stubEnv("VERCEL", "1"); + const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); + const fromAddress = (ip: string) => + isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT, { + headers: new Headers({ "x-real-ip": ip }), + }); + + for (let index = 0; index < 150; index++) { + expect(await fromAddress(`198.51.100.${index}`)).toBe(false); + } + }); + it("shares one larger bucket when there is no key and no client address", async () => { mocks.headers.mockRejectedValue(new Error("outside a request scope")); const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); diff --git a/apps/web/lib/rate-limit.ts b/apps/web/lib/rate-limit.ts index 667602cfd3e..3875563d672 100644 --- a/apps/web/lib/rate-limit.ts +++ b/apps/web/lib/rate-limit.ts @@ -52,10 +52,7 @@ export async function isRateLimited( ); if (firewallDecision !== undefined) return firewallDecision; - return await isLocallyRateLimited( - ruleId, - opts?.key || clientAddress(headersList), - ); + return await isLocallyRateLimited(ruleId, opts?.key, headersList); } catch (error) { console.warn(`Rate limit check failed for "${ruleId}":`, error); return false; @@ -166,28 +163,57 @@ const DEFAULT_FALLBACK_RATE_LIMIT: FallbackRateLimit = { windowMs: MINUTE_MS, }; -// Without a key or client address every caller shares one bucket (a proxy -// that forwards no client IP), so that bucket gets a multiple of the -// per-client limit to avoid locking out a whole self-hosted deploy. -const ANONYMOUS_LIMIT_MULTIPLIER = 10; +// Keyless requests also count against one bucket per rule, sized as a multiple +// of the per-client limit. It catches callers with no client address (a proxy +// that forwards none) and, off Vercel, callers that rotate x-real-ip or +// x-forwarded-for themselves, without letting one client lock out a whole +// self-hosted deploy. +const SHARED_LIMIT_MULTIPLIER = 10; const MAX_LOCAL_BUCKETS = 10_000; +const LOCAL_BUCKET_SWEEP_INTERVAL_MS = 10_000; const MAX_PLAIN_BUCKET_KEY_LENGTH = 256; const localBuckets = new Map(); +let nextLocalBucketSweepAt = 0; async function isLocallyRateLimited( ruleId: string, - clientKey: string | undefined, + key: string | undefined, + headersList: Headers, ): Promise { const rule = FALLBACK_RATE_LIMITS[ruleId] ?? DEFAULT_FALLBACK_RATE_LIMIT; - const limit = clientKey - ? rule.limit - : rule.limit * ANONYMOUS_LIMIT_MULTIPLIER; - const bucketKey = clientKey - ? `${ruleId}|key|${await compactBucketKey(clientKey)}` - : `${ruleId}|anonymous`; - const now = Date.now(); + if (key) { + return countLocalRequest( + `${ruleId}|key|${await compactBucketKey(key)}`, + rule.limit, + rule.windowMs, + ); + } + const address = clientAddress(headersList); + if (address) { + const addressLimited = countLocalRequest( + `${ruleId}|ip|${await compactBucketKey(address)}`, + rule.limit, + rule.windowMs, + ); + if (addressLimited) return true; + if (process.env.VERCEL === "1") return false; + } + + return countLocalRequest( + `${ruleId}|shared`, + rule.limit * SHARED_LIMIT_MULTIPLIER, + rule.windowMs, + ); +} + +function countLocalRequest( + bucketKey: string, + limit: number, + windowMs: number, +): boolean { + const now = Date.now(); const bucket = localBuckets.get(bucketKey); if (bucket && bucket.resetAt > now) { bucket.count += 1; @@ -196,14 +222,17 @@ async function isLocallyRateLimited( localBuckets.delete(bucketKey); reserveLocalBucket(now); - localBuckets.set(bucketKey, { count: 1, resetAt: now + rule.windowMs }); + localBuckets.set(bucketKey, { count: 1, resetAt: now + windowMs }); return limit < 1; } function reserveLocalBucket(now: number) { if (localBuckets.size < MAX_LOCAL_BUCKETS) return; - for (const [key, bucket] of localBuckets) { - if (bucket.resetAt <= now) localBuckets.delete(key); + if (now >= nextLocalBucketSweepAt) { + nextLocalBucketSweepAt = now + LOCAL_BUCKET_SWEEP_INTERVAL_MS; + for (const [key, bucket] of localBuckets) { + if (bucket.resetAt <= now) localBuckets.delete(key); + } } for (const key of localBuckets.keys()) { if (localBuckets.size < MAX_LOCAL_BUCKETS) return; From 1b2b9d4a7efd9ed606ed076d6c9d6f92adebed96 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:40:03 +0000 Subject: [PATCH 3/3] fix(web): align fallback rate limits with the production rule values --- apps/web/__tests__/unit/rate-limit.test.ts | 36 ++++++++++++---------- apps/web/lib/rate-limit.ts | 20 ++++++------ 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/apps/web/__tests__/unit/rate-limit.test.ts b/apps/web/__tests__/unit/rate-limit.test.ts index 18c1c663162..39498cf7a32 100644 --- a/apps/web/__tests__/unit/rate-limit.test.ts +++ b/apps/web/__tests__/unit/rate-limit.test.ts @@ -59,8 +59,8 @@ describe("isRateLimited outside production", () => { const send = (key: string) => isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key }); - expect(await callTimes(5, () => send("email-a"))).toEqual( - Array(5).fill(false), + expect(await callTimes(10, () => send("email-a"))).toEqual( + Array(10).fill(false), ); expect(await send("email-a")).toBe(true); expect(await send("email-b")).toBe(false); @@ -69,7 +69,7 @@ describe("isRateLimited outside production", () => { it("keeps separate buckets per rule for the same key", async () => { const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); - await callTimes(5, () => + await callTimes(10, () => isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "shared" }), ); @@ -87,7 +87,7 @@ describe("isRateLimited outside production", () => { const verify = () => isRateLimited(RATE_LIMIT_IDS.MOBILE_VIDEO_PASSWORD, { key: "user-1" }); - await callTimes(10, verify); + await callTimes(20, verify); expect(await verify()).toBe(true); vi.advanceTimersByTime(10 * 60_000); @@ -101,7 +101,7 @@ describe("isRateLimited outside production", () => { headers: new Headers(init), }); - await callTimes(10, () => + await callTimes(30, () => fromHeaders({ "x-real-ip": "203.0.113.1", "x-forwarded-for": "198.51.100.9", @@ -112,7 +112,7 @@ describe("isRateLimited outside production", () => { false, ); - await callTimes(9, () => + await callTimes(29, () => fromHeaders({ "x-forwarded-for": "198.51.100.9, 10.0.0.1" }), ); expect(await fromHeaders({ "x-forwarded-for": "198.51.100.9" })).toBe(true); @@ -123,7 +123,7 @@ describe("isRateLimited outside production", () => { mocks.headers.mockResolvedValue(new Headers({ "x-real-ip": "192.0.2.4" })); const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); - await callTimes(10, () => + await callTimes(30, () => isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT), ); expect(await isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT)).toBe(true); @@ -141,8 +141,10 @@ describe("isRateLimited outside production", () => { headers: new Headers({ "x-forwarded-for": ip }), }); - for (let index = 0; index < 100; index++) { - expect(await fromAddress(`198.51.100.${index}`)).toBe(false); + for (let index = 0; index < 300; index++) { + expect(await fromAddress(`198.51.${index >> 8}.${index & 255}`)).toBe( + false, + ); } expect(await fromAddress("203.0.113.250")).toBe(true); }); @@ -166,8 +168,10 @@ describe("isRateLimited outside production", () => { headers: new Headers({ "x-real-ip": ip }), }); - for (let index = 0; index < 150; index++) { - expect(await fromAddress(`198.51.100.${index}`)).toBe(false); + for (let index = 0; index < 400; index++) { + expect(await fromAddress(`198.51.${index >> 8}.${index & 255}`)).toBe( + false, + ); } }); @@ -176,7 +180,7 @@ describe("isRateLimited outside production", () => { const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); const anonymous = () => isRateLimited(RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT); - expect(await callTimes(100, anonymous)).toEqual(Array(100).fill(false)); + expect(await callTimes(300, anonymous)).toEqual(Array(300).fill(false)); expect(await anonymous()).toBe(true); }); @@ -193,7 +197,7 @@ describe("isRateLimited outside production", () => { const send = (key: string) => isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key }); - await callTimes(5, () => send("oldest")); + await callTimes(10, () => send("oldest")); expect(await send("oldest")).toBe(true); for (let index = 0; index < 10_000; index++) await send(`filler-${index}`); @@ -205,7 +209,7 @@ describe("isRateLimited outside production", () => { const { isRateLimited, RATE_LIMIT_IDS } = await loadRateLimit(); const longKey = "x".repeat(100_000); - await callTimes(5, () => + await callTimes(10, () => isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: longKey }), ); expect( @@ -261,7 +265,7 @@ describe("isRateLimited in production", () => { const send = () => isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, { key: "email" }); - expect(await callTimes(5, send)).toEqual(Array(5).fill(false)); + expect(await callTimes(10, send)).toEqual(Array(10).fill(false)); expect(await send()).toBe(true); }); @@ -275,7 +279,7 @@ describe("isRateLimited in production", () => { headers: new Headers({ "x-forwarded-for": "198.51.100.7" }), }); - expect(await callTimes(10, verify)).toEqual(Array(10).fill(false)); + expect(await callTimes(20, verify)).toEqual(Array(20).fill(false)); await expect(verify()).resolves.toBe(true); }); }); diff --git a/apps/web/lib/rate-limit.ts b/apps/web/lib/rate-limit.ts index 3875563d672..fe9889b6190 100644 --- a/apps/web/lib/rate-limit.ts +++ b/apps/web/lib/rate-limit.ts @@ -108,23 +108,23 @@ export const RATE_LIMIT_IDS = { AGENT_AUTHORIZATION: "rl_agent_authorization", AGENT_UNLOCK: "rl_agent_unlock", AGENT_LOOM_IMPORT: "rl_loom_import_per_user", - /** Email OTP verification attempts (brute-force guard). Suggested: 10 / 10m per key (email). */ + /** Email OTP verification attempts (brute-force guard). Suggested: 20 / 10m per key (email). */ AUTH_OTP_VERIFY: "rl_auth_otp_verify", - /** Email OTP / magic-link send (mailbomb + token-reseed guard). Suggested: 5 / 10m per key (email). */ + /** Email OTP / magic-link send (mailbomb + token-reseed guard). Suggested: 10 / 10m per key (email). */ AUTH_OTP_SEND: "rl_auth_otp_send", /** Unauthed Loom download/convert (ffmpeg + memory DoS). Suggested: 10 / 1m per IP. */ LOOM_DOWNLOAD: "rl_loom_download", - /** Unauthed transcript translation (Groq cost). Suggested: 10 / 1m per IP. */ + /** Unauthed transcript translation (Groq cost). Suggested: 30 / 1m per IP. */ TRANSLATE_TRANSCRIPT: "rl_translate_transcript", /** Anonymous support-chat messages (Groq + Supermemory cost). Suggested: 20 / 1m per IP. */ MESSENGER_MESSAGE: "rl_messenger_message", - /** Unauthed analytics view tracking (Tinybird ingest + notifications). Suggested: 60 / 1m per IP. */ + /** Unauthed analytics view tracking (Tinybird ingest + notifications). Suggested: 120 / 1m per IP. */ ANALYTICS_TRACK: "rl_analytics_track", /** Unauthed guest checkout (Stripe object/cost abuse). Suggested: 20 / 10m per IP. */ GUEST_CHECKOUT: "rl_guest_checkout", /** Unauthed desktop log → Discord forwarding (spam). Suggested: 10 / 1m per IP. */ DESKTOP_LOGS: "rl_desktop_logs", - /** Mobile share password attempts (brute-force guard). Suggested: 10 / 10m per key (user). */ + /** Mobile share password attempts (brute-force guard). Suggested: 20 / 10m per key (user). */ MOBILE_VIDEO_PASSWORD: "rl_mobile_video_password", /** Unauthed docs Ask AI questions (Anthropic cost). Suggested: 10 / 1m per IP. */ DOCS_ASK: "rl_docs_ask", @@ -141,16 +141,16 @@ const FALLBACK_RATE_LIMITS: Record = { [RATE_LIMIT_IDS.AGENT_AUTHORIZATION]: { limit: 10, windowMs: 10 * MINUTE_MS }, [RATE_LIMIT_IDS.AGENT_UNLOCK]: { limit: 30, windowMs: 10 * MINUTE_MS }, [RATE_LIMIT_IDS.AGENT_LOOM_IMPORT]: { limit: 20, windowMs: MINUTE_MS }, - [RATE_LIMIT_IDS.AUTH_OTP_VERIFY]: { limit: 10, windowMs: 10 * MINUTE_MS }, - [RATE_LIMIT_IDS.AUTH_OTP_SEND]: { limit: 5, windowMs: 10 * MINUTE_MS }, + [RATE_LIMIT_IDS.AUTH_OTP_VERIFY]: { limit: 20, windowMs: 10 * MINUTE_MS }, + [RATE_LIMIT_IDS.AUTH_OTP_SEND]: { limit: 10, windowMs: 10 * MINUTE_MS }, [RATE_LIMIT_IDS.LOOM_DOWNLOAD]: { limit: 10, windowMs: MINUTE_MS }, - [RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT]: { limit: 10, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.TRANSLATE_TRANSCRIPT]: { limit: 30, windowMs: MINUTE_MS }, [RATE_LIMIT_IDS.MESSENGER_MESSAGE]: { limit: 20, windowMs: MINUTE_MS }, - [RATE_LIMIT_IDS.ANALYTICS_TRACK]: { limit: 60, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.ANALYTICS_TRACK]: { limit: 120, windowMs: MINUTE_MS }, [RATE_LIMIT_IDS.GUEST_CHECKOUT]: { limit: 20, windowMs: 10 * MINUTE_MS }, [RATE_LIMIT_IDS.DESKTOP_LOGS]: { limit: 10, windowMs: MINUTE_MS }, [RATE_LIMIT_IDS.MOBILE_VIDEO_PASSWORD]: { - limit: 10, + limit: 20, windowMs: 10 * MINUTE_MS, }, [RATE_LIMIT_IDS.DOCS_ASK]: { limit: 10, windowMs: MINUTE_MS },