How to remove the global context from a nodejs module?

浪子不回头ぞ 提交于 2019-12-04 09:47:58

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13981885/how-to-remove-the-global-context-from-a-nodejs-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!