Skip to content

Commit

Permalink
feat(module): implements start of limiter module
Browse files Browse the repository at this point in the history
  • Loading branch information
jmcdo29 committed May 30, 2020
0 parents commit 35dbff5
Show file tree
Hide file tree
Showing 22 changed files with 7,341 additions and 0 deletions.
24 changes: 24 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
root: true,
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
34 changes: 34 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# compiled output
/dist
/node_modules

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# OS
.DS_Store

# Tests
/coverage
/.nyc_output

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# The MIT License

Copyright 2019 Jay McDoniel, contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Nest Rate Limiter Package

## Decorator

@RateLimit(limit: number = 20, ttl: number = 60)

This decorator will set MAX_LIMIT and TTL_LIMIT metadatas on the route, for retrieval from the `Reflector` class. Can be applied to controllers and routes

## RateLimitGuard

Global guard. Check if metadata exists for guard. If not, check if route is in `ignoreList`. If so, return `true`. If not, apply defaults from package (configured via module).
If metadata does exist, use metadata instead of defaults (easy overriding)
Pull rateStorage from `RateStorage` class via `getRecord()` method. Will return a number, if number is gte max, return `false`. If value is less than max, add value to `RateStorage` with `addRecord()` and return `true`

## RateStorage

Class to handle the details when it comes to keeping track of the requests. Early implementation would be something like this
```ts
class RateStorage {
private storage: Record<string, number>;

addRecord(key: string, ttl: number): void {
this.storage[key] = this.storage[key] ? this.storage[key] + 1 : 1;
setTimeout(() => this.storage[key]--, ttl * 1000)
}

getRecord(key: string): number {
return this.storage[key] || 0;
}
}
```

More than likely, the key would be a mixture of IP and REST route, to allow for keeping each route separate and still track multiple IPs. The guard would need to be in charge of checking if `req.ips` or `req.ip` needs to be used.
4 changes: 4 additions & 0 deletions nest-cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}
73 changes: 73 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{
"name": "nestjs-limiter",
"version": "0.0.1",
"description": "",
"author": "",
"private": false,
"license": "MIT",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib"
],
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@golevelup/nestjs-modules": "^0.4.1",
"@nestjs/common": "^7.0.0",
"@nestjs/core": "^7.0.0",
"@nestjs/platform-express": "^7.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4"
},
"devDependencies": {
"@nestjs/cli": "^7.0.0",
"@nestjs/schematics": "^7.0.0",
"@nestjs/testing": "^7.0.0",
"@types/express": "^4.17.3",
"@types/jest": "25.1.4",
"@types/node": "^13.9.1",
"@types/supertest": "^2.0.8",
"@typescript-eslint/eslint-plugin": "^2.23.0",
"@typescript-eslint/parser": "^2.23.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"jest": "^25.1.0",
"prettier": "^1.19.1",
"supertest": "^4.0.2",
"ts-jest": "25.2.1",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
6 changes: 6 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export * from './limiter.decorator';
export * from './limiter.interface';
export * from './limiter.module';
export * from './limiter.service';
export * from './limiter.guard';
export * from './rate-storage.interface';
10 changes: 10 additions & 0 deletions src/limiter-core.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createConfigurableDynamicRootModule } from '@golevelup/nestjs-modules';
import { Module } from '@nestjs/common';
import { LIMIT_OPTIONS } from './limiter.constants';
import { LimiterOptions } from './limiter.interface';

@Module({})
export class LimiterCoreModule extends createConfigurableDynamicRootModule<
LimiterCoreModule,
LimiterOptions
>(LIMIT_OPTIONS) {}
3 changes: 3 additions & 0 deletions src/limiter.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const CALL_LIMIT = 'LIMITER:CALL_LIMIT';
export const RATE_TTL = 'LIMITER:RATE_TTL';
export const LIMIT_OPTIONS = 'LIMITER:MODULE_OPTIONS';
25 changes: 25 additions & 0 deletions src/limiter.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { CALL_LIMIT, RATE_TTL } from './limiter.constants';

function setRateLimitMetadata(
target: Function,
limit: number,
ttl: number,
): void {
Reflect.defineMetadata(CALL_LIMIT, limit, target);
Reflect.defineMetadata(RATE_TTL, ttl, target);
}

export const RateLimit = (
callLimit = 20,
ttl = 60,
): ClassDecorator | MethodDecorator => {
return (
target: Function | Record<string, any>,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<any>,
) => {
const metaTarget = descriptor ? descriptor.value : target;
setRateLimitMetadata(metaTarget, callLimit, ttl);
return descriptor ? descriptor.value : target;
};
};
Empty file added src/limiter.guard.ts
Empty file.
9 changes: 9 additions & 0 deletions src/limiter.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { RateLimitStorage } from './rate-storage.interface';
import { Type } from './type';

export interface LimiterOptions {
ignoreList?: string[];
callLimit?: number;
callWindow?: number;
storage?: Type<RateLimitStorage>
}
16 changes: 16 additions & 0 deletions src/limiter.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { AsyncModuleConfig } from '@golevelup/nestjs-modules';
import { Global, Module } from '@nestjs/common';
import { LimiterCoreModule } from './limiter-core.module';
import { LimiterOptions } from './limiter.interface';

@Global()
@Module({})
export class LimiterModule {
static forRoot(options?: LimiterOptions) {
return LimiterCoreModule.forRoot(LimiterCoreModule, options);
}

static forRootAsync(options?: AsyncModuleConfig<LimiterOptions>) {
return LimiterCoreModule.forRootAsync(LimiterCoreModule, options);
}
}
16 changes: 16 additions & 0 deletions src/limiter.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Injectable } from '@nestjs/common';
import { RateLimitStorage } from './rate-storage.interface';

@Injectable()
export class LocalLimitStorage implements RateLimitStorage {
storage: Record<string, number>;

getRecord(key: string): number {
return this.storage[key] || 0;
}

addRecord(key: string, ttl: number): void {
this.storage[key] = this.storage[key] ? this.storage[key] + 1 : 1;
setTimeout(() => this.storage[key]--, ttl * 1000);
}
}
8 changes: 8 additions & 0 deletions src/rate-storage.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export interface RateLimitStorage {
storage: Record<string, number>;

getRecord(key: string): number;
addRecord(key: string, tty: number): void;
}

export const RateLimitStorage = Symbol('RateLimitStorage');
3 changes: 3 additions & 0 deletions src/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { RateLimitStorage } from './rate-storage.interface';

export type Type<T extends RateLimitStorage> = { new(...args: any[]): T };
24 changes: 24 additions & 0 deletions test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';

describe('AppController (e2e)', () => {
let app: INestApplication;

beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();

app = moduleFixture.createNestApplication();
await app.init();
});

it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
9 changes: 9 additions & 0 deletions test/jest-e2e.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
8 changes: 8 additions & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"outDir": "lib"
},
"extends": "./tsconfig.json",
"include": ["src"],
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
15 changes: 15 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
},
"exclude": ["node_modules", "dist"]
}
Loading

0 comments on commit 35dbff5

Please sign in to comment.