-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (37 loc) · 1.12 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
const safeRegex = require('safe-regex');
const options = {
keys: ['where'],
}
const traverse = (key, val, func, parentObj) => {
if (Array.isArray(val)) {
val.forEach((e, i) => traverse(i, e, func, val));
} else if (val && (typeof val === 'object') && Object.keys(val).length) {
Object.keys(val).forEach(k => traverse(k, val[k], func, val));
} else {
func(key, val, parentObj);
}
}
const traverseObject = (obj, func) => {
traverse(null, obj, func);
}
const sanitizeMongoQuery = (selector) => {
const keyRegex = new RegExp(options.keys.join('|'), 'i');
traverseObject(selector, (key, val, parentObj) => {
if (key) {
const match = keyRegex.exec(key);
if (match) throw new Error(`${match[0]} operator not allowed`)
}
if (
(/like|regex/i.test(key) || (val instanceof RegExp))
&& !safeRegex(val)
) throw new Error('unsafe regex');
});
return selector;
}
const setOptions = (requiredOptions) => {
Object.assign(options, requiredOptions);
}
module.exports = {
sanitizeMongoQuery,
setOptions
}