Created
April 4, 2016 16:08
-
-
Save davidrapin/bc24a126408f1e799c630b44563a10a5 to your computer and use it in GitHub Desktop.
NodeJS module security
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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