const path = require('path');
/**
* Verifies the integrity of a file path.
*
* @param {string} filePath The file path to verify.
* @param {string} expectedBase The expected base directory for the file.
* @returns {boolean} True if the path is valid, false otherwise.
*/
function verifyFilePath(filePath, expectedBase) {
console.debug(`Verifying file path: ${filePath}, against base: ${expectedBase}`);
try {
// Resolve the file path to its absolute path.
const absolutePath = path.resolve(filePath);
console.debug(`Resolved absolute path: ${absolutePath}`);
// Ensure the absolute path is within the expected base directory.
if (!absolutePath.startsWith(expectedBase)) {
console.warn(`Path ${filePath} does not start with the expected base ${expectedBase}.`);
return false;
}
//Handle relative paths
if(filePath.startsWith('.')){
console.warn(`Path ${filePath} starts with a dot. Consider using absolute paths.`);
}
return true; // Path is valid.
} catch (error) {
console.error(`Error verifying path ${filePath}: ${error.message}`);
return false; // Path is invalid due to an error.
}
}
module.exports = verifyFilePath;
Add your comment