-
Notifications
You must be signed in to change notification settings - Fork 0
/
botBanning.js
66 lines (56 loc) · 1.66 KB
/
botBanning.js
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
const IPRange = require('./IPRange');
const {escapeRegex} = require('./utils');
const bannedUserAgents = [
' HTTrack ',
'Wget/',
'http://www.80legs.com/webcrawler.html',
'SISTRIX Crawler',
'http://www.diffbot.com',
'http://www.seokicks.de/robot.html',
'scrapy.org',
'libwww-perl',
'Xenu Link Sleuth',
'http://www.msai.in',
'TencentTraveler', // Might be real browser or a real search engine
'EtaoSpider',
'Python-urllib/',
'YisouSpider',
'Screaming Frog SEO Spider',
];
function banned(ctx, email) {
const ip = ctx.$req.ip();
const emailStr = email ? `If you think this is by mistake, send us an email at ${email}` : '';
ctx.status = 403;
ctx.body = `<pre>Our system has detected unusual traffic from your ip ${ip}. Hence your ip has been banned temporarily.\n${emailStr}</pre>`;
}
module.exports = function enableBotBanning(app, options) {
if (!options || options.enabled === false) return;
let userAgents = [];
let bannedUaRegex;
if (options.commonBots) {
userAgents = bannedUserAgents;
}
if (options.userAgents) {
userAgents = userAgents.concat(options.userAgents);
}
if (userAgents.length) {
bannedUaRegex = new RegExp(bannedUserAgents.map(escapeRegex).join('|'));
}
let bannedIpRange;
if (options.ips) {
bannedIpRange = new IPRange(options.ips);
}
if (!bannedUaRegex && !bannedIpRange) return;
const email = options.email;
app.use(async (ctx, next) => {
if (bannedUaRegex) {
const userAgent = ctx.headers['user-agent'] || '';
if (bannedUaRegex.test(userAgent)) return banned(ctx, email);
}
if (bannedIpRange) {
const ip = ctx.$req.ip();
if (bannedIpRange.has(ip)) return banned(ctx, email);
}
return next();
});
};