Any thoughts on how one would go about removing the global context from a nodejs module?
I'm not looking for a solution to the below problem, but if you need more context here you go.
I'm working on a project where my users are able to upload their own nodejs modules and, if it fits a predefined framework, it will run on our at periodic times through out the day. Obviously this is a major security concern. A good 90% solution would simply be removing the global context.
As stated in the comments, you really need to run user-supplied modules in a separate process because an infinite loop will freeze any node process.
You should start with the VM module:
require).Here's an example:
var fs = require('fs'),
vm = require('vm');
function runCode(fileName) {
var code = fs.readFileSync(fileName),
sandbox = {
console: console,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
require: require,
module: module,
exports: exports,
process: process,
Buffer: Buffer
};
vm.runInNewContext(code, sandbox, fileName);
}
The user-supplied code will be able to access everything that I passed in the sandbox, as if it was in the global scope. In my case, I chose to expose almost everything from the real node.js global scope. You can chose what not to expose.
Also, you should check child_process.spawn if you want your solution to be secure.