index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*!
  2. * resolve-path
  3. * Copyright(c) 2014 Jonathan Ong
  4. * Copyright(c) 2015-2018 Douglas Christopher Wilson
  5. * MIT Licensed
  6. */
  7. 'use strict'
  8. /**
  9. * Module dependencies.
  10. * @private
  11. */
  12. var createError = require('http-errors')
  13. var join = require('path').join
  14. var normalize = require('path').normalize
  15. var pathIsAbsolute = require('path-is-absolute')
  16. var resolve = require('path').resolve
  17. var sep = require('path').sep
  18. /**
  19. * Module exports.
  20. * @public
  21. */
  22. module.exports = resolvePath
  23. /**
  24. * Module variables.
  25. * @private
  26. */
  27. var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
  28. /**
  29. * Resolve relative path against a root path
  30. *
  31. * @param {string} rootPath
  32. * @param {string} relativePath
  33. * @return {string}
  34. * @public
  35. */
  36. function resolvePath (rootPath, relativePath) {
  37. var path = relativePath
  38. var root = rootPath
  39. // root is optional, similar to root.resolve
  40. if (arguments.length === 1) {
  41. path = rootPath
  42. root = process.cwd()
  43. }
  44. if (root == null) {
  45. throw new TypeError('argument rootPath is required')
  46. }
  47. if (typeof root !== 'string') {
  48. throw new TypeError('argument rootPath must be a string')
  49. }
  50. if (path == null) {
  51. throw new TypeError('argument relativePath is required')
  52. }
  53. if (typeof path !== 'string') {
  54. throw new TypeError('argument relativePath must be a string')
  55. }
  56. // containing NULL bytes is malicious
  57. if (path.indexOf('\0') !== -1) {
  58. throw createError(400, 'Malicious Path')
  59. }
  60. // path should never be absolute
  61. if (pathIsAbsolute.posix(path) || pathIsAbsolute.win32(path)) {
  62. throw createError(400, 'Malicious Path')
  63. }
  64. // path outside root
  65. if (UP_PATH_REGEXP.test(normalize('.' + sep + path))) {
  66. throw createError(403)
  67. }
  68. // join the relative path
  69. return normalize(join(resolve(root), path))
  70. }