如何从nodejs模块中删除全局上下文? [英] How to remove the global context from a nodejs module?

查看:216
本文介绍了如何从nodejs模块中删除全局上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何从nodejs模块中删除全局上下文的任何想法?

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.

我正在开发一个项目,我的用户可以上传他们自己的nodejs模块,如果它适合预定义的框架,它将在我们定期运行的一天中运行。显然这是一个重大的安全问题。一个好的90%解决方案只是删除全局背景。

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.

你应该从 VM 模块:


  • 读取文件内容( fs.readFile ,而不是 require )。

  • 定义一个新的全球对象。您可以选择公开您想要的任何内容(并隐藏其余部分)。

  • 运行用户代码。

  • 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.

以下是一个例子:


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);
}

用户提供的代码将能够访问我在沙箱中传递的所有内容,就好像它在全球范围。就我而言,我选择从真实的node.js全局范围中公开几乎所有内容。您可以选择不公开的内容。

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.

此外,您应该检查 child_process.spawn 如果您希望您的解决方案安全。

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

这篇关于如何从nodejs模块中删除全局上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆