-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
42 lines (34 loc) · 1.26 KB
/
middleware.ts
File metadata and controls
42 lines (34 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
/** Sliding window rate limit for live research API (abuse / cost protection). */
const WINDOW_MS = 60_000;
const MAX_REQUESTS = 45;
type GlobalWithRl = typeof globalThis & { __researchLiveRl?: Map<string, number[]> };
function clientKey(req: NextRequest): string {
const forwarded = req.headers.get("x-forwarded-for");
const first = forwarded?.split(",")[0]?.trim();
return first || req.headers.get("x-real-ip") || "unknown";
}
export function middleware(req: NextRequest) {
const g = globalThis as GlobalWithRl;
if (!g.__researchLiveRl) g.__researchLiveRl = new Map<string, number[]>();
const now = Date.now();
const key = clientKey(req);
const prev = g.__researchLiveRl.get(key) ?? [];
const windowed = prev.filter((t) => now - t < WINDOW_MS);
if (windowed.length >= MAX_REQUESTS) {
return NextResponse.json(
{ error: "Too many requests", retryAfterSec: Math.ceil(WINDOW_MS / 1000) },
{
status: 429,
headers: { "Retry-After": String(Math.ceil(WINDOW_MS / 1000)) },
}
);
}
windowed.push(now);
g.__researchLiveRl.set(key, windowed);
return NextResponse.next();
}
export const config = {
matcher: "/api/research/live",
};