@geekmidas/rate-limit 0.1.0 → 0.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.
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +4 -3
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +23 -7
- package/src/__benchmarks__/rateLimit.bench.ts +109 -0
- package/src/__tests__/rate-limit.spec.ts +314 -314
- package/src/index.ts +209 -209
- package/tsconfig.json +9 -0
package/src/index.ts
CHANGED
|
@@ -6,285 +6,285 @@ import type { Service, ServiceRecord } from '@geekmidas/services';
|
|
|
6
6
|
* Error thrown when rate limit is exceeded
|
|
7
7
|
*/
|
|
8
8
|
export class TooManyRequestsError extends Error {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
9
|
+
public readonly statusCode = 429;
|
|
10
|
+
public readonly retryAfter?: number;
|
|
11
|
+
|
|
12
|
+
constructor(message?: string, retryAfter?: number) {
|
|
13
|
+
super(message || 'Too many requests, please try again later.');
|
|
14
|
+
this.name = 'TooManyRequestsError';
|
|
15
|
+
this.retryAfter = retryAfter;
|
|
16
|
+
}
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Rate limit configuration for an endpoint
|
|
21
21
|
*/
|
|
22
|
-
export interface RateLimitConfig
|
|
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
|
-
|
|
22
|
+
export interface RateLimitConfig {
|
|
23
|
+
/**
|
|
24
|
+
* Maximum number of requests allowed in the window
|
|
25
|
+
*/
|
|
26
|
+
limit: number;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Time window in milliseconds
|
|
30
|
+
*/
|
|
31
|
+
windowMs: number;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Cache instance to store rate limit data
|
|
35
|
+
*/
|
|
36
|
+
cache: Cache;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Key generator function to identify clients
|
|
40
|
+
* Defaults to using IP address
|
|
41
|
+
*/
|
|
42
|
+
keyGenerator?: RateLimitKeyGenerator;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Skip rate limiting for certain requests
|
|
46
|
+
*/
|
|
47
|
+
skip?: RateLimitSkipFn;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Optional message to return when rate limit is exceeded
|
|
51
|
+
*/
|
|
52
|
+
message?: string;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Optional custom handler when rate limit is exceeded
|
|
56
|
+
*/
|
|
57
|
+
handler?: RateLimitExceededHandler;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Whether to include rate limit headers in response
|
|
61
|
+
* @default true
|
|
62
|
+
*/
|
|
63
|
+
standardHeaders?: boolean;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Whether to include legacy rate limit headers
|
|
67
|
+
* @default false
|
|
68
|
+
*/
|
|
69
|
+
legacyHeaders?: boolean;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
/**
|
|
73
73
|
* Context for rate limiting decisions
|
|
74
74
|
*/
|
|
75
75
|
export interface RateLimitContext<
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
TServices extends Service[] = [],
|
|
77
|
+
TLogger extends Logger = Logger,
|
|
78
|
+
TSession = unknown,
|
|
79
79
|
> {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
80
|
+
header: (key: string) => string | undefined;
|
|
81
|
+
services: ServiceRecord<TServices>;
|
|
82
|
+
logger: TLogger;
|
|
83
|
+
session: TSession;
|
|
84
|
+
path: string;
|
|
85
|
+
method: string;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
88
|
/**
|
|
89
89
|
* Function to generate a unique key for rate limiting
|
|
90
90
|
*/
|
|
91
91
|
export type RateLimitKeyGenerator<
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
92
|
+
TServices extends Service[] = [],
|
|
93
|
+
TLogger extends Logger = Logger,
|
|
94
|
+
TSession = unknown,
|
|
95
95
|
> = (
|
|
96
|
-
|
|
96
|
+
ctx: RateLimitContext<TServices, TLogger, TSession>,
|
|
97
97
|
) => string | Promise<string>;
|
|
98
98
|
|
|
99
99
|
/**
|
|
100
100
|
* Function to determine if rate limiting should be skipped
|
|
101
101
|
*/
|
|
102
102
|
export type RateLimitSkipFn<
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
103
|
+
TServices extends Service[] = [],
|
|
104
|
+
TLogger extends Logger = Logger,
|
|
105
|
+
TSession = unknown,
|
|
106
106
|
> = (
|
|
107
|
-
|
|
107
|
+
ctx: RateLimitContext<TServices, TLogger, TSession>,
|
|
108
108
|
) => boolean | Promise<boolean>;
|
|
109
109
|
|
|
110
110
|
/**
|
|
111
111
|
* Handler for when rate limit is exceeded
|
|
112
112
|
*/
|
|
113
113
|
export type RateLimitExceededHandler<
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
114
|
+
TServices extends Service[] = [],
|
|
115
|
+
TLogger extends Logger = Logger,
|
|
116
|
+
TSession = unknown,
|
|
117
117
|
> = (
|
|
118
|
-
|
|
119
|
-
|
|
118
|
+
ctx: RateLimitContext<TServices, TLogger, TSession>,
|
|
119
|
+
info: RateLimitInfo,
|
|
120
120
|
) => void | Promise<void>;
|
|
121
121
|
|
|
122
122
|
/**
|
|
123
123
|
* Information about current rate limit status
|
|
124
124
|
*/
|
|
125
125
|
export interface RateLimitInfo {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
126
|
+
/**
|
|
127
|
+
* Current request count in the window
|
|
128
|
+
*/
|
|
129
|
+
count: number;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Maximum allowed requests
|
|
133
|
+
*/
|
|
134
|
+
limit: number;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Remaining requests allowed
|
|
138
|
+
*/
|
|
139
|
+
remaining: number;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Time when the window resets (Unix timestamp)
|
|
143
|
+
*/
|
|
144
|
+
resetTime: number;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Time until reset in milliseconds
|
|
148
|
+
*/
|
|
149
|
+
retryAfter: number;
|
|
150
150
|
}
|
|
151
151
|
|
|
152
152
|
/**
|
|
153
153
|
* Headers to be set on responses
|
|
154
154
|
*/
|
|
155
155
|
export interface RateLimitHeaders {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
156
|
+
'X-RateLimit-Limit'?: string;
|
|
157
|
+
'X-RateLimit-Remaining'?: string;
|
|
158
|
+
'X-RateLimit-Reset'?: string;
|
|
159
|
+
'Retry-After'?: string;
|
|
160
|
+
'X-RateLimit-Retry-After'?: string;
|
|
161
|
+
'X-RateLimit-Reset-After'?: string;
|
|
162
162
|
}
|
|
163
163
|
|
|
164
164
|
/**
|
|
165
165
|
* Data stored in cache for rate limiting
|
|
166
166
|
*/
|
|
167
167
|
export interface RateLimitData {
|
|
168
|
-
|
|
169
|
-
|
|
168
|
+
count: number;
|
|
169
|
+
resetTime: number;
|
|
170
170
|
}
|
|
171
171
|
|
|
172
172
|
/**
|
|
173
173
|
* Default key generator using IP address
|
|
174
174
|
*/
|
|
175
175
|
export const defaultKeyGenerator: RateLimitKeyGenerator = (ctx) => {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
176
|
+
// Try various headers for IP address
|
|
177
|
+
const ip =
|
|
178
|
+
ctx.header('x-forwarded-for')?.split(',')[0]?.trim() ||
|
|
179
|
+
ctx.header('x-real-ip') ||
|
|
180
|
+
ctx.header('x-client-ip') ||
|
|
181
|
+
ctx.header('cf-connecting-ip') ||
|
|
182
|
+
'unknown';
|
|
183
|
+
|
|
184
|
+
return `rate-limit:${ctx.method}:${ctx.path}:${ip}`;
|
|
185
185
|
};
|
|
186
186
|
|
|
187
187
|
/**
|
|
188
188
|
* Check rate limit and throw error if exceeded
|
|
189
189
|
*/
|
|
190
190
|
export async function checkRateLimit<
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
191
|
+
TServices extends Service[] = [],
|
|
192
|
+
TLogger extends Logger = Logger,
|
|
193
|
+
TSession = unknown,
|
|
194
194
|
>(
|
|
195
|
-
|
|
196
|
-
|
|
195
|
+
config: RateLimitConfig,
|
|
196
|
+
ctx: RateLimitContext<TServices, TLogger, TSession>,
|
|
197
197
|
): Promise<RateLimitInfo> {
|
|
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
|
-
|
|
198
|
+
// Check if we should skip rate limiting
|
|
199
|
+
if (config.skip && (await config.skip(ctx))) {
|
|
200
|
+
return {
|
|
201
|
+
count: 0,
|
|
202
|
+
limit: config.limit,
|
|
203
|
+
remaining: config.limit,
|
|
204
|
+
resetTime: Date.now() + config.windowMs,
|
|
205
|
+
retryAfter: config.windowMs,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Generate key for this request
|
|
210
|
+
const keyGenerator = config.keyGenerator || defaultKeyGenerator;
|
|
211
|
+
const key = await keyGenerator(ctx);
|
|
212
|
+
|
|
213
|
+
// Get current data from cache
|
|
214
|
+
const now = Date.now();
|
|
215
|
+
let data = await config.cache.get<RateLimitData>(key);
|
|
216
|
+
|
|
217
|
+
// If no data or window expired, create new entry
|
|
218
|
+
if (!data || data.resetTime <= now) {
|
|
219
|
+
const resetTime = now + config.windowMs;
|
|
220
|
+
data = { count: 1, resetTime };
|
|
221
|
+
|
|
222
|
+
// Store with TTL matching the window
|
|
223
|
+
const ttlSeconds = Math.ceil(config.windowMs / 1000);
|
|
224
|
+
await config.cache.set(key, data, ttlSeconds);
|
|
225
|
+
} else {
|
|
226
|
+
// Increment count
|
|
227
|
+
data.count++;
|
|
228
|
+
|
|
229
|
+
// Calculate remaining TTL
|
|
230
|
+
const remainingMs = data.resetTime - now;
|
|
231
|
+
const ttlSeconds = Math.ceil(remainingMs / 1000);
|
|
232
|
+
await config.cache.set(key, data, ttlSeconds);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Calculate rate limit info
|
|
236
|
+
const info: RateLimitInfo = {
|
|
237
|
+
count: data.count,
|
|
238
|
+
limit: config.limit,
|
|
239
|
+
remaining: Math.max(0, config.limit - data.count),
|
|
240
|
+
resetTime: data.resetTime,
|
|
241
|
+
retryAfter: data.resetTime - now,
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// Check if limit exceeded
|
|
245
|
+
if (data.count > config.limit) {
|
|
246
|
+
// Call custom handler if provided
|
|
247
|
+
if (config.handler) {
|
|
248
|
+
await config.handler(ctx, info);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Throw rate limit error
|
|
252
|
+
const retryAfterSeconds = Math.ceil(info.retryAfter / 1000);
|
|
253
|
+
throw new TooManyRequestsError(
|
|
254
|
+
config.message || 'Too many requests, please try again later.',
|
|
255
|
+
retryAfterSeconds,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return info;
|
|
260
260
|
}
|
|
261
261
|
|
|
262
262
|
/**
|
|
263
263
|
* Generate rate limit headers
|
|
264
264
|
*/
|
|
265
265
|
export function getRateLimitHeaders(
|
|
266
|
-
|
|
267
|
-
|
|
266
|
+
info: RateLimitInfo,
|
|
267
|
+
config: RateLimitConfig,
|
|
268
268
|
): RateLimitHeaders {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
269
|
+
const headers: RateLimitHeaders = {};
|
|
270
|
+
|
|
271
|
+
if (config.standardHeaders !== false) {
|
|
272
|
+
headers['X-RateLimit-Limit'] = info.limit.toString();
|
|
273
|
+
headers['X-RateLimit-Remaining'] = info.remaining.toString();
|
|
274
|
+
headers['X-RateLimit-Reset'] = new Date(info.resetTime).toISOString();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (config.legacyHeaders) {
|
|
278
|
+
headers['X-RateLimit-Retry-After'] = info.retryAfter.toString();
|
|
279
|
+
headers['X-RateLimit-Reset-After'] = Math.ceil(
|
|
280
|
+
info.retryAfter / 1000,
|
|
281
|
+
).toString();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Always set Retry-After when limit is exceeded
|
|
285
|
+
if (info.remaining === 0) {
|
|
286
|
+
headers['Retry-After'] = Math.ceil(info.retryAfter / 1000).toString();
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return headers;
|
|
290
290
|
}
|