11/**
22 * @param {import('http').IncomingMessage } req
3- * @returns {Promise<string | Uint8Array > }
3+ * @returns {Promise<Uint8Array | string | null > }
44 */
55export function getRawBody ( req ) {
66 return new Promise ( ( fulfil , reject ) => {
77 const h = req . headers ;
88
99 if ( ! h [ 'content-type' ] ) {
10- fulfil ( null ) ;
11- return ;
10+ return fulfil ( null ) ;
1211 }
1312
1413 req . on ( 'error' , reject ) ;
1514
1615 const length = Number ( h [ 'content-length' ] ) ;
1716
18- /** @type {Uint8Array } */
19- let data ;
20-
21- if ( ! isNaN ( length ) ) {
22- data = new Uint8Array ( length ) ;
17+ // https://github.com/jshttp/type-is/blob/c1f4388c71c8a01f79934e68f630ca4a15fffcd6/index.js#L81-L95
18+ if ( isNaN ( length ) && h [ 'transfer-encoding' ] == null ) {
19+ return fulfil ( null ) ;
20+ }
2321
24- let i = 0 ;
22+ let data = new Uint8Array ( length || 0 ) ;
2523
24+ if ( length > 0 ) {
25+ let offset = 0 ;
2626 req . on ( 'data' , ( chunk ) => {
27- data . set ( chunk , i ) ;
28- i += chunk . length ;
29- } ) ;
30- } else {
31- // https://github.com/jshttp/type-is/blob/c1f4388c71c8a01f79934e68f630ca4a15fffcd6/index.js#L81-L95
32- if ( h [ 'transfer-encoding' ] === undefined ) {
33- fulfil ( null ) ;
34- return ;
35- }
27+ const new_len = offset + Buffer . byteLength ( chunk ) ;
3628
37- data = new Uint8Array ( 0 ) ;
29+ if ( new_len > length ) {
30+ return reject ( {
31+ status : 413 ,
32+ reason : 'Exceeded "Content-Length" limit'
33+ } ) ;
34+ }
3835
36+ data . set ( chunk , offset ) ;
37+ offset = new_len ;
38+ } ) ;
39+ } else {
3940 req . on ( 'data' , ( chunk ) => {
4041 const new_data = new Uint8Array ( data . length + chunk . length ) ;
41- new_data . set ( data ) ;
42+ new_data . set ( data , 0 ) ;
4243 new_data . set ( chunk , data . length ) ;
4344 data = new_data ;
4445 } ) ;
@@ -48,11 +49,11 @@ export function getRawBody(req) {
4849 const [ type ] = h [ 'content-type' ] . split ( / ; \s * / ) ;
4950
5051 if ( type === 'application/octet-stream' ) {
51- fulfil ( data ) ;
52+ return fulfil ( data ) ;
5253 }
5354
54- const decoder = new TextDecoder ( h [ 'content-encoding' ] || 'utf-8' ) ;
55- fulfil ( decoder . decode ( data ) ) ;
55+ const encoding = h [ 'content-encoding' ] || 'utf-8' ;
56+ fulfil ( new TextDecoder ( encoding ) . decode ( data ) ) ;
5657 } ) ;
5758 } ) ;
5859}
0 commit comments