1. const path = require('path');
  2. /**
  3. * Verifies the integrity of a file path.
  4. *
  5. * @param {string} filePath The file path to verify.
  6. * @param {string} expectedBase The expected base directory for the file.
  7. * @returns {boolean} True if the path is valid, false otherwise.
  8. */
  9. function verifyFilePath(filePath, expectedBase) {
  10. console.debug(`Verifying file path: ${filePath}, against base: ${expectedBase}`);
  11. try {
  12. // Resolve the file path to its absolute path.
  13. const absolutePath = path.resolve(filePath);
  14. console.debug(`Resolved absolute path: ${absolutePath}`);
  15. // Ensure the absolute path is within the expected base directory.
  16. if (!absolutePath.startsWith(expectedBase)) {
  17. console.warn(`Path ${filePath} does not start with the expected base ${expectedBase}.`);
  18. return false;
  19. }
  20. //Handle relative paths
  21. if(filePath.startsWith('.')){
  22. console.warn(`Path ${filePath} starts with a dot. Consider using absolute paths.`);
  23. }
  24. return true; // Path is valid.
  25. } catch (error) {
  26. console.error(`Error verifying path ${filePath}: ${error.message}`);
  27. return false; // Path is invalid due to an error.
  28. }
  29. }
  30. module.exports = verifyFilePath;

Add your comment