From 9db5fd7884879d055246abf7c92b240ae8735e98 Mon Sep 17 00:00:00 2001 From: muxator Date: Thu, 23 Aug 2018 07:20:17 +0200 Subject: [PATCH] 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 --- src/node/utils/AbsolutePaths.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/node/utils/AbsolutePaths.js b/src/node/utils/AbsolutePaths.js index 6d67bd15d..55dfc98e3 100644 --- a/src/node/utils/AbsolutePaths.js +++ b/src/node/utils/AbsolutePaths.js @@ -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; +};