{{ message }}
-
-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathSafe-Script.js
More file actions
385 lines (358 loc) · 11.4 KB
/
Copy pathSafe-Script.js
File metadata and controls
385 lines (358 loc) · 11.4 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/* eslint-disable unicorn/no-top-level-side-effects -- Temporary? */
/* eslint-disable no-bitwise -- Convenient */
import jsep from 'jsep';
import jsepRegex from '@jsep-plugin/regex';
import jsepAssignment from '@jsep-plugin/assignment';
/**
* @import {EvaluatedResult, UnknownResult} from './jsonpath.js';
*/
/**
* @typedef {any} AssignmentExpression
*/
/**
* @typedef {any} Substitution
*/
/**
* @typedef {any} AnyParameter
*/
/**
* @typedef {Record<string, Substitution>} Substitutions
*/
// 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__'
]);
// Every function-constructor variant, along with the invocation helpers which
// could otherwise reach them indirectly, e.g., `Function.call(0, 'code')()`
/** @type {WeakSet<object>} */
const BLOCKED_FUNCTIONS = new WeakSet([
Function,
// eslint-disable-next-line no-empty-function -- Only need the constructor
function *() {}.constructor,
// eslint-disable-next-line no-empty-function -- Only need the constructor
async function () {}.constructor,
// eslint-disable-next-line no-empty-function -- Only need the constructor
async function *() {}.constructor,
Function.prototype.call,
Function.prototype.apply,
Function.prototype.bind,
Reflect.apply,
Reflect.construct
]);
/**
* @param {UnknownResult} value
* @returns {boolean}
*/
const isBlockedFunction = (value) => {
return typeof value === 'function' && BLOCKED_FUNCTIONS.has(value);
};
/**
* @typedef {Record<
* string,
* (a: AnyParameter, b: AnyParameter) => UnknownResult
* >} OperatorTable
*/
// eslint-disable-next-line @stylistic/max-len -- Long
const BINOPS = Object.assign(Object.create(null), /** @type {OperatorTable} */ ({
'||': (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()
}));
/**
* @typedef {{
* [key: string]: (a: AnyParameter) => UnknownResult
* }} UnaryOperatorTable
*/
// eslint-disable-next-line @stylistic/max-len -- Long
const UNOPS = Object.assign(Object.create(null), /** @type {UnaryOperatorTable} */ ({
'-': (a) => -(/** @type {EvaluatedResult} */ (a)),
'!': (a) => !a,
'~': (a) => ~(/** @type {EvaluatedResult} */ (a)),
// eslint-disable-next-line no-implicit-coercion -- API
'+': (a) => +(/** @type {EvaluatedResult} */ (a)),
typeof: (a) => typeof a,
void: () => undefined
}));
const SafeEval = {
/**
* @param {jsep.Expression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalAst (ast, subs) {
switch (ast.type) {
case 'BinaryExpression':
case 'LogicalExpression':
return SafeEval.evalBinaryExpression(
/** @type {jsep.BinaryExpression} */ (ast),
subs
);
case 'Compound':
return SafeEval.evalCompound(
/** @type {jsep.Compound} */ (ast),
subs
);
case 'ConditionalExpression':
return SafeEval.evalConditionalExpression(
/** @type {jsep.ConditionalExpression} */ (ast),
subs
);
case 'Identifier':
return SafeEval.evalIdentifier(
/** @type {jsep.Identifier} */ (ast),
subs
);
case 'Literal':
return SafeEval.evalLiteral(/** @type {jsep.Literal} */ (ast));
case 'MemberExpression':
return SafeEval.evalMemberExpression(
/** @type {jsep.MemberExpression} */ (ast),
subs
);
case 'UnaryExpression':
return SafeEval.evalUnaryExpression(
/** @type {jsep.UnaryExpression} */ (ast),
subs
);
case 'ArrayExpression':
return SafeEval.evalArrayExpression(
/** @type {jsep.ArrayExpression} */ (ast),
subs
);
case 'CallExpression':
return SafeEval.evalCallExpression(
/** @type {jsep.CallExpression} */ (ast),
subs
);
case 'AssignmentExpression':
return SafeEval.evalAssignmentExpression(
/** @type {AssignmentExpression} */ (ast),
subs
);
default:
throw new SyntaxError('Unexpected expression', {
cause: ast
});
}
},
/**
* @param {jsep.BinaryExpression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalBinaryExpression (ast, subs) {
/* c8 ignore next 3 -- Defensive guard for malformed ASTs */
if (!Object.hasOwn(BINOPS, ast.operator)) {
throw new SyntaxError(`Unknown binary operator: ${ast.operator}`);
}
const result = BINOPS[ast.operator](
SafeEval.evalAst(ast.left, subs),
() => SafeEval.evalAst(ast.right, subs)
);
return result;
},
/**
* @param {jsep.Compound} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalCompound (ast, subs) {
let last;
for (let i = 0; i < ast.body.length; i++) {
if (
ast.body[i].type === 'Identifier' &&
['var', 'let', 'const'].includes(
/** @type {jsep.Identifier} */
(ast.body[i]).name
) &&
Object.hasOwn(ast.body, i + 1) &&
ast.body[i + 1].type === 'AssignmentExpression'
) {
// var x=2; is detected as
// [{Identifier var}, {AssignmentExpression x=2}]
i += 1;
}
const expr = ast.body[i];
last = SafeEval.evalAst(expr, subs);
}
return last;
},
/**
* @param {jsep.ConditionalExpression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalConditionalExpression (ast, subs) {
if (SafeEval.evalAst(ast.test, subs)) {
return SafeEval.evalAst(ast.consequent, subs);
}
return SafeEval.evalAst(ast.alternate, subs);
},
/**
* @param {jsep.Identifier} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalIdentifier (ast, subs) {
if (Object.hasOwn(subs, ast.name)) {
return subs[ast.name];
}
throw new ReferenceError(`${ast.name} is not defined`);
},
/**
* @param {jsep.Literal} ast
* @returns {UnknownResult}
*/
evalLiteral (ast) {
return ast.value;
},
/**
* @param {jsep.MemberExpression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
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, subs) // `object[property]`
: ast.property.name // `object.property` property is Identifier
);
const obj = SafeEval.evalAst(ast.object, subs);
if (obj === undefined || obj === null) {
throw new TypeError(
`Cannot read properties of ${obj} (reading '${prop}')`
);
}
if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
throw new TypeError(
`Cannot read properties of ${obj} (reading '${prop}')`
);
}
const result = /** @type {Record<string, UnknownResult>} */ (obj)[prop];
if (isBlockedFunction(result)) {
throw new TypeError('Function constructor is disabled');
}
if (typeof result === 'function') {
return result.bind(obj); // arrow functions aren't affected by bind.
}
return result;
},
/**
* @param {jsep.UnaryExpression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalUnaryExpression (ast, subs) {
/* c8 ignore next 3 -- Defensive guard for malformed ASTs */
if (!Object.hasOwn(UNOPS, ast.operator)) {
throw new SyntaxError(`Unknown unary operator: ${ast.operator}`);
}
const operand = SafeEval.evalAst(ast.argument, subs);
return UNOPS[ast.operator](operand);
},
/**
* @param {jsep.ArrayExpression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalArrayExpression (ast, subs) {
return ast.elements.map((el) => SafeEval.evalAst(
/** @type {jsep.Expression} */
(el),
subs
));
},
/**
* @param {jsep.CallExpression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalCallExpression (ast, subs) {
const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
const func = SafeEval.evalAst(ast.callee, subs);
if (
isBlockedFunction(func) ||
args.some((arg) => isBlockedFunction(arg))
) {
throw new Error('Function constructor is disabled');
}
return (/** @type {(...args: AnyParameter[]) => UnknownResult} */ (
func
))(...args);
},
/**
* @param {AssignmentExpression} ast
* @param {Substitutions} subs
* @returns {UnknownResult}
*/
evalAssignmentExpression (ast, subs) {
if (ast.left.type !== 'Identifier') {
throw new SyntaxError('Invalid left-hand side in assignment');
}
const id = /** @type {jsep.Identifier} */ (
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 = /** @type {unknown} */ (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(
/** @type {jsep.Expression} */ (this.ast),
keyMap
);
}
}
export {SafeScript};
You can’t perform that action at this time.
