This repository has been archived by the owner on Aug 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
83 lines (63 loc) · 1.88 KB
/
index.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const {isArray} = require('util');
const Rule = require('./rule');
const DEFAULT_CHECK_INTERVAL = 1000; // One second
const DEFAULT_RULES = [{regexp: '.*'}];
class DDDoS {
constructor(options = {}) {
if (options === null) {
options = {};
}
let checkInterval = Number(options.checkInterval);
if (isNaN(checkInterval) || checkInterval <= 0) {
checkInterval = DEFAULT_CHECK_INTERVAL;
}
this.checkInterval = checkInterval;
this.paths = new Map();
this.rules = [];
const rules = isArray(options.rules) ? options.rules : DEFAULT_RULES;
rules.forEach(rule => this._addRule(rule, options));
setInterval(this._check.bind(this), checkInterval);
}
request(ip, path, ddos, next) {
if (typeof path !== 'string') {
path = '';
}
const rule = this.paths.get(path);
if (rule) {
rule.use(ip, path, ddos, next);
return;
}
this.rules.some(rule => {
const matches = path.match(rule.regexp);
if (matches) {
rule.use(ip, path, ddos, next);
}
return matches;
});
}
express(ipPropertyName, pathPropertyName) {
if (typeof ipPropertyName !== 'string' || !ipPropertyName) {
ipPropertyName = 'ip';
}
if (typeof pathPropertyName !== 'string' || !pathPropertyName) {
pathPropertyName = 'path';
}
return (req, res, next) => {
this.request(req[ipPropertyName], req[pathPropertyName], (errorCode, errorData) => {
res.status(errorCode).send(errorData);
}, next);
};
}
_addRule(rule, options) {
if (typeof rule.regexp === 'string') {
this.rules.push(new Rule(rule, options));
} else if (typeof rule.string === 'string') {
this.paths.set(rule.string, new Rule(rule, options));
}
}
_check() {
this.paths.forEach(path => path.check());
this.rules.forEach(rule => rule.check());
}
}
module.exports = DDDoS;