-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (61 loc) · 2.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var CoreModule = require('module');
var Shield = function(spec) {
var exceptions = [];
var cache = new Map();
var whitelist = spec.mode === 'white-list';
var originals = {};
originals.require = CoreModule.prototype.require;
originals.load = CoreModule.prototype.constructor._load;
var isAllowed = function(path, module) {
var cached = cache.has(path);
if(cached) return cache.get(path);
var caught = exceptions.some(function(x) {
var toRequirePattern = new RegExp(x.toRequire);
var caughtToRequire = toRequirePattern.test(path);
if(!x.fromModules || !caughtToRequire) {
return caughtToRequire;
}
var fromModulesPattern = new RegExp(x.fromModules);
var caughtFromModules = fromModulesPattern.test(module.filename);
return caughtFromModules;
});
var allowed = caught?whitelist:!whitelist;
cache.set(path, allowed);
return allowed;
};
var localLoad = function(path, parent, isMain) {
var allowed = isAllowed(path);
if(allowed) {
return originals.load(path, parent, isMain);
} else {
// TODO: The module object is wrong here
throw new Error(`Mode: ${spec.mode}. '${module.filename}' attempted to load('${path}')`);
}
};
var localRequire = function(path) {
var module = this;
var allowed = isAllowed(path, module);
if(allowed) {
var required = originals.require(path);
return required;
} else {
throw new Error(`Mode: ${spec.mode}. '${module.filename}' attempted to require('${path}')`);
}
};
CoreModule.prototype.require = localRequire;
CoreModule.prototype.constructor._load = localLoad;
var except = function(toRequire, fromModules) {
exceptions.push({
toRequire: toRequire,
fromModules: fromModules
});
};
return {
require: localRequire,
except: except
};
};
module.exports = function(spec) {
var result = new Shield(spec);
return result;
};