Skip to content

Instantly share code, notes, and snippets.

@davidrapin
Created April 4, 2016 16:08
Show Gist options
  • Save davidrapin/bc24a126408f1e799c630b44563a10a5 to your computer and use it in GitHub Desktop.
Save davidrapin/bc24a126408f1e799c630b44563a10a5 to your computer and use it in GitHub Desktop.
NodeJS module security
// this is a work-in-progress (currently broken), don't use it as-is.
function patchRequire(verbose) {
var Module = require('module');
var originalRequire = Module.prototype.require;
var SENSITIVE_MODULES = ['fs', 'child_process', 'cluster', 'vm'];
var stack = [];
/**
* @param {string} moduleId Package id
* @param {boolean} [trusted=false] Whether the required package is trusted
* @return {*}
*/
Module.prototype.require = function(moduleId, trusted) {
trusted = (trusted === undefined) ? true : !!trusted;
var parentTrust = stack.length ? stack[stack.length - 1].trusted : true;
if (!parentTrust && SENSITIVE_MODULES.includes(moduleId)) {
throw new Error(
'untrusted require chain' +
stack.map(r => r.id + '[' + r.trusted + ']').join(' -> ') + ' => ' + moduleId
);
}
stack.push({id: moduleId, trusted: trusted && parentTrust});
try {
if (verbose && moduleId.indexOf('fs') >= 0) {
console.log(stack.map(r => r.id + '[' + r.trusted + ']').join(' -> ') + ' => ' + moduleId);
}
return originalRequire.call(this, moduleId);
} finally {
stack.pop();
}
};
// patch current module
global.require = Module.prototype.require;
}
patchRequire(true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment