@oxog/spark 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +632 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,320 +1,370 @@
1
- const DEFAULT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
2
- const DEFAULT_MAX_REQUESTS = 100;
3
- const DEFAULT_MESSAGE = 'Too many requests, please try again later.';
4
-
5
- class MemoryStore {
6
- constructor() {
7
- this.store = new Map();
8
- this.resetTimes = new Map();
9
- }
10
-
11
- async incr(key, windowMs) {
12
- const now = Date.now();
13
- const resetTime = this.resetTimes.get(key) || now;
14
-
15
- if (now > resetTime) {
16
- this.store.set(key, 1);
17
- this.resetTimes.set(key, now + windowMs);
18
- return { totalHits: 1, resetTime: now + windowMs };
19
- }
20
-
21
- const current = this.store.get(key) || 0;
22
- const newCount = current + 1;
23
- this.store.set(key, newCount);
24
-
25
- return { totalHits: newCount, resetTime };
26
- }
27
-
28
- async decrement(key) {
29
- const current = this.store.get(key) || 0;
30
- if (current > 0) {
31
- this.store.set(key, current - 1);
32
- }
33
- }
34
-
35
- async reset(key) {
36
- this.store.delete(key);
37
- this.resetTimes.delete(key);
38
- }
39
-
40
- cleanup() {
41
- const now = Date.now();
42
- for (const [key, resetTime] of this.resetTimes) {
43
- if (now > resetTime) {
44
- this.store.delete(key);
45
- this.resetTimes.delete(key);
46
- }
47
- }
48
- }
49
- }
50
-
51
- function rateLimit(options = {}) {
52
- const opts = {
53
- windowMs: options.windowMs || DEFAULT_WINDOW_MS,
54
- max: options.max || DEFAULT_MAX_REQUESTS,
55
- message: options.message || DEFAULT_MESSAGE,
56
- statusCode: options.statusCode || 429,
57
- headers: options.headers !== false,
58
- keyGenerator: options.keyGenerator || defaultKeyGenerator,
59
- handler: options.handler || defaultHandler,
60
- onLimitReached: options.onLimitReached,
61
- skipSuccessfulRequests: options.skipSuccessfulRequests || false,
62
- skipFailedRequests: options.skipFailedRequests || false,
63
- store: options.store || new MemoryStore(),
64
- ...options
65
- };
66
-
67
- // Start cleanup interval
68
- let cleanupInterval;
69
- if (opts.store.cleanup) {
70
- // Use smaller interval for cleanup (1/4 of window)
71
- const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
72
- cleanupInterval = setInterval(() => {
73
- opts.store.cleanup();
74
- }, cleanupPeriod);
75
-
76
- // Allow cleanup interval to be stopped when server shuts down
77
- if (cleanupInterval.unref) {
78
- cleanupInterval.unref();
79
- }
80
- }
81
-
82
- const middleware = async (ctx, next) => {
83
- const key = opts.keyGenerator(ctx);
84
- const { totalHits, resetTime } = await opts.store.incr(key, opts.windowMs);
85
-
86
- if (opts.headers) {
87
- ctx.set('X-RateLimit-Limit', opts.max);
88
- ctx.set('X-RateLimit-Remaining', Math.max(0, opts.max - totalHits));
89
- ctx.set('X-RateLimit-Reset', new Date(resetTime).toISOString());
90
- }
91
-
92
- if (totalHits <= opts.max) {
93
- await next();
94
-
95
- if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
96
- await opts.store.decrement(key);
97
- }
98
- } else {
99
- if (opts.onLimitReached) {
100
- opts.onLimitReached(ctx, opts);
101
- }
102
-
103
- return opts.handler(ctx, opts);
104
- }
105
-
106
- if (opts.skipFailedRequests && ctx.statusCode >= 400) {
107
- await opts.store.decrement(key);
108
- }
109
- };
110
-
111
- // Attach cleanup method to middleware for manual cleanup
112
- middleware.cleanup = () => {
113
- if (cleanupInterval) {
114
- clearInterval(cleanupInterval);
115
- cleanupInterval = null;
116
- }
117
- if (opts.store.cleanup) {
118
- opts.store.cleanup();
119
- }
120
- };
121
-
122
- // Attach store for external access if needed
123
- middleware.store = opts.store;
124
-
125
- return middleware;
126
- }
127
-
128
- function defaultKeyGenerator(ctx) {
129
- return ctx.ip();
130
- }
131
-
132
- function defaultHandler(ctx, opts) {
133
- ctx.set('Retry-After', Math.round(opts.windowMs / 1000));
134
- ctx.status(opts.statusCode).json({
135
- error: 'Too Many Requests',
136
- message: opts.message
137
- });
138
- }
139
-
140
- function slowDown(options = {}) {
141
- const opts = {
142
- windowMs: options.windowMs || DEFAULT_WINDOW_MS,
143
- delayAfter: options.delayAfter || 1,
144
- delayMs: options.delayMs || 1000,
145
- maxDelayMs: options.maxDelayMs || 60000,
146
- skipSuccessfulRequests: options.skipSuccessfulRequests || false,
147
- skipFailedRequests: options.skipFailedRequests || false,
148
- keyGenerator: options.keyGenerator || defaultKeyGenerator,
149
- store: options.store || new MemoryStore(),
150
- ...options
151
- };
152
-
153
- // Start cleanup interval for slowDown store
154
- let cleanupInterval;
155
- if (opts.store.cleanup) {
156
- const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
157
- cleanupInterval = setInterval(() => {
158
- opts.store.cleanup();
159
- }, cleanupPeriod);
160
-
161
- if (cleanupInterval.unref) {
162
- cleanupInterval.unref();
163
- }
164
- }
165
-
166
- const middleware = async (ctx, next) => {
167
- const key = opts.keyGenerator(ctx);
168
- const { totalHits } = await opts.store.incr(key, opts.windowMs);
169
-
170
- if (totalHits > opts.delayAfter) {
171
- const delay = Math.min(
172
- (totalHits - opts.delayAfter) * opts.delayMs,
173
- opts.maxDelayMs
174
- );
175
-
176
- await new Promise(resolve => setTimeout(resolve, delay));
177
- }
178
-
179
- await next();
180
-
181
- if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
182
- await opts.store.decrement(key);
183
- }
184
-
185
- if (opts.skipFailedRequests && ctx.statusCode >= 400) {
186
- await opts.store.decrement(key);
187
- }
188
- };
189
-
190
- // Attach cleanup method
191
- middleware.cleanup = () => {
192
- if (cleanupInterval) {
193
- clearInterval(cleanupInterval);
194
- cleanupInterval = null;
195
- }
196
- if (opts.store.cleanup) {
197
- opts.store.cleanup();
198
- }
199
- };
200
-
201
- middleware.store = opts.store;
202
-
203
- return middleware;
204
- }
205
-
206
- class TokenBucket {
207
- constructor(capacity, refillRate, refillPeriod = 1000) {
208
- this.capacity = capacity;
209
- this.tokens = capacity;
210
- this.refillRate = refillRate;
211
- this.refillPeriod = refillPeriod;
212
- this.lastRefill = Date.now();
213
- }
214
-
215
- consume(tokens = 1) {
216
- this.refill();
217
-
218
- if (this.tokens >= tokens) {
219
- this.tokens -= tokens;
220
- return true;
221
- }
222
-
223
- return false;
224
- }
225
-
226
- refill() {
227
- const now = Date.now();
228
- const timePassed = now - this.lastRefill;
229
- const tokensToAdd = Math.floor(timePassed / this.refillPeriod * this.refillRate);
230
-
231
- if (tokensToAdd > 0) {
232
- this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
233
- this.lastRefill = now;
234
- }
235
- }
236
- }
237
-
238
- function tokenBucket(options = {}) {
239
- const opts = {
240
- capacity: options.capacity || 10,
241
- refillRate: options.refillRate || 1,
242
- refillPeriod: options.refillPeriod || 1000,
243
- keyGenerator: options.keyGenerator || defaultKeyGenerator,
244
- message: options.message || DEFAULT_MESSAGE,
245
- statusCode: options.statusCode || 429,
246
- cleanupPeriod: options.cleanupPeriod || 300000, // 5 minutes
247
- maxBuckets: options.maxBuckets || 10000, // Maximum number of buckets to prevent memory leak
248
- ...options
249
- };
250
-
251
- const buckets = new Map();
252
- const lastActivity = new Map();
253
-
254
- // Cleanup old buckets
255
- const cleanupInterval = setInterval(() => {
256
- const now = Date.now();
257
- const keysToDelete = [];
258
-
259
- for (const [key, timestamp] of lastActivity) {
260
- if (now - timestamp > opts.cleanupPeriod) {
261
- keysToDelete.push(key);
262
- }
263
- }
264
-
265
- for (const key of keysToDelete) {
266
- buckets.delete(key);
267
- lastActivity.delete(key);
268
- }
269
- }, Math.max(60000, opts.cleanupPeriod / 4));
270
-
271
- if (cleanupInterval.unref) {
272
- cleanupInterval.unref();
273
- }
274
-
275
- const middleware = async (ctx, next) => {
276
- const key = opts.keyGenerator(ctx);
277
-
278
- // Prevent unlimited growth
279
- if (!buckets.has(key) && buckets.size >= opts.maxBuckets) {
280
- // Remove oldest bucket
281
- const oldestKey = lastActivity.entries().next().value?.[0];
282
- if (oldestKey) {
283
- buckets.delete(oldestKey);
284
- lastActivity.delete(oldestKey);
285
- }
286
- }
287
-
288
- if (!buckets.has(key)) {
289
- buckets.set(key, new TokenBucket(opts.capacity, opts.refillRate, opts.refillPeriod));
290
- }
291
-
292
- const bucket = buckets.get(key);
293
- lastActivity.set(key, Date.now());
294
-
295
- if (bucket.consume()) {
296
- await next();
297
- } else {
298
- ctx.status(opts.statusCode).json({
299
- error: 'Too Many Requests',
300
- message: opts.message
301
- });
302
- }
303
- };
304
-
305
- // Attach cleanup method
306
- middleware.cleanup = () => {
307
- if (cleanupInterval) {
308
- clearInterval(cleanupInterval);
309
- }
310
- buckets.clear();
311
- lastActivity.clear();
312
- };
313
-
314
- return middleware;
315
- }
316
-
317
- module.exports = rateLimit;
318
- module.exports.slowDown = slowDown;
319
- module.exports.tokenBucket = tokenBucket;
1
+ 'use strict';
2
+
3
+ const DEFAULT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
4
+ const DEFAULT_MAX_REQUESTS = 100;
5
+ const DEFAULT_MESSAGE = 'Too many requests, please try again later.';
6
+
7
+ class MemoryStore {
8
+ constructor(options = {}) {
9
+ this.store = new Map();
10
+ this.resetTimes = new Map();
11
+ // SECURITY: Limit maximum number of keys to prevent memory exhaustion
12
+ this.maxKeys = options.maxKeys || 10000;
13
+ this.lastAccessTimes = new Map(); // Track LRU
14
+ }
15
+
16
+ async incr(key, windowMs) {
17
+ const now = Date.now();
18
+ const resetTime = this.resetTimes.get(key);
19
+
20
+ if (!this.store.has(key) && this.store.size >= this.maxKeys) {
21
+ this._evictOldest();
22
+ }
23
+
24
+ this.lastAccessTimes.set(key, now);
25
+
26
+ // Start a new window for unknown keys and expired windows
27
+ if (resetTime === undefined || now >= resetTime || !this.store.has(key)) {
28
+ this.store.set(key, 1);
29
+ this.resetTimes.set(key, now + windowMs);
30
+ return { totalHits: 1, resetTime: now + windowMs };
31
+ }
32
+
33
+ const newCount = this.store.get(key) + 1;
34
+ this.store.set(key, newCount);
35
+ return { totalHits: newCount, resetTime };
36
+ }
37
+
38
+ async decrement(key) {
39
+ const current = this.store.get(key) || 0;
40
+ if (current > 0) {
41
+ this.store.set(key, current - 1);
42
+ }
43
+ }
44
+
45
+ async reset(key) {
46
+ this.store.delete(key);
47
+ this.resetTimes.delete(key);
48
+ this.lastAccessTimes.delete(key);
49
+ }
50
+
51
+ cleanup() {
52
+ // SECURITY NOTE: Potential race condition exists here
53
+ // Cleanup runs periodically and could conflict with concurrent incr() calls
54
+ // This is acceptable for MemoryStore as Map operations are atomic in single-threaded Node.js
55
+ // For distributed stores, use atomic operations or locks for production deployments
56
+ const now = Date.now();
57
+ for (const [key, resetTime] of this.resetTimes) {
58
+ if (now > resetTime) {
59
+ this.store.delete(key);
60
+ this.resetTimes.delete(key);
61
+ this.lastAccessTimes.delete(key);
62
+ }
63
+ }
64
+ }
65
+
66
+ _evictOldest() {
67
+ // Find and remove the least recently used entry
68
+ let oldestKey = null;
69
+ let oldestTime = Infinity;
70
+
71
+ for (const [key, time] of this.lastAccessTimes) {
72
+ if (time < oldestTime) {
73
+ oldestTime = time;
74
+ oldestKey = key;
75
+ }
76
+ }
77
+
78
+ if (oldestKey) {
79
+ this.store.delete(oldestKey);
80
+ this.resetTimes.delete(oldestKey);
81
+ this.lastAccessTimes.delete(oldestKey);
82
+ }
83
+ }
84
+ }
85
+
86
+ function rateLimit(options = {}) {
87
+ const opts = {
88
+ windowMs: options.windowMs || DEFAULT_WINDOW_MS,
89
+ max: options.max || DEFAULT_MAX_REQUESTS,
90
+ message: options.message || DEFAULT_MESSAGE,
91
+ statusCode: options.statusCode || 429,
92
+ headers: options.headers !== false,
93
+ keyGenerator: options.keyGenerator || defaultKeyGenerator,
94
+ handler: options.handler || defaultHandler,
95
+ onLimitReached: options.onLimitReached,
96
+ skipSuccessfulRequests: options.skipSuccessfulRequests || false,
97
+ skipFailedRequests: options.skipFailedRequests || false,
98
+ // SECURITY: Pass maxKeys to MemoryStore to prevent unbounded memory growth
99
+ store: options.store || new MemoryStore({ maxKeys: options.maxKeys }),
100
+ ...options
101
+ };
102
+
103
+ // Start cleanup interval
104
+ let cleanupInterval;
105
+ if (opts.store.cleanup) {
106
+ // Use smaller interval for cleanup (1/4 of window)
107
+ const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
108
+ cleanupInterval = setInterval(() => {
109
+ opts.store.cleanup();
110
+ }, cleanupPeriod);
111
+
112
+ // Allow cleanup interval to be stopped when server shuts down
113
+ if (cleanupInterval.unref) {
114
+ cleanupInterval.unref();
115
+ }
116
+ }
117
+
118
+ const middleware = async (ctx, next) => {
119
+ if (typeof opts.skip === 'function' && await opts.skip(ctx)) {
120
+ return next();
121
+ }
122
+
123
+ const key = opts.keyGenerator(ctx);
124
+ const { totalHits, resetTime } = await opts.store.incr(key, opts.windowMs);
125
+
126
+ if (opts.headers) {
127
+ ctx.set('X-RateLimit-Limit', opts.max);
128
+ ctx.set('X-RateLimit-Remaining', Math.max(0, opts.max - totalHits));
129
+ ctx.set('X-RateLimit-Reset', new Date(resetTime).toISOString());
130
+ }
131
+
132
+ if (totalHits <= opts.max) {
133
+ await next();
134
+
135
+ if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
136
+ await opts.store.decrement(key);
137
+ }
138
+ } else {
139
+ if (opts.onLimitReached) {
140
+ opts.onLimitReached(ctx, opts);
141
+ }
142
+
143
+ return opts.handler(ctx, opts, resetTime);
144
+ }
145
+
146
+ if (opts.skipFailedRequests && ctx.statusCode >= 400) {
147
+ await opts.store.decrement(key);
148
+ }
149
+ };
150
+
151
+ // Attach cleanup method to middleware for manual cleanup
152
+ middleware.cleanup = () => {
153
+ if (cleanupInterval) {
154
+ clearInterval(cleanupInterval);
155
+ cleanupInterval = null;
156
+ }
157
+ if (opts.store.cleanup) {
158
+ opts.store.cleanup();
159
+ }
160
+ };
161
+
162
+ // Attach store for external access if needed
163
+ middleware.store = opts.store;
164
+
165
+ return middleware;
166
+ }
167
+
168
+ function defaultKeyGenerator(ctx) {
169
+ return ctx.ip();
170
+ }
171
+
172
+ function defaultHandler(ctx, opts, resetTime) {
173
+ const retryAfterMs = resetTime ? resetTime - Date.now() : opts.windowMs;
174
+ ctx.set('Retry-After', Math.max(1, Math.ceil(retryAfterMs / 1000)));
175
+ ctx.status(opts.statusCode).json({
176
+ error: 'Too Many Requests',
177
+ message: opts.message
178
+ });
179
+ }
180
+
181
+ function slowDown(options = {}) {
182
+ const opts = {
183
+ windowMs: options.windowMs || DEFAULT_WINDOW_MS,
184
+ delayAfter: options.delayAfter || 1,
185
+ delayMs: options.delayMs || 1000,
186
+ maxDelayMs: options.maxDelayMs || 60000,
187
+ skipSuccessfulRequests: options.skipSuccessfulRequests || false,
188
+ skipFailedRequests: options.skipFailedRequests || false,
189
+ keyGenerator: options.keyGenerator || defaultKeyGenerator,
190
+ // SECURITY FIX (BUG-SEC-009): Pass maxKeys to prevent memory exhaustion in slowDown
191
+ store: options.store || new MemoryStore({ maxKeys: options.maxKeys }),
192
+ ...options
193
+ };
194
+
195
+ // Start cleanup interval for slowDown store
196
+ let cleanupInterval;
197
+ if (opts.store.cleanup) {
198
+ const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
199
+ cleanupInterval = setInterval(() => {
200
+ opts.store.cleanup();
201
+ }, cleanupPeriod);
202
+
203
+ if (cleanupInterval.unref) {
204
+ cleanupInterval.unref();
205
+ }
206
+ }
207
+
208
+ const middleware = async (ctx, next) => {
209
+ const key = opts.keyGenerator(ctx);
210
+ const { totalHits } = await opts.store.incr(key, opts.windowMs);
211
+
212
+ if (totalHits > opts.delayAfter) {
213
+ const delay = Math.min(
214
+ (totalHits - opts.delayAfter) * opts.delayMs,
215
+ opts.maxDelayMs
216
+ );
217
+
218
+ await new Promise(resolve => setTimeout(resolve, delay));
219
+ }
220
+
221
+ await next();
222
+
223
+ if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
224
+ await opts.store.decrement(key);
225
+ }
226
+
227
+ if (opts.skipFailedRequests && ctx.statusCode >= 400) {
228
+ await opts.store.decrement(key);
229
+ }
230
+ };
231
+
232
+ // Attach cleanup method
233
+ middleware.cleanup = () => {
234
+ if (cleanupInterval) {
235
+ clearInterval(cleanupInterval);
236
+ cleanupInterval = null;
237
+ }
238
+ if (opts.store.cleanup) {
239
+ opts.store.cleanup();
240
+ }
241
+ };
242
+
243
+ middleware.store = opts.store;
244
+
245
+ return middleware;
246
+ }
247
+
248
+ class TokenBucket {
249
+ constructor(capacity, refillRate, refillPeriod = 1000) {
250
+ this.capacity = capacity;
251
+ this.tokens = capacity;
252
+ this.refillRate = refillRate;
253
+ this.refillPeriod = refillPeriod;
254
+ this.lastRefill = Date.now();
255
+ }
256
+
257
+ consume(tokens = 1) {
258
+ this.refill();
259
+
260
+ if (this.tokens >= tokens) {
261
+ this.tokens -= tokens;
262
+ return true;
263
+ }
264
+
265
+ return false;
266
+ }
267
+
268
+ refill() {
269
+ const now = Date.now();
270
+ const timePassed = now - this.lastRefill;
271
+ const tokensToAdd = Math.floor(timePassed / this.refillPeriod * this.refillRate);
272
+
273
+ if (tokensToAdd > 0) {
274
+ this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
275
+ this.lastRefill = now;
276
+ }
277
+ }
278
+ }
279
+
280
+ function tokenBucket(options = {}) {
281
+ const opts = {
282
+ capacity: options.capacity || 10,
283
+ refillRate: options.refillRate || 1,
284
+ refillPeriod: options.refillPeriod || 1000,
285
+ keyGenerator: options.keyGenerator || defaultKeyGenerator,
286
+ message: options.message || DEFAULT_MESSAGE,
287
+ statusCode: options.statusCode || 429,
288
+ cleanupPeriod: options.cleanupPeriod || 300000, // 5 minutes
289
+ maxBuckets: options.maxBuckets || 10000, // Maximum number of buckets to prevent memory leak
290
+ ...options
291
+ };
292
+
293
+ const buckets = new Map();
294
+ const lastActivity = new Map();
295
+
296
+ // Cleanup old buckets
297
+ const cleanupInterval = setInterval(() => {
298
+ const now = Date.now();
299
+ const keysToDelete = [];
300
+
301
+ for (const [key, timestamp] of lastActivity) {
302
+ if (now - timestamp > opts.cleanupPeriod) {
303
+ keysToDelete.push(key);
304
+ }
305
+ }
306
+
307
+ for (const key of keysToDelete) {
308
+ buckets.delete(key);
309
+ lastActivity.delete(key);
310
+ }
311
+ }, Math.max(60000, opts.cleanupPeriod / 4));
312
+
313
+ if (cleanupInterval.unref) {
314
+ cleanupInterval.unref();
315
+ }
316
+
317
+ const middleware = async (ctx, next) => {
318
+ const key = opts.keyGenerator(ctx);
319
+
320
+ // Prevent unlimited growth
321
+ if (!buckets.has(key) && buckets.size >= opts.maxBuckets) {
322
+ // SECURITY: Remove least recently used bucket (LRU eviction)
323
+ // Find the entry with the smallest timestamp (oldest access time)
324
+ let oldestKey = null;
325
+ let oldestTime = Infinity;
326
+ for (const [k, timestamp] of lastActivity) {
327
+ if (timestamp < oldestTime) {
328
+ oldestTime = timestamp;
329
+ oldestKey = k;
330
+ }
331
+ }
332
+ if (oldestKey) {
333
+ buckets.delete(oldestKey);
334
+ lastActivity.delete(oldestKey);
335
+ }
336
+ }
337
+
338
+ if (!buckets.has(key)) {
339
+ buckets.set(key, new TokenBucket(opts.capacity, opts.refillRate, opts.refillPeriod));
340
+ }
341
+
342
+ const bucket = buckets.get(key);
343
+ lastActivity.set(key, Date.now());
344
+
345
+ if (bucket.consume()) {
346
+ await next();
347
+ } else {
348
+ ctx.status(opts.statusCode).json({
349
+ error: 'Too Many Requests',
350
+ message: opts.message
351
+ });
352
+ }
353
+ };
354
+
355
+ // Attach cleanup method
356
+ middleware.cleanup = () => {
357
+ if (cleanupInterval) {
358
+ clearInterval(cleanupInterval);
359
+ }
360
+ buckets.clear();
361
+ lastActivity.clear();
362
+ };
363
+
364
+ return middleware;
365
+ }
366
+
367
+ module.exports = rateLimit;
368
+ module.exports.slowDown = slowDown;
369
+ module.exports.tokenBucket = tokenBucket;
320
370
  module.exports.MemoryStore = MemoryStore;