如何在node.js javascript中限制对apis的访问? [英] How restrict access to apis in node.js javascript?
问题描述
我做了一些研究,找不到任何让我的案子成功的事情。
I did a little research and couldn't find anything that makes my case success.
所以,我正在加载 .js
来自带有 require(..)
的外部脚本,每个脚本导出一个函数..
So, I'm loading .js
from external scripts with require(..)
, each script exports a function ..
main.js
var main=10;
var mod1 = require("./mod1.js");
mod1.js
module.exports=function(){
console.log('loaded');
var net=require('net'); // i don't want it to be able to require certain node.js apis
net.create...;
}
我看到了一些 .json的方式
file声明权限
,如果是,则授予对脚本的访问权限。如何在核心node.js apis上实现类似的东西?
I saw some ways where a .json
file declares the permissions
and if so it grants access to script. How can something like that be achieved for core node.js apis?
推荐答案
根据您的具体需求,您可能能够使用 vm
模块(内置于Node)作为一种沙箱的事情:
Depending on what exactly you want, you might be able use the vm
module (which is built-in to Node) as a sort of sandbox thing:
var vm = require('vm');
var fs = require('fs');
var safe_require = function(mod) {
var code = fs.readFileSync(require.resolve(mod));
var sandbox = {
console : console,
module : {},
require : function(mod) {
// as a simple example, we'll block any requiring of the 'net' module, but
// you could implement some sort of whitelisting/blacklisting for modules
// that are/aren't allowed to be loaded from your module:
if (mod === 'net') {
throw Error('not allowed');
}
// if the module is okay to load, load it:
return require.apply(this, arguments);
}
};
vm.runInNewContext(code, sandbox, __filename);
return sandbox.module.exports;
};
var mod = safe_require('./mod1');
(如您所见,Node的任何内置函数,如控制台
,要在 safe_require
模块中使用,需要在沙箱对象中传递
(as you can see, any built-in functions of Node, like console
, that you want to use in the modules that are safe_require
'd need to be passed in the sandbox object)
这篇关于如何在node.js javascript中限制对apis的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!