You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.6 KiB
55 lines
1.6 KiB
const SESSION_LIMIT = 20;
|
|
const IP_DAILY_LIMIT = 50;
|
|
|
|
interface RateCounter {
|
|
count: number;
|
|
date: string;
|
|
}
|
|
|
|
const sessionCounters = new Map<string, RateCounter>();
|
|
const ipCounters = new Map<string, RateCounter>();
|
|
|
|
function getTodayStr(): string {
|
|
return new Date().toISOString().slice(0, 10);
|
|
}
|
|
|
|
function getCounter(map: Map<string, RateCounter>, key: string): RateCounter {
|
|
const today = getTodayStr();
|
|
let counter = map.get(key);
|
|
if (!counter || counter.date !== today) {
|
|
counter = { count: 0, date: today };
|
|
map.set(key, counter);
|
|
}
|
|
return counter;
|
|
}
|
|
|
|
export interface RateLimitResult {
|
|
sessionRemaining: number;
|
|
ipRemaining: number;
|
|
blocked: boolean;
|
|
}
|
|
|
|
export function checkRateLimit(sessionId: string, ip: string): RateLimitResult {
|
|
const sessionCounter = getCounter(sessionCounters, sessionId);
|
|
const ipCounter = getCounter(ipCounters, ip);
|
|
|
|
const sessionRemaining = Math.max(0, SESSION_LIMIT - sessionCounter.count);
|
|
const ipRemaining = Math.max(0, IP_DAILY_LIMIT - ipCounter.count);
|
|
const blocked = sessionRemaining === 0 || ipRemaining === 0;
|
|
|
|
return { sessionRemaining, ipRemaining, blocked };
|
|
}
|
|
|
|
export function incrementRateLimit(sessionId: string, ip: string): void {
|
|
const sessionCounter = getCounter(sessionCounters, sessionId);
|
|
const ipCounter = getCounter(ipCounters, ip);
|
|
sessionCounter.count++;
|
|
ipCounter.count++;
|
|
}
|
|
|
|
export function getRateLimitInfo(sessionId: string, ip: string): RateLimitResult {
|
|
return checkRateLimit(sessionId, ip);
|
|
}
|
|
|
|
export const SESSION_LIMIT_VALUE = SESSION_LIMIT;
|
|
export const IP_DAILY_LIMIT_VALUE = IP_DAILY_LIMIT;
|
|
|