-
Notifications
You must be signed in to change notification settings - Fork 53
/
xssValidator.ts
67 lines (63 loc) 路 2.05 KB
/
xssValidator.ts
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { FilterXSS, IFilterXSSOptions } from 'xss'
import {
defineEventHandler,
createError,
getQuery,
readBody,
getRouteRules
} from '#imports'
import { HTTPMethod } from '~/src/module'
export default defineEventHandler(async (event) => {
const { security } = getRouteRules(event)
if (security?.xssValidator) {
const filterOpt: IFilterXSSOptions = {
...security.xssValidator,
escapeHtml: undefined
}
if (security.xssValidator.escapeHtml === false) {
// No html escaping (by default "<" is replaced by "<" and ">" by ">")
filterOpt.escapeHtml = (value: string) => value
}
const xssValidator = new FilterXSS(filterOpt)
if (event.node.req.socket.readyState !== 'readOnly') {
if (
security.xssValidator.methods &&
security.xssValidator.methods.includes(
event.node.req.method! as HTTPMethod
)
) {
const valueToFilter =
event.node.req.method === 'GET'
? getQuery(event)
: event.node.req.headers['content-type']?.includes(
'multipart/form-data'
)
? await readMultipartFormData(event)
: await readBody(event)
// Fix for problems when one middleware is returning an error and it is catched in the next
if (valueToFilter && Object.keys(valueToFilter).length) {
if (
valueToFilter.statusMessage &&
valueToFilter.statusMessage !== 'Bad Request'
) {
return
}
const stringifiedValue = JSON.stringify(valueToFilter)
const processedValue = xssValidator.process(
JSON.stringify(valueToFilter)
)
if (processedValue !== stringifiedValue) {
const badRequestError = {
statusCode: 400,
statusMessage: 'Bad Request'
}
if (security.xssValidator.throwError === false) {
return badRequestError
}
throw createError(badRequestError)
}
}
}
}
}
})