pinggy 0.6.9 → 0.6.11
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.
- package/ARCHITECTURE.md +21 -8
- package/CLAUDE.md +7 -3
- package/README.md +12 -0
- package/dist/{chunk-MHQ3CVEB.js → chunk-P54K7NPF.js} +5 -1
- package/dist/chunk-RYO5T2JT.js +1947 -0
- package/dist/{chunk-LF6WMFWT.js → chunk-W47AYOH2.js} +6800 -2025
- package/dist/{daemonChild-WTZ7X6SZ.js → daemonChild-GGG34AOT.js} +7 -5
- package/dist/index.cjs +3234 -432
- package/dist/index.d.cts +75 -2
- package/dist/index.d.ts +75 -2
- package/dist/index.js +21 -5
- package/dist/{ipcClient-IZ5R6TPN.js → ipcClient-6QESURCH.js} +1 -1
- package/dist/{main-INPCUGAN.js → main-FCIOVX5I.js} +5 -8
- package/dist/{updateChild-BPWBQ3WR.js → updateChild-RNCLN24C.js} +12 -14
- package/package.json +1 -1
- package/scripts/install/install.ps1 +3 -2
- package/scripts/install/install.sh +13 -7
- package/dist/chunk-HJECJ7LC.js +0 -889
- package/dist/chunk-OQVFQ5VG.js +0 -1041
- package/dist/chunk-Q5RYSWFK.js +0 -2204
package/dist/chunk-Q5RYSWFK.js
DELETED
|
@@ -1,2204 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
IPCClient
|
|
3
|
-
} from "./chunk-MHQ3CVEB.js";
|
|
4
|
-
import {
|
|
5
|
-
TunnelAlreadyRunningError,
|
|
6
|
-
TunnelManager,
|
|
7
|
-
TunnelRebuildInProgressError
|
|
8
|
-
} from "./chunk-5HBGVJSW.js";
|
|
9
|
-
import {
|
|
10
|
-
ensureDaemonRunning,
|
|
11
|
-
getDaemonInfo,
|
|
12
|
-
getInProcessDaemonHandle,
|
|
13
|
-
ipcMismatchMessage,
|
|
14
|
-
isIpcCompatible,
|
|
15
|
-
printDaemonVersionNoticeOnce
|
|
16
|
-
} from "./chunk-OQVFQ5VG.js";
|
|
17
|
-
import {
|
|
18
|
-
SessionMode
|
|
19
|
-
} from "./chunk-MKGD2QAI.js";
|
|
20
|
-
import {
|
|
21
|
-
ErrorCode,
|
|
22
|
-
NewErrorResponseObject,
|
|
23
|
-
NewResponseObject,
|
|
24
|
-
RemoteManagementStatus,
|
|
25
|
-
errorMessage,
|
|
26
|
-
getVersion,
|
|
27
|
-
isErrorResponse,
|
|
28
|
-
isValidPort,
|
|
29
|
-
newErrorResponse,
|
|
30
|
-
newStats,
|
|
31
|
-
newStatus,
|
|
32
|
-
printer_default
|
|
33
|
-
} from "./chunk-HTIWY3O5.js";
|
|
34
|
-
import {
|
|
35
|
-
logger
|
|
36
|
-
} from "./chunk-DGAH7UVX.js";
|
|
37
|
-
|
|
38
|
-
// src/remote_management/remote_schema.ts
|
|
39
|
-
import { HaProxyVersion, TunnelType } from "@pinggy/pinggy";
|
|
40
|
-
import { z } from "zod";
|
|
41
|
-
var HeaderModificationSchema = z.object({
|
|
42
|
-
key: z.string(),
|
|
43
|
-
value: z.array(z.string()).nullable().optional(),
|
|
44
|
-
type: z.enum(["add", "remove", "update"])
|
|
45
|
-
});
|
|
46
|
-
var AdditionalForwardingSchema = z.object({
|
|
47
|
-
remoteDomain: z.string().optional(),
|
|
48
|
-
remotePort: z.number().optional(),
|
|
49
|
-
localDomain: z.string(),
|
|
50
|
-
localPort: z.number()
|
|
51
|
-
});
|
|
52
|
-
var TunnelConfigSchema = z.object({
|
|
53
|
-
allowPreflight: z.boolean().optional(),
|
|
54
|
-
// primary key
|
|
55
|
-
allowpreflight: z.boolean().optional(),
|
|
56
|
-
// legacy key
|
|
57
|
-
autoreconnect: z.boolean(),
|
|
58
|
-
basicauth: z.array(z.object({ username: z.string(), password: z.string() })).nullable(),
|
|
59
|
-
bearerauth: z.array(z.string()).nullable(),
|
|
60
|
-
configid: z.string(),
|
|
61
|
-
configname: z.string(),
|
|
62
|
-
greetmsg: z.string().optional(),
|
|
63
|
-
force: z.boolean(),
|
|
64
|
-
forwardedhost: z.string(),
|
|
65
|
-
fullRequestUrl: z.boolean(),
|
|
66
|
-
headermodification: z.array(HeaderModificationSchema),
|
|
67
|
-
httpsOnly: z.boolean(),
|
|
68
|
-
internalwebdebuggerport: z.number(),
|
|
69
|
-
ipwhitelist: z.array(z.string()).nullable(),
|
|
70
|
-
localport: z.number(),
|
|
71
|
-
localsservertls: z.union([z.boolean(), z.string()]),
|
|
72
|
-
localservertlssni: z.string().nullable(),
|
|
73
|
-
regioncode: z.string(),
|
|
74
|
-
noReverseProxy: z.boolean(),
|
|
75
|
-
serveraddress: z.string(),
|
|
76
|
-
serverport: z.number(),
|
|
77
|
-
statusCheckInterval: z.number(),
|
|
78
|
-
token: z.string(),
|
|
79
|
-
tunnelTimeout: z.number(),
|
|
80
|
-
type: z.enum([
|
|
81
|
-
TunnelType.Http,
|
|
82
|
-
TunnelType.Tcp,
|
|
83
|
-
TunnelType.Udp,
|
|
84
|
-
TunnelType.Tls,
|
|
85
|
-
TunnelType.TlsTcp
|
|
86
|
-
]),
|
|
87
|
-
webdebuggerport: z.number(),
|
|
88
|
-
xff: z.string(),
|
|
89
|
-
additionalForwarding: z.array(AdditionalForwardingSchema).optional(),
|
|
90
|
-
serve: z.string().optional()
|
|
91
|
-
}).superRefine((data, ctx) => {
|
|
92
|
-
if (data.allowPreflight === void 0 && data.allowpreflight === void 0) {
|
|
93
|
-
ctx.addIssue({
|
|
94
|
-
code: "custom",
|
|
95
|
-
message: "Either allowPreflight or allowpreflight is required",
|
|
96
|
-
path: ["allowPreflight"]
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
}).transform((data) => ({
|
|
100
|
-
...data,
|
|
101
|
-
allowPreflight: data.allowPreflight ?? data.allowpreflight,
|
|
102
|
-
allowpreflight: data.allowPreflight ?? data.allowpreflight
|
|
103
|
-
}));
|
|
104
|
-
var StartSchema = z.object({
|
|
105
|
-
tunnelID: z.string().nullable().optional(),
|
|
106
|
-
tunnelConfig: TunnelConfigSchema
|
|
107
|
-
});
|
|
108
|
-
var StopSchema = z.object({
|
|
109
|
-
tunnelID: z.string().min(1)
|
|
110
|
-
});
|
|
111
|
-
var GetSchema = StopSchema;
|
|
112
|
-
var RestartSchema = StopSchema;
|
|
113
|
-
var UpdateConfigSchema = z.object({
|
|
114
|
-
tunnelConfig: TunnelConfigSchema
|
|
115
|
-
});
|
|
116
|
-
var ForwardingEntryV2Schema = z.object({
|
|
117
|
-
listenAddress: z.string().optional(),
|
|
118
|
-
address: z.string(),
|
|
119
|
-
type: z.enum([TunnelType.Http, TunnelType.Tcp, TunnelType.Udp, TunnelType.Tls, TunnelType.TlsTcp]).default(TunnelType.Http)
|
|
120
|
-
});
|
|
121
|
-
var OptionalSchema = z.object({
|
|
122
|
-
sniServerName: z.string().optional(),
|
|
123
|
-
ssl: z.boolean().optional(),
|
|
124
|
-
additionalArguments: z.string().optional(),
|
|
125
|
-
serve: z.string().optional(),
|
|
126
|
-
manage: z.string().optional(),
|
|
127
|
-
remoteManagement: z.object({ serverUrl: z.string(), apiKey: z.string() }).optional(),
|
|
128
|
-
noTui: z.boolean().optional()
|
|
129
|
-
}).catchall(z.unknown());
|
|
130
|
-
var TunnelConfigV1Schema = z.object({
|
|
131
|
-
// Meta Info
|
|
132
|
-
version: z.string(),
|
|
133
|
-
name: z.string(),
|
|
134
|
-
configId: z.string(),
|
|
135
|
-
hostKeyCheck: z.boolean().optional(),
|
|
136
|
-
platformValue: z.string().optional(),
|
|
137
|
-
isQRCode: z.boolean().optional(),
|
|
138
|
-
// General tunnel configurations
|
|
139
|
-
serverAddress: z.string().optional(),
|
|
140
|
-
token: z.string().optional(),
|
|
141
|
-
autoReconnect: z.boolean().optional(),
|
|
142
|
-
reconnectInterval: z.number().optional(),
|
|
143
|
-
maxReconnectAttempts: z.number().optional(),
|
|
144
|
-
force: z.boolean(),
|
|
145
|
-
keepAliveInterval: z.number().optional(),
|
|
146
|
-
webDebugger: z.string(),
|
|
147
|
-
//Forwarding
|
|
148
|
-
// Either a URL string (e.g. "https://localhost:5555") or an array of forwarding entries.
|
|
149
|
-
forwarding: z.union([
|
|
150
|
-
z.string(),
|
|
151
|
-
z.array(ForwardingEntryV2Schema)
|
|
152
|
-
]),
|
|
153
|
-
// IP whitelist
|
|
154
|
-
ipWhitelist: z.array(z.string()).optional(),
|
|
155
|
-
basicAuth: z.array(z.object({ username: z.string(), password: z.string() })).optional(),
|
|
156
|
-
bearerTokenAuth: z.array(z.string()).optional(),
|
|
157
|
-
headerModification: z.array(HeaderModificationSchema).optional(),
|
|
158
|
-
reverseProxy: z.boolean().optional(),
|
|
159
|
-
xForwardedFor: z.boolean().optional(),
|
|
160
|
-
httpsOnly: z.boolean().optional(),
|
|
161
|
-
originalRequestUrl: z.boolean().optional(),
|
|
162
|
-
allowPreflight: z.boolean().optional(),
|
|
163
|
-
haProxy: z.enum([HaProxyVersion.V1, HaProxyVersion.V2]).optional(),
|
|
164
|
-
serve: z.string().optional(),
|
|
165
|
-
optional: z.record(z.string(), z.unknown()).optional()
|
|
166
|
-
}).superRefine((config, ctx) => {
|
|
167
|
-
if (!config.haProxy) {
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
const entries = Array.isArray(config.forwarding) ? config.forwarding : [];
|
|
171
|
-
const primaryType = entries.length > 0 ? entries[0].type : void 0;
|
|
172
|
-
if (primaryType !== TunnelType.Tcp) {
|
|
173
|
-
ctx.addIssue({
|
|
174
|
-
code: "custom",
|
|
175
|
-
path: ["haProxy"],
|
|
176
|
-
message: `haProxy can only be used with "tcp" tunnels, but the first forwarding rule has type: ${primaryType ?? TunnelType.Http}`
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
});
|
|
180
|
-
var TUNNEL_CONFIG_V1_KEYS = Object.keys(
|
|
181
|
-
TunnelConfigV1Schema.shape
|
|
182
|
-
);
|
|
183
|
-
var StartV2Schema = z.object({
|
|
184
|
-
tunnelID: z.string().nullable().optional(),
|
|
185
|
-
tunnelConfig: TunnelConfigV1Schema
|
|
186
|
-
});
|
|
187
|
-
var UpdateConfigV2Schema = z.object({
|
|
188
|
-
tunnelConfig: TunnelConfigV1Schema
|
|
189
|
-
});
|
|
190
|
-
function pinggyOptionsToTunnelConfigV1(opts, configStoredInCli) {
|
|
191
|
-
const parsedTokens = opts.bearerTokenAuth ? Array.isArray(opts.bearerTokenAuth) ? opts.bearerTokenAuth : JSON.parse(opts.bearerTokenAuth) : [];
|
|
192
|
-
return {
|
|
193
|
-
version: configStoredInCli.version || "1.0",
|
|
194
|
-
name: configStoredInCli.name || "",
|
|
195
|
-
configId: configStoredInCli.configId || "",
|
|
196
|
-
serverAddress: opts.serverAddress || "a.pinggy.io:443",
|
|
197
|
-
token: opts.token || "",
|
|
198
|
-
autoReconnect: opts.autoReconnect ?? true,
|
|
199
|
-
reconnectInterval: opts.reconnectInterval,
|
|
200
|
-
maxReconnectAttempts: opts.maxReconnectAttempts,
|
|
201
|
-
force: opts.force ?? false,
|
|
202
|
-
webDebugger: opts.webDebugger || "",
|
|
203
|
-
forwarding: opts.forwarding ? opts.forwarding : "",
|
|
204
|
-
ipWhitelist: opts.ipWhitelist ? Array.isArray(opts.ipWhitelist) ? opts.ipWhitelist : JSON.parse(opts.ipWhitelist) : [],
|
|
205
|
-
basicAuth: opts.basicAuth && Object.keys(opts.basicAuth).length ? opts.basicAuth : void 0,
|
|
206
|
-
bearerTokenAuth: parsedTokens.length ? parsedTokens : void 0,
|
|
207
|
-
headerModification: opts.headerModification || [],
|
|
208
|
-
reverseProxy: opts.reverseProxy ?? false,
|
|
209
|
-
xForwardedFor: !!opts.xForwardedFor,
|
|
210
|
-
httpsOnly: opts.httpsOnly ?? false,
|
|
211
|
-
originalRequestUrl: opts.originalRequestUrl ?? false,
|
|
212
|
-
allowPreflight: opts.allowPreflight ?? false,
|
|
213
|
-
haProxy: opts.haProxy,
|
|
214
|
-
optional: {
|
|
215
|
-
...configStoredInCli.optional || {},
|
|
216
|
-
...opts.optional || {}
|
|
217
|
-
}
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
function tunnelConfigToPinggyOptions(config) {
|
|
221
|
-
const forwardingData = [];
|
|
222
|
-
forwardingData.push({
|
|
223
|
-
address: `${config.forwardedhost}:${config.localport}`,
|
|
224
|
-
type: config.type || TunnelType.Http
|
|
225
|
-
// Default to HTTP for the primary forwarding entry
|
|
226
|
-
});
|
|
227
|
-
if (config.additionalForwarding && Array.isArray(config.additionalForwarding)) {
|
|
228
|
-
config.additionalForwarding.forEach((entry) => {
|
|
229
|
-
if (entry.localDomain && entry.localPort && entry.remoteDomain) {
|
|
230
|
-
const listenAddress = entry.remotePort && isValidPort(entry.remotePort) ? `${entry.remoteDomain}:${entry.remotePort}` : entry.remoteDomain;
|
|
231
|
-
forwardingData.push({
|
|
232
|
-
address: `${entry.localDomain}:${entry.localPort}`,
|
|
233
|
-
listenAddress,
|
|
234
|
-
type: TunnelType.Http
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
});
|
|
238
|
-
}
|
|
239
|
-
return {
|
|
240
|
-
token: config.token || "",
|
|
241
|
-
serverAddress: config.serveraddress || "free.pinggy.io",
|
|
242
|
-
forwarding: forwardingData,
|
|
243
|
-
webDebugger: config.webdebuggerport ? `localhost:${config.webdebuggerport}` : "",
|
|
244
|
-
ipWhitelist: config.ipwhitelist || [],
|
|
245
|
-
basicAuth: config.basicauth ? config.basicauth : [],
|
|
246
|
-
bearerTokenAuth: config.bearerauth || [],
|
|
247
|
-
headerModification: config.headermodification,
|
|
248
|
-
xForwardedFor: !!config.xff,
|
|
249
|
-
httpsOnly: config.httpsOnly,
|
|
250
|
-
originalRequestUrl: config.fullRequestUrl,
|
|
251
|
-
allowPreflight: config.allowPreflight,
|
|
252
|
-
reverseProxy: config.noReverseProxy,
|
|
253
|
-
force: config.force,
|
|
254
|
-
autoReconnect: config.autoreconnect,
|
|
255
|
-
optional: {
|
|
256
|
-
sniServerName: config.localservertlssni || ""
|
|
257
|
-
}
|
|
258
|
-
};
|
|
259
|
-
}
|
|
260
|
-
function pinggyOptionsToTunnelConfig(opts, configid, configName, localserverTls, greetMsg, serve) {
|
|
261
|
-
let primaryEntry;
|
|
262
|
-
let additionalEntries = [];
|
|
263
|
-
if (Array.isArray(opts.forwarding)) {
|
|
264
|
-
primaryEntry = opts.forwarding.find((e) => !e.listenAddress) ?? opts.forwarding[0];
|
|
265
|
-
additionalEntries = opts.forwarding.filter(
|
|
266
|
-
(e) => e !== primaryEntry && Boolean(e.listenAddress)
|
|
267
|
-
);
|
|
268
|
-
}
|
|
269
|
-
const forwarding = primaryEntry ? String(primaryEntry.address) : String(opts.forwarding);
|
|
270
|
-
const [parsedForwardedHost, portStr] = forwarding.split(":");
|
|
271
|
-
const parsedLocalPort = parseInt(portStr, 10);
|
|
272
|
-
const tunnelType = primaryEntry?.type ?? TunnelType.Http;
|
|
273
|
-
const additionalForwarding = additionalEntries.map((e) => {
|
|
274
|
-
const [localDomain, localPortStr] = String(e.address).split(":");
|
|
275
|
-
const [remoteDomain, remotePortStr] = String(e.listenAddress).split(":");
|
|
276
|
-
const localPort = parseInt(localPortStr, 10);
|
|
277
|
-
const remotePort = parseInt(remotePortStr, 10);
|
|
278
|
-
return {
|
|
279
|
-
localDomain,
|
|
280
|
-
localPort: isNaN(localPort) ? 0 : localPort,
|
|
281
|
-
remoteDomain,
|
|
282
|
-
remotePort: isNaN(remotePort) ? 0 : remotePort
|
|
283
|
-
};
|
|
284
|
-
});
|
|
285
|
-
const parsedTokens = opts.bearerTokenAuth ? Array.isArray(opts.bearerTokenAuth) ? opts.bearerTokenAuth : JSON.parse(opts.bearerTokenAuth) : [];
|
|
286
|
-
return {
|
|
287
|
-
allowPreflight: opts.allowPreflight ?? false,
|
|
288
|
-
allowpreflight: opts.allowPreflight ?? false,
|
|
289
|
-
autoreconnect: opts.autoReconnect ?? false,
|
|
290
|
-
basicauth: opts.basicAuth && Object.keys(opts.basicAuth).length ? opts.basicAuth : null,
|
|
291
|
-
bearerauth: parsedTokens.length ? [parsedTokens.join(",")] : null,
|
|
292
|
-
configid,
|
|
293
|
-
configname: configName,
|
|
294
|
-
greetmsg: greetMsg || "",
|
|
295
|
-
force: opts.force ?? false,
|
|
296
|
-
forwardedhost: parsedForwardedHost || "localhost",
|
|
297
|
-
fullRequestUrl: opts.originalRequestUrl ?? false,
|
|
298
|
-
headermodification: opts.headerModification || [],
|
|
299
|
-
//structured list
|
|
300
|
-
httpsOnly: opts.httpsOnly ?? false,
|
|
301
|
-
internalwebdebuggerport: 0,
|
|
302
|
-
ipwhitelist: opts.ipWhitelist ? Array.isArray(opts.ipWhitelist) ? opts.ipWhitelist : JSON.parse(opts.ipWhitelist) : null,
|
|
303
|
-
localport: parsedLocalPort || 0,
|
|
304
|
-
localservertlssni: null,
|
|
305
|
-
regioncode: "",
|
|
306
|
-
noReverseProxy: opts.reverseProxy ?? false,
|
|
307
|
-
serveraddress: opts.serverAddress || "free.pinggy.io",
|
|
308
|
-
serverport: 0,
|
|
309
|
-
statusCheckInterval: 0,
|
|
310
|
-
token: opts.token || "",
|
|
311
|
-
tunnelTimeout: 0,
|
|
312
|
-
type: tunnelType,
|
|
313
|
-
webdebuggerport: Number(opts.webDebugger?.split(":")[0]) || 0,
|
|
314
|
-
xff: opts.xForwardedFor ? "1" : "",
|
|
315
|
-
localsservertls: localserverTls || false,
|
|
316
|
-
additionalForwarding: additionalForwarding || [],
|
|
317
|
-
serve: serve || ""
|
|
318
|
-
};
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
// src/remote_management/handler.ts
|
|
322
|
-
var TunnelOperations = class {
|
|
323
|
-
constructor() {
|
|
324
|
-
this.tunnelManager = TunnelManager.getInstance();
|
|
325
|
-
}
|
|
326
|
-
buildStatus(tunnelId, state, errorCode) {
|
|
327
|
-
const status = newStatus(state, errorCode, "");
|
|
328
|
-
try {
|
|
329
|
-
const managed = this.tunnelManager.getManagedTunnel("", tunnelId);
|
|
330
|
-
if (managed) {
|
|
331
|
-
status.createdtimestamp = managed.createdAt || "";
|
|
332
|
-
status.starttimestamp = managed.startedAt || "";
|
|
333
|
-
status.endtimestamp = managed.stoppedAt || "";
|
|
334
|
-
}
|
|
335
|
-
if (managed?.lastError) {
|
|
336
|
-
status.lastError = managed.lastError;
|
|
337
|
-
if (managed.lastError.isFatal) {
|
|
338
|
-
status.errormsg = managed.lastError.message;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
} catch (e) {
|
|
342
|
-
}
|
|
343
|
-
return status;
|
|
344
|
-
}
|
|
345
|
-
// --- Placeholder response ---
|
|
346
|
-
buildPendingTunnelResponse(tunnelid, tunnelConfig, configid, tunnelName, serve) {
|
|
347
|
-
return {
|
|
348
|
-
tunnelid,
|
|
349
|
-
remoteurls: [],
|
|
350
|
-
tunnelconfig: pinggyOptionsToTunnelConfig(tunnelConfig, configid, tunnelName, false, void 0, serve),
|
|
351
|
-
status: this.buildStatus(tunnelid, "starting" /* Starting */, "" /* NoError */),
|
|
352
|
-
stats: newStats()
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
buildPendingTunnelResponseV2(tunnelid, tunnelConfig, configFromCli, configid, tunnelName, serve) {
|
|
356
|
-
return {
|
|
357
|
-
tunnelid,
|
|
358
|
-
remoteurls: [],
|
|
359
|
-
tunnelconfig: pinggyOptionsToTunnelConfigV1(tunnelConfig, configFromCli),
|
|
360
|
-
status: this.buildStatus(tunnelid, "starting" /* Starting */, "" /* NoError */),
|
|
361
|
-
stats: newStats(),
|
|
362
|
-
greetmsg: ""
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
// --- Helper to construct TunnelResponse ---
|
|
366
|
-
async buildTunnelResponse(tunnelid, tunnelConfig, configid, tunnelName, serve) {
|
|
367
|
-
const stats = this.tunnelManager.getLatestTunnelStats(tunnelid) || newStats();
|
|
368
|
-
const [status, tlsInfo, greetMsg, remoteurls] = await Promise.all([
|
|
369
|
-
this.tunnelManager.getTunnelStatus(tunnelid),
|
|
370
|
-
this.tunnelManager.getLocalserverTlsInfo(tunnelid),
|
|
371
|
-
this.tunnelManager.getTunnelGreetMessage(tunnelid),
|
|
372
|
-
this.tunnelManager.getTunnelUrls(tunnelid)
|
|
373
|
-
]);
|
|
374
|
-
return {
|
|
375
|
-
tunnelid,
|
|
376
|
-
remoteurls,
|
|
377
|
-
tunnelconfig: pinggyOptionsToTunnelConfig(tunnelConfig, configid, tunnelName, tlsInfo, greetMsg),
|
|
378
|
-
status: this.buildStatus(tunnelid, status, "" /* NoError */),
|
|
379
|
-
stats
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
async buildTunnelResponseV2(tunnelid, tunnelConfig, configFromCli, configid, tunnelName, serve) {
|
|
383
|
-
const stats = this.tunnelManager.getLatestTunnelStats(tunnelid) || newStats();
|
|
384
|
-
const [status, greetMsg, remoteurls] = await Promise.all([
|
|
385
|
-
this.tunnelManager.getTunnelStatus(tunnelid),
|
|
386
|
-
this.tunnelManager.getTunnelGreetMessage(tunnelid),
|
|
387
|
-
this.tunnelManager.getTunnelUrls(tunnelid)
|
|
388
|
-
]);
|
|
389
|
-
return {
|
|
390
|
-
tunnelid,
|
|
391
|
-
remoteurls,
|
|
392
|
-
tunnelconfig: pinggyOptionsToTunnelConfigV1(tunnelConfig, configFromCli),
|
|
393
|
-
status: this.buildStatus(tunnelid, status, "" /* NoError */),
|
|
394
|
-
stats,
|
|
395
|
-
greetmsg: greetMsg
|
|
396
|
-
};
|
|
397
|
-
}
|
|
398
|
-
error(code, err, fallback) {
|
|
399
|
-
return newErrorResponse({
|
|
400
|
-
code,
|
|
401
|
-
message: err instanceof Error ? err.message : fallback
|
|
402
|
-
});
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* A restart or update of a tunnel another one is still rebuilding. A no-wait call checks this before
|
|
406
|
-
* it answers, because a throw from the call it does not await is only logged.
|
|
407
|
-
*/
|
|
408
|
-
rebuildInProgress(tunnelid) {
|
|
409
|
-
const err = new TunnelRebuildInProgressError(tunnelid);
|
|
410
|
-
return this.error(ErrorCode.TunnelAlreadyRunningError, err, err.message);
|
|
411
|
-
}
|
|
412
|
-
// --- Operations ---
|
|
413
|
-
async handleStart(config, noWait = false, origin = "cli") {
|
|
414
|
-
try {
|
|
415
|
-
const opts = tunnelConfigToPinggyOptions(config);
|
|
416
|
-
const managed = await this.tunnelManager.createTunnel({
|
|
417
|
-
...opts,
|
|
418
|
-
configId: config.configid,
|
|
419
|
-
name: config.configname,
|
|
420
|
-
optional: {
|
|
421
|
-
serve: config.serve
|
|
422
|
-
}
|
|
423
|
-
}, origin);
|
|
424
|
-
const { tunnelid, tunnelName, serve, tunnelConfig } = managed;
|
|
425
|
-
const startPromise = this.tunnelManager.startTunnel(tunnelid);
|
|
426
|
-
if (noWait) {
|
|
427
|
-
startPromise.catch((err) => {
|
|
428
|
-
logger.error("No-wait startTunnel failed", { tunnelid, err: String(err) });
|
|
429
|
-
});
|
|
430
|
-
return this.buildPendingTunnelResponse(tunnelid, tunnelConfig, config.configid, tunnelName, serve);
|
|
431
|
-
}
|
|
432
|
-
await startPromise;
|
|
433
|
-
const tunnelPconfig = await this.tunnelManager.getTunnelConfig("", tunnelid);
|
|
434
|
-
return this.buildTunnelResponse(tunnelid, tunnelPconfig, config.configid, tunnelName, serve);
|
|
435
|
-
} catch (err) {
|
|
436
|
-
return this.error(ErrorCode.ErrorStartingTunnel, err, "Unknown error occurred while starting tunnel");
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
async handleStartV2(config, noWait = false, origin = "cli") {
|
|
440
|
-
try {
|
|
441
|
-
const managed = await this.tunnelManager.createTunnel(config, origin);
|
|
442
|
-
const { tunnelid, tunnelConfig } = managed;
|
|
443
|
-
const startPromise = this.tunnelManager.startTunnel(tunnelid);
|
|
444
|
-
if (noWait) {
|
|
445
|
-
startPromise.catch((err) => {
|
|
446
|
-
logger.error("No-wait startTunnel failed", { tunnelid, err: String(err) });
|
|
447
|
-
});
|
|
448
|
-
return this.buildPendingTunnelResponseV2(tunnelid, tunnelConfig, config, config.configId, config.name, config.serve);
|
|
449
|
-
}
|
|
450
|
-
await startPromise;
|
|
451
|
-
const tunnelPconfig = await this.tunnelManager.getTunnelConfig("", tunnelid);
|
|
452
|
-
return this.buildTunnelResponseV2(tunnelid, tunnelPconfig, config, config.configId, config.name, config.serve);
|
|
453
|
-
} catch (err) {
|
|
454
|
-
if (err instanceof TunnelAlreadyRunningError) {
|
|
455
|
-
return this.error(ErrorCode.TunnelAlreadyRunningError, err, err.message);
|
|
456
|
-
}
|
|
457
|
-
return this.error(ErrorCode.ErrorStartingTunnel, err, "Unknown error occurred while starting tunnel");
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
async handleUpdateConfig(config, noWait = false) {
|
|
461
|
-
try {
|
|
462
|
-
const opts = tunnelConfigToPinggyOptions(config);
|
|
463
|
-
const updateOpts = {
|
|
464
|
-
...opts,
|
|
465
|
-
configId: config.configid,
|
|
466
|
-
name: config.configname,
|
|
467
|
-
optional: {
|
|
468
|
-
serve: config.serve
|
|
469
|
-
}
|
|
470
|
-
};
|
|
471
|
-
if (noWait) {
|
|
472
|
-
const existing = this.tunnelManager.getManagedTunnel(config.configid);
|
|
473
|
-
if (!existing.tunnelConfig) throw new Error("Invalid tunnel state before configuration update");
|
|
474
|
-
if (existing.rebuild) return this.rebuildInProgress(existing.tunnelid);
|
|
475
|
-
if (!existing.isStopped) {
|
|
476
|
-
this.tunnelManager.updateConfig(updateOpts).catch((err) => {
|
|
477
|
-
logger.error("No-wait updateConfig failed", { configid: config.configid, err: String(err) });
|
|
478
|
-
});
|
|
479
|
-
return this.buildPendingTunnelResponse(existing.tunnelid, existing.tunnelConfig, config.configid, existing.tunnelName, existing.serve);
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
const tunnel = await this.tunnelManager.updateConfig(updateOpts);
|
|
483
|
-
if (!tunnel.instance || !tunnel.tunnelConfig)
|
|
484
|
-
throw new Error("Invalid tunnel state after configuration update");
|
|
485
|
-
return this.buildTunnelResponse(tunnel.tunnelid, tunnel.tunnelConfig, config.configid, tunnel.tunnelName, tunnel.serve);
|
|
486
|
-
} catch (err) {
|
|
487
|
-
return this.error(ErrorCode.InternalServerError, err, "Failed to update tunnel configuration");
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
async handleUpdateConfigV2(config, noWait = false) {
|
|
491
|
-
try {
|
|
492
|
-
if (noWait) {
|
|
493
|
-
const existing = this.tunnelManager.getManagedTunnel(config.configId);
|
|
494
|
-
if (!existing.tunnelConfig) throw new Error("Invalid tunnel state before configuration update");
|
|
495
|
-
if (existing.rebuild) return this.rebuildInProgress(existing.tunnelid);
|
|
496
|
-
if (!existing.isStopped) {
|
|
497
|
-
this.tunnelManager.updateConfig(config).catch((err) => {
|
|
498
|
-
logger.error("No-wait updateConfigV2 failed", { configId: config.configId, err: String(err) });
|
|
499
|
-
});
|
|
500
|
-
return this.buildPendingTunnelResponseV2(existing.tunnelid, existing.tunnelConfig, config, config.configId, existing.tunnelName, existing.serve);
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
const tunnel = await this.tunnelManager.updateConfig(config);
|
|
504
|
-
if (!tunnel.instance || !tunnel.tunnelConfig)
|
|
505
|
-
throw new Error("Invalid tunnel state after configuration update");
|
|
506
|
-
return this.buildTunnelResponseV2(tunnel.tunnelid, tunnel.tunnelConfig, config, config.configId, tunnel.tunnelName, tunnel.serve);
|
|
507
|
-
} catch (err) {
|
|
508
|
-
return this.error(ErrorCode.InternalServerError, err, "Failed to update tunnel configuration");
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
async handleListV2() {
|
|
512
|
-
try {
|
|
513
|
-
const tunnels = await this.tunnelManager.getAllTunnels();
|
|
514
|
-
if (tunnels.length === 0) {
|
|
515
|
-
return [];
|
|
516
|
-
}
|
|
517
|
-
return Promise.all(
|
|
518
|
-
tunnels.map(async (t) => {
|
|
519
|
-
const rawStats = this.tunnelManager.getLatestTunnelStats(t.tunnelid) || newStats();
|
|
520
|
-
const [status, tlsInfo, greetMsg] = await Promise.all([
|
|
521
|
-
this.tunnelManager.getTunnelStatus(t.tunnelid),
|
|
522
|
-
this.tunnelManager.getLocalserverTlsInfo(t.tunnelid),
|
|
523
|
-
this.tunnelManager.getTunnelGreetMessage(t.tunnelid)
|
|
524
|
-
]);
|
|
525
|
-
const tunnelConfguration = status !== "closed" /* Closed */ && status !== "exited" /* Exited */ ? await this.tunnelManager.getTunnelConfig("", t.tunnelid) : t.tunnelConfig;
|
|
526
|
-
const tunnelConfig = pinggyOptionsToTunnelConfigV1(tunnelConfguration, t.tunnelConfig);
|
|
527
|
-
return {
|
|
528
|
-
tunnelid: t.tunnelid,
|
|
529
|
-
remoteurls: t.remoteurls,
|
|
530
|
-
status: this.buildStatus(t.tunnelid, status, "" /* NoError */),
|
|
531
|
-
stats: rawStats,
|
|
532
|
-
tunnelconfig: tunnelConfig,
|
|
533
|
-
greetmsg: greetMsg
|
|
534
|
-
};
|
|
535
|
-
})
|
|
536
|
-
);
|
|
537
|
-
} catch (err) {
|
|
538
|
-
return this.error(ErrorCode.InternalServerError, err, "Failed to list tunnels");
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
async handleList() {
|
|
542
|
-
try {
|
|
543
|
-
const tunnels = await this.tunnelManager.getAllTunnels();
|
|
544
|
-
if (tunnels.length === 0) {
|
|
545
|
-
return [];
|
|
546
|
-
}
|
|
547
|
-
return Promise.all(
|
|
548
|
-
tunnels.map(async (t) => {
|
|
549
|
-
const rawStats = this.tunnelManager.getLatestTunnelStats(t.tunnelid) || newStats();
|
|
550
|
-
const [status, tlsInfo, greetMsg] = await Promise.all([
|
|
551
|
-
this.tunnelManager.getTunnelStatus(t.tunnelid),
|
|
552
|
-
this.tunnelManager.getLocalserverTlsInfo(t.tunnelid),
|
|
553
|
-
this.tunnelManager.getTunnelGreetMessage(t.tunnelid)
|
|
554
|
-
]);
|
|
555
|
-
const pinggyOptions = status !== "closed" /* Closed */ && status !== "exited" /* Exited */ ? await this.tunnelManager.getTunnelConfig("", t.tunnelid) : t.tunnelConfig;
|
|
556
|
-
const tunnelConfig = pinggyOptionsToTunnelConfig(pinggyOptions, t.configId, t.tunnelName, tlsInfo, greetMsg, t.serve);
|
|
557
|
-
return {
|
|
558
|
-
tunnelid: t.tunnelid,
|
|
559
|
-
remoteurls: t.remoteurls,
|
|
560
|
-
status: this.buildStatus(t.tunnelid, status, "" /* NoError */),
|
|
561
|
-
stats: rawStats,
|
|
562
|
-
tunnelconfig: tunnelConfig
|
|
563
|
-
};
|
|
564
|
-
})
|
|
565
|
-
);
|
|
566
|
-
} catch (err) {
|
|
567
|
-
return this.error(ErrorCode.InternalServerError, err, "Failed to list tunnels");
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
async handleStop(tunnelid) {
|
|
571
|
-
try {
|
|
572
|
-
const { configId } = this.tunnelManager.stopTunnel(tunnelid);
|
|
573
|
-
const managed = this.tunnelManager.getManagedTunnel("", tunnelid);
|
|
574
|
-
if (!managed?.tunnelConfig) throw new Error(`Tunnel config for ID "${tunnelid}" not found`);
|
|
575
|
-
return this.buildTunnelResponse(tunnelid, managed.tunnelConfig, configId, managed.tunnelName, managed.serve);
|
|
576
|
-
} catch (err) {
|
|
577
|
-
return this.error(ErrorCode.TunnelNotFound, err, "Failed to stop tunnel");
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
async handleGet(tunnelid) {
|
|
581
|
-
try {
|
|
582
|
-
const managed = this.tunnelManager.getManagedTunnel("", tunnelid);
|
|
583
|
-
if (!managed?.tunnelConfig) throw new Error(`Tunnel config for ID "${tunnelid}" not found`);
|
|
584
|
-
return this.buildTunnelResponse(tunnelid, managed.tunnelConfig, managed.configId, managed.tunnelName, managed.serve);
|
|
585
|
-
} catch (err) {
|
|
586
|
-
return this.error(ErrorCode.TunnelNotFound, err, "Failed to get tunnel information");
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
async handleRestart(tunnelid, noWait = false) {
|
|
590
|
-
try {
|
|
591
|
-
if (noWait) {
|
|
592
|
-
const managed2 = this.tunnelManager.getManagedTunnel("", tunnelid);
|
|
593
|
-
if (!managed2?.tunnelConfig) throw new Error(`Tunnel config for ID "${tunnelid}" not found`);
|
|
594
|
-
if (managed2.rebuild) return this.rebuildInProgress(tunnelid);
|
|
595
|
-
this.tunnelManager.restartTunnel(tunnelid).catch((err) => {
|
|
596
|
-
logger.error("No-wait restartTunnel failed", { tunnelid, err: String(err) });
|
|
597
|
-
});
|
|
598
|
-
return this.buildPendingTunnelResponse(tunnelid, managed2.tunnelConfig, managed2.configId, managed2.tunnelName, managed2.serve);
|
|
599
|
-
}
|
|
600
|
-
await this.tunnelManager.restartTunnel(tunnelid);
|
|
601
|
-
const managed = this.tunnelManager.getManagedTunnel("", tunnelid);
|
|
602
|
-
if (!managed?.tunnelConfig) throw new Error(`Tunnel config for ID "${tunnelid}" not found`);
|
|
603
|
-
return this.buildTunnelResponse(tunnelid, managed.tunnelConfig, managed.configId, managed.tunnelName, managed.serve);
|
|
604
|
-
} catch (err) {
|
|
605
|
-
if (err instanceof TunnelRebuildInProgressError) {
|
|
606
|
-
return this.rebuildInProgress(tunnelid);
|
|
607
|
-
}
|
|
608
|
-
return this.error(ErrorCode.TunnelNotFound, err, "Failed to restart tunnel");
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
handleRegisterStatsListener(tunnelid, listener) {
|
|
612
|
-
void this.tunnelManager.registerStatsListener(tunnelid, listener);
|
|
613
|
-
}
|
|
614
|
-
handleUnregisterStatsListener(tunnelid, listnerId) {
|
|
615
|
-
this.tunnelManager.deregisterStatsListener(tunnelid, listnerId);
|
|
616
|
-
}
|
|
617
|
-
handleGetTunnelStats(tunnelid) {
|
|
618
|
-
try {
|
|
619
|
-
const stats = this.tunnelManager.getTunnelStats(tunnelid);
|
|
620
|
-
if (!stats) {
|
|
621
|
-
return Promise.resolve([newStats()]);
|
|
622
|
-
}
|
|
623
|
-
return Promise.resolve(stats);
|
|
624
|
-
} catch (err) {
|
|
625
|
-
return Promise.resolve(this.error(ErrorCode.TunnelNotFound, err, "Failed to get tunnel stats"));
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
handleRegisterDisconnectListener(tunnelid, listener) {
|
|
629
|
-
void this.tunnelManager.registerDisconnectListener(tunnelid, listener);
|
|
630
|
-
}
|
|
631
|
-
handleRemoveStoppedTunnelByConfigId(configId) {
|
|
632
|
-
try {
|
|
633
|
-
return this.tunnelManager.removeStoppedTunnelByConfigId(configId);
|
|
634
|
-
} catch (err) {
|
|
635
|
-
return this.error(ErrorCode.InternalServerError, err, "Failed to remove stopped tunnel by configId");
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
handleRemoveStoppedTunnelByTunnelId(tunnelId) {
|
|
639
|
-
try {
|
|
640
|
-
return this.tunnelManager.removeStoppedTunnelByTunnelId(tunnelId);
|
|
641
|
-
} catch (err) {
|
|
642
|
-
return this.error(ErrorCode.InternalServerError, err, "Failed to remove stopped tunnel by tunnelId");
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
};
|
|
646
|
-
|
|
647
|
-
// src/remote_management/remoteManagement.ts
|
|
648
|
-
import WebSocket from "ws";
|
|
649
|
-
|
|
650
|
-
// src/remote_management/websocket_printer.ts
|
|
651
|
-
import pico from "picocolors";
|
|
652
|
-
var PENDING_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
653
|
-
var PendingTracker = class {
|
|
654
|
-
constructor() {
|
|
655
|
-
this.entries = /* @__PURE__ */ new Map();
|
|
656
|
-
}
|
|
657
|
-
queue(entry) {
|
|
658
|
-
this.latestConfigId = entry.configId;
|
|
659
|
-
this.entries.set(entry.configId, entry);
|
|
660
|
-
}
|
|
661
|
-
/** Store an entry without claiming the latest cursor. */
|
|
662
|
-
upsert(entry) {
|
|
663
|
-
this.entries.set(entry.configId, entry);
|
|
664
|
-
}
|
|
665
|
-
get(configId) {
|
|
666
|
-
return this.entries.get(configId);
|
|
667
|
-
}
|
|
668
|
-
find(configId, tunnelId) {
|
|
669
|
-
const byConfigId = this.entries.get(configId);
|
|
670
|
-
if (byConfigId) {
|
|
671
|
-
return byConfigId;
|
|
672
|
-
}
|
|
673
|
-
if (!tunnelId) {
|
|
674
|
-
return void 0;
|
|
675
|
-
}
|
|
676
|
-
for (const entry of this.entries.values()) {
|
|
677
|
-
if (entry.tunnelId === tunnelId) {
|
|
678
|
-
return entry;
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
return void 0;
|
|
682
|
-
}
|
|
683
|
-
delete(configId) {
|
|
684
|
-
this.entries.delete(configId);
|
|
685
|
-
if (this.latestConfigId === configId) {
|
|
686
|
-
this.latestConfigId = void 0;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
get latest() {
|
|
690
|
-
return this.latestConfigId;
|
|
691
|
-
}
|
|
692
|
-
get hasLatest() {
|
|
693
|
-
return this.entries.size > 0 && this.latestConfigId !== void 0;
|
|
694
|
-
}
|
|
695
|
-
isLatest(configId) {
|
|
696
|
-
return configId === this.latestConfigId;
|
|
697
|
-
}
|
|
698
|
-
cleanupExpired(onTimeout) {
|
|
699
|
-
const now = Date.now();
|
|
700
|
-
for (const [configId, entry] of this.entries) {
|
|
701
|
-
if (now - entry.queuedAt <= PENDING_TIMEOUT_MS) {
|
|
702
|
-
continue;
|
|
703
|
-
}
|
|
704
|
-
const wasLatest = this.isLatest(configId);
|
|
705
|
-
this.delete(configId);
|
|
706
|
-
onTimeout(entry, wasLatest);
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
};
|
|
710
|
-
var RemoteManagementWebSocketPrinter = class {
|
|
711
|
-
constructor() {
|
|
712
|
-
this.pendingStarts = new PendingTracker();
|
|
713
|
-
this.pendingActions = new PendingTracker();
|
|
714
|
-
// tunnelId -> details, fed by monitorList. Stop/restart requests only carry
|
|
715
|
-
// a tunnelId; without this the spinner shows the raw id.
|
|
716
|
-
this.tunnelDetailsCache = /* @__PURE__ */ new Map();
|
|
717
|
-
}
|
|
718
|
-
queueStart(config) {
|
|
719
|
-
this.cleanupExpiredPendingStarts();
|
|
720
|
-
const entry = {
|
|
721
|
-
configId: this.getConfigIdFromRequest(config),
|
|
722
|
-
configName: this.getConfigNameFromRequest(config),
|
|
723
|
-
queuedAt: Date.now()
|
|
724
|
-
};
|
|
725
|
-
this.pendingStarts.queue(entry);
|
|
726
|
-
printer_default.startSpinner("Starting tunnel with config name: " + entry.configName);
|
|
727
|
-
}
|
|
728
|
-
failQueuedStart(config, reason) {
|
|
729
|
-
const configId = this.getConfigIdFromRequest(config);
|
|
730
|
-
const pending = this.pendingStarts.get(configId);
|
|
731
|
-
const configName = pending?.configName || this.getConfigNameFromRequest(config);
|
|
732
|
-
const wasLatest = this.pendingStarts.isLatest(configId);
|
|
733
|
-
this.pendingStarts.delete(configId);
|
|
734
|
-
if (wasLatest) {
|
|
735
|
-
printer_default.stopSpinnerFail(`Failed to start tunnel with config name: ${configName}. ${reason}`);
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
handleStartResult(config, result) {
|
|
739
|
-
this.cleanupExpiredPendingStarts();
|
|
740
|
-
const requestedConfigId = this.getConfigIdFromRequest(config);
|
|
741
|
-
if (this.pendingStarts.latest && !this.pendingStarts.isLatest(requestedConfigId)) {
|
|
742
|
-
this.pendingStarts.delete(requestedConfigId);
|
|
743
|
-
return;
|
|
744
|
-
}
|
|
745
|
-
if (isErrorResponse(result)) {
|
|
746
|
-
this.failQueuedStart(config, result.message);
|
|
747
|
-
return;
|
|
748
|
-
}
|
|
749
|
-
const pending = this.pendingStarts.get(requestedConfigId) || {
|
|
750
|
-
configId: requestedConfigId,
|
|
751
|
-
configName: this.getConfigNameFromRequest(config),
|
|
752
|
-
queuedAt: Date.now()
|
|
753
|
-
};
|
|
754
|
-
pending.tunnelId = result.tunnelid;
|
|
755
|
-
this.pendingStarts.upsert(pending);
|
|
756
|
-
if (result.remoteurls.length > 0) {
|
|
757
|
-
this.completePendingStart(pending, result.remoteurls);
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
printStopRequested(tunnelId) {
|
|
761
|
-
const details = this.resolveTunnelDetails(tunnelId);
|
|
762
|
-
this.clearPendingAction(details.configId, tunnelId);
|
|
763
|
-
printer_default.startSpinner("Stopping tunnel with config name: " + details.configName);
|
|
764
|
-
}
|
|
765
|
-
handleStopResult(tunnelId, result) {
|
|
766
|
-
const details = this.resolveTunnelDetails(tunnelId, result);
|
|
767
|
-
if (isErrorResponse(result)) {
|
|
768
|
-
printer_default.stopSpinnerFail("Failed to stop tunnel with config name: " + details.configName);
|
|
769
|
-
return;
|
|
770
|
-
}
|
|
771
|
-
this.pendingStarts.delete(details.configId);
|
|
772
|
-
printer_default.stopSpinnerSuccess("Stopped tunnel with config name: " + details.configName);
|
|
773
|
-
}
|
|
774
|
-
printRestartRequested(tunnelId) {
|
|
775
|
-
const details = this.resolveTunnelDetails(tunnelId);
|
|
776
|
-
this.clearPendingAction(details.configId, tunnelId);
|
|
777
|
-
printer_default.startSpinner("Restarting tunnel with config name: " + details.configName);
|
|
778
|
-
}
|
|
779
|
-
handleRestartResult(tunnelId, result) {
|
|
780
|
-
const details = this.resolveTunnelDetails(tunnelId, result);
|
|
781
|
-
if (isErrorResponse(result)) {
|
|
782
|
-
printer_default.warn(`Failed to restart tunnel with config name: ${details.configName}. ${result.message}`);
|
|
783
|
-
printer_default.stopSpinnerFail("Failed to restart tunnel with config name: " + details.configName);
|
|
784
|
-
return;
|
|
785
|
-
}
|
|
786
|
-
this.queuePendingAction("restart", details.configId, details.configName, result.tunnelid);
|
|
787
|
-
}
|
|
788
|
-
printUpdateConfigRequested(config) {
|
|
789
|
-
const configName = this.getConfigNameFromRequest(config);
|
|
790
|
-
this.clearPendingAction(this.getConfigIdFromRequest(config));
|
|
791
|
-
printer_default.startSpinner("Updating tunnel configuration for: " + configName);
|
|
792
|
-
}
|
|
793
|
-
handleUpdateConfigResult(config, result) {
|
|
794
|
-
const configId = this.getConfigIdFromRequest(config);
|
|
795
|
-
const configName = this.getConfigNameFromRequest(config);
|
|
796
|
-
if (isErrorResponse(result)) {
|
|
797
|
-
printer_default.stopSpinnerFail(`Failed to update tunnel configuration for: ${configName}. ${result.message}`);
|
|
798
|
-
return;
|
|
799
|
-
}
|
|
800
|
-
if (result.status.state === "exited" /* Exited */) {
|
|
801
|
-
printer_default.stopSpinnerSuccess(`Tunnel configuration updated: ${configName}.`);
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
this.queuePendingAction("update", configId, configName, result.tunnelid);
|
|
805
|
-
}
|
|
806
|
-
clearPendingAction(configId, tunnelId) {
|
|
807
|
-
const entry = this.pendingActions.find(configId, tunnelId);
|
|
808
|
-
if (!entry) {
|
|
809
|
-
return;
|
|
810
|
-
}
|
|
811
|
-
this.pendingActions.delete(entry.configId);
|
|
812
|
-
}
|
|
813
|
-
queuePendingAction(action, configId, configName, tunnelId) {
|
|
814
|
-
this.cleanupExpiredPendingActions();
|
|
815
|
-
this.pendingActions.queue({ action, configId, configName, queuedAt: Date.now(), tunnelId });
|
|
816
|
-
}
|
|
817
|
-
printActionComplete(action, configName, urls) {
|
|
818
|
-
const message = action === "restart" ? `Restarted tunnel with config name: ${configName}` : `Tunnel configuration updated and restarted: ${configName}`;
|
|
819
|
-
printer_default.stopSpinnerSuccess(message);
|
|
820
|
-
printer_default.info(pico.cyanBright("Remote URLs:"));
|
|
821
|
-
urls.forEach((url) => printer_default.print(" " + pico.magentaBright(url)));
|
|
822
|
-
}
|
|
823
|
-
monitorList(result) {
|
|
824
|
-
this.cleanupExpiredPendingStarts();
|
|
825
|
-
this.cleanupExpiredPendingActions();
|
|
826
|
-
if (!Array.isArray(result)) {
|
|
827
|
-
return;
|
|
828
|
-
}
|
|
829
|
-
for (const tunnel of result) {
|
|
830
|
-
this.tunnelDetailsCache.set(tunnel.tunnelid, {
|
|
831
|
-
configId: this.getConfigIdFromTunnel(tunnel),
|
|
832
|
-
configName: this.getConfigNameFromTunnel(tunnel)
|
|
833
|
-
});
|
|
834
|
-
}
|
|
835
|
-
this.resolvePendingFromList(
|
|
836
|
-
result,
|
|
837
|
-
this.pendingStarts,
|
|
838
|
-
(entry, urls) => this.completePendingStart(entry, urls),
|
|
839
|
-
(entry, reason) => printer_default.stopSpinnerFail(`Tunnel start did not complete for config name: ${entry.configName}. ${reason}`)
|
|
840
|
-
);
|
|
841
|
-
this.resolvePendingFromList(
|
|
842
|
-
result,
|
|
843
|
-
this.pendingActions,
|
|
844
|
-
(entry, urls) => {
|
|
845
|
-
this.pendingActions.delete(entry.configId);
|
|
846
|
-
this.printActionComplete(entry.action, entry.configName, urls);
|
|
847
|
-
},
|
|
848
|
-
(entry, reason) => {
|
|
849
|
-
const verb = entry.action === "restart" ? "Restart" : "Configuration update";
|
|
850
|
-
printer_default.stopSpinnerFail(`${verb} did not complete for config name: ${entry.configName}. ${reason}`);
|
|
851
|
-
}
|
|
852
|
-
);
|
|
853
|
-
}
|
|
854
|
-
resolvePendingFromList(tunnels, tracker, onComplete, onExited) {
|
|
855
|
-
if (!tracker.hasLatest) {
|
|
856
|
-
return;
|
|
857
|
-
}
|
|
858
|
-
for (const tunnel of tunnels) {
|
|
859
|
-
const entry = tracker.find(this.getConfigIdFromTunnel(tunnel), tunnel.tunnelid);
|
|
860
|
-
if (!entry || !tracker.isLatest(entry.configId)) {
|
|
861
|
-
continue;
|
|
862
|
-
}
|
|
863
|
-
entry.tunnelId = tunnel.tunnelid;
|
|
864
|
-
tracker.upsert(entry);
|
|
865
|
-
if (tunnel.remoteurls.length > 0) {
|
|
866
|
-
onComplete(entry, tunnel.remoteurls);
|
|
867
|
-
continue;
|
|
868
|
-
}
|
|
869
|
-
if (tunnel.status.state === "exited" /* Exited */) {
|
|
870
|
-
tracker.delete(entry.configId);
|
|
871
|
-
onExited(entry, tunnel.status.errormsg || "Tunnel exited before a public URL was assigned");
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
completePendingStart(entry, urls) {
|
|
876
|
-
if (this.pendingStarts.latest && !this.pendingStarts.isLatest(entry.configId)) {
|
|
877
|
-
this.pendingStarts.delete(entry.configId);
|
|
878
|
-
return;
|
|
879
|
-
}
|
|
880
|
-
this.pendingStarts.delete(entry.configId);
|
|
881
|
-
printer_default.stopSpinnerSuccess(`Tunnel started with config name: ${entry.configName}.`);
|
|
882
|
-
printer_default.info(pico.cyanBright("Remote URLs:"));
|
|
883
|
-
(urls ?? []).forEach(
|
|
884
|
-
(url) => printer_default.print(" " + pico.magentaBright(url))
|
|
885
|
-
);
|
|
886
|
-
}
|
|
887
|
-
cleanupExpiredPendingStarts() {
|
|
888
|
-
this.pendingStarts.cleanupExpired((entry, wasLatest) => {
|
|
889
|
-
const message = `Timed out while waiting for tunnel URL for config name: ${entry.configName}`;
|
|
890
|
-
if (wasLatest) {
|
|
891
|
-
printer_default.stopSpinnerFail(message);
|
|
892
|
-
} else {
|
|
893
|
-
printer_default.warn(message);
|
|
894
|
-
}
|
|
895
|
-
logger.warn("Pending websocket start entry expired", { configId: entry.configId, tunnelId: entry.tunnelId });
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
cleanupExpiredPendingActions() {
|
|
899
|
-
this.pendingActions.cleanupExpired((entry, wasLatest) => {
|
|
900
|
-
const verb = entry.action === "restart" ? "restart" : "configuration update";
|
|
901
|
-
const message = `Timed out while waiting for tunnel URL after ${verb} for config name: ${entry.configName}`;
|
|
902
|
-
if (wasLatest) {
|
|
903
|
-
printer_default.stopSpinnerFail(message);
|
|
904
|
-
} else {
|
|
905
|
-
printer_default.warn(message);
|
|
906
|
-
}
|
|
907
|
-
logger.warn("Pending websocket action entry expired", { configId: entry.configId, tunnelId: entry.tunnelId, action: entry.action });
|
|
908
|
-
});
|
|
909
|
-
}
|
|
910
|
-
resolveTunnelDetails(tunnelId, result) {
|
|
911
|
-
if (result && !isErrorResponse(result)) {
|
|
912
|
-
return {
|
|
913
|
-
configId: this.getConfigIdFromTunnel(result),
|
|
914
|
-
configName: this.getConfigNameFromTunnel(result)
|
|
915
|
-
};
|
|
916
|
-
}
|
|
917
|
-
return this.tunnelDetailsCache.get(tunnelId) ?? {
|
|
918
|
-
configId: tunnelId,
|
|
919
|
-
configName: tunnelId
|
|
920
|
-
};
|
|
921
|
-
}
|
|
922
|
-
getConfigIdFromRequest(config) {
|
|
923
|
-
return "configid" in config ? config.configid : config.configId;
|
|
924
|
-
}
|
|
925
|
-
getConfigNameFromRequest(config) {
|
|
926
|
-
return "configname" in config ? config.configname : config.name;
|
|
927
|
-
}
|
|
928
|
-
getConfigIdFromTunnel(tunnel) {
|
|
929
|
-
return "configid" in tunnel.tunnelconfig ? tunnel.tunnelconfig.configid : tunnel.tunnelconfig.configId;
|
|
930
|
-
}
|
|
931
|
-
getConfigNameFromTunnel(tunnel) {
|
|
932
|
-
return "configname" in tunnel.tunnelconfig ? tunnel.tunnelconfig.configname : tunnel.tunnelconfig.name;
|
|
933
|
-
}
|
|
934
|
-
};
|
|
935
|
-
var remoteManagementWebSocketPrinter = new RemoteManagementWebSocketPrinter();
|
|
936
|
-
|
|
937
|
-
// src/remote_management/websocket_handlers.ts
|
|
938
|
-
import z2 from "zod";
|
|
939
|
-
var WsCommand = {
|
|
940
|
-
Start: "start",
|
|
941
|
-
StartV2: "start-v2",
|
|
942
|
-
Stop: "stop",
|
|
943
|
-
Get: "get",
|
|
944
|
-
Restart: "restart",
|
|
945
|
-
UpdateConfig: "updateconfig",
|
|
946
|
-
UpdateConfigV2: "update-config-v2",
|
|
947
|
-
List: "list",
|
|
948
|
-
ListV2: "list-v2",
|
|
949
|
-
GetVersion: "get-version"
|
|
950
|
-
};
|
|
951
|
-
var WebSocketCommandHandler = class {
|
|
952
|
-
constructor(handler) {
|
|
953
|
-
this.tunnelHandler = handler ?? new TunnelOperations();
|
|
954
|
-
}
|
|
955
|
-
safeParse(text) {
|
|
956
|
-
if (!text) return void 0;
|
|
957
|
-
try {
|
|
958
|
-
return JSON.parse(text);
|
|
959
|
-
} catch (e) {
|
|
960
|
-
logger.warn("Invalid JSON payload", { error: String(e), text });
|
|
961
|
-
return void 0;
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
sendResponse(ws, resp) {
|
|
965
|
-
const payload = {
|
|
966
|
-
...resp,
|
|
967
|
-
response: Buffer.from(resp.response || []).toString("base64")
|
|
968
|
-
};
|
|
969
|
-
ws.send(JSON.stringify(payload));
|
|
970
|
-
}
|
|
971
|
-
sendError(ws, req, message, code = ErrorCode.InternalServerError) {
|
|
972
|
-
const resp = NewErrorResponseObject({ code, message });
|
|
973
|
-
resp.command = req.command || "";
|
|
974
|
-
resp.requestid = req.requestid || "";
|
|
975
|
-
this.sendResponse(ws, resp);
|
|
976
|
-
}
|
|
977
|
-
async handleStartReq(req, raw) {
|
|
978
|
-
let queuedConfig;
|
|
979
|
-
try {
|
|
980
|
-
const dc = StartSchema.parse(raw);
|
|
981
|
-
queuedConfig = dc.tunnelConfig;
|
|
982
|
-
remoteManagementWebSocketPrinter.queueStart(dc.tunnelConfig);
|
|
983
|
-
const result = await this.tunnelHandler.handleStart(dc.tunnelConfig, true);
|
|
984
|
-
remoteManagementWebSocketPrinter.handleStartResult(dc.tunnelConfig, result);
|
|
985
|
-
return this.wrapResponse(result, req);
|
|
986
|
-
} catch (e) {
|
|
987
|
-
if (queuedConfig) {
|
|
988
|
-
remoteManagementWebSocketPrinter.failQueuedStart(queuedConfig, String(e));
|
|
989
|
-
}
|
|
990
|
-
if (e instanceof z2.ZodError) {
|
|
991
|
-
printer_default.warn("Validation failed for start request");
|
|
992
|
-
return NewErrorResponseObject({ code: ErrorCode.InvalidBodyFormatError, message: "Validation failed" });
|
|
993
|
-
}
|
|
994
|
-
printer_default.warn(`Error in handleStartReq error: ${String(e)}`);
|
|
995
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
async handleStartV2Req(req, raw) {
|
|
999
|
-
let queuedConfig;
|
|
1000
|
-
try {
|
|
1001
|
-
const dc = StartV2Schema.parse(raw);
|
|
1002
|
-
queuedConfig = dc.tunnelConfig;
|
|
1003
|
-
remoteManagementWebSocketPrinter.queueStart(dc.tunnelConfig);
|
|
1004
|
-
const result = await this.tunnelHandler.handleStartV2(dc.tunnelConfig, true);
|
|
1005
|
-
remoteManagementWebSocketPrinter.handleStartResult(dc.tunnelConfig, result);
|
|
1006
|
-
return this.wrapResponse(result, req);
|
|
1007
|
-
} catch (e) {
|
|
1008
|
-
if (queuedConfig) {
|
|
1009
|
-
remoteManagementWebSocketPrinter.failQueuedStart(queuedConfig, String(e));
|
|
1010
|
-
}
|
|
1011
|
-
if (e instanceof z2.ZodError) {
|
|
1012
|
-
printer_default.warn("Validation failed for start-v2 request");
|
|
1013
|
-
return NewErrorResponseObject({ code: ErrorCode.InvalidBodyFormatError, message: "Validation failed" });
|
|
1014
|
-
}
|
|
1015
|
-
printer_default.warn(`Error in handleStartV2Req error: ${String(e)}`);
|
|
1016
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
async handleStopReq(req, raw) {
|
|
1020
|
-
let tunnelID;
|
|
1021
|
-
try {
|
|
1022
|
-
const dc = StopSchema.parse(raw);
|
|
1023
|
-
tunnelID = dc.tunnelID;
|
|
1024
|
-
remoteManagementWebSocketPrinter.printStopRequested(dc.tunnelID);
|
|
1025
|
-
const result = await this.tunnelHandler.handleStop(dc.tunnelID);
|
|
1026
|
-
remoteManagementWebSocketPrinter.handleStopResult(dc.tunnelID, result);
|
|
1027
|
-
return this.wrapResponse(result, req);
|
|
1028
|
-
} catch (e) {
|
|
1029
|
-
if (e instanceof z2.ZodError) {
|
|
1030
|
-
printer_default.warn("Validation failed for stop request");
|
|
1031
|
-
return NewErrorResponseObject({ code: ErrorCode.InvalidBodyFormatError, message: "Validation failed" });
|
|
1032
|
-
}
|
|
1033
|
-
if (tunnelID) {
|
|
1034
|
-
remoteManagementWebSocketPrinter.handleStopResult(tunnelID, newErrorResponse({ code: ErrorCode.InternalServerError, message: errorMessage(e) }));
|
|
1035
|
-
}
|
|
1036
|
-
printer_default.warn(`Error in handleStopReq error: ${String(e)}`);
|
|
1037
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
async handleGetReq(req, raw) {
|
|
1041
|
-
try {
|
|
1042
|
-
const dc = GetSchema.parse(raw);
|
|
1043
|
-
const result = await this.tunnelHandler.handleGet(dc.tunnelID);
|
|
1044
|
-
return this.wrapResponse(result, req);
|
|
1045
|
-
} catch (e) {
|
|
1046
|
-
if (e instanceof z2.ZodError) {
|
|
1047
|
-
printer_default.warn("Validation failed for get request");
|
|
1048
|
-
return NewErrorResponseObject({ code: ErrorCode.InvalidBodyFormatError, message: "Validation failed" });
|
|
1049
|
-
}
|
|
1050
|
-
printer_default.warn(`Error in handleGetReq error: ${String(e)}`);
|
|
1051
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
async handleRestartReq(req, raw) {
|
|
1055
|
-
let tunnelID;
|
|
1056
|
-
try {
|
|
1057
|
-
const dc = RestartSchema.parse(raw);
|
|
1058
|
-
tunnelID = dc.tunnelID;
|
|
1059
|
-
remoteManagementWebSocketPrinter.printRestartRequested(dc.tunnelID);
|
|
1060
|
-
const result = await this.tunnelHandler.handleRestart(dc.tunnelID, true);
|
|
1061
|
-
remoteManagementWebSocketPrinter.handleRestartResult(dc.tunnelID, result);
|
|
1062
|
-
return this.wrapResponse(result, req);
|
|
1063
|
-
} catch (e) {
|
|
1064
|
-
if (e instanceof z2.ZodError) {
|
|
1065
|
-
printer_default.warn("Validation failed for restart request");
|
|
1066
|
-
return NewErrorResponseObject({ code: ErrorCode.InvalidBodyFormatError, message: "Validation failed" });
|
|
1067
|
-
}
|
|
1068
|
-
if (tunnelID) {
|
|
1069
|
-
remoteManagementWebSocketPrinter.handleRestartResult(tunnelID, newErrorResponse({ code: ErrorCode.InternalServerError, message: errorMessage(e) }));
|
|
1070
|
-
}
|
|
1071
|
-
printer_default.warn(`Error in handleRestartReq error: ${String(e)}`);
|
|
1072
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
async handleUpdateConfigReq(req, raw) {
|
|
1076
|
-
let parsedConfig;
|
|
1077
|
-
try {
|
|
1078
|
-
const dc = UpdateConfigSchema.parse(raw);
|
|
1079
|
-
parsedConfig = dc.tunnelConfig;
|
|
1080
|
-
remoteManagementWebSocketPrinter.printUpdateConfigRequested(dc.tunnelConfig);
|
|
1081
|
-
const result = await this.tunnelHandler.handleUpdateConfig(dc.tunnelConfig, true);
|
|
1082
|
-
remoteManagementWebSocketPrinter.handleUpdateConfigResult(dc.tunnelConfig, result);
|
|
1083
|
-
return this.wrapResponse(result, req);
|
|
1084
|
-
} catch (e) {
|
|
1085
|
-
if (e instanceof z2.ZodError) {
|
|
1086
|
-
printer_default.warn("Validation failed for updateconfig request");
|
|
1087
|
-
return NewErrorResponseObject({ code: ErrorCode.InvalidBodyFormatError, message: "Validation failed" });
|
|
1088
|
-
}
|
|
1089
|
-
if (parsedConfig) {
|
|
1090
|
-
remoteManagementWebSocketPrinter.handleUpdateConfigResult(parsedConfig, newErrorResponse({ code: ErrorCode.InternalServerError, message: errorMessage(e) }));
|
|
1091
|
-
}
|
|
1092
|
-
printer_default.warn(`Error in handleUpdateConfigReq error: ${String(e)}`);
|
|
1093
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
async handleUpdateConfigV2Req(req, raw) {
|
|
1097
|
-
let parsedConfig;
|
|
1098
|
-
try {
|
|
1099
|
-
const dc = UpdateConfigV2Schema.parse(raw);
|
|
1100
|
-
parsedConfig = dc.tunnelConfig;
|
|
1101
|
-
remoteManagementWebSocketPrinter.printUpdateConfigRequested(dc.tunnelConfig);
|
|
1102
|
-
const result = await this.tunnelHandler.handleUpdateConfigV2(dc.tunnelConfig, true);
|
|
1103
|
-
remoteManagementWebSocketPrinter.handleUpdateConfigResult(dc.tunnelConfig, result);
|
|
1104
|
-
return this.wrapResponse(result, req);
|
|
1105
|
-
} catch (e) {
|
|
1106
|
-
if (e instanceof z2.ZodError) {
|
|
1107
|
-
printer_default.warn("Validation failed for update-config-v2 request");
|
|
1108
|
-
return NewErrorResponseObject({ code: ErrorCode.InvalidBodyFormatError, message: "Validation failed" });
|
|
1109
|
-
}
|
|
1110
|
-
if (parsedConfig) {
|
|
1111
|
-
remoteManagementWebSocketPrinter.handleUpdateConfigResult(parsedConfig, newErrorResponse({ code: ErrorCode.InternalServerError, message: errorMessage(e) }));
|
|
1112
|
-
}
|
|
1113
|
-
printer_default.warn(`Error in handleUpdateConfigV2Req error: ${String(e)}`);
|
|
1114
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
async handleListReq(req) {
|
|
1118
|
-
try {
|
|
1119
|
-
const result = await this.tunnelHandler.handleList();
|
|
1120
|
-
remoteManagementWebSocketPrinter.monitorList(result);
|
|
1121
|
-
return this.wrapResponse(result, req);
|
|
1122
|
-
} catch (e) {
|
|
1123
|
-
printer_default.warn(`Error in handleListReq error: ${String(e)}`);
|
|
1124
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
async handleListV2Req(req) {
|
|
1128
|
-
try {
|
|
1129
|
-
const result = await this.tunnelHandler.handleListV2();
|
|
1130
|
-
remoteManagementWebSocketPrinter.monitorList(result);
|
|
1131
|
-
return this.wrapResponse(result, req);
|
|
1132
|
-
} catch (e) {
|
|
1133
|
-
printer_default.warn(`Error in handleListV2Req error: ${String(e)}`);
|
|
1134
|
-
return NewErrorResponseObject({ code: ErrorCode.InternalServerError, message: String(e) });
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
handleGetVersionReq(ws, req) {
|
|
1138
|
-
try {
|
|
1139
|
-
const versionResponse = {
|
|
1140
|
-
cli_version: getVersion()
|
|
1141
|
-
};
|
|
1142
|
-
const payload = {
|
|
1143
|
-
command: req.command,
|
|
1144
|
-
requestid: req.requestid,
|
|
1145
|
-
response: JSON.stringify(versionResponse),
|
|
1146
|
-
error: false
|
|
1147
|
-
};
|
|
1148
|
-
ws.send(JSON.stringify(payload));
|
|
1149
|
-
} catch (e) {
|
|
1150
|
-
printer_default.warn(`Error in handleGetVersionReq error: ${String(e)}`);
|
|
1151
|
-
this.sendError(ws, req, String(e));
|
|
1152
|
-
}
|
|
1153
|
-
}
|
|
1154
|
-
wrapResponse(result, req) {
|
|
1155
|
-
if (isErrorResponse(result)) {
|
|
1156
|
-
const errResp = NewErrorResponseObject(result);
|
|
1157
|
-
errResp.command = req.command;
|
|
1158
|
-
errResp.requestid = req.requestid;
|
|
1159
|
-
return errResp;
|
|
1160
|
-
}
|
|
1161
|
-
const finalResult = JSON.parse(JSON.stringify(result));
|
|
1162
|
-
if (Array.isArray(finalResult)) {
|
|
1163
|
-
finalResult.forEach((item) => {
|
|
1164
|
-
if (item?.tunnelconfig) {
|
|
1165
|
-
delete item.tunnelconfig.allowPreflight;
|
|
1166
|
-
}
|
|
1167
|
-
});
|
|
1168
|
-
} else if (finalResult?.tunnelconfig) {
|
|
1169
|
-
delete finalResult.tunnelconfig.allowPreflight;
|
|
1170
|
-
}
|
|
1171
|
-
const respObj = NewResponseObject(finalResult);
|
|
1172
|
-
respObj.command = req.command;
|
|
1173
|
-
respObj.requestid = req.requestid;
|
|
1174
|
-
return respObj;
|
|
1175
|
-
}
|
|
1176
|
-
async handle(ws, req) {
|
|
1177
|
-
const cmd = (req.command || "").toLowerCase();
|
|
1178
|
-
const raw = this.safeParse(req.data);
|
|
1179
|
-
try {
|
|
1180
|
-
let response;
|
|
1181
|
-
switch (cmd) {
|
|
1182
|
-
case WsCommand.Start: {
|
|
1183
|
-
response = await this.handleStartReq(req, raw);
|
|
1184
|
-
break;
|
|
1185
|
-
}
|
|
1186
|
-
case WsCommand.StartV2: {
|
|
1187
|
-
response = await this.handleStartV2Req(req, raw);
|
|
1188
|
-
break;
|
|
1189
|
-
}
|
|
1190
|
-
case WsCommand.Stop: {
|
|
1191
|
-
response = await this.handleStopReq(req, raw);
|
|
1192
|
-
break;
|
|
1193
|
-
}
|
|
1194
|
-
case WsCommand.Get: {
|
|
1195
|
-
response = await this.handleGetReq(req, raw);
|
|
1196
|
-
break;
|
|
1197
|
-
}
|
|
1198
|
-
case WsCommand.Restart: {
|
|
1199
|
-
response = await this.handleRestartReq(req, raw);
|
|
1200
|
-
break;
|
|
1201
|
-
}
|
|
1202
|
-
case WsCommand.UpdateConfig: {
|
|
1203
|
-
response = await this.handleUpdateConfigReq(req, raw);
|
|
1204
|
-
break;
|
|
1205
|
-
}
|
|
1206
|
-
case WsCommand.UpdateConfigV2: {
|
|
1207
|
-
response = await this.handleUpdateConfigV2Req(req, raw);
|
|
1208
|
-
break;
|
|
1209
|
-
}
|
|
1210
|
-
case WsCommand.List: {
|
|
1211
|
-
response = await this.handleListReq(req);
|
|
1212
|
-
break;
|
|
1213
|
-
}
|
|
1214
|
-
case WsCommand.ListV2: {
|
|
1215
|
-
response = await this.handleListV2Req(req);
|
|
1216
|
-
break;
|
|
1217
|
-
}
|
|
1218
|
-
case WsCommand.GetVersion: {
|
|
1219
|
-
this.handleGetVersionReq(ws, req);
|
|
1220
|
-
return;
|
|
1221
|
-
}
|
|
1222
|
-
default:
|
|
1223
|
-
if (typeof req.command === "string") {
|
|
1224
|
-
logger.warn("Unknown command", { command: req.command });
|
|
1225
|
-
}
|
|
1226
|
-
return this.sendError(ws, req, "Invalid command");
|
|
1227
|
-
}
|
|
1228
|
-
logger.debug("Sending response", { command: response.command, requestid: response.requestid });
|
|
1229
|
-
this.sendResponse(ws, response);
|
|
1230
|
-
} catch (e) {
|
|
1231
|
-
if (e instanceof z2.ZodError) {
|
|
1232
|
-
logger.warn("Validation failed", { cmd, issues: e.issues });
|
|
1233
|
-
return this.sendError(ws, req, "Invalid request data", ErrorCode.InvalidBodyFormatError);
|
|
1234
|
-
}
|
|
1235
|
-
logger.error("Error handling command", { cmd, error: errorMessage(e) });
|
|
1236
|
-
return this.sendError(ws, req, errorMessage(e) || "Internal error");
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
};
|
|
1240
|
-
function sendVersionResponse(ws) {
|
|
1241
|
-
const versionResponse = {
|
|
1242
|
-
cli_version: getVersion()
|
|
1243
|
-
};
|
|
1244
|
-
const payload = {
|
|
1245
|
-
command: WsCommand.GetVersion,
|
|
1246
|
-
requestid: "0",
|
|
1247
|
-
response: JSON.stringify(versionResponse),
|
|
1248
|
-
error: false
|
|
1249
|
-
};
|
|
1250
|
-
ws.send(JSON.stringify(payload));
|
|
1251
|
-
}
|
|
1252
|
-
function handleConnectionStatusMessage(firstMessage) {
|
|
1253
|
-
try {
|
|
1254
|
-
const text = typeof firstMessage === "string" ? firstMessage : firstMessage.toString();
|
|
1255
|
-
const cs = JSON.parse(text);
|
|
1256
|
-
if (!cs.success) {
|
|
1257
|
-
const msg = cs.error_msg || "Connection failed";
|
|
1258
|
-
printer_default.warn(`Connection failed: ${msg}`);
|
|
1259
|
-
logger.warn("Remote management connection failed", { error_code: cs.error_code, error_msg: msg });
|
|
1260
|
-
return false;
|
|
1261
|
-
}
|
|
1262
|
-
return true;
|
|
1263
|
-
} catch (e) {
|
|
1264
|
-
logger.warn("Failed to parse connection status message", { error: String(e) });
|
|
1265
|
-
return true;
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
// src/remote_management/remoteManagement.ts
|
|
1270
|
-
var RECONNECT_SLEEP_MS = 5e3;
|
|
1271
|
-
var PING_INTERVAL_MS = 3e4;
|
|
1272
|
-
var RemoteManagementUnauthorizedError = class extends Error {
|
|
1273
|
-
constructor() {
|
|
1274
|
-
super("Unauthorized. Please enter a valid token.");
|
|
1275
|
-
this.name = "RemoteManagementUnauthorizedError";
|
|
1276
|
-
}
|
|
1277
|
-
};
|
|
1278
|
-
var _remoteManagementState = {
|
|
1279
|
-
status: "NOT_RUNNING",
|
|
1280
|
-
errorMessage: ""
|
|
1281
|
-
};
|
|
1282
|
-
var _stopRequested = false;
|
|
1283
|
-
var currentWs = null;
|
|
1284
|
-
function buildRemoteManagementWsUrl(manage) {
|
|
1285
|
-
let baseUrl = (manage || "dashboard.pinggy.io").trim();
|
|
1286
|
-
if (!(baseUrl.startsWith("ws://") || baseUrl.startsWith("wss://"))) {
|
|
1287
|
-
baseUrl = "wss://" + baseUrl;
|
|
1288
|
-
}
|
|
1289
|
-
const trimmed = baseUrl.replace(/\/$/, "");
|
|
1290
|
-
return `${trimmed}/backend/api/v1/remote-management/connect`;
|
|
1291
|
-
}
|
|
1292
|
-
function extractHostname(u) {
|
|
1293
|
-
try {
|
|
1294
|
-
const url = new URL(u);
|
|
1295
|
-
return url.host;
|
|
1296
|
-
} catch {
|
|
1297
|
-
return u;
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
function sleep(ms) {
|
|
1301
|
-
return new Promise((res) => setTimeout(res, ms));
|
|
1302
|
-
}
|
|
1303
|
-
async function initiateRemoteManagement(remoteManagementConfig, tunnelHandler) {
|
|
1304
|
-
if (!remoteManagementConfig.apiKey || remoteManagementConfig.apiKey.trim().length === 0) {
|
|
1305
|
-
throw new Error("Remote management token is required (use --remote-management <TOKEN>)");
|
|
1306
|
-
}
|
|
1307
|
-
const wsUrl = remoteManagementConfig.serverUrl;
|
|
1308
|
-
const wsHost = extractHostname(wsUrl);
|
|
1309
|
-
logger.info("Remote management mode enabled.");
|
|
1310
|
-
_stopRequested = false;
|
|
1311
|
-
const sigintHandler = () => {
|
|
1312
|
-
_stopRequested = true;
|
|
1313
|
-
};
|
|
1314
|
-
process.once("SIGINT", sigintHandler);
|
|
1315
|
-
const logConnecting = () => {
|
|
1316
|
-
printer_default.print(`Connecting to ${wsHost}`);
|
|
1317
|
-
logger.info("Connecting to remote management", { wsUrl });
|
|
1318
|
-
};
|
|
1319
|
-
while (!_stopRequested) {
|
|
1320
|
-
logConnecting();
|
|
1321
|
-
setRemoteManagementState({ status: RemoteManagementStatus.Connecting, errorMessage: "" });
|
|
1322
|
-
try {
|
|
1323
|
-
await handleWebSocketConnection(wsUrl, wsHost, remoteManagementConfig.apiKey, void 0, tunnelHandler);
|
|
1324
|
-
} catch (error) {
|
|
1325
|
-
if (error instanceof RemoteManagementUnauthorizedError) {
|
|
1326
|
-
throw error;
|
|
1327
|
-
}
|
|
1328
|
-
logger.warn("Remote management connection error", { error: String(error) });
|
|
1329
|
-
}
|
|
1330
|
-
if (_stopRequested) {
|
|
1331
|
-
break;
|
|
1332
|
-
}
|
|
1333
|
-
printer_default.warn(`Remote management disconnected. Reconnecting in ${RECONNECT_SLEEP_MS / 1e3} seconds...`);
|
|
1334
|
-
logger.info("Reconnecting to remote management after disconnect");
|
|
1335
|
-
await sleep(RECONNECT_SLEEP_MS);
|
|
1336
|
-
}
|
|
1337
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
1338
|
-
logger.info("Remote management stopped.");
|
|
1339
|
-
return getRemoteManagementState();
|
|
1340
|
-
}
|
|
1341
|
-
async function handleWebSocketConnection(wsUrl, wsHost, token, onOpenCallback, tunnelHandler) {
|
|
1342
|
-
return new Promise((resolve, reject) => {
|
|
1343
|
-
const ws = new WebSocket(wsUrl, {
|
|
1344
|
-
headers: { Authorization: `Bearer ${token}` }
|
|
1345
|
-
});
|
|
1346
|
-
currentWs = ws;
|
|
1347
|
-
let heartbeat = null;
|
|
1348
|
-
let firstMessage = true;
|
|
1349
|
-
let settled = false;
|
|
1350
|
-
const cleanup = (err) => {
|
|
1351
|
-
if (settled) {
|
|
1352
|
-
return;
|
|
1353
|
-
}
|
|
1354
|
-
settled = true;
|
|
1355
|
-
if (heartbeat) {
|
|
1356
|
-
clearInterval(heartbeat);
|
|
1357
|
-
}
|
|
1358
|
-
currentWs = null;
|
|
1359
|
-
if (err) {
|
|
1360
|
-
reject(err);
|
|
1361
|
-
} else {
|
|
1362
|
-
resolve();
|
|
1363
|
-
}
|
|
1364
|
-
};
|
|
1365
|
-
ws.once("open", () => {
|
|
1366
|
-
printer_default.success(`Connected to ${wsHost}`);
|
|
1367
|
-
setRemoteManagementState({ status: RemoteManagementStatus.Running, errorMessage: "" });
|
|
1368
|
-
onOpenCallback?.();
|
|
1369
|
-
heartbeat = setInterval(() => {
|
|
1370
|
-
if (ws.readyState === WebSocket.OPEN) ws.ping();
|
|
1371
|
-
}, PING_INTERVAL_MS);
|
|
1372
|
-
});
|
|
1373
|
-
ws.on("ping", () => ws.pong());
|
|
1374
|
-
ws.on("message", async (data) => {
|
|
1375
|
-
try {
|
|
1376
|
-
if (firstMessage) {
|
|
1377
|
-
firstMessage = false;
|
|
1378
|
-
const ok = handleConnectionStatusMessage(data);
|
|
1379
|
-
if (!ok) {
|
|
1380
|
-
ws.close();
|
|
1381
|
-
return;
|
|
1382
|
-
}
|
|
1383
|
-
sendVersionResponse(ws);
|
|
1384
|
-
return;
|
|
1385
|
-
}
|
|
1386
|
-
setRemoteManagementState({ status: RemoteManagementStatus.Running, errorMessage: "" });
|
|
1387
|
-
const req = JSON.parse(data.toString("utf8"));
|
|
1388
|
-
await new WebSocketCommandHandler(tunnelHandler).handle(ws, req);
|
|
1389
|
-
} catch (e) {
|
|
1390
|
-
logger.warn("Failed handling websocket message", { error: String(e) });
|
|
1391
|
-
}
|
|
1392
|
-
});
|
|
1393
|
-
ws.on("unexpected-response", (_, res) => {
|
|
1394
|
-
if (res.statusCode === 401) {
|
|
1395
|
-
setRemoteManagementState({ status: RemoteManagementStatus.NotRunning, errorMessage: `HTTP ${res.statusCode}` });
|
|
1396
|
-
logger.error("Unauthorized (401) on remote management connect");
|
|
1397
|
-
cleanup(new RemoteManagementUnauthorizedError());
|
|
1398
|
-
ws.close();
|
|
1399
|
-
} else {
|
|
1400
|
-
logger.warn("Unexpected HTTP response ", { statusCode: res.statusCode });
|
|
1401
|
-
printer_default.warn(`Unexpected HTTP ${res.statusCode}. Retrying...`);
|
|
1402
|
-
cleanup();
|
|
1403
|
-
ws.close();
|
|
1404
|
-
}
|
|
1405
|
-
});
|
|
1406
|
-
ws.on("close", (code, reason) => {
|
|
1407
|
-
setRemoteManagementState({ status: RemoteManagementStatus.NotRunning, errorMessage: "" });
|
|
1408
|
-
logger.info("WebSocket closed", { code, reason: reason.toString() });
|
|
1409
|
-
printer_default.warn(`Disconnected (code: ${code}). Retrying in ${RECONNECT_SLEEP_MS / 1e3}s...`);
|
|
1410
|
-
cleanup();
|
|
1411
|
-
});
|
|
1412
|
-
ws.on("error", (err) => {
|
|
1413
|
-
setRemoteManagementState({ status: RemoteManagementStatus.Error, errorMessage: err.message });
|
|
1414
|
-
logger.warn("WebSocket error", { error: err.message });
|
|
1415
|
-
printer_default.warn(err.message);
|
|
1416
|
-
cleanup();
|
|
1417
|
-
});
|
|
1418
|
-
});
|
|
1419
|
-
}
|
|
1420
|
-
async function closeRemoteManagement(timeoutMs = 1e4) {
|
|
1421
|
-
_stopRequested = true;
|
|
1422
|
-
try {
|
|
1423
|
-
if (currentWs) {
|
|
1424
|
-
try {
|
|
1425
|
-
setRemoteManagementState({ status: RemoteManagementStatus.Disconnecting, errorMessage: "" });
|
|
1426
|
-
currentWs.close();
|
|
1427
|
-
} catch (e) {
|
|
1428
|
-
logger.warn("Error while closing current remote management websocket", { error: String(e) });
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
const start = Date.now();
|
|
1432
|
-
while (_remoteManagementState.status === "RUNNING") {
|
|
1433
|
-
if (Date.now() - start > timeoutMs) {
|
|
1434
|
-
logger.warn("Timed out waiting for remote management to stop");
|
|
1435
|
-
break;
|
|
1436
|
-
}
|
|
1437
|
-
await sleep(200);
|
|
1438
|
-
}
|
|
1439
|
-
} finally {
|
|
1440
|
-
currentWs = null;
|
|
1441
|
-
setRemoteManagementState({ status: RemoteManagementStatus.NotRunning, errorMessage: "" });
|
|
1442
|
-
return getRemoteManagementState();
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
function startRemoteManagement(remoteManagementConfig, tunnelHandler) {
|
|
1446
|
-
if (!remoteManagementConfig.apiKey || remoteManagementConfig.apiKey.trim().length === 0) {
|
|
1447
|
-
return Promise.reject(new Error("Remote management token is required"));
|
|
1448
|
-
}
|
|
1449
|
-
const wsUrl = remoteManagementConfig.serverUrl;
|
|
1450
|
-
const wsHost = extractHostname(wsUrl);
|
|
1451
|
-
logger.info("Remote management mode enabled.");
|
|
1452
|
-
_stopRequested = false;
|
|
1453
|
-
return new Promise((resolve, reject) => {
|
|
1454
|
-
let firstSettled = false;
|
|
1455
|
-
const settleOnce = (err) => {
|
|
1456
|
-
if (firstSettled) {
|
|
1457
|
-
return;
|
|
1458
|
-
}
|
|
1459
|
-
firstSettled = true;
|
|
1460
|
-
if (err) {
|
|
1461
|
-
reject(err);
|
|
1462
|
-
} else {
|
|
1463
|
-
resolve(getRemoteManagementState());
|
|
1464
|
-
}
|
|
1465
|
-
};
|
|
1466
|
-
const runLoop = async () => {
|
|
1467
|
-
const sigintHandler = () => {
|
|
1468
|
-
_stopRequested = true;
|
|
1469
|
-
};
|
|
1470
|
-
process.once("SIGINT", sigintHandler);
|
|
1471
|
-
while (!_stopRequested) {
|
|
1472
|
-
logger.info("Connecting to remote management", { wsUrl });
|
|
1473
|
-
setRemoteManagementState({ status: RemoteManagementStatus.Connecting, errorMessage: "" });
|
|
1474
|
-
try {
|
|
1475
|
-
await handleWebSocketConnection(wsUrl, wsHost, remoteManagementConfig.apiKey, () => settleOnce(), tunnelHandler);
|
|
1476
|
-
} catch (error) {
|
|
1477
|
-
if (error instanceof RemoteManagementUnauthorizedError) {
|
|
1478
|
-
settleOnce(error);
|
|
1479
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
1480
|
-
return;
|
|
1481
|
-
}
|
|
1482
|
-
settleOnce();
|
|
1483
|
-
logger.warn("Remote management connection error", { error: String(error) });
|
|
1484
|
-
}
|
|
1485
|
-
if (_stopRequested) {
|
|
1486
|
-
break;
|
|
1487
|
-
}
|
|
1488
|
-
logger.info("Reconnecting to remote management after disconnect");
|
|
1489
|
-
await sleep(RECONNECT_SLEEP_MS);
|
|
1490
|
-
}
|
|
1491
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
1492
|
-
logger.info("Remote management stopped.");
|
|
1493
|
-
};
|
|
1494
|
-
runLoop().catch((err) => settleOnce(err instanceof Error ? err : new Error(String(err))));
|
|
1495
|
-
});
|
|
1496
|
-
}
|
|
1497
|
-
function getRemoteManagementState() {
|
|
1498
|
-
return _remoteManagementState;
|
|
1499
|
-
}
|
|
1500
|
-
function setRemoteManagementState(state, errorMessage2) {
|
|
1501
|
-
_remoteManagementState = {
|
|
1502
|
-
status: state.status,
|
|
1503
|
-
errorMessage: errorMessage2 || ""
|
|
1504
|
-
};
|
|
1505
|
-
}
|
|
1506
|
-
|
|
1507
|
-
// src/daemon/ws/wsStream.ts
|
|
1508
|
-
import { WebSocket as WebSocket2 } from "ws";
|
|
1509
|
-
var WS_NORMAL_CLOSE = 1e3;
|
|
1510
|
-
var WsStream = class {
|
|
1511
|
-
constructor(getWsUrl) {
|
|
1512
|
-
this.getWsUrl = getWsUrl;
|
|
1513
|
-
this.ws = null;
|
|
1514
|
-
this.wsReady = null;
|
|
1515
|
-
this.wsResolve = null;
|
|
1516
|
-
this.subscribedTunnels = /* @__PURE__ */ new Map();
|
|
1517
|
-
this.callbacks = {
|
|
1518
|
-
stats: [],
|
|
1519
|
-
disconnect: [],
|
|
1520
|
-
reconnecting: [],
|
|
1521
|
-
reconnected: [],
|
|
1522
|
-
reconnection_failed: [],
|
|
1523
|
-
error: [],
|
|
1524
|
-
url_ready: [],
|
|
1525
|
-
worker_error: [],
|
|
1526
|
-
will_reconnect: [],
|
|
1527
|
-
stopped: []
|
|
1528
|
-
};
|
|
1529
|
-
this.openListeners = [];
|
|
1530
|
-
this.closeListeners = [];
|
|
1531
|
-
}
|
|
1532
|
-
// Lifecycle
|
|
1533
|
-
async ensureOpen() {
|
|
1534
|
-
if (this.ws && this.ws.readyState === WebSocket2.OPEN) return;
|
|
1535
|
-
this.wsReady = new Promise((resolve) => {
|
|
1536
|
-
this.wsResolve = resolve;
|
|
1537
|
-
});
|
|
1538
|
-
this.ws = new WebSocket2(this.getWsUrl());
|
|
1539
|
-
this.ws.on("open", () => {
|
|
1540
|
-
if (this.wsResolve) {
|
|
1541
|
-
this.wsResolve();
|
|
1542
|
-
this.wsResolve = null;
|
|
1543
|
-
}
|
|
1544
|
-
for (const cb of this.openListeners) {
|
|
1545
|
-
try {
|
|
1546
|
-
cb();
|
|
1547
|
-
} catch (err) {
|
|
1548
|
-
logger.debug("WsStream open listener threw", { error: errorMessage(err) });
|
|
1549
|
-
}
|
|
1550
|
-
}
|
|
1551
|
-
});
|
|
1552
|
-
this.ws.on("message", (data) => this.handleMessage(data.toString()));
|
|
1553
|
-
this.ws.on("close", (code) => {
|
|
1554
|
-
this.ws = null;
|
|
1555
|
-
this.wsReady = null;
|
|
1556
|
-
this.wsResolve = null;
|
|
1557
|
-
for (const cb of this.closeListeners) {
|
|
1558
|
-
try {
|
|
1559
|
-
cb(code);
|
|
1560
|
-
} catch (err) {
|
|
1561
|
-
logger.debug("WsStream close listener threw", { error: errorMessage(err) });
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
});
|
|
1565
|
-
this.ws.on("error", (err) => {
|
|
1566
|
-
logger.debug("WsStream WS error", { error: errorMessage(err) });
|
|
1567
|
-
});
|
|
1568
|
-
await this.wsReady;
|
|
1569
|
-
}
|
|
1570
|
-
/** Send a normal close (1000). Use for user-initiated shutdown. */
|
|
1571
|
-
closeNormally() {
|
|
1572
|
-
if (!this.ws) return;
|
|
1573
|
-
try {
|
|
1574
|
-
this.ws.close(WS_NORMAL_CLOSE, "Client closing");
|
|
1575
|
-
} catch {
|
|
1576
|
-
}
|
|
1577
|
-
this.ws = null;
|
|
1578
|
-
this.wsReady = null;
|
|
1579
|
-
this.wsResolve = null;
|
|
1580
|
-
this.subscribedTunnels.clear();
|
|
1581
|
-
}
|
|
1582
|
-
/** Hard kill the socket. Use when daemon is known dead. */
|
|
1583
|
-
terminate() {
|
|
1584
|
-
if (!this.ws) return;
|
|
1585
|
-
try {
|
|
1586
|
-
this.ws.terminate();
|
|
1587
|
-
} catch {
|
|
1588
|
-
}
|
|
1589
|
-
this.ws = null;
|
|
1590
|
-
this.wsReady = null;
|
|
1591
|
-
this.wsResolve = null;
|
|
1592
|
-
this.subscribedTunnels.clear();
|
|
1593
|
-
}
|
|
1594
|
-
isOpen() {
|
|
1595
|
-
return !!this.ws && this.ws.readyState === WebSocket2.OPEN;
|
|
1596
|
-
}
|
|
1597
|
-
// Subscriptions
|
|
1598
|
-
async subscribe(tunnelId, mode = SessionMode.Foreground) {
|
|
1599
|
-
await this.ensureOpen();
|
|
1600
|
-
if (this.subscribedTunnels.has(tunnelId)) return;
|
|
1601
|
-
const msg = { type: "subscribe", tunnelId, mode };
|
|
1602
|
-
this.ws.send(JSON.stringify(msg));
|
|
1603
|
-
this.subscribedTunnels.set(tunnelId, { mode });
|
|
1604
|
-
}
|
|
1605
|
-
/**
|
|
1606
|
-
* Remove the local subscription. Sends an unsubscribe frame if the socket
|
|
1607
|
-
* is still open; if not, the daemon cleans up server-side when the session
|
|
1608
|
-
* closes. Returns true if the caller had this subscription.
|
|
1609
|
-
*/
|
|
1610
|
-
unsubscribe(tunnelId) {
|
|
1611
|
-
const wasSubscribed = this.subscribedTunnels.delete(tunnelId);
|
|
1612
|
-
if (!wasSubscribed) return false;
|
|
1613
|
-
if (this.ws && this.ws.readyState === WebSocket2.OPEN) {
|
|
1614
|
-
try {
|
|
1615
|
-
const msg = { type: "unsubscribe", tunnelId };
|
|
1616
|
-
this.ws.send(JSON.stringify(msg));
|
|
1617
|
-
} catch {
|
|
1618
|
-
}
|
|
1619
|
-
}
|
|
1620
|
-
return true;
|
|
1621
|
-
}
|
|
1622
|
-
hasSubscriptions() {
|
|
1623
|
-
return this.subscribedTunnels.size > 0;
|
|
1624
|
-
}
|
|
1625
|
-
subscriptionCount() {
|
|
1626
|
-
return this.subscribedTunnels.size;
|
|
1627
|
-
}
|
|
1628
|
-
isSubscribed(tunnelId) {
|
|
1629
|
-
return this.subscribedTunnels.has(tunnelId);
|
|
1630
|
-
}
|
|
1631
|
-
/** Snapshot of current subscriptions, for the reconnect path to replay. */
|
|
1632
|
-
snapshotSubscriptions() {
|
|
1633
|
-
return Array.from(this.subscribedTunnels.entries());
|
|
1634
|
-
}
|
|
1635
|
-
/**
|
|
1636
|
-
* Re-open the WS (fresh socket) and re-subscribe a previously captured set.
|
|
1637
|
-
* Clears existing state first so ensureOpen builds a new connection.
|
|
1638
|
-
*/
|
|
1639
|
-
async restoreSubscriptions(snapshot) {
|
|
1640
|
-
this.subscribedTunnels.clear();
|
|
1641
|
-
this.ws = null;
|
|
1642
|
-
this.wsReady = null;
|
|
1643
|
-
this.wsResolve = null;
|
|
1644
|
-
await this.ensureOpen();
|
|
1645
|
-
for (const [tunnelId, info] of snapshot) {
|
|
1646
|
-
const msg = { type: "subscribe", tunnelId, mode: info.mode };
|
|
1647
|
-
this.ws.send(JSON.stringify(msg));
|
|
1648
|
-
this.subscribedTunnels.set(tunnelId, info);
|
|
1649
|
-
}
|
|
1650
|
-
}
|
|
1651
|
-
// Event registration
|
|
1652
|
-
onOpen(cb) {
|
|
1653
|
-
this.openListeners.push(cb);
|
|
1654
|
-
}
|
|
1655
|
-
onClose(cb) {
|
|
1656
|
-
this.closeListeners.push(cb);
|
|
1657
|
-
}
|
|
1658
|
-
onStats(cb) {
|
|
1659
|
-
this.callbacks.stats.push(cb);
|
|
1660
|
-
}
|
|
1661
|
-
onDisconnect(cb) {
|
|
1662
|
-
this.callbacks.disconnect.push(cb);
|
|
1663
|
-
}
|
|
1664
|
-
// Removal replaces the array instead of splicing it, so a callback that
|
|
1665
|
-
// unregisters itself while handleMessage is iterating cannot make the
|
|
1666
|
-
// dispatch loop skip the next callback. The removal applies from the next
|
|
1667
|
-
// event on.
|
|
1668
|
-
offStats(cb) {
|
|
1669
|
-
this.callbacks.stats = this.callbacks.stats.filter((c) => c !== cb);
|
|
1670
|
-
}
|
|
1671
|
-
offDisconnect(cb) {
|
|
1672
|
-
this.callbacks.disconnect = this.callbacks.disconnect.filter((c) => c !== cb);
|
|
1673
|
-
}
|
|
1674
|
-
onReconnecting(cb) {
|
|
1675
|
-
this.callbacks.reconnecting.push(cb);
|
|
1676
|
-
}
|
|
1677
|
-
onReconnected(cb) {
|
|
1678
|
-
this.callbacks.reconnected.push(cb);
|
|
1679
|
-
}
|
|
1680
|
-
onReconnectionFailed(cb) {
|
|
1681
|
-
this.callbacks.reconnection_failed.push(cb);
|
|
1682
|
-
}
|
|
1683
|
-
onError(cb) {
|
|
1684
|
-
this.callbacks.error.push(cb);
|
|
1685
|
-
}
|
|
1686
|
-
onUrlReady(cb) {
|
|
1687
|
-
this.callbacks.url_ready.push(cb);
|
|
1688
|
-
}
|
|
1689
|
-
onWorkerError(cb) {
|
|
1690
|
-
this.callbacks.worker_error.push(cb);
|
|
1691
|
-
}
|
|
1692
|
-
onWillReconnect(cb) {
|
|
1693
|
-
this.callbacks.will_reconnect.push(cb);
|
|
1694
|
-
}
|
|
1695
|
-
onStopped(cb) {
|
|
1696
|
-
this.callbacks.stopped.push(cb);
|
|
1697
|
-
}
|
|
1698
|
-
// Private
|
|
1699
|
-
handleMessage(raw) {
|
|
1700
|
-
let msg;
|
|
1701
|
-
try {
|
|
1702
|
-
msg = JSON.parse(raw);
|
|
1703
|
-
} catch {
|
|
1704
|
-
return;
|
|
1705
|
-
}
|
|
1706
|
-
if (msg.type !== "tunnel_event") return;
|
|
1707
|
-
const { tunnelId, event, payload } = msg;
|
|
1708
|
-
switch (event) {
|
|
1709
|
-
case "stats":
|
|
1710
|
-
for (const cb of this.callbacks.stats) cb(tunnelId, payload.stats);
|
|
1711
|
-
break;
|
|
1712
|
-
case "disconnect": {
|
|
1713
|
-
const p = payload;
|
|
1714
|
-
for (const cb of this.callbacks.disconnect) cb(tunnelId, p.error, p.messages);
|
|
1715
|
-
break;
|
|
1716
|
-
}
|
|
1717
|
-
case "reconnecting":
|
|
1718
|
-
for (const cb of this.callbacks.reconnecting) cb(tunnelId, payload.retryCnt);
|
|
1719
|
-
break;
|
|
1720
|
-
case "reconnected":
|
|
1721
|
-
for (const cb of this.callbacks.reconnected) cb(tunnelId, payload.urls);
|
|
1722
|
-
break;
|
|
1723
|
-
case "reconnection_failed":
|
|
1724
|
-
for (const cb of this.callbacks.reconnection_failed) cb(tunnelId, payload.retryCnt);
|
|
1725
|
-
break;
|
|
1726
|
-
case "error": {
|
|
1727
|
-
const p = payload;
|
|
1728
|
-
for (const cb of this.callbacks.error) cb(tunnelId, p.message, p.isFatal);
|
|
1729
|
-
break;
|
|
1730
|
-
}
|
|
1731
|
-
case "url_ready":
|
|
1732
|
-
for (const cb of this.callbacks.url_ready) cb(tunnelId, payload.urls);
|
|
1733
|
-
break;
|
|
1734
|
-
case "worker_error":
|
|
1735
|
-
for (const cb of this.callbacks.worker_error) cb(tunnelId, payload.message);
|
|
1736
|
-
break;
|
|
1737
|
-
case "will_reconnect": {
|
|
1738
|
-
const p = payload;
|
|
1739
|
-
for (const cb of this.callbacks.will_reconnect) cb(tunnelId, p.error, p.messages);
|
|
1740
|
-
break;
|
|
1741
|
-
}
|
|
1742
|
-
case "stopped":
|
|
1743
|
-
for (const cb of this.callbacks.stopped) cb(tunnelId);
|
|
1744
|
-
break;
|
|
1745
|
-
}
|
|
1746
|
-
}
|
|
1747
|
-
};
|
|
1748
|
-
|
|
1749
|
-
// src/daemon/daemonHealth.ts
|
|
1750
|
-
var RECONNECT_ATTEMPTS = 3;
|
|
1751
|
-
var RECONNECT_INTERVAL_MS = 1e3;
|
|
1752
|
-
var HEARTBEAT_INTERVAL_MS = 5e3;
|
|
1753
|
-
var HEARTBEAT_TIMEOUT_MS = 2e3;
|
|
1754
|
-
var HEARTBEAT_FAILURE_THRESHOLD = 2;
|
|
1755
|
-
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1756
|
-
var DaemonHealth = class {
|
|
1757
|
-
constructor(getIpc, stream) {
|
|
1758
|
-
this.getIpc = getIpc;
|
|
1759
|
-
this.stream = stream;
|
|
1760
|
-
this.originalPid = null;
|
|
1761
|
-
this.lost = false;
|
|
1762
|
-
this.reconnecting = false;
|
|
1763
|
-
this.heartbeatTimer = null;
|
|
1764
|
-
this.lostCallbacks = [];
|
|
1765
|
-
this.reconnectingCallbacks = [];
|
|
1766
|
-
this.reconnectedCallbacks = [];
|
|
1767
|
-
this.stream.onOpen(() => this.startHeartbeat());
|
|
1768
|
-
this.stream.onClose((code) => {
|
|
1769
|
-
this.stopHeartbeat();
|
|
1770
|
-
if (code === WS_NORMAL_CLOSE) return;
|
|
1771
|
-
if (this.lost || this.reconnecting) return;
|
|
1772
|
-
if (!this.stream.hasSubscriptions()) return;
|
|
1773
|
-
this.reconnecting = true;
|
|
1774
|
-
this.attemptReconnect().catch((err) => logger.debug("Reconnect loop threw", { error: err?.message })).finally(() => {
|
|
1775
|
-
this.reconnecting = false;
|
|
1776
|
-
});
|
|
1777
|
-
});
|
|
1778
|
-
}
|
|
1779
|
-
bindPid(pid) {
|
|
1780
|
-
this.originalPid = pid;
|
|
1781
|
-
}
|
|
1782
|
-
/**
|
|
1783
|
-
* Forget a previous loss verdict. Called when the client re-binds to a
|
|
1784
|
-
* live daemon via ensureDaemon():
|
|
1785
|
-
*/
|
|
1786
|
-
reset() {
|
|
1787
|
-
this.lost = false;
|
|
1788
|
-
}
|
|
1789
|
-
isLost() {
|
|
1790
|
-
return this.lost;
|
|
1791
|
-
}
|
|
1792
|
-
onLost(cb) {
|
|
1793
|
-
this.lostCallbacks.push(cb);
|
|
1794
|
-
}
|
|
1795
|
-
onReconnecting(cb) {
|
|
1796
|
-
this.reconnectingCallbacks.push(cb);
|
|
1797
|
-
}
|
|
1798
|
-
onReconnected(cb) {
|
|
1799
|
-
this.reconnectedCallbacks.push(cb);
|
|
1800
|
-
}
|
|
1801
|
-
startHeartbeat() {
|
|
1802
|
-
this.stopHeartbeat();
|
|
1803
|
-
let consecutiveFailures = 0;
|
|
1804
|
-
this.heartbeatTimer = setInterval(async () => {
|
|
1805
|
-
if (this.lost || this.reconnecting) return;
|
|
1806
|
-
const ipc = this.getIpc();
|
|
1807
|
-
if (!ipc) return;
|
|
1808
|
-
try {
|
|
1809
|
-
await ipc.ping(HEARTBEAT_TIMEOUT_MS);
|
|
1810
|
-
consecutiveFailures = 0;
|
|
1811
|
-
} catch (err) {
|
|
1812
|
-
consecutiveFailures += 1;
|
|
1813
|
-
if (consecutiveFailures >= HEARTBEAT_FAILURE_THRESHOLD) {
|
|
1814
|
-
this.triggerLost("heartbeat", errorMessage(err));
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
}, HEARTBEAT_INTERVAL_MS);
|
|
1818
|
-
}
|
|
1819
|
-
stopHeartbeat() {
|
|
1820
|
-
if (this.heartbeatTimer) {
|
|
1821
|
-
clearInterval(this.heartbeatTimer);
|
|
1822
|
-
this.heartbeatTimer = null;
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
async attemptReconnect() {
|
|
1826
|
-
const snapshot = this.stream.snapshotSubscriptions();
|
|
1827
|
-
for (let attempt = 1; attempt <= RECONNECT_ATTEMPTS; attempt++) {
|
|
1828
|
-
for (const cb of this.reconnectingCallbacks) {
|
|
1829
|
-
try {
|
|
1830
|
-
cb(attempt, RECONNECT_ATTEMPTS);
|
|
1831
|
-
} catch {
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
await sleep2(RECONNECT_INTERVAL_MS);
|
|
1835
|
-
if (this.lost) return;
|
|
1836
|
-
const info = getDaemonInfo();
|
|
1837
|
-
if (!info) {
|
|
1838
|
-
this.triggerLost("dead");
|
|
1839
|
-
return;
|
|
1840
|
-
}
|
|
1841
|
-
if (info.pid !== this.originalPid) {
|
|
1842
|
-
this.triggerLost("respawned", `was pid ${this.originalPid}, now pid ${info.pid}`);
|
|
1843
|
-
return;
|
|
1844
|
-
}
|
|
1845
|
-
try {
|
|
1846
|
-
const ipc = this.getIpc();
|
|
1847
|
-
if (!ipc) throw new Error("IPC client missing");
|
|
1848
|
-
await ipc.ping(HEARTBEAT_TIMEOUT_MS);
|
|
1849
|
-
await this.stream.restoreSubscriptions(snapshot);
|
|
1850
|
-
for (const cb of this.reconnectedCallbacks) {
|
|
1851
|
-
try {
|
|
1852
|
-
cb();
|
|
1853
|
-
} catch {
|
|
1854
|
-
}
|
|
1855
|
-
}
|
|
1856
|
-
return;
|
|
1857
|
-
} catch (err) {
|
|
1858
|
-
logger.debug("Reconnect attempt failed", { attempt, error: errorMessage(err) });
|
|
1859
|
-
}
|
|
1860
|
-
}
|
|
1861
|
-
this.triggerLost("hung");
|
|
1862
|
-
}
|
|
1863
|
-
triggerLost(reason, detail) {
|
|
1864
|
-
if (this.lost) return;
|
|
1865
|
-
this.lost = true;
|
|
1866
|
-
this.stopHeartbeat();
|
|
1867
|
-
this.stream.terminate();
|
|
1868
|
-
for (const cb of this.lostCallbacks) {
|
|
1869
|
-
try {
|
|
1870
|
-
cb(reason, detail);
|
|
1871
|
-
} catch (err) {
|
|
1872
|
-
logger.debug("daemon-lost callback threw", { error: errorMessage(err) });
|
|
1873
|
-
}
|
|
1874
|
-
}
|
|
1875
|
-
}
|
|
1876
|
-
};
|
|
1877
|
-
|
|
1878
|
-
// src/daemon/tunnelClient.ts
|
|
1879
|
-
var TunnelClient = class _TunnelClient {
|
|
1880
|
-
constructor(options = {}) {
|
|
1881
|
-
this.ipc = null;
|
|
1882
|
-
// App-compat shim state: registered listeners by id, and the tunnels whose
|
|
1883
|
-
// stream subscription those registrations opened (as opposed to attach()).
|
|
1884
|
-
this.shimStatsListeners = /* @__PURE__ */ new Map();
|
|
1885
|
-
this.shimDisconnectListeners = /* @__PURE__ */ new Map();
|
|
1886
|
-
this.shimSubscribedTunnels = /* @__PURE__ */ new Set();
|
|
1887
|
-
this.shimListenerSeq = 0;
|
|
1888
|
-
this.boundDaemon = null;
|
|
1889
|
-
this.origin = options.origin ?? "cli";
|
|
1890
|
-
this.printVersionNotice = options.printVersionNotice ?? printDaemonVersionNoticeOnce;
|
|
1891
|
-
this.stream = new WsStream(() => {
|
|
1892
|
-
if (!this.ipc) throw new Error("TunnelClient not initialized. Call ensureDaemon() first.");
|
|
1893
|
-
return this.ipc.getWsUrl();
|
|
1894
|
-
});
|
|
1895
|
-
this.health = new DaemonHealth(() => this.ipc, this.stream);
|
|
1896
|
-
}
|
|
1897
|
-
/**
|
|
1898
|
-
* @param options.holdVersionNotice leaves the "daemon runs an older version" line for `printHeldVersionNotice()`.
|
|
1899
|
-
* A caller with a spinner running uses this, so the line does not land on the spinner.
|
|
1900
|
-
*/
|
|
1901
|
-
async ensureDaemon(options = {}) {
|
|
1902
|
-
this.bindDaemon(await ensureDaemonRunning());
|
|
1903
|
-
if (!options.holdVersionNotice) this.printHeldVersionNotice();
|
|
1904
|
-
}
|
|
1905
|
-
printHeldVersionNotice() {
|
|
1906
|
-
if (this.boundDaemon) this.printVersionNotice(this.boundDaemon);
|
|
1907
|
-
}
|
|
1908
|
-
/**
|
|
1909
|
-
* Connects to the daemon that runs now, and never starts one. For commands that only read state.
|
|
1910
|
-
* Throws when that daemon speaks another IPC version, as ensureDaemon() does.
|
|
1911
|
-
*
|
|
1912
|
-
* @returns false when no daemon runs
|
|
1913
|
-
*/
|
|
1914
|
-
connectIfRunning() {
|
|
1915
|
-
const info = getDaemonInfo();
|
|
1916
|
-
if (!info) return false;
|
|
1917
|
-
if (!isIpcCompatible(info)) throw new Error(ipcMismatchMessage(info));
|
|
1918
|
-
this.bindDaemon(info);
|
|
1919
|
-
this.printHeldVersionNotice();
|
|
1920
|
-
return true;
|
|
1921
|
-
}
|
|
1922
|
-
bindDaemon(info) {
|
|
1923
|
-
this.boundDaemon = info;
|
|
1924
|
-
this.ipc = new IPCClient(info.port, this.origin);
|
|
1925
|
-
this.health.bindPid(info.pid);
|
|
1926
|
-
this.health.reset();
|
|
1927
|
-
}
|
|
1928
|
-
static async forRemoteManagement() {
|
|
1929
|
-
const client = new _TunnelClient({ origin: "remote" });
|
|
1930
|
-
await client.ensureDaemon();
|
|
1931
|
-
client.health.startHeartbeat();
|
|
1932
|
-
return client;
|
|
1933
|
-
}
|
|
1934
|
-
/**
|
|
1935
|
-
* Close the WebSocket connection and cleanup.
|
|
1936
|
-
*/
|
|
1937
|
-
close() {
|
|
1938
|
-
this.health.stopHeartbeat();
|
|
1939
|
-
this.stream.closeNormally();
|
|
1940
|
-
}
|
|
1941
|
-
async ping() {
|
|
1942
|
-
this.assertClient();
|
|
1943
|
-
return this.ipc.ping();
|
|
1944
|
-
}
|
|
1945
|
-
// Tunnel Operations (HTTP)
|
|
1946
|
-
// Callers construct config from SDK shapes (FinalConfig) that are
|
|
1947
|
-
// structurally compatible with the zod-derived wire type but not nominally
|
|
1948
|
-
// identical. Accept the SDK shape and cast at the IPC boundary.
|
|
1949
|
-
async handleStartV2(config, noWait, mode) {
|
|
1950
|
-
this.assertClient();
|
|
1951
|
-
return this.ipc.startTunnelWithConfig(config, mode ?? SessionMode.Detached, noWait);
|
|
1952
|
-
}
|
|
1953
|
-
async handleStart(config, noWait, mode) {
|
|
1954
|
-
this.assertClient();
|
|
1955
|
-
return this.ipc.startTunnelV1(config, mode ?? SessionMode.Detached, noWait);
|
|
1956
|
-
}
|
|
1957
|
-
async handleUpdateConfig(config, noWait) {
|
|
1958
|
-
this.assertClient();
|
|
1959
|
-
return this.ipc.updateConfig(config, noWait);
|
|
1960
|
-
}
|
|
1961
|
-
async handleUpdateConfigV2(config, noWait) {
|
|
1962
|
-
this.assertClient();
|
|
1963
|
-
return this.ipc.updateConfigV2(config, noWait);
|
|
1964
|
-
}
|
|
1965
|
-
async handleStop(tunnelId) {
|
|
1966
|
-
this.assertClient();
|
|
1967
|
-
return this.ipc.stopTunnel(tunnelId);
|
|
1968
|
-
}
|
|
1969
|
-
async handleListV2() {
|
|
1970
|
-
this.assertClient();
|
|
1971
|
-
return this.ipc.listTunnels();
|
|
1972
|
-
}
|
|
1973
|
-
async handleList() {
|
|
1974
|
-
this.assertClient();
|
|
1975
|
-
return this.ipc.listTunnelsV1();
|
|
1976
|
-
}
|
|
1977
|
-
handleRemoveStoppedTunnelByTunnelId(tunnelId) {
|
|
1978
|
-
this.assertClient();
|
|
1979
|
-
void this.ipc.removeStoppedTunnel({ tunnelid: tunnelId });
|
|
1980
|
-
return true;
|
|
1981
|
-
}
|
|
1982
|
-
handleRemoveStoppedTunnelByConfigId(configId) {
|
|
1983
|
-
this.assertClient();
|
|
1984
|
-
void this.ipc.removeStoppedTunnel({ configId });
|
|
1985
|
-
return true;
|
|
1986
|
-
}
|
|
1987
|
-
async handleGet(tunnelId) {
|
|
1988
|
-
this.assertClient();
|
|
1989
|
-
return this.ipc.getTunnel(tunnelId);
|
|
1990
|
-
}
|
|
1991
|
-
async handleRestart(tunnelId, noWait) {
|
|
1992
|
-
this.assertClient();
|
|
1993
|
-
return this.ipc.restartTunnel(tunnelId, noWait);
|
|
1994
|
-
}
|
|
1995
|
-
async shutdown() {
|
|
1996
|
-
this.assertClient();
|
|
1997
|
-
await this.ipc.shutdown();
|
|
1998
|
-
this.close();
|
|
1999
|
-
}
|
|
2000
|
-
/**
|
|
2001
|
-
* Tear down the daemon hosted in THIS process, if any. Stops all tunnels
|
|
2002
|
-
* and removes daemon.json + daemon-state.json so the next CLI run doesn't
|
|
2003
|
-
* "crash-recover" tunnels that died with the host application.
|
|
2004
|
-
*/
|
|
2005
|
-
shutdownInProcessDaemon() {
|
|
2006
|
-
const handle = getInProcessDaemonHandle();
|
|
2007
|
-
if (!handle) return false;
|
|
2008
|
-
try {
|
|
2009
|
-
this.close();
|
|
2010
|
-
} catch {
|
|
2011
|
-
}
|
|
2012
|
-
handle.shutdown();
|
|
2013
|
-
return true;
|
|
2014
|
-
}
|
|
2015
|
-
async getLogLevel() {
|
|
2016
|
-
this.assertClient();
|
|
2017
|
-
const res = await this.ipc.getLogLevel();
|
|
2018
|
-
return res.level;
|
|
2019
|
-
}
|
|
2020
|
-
async setLogLevel(level) {
|
|
2021
|
-
this.assertClient();
|
|
2022
|
-
await this.ipc.setLogLevel(level);
|
|
2023
|
-
}
|
|
2024
|
-
async getTunnelLogging() {
|
|
2025
|
-
this.assertClient();
|
|
2026
|
-
const res = await this.ipc.getTunnelLogging();
|
|
2027
|
-
return res.enabled;
|
|
2028
|
-
}
|
|
2029
|
-
async setTunnelLogging(enabled) {
|
|
2030
|
-
this.assertClient();
|
|
2031
|
-
await this.ipc.setTunnelLogging(enabled);
|
|
2032
|
-
}
|
|
2033
|
-
async getLogPaths() {
|
|
2034
|
-
this.assertClient();
|
|
2035
|
-
return await this.ipc.getLogPaths();
|
|
2036
|
-
}
|
|
2037
|
-
async resolveLogPath(q) {
|
|
2038
|
-
this.assertClient();
|
|
2039
|
-
return await this.ipc.resolveLogPath(q);
|
|
2040
|
-
}
|
|
2041
|
-
async restart(tunnelId) {
|
|
2042
|
-
this.assertClient();
|
|
2043
|
-
await this.ipc.restartTunnel(tunnelId);
|
|
2044
|
-
}
|
|
2045
|
-
// Device agent (`pinggy device connect`). The daemon reads the token and the server from
|
|
2046
|
-
// device.json, so none of these takes either.
|
|
2047
|
-
async getDeviceAgentStatus() {
|
|
2048
|
-
this.assertClient();
|
|
2049
|
-
return this.ipc.getDeviceAgentStatus();
|
|
2050
|
-
}
|
|
2051
|
-
async startDeviceAgent() {
|
|
2052
|
-
this.assertClient();
|
|
2053
|
-
return this.ipc.startDeviceAgent();
|
|
2054
|
-
}
|
|
2055
|
-
async stopDeviceAgent() {
|
|
2056
|
-
this.assertClient();
|
|
2057
|
-
return this.ipc.stopDeviceAgent();
|
|
2058
|
-
}
|
|
2059
|
-
// Streaming — delegate to WsStream, guarded by daemon-lost
|
|
2060
|
-
async attach(tunnelId, mode = SessionMode.Foreground) {
|
|
2061
|
-
if (this.health.isLost()) return;
|
|
2062
|
-
await this.stream.subscribe(tunnelId, mode);
|
|
2063
|
-
}
|
|
2064
|
-
detach(tunnelId) {
|
|
2065
|
-
const wasSubscribed = this.stream.unsubscribe(tunnelId);
|
|
2066
|
-
if (!wasSubscribed) return;
|
|
2067
|
-
if (!this.stream.hasSubscriptions()) this.close();
|
|
2068
|
-
}
|
|
2069
|
-
// Event registration — delegate to WsStream
|
|
2070
|
-
onStats(cb) {
|
|
2071
|
-
this.stream.onStats(cb);
|
|
2072
|
-
}
|
|
2073
|
-
onDisconnect(cb) {
|
|
2074
|
-
this.stream.onDisconnect(cb);
|
|
2075
|
-
}
|
|
2076
|
-
offStats(cb) {
|
|
2077
|
-
this.stream.offStats(cb);
|
|
2078
|
-
}
|
|
2079
|
-
offDisconnect(cb) {
|
|
2080
|
-
this.stream.offDisconnect(cb);
|
|
2081
|
-
}
|
|
2082
|
-
onReconnecting(cb) {
|
|
2083
|
-
this.stream.onReconnecting(cb);
|
|
2084
|
-
}
|
|
2085
|
-
onReconnected(cb) {
|
|
2086
|
-
this.stream.onReconnected(cb);
|
|
2087
|
-
}
|
|
2088
|
-
onReconnectionFailed(cb) {
|
|
2089
|
-
this.stream.onReconnectionFailed(cb);
|
|
2090
|
-
}
|
|
2091
|
-
onError(cb) {
|
|
2092
|
-
this.stream.onError(cb);
|
|
2093
|
-
}
|
|
2094
|
-
onUrlReady(cb) {
|
|
2095
|
-
this.stream.onUrlReady(cb);
|
|
2096
|
-
}
|
|
2097
|
-
onWorkerError(cb) {
|
|
2098
|
-
this.stream.onWorkerError(cb);
|
|
2099
|
-
}
|
|
2100
|
-
onWillReconnect(cb) {
|
|
2101
|
-
this.stream.onWillReconnect(cb);
|
|
2102
|
-
}
|
|
2103
|
-
onStopped(cb) {
|
|
2104
|
-
this.stream.onStopped(cb);
|
|
2105
|
-
}
|
|
2106
|
-
// Daemon-loss events — delegate to DaemonHealth
|
|
2107
|
-
onDaemonLost(cb) {
|
|
2108
|
-
this.health.onLost(cb);
|
|
2109
|
-
}
|
|
2110
|
-
onDaemonReconnecting(cb) {
|
|
2111
|
-
this.health.onReconnecting(cb);
|
|
2112
|
-
}
|
|
2113
|
-
onDaemonReconnected(cb) {
|
|
2114
|
-
this.health.onReconnected(cb);
|
|
2115
|
-
}
|
|
2116
|
-
isDaemonLost() {
|
|
2117
|
-
return this.health.isLost();
|
|
2118
|
-
}
|
|
2119
|
-
// App-compat shims. Each registration is scoped to ONE tunnel, returns an
|
|
2120
|
-
// id, and is undone by the matching unregister call. Before this, every
|
|
2121
|
-
// register appended a callback that saw every subscribed tunnel's events
|
|
2122
|
-
// and could never be removed, so a consumer that registered per page view
|
|
2123
|
-
// received each stats update N times, forever.
|
|
2124
|
-
//
|
|
2125
|
-
// The first registration for a tunnel opens its stream subscription and
|
|
2126
|
-
// the last unregister drops it with a plain unsubscribe. detach() is not
|
|
2127
|
-
// used here on purpose: it closes the client once nothing is subscribed,
|
|
2128
|
-
// which also stops the daemon-health heartbeat, and a stats consumer must
|
|
2129
|
-
// not have that side effect.
|
|
2130
|
-
handleRegisterStatsListener(tunnelId, listener) {
|
|
2131
|
-
const wrapped = (id, stats) => {
|
|
2132
|
-
if (id === tunnelId) listener(id, stats);
|
|
2133
|
-
};
|
|
2134
|
-
const listenerId = this.nextShimListenerId("stats");
|
|
2135
|
-
this.shimStatsListeners.set(listenerId, { tunnelId, wrapped });
|
|
2136
|
-
this.stream.onStats(wrapped);
|
|
2137
|
-
this.subscribeForShim(tunnelId);
|
|
2138
|
-
return listenerId;
|
|
2139
|
-
}
|
|
2140
|
-
handleUnregisterStatsListener(_tunnelId, listenerId) {
|
|
2141
|
-
const entry = this.shimStatsListeners.get(listenerId);
|
|
2142
|
-
if (!entry) return;
|
|
2143
|
-
this.shimStatsListeners.delete(listenerId);
|
|
2144
|
-
this.stream.offStats(entry.wrapped);
|
|
2145
|
-
this.releaseShimSubscription(entry.tunnelId);
|
|
2146
|
-
}
|
|
2147
|
-
handleRegisterDisconnectListener(tunnelId, listener) {
|
|
2148
|
-
const wrapped = (id, error, messages) => {
|
|
2149
|
-
if (id === tunnelId) listener(id, error, messages);
|
|
2150
|
-
};
|
|
2151
|
-
const listenerId = this.nextShimListenerId("disconnect");
|
|
2152
|
-
this.shimDisconnectListeners.set(listenerId, { tunnelId, wrapped });
|
|
2153
|
-
this.stream.onDisconnect(wrapped);
|
|
2154
|
-
this.subscribeForShim(tunnelId);
|
|
2155
|
-
return listenerId;
|
|
2156
|
-
}
|
|
2157
|
-
handleUnregisterDisconnectListener(_tunnelId, listenerId) {
|
|
2158
|
-
const entry = this.shimDisconnectListeners.get(listenerId);
|
|
2159
|
-
if (!entry) return;
|
|
2160
|
-
this.shimDisconnectListeners.delete(listenerId);
|
|
2161
|
-
this.stream.offDisconnect(entry.wrapped);
|
|
2162
|
-
this.releaseShimSubscription(entry.tunnelId);
|
|
2163
|
-
}
|
|
2164
|
-
async handleGetTunnelStats(tunnelId) {
|
|
2165
|
-
this.assertClient();
|
|
2166
|
-
return this.ipc.getTunnelStats(tunnelId);
|
|
2167
|
-
}
|
|
2168
|
-
// Private
|
|
2169
|
-
nextShimListenerId(kind) {
|
|
2170
|
-
this.shimListenerSeq += 1;
|
|
2171
|
-
return `${kind}-${this.shimListenerSeq}`;
|
|
2172
|
-
}
|
|
2173
|
-
subscribeForShim(tunnelId) {
|
|
2174
|
-
if (!this.stream.isSubscribed(tunnelId)) this.shimSubscribedTunnels.add(tunnelId);
|
|
2175
|
-
this.attach(tunnelId, SessionMode.Detached).catch((err) => {
|
|
2176
|
-
logger.debug("Listener subscribe failed", { tunnelId, error: errorMessage(err) });
|
|
2177
|
-
});
|
|
2178
|
-
}
|
|
2179
|
-
releaseShimSubscription(tunnelId) {
|
|
2180
|
-
if (!this.shimSubscribedTunnels.has(tunnelId)) return;
|
|
2181
|
-
for (const entry of this.shimStatsListeners.values()) if (entry.tunnelId === tunnelId) return;
|
|
2182
|
-
for (const entry of this.shimDisconnectListeners.values()) if (entry.tunnelId === tunnelId) return;
|
|
2183
|
-
this.shimSubscribedTunnels.delete(tunnelId);
|
|
2184
|
-
this.stream.unsubscribe(tunnelId);
|
|
2185
|
-
}
|
|
2186
|
-
assertClient() {
|
|
2187
|
-
if (!this.ipc) {
|
|
2188
|
-
throw new Error("TunnelClient not initialized. Call ensureDaemon() first.");
|
|
2189
|
-
}
|
|
2190
|
-
}
|
|
2191
|
-
};
|
|
2192
|
-
|
|
2193
|
-
export {
|
|
2194
|
-
TunnelConfigV1Schema,
|
|
2195
|
-
TUNNEL_CONFIG_V1_KEYS,
|
|
2196
|
-
TunnelOperations,
|
|
2197
|
-
RemoteManagementUnauthorizedError,
|
|
2198
|
-
buildRemoteManagementWsUrl,
|
|
2199
|
-
initiateRemoteManagement,
|
|
2200
|
-
closeRemoteManagement,
|
|
2201
|
-
startRemoteManagement,
|
|
2202
|
-
getRemoteManagementState,
|
|
2203
|
-
TunnelClient
|
|
2204
|
-
};
|