AbsolutePaths: introduced isSubdir()

It can be used to check whether a user input or a configuration settings tries
to traverse the directory hierarchy, going out of its allowed bounds.

source: https://stackoverflow.com/questions/37521893/determine-if-a-path-is-subdirectory-of-another-in-node-js#45242825
pull/3473/head
muxator 2018-08-23 07:20:17 +02:00
parent 0728e66723
commit 9db5fd7884
1 changed files with 16 additions and 0 deletions

View File

@ -135,3 +135,19 @@ exports.makeAbsolute = function(somePath) {
absPathLogger.debug(`Relative path "${somePath}" can be rewritten to "${rewrittenPath}"`);
return rewrittenPath;
};
/**
* Returns whether arbitraryDir is a subdirectory of parent.
*
* @param {string} parent - a path to check arbitraryDir against
* @param {string} arbitraryDir - the function will check if this directory is
* a subdirectory of the base one
* @return {boolean}
*/
exports.isSubdir = function(parent, arbitraryDir) {
// modified from: https://stackoverflow.com/questions/37521893/determine-if-a-path-is-subdirectory-of-another-in-node-js#45242825
const relative = path.relative(parent, arbitraryDir);
const isSubdir = !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
return isSubdir;
};