SafePath.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* eslint-disable
  2. max-len,
  3. no-return-assign,
  4. */
  5. // TODO: This file was created by bulk-decaffeinate.
  6. // Fix any style issues and re-enable lint.
  7. /*
  8. * decaffeinate suggestions:
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS207: Consider shorter variations of null checks
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. // This file is shared between the frontend and server code of web, so that
  14. // filename validation is the same in both implementations.
  15. // The logic in all copies must be kept in sync:
  16. // app/src/Features/Project/SafePath.js
  17. // frontend/js/ide/directives/SafePath.js
  18. // frontend/js/features/file-tree/util/safe-path.js
  19. let SafePath
  20. const BADCHAR_RX = new RegExp(
  21. `\
  22. [\
  23. \\/\
  24. \\\\\
  25. \\*\
  26. \\u0000-\\u001F\
  27. \\u007F\
  28. \\u0080-\\u009F\
  29. \\uD800-\\uDFFF\
  30. ]\
  31. `,
  32. 'g'
  33. )
  34. const BADFILE_RX = new RegExp(
  35. `\
  36. (^\\.$)\
  37. |(^\\.\\.$)\
  38. |(^\\s+)\
  39. |(\\s+$)\
  40. `,
  41. 'g'
  42. )
  43. // Put a block on filenames which match javascript property names, as they
  44. // can cause exceptions where the code puts filenames into a hash. This is a
  45. // temporary workaround until the code in other places is made safe against
  46. // property names.
  47. //
  48. // The list of property names is taken from
  49. // ['prototype'].concat(Object.getOwnPropertyNames(Object.prototype))
  50. const BLOCKEDFILE_RX = new RegExp(`\
  51. ^(\
  52. prototype\
  53. |constructor\
  54. |toString\
  55. |toLocaleString\
  56. |valueOf\
  57. |hasOwnProperty\
  58. |isPrototypeOf\
  59. |propertyIsEnumerable\
  60. |__defineGetter__\
  61. |__lookupGetter__\
  62. |__defineSetter__\
  63. |__lookupSetter__\
  64. |__proto__\
  65. )$\
  66. `)
  67. const MAX_PATH = 1024 // Maximum path length, in characters. This is fairly arbitrary.
  68. export default SafePath = {
  69. clean(filename) {
  70. filename = filename.replace(BADCHAR_RX, '_')
  71. // for BADFILE_RX replace any matches with an equal number of underscores
  72. filename = filename.replace(BADFILE_RX, match =>
  73. new Array(match.length + 1).join('_')
  74. )
  75. // replace blocked filenames 'prototype' with '@prototype'
  76. filename = filename.replace(BLOCKEDFILE_RX, '@$1')
  77. return filename
  78. },
  79. isCleanFilename(filename) {
  80. return (
  81. SafePath.isAllowedLength(filename) &&
  82. !filename.match(BADCHAR_RX) &&
  83. !filename.match(BADFILE_RX)
  84. )
  85. },
  86. isAllowedLength(pathname) {
  87. return pathname.length > 0 && pathname.length <= MAX_PATH
  88. }
  89. }