@@ -3,7 +3,7 @@ import type { Inflate, Gunzip } from 'zlib';
33import zlib from 'zlib' ;
44import querystring from 'querystring' ;
55
6- import getBody from 'raw-body ' ;
6+ import getStream , { MaxBufferError } from 'get-stream ' ;
77import httpError from 'http-errors' ;
88import contentType from 'content-type' ;
99import type { ParsedMediaType } from 'content-type' ;
@@ -83,7 +83,7 @@ async function readBody(
8383 const charset = typeInfo . parameters . charset ?. toLowerCase ( ) ?? 'utf-8' ;
8484
8585 // Assert charset encoding per JSON RFC 7159 sec 8.1
86- if ( ! charset . startsWith ( 'utf-' ) ) {
86+ if ( charset !== 'utf8' && charset !== 'utf-8' && charset !== 'utf16le' ) {
8787 throw httpError ( 415 , `Unsupported charset "${ charset . toUpperCase ( ) } ".` ) ;
8888 }
8989
@@ -93,25 +93,22 @@ async function readBody(
9393 typeof contentEncoding === 'string'
9494 ? contentEncoding . toLowerCase ( )
9595 : 'identity' ;
96- const length = encoding === 'identity' ? req . headers [ 'content-length' ] : null ;
97- const limit = 100 * 1024 ; // 100kb
96+ const maxBuffer = 100 * 1024 ; // 100kb
9897 const stream = decompressed ( req , encoding ) ;
9998
10099 // Read body from stream.
101100 try {
102- return await getBody ( stream , { encoding : charset , length, limit } ) ;
101+ const buffer = await getStream . buffer ( stream , { maxBuffer } ) ;
102+ return buffer . toString ( charset ) ;
103103 } 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+ }
115112 }
116113}
117114
0 commit comments