@myrialabs/clopen 0.2.15 → 0.2.16

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.
@@ -1,57 +1,107 @@
1
- import { Tunnel, bin, install } from 'cloudflared';
1
+ /**
2
+ * Global Tunnel Manager
3
+ *
4
+ * Manages three types of Cloudflare Tunnels:
5
+ * - Quick: Random URL via trycloudflare.com (no account needed)
6
+ * - Remote: Dashboard-managed tunnels via token (ConfigHandler for ingress sync)
7
+ * - Local: Locally-managed tunnels (login, create, config file, run)
8
+ */
9
+
2
10
  import { debug } from '$shared/utils/logger';
3
- import { existsSync } from 'fs';
11
+ import { existsSync, mkdirSync, renameSync, writeFileSync, unlinkSync, rmSync } from 'fs';
12
+ import { homedir } from 'os';
13
+ import { join } from 'path';
14
+ import { getTunnelDir } from './tunnel-config';
15
+ import type { RemoteTunnelConfig, LocalTunnelConfig } from './tunnel-config';
16
+ import { getBinaryPath, isBinaryInstalled, installBinary, CloudflaredTunnel, type LoginHandle } from './cloudflared';
17
+
18
+ // --- Types ---
4
19
 
5
- interface TunnelInstance {
6
- tunnel: any;
20
+ export type TunnelType = 'quick' | 'remote' | 'local';
21
+
22
+ export interface IngressInfo {
23
+ hostname?: string;
24
+ service: string;
25
+ }
26
+
27
+ interface BaseTunnelInstance {
28
+ tunnel: CloudflaredTunnel;
29
+ startedAt: Date;
30
+ type: TunnelType;
31
+ }
32
+
33
+ interface QuickTunnelInstance extends BaseTunnelInstance {
34
+ type: 'quick';
7
35
  publicUrl: string;
8
36
  localPort: number;
9
- startedAt: Date;
10
37
  autoStopMinutes: number;
11
- autoStopTimer?: NodeJS.Timeout;
38
+ autoStopTimer?: ReturnType<typeof setTimeout>;
39
+ }
40
+
41
+ interface RemoteTunnelInstance extends BaseTunnelInstance {
42
+ type: 'remote';
43
+ configId: string;
44
+ label: string;
45
+ ingress: IngressInfo[];
46
+ }
47
+
48
+ interface LocalTunnelInstance extends BaseTunnelInstance {
49
+ type: 'local';
50
+ configId: string;
51
+ name: string;
52
+ ingress: IngressInfo[];
12
53
  }
13
54
 
55
+ // --- Cloudflared paths ---
56
+
57
+ const CERT_PATH = join(getTunnelDir(), 'cert.pem');
58
+ const DEFAULT_CLOUDFLARED_CERT = join(homedir(), '.cloudflared', 'cert.pem');
59
+
60
+ // --- Manager ---
61
+
14
62
  class GlobalTunnelManager {
15
- // Key format: "port" for global tunnels
16
- private activeTunnels = new Map<number, TunnelInstance>();
63
+ private quickTunnels = new Map<number, QuickTunnelInstance>();
64
+ private remoteTunnels = new Map<string, RemoteTunnelInstance>();
65
+ private localTunnels = new Map<string, LocalTunnelInstance>();
17
66
  private binaryInstalled = false;
67
+ private loginHandle: LoginHandle | null = null;
68
+
69
+ // Callback for pushing ingress updates to connected clients
70
+ private onRemoteIngressUpdate?: (configId: string, ingress: IngressInfo[]) => void;
71
+ // Callback for pushing tunnel list changes
72
+ private onStatusChanged?: () => void;
73
+
74
+ setRemoteIngressUpdateCallback(cb: (configId: string, ingress: IngressInfo[]) => void): void {
75
+ this.onRemoteIngressUpdate = cb;
76
+ }
77
+
78
+ setStatusChangedCallback(cb: () => void): void {
79
+ this.onStatusChanged = cb;
80
+ }
81
+
82
+ private notifyStatusChanged(): void {
83
+ this.onStatusChanged?.();
84
+ }
85
+
86
+ // --- Binary management ---
18
87
 
19
- /**
20
- * Ensure cloudflared binary is installed
21
- * Downloads binary on first use (~66MB, takes 30-60 seconds)
22
- */
23
88
  private async ensureBinaryInstalled(
24
89
  onProgress?: (stage: string, data?: any) => void
25
- ): Promise<{
26
- needsDownload: boolean;
27
- downloadTime?: number;
28
- }> {
29
- // Check if already verified in this session
90
+ ): Promise<{ needsDownload: boolean; downloadTime?: number }> {
30
91
  if (this.binaryInstalled) {
31
92
  onProgress?.('binary-ready', { cached: true });
32
93
  return { needsDownload: false };
33
94
  }
34
95
 
35
- // Check if binary file exists
36
- if (!existsSync(bin)) {
37
- debug.log('tunnel', '[PROGRESS:DOWNLOADING_BINARY] Cloudflared binary not found, downloading...');
38
- debug.log('tunnel', 'This may take 30-60 seconds on first use (downloading ~66MB)');
96
+ if (!isBinaryInstalled()) {
97
+ debug.log('tunnel', 'Cloudflared binary not found, downloading...');
39
98
  onProgress?.('downloading-binary', { size: '~66MB' });
40
99
 
41
100
  const startTime = Date.now();
42
-
43
101
  try {
44
- // Call install() from cloudflared package
45
- // This downloads the binary from Cloudflare's CDN
46
- await install(bin);
47
-
102
+ await installBinary();
48
103
  const downloadTime = Date.now() - startTime;
49
- debug.log('tunnel', `[PROGRESS:BINARY_READY] Cloudflared binary installed successfully in ${downloadTime}ms at: ${bin}`);
50
-
51
- // Verify the binary was actually created
52
- if (!existsSync(bin)) {
53
- throw new Error('Binary file was not created after installation');
54
- }
104
+ debug.log('tunnel', `Cloudflared binary installed in ${downloadTime}ms at: ${getBinaryPath()}`);
55
105
 
56
106
  this.binaryInstalled = true;
57
107
  onProgress?.('binary-ready', { downloaded: true, time: downloadTime });
@@ -59,90 +109,62 @@ class GlobalTunnelManager {
59
109
  } catch (error) {
60
110
  debug.error('tunnel', 'Failed to install cloudflared binary:', error);
61
111
  throw new Error(
62
- 'Failed to download cloudflared binary. Please check your internet connection and try again. ' +
63
- 'The tunnel feature requires downloading ~66MB on first use.'
112
+ 'Failed to download cloudflared binary. Please check your internet connection and try again.'
64
113
  );
65
114
  }
66
- } else {
67
- debug.log('tunnel', '[PROGRESS:BINARY_READY] Cloudflared binary already installed at:', bin);
68
- this.binaryInstalled = true;
69
- onProgress?.('binary-ready', { cached: true });
70
- return { needsDownload: false };
71
115
  }
116
+
117
+ debug.log('tunnel', 'Cloudflared binary already installed at:', getBinaryPath());
118
+ this.binaryInstalled = true;
119
+ onProgress?.('binary-ready', { cached: true });
120
+ return { needsDownload: false };
72
121
  }
73
122
 
74
- /**
75
- * Start cloudflared tunnel for a port
76
- */
77
- async startTunnel(
123
+ // --- Quick tunnel ---
124
+
125
+ async startQuickTunnel(
78
126
  port: number,
79
127
  autoStopMinutes: number = 60,
80
128
  onProgress?: (stage: string, data?: any) => void
81
- ): Promise<{ publicUrl: string; status: 'active'; binaryDownloaded: boolean; timings: any }> {
82
- debug.log('tunnel', '[PROGRESS:CHECKING_BINARY] Checking if binary is installed...');
129
+ ): Promise<{ publicUrl: string; binaryDownloaded: boolean; timings: Record<string, number> }> {
83
130
  onProgress?.('checking-binary');
84
-
85
- // Ensure binary is installed
86
131
  const binaryInfo = await this.ensureBinaryInstalled(onProgress);
87
- const timings: any = {};
88
-
89
- if (binaryInfo.needsDownload) {
90
- timings.binaryDownload = binaryInfo.downloadTime;
91
- }
132
+ const timings: Record<string, number> = {};
133
+ if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
92
134
 
93
- // Check if tunnel already exists for this port
94
- if (this.activeTunnels.has(port)) {
95
- const existing = this.activeTunnels.get(port)!;
96
- debug.log('tunnel', `Tunnel already exists for port ${port}, returning existing URL`);
97
- return {
98
- publicUrl: existing.publicUrl,
99
- status: 'active',
100
- binaryDownloaded: binaryInfo.needsDownload,
101
- timings
102
- };
135
+ if (this.quickTunnels.has(port)) {
136
+ const existing = this.quickTunnels.get(port)!;
137
+ return { publicUrl: existing.publicUrl, binaryDownloaded: binaryInfo.needsDownload, timings };
103
138
  }
104
139
 
105
- debug.log('tunnel', `[PROGRESS:STARTING_TUNNEL] Starting cloudflared tunnel for port ${port}...`);
106
140
  onProgress?.('starting-tunnel', { port });
107
-
108
141
  const tunnelStartTime = Date.now();
109
142
 
110
143
  try {
111
- // Create quick tunnel instance
112
- const tunnel = Tunnel.quick(`http://localhost:${port}`);
113
-
114
- // Log ALL events for debugging
115
- tunnel.on('url', (url: string) => debug.log('tunnel', `[EVENT] url: ${url}`));
116
- tunnel.on('connected', (info: any) => debug.log('tunnel', `[EVENT] connected:`, info));
117
- tunnel.on('error', (error: Error) => debug.error('tunnel', `[EVENT] error:`, error));
118
- tunnel.on('exit', (code: number | null) => debug.log('tunnel', `[EVENT] exit with code ${code}`));
119
- tunnel.on('stdout', (data: string) => debug.log('tunnel', `[STDOUT] ${data.trim()}`));
120
- tunnel.on('stderr', (data: string) => debug.log('tunnel', `[STDERR] ${data.trim()}`));
121
-
122
- // Wait for tunnel to be ready
123
- debug.log('tunnel', '[PROGRESS:GENERATING_URL] Waiting for public URL...');
144
+ const tunnel = CloudflaredTunnel.quick(`http://localhost:${port}`);
145
+
146
+ tunnel.on('error', (error: Error) => debug.error('tunnel', `[quick:${port}] error:`, error));
147
+ tunnel.on('exit', (code: number | null) => {
148
+ debug.log('tunnel', `[quick:${port}] exit code ${code}`);
149
+ this.quickTunnels.delete(port);
150
+ this.notifyStatusChanged();
151
+ });
152
+
124
153
  onProgress?.('generating-url');
125
154
 
126
155
  const publicUrl: string = await new Promise((resolve, reject) => {
127
156
  const timeout = setTimeout(() => {
128
157
  tunnel.stop();
129
- reject(new Error('Tunnel connection timeout (30s). Please check if port ' + port + ' is accessible and has a running service.'));
130
- }, 30000); // 30 second timeout
158
+ reject(new Error(`Tunnel connection timeout (30s). Please check if port ${port} is accessible.`));
159
+ }, 30000);
131
160
 
132
161
  tunnel.on('url', (url: string) => {
133
- // Validate that this is an actual tunnel URL, not the API endpoint
134
- if (url.includes('api.trycloudflare.com')) {
135
- debug.log('tunnel', `Ignoring API endpoint URL: ${url}`);
136
- return;
137
- }
138
-
139
- debug.log('tunnel', `[PROGRESS:CONNECTED] ✅ Tunnel connected! Public URL: ${url}`);
162
+ if (url.includes('api.trycloudflare.com')) return;
140
163
  clearTimeout(timeout);
141
164
  resolve(url);
142
165
  });
143
166
 
144
167
  tunnel.on('error', (error: Error) => {
145
- debug.error('tunnel', '[PROGRESS:FAILED] Tunnel error:', error);
146
168
  clearTimeout(timeout);
147
169
  reject(error);
148
170
  });
@@ -150,117 +172,481 @@ class GlobalTunnelManager {
150
172
  tunnel.once('exit', (code: number | null) => {
151
173
  if (code !== 0 && code !== null) {
152
174
  clearTimeout(timeout);
153
- reject(new Error(`Tunnel failed to start (exit code ${code}). Please check your internet connection.`));
175
+ reject(new Error(`Tunnel failed to start (exit code ${code}).`));
154
176
  }
155
177
  });
156
178
  });
157
179
 
158
180
  timings.tunnelStart = Date.now() - tunnelStartTime;
159
- timings.total = Date.now() - tunnelStartTime + (binaryInfo.downloadTime || 0);
160
-
161
- // Setup auto-stop timer
162
- const autoStopMs = autoStopMinutes * 60 * 1000;
163
- const autoStopTimer = setTimeout(
164
- () => {
165
- debug.log('tunnel', `Auto-stopping tunnel on port ${port} after ${autoStopMinutes} minutes`);
166
- this.stopTunnel(port);
167
- },
168
- autoStopMs
169
- );
170
-
171
- // Store tunnel instance
172
- const instance: TunnelInstance = {
181
+
182
+ let autoStopTimer: ReturnType<typeof setTimeout> | undefined;
183
+ if (autoStopMinutes > 0) {
184
+ autoStopTimer = setTimeout(async () => {
185
+ debug.log('tunnel', `Auto-stopping quick tunnel on port ${port}`);
186
+ await this.stopQuickTunnel(port);
187
+ }, autoStopMinutes * 60 * 1000);
188
+ }
189
+
190
+ this.quickTunnels.set(port, {
173
191
  tunnel,
174
192
  publicUrl,
175
193
  localPort: port,
194
+ type: 'quick',
176
195
  startedAt: new Date(),
177
196
  autoStopMinutes,
178
197
  autoStopTimer
179
- };
180
-
181
- this.activeTunnels.set(port, instance);
198
+ });
182
199
 
183
- debug.log('tunnel', `✅ Tunnel started successfully on port ${port}`);
184
- debug.log('tunnel', ` Public URL: ${publicUrl}`);
185
- debug.log('tunnel', ` Auto-stop: ${autoStopMinutes} minutes`);
186
- debug.log('tunnel', ` Timings:`, timings);
200
+ debug.log('tunnel', `Quick tunnel started on port ${port}: ${publicUrl}`);
187
201
  onProgress?.('connected', { publicUrl, timings });
202
+ this.notifyStatusChanged();
188
203
 
189
- return {
190
- publicUrl,
191
- status: 'active',
192
- binaryDownloaded: binaryInfo.needsDownload,
193
- timings
204
+ return { publicUrl, binaryDownloaded: binaryInfo.needsDownload, timings };
205
+ } catch (error) {
206
+ debug.error('tunnel', `Failed to start quick tunnel on port ${port}:`, error);
207
+ throw error;
208
+ }
209
+ }
210
+
211
+ async stopQuickTunnel(port: number): Promise<void> {
212
+ const instance = this.quickTunnels.get(port);
213
+ if (!instance) return;
214
+
215
+ if (instance.autoStopTimer) clearTimeout(instance.autoStopTimer);
216
+ try {
217
+ instance.tunnel.stop();
218
+ } catch { /* ignore */ }
219
+ this.quickTunnels.delete(port);
220
+ debug.log('tunnel', `Quick tunnel stopped on port ${port}`);
221
+ this.notifyStatusChanged();
222
+ }
223
+
224
+ // --- Remote tunnel (dashboard-managed) ---
225
+
226
+ async startRemoteTunnel(
227
+ config: RemoteTunnelConfig,
228
+ onProgress?: (stage: string, data?: any) => void
229
+ ): Promise<{ binaryDownloaded: boolean; timings: Record<string, number> }> {
230
+ onProgress?.('checking-binary');
231
+ const binaryInfo = await this.ensureBinaryInstalled(onProgress);
232
+ const timings: Record<string, number> = {};
233
+ if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
234
+
235
+ if (this.remoteTunnels.has(config.id)) {
236
+ return { binaryDownloaded: binaryInfo.needsDownload, timings };
237
+ }
238
+
239
+ onProgress?.('starting-tunnel', { label: config.label });
240
+ const tunnelStartTime = Date.now();
241
+
242
+ try {
243
+ const tunnel = CloudflaredTunnel.withToken(config.token);
244
+
245
+ const instance: RemoteTunnelInstance = {
246
+ tunnel,
247
+ type: 'remote',
248
+ configId: config.id,
249
+ label: config.label,
250
+ startedAt: new Date(),
251
+ ingress: []
194
252
  };
253
+
254
+ // Sync ingress from config events (emitted by the tunnel's built-in config handler)
255
+ tunnel.on('config', (data: { config: any; version: number }) => {
256
+ if (data.config?.ingress && Array.isArray(data.config.ingress)) {
257
+ instance.ingress = data.config.ingress.map((rule: any) => ({
258
+ hostname: rule.hostname,
259
+ service: rule.service
260
+ }));
261
+ debug.log('tunnel', `[remote:${config.label}] Config synced, ${instance.ingress.length} ingress rules`);
262
+ this.onRemoteIngressUpdate?.(config.id, instance.ingress);
263
+ }
264
+ });
265
+
266
+ tunnel.on('error', (error: Error) => debug.error('tunnel', `[remote:${config.label}] error:`, error));
267
+ tunnel.on('exit', (code: number | null) => {
268
+ debug.log('tunnel', `[remote:${config.label}] exit code ${code}`);
269
+ this.remoteTunnels.delete(config.id);
270
+ this.notifyStatusChanged();
271
+ });
272
+
273
+ onProgress?.('generating-url');
274
+
275
+ // Wait for first connection
276
+ await new Promise<void>((resolve, reject) => {
277
+ const timeout = setTimeout(() => {
278
+ tunnel.stop();
279
+ reject(new Error('Remote tunnel connection timeout (60s). Please check your token.'));
280
+ }, 60000);
281
+
282
+ tunnel.once('connected', () => {
283
+ clearTimeout(timeout);
284
+ resolve();
285
+ });
286
+
287
+ tunnel.once('error', (error: Error) => {
288
+ clearTimeout(timeout);
289
+ tunnel.stop();
290
+ reject(error);
291
+ });
292
+
293
+ tunnel.once('exit', (code: number | null) => {
294
+ if (code !== 0 && code !== null) {
295
+ clearTimeout(timeout);
296
+ reject(new Error(`Remote tunnel failed (exit code ${code}). Please verify your token.`));
297
+ }
298
+ });
299
+ });
300
+
301
+ timings.tunnelStart = Date.now() - tunnelStartTime;
302
+ this.remoteTunnels.set(config.id, instance);
303
+
304
+ debug.log('tunnel', `Remote tunnel started: ${config.label}`);
305
+ onProgress?.('connected', { timings });
306
+ this.notifyStatusChanged();
307
+
308
+ return { binaryDownloaded: binaryInfo.needsDownload, timings };
195
309
  } catch (error) {
196
- debug.error('tunnel', `Failed to start tunnel on port ${port}:`, error);
310
+ debug.error('tunnel', `Failed to start remote tunnel ${config.label}:`, error);
197
311
  throw error;
198
312
  }
199
313
  }
200
314
 
201
- /**
202
- * Stop tunnel for a port
203
- */
204
- async stopTunnel(port: number): Promise<void> {
205
- const instance = this.activeTunnels.get(port);
315
+ async stopRemoteTunnel(configId: string): Promise<void> {
316
+ const instance = this.remoteTunnels.get(configId);
317
+ if (!instance) return;
318
+
319
+ try {
320
+ instance.tunnel.stop();
321
+ } catch { /* ignore */ }
322
+ this.remoteTunnels.delete(configId);
323
+ debug.log('tunnel', `Remote tunnel stopped: ${instance.label}`);
324
+ this.notifyStatusChanged();
325
+ }
206
326
 
207
- if (!instance) {
208
- debug.log('tunnel', `No active tunnel found for port ${port}`);
327
+ getRemoteTunnelIngress(configId: string): IngressInfo[] {
328
+ return this.remoteTunnels.get(configId)?.ingress ?? [];
329
+ }
330
+
331
+ isRemoteTunnelActive(configId: string): boolean {
332
+ return this.remoteTunnels.has(configId);
333
+ }
334
+
335
+ // --- Local tunnel (locally-managed) ---
336
+
337
+ checkCloudflaredAuth(): { authenticated: boolean; certPath: string } {
338
+ // Migrate cert from default cloudflared location if it exists there but not in our dir
339
+ if (!existsSync(CERT_PATH) && existsSync(DEFAULT_CLOUDFLARED_CERT)) {
340
+ this.moveCertToTunnelDir();
341
+ }
342
+ const authenticated = existsSync(CERT_PATH);
343
+ return { authenticated, certPath: CERT_PATH };
344
+ }
345
+
346
+ async loginCloudflared(
347
+ onUrl?: (url: string) => void,
348
+ onComplete?: () => void,
349
+ onError?: (error: string) => void
350
+ ): Promise<void> {
351
+ await this.ensureBinaryInstalled();
352
+
353
+ if (this.loginHandle) {
354
+ onError?.('Login process already running');
209
355
  return;
210
356
  }
211
357
 
212
- debug.log('tunnel', `Stopping tunnel on port ${port}...`);
358
+ debug.log('tunnel', 'Starting cloudflared login...');
359
+
360
+ this.loginHandle = CloudflaredTunnel.login({
361
+ onUrl: (url) => {
362
+ debug.log('tunnel', `[login] Auth URL: ${url}`);
363
+ onUrl?.(url);
364
+ },
365
+ onComplete: () => {
366
+ this.loginHandle = null;
367
+ // Move cert.pem from ~/.cloudflared/ to our tunnel dir
368
+ this.moveCertToTunnelDir();
369
+ debug.log('tunnel', 'Cloudflared login successful');
370
+ onComplete?.();
371
+ },
372
+ onError: (message) => {
373
+ this.loginHandle = null;
374
+ debug.error('tunnel', `Cloudflared login failed: ${message}`);
375
+ onError?.(message);
376
+ }
377
+ });
378
+ }
213
379
 
214
- try {
215
- // Clear auto-stop timer
216
- if (instance.autoStopTimer) {
217
- clearTimeout(instance.autoStopTimer);
380
+ private moveCertToTunnelDir(): void {
381
+ if (existsSync(DEFAULT_CLOUDFLARED_CERT)) {
382
+ const tunnelDir = getTunnelDir();
383
+ if (!existsSync(tunnelDir)) {
384
+ mkdirSync(tunnelDir, { recursive: true });
218
385
  }
386
+ renameSync(DEFAULT_CLOUDFLARED_CERT, CERT_PATH);
387
+ debug.log('tunnel', `Cert moved: ${DEFAULT_CLOUDFLARED_CERT} -> ${CERT_PATH}`);
388
+ }
389
+ }
390
+
391
+ cancelLogin(): void {
392
+ if (this.loginHandle) {
393
+ debug.log('tunnel', 'Cloudflared login cancelled by user');
394
+ this.loginHandle.cancel();
395
+ this.loginHandle = null;
396
+ }
397
+ }
219
398
 
220
- // Stop tunnel
221
- if (instance.tunnel && typeof instance.tunnel.stop === 'function') {
222
- await instance.tunnel.stop();
399
+ logoutCloudflared(): { success: boolean } {
400
+ try {
401
+ if (existsSync(CERT_PATH)) {
402
+ unlinkSync(CERT_PATH);
403
+ debug.log('tunnel', 'Cloudflared cert.pem removed (logged out)');
223
404
  }
405
+ return { success: true };
406
+ } catch (error) {
407
+ debug.error('tunnel', 'Failed to remove cert.pem:', error);
408
+ return { success: false };
409
+ }
410
+ }
411
+
412
+ async createLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
413
+ await this.ensureBinaryInstalled();
414
+
415
+ // Write credentials directly to our dir (not ~/.cloudflared/)
416
+ const tunnelBaseDir = getTunnelDir();
417
+ if (!existsSync(tunnelBaseDir)) {
418
+ mkdirSync(tunnelBaseDir, { recursive: true });
419
+ }
420
+ const tempCredentials = join(tunnelBaseDir, `${name}.json`);
421
+ const result = await CloudflaredTunnel.createTunnel(name, { credentialsFile: tempCredentials, origincert: CERT_PATH });
422
+
423
+ // Organize into {tunnelId}/ subdirectory
424
+ const tunnelDir = join(tunnelBaseDir, result.tunnelId);
425
+ if (!existsSync(tunnelDir)) {
426
+ mkdirSync(tunnelDir, { recursive: true });
427
+ }
428
+ const finalCredentials = join(tunnelDir, 'credentials.json');
429
+ renameSync(tempCredentials, finalCredentials);
430
+
431
+ debug.log('tunnel', `Local tunnel created: ${name} (${result.tunnelId})`);
432
+ return { tunnelId: result.tunnelId, credentialsFile: finalCredentials };
433
+ }
434
+
435
+ async deleteLocalTunnel(tunnelId: string, credentialsFile?: string): Promise<void> {
436
+ await this.ensureBinaryInstalled();
437
+
438
+ await CloudflaredTunnel.deleteTunnel(tunnelId, { credentialsFile, origincert: CERT_PATH });
439
+ debug.log('tunnel', `Local tunnel deleted: ${tunnelId}`);
440
+ }
441
+
442
+ cleanupLocalTunnelFiles(tunnelId: string): void {
443
+ const configDir = join(getTunnelDir(), tunnelId);
444
+ if (existsSync(configDir)) {
445
+ rmSync(configDir, { recursive: true });
446
+ debug.log('tunnel', `Tunnel config directory removed: ${configDir}`);
447
+ }
448
+ }
449
+
450
+ async routeDns(tunnelName: string, hostname: string): Promise<{ alreadyExists: boolean }> {
451
+ await this.ensureBinaryInstalled();
452
+
453
+ const result = await CloudflaredTunnel.routeDns(tunnelName, hostname, { overwriteDns: true, origincert: CERT_PATH });
454
+ debug.log('tunnel', `DNS route ${result.alreadyExists ? 'updated' : 'added'}: ${hostname} -> ${tunnelName}`);
455
+ return result;
456
+ }
457
+
458
+ writeLocalTunnelConfig(config: LocalTunnelConfig): string {
459
+ const configDir = join(getTunnelDir(), config.tunnelId);
460
+ if (!existsSync(configDir)) {
461
+ mkdirSync(configDir, { recursive: true });
462
+ }
463
+
464
+ const configPath = join(configDir, 'config.yml');
465
+
466
+ const ingressRules = [
467
+ ...config.ingress.map((r) => ` - hostname: ${r.hostname}\n service: ${r.service}`),
468
+ ' - service: http_status:404'
469
+ ];
470
+
471
+ const yml = [
472
+ `tunnel: ${config.tunnelId}`,
473
+ `credentials-file: ${config.credentialsFile}`,
474
+ 'ingress:',
475
+ ...ingressRules
476
+ ].join('\n');
477
+
478
+ writeFileSync(configPath, yml, 'utf-8');
479
+ debug.log('tunnel', `Config file written: ${configPath}`);
480
+ return configPath;
481
+ }
482
+
483
+ async startLocalTunnel(
484
+ config: LocalTunnelConfig,
485
+ onProgress?: (stage: string, data?: any) => void
486
+ ): Promise<{ binaryDownloaded: boolean; timings: Record<string, number> }> {
487
+ onProgress?.('checking-binary');
488
+ const binaryInfo = await this.ensureBinaryInstalled(onProgress);
489
+ const timings: Record<string, number> = {};
490
+ if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
491
+
492
+ if (this.localTunnels.has(config.id)) {
493
+ return { binaryDownloaded: binaryInfo.needsDownload, timings };
494
+ }
495
+
496
+ if (config.ingress.length === 0) {
497
+ throw new Error('Cannot start tunnel without ingress rules. Add at least one hostname mapping.');
498
+ }
224
499
 
225
- // Remove from active tunnels
226
- this.activeTunnels.delete(port);
500
+ // Write config file
501
+ const configPath = this.writeLocalTunnelConfig(config);
227
502
 
228
- debug.log('tunnel', `✅ Tunnel stopped on port ${port}`);
503
+ onProgress?.('starting-tunnel', { name: config.name });
504
+ const tunnelStartTime = Date.now();
505
+
506
+ try {
507
+ const tunnel = CloudflaredTunnel.withConfig(configPath);
508
+
509
+ tunnel.on('error', (error: Error) => debug.error('tunnel', `[local:${config.name}] error:`, error));
510
+ tunnel.on('exit', (code: number | null) => {
511
+ debug.log('tunnel', `[local:${config.name}] exit code ${code}`);
512
+ this.localTunnels.delete(config.id);
513
+ this.notifyStatusChanged();
514
+ });
515
+
516
+ onProgress?.('generating-url');
517
+
518
+ // Wait for first connection
519
+ await new Promise<void>((resolve, reject) => {
520
+ const timeout = setTimeout(() => {
521
+ tunnel.stop();
522
+ reject(new Error('Local tunnel connection timeout (60s). Check your config and credentials.'));
523
+ }, 60000);
524
+
525
+ tunnel.once('connected', () => {
526
+ clearTimeout(timeout);
527
+ resolve();
528
+ });
529
+
530
+ tunnel.once('error', (error: Error) => {
531
+ clearTimeout(timeout);
532
+ tunnel.stop();
533
+ reject(error);
534
+ });
535
+
536
+ tunnel.once('exit', (code: number | null) => {
537
+ if (code !== 0 && code !== null) {
538
+ clearTimeout(timeout);
539
+ reject(new Error(`Local tunnel failed (exit code ${code}).`));
540
+ }
541
+ });
542
+ });
543
+
544
+ timings.tunnelStart = Date.now() - tunnelStartTime;
545
+
546
+ const instance: LocalTunnelInstance = {
547
+ tunnel,
548
+ type: 'local',
549
+ configId: config.id,
550
+ name: config.name,
551
+ startedAt: new Date(),
552
+ ingress: config.ingress.map((r) => ({ hostname: r.hostname, service: r.service }))
553
+ };
554
+
555
+ this.localTunnels.set(config.id, instance);
556
+ debug.log('tunnel', `Local tunnel started: ${config.name}`);
557
+ onProgress?.('connected', { timings });
558
+ this.notifyStatusChanged();
559
+
560
+ return { binaryDownloaded: binaryInfo.needsDownload, timings };
229
561
  } catch (error) {
230
- debug.error('tunnel', `Error stopping tunnel on port ${port}:`, error);
231
- // Still remove from active tunnels even if stop failed
232
- this.activeTunnels.delete(port);
562
+ debug.error('tunnel', `Failed to start local tunnel ${config.name}:`, error);
233
563
  throw error;
234
564
  }
235
565
  }
236
566
 
237
- /**
238
- * Get all active tunnels
239
- */
567
+ async stopLocalTunnel(configId: string): Promise<void> {
568
+ const instance = this.localTunnels.get(configId);
569
+ if (!instance) return;
570
+
571
+ try {
572
+ instance.tunnel.stop();
573
+ } catch { /* ignore */ }
574
+ this.localTunnels.delete(configId);
575
+ debug.log('tunnel', `Local tunnel stopped: ${instance.name}`);
576
+ this.notifyStatusChanged();
577
+ }
578
+
579
+ isLocalTunnelActive(configId: string): boolean {
580
+ return this.localTunnels.has(configId);
581
+ }
582
+
583
+ // --- Status / global ---
584
+
240
585
  getActiveTunnels(): Array<{
241
586
  port: number;
242
587
  publicUrl: string;
243
588
  startedAt: string;
244
589
  autoStopMinutes: number;
590
+ type: TunnelType;
591
+ label?: string;
592
+ configId?: string;
593
+ ingress?: IngressInfo[];
245
594
  }> {
246
- return Array.from(this.activeTunnels.entries()).map(([port, instance]) => ({
247
- port,
248
- publicUrl: instance.publicUrl,
249
- startedAt: instance.startedAt.toISOString(),
250
- autoStopMinutes: instance.autoStopMinutes
251
- }));
595
+ const tunnels: ReturnType<typeof this.getActiveTunnels> = [];
596
+
597
+ for (const [port, instance] of this.quickTunnels) {
598
+ tunnels.push({
599
+ port,
600
+ publicUrl: instance.publicUrl,
601
+ startedAt: instance.startedAt.toISOString(),
602
+ autoStopMinutes: instance.autoStopMinutes,
603
+ type: 'quick'
604
+ });
605
+ }
606
+
607
+ for (const [, instance] of this.remoteTunnels) {
608
+ const firstHostname = instance.ingress.find((r) => r.hostname)?.hostname;
609
+ tunnels.push({
610
+ port: 0,
611
+ publicUrl: firstHostname ? `https://${firstHostname}` : '',
612
+ startedAt: instance.startedAt.toISOString(),
613
+ autoStopMinutes: 0,
614
+ type: 'remote',
615
+ label: instance.label,
616
+ configId: instance.configId,
617
+ ingress: instance.ingress
618
+ });
619
+ }
620
+
621
+ for (const [, instance] of this.localTunnels) {
622
+ const firstHostname = instance.ingress.find((r) => r.hostname)?.hostname;
623
+ tunnels.push({
624
+ port: 0,
625
+ publicUrl: firstHostname ? `https://${firstHostname}` : '',
626
+ startedAt: instance.startedAt.toISOString(),
627
+ autoStopMinutes: 0,
628
+ type: 'local',
629
+ label: instance.name,
630
+ configId: instance.configId,
631
+ ingress: instance.ingress
632
+ });
633
+ }
634
+
635
+ return tunnels;
252
636
  }
253
637
 
254
- /**
255
- * Stop all tunnels
256
- */
257
638
  async stopAllTunnels(): Promise<void> {
258
639
  debug.log('tunnel', 'Stopping all tunnels...');
259
- const ports = Array.from(this.activeTunnels.keys());
260
- await Promise.all(ports.map((port) => this.stopTunnel(port)));
261
- debug.log('tunnel', '✅ All tunnels stopped');
640
+
641
+ const ops: Promise<void>[] = [];
642
+ for (const port of this.quickTunnels.keys()) ops.push(this.stopQuickTunnel(port));
643
+ for (const id of this.remoteTunnels.keys()) ops.push(this.stopRemoteTunnel(id));
644
+ for (const id of this.localTunnels.keys()) ops.push(this.stopLocalTunnel(id));
645
+
646
+ await Promise.all(ops);
647
+ debug.log('tunnel', 'All tunnels stopped');
262
648
  }
263
649
  }
264
650
 
265
- // Singleton instance
651
+ // Singleton
266
652
  export const globalTunnelManager = new GlobalTunnelManager();