This repository has been archived by the owner on Dec 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.js
541 lines (460 loc) · 15.3 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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
var parse = require('esprima').parse
var hoist = require('hoister')
var InfiniteChecker = require('./lib/infinite-checker')
var Primitives = require('./lib/primitives')
module.exports = safeEval
module.exports.eval = safeEval
module.exports.FunctionFactory = FunctionFactory
module.exports.Function = FunctionFactory()
var maxIterations = 1000000
// 'eval' with a controlled environment
function safeEval(src, parentContext){
var tree = prepareAst(src)
var context = Object.create(parentContext || {})
return finalValue(evaluateAst(tree, context))
}
// create a 'Function' constructor for a controlled environment
function FunctionFactory(parentContext){
var context = Object.create(parentContext || {})
return function Function() {
// normalize arguments array
var args = Array.prototype.slice.call(arguments)
var src = args.slice(-1)[0]
args = args.slice(0,-1)
if (typeof src === 'string'){
//HACK: esprima doesn't like returns outside functions
src = parse('function a(){' + src + '}').body[0].body
}
var tree = prepareAst(src)
return getFunction(tree, args, context)
}
}
// takes an AST or js source and returns an AST
function prepareAst(src){
var tree = (typeof src === 'string') ? parse(src, {loc: true}) : src
return hoist(tree)
}
// evaluate an AST in the given context
function evaluateAst(tree, context){
var safeFunction = FunctionFactory(context)
var primitives = Primitives(context)
// block scoped context for catch (ex) and 'let'
var blockContext = context
return walk(tree)
// recursively walk every node in an array
function walkAll(nodes){
var result = undefined
for (var i=0;i<nodes.length;i++){
var childNode = nodes[i]
if (childNode.type === 'EmptyStatement') continue
result = walk(childNode)
if (result instanceof ReturnValue){
return result
}
}
return result
}
// recursively evalutate the node of an AST
function walk(node, traceNode){
try {
if (!node) return
switch (node.type) {
case 'Program':
return walkAll(node.body)
case 'BlockStatement':
enterBlock()
var result = walkAll(node.body)
leaveBlock()
return result
case 'FunctionDeclaration':
var params = node.params.map(getName)
var value = getFunction(node.body, params, blockContext, node)
return context[node.id.name] = value
case 'FunctionExpression':
var params = node.params.map(getName)
// HACK: trace the function name for stack traces
if (!node.id && traceNode && traceNode.key && traceNode.key.type === 'Identifier') {
node.id = traceNode.key
}
return getFunction(node.body, params, blockContext, node)
case 'ReturnStatement':
var value = walk(node.argument)
return new ReturnValue('return', value)
case 'BreakStatement':
return new ReturnValue('break')
case 'ContinueStatement':
return new ReturnValue('continue')
case 'ExpressionStatement':
return walk(node.expression)
case 'AssignmentExpression':
return setValue(blockContext, node.left, node.right, node.operator)
case 'UpdateExpression':
return setValue(blockContext, node.argument, null, node.operator)
case 'VariableDeclaration':
node.declarations.forEach(function(declaration){
var target = node.kind === 'let' ? blockContext : context
if (declaration.init){
target[declaration.id.name] = walk(declaration.init)
} else {
target[declaration.id.name] = undefined
}
})
break
case 'SwitchStatement':
var defaultHandler = null
var matched = false
var value = walk(node.discriminant)
var result = undefined
enterBlock()
var i = 0
while (result == null){
if (i<node.cases.length){
if (node.cases[i].test){ // check or fall through
matched = matched || (walk(node.cases[i].test) === value)
} else if (defaultHandler == null) {
defaultHandler = i
}
if (matched){
var r = walkAll(node.cases[i].consequent)
if (r instanceof ReturnValue){ // break out
if (r.type == 'break') break
result = r
}
}
i += 1 // continue
} else if (!matched && defaultHandler != null){
// go back and do the default handler
i = defaultHandler
matched = true
} else {
// nothing we can do
break
}
}
leaveBlock()
return result
case 'IfStatement':
if (walk(node.test)){
return walk(node.consequent)
} else if (node.alternate) {
return walk(node.alternate)
}
case 'ForStatement':
var infinite = InfiniteChecker(maxIterations)
var result = undefined
enterBlock() // allow lets on delarations
for (walk(node.init); walk(node.test); walk(node.update)){
var r = walk(node.body)
// handle early return, continue and break
if (r instanceof ReturnValue){
if (r.type == 'continue') continue
if (r.type == 'break') break
result = r
break
}
infinite.check()
}
leaveBlock()
return result
case 'ForInStatement':
var infinite = InfiniteChecker(maxIterations)
var result = undefined
var value = walk(node.right)
var property = node.left
var target = context
enterBlock()
if (property.type == 'VariableDeclaration'){
walk(property)
property = property.declarations[0].id
if (property.kind === 'let'){
target = blockContext
}
}
for (var key in value){
setValue(target, property, {type: 'Literal', value: key})
var r = walk(node.body)
// handle early return, continue and break
if (r instanceof ReturnValue){
if (r.type == 'continue') continue
if (r.type == 'break') break
result = r
break
}
infinite.check()
}
leaveBlock()
return result
case 'WhileStatement':
var infinite = InfiniteChecker(maxIterations)
while (walk(node.test)){
walk(node.body)
infinite.check()
}
break
case 'TryStatement':
try {
walk(node.block)
} catch (error) {
enterBlock()
var catchClause = node.handlers[0]
if (catchClause) {
blockContext[catchClause.param.name] = error
walk(catchClause.body)
}
leaveBlock()
} finally {
if (node.finalizer) {
walk(node.finalizer)
}
}
break
case 'Literal':
return node.value
case 'UnaryExpression':
if (node.operator === 'delete' && node.argument.type === 'MemberExpression') {
var arg = node.argument
var parent = walk(arg.object)
var prop = arg.computed ? walk(arg.property) : arg.property.name
delete parent[prop]
return true
} else {
var val = walk(node.argument)
switch(node.operator) {
case '+': return +val
case '-': return -val
case '~': return ~val
case '!': return !val
case 'typeof': return typeof val
default: return unsupportedExpression(node)
}
}
case 'ArrayExpression':
var obj = blockContext['Array']()
for (var i=0;i<node.elements.length;i++){
obj.push(walk(node.elements[i]))
}
return obj
case 'ObjectExpression':
var obj = blockContext['Object']()
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i]
var value = (prop.value === null) ? prop.value : walk(prop.value, prop)
obj[prop.key.value || prop.key.name] = value
}
return obj
case 'NewExpression':
var args = node.arguments.map(function(arg){
return walk(arg)
})
var target = walk(node.callee)
return primitives.applyNew(target, args)
case 'BinaryExpression':
var l = walk(node.left)
var r = walk(node.right)
switch(node.operator) {
case '==': return l == r
case '===': return l === r
case '!=': return l != r
case '!==': return l !== r
case '+': return l + r
case '-': return l - r
case '*': return l * r
case '/': return l / r
case '%': return l % r
case '<': return l < r
case '<=': return l <= r
case '>': return l > r
case '>=': return l >= r
case '|': return l | r
case '&': return l & r
case '^': return l ^ r
case 'instanceof': return l instanceof r
default: return unsupportedExpression(node)
}
case 'LogicalExpression':
switch(node.operator) {
case '&&': return walk(node.left) && walk(node.right)
case '||': return walk(node.left) || walk(node.right)
default: return unsupportedExpression(node)
}
case 'ThisExpression':
return blockContext['this']
case 'Identifier':
if (node.name === 'undefined'){
return undefined
} else if (hasProperty(blockContext, node.name, primitives)){
return checkValue(blockContext[node.name])
} else {
throw new ReferenceError(node.name + ' is not defined')
}
case 'CallExpression':
var args = node.arguments.map(function(arg){
return walk(arg)
})
var object = null
var target = walk(node.callee)
if (node.callee.type === 'MemberExpression'){
object = walk(node.callee.object)
}
return checkValue(target.apply(object, args))
case 'MemberExpression':
var obj = walk(node.object)
if (node.computed){
var prop = walk(node.property)
} else {
var prop = node.property.name
}
obj = primitives.getPropertyObject(obj, prop)
return checkValue(obj[prop]);
case 'ConditionalExpression':
var val = walk(node.test)
return val ? walk(node.consequent) : walk(node.alternate)
case 'EmptyStatement':
return
default:
return unsupportedExpression(node)
}
} catch (ex) {
ex.trace = ex.trace || []
ex.trace.push(node)
throw ex
}
}
// safely retrieve a value
function checkValue(value){
if (value === Function){
value = safeFunction
}
return finalValue(value)
}
// block scope context control
function enterBlock(){
blockContext = Object.create(blockContext)
}
function leaveBlock(){
blockContext = Object.getPrototypeOf(blockContext)
}
// set a value in the specified context if allowed
function setValue(object, left, right, operator){
var name = null
if (left.type === 'Identifier'){
name = left.name
// handle parent context shadowing
object = objectForKey(object, name, primitives)
} else if (left.type === 'MemberExpression'){
if (left.computed){
name = walk(left.property)
} else {
name = left.property.name
}
object = walk(left.object)
}
// stop built in properties from being able to be changed
if (canSetProperty(object, name, primitives)){
switch(operator) {
case undefined: return object[name] = walk(right)
case '=': return object[name] = walk(right)
case '+=': return object[name] += walk(right)
case '-=': return object[name] -= walk(right)
case '++': return object[name]++
case '--': return object[name]--
}
}
}
}
// when an unsupported expression is encountered, throw an error
function unsupportedExpression(node){
console.error(node)
var err = new Error('Unsupported expression: ' + node.type)
err.node = node
throw err
}
// walk a provided object's prototypal hierarchy to retrieve an inherited object
function objectForKey(object, key, primitives){
var proto = primitives.getPrototypeOf(object)
if (!proto || hasOwnProperty(object, key)){
return object
} else {
return objectForKey(proto, key, primitives)
}
}
function hasProperty(object, key, primitives){
var proto = primitives.getPrototypeOf(object)
var hasOwn = hasOwnProperty(object, key)
if (object[key] !== undefined){
return true
} else if (!proto || hasOwn){
return hasOwn
} else {
return hasProperty(proto, key, primitives)
}
}
function hasOwnProperty(object, key){
return Object.prototype.hasOwnProperty.call(object, key)
}
function propertyIsEnumerable(object, key){
return Object.prototype.propertyIsEnumerable.call(object, key)
}
// determine if we have write access to a property
function canSetProperty(object, property, primitives){
if (property === '__proto__' || primitives.isPrimitive(object)){
return false
} else if (object != null){
if (hasOwnProperty(object, property)){
if (propertyIsEnumerable(object, property)){
return true
} else {
return false
}
} else {
return canSetProperty(primitives.getPrototypeOf(object), property, primitives)
}
} else {
return true
}
}
// generate a function with specified context
function getFunction(body, params, parentContext, traceNode){
return function(){
try {
var context = Object.create(parentContext)
if (this == global){
context['this'] = null
} else {
context['this'] = this
}
// normalize arguments array
var args = Array.prototype.slice.call(arguments)
context['arguments'] = arguments
args.forEach(function(arg,idx){
var param = params[idx]
if (param){
context[param] = arg
}
})
var result = evaluateAst(body, context)
if (result instanceof ReturnValue){
return result.value
}
} catch (ex) {
ex.trace = ex.trace || []
ex.trace.push(traceNode)
throw ex
}
}
}
function finalValue(value){
if (value instanceof ReturnValue){
return value.value
}
return value
}
// get the name of an identifier
function getName(identifier){
return identifier.name
}
// a ReturnValue struct for differentiating between expression result and return statement
function ReturnValue(type, value){
this.type = type
this.value = value
}