-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
79 lines (78 loc) · 2.5 KB
/
index.ts
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
interface OPTIONS {
// 启用严格模式
useStrict?: boolean;
// 沙箱中自动继承全局变量
inheritGlobal?: boolean;
// 黑名单列表
blacklist?: string[];
// 拦截 Function
interceptFunction?: boolean;
// 拦截 eval
interceptEval?: boolean;
}
interface BLACKMAP {
[other: string]: boolean;
}
export const createSandbox = (context: any = {}, options: OPTIONS = {}) => {
const global = Function('return this')();
const { useStrict, inheritGlobal = true, interceptFunction, interceptEval, blacklist = [] } = options;
const blackmap: BLACKMAP = {};
for (let i = 0; i < blacklist.length; i++) {
const name = blacklist[i];
blackmap[name] = true;
}
const createProxy = (context: any) => {
const proxy = new Proxy(context, {
set(target: any, p: string, value: any): boolean {
target[p] = value;
return true;
},
get(target: any, p: string): any {
if (blackmap.hasOwnProperty(p)) {
console.error(`Can't assess property: ${p} in blacklist`);
return undefined;
}
switch (p) {
case 'window':
case 'global':
case 'self':
case 'globalThis':
return proxy;
case 'Function':
if (interceptFunction) return (...args) => Function(...args).bind(proxy);
break;
case 'eval':
if (interceptEval) return code => Function(`return ${code}`).bind(proxy);
break;
}
if (inheritGlobal && !(p in target) && p in global) {
const value = global[p];
if (typeof value === 'function' && !value.prototype) return value.bind(global);
return value;
}
return target[p];
},
has(): boolean {
return true;
}
});
return proxy;
};
context = createProxy(context);
const sandbox = (script: string) => {
return new Function(
'global',
`
with (global) {
(function() {
${useStrict ? '"use strict";' : ''}
${script}
}).bind(global)();
};
`
)(context);
};
sandbox.context = context;
sandbox.exec = sandbox;
return sandbox;
};