From d8e45057c71ac00bfd9bcf8282f70eab4e0c2a17 Mon Sep 17 00:00:00 2001 From: Joe Previte Date: Fri, 16 Apr 2021 14:22:09 -0700 Subject: [PATCH] refactor: update rateLimiter to check try This changes adds a new method called `.canTry` to the rate limiter to check if there are tokens remaining in the bucket. It also adds suggestions from @oxy to make sure the user can brute force past the rate limiter. --- src/node/routes/login.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/node/routes/login.ts b/src/node/routes/login.ts index 3ec339c1..809c31f0 100644 --- a/src/node/routes/login.ts +++ b/src/node/routes/login.ts @@ -17,11 +17,15 @@ export class RateLimiter { private readonly minuteLimiter = new Limiter(2, "minute") private readonly hourLimiter = new Limiter(12, "hour") + public canTry(): boolean { + return this.minuteLimiter.getTokensRemaining() > 0 || this.hourLimiter.getTokensRemaining() > 0 + } + public try(): boolean { - if (this.minuteLimiter.tryRemoveTokens(1)) { - return true + if (this.canTry()) { + return this.minuteLimiter.tryRemoveTokens(1) || this.hourLimiter.tryRemoveTokens(1) } - return this.hourLimiter.tryRemoveTokens(1) + return false } } @@ -59,6 +63,11 @@ router.get("/", async (req, res) => { router.post("/", async (req, res) => { try { + // Check to see if they exceeded their login attempts + if (!limiter.canTry()) { + throw new Error("Login rate limited!") + } + if (!req.body.password) { throw new Error("Missing password") }