1
0
mirror of synced 2025-12-30 03:01:36 -05:00
Files
docs/middleware/handle-invalid-paths.js
2022-04-06 16:47:47 +00:00

66 lines
2.1 KiB
JavaScript

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(/<script/i)) {
statsd.increment(STATSD_KEY, 1, ['check:script-tag-injection'])
return res.sendStatus(400)
}
// Prevent some injection attacks targeting Fastly
if (req.path.match(/<esi:include/i)) {
statsd.increment(STATSD_KEY, 1, ['check:esi-injection-attack'])
return res.sendStatus(400)
}
// Prevent various malicious injection attacks targeting Next.js
if (req.path.match(/^\/_next[^/]/) || req.path === '/_next/data' || req.path === '/_next/data/') {
statsd.increment(STATSD_KEY, 1, ['check:nextjs-injection-attack'])
return next(404)
}
return next()
}