express-rate-limit 5.4.1 → 6.0.1
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 +97 -0
- package/dist/cjs/index.d.ts +2 -0
- package/dist/cjs/index.js +19 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/lib.d.ts +15 -0
- package/dist/cjs/lib.js +366 -0
- package/dist/cjs/lib.js.map +1 -0
- package/dist/cjs/memory-store.d.ts +61 -0
- package/dist/cjs/memory-store.js +167 -0
- package/dist/cjs/memory-store.js.map +1 -0
- package/dist/cjs/package.json +12 -0
- package/dist/cjs/types.d.ts +239 -0
- package/dist/cjs/types.js +5 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/lib.d.ts +15 -0
- package/dist/esm/lib.js +361 -0
- package/dist/esm/lib.js.map +1 -0
- package/dist/esm/memory-store.d.ts +61 -0
- package/dist/esm/memory-store.js +165 -0
- package/dist/esm/memory-store.js.map +1 -0
- package/dist/esm/package.json +13 -0
- package/dist/esm/types.d.ts +239 -0
- package/dist/esm/types.js +4 -0
- package/dist/esm/types.js.map +1 -0
- package/license.md +20 -0
- package/package.json +137 -51
- package/readme.md +492 -0
- package/tsconfig.json +18 -0
- package/LICENSE +0 -7
- package/README.md +0 -349
- package/lib/express-rate-limit.js +0 -190
- package/lib/memory-store.js +0 -47
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// /source/memory-store.ts
|
|
3
|
+
// A memory store for hit counts
|
|
4
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
5
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
6
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
7
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
8
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
9
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
10
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
11
|
+
});
|
|
12
|
+
};
|
|
13
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
14
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
|
15
|
+
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
16
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
17
|
+
function step(op) {
|
|
18
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
19
|
+
while (_) try {
|
|
20
|
+
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;
|
|
21
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
22
|
+
switch (op[0]) {
|
|
23
|
+
case 0: case 1: t = op; break;
|
|
24
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
25
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
26
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
27
|
+
default:
|
|
28
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
29
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
30
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
31
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
32
|
+
if (t[2]) _.ops.pop();
|
|
33
|
+
_.trys.pop(); continue;
|
|
34
|
+
}
|
|
35
|
+
op = body.call(thisArg, _);
|
|
36
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
37
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
exports.__esModule = true;
|
|
41
|
+
/**
|
|
42
|
+
* Calculates the time when all hit counters will be reset.
|
|
43
|
+
*
|
|
44
|
+
* @param windowMs {number} - The duration of a window (in milliseconds)
|
|
45
|
+
*
|
|
46
|
+
* @returns {Date}
|
|
47
|
+
*
|
|
48
|
+
* @private
|
|
49
|
+
*/
|
|
50
|
+
var calculateNextResetTime = function (windowMs) {
|
|
51
|
+
var resetTime = new Date();
|
|
52
|
+
resetTime.setMilliseconds(resetTime.getMilliseconds() + windowMs);
|
|
53
|
+
return resetTime;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* A {@link Store} that stores the hit count for each client in
|
|
57
|
+
* memory.
|
|
58
|
+
*
|
|
59
|
+
* @public
|
|
60
|
+
*/
|
|
61
|
+
var MemoryStore = /** @class */ (function () {
|
|
62
|
+
function MemoryStore() {
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Method that initializes the store.
|
|
66
|
+
*
|
|
67
|
+
* @param options {Options} - The options used to setup the middleware
|
|
68
|
+
*/
|
|
69
|
+
MemoryStore.prototype.init = function (options) {
|
|
70
|
+
var _this = this;
|
|
71
|
+
// Get the duration of a window from the options
|
|
72
|
+
this.windowMs = options.windowMs;
|
|
73
|
+
// Then calculate the reset time using that
|
|
74
|
+
this.resetTime = calculateNextResetTime(this.windowMs);
|
|
75
|
+
// Initialise the hit counter map
|
|
76
|
+
this.hits = {};
|
|
77
|
+
// Reset hit counts for ALL clients every `windowMs` - this will also
|
|
78
|
+
// re-calculate the `resetTime`
|
|
79
|
+
var interval = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
|
|
80
|
+
return __generator(this, function (_a) {
|
|
81
|
+
switch (_a.label) {
|
|
82
|
+
case 0: return [4 /*yield*/, this.resetAll()];
|
|
83
|
+
case 1:
|
|
84
|
+
_a.sent();
|
|
85
|
+
return [2 /*return*/];
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}); }, this.windowMs);
|
|
89
|
+
if (interval.unref) {
|
|
90
|
+
interval.unref();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Method to increment a client's hit counter.
|
|
95
|
+
*
|
|
96
|
+
* @param key {string} - The identifier for a client
|
|
97
|
+
*
|
|
98
|
+
* @returns {IncrementResponse} - The number of hits and reset time for that client
|
|
99
|
+
*
|
|
100
|
+
* @public
|
|
101
|
+
*/
|
|
102
|
+
MemoryStore.prototype.increment = function (key) {
|
|
103
|
+
var _a;
|
|
104
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
105
|
+
var totalHits;
|
|
106
|
+
return __generator(this, function (_b) {
|
|
107
|
+
totalHits = ((_a = this.hits[key]) !== null && _a !== void 0 ? _a : 0) + 1;
|
|
108
|
+
this.hits[key] = totalHits;
|
|
109
|
+
return [2 /*return*/, {
|
|
110
|
+
totalHits: totalHits,
|
|
111
|
+
resetTime: this.resetTime
|
|
112
|
+
}];
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Method to decrement a client's hit counter.
|
|
118
|
+
*
|
|
119
|
+
* @param key {string} - The identifier for a client
|
|
120
|
+
*
|
|
121
|
+
* @public
|
|
122
|
+
*/
|
|
123
|
+
MemoryStore.prototype.decrement = function (key) {
|
|
124
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
125
|
+
var current;
|
|
126
|
+
return __generator(this, function (_a) {
|
|
127
|
+
current = this.hits[key];
|
|
128
|
+
if (current) {
|
|
129
|
+
this.hits[key] = current - 1;
|
|
130
|
+
}
|
|
131
|
+
return [2 /*return*/];
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* Method to reset a client's hit counter.
|
|
137
|
+
*
|
|
138
|
+
* @param key {string} - The identifier for a client
|
|
139
|
+
*
|
|
140
|
+
* @public
|
|
141
|
+
*/
|
|
142
|
+
MemoryStore.prototype.resetKey = function (key) {
|
|
143
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
144
|
+
return __generator(this, function (_a) {
|
|
145
|
+
delete this.hits[key];
|
|
146
|
+
return [2 /*return*/];
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Method to reset everyone's hit counter.
|
|
152
|
+
*
|
|
153
|
+
* @public
|
|
154
|
+
*/
|
|
155
|
+
MemoryStore.prototype.resetAll = function () {
|
|
156
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
157
|
+
return __generator(this, function (_a) {
|
|
158
|
+
this.hits = {};
|
|
159
|
+
this.resetTime = calculateNextResetTime(this.windowMs);
|
|
160
|
+
return [2 /*return*/];
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
};
|
|
164
|
+
return MemoryStore;
|
|
165
|
+
}());
|
|
166
|
+
exports["default"] = MemoryStore;
|
|
167
|
+
//# sourceMappingURL=memory-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-store.js","sourceRoot":"","sources":["../../source/memory-store.ts"],"names":[],"mappings":";AAAA,0BAA0B;AAC1B,gCAAgC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIhC;;;;;;;;GAQG;AACH,IAAM,sBAAsB,GAAG,UAAC,QAAgB;IAC/C,IAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAA;IAC5B,SAAS,CAAC,eAAe,CAAC,SAAS,CAAC,eAAe,EAAE,GAAG,QAAQ,CAAC,CAAA;IACjE,OAAO,SAAS,CAAA;AACjB,CAAC,CAAA;AAED;;;;;GAKG;AACH;IAAA;IA+FA,CAAC;IA7EA;;;;OAIG;IACH,0BAAI,GAAJ,UAAK,OAAgB;QAArB,iBAiBC;QAhBA,gDAAgD;QAChD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAA;QAChC,2CAA2C;QAC3C,IAAI,CAAC,SAAS,GAAG,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QAEtD,iCAAiC;QACjC,IAAI,CAAC,IAAI,GAAG,EAAE,CAAA;QAEd,qEAAqE;QACrE,+BAA+B;QAC/B,IAAM,QAAQ,GAAG,WAAW,CAAC;;;4BAC5B,qBAAM,IAAI,CAAC,QAAQ,EAAE,EAAA;;wBAArB,SAAqB,CAAA;;;;aACrB,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;QACjB,IAAI,QAAQ,CAAC,KAAK,EAAE;YACnB,QAAQ,CAAC,KAAK,EAAE,CAAA;SAChB;IACF,CAAC;IAED;;;;;;;;OAQG;IACG,+BAAS,GAAf,UAAgB,GAAW;;;;;gBACpB,SAAS,GAAG,CAAC,MAAA,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,mCAAI,CAAC,CAAC,GAAG,CAAC,CAAA;gBAC3C,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,SAAS,CAAA;gBAE1B,sBAAO;wBACN,SAAS,WAAA;wBACT,SAAS,EAAE,IAAI,CAAC,SAAS;qBACzB,EAAA;;;KACD;IAED;;;;;;OAMG;IACG,+BAAS,GAAf,UAAgB,GAAW;;;;gBACpB,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBAC9B,IAAI,OAAO,EAAE;oBACZ,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,GAAG,CAAC,CAAA;iBAC5B;;;;KACD;IAED;;;;;;OAMG;IACG,8BAAQ,GAAd,UAAe,GAAW;;;gBACzB,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;;;;KACrB;IAED;;;;OAIG;IACG,8BAAQ,GAAd;;;gBACC,IAAI,CAAC,IAAI,GAAG,EAAE,CAAA;gBACd,IAAI,CAAC,SAAS,GAAG,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;;;;KACtD;IACF,kBAAC;AAAD,CAAC,AA/FD,IA+FC","sourcesContent":["// /source/memory-store.ts\n// A memory store for hit counts\n\nimport { Store, Options, IncrementResponse } from './types.js'\n\n/**\n * Calculates the time when all hit counters will be reset.\n *\n * @param windowMs {number} - The duration of a window (in milliseconds)\n *\n * @returns {Date}\n *\n * @private\n */\nconst calculateNextResetTime = (windowMs: number): Date => {\n\tconst resetTime = new Date()\n\tresetTime.setMilliseconds(resetTime.getMilliseconds() + windowMs)\n\treturn resetTime\n}\n\n/**\n * A {@link Store} that stores the hit count for each client in\n * memory.\n *\n * @public\n */\nexport default class MemoryStore implements Store {\n\t/**\n\t * The duration of time before which all hit counts are reset (in milliseconds).\n\t */\n\twindowMs!: number\n\n\t/**\n\t * The map that stores the number of hits for each client in memory.\n\t */\n\thits!: {\n\t\t[key: string]: number | undefined\n\t}\n\n\t/**\n\t * The time at which all hit counts will be reset.\n\t */\n\tresetTime!: Date\n\n\t/**\n\t * Method that initializes the store.\n\t *\n\t * @param options {Options} - The options used to setup the middleware\n\t */\n\tinit(options: Options): void {\n\t\t// Get the duration of a window from the options\n\t\tthis.windowMs = options.windowMs\n\t\t// Then calculate the reset time using that\n\t\tthis.resetTime = calculateNextResetTime(this.windowMs)\n\n\t\t// Initialise the hit counter map\n\t\tthis.hits = {}\n\n\t\t// Reset hit counts for ALL clients every `windowMs` - this will also\n\t\t// re-calculate the `resetTime`\n\t\tconst interval = setInterval(async () => {\n\t\t\tawait this.resetAll()\n\t\t}, this.windowMs)\n\t\tif (interval.unref) {\n\t\t\tinterval.unref()\n\t\t}\n\t}\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\t * @public\n\t */\n\tasync increment(key: string): Promise<IncrementResponse> {\n\t\tconst totalHits = (this.hits[key] ?? 0) + 1\n\t\tthis.hits[key] = totalHits\n\n\t\treturn {\n\t\t\ttotalHits,\n\t\t\tresetTime: this.resetTime,\n\t\t}\n\t}\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\t * @public\n\t */\n\tasync decrement(key: string): Promise<void> {\n\t\tconst current = this.hits[key]\n\t\tif (current) {\n\t\t\tthis.hits[key] = current - 1\n\t\t}\n\t}\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\t * @public\n\t */\n\tasync resetKey(key: string): Promise<void> {\n\t\tdelete this.hits[key]\n\t}\n\n\t/**\n\t * Method to reset everyone's hit counter.\n\t *\n\t * @public\n\t */\n\tasync resetAll(): Promise<void> {\n\t\tthis.hits = {}\n\t\tthis.resetTime = calculateNextResetTime(this.windowMs)\n\t}\n}\n"]}
|
|
@@ -0,0 +1,239 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
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;
|