pinggy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +182 -0
  3. package/dist/TunnelConfig.js +39 -0
  4. package/dist/TunnelManager.js +155 -0
  5. package/dist/cli/buildConfig.js +323 -0
  6. package/dist/cli/defaults.js +18 -0
  7. package/dist/cli/extendedOptions.js +134 -0
  8. package/dist/cli/help.js +37 -0
  9. package/dist/cli/options.js +36 -0
  10. package/dist/cli/remoteManagement.js +167 -0
  11. package/dist/cli/starCli.js +62 -0
  12. package/dist/cli/websocket_handlers.js +160 -0
  13. package/dist/index.js +60 -0
  14. package/dist/logger.js +67 -0
  15. package/dist/remote_management/handler.js +182 -0
  16. package/dist/remote_management/remoteManagement.js +159 -0
  17. package/dist/remote_management/remote_schema.js +122 -0
  18. package/dist/remote_management/websocket_handlers.js +163 -0
  19. package/dist/tui/asciArt.js +7 -0
  20. package/dist/tui/index.js +75 -0
  21. package/dist/tui/useTerminalSize.js +21 -0
  22. package/dist/tunnel_manager/TunnelManager.js +551 -0
  23. package/dist/tunnel_manager/handler.js +102 -0
  24. package/dist/tunnel_manager/remote_schema.js +106 -0
  25. package/dist/types.js +105 -0
  26. package/dist/utils/parseArgs.js +7 -0
  27. package/dist/utils/printer.js +68 -0
  28. package/dist/utils/util.js +3 -0
  29. package/jest.config.js +19 -0
  30. package/package.json +49 -0
  31. package/src/TunnelConfig.ts +40 -0
  32. package/src/_tests_/build_config.test.ts +91 -0
  33. package/src/cli/buildConfig.ts +357 -0
  34. package/src/cli/defaults.ts +20 -0
  35. package/src/cli/extendedOptions.ts +134 -0
  36. package/src/cli/help.ts +41 -0
  37. package/src/cli/options.ts +46 -0
  38. package/src/cli/starCli.tsx +118 -0
  39. package/src/cli/worker.ts +72 -0
  40. package/src/index.ts +65 -0
  41. package/src/logger.ts +86 -0
  42. package/src/remote_management/handler.ts +199 -0
  43. package/src/remote_management/remoteManagement.ts +168 -0
  44. package/src/remote_management/remote_schema.ts +134 -0
  45. package/src/remote_management/websocket_handlers.ts +166 -0
  46. package/src/tui/asciArt.ts +7 -0
  47. package/src/tui/hooks/useQrCodes.ts +27 -0
  48. package/src/tui/hooks/useReqResHeaders.ts +27 -0
  49. package/src/tui/hooks/useTerminalSize.ts +26 -0
  50. package/src/tui/hooks/useTerminalStats.ts +24 -0
  51. package/src/tui/hooks/useWebDebugger.ts +98 -0
  52. package/src/tui/index.tsx +221 -0
  53. package/src/tui/layout/Borders.tsx +15 -0
  54. package/src/tui/layout/Container.tsx +15 -0
  55. package/src/tui/sections/DebuggerDetailModal.tsx +53 -0
  56. package/src/tui/sections/KeyBindings.tsx +58 -0
  57. package/src/tui/sections/QrCodeSection.tsx +28 -0
  58. package/src/tui/sections/StatsSection.tsx +20 -0
  59. package/src/tui/sections/URLsSection.tsx +53 -0
  60. package/src/tui/utils/utils.ts +35 -0
  61. package/src/tunnel_manager/TunnelManager.ts +646 -0
  62. package/src/types.ts +234 -0
  63. package/src/utils/getFreePort.ts +41 -0
  64. package/src/utils/parseArgs.ts +29 -0
  65. package/src/utils/printer.ts +79 -0
  66. package/src/utils/util.ts +13 -0
  67. package/tsconfig.jest.json +8 -0
  68. package/tsconfig.json +17 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 PINGGY TECHNOLOGY PRIVATE LIMITED
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,182 @@
1
+ # Pinggy CLI (JavaScript)
2
+
3
+ Create secure, shareable tunnels to your localhost and manage them from the command line.
4
+
5
+ - Homepage: https://github.com/Pinggy-io/cli-js
6
+ - Package name: pinggy
7
+
8
+ ## Key features
9
+ - HTTP, TCP, UDP, TLS, TLSTCP tunnels to localhost
10
+ - SSH-style and user-friendly flags
11
+ - Web debugger for HTTP tunnels
12
+ - Extended options for auth, header manipulation, IP allowlists, CORS handling, etc.
13
+ - Remote management via secure WebSocket connection (works with Pinggy Dashboard)
14
+ - Configurable logging to file and/or stdout
15
+ - Save and load configuration files
16
+ - Simple file server mode for quickly sharing local files
17
+ - Built-in TUI (Text User Interface) for viewing tunnel statistics, requests, and responses in real time
18
+
19
+
20
+ ## Requirements
21
+ - Node.js 18+ (recommended). The CLI uses modern ESM and WebSocket features.
22
+ - A network connection that allows outgoing WebSocket/HTTPS traffic.
23
+
24
+
25
+ ## Installation
26
+ Global install is recommended for system-wide "pinggy" command.
27
+
28
+ - Using npm:
29
+ ``` bash
30
+ npm install -g pinggy
31
+ ```
32
+
33
+ After install, verify:
34
+ ```bash
35
+ pinggy --help
36
+ ```
37
+
38
+
39
+ ## Quick start
40
+ - Start a basic HTTP tunnel to localhost:3000:
41
+
42
+ ```bash
43
+ pinggy -R0:localhost:3000
44
+ ```
45
+
46
+ - Start a TCP tunnel (e.g., SSH on port 22):
47
+
48
+ ```bash
49
+ pinggy -R0:localhost:8000 tcp@free.pinggy.io
50
+ ```
51
+
52
+ - Start HTTP tunnel with web debugger on 4300:
53
+ ```bash
54
+ pinggy -R0:localhost:8000 -L4300:localhost:4300
55
+ ```
56
+
57
+ - Use a token and region/domain-like arg:
58
+ pinggy mytoken@a.example.com -p 3000. For more info read [docs](https://pinggy.io/docs/)
59
+
60
+ The CLI prints generated public URLs (HTTP/HTTPS or TCP) and keeps running until you press Ctrl+C.
61
+
62
+
63
+ ## Usage
64
+ Basic syntax:
65
+ pinggy [options] [user@domain]
66
+
67
+ - user@domain is optional. Domain can be any valid domain supported by the service backend (e.g., ap.example.com).
68
+
69
+ ### Options
70
+ The CLI supports both SSH-style flags and more descriptive long flags. Below is a consolidated list (only public ones are shown here). For the most up-to-date help, run pinggy --help.
71
+
72
+ - -R, --R <value> Local port forwarding (SSH-style).
73
+ Example: -R0:localhost:3000 forwards tunnel traffic to local port 3000.
74
+ - -L, --L <value> Web debugger address (SSH-style).
75
+ Example: -L4300:localhost:4300 starts web debugger on port 4300.
76
+ - -p, --server-port <value> Pinggy server port (default: 443).
77
+ - --type <value> Type of connection (e.g., tcp for raw TCP tunnel).
78
+ - -l, --localport <value> Local endpoint as [protocol:][host:]port.
79
+ Examples: --localport https://localhost:8000 or -l 3000
80
+ - -d, --debugger <value> Port for web debugger (e.g., -d 4300).
81
+ - --token <value> Token for authentication.
82
+
83
+ Logging:
84
+ - --loglevel <value> Logging level: ERROR, INFO, DEBUG.
85
+ - --logfile <path> Path to log file.
86
+ - -g, --printlog Also print logs to stdout.
87
+
88
+ Config:
89
+ - --saveconf <file> Create a configuration file based on the provided options.
90
+ - --conf <file> Load configuration from file; CLI options override it.
91
+
92
+ File server:
93
+ - --serve <path> Serve files from a local directory via a simple web server.
94
+
95
+ Remote control:
96
+ - --remote-management <token> Enable remote management of tunnels using api key.
97
+ - --manage <addr> Remote management server (default: dashboard.pinggy.io).
98
+ - --NoTUI Disable TUI in remote management mode.
99
+
100
+ Misc:
101
+ - --version Print version and exit.
102
+ - -h, --help Show help and exit.
103
+
104
+
105
+ ### Extended options
106
+ Extended options provide advanced controls. Specify them as positional values like x:https or w:192.168.1.0/24 alongside other CLI flags.
107
+
108
+ - x:https Enforce HTTPS-only (HTTP redirected to HTTPS).
109
+ - x:passpreflight | x:allowpreflight Allow CORS preflight to pass unchanged.
110
+ - x:reverseproxy Disable built-in reverse-proxy header injection.
111
+ - x:xff Add X-Forwarded-For.
112
+ - x:fullurl | x:fullrequesturl Include original request URL.
113
+ - w:<cidr>[,<cidr>...] Whitelist IPs (IPv4 CIDR).
114
+ - k:<token> Set Bearer token(s) for auth (repeatable).
115
+ - b:<user:pass> Add Basic Auth credentials (repeatable).
116
+ - a:<Key:Val> Add header.
117
+ - u:<Key:Val> Update header.
118
+ - r:<Key> Remove header.
119
+
120
+ Examples:
121
+ - Enforce HTTPS and XFF for local HTTPS server on 8443:
122
+ pinggy x:https x:xff -l https://localhost:8443
123
+
124
+ - Allow only a local subnet:
125
+ pinggy w:192.168.1.0/24 -l 8080
126
+
127
+ To generate advanced CLI arguments, use [Configure from Pinggy.io](https://pinggy.io/)
128
+
129
+
130
+ ## Remote management
131
+ You can control tunnels remotely using a secure WebSocket connection.
132
+
133
+ - Start remote management with a token:
134
+ ```bash
135
+ pinggy --remote-management <APIKEY>
136
+ ```
137
+
138
+ - Specify a management server (default is wss://dashboard.pinggy.io):
139
+ ```bash
140
+ pinggy --remote-management <TOKEN> --manage wss://custom.example.com
141
+ ```
142
+
143
+
144
+
145
+ ## Logging
146
+ You can control logs via CLI flags (which override environment variables). If logfile is provided, the log directory will be created if it does not exist.
147
+
148
+ - To log to file and stdout at INFO level:
149
+ ```bash
150
+ pinggy -p 3000 --logfile ~/.pinggy/pinggy.log --loglevel INFO --printlog
151
+ ```
152
+
153
+
154
+
155
+ ## Saving and loading configuration
156
+ - Save current options to a file:
157
+ ```bash
158
+ pinggy -p 443 -L4300:localhost:4300 -t -R0:127.0.0.1:8000 qr+force@free.pinggy.io x:noreverseproxy x:passpreflight x:xff --saveconf myconfig.json
159
+ ```
160
+ - Use a config as base and override with flags:
161
+ ```bash
162
+ pinggy --conf ./myconfig.json -p 8080
163
+ ```
164
+
165
+
166
+ ## File server mode
167
+ Serve a local directory quickly over a tunnel:
168
+ pinggy --serve /path/to/files
169
+ Optionally combine with other flags (auth, IP whitelist) as needed.
170
+
171
+
172
+ ## Signals and shutdown
173
+ Press Ctrl+C to stop. The CLI traps SIGINT and gracefully stops active tunnels before exiting.
174
+
175
+
176
+
177
+ ## Versioning
178
+ This package follows semantic versioning. See package.json for the current version.
179
+
180
+
181
+ ## License
182
+ Apache License Version 2.0
@@ -0,0 +1,39 @@
1
+ // @ts-ignore
2
+ export const TUNNEL_CONFIG = [
3
+ {
4
+ configId: "4ddea4c7-9c3a-4051-a3f1-04a60c55bc9a",
5
+ token: "adsfadsf",
6
+ serverAddress: "a.pinggy.io",
7
+ forwarding: "localhost:8000",
8
+ webDebugger: "",
9
+ tunnelType: ["http" /* TunnelType.Http */],
10
+ ipWhitelist: [],
11
+ bearerTokenAuth: [],
12
+ basicAuth: [],
13
+ headerModification: [],
14
+ xForwardedFor: "",
15
+ httpsOnly: false,
16
+ originalRequestUrl: false,
17
+ allowPreflight: false,
18
+ reverseProxy: false,
19
+ force: true,
20
+ },
21
+ {
22
+ configId: "4ddea4c7-9c3a-4051-a3f1-04a60c55bc9b",
23
+ token: "adsfadsf",
24
+ serverAddress: "a.pinggy.io",
25
+ forwarding: "localhost:8000",
26
+ webDebugger: "",
27
+ tunnelType: ["udp" /* TunnelType.Udp */],
28
+ ipWhitelist: [],
29
+ bearerTokenAuth: [],
30
+ basicAuth: [],
31
+ headerModification: [],
32
+ xForwardedFor: "",
33
+ httpsOnly: false,
34
+ originalRequestUrl: false,
35
+ allowPreflight: false,
36
+ reverseProxy: false,
37
+ force: true,
38
+ },
39
+ ];
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.TunnelManager = void 0;
13
+ const pinggy_1 = require("@pinggy/pinggy");
14
+ const logger_1 = require("./logger");
15
+ class TunnelManager {
16
+ constructor() {
17
+ this.tunnelsByTunnelId = new Map();
18
+ this.tunnelsByConfigId = new Map();
19
+ }
20
+ /**
21
+ * Create (but not start) a tunnel
22
+ */
23
+ createTunnel(config) {
24
+ const { configId, additionalForwarding } = config;
25
+ if (this.tunnelsByConfigId.has(configId)) {
26
+ throw new Error(`Tunnel with configId "${configId}" already exists`);
27
+ }
28
+ const tunnelId = crypto.randomUUID();
29
+ const instance = pinggy_1.pinggy.createTunnel(config);
30
+ const managed = {
31
+ tunnelId,
32
+ configId,
33
+ instance,
34
+ additionalForwarding,
35
+ };
36
+ this.tunnelsByTunnelId.set(tunnelId, managed);
37
+ this.tunnelsByConfigId.set(configId, managed);
38
+ logger_1.logger.info("Tunnel created", { configId, tunnelId });
39
+ return managed;
40
+ }
41
+ /**
42
+ * Start a tunnel that was created but not yet started
43
+ */
44
+ startTunnel(tunnelId) {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ const managed = this.tunnelsByTunnelId.get(tunnelId);
47
+ if (!managed)
48
+ throw new Error(`Tunnel with id "${tunnelId}" not found`);
49
+ logger_1.logger.info("Starting tunnel", { tunnelId, configId: managed.configId });
50
+ const urls = yield managed.instance.start();
51
+ logger_1.logger.info("Tunnel started", { tunnelId, urls });
52
+ // Apply any additional forwarding after the tunnel has started
53
+ if (Array.isArray(managed.additionalForwarding) && managed.additionalForwarding.length > 0) {
54
+ logger_1.logger.debug("Applying additional forwarding rules", managed.additionalForwarding);
55
+ for (const f of managed.additionalForwarding) {
56
+ try {
57
+ if (!f || !f.remotePort || !f.localDomain || !f.localPort)
58
+ continue;
59
+ const hostname = f.remoteDomain && f.remoteDomain.length > 0
60
+ ? `${f.remoteDomain}:${f.remotePort}`
61
+ : `${f.remotePort}`;
62
+ const target = `${f.localDomain}:${f.localPort}`;
63
+ managed.instance.tunnelRequestAdditionalForwarding(hostname, target);
64
+ logger_1.logger.info("Applied additional forwarding", { tunnelId, hostname, target });
65
+ }
66
+ catch (e) {
67
+ logger_1.logger.warn(`Failed to apply additional forwarding (${JSON.stringify(f)}):`, e);
68
+ }
69
+ }
70
+ }
71
+ return urls;
72
+ });
73
+ }
74
+ /**
75
+ * Stop a tunnel by tunnelId
76
+ */
77
+ stopTunnel(tunnelId) {
78
+ const managed = this.tunnelsByTunnelId.get(tunnelId);
79
+ if (!managed)
80
+ throw new Error(`Tunnel "${tunnelId}" not found`);
81
+ logger_1.logger.info("Stopping tunnel", { tunnelId, configId: managed.configId });
82
+ managed.instance.stop();
83
+ this.tunnelsByTunnelId.delete(tunnelId);
84
+ this.tunnelsByConfigId.delete(managed.configId);
85
+ logger_1.logger.info("Tunnel stopped", { tunnelId });
86
+ }
87
+ /**
88
+ * Get all public URLs for a tunnel
89
+ */
90
+ getTunnelUrls(tunnelId) {
91
+ const managed = this.tunnelsByTunnelId.get(tunnelId);
92
+ if (!managed)
93
+ throw new Error(`Tunnel "${tunnelId}" not found`);
94
+ const urls = managed.instance.urls();
95
+ logger_1.logger.debug("Queried tunnel URLs", { tunnelId, urls });
96
+ return urls;
97
+ }
98
+ /**
99
+ * Get status of a tunnel
100
+ */
101
+ getTunnelStatus(tunnelId) {
102
+ const managed = this.tunnelsByTunnelId.get(tunnelId);
103
+ if (!managed)
104
+ throw new Error(`Tunnel "${tunnelId}" not found`);
105
+ const status = managed.instance.getStatus();
106
+ logger_1.logger.debug("Queried tunnel status", { tunnelId, status });
107
+ return status;
108
+ }
109
+ /**
110
+ * Stop all tunnels
111
+ */
112
+ stopAllTunnels() {
113
+ for (const { instance } of this.tunnelsByTunnelId.values()) {
114
+ try {
115
+ instance.stop();
116
+ }
117
+ catch (e) {
118
+ logger_1.logger.warn("Error stopping tunnel instance", e);
119
+ }
120
+ }
121
+ this.tunnelsByTunnelId.clear();
122
+ this.tunnelsByConfigId.clear();
123
+ logger_1.logger.info("All tunnels stopped and cleared");
124
+ }
125
+ getTunnelInstance(configId, tunnelId) {
126
+ if (configId) {
127
+ const managed = this.tunnelsByConfigId.get(configId);
128
+ if (!managed)
129
+ throw new Error(`Tunnel "${configId}" not found`);
130
+ return managed.instance;
131
+ }
132
+ if (tunnelId) {
133
+ const managed = this.tunnelsByTunnelId.get(tunnelId);
134
+ if (!managed)
135
+ throw new Error(`Tunnel "${tunnelId}" not found`);
136
+ return managed.instance;
137
+ }
138
+ throw new Error(`Either configId or tunnelId must be provided`);
139
+ }
140
+ /**
141
+ * Get tunnel config by tunnelId
142
+ */
143
+ getTunnelConfig(configId, tunnelId) {
144
+ if (configId) {
145
+ const tunnelInstance = this.getTunnelInstance(configId);
146
+ return tunnelInstance.getConfig();
147
+ }
148
+ if (tunnelId) {
149
+ const tunnelInstance = this.getTunnelInstance(tunnelId);
150
+ return tunnelInstance.getConfig();
151
+ }
152
+ throw new Error(`Either configId or tunnelId must be provided`);
153
+ }
154
+ }
155
+ exports.TunnelManager = TunnelManager;