-
Notifications
You must be signed in to change notification settings - Fork 869
/
Copy pathfix-request-body.ts
65 lines (54 loc) · 1.65 KB
/
fix-request-body.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import type * as http from 'http';
import type { Request } from '../types';
import * as querystring from 'querystring';
type HandleBadRequestArgs = {
proxyReq: http.ClientRequest;
req: http.IncomingMessage;
res: http.ServerResponse;
};
/**
* Fix proxied body if bodyParser is involved.
*/
export function fixRequestBody(
proxyReq: http.ClientRequest,
req: http.IncomingMessage,
res: http.ServerResponse
): void {
const requestBody = (req as Request).body;
if (!requestBody) {
return;
}
const contentType = proxyReq.getHeader('Content-Type') as string;
if (!contentType) {
return;
}
// Handle bad request when unexpected "Connect: Upgrade" header is provided
if (/upgrade/gi.test(proxyReq.getHeader('Connection') as string)) {
handleBadRequest({ proxyReq, req, res });
return;
}
// Handle bad request when invalid request body is provided
if (hasInvalidKeys(requestBody)) {
handleBadRequest({ proxyReq, req, res });
return;
}
const writeBody = (bodyData: string) => {
// deepcode ignore ContentLengthInCode: bodyParser fix
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
};
if (contentType.includes('application/json')) {
writeBody(JSON.stringify(requestBody));
} else if (contentType.includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(requestBody));
}
}
function hasInvalidKeys(obj) {
return Object.keys(obj).some((key) => /[\n\r]/.test(key));
}
function handleBadRequest({ proxyReq, req, res }: HandleBadRequestArgs) {
res.writeHead(400);
res.end('Bad Request');
proxyReq.destroy();
req.destroy();
}