index.cjs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. // source/index.ts
  20. var index_exports = {};
  21. __export(index_exports, {
  22. MemoryStore: () => MemoryStore,
  23. default: () => rate_limit_default,
  24. ipKeyGenerator: () => ipKeyGenerator,
  25. rateLimit: () => rate_limit_default
  26. });
  27. module.exports = __toCommonJS(index_exports);
  28. // source/ip-key-generator.ts
  29. var import_node_net = require("node:net");
  30. var import_ip_address = require("ip-address");
  31. function ipKeyGenerator(ip, ipv6Subnet = 56) {
  32. if ((0, import_node_net.isIPv6)(ip)) {
  33. const address = new import_ip_address.Address6(ip);
  34. if (address.is4()) return address.to4().correctForm();
  35. if (ipv6Subnet) {
  36. const subnet = new import_ip_address.Address6(`${ip}/${ipv6Subnet}`);
  37. return `${subnet.startAddress().correctForm()}/${ipv6Subnet}`;
  38. }
  39. }
  40. return ip;
  41. }
  42. // source/memory-store.ts
  43. var MemoryStore = class {
  44. constructor(validations2) {
  45. this.validations = validations2;
  46. /**
  47. * These two maps store usage (requests) and reset time by key (for example, IP
  48. * addresses or API keys).
  49. *
  50. * They are split into two to avoid having to iterate through the entire set to
  51. * determine which ones need reset. Instead, `Client`s are moved from `previous`
  52. * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
  53. * left in `previous`, i.e., those that have not made any recent requests, are
  54. * known to be expired and can be deleted in bulk.
  55. */
  56. this.previous = /* @__PURE__ */ new Map();
  57. this.current = /* @__PURE__ */ new Map();
  58. /**
  59. * Confirmation that the keys incremented in once instance of MemoryStore
  60. * cannot affect other instances.
  61. */
  62. this.localKeys = true;
  63. }
  64. /**
  65. * Method that initializes the store.
  66. *
  67. * @param options {Options} - The options used to setup the middleware.
  68. */
  69. init(options) {
  70. this.windowMs = options.windowMs;
  71. this.validations?.windowMs(this.windowMs);
  72. if (this.interval) clearInterval(this.interval);
  73. this.interval = setInterval(() => {
  74. this.clearExpired();
  75. }, this.windowMs);
  76. this.interval.unref?.();
  77. }
  78. /**
  79. * Method to fetch a client's hit count and reset time.
  80. *
  81. * @param key {string} - The identifier for a client.
  82. *
  83. * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
  84. *
  85. * @public
  86. */
  87. async get(key) {
  88. return this.current.get(key) ?? this.previous.get(key);
  89. }
  90. /**
  91. * Method to increment a client's hit counter.
  92. *
  93. * @param key {string} - The identifier for a client.
  94. *
  95. * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
  96. *
  97. * @public
  98. */
  99. async increment(key) {
  100. const client = this.getClient(key);
  101. const now = Date.now();
  102. if (client.resetTime.getTime() <= now) {
  103. this.resetClient(client, now);
  104. }
  105. client.totalHits++;
  106. return client;
  107. }
  108. /**
  109. * Method to decrement a client's hit counter.
  110. *
  111. * @param key {string} - The identifier for a client.
  112. *
  113. * @public
  114. */
  115. async decrement(key) {
  116. const client = this.getClient(key);
  117. if (client.totalHits > 0) client.totalHits--;
  118. }
  119. /**
  120. * Method to reset a client's hit counter.
  121. *
  122. * @param key {string} - The identifier for a client.
  123. *
  124. * @public
  125. */
  126. async resetKey(key) {
  127. this.current.delete(key);
  128. this.previous.delete(key);
  129. }
  130. /**
  131. * Method to reset everyone's hit counter.
  132. *
  133. * @public
  134. */
  135. async resetAll() {
  136. this.current.clear();
  137. this.previous.clear();
  138. }
  139. /**
  140. * Method to stop the timer (if currently running) and prevent any memory
  141. * leaks.
  142. *
  143. * @public
  144. */
  145. shutdown() {
  146. clearInterval(this.interval);
  147. void this.resetAll();
  148. }
  149. /**
  150. * Recycles a client by setting its hit count to zero, and reset time to
  151. * `windowMs` milliseconds from now.
  152. *
  153. * NOT to be confused with `#resetKey()`, which removes a client from both the
  154. * `current` and `previous` maps.
  155. *
  156. * @param client {Client} - The client to recycle.
  157. * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
  158. *
  159. * @return {Client} - The modified client that was passed in, to allow for chaining.
  160. */
  161. resetClient(client, now = Date.now()) {
  162. client.totalHits = 0;
  163. client.resetTime.setTime(now + this.windowMs);
  164. return client;
  165. }
  166. /**
  167. * Retrieves or creates a client, given a key. Also ensures that the client being
  168. * returned is in the `current` map.
  169. *
  170. * @param key {string} - The key under which the client is (or is to be) stored.
  171. *
  172. * @returns {Client} - The requested client.
  173. */
  174. getClient(key) {
  175. if (this.current.has(key)) return this.current.get(key);
  176. let client;
  177. if (this.previous.has(key)) {
  178. client = this.previous.get(key);
  179. this.previous.delete(key);
  180. } else {
  181. client = { totalHits: 0, resetTime: /* @__PURE__ */ new Date() };
  182. this.resetClient(client);
  183. }
  184. this.current.set(key, client);
  185. return client;
  186. }
  187. /**
  188. * Move current clients to previous, create a new map for current.
  189. *
  190. * This function is called every `windowMs`.
  191. */
  192. clearExpired() {
  193. this.previous = this.current;
  194. this.current = /* @__PURE__ */ new Map();
  195. }
  196. };
  197. // source/rate-limit.ts
  198. var import_node_net3 = require("node:net");
  199. // source/headers.ts
  200. var import_node_buffer = require("node:buffer");
  201. var import_node_crypto = require("node:crypto");
  202. var SUPPORTED_DRAFT_VERSIONS = [
  203. "draft-6",
  204. "draft-7",
  205. "draft-8"
  206. ];
  207. var getResetSeconds = (windowMs, resetTime) => {
  208. let resetSeconds;
  209. if (resetTime) {
  210. const deltaSeconds = Math.ceil((resetTime.getTime() - Date.now()) / 1e3);
  211. resetSeconds = Math.max(0, deltaSeconds);
  212. } else {
  213. resetSeconds = Math.ceil(windowMs / 1e3);
  214. }
  215. return resetSeconds;
  216. };
  217. var getPartitionKey = (key) => {
  218. const hash = (0, import_node_crypto.createHash)("sha256");
  219. hash.update(key);
  220. const partitionKey = hash.digest("hex").slice(0, 12);
  221. return import_node_buffer.Buffer.from(partitionKey).toString("base64");
  222. };
  223. var setLegacyHeaders = (response, info) => {
  224. if (response.headersSent) return;
  225. response.setHeader("X-RateLimit-Limit", info.limit.toString());
  226. response.setHeader("X-RateLimit-Remaining", info.remaining.toString());
  227. if (info.resetTime instanceof Date) {
  228. response.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString());
  229. response.setHeader(
  230. "X-RateLimit-Reset",
  231. Math.ceil(info.resetTime.getTime() / 1e3).toString()
  232. );
  233. }
  234. };
  235. var setDraft6Headers = (response, info, windowMs) => {
  236. if (response.headersSent) return;
  237. const windowSeconds = Math.ceil(windowMs / 1e3);
  238. const resetSeconds = getResetSeconds(windowMs, info.resetTime);
  239. response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
  240. response.setHeader("RateLimit-Limit", info.limit.toString());
  241. response.setHeader("RateLimit-Remaining", info.remaining.toString());
  242. if (typeof resetSeconds === "number")
  243. response.setHeader("RateLimit-Reset", resetSeconds.toString());
  244. };
  245. var setDraft7Headers = (response, info, windowMs) => {
  246. if (response.headersSent) return;
  247. const windowSeconds = Math.ceil(windowMs / 1e3);
  248. const resetSeconds = getResetSeconds(windowMs, info.resetTime);
  249. response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
  250. response.setHeader(
  251. "RateLimit",
  252. `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`
  253. );
  254. };
  255. var setDraft8Headers = (response, info, windowMs, name, key) => {
  256. if (response.headersSent) return;
  257. const windowSeconds = Math.ceil(windowMs / 1e3);
  258. const resetSeconds = getResetSeconds(windowMs, info.resetTime);
  259. const partitionKey = getPartitionKey(key);
  260. const header = `r=${info.remaining}; t=${resetSeconds}`;
  261. const policy = `q=${info.limit}; w=${windowSeconds}; pk=:${partitionKey}:`;
  262. response.append("RateLimit", `"${name}"; ${header}`);
  263. response.append("RateLimit-Policy", `"${name}"; ${policy}`);
  264. };
  265. var setRetryAfterHeader = (response, info, windowMs) => {
  266. if (response.headersSent) return;
  267. const resetSeconds = getResetSeconds(windowMs, info.resetTime);
  268. response.setHeader("Retry-After", resetSeconds.toString());
  269. };
  270. // source/utils.ts
  271. var omitUndefinedProperties = (passedOptions) => {
  272. const omittedOptions = {};
  273. for (const k of Object.keys(passedOptions)) {
  274. const key = k;
  275. if (passedOptions[key] !== void 0) {
  276. omittedOptions[key] = passedOptions[key];
  277. }
  278. }
  279. return omittedOptions;
  280. };
  281. // source/validations.ts
  282. var import_node_net2 = require("node:net");
  283. var ValidationError = class extends Error {
  284. /**
  285. * The code must be a string, in snake case and all capital, that starts with
  286. * the substring `ERR_ERL_`.
  287. *
  288. * The message must be a string, starting with an uppercase character,
  289. * describing the issue in detail.
  290. */
  291. constructor(code, message) {
  292. const url = `https://express-rate-limit.github.io/${code}/`;
  293. super(`${message} See ${url} for more information.`);
  294. this.name = this.constructor.name;
  295. this.code = code;
  296. this.help = url;
  297. }
  298. };
  299. var ChangeWarning = class extends ValidationError {
  300. };
  301. var usedStores = /* @__PURE__ */ new Set();
  302. var singleCountKeys = /* @__PURE__ */ new WeakMap();
  303. var validations = {
  304. enabled: {
  305. default: true
  306. },
  307. // Should be EnabledValidations type, but that's a circular reference
  308. disable() {
  309. for (const k of Object.keys(this.enabled)) this.enabled[k] = false;
  310. },
  311. /**
  312. * Checks whether the IP address is valid, and that it does not have a port
  313. * number in it.
  314. *
  315. * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
  316. *
  317. * @param ip {string | undefined} - The IP address provided by Express as request.ip.
  318. *
  319. * @returns {void}
  320. */
  321. ip(ip) {
  322. if (ip === void 0) {
  323. throw new ValidationError(
  324. "ERR_ERL_UNDEFINED_IP_ADDRESS",
  325. `An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`
  326. );
  327. }
  328. if (!(0, import_node_net2.isIP)(ip)) {
  329. throw new ValidationError(
  330. "ERR_ERL_INVALID_IP_ADDRESS",
  331. `An invalid 'request.ip' (${ip}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`
  332. );
  333. }
  334. },
  335. /**
  336. * Makes sure the trust proxy setting is not set to `true`.
  337. *
  338. * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
  339. *
  340. * @param request {Request} - The Express request object.
  341. *
  342. * @returns {void}
  343. */
  344. trustProxy(request) {
  345. if (request.app.get("trust proxy") === true) {
  346. throw new ValidationError(
  347. "ERR_ERL_PERMISSIVE_TRUST_PROXY",
  348. `The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`
  349. );
  350. }
  351. },
  352. /**
  353. * Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
  354. * header is present.
  355. *
  356. * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
  357. *
  358. * @param request {Request} - The Express request object.
  359. *
  360. * @returns {void}
  361. */
  362. xForwardedForHeader(request) {
  363. if (request.headers["x-forwarded-for"] && request.app.get("trust proxy") === false) {
  364. throw new ValidationError(
  365. "ERR_ERL_UNEXPECTED_X_FORWARDED_FOR",
  366. `The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`
  367. );
  368. }
  369. },
  370. /**
  371. * 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)
  372. *
  373. * @param request {Request} - The Express request object.
  374. *
  375. * @returns {void}
  376. */
  377. forwardedHeader(request) {
  378. if (request.headers.forwarded && request.ip === request.socket?.remoteAddress) {
  379. throw new ValidationError(
  380. "ERR_ERL_FORWARDED_HEADER",
  381. `The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.`
  382. );
  383. }
  384. },
  385. /**
  386. * Ensures totalHits value from store is a positive integer.
  387. *
  388. * @param hits {any} - The `totalHits` returned by the store.
  389. */
  390. positiveHits(hits) {
  391. if (typeof hits !== "number" || hits < 1 || hits !== Math.round(hits)) {
  392. throw new ValidationError(
  393. "ERR_ERL_INVALID_HITS",
  394. `The totalHits value returned from the store must be a positive integer, got ${hits}`
  395. );
  396. }
  397. },
  398. /**
  399. * Ensures a single store instance is not used with multiple express-rate-limit instances
  400. */
  401. unsharedStore(store) {
  402. if (usedStores.has(store)) {
  403. const maybeUniquePrefix = store?.localKeys ? "" : " (with a unique prefix)";
  404. throw new ValidationError(
  405. "ERR_ERL_STORE_REUSE",
  406. `A Store instance must not be shared across multiple rate limiters. Create a new instance of ${store.constructor.name}${maybeUniquePrefix} for each limiter instead.`
  407. );
  408. }
  409. usedStores.add(store);
  410. },
  411. /**
  412. * Ensures a given key is incremented only once per request.
  413. *
  414. * @param request {Request} - The Express request object.
  415. * @param store {Store} - The store class.
  416. * @param key {string} - The key used to store the client's hit count.
  417. *
  418. * @returns {void}
  419. */
  420. singleCount(request, store, key) {
  421. let storeKeys = singleCountKeys.get(request);
  422. if (!storeKeys) {
  423. storeKeys = /* @__PURE__ */ new Map();
  424. singleCountKeys.set(request, storeKeys);
  425. }
  426. const storeKey = store.localKeys ? store : store.constructor.name;
  427. let keys = storeKeys.get(storeKey);
  428. if (!keys) {
  429. keys = [];
  430. storeKeys.set(storeKey, keys);
  431. }
  432. const prefixedKey = `${store.prefix ?? ""}${key}`;
  433. if (keys.includes(prefixedKey)) {
  434. throw new ValidationError(
  435. "ERR_ERL_DOUBLE_COUNT",
  436. `The hit count for ${key} was incremented more than once for a single request.`
  437. );
  438. }
  439. keys.push(prefixedKey);
  440. },
  441. /**
  442. * Warns the user that the behaviour for `max: 0` / `limit: 0` is
  443. * changing in the next major release.
  444. *
  445. * @param limit {number} - The maximum number of hits per client.
  446. *
  447. * @returns {void}
  448. */
  449. limit(limit) {
  450. if (limit === 0) {
  451. throw new ChangeWarning(
  452. "WRN_ERL_MAX_ZERO",
  453. "Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7"
  454. );
  455. }
  456. },
  457. /**
  458. * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
  459. * and will be removed in the next major release.
  460. *
  461. * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
  462. *
  463. * @returns {void}
  464. */
  465. draftPolliHeaders(draft_polli_ratelimit_headers) {
  466. if (draft_polli_ratelimit_headers) {
  467. throw new ChangeWarning(
  468. "WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS",
  469. `The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`
  470. );
  471. }
  472. },
  473. /**
  474. * Warns the user that the `onLimitReached` option is deprecated and
  475. * will be removed in the next major release.
  476. *
  477. * @param onLimitReached {any | undefined} - The maximum number of hits per client.
  478. *
  479. * @returns {void}
  480. */
  481. onLimitReached(onLimitReached) {
  482. if (onLimitReached) {
  483. throw new ChangeWarning(
  484. "WRN_ERL_DEPRECATED_ON_LIMIT_REACHED",
  485. "The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7."
  486. );
  487. }
  488. },
  489. /**
  490. * Warns the user when an invalid/unsupported version of the draft spec is passed.
  491. *
  492. * @param version {any | undefined} - The version passed by the user.
  493. *
  494. * @returns {void}
  495. */
  496. headersDraftVersion(version) {
  497. if (typeof version !== "string" || // @ts-expect-error This is fine. If version is not in the array, it will just return false.
  498. !SUPPORTED_DRAFT_VERSIONS.includes(version)) {
  499. const versionString = SUPPORTED_DRAFT_VERSIONS.join(", ");
  500. throw new ValidationError(
  501. "ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION",
  502. `standardHeaders: only the following versions of the IETF draft specification are supported: ${versionString}.`
  503. );
  504. }
  505. },
  506. /**
  507. * Warns the user when the selected headers option requires a reset time but
  508. * the store does not provide one.
  509. *
  510. * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
  511. *
  512. * @returns {void}
  513. */
  514. headersResetTime(resetTime) {
  515. if (!resetTime) {
  516. throw new ValidationError(
  517. "ERR_ERL_HEADERS_NO_RESET",
  518. `standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`
  519. );
  520. }
  521. },
  522. knownOptions(passedOptions) {
  523. if (!passedOptions) return;
  524. const optionsMap = {
  525. windowMs: true,
  526. limit: true,
  527. message: true,
  528. statusCode: true,
  529. legacyHeaders: true,
  530. standardHeaders: true,
  531. identifier: true,
  532. requestPropertyName: true,
  533. skipFailedRequests: true,
  534. skipSuccessfulRequests: true,
  535. keyGenerator: true,
  536. ipv6Subnet: true,
  537. handler: true,
  538. skip: true,
  539. requestWasSuccessful: true,
  540. store: true,
  541. validate: true,
  542. headers: true,
  543. max: true,
  544. passOnStoreError: true
  545. };
  546. const validOptions = Object.keys(optionsMap).concat(
  547. "draft_polli_ratelimit_headers",
  548. // not a valid option anymore, but we have a more specific check for this one, so don't warn for it here
  549. // from express-slow-down - https://github.com/express-rate-limit/express-slow-down/blob/main/source/types.ts#L65
  550. "delayAfter",
  551. "delayMs",
  552. "maxDelayMs"
  553. );
  554. for (const key of Object.keys(passedOptions)) {
  555. if (!validOptions.includes(key)) {
  556. throw new ValidationError(
  557. "ERR_ERL_UNKNOWN_OPTION",
  558. `Unexpected configuration option: ${key}`
  559. // todo: suggest a valid option with a short levenstein distance?
  560. );
  561. }
  562. }
  563. },
  564. /**
  565. * Checks the options.validate setting to ensure that only recognized
  566. * validations are enabled or disabled.
  567. *
  568. * If any unrecognized values are found, an error is logged that
  569. * includes the list of supported validations.
  570. */
  571. validationsConfig() {
  572. const supportedValidations = Object.keys(this).filter(
  573. (k) => !["enabled", "disable"].includes(k)
  574. );
  575. supportedValidations.push("default");
  576. for (const key of Object.keys(this.enabled)) {
  577. if (!supportedValidations.includes(key)) {
  578. throw new ValidationError(
  579. "ERR_ERL_UNKNOWN_VALIDATION",
  580. `options.validate.${key} is not recognized. Supported validate options are: ${supportedValidations.join(
  581. ", "
  582. )}.`
  583. );
  584. }
  585. }
  586. },
  587. /**
  588. * Checks to see if the instance was created inside of a request handler,
  589. * which would prevent it from working correctly, with the default memory
  590. * store (or any other store with localKeys.)
  591. */
  592. creationStack(store) {
  593. const { stack } = new Error(
  594. "express-rate-limit validation check (set options.validate.creationStack=false to disable)"
  595. );
  596. if (stack?.includes("Layer.handle [as handle_request]") || // express v4
  597. stack?.includes("Layer.handleRequest")) {
  598. if (!store.localKeys) {
  599. throw new ValidationError(
  600. "ERR_ERL_CREATED_IN_REQUEST_HANDLER",
  601. "express-rate-limit instance should *usually* be created at app initialization, not when responding to a request."
  602. );
  603. }
  604. throw new ValidationError(
  605. "ERR_ERL_CREATED_IN_REQUEST_HANDLER",
  606. "express-rate-limit instance should be created at app initialization, not when responding to a request."
  607. );
  608. }
  609. },
  610. ipv6Subnet(ipv6Subnet) {
  611. if (ipv6Subnet === false) {
  612. return;
  613. }
  614. if (!Number.isInteger(ipv6Subnet) || ipv6Subnet < 32 || ipv6Subnet > 64) {
  615. throw new ValidationError(
  616. "ERR_ERL_IPV6_SUBNET",
  617. `Unexpected ipv6Subnet value: ${ipv6Subnet}. Expected an integer between 32 and 64 (usually 48-64).`
  618. );
  619. }
  620. },
  621. ipv6SubnetOrKeyGenerator(options) {
  622. if (options.ipv6Subnet !== void 0 && options.keyGenerator) {
  623. throw new ValidationError(
  624. "ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR",
  625. `Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.`
  626. );
  627. }
  628. },
  629. keyGeneratorIpFallback(keyGenerator) {
  630. if (!keyGenerator) {
  631. return;
  632. }
  633. const src = keyGenerator.toString();
  634. if ((src.includes("req.ip") || src.includes("request.ip")) && !src.includes("ipKeyGenerator")) {
  635. throw new ValidationError(
  636. "ERR_ERL_KEY_GEN_IPV6",
  637. "Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits."
  638. );
  639. }
  640. },
  641. /**
  642. * Checks to see if the window duration is greater than 2^32 - 1. This is only
  643. * called by the default MemoryStore, since it uses Node's setInterval method.
  644. *
  645. * See https://nodejs.org/api/timers.html#setintervalcallback-delay-args.
  646. */
  647. windowMs(windowMs) {
  648. const SET_TIMEOUT_MAX = 2 ** 31 - 1;
  649. if (typeof windowMs !== "number" || Number.isNaN(windowMs) || windowMs < 1 || windowMs > SET_TIMEOUT_MAX) {
  650. throw new ValidationError(
  651. "ERR_ERL_WINDOW_MS",
  652. `Invalid windowMs value: ${windowMs}${typeof windowMs !== "number" ? ` (${typeof windowMs})` : ""}, must be a number between 1 and ${SET_TIMEOUT_MAX} when using the default MemoryStore`
  653. );
  654. }
  655. }
  656. };
  657. var getValidations = (_enabled) => {
  658. let enabled;
  659. if (typeof _enabled === "boolean") {
  660. enabled = {
  661. default: _enabled
  662. };
  663. } else {
  664. enabled = {
  665. default: true,
  666. ..._enabled
  667. };
  668. }
  669. const wrappedValidations = { enabled };
  670. for (const [name, validation] of Object.entries(validations)) {
  671. if (typeof validation === "function")
  672. wrappedValidations[name] = (...args) => {
  673. if (!(enabled[name] ?? enabled.default)) {
  674. return;
  675. }
  676. try {
  677. ;
  678. validation.apply(
  679. wrappedValidations,
  680. args
  681. );
  682. } catch (error) {
  683. if (error instanceof ChangeWarning) console.warn(error);
  684. else console.error(error);
  685. }
  686. };
  687. }
  688. return wrappedValidations;
  689. };
  690. // source/rate-limit.ts
  691. var isLegacyStore = (store) => (
  692. // Check that `incr` exists but `increment` does not - store authors might want
  693. // to keep both around for backwards compatibility.
  694. typeof store.incr === "function" && typeof store.increment !== "function"
  695. );
  696. var promisifyStore = (passedStore) => {
  697. if (!isLegacyStore(passedStore)) {
  698. return passedStore;
  699. }
  700. const legacyStore = passedStore;
  701. class PromisifiedStore {
  702. async increment(key) {
  703. return new Promise((resolve, reject) => {
  704. legacyStore.incr(
  705. key,
  706. (error, totalHits, resetTime) => {
  707. if (error) reject(error);
  708. resolve({ totalHits, resetTime });
  709. }
  710. );
  711. });
  712. }
  713. async decrement(key) {
  714. return legacyStore.decrement(key);
  715. }
  716. async resetKey(key) {
  717. return legacyStore.resetKey(key);
  718. }
  719. /* istanbul ignore next */
  720. async resetAll() {
  721. if (typeof legacyStore.resetAll === "function")
  722. return legacyStore.resetAll();
  723. }
  724. }
  725. return new PromisifiedStore();
  726. };
  727. var getOptionsFromConfig = (config) => {
  728. const { validations: validations2, ...directlyPassableEntries } = config;
  729. return {
  730. ...directlyPassableEntries,
  731. validate: validations2.enabled
  732. };
  733. };
  734. var parseOptions = (passedOptions) => {
  735. const notUndefinedOptions = omitUndefinedProperties(passedOptions);
  736. const validations2 = getValidations(notUndefinedOptions?.validate ?? true);
  737. validations2.validationsConfig();
  738. validations2.knownOptions(passedOptions);
  739. validations2.draftPolliHeaders(
  740. // @ts-expect-error see the note above.
  741. notUndefinedOptions.draft_polli_ratelimit_headers
  742. );
  743. validations2.onLimitReached(notUndefinedOptions.onLimitReached);
  744. if (notUndefinedOptions.ipv6Subnet !== void 0 && typeof notUndefinedOptions.ipv6Subnet !== "function") {
  745. validations2.ipv6Subnet(notUndefinedOptions.ipv6Subnet);
  746. }
  747. validations2.keyGeneratorIpFallback(notUndefinedOptions.keyGenerator);
  748. validations2.ipv6SubnetOrKeyGenerator(notUndefinedOptions);
  749. let standardHeaders = notUndefinedOptions.standardHeaders ?? false;
  750. if (standardHeaders === true) standardHeaders = "draft-6";
  751. const config = {
  752. windowMs: 60 * 1e3,
  753. limit: passedOptions.max ?? 5,
  754. // `max` is deprecated, but support it anyways.
  755. message: "Too many requests, please try again later.",
  756. statusCode: 429,
  757. legacyHeaders: passedOptions.headers ?? true,
  758. identifier(request, _response) {
  759. let duration = "";
  760. const property = config.requestPropertyName;
  761. const { limit } = request[property];
  762. const seconds = config.windowMs / 1e3;
  763. const minutes = config.windowMs / (1e3 * 60);
  764. const hours = config.windowMs / (1e3 * 60 * 60);
  765. const days = config.windowMs / (1e3 * 60 * 60 * 24);
  766. if (seconds < 60) duration = `${seconds}sec`;
  767. else if (minutes < 60) duration = `${minutes}min`;
  768. else if (hours < 24) duration = `${hours}hr${hours > 1 ? "s" : ""}`;
  769. else duration = `${days}day${days > 1 ? "s" : ""}`;
  770. return `${limit}-in-${duration}`;
  771. },
  772. requestPropertyName: "rateLimit",
  773. skipFailedRequests: false,
  774. skipSuccessfulRequests: false,
  775. requestWasSuccessful: (_request, response) => response.statusCode < 400,
  776. skip: (_request, _response) => false,
  777. async keyGenerator(request, response) {
  778. validations2.ip(request.ip);
  779. validations2.trustProxy(request);
  780. validations2.xForwardedForHeader(request);
  781. validations2.forwardedHeader(request);
  782. const ip = request.ip;
  783. let subnet = 56;
  784. if ((0, import_node_net3.isIPv6)(ip)) {
  785. subnet = typeof config.ipv6Subnet === "function" ? await config.ipv6Subnet(request, response) : config.ipv6Subnet;
  786. if (typeof config.ipv6Subnet === "function")
  787. validations2.ipv6Subnet(subnet);
  788. }
  789. return ipKeyGenerator(ip, subnet);
  790. },
  791. ipv6Subnet: 56,
  792. async handler(request, response, _next, _optionsUsed) {
  793. response.status(config.statusCode);
  794. const message = typeof config.message === "function" ? await config.message(
  795. request,
  796. response
  797. ) : config.message;
  798. if (!response.writableEnded) response.send(message);
  799. },
  800. passOnStoreError: false,
  801. // Allow the default options to be overridden by the passed options.
  802. ...notUndefinedOptions,
  803. // `standardHeaders` is resolved into a draft version above, use that.
  804. standardHeaders,
  805. // Note that this field is declared after the user's options are spread in,
  806. // so that this field doesn't get overridden with an un-promisified store!
  807. store: promisifyStore(
  808. notUndefinedOptions.store ?? new MemoryStore(validations2)
  809. ),
  810. // Print an error to the console if a few known misconfigurations are detected.
  811. validations: validations2
  812. };
  813. if (typeof config.store.increment !== "function" || typeof config.store.decrement !== "function" || typeof config.store.resetKey !== "function" || config.store.resetAll !== void 0 && typeof config.store.resetAll !== "function" || config.store.init !== void 0 && typeof config.store.init !== "function") {
  814. throw new TypeError(
  815. "An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface."
  816. );
  817. }
  818. return config;
  819. };
  820. var handleAsyncErrors = (fn) => async (request, response, next) => {
  821. try {
  822. await Promise.resolve(fn(request, response, next)).catch(next);
  823. } catch (error) {
  824. next(error);
  825. }
  826. };
  827. var rateLimit = (passedOptions) => {
  828. const config = parseOptions(passedOptions ?? {});
  829. const options = getOptionsFromConfig(config);
  830. config.validations.creationStack(config.store);
  831. config.validations.unsharedStore(config.store);
  832. if (typeof config.store.init === "function") config.store.init(options);
  833. const middleware = handleAsyncErrors(
  834. async (request, response, next) => {
  835. const closePromise = config.skipFailedRequests && new Promise((resolve) => response.once("close", resolve));
  836. const finishPromise = (config.skipFailedRequests || config.skipSuccessfulRequests) && new Promise((resolve) => response.once("finish", resolve));
  837. const errorPromise = config.skipFailedRequests && new Promise((resolve) => response.once("error", resolve));
  838. const skip = await config.skip(request, response);
  839. if (skip) {
  840. next();
  841. return;
  842. }
  843. const augmentedRequest = request;
  844. const key = await config.keyGenerator(request, response);
  845. let totalHits = 0;
  846. let resetTime;
  847. try {
  848. const incrementResult = await config.store.increment(key);
  849. totalHits = incrementResult.totalHits;
  850. resetTime = incrementResult.resetTime;
  851. } catch (error) {
  852. if (config.passOnStoreError) {
  853. console.error(
  854. "express-rate-limit: error from store, allowing request without rate-limiting.",
  855. error
  856. );
  857. next();
  858. return;
  859. }
  860. throw error;
  861. }
  862. config.validations.positiveHits(totalHits);
  863. config.validations.singleCount(request, config.store, key);
  864. const retrieveLimit = typeof config.limit === "function" ? config.limit(request, response) : config.limit;
  865. const limit = await retrieveLimit;
  866. config.validations.limit(limit);
  867. const info = {
  868. limit,
  869. used: totalHits,
  870. remaining: Math.max(limit - totalHits, 0),
  871. resetTime,
  872. key
  873. };
  874. Object.defineProperty(info, "current", {
  875. configurable: false,
  876. enumerable: false,
  877. value: totalHits
  878. });
  879. augmentedRequest[config.requestPropertyName] = info;
  880. if (config.legacyHeaders && !response.headersSent) {
  881. setLegacyHeaders(response, info);
  882. }
  883. if (config.standardHeaders && !response.headersSent) {
  884. switch (config.standardHeaders) {
  885. case "draft-6": {
  886. setDraft6Headers(response, info, config.windowMs);
  887. break;
  888. }
  889. case "draft-7": {
  890. config.validations.headersResetTime(info.resetTime);
  891. setDraft7Headers(response, info, config.windowMs);
  892. break;
  893. }
  894. case "draft-8": {
  895. const retrieveName = typeof config.identifier === "function" ? config.identifier(request, response) : config.identifier;
  896. const name = await retrieveName;
  897. config.validations.headersResetTime(info.resetTime);
  898. setDraft8Headers(response, info, config.windowMs, name, key);
  899. break;
  900. }
  901. default: {
  902. config.validations.headersDraftVersion(config.standardHeaders);
  903. break;
  904. }
  905. }
  906. }
  907. if (config.skipFailedRequests || config.skipSuccessfulRequests) {
  908. let decremented = false;
  909. const decrementKey = async () => {
  910. if (!decremented) {
  911. await config.store.decrement(key);
  912. decremented = true;
  913. }
  914. };
  915. if (config.skipFailedRequests) {
  916. if (finishPromise) {
  917. void finishPromise.then(async () => {
  918. if (!await config.requestWasSuccessful(request, response))
  919. await decrementKey();
  920. });
  921. }
  922. if (closePromise) {
  923. void closePromise.then(async () => {
  924. if (!response.writableEnded) await decrementKey();
  925. });
  926. }
  927. if (errorPromise) {
  928. void errorPromise.then(async () => {
  929. await decrementKey();
  930. });
  931. }
  932. }
  933. if (config.skipSuccessfulRequests) {
  934. if (finishPromise) {
  935. void finishPromise.then(async () => {
  936. if (await config.requestWasSuccessful(request, response))
  937. await decrementKey();
  938. });
  939. }
  940. }
  941. }
  942. config.validations.disable();
  943. if (totalHits > limit) {
  944. if (config.legacyHeaders || config.standardHeaders) {
  945. setRetryAfterHeader(response, info, config.windowMs);
  946. }
  947. config.handler(request, response, next, options);
  948. return;
  949. }
  950. next();
  951. }
  952. );
  953. const getThrowFn = () => {
  954. throw new Error("The current store does not support the get/getKey method");
  955. };
  956. middleware.resetKey = config.store.resetKey.bind(config.store);
  957. middleware.getKey = typeof config.store.get === "function" ? config.store.get.bind(config.store) : getThrowFn;
  958. return middleware;
  959. };
  960. var rate_limit_default = rateLimit;
  961. // Annotate the CommonJS export names for ESM import in node:
  962. 0 && (module.exports = {
  963. MemoryStore,
  964. ipKeyGenerator,
  965. rateLimit
  966. });
  967. module.exports = Object.assign(rateLimit, module.exports);