The sandbox
module spawns a child process and runs user scripts in a new context provided by vm
module. No global variables or node.js methods are accessible in user scripts because the global
variable is redefined( see line 28, 45-47, file shovel.js).
If you want to expose some objects and functions, e.g.,
var myobj = { x:12, y:12};
var add = function(a, b) { return a + b; };
to the user script, e.g.,
var b = 100;
myobj.x = add(myobj.x, b);
, prepend the object and the function to the user script and run it by sandbox
like this:
var Sandbox = require('sandbox');
var s = new Sandbox();
s.run('myobj=' + JSON.stringify(myobj) + ';'
+ 'add=' + add.toString() + ';'
+ userscript
+ '; print(myobj);',
function( output ) {
console.log(output);
});
The output includes the new value of myobj
:
{ result: 'null', console: [ { x: 112, y: 12 } ] }
There is a relative discussion: How restrict access to apis in node.js javascript?. But this method is against the rule: 'To prevent accidental global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code requires a separate process.' (see http://nodejs.org/api/vm.html)