Files
ipal-kit/dist/modules/shared/rateLimit.js
T

78 lines
2.9 KiB
JavaScript

/**
* 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();
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */ let lastSweep = Date.now();
const SWEEP_INTERVAL = 60_000;
function sweep(now) {
if (now - lastSweep < SWEEP_INTERVAL) {
return;
}
lastSweep = now;
for (const [key, bucket] of buckets){
if (bucket.resetAt <= now) {
buckets.delete(key);
}
}
}
/**
* 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 }) {
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, scope = 'form') {
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) {
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, scope, body) {
return Response.json(body, {
headers: {
'cache-control': 'no-store',
'retry-after': String(retryAfterSeconds(key, scope))
},
status: 429
});
}
//# sourceMappingURL=rateLimit.js.map