Skip to content
This repository has been archived by the owner on Nov 23, 2022. It is now read-only.

Adds support for CIDR blocks #98

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/rate-limiter.guard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Reflector } from '@nestjs/core'
import { Injectable, ExecutionContext, Inject, HttpStatus, Logger, HttpException, CanActivate } from '@nestjs/common'
import { Netmask } from 'netmask'
import {
RateLimiterMemory,
RateLimiterRes,
Expand Down Expand Up @@ -136,10 +137,18 @@ export class RateLimiterGuard implements CanActivate {
})
}

const ipBlockFilter = function (list: string[]): (key: string) => boolean {
const blocks = list.filter((ip) => ip.includes('/')).map((ip) => new Netmask(ip))

return (key): boolean => blocks.some((block) => block.contains(key))
}

rateLimiter = new RLWrapperBlackAndWhite({
limiter: rateLimiter,
whiteList: this.specificOptions?.whiteList || this.options.whiteList,
blackList: this.specificOptions?.blackList || this.options.blackList,
isWhiteListed: ipBlockFilter(this.specificOptions?.whiteList || this.options.whiteList),
isBlackListed: ipBlockFilter(this.specificOptions?.blackList || this.options.blackList),
runActionAnyway: false
})

Expand Down Expand Up @@ -173,7 +182,7 @@ export class RateLimiterGuard implements CanActivate {
}

protected getIpFromRequest(request: { ip: string }): string {
return request.ip?.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/)?.[0]
return request.ip?.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/)?.[0]
}

private httpHandler(context: ExecutionContext) {
Expand Down
87 changes: 41 additions & 46 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,21 @@
"test": "jest --config ./jest.config.js"
},
"dependencies": {
"netmask": "^2.0.2",
"rate-limiter-flexible": "2.1.10"
},
"devDependencies": {
"@nestjs/common": "latest",
"@nestjs/core": "latest",
"@types/jest": "^26.0.15",
"@types/netmask": "^1.0.30",
"@types/node": "^14.11.1",
"jest": "^26.6.3",
"prettier": "^2.1.1",
"reflect-metadata": "0.1.13",
"rxjs": "^6.6.3",
"ts-node": "^9.0.0",
"ts-jest": "^26.4.4",
"ts-node": "^9.0.0",
"typescript": "^4.0.2"
}
}
}