Skip to content

Commit

Permalink
[Task] #41 ratelimiter cleaning up periodicly
Browse files Browse the repository at this point in the history
  • Loading branch information
Type-Style committed Feb 13, 2024
1 parent db7558e commit f40a710
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
25 changes: 20 additions & 5 deletions src/middleware/limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import { slowDown, Options as slowDownOptions } from 'express-slow-down';
import logger from '@src/scripts/logger';


// TODO clean up after 1 day?
const ipsThatReachedLimit: RateLimit.obj = {};
/*
** configurations
*/

const baseOptions: Partial<rateLimiterOptions & slowDownOptions> = {
windowMs: 5 * 60 * 1000,
//skip: (req, res) => (res.locals.ip == process.env.LOCALHOST)
windowMs: 30 * 60 * 1000,
skip: (req, res) => (res.locals.ip == process.env.LOCALHOST)
}

const baseSlowDownOptions: Partial<slowDownOptions> = {
Expand All @@ -26,6 +27,20 @@ const baseRateLimitOptions: Partial<rateLimiterOptions> = {
}


/*
** cleanup
*/
const ipsThatReachedLimit: RateLimit.obj = {}; // prevent logs from flooding
setInterval(() => {
const oneHourAgo = Date.now() - 60 * 60 * 1000;
for (const ip in ipsThatReachedLimit) {
if (ipsThatReachedLimit[ip].time < oneHourAgo) {
delete ipsThatReachedLimit[ip];
}
}
}, 60 * 60 * 1000);


/*
** exported section
*/
Expand All @@ -37,7 +52,7 @@ export const errorRateLimiter = rateLimit({
handler: (req: Request, res: Response, next: NextFunction, options: rateLimiterOptions) => {
if (!Object.prototype.hasOwnProperty.call(ipsThatReachedLimit, res.locals.ip)) {
logger.error(`[RateLimit] for invalid requests reached ${res.locals.ip}, ${req.get('User-Agent')}`);
ipsThatReachedLimit[res.locals.ip] = { limitReachedOnError: true };
ipsThatReachedLimit[res.locals.ip] = { limitReachedOnError: true, time: Date.now() };
}
res.status(options.statusCode).send(options.message);
}
Expand Down
3 changes: 2 additions & 1 deletion types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
namespace RateLimit {
interface obj {
[key: string]: {
limitReachedOnError: boolean
limitReachedOnError: boolean,
time: number
}
}
}
Expand Down

0 comments on commit f40a710

Please sign in to comment.