Refactor login flow with reset token support
All checks were successful
Automated Container Build / build-and-push (push) Successful in 1m6s
All checks were successful
Automated Container Build / build-and-push (push) Successful in 1m6s
This commit is contained in:
parent
f0548bcc6e
commit
95af276d2e
11 changed files with 679 additions and 226 deletions
|
|
@ -12,20 +12,25 @@ 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 } {
|
||||
export function checkRateLimit(
|
||||
key: string,
|
||||
options: { windowMs?: number; maxRequests?: number } = {}
|
||||
): { allowed: boolean; retryAfterMs: number } {
|
||||
const now = Date.now();
|
||||
const entry = store.get(ip) ?? { timestamps: [] };
|
||||
const windowMs = options.windowMs ?? WINDOW_MS;
|
||||
const maxRequests = options.maxRequests ?? MAX_REQUESTS;
|
||||
const entry = store.get(key) ?? { timestamps: [] };
|
||||
|
||||
// Remove timestamps outside the window
|
||||
entry.timestamps = entry.timestamps.filter((t) => now - t < WINDOW_MS);
|
||||
entry.timestamps = entry.timestamps.filter((t) => now - t < windowMs);
|
||||
|
||||
if (entry.timestamps.length >= MAX_REQUESTS) {
|
||||
if (entry.timestamps.length >= maxRequests) {
|
||||
const oldestInWindow = entry.timestamps[0];
|
||||
const retryAfterMs = WINDOW_MS - (now - oldestInWindow);
|
||||
const retryAfterMs = windowMs - (now - oldestInWindow);
|
||||
return { allowed: false, retryAfterMs };
|
||||
}
|
||||
|
||||
entry.timestamps.push(now);
|
||||
store.set(ip, entry);
|
||||
store.set(key, entry);
|
||||
return { allowed: true, retryAfterMs: 0 };
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue