0

I want to build a nodejs application that allows users to enter their own JavaScript scripts to interact with my applications API for extensibility purposes.

I want this to be secure; I only want a specific set of objects exposed to the scripts.

Is there a secure way of doing this in node?

Jack Allan
  • 14,554
  • 11
  • 45
  • 57
  • Use a sandbox for this. For example, the [sandbox](http://gf3.github.io/sandbox/) module. – bnuhero Mar 21 '14 at 02:41
  • Thanks but it looks like you can't expose objects to the sandbox? I can't see how to get access to my api from within the sandbox? – Jack Allan Mar 21 '14 at 22:49

1 Answers1

0

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)

Community
  • 1
  • 1
bnuhero
  • 2,734
  • 1
  • 19
  • 16