-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
93 lines (78 loc) · 2.5 KB
/
Copy pathproxy.js
File metadata and controls
93 lines (78 loc) · 2.5 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
const path = require('path');
const { execSync } = require('child_process');
const { readFileSync } = require('fs');
const hoxy = require('hoxy');
const rootCAFolder = execSync('mkcert -CAROOT').toString('utf-8').trim();
const certLocation = path.join(rootCAFolder, 'rootCA.pem');
const keyLocation = path.join(rootCAFolder, 'rootCA-key.pem');
console.info(`Expecting root CA Cert in '${certLocation}' and Key in '${keyLocation}'.`);
const certAuthority = {
cert: readFileSync(certLocation),
key: readFileSync(keyLocation),
};
console.info('Root CA loaded successfully!');
const debug = process.env.FAKE_PROXY_DEBUG === 'true';
const port = process.env.FAKE_PROXY_PORT || 5000;
const throttlingMs = parseInt(process.env.FAKE_PROXY_THROTTLE_MS, 10) || 0;
const config = { certAuthority };
if(throttlingMs > 0){
console.info(`Slowing down the proxy by ${throttlingMs}ms per request.`);
config.slow = { latency: throttlingMs };
}
const proxy = hoxy.createServer(config).listen(port, () => console.info(`The proxy is listening on port ${port}.`));
proxy.log('error warn', process.stderr);
proxy.log('info', process.stdout);
const parseBody = req => {
let body = null;
if(req.buffer?.length){
const bodyAsStr = req.buffer.toString();
try {
body = JSON.parse(bodyAsStr);
} catch {
body = bodyAsStr;
}
return body;
}
if(req.json){
body = req.json;
return body;
}
if(req.params){
body = req.params;
return body;
}
if(req.string){
body = req.string;
return body;
}
return body;
};
proxy.intercept(
{
phase: 'request',
as: 'buffer'
},
req => console.info(
`Forwarding ${req.method} request to ${req.fullUrl()}${
debug ?
`\nHeaders: ${JSON.stringify(req.headers)}\nQuery: ${JSON.stringify(req.query)}\nBody: ${JSON.stringify(parseBody(req))}` :
''
}`
)
);
proxy.intercept(
{
phase: 'response',
as: 'buffer'
},
(req, res) => console.info(
`Received HTTP ${res.statusCode} from ${req.fullUrl()}${
debug ?
`\nBody: ${JSON.stringify(parseBody(res))}` :
''
}`
)
);
// We do not want to throw here because the proxy should continue to run even though it met an error
proxy.on('error', err => console.error('Error detected!', err));
process.on('uncaughtException', err => console.error('Uncaught Exception detected!', err));