import patterns from '../lib/patterns.js' import statsd from '../lib/statsd.js' const STATSD_KEY = 'middleware.handle_invalid_paths' export default function handleInvalidPaths(req, res, next) { // prevent open redirect vulnerability if (req.path.match(patterns.multipleSlashes)) { statsd.increment(STATSD_KEY, 1, ['check:multiple-slashes']) 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) } statsd.increment(STATSD_KEY, 1, ['check:decodeURIComponent']) 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) } statsd.increment(STATSD_KEY, 1, ['check:ERR_INVALID_URL']) return res.sendStatus(400) } // Prevent some script tag injection attacks if (req.path.match(/