vpn-split 21.0.32 → 21.0.34

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 (80) hide show
  1. package/VERIFIED-BUILD-DATA.jsonc +3 -3
  2. package/browser/package.json +1 -1
  3. package/browser-prod/fesm2022/vpn-split-browser-prod.mjs.map +1 -1
  4. package/browser-prod/package.json +1 -1
  5. package/lib/build-info._auto-generated_.d.ts +1 -1
  6. package/lib/build-info._auto-generated_.js +1 -1
  7. package/lib/package.json +1 -1
  8. package/lib-esm/app.d.ts +3 -0
  9. package/lib-esm/app.electron.d.ts +0 -0
  10. package/lib-esm/app.electron.js +82 -0
  11. package/lib-esm/app.electron.js.map +1 -0
  12. package/lib-esm/app.hosts.d.ts +95 -0
  13. package/lib-esm/app.hosts.js +157 -0
  14. package/lib-esm/app.hosts.js.map +1 -0
  15. package/lib-esm/app.js +204 -0
  16. package/lib-esm/app.js.map +1 -0
  17. package/lib-esm/app.vscode.d.ts +9 -0
  18. package/lib-esm/app.vscode.js +33 -0
  19. package/lib-esm/app.vscode.js.map +1 -0
  20. package/lib-esm/index.d.ts +1 -0
  21. package/lib-esm/index.js +2 -0
  22. package/lib-esm/index.js.map +1 -0
  23. package/lib-esm/lib/build-info._auto-generated_.d.ts +24 -0
  24. package/lib-esm/lib/build-info._auto-generated_.js +27 -0
  25. package/lib-esm/lib/build-info._auto-generated_.js.map +1 -0
  26. package/lib-esm/lib/env/env.angular-node-app.d.ts +66 -0
  27. package/lib-esm/lib/env/env.angular-node-app.js +135 -0
  28. package/lib-esm/lib/env/env.angular-node-app.js.map +1 -0
  29. package/lib-esm/lib/env/env.docs-webapp.d.ts +66 -0
  30. package/lib-esm/lib/env/env.docs-webapp.js +135 -0
  31. package/lib-esm/lib/env/env.docs-webapp.js.map +1 -0
  32. package/lib-esm/lib/env/env.electron-app.d.ts +66 -0
  33. package/lib-esm/lib/env/env.electron-app.js +135 -0
  34. package/lib-esm/lib/env/env.electron-app.js.map +1 -0
  35. package/lib-esm/lib/env/env.mobile-app.d.ts +66 -0
  36. package/lib-esm/lib/env/env.mobile-app.js +135 -0
  37. package/lib-esm/lib/env/env.mobile-app.js.map +1 -0
  38. package/lib-esm/lib/env/env.npm-lib-and-cli-tool.d.ts +66 -0
  39. package/lib-esm/lib/env/env.npm-lib-and-cli-tool.js +135 -0
  40. package/lib-esm/lib/env/env.npm-lib-and-cli-tool.js.map +1 -0
  41. package/lib-esm/lib/env/env.vscode-plugin.d.ts +66 -0
  42. package/lib-esm/lib/env/env.vscode-plugin.js +135 -0
  43. package/lib-esm/lib/env/env.vscode-plugin.js.map +1 -0
  44. package/lib-esm/lib/env/index.d.ts +6 -0
  45. package/lib-esm/lib/env/index.js +7 -0
  46. package/lib-esm/lib/env/index.js.map +1 -0
  47. package/lib-esm/lib/hostile.backend.d.ts +37 -0
  48. package/lib-esm/lib/hostile.backend.js +118 -0
  49. package/lib-esm/lib/hostile.backend.js.map +1 -0
  50. package/lib-esm/lib/index._auto-generated_.d.ts +0 -0
  51. package/lib-esm/lib/index._auto-generated_.js +6 -0
  52. package/lib-esm/lib/index._auto-generated_.js.map +1 -0
  53. package/lib-esm/lib/index.d.ts +2 -0
  54. package/lib-esm/lib/index.js +5 -0
  55. package/lib-esm/lib/index.js.map +1 -0
  56. package/lib-esm/lib/migrations/index.d.ts +1 -0
  57. package/lib-esm/lib/migrations/index.js +3 -0
  58. package/lib-esm/lib/migrations/index.js.map +1 -0
  59. package/lib-esm/lib/migrations/migrations_index._auto-generated_.d.ts +0 -0
  60. package/lib-esm/lib/migrations/migrations_index._auto-generated_.js +4 -0
  61. package/lib-esm/lib/migrations/migrations_index._auto-generated_.js.map +1 -0
  62. package/lib-esm/lib/models.d.ts +61 -0
  63. package/lib-esm/lib/models.js +177 -0
  64. package/lib-esm/lib/models.js.map +1 -0
  65. package/lib-esm/lib/start.backend.d.ts +0 -0
  66. package/lib-esm/lib/start.backend.js +24 -0
  67. package/lib-esm/lib/start.backend.js.map +1 -0
  68. package/lib-esm/lib/vpn-split.backend.d.ts +56 -0
  69. package/lib-esm/lib/vpn-split.backend.js +739 -0
  70. package/lib-esm/lib/vpn-split.backend.js.map +1 -0
  71. package/lib-prod/build-info._auto-generated_.d.ts +1 -1
  72. package/lib-prod/build-info._auto-generated_.js +1 -1
  73. package/lib-prod/models.js.map +1 -1
  74. package/lib-prod/package.json +1 -1
  75. package/lib-prod/vpn-split.backend.js.map +1 -1
  76. package/package.json +1 -1
  77. package/src.js +4 -20
  78. package/websql/package.json +1 -1
  79. package/websql-prod/fesm2022/vpn-split-websql-prod.mjs.map +1 -1
  80. package/websql-prod/package.json +1 -1
@@ -0,0 +1,739 @@
1
+ //#region imports
2
+ import { execSync } from 'child_process';
3
+ // TODO I am using TCP ugrade not UDP!
4
+ import * as dgram from 'dgram'; // <-- For UDP sockets
5
+ import * as http from 'http';
6
+ import axios from 'axios';
7
+ import * as express from 'express';
8
+ import * as httpProxy from 'http-proxy';
9
+ import { Log, Level } from 'ng2-logger/lib';
10
+ import { config } from 'tnp-core/lib';
11
+ import { _, path, fse, https, isElevated, crossPlatformPath, UtilsOs, UtilsNetwork, } from 'tnp-core/lib';
12
+ import { CoreModels } from 'tnp-core/lib';
13
+ import { Helpers, HelpersTaon } from 'tnp-helpers/lib';
14
+ import { Hostile } from './hostile.backend';
15
+ import { HostForServer } from './models';
16
+ const HOST_FILE_PATH = UtilsNetwork.getEtcHostsPath();
17
+ const log = Log.create('vpn-split', Level.INFO);
18
+ //#endregion
19
+ //#region consts
20
+ const GENERATED = '#GENERATED_BY_CLI#';
21
+ const EOL = process.platform === 'win32' ? '\r\n' : '\n';
22
+ const SERVERS_PATH = '/$$$$servers$$$$';
23
+ const HOST_FILE_PATHUSER = crossPlatformPath([
24
+ UtilsOs.getRealHomeDir(),
25
+ 'hosts-file__vpn-split',
26
+ ]);
27
+ const from = HostForServer.From;
28
+ const DefaultEtcHosts = {
29
+ 'localhost alias': from({
30
+ ipOrDomain: '127.0.0.1',
31
+ aliases: 'localhost',
32
+ isDefault: true,
33
+ }),
34
+ broadcasthost: from({
35
+ ipOrDomain: '255.255.255.255',
36
+ aliases: 'broadcasthost',
37
+ isDefault: true,
38
+ }),
39
+ 'localhost alias ipv6': from({
40
+ ipOrDomain: '::1',
41
+ aliases: 'localhost',
42
+ isDefault: true,
43
+ }),
44
+ };
45
+ //#endregion
46
+ export class VpnSplit {
47
+ portsToPass;
48
+ hosts;
49
+ cwd;
50
+ //#region getters
51
+ get hostsArr() {
52
+ const hosts = this.hosts;
53
+ return _.keys(hosts).map(hostName => {
54
+ const v = hosts[hostName];
55
+ v.name = hostName;
56
+ return v;
57
+ });
58
+ }
59
+ get hostsArrWithoutDefault() {
60
+ return this.hostsArr.filter(f => !f.isDefault);
61
+ }
62
+ get serveKeyName() {
63
+ return 'tmp-' + config.file.server_key;
64
+ }
65
+ get serveKeyPath() {
66
+ return path.join(this.cwd, this.serveKeyName);
67
+ }
68
+ get serveCertName() {
69
+ return 'tmp-' + config.file.server_cert;
70
+ }
71
+ get serveCertPath() {
72
+ return path.join(this.cwd, this.serveCertName);
73
+ }
74
+ get serveCertChainName() {
75
+ return 'tmp-' + config.file.server_chain_cert;
76
+ }
77
+ get serveCertChainPath() {
78
+ return path.join(this.cwd, this.serveCertChainName);
79
+ }
80
+ //#endregion
81
+ //#region fields
82
+ __hostile;
83
+ //#endregion
84
+ //#region singleton
85
+ static _instances = {};
86
+ constructor(portsToPass, hosts, cwd) {
87
+ this.portsToPass = portsToPass;
88
+ this.hosts = hosts;
89
+ this.cwd = cwd;
90
+ this.__hostile = new Hostile();
91
+ }
92
+ static async Instance({ ports = [80, 443, 4443, 22, 2222, 8180, 8080, 4407, 7999, 9443], additionalDefaultHosts = {}, cwd = process.cwd(), allowNotSudo = false, } = {}) {
93
+ if (!(await isElevated()) && !allowNotSudo) {
94
+ Helpers.error(`[vpn-split] Please run this program as sudo (or admin on windows)`, false, true);
95
+ }
96
+ if (!VpnSplit._instances[cwd]) {
97
+ VpnSplit._instances[cwd] = new VpnSplit(ports, _.merge(DefaultEtcHosts, additionalDefaultHosts), cwd);
98
+ }
99
+ return VpnSplit._instances[cwd];
100
+ }
101
+ //#endregion
102
+ //#region start server
103
+ async startServer(saveHostInUserFolder = false) {
104
+ this.createCertificateIfNotExists();
105
+ const hostsForCert = this.hosts;
106
+ // const domainsForCert: string[] = Utils.uniqArray(
107
+ // Object.keys(hostsForCert).reduce((prev, curr) => {
108
+ // const host = hostsForCert[curr] as HostForServer;
109
+ // host.aliases.forEach(alias => {
110
+ // if (!host.isDefault) {
111
+ // prev.push(alias);
112
+ // }
113
+ // });
114
+ // return prev;
115
+ // }, [] as string[]),
116
+ // );
117
+ // this.ensureMkcertCertificate(domainsForCert);
118
+ //#region modify /etc/host to direct traffic appropriately
119
+ saveHosts(hostsForCert, { saveHostInUserFolder });
120
+ //#endregion
121
+ // Start TCP/HTTPS passthrough
122
+ for (const portToPassthrough of this.portsToPass) {
123
+ await this.serverPassthrough(portToPassthrough);
124
+ }
125
+ // Start UDP passthrough
126
+ for (const portToPassthrough of this.portsToPass) {
127
+ await this.serverUdpPassthrough(portToPassthrough);
128
+ }
129
+ Helpers.info(`Activated (server).`);
130
+ }
131
+ //#endregion
132
+ //#region apply hosts
133
+ applyHosts(hosts) {
134
+ // console.log(hosts);
135
+ saveHosts(hosts);
136
+ }
137
+ applyHostsLocal(hosts) {
138
+ // console.log(hosts);
139
+ saveHostsLocal(hosts);
140
+ }
141
+ //#endregion
142
+ //#region start client
143
+ async startClient(vpnServerTargets, options) {
144
+ options = options || {};
145
+ const { saveHostInUserFolder } = options;
146
+ if (!Array.isArray(vpnServerTargets)) {
147
+ vpnServerTargets = [vpnServerTargets];
148
+ }
149
+ for (const vpnServerTarget of vpnServerTargets) {
150
+ await this.preventBadTargetForClient(vpnServerTarget);
151
+ }
152
+ this.createCertificateIfNotExists();
153
+ // Get remote host definitions from remote server
154
+ const hosts = [];
155
+ for (const vpnServerTarget of vpnServerTargets) {
156
+ const newHosts = await this.getRemoteHosts(vpnServerTarget);
157
+ for (const host of newHosts) {
158
+ // Mark the original VPN server domain
159
+ host.originHostname = vpnServerTarget.hostname;
160
+ hosts.push(host);
161
+ }
162
+ }
163
+ // Merge with original, redirecting all non-default entries to 127.0.0.1
164
+ const originalHosts = this.hostsArr;
165
+ const combinedHostsObj = _.values([
166
+ ...originalHosts,
167
+ ...hosts.map(h => HostForServer.From({
168
+ aliases: h.alias,
169
+ ipOrDomain: h.ip,
170
+ originHostname: h.originHostname,
171
+ }, `external host ${h.alias} ${h.ip}`)),
172
+ ]
173
+ .map(c => {
174
+ let copy = c.clone();
175
+ if (!copy.isDefault) {
176
+ copy.ip = `127.0.0.1`;
177
+ }
178
+ return copy;
179
+ })
180
+ .reduce((prev, curr) => {
181
+ return _.merge(prev, {
182
+ [curr.aliases.join(' ')]: curr,
183
+ });
184
+ }, {}));
185
+ const hostsForCert = options.useHost ? options.useHost : combinedHostsObj;
186
+ // const domainsForCert: string[] = Utils.uniqArray(
187
+ // Object.keys(hostsForCert).reduce((prev, curr) => {
188
+ // const host = hostsForCert[curr] as HostForServer;
189
+ // host.aliases.forEach(alias => {
190
+ // if (!host.isDefault) {
191
+ // prev.push(alias);
192
+ // }
193
+ // });
194
+ // return prev;
195
+ // }, [] as string[]),
196
+ // );
197
+ // this.ensureMkcertCertificate(domainsForCert);
198
+ saveHosts(hostsForCert, {
199
+ saveHostInUserFolder,
200
+ });
201
+ // Start TCP/HTTPS passthrough
202
+ for (const portToPassthrough of this.portsToPass) {
203
+ await this.clientPassthrough(portToPassthrough, vpnServerTargets, combinedHostsObj);
204
+ }
205
+ // Start UDP passthrough
206
+ for (const portToPassthrough of this.portsToPass) {
207
+ await this.clientUdpPassthrough(portToPassthrough, vpnServerTargets, combinedHostsObj);
208
+ }
209
+ Helpers.info(`Client activated`);
210
+ }
211
+ //#endregion
212
+ //#region private methods / get remote hosts
213
+ async getRemoteHosts(vpnServerTarget) {
214
+ try {
215
+ const url = `http://${vpnServerTarget.hostname}${SERVERS_PATH}`;
216
+ const response = await axios({ url, method: 'GET' });
217
+ return response.data;
218
+ }
219
+ catch (err) {
220
+ Helpers.error(`Remote server: ${vpnServerTarget.hostname} may be inactive...`, true, true);
221
+ return [];
222
+ }
223
+ }
224
+ //#endregion
225
+ //#region private methods / create certificate
226
+ createCertificateIfNotExists() {
227
+ if (!Helpers.exists(this.serveKeyPath) ||
228
+ !Helpers.exists(this.serveCertPath)) {
229
+ Helpers.info(`[vpn-split] Generating new self-signed certificate for localhost...`);
230
+ const commandGen = UtilsOs.isRunningInWindowsPowerShell()
231
+ ? `powershell -Command "& 'C:\\Program Files\\Git\\usr\\bin\\openssl.exe' req -nodes -new -x509 -keyout ${this.serveKeyName} -out ${this.serveCertName}"`
232
+ : `openssl req -nodes -new -x509 -keyout ${this.serveKeyName} -out ${this.serveCertName}`;
233
+ Helpers.run(commandGen, { cwd: this.cwd, output: true }).sync();
234
+ }
235
+ }
236
+ //#endregion
237
+ //#region private methods / TCP & HTTPS passthrough
238
+ getTarget({ req, res, port, hostname, }) {
239
+ return `${req.protocol}://${hostname}:${port}`;
240
+ }
241
+ getProxyConfig({ req, res, port, hostname, isHttps, }) {
242
+ const serverPassthrough = !!hostname;
243
+ const target = this.getTarget({
244
+ req,
245
+ res,
246
+ port,
247
+ hostname: serverPassthrough ? hostname : req.hostname,
248
+ });
249
+ // console.log({
250
+ // target,
251
+ // port,
252
+ // hostname,
253
+ // reqHostname: req.hostname,
254
+ // serverPassthrough,
255
+ // });
256
+ return isHttps
257
+ ? {
258
+ target,
259
+ ssl: {
260
+ key: fse.readFileSync(this.serveKeyPath),
261
+ cert: fse.readFileSync(this.serveCertPath),
262
+ },
263
+ // agent: new https.Agent({
264
+ // secureOptions: crypto.constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION,
265
+ // }),
266
+ // changeOrigin: true,
267
+ secure: true,
268
+ }
269
+ : { target };
270
+ }
271
+ getNotFoundMsg(req, res, port, type) {
272
+ return `[vpn-split] You are requesting a URL that is not in proxy reach [${type}]
273
+ Protocol: ${req.protocol}
274
+ Hostname: ${req.hostname}
275
+ OriginalUrl: ${req.originalUrl}
276
+ Req.method: ${req.method}
277
+ Port: ${port}
278
+ SERVERS_PATH: ${SERVERS_PATH}`;
279
+ }
280
+ getMaybeChangeOriginTrueMsg(req, res, port, type) {
281
+ return `[vpn-split] Possibly need changeOrigin: true in your proxy config
282
+ Protocol: ${req.protocol}
283
+ Hostname: ${req.hostname}
284
+ OriginalUrl: ${req.originalUrl}
285
+ Req.method: ${req.method}
286
+ Port: ${port}`;
287
+ }
288
+ filterHeaders(req, res) {
289
+ // If you have any headers to remove, do it here:
290
+ const headersToRemove = [
291
+ // 'Strict-Transport-Security',
292
+ // 'Content-Security-Policy',
293
+ // ...
294
+ ];
295
+ headersToRemove.forEach(headerName => {
296
+ delete req.headers[headerName];
297
+ res.setHeader(headerName, '');
298
+ });
299
+ }
300
+ isHttpsPort(port) {
301
+ // Decide your logic for “is HTTPS” here
302
+ return [443, 4443, 9443].includes(port);
303
+ }
304
+ //#region server passthrough (TCP/HTTPS)
305
+ async serverPassthrough(portToPassthrough) {
306
+ const isHttps = this.isHttpsPort(portToPassthrough);
307
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
308
+ const app = express();
309
+ const proxy = httpProxy.createProxyServer({});
310
+ const localIp = await UtilsNetwork.getLocalIpAddresses();
311
+ const currentLocalIps = [
312
+ CoreModels.localhostDomain,
313
+ CoreModels.localhostIp127,
314
+ ...localIp.map(a => a.address),
315
+ ];
316
+ app.use((req, res, next) => {
317
+ this.filterHeaders(req, res);
318
+ if (currentLocalIps.includes(req.hostname)) {
319
+ if (req.method === 'GET' && req.originalUrl === SERVERS_PATH) {
320
+ res.send(JSON.stringify(this.hostsArrWithoutDefault.map(h => ({
321
+ ip: h.ip,
322
+ alias: HelpersTaon.arrays.from(h.aliases).join(' '),
323
+ }))));
324
+ }
325
+ else {
326
+ const msg = this.getNotFoundMsg(req, res, portToPassthrough, 'server');
327
+ log.d(msg);
328
+ res.send(msg);
329
+ }
330
+ next();
331
+ }
332
+ else {
333
+ proxy.web(req, res, this.getProxyConfig({ req, res, port: portToPassthrough, isHttps }), next);
334
+ }
335
+ });
336
+ const server = isHttps
337
+ ? https.createServer({
338
+ key: fse.readFileSync(this.serveKeyPath),
339
+ cert: fse.readFileSync(this.serveCertPath),
340
+ }, app)
341
+ : http.createServer(app);
342
+ await Helpers.killProcessByPort(portToPassthrough, { silent: true });
343
+ await new Promise((resolve, reject) => {
344
+ server.listen(portToPassthrough, () => {
345
+ console.log(`TCP/HTTPS server listening on port ${portToPassthrough} (secure=${isHttps})`);
346
+ resolve();
347
+ });
348
+ });
349
+ }
350
+ //#endregion
351
+ //#region client passthrough (TCP/HTTPS)
352
+ async clientPassthrough(portToPassthrough, vpnServerTargets, hostsArr) {
353
+ // Map from an alias => the “real” origin hostname (the server domain)
354
+ const aliasToOriginHostname = {};
355
+ for (const h of hostsArr) {
356
+ for (const alias of h.aliases) {
357
+ aliasToOriginHostname[alias] = h.originHostname;
358
+ }
359
+ }
360
+ // Remove defaults from the map so we don't cause collisions
361
+ delete aliasToOriginHostname['localhost'];
362
+ delete aliasToOriginHostname['broadcasthost'];
363
+ // Build a dictionary from originHostname => URL (for quick lookup)
364
+ const originToUrlMap = {};
365
+ for (const url of vpnServerTargets) {
366
+ originToUrlMap[url.hostname] = url;
367
+ }
368
+ const isHttps = this.isHttpsPort(portToPassthrough);
369
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
370
+ const app = express();
371
+ const proxy = httpProxy.createProxyServer({});
372
+ app.use((req, res, next) => {
373
+ this.filterHeaders(req, res);
374
+ // Identify the real origin server based on alias
375
+ const originHostname = aliasToOriginHostname[req.hostname];
376
+ if (!originHostname) {
377
+ // Not one of our known aliases
378
+ const msg = this.getMaybeChangeOriginTrueMsg(req, res, portToPassthrough, 'client');
379
+ res.send(msg);
380
+ next();
381
+ return;
382
+ }
383
+ // Proxy onward to the real server domain at the same port
384
+ const targetUrlObj = originToUrlMap[originHostname];
385
+ if (!targetUrlObj) {
386
+ const notFoundMsg = this.getNotFoundMsg(req, res, portToPassthrough, 'client');
387
+ res.send(notFoundMsg);
388
+ next();
389
+ return;
390
+ }
391
+ // Forward
392
+ proxy.web(req, res, this.getProxyConfig({
393
+ req,
394
+ res,
395
+ port: portToPassthrough,
396
+ isHttps,
397
+ hostname: targetUrlObj.hostname,
398
+ }), next);
399
+ });
400
+ const server = isHttps
401
+ ? https.createServer({
402
+ key: fse.readFileSync(this.serveKeyPath),
403
+ cert: fse.readFileSync(this.serveCertPath),
404
+ }, app)
405
+ : http.createServer(app);
406
+ await Helpers.killProcessByPort(portToPassthrough, { silent: true });
407
+ await new Promise((resolve, reject) => {
408
+ server.listen(portToPassthrough, () => {
409
+ log.i(`TCP/HTTPS client listening on port ${portToPassthrough} (secure=${isHttps})`);
410
+ resolve();
411
+ });
412
+ });
413
+ }
414
+ //#endregion
415
+ //#region UDP passthrough
416
+ /**
417
+ * Start a UDP socket for “server” mode on a given port.
418
+ * This example forwards inbound messages right back to the sender,
419
+ * or you can forward them to an external IP:port if desired.
420
+ */
421
+ async serverUdpPassthrough(port) {
422
+ return;
423
+ // Example of a simple “echo-style” server or forwarder
424
+ const socket = dgram.createSocket('udp4');
425
+ // (Optionally) kill existing processes on that port – though for UDP
426
+ // we might not have a direct “listener process.” Adjust as needed.
427
+ // await Helpers.killProcessByPort(port, { silent: true }).catch(() => {});
428
+ socket.on('message', (msg, rinfo) => {
429
+ // rinfo contains { address, port } of the sender
430
+ // In a typical “server” scenario, you might:
431
+ // 1. Inspect msg
432
+ // 2. Possibly forward to some real backend if needed
433
+ // 3. Or just echo it back
434
+ // For a real forward, do something like:
435
+ // const backendHost = 'some-other-host-or-ip';
436
+ // const backendPort = 9999;
437
+ // socket.send(msg, 0, msg.length, backendPort, backendHost);
438
+ // For a basic echo server:
439
+ socket.send(msg, 0, msg.length, rinfo.port, rinfo.address, err => {
440
+ if (err) {
441
+ log.er(`UDP server send error: ${err}`);
442
+ }
443
+ });
444
+ });
445
+ socket.on('listening', () => {
446
+ const address = socket.address();
447
+ log.i(`UDP server listening at ${address.address}:${address.port}`);
448
+ });
449
+ socket.bind(port);
450
+ }
451
+ /**
452
+ * Start a UDP socket for “client” mode on a given port.
453
+ * This example also just does a trivial pass-through or echo,
454
+ * but you can adapt to forward to a remote server.
455
+ */
456
+ async clientUdpPassthrough(port, vpnServerTargets, hostsArr) {
457
+ return;
458
+ // console.log(`Client UDP passthrough, port ${port}` );
459
+ // In client mode, we typically intercept local UDP traffic on “port”
460
+ // and forward it to the remote server. Then we forward the remote
461
+ // server's response back to the local client.
462
+ const socket = dgram.createSocket('udp4');
463
+ // await Helpers.killProcessByPort(port, { silent: true }).catch(() => {});
464
+ // For simplicity, pick the first server from the array
465
+ // Or add your own logic to choose among multiple.
466
+ const primaryTarget = vpnServerTargets[0];
467
+ const targetHost = primaryTarget.hostname;
468
+ // Choose the same port or a custom port
469
+ const targetPort = port;
470
+ // A map to remember who originally sent us a packet,
471
+ // so we can route the response back properly.
472
+ // Key could be “targetHost:targetPort => { address, port }”
473
+ // or “clientAddress:clientPort” => { remoteAddress, remotePort }.
474
+ // Adapt to your scenario.
475
+ const clientMap = new Map();
476
+ socket.on('message', (msg, rinfo) => {
477
+ //
478
+ // If the message is from a local client, forward to server.
479
+ // If the message is from the server, forward back to the correct client.
480
+ //
481
+ // Check if it’s from local or remote by address. This is simplistic:
482
+ const isFromLocal = !_.includes(hostsArr.map(h => h.ipOrDomain), rinfo.address);
483
+ if (isFromLocal) {
484
+ // Received from local => forward to “server” (the VPN server)
485
+ // Keep track of who we got this from (the local client)
486
+ const key = `local-${rinfo.address}:${rinfo.port}`;
487
+ clientMap.set(key, rinfo);
488
+ // Forward to remote
489
+ socket.send(msg, 0, msg.length, targetPort, targetHost, err => {
490
+ if (err) {
491
+ log.er(`UDP client forward error: ${err}`);
492
+ }
493
+ });
494
+ }
495
+ else {
496
+ // Probably from remote => forward back to whichever local client sent it
497
+ // In a more advanced scenario, parse the payload or maintain a bigger table
498
+ // with NAT-like sessions.
499
+ //
500
+ // For now, we guess it’s from the “VPN server”
501
+ // We'll just route it back to the single local client that we stored
502
+ // or do multiple if we had a better NAT map.
503
+ // If you have multi-target or multi-client logic, adapt here.
504
+ // For example, search clientMap by something in the msg or a NAT key.
505
+ clientMap.forEach((localRinfo, key) => {
506
+ socket.send(msg, 0, msg.length, localRinfo.port, localRinfo.address, err => {
507
+ if (err) {
508
+ log.er(`UDP client re-send error: ${err}`);
509
+ }
510
+ });
511
+ });
512
+ }
513
+ });
514
+ socket.on('listening', () => {
515
+ const address = socket.address();
516
+ log.i(`UDP client listening at ${address.address}:${address.port}, forwarding to ${targetHost}:${targetPort}`);
517
+ });
518
+ socket.bind(port);
519
+ }
520
+ //#endregion
521
+ //#region private methods / get port from request
522
+ getPortFromRequest(req) {
523
+ const host = req.headers.host;
524
+ const protocol = req.protocol;
525
+ if (host) {
526
+ const hostParts = host.split(':');
527
+ if (hostParts.length === 2) {
528
+ return Number(hostParts[1]);
529
+ }
530
+ else {
531
+ return protocol === 'https' ? 443 : 80;
532
+ }
533
+ }
534
+ return 80;
535
+ }
536
+ //#endregion
537
+ // Put this method in your VpnSplit class (or outside as a static helper)
538
+ ensureMkcertCertificate(domains) {
539
+ //#region @backendFunc
540
+ // console.log('Domains for cert:', domains);
541
+ // Helpers.error(``,false,true);
542
+ if (!UtilsOs.commandExistsSync('mkcert')) {
543
+ Helpers.error('[vpn-split] mkcert is not installed.', false, true);
544
+ }
545
+ const certPath = this.serveCertPath; // e.g. .../tmp-server_cert
546
+ const keyPath = this.serveKeyPath; // e.g. .../tmp-server_key
547
+ const allNames = [
548
+ 'localhost',
549
+ '127.0.0.1',
550
+ // '::1',
551
+ // optional: common local networks so the cert also works for raw IP access
552
+ // '10.0.0.0/8',
553
+ // '172.16.0.0/12',
554
+ // '192.168.0.0/16',
555
+ ...domains, // <-- your 120+ domains here
556
+ ];
557
+ // Helper: run mkcert and capture output
558
+ const runMkcert = (args) => {
559
+ try {
560
+ return execSync(`mkcert ${args}`, { stdio: 'pipe' }).toString().trim();
561
+ }
562
+ catch (err) {
563
+ const stderr = err.stderr?.toString() || '';
564
+ if (stderr.includes('command not found')) {
565
+ Helpers.error('[vpn-split] mkcert is not installed. Install it first: https://github.com/FiloSottile/mkcert', false, true);
566
+ }
567
+ throw err;
568
+ }
569
+ };
570
+ // 1. Check if the root CA is already installed
571
+ let caInstalled = false;
572
+ try {
573
+ const output = runMkcert('-CAROOT');
574
+ // If -CAROOT succeeds and the root files exist → CA is installed
575
+ const rootDir = crossPlatformPath(output.trim());
576
+ if (rootDir &&
577
+ fse.pathExistsSync(crossPlatformPath([rootDir, 'rootCA.pem']))) {
578
+ Helpers.info('[vpn-split] mkcert local CA is already installed');
579
+ caInstalled = true;
580
+ }
581
+ else {
582
+ Helpers.info('[vpn-split] mkcert local CA is NOT installed');
583
+ }
584
+ }
585
+ catch {
586
+ Helpers.info('[vpn-split] mkcert error checking local CA installation');
587
+ }
588
+ // 2. Install the local CA if needed (requires sudo once)
589
+ if (!caInstalled) {
590
+ Helpers.info('[vpn-split] Installing mkcert local CA (requires sudo once)...');
591
+ try {
592
+ execSync('mkcert -install', { stdio: 'inherit' });
593
+ Helpers.info('[vpn-split] Local CA installed and trusted system-wide');
594
+ }
595
+ catch (err) {
596
+ Helpers.error('[vpn-split] Failed to run "mkcert -install". Run it manually with sudo.', false, true);
597
+ }
598
+ }
599
+ const isWindows = process.platform === 'win32';
600
+ // const maxArgLength = isWindows ? 2000 : 8000; // Conservative limits
601
+ let tempCertFiles = [];
602
+ let tempKeyFiles = [];
603
+ if (allNames.length <= 20 || !isWindows) {
604
+ // Small list or non-Windows: one shot
605
+ const namesArg = allNames.map(d => `"${d}"`).join(' ');
606
+ const mkcertCmd = `-key-file "${keyPath}" -cert-file "${certPath}" ${namesArg}`;
607
+ fse.ensureDirSync(path.dirname(certPath));
608
+ runMkcert(mkcertCmd);
609
+ }
610
+ else {
611
+ // Big list on Windows: Batch into chunks of ~20 domains
612
+ const chunkSize = 20;
613
+ fse.ensureDirSync(path.dirname(certPath));
614
+ for (let i = 0; i < allNames.length; i += chunkSize) {
615
+ const chunk = allNames.slice(i, i + chunkSize);
616
+ const tempCert = `${certPath}.${i}.pem`;
617
+ const tempKey = `${keyPath}.${i}.pem`;
618
+ const namesArg = chunk.map(d => `"${d}"`).join(' ');
619
+ const mkcertCmd = `-key-file "${tempKey}" -cert-file "${tempCert}" ${namesArg}`;
620
+ Helpers.info(`[vpn-split] Generating batch ${Math.floor(i / chunkSize) + 1}/${Math.ceil(allNames.length / chunkSize)}...`);
621
+ runMkcert(mkcertCmd);
622
+ tempCertFiles.push(tempCert);
623
+ tempKeyFiles.push(tempKey);
624
+ }
625
+ // 3. Merge all temp certs into one (cert chain + leaves) and pick first key
626
+ Helpers.info('[vpn-split] Merging batches into final cert...');
627
+ const firstKey = tempKeyFiles[0];
628
+ fse.copySync(firstKey, keyPath); // Use the first key (all are identical)
629
+ // Concat all certs (mkcert output is already PEM-formatted)
630
+ const mergedCertContent = tempCertFiles
631
+ .map(f => fse.readFileSync(f, 'utf8'))
632
+ .join('\n'); // PEM certs stack nicely
633
+ fse.writeFileSync(certPath, mergedCertContent);
634
+ // Clean up temps
635
+ tempCertFiles.forEach(f => fse.removeSync(f));
636
+ tempKeyFiles.slice(1).forEach(f => fse.removeSync(f)); // Keep first key as backup if needed
637
+ Helpers.info('[vpn-split] Merged cert ready!');
638
+ }
639
+ // Verify
640
+ if (!fse.existsSync(certPath) || !fse.existsSync(keyPath)) {
641
+ Helpers.error('[vpn-split] Files missing after generation!', false, true);
642
+ }
643
+ else {
644
+ Helpers.info(`[vpn-split] Trusted cert ready: ${allNames.length} hostnames covered`);
645
+ }
646
+ //#endregion
647
+ }
648
+ //#region private methods / prevent bad target for client
649
+ async preventBadTargetForClient(vpnServerTarget) {
650
+ if (!vpnServerTarget) {
651
+ const currentLocalIp = await UtilsNetwork.getFirstIpV4LocalActiveIpAddress();
652
+ Helpers.error(`[vpn-server] Please provide a correct target server.\n` +
653
+ `Example:\n` +
654
+ `vpn-server ${currentLocalIp}\n\n` +
655
+ `Your local IP is: ${currentLocalIp}`, false, true);
656
+ }
657
+ }
658
+ }
659
+ //#region helper / gen msg
660
+ const genMsg = `
661
+ ################################################
662
+ ## This file is generated #####################
663
+ ################################################
664
+ `.trim() + EOL;
665
+ //#endregion
666
+ //#region helpers / save hosts
667
+ function saveHosts(hosts, options) {
668
+ const { saveHostInUserFolder } = options || {};
669
+ if (_.isArray(hosts)) {
670
+ hosts = hosts.reduce((prev, curr) => {
671
+ return _.merge(prev, {
672
+ [curr.name]: curr,
673
+ });
674
+ }, {});
675
+ }
676
+ const toSave = parseHost(hosts, !!saveHostInUserFolder);
677
+ if (saveHostInUserFolder) {
678
+ Helpers.writeFile(HOST_FILE_PATHUSER, toSave);
679
+ }
680
+ else {
681
+ Helpers.writeFile(HOST_FILE_PATH, toSave);
682
+ }
683
+ }
684
+ function saveHostsLocal(hosts, options) {
685
+ const { saveHostInUserFolder } = options || {};
686
+ if (_.isArray(hosts)) {
687
+ hosts = hosts.reduce((prev, curr) => {
688
+ return _.merge(prev, {
689
+ [curr.name]: curr,
690
+ });
691
+ }, {});
692
+ }
693
+ const toSave = parseHost(hosts, !!saveHostInUserFolder, true);
694
+ if (saveHostInUserFolder) {
695
+ Helpers.writeFile(HOST_FILE_PATHUSER, toSave);
696
+ }
697
+ else {
698
+ Helpers.writeFile(HOST_FILE_PATH, toSave);
699
+ }
700
+ }
701
+ //#endregion
702
+ //#region helpers / parse hosts
703
+ function parseHost(hosts, saveHostInUserFolder, useLocal = false) {
704
+ // hosts = _.merge(hosts, DefaultEtcHosts);
705
+ hosts = {
706
+ ...DefaultEtcHosts,
707
+ ...hosts,
708
+ };
709
+ _.keys(hosts).forEach(hostName => {
710
+ const v = hosts[hostName];
711
+ v.name = hostName;
712
+ });
713
+ return (genMsg +
714
+ EOL +
715
+ _.keys(hosts)
716
+ .map(hostName => {
717
+ const v = hosts[hostName];
718
+ if (v.skipUpdateOfServerEtcHosts) {
719
+ console.warn(`[vpn-split] Skip saving host: ${v.name} (${v.ipOrDomain})`);
720
+ return `# SKIPPING HOST ${v.ipOrDomain} ${v.aliases.join(' ')} ${GENERATED}`; // Skip saving this host
721
+ }
722
+ const aliasesStr = v.aliases.join(' ');
723
+ if (saveHostInUserFolder) {
724
+ // For a user-specific hosts file:
725
+ return useLocal
726
+ ? `127.0.0.1 ${aliasesStr}`
727
+ : `${v.disabled ? '#' : ''}${v.ipOrDomain} ${aliasesStr}`;
728
+ }
729
+ return useLocal
730
+ ? `127.0.0.1 ${aliasesStr}`
731
+ : `${v.disabled ? '#' : ''}${v.ipOrDomain} ${aliasesStr} # ${v.name} ${GENERATED}`;
732
+ })
733
+ .join(EOL) +
734
+ EOL +
735
+ EOL +
736
+ genMsg);
737
+ }
738
+ //#endregion
739
+ //# sourceMappingURL=vpn-split.backend.js.map