@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.
- package/CHANGELOG.md +632 -293
- package/LICENSE +20 -20
- package/README.md +288 -241
- package/package.json +83 -89
- package/src/core/application.js +1070 -956
- package/src/core/context.js +1100 -830
- package/src/core/middleware.js +305 -217
- package/src/index.js +183 -278
- package/src/middleware/body-parser.js +484 -526
- package/src/middleware/cache.js +179 -170
- package/src/middleware/compression.js +179 -182
- package/src/middleware/cors.js +178 -95
- package/src/middleware/health.js +221 -218
- package/src/middleware/logger.js +197 -194
- package/src/middleware/metrics.js +341 -327
- package/src/middleware/rate-limit.js +369 -319
- package/src/middleware/security.js +444 -332
- package/src/middleware/session.js +649 -529
- package/src/middleware/static.js +406 -299
- package/src/router/layer.js +199 -117
- package/src/router/route.js +151 -123
- package/src/router/router.js +705 -755
- package/src/utils/async-handler.js +147 -144
- package/src/utils/context-pool.js +85 -82
- package/src/utils/regex-validator.js +189 -176
- package/src/utils/safe-json.js +110 -0
- package/types/index.d.ts +536 -291
- package/dist/LICENSE +0 -21
- package/dist/README.md +0 -242
- package/dist/core/application.js +0 -957
- package/dist/core/context.js +0 -831
- package/dist/core/middleware.js +0 -218
- package/dist/core/request.js +0 -333
- package/dist/core/response.js +0 -375
- package/dist/index.js +0 -278
- package/dist/middleware/body-parser.js +0 -526
- package/dist/middleware/cache.js +0 -171
- package/dist/middleware/compression.js +0 -183
- package/dist/middleware/cors.js +0 -95
- package/dist/middleware/health.js +0 -219
- package/dist/middleware/index.js +0 -21
- package/dist/middleware/logger.js +0 -195
- package/dist/middleware/metrics.js +0 -328
- package/dist/middleware/rate-limit.js +0 -320
- package/dist/middleware/security.js +0 -333
- package/dist/middleware/session.js +0 -530
- package/dist/middleware/static.js +0 -299
- package/dist/package.json +0 -62
- package/dist/router/layer.js +0 -117
- package/dist/router/route.js +0 -123
- package/dist/router/router.js +0 -756
- package/dist/types/index.d.ts +0 -291
- package/dist/utils/async-handler.js +0 -145
- package/dist/utils/cache.js +0 -441
- package/dist/utils/context-pool.js +0 -83
- package/dist/utils/error-types.js +0 -132
- package/dist/utils/http.js +0 -413
- package/dist/utils/regex-validator.js +0 -177
- package/src/core/request.js +0 -333
- package/src/core/response.js +0 -375
- package/src/middleware/index.js +0 -21
- package/src/utils/cache.js +0 -441
- package/src/utils/error-types.js +0 -132
- package/src/utils/http.js +0 -413
|
@@ -1,320 +1,370 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
if (cleanupInterval) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
opts.store.cleanup();
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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;
|