{"name":"rate-limiter-flexible","version":"2.3.3","keywords":["authorization","security","rate","limit","ratelimter","brute","force","bruteforce","throttle","koa","express","hapi","auth","ddos","queue"],"author":{"name":"animir","email":"animirr@gmail.com"},"license":"ISC","_id":"rate-limiter-flexible@2.3.3","maintainers":[{"name":"animir","email":"animirr@gmail.com"}],"homepage":"https://github.com/animir/node-rate-limiter-flexible#readme","bugs":{"url":"https://github.com/animir/node-rate-limiter-flexible/issues"},"dist":{"shasum":"1f119a2657eff037f1939aa3c17e6453822d635b","tarball":"http://registry-npm.ywwl.com/rate-limiter-flexible/download/rate-limiter-flexible-2.3.3.tgz","fileCount":29,"integrity":"sha512-1LYLzApGP5snBf/VP/PEYpWRnPiCYlPA7nqXq9VawQCFZ9Uc2pYgeOjeyNuoNRO+tUzOQuEA5IISaltbiMU2tg==","signatures":[{"sig":"MEQCIBFwOMdFJDK58PpN91+wXp0A1Kg00BZeAa2zcjR911TwAiBP/uQknWEqv6uCznMbo93GTFImOcr5xYbx3r8bYEE9xQ==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":119821,"size":24961,"noattachment":false,"key":"/rate-limiter-flexible/-/rate-limiter-flexible-2.3.3.tgz"},"main":"index.js","types":"./lib/index.d.ts","gitHead":"f3f237b321cbbab0833e0615f7762feb281e1da5","scripts":{"test":"istanbul -v cover -- _mocha --recursive","eslint":"eslint --quiet lib/**/**.js test/**/**.js","coveralls":"cat ./coverage/lcov.info | coveralls","debug-test":"mocha --inspect-brk lib/**/**.test.js","eslint-fix":"eslint --fix lib/**/**.js test/**/**.js"},"_npmUser":{"name":"animir","email":"animirr@gmail.com"},"repository":{"url":"git+https://github.com/animir/node-rate-limiter-flexible.git","type":"git"},"_npmVersion":"6.14.11","description":"Node.js rate limiter by key and protection from DDoS and Brute-Force attacks in process Memory, Redis, MongoDb, Memcached, MySQL, PostgreSQL, Cluster or PM","directories":{},"_nodeVersion":"12.21.0","_hasShrinkwrap":false,"devDependencies":{"chai":"^4.1.2","mocha":"^5.1.1","sinon":"^5.0.10","eslint":"^4.19.1","istanbul":"^0.4.5","coveralls":"^3.0.1","redis-mock":"^0.48.0","memcached-mock":"^0.1.0","eslint-plugin-node":"^6.0.1","eslint-plugin-import":"^2.7.0","eslint-plugin-security":"^1.4.0","eslint-config-airbnb-base":"^12.1.0"},"_npmOperationalInternal":{"tmp":"tmp/rate-limiter-flexible_2.3.3_1635727716122_0.5533175247941267","host":"s3://npm-registry-packages"},"readme":"[![npm version](https://badge.fury.io/js/rate-limiter-flexible.svg)](https://www.npmjs.com/package/rate-limiter-flexible)\n![npm](https://img.shields.io/npm/dm/rate-limiter-flexible.svg)\n[![node version][node-image]][node-url]\n[![deno version](https://img.shields.io/badge/deno-^1.5.3-lightgrey?logo=deno)](https://github.com/denoland/deno)\n\n[node-image]: https://img.shields.io/badge/node.js-%3E=_20.0-green.svg?style=flat-square\n[node-url]: http://nodejs.org/download/\n\n<img src=\"img/rlflx-logo-small.png\" width=\"50\" alt=\"Logo\"/>\n\n## node-rate-limiter-flexible\n\n**rate-limiter-flexible** counts and limits the number of events and protects from DoS and brute force attacks at any scale.\n\nIt works with _Valkey_, _Redis_, _Prisma_, _DynamoDB_, process _Memory_, _Cluster_ or _PM2_, _Memcached_, _MongoDB_, _MySQL_, _SQLite_, and _PostgreSQL_.\n\nMemory limiter also works in the browser.\n\n**AI tools** See [llms.txt](https://github.com/animir/node-rate-limiter-flexible/blob/master/llms.txt) and [CONTEXT.md](https://github.com/animir/node-rate-limiter-flexible/blob/master/CONTEXT.md) for LLM-friendly documentation.\n\n**Atomic increments.** All operations in memory or distributed environment use atomic increments against race conditions.\n\n**Fast.** Average request takes `0.7ms` in Cluster and `2.5ms` in Distributed application. See [benchmarks](https://github.com/animir/node-rate-limiter-flexible#benchmark).\n\n**Flexible.** Combine limiters, block key for some duration, delay actions, manage failover with insurance options, configure smart key blocking in memory and many others.\n\n**Ready for growth.** It provides a unified API for all limiters. Whenever your application grows, it is ready. Prepare your limiters in minutes.\n\n**Friendly.** No matter which node package you prefer: [`valkey-glide`](https://www.npmjs.com/package/@valkey/valkey-glide) or [`iovalkey`](https://www.npmjs.com/package/iovalkey), `redis` or `ioredis`, `sequelize`/`typeorm` or `knex`, `memcached`, native driver or `mongoose`. It works with all of them.\n\n**In-memory blocks.** Avoid extra requests to store with [inMemoryBlockOnConsumed](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#inmemoryblockonconsumed).\n\n**Deno compatible** See [this example](https://gist.github.com/animir/d06ca92931677f330d3f2d4c6c3108e4) \n\nThe Flexible Fixed Window algorithm starts counting from the moment a request is received, diversifying rate limit reset times across clients. Read more [here](https://github.com/animir/node-rate-limiter-flexible/wiki/Fixed-Window-rate-limiting-algorithm-explained)\n\n## Installation\n\n`npm i --save rate-limiter-flexible`\n\n`yarn add rate-limiter-flexible`\n\n## Import\n  \n  ```javascript\n  import { RateLimiterMemory } from \"rate-limiter-flexible\";\n  \n  // or import directly\n  import RateLimiterMemory from \"rate-limiter-flexible/lib/RateLimiterMemory.js\";\n  ```\n\n## Basic Example\n\nPoints can be consumed by IP address, user ID, authorisation token, API route or any other string.\n\n```javascript\nconst opts = {\n  points: 6, // 6 points\n  duration: 1, // Per second\n};\n\nconst rateLimiter = new RateLimiterMemory(opts);\n\nrateLimiter.consume(remoteAddress, 2) // consume 2 points\n    .then((rateLimiterRes) => {\n      // 2 points consumed\n    })\n    .catch((rateLimiterRes) => {\n      // Not enough points to consume\n    });\n```\n\n#### RateLimiterRes object\n\nThe Promise's `resolve` and `reject` callbacks both return an instance of the `RateLimiterRes` class if there is no error.\nObject attributes:\n```javascript\nRateLimiterRes = {\n    msBeforeNext: 250, // Number of milliseconds before next action can be done\n    remainingPoints: 0, // Number of remaining points in current duration \n    consumedPoints: 5, // Number of consumed points in current duration \n    isFirstInDuration: false, // action is first in current duration \n}\n```\n\nYou may want to set HTTP headers for the response:\n```javascript\nconst headers = {\n  \"Retry-After\": rateLimiterRes.msBeforeNext / 1000,\n  \"X-RateLimit-Limit\": opts.points,\n  \"X-RateLimit-Remaining\": rateLimiterRes.remainingPoints,\n  \"X-RateLimit-Reset\": Math.ceil((Date.now() + rateLimiterRes.msBeforeNext) / 1000)\n}\n```\n\n### Advantages:\n* no race conditions\n* no production dependencies\n* TypeScript declaration bundled\n* Block Strategy against really powerful DoS attacks (like 100k requests per sec) [Read about it and benchmarking here](https://github.com/animir/node-rate-limiter-flexible/wiki/In-memory-Block-Strategy)\n* Insurance Strategy as emergency solution if database/store is down [Read about Insurance Strategy here](https://github.com/animir/node-rate-limiter-flexible/wiki/Insurance-Strategy)\n* works in Cluster or PM2 without additional software [See RateLimiterCluster benchmark and detailed description here](https://github.com/animir/node-rate-limiter-flexible/wiki/Cluster)\n* useful `get`, `set`, `block`, `delete`, `penalty` and `reward` methods\n\nFull documentation is on [Wiki](https://github.com/animir/node-rate-limiter-flexible/wiki)\n\n### Middlewares, plugins and other packages\n* [Express middleware](https://github.com/animir/node-rate-limiter-flexible/wiki/Express-Middleware)\n* [Koa middleware](https://github.com/animir/node-rate-limiter-flexible/wiki/Koa-Middleware)\n* [Hapi plugin](https://github.com/animir/node-rate-limiter-flexible/wiki/Hapi-plugin)\n* GraphQL [graphql-rate-limit-directive](https://www.npmjs.com/package/graphql-rate-limit-directive)\n* NestJS [nestjs-rate-limiter](https://www.npmjs.com/package/nestjs-rate-limiter)\n* Fastify-based NestJS app try [nestjs-fastify-rate-limiter](https://www.npmjs.com/package/nestjs-fastify-rate-limiter)\n\nCopy/paste examples on Wiki:\n* [Minimal protection against password brute-force](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#minimal-protection-against-password-brute-force)\n* [Login endpoint protection](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#login-endpoint-protection)\n* [Apply Block Strategy](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#apply-in-memory-block-strategy-to-avoid-extra-requests-to-store)\n* [Setup Insurance Strategy](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#setup-insurance-strategy-for-store-limiters)\n* [Websocket connection prevent flooding](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#websocket-single-connection-prevent-flooding)\n* [Dynamic block duration](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#dynamic-block-duration)\n* [Authorized users specific limits](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users)\n* [Different limits for different parts of application](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#different-limits-for-different-parts-of-application)\n* [Third-party API, crawler, bot rate limiting](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#third-party-api-crawler-bot-rate-limiting)\n\n### Migration from other packages\n* [express-brute](https://github.com/animir/node-rate-limiter-flexible/wiki/ExpressBrute-migration) Bonus: race conditions fixed, prod deps removed\n* [limiter](https://github.com/animir/node-rate-limiter-flexible/wiki/RateLimiterQueue#migration-from-limiter) Bonus: multi-server support, respects queue order, native promises\n\n### Docs and Examples\n\n* [Options](https://github.com/animir/node-rate-limiter-flexible/wiki/Options)\n* [API methods](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods)\n\n* [Drizzle](https://github.com/animir/node-rate-limiter-flexible/wiki/Drizzle) Atomic and non-atomic counters.\n* [DynamoDb](https://github.com/animir/node-rate-limiter-flexible/wiki/DynamoDB)\n* [Etcd](https://github.com/animir/node-rate-limiter-flexible/wiki/Etcd) Atomic and non-atomic counters.\n* [Memcached](https://github.com/animir/node-rate-limiter-flexible/wiki/Memcache)\n* [Memory](https://github.com/animir/node-rate-limiter-flexible/wiki/Memory) Supports dump() and restore() for graceful restarts and green/blue deployment\n* [Mongo](https://github.com/animir/node-rate-limiter-flexible/wiki/Mongo) (with [sharding support](https://github.com/animir/node-rate-limiter-flexible/wiki/Mongo#mongodb-sharding-options))\n* [MySQL](https://github.com/animir/node-rate-limiter-flexible/wiki/MySQL) (support Sequelize and Knex)\n* [Postgres](https://github.com/animir/node-rate-limiter-flexible/wiki/PostgreSQL) (support Sequelize, TypeORM and Knex)\n* [Prisma](https://github.com/animir/node-rate-limiter-flexible/wiki/Prisma)\n* [Redis](https://github.com/animir/node-rate-limiter-flexible/wiki/Redis) Atomic and non-atomic counters.\n* [SQLite](https://github.com/animir/node-rate-limiter-flexible/wiki/SQLite)\n* Valkey: [iovalkey](https://github.com/animir/node-rate-limiter-flexible/wiki/IoValkey) or [ValkeyGlide](https://github.com/animir/node-rate-limiter-flexible/wiki/Valkey-Glide)\n* [RateLimiterCluster](https://github.com/animir/node-rate-limiter-flexible/wiki/Cluster) ([PM2 cluster docs read here](https://github.com/animir/node-rate-limiter-flexible/wiki/PM2-cluster))\n* [BurstyRateLimiter](https://github.com/animir/node-rate-limiter-flexible/wiki/BurstyRateLimiter) Traffic burst support\n* [RateLimiterUnion](https://github.com/animir/node-rate-limiter-flexible/wiki/RateLimiterUnion) Combine 2 or more limiters to act as single\n* [RLWrapperBlackAndWhite](https://github.com/animir/node-rate-limiter-flexible/wiki/Black-and-White-lists) Black and White lists\n* [RLWrapperTimeouts](https://github.com/animir/node-rate-limiter-flexible/wiki/RLWrapperTimeouts) Timeouts\n* [RateLimiterQueue](https://github.com/animir/node-rate-limiter-flexible/wiki/RateLimiterQueue) Rate limiter with FIFO queue\n* [AWS SDK v3 Client Rate Limiter](https://github.com/animir/node-rate-limiter-flexible/wiki/AWS-SDK-v3-Client-Rate-Limiter) Prevent punishing rate limit.\n\n### Changelog\n\nSee [releases](https://github.com/animir/node-rate-limiter-flexible/releases) for detailed changelog.\n\n## Basic Options\n\n* **points** \n    \n    `Required` \n    \n    Maximum number of points that can be consumed over duration\n\n* **duration** \n\n    `Required` \n    \n    Number of seconds before consumed points are reset.\n    \n    Points are never reset if `duration` is set to 0.\n\n* **storeClient** \n\n    `Required for store limiters` \n\n    Must be pool or connection created with store client packages, e.g. `@valkey/valkey-glide`, `ioredis`, `iovalkey`, `redis`,  `memcached`, `mongodb`, `pg`, `mysql2`, `mysql`, etc.\n\n### Other options on Wiki:\n* [keyPrefix](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#keyprefix) Make keys unique among different limiters.\n* [blockDuration](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#blockduration) Block for N seconds, if consumed more than points.\n* [inMemoryBlockOnConsumed](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#inmemoryblockonconsumed) Avoid extra requests to store.\n* [inMemoryBlockDuration](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#inmemoryblockduration)\n* [insuranceLimiter](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#insurancelimiter) Make it more stable with less efforts.\n* [storeType](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#storetype) Have to be set to `knex`, if you use it.\n* [dbName](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#dbname) Where to store points.\n* [tableName](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#tablename) Table/collection.\n* [tableCreated](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#tablecreated) Is table already created in MySQL, SQLite or PostgreSQL.\n* [clearExpiredByTimeout](https://github.com/animir/node-rate-limiter-flexible/wiki/Options#clearexpiredbytimeout) For MySQL, SQLite and PostgreSQL.\n\nSee [full list of options](https://github.com/animir/node-rate-limiter-flexible/wiki/Options).\n\n## API\n\nRead detailed description on Wiki.\n\n* [consume(key, points = 1)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimiterconsumekey-points--1) Consume points by key.\n* [get(key)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimitergetkey) Get `RateLimiterRes` or `null`.\n* [set(key, points, secDuration)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimitersetkey-points-secduration) Set points by key.\n* [block(key, secDuration)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimiterblockkey-secduration) Block key for `secDuration` seconds.\n* [delete(key)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimiterdeletekey) Reset consumed points.\n* [deleteInMemoryBlockedAll](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimiterdeleteinmemoryblockedall)\n* [penalty(key, points = 1)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimiterpenaltykey-points--1) Increase number of consumed points in current duration.\n* [reward(key, points = 1)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimiterrewardkey-points--1) Decrease number of consumed points in current duration.\n* [getKey(key)](https://github.com/animir/node-rate-limiter-flexible/wiki/API-methods#ratelimitergetkeykey) Get internal prefixed key.\n\n## Contributions\n\nAppreciated, feel free!\n\nMake sure you've launched `npm run eslint` before creating PR, all errors have to be fixed.\n\nYou can try to run `npm run eslint-fix` to fix some issues.\n\nAny new limiter with storage must be extended from `RateLimiterStoreAbstract`.\nIt has to implement 4 methods:\n* `_getRateLimiterRes` parses raw data from store to `RateLimiterRes` object.\n* `_upsert` may be atomic or non-atomic upsert (increment). It inserts or updates the value by key and returns raw data. \n    If it doesn't make an atomic upsert (increment), the class should be suffixed with `NonAtomic`, e.g. `RateLimiterRedisNonAtomic`. \n    \n    It must support `forceExpire` mode to overwrite key expiration time.\n* `_get` returns raw data by key or `null` if there is no key.\n* `_delete` deletes all key-related data and returns `true` on deleted, `false` if key is not found.\n\nAll other methods depend on the store. See `RateLimiterRedis` or `RateLimiterPostgres` for examples.\n\nFor wrapper classes that don't need full `RateLimiterAbstract` functionality, extend `RateLimiterCompatibleAbstract` instead. It requires implementing `consume`, `penalty`, `reward`, `get`, `set`, `block`, `delete` methods and `blockDuration`/`execEvenly` getters/setters. If the wrapper doesn't use `blockDuration` or `execEvenly`, empty no-op implementations can be provided. See `RLWrapperBlackAndWhite` for an example.\n\nNote: all changes should be covered by tests.\n","publish_time":1635727716282,"_cnpm_publish_time":1635727716282,"dist-tags":{"latest":"11.5.0"}}