@push.rocks/smartproxy 3.0.60 → 3.1.0

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.
@@ -0,0 +1,38 @@
1
+ import * as plugins from './smartproxy.plugins.js';
2
+ import './smartproxy.classes.proxyworker.js';
3
+ import './smartproxy.portproxy.js';
4
+ export class SmartProxy {
5
+ constructor(optionsArg = {}) {
6
+ this.smartsystem = new plugins.smartsystem.Smartsystem();
7
+ this.reverseConfigs = [];
8
+ this.options = optionsArg;
9
+ }
10
+ async updateReverseConfigs(reverseConfigsArg) {
11
+ // TODO search for old hostCandidates with that target
12
+ this.reverseConfigs = reverseConfigsArg;
13
+ if (this.proxyWorkerFunctions) {
14
+ await this.proxyWorkerFunctions.updateReverseConfigs(this.reverseConfigs);
15
+ }
16
+ }
17
+ async start() {
18
+ this.proxyWorkerFunctions = await plugins.smartspawn.spawn(new plugins.smartspawn.Worker('./smartproxy.classes.proxyworker'));
19
+ this.proxyWorkerFunctions.updateReverseConfigs(this.reverseConfigs);
20
+ this.portProxyFunctions = await plugins.smartspawn.spawn(new plugins.smartspawn.Worker('./smartproxy.portproxy'));
21
+ await this.portProxyFunctions.start(this.options.port);
22
+ await this.proxyWorkerFunctions.start();
23
+ console.log('successfully spawned portproxy and proxyworkers!');
24
+ }
25
+ async updateDefaultHeaders(defaultHeadersArg) {
26
+ await this.proxyWorkerFunctions.addDefaultHeaders(defaultHeadersArg);
27
+ }
28
+ async stop() {
29
+ await this.proxyWorkerFunctions.stop();
30
+ await plugins.smartspawn.Thread.terminate(this.proxyWorkerFunctions);
31
+ console.log('proxy worker stopped');
32
+ await this.portProxyFunctions.stop();
33
+ await plugins.smartspawn.Thread.terminate(this.portProxyFunctions);
34
+ console.log('portproxy stopped');
35
+ console.log('Terminated all childs!');
36
+ }
37
+ }
38
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRwcm94eS5jbGFzc2VzL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FDLENBQUM7SUFDeEMsQ0FBQztDQUNGIn0=
package/npmextra.json CHANGED
@@ -2,17 +2,33 @@
2
2
  "gitzone": {
3
3
  "projectType": "npm",
4
4
  "module": {
5
- "githost": "gitlab.com",
5
+ "githost": "code.foss.global",
6
6
  "gitscope": "push.rocks",
7
7
  "gitrepo": "smartproxy",
8
8
  "description": "a proxy for handling high workloads of proxying",
9
9
  "npmPackagename": "@push.rocks/smartproxy",
10
10
  "license": "MIT",
11
- "projectDomain": "push.rocks"
11
+ "projectDomain": "push.rocks",
12
+ "keywords": [
13
+ "proxy",
14
+ "network traffic",
15
+ "high workload",
16
+ "http",
17
+ "https",
18
+ "websocket",
19
+ "network routing",
20
+ "ssl redirect",
21
+ "port mapping",
22
+ "reverse proxy",
23
+ "authentication"
24
+ ]
12
25
  }
13
26
  },
14
27
  "npmci": {
15
28
  "npmGlobalTools": [],
16
29
  "npmAccessLevel": "public"
30
+ },
31
+ "tsdoc": {
32
+ "legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
17
33
  }
18
34
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@push.rocks/smartproxy",
3
- "version": "3.0.60",
3
+ "version": "3.1.0",
4
4
  "private": false,
5
5
  "description": "a proxy for handling high workloads of proxying",
6
6
  "main": "dist_ts/index.js",
@@ -8,12 +8,6 @@
8
8
  "type": "module",
9
9
  "author": "Lossless GmbH",
10
10
  "license": "MIT",
11
- "scripts": {
12
- "test": "(tstest test/)",
13
- "build": "(tsbuild --web --allowimplicitany)",
14
- "format": "(gitzone format)",
15
- "buildDocs": "tsdoc"
16
- },
17
11
  "devDependencies": {
18
12
  "@gitzone/tsbuild": "^2.1.66",
19
13
  "@gitzone/tsrun": "^1.2.44",
@@ -45,5 +39,29 @@
45
39
  ],
46
40
  "browserslist": [
47
41
  "last 1 chrome versions"
48
- ]
49
- }
42
+ ],
43
+ "keywords": [
44
+ "proxy",
45
+ "network traffic",
46
+ "high workload",
47
+ "http",
48
+ "https",
49
+ "websocket",
50
+ "network routing",
51
+ "ssl redirect",
52
+ "port mapping",
53
+ "reverse proxy",
54
+ "authentication"
55
+ ],
56
+ "homepage": "https://code.foss.global/push.rocks/smartproxy",
57
+ "repository": {
58
+ "type": "git",
59
+ "url": "https://code.foss.global/push.rocks/smartproxy.git"
60
+ },
61
+ "scripts": {
62
+ "test": "(tstest test/)",
63
+ "build": "(tsbuild --web --allowimplicitany)",
64
+ "format": "(gitzone format)",
65
+ "buildDocs": "tsdoc"
66
+ }
67
+ }
@@ -0,0 +1 @@
1
+
package/readme.md CHANGED
@@ -1,39 +1,118 @@
1
1
  # @push.rocks/smartproxy
2
- a proxy for handling high workloads of proxying
3
-
4
- ## Availabililty and Links
5
- * [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartproxy)
6
- * [gitlab.com (source)](https://gitlab.com/push.rocks/smartproxy)
7
- * [github.com (source mirror)](https://github.com/push.rocks/smartproxy)
8
- * [docs (typedoc)](https://push.rocks.gitlab.io/smartproxy/)
9
-
10
- ## Status for master
11
-
12
- Status Category | Status Badge
13
- -- | --
14
- GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/smartproxy/badges/master/pipeline.svg)](https://lossless.cloud)
15
- GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/smartproxy/badges/master/coverage.svg)](https://lossless.cloud)
16
- npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/smartproxy)](https://lossless.cloud)
17
- Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/smartproxy)](https://lossless.cloud)
18
- TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
19
- node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
20
- Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
21
- PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@push.rocks/smartproxy)](https://lossless.cloud)
22
- PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/smartproxy)](https://lossless.cloud)
23
- BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/smartproxy)](https://lossless.cloud)
2
+ A proxy for handling high workloads of proxying.
3
+
4
+ ## Install
5
+ To install `@push.rocks/smartproxy`, run the following command in your project's root directory:
6
+
7
+ ```bash
8
+ npm install @push.rocks/smartproxy --save
9
+ ```
10
+
11
+ This will add `@push.rocks/smartproxy` to your project's dependencies.
24
12
 
25
13
  ## Usage
26
14
 
27
- ## Contribution
15
+ `@push.rocks/smartproxy` is a versatile package for setting up and handling proxies with various capabilities such as SSL redirection, port proxying, and creating network proxies with complex routing rules. Below is a comprehensive guide on using its features.
16
+
17
+ ### Setting Up a Network Proxy
18
+
19
+ Create a network proxy to route incoming HTTPS requests to different local servers based on the hostname.
20
+
21
+ ```typescript
22
+ import { NetworkProxy } from '@push.rocks/smartproxy';
23
+
24
+ // Instantiate the NetworkProxy with desired options
25
+ const myNetworkProxy = new NetworkProxy({ port: 443 });
26
+
27
+ // Define your reverse proxy configurations
28
+ const proxyConfigs = [
29
+ {
30
+ destinationIp: '127.0.0.1',
31
+ destinationPort: '3000',
32
+ hostName: 'example.com',
33
+ privateKey: `-----BEGIN PRIVATE KEY-----
34
+ PRIVATE_KEY_CONTENT
35
+ -----END PRIVATE KEY-----`,
36
+ publicKey: `-----BEGIN CERTIFICATE-----
37
+ CERTIFICATE_CONTENT
38
+ -----END CERTIFICATE-----`,
39
+ },
40
+ // Add more reverse proxy configurations here
41
+ ];
42
+
43
+ // Start the network proxy
44
+ await myNetworkProxy.start();
45
+
46
+ // Update proxy configurations dynamically
47
+ await myNetworkProxy.updateProxyConfigs(proxyConfigs);
48
+
49
+ // Optionally, add default headers to all responses
50
+ await myNetworkProxy.addDefaultHeaders({
51
+ 'X-Powered-By': 'smartproxy',
52
+ });
53
+ ```
54
+
55
+ ### Port Proxying
56
+
57
+ You can also set up a port proxy to forward traffic from one port to another, which is useful for dynamic port forwarding scenarios.
58
+
59
+ ```typescript
60
+ import { PortProxy } from '@push.rocks/smartproxy';
61
+
62
+ // Create a PortProxy to forward traffic from port 5000 to port 3000
63
+ const myPortProxy = new PortProxy(5000, 3000);
64
+
65
+ // Start the port proxy
66
+ await myPortProxy.start();
67
+
68
+ // To stop the port proxy, simply call
69
+ await myPortProxy.stop();
70
+ ```
71
+
72
+ ### Enabling SSL Redirection
73
+
74
+ Easily redirect HTTP traffic to HTTPS using the `SslRedirect` class. This is particularly useful when ensuring all traffic uses encryption.
75
+
76
+ ```typescript
77
+ import { SslRedirect } from '@push.rocks/smartproxy';
78
+
79
+ // Instantiate the SslRedirect on port 80 (HTTP)
80
+ const mySslRedirect = new SslRedirect(80);
81
+
82
+ // Start listening and redirecting to HTTPS
83
+ await mySslRedirect.start();
84
+
85
+ // To stop the redirection, use
86
+ await mySslRedirect.stop();
87
+ ```
88
+
89
+ ### Advanced Usage
90
+
91
+ The package integrates seamlessly with TypeScript, allowing for advanced use cases, such as implementing custom routing logic, authentication mechanisms, and handling WebSocket connections through the network proxy.
92
+
93
+ For a more advanced setup involving WebSocket proxying and dynamic configuration reloading, refer to the network proxy example provided above. The WebSocket support demonstrates how seamless it is to work with real-time applications.
94
+
95
+ Remember, when dealing with certificates and private keys for HTTPS configurations, always secure your keys and store them appropriately.
96
+
97
+ `@push.rocks/smartproxy` provides a solid foundation for handling high workloads and complex proxying requirements with ease, whether you're implementing SSL redirections, port forwarding, or extensive routing and WebSocket support in your network.
98
+
99
+ For more information on how to use the features, refer to the in-depth documentation available in the package's repository or the npm package description.
100
+
101
+ ## License and Legal Information
102
+
103
+ This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
104
+
105
+ **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
106
+
107
+ ### Trademarks
28
108
 
29
- We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
109
+ This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
30
110
 
31
- ## Contribution
111
+ ### Company Information
32
112
 
33
- We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
113
+ Task Venture Capital GmbH
114
+ Registered at District court Bremen HRB 35230 HB, Germany
34
115
 
35
- For further information read the linked docs at the top of this readme.
116
+ For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
36
117
 
37
- ## Legal
38
- > MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
39
- | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
118
+ By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
@@ -1,8 +1,8 @@
1
1
  /**
2
- * autocreated commitinfo by @pushrocks/commitinfo
2
+ * autocreated commitinfo by @push.rocks/commitinfo
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/smartproxy',
6
- version: '3.0.60',
6
+ version: '3.1.0',
7
7
  description: 'a proxy for handling high workloads of proxying'
8
8
  }
@@ -5,6 +5,10 @@ export interface INetworkProxyOptions {
5
5
  port: number;
6
6
  }
7
7
 
8
+ interface WebSocketWithHeartbeat extends plugins.wsDefault {
9
+ lastPong: number;
10
+ }
11
+
8
12
  export class NetworkProxy {
9
13
  // INSTANCE
10
14
  public options: INetworkProxyOptions;
@@ -13,6 +17,7 @@ export class NetworkProxy {
13
17
  public router = new ProxyRouter();
14
18
  public socketMap = new plugins.lik.ObjectMap<plugins.net.Socket>();
15
19
  public defaultHeaders: { [key: string]: string } = {};
20
+ public heartbeatInterval: NodeJS.Timeout;
16
21
 
17
22
  public alreadyAddedReverseConfigs: {
18
23
  [hostName: string]: plugins.tsclass.network.IReverseProxyConfig;
@@ -186,76 +191,103 @@ JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
186
191
  return endOriginReqRes();
187
192
  }
188
193
  console.log(destinationUrl);
189
- const proxyResponse = await plugins.smartrequest.request(
190
- destinationUrl,
191
- {
192
- method: originRequest.method,
193
- headers: {
194
- ...originRequest.headers,
195
- 'X-Forwarded-Host': originRequest.headers.host,
196
- 'X-Forwarded-Proto': 'https',
194
+ try {
195
+ const proxyResponse = await plugins.smartrequest.request(
196
+ destinationUrl,
197
+ {
198
+ method: originRequest.method,
199
+ headers: {
200
+ ...originRequest.headers,
201
+ 'X-Forwarded-Host': originRequest.headers.host,
202
+ 'X-Forwarded-Proto': 'https',
203
+ },
204
+ keepAlive: true,
197
205
  },
198
- keepAlive: true,
199
- },
200
- true, // lets make this streaming
201
- (proxyRequest) => {
202
- originRequest.on('data', (data) => {
203
- proxyRequest.write(data);
204
- });
205
- originRequest.on('end', (data) => {
206
- proxyRequest.end();
207
- });
208
- originRequest.on('error', () => {
209
- proxyRequest.end();
210
- });
211
- originRequest.on('close', () => {
212
- proxyRequest.end();
213
- });
214
- originRequest.on('timeout', () => {
215
- proxyRequest.end();
216
- originRequest.destroy();
217
- });
218
- proxyRequest.on('error', () => {
219
- endOriginReqRes();
220
- });
206
+ true, // lets make this streaming (keepAlive)
207
+ (proxyRequest) => {
208
+ originRequest.on('data', (data) => {
209
+ proxyRequest.write(data);
210
+ });
211
+ originRequest.on('end', () => {
212
+ proxyRequest.end();
213
+ });
214
+ originRequest.on('error', () => {
215
+ proxyRequest.end();
216
+ });
217
+ originRequest.on('close', () => {
218
+ proxyRequest.end();
219
+ });
220
+ originRequest.on('timeout', () => {
221
+ proxyRequest.end();
222
+ originRequest.destroy();
223
+ });
224
+ proxyRequest.on('error', () => {
225
+ endOriginReqRes();
226
+ });
227
+ }
228
+ );
229
+ originResponse.statusCode = proxyResponse.statusCode;
230
+ console.log(proxyResponse.statusCode);
231
+ for (const defaultHeader of Object.keys(this.defaultHeaders)) {
232
+ originResponse.setHeader(defaultHeader, this.defaultHeaders[defaultHeader]);
221
233
  }
222
- );
223
- originResponse.statusCode = proxyResponse.statusCode;
224
- console.log(proxyResponse.statusCode);
225
- for (const defaultHeader of Object.keys(this.defaultHeaders)) {
226
- originResponse.setHeader(defaultHeader, this.defaultHeaders[defaultHeader]);
227
- }
228
- for (const header of Object.keys(proxyResponse.headers)) {
229
- originResponse.setHeader(header, proxyResponse.headers[header]);
234
+ for (const header of Object.keys(proxyResponse.headers)) {
235
+ originResponse.setHeader(header, proxyResponse.headers[header]);
236
+ }
237
+ proxyResponse.on('data', (data) => {
238
+ originResponse.write(data);
239
+ });
240
+ proxyResponse.on('end', () => {
241
+ originResponse.end();
242
+ });
243
+ proxyResponse.on('error', () => {
244
+ originResponse.destroy();
245
+ });
246
+ proxyResponse.on('close', () => {
247
+ originResponse.end();
248
+ });
249
+ proxyResponse.on('timeout', () => {
250
+ originResponse.end();
251
+ originResponse.destroy();
252
+ });
253
+ } catch (error) {
254
+ console.error('Error while processing request:', error);
255
+ endOriginReqRes(502, 'Bad Gateway: Error processing the request');
230
256
  }
231
- proxyResponse.on('data', (data) => {
232
- originResponse.write(data);
233
- });
234
- proxyResponse.on('end', () => {
235
- originResponse.end();
236
- });
237
- proxyResponse.on('error', () => {
238
- originResponse.destroy();
239
- });
240
- proxyResponse.on('close', () => {
241
- originResponse.end();
242
- });
243
- proxyResponse.on('timeout', () => {
244
- originResponse.end();
245
- originResponse.destroy();
246
- });
247
257
  }
248
258
  );
249
259
 
250
260
  // Enable websockets
251
261
  const wsServer = new plugins.ws.WebSocketServer({ server: this.httpsServer });
262
+
263
+ // Set up the heartbeat interval
264
+ this.heartbeatInterval = setInterval(() => {
265
+ wsServer.clients.forEach((ws: plugins.wsDefault) => {
266
+ const wsIncoming = ws as WebSocketWithHeartbeat;
267
+ if (!wsIncoming.lastPong) {
268
+ wsIncoming.lastPong = Date.now();
269
+ }
270
+ if (Date.now() - wsIncoming.lastPong > 5 * 60 * 1000) {
271
+ console.log('Terminating websocket due to missing pong for 5 minutes.');
272
+ wsIncoming.terminate();
273
+ } else {
274
+ wsIncoming.ping();
275
+ }
276
+ });
277
+ }, 60000); // runs every 1 minute
278
+
252
279
  wsServer.on(
253
280
  'connection',
254
- async (wsIncoming: plugins.wsDefault, reqArg: plugins.http.IncomingMessage) => {
281
+ async (wsIncoming: WebSocketWithHeartbeat, reqArg: plugins.http.IncomingMessage) => {
255
282
  console.log(
256
283
  `wss proxy: got connection for wsc for https://${reqArg.headers.host}${reqArg.url}`
257
284
  );
258
285
 
286
+ wsIncoming.lastPong = Date.now();
287
+ wsIncoming.on('pong', () => {
288
+ wsIncoming.lastPong = Date.now();
289
+ });
290
+
259
291
  let wsOutgoing: plugins.wsDefault;
260
292
 
261
293
  const outGoingDeferred = plugins.smartpromise.defer();
@@ -277,30 +309,42 @@ JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
277
309
  }
278
310
 
279
311
  wsIncoming.on('message', async (message, isBinary) => {
280
- await outGoingDeferred.promise;
281
- // console.log("client to upstream", message);
282
- wsOutgoing.send(message, { binary: isBinary });
312
+ try {
313
+ await outGoingDeferred.promise;
314
+ wsOutgoing.send(message, { binary: isBinary });
315
+ } catch (error) {
316
+ console.error('Error sending message to wsOutgoing:', error);
317
+ }
283
318
  });
284
319
 
285
320
  wsOutgoing.on('message', async (message, isBinary) => {
286
- // console.log("upstream to client", message);
287
- wsIncoming.send(message, { binary: isBinary });
321
+ try {
322
+ wsIncoming.send(message, { binary: isBinary });
323
+ } catch (error) {
324
+ console.error('Error sending message to wsIncoming:', error);
325
+ }
288
326
  });
327
+
289
328
  const terminateWsOutgoing = () => {
290
- wsOutgoing.terminate();
291
- console.log('terminated outgoing ws.');
329
+ if (wsOutgoing) {
330
+ wsOutgoing.terminate();
331
+ console.log('terminated outgoing ws.');
332
+ }
292
333
  };
293
334
  wsIncoming.on('error', () => terminateWsOutgoing());
294
335
  wsIncoming.on('close', () => terminateWsOutgoing());
295
336
 
296
337
  const terminateWsIncoming = () => {
297
- wsIncoming.terminate();
298
- console.log('terminated incoming ws.');
338
+ if (wsIncoming) {
339
+ wsIncoming.terminate();
340
+ console.log('terminated incoming ws.');
341
+ }
299
342
  };
300
343
  wsOutgoing.on('error', () => terminateWsIncoming());
301
344
  wsOutgoing.on('close', () => terminateWsIncoming());
302
345
  }
303
346
  );
347
+
304
348
  this.httpsServer.keepAliveTimeout = 600 * 1000;
305
349
  this.httpsServer.headersTimeout = 600 * 1000;
306
350
 
@@ -339,8 +383,6 @@ JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
339
383
  this.proxyConfigs = proxyConfigsArg;
340
384
  this.router.setNewProxyConfigs(proxyConfigsArg);
341
385
  for (const hostCandidate of this.proxyConfigs) {
342
- // console.log(hostCandidate);
343
-
344
386
  const existingHostNameConfig = this.alreadyAddedReverseConfigs[hostCandidate.hostName];
345
387
 
346
388
  if (!existingHostNameConfig) {
@@ -360,7 +402,6 @@ JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
360
402
  cert: hostCandidate.publicKey,
361
403
  key: hostCandidate.privateKey,
362
404
  });
363
- this.httpsServer;
364
405
  }
365
406
  }
366
407
 
@@ -379,5 +420,7 @@ JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
379
420
  socket.destroy();
380
421
  });
381
422
  await done.promise;
423
+ clearInterval(this.heartbeatInterval);
424
+ console.log('NetworkProxy -> OK: Server has been stopped and all connections closed.');
382
425
  }
383
426
  }