mcp and content fix
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
type Bucket = { count: number; resetAt: number }
|
||||
|
||||
/**
|
||||
* Per-key fixed window, in memory. Shared by submitForm, createSearchRoute and
|
||||
* createMcpRoute — each uses its own `scope`, so a busy search box never eats
|
||||
* into the contact form's budget.
|
||||
*
|
||||
* Deliberately simple: no Redis, no dependency. The trade-off is that the
|
||||
* counter lives in one process — with several instances behind a load balancer
|
||||
* each keeps its own, so the effective limit is per-instance, not global. For a
|
||||
* contact form that's fine (it raises the cost of flooding without pretending
|
||||
* to be airtight); a high-security form should put a real limiter in front.
|
||||
*
|
||||
* State is module-level, so it survives between requests but resets on redeploy
|
||||
* — acceptable for abuse throttling.
|
||||
*/
|
||||
const buckets = new Map<string, Bucket>()
|
||||
|
||||
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */
|
||||
let lastSweep = Date.now()
|
||||
const SWEEP_INTERVAL = 60_000
|
||||
|
||||
function sweep(now: number) {
|
||||
if (now - lastSweep < SWEEP_INTERVAL) {return}
|
||||
lastSweep = now
|
||||
for (const [key, bucket] of buckets) {
|
||||
if (bucket.resetAt <= now) {buckets.delete(key)}
|
||||
}
|
||||
}
|
||||
|
||||
export type RateLimitArgs = {
|
||||
/** Identifier to limit on — typically the client IP. */
|
||||
key: string
|
||||
/** Max submissions allowed per window. Defaults to 5. */
|
||||
max?: number
|
||||
/** Separate counter space per feature, e.g. 'form', 'search', 'mcp'. Default 'form'. */
|
||||
scope?: string
|
||||
/** Window length in ms. Defaults to 60_000 (one minute). */
|
||||
windowMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when the request is within the limit, false when it should be
|
||||
* rejected. A missing key (no IP) is allowed through — better to accept a
|
||||
* submission than to block everyone behind a proxy that strips the header.
|
||||
*/
|
||||
export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }: { cost?: number } & RateLimitArgs): boolean {
|
||||
if (!key) {return true}
|
||||
|
||||
const now = Date.now()
|
||||
sweep(now)
|
||||
|
||||
const id = `${scope}:${key}`
|
||||
const bucket = buckets.get(id)
|
||||
|
||||
if (!bucket || bucket.resetAt <= now) {
|
||||
if (cost > max) {return false}
|
||||
buckets.set(id, { count: cost, resetAt: now + windowMs })
|
||||
return true
|
||||
}
|
||||
|
||||
if (bucket.count + cost > max) {
|
||||
return false
|
||||
}
|
||||
|
||||
bucket.count += cost
|
||||
return true
|
||||
}
|
||||
|
||||
/** Seconds until the key's window resets — for a Retry-After header. */
|
||||
export function retryAfterSeconds(key: string, scope = 'form'): number {
|
||||
const bucket = buckets.get(`${scope}:${key}`)
|
||||
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the
|
||||
* edge, the real visitor), then the first `x-forwarded-for` hop, then
|
||||
* `x-real-ip`. Empty string when none — the limiter then lets the request through.
|
||||
*/
|
||||
export function clientIp(req: Request): string {
|
||||
const h = req.headers
|
||||
return (
|
||||
h.get('cf-connecting-ip')?.trim() ||
|
||||
h.get('x-forwarded-for')?.split(',')[0]?.trim() ||
|
||||
h.get('x-real-ip')?.trim() ||
|
||||
''
|
||||
)
|
||||
}
|
||||
|
||||
/** Standard 429 for route handlers. */
|
||||
export function tooManyRequests(key: string, scope: string, body: unknown): Response {
|
||||
return Response.json(body, {
|
||||
headers: { 'cache-control': 'no-store', 'retry-after': String(retryAfterSeconds(key, scope)) },
|
||||
status: 429,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user