1.0.0 โ€ข Published 8 months ago

@lock-sdk/rate-limit v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago

Rate Limit

A powerful and flexible rate limiting module for the Lock security framework. Protect your backend services from abuse, brute-force attacks, DDoS attempts, and unexpected surges in traffic using a variety of strategies and pluggable storage options.

๐Ÿš€ Features

  • โœ… Fixed, sliding, token, and leaky bucket strategies
  • ๐ŸŒ Country-based throttling via IP geolocation
  • ๐ŸŒ Distributed rate limit storage with Redis & Upstash support
  • ๐Ÿ›ก๏ธ Built-in DDoS heuristics and adaptive escalation
  • ๐Ÿง  Custom key generators and smart skip logic
  • ๐Ÿ“ฆ Headers for standard and RFC-compliant rate info
  • ๐Ÿ”ฅ Fast in-memory caching via LRU strategies

๐Ÿ›  Usage

Basic Example (100 requests per minute)

import { secure, rateLimit } from '@lock-sdk/main';

const middleware = secure()(
  rateLimit({
    limit: 100,
    windowMs: 60_000, // 1 minute
  })
);

โš™๏ธ Configuration

OptionTypeDescription
limitnumberMax number of requests allowed in the window
windowMsnumberDuration of window in milliseconds
strategy'fixed-window' | 'sliding-window' | 'token-bucket' | 'leaky-bucket' | 'adaptive'Algorithm used to track requests
storage'memory' | 'redis' | 'upstash'Backend for storing request counters
headersbooleanWhether to add rate-limit headers
standardHeadersbooleanInclude legacy X-RateLimit-* headers
statusCodenumberResponse code on limit exceeded (default: 429)
messagestringError message when blocked
resourcesRecord<string, { limit, windowMs }>Route-specific throttles
countryLimitsRecord<string, { limit, windowMs }>Per-country overrides
geoProvider{ type: 'ipapi' | 'maxmind' }Used for country detection
ddosPreventionobjectEnable traffic heuristics for spike prevention
keyGeneratorFunctionCustom function to generate unique request key
skipFunctionFunctionSkip check conditionally (e.g., internal IPs)

๐Ÿ“ก Header Output

When enabled, Lock sets the following headers:

HeaderDescription
X-RateLimit-LimitMax requests per window
X-RateLimit-RemainingRequests remaining in current window
X-RateLimit-ResetTime (seconds) until window resets
Retry-AfterDelay before retrying (if blocked)

๐Ÿงช Example: Per-resource Limits

rateLimit({
  limit: 100,
  windowMs: 60_000,
  resources: {
    '/api/login': { limit: 10, windowMs: 60_000 },
    '/api/posts': { limit: 500, windowMs: 60_000 },
  },
});

๐ŸŒ Example: Country-specific Throttling

rateLimit({
  limit: 100,
  windowMs: 60_000,
  geoProvider: { type: 'ipapi' },
  countryLimits: {
    US: { limit: 200, windowMs: 60_000 },
  },
});

๐Ÿ” DDoS Protection

Built-in heuristic-based protection:

ddosPrevention: {
  enabled: true,
  requestRateThreshold: 100,
  burstThreshold: 30,
  banDurationMs: 600_000
}

๐Ÿงฉ Storage Backends

Memory (Default)

storage: 'memory',
memoryOptions: {
  max: 10_000,
  ttl: 3600_000
}

Redis

storage: 'redis',
redis: {
  url: 'redis://localhost:6379',
  password: 'secret'
  //pass username if using Redis cloud
}

Upstash

storage: 'upstash',
upstash: {
  url: process.env.UPSTASH_REDIS_REST_URL!,
  token: process.env.UPSTASH_REDIS_REST_TOKEN!
}

๐Ÿ’ก Pro Tip: Custom Key (e.g., User ID)

rateLimit({
  keyGenerator: async ctx => ctx.request.headers['x-user-id'] || 'anonymous',
});

๐Ÿงช Testing

Use any HTTP client like curl, Postman, or k6 to simulate burst requests and test blocking.

๐Ÿ›ก Maintained By

Lock Team