1import type { Hono } from "hono";2import { clientIp } from "../server/client.ts";34567const RATE = 60; 8const BURST = 20; 9const MINUTE = 60_000;10const HEAVY = /^\/[^/]+\/(?:koh\/bundle$|archive\/|files\/|raw\/|saves\/)/;111213export function registerHeavyLimit(app: Hono): void {14 const buckets = new Map<string, { tokens: number; at: number }>();15 16 const take = (ip: string, now: number): number => {17 const bucket = buckets.get(ip);18 19 if (!bucket && buckets.size > 4096) {20 for (const [key, it] of buckets) {21 if (it.tokens + ((now - it.at) * RATE) / MINUTE >= BURST) buckets.delete(key);22 }23 }24 const held = (bucket?.tokens ?? BURST) + ((now - (bucket?.at ?? now)) * RATE) / MINUTE;25 const tokens = Math.min(BURST, held);26 buckets.set(ip, { tokens: Math.max(0, tokens - 1), at: now });27 if (tokens >= 1) return 0;28 return Math.max(1, Math.ceil(((1 - tokens) * MINUTE) / RATE / 1000));29 };30 app.use("*", async (c, next) => {31 const ip = clientIp(c);32 33 if (ip !== "" && c.req.method !== "HEAD" && HEAVY.test(c.req.path)) {34 const wait = take(ip, Date.now());35 if (wait > 0) return c.text("too many requests\n", 429, { "Retry-After": String(wait) });36 }37 await next();38 });39}