SafePath.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // Both copies must be kept in sync:
  16. // app/coffee/Features/Project/SafePath.coffee
  17. // public/coffee/ide/directives/SafePath.coffee
  18. let SafePath
  19. const BADCHAR_RX = new RegExp(
  20. `\
  21. [\
  22. \\/\
  23. \\\\\
  24. \\*\
  25. \\u0000-\\u001F\
  26. \\u007F\
  27. \\u0080-\\u009F\
  28. \\uD800-\\uDFFF\
  29. ]\
  30. `,
  31. 'g'
  32. )
  33. const BADFILE_RX = new RegExp(
  34. `\
  35. (^\\.$)\
  36. |(^\\.\\.$)\
  37. |(^\\s+)\
  38. |(\\s+$)\
  39. `,
  40. 'g'
  41. )
  42. // Put a block on filenames which match javascript property names, as they
  43. // can cause exceptions where the code puts filenames into a hash. This is a
  44. // temporary workaround until the code in other places is made safe against
  45. // property names.
  46. //
  47. // The list of property names is taken from
  48. // ['prototype'].concat(Object.getOwnPropertyNames(Object.prototype))
  49. const BLOCKEDFILE_RX = new RegExp(`\
  50. ^(\
  51. prototype\
  52. |constructor\
  53. |toString\
  54. |toLocaleString\
  55. |valueOf\
  56. |hasOwnProperty\
  57. |isPrototypeOf\
  58. |propertyIsEnumerable\
  59. |__defineGetter__\
  60. |__lookupGetter__\
  61. |__defineSetter__\
  62. |__lookupSetter__\
  63. |__proto__\
  64. )$\
  65. `)
  66. const MAX_PATH = 1024 // Maximum path length, in characters. This is fairly arbitrary.
  67. export default (SafePath = {
  68. clean(filename) {
  69. filename = filename.replace(BADCHAR_RX, '_')
  70. // for BADFILE_RX replace any matches with an equal number of underscores
  71. filename = filename.replace(BADFILE_RX, match =>
  72. new Array(match.length + 1).join('_')
  73. )
  74. // replace blocked filenames 'prototype' with '@prototype'
  75. filename = filename.replace(BLOCKEDFILE_RX, '@$1')
  76. return filename
  77. },
  78. isCleanFilename(filename) {
  79. return (
  80. SafePath.isAllowedLength(filename) &&
  81. !filename.match(BADCHAR_RX) &&
  82. !filename.match(BADFILE_RX)
  83. )
  84. },
  85. isAllowedLength(pathname) {
  86. return pathname.length > 0 && pathname.length <= MAX_PATH
  87. }
  88. })