Spaces:
Running
Running
Download lib/rateLimit.ts from 2Btainment/Drip-Creator: direct link, hf CLI and curl.
- Browser
- Download file 1.59 kB
-
https://huggingface.co/spaces/2Btainment/Drip-Creator/resolve/main/lib/rateLimit.ts
- Command line
-
hf download hf://spaces/2Btainment/Drip-Creator/lib/rateLimit.ts
-
curl -L -o rateLimit.ts https://huggingface.co/spaces/2Btainment/Drip-Creator/resolve/main/lib/rateLimit.ts
1.59 kB
| /* ============================================================ | |
| * Rate-Limit (In-Memory, gleitendes 1h-Fenster pro IP) | |
| * Schützt die Free-Tier-Keys, wenn der Space öffentlich läuft. | |
| * Konfigurierbar via RATE_LIMIT_PER_HOUR (0 = deaktiviert). | |
| * ============================================================ */ | |
| const RATE_LIMIT = Number(process.env.RATE_LIMIT_PER_HOUR ?? 30); | |
| const WINDOW_MS = 60 * 60 * 1000; | |
| const hits = new Map<string, number[]>(); | |
| /** Liefert true, wenn das Limit überschritten ist — sonst zählt der Request. */ | |
| export function rateLimited(ip: string): boolean { | |
| if (RATE_LIMIT <= 0) return false; | |
| const now = Date.now(); | |
| const cutoff = now - WINDOW_MS; | |
| // Gelegenlich aufräumen (Map wächst sonst unbegrenzt) | |
| if (hits.size > 5000) { | |
| for (const [key, list] of hits) { | |
| const alive = list.filter((t) => t > cutoff); | |
| if (alive.length === 0) hits.delete(key); | |
| else hits.set(key, alive); | |
| } | |
| } | |
| const list = (hits.get(ip) || []).filter((t) => t > cutoff); | |
| if (list.length >= RATE_LIMIT) { | |
| hits.set(ip, list); | |
| return true; | |
| } | |
| list.push(now); | |
| hits.set(ip, list); | |
| return false; | |
| } | |
| /** Client-IP aus Proxy-Headern (HF/Vercel) oder Socket ermitteln. */ | |
| export function clientIp(req: { headers: Record<string, unknown>; socket?: { remoteAddress?: string } }): string { | |
| const fwd = req.headers["x-forwarded-for"]; | |
| if (typeof fwd === "string" && fwd.length > 0) return fwd.split(",")[0].trim(); | |
| if (Array.isArray(fwd) && fwd.length > 0) return String(fwd[0]); | |
| return req.socket?.remoteAddress || "unknown"; | |
| } | |