-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathboundedRateLimitStore.js
More file actions
266 lines (239 loc) · 9.13 KB
/
Copy pathboundedRateLimitStore.js
File metadata and controls
266 lines (239 loc) · 9.13 KB
1
2
3
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
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
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
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
'use strict';
const DEFAULT_MAX_KEYS = 20_000;
const DEFAULT_MAX_WINDOW_MS = 24 * 60 * 60 * 1000;
const DEFAULT_MAX_KEY_LENGTH = 512;
const DEFAULT_SWEEP_INTERVAL_MS = 60 * 1000;
const MAX_TIMER_MS = 2_147_483_647;
const FAIL_CLOSED_HITS = Number.MAX_SAFE_INTEGER;
/**
* An in-process express-rate-limit v7 Store with strict memory and TTL bounds.
*
* Active counters are never evicted to admit a new key. When the store is at
* capacity (or cannot safely identify a key), increment() returns the largest
* valid hit count. This makes express-rate-limit reject the request without
* turning ordinary admission pressure into an application error.
*/
class BoundedRateLimitStore {
constructor({
maxKeys = DEFAULT_MAX_KEYS,
maxWindowMs = DEFAULT_MAX_WINDOW_MS,
maxKeyLength = DEFAULT_MAX_KEY_LENGTH,
sweepIntervalMs = Math.min(DEFAULT_SWEEP_INTERVAL_MS, maxWindowMs),
autoSweep = true,
now = Date.now,
setIntervalFn = setInterval,
clearIntervalFn = clearInterval,
} = {}) {
this.maxKeys = requirePositiveInteger(maxKeys, 'maxKeys');
this.maxWindowMs = requireTimerDuration(maxWindowMs, 'maxWindowMs');
this.maxKeyLength = requirePositiveInteger(maxKeyLength, 'maxKeyLength');
this.sweepIntervalMs = requireTimerDuration(sweepIntervalMs, 'sweepIntervalMs');
if (this.sweepIntervalMs > this.maxWindowMs) {
throw new RangeError('sweepIntervalMs must not exceed maxWindowMs');
}
if (typeof autoSweep !== 'boolean') throw new TypeError('autoSweep must be a boolean');
if (typeof now !== 'function') throw new TypeError('now must be a function');
if (typeof setIntervalFn !== 'function') throw new TypeError('setIntervalFn must be a function');
if (typeof clearIntervalFn !== 'function') throw new TypeError('clearIntervalFn must be a function');
this.localKeys = true;
this.windowMs = undefined;
this._autoSweep = autoSweep;
this._now = now;
this._setInterval = setIntervalFn;
this._clearInterval = clearIntervalFn;
this._clients = new Map();
this._timer = undefined;
this._initialized = false;
this._metrics = {
increments: 0,
decrements: 0,
expired: 0,
capacityDenied: 0,
invalidKeys: 0,
clockErrors: 0,
timerErrors: 0,
sweeps: 0,
resets: 0,
};
}
/** Initialize the Store from express-rate-limit's normalized options. */
init(options) {
const windowMs = requireTimerDuration(options?.windowMs, 'options.windowMs');
if (windowMs > this.maxWindowMs) {
throw new RangeError(`options.windowMs must not exceed ${this.maxWindowMs}`);
}
if (typeof options?.limit === 'number' && options.limit >= FAIL_CLOSED_HITS) {
throw new RangeError(`options.limit must be less than ${FAIL_CLOSED_HITS}`);
}
this.stopSweeper();
this._clients.clear();
this.windowMs = windowMs;
this._initialized = true;
if (this._autoSweep) this._startSweeper();
}
get(key) {
if (!this._initialized || !this._isValidKey(key)) return undefined;
const timestamp = this._readNow();
if (timestamp === undefined) return undefined;
const client = this._readClient(key, timestamp);
return client ? responseFor(client) : undefined;
}
increment(key) {
this._metrics.increments += 1;
const timestamp = this._readNow();
if (!this._initialized || timestamp === undefined) return this._failClosed(timestamp);
if (!this._isValidKey(key)) {
this._metrics.invalidKeys += 1;
return this._failClosed(timestamp);
}
let client = this._readClient(key, timestamp);
if (!client) {
if (this._clients.size >= this.maxKeys) this._sweepExpired(timestamp);
if (this._clients.size >= this.maxKeys) {
this._metrics.capacityDenied += 1;
return this._failClosed(timestamp);
}
const expiresAt = timestamp + this.windowMs;
client = { totalHits: 0, expiresAt };
this._clients.set(key, client);
}
if (client.totalHits < FAIL_CLOSED_HITS) client.totalHits += 1;
return responseFor(client);
}
decrement(key) {
if (!this._initialized || !this._isValidKey(key)) return;
const timestamp = this._readNow();
if (timestamp === undefined) return;
const client = this._readClient(key, timestamp);
if (!client) return;
this._metrics.decrements += 1;
if (client.totalHits <= 1) {
// A zero-hit bucket carries no security value and retaining it would
// make skipSuccessfulRequests vulnerable to capacity exhaustion.
this._clients.delete(key);
} else {
client.totalHits -= 1;
}
}
resetKey(key) {
if (!this._isValidKey(key)) return;
if (this._clients.delete(key)) this._metrics.resets += 1;
}
resetAll() {
if (this._clients.size > 0) this._metrics.resets += this._clients.size;
this._clients.clear();
}
/** Stop the periodic sweeper while retaining counters for lazy expiry. */
stopSweeper() {
if (this._timer === undefined) return false;
const timer = this._timer;
this._timer = undefined;
try {
this._clearInterval(timer);
} catch {
this._metrics.timerErrors += 1;
}
return true;
}
/** express-rate-limit Store lifecycle hook. Requests fail closed afterward. */
shutdown() {
this.stopSweeper();
this.resetAll();
this._initialized = false;
}
getMetrics() {
if (this._initialized) {
const timestamp = this._readNow();
if (timestamp !== undefined) this._sweepExpired(timestamp);
}
return {
...this._metrics,
size: this._clients.size,
maxKeys: this.maxKeys,
maxWindowMs: this.maxWindowMs,
windowMs: this.windowMs,
initialized: this._initialized,
timerActive: this._timer !== undefined,
};
}
_startSweeper() {
try {
this._timer = this._setInterval(() => {
try {
const timestamp = this._readNow();
if (timestamp !== undefined) this._sweepExpired(timestamp);
} catch {
// A scheduler callback must never become an uncaught error.
this._metrics.timerErrors += 1;
}
}, this.sweepIntervalMs);
if (typeof this._timer?.unref === 'function') this._timer.unref();
} catch (error) {
this._timer = undefined;
this._initialized = false;
throw error;
}
}
_readClient(key, timestamp) {
const client = this._clients.get(key);
if (!client) return undefined;
if (client.expiresAt <= timestamp) {
this._clients.delete(key);
this._metrics.expired += 1;
return undefined;
}
return client;
}
_sweepExpired(timestamp) {
this._metrics.sweeps += 1;
for (const [key, client] of this._clients) {
if (client.expiresAt > timestamp) continue;
this._clients.delete(key);
this._metrics.expired += 1;
}
}
_readNow() {
try {
const timestamp = this._now();
if (Number.isSafeInteger(timestamp) && timestamp >= 0 && timestamp <= 8_640_000_000_000_000 - this.maxWindowMs) {
return timestamp;
}
} catch {
// Converted below into a fail-closed increment result.
}
this._metrics.clockErrors += 1;
return undefined;
}
_isValidKey(key) {
return typeof key === 'string' && key.length > 0 && key.length <= this.maxKeyLength;
}
_failClosed(timestamp) {
const fallback = Number.isSafeInteger(timestamp) && timestamp >= 0 ? timestamp : safeWallClock();
const ttl = this.windowMs || this.maxWindowMs;
return { totalHits: FAIL_CLOSED_HITS, resetTime: new Date(fallback + ttl) };
}
}
function responseFor(client) {
return { totalHits: client.totalHits, resetTime: new Date(client.expiresAt) };
}
function safeWallClock() {
const timestamp = Date.now();
return Number.isSafeInteger(timestamp) && timestamp >= 0 ? timestamp : 0;
}
function requirePositiveInteger(value, name) {
if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${name} must be a positive integer`);
return value;
}
function requireTimerDuration(value, name) {
const duration = requirePositiveInteger(value, name);
if (duration > MAX_TIMER_MS) throw new RangeError(`${name} must not exceed ${MAX_TIMER_MS}`);
return duration;
}
module.exports = {
BoundedRateLimitStore,
DEFAULT_MAX_KEYS,
DEFAULT_MAX_WINDOW_MS,
DEFAULT_MAX_KEY_LENGTH,
DEFAULT_SWEEP_INTERVAL_MS,
FAIL_CLOSED_HITS,
};