I don't know if this is the best solution but I did manage to accomplish this. The context object for the repl is the global object. It's just automatically augmented with everything from global
. This means you can iterate over the properties on it and remove the ones you are not interested in.
https://gist.github.com/Chevex/7000130
// Function to determine if an array contains a specific value.
function contains(array, value) {
for(var i = 0; i < array.length; i++) {
if(array[i] === value) return true;
}
return false;
}
var repl = require('repl'),
newRepl = repl.start('> ');
var allowedGlobals = ['ArrayBuffer', 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array',
'Uint32Array', 'Float32Array', 'Float64Array', 'DataView', 'Buffer', 'setTimeout', 'setInterval',
'clearTimeout', 'clearInterval', 'console', '_'];
for (var key in newRepl.context) {
if (!contains(allowedGlobals, key)) {
delete newRepl.context[key];
}
}
It's kind of annoying having to maintain a string array of global variables I want to allow, but at least this white-lists them. If node updates and adds something new to the global scope it won't be exposed until I explicitly add it to the list.
If you need to also white-list repl commands or eliminate the repl's access to node core modules then see this question.