如何限制节点repl对内部节点模块的访问?

时间:2013-10-16 00:58:53

标签: javascript node.js module read-eval-print-loop node-repl

previous question中,我想出了如何从repl上下文中消除不需要的全局变量。但是,我发现repl可以自动访问所有内部节点模块,而无需使用require。我不知道如何禁用它。我甚至尝试覆盖repl本身的模块变量,但它不起作用。

  

> fs =“test”;
  > FS

它仍显示fs原始值。这是非常不幸的,因为我试图公开一个公共代表,但它让他们可以访问整个服务器。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

正如您所说,REPL可以访问core modules

(但是,经过检查,我能够用节点0.10.20覆盖它们,所以应该有一个解决方案)

> fs
> { Stats: [Function], …
> fs = 'hello';
> fs
'hello'

更好的方法是在创建repl实例之前覆盖repl._builtinLibs

var repl = require('repl');
repl._builtinLibs = [];
repl.start('> ');

此外,如果您不想公开.save.load等命令,那么白名单repl命令相当简单。

var allowedReplCmds = ['.break', '.clear', '.help'];

var newRepl = repl.start('> ');
for (var key in newRepl.commands)
    if (!allowedReplCmds.contains(key))
        delete replInstance.commands[key];

注意:数组通常没有contains方法,所以我添加了一个。

Array.prototype.contains = function(v) {
    for(var i = 0; i < this.length; i++) {
        if(this[i] === v) return true;
    }
    return false;
};

如果要从repl实例的全局范围中删除变量,请参阅this question


  

请注意,向公众公开REPL是非常不安全的。

您可以轻松崩溃整个服务器

> setTimeout(function () { throw 'bye bye!'; }, 0);

异步回调中发生的错误不会被REPL捕获并关闭node.js实例。

您可以阻止服务器

> while(true) {};

您最好的选择是使用child_process,readline和vm在单独的进程中编写自己的REPL代码。这是一个起点:

主人:

// master.js
var fork = require('child_process').fork;

// functions exposed to the repl
var replApi = {
  hello: function () {
    return 'world!';
  },

  unknown: function () {
    return 'unknown';
  }
};

function forkRepl() {
  var repl = fork('./child_repl');

  repl.on('message', function (command) {
    var fun = replApi[command] || replApi.unknown;
     repl.send(fun());
  });

  // restart the repl if it dies
  repl.on('exit', forkRepl);
}

forkRepl();

和repl的单独过程:

// child_repl.js
var readline = require('readline'),
    vm = require('vm');

var context = vm.createContext({
  hello: function () {
    process.send('hello');
  }
});

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.on('line', function (line) {
  vm.runInContext(line, context, 'repl.vm');
});

process.on('message', function (message) {
  console.log('master:', message);
});

rl.prompt();
相关问题