gpt4 book ai didi

javascript - 如何限制对 node.js javascript 中的 api 的访问?

转载 作者:数据小太阳 更新时间:2023-10-29 06:02:14 24 4
gpt4 key购买 nike

我做了一些调查,但找不到任何能让我的案例成功的东西。

因此,我使用 require(..) 从外部脚本加载 .js,每个脚本导出一个函数 ..

ma​​in.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 文件声明了 permissions,如果是这样,它就授予对脚本的访问权限。如何为核心 node.js api 实现类似的东西?

最佳答案

根据您的具体需要,您可以使用 vm模块(内置于 Node)作为一种沙盒:

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

(如您所见,任何您想在 safe_require 模块中使用的 Node 内置函数,如 console 都需要传入沙箱对象)

关于javascript - 如何限制对 node.js javascript 中的 api 的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19443543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com