forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.js
More file actions
237 lines (215 loc) · 6.27 KB
/
Copy pathsecurity.js
File metadata and controls
237 lines (215 loc) · 6.27 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import helmet from "helmet";
import rateLimit from "express-rate-limit";
import mongoSanitize from "express-mongo-sanitize";
import hpp from "hpp";
import logger from "../config/logger.js";
/**
* Helmet - Sets various HTTP headers for security
*/
export const helmetMiddleware = helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
crossOriginEmbedderPolicy: false,
});
/**
* Rate Limiting - Prevents brute force attacks
*/
export const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: "Too many requests from this IP, please try again later.",
standardHeaders: true,
legacyHeaders: false,
skip: () => process.env.NODE_ENV === "test",
handler: (req, res) => {
logger.warn(`Rate limit exceeded for IP: ${req.ip}`);
res.status(429).json({
success: false,
message: "Too many requests, please try again later.",
});
},
});
/**
* Make a rate limiter configured from env overrides.
* @param {number} defaultMax – default max requests in the window
* @param {number} defaultWindow – default window in ms
* @param {string} prefix – env var prefix (e.g. "RATE_LIMIT_AUTH")
*/
function makeLimiter(defaultMax, defaultWindow, prefix) {
const max = parseInt(process.env[`${prefix}_MAX`], 10) || defaultMax;
const windowMs =
parseInt(process.env[`${prefix}_WINDOW_MS`], 10) || defaultWindow;
const skip = () => process.env[`${prefix}_DISABLE`] === "true";
return rateLimit({
windowMs,
max,
skip,
standardHeaders: true,
legacyHeaders: false,
handler: (req, res) => {
logger.warn(`Rate limit exceeded for ${prefix} – IP: ${req.ip}`);
res.status(429).json({
success: false,
message: "Too many requests, please try again later.",
});
},
});
}
/**
* Moderate – for mutation endpoints (purchase, email, upload, payouts).
* 100 requests per 15 minutes by default.
*/
export const standardLimiter = makeLimiter(
100,
15 * 60 * 1000,
"RATE_LIMIT_STANDARD",
);
/**
* Generous – for read-heavy & content endpoints (courses, books, reels,
* spaces, search, progress, notifications, stellar).
* 500 requests per 15 minutes by default.
*/
export const generousLimiter = makeLimiter(
500,
15 * 60 * 1000,
"RATE_LIMIT_GENEROUS",
);
/**
* Strict rate limiting for authentication routes
*/
export const authLimiter = rateLimit({
windowMs: 2 * 60 * 1000, // 2 minutes
max: 5, // Limit each IP to 5 login requests per windowMs
message: "Too many login attempts, please try again later.",
skipSuccessfulRequests: true,
skip: () => process.env.NODE_ENV === "test",
handler: (req, res) => {
logger.warn(`Auth rate limit exceeded for IP: ${req.ip}`);
res.status(429).json({
success: false,
message: "Too many login attempts. Please try again later.",
});
},
});
/**
* Rate limiting specifically for token refresh route
*/
export const refreshLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 50, // Limit each IP to 50 refresh requests per windowMs
message: "Too many refresh attempts, please try again later.",
standardHeaders: true,
legacyHeaders: false,
skip: () => process.env.NODE_ENV === "test",
handler: (req, res) => {
logger.warn(`Refresh rate limit exceeded for IP: ${req.ip}`);
res.status(429).json({
success: false,
message: "Too many refresh attempts, please try again later.",
});
},
});
/**
* MongoDB Injection Protection
* Custom implementation for Express 5 compatibility
* Sanitizes user input to prevent NoSQL injection attacks
*/
export const mongoSanitizeMiddleware = (req, res, next) => {
const sanitize = (obj) => {
if (obj && typeof obj === "object") {
Object.keys(obj).forEach((key) => {
// Remove keys starting with $ or containing .
if (key.startsWith("$") || key.includes(".")) {
logger.warn(
`Sanitized potentially malicious key: ${key} from IP: ${req.ip}`
);
delete obj[key];
} else if (typeof obj[key] === "object" && obj[key] !== null) {
sanitize(obj[key]);
}
});
}
return obj;
};
if (req.body) req.body = sanitize(req.body);
if (req.params) req.params = sanitize(req.params);
// Note: req.query is read-only in Express 5, skip sanitization
next();
};
/**
* HTTP Parameter Pollution Protection
* Prevents attacks that send multiple parameters with the same name
*/
export const hppMiddleware = hpp({
whitelist: [
// Add parameters that are allowed to be arrays
"tags",
"categories",
"interests",
],
});
/**
* Custom security headers middleware
*/
export const customSecurityHeaders = (req, res, next) => {
// Remove powered by header
res.removeHeader("X-Powered-By");
// Add custom security headers
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-XSS-Protection", "1; mode=block");
res.setHeader(
"Strict-Transport-Security",
"max-age=31536000; includeSubDomains"
);
next();
};
/**
* Request logging middleware
*/
export const requestLogger = (req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const duration = Date.now() - start;
const logMessage = `${req.method} ${req.originalUrl} ${res.statusCode} - ${duration}ms - IP: ${req.ip}`;
if (res.statusCode >= 400) {
logger.warn(logMessage);
} else {
logger.http(logMessage);
}
});
next();
};
/**
* IP Whitelist/Blacklist middleware (optional)
*/
export const ipFilter = (req, res, next) => {
const blockedIPs = process.env.BLOCKED_IPS?.split(",") || [];
const clientIP = req.ip || req.connection.remoteAddress;
if (blockedIPs.includes(clientIP)) {
logger.error(`Blocked IP attempted access: ${clientIP}`);
return res.status(403).json({
success: false,
message: "Access denied",
});
}
next();
};
export default {
helmetMiddleware,
standardLimiter,
generousLimiter,
authLimiter,
refreshLimiter,
mongoSanitizeMiddleware,
hppMiddleware,
customSecurityHeaders,
requestLogger,
ipFilter,
};