11'use strict'
22
3- const rawbody = require ( 'raw-body' )
43const rules = require ( '../rules' )
54
5+ function getBodyAsString ( body ) {
6+ if ( typeof body === 'object' ) {
7+ return JSON . stringify ( body )
8+ } else if ( Buffer . isBuffer ( body ) ) {
9+ return body . toString ( 'utf-8' )
10+ }
11+
12+ return body
13+ }
14+
615function sqlInjection ( options = { } ) {
716 const { loggerFunction = noop } = options
817
918 return ( request , response , next ) => {
10- request . _protect = request . _protect || { }
1119 // return 403 if SQL injection found
1220 if ( rules . isSqlInjection ( request . originalUrl ) ) {
1321 loggerFunction ( 'sql-injection' , {
@@ -17,31 +25,15 @@ function sqlInjection (options = {}) {
1725 }
1826
1927 if ( options . body ) {
20- if ( request . _protect . body ) {
21- if ( rules . isXss ( request . _protect . body ) ) {
22- loggerFunction ( 'xss' , {
23- body : request . _protect . body
24- } )
25- return response . sendStatus ( 403 )
26- }
27- return next ( )
28+ const body = getBodyAsString ( request . body )
29+
30+ if ( rules . isSqlInjection ( body ) ) {
31+ loggerFunction ( 'sql-injection' , {
32+ body
33+ } )
34+ return response . sendStatus ( 403 )
2835 }
29- return rawbody ( request , Object . assign ( { } , options . body , {
30- encoding : 'utf-8'
31- } ) )
32- . then ( ( body ) => {
33- request . _protect . body = body
34- if ( rules . isSqlInjection ( body ) ) {
35- loggerFunction ( 'sql-injection' , {
36- body
37- } )
38- return response . sendStatus ( 403 )
39- }
40- return next ( )
41- } )
42- . catch ( ( error ) => {
43- next ( error )
44- } )
36+ return next ( )
4537 }
4638
4739 return next ( )
@@ -52,7 +44,6 @@ function xss (options = {}) {
5244 const { loggerFunction = noop } = options
5345
5446 return ( request , response , next ) => {
55- request . _protect = request . _protect || { }
5647 // return 403 if XSS found
5748 if ( rules . isXss ( request . originalUrl ) ) {
5849 loggerFunction ( 'xss' , {
@@ -62,31 +53,13 @@ function xss (options = {}) {
6253 }
6354
6455 if ( options . body ) {
65- if ( request . _protect . body ) {
66- if ( rules . isXss ( request . _protect . body ) ) {
67- loggerFunction ( 'xss' , {
68- body : request . _protect . body
69- } )
70- return response . sendStatus ( 403 )
71- }
72- return next ( )
56+ const body = getBodyAsString ( request . body )
57+ if ( rules . isXss ( body ) ) {
58+ loggerFunction ( 'xss' , {
59+ body
60+ } )
61+ return response . sendStatus ( 403 )
7362 }
74- return rawbody ( request , Object . assign ( { } , options . body , {
75- encoding : 'utf-8'
76- } ) )
77- . then ( ( body ) => {
78- request . _protect . body = body
79- if ( rules . isXss ( body ) ) {
80- loggerFunction ( 'xss' , {
81- body
82- } )
83- return response . sendStatus ( 403 )
84- }
85- return next ( )
86- } )
87- . catch ( ( error ) => {
88- next ( error )
89- } )
9063 }
9164
9265 return next ( )
0 commit comments