-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproxy.js
More file actions
236 lines (204 loc) · 7.01 KB
/
Copy pathproxy.js
File metadata and controls
236 lines (204 loc) · 7.01 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
const fs = require('fs');
const http = require('http');
const path = require('path');
const Url = require('url');
const httpProxy = require('http-proxy');
const Meta = require('@mutable/meta');
const tooBusy = require('toobusy-js');
const Routes = require('./routes');
const { IsObject, DebugPrint, IsIP } = require('./utils');
const defaultPage404 = fs.readFileSync(path.join(__dirname, '../static/404.html')).toString();
const defaultPage401 = fs.readFileSync(path.join(__dirname, '../static/401.html')).toString();
function TimeTrack(req, label) {
if (
req.headers.timetrack
&& (req.headers.timetrack === '*' || req.headers.timetrack === req.url)
) {
if (!req.startTime) req.startTime = Date.now();
if (!req.startTimeRandom) req.startTimeRandom = Math.floor(Math.random() * (1000000 + 1));
console.log(
`TimeTrack :: ${label} :: http://${req.headers.host}${req.url} ${req.startTime}-${
req.startTimeRandom
} ${Date.now() - req.startTime}`,
);
}
}
function SendWeb(res, content, code) {
if (!res.headersSent) {
if (typeof code === 'number') res.writeHead(code);
res.end(content);
}
}
function ReplaceServerUrl(host, protocol) {
const url = Url.parse(host.target);
DebugPrint('_replaceServerUrl', url.hostname);
if (url.hostname.indexOf('.') > -1) {
return Promise.resolve(host);
}
return Meta.service(url.hostname).then(
(service) => {
if (protocol) url.protocol = protocol;
url.host = service[(Math.random() * service.length) | 0];
host.target = service.length ? Url.format(url) : host.target;
DebugPrint('_replaceServerUrlSuccess', host);
return host;
},
() => host,
);
}
function RoutePage500(res, err) {
SendWeb(res, err || 'Something seems to be wrong', 500);
}
function HasEncryptedConnection(req) {
return req.connection.encrypted || req.connection.pair;
}
function GetPort(req) {
const res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
if (res) {
return res[1];
}
return HasEncryptedConnection(req) ? '443' : '80';
}
function SetXHeaders(req) {
req.headers['x-forwarded-for'] = req.connection.remoteAddress;
req.headers['x-forwarded-host'] = req.headers.host;
req.headers['x-forwarded-port'] = GetPort(req);
req.headers['x-forwarded-proto'] = req.isSpdy || HasEncryptedConnection(req) ? 'https' : 'http';
}
class Proxy {
constructor(config, checkAuth) {
if (checkAuth && typeof checkAuth === 'function') this._checkAuth = checkAuth;
if (config) this.config = config;
this._proxy = httpProxy.createProxyServer({ ws: true, xfwd: false });
this._proxy.on('error', (err, req, res) => this._onError(err, req, res));
this._proxy.on('proxyRes', (proxyRes, req) => TimeTrack(req, '_onProxyRes'));
this._routes = new Routes(config);
if (config) this.updateConfig(config);
this.startProxy();
}
updateConfig(config) {
this._page404 = config.page404 || defaultPage404;
this._page401 = config.page401 || defaultPage401;
this._routes.updateConfig(config);
}
startProxy() {
const port = process.env.PORT || 80;
this._serverHttp = http.createServer(this._proxyingWeb.bind(this));
this._serverHttp.on('upgrade', this._proxyingWebSockets.bind(this));
this._serverHttp.listen(port);
console.log(`listen on port ${port}`);
return this._serverHttp;
}
_proxyingWeb(req, res) {
if (!this._isLocal(req, res)) {
DebugPrint('_proxyingWeb', req.headers.host + req.url);
TimeTrack(req, '_proxyingWeb');
this._routes
.getTarget(`http://${req.headers.host}${req.url}`, req.headers)
.then(host => ReplaceServerUrl(host), () => this._routePage404(res))
.done(host => this._proxyWeb(req, res, host));
}
}
_proxyingWebSockets(req, res, socket, head) {
if (!this._isLocal(req, res)) {
this._routes
.getTarget(`http://${req.headers.host}${req.url}`, req.headers)
.then(host => ReplaceServerUrl(host), () => this._routePage404(res))
.done(host => this._proxyWebSockets(req, socket, head, host));
}
}
async _proxyWebSockets(req, socket, head, opt, cb) {
const url = Url.parse(opt.target);
req.url = url.path;
opt.target = Url.format({ protocol: url.protocol, host: url.host });
DebugPrint('_proxyWebSockets', opt.target + req.url);
if (this._checkAuth) {
try {
await this._checkAuth(req, opt, this.config);
} catch (e) {
DebugPrint('_proxyWebSockets', e);
}
}
try {
SetXHeaders(req);
if (opt.changeHost) req.headers.host = url.host;
DebugPrint('headers', req.headers);
return this._proxy.ws(req, socket, head, opt, (err) => {
if (err && err.code && err.code === 'ECONNREFUSED' && typeof cb === 'function') cb();
});
} catch (e) {
console.error('error:: _proxyWebSockets: ', e);
return e;
}
}
async _proxyWeb(req, res, opt) {
if (!IsObject(opt)) return this._checkRoutes(req, res);
const url = Url.parse(opt.target);
req.headers.host = req.headers.host || '';
req.url = url.path;
url.pathname = '';
opt.target = Url.format({ protocol: url.protocol, host: url.host });
DebugPrint('_proxyWeb', opt.target + req.url);
if (opt.redirect) {
res.writeHead(opt.statusCode || 302, {
location: Url.resolve(opt.target, req.url),
});
res.end();
} else if (opt.content) {
SendWeb(res, opt.content, opt.statusCode || 200);
} else {
if (this._checkAuth) {
try {
await this._checkAuth(req, opt, this.config);
} catch (e) {
DebugPrint('_proxyWeb', e);
this._routePage401(res);
}
}
try {
SetXHeaders(req);
if (opt.changeHost) req.headers.host = url.host;
DebugPrint('headers', req.headers);
TimeTrack(req, '_proxyWeb');
this._proxy.web(req, res, opt);
} catch (e) {
TimeTrack(req, '_proxyWeb catch');
this._routePage404(res);
}
}
return res;
}
_routePage404(res) {
SendWeb(res, this._page404 || '404', 404);
}
_routePage401(res) {
SendWeb(res, this._page401 || '401', 401);
}
_onError(err, req, res) {
TimeTrack(req, '_onError');
if (!err || !err.code) return RoutePage500(res);
if (err.code === 'ECONNREFUSED') return RoutePage500(res, 'Error with ECONNREFUSED');
return this._routePage404(res);
}
_checkRoutes(req, res) {
const theUrlis = Url.parse(`http://${req.headers.host}${req.url}`);
switch (theUrlis.pathname) {
case '/health':
res.end(`${tooBusy.lag()}`);
break;
default:
this._routePage404(res);
}
}
_isLocal(req, res) {
if (
req.headers.host === `${process.env.MYIP}:${process.env.PORT}`
|| (!IsIP.test(req.headers.host)
&& req.headers.host !== `${process.env.MYHOST || 'localhost'}:${process.env.PORT}`
&& req.headers.host !== `${process.env.HOSTNAME || ''}:${process.env.PORT}`)
) return false;
this._checkRoutes(req, res);
return true;
}
}
module.exports = Proxy;