-
-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathSafe-Script.js
More file actions
208 lines (202 loc) · 7.26 KB
/
Safe-Script.js
File metadata and controls
208 lines (202 loc) · 7.26 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/* eslint-disable no-bitwise -- Convenient */
import jsep from 'jsep';
import jsepRegex from '@jsep-plugin/regex';
import jsepAssignment from '@jsep-plugin/assignment';
// register plugins
jsep.plugins.register(jsepRegex, jsepAssignment);
jsep.addUnaryOp('typeof');
jsep.addUnaryOp('void');
jsep.addLiteral('null', null);
jsep.addLiteral('undefined', undefined);
const BLOCKED_PROTO_PROPERTIES = new Set([
'constructor',
'__proto__',
'__defineGetter__',
'__defineSetter__',
'__lookupGetter__',
'__lookupSetter__'
]);
const SafeEval = {
/**
* @param {jsep.Expression} ast
* @param {Record<string, any>} subs
*/
evalAst (ast, subs) {
switch (ast.type) {
case 'BinaryExpression':
case 'LogicalExpression':
return SafeEval.evalBinaryExpression(ast, subs);
case 'Compound':
return SafeEval.evalCompound(ast, subs);
case 'ConditionalExpression':
return SafeEval.evalConditionalExpression(ast, subs);
case 'Identifier':
return SafeEval.evalIdentifier(ast, subs);
case 'Literal':
return SafeEval.evalLiteral(ast, subs);
case 'MemberExpression':
return SafeEval.evalMemberExpression(ast, subs);
case 'UnaryExpression':
return SafeEval.evalUnaryExpression(ast, subs);
case 'ArrayExpression':
return SafeEval.evalArrayExpression(ast, subs);
case 'CallExpression':
return SafeEval.evalCallExpression(ast, subs);
case 'AssignmentExpression':
return SafeEval.evalAssignmentExpression(ast, subs);
default:
throw SyntaxError('Unexpected expression', ast);
}
},
evalBinaryExpression (ast, subs) {
const result = {
'||': (a, b) => a || b(),
'&&': (a, b) => a && b(),
'|': (a, b) => a | b(),
'^': (a, b) => a ^ b(),
'&': (a, b) => a & b(),
// eslint-disable-next-line eqeqeq -- API
'==': (a, b) => a == b(),
// eslint-disable-next-line eqeqeq -- API
'!=': (a, b) => a != b(),
'===': (a, b) => a === b(),
'!==': (a, b) => a !== b(),
'<': (a, b) => a < b(),
'>': (a, b) => a > b(),
'<=': (a, b) => a <= b(),
'>=': (a, b) => a >= b(),
'<<': (a, b) => a << b(),
'>>': (a, b) => a >> b(),
'>>>': (a, b) => a >>> b(),
'+': (a, b) => a + b(),
'-': (a, b) => a - b(),
'*': (a, b) => a * b(),
'/': (a, b) => a / b(),
'%': (a, b) => a % b()
}[ast.operator](
SafeEval.evalAst(ast.left, subs),
() => SafeEval.evalAst(ast.right, subs)
);
return result;
},
evalCompound (ast, subs) {
let last;
for (let i = 0; i < ast.body.length; i++) {
if (
ast.body[i].type === 'Identifier' &&
['var', 'let', 'const'].includes(ast.body[i].name) &&
ast.body[i + 1] &&
ast.body[i + 1].type === 'AssignmentExpression'
) {
// var x=2; is detected as
// [{Identifier var}, {AssignmentExpression x=2}]
// eslint-disable-next-line @stylistic/max-len -- Long
// eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
i += 1;
}
const expr = ast.body[i];
last = SafeEval.evalAst(expr, subs);
}
return last;
},
evalConditionalExpression (ast, subs) {
if (SafeEval.evalAst(ast.test, subs)) {
return SafeEval.evalAst(ast.consequent, subs);
}
return SafeEval.evalAst(ast.alternate, subs);
},
evalIdentifier (ast, subs) {
if (Object.hasOwn(subs, ast.name)) {
return subs[ast.name];
}
throw ReferenceError(`${ast.name} is not defined`);
},
evalLiteral (ast) {
return ast.value;
},
evalMemberExpression (ast, subs) {
const prop = String(
// NOTE: `String(value)` throws error when
// value has overwritten the toString method to return non-string
// i.e. `value = {toString: () => []}`
ast.computed
? SafeEval.evalAst(ast.property) // `object[property]`
: ast.property.name // `object.property` property is Identifier
);
const obj = SafeEval.evalAst(ast.object, subs);
if (obj === undefined || obj === null) {
throw TypeError(
`Cannot read properties of ${obj} (reading '${prop}')`
);
}
if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
throw TypeError(
`Cannot read properties of ${obj} (reading '${prop}')`
);
}
const result = obj[prop];
if (typeof result === 'function') {
return result.bind(obj); // arrow functions aren't affected by bind.
}
return result;
},
evalUnaryExpression (ast, subs) {
const result = {
'-': (a) => -SafeEval.evalAst(a, subs),
'!': (a) => !SafeEval.evalAst(a, subs),
'~': (a) => ~SafeEval.evalAst(a, subs),
// eslint-disable-next-line no-implicit-coercion -- API
'+': (a) => +SafeEval.evalAst(a, subs),
typeof: (a) => typeof SafeEval.evalAst(a, subs),
// eslint-disable-next-line no-void, sonarjs/void-use -- feature
void: (a) => void SafeEval.evalAst(a, subs)
}[ast.operator](ast.argument);
return result;
},
evalArrayExpression (ast, subs) {
return ast.elements.map((el) => SafeEval.evalAst(el, subs));
},
evalCallExpression (ast, subs) {
const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
const func = SafeEval.evalAst(ast.callee, subs);
/* c8 ignore start */
if (func === Function) {
// unreachable since BLOCKED_PROTO_PROPERTIES includes 'constructor'
throw new Error('Function constructor is disabled');
}
/* c8 ignore end */
return func(...args);
},
evalAssignmentExpression (ast, subs) {
if (ast.left.type !== 'Identifier') {
throw SyntaxError('Invalid left-hand side in assignment');
}
const id = ast.left.name;
const value = SafeEval.evalAst(ast.right, subs);
subs[id] = value;
return subs[id];
}
};
/**
* A replacement for NodeJS' VM.Script which is also {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP | Content Security Policy} friendly.
*/
class SafeScript {
/**
* @param {string} expr Expression to evaluate
*/
constructor (expr) {
this.code = expr;
this.ast = jsep(this.code);
}
/**
* @param {object} context Object whose items will be added
* to evaluation
* @returns {EvaluatedResult} Result of evaluated code
*/
runInNewContext (context) {
// `Object.create(null)` creates a prototypeless object
const keyMap = Object.assign(Object.create(null), context);
return SafeEval.evalAst(this.ast, keyMap);
}
}
export {SafeScript};