index.d.ts 17 KB

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