resolve.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict';
  19. const path = require('path');
  20. const debug = require('debug')('joystream:util:fs:resolve');
  21. /*
  22. * Resolves name relative to base, throwing an error if the given
  23. * name wants to break out of the base directory.
  24. *
  25. * The problem is, we want to use node's functions so we don't add
  26. * platform dependent code, but node's path.resolve() function is a little
  27. * useless for our case because it does not care about breaking out of
  28. * a base directory.
  29. */
  30. function resolve(base, name)
  31. {
  32. debug('Resolving', name);
  33. // In a firs step, we strip leading slashes from the name, because they're
  34. // just saying "relative to the base" in our use case.
  35. var res = name.replace(/^\/+/, '');
  36. debug('Stripped', res);
  37. // At this point resolving the path should stay within the base we specify.
  38. // We do specify a base other than the file system root, because the file
  39. // everything is always relative to the file system root.
  40. const test_base = path.join(path.sep, 'test-base');
  41. debug('Test base is', test_base);
  42. res = path.resolve(test_base, res);
  43. debug('Resolved', res);
  44. // Ok, we can check for violations now.
  45. if (res.slice(0, test_base.length) != test_base) {
  46. throw Error(`Name "${name}" cannot be resolved to a repo relative path, aborting!`);
  47. }
  48. // If we strip the base now, we have the relative name resolved.
  49. res = res.slice(test_base.length + 1);
  50. debug('Relative', res);
  51. // Finally we can join this relative name to the requested base.
  52. var res = path.join(base, res);
  53. debug('Result', res);
  54. return res;
  55. }
  56. module.exports = resolve;