index.d.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. // Generated by dts-bundle-generator v8.1.2
  2. import { NextFunction, Request, RequestHandler, Response } from 'express';
  3. /**
  4. * Returns the IP address itself for IPv4, or a CIDR-notation subnet for IPv6.
  5. *
  6. * If you write a custom keyGenerator that allows a fallback to IP address for
  7. * unauthenticated users, return ipKeyGenerator(req.ip) rather than just req.ip.
  8. *
  9. * For more information, {@see Options.ipv6Subnet}.
  10. *
  11. * @param ip {string} - The IP address to process, usually request.ip.
  12. * @param ipv6Subnet {number | false} - The subnet mask for IPv6 addresses.
  13. *
  14. * @returns {string} - The key generated from the IP address
  15. *
  16. * @public
  17. */
  18. export declare function ipKeyGenerator(ip: string, ipv6Subnet?: number | false): string;
  19. declare const SUPPORTED_DRAFT_VERSIONS: readonly [
  20. "draft-6",
  21. "draft-7",
  22. "draft-8"
  23. ];
  24. declare const validations: {
  25. enabled: {
  26. [key: string]: boolean;
  27. };
  28. disable(): void;
  29. /**
  30. * Checks whether the IP address is valid, and that it does not have a port
  31. * number in it.
  32. *
  33. * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
  34. *
  35. * @param ip {string | undefined} - The IP address provided by Express as request.ip.
  36. *
  37. * @returns {void}
  38. */
  39. ip(ip: string | undefined): void;
  40. /**
  41. * Makes sure the trust proxy setting is not set to `true`.
  42. *
  43. * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
  44. *
  45. * @param request {Request} - The Express request object.
  46. *
  47. * @returns {void}
  48. */
  49. trustProxy(request: Request): void;
  50. /**
  51. * Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
  52. * header is present.
  53. *
  54. * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
  55. *
  56. * @param request {Request} - The Express request object.
  57. *
  58. * @returns {void}
  59. */
  60. xForwardedForHeader(request: Request): void;
  61. /**
  62. * 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)
  63. *
  64. * @param request {Request} - The Express request object.
  65. *
  66. * @returns {void}
  67. */
  68. forwardedHeader(request: Request): void;
  69. /**
  70. * Ensures totalHits value from store is a positive integer.
  71. *
  72. * @param hits {any} - The `totalHits` returned by the store.
  73. */
  74. positiveHits(hits: any): void;
  75. /**
  76. * Ensures a single store instance is not used with multiple express-rate-limit instances
  77. */
  78. unsharedStore(store: Store): void;
  79. /**
  80. * Ensures a given key is incremented only once per request.
  81. *
  82. * @param request {Request} - The Express request object.
  83. * @param store {Store} - The store class.
  84. * @param key {string} - The key used to store the client's hit count.
  85. *
  86. * @returns {void}
  87. */
  88. singleCount(request: Request, store: Store, key: string): void;
  89. /**
  90. * Warns the user that the behaviour for `max: 0` / `limit: 0` is
  91. * changing in the next major release.
  92. *
  93. * @param limit {number} - The maximum number of hits per client.
  94. *
  95. * @returns {void}
  96. */
  97. limit(limit: number): void;
  98. /**
  99. * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
  100. * and will be removed in the next major release.
  101. *
  102. * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
  103. *
  104. * @returns {void}
  105. */
  106. draftPolliHeaders(draft_polli_ratelimit_headers?: any): void;
  107. /**
  108. * Warns the user that the `onLimitReached` option is deprecated and
  109. * will be removed in the next major release.
  110. *
  111. * @param onLimitReached {any | undefined} - The maximum number of hits per client.
  112. *
  113. * @returns {void}
  114. */
  115. onLimitReached(onLimitReached?: any): void;
  116. /**
  117. * Warns the user when an invalid/unsupported version of the draft spec is passed.
  118. *
  119. * @param version {any | undefined} - The version passed by the user.
  120. *
  121. * @returns {void}
  122. */
  123. headersDraftVersion(version?: any): void;
  124. /**
  125. * Warns the user when the selected headers option requires a reset time but
  126. * the store does not provide one.
  127. *
  128. * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
  129. *
  130. * @returns {void}
  131. */
  132. headersResetTime(resetTime?: Date): void;
  133. knownOptions(passedOptions?: Partial<Options>): void;
  134. /**
  135. * Checks the options.validate setting to ensure that only recognized
  136. * validations are enabled or disabled.
  137. *
  138. * If any unrecognized values are found, an error is logged that
  139. * includes the list of supported validations.
  140. */
  141. validationsConfig(): void;
  142. /**
  143. * Checks to see if the instance was created inside of a request handler,
  144. * which would prevent it from working correctly, with the default memory
  145. * store (or any other store with localKeys.)
  146. */
  147. creationStack(store: Store): void;
  148. ipv6Subnet(ipv6Subnet?: any): void;
  149. ipv6SubnetOrKeyGenerator(options: Partial<Options>): void;
  150. keyGeneratorIpFallback(keyGenerator?: ValueDeterminingMiddleware<string>): void;
  151. /**
  152. * Checks to see if the window duration is greater than 2^32 - 1. This is only
  153. * called by the default MemoryStore, since it uses Node's setInterval method.
  154. *
  155. * See https://nodejs.org/api/timers.html#setintervalcallback-delay-args.
  156. */
  157. windowMs(windowMs: number): void;
  158. };
  159. export type Validations = typeof validations;
  160. /**
  161. * Callback that fires when a client's hit counter is incremented.
  162. *
  163. * @param error {Error | undefined} - The error that occurred, if any.
  164. * @param totalHits {number} - The number of hits for that client so far.
  165. * @param resetTime {Date | undefined} - The time when the counter resets.
  166. */
  167. export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void;
  168. /**
  169. * Method (in the form of middleware) to generate/retrieve a value based on the
  170. * incoming request.
  171. *
  172. * @param request {Request} - The Express request object.
  173. * @param response {Response} - The Express response object.
  174. *
  175. * @returns {T} - The value needed.
  176. */
  177. export type ValueDeterminingMiddleware<T> = (request: Request, response: Response) => T | Promise<T>;
  178. /**
  179. * Express request handler that sends back a response when a client is
  180. * rate-limited.
  181. *
  182. * @param request {Request} - The Express request object.
  183. * @param response {Response} - The Express response object.
  184. * @param next {NextFunction} - The Express `next` function, can be called to skip responding.
  185. * @param optionsUsed {Options} - The options used to set up the middleware.
  186. */
  187. export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void;
  188. /**
  189. * Event callback that is triggered on a client's first request that exceeds the limit
  190. * but not for subsequent requests. May be used for logging, etc. Should *not*
  191. * send a response.
  192. *
  193. * @param request {Request} - The Express request object.
  194. * @param response {Response} - The Express response object.
  195. * @param optionsUsed {Options} - The options used to set up the middleware.
  196. */
  197. export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void;
  198. /**
  199. * Data returned from the `Store` when a client's hit counter is incremented.
  200. *
  201. * @property totalHits {number} - The number of hits for that client so far.
  202. * @property resetTime {Date | undefined} - The time when the counter resets.
  203. */
  204. export type ClientRateLimitInfo = {
  205. totalHits: number;
  206. resetTime: Date | undefined;
  207. };
  208. export type IncrementResponse = ClientRateLimitInfo;
  209. /**
  210. * A modified Express request handler with the rate limit functions.
  211. */
  212. export type RateLimitRequestHandler = RequestHandler & {
  213. /**
  214. * Method to reset a client's hit counter.
  215. *
  216. * @param key {string} - The identifier for a client.
  217. */
  218. resetKey: (key: string) => void;
  219. /**
  220. * Method to fetch a client's hit count and reset time.
  221. *
  222. * @param key {string} - The identifier for a client.
  223. *
  224. * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
  225. */
  226. getKey: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
  227. };
  228. /**
  229. * An interface that all hit counter stores must implement.
  230. *
  231. * @deprecated 6.x - Implement the `Store` interface instead.
  232. */
  233. export type LegacyStore = {
  234. /**
  235. * Method to increment a client's hit counter.
  236. *
  237. * @param key {string} - The identifier for a client.
  238. * @param callback {IncrementCallback} - The callback to call once the counter is incremented.
  239. */
  240. incr: (key: string, callback: IncrementCallback) => void;
  241. /**
  242. * Method to decrement a client's hit counter.
  243. *
  244. * @param key {string} - The identifier for a client.
  245. */
  246. decrement: (key: string) => void;
  247. /**
  248. * Method to reset a client's hit counter.
  249. *
  250. * @param key {string} - The identifier for a client.
  251. */
  252. resetKey: (key: string) => void;
  253. /**
  254. * Method to reset everyone's hit counter.
  255. */
  256. resetAll?: () => void;
  257. };
  258. /**
  259. * An interface that all hit counter stores must implement.
  260. */
  261. export type Store = {
  262. /**
  263. * Method that initializes the store, and has access to the options passed to
  264. * the middleware too.
  265. *
  266. * @param options {Options} - The options used to setup the middleware.
  267. */
  268. init?: (options: Options) => void;
  269. /**
  270. * Method to fetch a client's hit count and reset time.
  271. *
  272. * @param key {string} - The identifier for a client.
  273. *
  274. * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
  275. */
  276. get?: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
  277. /**
  278. * Method to increment a client's hit counter.
  279. *
  280. * @param key {string} - The identifier for a client.
  281. *
  282. * @returns {IncrementResponse | undefined} - The number of hits and reset time for that client.
  283. */
  284. increment: (key: string) => Promise<IncrementResponse> | IncrementResponse;
  285. /**
  286. * Method to decrement a client's hit counter.
  287. *
  288. * @param key {string} - The identifier for a client.
  289. */
  290. decrement: (key: string) => Promise<void> | void;
  291. /**
  292. * Method to reset a client's hit counter.
  293. *
  294. * @param key {string} - The identifier for a client.
  295. */
  296. resetKey: (key: string) => Promise<void> | void;
  297. /**
  298. * Method to reset everyone's hit counter.
  299. */
  300. resetAll?: () => Promise<void> | void;
  301. /**
  302. * Method to shutdown the store, stop timers, and release all resources.
  303. */
  304. shutdown?: () => Promise<void> | void;
  305. /**
  306. * Flag to indicate that keys incremented in one instance of this store can
  307. * not affect other instances. Typically false if a database is used, true for
  308. * MemoryStore.
  309. *
  310. * Used to help detect double-counting misconfigurations.
  311. */
  312. localKeys?: boolean;
  313. /**
  314. * Optional value that the store prepends to keys
  315. *
  316. * Used by the double-count check to avoid false-positives when a key is counted
  317. * twice, but with different prefixes.
  318. */
  319. prefix?: string;
  320. };
  321. export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number];
  322. /**
  323. * Validate configuration object for enabling or disabling specific validations.
  324. *
  325. * The keys must also be keys in the validations object, except `enable`, `disable`,
  326. * and `default`.
  327. */
  328. export type EnabledValidations = {
  329. [key in keyof Omit<Validations, "enabled" | "disable"> | "default"]?: boolean;
  330. };
  331. /**
  332. * The configuration options for the rate limiter.
  333. */
  334. export type Options = {
  335. /**
  336. * How long we should remember the requests.
  337. *
  338. * Defaults to `60000` ms (= 1 minute).
  339. */
  340. windowMs: number;
  341. /**
  342. * The maximum number of connections to allow during the `window` before
  343. * rate limiting the client.
  344. *
  345. * Can be the limit itself as a number or express middleware that parses
  346. * the request and then figures out the limit.
  347. *
  348. * Defaults to `5`.
  349. */
  350. limit: number | ValueDeterminingMiddleware<number>;
  351. /**
  352. * The response body to send back when a client is rate limited.
  353. *
  354. * Defaults to `'Too many requests, please try again later.'`
  355. */
  356. message: any | ValueDeterminingMiddleware<any>;
  357. /**
  358. * The HTTP status code to send back when a client is rate limited.
  359. *
  360. * Defaults to `HTTP 429 Too Many Requests` (RFC 6585).
  361. */
  362. statusCode: number;
  363. /**
  364. * Whether to send `X-RateLimit-*` headers with the rate limit and the number
  365. * of requests.
  366. *
  367. * Defaults to `true` (for backward compatibility).
  368. */
  369. legacyHeaders: boolean;
  370. /**
  371. * Whether to enable support for the standardized rate limit headers (`RateLimit-*`).
  372. *
  373. * Defaults to `false` (for backward compatibility, but its use is recommended).
  374. */
  375. standardHeaders: boolean | DraftHeadersVersion;
  376. /**
  377. * The name used to identify the quota policy in the `RateLimit` headers as per
  378. * the 8th draft of the IETF specification.
  379. *
  380. * Defaults to `{limit}-in-{window}`.
  381. */
  382. identifier: string | ValueDeterminingMiddleware<string>;
  383. /**
  384. * The name of the property on the request object to store the rate limit info.
  385. *
  386. * Defaults to `rateLimit`.
  387. */
  388. requestPropertyName: string;
  389. /**
  390. * If `true`, the library will (by default) skip all requests that have a 4XX
  391. * or 5XX status.
  392. *
  393. * Defaults to `false`.
  394. */
  395. skipFailedRequests: boolean;
  396. /**
  397. * If `true`, the library will (by default) skip all requests that have a
  398. * status code less than 400.
  399. *
  400. * Defaults to `false`.
  401. */
  402. skipSuccessfulRequests: boolean;
  403. /**
  404. * Method to generate custom identifiers for clients.
  405. *
  406. * By default, the client's IP address is used.
  407. */
  408. keyGenerator: ValueDeterminingMiddleware<string>;
  409. /**
  410. * IPv6 subnet mask applied to IPv6 addresses in the default keyGenerator.
  411. *
  412. * Default is 56. The valid range is technically 1-128 but the value should
  413. * generally be in the 32-64 range.
  414. *
  415. * Smaller numbers are more aggressive, larger numbers are more lenient. Try
  416. * bumping to 60 or 64 if you see evidence of users being blocked incorrectly.
  417. *
  418. * May also be set to a function that returns a number based on the request.
  419. *
  420. * See the documentation for more info:
  421. * https://express-rate-limit.mintlify.app/reference/configuration#ipv6subnet.
  422. */
  423. ipv6Subnet: 64 | 60 | 56 | 52 | 50 | 48 | 32 | number | ValueDeterminingMiddleware<number> | false;
  424. /**
  425. * Express request handler that sends back a response when a client is
  426. * rate-limited.
  427. *
  428. * By default, sends back the `statusCode` and `message` set via the options.
  429. */
  430. handler: RateLimitExceededEventHandler;
  431. /**
  432. * Method (in the form of middleware) to determine whether or not this request
  433. * counts towards a client's quota.
  434. *
  435. * By default, skips no requests.
  436. */
  437. skip: ValueDeterminingMiddleware<boolean>;
  438. /**
  439. * Method to determine whether or not the request counts as 'successful'. Used
  440. * when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true.
  441. *
  442. * By default, requests with a response status code less than 400 are considered
  443. * successful.
  444. */
  445. requestWasSuccessful: ValueDeterminingMiddleware<boolean>;
  446. /**
  447. * The `Store` to use to store the hit count for each client.
  448. *
  449. * By default, the built-in `MemoryStore` will be used.
  450. */
  451. store: Store | LegacyStore;
  452. /**
  453. * The list of validation checks that should run.
  454. */
  455. validate: boolean | EnabledValidations;
  456. /**
  457. * Whether to send `X-RateLimit-*` headers with the rate limit and the number
  458. * of requests.
  459. *
  460. * @deprecated 6.x - This option was renamed to `legacyHeaders`.
  461. */
  462. headers?: boolean;
  463. /**
  464. * The maximum number of connections to allow during the `window` before
  465. * rate limiting the client.
  466. *
  467. * Can be the limit itself as a number or express middleware that parses
  468. * the request and then figures out the limit.
  469. *
  470. * @deprecated 7.x - This option was renamed to `limit`. However, it will not
  471. * be removed from the library in the foreseeable future.
  472. */
  473. max?: number | ValueDeterminingMiddleware<number>;
  474. /**
  475. * If the Store generates an error, allow the request to pass.
  476. */
  477. passOnStoreError: boolean;
  478. };
  479. /**
  480. * The extended request object that includes information about the client's
  481. * rate limit.
  482. */
  483. export type AugmentedRequest = Request & {
  484. [key: string]: RateLimitInfo;
  485. };
  486. /**
  487. * The rate limit related information for each client included in the
  488. * Express request object.
  489. */
  490. export type RateLimitInfo = {
  491. limit: number;
  492. used: number;
  493. remaining: number;
  494. resetTime: Date | undefined;
  495. key: string;
  496. };
  497. /**
  498. * The record that stores information about a client - namely, how many times
  499. * they have hit the endpoint, and when their hit count resets.
  500. *
  501. * Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field.
  502. */
  503. export type Client = {
  504. totalHits: number;
  505. resetTime: Date;
  506. };
  507. /**
  508. * A `Store` that stores the hit count for each client in memory.
  509. *
  510. * @public
  511. */
  512. export declare class MemoryStore implements Store {
  513. private validations?;
  514. /**
  515. * The duration of time before which all hit counts are reset (in milliseconds).
  516. */
  517. windowMs: number;
  518. /**
  519. * These two maps store usage (requests) and reset time by key (for example, IP
  520. * addresses or API keys).
  521. *
  522. * They are split into two to avoid having to iterate through the entire set to
  523. * determine which ones need reset. Instead, `Client`s are moved from `previous`
  524. * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
  525. * left in `previous`, i.e., those that have not made any recent requests, are
  526. * known to be expired and can be deleted in bulk.
  527. */
  528. previous: Map<string, Client>;
  529. current: Map<string, Client>;
  530. /**
  531. * A reference to the active timer.
  532. */
  533. interval?: NodeJS.Timeout;
  534. /**
  535. * Confirmation that the keys incremented in once instance of MemoryStore
  536. * cannot affect other instances.
  537. */
  538. localKeys: boolean;
  539. constructor(validations?: Validations | undefined);
  540. /**
  541. * Method that initializes the store.
  542. *
  543. * @param options {Options} - The options used to setup the middleware.
  544. */
  545. init(options: Options): void;
  546. /**
  547. * Method to fetch a client's hit count and reset time.
  548. *
  549. * @param key {string} - The identifier for a client.
  550. *
  551. * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
  552. *
  553. * @public
  554. */
  555. get(key: string): Promise<ClientRateLimitInfo | undefined>;
  556. /**
  557. * Method to increment a client's hit counter.
  558. *
  559. * @param key {string} - The identifier for a client.
  560. *
  561. * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
  562. *
  563. * @public
  564. */
  565. increment(key: string): Promise<ClientRateLimitInfo>;
  566. /**
  567. * Method to decrement a client's hit counter.
  568. *
  569. * @param key {string} - The identifier for a client.
  570. *
  571. * @public
  572. */
  573. decrement(key: string): Promise<void>;
  574. /**
  575. * Method to reset a client's hit counter.
  576. *
  577. * @param key {string} - The identifier for a client.
  578. *
  579. * @public
  580. */
  581. resetKey(key: string): Promise<void>;
  582. /**
  583. * Method to reset everyone's hit counter.
  584. *
  585. * @public
  586. */
  587. resetAll(): Promise<void>;
  588. /**
  589. * Method to stop the timer (if currently running) and prevent any memory
  590. * leaks.
  591. *
  592. * @public
  593. */
  594. shutdown(): void;
  595. /**
  596. * Recycles a client by setting its hit count to zero, and reset time to
  597. * `windowMs` milliseconds from now.
  598. *
  599. * NOT to be confused with `#resetKey()`, which removes a client from both the
  600. * `current` and `previous` maps.
  601. *
  602. * @param client {Client} - The client to recycle.
  603. * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
  604. *
  605. * @return {Client} - The modified client that was passed in, to allow for chaining.
  606. */
  607. private resetClient;
  608. /**
  609. * Retrieves or creates a client, given a key. Also ensures that the client being
  610. * returned is in the `current` map.
  611. *
  612. * @param key {string} - The key under which the client is (or is to be) stored.
  613. *
  614. * @returns {Client} - The requested client.
  615. */
  616. private getClient;
  617. /**
  618. * Move current clients to previous, create a new map for current.
  619. *
  620. * This function is called every `windowMs`.
  621. */
  622. private clearExpired;
  623. }
  624. /**
  625. *
  626. * Create an instance of IP rate-limiting middleware for Express.
  627. *
  628. * @param passedOptions {Options} - Options to configure the rate limiter.
  629. *
  630. * @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration.
  631. *
  632. * @public
  633. */
  634. export declare const rateLimit: (passedOptions?: Partial<Options>) => RateLimitRequestHandler;
  635. export {
  636. rateLimit as default,
  637. };
  638. export {};