express-rate-limit 6.0.0 → 6.0.4

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.
@@ -1,239 +0,0 @@
1
- import Express from 'express';
2
- /**
3
- * Callback that fires when a client's hit counter is incremented.
4
- *
5
- * @param error {Error | undefined} - The error that occurred, if any
6
- * @param totalHits {number} - The number of hits for that client so far
7
- * @param resetTime {Date | undefined} - The time when the counter resets
8
- */
9
- export declare type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void;
10
- /**
11
- * Method (in the form of middleware) to generate/retrieve a value based on the
12
- * incoming request
13
- *
14
- * @param request {Express.Request} - The Express request object
15
- * @param response {Express.Response} - The Express response object
16
- *
17
- * @returns {T} - The value needed
18
- */
19
- export declare type ValueDeterminingMiddleware<T> = (request: Express.Request, response: Express.Response) => T | Promise<T>;
20
- /**
21
- * Express request handler that sends back a response when a client is
22
- * rate-limited.
23
- *
24
- * @param request {Express.Request} - The Express request object
25
- * @param response {Express.Response} - The Express response object
26
- * @param next {Express.NextFunction} - The Express `next` function, can be called to skip responding
27
- * @param optionsUsed {Options} - The options used to set up the middleware
28
- */
29
- export declare type RateLimitExceededEventHandler = (request: Express.Request, response: Express.Response, next: Express.NextFunction, optionsUsed: Options) => void;
30
- /**
31
- * Event callback that is triggered on a client's first request that exceeds the limit
32
- * but not for subsequent requests. May be used for logging, etc. Should *not*
33
- * send a response.
34
- *
35
- * @param request {Express.Request} - The Express request object
36
- * @param response {Express.Response} - The Express response object
37
- * @param optionsUsed {Options} - The options used to set up the middleware
38
- */
39
- export declare type RateLimitReachedEventHandler = (request: Express.Request, response: Express.Response, optionsUsed: Options) => void;
40
- /**
41
- * Data returned from the `Store` when a client's hit counter is incremented.
42
- *
43
- * @property totalHits {number} - The number of hits for that client so far
44
- * @property resetTime {Date | undefined} - The time when the counter resets
45
- */
46
- export declare type IncrementResponse = {
47
- totalHits: number;
48
- resetTime: Date | undefined;
49
- };
50
- /**
51
- * A modified Express request handler with the rate limit functions.
52
- */
53
- export declare type RateLimitRequestHandler = Express.RequestHandler & {
54
- /**
55
- * Method to reset a client's hit counter.
56
- *
57
- * @param key {string} - The identifier for a client
58
- */
59
- resetKey: (key: string) => void;
60
- };
61
- /**
62
- * An interface that all hit counter stores must implement.
63
- *
64
- * @deprecated 6.x - Implement the `Store` interface instead.
65
- */
66
- export interface LegacyStore {
67
- /**
68
- * Method to increment a client's hit counter.
69
- *
70
- * @param key {string} - The identifier for a client
71
- * @param callback {IncrementCallback} - The callback to call once the counter is incremented
72
- */
73
- incr: (key: string, callback: IncrementCallback) => void;
74
- /**
75
- * Method to decrement a client's hit counter.
76
- *
77
- * @param key {string} - The identifier for a client
78
- */
79
- decrement: (key: string) => void;
80
- /**
81
- * Method to reset a client's hit counter.
82
- *
83
- * @param key {string} - The identifier for a client
84
- */
85
- resetKey: (key: string) => void;
86
- /**
87
- * Method to reset everyone's hit counter.
88
- */
89
- resetAll?: () => void;
90
- }
91
- /**
92
- * An interface that all hit counter stores must implement.
93
- */
94
- export interface Store {
95
- /**
96
- * Method that initializes the store, and has access to the options passed to
97
- * the middleware too.
98
- *
99
- * @param options {Options} - The options used to setup the middleware
100
- */
101
- init?: (options: Options) => void;
102
- /**
103
- * Method to increment a client's hit counter.
104
- *
105
- * @param key {string} - The identifier for a client
106
- *
107
- * @returns {IncrementResponse} - The number of hits and reset time for that client
108
- */
109
- increment: (key: string) => Promise<IncrementResponse> | IncrementResponse;
110
- /**
111
- * Method to decrement a client's hit counter.
112
- *
113
- * @param key {string} - The identifier for a client
114
- */
115
- decrement: (key: string) => Promise<void> | void;
116
- /**
117
- * Method to reset a client's hit counter.
118
- *
119
- * @param key {string} - The identifier for a client
120
- */
121
- resetKey: (key: string) => Promise<void> | void;
122
- /**
123
- * Method to reset everyone's hit counter.
124
- */
125
- resetAll?: () => Promise<void> | void;
126
- }
127
- /**
128
- * The configuration options for the rate limiter.
129
- */
130
- export interface Options {
131
- /**
132
- * How long we should remember the requests.
133
- */
134
- readonly windowMs: number;
135
- /**
136
- * The maximum number of connection to allow during the `window` before
137
- * rate limiting the client.
138
- *
139
- * Can be the limit itself as a number or express middleware that parses
140
- * the request and then figures out the limit.
141
- */
142
- readonly max: number | ValueDeterminingMiddleware<number>;
143
- /**
144
- * The response body to send back when a client is rate limited.
145
- */
146
- readonly message: any;
147
- /**
148
- * The HTTP status code to send back when a client is rate limited.
149
- *
150
- * Defaults to `HTTP 429 Too Many Requests` (RFC 6585).
151
- */
152
- readonly statusCode: number;
153
- /**
154
- * Whether to send `X-RateLimit-*` headers with the rate limit and the number
155
- * of requests.
156
- */
157
- readonly legacyHeaders: boolean;
158
- /**
159
- * Whether to enable support for the rate limit standardization headers (`RateLimit-*`).
160
- */
161
- readonly standardHeaders: boolean;
162
- /**
163
- * The name of the property on the request object to store the rate limit info.
164
- *
165
- * Defaults to `rateLimit`.
166
- */
167
- readonly requestPropertyName: string;
168
- /**
169
- * If `true`, the library will (by default) skip all requests that have a 4XX
170
- * or 5XX status.
171
- */
172
- readonly skipFailedRequests: boolean;
173
- /**
174
- * If `true`, the library will (by default) skip all requests that have a
175
- * status code less than 400.
176
- */
177
- readonly skipSuccessfulRequests: boolean;
178
- /**
179
- * Method to determine whether or not the request counts as 'succesful'. Used
180
- * when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true.
181
- */
182
- readonly requestWasSuccessful: ValueDeterminingMiddleware<boolean>;
183
- /**
184
- * Method to generate custom identifiers for clients.
185
- *
186
- * By default, the client's IP address is used.
187
- */
188
- readonly keyGenerator: ValueDeterminingMiddleware<string>;
189
- /**
190
- * Method (in the form of middleware) to determine whether or not this request
191
- * counts towards a client's quota.
192
- */
193
- readonly skip: ValueDeterminingMiddleware<boolean>;
194
- /**
195
- * Express request handler that sends back a response when a client is
196
- * rate-limited.
197
- */
198
- readonly handler: RateLimitExceededEventHandler;
199
- /**
200
- * Express request handler that sends back a response when a client has
201
- * reached their rate limit, and will be rate limited on their next request.
202
- */
203
- readonly onLimitReached: RateLimitReachedEventHandler;
204
- /**
205
- * The {@link Store} to use to store the hit count for each client.
206
- */
207
- store: Store;
208
- /**
209
- * Whether to send `X-RateLimit-*` headers with the rate limit and the number
210
- * of requests.
211
- *
212
- * @deprecated 6.x - This option was renamed to `legacyHeaders`.
213
- */
214
- headers?: boolean;
215
- /**
216
- * Whether to send `RateLimit-*` headers with the rate limit and the number
217
- * of requests.
218
- *
219
- * @deprecated 6.x - This option was renamed to `standardHeaders`.
220
- */
221
- draft_polli_ratelimit_headers?: boolean;
222
- }
223
- /**
224
- * The extended request object that includes information about the client's
225
- * rate limit.
226
- */
227
- export declare type AugmentedRequest = Express.Request & {
228
- [key: string]: RateLimitInfo;
229
- };
230
- /**
231
- * The rate limit related information for each client included in the
232
- * Express request object.
233
- */
234
- export interface RateLimitInfo {
235
- readonly limit: number;
236
- readonly current: number;
237
- readonly remaining: number;
238
- readonly resetTime: Date | undefined;
239
- }
package/dist/cjs/types.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
- // /source/types.ts
3
- // All the types used by this package
4
- exports.__esModule = true;
5
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../source/types.ts"],"names":[],"mappings":";AAAA,mBAAmB;AACnB,qCAAqC","sourcesContent":["// /source/types.ts\n// All the types used by this package\n\nimport Express from 'express'\n\n/**\n * Callback that fires when a client's hit counter is incremented.\n *\n * @param error {Error | undefined} - The error that occurred, if any\n * @param totalHits {number} - The number of hits for that client so far\n * @param resetTime {Date | undefined} - The time when the counter resets\n */\nexport type IncrementCallback = (\n\terror: Error | undefined,\n\ttotalHits: number,\n\tresetTime: Date | undefined,\n) => void\n\n/**\n * Method (in the form of middleware) to generate/retrieve a value based on the\n * incoming request\n *\n * @param request {Express.Request} - The Express request object\n * @param response {Express.Response} - The Express response object\n *\n * @returns {T} - The value needed\n */\nexport type ValueDeterminingMiddleware<T> = (\n\trequest: Express.Request,\n\tresponse: Express.Response,\n) => T | Promise<T>\n\n/**\n * Express request handler that sends back a response when a client is\n * rate-limited.\n *\n * @param request {Express.Request} - The Express request object\n * @param response {Express.Response} - The Express response object\n * @param next {Express.NextFunction} - The Express `next` function, can be called to skip responding\n * @param optionsUsed {Options} - The options used to set up the middleware\n */\nexport type RateLimitExceededEventHandler = (\n\trequest: Express.Request,\n\tresponse: Express.Response,\n\tnext: Express.NextFunction,\n\toptionsUsed: Options,\n) => void\n\n/**\n * Event callback that is triggered on a client's first request that exceeds the limit\n * but not for subsequent requests. May be used for logging, etc. Should *not*\n * send a response.\n *\n * @param request {Express.Request} - The Express request object\n * @param response {Express.Response} - The Express response object\n * @param optionsUsed {Options} - The options used to set up the middleware\n */\nexport type RateLimitReachedEventHandler = (\n\trequest: Express.Request,\n\tresponse: Express.Response,\n\toptionsUsed: Options,\n) => void\n\n/**\n * Data returned from the `Store` when a client's hit counter is incremented.\n *\n * @property totalHits {number} - The number of hits for that client so far\n * @property resetTime {Date | undefined} - The time when the counter resets\n */\nexport type IncrementResponse = {\n\ttotalHits: number\n\tresetTime: Date | undefined\n}\n\n/**\n * A modified Express request handler with the rate limit functions.\n */\nexport type RateLimitRequestHandler = Express.RequestHandler & {\n\t/**\n\t * Method to reset a client's hit counter.\n\t *\n\t * @param key {string} - The identifier for a client\n\t */\n\tresetKey: (key: string) => void\n}\n\n/**\n * An interface that all hit counter stores must implement.\n *\n * @deprecated 6.x - Implement the `Store` interface instead.\n */\nexport interface LegacyStore {\n\t/**\n\t * Method to increment a client's hit counter.\n\t *\n\t * @param key {string} - The identifier for a client\n\t * @param callback {IncrementCallback} - The callback to call once the counter is incremented\n\t */\n\tincr: (key: string, callback: IncrementCallback) => void\n\n\t/**\n\t * Method to decrement a client's hit counter.\n\t *\n\t * @param key {string} - The identifier for a client\n\t */\n\tdecrement: (key: string) => void\n\n\t/**\n\t * Method to reset a client's hit counter.\n\t *\n\t * @param key {string} - The identifier for a client\n\t */\n\tresetKey: (key: string) => void\n\n\t/**\n\t * Method to reset everyone's hit counter.\n\t */\n\tresetAll?: () => void\n}\n\n/**\n * An interface that all hit counter stores must implement.\n */\nexport interface Store {\n\t/**\n\t * Method that initializes the store, and has access to the options passed to\n\t * the middleware too.\n\t *\n\t * @param options {Options} - The options used to setup the middleware\n\t */\n\tinit?: (options: Options) => void\n\n\t/**\n\t * Method to increment a client's hit counter.\n\t *\n\t * @param key {string} - The identifier for a client\n\t *\n\t * @returns {IncrementResponse} - The number of hits and reset time for that client\n\t */\n\tincrement: (key: string) => Promise<IncrementResponse> | IncrementResponse\n\n\t/**\n\t * Method to decrement a client's hit counter.\n\t *\n\t * @param key {string} - The identifier for a client\n\t */\n\tdecrement: (key: string) => Promise<void> | void\n\n\t/**\n\t * Method to reset a client's hit counter.\n\t *\n\t * @param key {string} - The identifier for a client\n\t */\n\tresetKey: (key: string) => Promise<void> | void\n\n\t/**\n\t * Method to reset everyone's hit counter.\n\t */\n\tresetAll?: () => Promise<void> | void\n}\n\n/**\n * The configuration options for the rate limiter.\n */\nexport interface Options {\n\t/**\n\t * How long we should remember the requests.\n\t */\n\treadonly windowMs: number\n\n\t/**\n\t * The maximum number of connection to allow during the `window` before\n\t * rate limiting the client.\n\t *\n\t * Can be the limit itself as a number or express middleware that parses\n\t * the request and then figures out the limit.\n\t */\n\treadonly max: number | ValueDeterminingMiddleware<number>\n\n\t/**\n\t * The response body to send back when a client is rate limited.\n\t */\n\treadonly message: any\n\n\t/**\n\t * The HTTP status code to send back when a client is rate limited.\n\t *\n\t * Defaults to `HTTP 429 Too Many Requests` (RFC 6585).\n\t */\n\treadonly statusCode: number\n\n\t/**\n\t * Whether to send `X-RateLimit-*` headers with the rate limit and the number\n\t * of requests.\n\t */\n\treadonly legacyHeaders: boolean\n\n\t/**\n\t * Whether to enable support for the rate limit standardization headers (`RateLimit-*`).\n\t */\n\treadonly standardHeaders: boolean\n\n\t/**\n\t * The name of the property on the request object to store the rate limit info.\n\t *\n\t * Defaults to `rateLimit`.\n\t */\n\treadonly requestPropertyName: string\n\n\t/**\n\t * If `true`, the library will (by default) skip all requests that have a 4XX\n\t * or 5XX status.\n\t */\n\treadonly skipFailedRequests: boolean\n\n\t/**\n\t * If `true`, the library will (by default) skip all requests that have a\n\t * status code less than 400.\n\t */\n\treadonly skipSuccessfulRequests: boolean\n\n\t/**\n\t * Method to determine whether or not the request counts as 'succesful'. Used\n\t * when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true.\n\t */\n\treadonly requestWasSuccessful: ValueDeterminingMiddleware<boolean>\n\n\t/**\n\t * Method to generate custom identifiers for clients.\n\t *\n\t * By default, the client's IP address is used.\n\t */\n\treadonly keyGenerator: ValueDeterminingMiddleware<string>\n\n\t/**\n\t * Method (in the form of middleware) to determine whether or not this request\n\t * counts towards a client's quota.\n\t */\n\treadonly skip: ValueDeterminingMiddleware<boolean>\n\n\t/**\n\t * Express request handler that sends back a response when a client is\n\t * rate-limited.\n\t */\n\treadonly handler: RateLimitExceededEventHandler\n\n\t/**\n\t * Express request handler that sends back a response when a client has\n\t * reached their rate limit, and will be rate limited on their next request.\n\t */\n\treadonly onLimitReached: RateLimitReachedEventHandler\n\n\t/**\n\t * The {@link Store} to use to store the hit count for each client.\n\t */\n\tstore: Store\n\n\t/**\n\t * Whether to send `X-RateLimit-*` headers with the rate limit and the number\n\t * of requests.\n\t *\n\t * @deprecated 6.x - This option was renamed to `legacyHeaders`.\n\t */\n\theaders?: boolean\n\n\t/**\n\t * Whether to send `RateLimit-*` headers with the rate limit and the number\n\t * of requests.\n\t *\n\t * @deprecated 6.x - This option was renamed to `standardHeaders`.\n\t */\n\tdraft_polli_ratelimit_headers?: boolean\n}\n\n/**\n * The extended request object that includes information about the client's\n * rate limit.\n */\nexport type AugmentedRequest = Express.Request & {\n\t[key: string]: RateLimitInfo\n}\n\n/**\n * The rate limit related information for each client included in the\n * Express request object.\n */\nexport interface RateLimitInfo {\n\treadonly limit: number\n\treadonly current: number\n\treadonly remaining: number\n\treadonly resetTime: Date | undefined\n}\n"]}
@@ -1,2 +0,0 @@
1
- export * from './types.js';
2
- export { default } from './lib.js';
package/dist/esm/index.js DELETED
@@ -1,5 +0,0 @@
1
- // /source/index.ts
2
- // Export away!
3
- export * from './types.js';
4
- export { default } from './lib.js';
5
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/index.ts"],"names":[],"mappings":"AAAA,mBAAmB;AACnB,eAAe;AAEf,cAAc,YAAY,CAAA;AAC1B,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAA","sourcesContent":["// /source/index.ts\n// Export away!\n\nexport * from './types.js'\nexport { default } from './lib.js'\n"]}
package/dist/esm/lib.d.ts DELETED
@@ -1,15 +0,0 @@
1
- import { Options, RateLimitRequestHandler, LegacyStore, Store } from './types.js';
2
- /**
3
- *
4
- * Create an instance of IP rate-limiting middleware for Express.
5
- *
6
- * @param passedOptions {Options} - Options to configure the rate limiter
7
- *
8
- * @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration
9
- *
10
- * @public
11
- */
12
- declare const rateLimit: (passedOptions?: (Omit<Partial<Options>, "store"> & {
13
- store?: LegacyStore | Store | undefined;
14
- }) | undefined) => RateLimitRequestHandler;
15
- export default rateLimit;
package/dist/esm/lib.js DELETED
@@ -1,361 +0,0 @@
1
- // /source/lib.ts
2
- // The option parser and rate limiting middleware
3
- var __assign = (this && this.__assign) || function () {
4
- __assign = Object.assign || function(t) {
5
- for (var s, i = 1, n = arguments.length; i < n; i++) {
6
- s = arguments[i];
7
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8
- t[p] = s[p];
9
- }
10
- return t;
11
- };
12
- return __assign.apply(this, arguments);
13
- };
14
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
15
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
16
- return new (P || (P = Promise))(function (resolve, reject) {
17
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
20
- step((generator = generator.apply(thisArg, _arguments || [])).next());
21
- });
22
- };
23
- var __generator = (this && this.__generator) || function (thisArg, body) {
24
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
25
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
26
- function verb(n) { return function (v) { return step([n, v]); }; }
27
- function step(op) {
28
- if (f) throw new TypeError("Generator is already executing.");
29
- while (_) try {
30
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
31
- if (y = 0, t) op = [op[0] & 2, t.value];
32
- switch (op[0]) {
33
- case 0: case 1: t = op; break;
34
- case 4: _.label++; return { value: op[1], done: false };
35
- case 5: _.label++; y = op[1]; op = [0]; continue;
36
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
37
- default:
38
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
39
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
40
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
41
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
42
- if (t[2]) _.ops.pop();
43
- _.trys.pop(); continue;
44
- }
45
- op = body.call(thisArg, _);
46
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
47
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
48
- }
49
- };
50
- import MemoryStore from './memory-store.js';
51
- /**
52
- * Type guard to check if a store is legacy store.
53
- *
54
- * @param store {LegacyStore | Store} - The store to check
55
- *
56
- * @return {boolean} - Whether the store is a legacy store
57
- */
58
- var isLegacyStore = function (store) {
59
- // Check that `incr` exists but `increment` does not - store authors might want
60
- // to keep both around for backwards compatibility.
61
- return typeof store.incr === 'function' &&
62
- typeof store.increment !== 'function';
63
- };
64
- /**
65
- * Converts a legacy store to the promisified version.
66
- *
67
- * @param store {LegacyStore | Store} - The legacy store or even a modern store
68
- *
69
- * @returns {Store} - The promisified version of the store
70
- */
71
- var promisifyStore = function (passedStore) {
72
- if (!isLegacyStore(passedStore)) {
73
- // It's not an old store, return as is
74
- return passedStore;
75
- }
76
- // Why can't Typescript understand this?
77
- var legacyStore = passedStore;
78
- // A promisified version of the store
79
- var PromisifiedStore = /** @class */ (function () {
80
- function PromisifiedStore() {
81
- }
82
- PromisifiedStore.prototype.increment = function (key) {
83
- return __awaiter(this, void 0, void 0, function () {
84
- return __generator(this, function (_a) {
85
- return [2 /*return*/, new Promise(function (resolve, reject) {
86
- legacyStore.incr(key, function (error, totalHits, resetTime) {
87
- if (error)
88
- reject(error);
89
- resolve({ totalHits: totalHits, resetTime: resetTime });
90
- });
91
- })];
92
- });
93
- });
94
- };
95
- PromisifiedStore.prototype.decrement = function (key) {
96
- return __awaiter(this, void 0, void 0, function () {
97
- return __generator(this, function (_a) {
98
- return [2 /*return*/, Promise.resolve(legacyStore.decrement(key))];
99
- });
100
- });
101
- };
102
- PromisifiedStore.prototype.resetKey = function (key) {
103
- return __awaiter(this, void 0, void 0, function () {
104
- return __generator(this, function (_a) {
105
- return [2 /*return*/, Promise.resolve(legacyStore.resetKey(key))];
106
- });
107
- });
108
- };
109
- PromisifiedStore.prototype.resetAll = function () {
110
- return __awaiter(this, void 0, void 0, function () {
111
- return __generator(this, function (_a) {
112
- if (typeof legacyStore.resetAll === 'function')
113
- return [2 /*return*/, Promise.resolve(legacyStore.resetAll())];
114
- return [2 /*return*/];
115
- });
116
- });
117
- };
118
- return PromisifiedStore;
119
- }());
120
- return new PromisifiedStore();
121
- };
122
- /**
123
- * Adds the defaults for options the user has not specified.
124
- *
125
- * @param options {Options} - The options the user specifies
126
- *
127
- * @returns {Options} - A complete configuration object
128
- */
129
- var parseOptions = function (passedOptions) {
130
- // Now add the defaults for the other options
131
- var _a, _b;
132
- var options = __assign({ windowMs: 60 * 1000, store: new MemoryStore(), max: 5, message: 'Too many requests, please try again later.', statusCode: 429, legacyHeaders: (_a = passedOptions.headers) !== null && _a !== void 0 ? _a : true, standardHeaders: (_b = passedOptions.draft_polli_ratelimit_headers) !== null && _b !== void 0 ? _b : false, requestPropertyName: 'rateLimit', skipFailedRequests: false, skipSuccessfulRequests: false, requestWasSuccessful: function (_request, response) { return response.statusCode < 400; }, skip: function (_request, _response) {
133
- return false;
134
- }, keyGenerator: function (request, _response) {
135
- if (!request.ip) {
136
- console.error('WARN | `express-rate-limit` | `request.ip` is undefined. You can avoid this by providing a custom `keyGenerator` function, but it may be indicative of a larger issue.');
137
- }
138
- return request.ip;
139
- }, handler: function (_request, response, _next, _optionsUsed) {
140
- response.status(options.statusCode).send(options.message);
141
- }, onLimitReached: function (_request, _response, _optionsUsed) { } }, passedOptions);
142
- // Ensure that the store passed implements the either the `Store` or `LegacyStore`
143
- // interface
144
- if ((typeof options.store.incr !== 'function' &&
145
- typeof options.store.increment !== 'function') ||
146
- typeof options.store.decrement !== 'function' ||
147
- typeof options.store.resetKey !== 'function' ||
148
- (typeof options.store.resetAll !== 'undefined' &&
149
- typeof options.store.resetAll !== 'function') ||
150
- (typeof options.store.init !== 'undefined' &&
151
- typeof options.store.init !== 'function')) {
152
- throw new TypeError('An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface.');
153
- }
154
- // Promisify the store, if it is not already
155
- options.store = promisifyStore(options.store);
156
- // Return the 'clean' options
157
- return options;
158
- };
159
- /**
160
- * Just pass on any errors for the developer to handle, usually as a HTTP 500
161
- * Internal Server Error.
162
- *
163
- * @param fn {Express.RequestHandler} - The request handler for which to handle errors
164
- *
165
- * @returns {Express.RequestHandler} - The request handler wrapped with a `.catch` clause
166
- *
167
- * @private
168
- */
169
- var handleAsyncErrors = function (fn) {
170
- return function (request, response, next) { return __awaiter(void 0, void 0, void 0, function () {
171
- var error_1;
172
- return __generator(this, function (_a) {
173
- switch (_a.label) {
174
- case 0:
175
- _a.trys.push([0, 2, , 3]);
176
- return [4 /*yield*/, Promise.resolve(fn(request, response, next))["catch"](next)];
177
- case 1:
178
- _a.sent();
179
- return [3 /*break*/, 3];
180
- case 2:
181
- error_1 = _a.sent();
182
- next(error_1);
183
- return [3 /*break*/, 3];
184
- case 3: return [2 /*return*/];
185
- }
186
- });
187
- }); };
188
- };
189
- /**
190
- *
191
- * Create an instance of IP rate-limiting middleware for Express.
192
- *
193
- * @param passedOptions {Options} - Options to configure the rate limiter
194
- *
195
- * @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration
196
- *
197
- * @public
198
- */
199
- var rateLimit = function (passedOptions) {
200
- // Parse the options and add the default values for unspecified options
201
- var options = parseOptions(passedOptions !== null && passedOptions !== void 0 ? passedOptions : {});
202
- // Call the `init` method on the store, if it exists
203
- if (typeof options.store.init === 'function')
204
- options.store.init(options);
205
- // Then return the actual middleware
206
- var middleware = handleAsyncErrors(function (request, response, next) { return __awaiter(void 0, void 0, void 0, function () {
207
- var skip, augmentedRequest, key, _a, totalHits, resetTime, retrieveQuota, maxHits, deltaSeconds, decremented_1, decrementKey_1;
208
- return __generator(this, function (_b) {
209
- switch (_b.label) {
210
- case 0: return [4 /*yield*/, options.skip(request, response)];
211
- case 1:
212
- skip = _b.sent();
213
- if (skip) {
214
- next();
215
- return [2 /*return*/];
216
- }
217
- augmentedRequest = request;
218
- return [4 /*yield*/, options.keyGenerator(request, response)
219
- // Increment the client's hit counter by one
220
- ];
221
- case 2:
222
- key = _b.sent();
223
- return [4 /*yield*/, options.store.increment(key)
224
- // Get the quota (max number of hits) for each client
225
- ];
226
- case 3:
227
- _a = _b.sent(), totalHits = _a.totalHits, resetTime = _a.resetTime;
228
- retrieveQuota = typeof options.max === 'function'
229
- ? options.max(request, response)
230
- : options.max;
231
- return [4 /*yield*/, retrieveQuota
232
- // Set the rate limit information on the augmented request object
233
- ];
234
- case 4:
235
- maxHits = _b.sent();
236
- // Set the rate limit information on the augmented request object
237
- augmentedRequest[options.requestPropertyName] = {
238
- limit: maxHits,
239
- current: totalHits,
240
- remaining: Math.max(maxHits - totalHits, 0),
241
- resetTime: resetTime
242
- };
243
- // Set the X-RateLimit headers on the response object if enabled
244
- if (options.legacyHeaders && !response.headersSent) {
245
- response.setHeader('X-RateLimit-Limit', maxHits);
246
- response.setHeader('X-RateLimit-Remaining', augmentedRequest[options.requestPropertyName].remaining);
247
- // If we have a resetTime, also provide the current date to help avoid issues with incorrect clocks
248
- if (resetTime instanceof Date) {
249
- response.setHeader('Date', new Date().toUTCString());
250
- response.setHeader('X-RateLimit-Reset', Math.ceil(resetTime.getTime() / 1000));
251
- }
252
- }
253
- // Set the standardized RateLimit headers on the response object
254
- // if enabled
255
- if (options.standardHeaders && !response.headersSent) {
256
- response.setHeader('RateLimit-Limit', maxHits);
257
- response.setHeader('RateLimit-Remaining', augmentedRequest[options.requestPropertyName].remaining);
258
- if (resetTime) {
259
- deltaSeconds = Math.ceil((resetTime.getTime() - Date.now()) / 1000);
260
- response.setHeader('RateLimit-Reset', Math.max(0, deltaSeconds));
261
- }
262
- }
263
- // If we are to skip failed/successfull requests, decrement the
264
- // counter accordingly once we know the status code of the request
265
- if (options.skipFailedRequests || options.skipSuccessfulRequests) {
266
- decremented_1 = false;
267
- decrementKey_1 = function () { return __awaiter(void 0, void 0, void 0, function () {
268
- return __generator(this, function (_a) {
269
- switch (_a.label) {
270
- case 0:
271
- if (!!decremented_1) return [3 /*break*/, 2];
272
- return [4 /*yield*/, options.store.decrement(key)];
273
- case 1:
274
- _a.sent();
275
- decremented_1 = true;
276
- _a.label = 2;
277
- case 2: return [2 /*return*/];
278
- }
279
- });
280
- }); };
281
- if (options.skipFailedRequests) {
282
- response.on('finish', function () { return __awaiter(void 0, void 0, void 0, function () {
283
- return __generator(this, function (_a) {
284
- switch (_a.label) {
285
- case 0:
286
- if (!!options.requestWasSuccessful(request, response)) return [3 /*break*/, 2];
287
- return [4 /*yield*/, decrementKey_1()];
288
- case 1:
289
- _a.sent();
290
- _a.label = 2;
291
- case 2: return [2 /*return*/];
292
- }
293
- });
294
- }); });
295
- response.on('close', function () { return __awaiter(void 0, void 0, void 0, function () {
296
- return __generator(this, function (_a) {
297
- switch (_a.label) {
298
- case 0:
299
- if (!!response.writableEnded) return [3 /*break*/, 2];
300
- return [4 /*yield*/, decrementKey_1()];
301
- case 1:
302
- _a.sent();
303
- _a.label = 2;
304
- case 2: return [2 /*return*/];
305
- }
306
- });
307
- }); });
308
- response.on('error', function () { return __awaiter(void 0, void 0, void 0, function () {
309
- return __generator(this, function (_a) {
310
- switch (_a.label) {
311
- case 0: return [4 /*yield*/, decrementKey_1()];
312
- case 1:
313
- _a.sent();
314
- return [2 /*return*/];
315
- }
316
- });
317
- }); });
318
- }
319
- if (options.skipSuccessfulRequests) {
320
- response.on('finish', function () { return __awaiter(void 0, void 0, void 0, function () {
321
- return __generator(this, function (_a) {
322
- switch (_a.label) {
323
- case 0:
324
- if (!options.requestWasSuccessful(request, response)) return [3 /*break*/, 2];
325
- return [4 /*yield*/, decrementKey_1()];
326
- case 1:
327
- _a.sent();
328
- _a.label = 2;
329
- case 2: return [2 /*return*/];
330
- }
331
- });
332
- }); });
333
- }
334
- }
335
- // Call the {@link Options.onLimitReached} callback on
336
- // the first request where client exceeds their rate limit.
337
- if (maxHits && totalHits === maxHits + 1) {
338
- options.onLimitReached(request, response, options);
339
- }
340
- // If the client has exceeded their rate limit, set the Retry-After
341
- // header and call the {@link Options.handler} function
342
- if (maxHits && totalHits > maxHits) {
343
- if ((options.legacyHeaders || options.standardHeaders) &&
344
- !response.headersSent) {
345
- response.setHeader('Retry-After', Math.ceil(options.windowMs / 1000));
346
- }
347
- options.handler(request, response, next, options);
348
- return [2 /*return*/];
349
- }
350
- next();
351
- return [2 /*return*/];
352
- }
353
- });
354
- }); });
355
- middleware.resetKey =
356
- options.store.resetKey.bind(options.store);
357
- return middleware;
358
- };
359
- // Export it to the world!
360
- export default rateLimit;
361
- //# sourceMappingURL=lib.js.map