UNPKG

limiter.js

Version:

limiter.js is a Node.js/TypeScript library that provides simple Rate limiter protection for Express applications. It tracks requests per IP address and enforces rate limits within a sliding time window. If an IP exceeds the allowed requests, limiter.js ca

61 lines (60 loc) 1.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IPTracker = void 0; class IPTracker { constructor(ipAddress) { this.banCount = 0; // Track number of times this IP has been banned this.permanentBan = false; this.ipAddress = ipAddress; this.hits = []; this.bannedUntil = null; } recordHit(timestamp) { this.hits.push(timestamp); } /** * Get the number of hits in the last `windowMs` milliseconds. * @param windowMs The time window in milliseconds to check for hits. * @returns The count of hits in the specified time window. */ getHitCountInWindow(windowMs) { const currentTime = Date.now(); this.hits = this.hits.filter((hit) => hit > currentTime - windowMs); return this.hits.length; } /** * Check if the IP is currently banned. * @param currentTime The current time in milliseconds since epoch. * @returns True if the IP is banned, false otherwise. */ isBanned(currentTime) { return (this.permanentBan || (this.bannedUntil !== null && currentTime < this.bannedUntil)); } getIsPermanentlyBanned() { return this.permanentBan; } getBanCount() { return this.banCount; } /** * Ban the IP for a specified duration in milliseconds. * @param durationMs The duration in milliseconds for which to ban the IP. */ ban(durationMs) { const currentTime = Date.now(); this.bannedUntil = currentTime + durationMs; this.banCount++; // Increment ban count when IP is banned } /** * Permanently ban the IP. */ banPermanently() { this.permanentBan = true; this.bannedUntil = null; // Clear any temporary ban } getIpAddress() { return this.ipAddress; } } exports.IPTracker = IPTracker;