如何在nodejs中对调用者隐藏函数实现

How to hide function implementation from caller in nodejs

我正在通过 module.exports 导出一个 js 模块。调用函数需要此模块并调用导出函数。

代码看起来像这样:

file1.js

module.exports = {
 Info: showInfo
}

function showInfo(param1, callback) {
 callback(null, getInfo(param1))
}
let secretCode = 'xyz';

function getInfo(p1) {
 return EncodeInfo(param1, secretCode);
}

function EncodeInfo(p2, p3) {
 //some code
}

file2.js

var f1 = require('./file1');

f1.Info("some value");

现在的问题是 file2.js 由客户在运行时提供,代码被部署到服务器。服务器入口点函数调用 file2.js 中的入口函数。 file2.js 只能访问核心节点库、日志记录功能和请求模块。

我需要隐藏里面写的内容file1.js。客户可以这样做来查看代码

console.log(f1.Info.toString());
//this will print following
/*
function showInfo(param1, callback){
    callback(null, getInfo(param1)) 
}
*/

没关系,因为 getInfo() 代码被隐藏了。此外,隐藏了其他私有函数和变量。另请注意,客户无法安装任何其他节点模块,仅提供 file2.js

请注意,我无法控制他在 file2.js 中写的内容,我也无法在将 file2.js 与其余代码合并之前进行扫描。

问题 1: 问题很简单,我的假设是否正确?或者有什么方法可以让他看到其余的代码实现或导入(需要)模块的任何其他细节?也许通过原型?

问题二: 有什么办法可以让他看到服务器入口点功能实现的细节。客户确实有权访问流程,因此 process.env,但没关系。我更关心其他文件的代码。

是的,file2不能访问file1secretVariable是正确的,它通过闭包隐藏得很好。

file2 is provided by the customer at runtime and code gets deployed to the server

那你输了。不要在您的服务器上只 运行 不受信任的代码!代码使用 var f1 = fs.readFileSync('./file1'); 而不是 require('./file1') 是微不足道的,公开您的代码及其 "secret" 变量。可能还有无数种其他方式。

如果您想 运行 不受信任的代码,您需要使用适当的沙盒解决方案。