bdy 1.7.46-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/.eslintrc.yml +23 -0
  2. package/LICENSE +21 -0
  3. package/bin/cli.js +5 -0
  4. package/dockerfile +15 -0
  5. package/link.sh +3 -0
  6. package/package.json +39 -0
  7. package/src/agent/linux.js +127 -0
  8. package/src/agent/manager.js +404 -0
  9. package/src/agent/osx.js +150 -0
  10. package/src/agent/socket/tunnel.js +232 -0
  11. package/src/agent/socket.js +260 -0
  12. package/src/agent/system.js +205 -0
  13. package/src/agent/wait.js +20 -0
  14. package/src/agent/windows.js +168 -0
  15. package/src/agent.js +248 -0
  16. package/src/api/agent.js +95 -0
  17. package/src/api/buddy.js +131 -0
  18. package/src/api/socket.js +142 -0
  19. package/src/cfg.js +228 -0
  20. package/src/command/agent/disable.js +37 -0
  21. package/src/command/agent/enable.js +117 -0
  22. package/src/command/agent/restart.js +28 -0
  23. package/src/command/agent/run.js +16 -0
  24. package/src/command/agent/start.js +28 -0
  25. package/src/command/agent/status.js +45 -0
  26. package/src/command/agent/stop.js +28 -0
  27. package/src/command/agent/tunnel/http.js +47 -0
  28. package/src/command/agent/tunnel/list.js +27 -0
  29. package/src/command/agent/tunnel/start.js +38 -0
  30. package/src/command/agent/tunnel/status.js +32 -0
  31. package/src/command/agent/tunnel/stop.js +30 -0
  32. package/src/command/agent/tunnel/tcp.js +47 -0
  33. package/src/command/agent/tunnel/tls.js +47 -0
  34. package/src/command/agent/tunnel.js +21 -0
  35. package/src/command/agent/update.js +43 -0
  36. package/src/command/agent/version.js +23 -0
  37. package/src/command/agent.js +27 -0
  38. package/src/command/config/add/http.js +33 -0
  39. package/src/command/config/add/tcp.js +33 -0
  40. package/src/command/config/add/tls.js +33 -0
  41. package/src/command/config/add.js +13 -0
  42. package/src/command/config/get/region.js +13 -0
  43. package/src/command/config/get/timeout.js +13 -0
  44. package/src/command/config/get/token.js +13 -0
  45. package/src/command/config/get/tunnel.js +21 -0
  46. package/src/command/config/get/tunnels.js +13 -0
  47. package/src/command/config/get/whitelist.js +13 -0
  48. package/src/command/config/get.js +19 -0
  49. package/src/command/config/remove/tunnel.js +22 -0
  50. package/src/command/config/remove.js +9 -0
  51. package/src/command/config/set/region.js +19 -0
  52. package/src/command/config/set/timeout.js +22 -0
  53. package/src/command/config/set/token.js +18 -0
  54. package/src/command/config/set/whitelist.js +19 -0
  55. package/src/command/config/set.js +15 -0
  56. package/src/command/config.js +15 -0
  57. package/src/command/http.js +34 -0
  58. package/src/command/pre.js +47 -0
  59. package/src/command/start.js +31 -0
  60. package/src/command/tcp.js +32 -0
  61. package/src/command/tls.js +32 -0
  62. package/src/command/version.js +10 -0
  63. package/src/format.js +171 -0
  64. package/src/index.js +32 -0
  65. package/src/input.js +283 -0
  66. package/src/logger.js +87 -0
  67. package/src/output/interactive/tunnel.js +871 -0
  68. package/src/output/noninteractive/agent/tunnels.js +32 -0
  69. package/src/output/noninteractive/config/tunnel.js +52 -0
  70. package/src/output/noninteractive/config/tunnels.js +19 -0
  71. package/src/output/noninteractive/tunnel.js +79 -0
  72. package/src/output.js +136 -0
  73. package/src/server/cert.js +51 -0
  74. package/src/server/http1.js +79 -0
  75. package/src/server/http2.js +79 -0
  76. package/src/server/sftp.js +474 -0
  77. package/src/server/ssh.js +107 -0
  78. package/src/server/tls.js +41 -0
  79. package/src/ssh/client.js +196 -0
  80. package/src/texts.js +447 -0
  81. package/src/tunnel/agent.js +100 -0
  82. package/src/tunnel/compression.js +32 -0
  83. package/src/tunnel/dns.js +55 -0
  84. package/src/tunnel/html/404.html +129 -0
  85. package/src/tunnel/html/503.html +136 -0
  86. package/src/tunnel/html.js +32 -0
  87. package/src/tunnel/http/log.js +204 -0
  88. package/src/tunnel/http/serve.js +127 -0
  89. package/src/tunnel/http/stream.js +46 -0
  90. package/src/tunnel/http.js +406 -0
  91. package/src/tunnel/identification.js +95 -0
  92. package/src/tunnel/latency.js +63 -0
  93. package/src/tunnel/tcp.js +71 -0
  94. package/src/tunnel.js +696 -0
  95. package/src/utils.js +496 -0
  96. package/unlink.sh +3 -0
@@ -0,0 +1,46 @@
1
+ const { Transform } = require('stream');
2
+
3
+ class TunnelHttpStream extends Transform {
4
+ constructor(maxSize) {
5
+ super();
6
+ this.maxSize = maxSize;
7
+ this.data = Buffer.alloc(0);
8
+ this.realLength = 0;
9
+ this.tooLarge = false;
10
+ this.backPressure = [];
11
+ }
12
+
13
+ _transform(chunk, encoding, callback) {
14
+ if (!this.tooLarge) {
15
+ if (this.data.length + chunk.length > this.maxSize) {
16
+ this.tooLarge = true;
17
+ this.data = Buffer.alloc(0);
18
+ } else {
19
+ this.data = Buffer.concat([this.data, chunk]);
20
+ }
21
+ }
22
+ this.realLength += chunk.length;
23
+ this.backPressure.push(chunk);
24
+ this._pushBackPressure();
25
+ callback();
26
+ }
27
+
28
+ _pushBackPressure() {
29
+ while(this.backPressure.length > 0) {
30
+ const chunk = this.backPressure.shift();
31
+ if (!this.push(chunk)) {
32
+ this.once('drain', () => {
33
+ this._pushBackPressure();
34
+ });
35
+ break;
36
+ }
37
+ }
38
+ }
39
+
40
+ pipeToNothing(done) {
41
+ this.once('end', done);
42
+ this.resume();
43
+ }
44
+ }
45
+
46
+ module.exports = TunnelHttpStream;
@@ -0,0 +1,406 @@
1
+ const EventEmitter = require('events');
2
+ const { v4 } = require('uuid');
3
+ const http = require('http');
4
+ const {
5
+ DEFAULT_TIMEOUT,
6
+ getRealTargetHost
7
+ } = require('../utils.js');
8
+ const TunnelAgent = require('./agent.js');
9
+ const url = require('url');
10
+ const TunnelHtml = require('./html.js');
11
+ const TunnelCompression = require('./compression.js');
12
+ const https = require('https');
13
+ const TunnelHttpServe = require('./http/serve.js');
14
+ const logger = require('../logger.js');
15
+ const { LOG_ERROR } = require('../texts.js');
16
+ const stream = require('stream');
17
+ const {
18
+ TUNNEL_IDENTIFIED_HTTP1,
19
+ TUNNEL_IDENTIFIED_HTTP2,
20
+ TUNNEL_COMPRESSION_METHOD_IDENTITY
21
+ } = require('../utils');
22
+
23
+ class TunnelHttp extends EventEmitter {
24
+ constructor({
25
+ req,
26
+ res,
27
+ proto,
28
+ host,
29
+ port,
30
+ hostHeader,
31
+ serve,
32
+ timeout,
33
+ httpIdentify,
34
+ verify,
35
+ httpLog,
36
+ compression,
37
+ headers,
38
+ responseHeaders,
39
+ auth = null,
40
+ }) {
41
+ super();
42
+ this.id = v4();
43
+ this.host = host;
44
+ this.port = port;
45
+ this.proto = proto;
46
+ this.auth = auth;
47
+ this.req = req;
48
+ this.res = res;
49
+ this.hostHeader = hostHeader;
50
+ this.timeout = timeout || DEFAULT_TIMEOUT;
51
+ this.httpIdentify = httpIdentify;
52
+ this.verify = verify;
53
+ this.compression = compression;
54
+ this.headers = {};
55
+ this.responseHeaders = {};
56
+ this.serve = serve;
57
+ if (responseHeaders) {
58
+ responseHeaders.forEach((header) => {
59
+ this.responseHeaders[header.name.toLowerCase()] = header.value;
60
+ });
61
+ }
62
+ if (headers) {
63
+ headers.forEach((header) => {
64
+ this.headers[header.name.toLowerCase()] = header.value;
65
+ });
66
+ }
67
+ this.httpLog = httpLog;
68
+ this.logRequest = null;
69
+ }
70
+
71
+ outputEnd(code, html) {
72
+ try {
73
+ if (this.logRequest) {
74
+ const s = new stream.Readable();
75
+ s.push(html);
76
+ s.push(null);
77
+ s.pipe(this.logRequest.responseBody);
78
+ }
79
+ this.httpLog.newResponse(this.req, code, {}, this.logRequest);
80
+ this.res.statusCode = code;
81
+ this.res.end(html);
82
+ } catch (err) {
83
+ // do nothing
84
+ }
85
+ this.clear();
86
+ }
87
+
88
+ getDisplayTarget() {
89
+ let t = `${this.proto}://${this.host}`;
90
+ if (this.proto === 'http' && this.port !== 80) t += `:${this.port}`;
91
+ else if (this.proto === 'https' && this.port !== 443) t += `:${this.port}`;
92
+ return t;
93
+ }
94
+
95
+ output503() {
96
+ this.outputEnd(503, TunnelHtml.get503(this.getDisplayTarget()));
97
+ }
98
+
99
+ outputHeaders(statusCode, headers) {
100
+ this.res.statusCode = statusCode;
101
+ Object.keys(headers).forEach((name) => {
102
+ this.res.setHeader(name.toLowerCase(), headers[name]);
103
+ });
104
+ Object.keys(this.responseHeaders).forEach((name) => {
105
+ this.res.setHeader(name.toLowerCase(), this.responseHeaders[name]);
106
+ });
107
+ }
108
+
109
+ getHostHeader() {
110
+ if (this.hostHeader) return this.hostHeader;
111
+ let h = this.host;
112
+ if (this.proto === 'http' && this.port !== 80) h += `:${this.port}`;
113
+ else if (this.proto === 'https' && this.port !== 443) h += `:${this.port}`;
114
+ return h;
115
+ }
116
+
117
+ getRequestHeaders(http2) {
118
+ const h = {};
119
+ let ip;
120
+ if (this.req.httpVersion === '2.0') {
121
+ ip = this.req.socket.stream ? this.req.socket.stream.remoteAddress : '::1';
122
+ } else {
123
+ ip = this.req.socket.remoteAddress;
124
+ }
125
+ if (http2) {
126
+ h[':scheme'] = this.proto;
127
+ h[':authority'] = this.getHostHeader();
128
+ h[':method'] = this.getMethod();
129
+ h[':path'] = this.getPath();
130
+ } else {
131
+ h.host = this.getHostHeader();
132
+ }
133
+ h['x-forwarded-for'] = ip || '0.0.0.0';
134
+ h['x-forwarded-proto'] = 'https';
135
+ if (this.auth) {
136
+ h['authorization'] = `Basic ${Buffer.from(this.auth).toString('base64')}`;
137
+ }
138
+ return h;
139
+ }
140
+
141
+ getClearedHeaders(headers = {}, compressionMethod) {
142
+ const hop = [
143
+ ':method',
144
+ ':path',
145
+ ':scheme',
146
+ ':authority',
147
+ ':status',
148
+ 'keep-alive',
149
+ 'host',
150
+ 'connection',
151
+ 'proxy-authenticate',
152
+ 'proxy-connection',
153
+ 'Proxy-authorization',
154
+ 'trailer',
155
+ 'upgrade',
156
+ 'transfer-encoding',
157
+ 'strict-transport-security',
158
+ 'te'
159
+ ];
160
+ const tmp = {};
161
+ if (compressionMethod && compressionMethod !== TUNNEL_COMPRESSION_METHOD_IDENTITY) {
162
+ tmp['content-encoding'] = compressionMethod;
163
+ hop.push('content-length');
164
+ hop.push('content-encoding');
165
+ }
166
+ Object.keys(headers).forEach((name) => {
167
+ if (!hop.includes(name)) {
168
+ tmp[name] = headers[name];
169
+ }
170
+ });
171
+ return tmp;
172
+ }
173
+
174
+ getPath() {
175
+ const {
176
+ pathname,
177
+ search,
178
+ } = url.parse(this.req.url);
179
+ let path = pathname;
180
+ if (search) path += search;
181
+ return path;
182
+ }
183
+
184
+ getMethod() {
185
+ return this.req.method;
186
+ }
187
+
188
+ createRequestHttp1() {
189
+ const reqHeaders = this.req.headers;
190
+ const method = this.getMethod();
191
+ const path = this.getPath();
192
+ const headers = {
193
+ ...this.getClearedHeaders(reqHeaders),
194
+ ...this.headers,
195
+ ...this.getRequestHeaders(false)
196
+ };
197
+ const r = http.request({
198
+ agent: TunnelAgent.getHttp1(),
199
+ host: getRealTargetHost(this.host),
200
+ port: this.port,
201
+ method,
202
+ protocol: 'http:',
203
+ setHost: false,
204
+ path,
205
+ headers
206
+ });
207
+ this.logRequest = this.httpLog.newRequest(method, headers, path, TUNNEL_IDENTIFIED_HTTP1, this.req);
208
+ r.on('response', (proxyRes) => {
209
+ this.proxyRes = proxyRes;
210
+ const statusCode = this.proxyRes.statusCode;
211
+ const resHeaders = this.proxyRes.headers;
212
+ const compressionMethod = TunnelCompression.detect(this.compression, reqHeaders, resHeaders);
213
+ this.outputHeaders(statusCode, this.getClearedHeaders(resHeaders, compressionMethod));
214
+ if (this.logRequest) {
215
+ this.proxyRes.pipe(this.logRequest.responseBody).pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
216
+ } else {
217
+ this.proxyRes.pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
218
+ }
219
+ this.httpLog.newResponse(this.req, statusCode, resHeaders, this.logRequest);
220
+ });
221
+ return r;
222
+ }
223
+
224
+ createRequestHttps1() {
225
+ const reqHeaders = this.req.headers;
226
+ const method = this.getMethod();
227
+ const headers = {
228
+ ...this.getClearedHeaders(reqHeaders),
229
+ ...this.headers,
230
+ ...this.getRequestHeaders(false)
231
+ };
232
+ const path = this.getPath();
233
+ const r = https.request({
234
+ agent: TunnelAgent.getHttps1(),
235
+ host: getRealTargetHost(this.host),
236
+ port: this.port,
237
+ method,
238
+ protocol: 'https:',
239
+ setHost: false,
240
+ path,
241
+ rejectUnauthorized: this.verify,
242
+ headers
243
+ });
244
+ this.logRequest = this.httpLog.newRequest(method, headers, path, TUNNEL_IDENTIFIED_HTTP1, this.req);
245
+ r.on('response', (proxyRes) => {
246
+ this.proxyRes = proxyRes;
247
+ const statusCode = this.proxyRes.statusCode;
248
+ const resHeaders = this.proxyRes.headers;
249
+ const compressionMethod = TunnelCompression.detect(this.compression, reqHeaders, resHeaders);
250
+ this.outputHeaders(statusCode, this.getClearedHeaders(resHeaders, compressionMethod));
251
+ if (this.logRequest) {
252
+ this.proxyRes.pipe(this.logRequest.responseBody).pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
253
+ } else {
254
+ this.proxyRes.pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
255
+ }
256
+ this.httpLog.newResponse(this.req, statusCode, resHeaders, this.logRequest);
257
+ });
258
+ return r;
259
+ }
260
+
261
+ createServe() {
262
+ const reqHeaders = this.req.headers;
263
+ const r = new TunnelHttpServe(this.serve);
264
+ const method = this.getMethod();
265
+ const path = this.getPath();
266
+ this.logRequest = this.httpLog.newRequest(method, reqHeaders, path, TUNNEL_IDENTIFIED_HTTP1, this.req);
267
+ r.on('response', (statusCode, resHeaders, stream) => {
268
+ if (!stream) {
269
+ this.outputHeaders(statusCode, this.getClearedHeaders(resHeaders));
270
+ this.res.end();
271
+ } else {
272
+ const compressionMethod = TunnelCompression.detect(this.compression, reqHeaders, resHeaders);
273
+ this.outputHeaders(statusCode, this.getClearedHeaders(resHeaders, compressionMethod));
274
+ if (this.logRequest) {
275
+ stream.pipe(this.logRequest.responseBody).pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
276
+ } else {
277
+ stream.pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
278
+ }
279
+ }
280
+ this.httpLog.newResponse(this.req, statusCode, resHeaders, this.logRequest);
281
+ });
282
+ return r;
283
+ }
284
+
285
+ async createRequestHttps2() {
286
+ const reqHeaders = this.req.headers;
287
+ const authority = `${this.proto}://${getRealTargetHost(this.host)}:${this.port}`;
288
+ const client = await TunnelAgent.getHttp2Client(authority, this.host, this.verify);
289
+ const method = this.getMethod();
290
+ const path = this.getPath();
291
+ const headers = {
292
+ ...this.getClearedHeaders(reqHeaders),
293
+ ...this.headers,
294
+ ...this.getRequestHeaders(true)
295
+ };
296
+ const r = client.request(headers);
297
+ this.logRequest = this.httpLog.newRequest(method, headers, path, TUNNEL_IDENTIFIED_HTTP2, this.req);
298
+ r.on('response', (resHeaders) => {
299
+ const status = resHeaders[':status'] || 200;
300
+ const compressionMethod = TunnelCompression.detect(this.compression, reqHeaders, resHeaders);
301
+ this.outputHeaders(status, this.getClearedHeaders(resHeaders, compressionMethod));
302
+ if (this.logRequest) {
303
+ r.pipe(this.logRequest.responseBody).pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
304
+ } else {
305
+ r.pipe(TunnelCompression.compress(compressionMethod)).pipe(this.res);
306
+ }
307
+ this.httpLog.newResponse(this.req, status, resHeaders, this.logRequest);
308
+ });
309
+ return r;
310
+ }
311
+
312
+ async createRequest() {
313
+ if (this.httpIdentify === TUNNEL_IDENTIFIED_HTTP1) {
314
+ if (this.proto === 'http') return this.createRequestHttp1();
315
+ return this.createRequestHttps1();
316
+ }
317
+ return this.createRequestHttps2();
318
+ }
319
+
320
+ clear() {
321
+ if (this.req) {
322
+ this.req.removeAllListeners();
323
+ this.req = null;
324
+ }
325
+ if (this.res) {
326
+ this.res.removeAllListeners();
327
+ this.res = null;
328
+ }
329
+ if (this.proxyReq) {
330
+ this.proxyReq.removeAllListeners();
331
+ this.proxyReq = null;
332
+ }
333
+ if (this.proxyRes) {
334
+ this.proxyRes.removeAllListeners();
335
+ this.proxyRes = null;
336
+ }
337
+ if (this.httpLog) {
338
+ this.httpLog = null;
339
+ }
340
+ if (this.logRequest) {
341
+ this.logRequest.removeAllListeners();
342
+ this.logRequest = null;
343
+ }
344
+ }
345
+
346
+ async pipe() {
347
+ if (this.serve) {
348
+ try {
349
+ this.proxyReq = this.createServe();
350
+ } catch (err) {
351
+ logger.debug(LOG_ERROR);
352
+ logger.debug(err);
353
+ this.output503();
354
+ return;
355
+ }
356
+ this.proxyReq.on('error', () => {
357
+ this.output503();
358
+ });
359
+ this.proxyReq.on('close', () => {
360
+ setTimeout(() => {
361
+ this.clear();
362
+ }, 5000);
363
+ });
364
+ this.proxyReq.process(this.req);
365
+ } else {
366
+ try {
367
+ this.proxyReq = await this.createRequest();
368
+ } catch (err) {
369
+ logger.debug(LOG_ERROR);
370
+ logger.debug(err);
371
+ if (this.logRequest) {
372
+ this.req.pipe(this.logRequest.requestBody);
373
+ // no real request waiting for this data -> push it into the void
374
+ this.logRequest.requestBody.pipeToNothing(() => {
375
+ // wait for piping request
376
+ this.output503();
377
+ });
378
+ return;
379
+ }
380
+ this.output503();
381
+ return;
382
+ }
383
+ this.proxyReq.setTimeout(this.timeout * 1000);
384
+ this.proxyReq.on('timeout', () => {
385
+ this.output503();
386
+ });
387
+ this.proxyReq.on('error', (err) => {
388
+ logger.debug(LOG_ERROR);
389
+ logger.debug(err);
390
+ this.output503();
391
+ });
392
+ this.proxyReq.on('close', () => {
393
+ setTimeout(() => {
394
+ this.clear();
395
+ }, 5000);
396
+ });
397
+ if (this.logRequest) {
398
+ this.req.pipe(this.logRequest.requestBody).pipe(this.proxyReq);
399
+ } else {
400
+ this.req.pipe(this.proxyReq);
401
+ }
402
+ }
403
+ }
404
+ }
405
+
406
+ module.exports = TunnelHttp;
@@ -0,0 +1,95 @@
1
+ const EventEmitter = require('events');
2
+ const tls = require('tls');
3
+ const net = require('net');
4
+ const { getRealTargetHost } = require('../utils.js');
5
+ const {
6
+ EVENT_TUNNEL_IDENTIFIED,
7
+ TUNNEL_IDENTIFIED_HTTP1,
8
+ TUNNEL_IDENTIFIED_HTTP2
9
+ } = require('../utils');
10
+
11
+ const CHECK_INTERVAL = 300000;
12
+ const CHECK_TIMEOUT = 5000;
13
+
14
+ class TunnelIdentification extends EventEmitter {
15
+ constructor(proto, host, port, forceHttp2) {
16
+ super();
17
+ this.proto = proto;
18
+ this.host = getRealTargetHost(host);
19
+ this.port = port;
20
+ this.forceHttp2 = forceHttp2;
21
+ this.type = TUNNEL_IDENTIFIED_HTTP1;
22
+ this.identify();
23
+ this.ts = setInterval(() => this.identify(), CHECK_INTERVAL);
24
+ }
25
+
26
+ stop() {
27
+ if (this.ts) {
28
+ clearInterval(this.ts);
29
+ this.ts = null;
30
+ }
31
+ }
32
+
33
+ identify() {
34
+ if (this.forceHttp2) {
35
+ this.type = TUNNEL_IDENTIFIED_HTTP2;
36
+ this.emit(EVENT_TUNNEL_IDENTIFIED, TUNNEL_IDENTIFIED_HTTP2);
37
+ return;
38
+ }
39
+ let socket;
40
+ const close = () => {
41
+ try {
42
+ socket.removeAllListeners();
43
+ socket.close();
44
+ } catch (err) {
45
+ // do nothing
46
+ }
47
+ };
48
+ const connected = () => {
49
+ if (socket.alpnProtocol) {
50
+ if (socket.alpnProtocol === 'h2') {
51
+ this.type = TUNNEL_IDENTIFIED_HTTP2;
52
+ this.emit(EVENT_TUNNEL_IDENTIFIED, TUNNEL_IDENTIFIED_HTTP2);
53
+ } else {
54
+ this.type = TUNNEL_IDENTIFIED_HTTP1;
55
+ this.emit(EVENT_TUNNEL_IDENTIFIED, TUNNEL_IDENTIFIED_HTTP1);
56
+ }
57
+ close();
58
+ } else {
59
+ socket.write('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
60
+ socket.on('data', (d) => {
61
+ if (/HTTP\/1\.1/.test(d.toString('utf8'))) {
62
+ this.type = TUNNEL_IDENTIFIED_HTTP1;
63
+ this.emit(EVENT_TUNNEL_IDENTIFIED, TUNNEL_IDENTIFIED_HTTP1);
64
+ } else {
65
+ this.type = TUNNEL_IDENTIFIED_HTTP2;
66
+ this.emit(EVENT_TUNNEL_IDENTIFIED, TUNNEL_IDENTIFIED_HTTP2);
67
+ }
68
+ close();
69
+ });
70
+ }
71
+ };
72
+ if (this.proto === 'http') {
73
+ socket = net.connect({
74
+ host: this.host,
75
+ port: this.port,
76
+ });
77
+ socket.on('connect', connected);
78
+ } else {
79
+ socket = tls.connect({
80
+ host: this.host,
81
+ port: this.port,
82
+ rejectUnauthorized: true,
83
+ ALPNProtocols: ['h2', 'http/1.1'],
84
+ servername: this.host
85
+ });
86
+ socket.on('secureConnect', connected);
87
+ }
88
+ socket.setTimeout(CHECK_TIMEOUT);
89
+ socket.on('timeout', close);
90
+ socket.on('error', close);
91
+ socket.on('close', close);
92
+ }
93
+ }
94
+
95
+ module.exports = TunnelIdentification;
@@ -0,0 +1,63 @@
1
+ const { Socket } = require('net');
2
+ const EventEmitter = require('events');
3
+ const { getRealTargetHost } = require('../utils.js');
4
+ const { TUNNEL_LATENCY_EVENT_RECONNECTED } = require('../utils');
5
+
6
+ class TunnelLatency extends EventEmitter {
7
+ constructor(host, port) {
8
+ super();
9
+ this.latency = -1;
10
+ this.isChecking = false;
11
+ this.port = port;
12
+ this.host = getRealTargetHost(host);
13
+ this.ts = null;
14
+ }
15
+
16
+ check() {
17
+ if (this.isChecking) return;
18
+ this.isChecking = true;
19
+ let socket = new Socket();
20
+ let ts = null;
21
+ const clear = () => {
22
+ clearTimeout(ts);
23
+ socket.removeAllListeners();
24
+ socket.once('error', () => {});
25
+ socket.end();
26
+ socket = null;
27
+ this.isChecking = false;
28
+ };
29
+ ts = setTimeout(() => {
30
+ this.latency = -1;
31
+ clear();
32
+ }, 30000);
33
+ const start = process.hrtime();
34
+ socket.on('error', () => {
35
+ this.latency = -1;
36
+ clear();
37
+ });
38
+ socket.on('ready', () => {
39
+ const elapsed = process.hrtime(start);
40
+ if (this.latency < 0) this.emit(TUNNEL_LATENCY_EVENT_RECONNECTED);
41
+ this.latency = elapsed[0] * 1000 + elapsed[1] / 1000000; // ms
42
+ clear();
43
+ });
44
+ socket.connect(this.port, this.host);
45
+ }
46
+
47
+ startChecking() {
48
+ this.check();
49
+ this.stopChecking();
50
+ this.ts = setInterval(() => {
51
+ this.check();
52
+ }, 3000);
53
+ }
54
+
55
+ stopChecking() {
56
+ if (this.ts) {
57
+ clearInterval(this.ts);
58
+ this.ts = null;
59
+ }
60
+ }
61
+ }
62
+
63
+ module.exports = TunnelLatency;
@@ -0,0 +1,71 @@
1
+ const { Socket } = require('net');
2
+ const { v4 } = require('uuid');
3
+ const EventEmitter = require('events');
4
+ const { getRealTargetHost } = require('../utils.js');
5
+ const { TCP_EVENT_CLOSED } = require('../utils');
6
+
7
+ class TunnelTcp extends EventEmitter {
8
+ constructor(host, port, stream) {
9
+ super();
10
+ this.id = v4();
11
+ this.host = host;
12
+ this.port = port;
13
+ this.stream = stream;
14
+ this.socket = new Socket();
15
+ }
16
+
17
+ end() {
18
+ try {
19
+ this.stream.unpipe();
20
+ this.socket.unpipe();
21
+ } catch (err) {
22
+ // do nothing
23
+ }
24
+ try {
25
+ this.stream.removeAllListeners();
26
+ this.stream.on('error', () => {});
27
+ this.stream.end();
28
+ } catch (err) {
29
+ // do nothing
30
+ }
31
+ try {
32
+ this.socket.removeAllListeners();
33
+ this.socket.once('error', () => {});
34
+ this.socket.end();
35
+ } catch(err) {
36
+ // do nothing
37
+ }
38
+ this.socket = null;
39
+ this.stream = null;
40
+ this.host = null;
41
+ this.port = null;
42
+ this.emit(TCP_EVENT_CLOSED);
43
+ }
44
+
45
+ pipe() {
46
+ this.socket.on('error', () => {
47
+ this.end();
48
+ });
49
+ this.socket.on('close', () => {
50
+ this.end();
51
+ });
52
+ this.stream.on('error', () => {
53
+ this.end();
54
+ });
55
+ this.stream.on('close', () => {
56
+ this.end();
57
+ });
58
+ try {
59
+ this.socket.connect({
60
+ host: getRealTargetHost(this.host),
61
+ port: this.port
62
+ }, () => {
63
+ this.socket.pipe(this.stream).pipe(this.socket);
64
+ });
65
+ } catch (err) {
66
+ this.end();
67
+ }
68
+ }
69
+ }
70
+
71
+ module.exports = TunnelTcp;