This commit is contained in:
2026-08-14 16:03:47 +01:00
parent fd53e3f4fb
commit dfdc3b2840
2463 changed files with 186456 additions and 111315 deletions
+76 -24
View File
@@ -36,7 +36,7 @@ function ipKeyGenerator(ip, ipv6Subnet = 56) {
if (address.is4()) return address.to4().correctForm();
if (ipv6Subnet) {
const subnet = new import_ip_address.Address6(`${ip}/${ipv6Subnet}`);
return `${subnet.startAddress().correctForm()}/${ipv6Subnet}`;
return subnet.networkForm();
}
}
return ip;
@@ -201,6 +201,16 @@ var MemoryStore = class {
// source/rate-limit.ts
var import_node_net3 = require("node:net");
// source/console-logger.ts
var ConsoleLogger = {
warn(...args) {
console.warn(...args.reverse());
},
error(...args) {
console.error(...args.reverse());
}
};
// source/headers.ts
var import_node_buffer = require("node:buffer");
var import_node_crypto = require("node:crypto");
@@ -548,7 +558,8 @@ var validations = {
validate: true,
headers: true,
max: true,
passOnStoreError: true
passOnStoreError: true,
logger: true
};
const validOptions = Object.keys(optionsMap).concat(
"draft_polli_ratelimit_headers",
@@ -661,7 +672,15 @@ var validations = {
}
}
};
var getValidations = (_enabled) => {
function validateLogger(logger) {
if (typeof logger !== "object" || typeof logger.error !== "function" || typeof logger.warn !== "function") {
throw new TypeError(
"Provided logger does not implement the Logger interface"
);
}
}
var getValidations = (_enabled, logger) => {
validateLogger(logger);
let enabled;
if (typeof _enabled === "boolean") {
enabled = {
@@ -687,8 +706,8 @@ var getValidations = (_enabled) => {
args
);
} catch (error) {
if (error instanceof ChangeWarning) console.warn(error);
else console.error(error);
if (error instanceof ChangeWarning) logger.warn(error);
else logger.error(error);
}
};
}
@@ -741,7 +760,11 @@ var getOptionsFromConfig = (config) => {
};
var parseOptions = (passedOptions) => {
const notUndefinedOptions = omitUndefinedProperties(passedOptions);
const validations2 = getValidations(notUndefinedOptions?.validate ?? true);
const logger = passedOptions.logger ?? ConsoleLogger;
const validations2 = getValidations(
notUndefinedOptions?.validate ?? true,
logger
);
validations2.validationsConfig();
validations2.knownOptions(passedOptions);
validations2.draftPolliHeaders(
@@ -816,7 +839,8 @@ var parseOptions = (passedOptions) => {
notUndefinedOptions.store ?? new MemoryStore(validations2)
),
// Print an error to the console if a few known misconfigurations are detected.
validations: validations2
validations: validations2,
logger
};
if (typeof config.store.increment !== "function" || typeof config.store.decrement !== "function" || typeof config.store.resetKey !== "function" || config.store.resetAll !== void 0 && typeof config.store.resetAll !== "function" || config.store.init !== void 0 && typeof config.store.init !== "function") {
throw new TypeError(
@@ -837,9 +861,29 @@ var rateLimit = (passedOptions) => {
const options = getOptionsFromConfig(config);
config.validations.creationStack(config.store);
config.validations.unsharedStore(config.store);
if (typeof config.store.init === "function") config.store.init(options);
if (typeof config.store.init === "function") {
try {
const storeInit = config.store.init(options);
if (storeInit instanceof Promise) {
storeInit.catch(
(error) => config.logger.error(
error,
"express-rate-limit: async error during store initialization."
)
);
}
} catch (error) {
config.logger.error(
error,
"express-rate-limit: error during store initialization."
);
}
}
const middleware = handleAsyncErrors(
async (request, response, next) => {
const closePromise = config.skipFailedRequests && new Promise((resolve) => response.once("close", resolve));
const finishPromise = (config.skipFailedRequests || config.skipSuccessfulRequests) && new Promise((resolve) => response.once("finish", resolve));
const errorPromise = config.skipFailedRequests && new Promise((resolve) => response.once("error", resolve));
const skip = await config.skip(request, response);
if (skip) {
next();
@@ -855,9 +899,9 @@ var rateLimit = (passedOptions) => {
resetTime = incrementResult.resetTime;
} catch (error) {
if (config.passOnStoreError) {
console.error(
"express-rate-limit: error from store, allowing request without rate-limiting.",
error
config.logger.error(
error,
"express-rate-limit: error from store, allowing request without rate-limiting."
);
next();
return;
@@ -918,22 +962,30 @@ var rateLimit = (passedOptions) => {
}
};
if (config.skipFailedRequests) {
response.on("finish", async () => {
if (!await config.requestWasSuccessful(request, response))
if (finishPromise) {
void finishPromise.then(async () => {
if (!await config.requestWasSuccessful(request, response))
await decrementKey();
});
}
if (closePromise) {
void closePromise.then(async () => {
if (!response.writableEnded) await decrementKey();
});
}
if (errorPromise) {
void errorPromise.then(async () => {
await decrementKey();
});
response.on("close", async () => {
if (!response.writableEnded) await decrementKey();
});
response.on("error", async () => {
await decrementKey();
});
});
}
}
if (config.skipSuccessfulRequests) {
response.on("finish", async () => {
if (await config.requestWasSuccessful(request, response))
await decrementKey();
});
if (finishPromise) {
void finishPromise.then(async () => {
if (await config.requestWasSuccessful(request, response))
await decrementKey();
});
}
}
}
config.validations.disable();
+31 -1
View File
@@ -159,6 +159,26 @@ declare const validations: {
windowMs(windowMs: number): void;
};
export type Validations = typeof validations;
/**
* Basic logging function
*
* @param error {unknown} - The error to log
* @param message {string | undefined} - Additional details about the error
*/
export type LoggerFn = (error: unknown, message?: string) => void;
/**
* Minimal interface for logging warnings and errors
*/
export type Logger = {
/**
* Function to log an error
*/
error: LoggerFn;
/**
* Function to log a warning
*/
warn: LoggerFn;
};
/**
* Callback that fires when a client's hit counter is incremented.
*
@@ -265,9 +285,15 @@ export type Store = {
* Method that initializes the store, and has access to the options passed to
* the middleware too.
*
* Called once during initialization.
*
* Errors / promise rejections will be caught and logged.
*
* Note that the result is not awaited - other store methods (such as increment) may be called before init returns and/or after it throws/rejects.
*
* @param options {Options} - The options used to setup the middleware.
*/
init?: (options: Options) => void;
init?: (options: Options) => void | Promise<void>;
/**
* Method to fetch a client's hit count and reset time.
*
@@ -477,6 +503,10 @@ export type Options = {
* If the Store generates an error, allow the request to pass.
*/
passOnStoreError: boolean;
/**
* The logger to use to log errors. If absent, logs to the console.
*/
logger: Logger;
};
/**
* The extended request object that includes information about the client's
+31 -1
View File
@@ -159,6 +159,26 @@ declare const validations: {
windowMs(windowMs: number): void;
};
export type Validations = typeof validations;
/**
* Basic logging function
*
* @param error {unknown} - The error to log
* @param message {string | undefined} - Additional details about the error
*/
export type LoggerFn = (error: unknown, message?: string) => void;
/**
* Minimal interface for logging warnings and errors
*/
export type Logger = {
/**
* Function to log an error
*/
error: LoggerFn;
/**
* Function to log a warning
*/
warn: LoggerFn;
};
/**
* Callback that fires when a client's hit counter is incremented.
*
@@ -265,9 +285,15 @@ export type Store = {
* Method that initializes the store, and has access to the options passed to
* the middleware too.
*
* Called once during initialization.
*
* Errors / promise rejections will be caught and logged.
*
* Note that the result is not awaited - other store methods (such as increment) may be called before init returns and/or after it throws/rejects.
*
* @param options {Options} - The options used to setup the middleware.
*/
init?: (options: Options) => void;
init?: (options: Options) => void | Promise<void>;
/**
* Method to fetch a client's hit count and reset time.
*
@@ -477,6 +503,10 @@ export type Options = {
* If the Store generates an error, allow the request to pass.
*/
passOnStoreError: boolean;
/**
* The logger to use to log errors. If absent, logs to the console.
*/
logger: Logger;
};
/**
* The extended request object that includes information about the client's
+31 -1
View File
@@ -159,6 +159,26 @@ declare const validations: {
windowMs(windowMs: number): void;
};
export type Validations = typeof validations;
/**
* Basic logging function
*
* @param error {unknown} - The error to log
* @param message {string | undefined} - Additional details about the error
*/
export type LoggerFn = (error: unknown, message?: string) => void;
/**
* Minimal interface for logging warnings and errors
*/
export type Logger = {
/**
* Function to log an error
*/
error: LoggerFn;
/**
* Function to log a warning
*/
warn: LoggerFn;
};
/**
* Callback that fires when a client's hit counter is incremented.
*
@@ -265,9 +285,15 @@ export type Store = {
* Method that initializes the store, and has access to the options passed to
* the middleware too.
*
* Called once during initialization.
*
* Errors / promise rejections will be caught and logged.
*
* Note that the result is not awaited - other store methods (such as increment) may be called before init returns and/or after it throws/rejects.
*
* @param options {Options} - The options used to setup the middleware.
*/
init?: (options: Options) => void;
init?: (options: Options) => void | Promise<void>;
/**
* Method to fetch a client's hit count and reset time.
*
@@ -477,6 +503,10 @@ export type Options = {
* If the Store generates an error, allow the request to pass.
*/
passOnStoreError: boolean;
/**
* The logger to use to log errors. If absent, logs to the console.
*/
logger: Logger;
};
/**
* The extended request object that includes information about the client's
+76 -24
View File
@@ -7,7 +7,7 @@ function ipKeyGenerator(ip, ipv6Subnet = 56) {
if (address.is4()) return address.to4().correctForm();
if (ipv6Subnet) {
const subnet = new Address6(`${ip}/${ipv6Subnet}`);
return `${subnet.startAddress().correctForm()}/${ipv6Subnet}`;
return subnet.networkForm();
}
}
return ip;
@@ -172,6 +172,16 @@ var MemoryStore = class {
// source/rate-limit.ts
import { isIPv6 as isIPv62 } from "node:net";
// source/console-logger.ts
var ConsoleLogger = {
warn(...args) {
console.warn(...args.reverse());
},
error(...args) {
console.error(...args.reverse());
}
};
// source/headers.ts
import { Buffer } from "node:buffer";
import { createHash } from "node:crypto";
@@ -519,7 +529,8 @@ var validations = {
validate: true,
headers: true,
max: true,
passOnStoreError: true
passOnStoreError: true,
logger: true
};
const validOptions = Object.keys(optionsMap).concat(
"draft_polli_ratelimit_headers",
@@ -632,7 +643,15 @@ var validations = {
}
}
};
var getValidations = (_enabled) => {
function validateLogger(logger) {
if (typeof logger !== "object" || typeof logger.error !== "function" || typeof logger.warn !== "function") {
throw new TypeError(
"Provided logger does not implement the Logger interface"
);
}
}
var getValidations = (_enabled, logger) => {
validateLogger(logger);
let enabled;
if (typeof _enabled === "boolean") {
enabled = {
@@ -658,8 +677,8 @@ var getValidations = (_enabled) => {
args
);
} catch (error) {
if (error instanceof ChangeWarning) console.warn(error);
else console.error(error);
if (error instanceof ChangeWarning) logger.warn(error);
else logger.error(error);
}
};
}
@@ -712,7 +731,11 @@ var getOptionsFromConfig = (config) => {
};
var parseOptions = (passedOptions) => {
const notUndefinedOptions = omitUndefinedProperties(passedOptions);
const validations2 = getValidations(notUndefinedOptions?.validate ?? true);
const logger = passedOptions.logger ?? ConsoleLogger;
const validations2 = getValidations(
notUndefinedOptions?.validate ?? true,
logger
);
validations2.validationsConfig();
validations2.knownOptions(passedOptions);
validations2.draftPolliHeaders(
@@ -787,7 +810,8 @@ var parseOptions = (passedOptions) => {
notUndefinedOptions.store ?? new MemoryStore(validations2)
),
// Print an error to the console if a few known misconfigurations are detected.
validations: validations2
validations: validations2,
logger
};
if (typeof config.store.increment !== "function" || typeof config.store.decrement !== "function" || typeof config.store.resetKey !== "function" || config.store.resetAll !== void 0 && typeof config.store.resetAll !== "function" || config.store.init !== void 0 && typeof config.store.init !== "function") {
throw new TypeError(
@@ -808,9 +832,29 @@ var rateLimit = (passedOptions) => {
const options = getOptionsFromConfig(config);
config.validations.creationStack(config.store);
config.validations.unsharedStore(config.store);
if (typeof config.store.init === "function") config.store.init(options);
if (typeof config.store.init === "function") {
try {
const storeInit = config.store.init(options);
if (storeInit instanceof Promise) {
storeInit.catch(
(error) => config.logger.error(
error,
"express-rate-limit: async error during store initialization."
)
);
}
} catch (error) {
config.logger.error(
error,
"express-rate-limit: error during store initialization."
);
}
}
const middleware = handleAsyncErrors(
async (request, response, next) => {
const closePromise = config.skipFailedRequests && new Promise((resolve) => response.once("close", resolve));
const finishPromise = (config.skipFailedRequests || config.skipSuccessfulRequests) && new Promise((resolve) => response.once("finish", resolve));
const errorPromise = config.skipFailedRequests && new Promise((resolve) => response.once("error", resolve));
const skip = await config.skip(request, response);
if (skip) {
next();
@@ -826,9 +870,9 @@ var rateLimit = (passedOptions) => {
resetTime = incrementResult.resetTime;
} catch (error) {
if (config.passOnStoreError) {
console.error(
"express-rate-limit: error from store, allowing request without rate-limiting.",
error
config.logger.error(
error,
"express-rate-limit: error from store, allowing request without rate-limiting."
);
next();
return;
@@ -889,22 +933,30 @@ var rateLimit = (passedOptions) => {
}
};
if (config.skipFailedRequests) {
response.on("finish", async () => {
if (!await config.requestWasSuccessful(request, response))
if (finishPromise) {
void finishPromise.then(async () => {
if (!await config.requestWasSuccessful(request, response))
await decrementKey();
});
}
if (closePromise) {
void closePromise.then(async () => {
if (!response.writableEnded) await decrementKey();
});
}
if (errorPromise) {
void errorPromise.then(async () => {
await decrementKey();
});
response.on("close", async () => {
if (!response.writableEnded) await decrementKey();
});
response.on("error", async () => {
await decrementKey();
});
});
}
}
if (config.skipSuccessfulRequests) {
response.on("finish", async () => {
if (await config.requestWasSuccessful(request, response))
await decrementKey();
});
if (finishPromise) {
void finishPromise.then(async () => {
if (await config.requestWasSuccessful(request, response))
await decrementKey();
});
}
}
}
config.validations.disable();
+14 -13
View File
@@ -1,6 +1,6 @@
{
"name": "express-rate-limit",
"version": "8.3.0",
"version": "8.5.2",
"description": "Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.",
"author": {
"name": "Nathan Friedly",
@@ -70,37 +70,38 @@
"test:lib": "jest",
"test:ext": "cd test/external/ && bash run-all-tests",
"test": "run-s lint test:lib",
"format-test": "run-s format test:lib",
"pre-commit": "lint-staged",
"prepare": "run-s compile && husky"
},
"dependencies": {
"ip-address": "10.1.0"
"ip-address": "^10.2.0"
},
"peerDependencies": {
"express": ">= 4.11"
},
"devDependencies": {
"@biomejs/biome": "2.3.4",
"@biomejs/biome": "2.4.6",
"@express-rate-limit/prettier": "1.1.1",
"@express-rate-limit/tsconfig": "1.0.2",
"@jest/globals": "30.2.0",
"@jest/globals": "30.4.1",
"@types/express": "5.0.6",
"@types/jest": "30.0.0",
"@types/node": "25.3.3",
"@types/supertest": "6.0.3",
"del-cli": "6.0.0",
"@types/node": "25.7.0",
"@types/supertest": "7.2.0",
"del-cli": "7.0.0",
"dts-bundle-generator": "8.1.2",
"esbuild": "0.27.3",
"esbuild": "0.28.0",
"express": "5.2.1",
"husky": "9.1.7",
"jest": "30.2.0",
"lint-staged": "16.3.1",
"mintlify": "4.2.392",
"jest": "30.4.2",
"lint-staged": "17.0.4",
"mintlify": "4.2.559",
"npm-run-all": "4.1.5",
"prettier": "3.8.1",
"prettier": "3.8.3",
"ratelimit-header-parser": "0.1.0",
"supertest": "7.2.2",
"ts-jest": "29.4.6",
"ts-jest": "29.4.9",
"ts-node": "10.9.2",
"typescript": "5.9.3"
},
+5 -17
View File
@@ -66,24 +66,10 @@ default values.
| [`skipFailedRequests`] | `boolean` | Uncount 4xx/5xx responses. |
| [`requestWasSuccessful`] | `function` | Used by `skipSuccessfulRequests` and `skipFailedRequests`. |
| [`validate`] | `boolean` \| `object` | Enable or disable built-in validation checks. |
| [`logger`] | `Logger` | Custom logger |
## Thank You
Sponsored by [Zuplo](https://zuplo.link/express-rate-limit) a fully-managed API
Gateway for developers. Add
[dynamic rate-limiting](https://zuplo.link/dynamic-rate-limiting),
authentication and more to any API in minutes. Learn more at
[zuplo.com](https://zuplo.link/express-rate-limit)
<p align="center">
<a href="https://zuplo.link/express-rate-limit">
<picture width="322">
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/express-rate-limit/express-rate-limit/assets/114976/cd2f6fa7-eae1-4fbb-be7d-b17df4c6f383">
<img alt="zuplo-logo" src="https://github.com/express-rate-limit/express-rate-limit/assets/114976/66fd75fa-b39e-4a8c-8d7a-52369bf244dc" width="322">
</picture>
</a>
</p>
---
Thanks to Mintlify for hosting the documentation at
@@ -97,7 +83,7 @@ Thanks to Mintlify for hosting the documentation at
---
Finally, thank you to everyone who's contributed to this project in any way! 🫶
And thank you to everyone who's contributed to this project in any way! 🫶
## Issues and Contributing
@@ -108,7 +94,7 @@ If you need help with something, feel free to
[start a discussion](https://github.com/express-rate-limit/express-rate-limit/discussions/new)!
If you wish to contribute to the library, thanks! First, please read
[the contributing guide](https://express-rate-limit.mintlify.app/docs/guides/contributing.mdx).
[the contributing guide](https://express-rate-limit.mintlify.app/guides/contributing).
Then you can pick up any issue and fix/implement it!
## License
@@ -149,3 +135,5 @@ MIT © [Nathan Friedly](http://nfriedly.com/),
https://express-rate-limit.mintlify.app/reference/configuration#requestwassuccessful
[`validate`]:
https://express-rate-limit.mintlify.app/reference/configuration#validate
[`logger`]:
https://express-rate-limit.mintlify.app/reference/configuration#logger