npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

secure-rate-limiter

v4.0.0

Published

Advanced rate-limiting with bot detection, behavioral analysis, and DDoS protection

Readme

Secure Rate Limiter 🛡️

Advanced rate-limiting middleware for Node.js with comprehensive bot detection, behavioral analysis, and DDoS protection.

Features

  • Multi-layered Protection: Rate limiting, burst detection, behavioral analysis
  • Advanced Bot Detection: Pattern-based detection beyond simple user-agent checks
  • IP Spoofing Detection: Identifies suspicious header manipulation
  • Temporary Banning: Progressive punishment system for repeat offenders
  • Connection Limiting: Prevents connection flooding attacks
  • Behavioral Analysis: Detects script-like timing patterns and fingerprint rotation
  • Comprehensive Logging: Security event logging with detailed analytics
  • Memory Efficient: Automatic cleanup of old tracking data

Installation

npm install secure-rate-limiter

Quick Start

const express = require('express');
const SecureRateLimiter = require('secure-rate-limiter');

const app = express();

// Initialize with default settings
const limiter = new SecureRateLimiter();

// Apply to all routes
app.use(limiter.middleware());

// Or apply to specific routes
app.get('/api/*', limiter.middleware(), (req, res) => {
  res.json({ message: 'API endpoint protected' });
});

app.listen(3000);

Configuration

const limiter = new SecureRateLimiter({
  windowMs: 60 * 1000,           // Time window (1 minute)
  maxRequests: 50,               // Max requests per window
  burstThreshold: 10,            // Max requests in burst window
  burstWindowMs: 5 * 1000,       // Burst detection window (5 seconds)
  delayThresholdMs: 500,         // Min delay between requests (ms)
  suspiciousThreshold: 3,        // Strikes before temp ban
  tempBanDurationMs: 10 * 60 * 1000, // Temp ban duration (10 minutes)
  maxConnectionsPerIP: 20,       // Max concurrent connections per IP
  botKeywords: [                 // Additional bot detection keywords
    'mybot', 'scraper'
  ]
});

Advanced Usage

Manual IP Management

// Ban an IP manually
limiter.banIP('192.168.1.100', 'Suspicious activity');

// Unban an IP
limiter.unbanIP('192.168.1.100');

// Get current statistics
const stats = limiter.getStats();
console.log(stats);
// {
//   totalFingerprints: 150,
//   tempBannedIPs: 5,
//   suspiciousIPs: 12,
//   activeConnections: 45
// }

Custom Bot Detection

const limiter = new SecureRateLimiter({
  botKeywords: [
    'Googlebot', 'Bingbot', 'curl', 'wget',
    'python-requests', 'scrapy', 'selenium'
  ]
});

Environment-Specific Configuration

// Development - More lenient
const devLimiter = new SecureRateLimiter({
  maxRequests: 1000,
  burstThreshold: 50,
  tempBanDurationMs: 60 * 1000 // 1 minute
});

// Production - Strict security
const prodLimiter = new SecureRateLimiter({
  maxRequests: 30,
  burstThreshold: 5,
  delayThresholdMs: 1000,
  tempBanDurationMs: 30 * 60 * 1000 // 30 minutes
});

Protection Mechanisms

1. Rate Limiting

  • Tracks requests per IP/fingerprint combination
  • Configurable time windows and request limits
  • Progressive enforcement with temporary bans

2. Burst Detection

  • Monitors rapid-fire requests in short time windows
  • Separate threshold for burst vs sustained traffic
  • Immediate blocking of burst attacks

3. Bot Detection

  • User-Agent analysis with keyword matching
  • Header pattern analysis (missing standard headers)
  • Behavioral fingerprinting

4. Behavioral Analysis

  • Request timing analysis to detect scripts
  • User-Agent rotation detection
  • Multiple fingerprint tracking per IP

5. Connection Limiting

  • Prevents connection flooding
  • Per-IP concurrent connection limits
  • Automatic cleanup on connection close

6. IP Spoofing Detection

  • Analyzes conflicting IP headers
  • Detects header manipulation attempts
  • Blocks requests with suspicious header combinations

Logging

The middleware creates detailed logs in the logs/ directory:

  • requests.log - All requests with classifications
  • security.log - Security events only (blocks, bans, suspicious activity)

Log format:

2024-01-15T10:30:45.123Z | IP: 192.168.1.100 | UA: Mozilla/5.0... | Status: blocked | Burst limit exceeded

Performance Considerations

  • Memory Usage: Automatic cleanup prevents memory leaks
  • CPU Impact: Minimal overhead with efficient algorithms
  • Scalability: Designed for high-traffic applications
  • Cleanup: Automatic cleanup every 5 minutes removes stale data

Integration Examples

Express.js

const express = require('express');
const SecureRateLimiter = require('secure-rate-limiter');

const app = express();
const limiter = new SecureRateLimiter();

app.use(limiter.middleware());

Koa.js

const Koa = require('koa');
const SecureRateLimiter = require('secure-rate-limiter');

const app = new Koa();
const limiter = new SecureRateLimiter();

app.use(async (ctx, next) => {
  return new Promise((resolve, reject) => {
    limiter.middleware()(ctx.req, ctx.res, (err) => {
      if (err) reject(err);
      else resolve(next());
    });
  });
});

Testing Against Attacks

The middleware has been tested against various attack patterns:

  • High-volume request floods
  • Rotating User-Agent attacks
  • IP header spoofing
  • Distributed attacks with multiple IPs
  • Timing-based evasion attempts

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Submit a pull request

License

MIT License - see LICENSE file for details.

Support

For issues and questions:

  • GitHub Issues: Report a bug
  • Documentation: See examples above
  • Version: 2.0.0