GithubHelp home page GithubHelp logo

rayriffy / elysia-rate-limit Goto Github PK

View Code? Open in Web Editor NEW
72.0 2.0 5.0 225 KB

Lightweight rate limiter plugin for Elysia.js

Home Page: https://npm.im/elysia-rate-limit

License: MIT License

TypeScript 100.00%
elysia rate-limit rate-limiting api bun middleware

elysia-rate-limit's People

Contributors

armada45-pixel avatar github-actions[bot] avatar rayriffy avatar ricardo-devis-agullo avatar tnfangel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

elysia-rate-limit's Issues

[BUG] On limit exceeded, response is not given

Before open the issue

  • I tried remove node_modules/, bun.lockb, and do a clean installation.
  • I tried update Bun, and Elysia to latest version.

Describe the bug
When a user reach the limit, the response is never given

To Reproduce
Please provide a small reproduction project if possible. Steps to reproduce the behavior:

  1. Go to 'https://github.com/qlaffont/starter-elysia'
  2. Run bun i && docker-compose up -d && cp .env.example .env && bun dev
  3. Go to http://localhost:3000/swagger and execute /auth/login with random password and email more than 6 times
  4. You will see that the response is never given to the client on 6th time

Expected behavior
A clear and concise description of what you expected to happen.
Return response 429

Environments

  1. Bun version: 1.1.0
  2. Host Operating system: Linux pop-os 6.8.0-76060800daily20240311-generic #202403110203171139393022.04~331756a SMP PREEMPT_DYNAMIC Mon M x86_64 x86_64 x86_64 GNU/Linux
  3. Running on Docker?: no

Screenshots
image
image

Additional Context
For me I have checked source code, nothing seems strange or with bugs. So maybe elysia directly ?

Default generator is unable to determine client IP address

image

Describe the bug
Default generator is unable to determine client IP address.

To Reproduce
I used the example code in README

import { Elysia } from 'elysia'
import { rateLimit } from 'elysia-rate-limit'

const app = new Elysia().use(rateLimit({
        max: 1,
        duration: 60,
        responseMessage: "Too many login attempts. Please try again later.",
    }))
    .post(...)
    .listen(3000)

Expected behavior
It should just work

Additional context
Versions
Bun: 1.0.33
elysia-rate-limit: 3.0.0

Let me know if other details would help!

Response is never given to the user

Before open the issue

  • I tried remove node_modules/, bun.lockb, and do a clean install.

Describe the bug
A clear and concise description of what the bug is.
The response is not given (until it exceed the limit).

To Reproduce
Steps to reproduce the behavior:

  1. Clone 'https://github.com/qlaffont/starter-elysia/tree/master'
  2. Uncomment src/loader/RestLoader.ts lines 2 & 12-37
  3. bun dev
  4. Go to http://localhost:3000/ping

Expected behavior
On call to /ping, should return {ping : "pong"}

Throw the bearer utility into the generator

Is it possible to somehow throw the bearer utility into the generator?

import bearer from '@elysiajs/bearer'

const app = new Elysia()
  .use(cors())
  .use(bearer())
  .use(
    rateLimit({
      generator: (req) => {
        console.log(req.headers, bearer)
        return bearer
      },
    })
  )
  .use(v1)
  .listen(3000)

Duplicate run when use multiple time

Before open the issue

  • I tried remove node_modules/, bun.lockb, and do a clean installation.
  • I tried update Bun, and Elysia to latest version.

Describe the bug
Like title
Duplicate run when use multiple time
Issue example
gaurishhs/elysia-ip#18 (comment)

onBeforehandler will stack not repleace them seft if not using name in plugin instance

new Elysia()

and name it using

new Elysia({ name: "elysia-rate-limit" })

Screenshots
image

Elysia is not initialized yet. Please call .listen() first.

Before open the issue

  • I tried remove node_modules/, bun.lockb, and do a clean installation.
  • I tried update Bun, and Elysia to latest version.

Describe the bug
A clear and concise description of what the bug is.
when I use rateLimit on Elysia and I start the server with app.listen(), the rateLimit package plugin throws an error saying "Elysia is not initialized yet. Please call .listen() first."

To Reproduce
Please provide a small reproduction project if possible. Steps to reproduce the behavior:

const app = new Elysia()

app.group('/group', (app) =>
  app.use(
    rateLimit({
      duration: 1000 * 60 * 60 * 24, // a day
      max: 1000,
      generator: (req, server) => server?.requestIP(req)?.address ?? "",
    }),
  ).get('/', () => 'Hello World')
)

app.listen(3000)

then run the file with

bun --watch <path-to-the-file>

make a request to the endpoint

curl --request GET \
  --url http://localhost:3000/group/

and see the server logs:

    e:  9 |     options.context.init(options);
  10 |     return (app) => {
  11 |         app.onBeforeHandle({ as: 'global' }, async ({ set, request }) => {
  12 |             let clientKey;
  13 |             if (app.server === null)
  14 |                 throw new Error('Elysia is not initialized yet. Please call .listen() first.');
                             ^
  error: Elysia is not initialized yet. Please call .listen() first.
        at path-to-your-project/node_modules/elysia-rate-limit/dist/services/plugin.js:14:23
        at path-to-your-project/node_modules/elysia-rate-limit/dist/services/plugin.js:11:55

Expected behavior
don't throw an error saying you haven't called app.listen() if you indeed did.

Environments

  1. Bun version: 1.0.35
  2. Host Operating system:
  3. Running on Docker?: no

Screenshots
If applicable, add screenshots to help explain your problem.
image

Additional context
Add any other context about the problem here.

Unable to determine client IP

I am currently using bun 1.0.22, elysia 0.8.8 and elysia rate limit 2.0.1.
I am using it like this

.use(
    rateLimit({
      duration: 10000,
    })
  )

and it is showing in the terminal:
[elysia-rate-limit] generator is unable to determine client IP address. Are you using older version of Bun?

Use LRU cache for default context

Is your feature request related to a problem? Please describe.
The default context doesn't have a memory limit, which can be problematic when a server is heavily requested.

Describe the solution you'd like
That the default context uses a cache with a limit you can customize so you can control the max memory it will use.

Describe alternatives you've considered
The other option would be to let users implement it themselves on their own context, but I think it's a good default to have.

Additional context
The idea would be to use a lru cache, like @fastify/rate-limit does, and then add a new option like cache where you can customize to size of the cache.

Happy to do a PR if this is approved.

Rate limit for individual endpoint

Is your feature request related to a problem? Please describe.
Currently I am rate limiting the project with 10 requests per minute, but is it possible we can have rate limit for individual endpoints or group of endpoints? For instance, you may only be able to request SMS verification code once every 60 seconds, but for retrieving the data you can do max 10 requests every minute.

Describe the solution you'd like
An argument that set the rate limit for individual endpoint without sharing the limit across the connection.

Describe alternatives you've considered
I’ve thought that I may introduce the rate limit in each endpoint, but it adds extra code and complexity.

rateLimit for each path has a common counter

If we set rateLimit for each Route, this limit will be shared. So if we use up the limit on one of the Routes, we will be blocked everywhere.
Solution: we need to keep a counter for each Route

const smsVerificationRoutes = new Elysia()
  .use(rateLimit())
  // your sms routes here

const apiRoutes = new Elysia()
  .use(rateLimit())
  // your api routes here

const server = new Elysia()
  .use(smsVerificationRoutes)
  .use(apiRoutes)
  .listen(3000)

Using guard does not help

const routerAuth = new Elysia().group('/auth', (app) =>
  app
    .guard((app) =>
      app
        .use(rateLimit())
...

duration overwritten

As a result, the duration in smsVerificationRoutes will be 200 seconds instead of 100, which is an error.

const smsVerificationRoutes = new Elysia()
  .use(rateLimit({
  duration: 100000
}))
  // your sms routes here

const apiRoutes = new Elysia()
  .use(rateLimit({
  duration: 200000
}))
  // your api routes here

const server = new Elysia()
  .use(smsVerificationRoutes)
  .use(apiRoutes)
  .listen(3000)

smsVerificationRoutes
Ratelimit-Reset:
200
Retry-After:
100

apiRoutes
Ratelimit-Reset:
200
Retry-After:
200

Ability to hide Ratelimit-* headers

Please consider adding an option to the configuration to hide Ratelimit-* response headers
There are probably scenarios where you don't want to reveal limit information on a particular route.

Unable to determine client IP address

Before open the issue

  • I tried remove node_modules/, bun.lockb, and do a clean installation.
  • I tried update Bun, and Elysia to latest version.

Describe the bug
[elysia-rate-limit] generator is unable to determine client IP address. Are you using older version of Bun?

To Reproduce
I imported and called .use(), nothing else.
Screenshot 2024-04-02 at 05 05 16

Expected behavior
This error message should not appear, and plugin can successfully detect the IP address.

Environments

  1. Bun version: 1.1.0
  2. Host Operating system: macOS 14.4.1
  3. Running on Docker?: no

Screenshots
If applicable, add screenshots to help explain your problem.
Screenshot 2024-04-02 at 05 03 39

Additional context
package.json:

{
  "name": "study-app",
  "version": "1.0.2",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "bun run --watch src/index.ts",
    "start": "NODE_ENV=production bun run src/index.ts"
  },
  "dependencies": {
    "@elysiajs/bearer": "^1.0.2",
    "@elysiajs/cors": "^1.0.2",
    "@elysiajs/jwt": "^1.0.2",
    "@elysiajs/static": "^1.0.2",
    "@elysiajs/swagger": "^0.8.5",
    "@types/pluralize": "^0.0.33",
    "elysia": "^1.0.10",
    "elysia-rate-limit": "^3.1.0",
    "ioredis": "^5.3.2",
    "mongoose": "^8.2.1",
    "openai": "^4.31.0",
    "pluralize": "^8.0.0",
    "tencentcloud-sdk-nodejs-sms": "^4.0.789",
    "uuid": "^9.0.1"
  },
  "devDependencies": {
    "@types/uuid": "^9.0.8",
    "bun-types": "latest"
  },
  "module": "src/index.js"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.