Mat*_*att 1 api function tostring node.js
在浏览器中运行javascript时,无需尝试隐藏功能代码,因为它已下载并可以在源代码中查看。
在服务器上运行时,情况会改变。在诸如api这样的用例中,您想为用户提供要调用的函数,而又不允许他们查看正在运行的代码。
在我们的特定情况下,我们想在节点内部执行用户提交的javascript。我们能够对node.js api进行沙箱化,但是我们希望将自己的api添加到此沙箱中,而用户则无法toString函数来查看正在运行的代码。
是否有人有一种模式或一种防止用户输出功能代码的方法?
更新:
这是基于以下公认答案的完整解决方案(我相信)。请注意,尽管已使用客户端代码进行了演示。您不会使用此客户端,因为有人可以通过简单地阅读下载的代码来看到隐藏功能的内容(尽管如果使用了缩小功能,它可能会稍微慢一些来检查代码)。
这是供服务器端使用的,您要允许用户在沙盒环境中运行api代码,但不允许他们查看api的功能。这段代码中的沙箱仅用于说明这一点。这不是实际的沙箱实现。
// function which hides another function by returning an anonymous
// function which calls the hidden function (ie. places the hidden
// function in a closure to enable access when the wraped function is passed to the sandbox)
function wrapFunc(funcToHide) {
var shownFunc = function() {
funcToHide();
};
return shownFunc;
}
// function whose contents you want to hide
function secretFunc() {
alert('hello');
}
// api object (will be passed to the sandbox to enable access to
// the hidden function)
var apiFunc = wrapFunc(secretFunc);
var api = {};
api.apiFunc = apiFunc;
// sandbox (not an actual sandbox implementation - just for demo)
(function(api) {
console.log(api);
alert(api.apiFunc.toString());
api.apiFunc();
})(api);
Run Code Online (Sandbox Code Playgroud)
如果将回调包装在一个函数中,则可以在该作用域中使用另一个实际上对回调作用域隐藏的函数,因此:
function hideCall(funcToHide) {
var hiddenFunc = funcToHide;
var shownFunc = function() {
hiddenFunc();
};
return shownFunc;
}
Run Code Online (Sandbox Code Playgroud)
然后这样跑
var shtumCallBack = hideCall(secretSquirrelFunc);
userCode.tryUnwindingThis(shtumCallBack);
Run Code Online (Sandbox Code Playgroud)
userCode范围将无法访问,secretSquirrelFunc除非调用它,因为它将需要的范围hideCall是不可用的函数的范围。