@@ -254,9 +254,10 @@ res.json = function json(obj) {
254
254
255
255
// settings
256
256
var app = this . app ;
257
+ var escape = app . get ( 'json escape' )
257
258
var replacer = app . get ( 'json replacer' ) ;
258
259
var spaces = app . get ( 'json spaces' ) ;
259
- var body = stringify ( val , replacer , spaces ) ;
260
+ var body = stringify ( val , replacer , spaces , escape )
260
261
261
262
// content-type
262
263
if ( ! this . get ( 'Content-Type' ) ) {
@@ -296,9 +297,10 @@ res.jsonp = function jsonp(obj) {
296
297
297
298
// settings
298
299
var app = this . app ;
300
+ var escape = app . get ( 'json escape' )
299
301
var replacer = app . get ( 'json replacer' ) ;
300
302
var spaces = app . get ( 'json spaces' ) ;
301
- var body = stringify ( val , replacer , spaces ) ;
303
+ var body = stringify ( val , replacer , spaces , escape )
302
304
var callback = this . req . query [ app . get ( 'jsonp callback name' ) ] ;
303
305
304
306
// content-type
@@ -1098,14 +1100,38 @@ function sendfile(res, file, options, callback) {
1098
1100
}
1099
1101
1100
1102
/**
1101
- * Stringify JSON, like JSON.stringify, but v8 optimized.
1103
+ * Stringify JSON, like JSON.stringify, but v8 optimized, with the
1104
+ * ability to escape characters that can trigger HTML sniffing.
1105
+ *
1106
+ * @param {* } value
1107
+ * @param {function } replaces
1108
+ * @param {number } spaces
1109
+ * @param {boolean } escape
1110
+ * @returns {string }
1102
1111
* @private
1103
1112
*/
1104
1113
1105
- function stringify ( value , replacer , spaces ) {
1114
+ function stringify ( value , replacer , spaces , escape ) {
1106
1115
// v8 checks arguments.length for optimizing simple call
1107
1116
// https://bugs.chromium.org/p/v8/issues/detail?id=4730
1108
- return replacer || spaces
1117
+ var json = replacer || spaces
1109
1118
? JSON . stringify ( value , replacer , spaces )
1110
1119
: JSON . stringify ( value ) ;
1120
+
1121
+ if ( escape ) {
1122
+ json = json . replace ( / [ < > & ] / g, function ( c ) {
1123
+ switch ( c . charCodeAt ( 0 ) ) {
1124
+ case 0x3c :
1125
+ return '\\u003c'
1126
+ case 0x3e :
1127
+ return '\\u003e'
1128
+ case 0x26 :
1129
+ return '\\u0026'
1130
+ default :
1131
+ return c
1132
+ }
1133
+ } )
1134
+ }
1135
+
1136
+ return json
1111
1137
}
0 commit comments