@oxog/spark 1.1.1 → 1.3.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 +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +538 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,322 +1,370 @@
1
1
  'use strict';
2
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() {
9
- this.store = new Map();
10
- this.resetTimes = new Map();
11
- }
12
-
13
- async incr(key, windowMs) {
14
- const now = Date.now();
15
- const resetTime = this.resetTimes.get(key) || now;
16
-
17
- if (now > resetTime) {
18
- this.store.set(key, 1);
19
- this.resetTimes.set(key, now + windowMs);
20
- return { totalHits: 1, resetTime: now + windowMs };
21
- }
22
-
23
- const current = this.store.get(key) || 0;
24
- const newCount = current + 1;
25
- this.store.set(key, newCount);
26
-
27
- return { totalHits: newCount, resetTime };
28
- }
29
-
30
- async decrement(key) {
31
- const current = this.store.get(key) || 0;
32
- if (current > 0) {
33
- this.store.set(key, current - 1);
34
- }
35
- }
36
-
37
- async reset(key) {
38
- this.store.delete(key);
39
- this.resetTimes.delete(key);
40
- }
41
-
42
- cleanup() {
43
- const now = Date.now();
44
- for (const [key, resetTime] of this.resetTimes) {
45
- if (now > resetTime) {
46
- this.store.delete(key);
47
- this.resetTimes.delete(key);
48
- }
49
- }
50
- }
51
- }
52
-
53
- function rateLimit(options = {}) {
54
- const opts = {
55
- windowMs: options.windowMs || DEFAULT_WINDOW_MS,
56
- max: options.max || DEFAULT_MAX_REQUESTS,
57
- message: options.message || DEFAULT_MESSAGE,
58
- statusCode: options.statusCode || 429,
59
- headers: options.headers !== false,
60
- keyGenerator: options.keyGenerator || defaultKeyGenerator,
61
- handler: options.handler || defaultHandler,
62
- onLimitReached: options.onLimitReached,
63
- skipSuccessfulRequests: options.skipSuccessfulRequests || false,
64
- skipFailedRequests: options.skipFailedRequests || false,
65
- store: options.store || new MemoryStore(),
66
- ...options
67
- };
68
-
69
- // Start cleanup interval
70
- let cleanupInterval;
71
- if (opts.store.cleanup) {
72
- // Use smaller interval for cleanup (1/4 of window)
73
- const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
74
- cleanupInterval = setInterval(() => {
75
- opts.store.cleanup();
76
- }, cleanupPeriod);
77
-
78
- // Allow cleanup interval to be stopped when server shuts down
79
- if (cleanupInterval.unref) {
80
- cleanupInterval.unref();
81
- }
82
- }
83
-
84
- const middleware = async (ctx, next) => {
85
- const key = opts.keyGenerator(ctx);
86
- const { totalHits, resetTime } = await opts.store.incr(key, opts.windowMs);
87
-
88
- if (opts.headers) {
89
- ctx.set('X-RateLimit-Limit', opts.max);
90
- ctx.set('X-RateLimit-Remaining', Math.max(0, opts.max - totalHits));
91
- ctx.set('X-RateLimit-Reset', new Date(resetTime).toISOString());
92
- }
93
-
94
- if (totalHits <= opts.max) {
95
- await next();
96
-
97
- if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
98
- await opts.store.decrement(key);
99
- }
100
- } else {
101
- if (opts.onLimitReached) {
102
- opts.onLimitReached(ctx, opts);
103
- }
104
-
105
- return opts.handler(ctx, opts);
106
- }
107
-
108
- if (opts.skipFailedRequests && ctx.statusCode >= 400) {
109
- await opts.store.decrement(key);
110
- }
111
- };
112
-
113
- // Attach cleanup method to middleware for manual cleanup
114
- middleware.cleanup = () => {
115
- if (cleanupInterval) {
116
- clearInterval(cleanupInterval);
117
- cleanupInterval = null;
118
- }
119
- if (opts.store.cleanup) {
120
- opts.store.cleanup();
121
- }
122
- };
123
-
124
- // Attach store for external access if needed
125
- middleware.store = opts.store;
126
-
127
- return middleware;
128
- }
129
-
130
- function defaultKeyGenerator(ctx) {
131
- return ctx.ip();
132
- }
133
-
134
- function defaultHandler(ctx, opts) {
135
- ctx.set('Retry-After', Math.round(opts.windowMs / 1000));
136
- ctx.status(opts.statusCode).json({
137
- error: 'Too Many Requests',
138
- message: opts.message
139
- });
140
- }
141
-
142
- function slowDown(options = {}) {
143
- const opts = {
144
- windowMs: options.windowMs || DEFAULT_WINDOW_MS,
145
- delayAfter: options.delayAfter || 1,
146
- delayMs: options.delayMs || 1000,
147
- maxDelayMs: options.maxDelayMs || 60000,
148
- skipSuccessfulRequests: options.skipSuccessfulRequests || false,
149
- skipFailedRequests: options.skipFailedRequests || false,
150
- keyGenerator: options.keyGenerator || defaultKeyGenerator,
151
- store: options.store || new MemoryStore(),
152
- ...options
153
- };
154
-
155
- // Start cleanup interval for slowDown store
156
- let cleanupInterval;
157
- if (opts.store.cleanup) {
158
- const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
159
- cleanupInterval = setInterval(() => {
160
- opts.store.cleanup();
161
- }, cleanupPeriod);
162
-
163
- if (cleanupInterval.unref) {
164
- cleanupInterval.unref();
165
- }
166
- }
167
-
168
- const middleware = async (ctx, next) => {
169
- const key = opts.keyGenerator(ctx);
170
- const { totalHits } = await opts.store.incr(key, opts.windowMs);
171
-
172
- if (totalHits > opts.delayAfter) {
173
- const delay = Math.min(
174
- (totalHits - opts.delayAfter) * opts.delayMs,
175
- opts.maxDelayMs
176
- );
177
-
178
- await new Promise(resolve => setTimeout(resolve, delay));
179
- }
180
-
181
- await next();
182
-
183
- if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
184
- await opts.store.decrement(key);
185
- }
186
-
187
- if (opts.skipFailedRequests && ctx.statusCode >= 400) {
188
- await opts.store.decrement(key);
189
- }
190
- };
191
-
192
- // Attach cleanup method
193
- middleware.cleanup = () => {
194
- if (cleanupInterval) {
195
- clearInterval(cleanupInterval);
196
- cleanupInterval = null;
197
- }
198
- if (opts.store.cleanup) {
199
- opts.store.cleanup();
200
- }
201
- };
202
-
203
- middleware.store = opts.store;
204
-
205
- return middleware;
206
- }
207
-
208
- class TokenBucket {
209
- constructor(capacity, refillRate, refillPeriod = 1000) {
210
- this.capacity = capacity;
211
- this.tokens = capacity;
212
- this.refillRate = refillRate;
213
- this.refillPeriod = refillPeriod;
214
- this.lastRefill = Date.now();
215
- }
216
-
217
- consume(tokens = 1) {
218
- this.refill();
219
-
220
- if (this.tokens >= tokens) {
221
- this.tokens -= tokens;
222
- return true;
223
- }
224
-
225
- return false;
226
- }
227
-
228
- refill() {
229
- const now = Date.now();
230
- const timePassed = now - this.lastRefill;
231
- const tokensToAdd = Math.floor(timePassed / this.refillPeriod * this.refillRate);
232
-
233
- if (tokensToAdd > 0) {
234
- this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
235
- this.lastRefill = now;
236
- }
237
- }
238
- }
239
-
240
- function tokenBucket(options = {}) {
241
- const opts = {
242
- capacity: options.capacity || 10,
243
- refillRate: options.refillRate || 1,
244
- refillPeriod: options.refillPeriod || 1000,
245
- keyGenerator: options.keyGenerator || defaultKeyGenerator,
246
- message: options.message || DEFAULT_MESSAGE,
247
- statusCode: options.statusCode || 429,
248
- cleanupPeriod: options.cleanupPeriod || 300000, // 5 minutes
249
- maxBuckets: options.maxBuckets || 10000, // Maximum number of buckets to prevent memory leak
250
- ...options
251
- };
252
-
253
- const buckets = new Map();
254
- const lastActivity = new Map();
255
-
256
- // Cleanup old buckets
257
- const cleanupInterval = setInterval(() => {
258
- const now = Date.now();
259
- const keysToDelete = [];
260
-
261
- for (const [key, timestamp] of lastActivity) {
262
- if (now - timestamp > opts.cleanupPeriod) {
263
- keysToDelete.push(key);
264
- }
265
- }
266
-
267
- for (const key of keysToDelete) {
268
- buckets.delete(key);
269
- lastActivity.delete(key);
270
- }
271
- }, Math.max(60000, opts.cleanupPeriod / 4));
272
-
273
- if (cleanupInterval.unref) {
274
- cleanupInterval.unref();
275
- }
276
-
277
- const middleware = async (ctx, next) => {
278
- const key = opts.keyGenerator(ctx);
279
-
280
- // Prevent unlimited growth
281
- if (!buckets.has(key) && buckets.size >= opts.maxBuckets) {
282
- // Remove oldest bucket
283
- const oldestKey = lastActivity.entries().next().value?.[0];
284
- if (oldestKey) {
285
- buckets.delete(oldestKey);
286
- lastActivity.delete(oldestKey);
287
- }
288
- }
289
-
290
- if (!buckets.has(key)) {
291
- buckets.set(key, new TokenBucket(opts.capacity, opts.refillRate, opts.refillPeriod));
292
- }
293
-
294
- const bucket = buckets.get(key);
295
- lastActivity.set(key, Date.now());
296
-
297
- if (bucket.consume()) {
298
- await next();
299
- } else {
300
- ctx.status(opts.statusCode).json({
301
- error: 'Too Many Requests',
302
- message: opts.message
303
- });
304
- }
305
- };
306
-
307
- // Attach cleanup method
308
- middleware.cleanup = () => {
309
- if (cleanupInterval) {
310
- clearInterval(cleanupInterval);
311
- }
312
- buckets.clear();
313
- lastActivity.clear();
314
- };
315
-
316
- return middleware;
317
- }
318
-
319
- module.exports = rateLimit;
320
- module.exports.slowDown = slowDown;
321
- module.exports.tokenBucket = tokenBucket;
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;
322
370
  module.exports.MemoryStore = MemoryStore;