UNPKG

@aikidosec/firewall

Version:

Zen by Aikido is an embedded Web Application Firewall that autonomously protects Node.js apps against common and critical attacks

32 lines (31 loc) 1.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RateLimiter = void 0; const LRUMap_1 = require("./LRUMap"); /** * Sliding window rate limiter implementation */ class RateLimiter { constructor(maxItems, timeToLiveInMS) { this.maxItems = maxItems; this.timeToLiveInMS = timeToLiveInMS; this.rateLimitedItems = new LRUMap_1.LRUMap(maxItems, timeToLiveInMS); } isAllowed(key, windowSizeInMS, maxRequests) { const currentTime = performance.now(); const requestTimestamps = this.rateLimitedItems.get(key) || []; // Filter out timestamps that are older than windowSizeInMS and already expired const filteredTimestamps = requestTimestamps.filter((timestamp) => currentTime - timestamp <= windowSizeInMS); // Ensure the number of entries exceeds maxRequests by only 1 if (filteredTimestamps.length > maxRequests + 1) { filteredTimestamps.splice(0, filteredTimestamps.length - (maxRequests + 1)); } // Add current request timestamp to the list filteredTimestamps.push(currentTime); // Update the list of timestamps for the key this.rateLimitedItems.set(key, filteredTimestamps); // Check if the number of requests is less or equal to the maxRequests return filteredTimestamps.length <= maxRequests; } } exports.RateLimiter = RateLimiter;