SafePath.coffee 796 B

12345678910111213141516171819202122232425262728293031
  1. Path = require('path')
  2. BADCHAR_RX = ///
  3. [
  4. \/ # no slashes
  5. \* # no asterisk
  6. \u0000-\u001F # no control characters (0-31)
  7. \u007F # no delete
  8. \u0080-\u009F # no unicode control characters (C1)
  9. \uD800-\uDFFF # no unicode surrogate characters
  10. ]
  11. ///g
  12. BADFILE_RX = ///
  13. (^\.$) # reject . as a filename
  14. | (^\.\.$) # reject .. as a filename
  15. | (^\s+) # reject leading space
  16. | (\s+$) # reject trailing space
  17. ///g
  18. MAX_PATH = 1024 # Maximum path length, in characters. This is fairly arbitrary.
  19. module.exports = SafePath =
  20. isCleanFilename: (filename) ->
  21. return SafePath.isAllowedLength(filename) &&
  22. not filename.match(BADCHAR_RX) &&
  23. not filename.match(BADFILE_RX)
  24. isAllowedLength: (pathname) ->
  25. return pathname.length > 0 && pathname.length <= MAX_PATH