沙盒中唯一易于实现的部分是保护您的接口和您自己的自定义 Javascript 函数。
您可以创建一种情况,您自己的任何全局变量都不能被修改,并且用户代码从外部世界接收的唯一变量是副本。
为此,请将用户代码放入您创建的函数中(类似于加载节点模块的方式),然后将 API 的副本作为参数传递给您包装用户代码的主函数(可能传递它是一个具有对象属性的对象)。然后,用户代码所能做的就是修改副本,而不是修改任何原始代码,这样就不会影响任何其他代码。
使用您的示例:
// interfaces created inside some private scope
(function() {
//public class you can interface (should be immutable)
function InterfaceClass () {
this.x = 0;
thix.y = 0;
}
var api = {Interface: InterfaceClass};
launchUsercode(api);
})();
// user code is wrapped in your own function creating a private scope
function launchUsercode(api) {
//executing users code (in a sandbox of some sort)
function userCode () {
//allow this:
var interface = new api.Interface();
interface.x = 1;
// mucking with api.Interface does not do anything other than
// mess up their own environment
}
userCode();
};
仅供参考,唯一可以保护的是重新定义您自己的功能。这个用户代码可以自由地做任何 node.js 应用程序可以做的事情,启动服务器,读/写文件系统,关闭进程,启动子进程等......这甚至不接近一般安全. 这是一个非常困难的问题,可能需要具有自己的文件系统和独立进程以及大量进程管理的全面防火墙虚拟机来解决。这根本不是一件容易的事。