-
Notifications
You must be signed in to change notification settings - Fork 67k
Expand file tree
/
Copy pathhandle-malformed-urls.ts
More file actions
30 lines (27 loc) · 957 Bytes
/
handle-malformed-urls.ts
File metadata and controls
30 lines (27 loc) · 957 Bytes
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
import type { Response, NextFunction } from 'express'
import { defaultCacheControl } from '@/frame/middleware/cache-control'
import { ExtendedRequest } from '@/types'
/**
* Middleware to handle malformed UTF-8 sequences in URLs that cause
* decodeURIComponent to fail. This prevents crashes from malicious
* requests containing invalid URL-encoded sequences like %FF.
*/
export default function handleMalformedUrls(
req: ExtendedRequest,
res: Response,
next: NextFunction,
) {
// Check URL for malformed UTF-8 sequences
// Express/router doesn't catch these during initial parsing - they cause
// crashes later when decodeURIComponent is called at the router level
const url = req.originalUrl || req.url
try {
decodeURIComponent(url)
} catch {
// If any decoding fails, this is a malformed URL
defaultCacheControl(res)
res.status(400).type('text').send('Bad Request: Malformed URL')
return
}
return next()
}