Coder Social home page Coder Social logo

cloudnode-pro / ratelimit Goto Github PK

View Code? Open in Web Editor NEW
2.0 0.0 0.0 287 KB

Simple ratelimiter for Node.js

Home Page: https://cloudnode.pro

License: GNU General Public License v3.0

JavaScript 53.58% TypeScript 46.42%
limit limiter rate ratelimit ratelimiter

ratelimit's Introduction

Rate limiting utility

npm npm downloads test: passing coverage: 100% build: passing CodeQL

A relatively simple utility for abstract rate limiting. This library uses memory storage (i.e. does not rely on external database or writing data on your file system). Rate limits are reset if the process is restarted.

Get started

Install package from npm

npm i cldn-ratelimit

Import in your project

Here is a very simple demo demonstrating very basic limiting of login attempts.

import {RateLimit} from 'cldn-ratelimit';

const rateLimit = new RateLimit("login-attempts", 3, 60); // max 3 requests per 60 seconds

const attemptLogin = (username, password) => {
	if (!rateLimit.attempt(username).allow) return "rate-limited";
	if (username === "john.doe" && password === "password123") return "success";
	return "wrong-password";
}

attemptLogin("john.doe", "wrongpass"); //-> "wrong-password"
attemptLogin("john.doe", "wrongpass2"); //-> "wrong-password"
attemptLogin("john.doe", "wrongpass"); //-> "wrong-password"
attemptLogin("john.doe", "password123"); //-> "rate-limited"
// wait 60 seconds
attemptLogin("john.doe", "password123"); //-> "success"

If you want to reset the rate limit after a successful login, call rateLimit.reset(username).

Documentation

Table of contents

Class: RateLimit

Rate limit

Static method: RateLimit.attempt(name, source, [attempts], [callback])

Make an attempt with a source ID

  • name string The name of the rate limit
  • source string Unique source identifier (e.g. username, IP, etc.)
  • attempts number The number of attempts to make. Default: 1
  • callback function Callback function. Default: undefined
  • Returns: AttemptResult
  • Throws: Error If the rate limit does not exist

Static method: RateLimit.check(name, source, [callback])

Check the attempt state for a source ID without decrementing the remaining attempts

  • name string The name of the rate limit
  • source string Unique source identifier (e.g. username, IP, etc.)
  • callback function Callback function. Default: undefined
  • Returns: AttemptResult
  • Throws: Error If the rate limit does not exist

Static method: RateLimit.clear(name)

Clear rate limit attempts storage. This is equivalent to resetting all rate limits.

  • name string The name of the rate limit
  • Returns: void
  • Throws: Error If the rate limit does not exist

Static method: RateLimit.create(name, limit, timeWindow)

Create a new rate limit

  • name string The name of the rate limit
  • limit number The number of attempts allowed per time window (e.g. 60)
  • timeWindow number The time window in seconds (e.g. 60)
  • Returns: RateLimit

Static method: RateLimit.delete(name)

Delete the rate limit instance. After it is deleted, it should not be used any further without constructing a new instance.

  • name string The name of the rate limit
  • Returns: void
  • Throws: Error If the rate limit does not exist

Static method: RateLimit.get(name)

Get a rate limit instance

Static method: RateLimit.reset(name, source)

Reset limit for a source ID. The storage entry will be deleted and a new one will be created on the next attempt.

  • name string The name of the rate limit
  • source string Unique source identifier (e.g. username, IP, etc.)
  • Returns: void
  • Throws: Error If the rate limit does not exist

Static method: RateLimit.setRemaining(name, source, remaining)

Set the remaining attempts for a source ID.

Warning: This is not recommended as the remaining attempts depend on the limit of the instance.

  • name string The name of the rate limit
  • source string Unique source identifier (e.g. username, IP, etc.)
  • remaining number The number of remaining attempts
  • Returns: void
  • Throws: Error If the rate limit does not exist

new RateLimit(name, limit, timeWindow)

Create a new rate limit

  • name string The name of the rate limit
  • limit number The number of attempts allowed per time window (e.g. 60)
  • timeWindow number The time window in seconds (e.g. 60)
  • Throws: Error If the rate limit already exists

rateLimit.attempt(source, [attempts], [callback])

Make an attempt with a source ID

rateLimit.check(source, [callback])

Check the attempt state for a source ID without decrementing the remaining attempts

rateLimit.clear()

Clear rate limit attempts storage. This is equivalent to resetting all rate limits.

rateLimit.delete()

Delete the rate limit instance. After it is deleted, it should not be used any further without constructing a new instance.

rateLimit.limit

The number of requests allowed per time window

rateLimit.name

Get rate limit name

rateLimit.reset(source)

Reset limit for a source ID. The storage entry will be deleted and a new one will be created on the next attempt.

  • source string Unique source identifier (e.g. username, IP, etc.)
  • Returns: void

rateLimit.setRemaining(source, remaining)

Set the remaining attempts for a source ID.

Warning: This is not recommended as the remaining attempts depend on the limit of the instance.

  • source string Unique source identifier (e.g. username, IP, etc.)
  • remaining number The number of remaining attempts
  • Returns: void

rateLimit.timeWindow

The time window in seconds (e.g. 60)

Interface: AttemptResult

The result from a rate limit attempt

attemptResult.limit

The number of requests this rate limit allows per time window

attemptResult.remaining

The number of requests remaining in the current time window

attemptResult.reset

The number of seconds until the current time window resets

attemptResult.rateLimit

The rate limit that this attempt was made on

attemptResult.allow

Whether this attempt should be allowed to proceed. If false, the attempt is rate limited.

ratelimit's People

Contributors

dependabot[bot] avatar zefir-git avatar

Stargazers

 avatar

ratelimit's Issues

Add optional arg for callback

Implement to relevant methods an optiona arg for callback. If callback is provided, method response is also sent to the callback.

This can also be useful for implementing express middleware in the future.

Option for dual source input

Allow providing an array of source strings. An attempt should be recorded for both source IDs and the attempt should fail if either of the sources is limited.

A way to make an attempt and decide whether to count it later

Is your feature request related to a problem? Please describe.
When making an attempt that ends up with an error, the attempt is still recorded.

Describe the solution you'd like
Some way that would allow you to decide later whether to count the attempt towards the source's attempts, perhaps using a callback of some sort.

Express middleware

Implement an easy way to implement rate limits with Express using middleware

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.