-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.middleware.js
More file actions
45 lines (43 loc) · 1.6 KB
/
security.middleware.js
File metadata and controls
45 lines (43 loc) · 1.6 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
import aj from '#config/arcjet.js';
import logger from '#config/logger.js';
import { slidingWindow } from '@arcjet/node';
const securityMiddleware = async (req, res, next) => {
try {
const role = res.user?.role || 'guest';
let limit;
switch(role){
case 'admin':
limit=20;
break;
case 'user':
limit=10;
break;
default:
limit=5;
}
const client = aj.withRule(slidingWindow( {
mode: 'LIVE',
interval: '1m',
max: limit,
name: `${role}_req_limit`
}));
const decision = await client.protect(req);
if(decision.isDenied() && decision.reason.isBot()){
logger.error('Bot detected:' , {ip: req.ip, userAgent: req.get('User-Agent'), path: req.path});
return res.status(403).json({ error: 'Forbidden' , message: 'Bot detected' });
}
if(decision.isDenied() && decision.reason.isShield()){
logger.error('Shield detected:' , {ip: req.ip, userAgent: req.get('User-Agent'), path: req.path});
return res.status(403).json({ error: 'Forbidden' , message: 'Shield detected' });
}
if(decision.isDenied() && decision.reason.isRateLimit()){
logger.error('Rate limit exceeded:' , {ip: req.ip, userAgent: req.get('User-Agent'), path: req.path});
return res.status(429).json({ error: 'Too Many Requests' , message: 'Rate limit exceeded' });
}
next();
} catch (e) {
console.error('Arcjet middleware error', e);
return res.status(500).json({ error: 'Internal Server Error' , message: 'something went wrong with security middleware' });
}
};
export default securityMiddleware;