🚨 Shai-Hulud Strikes Again:834 Packages Compromised.Technical Analysis →
Socket
Book a DemoInstallSign in
Socket

@betsys-nestjs/rate-limiter

Package Overview
Dependencies
Maintainers
9
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@betsys-nestjs/rate-limiter

This library serves as an abstraction for specific rate limiting of requests.

latest
npmnpm
Version
4.0.0
Version published
Maintainers
9
Created
Source

Rate limiter library

  • Serves as an abstraction for specific rate limiting of requests.
  • Specific rate limit can be set for either the whole application, controller, or a specific endpoint based on the placement of the decorator (examples below).
  • Supports any type of storage (Redis, Memory, etc.).

Dependencies

PackageVersion
@nestjs/common^9.0.0
express^4.0.0
@nestjs/core>=9.0.0 <10.0.0
reflect-metadata>=0.1.13 <0.2.0
@nestjs/terminus^9.0.0
rxjs>=7.8.0 <8.0.0

Usage

@Module({
  imports: [
    RateLimiterModule.forFeature()
  ],
})
export class AppModule {}

Rate limit counter

By default Rate limit module uses memory counter, but you can implement your own rate limit counter based on the abstraction provided by this library.

Example of redis rate limit counter using @betsys-nestjs/redis:

import { Injectable } from '@nestjs/common';
import { InjectClientWithoutKeyPrefixProvider, RedisClientWithoutKeyPrefix } from '@betsys-nestjs/redis';
import { RateLimitCounterInterface } from '@betsys-nestjs/rate-limiter'

@Injectable()
export class RedisRateLimitCounter implements RateLimitCounterInterface {
    protected TTL = 3600;
    private readonly mainRedisKey = 'REDIS_KEY'
    constructor(
      @InjectClientWithoutKeyPrefixProvider()
      protected readonly redisClientService: RedisClientWithoutKeyPrefix,
    ) {
    }

    async inc(key: string, keyType?: string): Promise<void> {
        const redisKey = `${this.mainRedisKey}:${keyType ?? 'default'}:${key}`;
        const nowInMicroseconds = Date.now() / 1000;

        await this.redisClientService.zadd(redisKey, nowInMicroseconds, nowInMicroseconds);
        await this.redisClientService.expire(redisKey, this.TTL);
    }

    async getCount(key: string, timeSpanMs: number, keyType?: string): Promise<number> {
        const redisKey = `${this.mainRedisKey}:${keyType ?? 'default'}:${key}`;
        const nowInMicroseconds = Date.now() / 1000;

        return this.redisClientService.eval(
            this.getCountLuaScript(),
            1,
            [redisKey, timeSpanMs, nowInMicroseconds],
        ) as unknown as Promise<number>;
    }

    private getCountLuaScript = (): string => `
        -- NAME: nestjs:rate_limiter

        local key = KEYS[1]
        local window = tonumber(ARGV[1])
        local now = tonumber(ARGV[2])

        redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)

        return redis.call('ZLEXCOUNT', key, '-', '+')
    `;
}

To start using RedisRateLimitCounter, insert class reference, with RedisModule to forFeature method in RateLimiter.module like this:

import { RedisModule } from '@betsys-nestjs/redis'

@Module({
  imports: [
    RateLimiterModule.forFeature({
        imports: [RedisModule.forFeature({
            prefix: 'REDIS_PREFIX',
            redisOptions: {
                commandTimeout: 360000,
            },
        })],
        counter: RedisRateLimitCounter,
    })
  ],
})
export class AppModule {}

Guards

  • The main logic of rate limiting in this library is based on the functionality of Nest.js guards.
  • Every guard needs to extend the abstract RateLimiterGuard and be Injectable.

Example implementation:

@Injectable()
export class IpRateLimiterGuard extends RateLimiterGuard {
    constructor(
        @InjectRateLimitCounter() protected readonly limitCounter: RateLimitCounterInterface,
        @Inject(KEY) protected readonly config: RateLimiterInstanceConfig,
    ) {
        super(
            config, // Config can also be declared here directly, instead of having a separate config file
            (req: Request): KeyResolverInterface => {
                return {
                    key: req.ip,
                    keyType: 'ip',
                };
            },
            limitCounter, // Counter can also be constructed here if it does not require DI (e.g. Memory storage)
            () => {
                // This is the callback, that is called upon exceeding the set limit from the configuration
                throw new TooManyRequestsForPhoneException();
            },
        );
    }
}

Example usage:

  • whole application or a module:
@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: IpRateLimiterGuard,
    },
  ],
})
export class AppModule {}
  • whole controller with all its methods:
@UseGuards(IpRateLimiterGuard)
export class CatsController {}
  • single method in controller:
@UseGuards(IpRateLimiterGuard)
async verify(@Req() req: Request, @Res() res: Response) {}

Exception filter

  • Since in most of the use cases it is wanted to return a custom HTTP response based on the thrown exceeded rate limit exception, we have created a simple exception filter, that can be used to do so.

Example implementation:

  • Every exception thrown in the exceeded limit callback must extend the RateLimitExceededBaseException from within the library.
export class TooManyRequestsFromIpException extends RateLimitExceededBaseException {
    constructor() {
        super('You have had too many requests from your IP address.');
    }
}

Example usage:

  • you must register the exception filter in the application bootstrap
app.useGlobalFilters(new RateLimitExceededExceptionFilter());

FAQ

  • Q: How can I use multiple rate limits at the same time?
  • A: Simply provide all of them to the @UseGuards decorator or the application globals. Their order is from the first one to the last one if setup with one decorator and the other way around if set up by multiple @UseGuards decorators. @UseGuards(PhoneRateLimiterGuard, IpRateLimiterGuard, ...)

FAQs

Package last updated on 09 Oct 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts