init project
This commit is contained in:
+1080
File diff suppressed because it is too large
Load Diff
+688
@@ -0,0 +1,688 @@
|
||||
// Generated by dts-bundle-generator v8.1.2
|
||||
|
||||
import { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
|
||||
/**
|
||||
* Returns the IP address itself for IPv4, or a CIDR-notation subnet for IPv6.
|
||||
*
|
||||
* If you write a custom keyGenerator that allows a fallback to IP address for
|
||||
* unauthenticated users, return ipKeyGenerator(req.ip) rather than just req.ip.
|
||||
*
|
||||
* For more information, {@see Options.ipv6Subnet}.
|
||||
*
|
||||
* @param ip {string} - The IP address to process, usually request.ip.
|
||||
* @param ipv6Subnet {number | false} - The subnet mask for IPv6 addresses.
|
||||
*
|
||||
* @returns {string} - The key generated from the IP address
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare function ipKeyGenerator(ip: string, ipv6Subnet?: number | false): string;
|
||||
declare const SUPPORTED_DRAFT_VERSIONS: readonly [
|
||||
"draft-6",
|
||||
"draft-7",
|
||||
"draft-8"
|
||||
];
|
||||
declare const validations: {
|
||||
enabled: {
|
||||
[key: string]: boolean;
|
||||
};
|
||||
disable(): void;
|
||||
/**
|
||||
* Checks whether the IP address is valid, and that it does not have a port
|
||||
* number in it.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
|
||||
*
|
||||
* @param ip {string | undefined} - The IP address provided by Express as request.ip.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
ip(ip: string | undefined): void;
|
||||
/**
|
||||
* Makes sure the trust proxy setting is not set to `true`.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
trustProxy(request: Request): void;
|
||||
/**
|
||||
* Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
|
||||
* header is present.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
xForwardedForHeader(request: Request): void;
|
||||
/**
|
||||
* Alert the user if the Forwarded header is set (standardized version of X-Forwarded-For - not supported by express as of version 5.1.0)
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
forwardedHeader(request: Request): void;
|
||||
/**
|
||||
* Ensures totalHits value from store is a positive integer.
|
||||
*
|
||||
* @param hits {any} - The `totalHits` returned by the store.
|
||||
*/
|
||||
positiveHits(hits: any): void;
|
||||
/**
|
||||
* Ensures a single store instance is not used with multiple express-rate-limit instances
|
||||
*/
|
||||
unsharedStore(store: Store): void;
|
||||
/**
|
||||
* Ensures a given key is incremented only once per request.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param store {Store} - The store class.
|
||||
* @param key {string} - The key used to store the client's hit count.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
singleCount(request: Request, store: Store, key: string): void;
|
||||
/**
|
||||
* Warns the user that the behaviour for `max: 0` / `limit: 0` is
|
||||
* changing in the next major release.
|
||||
*
|
||||
* @param limit {number} - The maximum number of hits per client.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
limit(limit: number): void;
|
||||
/**
|
||||
* Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
|
||||
* and will be removed in the next major release.
|
||||
*
|
||||
* @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
draftPolliHeaders(draft_polli_ratelimit_headers?: any): void;
|
||||
/**
|
||||
* Warns the user that the `onLimitReached` option is deprecated and
|
||||
* will be removed in the next major release.
|
||||
*
|
||||
* @param onLimitReached {any | undefined} - The maximum number of hits per client.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
onLimitReached(onLimitReached?: any): void;
|
||||
/**
|
||||
* Warns the user when an invalid/unsupported version of the draft spec is passed.
|
||||
*
|
||||
* @param version {any | undefined} - The version passed by the user.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
headersDraftVersion(version?: any): void;
|
||||
/**
|
||||
* Warns the user when the selected headers option requires a reset time but
|
||||
* the store does not provide one.
|
||||
*
|
||||
* @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
headersResetTime(resetTime?: Date): void;
|
||||
knownOptions(passedOptions?: Partial<Options>): void;
|
||||
/**
|
||||
* Checks the options.validate setting to ensure that only recognized
|
||||
* validations are enabled or disabled.
|
||||
*
|
||||
* If any unrecognized values are found, an error is logged that
|
||||
* includes the list of supported validations.
|
||||
*/
|
||||
validationsConfig(): void;
|
||||
/**
|
||||
* Checks to see if the instance was created inside of a request handler,
|
||||
* which would prevent it from working correctly, with the default memory
|
||||
* store (or any other store with localKeys.)
|
||||
*/
|
||||
creationStack(store: Store): void;
|
||||
ipv6Subnet(ipv6Subnet?: any): void;
|
||||
ipv6SubnetOrKeyGenerator(options: Partial<Options>): void;
|
||||
keyGeneratorIpFallback(keyGenerator?: ValueDeterminingMiddleware<string>): void;
|
||||
/**
|
||||
* Checks to see if the window duration is greater than 2^32 - 1. This is only
|
||||
* called by the default MemoryStore, since it uses Node's setInterval method.
|
||||
*
|
||||
* See https://nodejs.org/api/timers.html#setintervalcallback-delay-args.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @param error {Error | undefined} - The error that occurred, if any.
|
||||
* @param totalHits {number} - The number of hits for that client so far.
|
||||
* @param resetTime {Date | undefined} - The time when the counter resets.
|
||||
*/
|
||||
export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void;
|
||||
/**
|
||||
* Method (in the form of middleware) to generate/retrieve a value based on the
|
||||
* incoming request.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
*
|
||||
* @returns {T} - The value needed.
|
||||
*/
|
||||
export type ValueDeterminingMiddleware<T> = (request: Request, response: Response) => T | Promise<T>;
|
||||
/**
|
||||
* Express request handler that sends back a response when a client is
|
||||
* rate-limited.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
* @param next {NextFunction} - The Express `next` function, can be called to skip responding.
|
||||
* @param optionsUsed {Options} - The options used to set up the middleware.
|
||||
*/
|
||||
export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void;
|
||||
/**
|
||||
* Event callback that is triggered on a client's first request that exceeds the limit
|
||||
* but not for subsequent requests. May be used for logging, etc. Should *not*
|
||||
* send a response.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
* @param optionsUsed {Options} - The options used to set up the middleware.
|
||||
*/
|
||||
export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void;
|
||||
/**
|
||||
* Data returned from the `Store` when a client's hit counter is incremented.
|
||||
*
|
||||
* @property totalHits {number} - The number of hits for that client so far.
|
||||
* @property resetTime {Date | undefined} - The time when the counter resets.
|
||||
*/
|
||||
export type ClientRateLimitInfo = {
|
||||
totalHits: number;
|
||||
resetTime: Date | undefined;
|
||||
};
|
||||
export type IncrementResponse = ClientRateLimitInfo;
|
||||
/**
|
||||
* A modified Express request handler with the rate limit functions.
|
||||
*/
|
||||
export type RateLimitRequestHandler = RequestHandler & {
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => void;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*/
|
||||
getKey: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
|
||||
};
|
||||
/**
|
||||
* An interface that all hit counter stores must implement.
|
||||
*
|
||||
* @deprecated 6.x - Implement the `Store` interface instead.
|
||||
*/
|
||||
export type LegacyStore = {
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
* @param callback {IncrementCallback} - The callback to call once the counter is incremented.
|
||||
*/
|
||||
incr: (key: string, callback: IncrementCallback) => void;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
decrement: (key: string) => void;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => void;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*/
|
||||
resetAll?: () => void;
|
||||
};
|
||||
/**
|
||||
* An interface that all hit counter stores must implement.
|
||||
*/
|
||||
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 | Promise<void>;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*/
|
||||
get?: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {IncrementResponse | undefined} - The number of hits and reset time for that client.
|
||||
*/
|
||||
increment: (key: string) => Promise<IncrementResponse> | IncrementResponse;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
decrement: (key: string) => Promise<void> | void;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => Promise<void> | void;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*/
|
||||
resetAll?: () => Promise<void> | void;
|
||||
/**
|
||||
* Method to shutdown the store, stop timers, and release all resources.
|
||||
*/
|
||||
shutdown?: () => Promise<void> | void;
|
||||
/**
|
||||
* Flag to indicate that keys incremented in one instance of this store can
|
||||
* not affect other instances. Typically false if a database is used, true for
|
||||
* MemoryStore.
|
||||
*
|
||||
* Used to help detect double-counting misconfigurations.
|
||||
*/
|
||||
localKeys?: boolean;
|
||||
/**
|
||||
* Optional value that the store prepends to keys
|
||||
*
|
||||
* Used by the double-count check to avoid false-positives when a key is counted
|
||||
* twice, but with different prefixes.
|
||||
*/
|
||||
prefix?: string;
|
||||
};
|
||||
export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number];
|
||||
/**
|
||||
* Validate configuration object for enabling or disabling specific validations.
|
||||
*
|
||||
* The keys must also be keys in the validations object, except `enable`, `disable`,
|
||||
* and `default`.
|
||||
*/
|
||||
export type EnabledValidations = {
|
||||
[key in keyof Omit<Validations, "enabled" | "disable"> | "default"]?: boolean;
|
||||
};
|
||||
/**
|
||||
* The configuration options for the rate limiter.
|
||||
*/
|
||||
export type Options = {
|
||||
/**
|
||||
* How long we should remember the requests.
|
||||
*
|
||||
* Defaults to `60000` ms (= 1 minute).
|
||||
*/
|
||||
windowMs: number;
|
||||
/**
|
||||
* The maximum number of connections to allow during the `window` before
|
||||
* rate limiting the client.
|
||||
*
|
||||
* Can be the limit itself as a number or express middleware that parses
|
||||
* the request and then figures out the limit.
|
||||
*
|
||||
* Defaults to `5`.
|
||||
*/
|
||||
limit: number | ValueDeterminingMiddleware<number>;
|
||||
/**
|
||||
* The response body to send back when a client is rate limited.
|
||||
*
|
||||
* Defaults to `'Too many requests, please try again later.'`
|
||||
*/
|
||||
message: any | ValueDeterminingMiddleware<any>;
|
||||
/**
|
||||
* The HTTP status code to send back when a client is rate limited.
|
||||
*
|
||||
* Defaults to `HTTP 429 Too Many Requests` (RFC 6585).
|
||||
*/
|
||||
statusCode: number;
|
||||
/**
|
||||
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
|
||||
* of requests.
|
||||
*
|
||||
* Defaults to `true` (for backward compatibility).
|
||||
*/
|
||||
legacyHeaders: boolean;
|
||||
/**
|
||||
* Whether to enable support for the standardized rate limit headers (`RateLimit-*`).
|
||||
*
|
||||
* Defaults to `false` (for backward compatibility, but its use is recommended).
|
||||
*/
|
||||
standardHeaders: boolean | DraftHeadersVersion;
|
||||
/**
|
||||
* The name used to identify the quota policy in the `RateLimit` headers as per
|
||||
* the 8th draft of the IETF specification.
|
||||
*
|
||||
* Defaults to `{limit}-in-{window}`.
|
||||
*/
|
||||
identifier: string | ValueDeterminingMiddleware<string>;
|
||||
/**
|
||||
* The name of the property on the request object to store the rate limit info.
|
||||
*
|
||||
* Defaults to `rateLimit`.
|
||||
*/
|
||||
requestPropertyName: string;
|
||||
/**
|
||||
* If `true`, the library will (by default) skip all requests that have a 4XX
|
||||
* or 5XX status.
|
||||
*
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
skipFailedRequests: boolean;
|
||||
/**
|
||||
* If `true`, the library will (by default) skip all requests that have a
|
||||
* status code less than 400.
|
||||
*
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
skipSuccessfulRequests: boolean;
|
||||
/**
|
||||
* Method to generate custom identifiers for clients.
|
||||
*
|
||||
* By default, the client's IP address is used.
|
||||
*/
|
||||
keyGenerator: ValueDeterminingMiddleware<string>;
|
||||
/**
|
||||
* IPv6 subnet mask applied to IPv6 addresses in the default keyGenerator.
|
||||
*
|
||||
* Default is 56. The valid range is technically 1-128 but the value should
|
||||
* generally be in the 32-64 range.
|
||||
*
|
||||
* Smaller numbers are more aggressive, larger numbers are more lenient. Try
|
||||
* bumping to 60 or 64 if you see evidence of users being blocked incorrectly.
|
||||
*
|
||||
* May also be set to a function that returns a number based on the request.
|
||||
*
|
||||
* See the documentation for more info:
|
||||
* https://express-rate-limit.mintlify.app/reference/configuration#ipv6subnet.
|
||||
*/
|
||||
ipv6Subnet: 64 | 60 | 56 | 52 | 50 | 48 | 32 | number | ValueDeterminingMiddleware<number> | false;
|
||||
/**
|
||||
* Express request handler that sends back a response when a client is
|
||||
* rate-limited.
|
||||
*
|
||||
* By default, sends back the `statusCode` and `message` set via the options.
|
||||
*/
|
||||
handler: RateLimitExceededEventHandler;
|
||||
/**
|
||||
* Method (in the form of middleware) to determine whether or not this request
|
||||
* counts towards a client's quota.
|
||||
*
|
||||
* By default, skips no requests.
|
||||
*/
|
||||
skip: ValueDeterminingMiddleware<boolean>;
|
||||
/**
|
||||
* Method to determine whether or not the request counts as 'successful'. Used
|
||||
* when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true.
|
||||
*
|
||||
* By default, requests with a response status code less than 400 are considered
|
||||
* successful.
|
||||
*/
|
||||
requestWasSuccessful: ValueDeterminingMiddleware<boolean>;
|
||||
/**
|
||||
* The `Store` to use to store the hit count for each client.
|
||||
*
|
||||
* By default, the built-in `MemoryStore` will be used.
|
||||
*/
|
||||
store: Store | LegacyStore;
|
||||
/**
|
||||
* The list of validation checks that should run.
|
||||
*/
|
||||
validate: boolean | EnabledValidations;
|
||||
/**
|
||||
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
|
||||
* of requests.
|
||||
*
|
||||
* @deprecated 6.x - This option was renamed to `legacyHeaders`.
|
||||
*/
|
||||
headers?: boolean;
|
||||
/**
|
||||
* The maximum number of connections to allow during the `window` before
|
||||
* rate limiting the client.
|
||||
*
|
||||
* Can be the limit itself as a number or express middleware that parses
|
||||
* the request and then figures out the limit.
|
||||
*
|
||||
* @deprecated 7.x - This option was renamed to `limit`. However, it will not
|
||||
* be removed from the library in the foreseeable future.
|
||||
*/
|
||||
max?: number | ValueDeterminingMiddleware<number>;
|
||||
/**
|
||||
* 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
|
||||
* rate limit.
|
||||
*/
|
||||
export type AugmentedRequest = Request & {
|
||||
[key: string]: RateLimitInfo;
|
||||
};
|
||||
/**
|
||||
* The rate limit related information for each client included in the
|
||||
* Express request object.
|
||||
*/
|
||||
export type RateLimitInfo = {
|
||||
limit: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
resetTime: Date | undefined;
|
||||
key: string;
|
||||
};
|
||||
/**
|
||||
* The record that stores information about a client - namely, how many times
|
||||
* they have hit the endpoint, and when their hit count resets.
|
||||
*
|
||||
* Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field.
|
||||
*/
|
||||
export type Client = {
|
||||
totalHits: number;
|
||||
resetTime: Date;
|
||||
};
|
||||
/**
|
||||
* A `Store` that stores the hit count for each client in memory.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare class MemoryStore implements Store {
|
||||
private validations?;
|
||||
/**
|
||||
* The duration of time before which all hit counts are reset (in milliseconds).
|
||||
*/
|
||||
windowMs: number;
|
||||
/**
|
||||
* These two maps store usage (requests) and reset time by key (for example, IP
|
||||
* addresses or API keys).
|
||||
*
|
||||
* They are split into two to avoid having to iterate through the entire set to
|
||||
* determine which ones need reset. Instead, `Client`s are moved from `previous`
|
||||
* to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
|
||||
* left in `previous`, i.e., those that have not made any recent requests, are
|
||||
* known to be expired and can be deleted in bulk.
|
||||
*/
|
||||
previous: Map<string, Client>;
|
||||
current: Map<string, Client>;
|
||||
/**
|
||||
* A reference to the active timer.
|
||||
*/
|
||||
interval?: NodeJS.Timeout;
|
||||
/**
|
||||
* Confirmation that the keys incremented in once instance of MemoryStore
|
||||
* cannot affect other instances.
|
||||
*/
|
||||
localKeys: boolean;
|
||||
constructor(validations?: Validations | undefined);
|
||||
/**
|
||||
* Method that initializes the store.
|
||||
*
|
||||
* @param options {Options} - The options used to setup the middleware.
|
||||
*/
|
||||
init(options: Options): void;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
get(key: string): Promise<ClientRateLimitInfo | undefined>;
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
increment(key: string): Promise<ClientRateLimitInfo>;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
decrement(key: string): Promise<void>;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
resetKey(key: string): Promise<void>;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
resetAll(): Promise<void>;
|
||||
/**
|
||||
* Method to stop the timer (if currently running) and prevent any memory
|
||||
* leaks.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
shutdown(): void;
|
||||
/**
|
||||
* Recycles a client by setting its hit count to zero, and reset time to
|
||||
* `windowMs` milliseconds from now.
|
||||
*
|
||||
* NOT to be confused with `#resetKey()`, which removes a client from both the
|
||||
* `current` and `previous` maps.
|
||||
*
|
||||
* @param client {Client} - The client to recycle.
|
||||
* @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
|
||||
*
|
||||
* @return {Client} - The modified client that was passed in, to allow for chaining.
|
||||
*/
|
||||
private resetClient;
|
||||
/**
|
||||
* Retrieves or creates a client, given a key. Also ensures that the client being
|
||||
* returned is in the `current` map.
|
||||
*
|
||||
* @param key {string} - The key under which the client is (or is to be) stored.
|
||||
*
|
||||
* @returns {Client} - The requested client.
|
||||
*/
|
||||
private getClient;
|
||||
/**
|
||||
* Move current clients to previous, create a new map for current.
|
||||
*
|
||||
* This function is called every `windowMs`.
|
||||
*/
|
||||
private clearExpired;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* Create an instance of IP rate-limiting middleware for Express.
|
||||
*
|
||||
* @param passedOptions {Options} - Options to configure the rate limiter.
|
||||
*
|
||||
* @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare const rateLimit: (passedOptions?: Partial<Options>) => RateLimitRequestHandler;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const SECOND: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const MINUTE: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const HOUR: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const DAY: number;
|
||||
|
||||
export {
|
||||
rateLimit as default,
|
||||
};
|
||||
|
||||
export {};
|
||||
+688
@@ -0,0 +1,688 @@
|
||||
// Generated by dts-bundle-generator v8.1.2
|
||||
|
||||
import { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
|
||||
/**
|
||||
* Returns the IP address itself for IPv4, or a CIDR-notation subnet for IPv6.
|
||||
*
|
||||
* If you write a custom keyGenerator that allows a fallback to IP address for
|
||||
* unauthenticated users, return ipKeyGenerator(req.ip) rather than just req.ip.
|
||||
*
|
||||
* For more information, {@see Options.ipv6Subnet}.
|
||||
*
|
||||
* @param ip {string} - The IP address to process, usually request.ip.
|
||||
* @param ipv6Subnet {number | false} - The subnet mask for IPv6 addresses.
|
||||
*
|
||||
* @returns {string} - The key generated from the IP address
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare function ipKeyGenerator(ip: string, ipv6Subnet?: number | false): string;
|
||||
declare const SUPPORTED_DRAFT_VERSIONS: readonly [
|
||||
"draft-6",
|
||||
"draft-7",
|
||||
"draft-8"
|
||||
];
|
||||
declare const validations: {
|
||||
enabled: {
|
||||
[key: string]: boolean;
|
||||
};
|
||||
disable(): void;
|
||||
/**
|
||||
* Checks whether the IP address is valid, and that it does not have a port
|
||||
* number in it.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
|
||||
*
|
||||
* @param ip {string | undefined} - The IP address provided by Express as request.ip.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
ip(ip: string | undefined): void;
|
||||
/**
|
||||
* Makes sure the trust proxy setting is not set to `true`.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
trustProxy(request: Request): void;
|
||||
/**
|
||||
* Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
|
||||
* header is present.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
xForwardedForHeader(request: Request): void;
|
||||
/**
|
||||
* Alert the user if the Forwarded header is set (standardized version of X-Forwarded-For - not supported by express as of version 5.1.0)
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
forwardedHeader(request: Request): void;
|
||||
/**
|
||||
* Ensures totalHits value from store is a positive integer.
|
||||
*
|
||||
* @param hits {any} - The `totalHits` returned by the store.
|
||||
*/
|
||||
positiveHits(hits: any): void;
|
||||
/**
|
||||
* Ensures a single store instance is not used with multiple express-rate-limit instances
|
||||
*/
|
||||
unsharedStore(store: Store): void;
|
||||
/**
|
||||
* Ensures a given key is incremented only once per request.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param store {Store} - The store class.
|
||||
* @param key {string} - The key used to store the client's hit count.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
singleCount(request: Request, store: Store, key: string): void;
|
||||
/**
|
||||
* Warns the user that the behaviour for `max: 0` / `limit: 0` is
|
||||
* changing in the next major release.
|
||||
*
|
||||
* @param limit {number} - The maximum number of hits per client.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
limit(limit: number): void;
|
||||
/**
|
||||
* Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
|
||||
* and will be removed in the next major release.
|
||||
*
|
||||
* @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
draftPolliHeaders(draft_polli_ratelimit_headers?: any): void;
|
||||
/**
|
||||
* Warns the user that the `onLimitReached` option is deprecated and
|
||||
* will be removed in the next major release.
|
||||
*
|
||||
* @param onLimitReached {any | undefined} - The maximum number of hits per client.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
onLimitReached(onLimitReached?: any): void;
|
||||
/**
|
||||
* Warns the user when an invalid/unsupported version of the draft spec is passed.
|
||||
*
|
||||
* @param version {any | undefined} - The version passed by the user.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
headersDraftVersion(version?: any): void;
|
||||
/**
|
||||
* Warns the user when the selected headers option requires a reset time but
|
||||
* the store does not provide one.
|
||||
*
|
||||
* @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
headersResetTime(resetTime?: Date): void;
|
||||
knownOptions(passedOptions?: Partial<Options>): void;
|
||||
/**
|
||||
* Checks the options.validate setting to ensure that only recognized
|
||||
* validations are enabled or disabled.
|
||||
*
|
||||
* If any unrecognized values are found, an error is logged that
|
||||
* includes the list of supported validations.
|
||||
*/
|
||||
validationsConfig(): void;
|
||||
/**
|
||||
* Checks to see if the instance was created inside of a request handler,
|
||||
* which would prevent it from working correctly, with the default memory
|
||||
* store (or any other store with localKeys.)
|
||||
*/
|
||||
creationStack(store: Store): void;
|
||||
ipv6Subnet(ipv6Subnet?: any): void;
|
||||
ipv6SubnetOrKeyGenerator(options: Partial<Options>): void;
|
||||
keyGeneratorIpFallback(keyGenerator?: ValueDeterminingMiddleware<string>): void;
|
||||
/**
|
||||
* Checks to see if the window duration is greater than 2^32 - 1. This is only
|
||||
* called by the default MemoryStore, since it uses Node's setInterval method.
|
||||
*
|
||||
* See https://nodejs.org/api/timers.html#setintervalcallback-delay-args.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @param error {Error | undefined} - The error that occurred, if any.
|
||||
* @param totalHits {number} - The number of hits for that client so far.
|
||||
* @param resetTime {Date | undefined} - The time when the counter resets.
|
||||
*/
|
||||
export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void;
|
||||
/**
|
||||
* Method (in the form of middleware) to generate/retrieve a value based on the
|
||||
* incoming request.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
*
|
||||
* @returns {T} - The value needed.
|
||||
*/
|
||||
export type ValueDeterminingMiddleware<T> = (request: Request, response: Response) => T | Promise<T>;
|
||||
/**
|
||||
* Express request handler that sends back a response when a client is
|
||||
* rate-limited.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
* @param next {NextFunction} - The Express `next` function, can be called to skip responding.
|
||||
* @param optionsUsed {Options} - The options used to set up the middleware.
|
||||
*/
|
||||
export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void;
|
||||
/**
|
||||
* Event callback that is triggered on a client's first request that exceeds the limit
|
||||
* but not for subsequent requests. May be used for logging, etc. Should *not*
|
||||
* send a response.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
* @param optionsUsed {Options} - The options used to set up the middleware.
|
||||
*/
|
||||
export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void;
|
||||
/**
|
||||
* Data returned from the `Store` when a client's hit counter is incremented.
|
||||
*
|
||||
* @property totalHits {number} - The number of hits for that client so far.
|
||||
* @property resetTime {Date | undefined} - The time when the counter resets.
|
||||
*/
|
||||
export type ClientRateLimitInfo = {
|
||||
totalHits: number;
|
||||
resetTime: Date | undefined;
|
||||
};
|
||||
export type IncrementResponse = ClientRateLimitInfo;
|
||||
/**
|
||||
* A modified Express request handler with the rate limit functions.
|
||||
*/
|
||||
export type RateLimitRequestHandler = RequestHandler & {
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => void;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*/
|
||||
getKey: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
|
||||
};
|
||||
/**
|
||||
* An interface that all hit counter stores must implement.
|
||||
*
|
||||
* @deprecated 6.x - Implement the `Store` interface instead.
|
||||
*/
|
||||
export type LegacyStore = {
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
* @param callback {IncrementCallback} - The callback to call once the counter is incremented.
|
||||
*/
|
||||
incr: (key: string, callback: IncrementCallback) => void;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
decrement: (key: string) => void;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => void;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*/
|
||||
resetAll?: () => void;
|
||||
};
|
||||
/**
|
||||
* An interface that all hit counter stores must implement.
|
||||
*/
|
||||
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 | Promise<void>;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*/
|
||||
get?: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {IncrementResponse | undefined} - The number of hits and reset time for that client.
|
||||
*/
|
||||
increment: (key: string) => Promise<IncrementResponse> | IncrementResponse;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
decrement: (key: string) => Promise<void> | void;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => Promise<void> | void;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*/
|
||||
resetAll?: () => Promise<void> | void;
|
||||
/**
|
||||
* Method to shutdown the store, stop timers, and release all resources.
|
||||
*/
|
||||
shutdown?: () => Promise<void> | void;
|
||||
/**
|
||||
* Flag to indicate that keys incremented in one instance of this store can
|
||||
* not affect other instances. Typically false if a database is used, true for
|
||||
* MemoryStore.
|
||||
*
|
||||
* Used to help detect double-counting misconfigurations.
|
||||
*/
|
||||
localKeys?: boolean;
|
||||
/**
|
||||
* Optional value that the store prepends to keys
|
||||
*
|
||||
* Used by the double-count check to avoid false-positives when a key is counted
|
||||
* twice, but with different prefixes.
|
||||
*/
|
||||
prefix?: string;
|
||||
};
|
||||
export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number];
|
||||
/**
|
||||
* Validate configuration object for enabling or disabling specific validations.
|
||||
*
|
||||
* The keys must also be keys in the validations object, except `enable`, `disable`,
|
||||
* and `default`.
|
||||
*/
|
||||
export type EnabledValidations = {
|
||||
[key in keyof Omit<Validations, "enabled" | "disable"> | "default"]?: boolean;
|
||||
};
|
||||
/**
|
||||
* The configuration options for the rate limiter.
|
||||
*/
|
||||
export type Options = {
|
||||
/**
|
||||
* How long we should remember the requests.
|
||||
*
|
||||
* Defaults to `60000` ms (= 1 minute).
|
||||
*/
|
||||
windowMs: number;
|
||||
/**
|
||||
* The maximum number of connections to allow during the `window` before
|
||||
* rate limiting the client.
|
||||
*
|
||||
* Can be the limit itself as a number or express middleware that parses
|
||||
* the request and then figures out the limit.
|
||||
*
|
||||
* Defaults to `5`.
|
||||
*/
|
||||
limit: number | ValueDeterminingMiddleware<number>;
|
||||
/**
|
||||
* The response body to send back when a client is rate limited.
|
||||
*
|
||||
* Defaults to `'Too many requests, please try again later.'`
|
||||
*/
|
||||
message: any | ValueDeterminingMiddleware<any>;
|
||||
/**
|
||||
* The HTTP status code to send back when a client is rate limited.
|
||||
*
|
||||
* Defaults to `HTTP 429 Too Many Requests` (RFC 6585).
|
||||
*/
|
||||
statusCode: number;
|
||||
/**
|
||||
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
|
||||
* of requests.
|
||||
*
|
||||
* Defaults to `true` (for backward compatibility).
|
||||
*/
|
||||
legacyHeaders: boolean;
|
||||
/**
|
||||
* Whether to enable support for the standardized rate limit headers (`RateLimit-*`).
|
||||
*
|
||||
* Defaults to `false` (for backward compatibility, but its use is recommended).
|
||||
*/
|
||||
standardHeaders: boolean | DraftHeadersVersion;
|
||||
/**
|
||||
* The name used to identify the quota policy in the `RateLimit` headers as per
|
||||
* the 8th draft of the IETF specification.
|
||||
*
|
||||
* Defaults to `{limit}-in-{window}`.
|
||||
*/
|
||||
identifier: string | ValueDeterminingMiddleware<string>;
|
||||
/**
|
||||
* The name of the property on the request object to store the rate limit info.
|
||||
*
|
||||
* Defaults to `rateLimit`.
|
||||
*/
|
||||
requestPropertyName: string;
|
||||
/**
|
||||
* If `true`, the library will (by default) skip all requests that have a 4XX
|
||||
* or 5XX status.
|
||||
*
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
skipFailedRequests: boolean;
|
||||
/**
|
||||
* If `true`, the library will (by default) skip all requests that have a
|
||||
* status code less than 400.
|
||||
*
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
skipSuccessfulRequests: boolean;
|
||||
/**
|
||||
* Method to generate custom identifiers for clients.
|
||||
*
|
||||
* By default, the client's IP address is used.
|
||||
*/
|
||||
keyGenerator: ValueDeterminingMiddleware<string>;
|
||||
/**
|
||||
* IPv6 subnet mask applied to IPv6 addresses in the default keyGenerator.
|
||||
*
|
||||
* Default is 56. The valid range is technically 1-128 but the value should
|
||||
* generally be in the 32-64 range.
|
||||
*
|
||||
* Smaller numbers are more aggressive, larger numbers are more lenient. Try
|
||||
* bumping to 60 or 64 if you see evidence of users being blocked incorrectly.
|
||||
*
|
||||
* May also be set to a function that returns a number based on the request.
|
||||
*
|
||||
* See the documentation for more info:
|
||||
* https://express-rate-limit.mintlify.app/reference/configuration#ipv6subnet.
|
||||
*/
|
||||
ipv6Subnet: 64 | 60 | 56 | 52 | 50 | 48 | 32 | number | ValueDeterminingMiddleware<number> | false;
|
||||
/**
|
||||
* Express request handler that sends back a response when a client is
|
||||
* rate-limited.
|
||||
*
|
||||
* By default, sends back the `statusCode` and `message` set via the options.
|
||||
*/
|
||||
handler: RateLimitExceededEventHandler;
|
||||
/**
|
||||
* Method (in the form of middleware) to determine whether or not this request
|
||||
* counts towards a client's quota.
|
||||
*
|
||||
* By default, skips no requests.
|
||||
*/
|
||||
skip: ValueDeterminingMiddleware<boolean>;
|
||||
/**
|
||||
* Method to determine whether or not the request counts as 'successful'. Used
|
||||
* when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true.
|
||||
*
|
||||
* By default, requests with a response status code less than 400 are considered
|
||||
* successful.
|
||||
*/
|
||||
requestWasSuccessful: ValueDeterminingMiddleware<boolean>;
|
||||
/**
|
||||
* The `Store` to use to store the hit count for each client.
|
||||
*
|
||||
* By default, the built-in `MemoryStore` will be used.
|
||||
*/
|
||||
store: Store | LegacyStore;
|
||||
/**
|
||||
* The list of validation checks that should run.
|
||||
*/
|
||||
validate: boolean | EnabledValidations;
|
||||
/**
|
||||
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
|
||||
* of requests.
|
||||
*
|
||||
* @deprecated 6.x - This option was renamed to `legacyHeaders`.
|
||||
*/
|
||||
headers?: boolean;
|
||||
/**
|
||||
* The maximum number of connections to allow during the `window` before
|
||||
* rate limiting the client.
|
||||
*
|
||||
* Can be the limit itself as a number or express middleware that parses
|
||||
* the request and then figures out the limit.
|
||||
*
|
||||
* @deprecated 7.x - This option was renamed to `limit`. However, it will not
|
||||
* be removed from the library in the foreseeable future.
|
||||
*/
|
||||
max?: number | ValueDeterminingMiddleware<number>;
|
||||
/**
|
||||
* 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
|
||||
* rate limit.
|
||||
*/
|
||||
export type AugmentedRequest = Request & {
|
||||
[key: string]: RateLimitInfo;
|
||||
};
|
||||
/**
|
||||
* The rate limit related information for each client included in the
|
||||
* Express request object.
|
||||
*/
|
||||
export type RateLimitInfo = {
|
||||
limit: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
resetTime: Date | undefined;
|
||||
key: string;
|
||||
};
|
||||
/**
|
||||
* The record that stores information about a client - namely, how many times
|
||||
* they have hit the endpoint, and when their hit count resets.
|
||||
*
|
||||
* Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field.
|
||||
*/
|
||||
export type Client = {
|
||||
totalHits: number;
|
||||
resetTime: Date;
|
||||
};
|
||||
/**
|
||||
* A `Store` that stores the hit count for each client in memory.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare class MemoryStore implements Store {
|
||||
private validations?;
|
||||
/**
|
||||
* The duration of time before which all hit counts are reset (in milliseconds).
|
||||
*/
|
||||
windowMs: number;
|
||||
/**
|
||||
* These two maps store usage (requests) and reset time by key (for example, IP
|
||||
* addresses or API keys).
|
||||
*
|
||||
* They are split into two to avoid having to iterate through the entire set to
|
||||
* determine which ones need reset. Instead, `Client`s are moved from `previous`
|
||||
* to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
|
||||
* left in `previous`, i.e., those that have not made any recent requests, are
|
||||
* known to be expired and can be deleted in bulk.
|
||||
*/
|
||||
previous: Map<string, Client>;
|
||||
current: Map<string, Client>;
|
||||
/**
|
||||
* A reference to the active timer.
|
||||
*/
|
||||
interval?: NodeJS.Timeout;
|
||||
/**
|
||||
* Confirmation that the keys incremented in once instance of MemoryStore
|
||||
* cannot affect other instances.
|
||||
*/
|
||||
localKeys: boolean;
|
||||
constructor(validations?: Validations | undefined);
|
||||
/**
|
||||
* Method that initializes the store.
|
||||
*
|
||||
* @param options {Options} - The options used to setup the middleware.
|
||||
*/
|
||||
init(options: Options): void;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
get(key: string): Promise<ClientRateLimitInfo | undefined>;
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
increment(key: string): Promise<ClientRateLimitInfo>;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
decrement(key: string): Promise<void>;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
resetKey(key: string): Promise<void>;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
resetAll(): Promise<void>;
|
||||
/**
|
||||
* Method to stop the timer (if currently running) and prevent any memory
|
||||
* leaks.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
shutdown(): void;
|
||||
/**
|
||||
* Recycles a client by setting its hit count to zero, and reset time to
|
||||
* `windowMs` milliseconds from now.
|
||||
*
|
||||
* NOT to be confused with `#resetKey()`, which removes a client from both the
|
||||
* `current` and `previous` maps.
|
||||
*
|
||||
* @param client {Client} - The client to recycle.
|
||||
* @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
|
||||
*
|
||||
* @return {Client} - The modified client that was passed in, to allow for chaining.
|
||||
*/
|
||||
private resetClient;
|
||||
/**
|
||||
* Retrieves or creates a client, given a key. Also ensures that the client being
|
||||
* returned is in the `current` map.
|
||||
*
|
||||
* @param key {string} - The key under which the client is (or is to be) stored.
|
||||
*
|
||||
* @returns {Client} - The requested client.
|
||||
*/
|
||||
private getClient;
|
||||
/**
|
||||
* Move current clients to previous, create a new map for current.
|
||||
*
|
||||
* This function is called every `windowMs`.
|
||||
*/
|
||||
private clearExpired;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* Create an instance of IP rate-limiting middleware for Express.
|
||||
*
|
||||
* @param passedOptions {Options} - Options to configure the rate limiter.
|
||||
*
|
||||
* @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare const rateLimit: (passedOptions?: Partial<Options>) => RateLimitRequestHandler;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const SECOND: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const MINUTE: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const HOUR: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const DAY: number;
|
||||
|
||||
export {
|
||||
rateLimit as default,
|
||||
};
|
||||
|
||||
export {};
|
||||
+688
@@ -0,0 +1,688 @@
|
||||
// Generated by dts-bundle-generator v8.1.2
|
||||
|
||||
import { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
|
||||
/**
|
||||
* Returns the IP address itself for IPv4, or a CIDR-notation subnet for IPv6.
|
||||
*
|
||||
* If you write a custom keyGenerator that allows a fallback to IP address for
|
||||
* unauthenticated users, return ipKeyGenerator(req.ip) rather than just req.ip.
|
||||
*
|
||||
* For more information, {@see Options.ipv6Subnet}.
|
||||
*
|
||||
* @param ip {string} - The IP address to process, usually request.ip.
|
||||
* @param ipv6Subnet {number | false} - The subnet mask for IPv6 addresses.
|
||||
*
|
||||
* @returns {string} - The key generated from the IP address
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare function ipKeyGenerator(ip: string, ipv6Subnet?: number | false): string;
|
||||
declare const SUPPORTED_DRAFT_VERSIONS: readonly [
|
||||
"draft-6",
|
||||
"draft-7",
|
||||
"draft-8"
|
||||
];
|
||||
declare const validations: {
|
||||
enabled: {
|
||||
[key: string]: boolean;
|
||||
};
|
||||
disable(): void;
|
||||
/**
|
||||
* Checks whether the IP address is valid, and that it does not have a port
|
||||
* number in it.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
|
||||
*
|
||||
* @param ip {string | undefined} - The IP address provided by Express as request.ip.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
ip(ip: string | undefined): void;
|
||||
/**
|
||||
* Makes sure the trust proxy setting is not set to `true`.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
trustProxy(request: Request): void;
|
||||
/**
|
||||
* Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
|
||||
* header is present.
|
||||
*
|
||||
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
xForwardedForHeader(request: Request): void;
|
||||
/**
|
||||
* Alert the user if the Forwarded header is set (standardized version of X-Forwarded-For - not supported by express as of version 5.1.0)
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
forwardedHeader(request: Request): void;
|
||||
/**
|
||||
* Ensures totalHits value from store is a positive integer.
|
||||
*
|
||||
* @param hits {any} - The `totalHits` returned by the store.
|
||||
*/
|
||||
positiveHits(hits: any): void;
|
||||
/**
|
||||
* Ensures a single store instance is not used with multiple express-rate-limit instances
|
||||
*/
|
||||
unsharedStore(store: Store): void;
|
||||
/**
|
||||
* Ensures a given key is incremented only once per request.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param store {Store} - The store class.
|
||||
* @param key {string} - The key used to store the client's hit count.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
singleCount(request: Request, store: Store, key: string): void;
|
||||
/**
|
||||
* Warns the user that the behaviour for `max: 0` / `limit: 0` is
|
||||
* changing in the next major release.
|
||||
*
|
||||
* @param limit {number} - The maximum number of hits per client.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
limit(limit: number): void;
|
||||
/**
|
||||
* Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
|
||||
* and will be removed in the next major release.
|
||||
*
|
||||
* @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
draftPolliHeaders(draft_polli_ratelimit_headers?: any): void;
|
||||
/**
|
||||
* Warns the user that the `onLimitReached` option is deprecated and
|
||||
* will be removed in the next major release.
|
||||
*
|
||||
* @param onLimitReached {any | undefined} - The maximum number of hits per client.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
onLimitReached(onLimitReached?: any): void;
|
||||
/**
|
||||
* Warns the user when an invalid/unsupported version of the draft spec is passed.
|
||||
*
|
||||
* @param version {any | undefined} - The version passed by the user.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
headersDraftVersion(version?: any): void;
|
||||
/**
|
||||
* Warns the user when the selected headers option requires a reset time but
|
||||
* the store does not provide one.
|
||||
*
|
||||
* @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
headersResetTime(resetTime?: Date): void;
|
||||
knownOptions(passedOptions?: Partial<Options>): void;
|
||||
/**
|
||||
* Checks the options.validate setting to ensure that only recognized
|
||||
* validations are enabled or disabled.
|
||||
*
|
||||
* If any unrecognized values are found, an error is logged that
|
||||
* includes the list of supported validations.
|
||||
*/
|
||||
validationsConfig(): void;
|
||||
/**
|
||||
* Checks to see if the instance was created inside of a request handler,
|
||||
* which would prevent it from working correctly, with the default memory
|
||||
* store (or any other store with localKeys.)
|
||||
*/
|
||||
creationStack(store: Store): void;
|
||||
ipv6Subnet(ipv6Subnet?: any): void;
|
||||
ipv6SubnetOrKeyGenerator(options: Partial<Options>): void;
|
||||
keyGeneratorIpFallback(keyGenerator?: ValueDeterminingMiddleware<string>): void;
|
||||
/**
|
||||
* Checks to see if the window duration is greater than 2^32 - 1. This is only
|
||||
* called by the default MemoryStore, since it uses Node's setInterval method.
|
||||
*
|
||||
* See https://nodejs.org/api/timers.html#setintervalcallback-delay-args.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @param error {Error | undefined} - The error that occurred, if any.
|
||||
* @param totalHits {number} - The number of hits for that client so far.
|
||||
* @param resetTime {Date | undefined} - The time when the counter resets.
|
||||
*/
|
||||
export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void;
|
||||
/**
|
||||
* Method (in the form of middleware) to generate/retrieve a value based on the
|
||||
* incoming request.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
*
|
||||
* @returns {T} - The value needed.
|
||||
*/
|
||||
export type ValueDeterminingMiddleware<T> = (request: Request, response: Response) => T | Promise<T>;
|
||||
/**
|
||||
* Express request handler that sends back a response when a client is
|
||||
* rate-limited.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
* @param next {NextFunction} - The Express `next` function, can be called to skip responding.
|
||||
* @param optionsUsed {Options} - The options used to set up the middleware.
|
||||
*/
|
||||
export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void;
|
||||
/**
|
||||
* Event callback that is triggered on a client's first request that exceeds the limit
|
||||
* but not for subsequent requests. May be used for logging, etc. Should *not*
|
||||
* send a response.
|
||||
*
|
||||
* @param request {Request} - The Express request object.
|
||||
* @param response {Response} - The Express response object.
|
||||
* @param optionsUsed {Options} - The options used to set up the middleware.
|
||||
*/
|
||||
export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void;
|
||||
/**
|
||||
* Data returned from the `Store` when a client's hit counter is incremented.
|
||||
*
|
||||
* @property totalHits {number} - The number of hits for that client so far.
|
||||
* @property resetTime {Date | undefined} - The time when the counter resets.
|
||||
*/
|
||||
export type ClientRateLimitInfo = {
|
||||
totalHits: number;
|
||||
resetTime: Date | undefined;
|
||||
};
|
||||
export type IncrementResponse = ClientRateLimitInfo;
|
||||
/**
|
||||
* A modified Express request handler with the rate limit functions.
|
||||
*/
|
||||
export type RateLimitRequestHandler = RequestHandler & {
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => void;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*/
|
||||
getKey: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
|
||||
};
|
||||
/**
|
||||
* An interface that all hit counter stores must implement.
|
||||
*
|
||||
* @deprecated 6.x - Implement the `Store` interface instead.
|
||||
*/
|
||||
export type LegacyStore = {
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
* @param callback {IncrementCallback} - The callback to call once the counter is incremented.
|
||||
*/
|
||||
incr: (key: string, callback: IncrementCallback) => void;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
decrement: (key: string) => void;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => void;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*/
|
||||
resetAll?: () => void;
|
||||
};
|
||||
/**
|
||||
* An interface that all hit counter stores must implement.
|
||||
*/
|
||||
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 | Promise<void>;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*/
|
||||
get?: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {IncrementResponse | undefined} - The number of hits and reset time for that client.
|
||||
*/
|
||||
increment: (key: string) => Promise<IncrementResponse> | IncrementResponse;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
decrement: (key: string) => Promise<void> | void;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*/
|
||||
resetKey: (key: string) => Promise<void> | void;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*/
|
||||
resetAll?: () => Promise<void> | void;
|
||||
/**
|
||||
* Method to shutdown the store, stop timers, and release all resources.
|
||||
*/
|
||||
shutdown?: () => Promise<void> | void;
|
||||
/**
|
||||
* Flag to indicate that keys incremented in one instance of this store can
|
||||
* not affect other instances. Typically false if a database is used, true for
|
||||
* MemoryStore.
|
||||
*
|
||||
* Used to help detect double-counting misconfigurations.
|
||||
*/
|
||||
localKeys?: boolean;
|
||||
/**
|
||||
* Optional value that the store prepends to keys
|
||||
*
|
||||
* Used by the double-count check to avoid false-positives when a key is counted
|
||||
* twice, but with different prefixes.
|
||||
*/
|
||||
prefix?: string;
|
||||
};
|
||||
export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number];
|
||||
/**
|
||||
* Validate configuration object for enabling or disabling specific validations.
|
||||
*
|
||||
* The keys must also be keys in the validations object, except `enable`, `disable`,
|
||||
* and `default`.
|
||||
*/
|
||||
export type EnabledValidations = {
|
||||
[key in keyof Omit<Validations, "enabled" | "disable"> | "default"]?: boolean;
|
||||
};
|
||||
/**
|
||||
* The configuration options for the rate limiter.
|
||||
*/
|
||||
export type Options = {
|
||||
/**
|
||||
* How long we should remember the requests.
|
||||
*
|
||||
* Defaults to `60000` ms (= 1 minute).
|
||||
*/
|
||||
windowMs: number;
|
||||
/**
|
||||
* The maximum number of connections to allow during the `window` before
|
||||
* rate limiting the client.
|
||||
*
|
||||
* Can be the limit itself as a number or express middleware that parses
|
||||
* the request and then figures out the limit.
|
||||
*
|
||||
* Defaults to `5`.
|
||||
*/
|
||||
limit: number | ValueDeterminingMiddleware<number>;
|
||||
/**
|
||||
* The response body to send back when a client is rate limited.
|
||||
*
|
||||
* Defaults to `'Too many requests, please try again later.'`
|
||||
*/
|
||||
message: any | ValueDeterminingMiddleware<any>;
|
||||
/**
|
||||
* The HTTP status code to send back when a client is rate limited.
|
||||
*
|
||||
* Defaults to `HTTP 429 Too Many Requests` (RFC 6585).
|
||||
*/
|
||||
statusCode: number;
|
||||
/**
|
||||
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
|
||||
* of requests.
|
||||
*
|
||||
* Defaults to `true` (for backward compatibility).
|
||||
*/
|
||||
legacyHeaders: boolean;
|
||||
/**
|
||||
* Whether to enable support for the standardized rate limit headers (`RateLimit-*`).
|
||||
*
|
||||
* Defaults to `false` (for backward compatibility, but its use is recommended).
|
||||
*/
|
||||
standardHeaders: boolean | DraftHeadersVersion;
|
||||
/**
|
||||
* The name used to identify the quota policy in the `RateLimit` headers as per
|
||||
* the 8th draft of the IETF specification.
|
||||
*
|
||||
* Defaults to `{limit}-in-{window}`.
|
||||
*/
|
||||
identifier: string | ValueDeterminingMiddleware<string>;
|
||||
/**
|
||||
* The name of the property on the request object to store the rate limit info.
|
||||
*
|
||||
* Defaults to `rateLimit`.
|
||||
*/
|
||||
requestPropertyName: string;
|
||||
/**
|
||||
* If `true`, the library will (by default) skip all requests that have a 4XX
|
||||
* or 5XX status.
|
||||
*
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
skipFailedRequests: boolean;
|
||||
/**
|
||||
* If `true`, the library will (by default) skip all requests that have a
|
||||
* status code less than 400.
|
||||
*
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
skipSuccessfulRequests: boolean;
|
||||
/**
|
||||
* Method to generate custom identifiers for clients.
|
||||
*
|
||||
* By default, the client's IP address is used.
|
||||
*/
|
||||
keyGenerator: ValueDeterminingMiddleware<string>;
|
||||
/**
|
||||
* IPv6 subnet mask applied to IPv6 addresses in the default keyGenerator.
|
||||
*
|
||||
* Default is 56. The valid range is technically 1-128 but the value should
|
||||
* generally be in the 32-64 range.
|
||||
*
|
||||
* Smaller numbers are more aggressive, larger numbers are more lenient. Try
|
||||
* bumping to 60 or 64 if you see evidence of users being blocked incorrectly.
|
||||
*
|
||||
* May also be set to a function that returns a number based on the request.
|
||||
*
|
||||
* See the documentation for more info:
|
||||
* https://express-rate-limit.mintlify.app/reference/configuration#ipv6subnet.
|
||||
*/
|
||||
ipv6Subnet: 64 | 60 | 56 | 52 | 50 | 48 | 32 | number | ValueDeterminingMiddleware<number> | false;
|
||||
/**
|
||||
* Express request handler that sends back a response when a client is
|
||||
* rate-limited.
|
||||
*
|
||||
* By default, sends back the `statusCode` and `message` set via the options.
|
||||
*/
|
||||
handler: RateLimitExceededEventHandler;
|
||||
/**
|
||||
* Method (in the form of middleware) to determine whether or not this request
|
||||
* counts towards a client's quota.
|
||||
*
|
||||
* By default, skips no requests.
|
||||
*/
|
||||
skip: ValueDeterminingMiddleware<boolean>;
|
||||
/**
|
||||
* Method to determine whether or not the request counts as 'successful'. Used
|
||||
* when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true.
|
||||
*
|
||||
* By default, requests with a response status code less than 400 are considered
|
||||
* successful.
|
||||
*/
|
||||
requestWasSuccessful: ValueDeterminingMiddleware<boolean>;
|
||||
/**
|
||||
* The `Store` to use to store the hit count for each client.
|
||||
*
|
||||
* By default, the built-in `MemoryStore` will be used.
|
||||
*/
|
||||
store: Store | LegacyStore;
|
||||
/**
|
||||
* The list of validation checks that should run.
|
||||
*/
|
||||
validate: boolean | EnabledValidations;
|
||||
/**
|
||||
* Whether to send `X-RateLimit-*` headers with the rate limit and the number
|
||||
* of requests.
|
||||
*
|
||||
* @deprecated 6.x - This option was renamed to `legacyHeaders`.
|
||||
*/
|
||||
headers?: boolean;
|
||||
/**
|
||||
* The maximum number of connections to allow during the `window` before
|
||||
* rate limiting the client.
|
||||
*
|
||||
* Can be the limit itself as a number or express middleware that parses
|
||||
* the request and then figures out the limit.
|
||||
*
|
||||
* @deprecated 7.x - This option was renamed to `limit`. However, it will not
|
||||
* be removed from the library in the foreseeable future.
|
||||
*/
|
||||
max?: number | ValueDeterminingMiddleware<number>;
|
||||
/**
|
||||
* 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
|
||||
* rate limit.
|
||||
*/
|
||||
export type AugmentedRequest = Request & {
|
||||
[key: string]: RateLimitInfo;
|
||||
};
|
||||
/**
|
||||
* The rate limit related information for each client included in the
|
||||
* Express request object.
|
||||
*/
|
||||
export type RateLimitInfo = {
|
||||
limit: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
resetTime: Date | undefined;
|
||||
key: string;
|
||||
};
|
||||
/**
|
||||
* The record that stores information about a client - namely, how many times
|
||||
* they have hit the endpoint, and when their hit count resets.
|
||||
*
|
||||
* Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field.
|
||||
*/
|
||||
export type Client = {
|
||||
totalHits: number;
|
||||
resetTime: Date;
|
||||
};
|
||||
/**
|
||||
* A `Store` that stores the hit count for each client in memory.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare class MemoryStore implements Store {
|
||||
private validations?;
|
||||
/**
|
||||
* The duration of time before which all hit counts are reset (in milliseconds).
|
||||
*/
|
||||
windowMs: number;
|
||||
/**
|
||||
* These two maps store usage (requests) and reset time by key (for example, IP
|
||||
* addresses or API keys).
|
||||
*
|
||||
* They are split into two to avoid having to iterate through the entire set to
|
||||
* determine which ones need reset. Instead, `Client`s are moved from `previous`
|
||||
* to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
|
||||
* left in `previous`, i.e., those that have not made any recent requests, are
|
||||
* known to be expired and can be deleted in bulk.
|
||||
*/
|
||||
previous: Map<string, Client>;
|
||||
current: Map<string, Client>;
|
||||
/**
|
||||
* A reference to the active timer.
|
||||
*/
|
||||
interval?: NodeJS.Timeout;
|
||||
/**
|
||||
* Confirmation that the keys incremented in once instance of MemoryStore
|
||||
* cannot affect other instances.
|
||||
*/
|
||||
localKeys: boolean;
|
||||
constructor(validations?: Validations | undefined);
|
||||
/**
|
||||
* Method that initializes the store.
|
||||
*
|
||||
* @param options {Options} - The options used to setup the middleware.
|
||||
*/
|
||||
init(options: Options): void;
|
||||
/**
|
||||
* Method to fetch a client's hit count and reset time.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
get(key: string): Promise<ClientRateLimitInfo | undefined>;
|
||||
/**
|
||||
* Method to increment a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
increment(key: string): Promise<ClientRateLimitInfo>;
|
||||
/**
|
||||
* Method to decrement a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
decrement(key: string): Promise<void>;
|
||||
/**
|
||||
* Method to reset a client's hit counter.
|
||||
*
|
||||
* @param key {string} - The identifier for a client.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
resetKey(key: string): Promise<void>;
|
||||
/**
|
||||
* Method to reset everyone's hit counter.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
resetAll(): Promise<void>;
|
||||
/**
|
||||
* Method to stop the timer (if currently running) and prevent any memory
|
||||
* leaks.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
shutdown(): void;
|
||||
/**
|
||||
* Recycles a client by setting its hit count to zero, and reset time to
|
||||
* `windowMs` milliseconds from now.
|
||||
*
|
||||
* NOT to be confused with `#resetKey()`, which removes a client from both the
|
||||
* `current` and `previous` maps.
|
||||
*
|
||||
* @param client {Client} - The client to recycle.
|
||||
* @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
|
||||
*
|
||||
* @return {Client} - The modified client that was passed in, to allow for chaining.
|
||||
*/
|
||||
private resetClient;
|
||||
/**
|
||||
* Retrieves or creates a client, given a key. Also ensures that the client being
|
||||
* returned is in the `current` map.
|
||||
*
|
||||
* @param key {string} - The key under which the client is (or is to be) stored.
|
||||
*
|
||||
* @returns {Client} - The requested client.
|
||||
*/
|
||||
private getClient;
|
||||
/**
|
||||
* Move current clients to previous, create a new map for current.
|
||||
*
|
||||
* This function is called every `windowMs`.
|
||||
*/
|
||||
private clearExpired;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* Create an instance of IP rate-limiting middleware for Express.
|
||||
*
|
||||
* @param passedOptions {Options} - Options to configure the rate limiter.
|
||||
*
|
||||
* @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare const rateLimit: (passedOptions?: Partial<Options>) => RateLimitRequestHandler;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const SECOND: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const MINUTE: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const HOUR: number;
|
||||
/**
|
||||
* @deprecated these are being replaced in the next major version
|
||||
*/
|
||||
export declare const DAY: number;
|
||||
|
||||
export {
|
||||
rateLimit as default,
|
||||
};
|
||||
|
||||
export {};
|
||||
+1036
File diff suppressed because it is too large
Load Diff
+20
@@ -0,0 +1,20 @@
|
||||
# MIT License
|
||||
|
||||
Copyright 2023 Nathan Friedly, Vedant K
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
{
|
||||
"name": "express-rate-limit",
|
||||
"version": "8.6.1",
|
||||
"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",
|
||||
"url": "http://nfriedly.com/"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/express-rate-limit/express-rate-limit",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/express-rate-limit/express-rate-limit.git"
|
||||
},
|
||||
"funding": "https://github.com/sponsors/express-rate-limit",
|
||||
"keywords": [
|
||||
"express-rate-limit",
|
||||
"express",
|
||||
"rate",
|
||||
"limit",
|
||||
"ratelimit",
|
||||
"rate-limit",
|
||||
"middleware",
|
||||
"ip",
|
||||
"auth",
|
||||
"authorization",
|
||||
"security",
|
||||
"brute",
|
||||
"force",
|
||||
"bruteforce",
|
||||
"brute-force",
|
||||
"attack"
|
||||
],
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.cts",
|
||||
"default": "./dist/index.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist/",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "del-cli dist/ coverage/ *.log *.tmp *.bak *.tgz",
|
||||
"build:cjs": "esbuild --packages=external --platform=node --bundle --target=es2022 --format=cjs --outfile=dist/index.cjs --footer:js=\"module.exports = Object.assign(rateLimit, module.exports);\" source/index.ts",
|
||||
"build:esm": "esbuild --packages=external --platform=node --bundle --target=es2022 --format=esm --outfile=dist/index.mjs source/index.ts",
|
||||
"build:types": "dts-bundle-generator --out-file=dist/index.d.ts source/index.ts && cp dist/index.d.ts dist/index.d.cts && cp dist/index.d.ts dist/index.d.mts",
|
||||
"compile": "run-s clean build:*",
|
||||
"docs": "cd docs && mintlify dev",
|
||||
"lint:code": "biome check",
|
||||
"lint:docs": "prettier --check docs/ *.md",
|
||||
"lint": "run-s lint:*",
|
||||
"format:code": "biome check --write",
|
||||
"format:docs": "prettier --write docs/ *.md",
|
||||
"format": "run-s format:*",
|
||||
"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": {
|
||||
"debug": "^4.4.3",
|
||||
"ip-address": "^10.2.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"express": ">= 4.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@asyncapi/specs": "6.11.1",
|
||||
"@biomejs/biome": "2.4.6",
|
||||
"@express-rate-limit/prettier": "1.1.1",
|
||||
"@express-rate-limit/tsconfig": "1.0.5",
|
||||
"@jest/globals": "30.4.1",
|
||||
"@types/debug": "4.1.13",
|
||||
"@types/express": "5.0.6",
|
||||
"@types/jest": "30.0.0",
|
||||
"@types/node": "26.1.1",
|
||||
"@types/supertest": "7.2.1",
|
||||
"del-cli": "7.0.0",
|
||||
"dts-bundle-generator": "8.1.2",
|
||||
"esbuild": "0.28.1",
|
||||
"express": "5.2.1",
|
||||
"husky": "9.1.7",
|
||||
"jest": "30.4.2",
|
||||
"lint-staged": "17.1.0",
|
||||
"mintlify": "4.2.715",
|
||||
"npm-run-all": "4.1.5",
|
||||
"prettier": "3.9.5",
|
||||
"ratelimit-header-parser": "0.1.0",
|
||||
"supertest": "7.2.2",
|
||||
"ts-jest": "29.4.11",
|
||||
"ts-node": "10.9.2",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"prettier": "@express-rate-limit/prettier",
|
||||
"lint-staged": {
|
||||
"*.{js,ts,json}": "biome check --write",
|
||||
"*.{md,yaml}": "prettier --write"
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
<h1 align="center"> <code>express-rate-limit</code> </h1>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/express-rate-limit/express-rate-limit/actions/workflows/ci.yaml)
|
||||
[](https://npmjs.org/package/express-rate-limit 'View this project on NPM')
|
||||
[](https://www.npmjs.com/package/express-rate-limit)
|
||||
[](license.md)
|
||||
|
||||
</div>
|
||||
|
||||
Basic rate-limiting middleware for [Express](http://expressjs.com/). Use to
|
||||
limit repeated requests to public APIs and/or endpoints such as password reset.
|
||||
Plays nice with
|
||||
[express-slow-down](https://www.npmjs.com/package/express-slow-down) and
|
||||
[ratelimit-header-parser](https://www.npmjs.com/package/ratelimit-header-parser).
|
||||
|
||||
## Usage
|
||||
|
||||
The [full documentation](https://express-rate-limit.mintlify.app/overview) is
|
||||
available on-line.
|
||||
|
||||
```ts
|
||||
import { rateLimit } from 'express-rate-limit'
|
||||
|
||||
const limiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
|
||||
standardHeaders: 'draft-8', // draft-6: `RateLimit-*` headers; draft-7 & draft-8: combined `RateLimit` header
|
||||
legacyHeaders: false, // Disable the `X-RateLimit-*` headers.
|
||||
ipv6Subnet: 56, // Set to 60 or 64 to be less aggressive, or 52 or 48 to be more aggressive
|
||||
// store: ... , // Redis, Memcached, etc. See below.
|
||||
})
|
||||
|
||||
// Apply the rate limiting middleware to all requests.
|
||||
app.use(limiter)
|
||||
```
|
||||
|
||||
### Data Stores
|
||||
|
||||
The rate limiter comes with a built-in memory store, and supports a variety of
|
||||
[external data stores](https://express-rate-limit.mintlify.app/reference/stores).
|
||||
|
||||
### Configuration
|
||||
|
||||
All function options may be async. Click the name for additional info and
|
||||
default values.
|
||||
|
||||
| Option | Type | Remarks |
|
||||
| -------------------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| [`windowMs`] | `number` | How long to remember requests for, in milliseconds. |
|
||||
| [`limit`] | `number` \| `function` | How many requests to allow. |
|
||||
| [`message`] | `string` \| `json` \| `function` | Response to return after limit is reached. |
|
||||
| [`statusCode`] | `number` | HTTP status code after limit is reached (default is 429). |
|
||||
| [`handler`] | `function` | Function to run after limit is reached (overrides `message` and `statusCode` settings, if set). |
|
||||
| [`legacyHeaders`] | `boolean` | Enable the `X-Rate-Limit` header. |
|
||||
| [`standardHeaders`] | `'draft-6'` \| `'draft-7'` \| `'draft-8'` | Enable the `Ratelimit` header. |
|
||||
| [`identifier`] | `string` \| `function` | Name associated with the quota policy enforced by this rate limiter. |
|
||||
| [`store`] | `Store` | Use a custom store to share hit counts across multiple nodes. |
|
||||
| [`passOnStoreError`] | `boolean` | Allow (`true`) or block (`false`, default) traffic if the store becomes unavailable. |
|
||||
| [`keyGenerator`] | `function` | Identify users (defaults to IP address). |
|
||||
| [`ipv6Subnet`] | `number` (32-64) \| `function` \| `false` | How many bits of IPv6 addresses to use in default `keyGenerator` |
|
||||
| [`requestPropertyName`] | `string` | Add rate limit info to the `req` object. |
|
||||
| [`skip`] | `function` | Return `true` to bypass the limiter for the given request. |
|
||||
| [`skipSuccessfulRequests`] | `boolean` | Uncount 1xx/2xx/3xx responses. |
|
||||
| [`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
|
||||
|
||||
---
|
||||
|
||||
Thanks to Mintlify for hosting the documentation at
|
||||
[express-rate-limit.mintlify.app](https://express-rate-limit.mintlify.app)
|
||||
|
||||
<p align="center">
|
||||
<a href="https://mintlify.com/?utm_campaign=devmark&utm_medium=readme&utm_source=express-rate-limit">
|
||||
<img height="75" src="https://devmark-public-assets.s3.us-west-2.amazonaws.com/sponsorships/mintlify.svg" alt="Create your docs today">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
And thank you to everyone who's contributed to this project in any way! 🫶
|
||||
|
||||
## Issues and Contributing
|
||||
|
||||
If you encounter a bug or want to see something added/changed, please go ahead
|
||||
and
|
||||
[open an issue](https://github.com/express-rate-limit/express-rate-limit/issues/new)!
|
||||
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/guides/contributing).
|
||||
Then you can pick up any issue and fix/implement it!
|
||||
|
||||
## License
|
||||
|
||||
MIT © [Nathan Friedly](http://nfriedly.com/),
|
||||
[Vedant K](https://github.com/gamemaker1)
|
||||
|
||||
[`windowMs`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#windowms
|
||||
[`limit`]: https://express-rate-limit.mintlify.app/reference/configuration#limit
|
||||
[`message`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#message
|
||||
[`statusCode`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#statuscode
|
||||
[`handler`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#handler
|
||||
[`legacyHeaders`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#legacyheaders
|
||||
[`standardHeaders`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#standardheaders
|
||||
[`identifier`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#identifier
|
||||
[`store`]: https://express-rate-limit.mintlify.app/reference/configuration#store
|
||||
[`passOnStoreError`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#passonstoreerror
|
||||
[`keyGenerator`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#keygenerator
|
||||
[`ipv6Subnet`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#ipv6subnet
|
||||
[`requestPropertyName`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#requestpropertyname
|
||||
[`skip`]: https://express-rate-limit.mintlify.app/reference/configuration#skip
|
||||
[`skipSuccessfulRequests`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#skipsuccessfulrequests
|
||||
[`skipFailedRequests`]:
|
||||
https://express-rate-limit.mintlify.app/reference/configuration#skipfailedrequests
|
||||
[`requestWasSuccessful`]:
|
||||
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
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"include": ["source/"],
|
||||
"exclude": ["node_modules/"],
|
||||
"extends": "@express-rate-limit/tsconfig",
|
||||
"compilerOptions": {
|
||||
"target": "ES2020"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user