Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

handle-invalid-paths.js 1.2 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  1. const patterns = require('../lib/patterns')
  2. module.exports = function handleInvalidPaths (req, res, next) {
  3. // prevent open redirect vulnerability
  4. if (req.path.match(patterns.multipleSlashes)) {
  5. return next(404)
  6. }
  7. // Prevent Express from blowing up with `URIError: Failed to decode param`
  8. // for paths like /%7B%
  9. try {
  10. decodeURIComponent(req.path)
  11. } catch (err) {
  12. if (process.env.NODE_ENV !== 'test') {
  13. console.error('unable to decode path', req.path, err)
  14. }
  15. return res.sendStatus(400)
  16. }
  17. // Prevent spammy request URLs from getting through by checking how they
  18. // handle being normalized twice in a row
  19. try {
  20. const origin = 'https://docs.github.com'
  21. const normalizedPath = new URL(req.path, origin).pathname
  22. // This may also throw an error with code `ERR_INVALID_URL`
  23. const reNormalizedPath = new URL(normalizedPath, origin).pathname
  24. if (reNormalizedPath !== normalizedPath) {
  25. throw new Error('URI keeps changing')
  26. }
  27. } catch (err) {
  28. if (process.env.NODE_ENV !== 'test') {
  29. console.error('unable to normalize path', req.path, err)
  30. }
  31. return res.sendStatus(400)
  32. }
  33. return next()
  34. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...