import type { Hono } from "hono"; import { clientIp } from "../server/client.ts"; // The expensive public answers — a whole-repo bundle, a tarball, a highlighted file, a raw object, // a save page's diff — carry a per-address budget, so one crawler can't hold the one request // thread. A HEAD fetches nothing, and the rest of the site is not counted. const RATE = 60; // requests a minute const BURST = 20; // allowed at once const MINUTE = 60_000; const HEAVY = /^\/[^/]+\/(?:koh\/bundle$|archive\/|files\/|raw\/|saves\/)/; /** 429 with `Retry-After` past the budget; small and in memory, one bucket per address. */ export function registerHeavyLimit(app: Hono): void { const buckets = new Map(); // The whole seconds `ip` must wait for a token, or 0 for one now. const take = (ip: string, now: number): number => { const bucket = buckets.get(ip); // Bounded: an address full again after a quiet minute needs no entry. if (!bucket && buckets.size > 4096) { for (const [key, it] of buckets) { if (it.tokens + ((now - it.at) * RATE) / MINUTE >= BURST) buckets.delete(key); } } const held = (bucket?.tokens ?? BURST) + ((now - (bucket?.at ?? now)) * RATE) / MINUTE; const tokens = Math.min(BURST, held); buckets.set(ip, { tokens: Math.max(0, tokens - 1), at: now }); if (tokens >= 1) return 0; return Math.max(1, Math.ceil(((1 - tokens) * MINUTE) / RATE / 1000)); }; app.use("*", async (c, next) => { const ip = clientIp(c); // An address no runtime gave can't tell clients apart, so it is not counted. if (ip !== "" && c.req.method !== "HEAD" && HEAVY.test(c.req.path)) { const wait = take(ip, Date.now()); if (wait > 0) return c.text("too many requests\n", 429, { "Retry-After": String(wait) }); } await next(); }); }