2.1.0 • Published 9 years ago

sbx v2.1.0

Weekly downloads
6
License
MIT
Repository
github
Last release
9 years ago

sbx


Run untrusted code as a VM in a child process

sbx allows you to run untrusted code in a more secure manner than simply using eval() or function(). To accomplish this, a child process is forked and untrusted code is run in vm with its own context. Inside the vm the untrusted code is wrapped in a try/catch inside an anonymous function in order to capture exceptions and output. Upon completion the context is returned to the user via callback or promise

Notes:
  • Code is run inside an anonymous function and should be written as such
  • Reserved variables _result, _exception, and _stdout are added to the context and should not be set by untrusted code
  • 'use strict' statements are removed from untrusted code as they cause exceptions for passed context variables


Documentation


API

sbx.vm( code, options, callback )

Returns

Promise That resolves to an SBXContext

Types

SBXContext

Capturing stdout

All arguments to console methods log, error, info, trace, and warn are automatically added as items in the _stdout context variable

You may also use the sbx.log method which is an alias for console.log

Example

var sbx = require('sbx')

var code = 'x++; console.log(\'I like the number\', x);'

var options = {
  context: { x: 7 },
  timeout: 100
}

var callback = function(error, context) {
  if (error) return console.error(error)
  console.log('The value of x = ', context.x)
}

sbx.vm(code, options, callback)

// > I like the number 8
// > The value of x = 8

Example with external module and promise result

var sbx = require('sbx')

var code      = 'var _ = require("lodash"); x = _.uniq(x); return x;'

var options = {
  context: { x: [1,1,2,2,3,4,5,6,6] },
  lockdown: false
}

sbx.vm(code, options).then(function (context) {
  console.log('The value of x = ', context.x, false)
  console.log(context._result)
}).catch(function (error) {
  console.error(error)
})

// > The value of x = [1, 2, 3, 4, 5, 6]
// > [1, 2, 3, 4, 5, 6]

Example with es2015 transform via babel + logging

var babel = require('babel-core')
var sbx = require('sbx')

var code = 'let fn = (msg) => msg\nsbx.log(message)\nreturn fn(message)'

var options = {
  context: { message: 'test' },
  transform: function (code, opts) {
    return babel.transform(code, {
      presets: ['es2015', 'stage-2'],
      plugins: ['transform-runtime']
    }).code
  }
}

sbx.vm(code, options).then(function(context) {
  console.log('Result = ', context._result)
  console.log(context._stdout)
})

// > Result = test
// > ['test']
2.1.0

9 years ago

2.0.3

9 years ago

2.0.2

9 years ago

2.0.1

9 years ago

2.0.0

9 years ago

1.0.10

9 years ago

1.0.9

10 years ago

1.0.8

10 years ago

1.0.7

10 years ago

1.0.6

10 years ago

1.0.5

10 years ago

1.0.4

10 years ago

1.0.3

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago

0.1.0

10 years ago