Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

---
Expand Down
8 changes: 8 additions & 0 deletions apps/backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
29 changes: 29 additions & 0 deletions apps/backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
5 changes: 5 additions & 0 deletions apps/backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
15 changes: 15 additions & 0 deletions apps/backend/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
89 changes: 89 additions & 0 deletions apps/backend/src/http/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -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,
];
3 changes: 3 additions & 0 deletions apps/backend/src/routes/analyze.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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) {
Expand Down
95 changes: 95 additions & 0 deletions apps/backend/test/rate-limit.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
Loading