-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathproxy.ts
More file actions
328 lines (295 loc) · 9.62 KB
/
proxy.ts
File metadata and controls
328 lines (295 loc) · 9.62 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { IContext, OnRequestDataCallback } from 'http-mitm-proxy';
import {
MockConfig,
HttpHeader,
JsonPathReplacer,
RegExpReplacer,
UpdateBodySpec,
UrlPattern,
} from '../types';
import _ from 'lodash';
import getPort from 'get-port';
import { Proxy, ProxyOptions } from '../proxy';
import ip from 'ip';
import os from 'os';
import path from 'path';
import fs from 'fs-extra';
import { minimatch } from 'minimatch';
import http from 'http';
import jsonpath from 'jsonpath';
import regexParser from 'regex-parser';
import { validateMockConfig } from '../schema';
import log from '../logger';
export function constructURLFromHttpRequest(request: {
protocol: string;
path: string;
host: string;
}) {
const urlString = `${request.protocol}${request?.host}${request.path}`;
return new URL(urlString);
}
export function modifyRequestUrl(ctx: IContext, mockConfig: MockConfig) {
if (!mockConfig.updateUrl || !ctx.clientToProxyRequest || !ctx.proxyToServerRequestOptions) {
return;
}
const { headers, url } = ctx.clientToProxyRequest;
const protocol = ctx.isSSL ? 'https://' : 'http://';
const originalUrl = constructURLFromHttpRequest({
host: headers.host!,
path: url!,
protocol,
});
const updateUrlMatchers = _.castArray(mockConfig.updateUrl);
const updatedUrlString = updateUrlMatchers.reduce((current, matcher) => {
return current.replace(parseRegex(matcher.regexp as string), matcher.value);
}, originalUrl.toString());
const updatedUrl = new URL(updatedUrlString);
ctx.proxyToServerRequestOptions.host = updatedUrl.hostname;
ctx.proxyToServerRequestOptions.path = `${updatedUrl.pathname}${updatedUrl.search}`;
ctx.proxyToServerRequestOptions.port = updatedUrl.port || ctx.proxyToServerRequestOptions.port;
ctx.proxyToServerRequestOptions.headers.host= updatedUrl.hostname;
}
export function modifyRequestHeaders(ctx: IContext, mockConfig: MockConfig) {
if (!mockConfig.headers || !ctx.proxyToServerRequestOptions) {
return;
}
const { headers } = ctx.proxyToServerRequestOptions;
if (mockConfig.headers?.add) {
Object.assign(headers, mockConfig.headers.add);
}
if (mockConfig.headers?.remove && Array.isArray(mockConfig.headers?.remove)) {
mockConfig.headers.remove.forEach((header: string) => delete headers[header]);
}
}
export function modifyRequestBody(ctx: IContext, mockConfig: MockConfig) {
const requestBodyChunks: Buffer[] = [];
ctx.onRequestData((ctx: IContext, chunk: Buffer, callback: OnRequestDataCallback) => {
requestBodyChunks.push(chunk);
callback(null, undefined);
});
ctx.onRequestEnd((ctx: IContext, callback: OnRequestDataCallback) => {
const originalBody = Buffer.concat(requestBodyChunks).toString('utf-8');
let postBody = mockConfig.requestBody || originalBody;
if (mockConfig.updateRequestBody) {
postBody = processBody(mockConfig.updateRequestBody, originalBody);
}
ctx.proxyToServerRequest?.setHeader('Content-Length', Buffer.byteLength(postBody));
ctx.proxyToServerRequest?.write(postBody);
callback();
});
}
export function modifyResponseBody(ctx: IContext, mockConfig: MockConfig) {
const responseBodyChunks: Buffer[] = [];
ctx.onResponseData((ctx: IContext, chunk: Buffer, callback: OnRequestDataCallback) => {
responseBodyChunks.push(chunk);
return callback(null, undefined);
});
ctx.onResponseEnd((ctx: IContext, callback: OnRequestDataCallback) => {
const originalResponse = Buffer.concat(responseBodyChunks).toString('utf8');
let responseBody = mockConfig.responseBody || originalResponse;
if (mockConfig.statusCode) {
ctx.proxyToClientResponse.writeHead(mockConfig.statusCode);
}
if (mockConfig.updateResponseBody) {
responseBody = processBody(mockConfig.updateResponseBody, responseBody);
}
ctx.proxyToClientResponse.write(responseBody);
callback(null);
});
}
export async function setupProxyServer(
sessionId: string,
deviceUDID: string,
isRealDevice: boolean,
certDirectory: string,
currentWifiProxyConfig?: ProxyOptions,
whitelistedDomains?: string[],
blacklistedDomains?: string[],
upstreamProxy?: string | null,
) {
const certificatePath = prepareCertificate(sessionId, certDirectory);
const port = await getPort();
const _ip = isRealDevice ? 'localhost' : ip.address('public', 'ipv4');
const proxy = new Proxy({
deviceUDID,
sessionId,
certificatePath,
port,
ip: _ip,
previousConfig: currentWifiProxyConfig,
whitelistedDomains,
blacklistedDomains,
upstreamProxy: upstreamProxy ?? null,
});
await proxy.start();
if (!proxy.isStarted()) {
throw new Error('Unable to start the proxy server');
}
return proxy;
}
export async function cleanUpProxyServer(proxy: Proxy) {
await proxy.stop();
// @ts-ignore
fs.rmdirSync(proxy.certificatePath, { recursive: true, force: true });
}
function prepareCertificate(sessionId: string, certDirectory: string) {
const sessionCertDirectory = path.join(os.tmpdir(), sessionId);
if(!fs.existsSync(certDirectory)){
throw new Error(`Error certDirectory doesn't exist (${certDirectory})`);
}
fs.copySync(certDirectory, sessionCertDirectory);
return sessionCertDirectory;
}
export function parseRegex(matcherString: string) {
try {
return regexParser(matcherString);
} catch (err) {
return matcherString;
}
}
export function addDefaultMocks(proxy: Proxy) {
// proxy.addMock({
// url: '**/reqres.in/api/**',
// statusCode: 400,
// });
// proxy.addMock({
// url: '**/api/login',
// method: 'post',
// updateRequestBody: [
// {
// jsonPath: '$.email',
// value: 'invalidemail@reqres.in',
// },
// ],
// });
// proxy.addMock({
// // url: '**/api/users*?*',
// // url: '/api/users?.*',
// // updateUrl: [
// // {
// // regexp: '/page=(\\d)+/g',
// // value: 'page=2',
// // },
// // ],
// // updateResponseBody: [
// // {
// // jsonPath: '$.data[?(/michael.*/.test(@.email))].first_name',
// // value: 'sudharsan',
// // },
// // {
// // jsonPath: '$.data[?(/michael.*/.test(@.email))].last_name',
// // value: 'selvaraj',
// // },
// // ],
// });
// proxy.addMock({
// url: '/appiumproxy.io/g',
// responseBody: MOCK_BACKEND_HTML,
// statusCode: 200,
// });
}
export function parseJson(obj: any) {
try {
return JSON.parse(obj);
} catch (err) {
return obj;
}
}
export function doesUrlMatch(pattern: UrlPattern, url: string) {
let jsonOrStringUrl = parseRegex(pattern);
try {
return jsonOrStringUrl instanceof RegExp
? jsonOrStringUrl.test(url)
: minimatch(url, jsonOrStringUrl);
} catch (err) {
log.error(`Error validating url ${pattern} against url ${url}`);
return false;
}
}
export function doesHttpMethodMatch(request: http.IncomingMessage, method: string | undefined) {
if (!method) {
return true;
}
return request.method && request.method.toLowerCase() == method.toLowerCase();
}
export function compileMockConfig(mocks: Array<MockConfig>) {
const compiledMock: MockConfig = {
url: '',
updateUrl: [],
headers: {
add: {},
remove: [],
},
responseHeaders: {
add: {},
remove: [],
},
updateRequestBody: [],
updateResponseBody: [],
};
mocks.reduce((finalMock, mock) => {
return _.mergeWith(finalMock, mock, (objValue, srcValue) => {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
});
}, compiledMock);
return compiledMock;
}
export function updateUsingJsonPath(spec: JsonPathReplacer, body: string) {
const parsedBody = parseJson(body);
if (typeof parsedBody !== 'object') {
return body;
}
const { jsonPath: path, value } = spec;
jsonpath.apply(parsedBody, path, (val) => value);
return JSON.stringify(parsedBody);
}
export function updateUsingRegExp(spec: RegExpReplacer, body: string) {
const { regexp, value } = spec;
return body.replace(new RegExp(regexp), value);
}
export function processBody(spec: UpdateBodySpec[], body: string) {
return spec.reduce((body: string, spec: UpdateBodySpec) => {
if (_.has(spec, 'jsonPath')) {
return updateUsingJsonPath(spec as JsonPathReplacer, body);
} else if (_.has(spec, 'regexp')) {
return updateUsingRegExp(spec as RegExpReplacer, body);
}
return body;
}, body);
}
function parseHeaderConfig(header?: HttpHeader) {
const parsedHeader = typeof header === 'string' ? parseJson(header) : header;
if (!parsedHeader || typeof parsedHeader !== 'object') return { add: {}, remove: [] };
return {
add: parsedHeader?.add ? parsedHeader.add : parsedHeader,
remove: parsedHeader?.remove ?? [],
};
}
export function sanitizeMockConfig(config: MockConfig) {
const isValid = validateMockConfig(config);
if (!isValid) {
throw new Error('Invalid config provided for api mock');
}
config.headers = parseHeaderConfig(config.headers);
config.responseHeaders = parseHeaderConfig(config.responseHeaders);
/* Validate if the config has corrent RegExp */
const pathsToValidate = [
'$.updateUrl[*].regexp',
'$.updateRequestBody[*].regexp',
'$.updateResponseBody[*].regexp',
];
for (const regexNodePath of pathsToValidate) {
const regexElements: string[] = jsonpath.query(config, regexNodePath);
regexElements.forEach((regexp) => {
if (typeof regexp !== 'string' || !(parseRegex(regexp) instanceof RegExp)) {
throw new Error(`Invalid Regular expression ${regexp} for field ${regexNodePath}`);
}
});
}
return config;
}
export function sleep(timeMs: number) {
return new Promise((resolve) => setTimeout(resolve, timeMs));
}