Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Cap daily API usage per space and fail closed when Redis is unavailable (#3196)
Luke Vellac4879646c872
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 571933c89..6434068a7 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -52,6 +52,8 @@"alreadyMember": "This person is already a member of this space","apiAccessUpgradeDescription": "Create API keys to manage your polls programmatically. Included with Pro, with a shared limit of {count} requests per minute across your space.","apiAccessUpgradeTitle": "Upgrade for API access",+ "apiDailyLimitLabel": "Daily limit",+ "apiDailyLimitValue": "{count, number} requests / day","apiKeyCreated": "API key created","apiKeyCreatedDescription": "Copy your API key now. You won't be able to see it again.","apiKeyLimitReached": "You've reached the maximum number of API keys. Revoke one before creating another.",@@ -583,7 +585,7 @@"numberOfSeats": "Number of seats","oidcAutoSignInDescription": "You are being redirected to the login page...","openPollCount": "{count, plural, other {# open}}",- "optional": "optional",+ "optional": "(optional)","optionalLabel": "(Optional)","optionCount": "{count, plural, one {# option} other {# options}}","optionsSelected": "{count, plural, =0 {None selected} one {# option selected} other {# options selected}}",diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-usage-limits.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-usage-limits.tsxindex b933fe808..440c906db 100644--- a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-usage-limits.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-usage-limits.tsx@@ -3,6 +3,7 @@import { ArrowUpRightIcon } from "lucide-react";import Link from "next/link";import {+ API_RATE_LIMIT_PER_DAY,API_RATE_LIMIT_PER_MINUTE,getApiDocsPath,} from "@/features/api-keys/constants";@@ -11,17 +12,31 @@ import { Trans } from "@/i18n/client";export function ApiUsageLimits() {return (<div className="flex flex-wrap items-baseline justify-between gap-x-6 gap-y-2">- <div className="flex items-baseline gap-3">- <span className="text-muted-foreground text-sm">- <Trans i18nKey="apiRateLimitLabel" defaults="Rate limit" />- </span>- <span className="font-medium text-sm tabular-nums">- <Trans- i18nKey="apiRateLimitValue"- defaults="{count} requests / minute"- values={{ count: API_RATE_LIMIT_PER_MINUTE }}- />- </span>+ <div className="flex flex-wrap items-baseline gap-x-6 gap-y-2">+ <div className="flex items-baseline gap-3">+ <span className="text-muted-foreground text-sm">+ <Trans i18nKey="apiRateLimitLabel" defaults="Rate limit" />+ </span>+ <span className="font-medium text-sm tabular-nums">+ <Trans+ i18nKey="apiRateLimitValue"+ defaults="{count} requests / minute"+ values={{ count: API_RATE_LIMIT_PER_MINUTE }}+ />+ </span>+ </div>+ <div className="flex items-baseline gap-3">+ <span className="text-muted-foreground text-sm">+ <Trans i18nKey="apiDailyLimitLabel" defaults="Daily limit" />+ </span>+ <span className="font-medium text-sm tabular-nums">+ <Trans+ i18nKey="apiDailyLimitValue"+ defaults="{count, number} requests / day"+ values={{ count: API_RATE_LIMIT_PER_DAY }}+ />+ </span>+ </div></div><Linkhref={getApiDocsPath()}diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex 341c25a89..ac9178310 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -57,8 +57,12 @@ vi.mock("next/server", () => ({after: vi.fn(),}));-vi.mock("@/lib/kv", () => ({- redis: null,+vi.mock("@/lib/feature-flags/server", () => ({+ isFeatureEnabled: () => false,+}));++vi.mock("@/lib/kv", async () => ({+ redis: (await import("../utils/fake-redis")).createFakeRedis(),}));vi.mock("@/lib/posthog", () => ({@@ -71,6 +75,7 @@ import { prisma } from "@rallly/database";import { after } from "next/server";import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";+import { redis } from "@/lib/kv";import {createPollRequestExamples,patchPollRequestExamples,@@ -85,6 +90,7 @@ import {listPollsSuccessResponseSchema,patchPollSuccessResponseSchema,} from "../schemas";+import type { FakeRedis } from "../utils/fake-redis";import { RATE_LIMIT_PER_MINUTE } from "../utils/rate-limit";import { app } from "./route";@@ -124,6 +130,7 @@ const mockApiKey = {describe("Private API - /polls", () => {beforeEach(() => {vi.clearAllMocks();+ (redis as unknown as FakeRedis).reset();// Mock findMany for the timing-safe lookupvi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([mockApiKey]);@@ -1742,9 +1749,8 @@ describe("Private API - /polls", () => {});describe("Rate limiting", () => {- // The rate limiter is keyed per space and shares a module-level memory- // store across the whole file. Use a dedicated space id here so the- // requests below don't count against (or get counted by) other tests.+ // The rate limiter is keyed per space. Use a dedicated space id here so+ // the requests below don't count against (or get counted by) other tests.const rateLimitSpaceId = "rate-limit-space-id";beforeEach(() => {diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.tsindex e0177820e..f291a0519 100644--- a/apps/web/src/app/api/private/[...route]/route.ts+++ b/apps/web/src/app/api/private/[...route]/route.ts@@ -46,7 +46,11 @@ import {} from "../schemas";import { spaceApiKeyAuth } from "../utils/api-key";import { apiError } from "../utils/poll";-import { RATE_LIMIT_PER_MINUTE, rateLimit } from "../utils/rate-limit";+import {+ RATE_LIMIT_PER_DAY,+ RATE_LIMIT_PER_MINUTE,+ rateLimit,+} from "../utils/rate-limit";import { wideEvent } from "../utils/wide-event";type Env = {@@ -122,9 +126,28 @@ const spaceNotProResponse = {},};+const retryAfterHeader = {+ "Retry-After": {+ description: "Seconds to wait before retrying the request.",+ schema: { type: "integer" as const },+ },+};+const rateLimitExceededResponse = {description:"Rate limit exceeded. Includes a `Retry-After` header indicating how many seconds to wait before retrying.",+ headers: retryAfterHeader,+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+};++const serviceUnavailableResponse = {+ description:+ "The API is temporarily unavailable, for maintenance or because the rate limit store cannot be reached. Includes a `Retry-After` header. Maintenance responses are sent before the rate limiter runs and carry no `RateLimit-*` headers.",+ headers: retryAfterHeader,content: {"application/json": {schema: resolver(errorResponseSchema),@@ -141,9 +164,11 @@ async function buildOpenApiSpec() {description: ["## Rate limits","",- `All endpoints share a single limit of **${RATE_LIMIT_PER_MINUTE} requests per minute per space**. The limit is per space, not per API key, so creating additional keys does not increase throughput.`,+ `All endpoints share two limits per space: **${RATE_LIMIT_PER_MINUTE} requests per minute** and **${RATE_LIMIT_PER_DAY} requests per day**. Both are fixed windows that open with the first request and reset when they expire. Both limits are per space, not per API key, so creating additional keys does not increase throughput.`,+ "",+ "Every response from an authenticated request includes the standard `RateLimit-*` headers. Responses sent before the limiter runs (`401`, `403`, and the maintenance `503`) do not. `RateLimit-Policy` lists both limits; `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` describe whichever limit is closest to being exhausted. When either limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.","",- "Every response includes the standard `RateLimit-*` headers describing the current limit, remaining quota, and reset time. When the limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.",+ "If the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.",].join("\n"),},components: {@@ -232,6 +257,7 @@ app.post(},403: spaceNotProResponse,429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,},}),validator("json", createPollInputSchema),@@ -472,6 +498,7 @@ app.get(},403: spaceNotProResponse,429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,},}),validator("query", listPollsQuerySchema),@@ -519,6 +546,7 @@ app.get(},403: spaceNotProResponse,429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,404: {description: "Poll not found",content: {@@ -606,6 +634,7 @@ app.patch(},403: spaceNotProResponse,429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,404: {description: "Poll not found",content: {@@ -679,6 +708,7 @@ app.get(},403: spaceNotProResponse,429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,404: {description: "Poll not found",content: {@@ -740,6 +770,7 @@ app.get(},403: spaceNotProResponse,429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,404: {description: "Poll not found",content: {@@ -801,6 +832,7 @@ app.delete(},403: spaceNotProResponse,429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,404: {description: "Poll not found",content: {diff --git a/apps/web/src/app/api/private/utils/fake-redis.ts b/apps/web/src/app/api/private/utils/fake-redis.tsnew file mode 100644index 000000000..a60ee2340--- /dev/null+++ b/apps/web/src/app/api/private/utils/fake-redis.ts@@ -0,0 +1,46 @@+/**+ * Test double for the subset of the Upstash client the rate limiter uses.+ * Interprets the increment script's semantics in memory: one counter per+ * key with an expiry, INCR on every call, expiry armed on first hit. Tests+ * control the clock through `now` and reset the store between cases.+ */+export type FakeRedis = ReturnType<typeof createFakeRedis>;++export function createFakeRedis(options?: { now?: () => number }) {+ const now = options?.now ?? (() => Date.now());+ let counters = new Map<string, { hits: number; expiresAt: number }>();+ let failWith: Error | null = null;++ const bump = (key: string, windowMs: number) => {+ const current = counters.get(key);+ if (!current || current.expiresAt <= now()) {+ const fresh = { hits: 1, expiresAt: now() + windowMs };+ counters.set(key, fresh);+ return [fresh.hits, windowMs];+ }+ current.hits += 1;+ return [current.hits, current.expiresAt - now()];+ };++ return {+ createScript: () => ({+ exec: async (keys: string[], args: string[]) => {+ if (failWith) {+ throw failWith;+ }+ return [+ ...bump(keys[0], Number(args[0])),+ ...bump(keys[1], Number(args[1])),+ ];+ },+ }),+ reset: () => {+ counters = new Map();+ failWith = null;+ },+ failNextCallsWith: (error: Error | null) => {+ failWith = error;+ },+ hits: (key: string) => counters.get(key)?.hits ?? 0,+ };+}diff --git a/apps/web/src/app/api/private/utils/rate-limit-in-process.test.ts b/apps/web/src/app/api/private/utils/rate-limit-in-process.test.tsnew file mode 100644index 000000000..e41f60528--- /dev/null+++ b/apps/web/src/app/api/private/utils/rate-limit-in-process.test.ts@@ -0,0 +1,99 @@+import { Hono } from "hono";+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));+vi.mock("@/lib/kv", () => ({ redis: null }));+vi.mock("@/lib/feature-flags/server", () => ({+ isFeatureEnabled: (feature: string) => feature === "inProcessRateLimit",+}));++import {+ createMemoryStore,+ RATE_LIMIT_PER_DAY,+ RATE_LIMIT_PER_MINUTE,+ rateLimit,+} from "./rate-limit";++const buildApp = (spaceId: string) => {+ const app = new Hono<{ Variables: { apiAuth: { spaceId: string } } }>();+ app.get(+ "/",+ async (c, next) => {+ c.set("apiAuth", { spaceId });+ await next();+ },+ rateLimit,+ (c) => c.json({ ok: true }),+ );+ return app;+};++describe("rateLimit middleware with the in-process store", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(Date.parse("2026-01-01T00:00:00.000Z"));+ });++ it("serves requests without Redis when the capability is on", async () => {+ // The store is module-level, so use a space no other test touches.+ const res = await buildApp("in-process-a").request("/");++ expect(res.status).toBe(200);+ expect(res.headers.get("RateLimit-Policy")).toBe(+ `${RATE_LIMIT_PER_MINUTE};w=60, ${RATE_LIMIT_PER_DAY};w=86400`,+ );+ expect(res.headers.get("RateLimit-Remaining")).toBe(+ String(RATE_LIMIT_PER_MINUTE - 1),+ );+ });++ it("enforces the per-minute window and releases it when the window expires", async () => {+ const app = buildApp("in-process-b");+ for (let i = 0; i < RATE_LIMIT_PER_MINUTE; i++) {+ await app.request("/");+ }++ const limited = await app.request("/");+ expect(limited.status).toBe(429);+ expect(limited.headers.get("Retry-After")).toBe("60");++ vi.advanceTimersByTime(60_000);++ const released = await app.request("/");+ expect(released.status).toBe(200);+ expect(released.headers.get("RateLimit-Remaining")).toBe(+ String(RATE_LIMIT_PER_MINUTE - 1),+ );+ });++ it("sweeps expired counters for other spaces without touching active ones", async () => {+ const store = createMemoryStore();+ await store.increment("dormant");+ vi.advanceTimersByTime(60_000);+ // Mid-window for "active": its minute counter must survive the sweep.+ await store.increment("active");+ vi.advanceTimersByTime(30_000);+ await store.increment("active");++ // The dormant minute counter expired and was swept; a fresh request+ // starts a new window instead of continuing the old count.+ const [dormantMinuteHits, , dormantDayHits] =+ await store.increment("dormant");+ expect(dormantMinuteHits).toBe(1);+ expect(dormantDayHits).toBe(2);++ const [activeMinuteHits] = await store.increment("active");+ expect(activeMinuteHits).toBe(3);+ });++ it("keeps counters separate per space", async () => {+ const a = buildApp("in-process-c");+ const b = buildApp("in-process-d");+ for (let i = 0; i < RATE_LIMIT_PER_MINUTE; i++) {+ await a.request("/");+ }++ expect((await a.request("/")).status).toBe(429);+ expect((await b.request("/")).status).toBe(200);+ });+});diff --git a/apps/web/src/app/api/private/utils/rate-limit-unconfigured.test.ts b/apps/web/src/app/api/private/utils/rate-limit-unconfigured.test.tsnew file mode 100644index 000000000..dc3fcfe77--- /dev/null+++ b/apps/web/src/app/api/private/utils/rate-limit-unconfigured.test.ts@@ -0,0 +1,43 @@+import { Hono } from "hono";+import { describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));+vi.mock("@/lib/kv", () => ({ redis: null }));+vi.mock("@/lib/feature-flags/server", () => ({+ isFeatureEnabled: () => false,+}));++import type { RateLimitFailure } from "./rate-limit";+import { rateLimit } from "./rate-limit";++describe("rateLimit middleware without a store", () => {+ it("fails closed with 503 instead of letting traffic through unmetered", async () => {+ let failure: RateLimitFailure | undefined;+ const app = new Hono<{+ Variables: {+ apiAuth: { spaceId: string };+ rateLimitFailure?: RateLimitFailure;+ };+ }>();+ app.get(+ "/",+ async (c, next) => {+ c.set("apiAuth", { spaceId: "space-1" });+ await next();+ failure = c.get("rateLimitFailure");+ },+ rateLimit,+ (c) => c.json({ ok: true }),+ );++ const res = await app.request("/");++ expect(res.status).toBe(503);+ expect(res.headers.get("Retry-After")).toBe("60");+ expect((await res.json()).error.code).toBe("SERVICE_UNAVAILABLE");+ expect(failure).toEqual({+ reason: "store_unavailable",+ message: "Rate limit store is not configured",+ });+ });+});diff --git a/apps/web/src/app/api/private/utils/rate-limit.test.ts b/apps/web/src/app/api/private/utils/rate-limit.test.tsnew file mode 100644index 000000000..51794abd5--- /dev/null+++ b/apps/web/src/app/api/private/utils/rate-limit.test.ts@@ -0,0 +1,183 @@+import { Hono } from "hono";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { FakeRedis } from "./fake-redis";++vi.mock("server-only", () => ({}));+vi.mock("@/lib/feature-flags/server", () => ({+ isFeatureEnabled: () => false,+}));++let clock = Date.parse("2026-01-01T00:00:00.000Z");++vi.mock("@/lib/kv", async () => ({+ redis: (await import("./fake-redis")).createFakeRedis({ now: () => clock }),+}));++import { redis } from "@/lib/kv";+import type { RateLimitFailure, RateLimitInfo } from "./rate-limit";+import {+ pickBindingWindow,+ RATE_LIMIT_PER_DAY,+ RATE_LIMIT_PER_MINUTE,+ rateLimit,+} from "./rate-limit";++const fakeRedis = redis as unknown as FakeRedis;++type TestEnv = {+ Variables: {+ apiAuth: { spaceId: string };+ rateLimit?: RateLimitInfo;+ rateLimitFailure?: RateLimitFailure;+ };+};++const buildApp = () => {+ const app = new Hono<TestEnv>();+ let captured: {+ rateLimit?: RateLimitInfo;+ rateLimitFailure?: RateLimitFailure;+ } = {};++ app.get(+ "/",+ async (c, next) => {+ c.set("apiAuth", { spaceId: "space-1" });+ await next();+ captured = {+ rateLimit: c.get("rateLimit"),+ rateLimitFailure: c.get("rateLimitFailure"),+ };+ },+ rateLimit,+ (c) => c.json({ ok: true }),+ );++ return { app, captured: () => captured };+};++const drain = async (app: Hono<TestEnv>, count: number) => {+ for (let i = 0; i < count; i++) {+ await app.request("/");+ }+};++describe("rateLimit middleware", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ clock = Date.parse("2026-01-01T00:00:00.000Z");+ vi.setSystemTime(clock);+ fakeRedis.reset();+ });++ it("counts a request against both windows and reports the closest one", async () => {+ const { app, captured } = buildApp();++ const res = await app.request("/");++ expect(res.status).toBe(200);+ expect(res.headers.get("RateLimit-Policy")).toBe(+ `${RATE_LIMIT_PER_MINUTE};w=60, ${RATE_LIMIT_PER_DAY};w=86400`,+ );+ expect(res.headers.get("RateLimit-Limit")).toBe(+ String(RATE_LIMIT_PER_MINUTE),+ );+ expect(res.headers.get("RateLimit-Remaining")).toBe(+ String(RATE_LIMIT_PER_MINUTE - 1),+ );+ expect(res.headers.get("RateLimit-Reset")).toBe("60");+ expect(captured().rateLimit).toMatchObject({+ minute: { used: 1, remaining: RATE_LIMIT_PER_MINUTE - 1 },+ day: { used: 1, remaining: RATE_LIMIT_PER_DAY - 1 },+ });+ });++ it("returns 429 once the per-minute limit is exceeded", async () => {+ const { app } = buildApp();+ await drain(app, RATE_LIMIT_PER_MINUTE);++ const res = await app.request("/");++ expect(res.status).toBe(429);+ expect(res.headers.get("Retry-After")).toBe("60");+ expect(res.headers.get("RateLimit-Remaining")).toBe("0");+ expect((await res.json()).error.code).toBe("RATE_LIMIT_EXCEEDED");+ });++ it("returns 429 once the daily limit is exceeded even when the minute window is fresh", async () => {+ const { app } = buildApp();+ const minuteMs = 60_000;++ // Spread the daily quota over enough minutes that no minute window trips.+ let sent = 0;+ let minutesElapsed = 0;+ while (sent < RATE_LIMIT_PER_DAY) {+ const batch = Math.min(RATE_LIMIT_PER_MINUTE, RATE_LIMIT_PER_DAY - sent);+ await drain(app, batch);+ sent += batch;+ clock += minuteMs;+ minutesElapsed += 1;+ vi.setSystemTime(clock);+ }++ const res = await app.request("/");++ expect(res.status).toBe(429);+ expect((await res.json()).error.code).toBe("RATE_LIMIT_EXCEEDED");+ expect(res.headers.get("RateLimit-Limit")).toBe(String(RATE_LIMIT_PER_DAY));+ expect(res.headers.get("RateLimit-Remaining")).toBe("0");+ // The day key was armed at the first request; Retry-After points at it.+ expect(res.headers.get("Retry-After")).toBe(+ String(86400 - minutesElapsed * 60),+ );+ });++ it("scopes both windows to the space", async () => {+ const { app } = buildApp();+ await drain(app, 3);++ expect(fakeRedis.hits("hrl:private-api:space-1")).toBe(3);+ expect(fakeRedis.hits("hrl:private-api:daily:space-1")).toBe(3);+ expect(fakeRedis.hits("hrl:private-api:space-2")).toBe(0);+ });++ it("fails closed with 503 when the store throws", async () => {+ const { app, captured } = buildApp();+ fakeRedis.failNextCallsWith(new Error("connection refused"));++ const res = await app.request("/");++ expect(res.status).toBe(503);+ expect(res.headers.get("Retry-After")).toBe("60");+ expect((await res.json()).error.code).toBe("SERVICE_UNAVAILABLE");+ expect(captured().rateLimitFailure).toEqual({+ reason: "store_error",+ message: "connection refused",+ });+ expect(captured().rateLimit).toBeUndefined();+ });+});++describe("pickBindingWindow", () => {+ const window = (limit: number, used: number) => ({+ limit,+ used,+ remaining: Math.max(limit - used, 0),+ resetTime: new Date(0),+ });++ it("prefers the minute window when it has the smaller share of quota left", () => {+ const info = { minute: window(60, 30), day: window(5000, 100) };+ expect(pickBindingWindow(info)).toBe(info.minute);+ });++ it("prefers the day window when it is closer to exhaustion", () => {+ const info = { minute: window(60, 1), day: window(5000, 4990) };+ expect(pickBindingWindow(info)).toBe(info.day);+ });++ it("breaks ties toward the minute window", () => {+ const info = { minute: window(60, 0), day: window(5000, 0) };+ expect(pickBindingWindow(info)).toBe(info.minute);+ });+});diff --git a/apps/web/src/app/api/private/utils/rate-limit.ts b/apps/web/src/app/api/private/utils/rate-limit.tsindex dc1bd123e..03ac80e06 100644--- a/apps/web/src/app/api/private/utils/rate-limit.ts+++ b/apps/web/src/app/api/private/utils/rate-limit.ts@@ -1,38 +1,245 @@-import { RedisStore } from "@hono-rate-limiter/redis";-import { rateLimiter } from "hono-rate-limiter";-import { API_RATE_LIMIT_PER_MINUTE } from "@/features/api-keys/constants";+import type { Context } from "hono";+import { createMiddleware } from "hono/factory";+import {+ API_RATE_LIMIT_PER_DAY,+ API_RATE_LIMIT_PER_MINUTE,+} from "@/features/api-keys/constants";+import { isFeatureEnabled } from "@/lib/feature-flags/server";import { redis } from "@/lib/kv";import { apiError } from "./poll";/**- * Re-exported for the OpenAPI docs and tests. The value lives in the- * api-keys feature so the settings UI can read it without pulling in this+ * Re-exported for the OpenAPI docs and tests. The values live in the+ * api-keys feature so the settings UI can read them without pulling in this* server-only module.*/export const RATE_LIMIT_PER_MINUTE = API_RATE_LIMIT_PER_MINUTE;+export const RATE_LIMIT_PER_DAY = API_RATE_LIMIT_PER_DAY;++const MINUTE_WINDOW_MS = 60 * 1000;+const DAY_WINDOW_MS = 24 * 60 * 60 * 1000;++export type RateLimitWindow = {+ limit: number;+ used: number;+ remaining: number;+ resetTime: Date;+};++export type RateLimitInfo = {+ minute: RateLimitWindow;+ day: RateLimitWindow;+};++export type RateLimitFailure = {+ reason: "store_unavailable" | "store_error";+ message: string;+};type RateLimitEnv = {Variables: {apiAuth: {spaceId: string;};+ rateLimit?: RateLimitInfo;+ rateLimitFailure?: RateLimitFailure;};};/**- * A single per-space rate limit shared by every endpoint. Must run after- * `spaceApiKeyAuth` so that `apiAuth.spaceId` is populated.+ * Increments both fixed windows atomically and returns their counters and+ * remaining TTLs. The expiry is set when a key is created, or re-armed if it+ * somehow lost its TTL, so a counter can never outlive its window.+ */+const INCREMENT_SCRIPT = `+local function bump(key, windowMs)+ local hits = redis.call("INCR", key)+ local ttl = redis.call("PTTL", key)+ if hits == 1 or ttl <= 0 then+ redis.call("PEXPIRE", key, windowMs)+ ttl = windowMs+ end+ return hits, ttl+end+local minuteHits, minuteTtl = bump(KEYS[1], tonumber(ARGV[1]))+local dayHits, dayTtl = bump(KEYS[2], tonumber(ARGV[2]))+return { minuteHits, minuteTtl, dayHits, dayTtl }+`;++type Counters = [+ minuteHits: number,+ minuteTtlMs: number,+ dayHits: number,+ dayTtlMs: number,+];++type RateLimitStore = {+ increment: (spaceId: string) => Promise<Counters>;+};++function createRedisStore(client: NonNullable<typeof redis>): RateLimitStore {+ const script = client.createScript<Counters>(INCREMENT_SCRIPT);+ return {+ increment: (spaceId) =>+ script.exec(+ [`hrl:private-api:${spaceId}`, `hrl:private-api:daily:${spaceId}`],+ [MINUTE_WINDOW_MS.toString(), DAY_WINDOW_MS.toString()],+ ),+ };+}++/**+ * Same semantics as the Lua script, held in process. Exact only when one+ * process serves every request, which is what the `inProcessRateLimit`+ * capability asserts. Expired counters are swept lazily, at most once a+ * minute on the request path, so revoked or dormant spaces do not pin+ * entries until restart. Active counters are never evicted early.+ */+export function createMemoryStore(): RateLimitStore {+ const counters = new Map<string, { hits: number; expiresAt: number }>();+ let lastSweepAt = 0;++ const sweep = (now: number) => {+ if (now - lastSweepAt < MINUTE_WINDOW_MS) {+ return;+ }+ lastSweepAt = now;+ for (const [key, entry] of counters) {+ if (entry.expiresAt <= now) {+ counters.delete(key);+ }+ }+ };++ const bump = (key: string, windowMs: number): [number, number] => {+ const now = Date.now();+ sweep(now);+ const current = counters.get(key);+ if (!current || current.expiresAt <= now) {+ counters.set(key, { hits: 1, expiresAt: now + windowMs });+ return [1, windowMs];+ }+ current.hits += 1;+ return [current.hits, current.expiresAt - now];+ };++ return {+ increment: async (spaceId) => [+ ...bump(`minute:${spaceId}`, MINUTE_WINDOW_MS),+ ...bump(`day:${spaceId}`, DAY_WINDOW_MS),+ ],+ };+}++function selectStore(): RateLimitStore | null {+ if (redis) {+ return createRedisStore(redis);+ }+ if (isFeatureEnabled("inProcessRateLimit")) {+ return createMemoryStore();+ }+ return null;+}++const store = selectStore();++function toWindow(limit: number, hits: number, ttlMs: number): RateLimitWindow {+ return {+ limit,+ used: hits,+ remaining: Math.max(limit - hits, 0),+ resetTime: new Date(Date.now() + ttlMs),+ };+}++function resetSeconds(window: RateLimitWindow) {+ return Math.max(+ 0,+ Math.ceil((window.resetTime.getTime() - Date.now()) / 1000),+ );+}++/**+ * The window closest to exhaustion, by fraction of quota left, is the one+ * the `RateLimit-*` headers report so a client backing off on them slows+ * down for whichever limit will bite first.+ */+export function pickBindingWindow(info: RateLimitInfo) {+ const minuteFraction = info.minute.remaining / info.minute.limit;+ const dayFraction = info.day.remaining / info.day.limit;+ return minuteFraction <= dayFraction ? info.minute : info.day;+}++function setRateLimitHeaders(c: Context, info: RateLimitInfo) {+ const binding = pickBindingWindow(info);+ c.header(+ "RateLimit-Policy",+ `${info.minute.limit};w=${MINUTE_WINDOW_MS / 1000}, ${info.day.limit};w=${DAY_WINDOW_MS / 1000}`,+ );+ c.header("RateLimit-Limit", binding.limit.toString());+ c.header("RateLimit-Remaining", binding.remaining.toString());+ c.header("RateLimit-Reset", resetSeconds(binding).toString());+}++function serviceUnavailable(c: Context, failure: RateLimitFailure) {+ c.set("rateLimitFailure", failure);+ return c.json(+ apiError(+ "SERVICE_UNAVAILABLE",+ "The API is temporarily unavailable. Retry after the time indicated in the Retry-After header.",+ ),+ 503,+ { "Retry-After": "60" },+ );+}++/**+ * Per-space rate limits shared by every endpoint: a per-minute window that+ * bounds burst rate and a daily window that bounds volume. Both count every+ * request, including rejected ones, and both key on the space so extra API+ * keys do not raise them. Must run after `spaceApiKeyAuth` so that+ * `apiAuth.spaceId` is populated.*- * Known limitation: when Redis/KV is unavailable the fallback is a per- * instance memory store, which on Vercel is effectively no limit. Accepted- * for now; request logging makes it observable.+ * Fails closed: without KV, and without the `inProcessRateLimit` capability+ * that makes a per-process counter exact, a missing store is a+ * misconfiguration and an unreachable store is an outage. Both answer 503+ * rather than letting traffic through unmetered, and both are surfaced on+ * the wide event via `rateLimitFailure`.*/-export const rateLimit = rateLimiter<RateLimitEnv>({- windowMs: 60 * 1000,- limit: RATE_LIMIT_PER_MINUTE,- keyGenerator: (c) => `private-api:${c.get("apiAuth").spaceId}`,- store: redis ? new RedisStore({ client: redis }) : undefined,- handler: (c) => {+export const rateLimit = createMiddleware<RateLimitEnv>(async (c, next) => {+ if (!store) {+ return serviceUnavailable(c, {+ reason: "store_unavailable",+ message: "Rate limit store is not configured",+ });+ }++ let result: Counters;+ try {+ result = await store.increment(c.get("apiAuth").spaceId);+ } catch (error) {+ return serviceUnavailable(c, {+ reason: "store_error",+ message: error instanceof Error ? error.message : String(error),+ });+ }++ const [minuteHits, minuteTtl, dayHits, dayTtl] = result;+ const info: RateLimitInfo = {+ minute: toWindow(RATE_LIMIT_PER_MINUTE, minuteHits, minuteTtl),+ day: toWindow(RATE_LIMIT_PER_DAY, dayHits, dayTtl),+ };++ c.set("rateLimit", info);+ setRateLimitHeaders(c, info);++ const exceeded = [info.minute, info.day].filter(+ (window) => window.used > window.limit,+ );++ if (exceeded.length > 0) {+ const retryAfter = Math.max(...exceeded.map(resetSeconds));+ c.header("Retry-After", retryAfter.toString());return c.json(apiError("RATE_LIMIT_EXCEEDED",@@ -40,5 +247,7 @@ export const rateLimit = rateLimiter<RateLimitEnv>({),429,);- },+ }++ await next();});diff --git a/apps/web/src/app/api/private/utils/wide-event.test.ts b/apps/web/src/app/api/private/utils/wide-event.test.tsindex 65c19ec3c..ddbbf6423 100644--- a/apps/web/src/app/api/private/utils/wide-event.test.ts+++ b/apps/web/src/app/api/private/utils/wide-event.test.ts@@ -1,6 +1,5 @@import { Hono } from "hono";import { bearerAuth } from "hono/bearer-auth";-import { rateLimiter } from "hono-rate-limiter";import { beforeEach, describe, expect, it, vi } from "vitest";const info = vi.fn();@@ -19,14 +18,24 @@ vi.mock("@rallly/logger", () => ({}),}));+import type { RateLimitFailure, RateLimitInfo } from "./rate-limit";import { wideEvent } from "./wide-event";type TestEnv = {Variables: {apiAuth?: { spaceId: string; apiKeyId: string };+ rateLimit?: RateLimitInfo;+ rateLimitFailure?: RateLimitFailure;};};+const window = (limit: number, used: number) => ({+ limit,+ used,+ remaining: limit - used,+ resetTime: new Date("2026-01-01T00:01:00.000Z"),+});+const buildApp = () => {const app = new Hono<TestEnv>();app.use("*", wideEvent);@@ -35,16 +44,27 @@ const buildApp = () => {"/ok",async (c, next) => {c.set("apiAuth", { spaceId: "space-1", apiKeyId: "key-1" });+ c.set("rateLimit", { minute: window(5, 1), day: window(100, 7) });await next();},- rateLimiter({- windowMs: 60_000,- limit: 5,- keyGenerator: () => "space-1",- }),(c) => c.json({ ok: true }),);+ app.get(+ "/store-down",+ async (c, next) => {+ c.set("apiAuth", { spaceId: "space-1", apiKeyId: "key-1" });+ await next();+ },+ (c) => {+ c.set("rateLimitFailure", {+ reason: "store_error",+ message: "connection refused",+ });+ return c.json({ error: {} }, 503);+ },+ );+app.get("/unauthorized",bearerAuth({ verifyToken: async () => false }),@@ -82,10 +102,29 @@ describe("wideEvent middleware", () => {rateLimiter: "private-api",rateLimiterConsumedPoints: 1,rateLimiterRemainingPoints: 4,+ rateLimiterDailyConsumedPoints: 7,+ rateLimiterDailyRemainingPoints: 93,});expect(typeof event.durationMs).toBe("number");});+ it("logs an error event with the store failure when the limiter fails closed", async () => {+ const res = await buildApp().request("/store-down");++ expect(res.status).toBe(503);+ expect(error).toHaveBeenCalledTimes(1);+ expect(error.mock.calls[0][0]).toMatchObject({+ statusCode: 503,+ spaceId: "space-1",+ rateLimiter: "private-api",+ rateLimiterError: "store_error",+ errorType: "RateLimitStoreError",+ errorCode: "SERVICE_UNAVAILABLE",+ errorMessage: "connection refused",+ isRetriable: true,+ });+ });+it("warns and captures a 401 without auth context", async () => {const res = await buildApp().request("/unauthorized");diff --git a/apps/web/src/app/api/private/utils/wide-event.ts b/apps/web/src/app/api/private/utils/wide-event.tsindex 522541fc4..d2fa473f9 100644--- a/apps/web/src/app/api/private/utils/wide-event.ts+++ b/apps/web/src/app/api/private/utils/wide-event.ts@@ -1,6 +1,6 @@import { createWideEvent, logger } from "@rallly/logger";import { createMiddleware } from "hono/factory";-import type { RateLimitInfo } from "hono-rate-limiter";+import type { RateLimitFailure, RateLimitInfo } from "./rate-limit";type WideEventEnv = {Variables: {@@ -9,6 +9,7 @@ type WideEventEnv = {apiKeyId: string;};rateLimit?: RateLimitInfo;+ rateLimitFailure?: RateLimitFailure;};};@@ -56,8 +57,22 @@ export const wideEvent = createMiddleware<WideEventEnv>(async (c, next) => {const rateLimit = c.get("rateLimit");if (rateLimit) {event.rateLimiter = "private-api";- event.rateLimiterConsumedPoints = rateLimit.used;- event.rateLimiterRemainingPoints = rateLimit.remaining;+ event.rateLimiterConsumedPoints = rateLimit.minute.used;+ event.rateLimiterRemainingPoints = rateLimit.minute.remaining;+ event.rateLimiterDailyConsumedPoints = rateLimit.day.used;+ event.rateLimiterDailyRemainingPoints = rateLimit.day.remaining;+ }++ // A fail-closed 503 from the rate limiter is returned, not thrown, so+ // `c.error` is empty; carry its cause so an outage is queryable.+ const rateLimitFailure = c.get("rateLimitFailure");+ if (rateLimitFailure) {+ event.rateLimiter = "private-api";+ event.rateLimiterError = rateLimitFailure.reason;+ event.errorType = "RateLimitStoreError";+ event.errorCode = "SERVICE_UNAVAILABLE";+ event.errorMessage = rateLimitFailure.message;+ event.isRetriable = true;}event.durationMs = Date.now() - startTime;diff --git a/apps/web/src/features/api-keys/constants.ts b/apps/web/src/features/api-keys/constants.tsindex 835443f28..77efa8eb3 100644--- a/apps/web/src/features/api-keys/constants.ts+++ b/apps/web/src/features/api-keys/constants.ts@@ -8,6 +8,17 @@*/export const API_RATE_LIMIT_PER_MINUTE = 60;+/**+ * Requests per 24 hour window allowed for a single space. The window+ * opens with the first request and both windows are fixed, not sliding. Bounds the+ * monthly worst case at roughly 150,000 requests so a runaway integration+ * stays a nuisance rather than a cost. The heaviest real integration does+ * about 45 requests a day, so this is not a limit anyone should reach.+ *+ * Same single-source-of-truth rule as the per-minute limit.+ */+export const API_RATE_LIMIT_PER_DAY = 5000;+/*** Path segment for the current version of the public API. Keeping it here* means moving between versions (e.g. `private` → `v1`) only touches onediff --git a/apps/web/src/lib/feature-flags/config.ts b/apps/web/src/lib/feature-flags/config.tsindex 3bdd2c339..60887d139 100644--- a/apps/web/src/lib/feature-flags/config.ts+++ b/apps/web/src/lib/feature-flags/config.ts@@ -5,6 +5,7 @@ import { isCalendarsEnabled } from "@/features/calendars/constants";import { isEventTypesEnabled } from "@/features/event-types/constants";import { isFeedbackEnabled } from "@/features/feedback/constants";import { isQuickCreateEnabled } from "@/features/quick-create/constants";+import { isSelfHosted } from "@/lib/constants";import type { FeatureFlagConfig } from "@/lib/feature-flags/types";import { isStorageEnabled } from "@/lib/storage";@@ -27,4 +28,8 @@ export const featureFlagConfig: FeatureFlagConfig = {// feature parity with the legacy admin and cuts over.pollAdmin: env.NODE_ENV === "development",quickCreate: isQuickCreateEnabled,+ // Self-hosted runs one process, so a per-process counter is an exact rate+ // limit and Redis is not required. Cloud runs many short-lived instances,+ // where a per-process counter is no limit at all, so it must use KV.+ inProcessRateLimit: isSelfHosted,};diff --git a/apps/web/src/lib/feature-flags/types.ts b/apps/web/src/lib/feature-flags/types.tsindex 0ecfa1832..3ed249f39 100644--- a/apps/web/src/lib/feature-flags/types.ts+++ b/apps/web/src/lib/feature-flags/types.ts@@ -9,6 +9,7 @@ export interface FeatureFlagConfig {eventTypes: boolean;pollAdmin: boolean;quickCreate: boolean;+ inProcessRateLimit: boolean;}export type Feature = keyof FeatureFlagConfig;