Repository navigation
Expand file tree
/
Copy pathhttpRequestParser.ts
More file actions
231 lines (203 loc) · 9.74 KB
/
Copy pathhttpRequestParser.ts
File metadata and controls
231 lines (203 loc) · 9.74 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import * as fs from 'fs-extra';
import { EOL } from 'os';
import { Stream } from 'stream';
import { SystemSettings } from '../models/configurationSettings';
import { FormParamEncodingStrategy } from '../models/formParamEncodingStrategy';
import { HttpRequest } from '../models/httpRequest';
import { RequestParser } from '../models/requestParser';
import { MimeUtility } from './mimeUtility';
import { getContentType, getHeader, removeHeader } from './misc';
import { parseRequestHeaders, resolveRequestBodyPath } from './requestParserUtil';
import { convertStreamToString } from './streamUtility';
import { VariableProcessor } from "./variableProcessor";
const CombinedStream = require('combined-stream');
const encodeurl = require('encodeurl');
enum ParseState {
URL,
Header,
Body,
}
export class HttpRequestParser implements RequestParser {
private readonly defaultMethod = 'GET';
private readonly queryStringLinePrefix = /^\s*[&\?]/;
private readonly inputFileSyntax = /^<(?:(?<processVariables>@)(?<encoding>\w+)?)?\s+(?<filepath>.+?)\s*$/;
private readonly defaultFileEncoding = 'utf8';
public constructor(private readonly requestRawText: string, private readonly settings: SystemSettings) {
}
public async parseHttpRequest(name?: string): Promise<HttpRequest> {
// parse follows http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
// split the request raw text into lines
const lines: string[] = this.requestRawText.split(EOL);
const requestLines: string[] = [];
const headersLines: string[] = [];
const bodyLines: string[] = [];
const variableLines: string[] = [];
let state = ParseState.URL;
let currentLine: string | undefined;
while ((currentLine = lines.shift()) !== undefined) {
const nextLine = lines[0];
switch (state) {
case ParseState.URL:
requestLines.push(currentLine.trim());
if (nextLine === undefined
|| this.queryStringLinePrefix.test(nextLine)) {
// request with request line only
} else if (nextLine.trim()) {
state = ParseState.Header;
} else {
// request with no headers but has body
// remove the blank line before the body
lines.shift();
state = ParseState.Body;
}
break;
case ParseState.Header:
headersLines.push(currentLine.trim());
if (nextLine?.trim() === '') {
// request with no headers but has body
// remove the blank line before the body
lines.shift();
state = ParseState.Body;
}
break;
case ParseState.Body:
bodyLines.push(currentLine);
break;
}
}
// parse request line
const requestLine = this.parseRequestLine(requestLines.map(l => l.trim()).join(''));
// parse headers lines
const headers = parseRequestHeaders(headersLines, this.settings.defaultHeaders, requestLine.url);
// let underlying node.js library recalculate the content length
removeHeader(headers, 'content-length');
// check request type
const isGraphQlRequest = getHeader(headers, 'X-Request-Type') === 'GraphQL';
if (isGraphQlRequest) {
removeHeader(headers, 'X-Request-Type');
// a request doesn't necessarily need variables to be considered a GraphQL request
const firstEmptyLine = bodyLines.findIndex(value => value.trim() === '');
if (firstEmptyLine !== -1) {
variableLines.push(...bodyLines.splice(firstEmptyLine + 1));
bodyLines.pop(); // remove the empty line between body and variables
}
}
// parse body lines
const contentTypeHeader = getContentType(headers);
let body = await this.parseBody(bodyLines, contentTypeHeader);
if (isGraphQlRequest) {
body = await this.createGraphQlBody(variableLines, contentTypeHeader, body);
} else if (this.settings.formParamEncodingStrategy !== FormParamEncodingStrategy.Never && typeof body === 'string' && MimeUtility.isFormUrlEncoded(contentTypeHeader)) {
if (this.settings.formParamEncodingStrategy === FormParamEncodingStrategy.Always) {
const stringPairs = body.split('&');
const encodedStringPairs: string[] = [];
for (const stringPair of stringPairs) {
const [name, ...values] = stringPair.split('=');
const value = values.join('=');
encodedStringPairs.push(`${encodeURIComponent(name)}=${encodeURIComponent(value)}`);
}
body = encodedStringPairs.join('&');
} else {
body = encodeurl(body);
}
}
// if Host header provided and url is relative path, change to absolute url
const host = getHeader(headers, 'Host');
if (host && requestLine.url[0] === '/') {
const [, port] = host.toString().split(':');
const scheme = port === '443' || port === '8443' ? 'https' : 'http';
requestLine.url = `${scheme}://${host}${requestLine.url}`;
}
return new HttpRequest(requestLine.method, requestLine.url, headers, body, bodyLines.join(EOL), name);
}
private async createGraphQlBody(variableLines: string[], contentTypeHeader: string | undefined, body: string | Stream | undefined) {
let variables = await this.parseBody(variableLines, contentTypeHeader);
if (variables && typeof variables !== 'string') {
variables = await convertStreamToString(variables);
}
if (body && typeof body !== 'string') {
body = await convertStreamToString(body);
}
const matched = body?.match(/^\s*query\s+([^@\{\(]+)/i);
const operationName = matched?.[1];
const graphQlPayload = {
query: body,
operationName,
variables: variables ? JSON.parse(variables) : {}
};
return JSON.stringify(graphQlPayload);
}
private parseRequestLine(line: string): { method: string, url: string } {
// Request-Line = Method SP Request-URI SP HTTP-Version CRLF
let method: string;
let url: string;
let match: RegExpExecArray | null;
if (match = /^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|CONNECT|TRACE)\s+/i.exec(line)) {
method = match[1];
url = line.substr(match[0].length);
} else {
// Only provides request url
method = this.defaultMethod;
url = line;
}
url = url.trim();
if (match = /\s+HTTP\/.*$/i.exec(url)) {
url = url.substr(0, match.index);
}
return { method, url };
}
private async parseBody(lines: string[], contentTypeHeader: string | undefined): Promise<string | Stream | undefined> {
if (lines.length === 0) {
return undefined;
}
// Check if needed to upload file
if (lines.every(line => !this.inputFileSyntax.test(line))) {
if (MimeUtility.isFormUrlEncoded(contentTypeHeader)) {
return lines.reduce((p, c, i) => {
p += `${(i === 0 || c.startsWith('&') ? '' : EOL)}${c}`;
return p;
}, '');
} else {
const lineEnding = this.getLineEnding(contentTypeHeader);
let result = lines.join(lineEnding);
if (MimeUtility.isNewlineDelimitedJSON(contentTypeHeader)) {
result += lineEnding;
}
return result;
}
} else {
const combinedStream = CombinedStream.create({ maxDataSize: 10 * 1024 * 1024 });
for (const [index, line] of lines.entries()) {
if (this.inputFileSyntax.test(line)) {
const groups = this.inputFileSyntax.exec(line);
const groupsValues = groups?.groups;
if (groups?.length === 4 && !!groupsValues) {
const inputFilePath = groupsValues.filepath;
const fileAbsolutePath = await resolveRequestBodyPath(inputFilePath);
if (fileAbsolutePath) {
if (groupsValues.processVariables) {
const buffer = await fs.readFile(fileAbsolutePath);
const fileContent = buffer.toString(groupsValues.encoding || this.defaultFileEncoding);
const resolvedContent = await VariableProcessor.processRawRequest(fileContent);
combinedStream.append(resolvedContent);
} else {
combinedStream.append(fs.createReadStream(fileAbsolutePath));
}
} else {
combinedStream.append(line);
}
}
} else {
combinedStream.append(line);
}
if (index !== lines.length - 1) {
combinedStream.append(this.getLineEnding(contentTypeHeader));
}
}
return combinedStream;
}
}
private getLineEnding(contentTypeHeader: string | undefined) {
return MimeUtility.isMultiPartFormData(contentTypeHeader) ? '\r\n' : EOL;
}
}