【问题标题】:Node.js prevent function inspection (toString)Node.js 阻止函数检查(toString)
【发布时间】: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


    【解决方案1】:

    如果您将回调包装在一个函数中,您可以在该范围内使用实际上隐藏在回调范围之外的另一个函数,因此:

    function hideCall(funcToHide) {
        var hiddenFunc = funcToHide;
        var shownFunc = function() {
            hiddenFunc();
        };
        return shownFunc;
    }
    

    那就这样跑

    var shtumCallBack = hideCall(secretSquirrelFunc);
    userCode.tryUnwindingThis(shtumCallBack);
    

    userCode 作用域将无法访问secretSquirrelFunc,除非调用它,因为它需要的作用域是不可用的hideCall 函数的作用域。

    【讨论】:

    • 出于好奇,为什么不覆盖toString? foo.toString = () => {}
    • @Kousha:因为你可以在你收到的对象上重新设置 toString 方法:secret.toString = secret.constructor.prototype.toString 然后调用它。
    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多