Spaces:
Sleeping
Sleeping
Commit Β·
2e1ef81
1
Parent(s): f19b08d
refactor: make rate-limiter require config lazily
Browse files- Resolve rate-limit settings at middleware creation instead of module load
- Decouple the rate limiter from global config to simplify testing
- README.md +1 -0
- src/rate-limiter.js +18 -22
README.md
CHANGED
|
@@ -270,6 +270,7 @@ See [tests/README.md](tests/README.md) for full documentation.
|
|
| 270 |
- **Centralized config** β all environment variables are read in `src/config.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
| 271 |
- **SQL query logging** β `src/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/database.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
| 272 |
- **Multi-environment** β `src/config.js` requires `src/load-env.js` at module level, which auto-loads dotenv using a priority chain based on `NODE_ENV`. Every consumer (server, migrate, seed) simply requires `config.js` and gets correct env values. In production, dotenv is skipped entirely β env vars must come from the deployment environment.
|
|
|
|
| 273 |
- **Testable seed script** β `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
|
| 274 |
- **CORS** enabled on all routes
|
| 275 |
- **Graceful shutdown** β handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
|
|
|
| 270 |
- **Centralized config** β all environment variables are read in `src/config.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
| 271 |
- **SQL query logging** β `src/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/database.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
| 272 |
- **Multi-environment** β `src/config.js` requires `src/load-env.js` at module level, which auto-loads dotenv using a priority chain based on `NODE_ENV`. Every consumer (server, migrate, seed) simply requires `config.js` and gets correct env values. In production, dotenv is skipped entirely β env vars must come from the deployment environment.
|
| 273 |
+
- **Lazy rate-limiter config** β `src/middleware/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
| 274 |
- **Testable seed script** β `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
|
| 275 |
- **CORS** enabled on all routes
|
| 276 |
- **Graceful shutdown** β handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
src/rate-limiter.js
CHANGED
|
@@ -1,40 +1,36 @@
|
|
| 1 |
'use strict';
|
| 2 |
|
| 3 |
-
const {
|
| 4 |
-
rateLimitWindowMs: WINDOW_MS,
|
| 5 |
-
rateLimitMax: MAX_REQ,
|
| 6 |
-
rateLimitEnabled: ENABLED,
|
| 7 |
-
rateLimitWindowSec: WINDOW_SEC,
|
| 8 |
-
} = require('./config');
|
| 9 |
-
|
| 10 |
const memStore = new Map();
|
| 11 |
|
| 12 |
-
function memFallback(ip) {
|
| 13 |
const now = Date.now();
|
| 14 |
let entry = memStore.get(ip);
|
| 15 |
if (!entry || entry.resetAt <= now) {
|
| 16 |
-
entry = { count: 0, resetAt: now +
|
| 17 |
memStore.set(ip, entry);
|
| 18 |
}
|
| 19 |
entry.count++;
|
| 20 |
-
const remaining = Math.max(0,
|
| 21 |
const reset = Math.ceil((entry.resetAt - now) / 1000);
|
| 22 |
-
return { count: entry.count, remaining, reset, limited: entry.count >
|
| 23 |
}
|
| 24 |
|
| 25 |
-
async function checkRedis(redis, ip) {
|
| 26 |
const key = `rl:${ip}`;
|
| 27 |
const count = await redis.incr(key);
|
| 28 |
if (count === 1) {
|
| 29 |
-
await redis.expire(key,
|
| 30 |
}
|
| 31 |
const ttl = await redis.ttl(key);
|
| 32 |
-
const remaining = Math.max(0,
|
| 33 |
-
return { count, remaining, reset: ttl, limited: count >
|
| 34 |
}
|
| 35 |
|
| 36 |
function createRateLimiter(redis) {
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
| 38 |
return async (_req, _res, next) => next();
|
| 39 |
}
|
| 40 |
|
|
@@ -49,25 +45,25 @@ function createRateLimiter(redis) {
|
|
| 49 |
|
| 50 |
if (redis && redis.connected) {
|
| 51 |
try {
|
| 52 |
-
info = await checkRedis(redis, ip);
|
| 53 |
usingRedis = true;
|
| 54 |
} catch (_) {
|
| 55 |
-
info = memFallback(ip);
|
| 56 |
}
|
| 57 |
} else {
|
| 58 |
-
info = memFallback(ip);
|
| 59 |
}
|
| 60 |
|
| 61 |
-
res.setHeader('X-RateLimit-Limit',
|
| 62 |
res.setHeader('X-RateLimit-Remaining', info.remaining);
|
| 63 |
res.setHeader('X-RateLimit-Reset', info.reset);
|
| 64 |
res.setHeader('X-RateLimit-Store', usingRedis ? 'redis' : 'memory');
|
| 65 |
|
| 66 |
if (info.limited) {
|
| 67 |
-
res.writeHead(429, { 'Content-Type': 'application/json', 'Retry-After':
|
| 68 |
res.end(JSON.stringify({
|
| 69 |
error: 'Too Many Requests',
|
| 70 |
-
message: `Rate limit exceeded. Max ${
|
| 71 |
retryAfter: info.reset,
|
| 72 |
}));
|
| 73 |
return;
|
|
|
|
| 1 |
'use strict';
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
const memStore = new Map();
|
| 4 |
|
| 5 |
+
function memFallback(ip, max, windowMs) {
|
| 6 |
const now = Date.now();
|
| 7 |
let entry = memStore.get(ip);
|
| 8 |
if (!entry || entry.resetAt <= now) {
|
| 9 |
+
entry = { count: 0, resetAt: now + windowMs };
|
| 10 |
memStore.set(ip, entry);
|
| 11 |
}
|
| 12 |
entry.count++;
|
| 13 |
+
const remaining = Math.max(0, max - entry.count);
|
| 14 |
const reset = Math.ceil((entry.resetAt - now) / 1000);
|
| 15 |
+
return { count: entry.count, remaining, reset, limited: entry.count > max };
|
| 16 |
}
|
| 17 |
|
| 18 |
+
async function checkRedis(redis, ip, max, windowSec) {
|
| 19 |
const key = `rl:${ip}`;
|
| 20 |
const count = await redis.incr(key);
|
| 21 |
if (count === 1) {
|
| 22 |
+
await redis.expire(key, windowSec);
|
| 23 |
}
|
| 24 |
const ttl = await redis.ttl(key);
|
| 25 |
+
const remaining = Math.max(0, max - count);
|
| 26 |
+
return { count, remaining, reset: ttl, limited: count > max };
|
| 27 |
}
|
| 28 |
|
| 29 |
function createRateLimiter(redis) {
|
| 30 |
+
const config = require('./config');
|
| 31 |
+
const { rateLimitEnabled: enabled, rateLimitMax: max, rateLimitWindowMs: windowMs, rateLimitWindowSec: windowSec } = config;
|
| 32 |
+
|
| 33 |
+
if (!enabled) {
|
| 34 |
return async (_req, _res, next) => next();
|
| 35 |
}
|
| 36 |
|
|
|
|
| 45 |
|
| 46 |
if (redis && redis.connected) {
|
| 47 |
try {
|
| 48 |
+
info = await checkRedis(redis, ip, max, windowSec);
|
| 49 |
usingRedis = true;
|
| 50 |
} catch (_) {
|
| 51 |
+
info = memFallback(ip, max, windowMs);
|
| 52 |
}
|
| 53 |
} else {
|
| 54 |
+
info = memFallback(ip, max, windowMs);
|
| 55 |
}
|
| 56 |
|
| 57 |
+
res.setHeader('X-RateLimit-Limit', max);
|
| 58 |
res.setHeader('X-RateLimit-Remaining', info.remaining);
|
| 59 |
res.setHeader('X-RateLimit-Reset', info.reset);
|
| 60 |
res.setHeader('X-RateLimit-Store', usingRedis ? 'redis' : 'memory');
|
| 61 |
|
| 62 |
if (info.limited) {
|
| 63 |
+
res.writeHead(429, { 'Content-Type': 'application/json', 'Retry-After': windowSec });
|
| 64 |
res.end(JSON.stringify({
|
| 65 |
error: 'Too Many Requests',
|
| 66 |
+
message: `Rate limit exceeded. Max ${max} requests per ${windowSec}s window.`,
|
| 67 |
retryAfter: info.reset,
|
| 68 |
}));
|
| 69 |
return;
|