resolve.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. debug('Resolving', name)
  32. // In a firs step, we strip leading slashes from the name, because they're
  33. // just saying "relative to the base" in our use case.
  34. let res = name.replace(/^\/+/, '')
  35. debug('Stripped', res)
  36. // At this point resolving the path should stay within the base we specify.
  37. // We do specify a base other than the file system root, because the file
  38. // everything is always relative to the file system root.
  39. const testBase = path.join(path.sep, 'test-base')
  40. debug('Test base is', testBase)
  41. res = path.resolve(testBase, res)
  42. debug('Resolved', res)
  43. // Ok, we can check for violations now.
  44. if (res.slice(0, testBase.length) !== testBase) {
  45. throw Error(`Name "${name}" cannot be resolved to a repo relative path, aborting!`)
  46. }
  47. // If we strip the base now, we have the relative name resolved.
  48. res = res.slice(testBase.length + 1)
  49. debug('Relative', res)
  50. // Finally we can join this relative name to the requested base.
  51. res = path.join(base, res)
  52. debug('Result', res)
  53. return res
  54. }
  55. module.exports = resolve