pinggy 0.3.5 → 0.3.6

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 (68) hide show
  1. package/README.md +1 -1
  2. package/dist/chunk-65R2GMKQ.js +2101 -0
  3. package/dist/index.cjs +1798 -1349
  4. package/dist/index.d.cts +616 -0
  5. package/dist/index.d.ts +616 -0
  6. package/dist/index.js +24 -2
  7. package/dist/{main-K44C44NW.js → main-2QDG7PWL.js} +166 -1705
  8. package/package.json +3 -4
  9. package/.github/workflows/npm-publish-github-packages.yml +0 -34
  10. package/.github/workflows/publish-binaries.yml +0 -223
  11. package/Makefile +0 -4
  12. package/caxa_build.js +0 -24
  13. package/dist/chunk-T5ESYDJY.js +0 -121
  14. package/ent.plist +0 -14
  15. package/jest.config.js +0 -19
  16. package/src/_tests_/build_config.test.ts +0 -91
  17. package/src/cli/buildConfig.ts +0 -535
  18. package/src/cli/defaults.ts +0 -20
  19. package/src/cli/extendedOptions.ts +0 -153
  20. package/src/cli/help.ts +0 -43
  21. package/src/cli/options.ts +0 -50
  22. package/src/cli/starCli.ts +0 -229
  23. package/src/index.ts +0 -31
  24. package/src/logger.ts +0 -138
  25. package/src/main.ts +0 -87
  26. package/src/remote_management/handler.ts +0 -244
  27. package/src/remote_management/remoteManagement.ts +0 -226
  28. package/src/remote_management/remote_schema.ts +0 -176
  29. package/src/remote_management/websocket_handlers.ts +0 -180
  30. package/src/tui/blessed/TunnelTui.ts +0 -340
  31. package/src/tui/blessed/components/DisplayUpdaters.ts +0 -189
  32. package/src/tui/blessed/components/KeyBindings.ts +0 -236
  33. package/src/tui/blessed/components/Modals.ts +0 -302
  34. package/src/tui/blessed/components/UIComponents.ts +0 -306
  35. package/src/tui/blessed/components/index.ts +0 -4
  36. package/src/tui/blessed/config.ts +0 -53
  37. package/src/tui/blessed/headerFetcher.ts +0 -42
  38. package/src/tui/blessed/index.ts +0 -2
  39. package/src/tui/blessed/qrCodeGenerator.ts +0 -20
  40. package/src/tui/blessed/webDebuggerConnection.ts +0 -128
  41. package/src/tui/ink/asciArt.ts +0 -7
  42. package/src/tui/ink/hooks/useQrCodes.ts +0 -27
  43. package/src/tui/ink/hooks/useReqResHeaders.ts +0 -27
  44. package/src/tui/ink/hooks/useTerminalSize.ts +0 -26
  45. package/src/tui/ink/hooks/useTerminalStats.ts +0 -24
  46. package/src/tui/ink/hooks/useWebDebugger.ts +0 -98
  47. package/src/tui/ink/index.tsx +0 -243
  48. package/src/tui/ink/layout/Borders.tsx +0 -15
  49. package/src/tui/ink/layout/Container.tsx +0 -15
  50. package/src/tui/ink/sections/DebuggerDetailModal.tsx +0 -53
  51. package/src/tui/ink/sections/KeyBindings.tsx +0 -58
  52. package/src/tui/ink/sections/QrCodeSection.tsx +0 -28
  53. package/src/tui/ink/sections/StatsSection.tsx +0 -20
  54. package/src/tui/ink/sections/URLsSection.tsx +0 -53
  55. package/src/tui/ink/utils/utils.ts +0 -35
  56. package/src/tui/spinner/spinner.ts +0 -64
  57. package/src/tunnel_manager/TunnelManager.ts +0 -1212
  58. package/src/types.ts +0 -255
  59. package/src/utils/FileServer.ts +0 -112
  60. package/src/utils/detect_vc_redist_on_windows.ts +0 -111
  61. package/src/utils/getFreePort.ts +0 -41
  62. package/src/utils/htmlTemplates.ts +0 -146
  63. package/src/utils/parseArgs.ts +0 -79
  64. package/src/utils/printer.ts +0 -81
  65. package/src/utils/util.ts +0 -18
  66. package/src/workers/file_serve_worker.ts +0 -33
  67. package/tsconfig.json +0 -17
  68. package/tsup.config.ts +0 -12
@@ -1,975 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ TunnelManager,
4
+ TunnelOperations,
5
+ closeRemoteManagement,
6
+ getRandomId,
7
+ getRemoteManagementState,
8
+ getVersion,
9
+ initiateRemoteManagement,
10
+ isValidPort,
11
+ parseRemoteManagement,
3
12
  printer_default
4
- } from "./chunk-T5ESYDJY.js";
13
+ } from "./chunk-65R2GMKQ.js";
5
14
  import {
6
15
  configureLogger,
7
16
  enablePackageLogging,
8
17
  logger
9
18
  } from "./chunk-HUN2MRZO.js";
10
19
 
11
- // src/tunnel_manager/TunnelManager.ts
12
- import { pinggy } from "@pinggy/pinggy";
13
- import path from "path";
14
- import { Worker } from "worker_threads";
15
- import { fileURLToPath } from "url";
16
-
17
- // src/utils/util.ts
18
- import { createRequire } from "module";
19
- import { randomUUID } from "crypto";
20
- function getRandomId() {
21
- return randomUUID();
22
- }
23
- function isValidPort(p) {
24
- return Number.isInteger(p) && p > 0 && p < 65536;
25
- }
26
- var require2 = createRequire(import.meta.url);
27
- var pkg = require2("../package.json");
28
- function getVersion() {
29
- return pkg.version ?? "";
30
- }
31
-
32
- // src/tunnel_manager/TunnelManager.ts
33
- var __filename2 = fileURLToPath(import.meta.url);
34
- var __dirname2 = path.dirname(__filename2);
35
- var TunnelManager = class _TunnelManager {
36
- constructor() {
37
- this.tunnelsByTunnelId = /* @__PURE__ */ new Map();
38
- this.tunnelsByConfigId = /* @__PURE__ */ new Map();
39
- this.tunnelStats = /* @__PURE__ */ new Map();
40
- this.tunnelStatsListeners = /* @__PURE__ */ new Map();
41
- this.tunnelErrorListeners = /* @__PURE__ */ new Map();
42
- this.tunnelDisconnectListeners = /* @__PURE__ */ new Map();
43
- this.tunnelWorkerErrorListeners = /* @__PURE__ */ new Map();
44
- this.tunnelStartListeners = /* @__PURE__ */ new Map();
45
- }
46
- static getInstance() {
47
- if (!_TunnelManager.instance) {
48
- _TunnelManager.instance = new _TunnelManager();
49
- }
50
- return _TunnelManager.instance;
51
- }
52
- /**
53
- * Creates a new managed tunnel instance with the given configuration.
54
- * Builds the config with forwarding rules and creates the tunnel instance.
55
- *
56
- * @param config - The tunnel configuration options
57
- * @param config.configid - Unique identifier for the tunnel configuration
58
- * @param config.tunnelid - Optional custom tunnel identifier. If not provided, a random UUID will be generated
59
- * @param config.additionalForwarding - Optional array of additional forwarding configurations
60
- *
61
- * @throws {Error} When configId is invalid or empty
62
- * @throws {Error} When a tunnel with the given configId already exists
63
- *
64
- * @returns {ManagedTunnel} A new managed tunnel instance containing the tunnel details,
65
- * status information, and statistics
66
- */
67
- async createTunnel(config) {
68
- const { configid, additionalForwarding, tunnelName } = config;
69
- if (configid === void 0 || configid.trim().length === 0) {
70
- throw new Error(`Invalid configId: "${configid}"`);
71
- }
72
- if (this.tunnelsByConfigId.has(configid)) {
73
- throw new Error(`Tunnel with configId "${configid}" already exists`);
74
- }
75
- const tunnelid = config.tunnelid || getRandomId();
76
- const configWithForwarding = this.buildPinggyConfig(config, additionalForwarding);
77
- return this._createTunnelWithProcessedConfig({
78
- configid,
79
- tunnelid,
80
- tunnelName,
81
- originalConfig: config,
82
- configWithForwarding,
83
- additionalForwarding,
84
- serve: config.serve,
85
- autoReconnect: config.autoReconnect !== void 0 ? config.autoReconnect : false
86
- });
87
- }
88
- /**
89
- * Internal method to create a tunnel with an already-processed configuration.
90
- * This is used by createTunnel, restartTunnel, and updateConfig to avoid config processing.
91
- *
92
- * @param params - Configuration parameters with already-processed forwarding rules
93
- * @returns The created ManagedTunnel instance
94
- * @private
95
- */
96
- async _createTunnelWithProcessedConfig(params) {
97
- let instance;
98
- try {
99
- instance = await pinggy.createTunnel(params.configWithForwarding);
100
- } catch (e) {
101
- logger.error("Error creating tunnel instance:", e);
102
- throw e;
103
- }
104
- const now = (/* @__PURE__ */ new Date()).toISOString();
105
- const managed = {
106
- tunnelid: params.tunnelid,
107
- configid: params.configid,
108
- tunnelName: params.tunnelName,
109
- instance,
110
- tunnelConfig: params.originalConfig,
111
- configWithForwarding: params.configWithForwarding,
112
- additionalForwarding: params.additionalForwarding,
113
- serve: params.serve,
114
- warnings: [],
115
- isStopped: false,
116
- createdAt: now,
117
- startedAt: null,
118
- stoppedAt: null,
119
- autoReconnect: params.autoReconnect
120
- };
121
- instance.setTunnelEstablishedCallback(({}) => {
122
- managed.startedAt = (/* @__PURE__ */ new Date()).toISOString();
123
- });
124
- this.setupStatsCallback(params.tunnelid, managed);
125
- this.setupErrorCallback(params.tunnelid, managed);
126
- this.setupDisconnectCallback(params.tunnelid, managed);
127
- this.setUpTunnelWorkerErrorCallback(params.tunnelid, managed);
128
- this.tunnelsByTunnelId.set(params.tunnelid, managed);
129
- this.tunnelsByConfigId.set(params.configid, managed);
130
- logger.info("Tunnel created", { configid: params.configid, tunnelid: params.tunnelid });
131
- return managed;
132
- }
133
- /**
134
- * Builds the Pinggy configuration by merging the default forwarding rule
135
- * with additional forwarding rules from additionalForwarding array.
136
- *
137
- * @param config - The base Pinggy configuration
138
- * @param additionalForwarding - Optional array of additional forwarding rules
139
- * @returns Modified PinggyOptions
140
- */
141
- buildPinggyConfig(config, additionalForwarding) {
142
- const forwardingRules = [];
143
- if (config.forwarding) {
144
- forwardingRules.push({
145
- type: config.tunnelType && config.tunnelType[0] || "http",
146
- address: config.forwarding
147
- });
148
- }
149
- if (Array.isArray(additionalForwarding) && additionalForwarding.length > 0) {
150
- for (const rule of additionalForwarding) {
151
- if (rule && rule.localDomain && rule.localPort && rule.remoteDomain && isValidPort(rule.localPort)) {
152
- const forwardingRule = {
153
- type: rule.protocol,
154
- // In Future we can make this dynamic based on user input
155
- address: `${rule.localDomain}:${rule.localPort}`,
156
- listenAddress: rule.remotePort && isValidPort(rule.remotePort) ? `${rule.remoteDomain}:${rule.remotePort}` : rule.remoteDomain
157
- };
158
- forwardingRules.push(forwardingRule);
159
- }
160
- }
161
- }
162
- return {
163
- ...config,
164
- forwarding: forwardingRules.length > 0 ? forwardingRules : config.forwarding
165
- };
166
- }
167
- /**
168
- * Start a tunnel that was created but not yet started
169
- */
170
- async startTunnel(tunnelId) {
171
- const managed = this.tunnelsByTunnelId.get(tunnelId);
172
- if (!managed) throw new Error(`Tunnel with id "${tunnelId}" not found`);
173
- logger.info("Starting tunnel", { tunnelId });
174
- let urls;
175
- try {
176
- urls = await managed.instance.start();
177
- } catch (error) {
178
- logger.error("Failed to start tunnel", { tunnelId, error });
179
- throw error;
180
- }
181
- logger.info("Tunnel started", { tunnelId, urls });
182
- if (managed.serve) {
183
- this.startStaticFileServer(managed);
184
- }
185
- try {
186
- const startListeners = this.tunnelStartListeners.get(tunnelId);
187
- if (startListeners) {
188
- for (const [id, listener] of startListeners) {
189
- try {
190
- listener(tunnelId, urls);
191
- } catch (err) {
192
- logger.debug("Error in start-listener callback", { listenerId: id, tunnelId, err });
193
- }
194
- }
195
- }
196
- } catch (e) {
197
- logger.warn("Failed to notify start listeners", { tunnelId, e });
198
- }
199
- return urls;
200
- }
201
- /**
202
- * Stops a running tunnel and updates its status.
203
- *
204
- * @param tunnelId - The unique identifier of the tunnel to stop
205
- * @throws {Error} If the tunnel with the given tunnelId is not found
206
- * @remarks
207
- * - Clears the tunnel's remote URLs
208
- * - Updates the tunnel's state to Exited if stopped successfully
209
- * - Logs the stop operation with tunnelId and configId
210
- */
211
- stopTunnel(tunnelId) {
212
- const managed = this.tunnelsByTunnelId.get(tunnelId);
213
- if (!managed) throw new Error(`Tunnel "${tunnelId}" not found`);
214
- logger.info("Stopping tunnel", { tunnelId, configId: managed.configid });
215
- try {
216
- managed.instance.stop();
217
- if (managed.serveWorker) {
218
- logger.info("terminating serveWorker");
219
- managed.serveWorker.terminate();
220
- }
221
- this.tunnelStats.delete(tunnelId);
222
- this.tunnelStatsListeners.delete(tunnelId);
223
- this.tunnelStats.delete(tunnelId);
224
- this.tunnelStatsListeners.delete(tunnelId);
225
- this.tunnelErrorListeners.delete(tunnelId);
226
- this.tunnelDisconnectListeners.delete(tunnelId);
227
- this.tunnelWorkerErrorListeners.delete(tunnelId);
228
- this.tunnelStartListeners.delete(tunnelId);
229
- managed.serveWorker = null;
230
- managed.warnings = managed.warnings ?? [];
231
- managed.isStopped = true;
232
- managed.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
233
- logger.info("Tunnel stopped", { tunnelId, configId: managed.configid });
234
- return { configid: managed.configid, tunnelid: managed.tunnelid };
235
- } catch (error) {
236
- logger.error("Failed to stop tunnel", { tunnelId, error });
237
- throw error;
238
- }
239
- }
240
- /**
241
- * Get all public URLs for a tunnel
242
- */
243
- async getTunnelUrls(tunnelId) {
244
- try {
245
- const managed = this.tunnelsByTunnelId.get(tunnelId);
246
- if (!managed || managed.isStopped) {
247
- logger.error(`Tunnel "${tunnelId}" not found when fetching URLs`);
248
- return [];
249
- }
250
- const urls = await managed.instance.urls();
251
- logger.debug("Queried tunnel URLs", { tunnelId, urls });
252
- return urls;
253
- } catch (error) {
254
- logger.error("Error fetching tunnel URLs", { tunnelId, error });
255
- throw error;
256
- }
257
- }
258
- /**
259
- * Get all TunnelStatus currently managed by this TunnelManager
260
- * @returns An array of all TunnelStatus objects
261
- */
262
- async getAllTunnels() {
263
- try {
264
- const tunnelList = await Promise.all(Array.from(this.tunnelsByTunnelId.values()).map(async (tunnel) => {
265
- return {
266
- tunnelid: tunnel.tunnelid,
267
- configid: tunnel.configid,
268
- tunnelName: tunnel.tunnelName,
269
- tunnelConfig: tunnel.tunnelConfig,
270
- remoteurls: !tunnel.isStopped ? await this.getTunnelUrls(tunnel.tunnelid) : [],
271
- additionalForwarding: tunnel.additionalForwarding,
272
- serve: tunnel.serve
273
- };
274
- }));
275
- return tunnelList;
276
- } catch (err) {
277
- logger.error("Error fetching tunnels", { error: err });
278
- return [];
279
- }
280
- }
281
- /**
282
- * Get status of a tunnel
283
- */
284
- async getTunnelStatus(tunnelId) {
285
- const managed = this.tunnelsByTunnelId.get(tunnelId);
286
- if (!managed) {
287
- logger.error(`Tunnel "${tunnelId}" not found when fetching status`);
288
- throw new Error(`Tunnel "${tunnelId}" not found`);
289
- }
290
- if (managed.isStopped) {
291
- return "exited";
292
- }
293
- const status = await managed.instance.getStatus();
294
- logger.debug("Queried tunnel status", { tunnelId, status });
295
- return status;
296
- }
297
- /**
298
- * Stop all tunnels
299
- */
300
- stopAllTunnels() {
301
- for (const { instance } of this.tunnelsByTunnelId.values()) {
302
- try {
303
- instance.stop();
304
- } catch (e) {
305
- logger.warn("Error stopping tunnel instance", e);
306
- }
307
- }
308
- this.tunnelsByTunnelId.clear();
309
- this.tunnelsByConfigId.clear();
310
- this.tunnelStats.clear();
311
- this.tunnelStatsListeners.clear();
312
- logger.info("All tunnels stopped and cleared");
313
- }
314
- /**
315
- * Remove a stopped tunnel's records so it will no longer be returned by list methods.
316
- *
317
- *
318
- * @param tunnelId - the tunnel id to remove
319
- * @returns true if the record was removed, false otherwise
320
- */
321
- removeStoppedTunnelByTunnelId(tunnelId) {
322
- const managed = this.tunnelsByTunnelId.get(tunnelId);
323
- if (!managed) {
324
- logger.debug("Attempted to remove non-existent tunnel", { tunnelId });
325
- return false;
326
- }
327
- if (!managed.isStopped) {
328
- logger.warn("Attempted to remove tunnel that is not stopped", { tunnelId });
329
- return false;
330
- }
331
- this._cleanupTunnelRecords(managed);
332
- logger.info("Removed stopped tunnel records", { tunnelId, configId: managed.configid });
333
- return true;
334
- }
335
- /**
336
- * Remove a stopped tunnel by its config id.
337
- * @param configId - the config id to remove
338
- * @returns true if the record was removed, false otherwise
339
- */
340
- removeStoppedTunnelByConfigId(configId) {
341
- const managed = this.tunnelsByConfigId.get(configId);
342
- if (!managed) {
343
- logger.debug("Attempted to remove non-existent tunnel by configId", { configId });
344
- return false;
345
- }
346
- return this.removeStoppedTunnelByTunnelId(managed.tunnelid);
347
- }
348
- _cleanupTunnelRecords(managed) {
349
- if (!managed.isStopped) {
350
- throw new Error(`Active tunnel "${managed.tunnelid}" cannot be removed`);
351
- }
352
- try {
353
- if (managed.serveWorker) {
354
- managed.serveWorker = null;
355
- }
356
- this.tunnelStats.delete(managed.tunnelid);
357
- this.tunnelStatsListeners.delete(managed.tunnelid);
358
- this.tunnelErrorListeners.delete(managed.tunnelid);
359
- this.tunnelDisconnectListeners.delete(managed.tunnelid);
360
- this.tunnelWorkerErrorListeners.delete(managed.tunnelid);
361
- this.tunnelStartListeners.delete(managed.tunnelid);
362
- this.tunnelsByTunnelId.delete(managed.tunnelid);
363
- this.tunnelsByConfigId.delete(managed.configid);
364
- } catch (e) {
365
- logger.warn("Failed cleaning up tunnel records", { tunnelId: managed.tunnelid, error: e });
366
- }
367
- }
368
- /**
369
- * Get tunnel instance by either configId or tunnelId
370
- * @param configId - The configuration ID of the tunnel
371
- * @param tunnelId - The tunnel ID
372
- * @returns The tunnel instance
373
- * @throws Error if neither configId nor tunnelId is provided, or if tunnel is not found
374
- */
375
- getTunnelInstance(configId, tunnelId) {
376
- if (configId) {
377
- const managed = this.tunnelsByConfigId.get(configId);
378
- if (!managed) throw new Error(`Tunnel "${configId}" not found`);
379
- return managed.instance;
380
- }
381
- if (tunnelId) {
382
- const managed = this.tunnelsByTunnelId.get(tunnelId);
383
- if (!managed) throw new Error(`Tunnel "${tunnelId}" not found`);
384
- return managed.instance;
385
- }
386
- throw new Error(`Either configId or tunnelId must be provided`);
387
- }
388
- /**
389
- * Get tunnel config by either configId or tunnelId
390
- * @param configId - The configuration ID of the tunnel
391
- * @param tunnelId - The tunnel ID
392
- * @returns The tunnel config
393
- * @throws Error if neither configId nor tunnelId is provided, or if tunnel is not found
394
- */
395
- async getTunnelConfig(configId, tunnelId) {
396
- if (configId) {
397
- const managed = this.tunnelsByConfigId.get(configId);
398
- if (!managed) {
399
- throw new Error(`Tunnel with configId "${configId}" not found`);
400
- }
401
- return managed.instance.getConfig();
402
- }
403
- if (tunnelId) {
404
- const managed = this.tunnelsByTunnelId.get(tunnelId);
405
- if (!managed) {
406
- throw new Error(`Tunnel with tunnelId "${tunnelId}" not found`);
407
- }
408
- return managed.instance.getConfig();
409
- }
410
- throw new Error(`Either configId or tunnelId must be provided`);
411
- }
412
- /**
413
- * Restarts a tunnel with its current configuration.
414
- * This function will stop the tunnel if it's running and start it again.
415
- * All configurations including additional forwarding rules are preserved.
416
- */
417
- async restartTunnel(tunnelid) {
418
- const existingTunnel = this.tunnelsByTunnelId.get(tunnelid);
419
- if (!existingTunnel) {
420
- throw new Error(`Tunnel "${tunnelid}" not found`);
421
- }
422
- logger.info("Initiating tunnel restart", {
423
- tunnelId: tunnelid,
424
- configId: existingTunnel.configid
425
- });
426
- try {
427
- const tunnelName = existingTunnel.tunnelName;
428
- const currentConfigId = existingTunnel.configid;
429
- const currentConfig = existingTunnel.tunnelConfig;
430
- const configWithForwarding = existingTunnel.configWithForwarding;
431
- const additionalForwarding = existingTunnel.additionalForwarding;
432
- const currentServe = existingTunnel.serve;
433
- const autoReconnect = existingTunnel.autoReconnect || false;
434
- this.tunnelsByTunnelId.delete(tunnelid);
435
- this.tunnelsByConfigId.delete(existingTunnel.configid);
436
- this.tunnelStats.delete(tunnelid);
437
- this.tunnelStatsListeners.delete(tunnelid);
438
- this.tunnelErrorListeners.delete(tunnelid);
439
- this.tunnelDisconnectListeners.delete(tunnelid);
440
- this.tunnelWorkerErrorListeners.delete(tunnelid);
441
- this.tunnelStartListeners.delete(tunnelid);
442
- const newTunnel = await this._createTunnelWithProcessedConfig({
443
- configid: currentConfigId,
444
- tunnelid,
445
- tunnelName,
446
- originalConfig: currentConfig,
447
- configWithForwarding,
448
- additionalForwarding,
449
- serve: currentServe,
450
- autoReconnect
451
- });
452
- if (existingTunnel.createdAt) {
453
- newTunnel.createdAt = existingTunnel.createdAt;
454
- }
455
- await this.startTunnel(newTunnel.tunnelid);
456
- } catch (error) {
457
- logger.error("Failed to restart tunnel", {
458
- tunnelid,
459
- error: error instanceof Error ? error.message : "Unknown error"
460
- });
461
- throw new Error(`Failed to restart tunnel: ${error instanceof Error ? error.message : "Unknown error"}`);
462
- }
463
- }
464
- /**
465
- * Updates the configuration of an existing tunnel.
466
- *
467
- * This method handles the process of updating a tunnel's configuration while preserving
468
- * its state. If the tunnel is running, it will be stopped, updated, and restarted.
469
- * In case of failure, it attempts to restore the original configuration.
470
- *
471
- * @param newConfig - The new configuration to apply, including configid and optional additional forwarding
472
- *
473
- * @returns Promise resolving to the updated ManagedTunnel
474
- * @throws Error if the tunnel is not found or if the update process fails
475
- */
476
- async updateConfig(newConfig) {
477
- const { configid, tunnelName: newTunnelName, additionalForwarding } = newConfig;
478
- if (!configid || configid.trim().length === 0) {
479
- throw new Error(`Invalid configid: "${configid}"`);
480
- }
481
- const existingTunnel = this.tunnelsByConfigId.get(configid);
482
- if (!existingTunnel) {
483
- throw new Error(`Tunnel with config id "${configid}" not found`);
484
- }
485
- const isStopped = existingTunnel.isStopped;
486
- const currentTunnelConfig = existingTunnel.tunnelConfig;
487
- const currentConfigWithForwarding = existingTunnel.configWithForwarding;
488
- const currentTunnelId = existingTunnel.tunnelid;
489
- const currentTunnelConfigId = existingTunnel.configid;
490
- const currentAdditionalForwarding = existingTunnel.additionalForwarding;
491
- const currentTunnelName = existingTunnel.tunnelName;
492
- const currentServe = existingTunnel.serve;
493
- const currentAutoReconnect = existingTunnel.autoReconnect || false;
494
- try {
495
- if (!isStopped) {
496
- existingTunnel.instance.stop();
497
- }
498
- this.tunnelsByTunnelId.delete(currentTunnelId);
499
- this.tunnelsByConfigId.delete(currentTunnelConfigId);
500
- const mergedBaseConfig = {
501
- ...newConfig,
502
- configid,
503
- tunnelName: newTunnelName !== void 0 ? newTunnelName : currentTunnelName,
504
- serve: newConfig.serve !== void 0 ? newConfig.serve : currentServe
505
- };
506
- const newConfigWithForwarding = this.buildPinggyConfig(
507
- mergedBaseConfig,
508
- additionalForwarding !== void 0 ? additionalForwarding : currentAdditionalForwarding
509
- );
510
- const newTunnel = await this._createTunnelWithProcessedConfig({
511
- configid,
512
- tunnelid: currentTunnelId,
513
- tunnelName: newTunnelName !== void 0 ? newTunnelName : currentTunnelName,
514
- originalConfig: mergedBaseConfig,
515
- configWithForwarding: newConfigWithForwarding,
516
- additionalForwarding: additionalForwarding !== void 0 ? additionalForwarding : currentAdditionalForwarding,
517
- serve: newConfig.serve !== void 0 ? newConfig.serve : currentServe,
518
- autoReconnect: currentAutoReconnect
519
- });
520
- if (!isStopped) {
521
- await this.startTunnel(newTunnel.tunnelid);
522
- }
523
- logger.info("Tunnel configuration updated", {
524
- tunnelId: newTunnel.tunnelid,
525
- configId: newTunnel.configid,
526
- isStopped
527
- });
528
- return newTunnel;
529
- } catch (error) {
530
- logger.error("Error updating tunnel configuration", {
531
- configId: configid,
532
- error: error instanceof Error ? error.message : String(error)
533
- });
534
- try {
535
- const originalTunnel = await this._createTunnelWithProcessedConfig({
536
- configid: currentTunnelConfigId,
537
- tunnelid: currentTunnelId,
538
- tunnelName: currentTunnelName,
539
- originalConfig: currentTunnelConfig,
540
- configWithForwarding: currentConfigWithForwarding,
541
- additionalForwarding: currentAdditionalForwarding,
542
- serve: currentServe,
543
- autoReconnect: currentAutoReconnect
544
- });
545
- if (!isStopped) {
546
- await this.startTunnel(originalTunnel.tunnelid);
547
- }
548
- logger.warn("Restored original tunnel configuration after update failure", {
549
- currentTunnelId,
550
- error: error instanceof Error ? error.message : "Unknown error"
551
- });
552
- } catch (restoreError) {
553
- logger.error("Failed to restore original tunnel configuration", {
554
- currentTunnelId,
555
- error: restoreError instanceof Error ? restoreError.message : "Unknown error"
556
- });
557
- }
558
- throw error;
559
- }
560
- }
561
- /**
562
- * Retrieve the ManagedTunnel object by either configId or tunnelId.
563
- * Throws an error if neither id is provided or the tunnel is not found.
564
- */
565
- getManagedTunnel(configId, tunnelId) {
566
- if (configId) {
567
- const managed = this.tunnelsByConfigId.get(configId);
568
- if (!managed) throw new Error(`Tunnel "${configId}" not found`);
569
- return managed;
570
- }
571
- if (tunnelId) {
572
- const managed = this.tunnelsByTunnelId.get(tunnelId);
573
- if (!managed) throw new Error(`Tunnel "${tunnelId}" not found`);
574
- return managed;
575
- }
576
- throw new Error(`Either configId or tunnelId must be provided`);
577
- }
578
- async getTunnelGreetMessage(tunnelId) {
579
- const managed = this.tunnelsByTunnelId.get(tunnelId);
580
- if (!managed) {
581
- logger.error(`Tunnel "${tunnelId}" not found when fetching greet message`);
582
- return null;
583
- }
584
- try {
585
- if (managed.isStopped) {
586
- return null;
587
- }
588
- const messages = await managed.instance.getGreetMessage();
589
- if (Array.isArray(messages)) {
590
- return messages.join(" ");
591
- }
592
- return messages ?? null;
593
- } catch (e) {
594
- logger.error(
595
- `Error fetching greet message for tunnel "${tunnelId}": ${e instanceof Error ? e.message : String(e)}`
596
- );
597
- return null;
598
- }
599
- }
600
- getTunnelStats(tunnelId) {
601
- const managed = this.tunnelsByTunnelId.get(tunnelId);
602
- if (!managed) {
603
- return null;
604
- }
605
- const stats = this.tunnelStats.get(tunnelId);
606
- return stats || null;
607
- }
608
- getLatestTunnelStats(tunnelId) {
609
- const managed = this.tunnelsByTunnelId.get(tunnelId);
610
- if (!managed) {
611
- return null;
612
- }
613
- const stats = this.tunnelStats.get(tunnelId);
614
- if (stats && stats.length > 0) {
615
- return stats[stats.length - 1];
616
- }
617
- return null;
618
- }
619
- /**
620
- * Registers a listener function to receive tunnel statistics updates.
621
- * The listener will be called whenever any tunnel's stats are updated.
622
- *
623
- * @param tunnelId - The tunnel ID to listen to stats for
624
- * @param listener - Function that receives tunnelId and stats when updates occur
625
- * @returns A unique listener ID that can be used to deregister the listener and tunnelId
626
- *
627
- * @throws {Error} When the specified tunnelId does not exist
628
- */
629
- async registerStatsListener(tunnelId, listener) {
630
- const managed = this.tunnelsByTunnelId.get(tunnelId);
631
- if (!managed) {
632
- throw new Error(`Tunnel "${tunnelId}" not found`);
633
- }
634
- if (!this.tunnelStatsListeners.has(tunnelId)) {
635
- this.tunnelStatsListeners.set(tunnelId, /* @__PURE__ */ new Map());
636
- }
637
- const listenerId = getRandomId();
638
- const tunnelListeners = this.tunnelStatsListeners.get(tunnelId);
639
- tunnelListeners.set(listenerId, listener);
640
- logger.info("Stats listener registered for tunnel", { tunnelId, listenerId });
641
- return [listenerId, tunnelId];
642
- }
643
- async registerErrorListener(tunnelId, listener) {
644
- const managed = this.tunnelsByTunnelId.get(tunnelId);
645
- if (!managed) {
646
- throw new Error(`Tunnel "${tunnelId}" not found`);
647
- }
648
- if (!this.tunnelErrorListeners.has(tunnelId)) {
649
- this.tunnelErrorListeners.set(tunnelId, /* @__PURE__ */ new Map());
650
- }
651
- const listenerId = getRandomId();
652
- const tunnelErrorListeners = this.tunnelErrorListeners.get(tunnelId);
653
- tunnelErrorListeners.set(listenerId, listener);
654
- logger.info("Error listener registered for tunnel", { tunnelId, listenerId });
655
- return listenerId;
656
- }
657
- async registerDisconnectListener(tunnelId, listener) {
658
- const managed = this.tunnelsByTunnelId.get(tunnelId);
659
- if (!managed) {
660
- throw new Error(`Tunnel "${tunnelId}" not found`);
661
- }
662
- if (!this.tunnelDisconnectListeners.has(tunnelId)) {
663
- this.tunnelDisconnectListeners.set(tunnelId, /* @__PURE__ */ new Map());
664
- }
665
- const listenerId = getRandomId();
666
- const tunnelDisconnectListeners = this.tunnelDisconnectListeners.get(tunnelId);
667
- tunnelDisconnectListeners.set(listenerId, listener);
668
- logger.info("Disconnect listener registered for tunnel", { tunnelId, listenerId });
669
- return listenerId;
670
- }
671
- async registerWorkerErrorListner(tunnelId, listener) {
672
- const managed = this.tunnelsByTunnelId.get(tunnelId);
673
- if (!managed) {
674
- throw new Error(`Tunnel "${tunnelId}" not found`);
675
- }
676
- if (!this.tunnelWorkerErrorListeners.has(tunnelId)) {
677
- this.tunnelWorkerErrorListeners.set(tunnelId, /* @__PURE__ */ new Map());
678
- }
679
- const listenerId = getRandomId();
680
- const tunnelWorkerErrorListner = this.tunnelWorkerErrorListeners.get(tunnelId);
681
- tunnelWorkerErrorListner?.set(listenerId, listener);
682
- logger.info("TunnelWorker error listener registered for tunnel", { tunnelId, listenerId });
683
- }
684
- async registerStartListener(tunnelId, listener) {
685
- const managed = this.tunnelsByTunnelId.get(tunnelId);
686
- if (!managed) {
687
- throw new Error(`Tunnel "${tunnelId}" not found`);
688
- }
689
- if (!this.tunnelStartListeners.has(tunnelId)) {
690
- this.tunnelStartListeners.set(tunnelId, /* @__PURE__ */ new Map());
691
- }
692
- const listenerId = getRandomId();
693
- const listeners = this.tunnelStartListeners.get(tunnelId);
694
- listeners.set(listenerId, listener);
695
- logger.info("Start listener registered for tunnel", { tunnelId, listenerId });
696
- return listenerId;
697
- }
698
- /**
699
- * Removes a previously registered stats listener.
700
- *
701
- * @param tunnelId - The tunnel ID the listener was registered for
702
- * @param listenerId - The unique ID returned when the listener was registered
703
- */
704
- deregisterStatsListener(tunnelId, listenerId) {
705
- const tunnelListeners = this.tunnelStatsListeners.get(tunnelId);
706
- if (!tunnelListeners) {
707
- logger.warn("No listeners found for tunnel", { tunnelId });
708
- return;
709
- }
710
- const removed = tunnelListeners.delete(listenerId);
711
- if (removed) {
712
- logger.info("Stats listener deregistered", { tunnelId, listenerId });
713
- if (tunnelListeners.size === 0) {
714
- this.tunnelStatsListeners.delete(tunnelId);
715
- }
716
- } else {
717
- logger.warn("Attempted to deregister non-existent stats listener", { tunnelId, listenerId });
718
- }
719
- }
720
- deregisterErrorListener(tunnelId, listenerId) {
721
- const listeners = this.tunnelErrorListeners.get(tunnelId);
722
- if (!listeners) {
723
- logger.warn("No error listeners found for tunnel", { tunnelId });
724
- return;
725
- }
726
- const removed = listeners.delete(listenerId);
727
- if (removed) {
728
- logger.info("Error listener deregistered", { tunnelId, listenerId });
729
- if (listeners.size === 0) {
730
- this.tunnelErrorListeners.delete(tunnelId);
731
- }
732
- } else {
733
- logger.warn("Attempted to deregister non-existent error listener", { tunnelId, listenerId });
734
- }
735
- }
736
- deregisterDisconnectListener(tunnelId, listenerId) {
737
- const listeners = this.tunnelDisconnectListeners.get(tunnelId);
738
- if (!listeners) {
739
- logger.warn("No disconnect listeners found for tunnel", { tunnelId });
740
- return;
741
- }
742
- const removed = listeners.delete(listenerId);
743
- if (removed) {
744
- logger.info("Disconnect listener deregistered", { tunnelId, listenerId });
745
- if (listeners.size === 0) {
746
- this.tunnelDisconnectListeners.delete(tunnelId);
747
- }
748
- } else {
749
- logger.warn("Attempted to deregister non-existent disconnect listener", { tunnelId, listenerId });
750
- }
751
- }
752
- async getLocalserverTlsInfo(tunnelId) {
753
- const managed = this.tunnelsByTunnelId.get(tunnelId);
754
- if (!managed) {
755
- logger.error(`Tunnel "${tunnelId}" not found when fetching local server TLS info`);
756
- return false;
757
- }
758
- try {
759
- if (managed.isStopped) {
760
- return false;
761
- }
762
- const tlsInfo = await managed.instance.getLocalServerTls();
763
- if (tlsInfo) {
764
- return tlsInfo;
765
- }
766
- return false;
767
- } catch (e) {
768
- logger.error(`Error fetching TLS info for tunnel "${tunnelId}": ${e instanceof Error ? e.message : e}`);
769
- return false;
770
- }
771
- }
772
- /**
773
- * Sets up the stats callback for a tunnel during creation.
774
- * This callback will update stored stats and notify all registered listeners.
775
- */
776
- setupStatsCallback(tunnelId, managed) {
777
- try {
778
- const callback = (usage) => {
779
- this.updateStats(tunnelId, usage);
780
- };
781
- managed.instance.setUsageUpdateCallback(callback);
782
- logger.debug("Stats callback set up for tunnel", { tunnelId });
783
- } catch (error) {
784
- logger.warn("Failed to set up stats callback", { tunnelId, error });
785
- }
786
- }
787
- notifyErrorListeners(tunnelId, errorMsg, isFatal) {
788
- try {
789
- const listeners = this.tunnelErrorListeners.get(tunnelId);
790
- if (!listeners) return;
791
- for (const [id, listener] of listeners) {
792
- try {
793
- listener(tunnelId, errorMsg, isFatal);
794
- } catch (err) {
795
- logger.debug("Error in error-listener callback", { listenerId: id, tunnelId, err });
796
- }
797
- }
798
- } catch (err) {
799
- logger.debug("Failed to notify error listeners", { tunnelId, err });
800
- }
801
- }
802
- setupErrorCallback(tunnelId, managed) {
803
- try {
804
- const callback = ({ errorNo, error, recoverable }) => {
805
- try {
806
- const msg = typeof error === "string" ? error : String(error);
807
- const isFatal = true;
808
- logger.debug("Tunnel reported error", { tunnelId, errorNo, errorMsg: msg, recoverable });
809
- this.notifyErrorListeners(tunnelId, msg, isFatal);
810
- } catch (e) {
811
- logger.warn("Error handling tunnel error callback", { tunnelId, e });
812
- }
813
- };
814
- managed.instance.setTunnelErrorCallback(callback);
815
- logger.debug("Error callback set up for tunnel", { tunnelId });
816
- } catch (error) {
817
- logger.warn("Failed to set up error callback", { tunnelId, error });
818
- }
819
- }
820
- setupDisconnectCallback(tunnelId, managed) {
821
- try {
822
- const callback = ({ error, messages }) => {
823
- try {
824
- logger.debug("Tunnel disconnected", { tunnelId, error, messages });
825
- const managedTunnel = this.tunnelsByTunnelId.get(tunnelId);
826
- if (managedTunnel) {
827
- managedTunnel.isStopped = true;
828
- managedTunnel.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
829
- }
830
- if (managedTunnel && managedTunnel.autoReconnect) {
831
- logger.info("Auto-reconnecting tunnel", { tunnelId });
832
- setTimeout(async () => {
833
- try {
834
- await this.restartTunnel(tunnelId);
835
- logger.info("Tunnel auto-reconnected successfully", { tunnelId });
836
- } catch (e) {
837
- logger.error("Failed to auto-reconnect tunnel", { tunnelId, e });
838
- }
839
- }, 1e4);
840
- }
841
- const listeners = this.tunnelDisconnectListeners.get(tunnelId);
842
- if (!listeners) return;
843
- for (const [id, listener] of listeners) {
844
- try {
845
- listener(tunnelId, error, messages);
846
- } catch (err) {
847
- logger.debug("Error in disconnect-listener callback", { listenerId: id, tunnelId, err });
848
- }
849
- }
850
- } catch (e) {
851
- logger.warn("Error handling tunnel disconnect callback", { tunnelId, e });
852
- }
853
- };
854
- managed.instance.setTunnelDisconnectedCallback(callback);
855
- logger.debug("Disconnect callback set up for tunnel", { tunnelId });
856
- } catch (error) {
857
- logger.warn("Failed to set up disconnect callback", { tunnelId, error });
858
- }
859
- }
860
- setUpTunnelWorkerErrorCallback(tunnelId, managed) {
861
- try {
862
- const callback = (error) => {
863
- try {
864
- logger.debug("Error in Tunnel Worker", { tunnelId, errorMessage: error.message });
865
- const listeners = this.tunnelWorkerErrorListeners.get(tunnelId);
866
- if (!listeners) return;
867
- for (const [id, listener] of listeners) {
868
- try {
869
- listener(tunnelId, error);
870
- } catch (err) {
871
- logger.debug("Error in worker-error-listener callback", { listenerId: id, tunnelId, err });
872
- }
873
- }
874
- } catch (e) {
875
- logger.warn("Error handling tunnel worker error callback", { tunnelId, e });
876
- }
877
- };
878
- managed.instance.setWorkerErrorCallback(callback);
879
- logger.debug("Disconnect callback set up for tunnel", { tunnelId });
880
- } catch (error) {
881
- logger.warn("Failed to setup tunnel worker error callback");
882
- }
883
- }
884
- /**
885
- * Updates the stored stats for a tunnel and notifies all registered listeners.
886
- */
887
- updateStats(tunnelId, rawUsage) {
888
- try {
889
- const normalizedStats = this.normalizeStats(rawUsage);
890
- const existingStats = this.tunnelStats.get(tunnelId) || [];
891
- const updatedStats = [...existingStats, normalizedStats];
892
- this.tunnelStats.set(tunnelId, updatedStats);
893
- const tunnelListeners = this.tunnelStatsListeners.get(tunnelId);
894
- if (tunnelListeners) {
895
- for (const [listenerId, listener] of tunnelListeners) {
896
- try {
897
- listener(tunnelId, normalizedStats);
898
- } catch (error) {
899
- logger.warn("Error in stats listener callback", { listenerId, tunnelId, error });
900
- }
901
- }
902
- }
903
- logger.debug("Stats updated and listeners notified", {
904
- tunnelId,
905
- listenersCount: tunnelListeners?.size || 0
906
- });
907
- } catch (error) {
908
- logger.warn("Error updating stats", { tunnelId, error });
909
- }
910
- }
911
- /**
912
- * Normalizes raw usage data from the SDK into a consistent TunnelStats format.
913
- */
914
- normalizeStats(rawStats) {
915
- const elapsed = this.parseNumber(rawStats.elapsedTime ?? 0);
916
- const liveConns = this.parseNumber(rawStats.numLiveConnections ?? 0);
917
- const totalConns = this.parseNumber(rawStats.numTotalConnections ?? 0);
918
- const reqBytes = this.parseNumber(rawStats.numTotalReqBytes ?? 0);
919
- const resBytes = this.parseNumber(rawStats.numTotalResBytes ?? 0);
920
- const txBytes = this.parseNumber(rawStats.numTotalTxBytes ?? 0);
921
- return {
922
- elapsedTime: elapsed,
923
- numLiveConnections: liveConns,
924
- numTotalConnections: totalConns,
925
- numTotalReqBytes: reqBytes,
926
- numTotalResBytes: resBytes,
927
- numTotalTxBytes: txBytes
928
- };
929
- }
930
- parseNumber(value) {
931
- const parsed = typeof value === "number" ? value : parseInt(String(value), 10);
932
- return isNaN(parsed) ? 0 : parsed;
933
- }
934
- startStaticFileServer(managed) {
935
- try {
936
- const __filename3 = fileURLToPath(import.meta.url);
937
- const __dirname3 = path.dirname(__filename3);
938
- const fileServerWorkerPath = path.join(__dirname3, "workers", "file_serve_worker.cjs");
939
- const staticServerWorker = new Worker(fileServerWorkerPath, {
940
- workerData: {
941
- dir: managed.serve,
942
- port: managed.tunnelConfig?.forwarding
943
- }
944
- });
945
- staticServerWorker.on("message", (msg) => {
946
- switch (msg.type) {
947
- case "started":
948
- logger.info("Static file server started", { dir: managed.serve });
949
- break;
950
- case "warning":
951
- if (msg.code === "INVALID_TUNNEL_SERVE_PATH") {
952
- managed.warnings = managed.warnings ?? [];
953
- managed.warnings.push({ code: msg.code, message: msg.message });
954
- }
955
- printer_default.warn(msg.message);
956
- break;
957
- case "error":
958
- managed.warnings = managed.warnings ?? [];
959
- managed.warnings.push({
960
- code: "UNKNOWN_WARNING",
961
- message: msg.message
962
- });
963
- break;
964
- }
965
- });
966
- managed.serveWorker = staticServerWorker;
967
- } catch (error) {
968
- logger.error("Error starting static file server", error);
969
- }
970
- }
971
- };
972
-
973
20
  // src/cli/options.ts
974
21
  var cliOptions = {
975
22
  // SSH-like options
@@ -995,7 +42,7 @@ var cliOptions = {
995
42
  v: { type: "boolean", description: "Print logs to stdout for Cli. Overrides PINGGY_LOG_STDOUT environment variable" },
996
43
  vv: { type: "boolean", description: "Enable detailed logging for the Node.js SDK and Libpinggy, including both info and debug level logs." },
997
44
  vvv: { type: "boolean", description: "Enable all logs from Cli, SDK and internal components." },
998
- autoreconnect: { type: "string", short: "a", description: "Automatically reconnect tunnel on failure. Use -a (defaults to true), -a true, or -a false." },
45
+ autoreconnect: { type: "string", short: "a", description: "Automatically reconnect tunnel on failure (enabled by default). Use -a false to disable." },
999
46
  // Save and load config
1000
47
  saveconf: { type: "string", description: "Create the configuration file based on the options provided here" },
1001
48
  conf: { type: "string", description: "Use the configuration file as base. Other options will be used to override this file" },
@@ -1195,16 +242,16 @@ function isValidIpV6Cidr(input) {
1195
242
  }
1196
243
 
1197
244
  // src/cli/buildConfig.ts
1198
- import { TunnelType as TunnelType2 } from "@pinggy/pinggy";
245
+ import { TunnelType } from "@pinggy/pinggy";
1199
246
  import fs from "fs";
1200
- import path2 from "path";
247
+ import path from "path";
1201
248
  var domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
1202
249
  var KEYWORDS = /* @__PURE__ */ new Set([
1203
- TunnelType2.Http,
1204
- TunnelType2.Tcp,
1205
- TunnelType2.Tls,
1206
- TunnelType2.Udp,
1207
- TunnelType2.TlsTcp,
250
+ TunnelType.Http,
251
+ TunnelType.Tcp,
252
+ TunnelType.Tls,
253
+ TunnelType.Udp,
254
+ TunnelType.TlsTcp,
1208
255
  "force",
1209
256
  "qr"
1210
257
  ]);
@@ -1222,7 +269,7 @@ function parseUserAndDomain(str) {
1222
269
  const [user, domain] = str.split("@", 2);
1223
270
  if (domainRegex.test(domain)) {
1224
271
  let processKeyword2 = function(keyword) {
1225
- if ([TunnelType2.Http, TunnelType2.Tcp, TunnelType2.Tls, TunnelType2.Udp, TunnelType2.TlsTcp].includes(keyword)) {
272
+ if ([TunnelType.Http, TunnelType.Tcp, TunnelType.Tls, TunnelType.Udp, TunnelType.TlsTcp].includes(keyword)) {
1226
273
  type = keyword;
1227
274
  } else if (keyword === "force") {
1228
275
  forceFlag = true;
@@ -1292,7 +339,7 @@ function parseUsers(positionalArgs, explicitToken) {
1292
339
  }
1293
340
  function parseType(finalConfig, values, inferredType) {
1294
341
  const t = inferredType || values.type || finalConfig.tunnelType;
1295
- if (t === TunnelType2.Http || t === TunnelType2.Tcp || t === TunnelType2.Tls || t === TunnelType2.Udp || t === TunnelType2.TlsTcp) {
342
+ if (t === TunnelType.Http || t === TunnelType.Tcp || t === TunnelType.Tls || t === TunnelType.Udp || t === TunnelType.TlsTcp) {
1296
343
  finalConfig.tunnelType = [t];
1297
344
  }
1298
345
  }
@@ -1499,10 +546,10 @@ function parseArgs(finalConfig, remainingPositionals) {
1499
546
  }
1500
547
  function storeJson(config, saveconf) {
1501
548
  if (saveconf) {
1502
- const path3 = saveconf;
549
+ const path2 = saveconf;
1503
550
  try {
1504
- fs.writeFileSync(path3, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
1505
- logger.info(`Configuration saved to ${path3}`);
551
+ fs.writeFileSync(path2, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
552
+ logger.info(`Configuration saved to ${path2}`);
1506
553
  } catch (err) {
1507
554
  const msg = err instanceof Error ? err.message : String(err);
1508
555
  logger.error("Error loading configuration:", msg);
@@ -1512,7 +559,7 @@ function storeJson(config, saveconf) {
1512
559
  function loadJsonConfig(config) {
1513
560
  const configpath = config["conf"];
1514
561
  if (typeof configpath === "string" && configpath.trim().length > 0) {
1515
- const filepath = path2.resolve(configpath);
562
+ const filepath = path.resolve(configpath);
1516
563
  try {
1517
564
  const data = fs.readFileSync(filepath, { encoding: "utf-8" });
1518
565
  const json = JSON.parse(data);
@@ -1574,7 +621,7 @@ async function buildFinalConfig(values, positionals) {
1574
621
  configid: getRandomId(),
1575
622
  token: token || (configFromFile?.token || (typeof values.token === "string" ? values.token : "")),
1576
623
  serverAddress: server || (configFromFile?.serverAddress || defaultOptions.serverAddress),
1577
- tunnelType: initialTunnel ? [initialTunnel] : configFromFile?.tunnelType || [TunnelType2.Http],
624
+ tunnelType: initialTunnel ? [initialTunnel] : configFromFile?.tunnelType || [TunnelType.Http],
1578
625
  NoTUI: values.notui || (configFromFile?.NoTUI || false),
1579
626
  qrCode: qrCode || (configFromFile?.qrCode || false),
1580
627
  autoReconnect: configFromFile?.autoReconnect ? configFromFile.autoReconnect : defaultOptions.autoReconnect
@@ -1599,727 +646,6 @@ async function buildFinalConfig(values, positionals) {
1599
646
  return finalConfig;
1600
647
  }
1601
648
 
1602
- // src/remote_management/remoteManagement.ts
1603
- import WebSocket from "ws";
1604
-
1605
- // src/types.ts
1606
- var ErrorCode = {
1607
- InvalidRequestMethodError: "INVALID_REQUEST_METHOD",
1608
- InvalidRequestBodyError: "COULD_NOT_READ_BODY",
1609
- InternalServerError: "INTERNAL_SERVER_ERROR",
1610
- InvalidBodyFormatError: "INVALID_DATA_FORMAT",
1611
- ErrorStartingTunnel: "ERROR_STARTING_TUNNEL",
1612
- TunnelNotFound: "TUNNEL_WITH_ID_OR_CONFIG_ID_NOT_FOUND",
1613
- TunnelAlreadyRunningError: "TUNNEL_WITH_ID_OR_CONFIG_ID_ALREADY_RUNNING",
1614
- WebsocketUpgradeFailError: "WEBSOCKET_UPGRADE_FAILED",
1615
- RemoteManagementAlreadyRunning: "REMOTE_MANAGEMENT_ALREADY_RUNNING",
1616
- RemoteManagementNotRunning: "REMOTE_MANAGEMENT_NOT_RUNNING",
1617
- RemoteManagementDeserializationFailed: "REMOTE_MANAGEMENT_DESERIALIZATION_FAILED"
1618
- };
1619
- function isErrorResponse(obj) {
1620
- return typeof obj === "object" && obj !== null && "code" in obj && "message" in obj && typeof obj.message === "string" && Object.values(ErrorCode).includes(obj.code);
1621
- }
1622
- function newErrorResponse(codeOrError, message) {
1623
- if (typeof codeOrError === "object") {
1624
- return codeOrError;
1625
- }
1626
- return {
1627
- code: codeOrError,
1628
- message
1629
- };
1630
- }
1631
- function NewResponseObject(data) {
1632
- const encoder = new TextEncoder();
1633
- const bytes = encoder.encode(JSON.stringify(data));
1634
- return {
1635
- response: bytes,
1636
- requestid: "",
1637
- command: "",
1638
- error: false,
1639
- errorresponse: {}
1640
- };
1641
- }
1642
- function NewErrorResponseObject(errorResponse) {
1643
- return {
1644
- response: new Uint8Array(),
1645
- requestid: "",
1646
- command: "",
1647
- error: true,
1648
- errorresponse: errorResponse
1649
- };
1650
- }
1651
- function newStatus(tunnelState, errorCode, errorMsg) {
1652
- let assignedState = tunnelState;
1653
- if (tunnelState === "live" /* Live */) {
1654
- assignedState = "running" /* Running */;
1655
- } else if (tunnelState === "idle" /* New */) {
1656
- assignedState = "idle" /* New */;
1657
- } else if (tunnelState === "closed" /* Closed */) {
1658
- assignedState = "exited" /* Exited */;
1659
- }
1660
- const now = (/* @__PURE__ */ new Date()).toISOString();
1661
- return {
1662
- state: assignedState,
1663
- errorcode: errorCode,
1664
- errormsg: errorMsg,
1665
- createdtimestamp: now,
1666
- starttimestamp: now,
1667
- endtimestamp: now,
1668
- warnings: []
1669
- };
1670
- }
1671
- function newStats() {
1672
- return {
1673
- numLiveConnections: 0,
1674
- numTotalConnections: 0,
1675
- numTotalReqBytes: 0,
1676
- numTotalResBytes: 0,
1677
- numTotalTxBytes: 0,
1678
- elapsedTime: 0
1679
- };
1680
- }
1681
- var RemoteManagementStatus = {
1682
- Connecting: "CONNECTING",
1683
- Disconnecting: "DISCONNECTING",
1684
- Reconnecting: "RECONNECTING",
1685
- Running: "RUNNING",
1686
- NotRunning: "NOT_RUNNING",
1687
- Error: "ERROR"
1688
- };
1689
-
1690
- // src/remote_management/remote_schema.ts
1691
- import { TunnelType as TunnelType3 } from "@pinggy/pinggy";
1692
- import { z } from "zod";
1693
- var HeaderModificationSchema = z.object({
1694
- key: z.string(),
1695
- value: z.array(z.string()).optional(),
1696
- type: z.enum(["add", "remove", "update"])
1697
- });
1698
- var AdditionalForwardingSchema = z.object({
1699
- remoteDomain: z.string().optional(),
1700
- remotePort: z.number().optional(),
1701
- localDomain: z.string(),
1702
- localPort: z.number()
1703
- });
1704
- var TunnelConfigSchema = z.object({
1705
- allowPreflight: z.boolean().optional(),
1706
- // primary key
1707
- allowpreflight: z.boolean().optional(),
1708
- // legacy key
1709
- autoreconnect: z.boolean(),
1710
- basicauth: z.array(z.object({ username: z.string(), password: z.string() })).nullable(),
1711
- bearerauth: z.string().nullable(),
1712
- configid: z.string(),
1713
- configname: z.string(),
1714
- greetmsg: z.string().optional(),
1715
- force: z.boolean(),
1716
- forwardedhost: z.string(),
1717
- fullRequestUrl: z.boolean(),
1718
- headermodification: z.array(HeaderModificationSchema),
1719
- httpsOnly: z.boolean(),
1720
- internalwebdebuggerport: z.number(),
1721
- ipwhitelist: z.array(z.string()).nullable(),
1722
- localport: z.number(),
1723
- localsservertls: z.union([z.boolean(), z.string()]),
1724
- localservertlssni: z.string().nullable(),
1725
- regioncode: z.string(),
1726
- noReverseProxy: z.boolean(),
1727
- serveraddress: z.string(),
1728
- serverport: z.number(),
1729
- statusCheckInterval: z.number(),
1730
- token: z.string(),
1731
- tunnelTimeout: z.number(),
1732
- type: z.enum([
1733
- TunnelType3.Http,
1734
- TunnelType3.Tcp,
1735
- TunnelType3.Udp,
1736
- TunnelType3.Tls,
1737
- TunnelType3.TlsTcp
1738
- ]),
1739
- webdebuggerport: z.number(),
1740
- xff: z.string(),
1741
- additionalForwarding: z.array(AdditionalForwardingSchema).optional(),
1742
- serve: z.string().optional()
1743
- }).superRefine((data, ctx) => {
1744
- if (data.allowPreflight === void 0 && data.allowpreflight === void 0) {
1745
- ctx.addIssue({
1746
- code: "custom",
1747
- message: "Either allowPreflight or allowpreflight is required",
1748
- path: ["allowPreflight"]
1749
- });
1750
- }
1751
- }).transform((data) => ({
1752
- ...data,
1753
- allowPreflight: data.allowPreflight ?? data.allowpreflight,
1754
- allowpreflight: data.allowPreflight ?? data.allowpreflight
1755
- }));
1756
- var StartSchema = z.object({
1757
- tunnelID: z.string().nullable().optional(),
1758
- tunnelConfig: TunnelConfigSchema
1759
- });
1760
- var StopSchema = z.object({
1761
- tunnelID: z.string().min(1)
1762
- });
1763
- var GetSchema = StopSchema;
1764
- var RestartSchema = StopSchema;
1765
- var UpdateConfigSchema = z.object({
1766
- tunnelConfig: TunnelConfigSchema
1767
- });
1768
- function tunnelConfigToPinggyOptions(config) {
1769
- return {
1770
- token: config.token || "",
1771
- serverAddress: config.serveraddress || "free.pinggy.io",
1772
- forwarding: `${config.forwardedhost || "localhost"}:${config.localport}`,
1773
- webDebugger: config.webdebuggerport ? `localhost:${config.webdebuggerport}` : "",
1774
- ipWhitelist: config.ipwhitelist || [],
1775
- basicAuth: config.basicauth ? config.basicauth : [],
1776
- bearerTokenAuth: config.bearerauth ? [config.bearerauth] : [],
1777
- headerModification: config.headermodification,
1778
- xForwardedFor: !!config.xff,
1779
- httpsOnly: config.httpsOnly,
1780
- originalRequestUrl: config.fullRequestUrl,
1781
- allowPreflight: config.allowPreflight,
1782
- reverseProxy: config.noReverseProxy,
1783
- force: config.force,
1784
- autoReconnect: config.autoreconnect,
1785
- optional: {
1786
- sniServerName: config.localservertlssni || ""
1787
- }
1788
- };
1789
- }
1790
- function pinggyOptionsToTunnelConfig(opts, configid, configName, localserverTls, greetMsg, additionalForwarding, serve) {
1791
- const forwarding = Array.isArray(opts.forwarding) ? String(opts.forwarding[0].address).replace("//", "").replace(/\/$/, "") : String(opts.forwarding).replace("//", "").replace(/\/$/, "");
1792
- const parsedForwardedHost = forwarding.split(":").length == 3 ? forwarding.split(":")[1] : forwarding.split(":")[0];
1793
- const parsedLocalPort = forwarding.split(":").length == 3 ? parseInt(forwarding.split(":")[2], 10) : parseInt(forwarding.split(":")[1], 10);
1794
- const tunnelType = (Array.isArray(opts.forwarding) ? opts.forwarding[0]?.type : void 0) ?? TunnelType3.Http;
1795
- const parsedTokens = opts.bearerTokenAuth ? Array.isArray(opts.bearerTokenAuth) ? opts.bearerTokenAuth : JSON.parse(opts.bearerTokenAuth) : [];
1796
- return {
1797
- allowPreflight: opts.allowPreflight ?? false,
1798
- allowpreflight: opts.allowPreflight ?? false,
1799
- autoreconnect: opts.autoReconnect ?? false,
1800
- basicauth: opts.basicAuth && Object.keys(opts.basicAuth).length ? opts.basicAuth : null,
1801
- bearerauth: parsedTokens.length ? parsedTokens.join(",") : null,
1802
- configid,
1803
- configname: configName,
1804
- greetmsg: greetMsg || "",
1805
- force: opts.force ?? false,
1806
- forwardedhost: parsedForwardedHost || "localhost",
1807
- fullRequestUrl: opts.originalRequestUrl ?? false,
1808
- headermodification: opts.headerModification || [],
1809
- //structured list
1810
- httpsOnly: opts.httpsOnly ?? false,
1811
- internalwebdebuggerport: 0,
1812
- ipwhitelist: opts.ipWhitelist ? Array.isArray(opts.ipWhitelist) ? opts.ipWhitelist : JSON.parse(opts.ipWhitelist) : null,
1813
- localport: parsedLocalPort || 0,
1814
- localservertlssni: null,
1815
- regioncode: "",
1816
- noReverseProxy: opts.reverseProxy ?? false,
1817
- serveraddress: opts.serverAddress || "free.pinggy.io",
1818
- serverport: 0,
1819
- statusCheckInterval: 0,
1820
- token: opts.token || "",
1821
- tunnelTimeout: 0,
1822
- type: tunnelType,
1823
- webdebuggerport: Number(opts.webDebugger?.split(":")[0]) || 0,
1824
- xff: opts.xForwardedFor ? "1" : "",
1825
- localsservertls: localserverTls || false,
1826
- additionalForwarding: additionalForwarding || [],
1827
- serve: serve || ""
1828
- };
1829
- }
1830
-
1831
- // src/remote_management/handler.ts
1832
- import { TunnelType as TunnelType4 } from "@pinggy/pinggy";
1833
- var TunnelOperations = class {
1834
- constructor() {
1835
- this.tunnelManager = TunnelManager.getInstance();
1836
- }
1837
- buildStatus(tunnelId, state, errorCode) {
1838
- const status = newStatus(state, errorCode, "");
1839
- try {
1840
- const managed = this.tunnelManager.getManagedTunnel("", tunnelId);
1841
- if (managed) {
1842
- status.createdtimestamp = managed.createdAt || "";
1843
- status.starttimestamp = managed.startedAt || "";
1844
- status.endtimestamp = managed.stoppedAt || "";
1845
- }
1846
- } catch (e) {
1847
- }
1848
- return status;
1849
- }
1850
- // --- Helper to construct TunnelResponse ---
1851
- async buildTunnelResponse(tunnelid, tunnelConfig, configid, tunnelName, additionalForwarding, serve) {
1852
- const [status, stats, tlsInfo, greetMsg, remoteurls] = await Promise.all([
1853
- this.tunnelManager.getTunnelStatus(tunnelid),
1854
- this.tunnelManager.getLatestTunnelStats(tunnelid) || newStats(),
1855
- this.tunnelManager.getLocalserverTlsInfo(tunnelid),
1856
- this.tunnelManager.getTunnelGreetMessage(tunnelid),
1857
- this.tunnelManager.getTunnelUrls(tunnelid)
1858
- ]);
1859
- return {
1860
- tunnelid,
1861
- remoteurls,
1862
- tunnelconfig: pinggyOptionsToTunnelConfig(tunnelConfig, configid, tunnelName, tlsInfo, greetMsg, additionalForwarding),
1863
- status: this.buildStatus(tunnelid, status, "" /* NoError */),
1864
- stats
1865
- };
1866
- }
1867
- error(code, err, fallback) {
1868
- return newErrorResponse({
1869
- code,
1870
- message: err instanceof Error ? err.message : fallback
1871
- });
1872
- }
1873
- // --- Operations ---
1874
- async handleStart(config) {
1875
- try {
1876
- const opts = tunnelConfigToPinggyOptions(config);
1877
- const additionalForwardingParsed = config.additionalForwarding || [];
1878
- const { tunnelid, instance, tunnelName, additionalForwarding, serve } = await this.tunnelManager.createTunnel({
1879
- ...opts,
1880
- tunnelType: Array.isArray(config.type) ? config.type : config.type ? [config.type] : [TunnelType4.Http],
1881
- // Temporary fix in future we will not use this field.
1882
- configid: config.configid,
1883
- tunnelName: config.configname,
1884
- additionalForwarding: additionalForwardingParsed,
1885
- serve: config.serve
1886
- });
1887
- this.tunnelManager.startTunnel(tunnelid);
1888
- const tunnelPconfig = await this.tunnelManager.getTunnelConfig("", tunnelid);
1889
- const resp = this.buildTunnelResponse(tunnelid, tunnelPconfig, config.configid, tunnelName, additionalForwarding, serve);
1890
- return resp;
1891
- } catch (err) {
1892
- return this.error(ErrorCode.ErrorStartingTunnel, err, "Unknown error occurred while starting tunnel");
1893
- }
1894
- }
1895
- async handleUpdateConfig(config) {
1896
- try {
1897
- const opts = tunnelConfigToPinggyOptions(config);
1898
- const tunnel = await this.tunnelManager.updateConfig({
1899
- ...opts,
1900
- tunnelType: Array.isArray(config.type) ? config.type : config.type ? [config.type] : [TunnelType4.Http],
1901
- // // Temporary fix in future we will not use this field.
1902
- configid: config.configid,
1903
- tunnelName: config.configname,
1904
- additionalForwarding: config.additionalForwarding || [],
1905
- serve: config.serve
1906
- });
1907
- if (!tunnel.instance || !tunnel.tunnelConfig)
1908
- throw new Error("Invalid tunnel state after configuration update");
1909
- return this.buildTunnelResponse(tunnel.tunnelid, tunnel.tunnelConfig, config.configid, tunnel.tunnelName, tunnel.additionalForwarding, tunnel.serve);
1910
- } catch (err) {
1911
- return this.error(ErrorCode.InternalServerError, err, "Failed to update tunnel configuration");
1912
- }
1913
- }
1914
- async handleList() {
1915
- try {
1916
- const tunnels = await this.tunnelManager.getAllTunnels();
1917
- if (tunnels.length === 0) {
1918
- return [];
1919
- }
1920
- return Promise.all(
1921
- tunnels.map(async (t) => {
1922
- const rawStats = this.tunnelManager.getLatestTunnelStats(t.tunnelid) || newStats();
1923
- const [status, tlsInfo, greetMsg] = await Promise.all([
1924
- this.tunnelManager.getTunnelStatus(t.tunnelid),
1925
- this.tunnelManager.getLocalserverTlsInfo(t.tunnelid),
1926
- this.tunnelManager.getTunnelGreetMessage(t.tunnelid)
1927
- ]);
1928
- const pinggyOptions = status !== "closed" /* Closed */ && status !== "exited" /* Exited */ ? await this.tunnelManager.getTunnelConfig("", t.tunnelid) : t.tunnelConfig;
1929
- const tunnelConfig = pinggyOptionsToTunnelConfig(pinggyOptions, t.configid, t.tunnelName, tlsInfo, greetMsg, t.additionalForwarding, t.serve);
1930
- return {
1931
- tunnelid: t.tunnelid,
1932
- remoteurls: t.remoteurls,
1933
- status: this.buildStatus(t.tunnelid, status, "" /* NoError */),
1934
- stats: rawStats,
1935
- tunnelconfig: tunnelConfig
1936
- };
1937
- })
1938
- );
1939
- } catch (err) {
1940
- return this.error(ErrorCode.InternalServerError, err, "Failed to list tunnels");
1941
- }
1942
- }
1943
- async handleStop(tunnelid) {
1944
- try {
1945
- const { configid } = this.tunnelManager.stopTunnel(tunnelid);
1946
- const managed = this.tunnelManager.getManagedTunnel("", tunnelid);
1947
- if (!managed?.tunnelConfig) throw new Error(`Tunnel config for ID "${tunnelid}" not found`);
1948
- return this.buildTunnelResponse(tunnelid, managed.tunnelConfig, configid, managed.tunnelName, managed.additionalForwarding, managed.serve);
1949
- } catch (err) {
1950
- return this.error(ErrorCode.TunnelNotFound, err, "Failed to stop tunnel");
1951
- }
1952
- }
1953
- async handleGet(tunnelid) {
1954
- try {
1955
- const managed = this.tunnelManager.getManagedTunnel("", tunnelid);
1956
- if (!managed?.tunnelConfig) throw new Error(`Tunnel config for ID "${tunnelid}" not found`);
1957
- return this.buildTunnelResponse(tunnelid, managed.tunnelConfig, managed.configid, managed.tunnelName, managed.additionalForwarding, managed.serve);
1958
- } catch (err) {
1959
- return this.error(ErrorCode.TunnelNotFound, err, "Failed to get tunnel information");
1960
- }
1961
- }
1962
- async handleRestart(tunnelid) {
1963
- try {
1964
- await this.tunnelManager.restartTunnel(tunnelid);
1965
- const managed = this.tunnelManager.getManagedTunnel("", tunnelid);
1966
- if (!managed?.tunnelConfig) throw new Error(`Tunnel config for ID "${tunnelid}" not found`);
1967
- return this.buildTunnelResponse(tunnelid, managed.tunnelConfig, managed.configid, managed.tunnelName, managed.additionalForwarding, managed.serve);
1968
- } catch (err) {
1969
- return this.error(ErrorCode.TunnelNotFound, err, "Failed to restart tunnel");
1970
- }
1971
- }
1972
- handleRegisterStatsListener(tunnelid, listener) {
1973
- this.tunnelManager.registerStatsListener(tunnelid, listener);
1974
- }
1975
- handleUnregisterStatsListener(tunnelid, listnerId) {
1976
- this.tunnelManager.deregisterStatsListener(tunnelid, listnerId);
1977
- }
1978
- handleGetTunnelStats(tunnelid) {
1979
- try {
1980
- const stats = this.tunnelManager.getTunnelStats(tunnelid);
1981
- if (!stats) {
1982
- return [newStats()];
1983
- }
1984
- return stats;
1985
- } catch (err) {
1986
- return this.error(ErrorCode.TunnelNotFound, err, "Failed to get tunnel stats");
1987
- }
1988
- }
1989
- handleRegisterDisconnectListener(tunnelid, listener) {
1990
- this.tunnelManager.registerDisconnectListener(tunnelid, listener);
1991
- }
1992
- handleRemoveStoppedTunnelByConfigId(configId) {
1993
- try {
1994
- return this.tunnelManager.removeStoppedTunnelByConfigId(configId);
1995
- } catch (err) {
1996
- return this.error(ErrorCode.InternalServerError, err, "Failed to remove stopped tunnel by configId");
1997
- }
1998
- }
1999
- handleRemoveStoppedTunnelByTunnelId(tunnelId) {
2000
- try {
2001
- return this.tunnelManager.removeStoppedTunnelByTunnelId(tunnelId);
2002
- } catch (err) {
2003
- return this.error(ErrorCode.InternalServerError, err, "Failed to remove stopped tunnel by tunnelId");
2004
- }
2005
- }
2006
- };
2007
-
2008
- // src/remote_management/websocket_handlers.ts
2009
- import z2 from "zod";
2010
- var WebSocketCommandHandler = class {
2011
- constructor() {
2012
- this.tunnelHandler = new TunnelOperations();
2013
- }
2014
- safeParse(text) {
2015
- if (!text) return void 0;
2016
- try {
2017
- return JSON.parse(text);
2018
- } catch (e) {
2019
- logger.warn("Invalid JSON payload", { error: String(e), text });
2020
- return void 0;
2021
- }
2022
- }
2023
- sendResponse(ws, resp) {
2024
- const payload = {
2025
- ...resp,
2026
- response: Buffer.from(resp.response || []).toString("base64")
2027
- };
2028
- ws.send(JSON.stringify(payload));
2029
- }
2030
- sendError(ws, req, message, code = ErrorCode.InternalServerError) {
2031
- const resp = NewErrorResponseObject({ code, message });
2032
- resp.command = req.command || "";
2033
- resp.requestid = req.requestid || "";
2034
- this.sendResponse(ws, resp);
2035
- }
2036
- async handleStartReq(req, raw) {
2037
- const dc = StartSchema.parse(raw);
2038
- printer_default.info("Starting tunnel with config name: " + dc.tunnelConfig.configname);
2039
- const result = await this.tunnelHandler.handleStart(dc.tunnelConfig);
2040
- return this.wrapResponse(result, req);
2041
- }
2042
- async handleStopReq(req, raw) {
2043
- const dc = StopSchema.parse(raw);
2044
- printer_default.info("Stopping tunnel with ID: " + dc.tunnelID);
2045
- const result = await this.tunnelHandler.handleStop(dc.tunnelID);
2046
- return this.wrapResponse(result, req);
2047
- }
2048
- async handleGetReq(req, raw) {
2049
- const dc = GetSchema.parse(raw);
2050
- const result = await this.tunnelHandler.handleGet(dc.tunnelID);
2051
- return this.wrapResponse(result, req);
2052
- }
2053
- async handleRestartReq(req, raw) {
2054
- const dc = RestartSchema.parse(raw);
2055
- const result = await this.tunnelHandler.handleRestart(dc.tunnelID);
2056
- return this.wrapResponse(result, req);
2057
- }
2058
- async handleUpdateConfigReq(req, raw) {
2059
- const dc = UpdateConfigSchema.parse(raw);
2060
- const result = await this.tunnelHandler.handleUpdateConfig(dc.tunnelConfig);
2061
- return this.wrapResponse(result, req);
2062
- }
2063
- async handleListReq(req) {
2064
- const result = await this.tunnelHandler.handleList();
2065
- return this.wrapResponse(result, req);
2066
- }
2067
- wrapResponse(result, req) {
2068
- if (isErrorResponse(result)) {
2069
- const errResp = NewErrorResponseObject(result);
2070
- errResp.command = req.command;
2071
- errResp.requestid = req.requestid;
2072
- return errResp;
2073
- }
2074
- const finalResult = JSON.parse(JSON.stringify(result));
2075
- if (Array.isArray(finalResult)) {
2076
- finalResult.forEach((item) => {
2077
- if (item?.tunnelconfig) {
2078
- delete item.tunnelconfig.allowPreflight;
2079
- }
2080
- });
2081
- } else if (finalResult?.tunnelconfig) {
2082
- delete finalResult.tunnelconfig.allowPreflight;
2083
- }
2084
- const respObj = NewResponseObject(finalResult);
2085
- respObj.command = req.command;
2086
- respObj.requestid = req.requestid;
2087
- return respObj;
2088
- }
2089
- async handle(ws, req) {
2090
- const cmd = (req.command || "").toLowerCase();
2091
- const raw = this.safeParse(req.data);
2092
- try {
2093
- let response;
2094
- switch (cmd) {
2095
- case "start": {
2096
- response = await this.handleStartReq(req, raw);
2097
- break;
2098
- }
2099
- case "stop": {
2100
- response = await this.handleStopReq(req, raw);
2101
- break;
2102
- }
2103
- case "get": {
2104
- response = await this.handleGetReq(req, raw);
2105
- break;
2106
- }
2107
- case "restart": {
2108
- response = await this.handleRestartReq(req, raw);
2109
- break;
2110
- }
2111
- case "updateconfig": {
2112
- response = await this.handleUpdateConfigReq(req, raw);
2113
- break;
2114
- }
2115
- case "list": {
2116
- response = await this.handleListReq(req);
2117
- break;
2118
- }
2119
- default:
2120
- if (typeof req.command === "string") {
2121
- logger.warn("Unknown command", { command: req.command });
2122
- }
2123
- return this.sendError(ws, req, "Invalid command");
2124
- }
2125
- logger.debug("Sending response", { command: response.command, requestid: response.requestid });
2126
- this.sendResponse(ws, response);
2127
- } catch (e) {
2128
- if (e instanceof z2.ZodError) {
2129
- logger.warn("Validation failed", { cmd, issues: e.issues });
2130
- return this.sendError(ws, req, "Invalid request data", ErrorCode.InvalidBodyFormatError);
2131
- }
2132
- logger.error("Error handling command", { cmd, error: String(e) });
2133
- return this.sendError(ws, req, e?.message || "Internal error");
2134
- }
2135
- }
2136
- };
2137
- function handleConnectionStatusMessage(firstMessage) {
2138
- try {
2139
- const text = typeof firstMessage === "string" ? firstMessage : firstMessage.toString();
2140
- const cs = JSON.parse(text);
2141
- if (!cs.success) {
2142
- const msg = cs.error_msg || "Connection failed";
2143
- printer_default.warn(`Connection failed: ${msg}`);
2144
- logger.warn("Remote management connection failed", { error_code: cs.error_code, error_msg: msg });
2145
- return false;
2146
- }
2147
- return true;
2148
- } catch (e) {
2149
- logger.warn("Failed to parse connection status message", { error: String(e) });
2150
- return true;
2151
- }
2152
- }
2153
-
2154
- // src/remote_management/remoteManagement.ts
2155
- var RECONNECT_SLEEP_MS = 5e3;
2156
- var PING_INTERVAL_MS = 3e4;
2157
- var _remoteManagementState = {
2158
- status: "NOT_RUNNING",
2159
- errorMessage: ""
2160
- };
2161
- var _stopRequested = false;
2162
- var currentWs = null;
2163
- function buildRemoteManagementWsUrl(manage) {
2164
- let baseUrl = (manage || "dashboard.pinggy.io").trim();
2165
- if (!(baseUrl.startsWith("ws://") || baseUrl.startsWith("wss://"))) {
2166
- baseUrl = "wss://" + baseUrl;
2167
- }
2168
- const trimmed = baseUrl.replace(/\/$/, "");
2169
- return `${trimmed}/backend/api/v1/remote-management/connect`;
2170
- }
2171
- function extractHostname(u) {
2172
- try {
2173
- const url = new URL(u);
2174
- return url.host;
2175
- } catch {
2176
- return u;
2177
- }
2178
- }
2179
- function sleep(ms) {
2180
- return new Promise((res) => setTimeout(res, ms));
2181
- }
2182
- async function parseRemoteManagement(values) {
2183
- const rmToken = values["remote-management"];
2184
- if (typeof rmToken === "string" && rmToken.trim().length > 0) {
2185
- const manageHost = values["manage"];
2186
- try {
2187
- await initiateRemoteManagement(rmToken, manageHost);
2188
- return { ok: true };
2189
- } catch (e) {
2190
- logger.error("Failed to initiate remote management:", e);
2191
- return { ok: false, error: e };
2192
- }
2193
- }
2194
- }
2195
- async function initiateRemoteManagement(token, manage) {
2196
- if (!token || token.trim().length === 0) {
2197
- throw new Error("Remote management token is required (use --remote-management <TOKEN>)");
2198
- }
2199
- const wsUrl = buildRemoteManagementWsUrl(manage);
2200
- const wsHost = extractHostname(wsUrl);
2201
- logger.info("Remote management mode enabled.");
2202
- _stopRequested = false;
2203
- const sigintHandler = () => {
2204
- _stopRequested = true;
2205
- };
2206
- process.once("SIGINT", sigintHandler);
2207
- const logConnecting = () => {
2208
- printer_default.print(`Connecting to ${wsHost}`);
2209
- logger.info("Connecting to remote management", { wsUrl });
2210
- };
2211
- while (!_stopRequested) {
2212
- logConnecting();
2213
- setRemoteManagementState({ status: RemoteManagementStatus.Connecting, errorMessage: "" });
2214
- try {
2215
- await handleWebSocketConnection(wsUrl, wsHost, token);
2216
- } catch (error) {
2217
- logger.warn("Remote management connection error", { error: String(error) });
2218
- }
2219
- if (_stopRequested) break;
2220
- printer_default.warn(`Remote management disconnected. Reconnecting in ${RECONNECT_SLEEP_MS / 1e3} seconds...`);
2221
- logger.info("Reconnecting to remote management after disconnect");
2222
- await sleep(RECONNECT_SLEEP_MS);
2223
- }
2224
- process.removeListener("SIGINT", sigintHandler);
2225
- logger.info("Remote management stopped.");
2226
- return getRemoteManagementState();
2227
- }
2228
- async function handleWebSocketConnection(wsUrl, wsHost, token) {
2229
- return new Promise((resolve) => {
2230
- const ws = new WebSocket(wsUrl, {
2231
- headers: { Authorization: `Bearer ${token}` }
2232
- });
2233
- currentWs = ws;
2234
- let heartbeat = null;
2235
- let firstMessage = true;
2236
- const cleanup = () => {
2237
- if (heartbeat) clearInterval(heartbeat);
2238
- currentWs = null;
2239
- resolve();
2240
- };
2241
- ws.once("open", () => {
2242
- printer_default.success(`Connected to ${wsHost}`);
2243
- heartbeat = setInterval(() => {
2244
- if (ws.readyState === WebSocket.OPEN) ws.ping();
2245
- }, PING_INTERVAL_MS);
2246
- });
2247
- ws.on("ping", () => ws.pong());
2248
- ws.on("message", async (data) => {
2249
- try {
2250
- if (firstMessage) {
2251
- firstMessage = false;
2252
- const ok = handleConnectionStatusMessage(data);
2253
- if (!ok) ws.close();
2254
- return;
2255
- }
2256
- setRemoteManagementState({ status: RemoteManagementStatus.Running, errorMessage: "" });
2257
- const req = JSON.parse(data.toString("utf8"));
2258
- await new WebSocketCommandHandler().handle(ws, req);
2259
- } catch (e) {
2260
- logger.warn("Failed handling websocket message", { error: String(e) });
2261
- }
2262
- });
2263
- ws.on("unexpected-response", (_, res) => {
2264
- setRemoteManagementState({ status: RemoteManagementStatus.NotRunning, errorMessage: `HTTP ${res.statusCode}` });
2265
- if (res.statusCode === 401) {
2266
- printer_default.error("Unauthorized. Please enter a valid token.");
2267
- logger.error("Unauthorized (401) on remote management connect");
2268
- } else {
2269
- printer_default.warn(`Unexpected HTTP ${res.statusCode}. Retrying...`);
2270
- logger.warn("Unexpected HTTP response", { statusCode: res.statusCode });
2271
- }
2272
- ws.close();
2273
- });
2274
- ws.on("close", (code, reason) => {
2275
- setRemoteManagementState({ status: RemoteManagementStatus.NotRunning, errorMessage: "" });
2276
- logger.info("WebSocket closed", { code, reason: reason.toString() });
2277
- printer_default.warn(`Disconnected (code: ${code}). Retrying...`);
2278
- cleanup();
2279
- });
2280
- ws.on("error", (err) => {
2281
- setRemoteManagementState({ status: RemoteManagementStatus.Error, errorMessage: err.message });
2282
- logger.warn("WebSocket error", { error: err.message });
2283
- printer_default.error(err);
2284
- cleanup();
2285
- });
2286
- });
2287
- }
2288
- async function closeRemoteManagement(timeoutMs = 1e4) {
2289
- _stopRequested = true;
2290
- try {
2291
- if (currentWs) {
2292
- try {
2293
- setRemoteManagementState({ status: RemoteManagementStatus.Disconnecting, errorMessage: "" });
2294
- currentWs.close();
2295
- } catch (e) {
2296
- logger.warn("Error while closing current remote management websocket", { error: String(e) });
2297
- }
2298
- }
2299
- const start = Date.now();
2300
- while (_remoteManagementState.status === "RUNNING") {
2301
- if (Date.now() - start > timeoutMs) {
2302
- logger.warn("Timed out waiting for remote management to stop");
2303
- break;
2304
- }
2305
- await sleep(200);
2306
- }
2307
- } finally {
2308
- currentWs = null;
2309
- setRemoteManagementState({ status: RemoteManagementStatus.NotRunning, errorMessage: "" });
2310
- return getRemoteManagementState();
2311
- }
2312
- }
2313
- function getRemoteManagementState() {
2314
- return _remoteManagementState;
2315
- }
2316
- function setRemoteManagementState(state, errorMessage) {
2317
- _remoteManagementState = {
2318
- status: state.status,
2319
- errorMessage: errorMessage || ""
2320
- };
2321
- }
2322
-
2323
649
  // src/utils/parseArgs.ts
2324
650
  import { parseArgs as parseArgs2 } from "util";
2325
651
  import * as os from "os";
@@ -2418,7 +744,7 @@ async function createQrCodes(urls) {
2418
744
  }
2419
745
 
2420
746
  // src/tui/blessed/webDebuggerConnection.ts
2421
- import WebSocket2 from "ws";
747
+ import WebSocket from "ws";
2422
748
 
2423
749
  // src/tui/blessed/config.ts
2424
750
  var defaultTuiConfig = {
@@ -2461,7 +787,7 @@ function createWebDebuggerConnection(webDebuggerUrl, onUpdate) {
2461
787
  trimPairs();
2462
788
  };
2463
789
  const connect = () => {
2464
- const ws = new WebSocket2(`ws://${webDebuggerUrl}/introspec/websocket`);
790
+ const ws = new WebSocket(`ws://${webDebuggerUrl}/introspec/websocket`);
2465
791
  socket = ws;
2466
792
  ws.on("open", () => {
2467
793
  logger.info("Web debugger connected.");
@@ -3064,6 +1390,91 @@ function closeDisconnectModal(screen, manager) {
3064
1390
  manager.inDisconnectView = false;
3065
1391
  screen.render();
3066
1392
  }
1393
+ function showReconnectingModal(screen, manager, retryCnt, message) {
1394
+ if (manager.reconnectModal) {
1395
+ manager.reconnectModal.destroy();
1396
+ manager.reconnectModal = null;
1397
+ }
1398
+ manager.inReconnectView = true;
1399
+ manager.reconnectModal = blessed2.box({
1400
+ parent: screen,
1401
+ top: "center",
1402
+ left: "center",
1403
+ width: "50%",
1404
+ height: "20%",
1405
+ border: {
1406
+ type: "line"
1407
+ },
1408
+ style: {
1409
+ border: {
1410
+ fg: "yellow"
1411
+ }
1412
+ },
1413
+ padding: { left: 2, right: 2, top: 1, bottom: 1 },
1414
+ tags: true,
1415
+ align: "center",
1416
+ valign: "middle"
1417
+ });
1418
+ const content = `{yellow-fg}{bold}Reconnecting...{/bold}{/yellow-fg}
1419
+
1420
+ ${message || `Attempt #${retryCnt} \u2014 trying to re-establish tunnel...`}
1421
+
1422
+ {gray-fg}Please wait{/gray-fg}`;
1423
+ manager.reconnectModal.setContent(content);
1424
+ manager.reconnectModal.focus();
1425
+ screen.render();
1426
+ }
1427
+ function closeReconnectingModal(screen, manager) {
1428
+ if (manager.reconnectModal) {
1429
+ manager.reconnectModal.destroy();
1430
+ manager.reconnectModal = null;
1431
+ }
1432
+ manager.inReconnectView = false;
1433
+ screen.render();
1434
+ }
1435
+ function showReconnectionFailedModal(screen, manager, retryCnt, onClose) {
1436
+ closeReconnectingModal(screen, manager);
1437
+ manager.inReconnectView = true;
1438
+ manager.reconnectModal = blessed2.box({
1439
+ parent: screen,
1440
+ top: "center",
1441
+ left: "center",
1442
+ width: "50%",
1443
+ height: "20%",
1444
+ border: {
1445
+ type: "line"
1446
+ },
1447
+ style: {
1448
+ border: {
1449
+ fg: "red"
1450
+ }
1451
+ },
1452
+ padding: { left: 2, right: 2, top: 1, bottom: 1 },
1453
+ tags: true,
1454
+ align: "center",
1455
+ valign: "middle"
1456
+ });
1457
+ const content = `{red-fg}{bold}Reconnection Failed{/bold}{/red-fg}
1458
+
1459
+ Failed to reconnect after ${retryCnt} attempts.
1460
+ Tunnel will be closed.
1461
+
1462
+ {white-bg}{black-fg}Closing in 5 seconds...{/black-fg}{/white-bg}`;
1463
+ manager.reconnectModal.setContent(content);
1464
+ manager.reconnectModal.focus();
1465
+ screen.render();
1466
+ const timeout = setTimeout(() => {
1467
+ closeReconnectingModal(screen, manager);
1468
+ if (onClose) onClose();
1469
+ }, 5e3);
1470
+ const keyHandler = () => {
1471
+ clearTimeout(timeout);
1472
+ closeReconnectingModal(screen, manager);
1473
+ if (onClose) onClose();
1474
+ };
1475
+ manager.reconnectModal.key(["escape", "enter", "space"], keyHandler);
1476
+ screen.key(["escape", "enter", "space"], keyHandler);
1477
+ }
3067
1478
  function showLoadingModal(screen, modalManager, message = "Loading...") {
3068
1479
  if (modalManager.loadingView) return;
3069
1480
  modalManager.loadingBox = blessed2.box({
@@ -3333,9 +1744,11 @@ var TunnelTui = class {
3333
1744
  detailModal: null,
3334
1745
  keyBindingsModal: null,
3335
1746
  disconnectModal: null,
1747
+ reconnectModal: null,
3336
1748
  inDetailView: false,
3337
1749
  keyBindingView: false,
3338
1750
  inDisconnectView: false,
1751
+ inReconnectView: false,
3339
1752
  loadingBox: null,
3340
1753
  loadingView: false,
3341
1754
  fetchAbortController: null
@@ -3363,8 +1776,8 @@ var TunnelTui = class {
3363
1776
  this.setupKeyBindings();
3364
1777
  }
3365
1778
  setupStatsListener() {
3366
- globalThis.__PINGGY_TUNNEL_STATS__ = (newStats2) => {
3367
- this.stats = { ...newStats2 };
1779
+ globalThis.__PINGGY_TUNNEL_STATS__ = (newStats) => {
1780
+ this.stats = { ...newStats };
3368
1781
  this.updateStatsDisplay();
3369
1782
  };
3370
1783
  }
@@ -3536,6 +1949,25 @@ Tunnel will be closed.` : info.messages?.join("\n") || "Disconnect request recei
3536
1949
  );
3537
1950
  }
3538
1951
  }
1952
+ updateReconnectingInfo(retryCnt, message) {
1953
+ showReconnectingModal(
1954
+ this.screen,
1955
+ this.modalManager,
1956
+ retryCnt,
1957
+ message
1958
+ );
1959
+ }
1960
+ closeReconnectingInfo() {
1961
+ closeReconnectingModal(this.screen, this.modalManager);
1962
+ }
1963
+ updateReconnectionFailed(retryCnt) {
1964
+ showReconnectionFailedModal(
1965
+ this.screen,
1966
+ this.modalManager,
1967
+ retryCnt,
1968
+ () => this.destroy()
1969
+ );
1970
+ }
3539
1971
  start() {
3540
1972
  this.screen.render();
3541
1973
  }
@@ -3632,6 +2064,35 @@ async function startCli(finalConfig, manager) {
3632
2064
  }
3633
2065
  printer_default.print(pico.gray("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
3634
2066
  printer_default.print(pico.gray("\nPress Ctrl+C to stop the tunnel.\n"));
2067
+ manager2.registerWillReconnectListener(tunnel.tunnelid, (tunnelId, error, messages) => {
2068
+ if (activeTui) {
2069
+ const msg = messages?.join("\n") || error || "Tunnel disconnected, reconnecting...";
2070
+ activeTui.updateReconnectingInfo(0, msg);
2071
+ } else if (finalConfig.autoReconnect) {
2072
+ printer_default.warn(error || "Tunnel connection reset");
2073
+ printer_default.startSpinner(messages?.join("\n"));
2074
+ }
2075
+ });
2076
+ manager2.registerReconnectingListener(tunnel.tunnelid, (tunnelId, retryCnt) => {
2077
+ if (activeTui) {
2078
+ activeTui.updateReconnectingInfo(retryCnt);
2079
+ } else if (finalConfig.autoReconnect) {
2080
+ printer_default.startSpinner(`Reconnecting to Pinggy (attempt #${retryCnt})`);
2081
+ }
2082
+ });
2083
+ manager2.registerReconnectionCompletedListener(tunnel.tunnelid, (tunnelId, urls) => {
2084
+ if (activeTui) {
2085
+ activeTui.closeReconnectingInfo();
2086
+ }
2087
+ });
2088
+ manager2.registerReconnectionFailedListener(tunnel.tunnelid, (tunnelId, retryCnt) => {
2089
+ if (activeTui) {
2090
+ activeTui.updateReconnectionFailed(retryCnt);
2091
+ } else {
2092
+ printer_default.stopSpinnerFail(`Reconnection failed after ${retryCnt} attempts`);
2093
+ process.exit(1);
2094
+ }
2095
+ });
3635
2096
  manager2.registerDisconnectListener(tunnel.tunnelid, async (tunnelId, error, messages) => {
3636
2097
  if (activeTui) {
3637
2098
  disconnectState = {
@@ -3710,7 +2171,7 @@ async function startCli(finalConfig, manager) {
3710
2171
  }
3711
2172
 
3712
2173
  // src/main.ts
3713
- import { fileURLToPath as fileURLToPath2 } from "url";
2174
+ import { fileURLToPath } from "url";
3714
2175
  import { argv } from "process";
3715
2176
  import { realpathSync } from "fs";
3716
2177
  async function main() {
@@ -3748,7 +2209,7 @@ async function main() {
3748
2209
  printer_default.error(error);
3749
2210
  }
3750
2211
  }
3751
- var currentFile = fileURLToPath2(import.meta.url);
2212
+ var currentFile = fileURLToPath(import.meta.url);
3752
2213
  var entryFile = null;
3753
2214
  try {
3754
2215
  entryFile = argv[1] ? realpathSync(argv[1]) : null;