@@ -3,7 +3,7 @@ import type { Inflate, Gunzip } from 'zlib';
3
3
import zlib from 'zlib' ;
4
4
import querystring from 'querystring' ;
5
5
6
- import getBody from 'raw-body ' ;
6
+ import getStream , { MaxBufferError } from 'get-stream ' ;
7
7
import httpError from 'http-errors' ;
8
8
import contentType from 'content-type' ;
9
9
import type { ParsedMediaType } from 'content-type' ;
@@ -83,7 +83,7 @@ async function readBody(
83
83
const charset = typeInfo . parameters . charset ?. toLowerCase ( ) ?? 'utf-8' ;
84
84
85
85
// Assert charset encoding per JSON RFC 7159 sec 8.1
86
- if ( ! charset . startsWith ( 'utf-' ) ) {
86
+ if ( charset !== 'utf8' && charset !== 'utf-8' && charset !== 'utf16le' ) {
87
87
throw httpError ( 415 , `Unsupported charset "${ charset . toUpperCase ( ) } ".` ) ;
88
88
}
89
89
@@ -93,25 +93,22 @@ async function readBody(
93
93
typeof contentEncoding === 'string'
94
94
? contentEncoding . toLowerCase ( )
95
95
: 'identity' ;
96
- const length = encoding === 'identity' ? req . headers [ 'content-length' ] : null ;
97
- const limit = 100 * 1024 ; // 100kb
96
+ const maxBuffer = 100 * 1024 ; // 100kb
98
97
const stream = decompressed ( req , encoding ) ;
99
98
100
99
// Read body from stream.
101
100
try {
102
- return await getBody ( stream , { encoding : charset , length, limit } ) ;
101
+ const buffer = await getStream . buffer ( stream , { maxBuffer } ) ;
102
+ return buffer . toString ( charset ) ;
103
103
} catch ( rawError : unknown ) {
104
- const error = httpError (
105
- 400 ,
106
- /* istanbul ignore next: Thrown by underlying library. */
107
- rawError instanceof Error ? rawError : String ( rawError ) ,
108
- ) ;
109
-
110
- error . message =
111
- error . type === 'encoding.unsupported'
112
- ? `Unsupported charset "${ charset . toUpperCase ( ) } ".`
113
- : `Invalid body: ${ error . message } .` ;
114
- throw error ;
104
+ /* istanbul ignore else: Thrown by underlying library. */
105
+ if ( rawError instanceof MaxBufferError ) {
106
+ throw httpError ( 413 , 'Invalid body: request entity too large.' ) ;
107
+ } else {
108
+ const message =
109
+ rawError instanceof Error ? rawError . message : String ( rawError ) ;
110
+ throw httpError ( 400 , `Invalid body: ${ message } .` ) ;
111
+ }
115
112
}
116
113
}
117
114
0 commit comments