-
Notifications
You must be signed in to change notification settings - Fork 368
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
94 additions
and
15 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,70 @@ | ||
import type { Request, Response, NextFunction } from 'express'; | ||
import { createClient } from 'redis'; | ||
import { RateLimiterRedis, RateLimiterMemory, RateLimiterRes } from 'rate-limiter-flexible'; | ||
import { getAccount, getRedisUrl } from '@nangohq/shared'; | ||
import { logger } from '@nangohq/shared'; | ||
|
||
const rateLimiter = await (async () => { | ||
const opts = { | ||
keyPrefix: 'middleware', | ||
points: 1200, | ||
duration: 60, | ||
blockDuration: 0 | ||
}; | ||
const url = getRedisUrl(); | ||
if (url) { | ||
const redisClient = await createClient({ url: url, disableOfflineQueue: true }).connect(); | ||
redisClient.on('error', (err) => { | ||
logger.error(`Redis (rate-limiter) error: ${err}`); | ||
}); | ||
return new RateLimiterRedis({ | ||
storeClient: redisClient, | ||
...opts | ||
}); | ||
} | ||
return new RateLimiterMemory(opts); | ||
})(); | ||
|
||
export const rateLimiterMiddleware = (req: Request, res: Response, next: NextFunction) => { | ||
const setXRateLimitHeaders = (rateLimiterRes: RateLimiterRes) => { | ||
const resetEpoch = Math.floor(new Date(Date.now() + rateLimiterRes.msBeforeNext).getTime() / 1000); | ||
res.setHeader('X-RateLimit-Limit', rateLimiter.points); | ||
res.setHeader('X-RateLimit-Remaining', rateLimiterRes.remainingPoints); | ||
res.setHeader('X-RateLimit-Reset', resetEpoch); | ||
}; | ||
const key = getKey(req, res); | ||
const pointsToConsume = getPointsToConsume(req); | ||
rateLimiter | ||
.consume(key, pointsToConsume) | ||
.then((rateLimiterRes) => { | ||
setXRateLimitHeaders(rateLimiterRes); | ||
next(); | ||
}) | ||
.catch((rateLimiterRes) => { | ||
res.setHeader('Retry-After', Math.floor(rateLimiterRes.msBeforeNext / 1000)); | ||
setXRateLimitHeaders(rateLimiterRes); | ||
logger.info(`Rate limit exceeded for ${key}. Request: ${req.method} ${req.path})`); | ||
next(); | ||
// TODO: | ||
// res.status(429).send('Too Many Requests'); | ||
}); | ||
}; | ||
|
||
function getKey(req: Request, res: Response): string { | ||
try { | ||
return `account-${getAccount(res)}`; | ||
} catch (e) { | ||
if (req.user) { | ||
return `user-${req.user.id}`; | ||
} | ||
return `ip-${req.ip}`; | ||
} | ||
} | ||
|
||
function getPointsToConsume(req: Request): number { | ||
if (['/api/v1/signin', '/api/v1/signup', '/api/v1/forgot-password', '/api/v1/reset-password'].includes(req.path)) { | ||
// limiting to 6 requests per period to avoid brute force attacks | ||
return rateLimiter.points / 6; | ||
} | ||
return 1; | ||
} |
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