-
-
Notifications
You must be signed in to change notification settings - Fork 163
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #258 from animir/prisma-support
Implement RateLimiterPrisma
- Loading branch information
Showing
10 changed files
with
628 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -41,9 +41,24 @@ jobs: | |
|
||
strategy: | ||
matrix: | ||
node-version: [14.x, 16.x, 18.x, 20.x] | ||
node-version: [16.x, 18.x, 20.x] | ||
redis-version: [6, 7] | ||
|
||
services: | ||
postgres: | ||
image: postgres | ||
env: | ||
POSTGRES_PASSWORD: secret | ||
POSTGRES_USER: root | ||
ports: | ||
- 5432:5432 | ||
# Set health checks to wait until postgres has started | ||
options: >- | ||
--health-cmd pg_isready | ||
--health-interval 10s | ||
--health-timeout 5s | ||
--health-retries 5 | ||
steps: | ||
- name: Checkout repository | ||
uses: actions/[email protected] | ||
|
@@ -62,6 +77,6 @@ jobs: | |
|
||
- name: Start DynamoDB local | ||
uses: rrainn/[email protected] | ||
|
||
- run: npm install | ||
- run: npm run test |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
const RateLimiterStoreAbstract = require('./RateLimiterStoreAbstract'); | ||
const RateLimiterRes = require('./RateLimiterRes'); | ||
|
||
class RateLimiterPrisma extends RateLimiterStoreAbstract { | ||
/** | ||
* Constructor for the rate limiter | ||
* @param {Object} opts - Options for the rate limiter | ||
*/ | ||
constructor(opts) { | ||
super(opts); | ||
|
||
this.modelName = opts.tableName || 'RateLimiterFlexible'; | ||
this.prismaClient = opts.storeClient; | ||
this.clearExpiredByTimeout = opts.clearExpiredByTimeout || true; | ||
|
||
if (!this.prismaClient) { | ||
throw new Error('Prisma client is not provided'); | ||
} | ||
|
||
if (this.clearExpiredByTimeout) { | ||
this._clearExpiredHourAgo(); | ||
} | ||
} | ||
|
||
_getRateLimiterRes(rlKey, changedPoints, result) { | ||
const res = new RateLimiterRes(); | ||
|
||
let doc = result; | ||
|
||
res.isFirstInDuration = doc.points === changedPoints; | ||
res.consumedPoints = doc.points; | ||
|
||
res.remainingPoints = Math.max(this.points - res.consumedPoints, 0); | ||
res.msBeforeNext = doc.expire !== null | ||
? Math.max(new Date(doc.expire).getTime() - Date.now(), 0) | ||
: -1; | ||
|
||
return res; | ||
} | ||
|
||
_upsert(key, points, msDuration, forceExpire = false) { | ||
if (!this.prismaClient) { | ||
return Promise.reject(new Error('Prisma client is not established')); | ||
} | ||
|
||
const now = new Date(); | ||
const newExpire = msDuration > 0 ? new Date(now.getTime() + msDuration) : null; | ||
|
||
return this.prismaClient.$transaction(async (prisma) => { | ||
const existingRecord = await prisma[this.modelName].findFirst({ | ||
where: { key: key }, | ||
}); | ||
|
||
if (existingRecord) { | ||
// Determine if we should update the expire field | ||
const shouldUpdateExpire = forceExpire || !existingRecord.expire || existingRecord.expire <= now || newExpire === null; | ||
|
||
return prisma[this.modelName].update({ | ||
where: { key: key }, | ||
data: { | ||
points: !shouldUpdateExpire ? existingRecord.points + points : points, | ||
...(shouldUpdateExpire && { expire: newExpire }), | ||
}, | ||
}); | ||
} else { | ||
return prisma[this.modelName].create({ | ||
data: { | ||
key: key, | ||
points: points, | ||
expire: newExpire, | ||
}, | ||
}); | ||
} | ||
}); | ||
} | ||
|
||
_get(rlKey) { | ||
if (!this.prismaClient) { | ||
return Promise.reject(new Error('Prisma client is not established')); | ||
} | ||
|
||
return this.prismaClient[this.modelName].findFirst({ | ||
where: { | ||
AND: [ | ||
{ key: rlKey }, | ||
{ | ||
OR: [ | ||
{ expire: { gt: new Date() } }, | ||
{ expire: null }, | ||
], | ||
}, | ||
], | ||
}, | ||
}); | ||
} | ||
|
||
_delete(rlKey) { | ||
if (!this.prismaClient) { | ||
return Promise.reject(new Error('Prisma client is not established')); | ||
} | ||
|
||
return this.prismaClient[this.modelName].deleteMany({ | ||
where: { | ||
key: rlKey, | ||
}, | ||
}).then(res => res.count > 0); | ||
} | ||
|
||
_clearExpiredHourAgo() { | ||
if (this._clearExpiredTimeoutId) { | ||
clearTimeout(this._clearExpiredTimeoutId); | ||
} | ||
this._clearExpiredTimeoutId = setTimeout(async () => { | ||
await this.prismaClient[this.modelName].deleteMany({ | ||
where: { | ||
expire: { | ||
lt: new Date(Date.now() - 3600000), | ||
}, | ||
}, | ||
}); | ||
this._clearExpiredHourAgo(); | ||
}, 300000); // Clear every 5 minutes | ||
} | ||
} | ||
|
||
module.exports = RateLimiterPrisma; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,13 @@ | ||
{ | ||
"name": "rate-limiter-flexible", | ||
"version": "4.0.1", | ||
"version": "5.0.0", | ||
"description": "Node.js rate limiter by key and protection from DDoS and Brute-Force attacks in process Memory, Redis, MongoDb, Memcached, MySQL, PostgreSQL, Cluster or PM", | ||
"main": "index.js", | ||
"scripts": { | ||
"dc:up": "docker-compose -f docker-compose.yml up -d", | ||
"dc:down": "docker-compose -f docker-compose.yml down", | ||
"test": "nyc --reporter=html --reporter=text mocha", | ||
"prisma:postgres": "prisma generate --schema=./test/RateLimiterPrisma/Postgres/schema.prisma && prisma db push --schema=./test/RateLimiterPrisma/Postgres/schema.prisma", | ||
"test": "npm run prisma:postgres && nyc --reporter=html --reporter=text mocha", | ||
"debug-test": "mocha --inspect-brk lib/**/**.test.js", | ||
"coveralls": "cat ./coverage/lcov.info | coveralls", | ||
"eslint": "eslint --quiet lib/**/**.js test/**/**.js", | ||
|
@@ -17,21 +18,22 @@ | |
"url": "git+https://github.com/animir/node-rate-limiter-flexible.git" | ||
}, | ||
"keywords": [ | ||
"ratelimter", | ||
"authorization", | ||
"security", | ||
"rate", | ||
"limit", | ||
"ratelimter", | ||
"brute", | ||
"force", | ||
"bruteforce", | ||
"throttle", | ||
"redis", | ||
"mongodb", | ||
"dynamodb", | ||
"mysql", | ||
"postgres", | ||
"prisma", | ||
"koa", | ||
"express", | ||
"hapi", | ||
"auth", | ||
"ddos", | ||
"queue" | ||
"hapi" | ||
], | ||
"author": "animir <[email protected]>", | ||
"license": "ISC", | ||
|
@@ -42,6 +44,7 @@ | |
"types": "./lib/index.d.ts", | ||
"devDependencies": { | ||
"@aws-sdk/client-dynamodb": "^3.431.0", | ||
"@prisma/client": "^5.8.0", | ||
"chai": "^4.1.2", | ||
"coveralls": "^3.0.1", | ||
"eslint": "^4.19.1", | ||
|
@@ -54,6 +57,7 @@ | |
"memcached-mock": "^0.1.0", | ||
"mocha": "^10.2.0", | ||
"nyc": "^15.1.0", | ||
"prisma": "^5.8.0", | ||
"redis": "^4.6.8", | ||
"redis-mock": "^0.48.0", | ||
"sinon": "^17.0.1" | ||
|
Oops, something went wrong.