forked from Lilly-Protocol/lily-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate-limit.ts
More file actions
54 lines (47 loc) · 1.5 KB
/
Copy pathrate-limit.ts
File metadata and controls
54 lines (47 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import type { Request, Response } from "express";
import rateLimit from "express-rate-limit";
import { securityConfig } from "./env";
interface RateLimitLocals {
resetTime?: Date | null;
}
/**
* Custom 429 handler used when an express-rate-limit limiter is exceeded.
* Reads the limiter-provided reset time from `res.locals.rateLimit` so the
* Retry-After header and the response envelope reflect when the window resets.
*/
export const rateLimitHandler = (
_request: Request,
response: Response,
): void => {
const resetTime =
(response.locals as { rateLimit?: RateLimitLocals }).rateLimit?.resetTime ??
null;
if (resetTime && resetTime.getTime() > Date.now()) {
const retryAfterSeconds = Math.max(
1,
Math.ceil((resetTime.getTime() - Date.now()) / 1000),
);
response.setHeader("Retry-After", String(retryAfterSeconds));
}
response.status(429).json({
success: false,
message: "Too many requests, please try again later.",
details: { resetTime: resetTime ? resetTime.toISOString() : null },
});
};
export const apiRateLimiter = rateLimit({
windowMs: securityConfig.rateLimitWindowMs,
limit: securityConfig.rateLimitMaxRequests,
standardHeaders: true,
legacyHeaders: false,
skip: () => process.env.NODE_ENV === "test",
handler: rateLimitHandler,
});
export const writeRateLimiter = rateLimit({
windowMs: 60_000,
limit: 20,
standardHeaders: true,
legacyHeaders: false,
skip: () => process.env.NODE_ENV === "test",
handler: rateLimitHandler,
});