Initial working commit
Some checks failed
Automated Container Build / build-and-push (push) Failing after 7s
Some checks failed
Automated Container Build / build-and-push (push) Failing after 7s
This commit is contained in:
parent
666ceb7325
commit
b7ce314f01
105 changed files with 35510 additions and 11 deletions
31
src/lib/rateLimiter.ts
Normal file
31
src/lib/rateLimiter.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/**
|
||||
* In-memory sliding window rate limiter.
|
||||
* Single-instance, single-user container — no need for Redis.
|
||||
*/
|
||||
|
||||
interface RateLimitEntry {
|
||||
timestamps: number[];
|
||||
}
|
||||
|
||||
const store = new Map<string, RateLimitEntry>();
|
||||
|
||||
const WINDOW_MS = 60 * 1000; // 1 minute
|
||||
const MAX_REQUESTS = 10;
|
||||
|
||||
export function checkRateLimit(ip: string): { allowed: boolean; retryAfterMs: number } {
|
||||
const now = Date.now();
|
||||
const entry = store.get(ip) ?? { timestamps: [] };
|
||||
|
||||
// Remove timestamps outside the window
|
||||
entry.timestamps = entry.timestamps.filter((t) => now - t < WINDOW_MS);
|
||||
|
||||
if (entry.timestamps.length >= MAX_REQUESTS) {
|
||||
const oldestInWindow = entry.timestamps[0];
|
||||
const retryAfterMs = WINDOW_MS - (now - oldestInWindow);
|
||||
return { allowed: false, retryAfterMs };
|
||||
}
|
||||
|
||||
entry.timestamps.push(now);
|
||||
store.set(ip, entry);
|
||||
return { allowed: true, retryAfterMs: 0 };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue