Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Count rate limits in Postgres
Claude96b8b2550724
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 24565ad..f928963 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -56,6 +56,11 @@ jobs:node-version-file: .nvmrccache: npm- run: npm ci+ # The tests that need a real Postgres: the rate limit statement and+ # the cleanup job's lock.+ - run: npm run test:db+ env:+ E2E_DATABASE_URL: postgres://signudoc:[email protected]:5432/signudoc_e2e- run: npx playwright install --with-deps chromium- run: npm run test:e2eenv:diff --git a/db/migrations/20261112070000_rate_limits.sql b/db/migrations/20261112070000_rate_limits.sqlnew file mode 100644index 0000000..9cd01cd--- /dev/null+++ b/db/migrations/20261112070000_rate_limits.sql@@ -0,0 +1,16 @@+-- Rate limit counters.+--+-- One row per thing being limited (a hash of "which limit, for whom"), with+-- how many requests it has made in its current window and when that window+-- ends. Kept in Postgres because a deployment on Vercel runs as many+-- short-lived instances that share nothing else.++create table if not exists public.rate_limits (+ key text primary key,+ count integer not null,+ expires_at bigint not null+);++-- For clearing out windows that have ended.+create index if not exists rate_limits_expires_at_idx+ on public.rate_limits (expires_at);diff --git a/package.json b/package.jsonindex a9c7369..d4061f8 100644--- a/package.json+++ b/package.json@@ -20,6 +20,7 @@"format": "prettier --write .","format:check": "prettier --check .","test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test \"src/**/*.test.ts\" \"db/**/*.test.mjs\"",+ "test:db": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test --test-concurrency=1 \"src/**/*.dbtest.ts\"","test:e2e": "playwright test"},"dependencies": {diff --git a/src/app/api/admin/email/route.ts b/src/app/api/admin/email/route.tsindex 158c752..4a355b4 100644--- a/src/app/api/admin/email/route.ts+++ b/src/app/api/admin/email/route.ts@@ -59,7 +59,7 @@ export async function POST(request: Request) {}const session = sessionResult;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "email_setup_action",key: buildRateLimitKey(["email-setup", session.user.id]),limit: 20,diff --git a/src/app/api/admin/settings/route.ts b/src/app/api/admin/settings/route.tsindex 1140a12..2ec2829 100644--- a/src/app/api/admin/settings/route.ts+++ b/src/app/api/admin/settings/route.ts@@ -28,7 +28,7 @@ export async function PUT(request: Request) {}const session = sessionResult;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "organization_settings_update",key: buildRateLimitKey(["organization-settings", session.user.id]),limit: 30,diff --git a/src/app/api/contact/route.ts b/src/app/api/contact/route.tsindex f3e4bce..69e776f 100644--- a/src/app/api/contact/route.ts+++ b/src/app/api/contact/route.ts@@ -25,7 +25,7 @@ export async function POST(request: Request) {const ipAddress = getClientIpAddress(request.headers);const userAgent = getRequestUserAgent(request.headers);- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "contact_form_submit",key: buildRateLimitKey(["contact-form",diff --git a/src/app/api/download/[token]/route.ts b/src/app/api/download/[token]/route.tsindex af0f4c5..9f495b2 100644--- a/src/app/api/download/[token]/route.ts+++ b/src/app/api/download/[token]/route.ts@@ -26,7 +26,7 @@ export async function GET(context: PublicDownloadRouteContext,) {const { token } = await context.params;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "public_download",key: buildRateLimitKey(["public-download",diff --git a/src/app/api/envelopes/[id]/nudge/route.ts b/src/app/api/envelopes/[id]/nudge/route.tsindex b7ebb29..a11a97b 100644--- a/src/app/api/envelopes/[id]/nudge/route.ts+++ b/src/app/api/envelopes/[id]/nudge/route.ts@@ -33,7 +33,7 @@ export async function POST(const session = sessionResult;const { id } = await context.params;const ipAddress = getClientIpAddress(request.headers);- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "envelope_nudge",key: buildRateLimitKey(["envelope-nudge", session.user.id, id]),limit: 5,diff --git a/src/app/api/envelopes/[id]/send/route.ts b/src/app/api/envelopes/[id]/send/route.tsindex 9314821..9e4bada 100644--- a/src/app/api/envelopes/[id]/send/route.ts+++ b/src/app/api/envelopes/[id]/send/route.ts@@ -37,7 +37,7 @@ export async function POST(const session = sessionResult;const { id } = await context.params;const ipAddress = getClientIpAddress(request.headers);- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "draft_envelope_send",key: buildRateLimitKey(["envelope-send", session.user.id]),limit: 10,diff --git a/src/app/api/envelopes/[id]/void/route.ts b/src/app/api/envelopes/[id]/void/route.tsindex 714afe2..baf6285 100644--- a/src/app/api/envelopes/[id]/void/route.ts+++ b/src/app/api/envelopes/[id]/void/route.ts@@ -30,7 +30,7 @@ export async function POST(const session = sessionResult;const { id } = await context.params;const ipAddress = getClientIpAddress(request.headers);- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "sent_envelope_void",key: buildRateLimitKey(["envelope-void", session.user.id, id]),limit: 20,diff --git a/src/app/api/envelopes/route.ts b/src/app/api/envelopes/route.tsindex 4404d23..07aadc6 100644--- a/src/app/api/envelopes/route.ts+++ b/src/app/api/envelopes/route.ts@@ -35,7 +35,7 @@ export async function POST(request: Request) {}const session = sessionResult;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "draft_envelope_create",key: buildRateLimitKey(["draft-create", session.user.id]),limit: 20,diff --git a/src/app/api/setup/route.ts b/src/app/api/setup/route.tsindex 8c7c195..691ab03 100644--- a/src/app/api/setup/route.ts+++ b/src/app/api/setup/route.ts@@ -60,7 +60,7 @@ async function createAdminAccount(input: {export async function POST(request: Request) {const ipAddress = getClientIpAddress(request.headers);- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "setup_submit",key: buildRateLimitKey(["setup", ipAddress ?? "unknown"]),limit: 10,diff --git a/src/app/api/signing/[token]/decline/route.ts b/src/app/api/signing/[token]/decline/route.tsindex 1693381..1eb3f43 100644--- a/src/app/api/signing/[token]/decline/route.ts+++ b/src/app/api/signing/[token]/decline/route.ts@@ -22,7 +22,7 @@ export async function POST(context: SigningDeclineRouteContext,) {const { token } = await context.params;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "signing_decline",key: buildRateLimitKey(["signing-decline",diff --git a/src/app/api/signing/[token]/document/route.ts b/src/app/api/signing/[token]/document/route.tsindex ff3b93d..6a54eb0 100644--- a/src/app/api/signing/[token]/document/route.ts+++ b/src/app/api/signing/[token]/document/route.ts@@ -17,7 +17,7 @@ export async function GET(context: SigningDocumentRouteContext,) {const { token } = await context.params;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "signing_document_read",key: buildRateLimitKey(["signing-document",diff --git a/src/app/api/signing/[token]/route.ts b/src/app/api/signing/[token]/route.tsindex 4460d2d..55e550b 100644--- a/src/app/api/signing/[token]/route.ts+++ b/src/app/api/signing/[token]/route.ts@@ -14,7 +14,7 @@ type SigningRouteContext = {export async function GET(request: Request, context: SigningRouteContext) {const { token } = await context.params;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "signing_token_read",key: buildRateLimitKey(["signing-read",diff --git a/src/app/api/signing/[token]/submit/route.ts b/src/app/api/signing/[token]/submit/route.tsindex fcbd007..ac1c9a6 100644--- a/src/app/api/signing/[token]/submit/route.ts+++ b/src/app/api/signing/[token]/submit/route.ts@@ -22,7 +22,7 @@ export async function POST(context: SigningSubmitRouteContext,) {const { token } = await context.params;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "signing_submit",key: buildRateLimitKey(["signing-submit",diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.tsindex e317c58..58999b3 100644--- a/src/app/api/uploads/route.ts+++ b/src/app/api/uploads/route.ts@@ -23,7 +23,7 @@ export async function POST(request: Request) {}const session = sessionResult;- const rateLimitResponse = applyRateLimit({+ const rateLimitResponse = await applyRateLimit({category: "direct_upload_authorize",key: buildRateLimitKey(["direct-upload", session.user.id]),limit: 30,diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.tsindex 2f75d0c..87a91ab 100644--- a/src/lib/auth/server.ts+++ b/src/lib/auth/server.ts@@ -15,6 +15,8 @@ import {type TransactionalEmailMessage,} from "../services/email.ts";import { withUserEmailLegalFooter } from "../services/email-legal-footer.ts";+import { consumeRateLimit } from "../security/rate-limit.ts";+import { getClientIpHeaderNames } from "../security/request.ts";import { requireConfigValue } from "../services/service-config.ts";import { getBranding, getSettings, getSetupState } from "../settings.ts";import { evaluateSignup } from "../signup-policy.ts";@@ -309,6 +311,9 @@ export function createAppAuth({return Array.from(trustedOrigins);},advanced: {+ // Where the visitor's address is read from, for rate limits and+ // sessions: the same headers the rest of the app trusts.+ ipAddress: { ipAddressHeaders: getClientIpHeaderNames(env) },// Secure cookies whenever the site is served over HTTPS, which is// always in production except for a build run on localhost.useSecureCookies: baseURL.startsWith("https://"),@@ -391,6 +396,25 @@ export function createAppAuth({}}),},+ // Better Auth limits its own routes (three sign-in or sign-up attempts+ // in ten seconds, for one). Its counts go in the same Postgres table as+ // the app's other limits, so they hold across instances.+ rateLimit: {+ customStorage: {+ consume: async (key, rule) => {+ const decision = await consumeRateLimit({+ key: `auth:${key}`,+ limit: rule.max,+ windowMs: rule.window * 1000,+ });++ return {+ allowed: decision.allowed,+ retryAfter: decision.allowed ? null : decision.retryAfterSeconds,+ };+ },+ },+ },session: {cookieCache: {enabled: true,diff --git a/src/lib/db/test-database.ts b/src/lib/db/test-database.tsnew file mode 100644index 0000000..eaa065a--- /dev/null+++ b/src/lib/db/test-database.ts@@ -0,0 +1,55 @@+import pg from "pg";++import { runMigrations } from "../../../db/migrate.mjs";++// For the tests that need a real Postgres (npm run test:db). They use the+// same disposable database as the end-to-end test, bring its schema up to+// date, and leave whatever else is in it alone.++const DEFAULT_TEST_DATABASE_URL =+ "postgres://signudoc:[email protected]:5432/signudoc_e2e";++async function ensureDatabaseExists(connectionString: string, name: string) {+ const maintenanceUrl = new URL(connectionString);++ maintenanceUrl.pathname = "/postgres";++ const client = new pg.Client({+ connectionString: maintenanceUrl.toString(),+ });++ try {+ await client.connect();++ const existing = await client.query(+ "select 1 from pg_database where datname = $1",+ [name],+ );++ if (existing.rowCount === 0) {+ await client.query(`create database "${name}"`);+ }+ } catch {+ // No access to the maintenance database: assume the test database was+ // made some other way and let the connection below report any problem.+ } finally {+ await client.end().catch(() => undefined);+ }+}++export async function openTestDatabase(): Promise<pg.Pool> {+ const connectionString =+ process.env.E2E_DATABASE_URL ?? DEFAULT_TEST_DATABASE_URL;+ const name = new URL(connectionString).pathname.replace(/^\//, "");++ if (!name.toLowerCase().includes("e2e")) {+ throw new Error(+ `Refusing to run database tests on "${name}". The test database must have "e2e" in its name.`,+ );+ }++ await ensureDatabaseExists(connectionString, name);+ await runMigrations({ connectionString, log: () => undefined });++ return new pg.Pool({ connectionString, max: 12 });+}diff --git a/src/lib/security/rate-limit.dbtest.ts b/src/lib/security/rate-limit.dbtest.tsnew file mode 100644index 0000000..d6e9aa2--- /dev/null+++ b/src/lib/security/rate-limit.dbtest.ts@@ -0,0 +1,143 @@+import assert from "node:assert/strict";+import { createHash, randomUUID } from "node:crypto";+import { after, before, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "../db/test-database.ts";+import { consumeRateLimit, deleteExpiredRateLimits } from "./rate-limit.ts";++// The rate limit statement against a real Postgres. Run with+// `npm run test:db`.+//+// Time is passed in rather than read from the clock, and set in the future+// so that nothing else clearing finished windows can take these rows.++const MINUTE = 60 * 1000;+const START = 4_000_000_000_000;++let database: pg.Pool;++before(async () => {+ database = await openTestDatabase();+});++after(async () => {+ await database.query(+ "delete from public.rate_limits where expires_at >= $1",+ [START],+ );+ await database.end();+});++function uniqueKey(label: string) {+ return `dbtest:${label}:${randomUUID()}`;+}++function hash(value: string) {+ return createHash("sha256").update(value).digest("hex");+}++test("requests up to the limit pass, the next one waits, and the count starts over when the window ends", async () => {+ const input = { key: uniqueKey("window"), limit: 2, windowMs: MINUTE };+ const at = (offset: number) =>+ consumeRateLimit({ ...input, now: START + offset }, { database });++ assert.deepEqual(await at(0), { allowed: true, retryAfterSeconds: 60 });+ assert.deepEqual(await at(1000), { allowed: true, retryAfterSeconds: 59 });+ assert.deepEqual(await at(15_000), { allowed: false, retryAfterSeconds: 45 });+ // Trying again while blocked does not push the window back.+ assert.deepEqual(await at(59_000), { allowed: false, retryAfterSeconds: 1 });+ assert.deepEqual(await at(MINUTE), { allowed: true, retryAfterSeconds: 60 });+ assert.deepEqual(await at(MINUTE + 1), {+ allowed: true,+ retryAfterSeconds: 60,+ });+ assert.equal((await at(MINUTE + 2)).allowed, false);+});++test("only a hash of the key is stored", async () => {+ const key = uniqueKey("hashed");++ await consumeRateLimit(+ { key, limit: 1, now: START, windowMs: MINUTE },+ { database },+ );++ const stored = await database.query<{ key: string }>(+ "select key from public.rate_limits where key = any($1)",+ [[key, hash(key)]],+ );++ assert.deepEqual(+ stored.rows.map((row) => row.key),+ [hash(key)],+ );+});++test("requests that arrive together are each counted once", async () => {+ const key = uniqueKey("burst");+ const decisions = await Promise.all(+ Array.from({ length: 40 }, () =>+ consumeRateLimit(+ { key, limit: 5, now: START, windowMs: MINUTE },+ { database },+ ),+ ),+ );++ assert.equal(decisions.filter((decision) => decision.allowed).length, 5);++ const stored = await database.query<{ count: number }>(+ "select count from public.rate_limits where key = $1",+ [hash(key)],+ );++ assert.equal(stored.rows[0]?.count, 40);+});++test("each key has its own count", async () => {+ const first = uniqueKey("separate");+ const second = uniqueKey("separate");+ const limit = { limit: 1, now: START, windowMs: MINUTE };++ assert.equal(+ (await consumeRateLimit({ ...limit, key: first }, { database })).allowed,+ true,+ );+ assert.equal(+ (await consumeRateLimit({ ...limit, key: second }, { database })).allowed,+ true,+ );+ assert.equal(+ (await consumeRateLimit({ ...limit, key: first }, { database })).allowed,+ false,+ );+});++test("finished windows are cleared and live ones are kept", async () => {+ const ended = uniqueKey("ended");+ const live = uniqueKey("live");++ await consumeRateLimit(+ { key: ended, limit: 1, now: START, windowMs: MINUTE },+ { database },+ );+ await consumeRateLimit(+ { key: live, limit: 1, now: START + 1, windowMs: MINUTE },+ { database },+ );++ // The first window ends exactly now; the second has a millisecond left.+ const removed = await deleteExpiredRateLimits(database, START + MINUTE);+ const remaining = await database.query<{ key: string }>(+ "select key from public.rate_limits where key = any($1)",+ [[hash(ended), hash(live)]],+ );++ assert.ok(removed >= 1);+ assert.deepEqual(+ remaining.rows.map((row) => row.key),+ [hash(live)],+ );+});diff --git a/src/lib/security/rate-limit.test.ts b/src/lib/security/rate-limit.test.tsnew file mode 100644index 0000000..e38944c--- /dev/null+++ b/src/lib/security/rate-limit.test.ts@@ -0,0 +1,161 @@+import assert from "node:assert/strict";+import { beforeEach, test } from "node:test";++import type { DbExecutor } from "../db/connection.ts";+import {+ clearRateLimitStoreForTests,+ consumeRateLimit,+ consumeRateLimitInMemory,+} from "./rate-limit.ts";++// The statement itself is exercised against a real Postgres in+// rate-limit.dbtest.ts. These tests cover what happens around it.++const MINUTE = 60 * 1000;+const START = 1_800_000_000_000;++type Query = { text: string; values: unknown[] };++function fakeDatabase(+ respond: (query: Query) => { count: number; expires_at: number } | Error,+) {+ const queries: Query[] = [];+ const database = {+ query: (text: string, values: unknown[]) => {+ const query = { text, values };++ queries.push(query);++ const response = respond(query);++ return response instanceof Error+ ? Promise.reject(response)+ : Promise.resolve({ rowCount: 1, rows: [response] });+ },+ } as unknown as DbExecutor;++ return { database, queries };+}++beforeEach(() => {+ clearRateLimitStoreForTests();+});++test("in memory, requests up to the limit are allowed and the next is not", () => {+ const input = { key: "contact:1.2.3.4", limit: 3, windowMs: MINUTE };++ for (let request = 0; request < 3; request += 1) {+ assert.equal(+ consumeRateLimitInMemory({ ...input, now: START + request }).allowed,+ true,+ );+ }++ assert.deepEqual(consumeRateLimitInMemory({ ...input, now: START + 10 }), {+ allowed: false,+ retryAfterSeconds: 60,+ });+});++test("in memory, the wait shrinks as the window runs out and trying again does not extend it", () => {+ const input = { key: "contact:1.2.3.4", limit: 1, windowMs: MINUTE };++ consumeRateLimitInMemory({ ...input, now: START });++ assert.equal(+ consumeRateLimitInMemory({ ...input, now: START + 15_000 })+ .retryAfterSeconds,+ 45,+ );+ assert.equal(+ consumeRateLimitInMemory({ ...input, now: START + 59_500 })+ .retryAfterSeconds,+ 1,+ );+ assert.equal(+ consumeRateLimitInMemory({ ...input, now: START + MINUTE }).allowed,+ true,+ );+});++test("in memory, each key has its own count", () => {+ const limit = { limit: 1, windowMs: MINUTE };++ assert.equal(+ consumeRateLimitInMemory({ ...limit, key: "a", now: START }).allowed,+ true,+ );+ assert.equal(+ consumeRateLimitInMemory({ ...limit, key: "b", now: START }).allowed,+ true,+ );+ assert.equal(+ consumeRateLimitInMemory({ ...limit, key: "a", now: START }).allowed,+ false,+ );+});++test("the database's count decides, and only a hash of the key is sent to it", async () => {+ const { database, queries } = fakeDatabase(() => ({+ count: 6,+ expires_at: START + 30_000,+ }));++ const decision = await consumeRateLimit(+ {+ key: "signing:secret-signing-token",+ limit: 5,+ now: START,+ windowMs: MINUTE,+ },+ { database },+ );++ assert.deepEqual(decision, { allowed: false, retryAfterSeconds: 30 });++ const [hashedKey, now, windowMs] = queries[0]?.values ?? [];++ assert.match(String(hashedKey), /^[0-9a-f]{64}$/);+ assert.equal(now, START);+ assert.equal(windowMs, MINUTE);+ assert.equal(JSON.stringify(queries).includes("secret-signing-token"), false);+});++test("a count within the limit is allowed", async () => {+ const { database } = fakeDatabase(() => ({+ count: 5,+ expires_at: START + MINUTE,+ }));++ assert.equal(+ (+ await consumeRateLimit(+ { key: "k", limit: 5, now: START, windowMs: MINUTE },+ { database },+ )+ ).allowed,+ true,+ );+});++test("when the database cannot be used the limit is still enforced, from memory", async (t) => {+ const warn = t.mock.method(console, "warn", () => undefined);+ const { database } = fakeDatabase(+ () => new Error('relation "public.rate_limits" does not exist'),+ );+ const input = { key: "contact:1.2.3.4", limit: 2, windowMs: MINUTE };+ const decisions = [];++ for (let request = 0; request < 3; request += 1) {+ decisions.push(+ await consumeRateLimit({ ...input, now: START + request }, { database }),+ );+ }++ assert.deepEqual(+ decisions.map((decision) => decision.allowed),+ [true, true, false],+ );+ // Said once, not once per request.+ assert.equal(warn.mock.callCount(), 1);+});diff --git a/src/lib/security/rate-limit.ts b/src/lib/security/rate-limit.tsindex 73c6c31..6542843 100644--- a/src/lib/security/rate-limit.ts+++ b/src/lib/security/rate-limit.ts@@ -1,95 +1,193 @@-type RateLimitResult = {- remaining: number;- resetAt: number;+import { createHash } from "node:crypto";++import { getDb, type DbExecutor } from "../db/connection.ts";++// Rate limits are counted in Postgres, in the rate_limits table: on Vercel+// the app runs as many short-lived instances, and a count kept in one of+// them is not a limit. Each check is a single statement, so two requests+// that arrive together cannot both read the old count.+//+// If the database cannot be asked (no database yet, or a preview deployment+// whose shared database does not have the table), the count is kept in this+// instance's memory instead, which is what the app did before.++export type RateLimitDecision = {+ allowed: boolean;+ /** Seconds until the current window ends. At least 1 when not allowed. */+ retryAfterSeconds: number;};-type SlidingWindowEntry = {+type RateLimitInput = {+ key: string;+ limit: number;+ now?: number;+ windowMs: number;+};++type ConsumeRateLimitOptions = {+ database?: DbExecutor;+};++type MemoryEntry = {+ count: number;expiresAt: number;- timestamps: number[];};declare global {- var __signudocRateLimitStore: Map<string, SlidingWindowEntry> | undefined;+ var __signudocRateLimitStore: Map<string, MemoryEntry> | undefined;var __signudocRateLimitSweepAt: number | undefined;+ var __signudocRateLimitWarnedAt: number | undefined;}-const rateLimitStore =- globalThis.__signudocRateLimitStore ??- (globalThis.__signudocRateLimitStore = new Map<string, SlidingWindowEntry>());--const RATE_LIMIT_SWEEP_INTERVAL_MS = 60 * 1000;+const memoryStore = (globalThis.__signudocRateLimitStore ??= new Map<+ string,+ MemoryEntry+>());++const MEMORY_SWEEP_INTERVAL_MS = 60 * 1000;+const FALLBACK_WARNING_INTERVAL_MS = 60 * 1000;+// One request in this many also clears out windows that have ended. The+// daily cleanup job does the same, so this only matters where there is none.+const DATABASE_SWEEP_ODDS = 200;++// The key names who is being limited, and for the signing pages that+// includes the signing token. Only a hash of it is stored.+function hashKey(key: string): string {+ return createHash("sha256").update(key).digest("hex");+}-function sweepExpiredRateLimitEntries(now: number) {- const nextSweepAt = globalThis.__signudocRateLimitSweepAt ?? 0;+function toDecision(+ count: number,+ expiresAt: number,+ input: RateLimitInput,+ now: number,+): RateLimitDecision {+ return {+ allowed: count <= input.limit,+ retryAfterSeconds: Math.max(1, Math.ceil((expiresAt - now) / 1000)),+ };+}- if (nextSweepAt > now) {+function sweepMemoryStore(now: number) {+ if ((globalThis.__signudocRateLimitSweepAt ?? 0) > now) {return;}- for (const [key, entry] of rateLimitStore.entries()) {+ for (const [key, entry] of memoryStore.entries()) {if (entry.expiresAt <= now) {- rateLimitStore.delete(key);+ memoryStore.delete(key);}}- globalThis.__signudocRateLimitSweepAt = now + RATE_LIMIT_SWEEP_INTERVAL_MS;+ globalThis.__signudocRateLimitSweepAt = now + MEMORY_SWEEP_INTERVAL_MS;}-export class RateLimitExceededError extends Error {- readonly retryAfterSeconds: number;+/** The same counting as the database does, for one instance only. */+export function consumeRateLimitInMemory(+ input: RateLimitInput,+): RateLimitDecision {+ const now = input.now ?? Date.now();- constructor(retryAfterSeconds: number) {- super("Too many requests. Please try again soon.");- this.name = "RateLimitExceededError";- this.retryAfterSeconds = retryAfterSeconds;- }-}+ sweepMemoryStore(now);-export function enforceSlidingWindowRateLimit(input: {- key: string;- limit: number;- now?: number;- windowMs: number;-}): RateLimitResult {- const now = input.now ?? Date.now();- const windowStart = now - input.windowMs;- sweepExpiredRateLimitEntries(now);- const entry = rateLimitStore.get(input.key) ?? {- expiresAt: windowStart,- timestamps: [],- };+ const existing = memoryStore.get(input.key);+ const entry =+ existing && existing.expiresAt > now+ ? { count: existing.count + 1, expiresAt: existing.expiresAt }+ : { count: 1, expiresAt: now + input.windowMs };++ memoryStore.set(input.key, entry);++ return toDecision(entry.count, entry.expiresAt, input, now);+}- entry.timestamps = entry.timestamps.filter((timestamp) => timestamp > windowStart);+function warnAboutFallback(error: unknown) {+ const now = Date.now();- if (entry.timestamps.length === 0) {- rateLimitStore.delete(input.key);- } else {- entry.expiresAt = (entry.timestamps.at(-1) ?? now) + input.windowMs;- rateLimitStore.set(input.key, entry);+ if ((globalThis.__signudocRateLimitWarnedAt ?? 0) > now) {+ return;}- if (entry.timestamps.length >= input.limit) {- const oldestTimestamp = entry.timestamps[0] ?? now;- const retryAfterSeconds = Math.max(- 1,- Math.ceil((oldestTimestamp + input.windowMs - now) / 1000),+ globalThis.__signudocRateLimitWarnedAt = now + FALLBACK_WARNING_INTERVAL_MS;+ console.warn(+ "[rate-limit] Counting in memory because the database could not be used:",+ error instanceof Error ? error.message : error,+ );+}++/**+ * Removes windows that have ended. Returns how many rows went. Called by the+ * cleanup job, and now and then by the limiter itself.+ */+export async function deleteExpiredRateLimits(+ database: DbExecutor = getDb(),+ now: number = Date.now(),+): Promise<number> {+ const result = await database.query(+ "delete from public.rate_limits where expires_at <= $1",+ [now],+ );++ return result.rowCount ?? 0;+}++/**+ * Counts one request against a limit and says whether it is within it.+ *+ * Windows are fixed: the first request starts one, and the count resets+ * when it ends. A request over the limit is still counted, but it does not+ * extend the window, so a client that keeps trying is let back in when the+ * window ends rather than never.+ */+export async function consumeRateLimit(+ input: RateLimitInput,+ { database }: ConsumeRateLimitOptions = {},+): Promise<RateLimitDecision> {+ const now = input.now ?? Date.now();++ try {+ const executor = database ?? getDb();+ const result = await executor.query<{+ count: number;+ expires_at: number;+ }>(+ `+ insert into public.rate_limits as current (key, count, expires_at)+ values ($1, 1, $2::bigint + $3::bigint)+ on conflict (key) do update set+ count = case+ when current.expires_at <= $2::bigint then 1+ else least(current.count + 1, 1000000)+ end,+ expires_at = case+ when current.expires_at <= $2::bigint+ then $2::bigint + $3::bigint+ else current.expires_at+ end+ returning count, expires_at+ `,+ [hashKey(input.key), now, input.windowMs],);- throw new RateLimitExceededError(retryAfterSeconds);- }+ const row = result.rows[0];- entry.timestamps.push(now);- entry.expiresAt = now + input.windowMs;- rateLimitStore.set(input.key, entry);+ if (!row) {+ throw new Error("The rate limit statement returned no row.");+ }- const oldestTimestamp = entry.timestamps[0] ?? now;+ if (Math.floor(Math.random() * DATABASE_SWEEP_ODDS) === 0) {+ void deleteExpiredRateLimits(executor, now).catch(() => undefined);+ }- return {- remaining: Math.max(0, input.limit - entry.timestamps.length),- resetAt: oldestTimestamp + input.windowMs,- };+ return toDecision(row.count, Number(row.expires_at), input, now);+ } catch (error) {+ warnAboutFallback(error);++ return consumeRateLimitInMemory({ ...input, now });+ }}export function clearRateLimitStoreForTests() {- rateLimitStore.clear();+ memoryStore.clear();globalThis.__signudocRateLimitSweepAt = undefined;+ globalThis.__signudocRateLimitWarnedAt = undefined;}diff --git a/src/lib/security/request.test.ts b/src/lib/security/request.test.tsnew file mode 100644index 0000000..5cbd165--- /dev/null+++ b/src/lib/security/request.test.ts@@ -0,0 +1,59 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import { getClientIpAddress, getClientIpHeaderNames } from "./request.ts";++const onVercel = { VERCEL: "1" };+const elsewhere = {};++test("on Vercel, the address Vercel wrote wins over one the visitor could have sent", () => {+ const headers = new Headers({+ "cf-connecting-ip": "198.51.100.9",+ "x-forwarded-for": "198.51.100.7",+ "x-real-ip": "203.0.113.5",+ "x-vercel-forwarded-for": "203.0.113.5",+ });++ assert.equal(getClientIpAddress(headers, onVercel), "203.0.113.5");+ assert.equal(+ getClientIpAddress(+ new Headers({+ "x-forwarded-for": "198.51.100.7",+ "x-real-ip": "203.0.113.5",+ }),+ onVercel,+ ),+ "203.0.113.5",+ );+});++test("off Vercel, Vercel's header means nothing and the proxy headers are used", () => {+ const headers = new Headers({+ "x-forwarded-for": "198.51.100.7, 10.0.0.1",+ "x-vercel-forwarded-for": "203.0.113.5",+ });++ assert.equal(getClientIpAddress(headers, elsewhere), "198.51.100.7");+ assert.equal(+ getClientIpAddress(+ new Headers({ "cf-connecting-ip": "198.51.100.9" }),+ elsewhere,+ ),+ "198.51.100.9",+ );+ assert.equal(+ getClientIpHeaderNames(elsewhere).includes("x-vercel-forwarded-for"),+ false,+ );+});++test("an empty header is passed over, and no header at all gives no address", () => {+ assert.equal(+ getClientIpAddress(+ new Headers({ "x-forwarded-for": " ", "x-real-ip": "203.0.113.5" }),+ elsewhere,+ ),+ "203.0.113.5",+ );+ assert.equal(getClientIpAddress(new Headers(), onVercel), null);+});diff --git a/src/lib/security/request.ts b/src/lib/security/request.tsindex ebceb4a..9b875b2 100644--- a/src/lib/security/request.ts+++ b/src/lib/security/request.ts@@ -1,15 +1,38 @@-export function getClientIpAddress(headers: Headers): string | null {- const forwardedFor = headers.get("x-forwarded-for")?.split(",")[0]?.trim();+type IpEnv = Record<string, string | undefined>;- if (forwardedFor) {- return forwardedFor;+function firstAddress(value: string | null): string | null {+ return value?.split(",")[0]?.trim() || null;+}++/**+ * The headers that carry the visitor's address, most trustworthy first.+ *+ * On Vercel, x-vercel-forwarded-for and x-real-ip are written by Vercel+ * itself and cannot be set by the visitor, so they come first.+ * https://vercel.com/docs/headers/request-headers+ *+ * Anywhere else those two names mean nothing special and anyone could send+ * them, so the usual proxy headers are used instead.+ */+export function getClientIpHeaderNames(env: IpEnv = process.env): string[] {+ return env.VERCEL === "1"+ ? ["x-vercel-forwarded-for", "x-real-ip", "x-forwarded-for"]+ : ["x-forwarded-for", "cf-connecting-ip", "x-real-ip"];+}++export function getClientIpAddress(+ headers: Headers,+ env: IpEnv = process.env,+): string | null {+ for (const name of getClientIpHeaderNames(env)) {+ const address = firstAddress(headers.get(name));++ if (address) {+ return address;+ }}- return (- headers.get("cf-connecting-ip")?.trim() ??- headers.get("x-real-ip")?.trim() ??- null- );+ return null;}export function getRequestUserAgent(headers: Headers): string | null {diff --git a/src/lib/security/route-controls.ts b/src/lib/security/route-controls.tsindex 69ca1a5..54c28cc 100644--- a/src/lib/security/route-controls.ts+++ b/src/lib/security/route-controls.ts@@ -1,7 +1,7 @@import { NextResponse } from "next/server";-import { RateLimitExceededError, enforceSlidingWindowRateLimit } from "./rate-limit.ts";import { logSecurityEvent } from "./logging.ts";+import { consumeRateLimit } from "./rate-limit.ts";import { getClientIpAddress, getRequestPathname } from "./request.ts";type RateLimitInput = {@@ -14,44 +14,40 @@ type RateLimitInput = {windowMs: number;};-function getRetryAfterHeaders(retryAfterSeconds: number) {- return {- "retry-after": String(retryAfterSeconds),- };-}--export function applyRateLimit(input: RateLimitInput): NextResponse | null {- try {- enforceSlidingWindowRateLimit({- key: input.key,- limit: input.limit,- windowMs: input.windowMs,- });-+/**+ * Counts this request against a limit. Returns the 429 response to send when+ * it is over, or null when the request may go ahead.+ */+export async function applyRateLimit(+ input: RateLimitInput,+): Promise<NextResponse | null> {+ const decision = await consumeRateLimit({+ key: input.key,+ limit: input.limit,+ windowMs: input.windowMs,+ });++ if (decision.allowed) {return null;- } catch (error) {- if (!(error instanceof RateLimitExceededError)) {- throw error;- }-- logSecurityEvent("warn", {- category: input.category,- ipAddress: getClientIpAddress(input.request.headers),- message: "Rate limit exceeded.",- path: getRequestPathname(input.request),- userId: input.userId ?? null,- });-- return NextResponse.json(- {- error: input.message ?? "Too many requests. Please try again soon.",- },- {- headers: getRetryAfterHeaders(error.retryAfterSeconds),- status: 429,- },- );}++ logSecurityEvent("warn", {+ category: input.category,+ ipAddress: getClientIpAddress(input.request.headers),+ message: "Rate limit exceeded.",+ path: getRequestPathname(input.request),+ userId: input.userId ?? null,+ });++ return NextResponse.json(+ {+ error: input.message ?? "Too many requests. Please try again soon.",+ },+ {+ headers: { "retry-after": String(decision.retryAfterSeconds) },+ status: 429,+ },+ );}export function buildRateLimitKey(parts: Array<string | null | undefined>) {