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

69 lines (68 loc) 2.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DDoSDetector = void 0; const RateLimiter_1 = require("./RateLimiter"); const IPTracker_1 = require("./IPTracker"); class DDoSDetector { constructor(config) { this.ipMap = new Map(); this.rateLimiter = new RateLimiter_1.RateLimiter(config.windowMs, config.maxHitsAllowed); this.banDurationMs = config.banDurationMs; this.parmanentBanThreshold = config.parmanentBanThreshold; } logStatus() { for (const [ip, tracker] of this.ipMap.entries()) { const hitCount = tracker.getHitCountInWindow(this.rateLimiter.getWindowMs()); const isBanned = tracker.isBanned(Date.now()); console.log(`IP: ${ip}, Hits: ${hitCount}, Banned: ${isBanned}, Banned Until: ${tracker.bannedUntil ? new Date(tracker.bannedUntil).toISOString() : "N/A"}`); } } logIPStatus(ip) { const tracker = this.ipMap.get(ip); if (tracker) { const hitCount = tracker.getHitCountInWindow(this.rateLimiter.getWindowMs()); const isBanned = tracker.isBanned(Date.now()); console.log(`IP: ${ip}, Hits: ${hitCount}, Banned: ${isBanned}, Banned Until: ${tracker.bannedUntil ? new Date(tracker.bannedUntil).toISOString() : "N/A"}, Permanently Banned: ${tracker.getIsParmanentlyBanned()}`); } else { console.log(`IP: ${ip} not found.`); } } handleRequest(ip) { let ipTracker = this.ipMap.get(ip); if (!ipTracker) { ipTracker = new IPTracker_1.IPTracker(ip); this.ipMap.set(ip, ipTracker); } // record ipTracker.recordHit(Date.now()); // Check for permanent ban condition const parmanentBlockDecision = this.rateLimiter.shouldBanPermanently(ipTracker, this.parmanentBanThreshold); if (parmanentBlockDecision) { ipTracker.banPermanently(); return { blocked: true, reason: "IP is permanently banned." }; } // check for temporary ban const blockDecision = this.rateLimiter.shouldBlock(ipTracker); if (blockDecision) { if (ipTracker.isBanned(Date.now())) { return { blocked: true, reason: "Warning: IP is currently banned." }; } else { ipTracker.ban(this.banDurationMs); return { blocked: true, reason: "Warning: Rate limit exceeded. Your IP has been banned.", }; } } else { return { blocked: false }; } } } exports.DDoSDetector = DDoSDetector;