diff --git a/webapp-next/pages/api/auth/index.ts b/webapp-next/pages/api/auth/index.ts index 64bde57..f6b23b5 100644 --- a/webapp-next/pages/api/auth/index.ts +++ b/webapp-next/pages/api/auth/index.ts @@ -31,8 +31,11 @@ export default async function handler( : req.socket.remoteAddress; // Rate limiting to prevent brute force auth - await limiter.check(res, 5, userIp as string); // 5 requests max per minute - + try { + await limiter.check(res, 5, userIp as string); // 5 requests max per minute + } catch (e: any) { + return res.status(e.statusCode).end(e.message); + } const client = new Client({ node: process.env.ELASTIC_HOST, auth: { @@ -85,7 +88,7 @@ export default async function handler( res.status(200).send({ response: 'ok' }); } } catch (error: any) { - console.log(error); + // console.log(error); if (error.statusCode === 401) { res.status(401).end(); } else { diff --git a/webapp-next/utils/rate-limit.ts b/webapp-next/utils/rate-limit.ts index 4e86d6d..094757b 100644 --- a/webapp-next/utils/rate-limit.ts +++ b/webapp-next/utils/rate-limit.ts @@ -2,34 +2,36 @@ import type { NextApiResponse } from 'next'; import { LRUCache } from 'lru-cache'; type Options = { - uniqueTokenPerInterval?: number - interval?: number -} + uniqueTokenPerInterval?: number; + interval?: number; +}; export default function rateLimit(options?: Options) { const tokenCache = new LRUCache({ max: options?.uniqueTokenPerInterval || 500, - ttl: options?.interval || 60000, - }) + ttl: options?.interval || 60000 + }); return { check: (res: NextApiResponse, limit: number, token: string) => new Promise((resolve, reject) => { - const tokenCount = (tokenCache.get(token) as number[]) || [0] + const tokenCount = (tokenCache.get(token) as number[]) || [0]; if (tokenCount[0] === 0) { - tokenCache.set(token, tokenCount) + tokenCache.set(token, tokenCount); } - tokenCount[0] += 1 + tokenCount[0] += 1; - const currentUsage = tokenCount[0] - const isRateLimited = currentUsage >= limit - res.setHeader('X-RateLimit-Limit', limit) + const currentUsage = tokenCount[0]; + const isRateLimited = currentUsage >= limit; + res.setHeader('X-RateLimit-Limit', limit); res.setHeader( 'X-RateLimit-Remaining', isRateLimited ? 0 : limit - currentUsage - ) + ); - return isRateLimited ? reject() : resolve() - }), - } -} \ No newline at end of file + return isRateLimited + ? reject({ statusCode: 429, message: 'Too many requests' }) + : resolve(); + }) + }; +}