From 89ecdf03eb36bea9a17e5a0116dd0f74fe5552d2 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:28:50 +0530 Subject: [PATCH 1/3] Rate limit analyses per visitor and per day --- apps/backend/package-lock.json | 29 ++++++++++ apps/backend/package.json | 1 + apps/backend/src/app.ts | 5 ++ apps/backend/src/config/env.ts | 15 +++++ apps/backend/src/http/rate-limit.ts | 89 +++++++++++++++++++++++++++++ apps/backend/src/routes/analyze.ts | 3 + 6 files changed, 142 insertions(+) create mode 100644 apps/backend/src/http/rate-limit.ts diff --git a/apps/backend/package-lock.json b/apps/backend/package-lock.json index 4e9d9fe..2ceb372 100644 --- a/apps/backend/package-lock.json +++ b/apps/backend/package-lock.json @@ -11,6 +11,7 @@ "cors": "^2.8.6", "dotenv": "^17.4.2", "express": "^5.2.1", + "express-rate-limit": "8.7.3", "multer": "^2.2.0", "typescript": "^6.0.3", "yauzl": "^2.10.0", @@ -2464,6 +2465,25 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "8.7.3", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.3.tgz", + "integrity": "sha512-zPLqDI2f0gV2WmGnacLf9XSSqn4VldRyP5LCzOwx0BKH40mO6+2PCFkoSsRO2jePx87/Kf6NUF6P2QOTKXHbQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/express/node_modules/media-typer": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", @@ -2957,6 +2977,15 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", diff --git a/apps/backend/package.json b/apps/backend/package.json index 1137b20..8017e16 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -25,6 +25,7 @@ "cors": "^2.8.6", "dotenv": "^17.4.2", "express": "^5.2.1", + "express-rate-limit": "8.7.3", "multer": "^2.2.0", "typescript": "^6.0.3", "yauzl": "^2.10.0", diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index 4e31ba4..d412b96 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -5,9 +5,14 @@ import analyzeRouter from "./routes/analyze.js"; import healthRouter from "./routes/health.js"; import jobsRouter from "./routes/jobs.js"; import { CorsError, toErrorResponse } from "./http/error-response.js"; +import { env } from "./config/env.js"; const app = express(); +// Read the visitor's real IP from X-Forwarded-For when running behind +// a reverse proxy (Render). Used by the rate limits. +app.set("trust proxy", env.TRUST_PROXY_HOPS); + const allowedOrigins = [ "http://localhost:5173", process.env.FRONTEND_URL, diff --git a/apps/backend/src/config/env.ts b/apps/backend/src/config/env.ts index 1e22f13..94005e3 100644 --- a/apps/backend/src/config/env.ts +++ b/apps/backend/src/config/env.ts @@ -15,6 +15,21 @@ const envSchema = z.object({ * HTTP 429 until one finishes. Protects memory and Gemini spend. */ MAX_CONCURRENT_JOBS: z.coerce.number().int().min(1).default(2), + /** + * Analyses one visitor (IP address) may start per hour. 0 = no limit. + */ + RATE_LIMIT_PER_HOUR: z.coerce.number().int().min(0).default(5), + /** + * Analyses the whole site may start per day, across all visitors. + * A hard ceiling on Gemini spend. 0 = no limit. + */ + RATE_LIMIT_PER_DAY: z.coerce.number().int().min(0).default(100), + /** + * Number of reverse proxies in front of the server (Render: 1). + * Needed to read the visitor's real IP from X-Forwarded-For; + * 0 if the server is reached directly. + */ + TRUST_PROXY_HOPS: z.coerce.number().int().min(0).default(1), /** * Upper bound on the prompt size sent to Gemini. Source files are * ranked by importance and added until this budget is reached. diff --git a/apps/backend/src/http/rate-limit.ts b/apps/backend/src/http/rate-limit.ts new file mode 100644 index 0000000..5d80d9c --- /dev/null +++ b/apps/backend/src/http/rate-limit.ts @@ -0,0 +1,89 @@ +import type { RequestHandler } from "express"; +import { + ipKeyGenerator, + rateLimit, + type AugmentedRequest, +} from "express-rate-limit"; + +import { env } from "../config/env.js"; + +const HOUR_MS = 60 * 60 * 1000; +const DAY_MS = 24 * HOUR_MS; + +function formatWait(resetTime: Date | undefined): string { + if (!resetTime) { + return "later"; + } + + const minutes = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 60_000)); + + if (minutes <= 60) { + return `in ${minutes} minute${minutes === 1 ? "" : "s"}`; + } + + const hours = Math.ceil(minutes / 60); + + return `in about ${hours} hour${hours === 1 ? "" : "s"}`; +} + +const passThrough: RequestHandler = (_req, _res, next) => next(); + +/** + * Limits for starting analyses (POST /api/analyze). Each analysis is a + * paid Gemini call, so the public demo needs a ceiling on usage. + * + * - per visitor: RATE_LIMIT_PER_HOUR analyses per IP address per hour + * (IPv6 addresses are grouped by /56 subnet, so one user cannot + * rotate through addresses) + * - whole site: RATE_LIMIT_PER_DAY analyses per day across all visitors + * + * Only accepted analyses count: requests that end in an error + * (bad upload, server busy, limit reached) do not use up the limit. + * Runs before the upload is received, so a limited visitor cannot + * send a large file first. + * + * Counters are kept in memory (single server instance). + */ +export const analysisRateLimits: RequestHandler[] = [ + env.RATE_LIMIT_PER_DAY > 0 + ? rateLimit({ + windowMs: DAY_MS, + limit: env.RATE_LIMIT_PER_DAY, + keyGenerator: () => "site", + skipFailedRequests: true, + standardHeaders: "draft-8", + legacyHeaders: false, + handler: (req, res) => { + res.status(429).json({ + success: false, + error: "DAILY_LIMIT_REACHED", + message: `This demo has reached its daily analysis limit. Please try again ${formatWait( + (req as AugmentedRequest).rateLimit?.resetTime, + )}.`, + }); + }, + }) + : passThrough, + + env.RATE_LIMIT_PER_HOUR > 0 + ? rateLimit({ + windowMs: HOUR_MS, + limit: env.RATE_LIMIT_PER_HOUR, + keyGenerator: (req) => ipKeyGenerator(req.ip ?? "unknown"), + skipFailedRequests: true, + standardHeaders: "draft-8", + legacyHeaders: false, + handler: (req, res) => { + res.status(429).json({ + success: false, + error: "RATE_LIMITED", + message: `You have started ${env.RATE_LIMIT_PER_HOUR} ${ + env.RATE_LIMIT_PER_HOUR === 1 ? "analysis" : "analyses" + } in the last hour. Please try again ${formatWait( + (req as AugmentedRequest).rateLimit?.resetTime, + )}.`, + }); + }, + }) + : passThrough, +]; diff --git a/apps/backend/src/routes/analyze.ts b/apps/backend/src/routes/analyze.ts index ae465f5..0615605 100644 --- a/apps/backend/src/routes/analyze.ts +++ b/apps/backend/src/routes/analyze.ts @@ -2,6 +2,7 @@ import fs from "node:fs/promises"; import { Router } from "express"; import { upload } from "../http/multer.js"; +import { analysisRateLimits } from "../http/rate-limit.js"; import { runAnalysisJob } from "../application/analysis-job.runner.js"; import { jobStore } from "../jobs/job.store.js"; import { env } from "../config/env.js"; @@ -11,11 +12,13 @@ const router = Router(); /** * Accepts a ZIP upload and starts a background analysis job. * + * Rate limits are checked before the upload is received. * Responds immediately with 202 and a job id. Progress and the final * report are delivered by GET /api/jobs/:id/events (Server-Sent Events). */ router.post( "/analyze", + ...analysisRateLimits, upload.single("repository"), async (req, res) => { if (!req.file) { From 9a63e8f4e23205add264948119576deae284758a Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:28:50 +0530 Subject: [PATCH 2/3] Test rate limits over HTTP --- apps/backend/test/rate-limit.test.ts | 95 ++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 apps/backend/test/rate-limit.test.ts diff --git a/apps/backend/test/rate-limit.test.ts b/apps/backend/test/rate-limit.test.ts new file mode 100644 index 0000000..4e84fe4 --- /dev/null +++ b/apps/backend/test/rate-limit.test.ts @@ -0,0 +1,95 @@ +import fs from "node:fs/promises"; +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +import { createZip } from "./helpers/zip.js"; + +// Small limits for the test. Each test file gets fresh modules, +// so these only apply here. +process.env.RATE_LIMIT_PER_HOUR = "2"; +process.env.RATE_LIMIT_PER_DAY = "3"; +process.env.TRUST_PROXY_HOPS = "1"; +process.env.MAX_CONCURRENT_JOBS = "100"; + +// Never run a real analysis: just delete the uploaded file. +vi.mock("../src/application/analysis-job.runner.js", () => ({ + runAnalysisJob: vi.fn(async (_jobId: string, zipPath: string) => { + await fs.rm(zipPath, { force: true }); + }), +})); + +const { default: app } = await import("../src/app.js"); + +let server: Server; +let baseUrl: string; +let zipBytes: Buffer; + +beforeAll(async () => { + zipBytes = await fs.readFile( + await createZip([{ name: "repo/index.ts", content: "export {};" }]), + ); + + server = app.listen(0); + await new Promise((resolve) => server.once("listening", resolve)); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(() => { + server.close(); +}); + +/** + * Uploads a file as if from `ip` (via the X-Forwarded-For header the + * proxy would add). + */ +async function upload(ip: string, fileName = "repo.zip") { + const form = new FormData(); + form.append("repository", new Blob([new Uint8Array(zipBytes)]), fileName); + + const response = await fetch(`${baseUrl}/api/analyze`, { + method: "POST", + body: form, + headers: { "X-Forwarded-For": ip }, + }); + + return { + status: response.status, + body: (await response.json()) as { error?: string; message?: string }, + headers: response.headers, + }; +} + +describe("analysis rate limits", () => { + it("does not count rejected uploads", async () => { + for (let i = 0; i < 4; i++) { + const rejected = await upload("203.0.113.1", "notes.txt"); + expect(rejected.status).toBe(400); + } + + expect((await upload("203.0.113.1")).status).toBe(202); + }); + + it("limits each visitor per hour", async () => { + expect((await upload("203.0.113.1")).status).toBe(202); + + const blocked = await upload("203.0.113.1"); + + expect(blocked.status).toBe(429); + expect(blocked.body.error).toBe("RATE_LIMITED"); + expect(blocked.body.message).toMatch(/try again in \d+ minutes?/); + expect(blocked.headers.get("ratelimit")).toBeTruthy(); + }); + + it("keeps separate limits for different visitors", async () => { + expect((await upload("198.51.100.7")).status).toBe(202); + }); + + it("stops everyone once the daily site limit is reached", async () => { + // 3 analyses accepted so far (2 + 1), which is the daily limit. + const blocked = await upload("192.0.2.50"); + + expect(blocked.status).toBe(429); + expect(blocked.body.error).toBe("DAILY_LIMIT_REACHED"); + }); +}); From ca84793527176a62624b04e109f4e1814ef82387 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 22:28:50 +0530 Subject: [PATCH 3/3] Document rate limit settings --- README.md | 9 +++++++++ apps/backend/.env.example | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/README.md b/README.md index b018f42..6ebb5c0 100644 --- a/README.md +++ b/README.md @@ -321,6 +321,13 @@ FRONTEND_URL=https://your-frontend.example # Optional: analyses allowed to run at once (extra uploads get HTTP 429) MAX_CONCURRENT_JOBS=2 +# Optional: rate limits on starting analyses (0 = no limit) +RATE_LIMIT_PER_HOUR=5 # per visitor (IP address) +RATE_LIMIT_PER_DAY=100 # whole site + +# Optional: reverse proxies in front of the server (Render: 1, direct: 0) +TRUST_PROXY_HOPS=1 + # Optional: prompt size cap; files are ranked by importance and added until it is reached MAX_PROMPT_TOKENS=150000 @@ -341,6 +348,8 @@ SAVE_DEBUG_ARTIFACTS=false | `GET` | `/api/jobs/:id` | Current job state as JSON. | | `GET` | `/api/health` | Health check. | +Starting an analysis is rate limited per visitor and per day for the whole site (HTTP 429 with a message saying when to retry). Only accepted analyses count, and limits are checked before the upload is received. + Each analysis runs as its own job, so concurrent users never see each other's progress. Finished jobs are kept in memory for 30 minutes. --- diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 7501188..e6eec6b 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -5,6 +5,14 @@ GEMINI_MODEL=gemini-2.5-flash # Analyses allowed to run at once; extra uploads get HTTP 429. MAX_CONCURRENT_JOBS=2 +# Rate limits on starting analyses (0 = no limit). +# Per visitor (IP address) per hour, and for the whole site per day. +RATE_LIMIT_PER_HOUR=5 +RATE_LIMIT_PER_DAY=100 + +# Reverse proxies in front of the server (Render: 1; direct access: 0). +TRUST_PROXY_HOPS=1 + # Prompt size cap. Files are ranked by importance and added until it is reached. MAX_PROMPT_TOKENS=150000