【发布时间】:2012-09-29 18:46:27
【问题描述】:
当 javascript 在浏览器中运行时,无需尝试隐藏函数代码,因为它已下载并可以在源代码中查看。
在服务器上运行时,情况会发生变化。在 api 等用例中,您希望为用户提供可调用的函数,但不允许他们查看正在运行的代码。
在我们的具体案例中,我们希望在节点内执行用户提交的 javascript。我们可以对 node.js api 进行沙箱处理,但是我们希望将自己的 api 添加到此沙箱中,而用户无法通过 toString 函数查看正在运行的代码。
是否有人有模式或知道阻止用户输出函数代码的方法?
更新:
这是基于以下公认答案的完整解决方案(我相信)。请注意,尽管这是使用客户端代码演示的。您将不使用此客户端,因为有人可以通过简单地阅读下载的代码来查看您隐藏函数的内容(尽管如果您使用了 minify,它可能会提供一些基本的减速来检查代码) .
这适用于服务器端使用,您希望允许用户在沙盒环境中运行 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);
【问题讨论】:
标签: api node.js function tostring