1
0
mirror of synced 2025-12-22 03:16:52 -05:00
Files
docs/middleware/handle-invalid-paths.js
James M. Greene a11d0075ef Prevent REALLY garbage request URLs (#18216)
* Block paths that do not normalize well
2021-03-12 02:58:47 +00:00

43 lines
1.2 KiB
JavaScript

const patterns = require('../lib/patterns')
module.exports = function handleInvalidPaths (req, res, next) {
// prevent open redirect vulnerability
if (req.path.match(patterns.multipleSlashes)) {
return next(404)
}
// Prevent Express from blowing up with `URIError: Failed to decode param`
// for paths like /%7B%
try {
decodeURIComponent(req.path)
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error('unable to decode path', req.path, err)
}
return res.sendStatus(400)
}
// Prevent spammy request URLs from getting through by checking how they
// handle being normalized twice in a row
try {
const origin = 'https://docs.github.com'
const normalizedPath = new URL(req.path, origin).pathname
// This may also throw an error with code `ERR_INVALID_URL`
const reNormalizedPath = new URL(normalizedPath, origin).pathname
if (reNormalizedPath !== normalizedPath) {
throw new Error('URI keeps changing')
}
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error('unable to normalize path', req.path, err)
}
return res.sendStatus(400)
}
return next()
}