简体   繁体   中英

How to remove the global context from a nodejs module?

Any thoughts on how one would go about removing the global context from a nodejs module?

I'm not looking for a solution to the below problem, but if you need more context here you go.

I'm working on a project where my users are able to upload their own nodejs modules and, if it fits a predefined framework, it will run on our at periodic times through out the day. Obviously this is a major security concern. A good 90% solution would simply be removing the global context.

As stated in the comments, you really need to run user-supplied modules in a separate process because an infinite loop will freeze any node process.

You should start with the VM module:

  • Read the file content (with fs.readFile , not require ).
  • Define a new global object. You can choose to expose anything you want (and hide the rest).
  • Run the user code.

Here's an example:

var fs = require('fs'),
    vm = require('vm');

function runCode(fileName) {
  var code = fs.readFileSync(fileName),
      sandbox = {
        console: console,
        setTimeout: setTimeout,
        clearTimeout: clearTimeout,
        require: require,
        module: module,
        exports: exports,
        process: process,
        Buffer: Buffer
      };

  vm.runInNewContext(code, sandbox, fileName);
}

The user-supplied code will be able to access everything that I passed in the sandbox, as if it was in the global scope. In my case, I chose to expose almost everything from the real node.js global scope. You can chose what not to expose.

Also, you should check child_process.spawn if you want your solution to be secure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM