@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.
@@ -2,90 +2,337 @@
2
2
  * Tunnel Operations
3
3
  *
4
4
  * HTTP endpoints for tunnel management:
5
- * - Start tunnel
6
- * - Stop tunnel
7
- * - Get tunnel status
5
+ * - Quick tunnel: start/stop with random URL
6
+ * - Remote tunnel: start/stop dashboard-managed tunnels
7
+ * - Local tunnel: auth, create, delete, ingress, route-dns, start/stop
8
8
  */
9
9
 
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { globalTunnelManager } from '../../tunnel/global-tunnel-manager';
13
+ import {
14
+ getRemoteTunnelConfigById,
15
+ getLocalTunnelConfigById,
16
+ addLocalTunnelConfig,
17
+ removeLocalTunnelConfig,
18
+ addLocalTunnelIngress,
19
+ removeLocalTunnelIngress,
20
+ getAuthorizedZone,
21
+ setAuthorizedZone,
22
+ clearAuthorizedZone
23
+ } from '../../tunnel/tunnel-config';
13
24
  import { debug } from '$shared/utils/logger';
25
+ import { ws } from '$backend/utils/ws';
26
+
27
+ // Wire up ingress update callback to push via WS
28
+ globalTunnelManager.setRemoteIngressUpdateCallback((configId, ingress) => {
29
+ ws.emit.global('tunnel:remote:ingress-update', { configId, ingress });
30
+ });
31
+
32
+ // Wire up status changed callback to push tunnel list via WS
33
+ globalTunnelManager.setStatusChangedCallback(() => {
34
+ const tunnels = globalTunnelManager.getActiveTunnels();
35
+ ws.emit.global('tunnel:status-changed', { tunnels });
36
+ });
14
37
 
15
38
  export const operationsHandler = createRouter()
16
- // Start tunnel
17
- .http('tunnel:start', {
39
+
40
+ // ═══════════════════════════════════════
41
+ // Quick Tunnel
42
+ // ═══════════════════════════════════════
43
+
44
+ .http('tunnel:quick:start', {
18
45
  data: t.Object({
19
46
  port: t.Number({ minimum: 1, maximum: 65535 }),
20
- autoStopMinutes: t.Optional(t.Number())
47
+ autoStopMinutes: t.Optional(t.Number({ minimum: 0 }))
21
48
  }),
22
49
  response: t.Any()
23
50
  }, async ({ data }) => {
24
- const startTime = Date.now();
25
- const { port, autoStopMinutes } = data;
51
+ const { port, autoStopMinutes = 60 } = data;
52
+ debug.log('tunnel', `[WS] Quick tunnel start: port=${port}, autoStop=${autoStopMinutes}`);
26
53
 
27
- debug.log('tunnel', `[WS] ====== Starting global tunnel request ======`);
28
- debug.log('tunnel', `[WS] Port: ${port}`);
29
- debug.log('tunnel', `[WS] Auto-stop: ${autoStopMinutes || 60} minutes`);
54
+ const result = await globalTunnelManager.startQuickTunnel(port, autoStopMinutes);
55
+ return result;
56
+ })
30
57
 
31
- // Validate port
32
- if (!port || port < 1 || port > 65535) {
33
- debug.error('tunnel', `[WS] Invalid port number: ${port}`);
34
- throw new Error('Invalid port number');
35
- }
58
+ .http('tunnel:quick:stop', {
59
+ data: t.Object({
60
+ port: t.Number()
61
+ }),
62
+ response: t.Object({ stopped: t.Boolean() })
63
+ }, async ({ data }) => {
64
+ await globalTunnelManager.stopQuickTunnel(data.port);
65
+ return { stopped: true };
66
+ })
36
67
 
37
- // Start tunnel without progress callback (HTTP-like pattern doesn't support progress)
38
- const result = await globalTunnelManager.startTunnel(
39
- port,
40
- autoStopMinutes || 60,
41
- undefined // No progress callback for HTTP pattern
42
- );
68
+ // ═══════════════════════════════════════
69
+ // Remote Tunnel (Dashboard-managed)
70
+ // ═══════════════════════════════════════
43
71
 
44
- debug.log('tunnel', `[WS] ✅ Tunnel started successfully in ${Date.now() - startTime}ms`);
72
+ .http('tunnel:remote:start', {
73
+ data: t.Object({
74
+ configId: t.String({ minLength: 1 })
75
+ }),
76
+ response: t.Any()
77
+ }, async ({ data }) => {
78
+ const config = getRemoteTunnelConfigById(data.configId);
79
+ if (!config) throw new Error('Remote tunnel config not found');
45
80
 
81
+ debug.log('tunnel', `[WS] Remote tunnel start: ${config.label}`);
82
+ const result = await globalTunnelManager.startRemoteTunnel(config);
46
83
  return result;
47
84
  })
48
85
 
49
- // Stop tunnel
50
- .http('tunnel:stop', {
86
+ .http('tunnel:remote:stop', {
87
+ data: t.Object({
88
+ configId: t.String({ minLength: 1 })
89
+ }),
90
+ response: t.Object({ stopped: t.Boolean() })
91
+ }, async ({ data }) => {
92
+ await globalTunnelManager.stopRemoteTunnel(data.configId);
93
+ return { stopped: true };
94
+ })
95
+
96
+ .http('tunnel:remote:ingress', {
51
97
  data: t.Object({
52
- port: t.Number({ minimum: 1, maximum: 65535 })
98
+ configId: t.String({ minLength: 1 })
53
99
  }),
54
100
  response: t.Object({
55
- stopped: t.Boolean()
101
+ ingress: t.Array(t.Object({
102
+ hostname: t.Optional(t.String()),
103
+ service: t.String()
104
+ }))
56
105
  })
57
106
  }, async ({ data }) => {
58
- const { port } = data;
107
+ const ingress = globalTunnelManager.getRemoteTunnelIngress(data.configId);
108
+ return { ingress };
109
+ })
59
110
 
60
- debug.log('tunnel', `[WS] Stop tunnel request for port ${port}`);
111
+ // ═══════════════════════════════════════
112
+ // Local Tunnel (Locally-managed)
113
+ // ═══════════════════════════════════════
61
114
 
62
- // Validate port
63
- if (!port || port < 1 || port > 65535) {
64
- debug.error('tunnel', `[WS] Invalid port number: ${port}`);
65
- throw new Error('Invalid port number');
115
+ .http('tunnel:local:auth-status', {
116
+ data: t.Object({}),
117
+ response: t.Object({
118
+ authenticated: t.Boolean(),
119
+ certPath: t.String(),
120
+ zone: t.Nullable(t.String())
121
+ })
122
+ }, async () => {
123
+ const auth = globalTunnelManager.checkCloudflaredAuth();
124
+ const zone = getAuthorizedZone();
125
+ return { ...auth, zone };
126
+ })
127
+
128
+ .http('tunnel:local:logout', {
129
+ data: t.Object({}),
130
+ response: t.Object({ success: t.Boolean() })
131
+ }, async () => {
132
+ globalTunnelManager.logoutCloudflared();
133
+ clearAuthorizedZone();
134
+ return { success: true };
135
+ })
136
+
137
+ .http('tunnel:local:set-zone', {
138
+ data: t.Object({
139
+ zone: t.String({ minLength: 1 })
140
+ }),
141
+ response: t.Object({ success: t.Boolean(), zone: t.String() })
142
+ }, async ({ data }) => {
143
+ setAuthorizedZone(data.zone);
144
+ return { success: true, zone: data.zone };
145
+ })
146
+
147
+ // Login is event-driven (push URL back via WS event)
148
+ .on('tunnel:local:login-start', {
149
+ data: t.Object({})
150
+ }, async ({ conn }) => {
151
+ const userId = ws.getUserId(conn);
152
+
153
+ await globalTunnelManager.loginCloudflared(
154
+ (url) => {
155
+ ws.emit.user(userId, 'tunnel:local:login-url', { url });
156
+ },
157
+ () => {
158
+ ws.emit.user(userId, 'tunnel:local:login-complete', {});
159
+ },
160
+ (error) => {
161
+ ws.emit.user(userId, 'tunnel:local:login-error', { message: error });
162
+ }
163
+ );
164
+ })
165
+
166
+ .on('tunnel:local:login-cancel', {
167
+ data: t.Object({})
168
+ }, async () => {
169
+ globalTunnelManager.cancelLogin();
170
+ })
171
+
172
+ .http('tunnel:local:create', {
173
+ data: t.Object({
174
+ name: t.String({ minLength: 1, maxLength: 100 })
175
+ }),
176
+ response: t.Object({
177
+ id: t.String(),
178
+ name: t.String(),
179
+ tunnelId: t.String()
180
+ })
181
+ }, async ({ data }) => {
182
+ debug.log('tunnel', `[WS] Creating local tunnel: ${data.name}`);
183
+
184
+ const result = await globalTunnelManager.createLocalTunnel(data.name);
185
+ const config = addLocalTunnelConfig(data.name, result.tunnelId, result.credentialsFile);
186
+
187
+ return { id: config.id, name: config.name, tunnelId: config.tunnelId };
188
+ })
189
+
190
+ .http('tunnel:local:delete', {
191
+ data: t.Object({
192
+ id: t.String({ minLength: 1 })
193
+ }),
194
+ response: t.Object({ success: t.Boolean() })
195
+ }, async ({ data }) => {
196
+ const config = getLocalTunnelConfigById(data.id);
197
+ if (!config) throw new Error('Local tunnel config not found');
198
+
199
+ // Stop if running
200
+ if (globalTunnelManager.isLocalTunnelActive(data.id)) {
201
+ await globalTunnelManager.stopLocalTunnel(data.id);
202
+ }
203
+
204
+ // Delete from Cloudflare
205
+ try {
206
+ await globalTunnelManager.deleteLocalTunnel(config.tunnelId, config.credentialsFile);
207
+ } catch (error) {
208
+ debug.warn('tunnel', `Could not delete tunnel from Cloudflare (may already be deleted):`, error);
66
209
  }
67
210
 
68
- // Stop tunnel
69
- await globalTunnelManager.stopTunnel(port);
211
+ // Remove from config and cleanup files
212
+ removeLocalTunnelConfig(data.id);
213
+ globalTunnelManager.cleanupLocalTunnelFiles(config.tunnelId);
214
+ return { success: true };
215
+ })
216
+
217
+ .http('tunnel:local:ingress:add', {
218
+ data: t.Object({
219
+ id: t.String({ minLength: 1 }),
220
+ hostname: t.String({ minLength: 1 }),
221
+ service: t.String({ minLength: 1 })
222
+ }),
223
+ response: t.Object({
224
+ success: t.Boolean(),
225
+ ingress: t.Array(t.Object({
226
+ hostname: t.String(),
227
+ service: t.String()
228
+ })),
229
+ dnsRouted: t.Boolean(),
230
+ dnsError: t.Nullable(t.String())
231
+ })
232
+ }, async ({ data }) => {
233
+ const tunnelConfig = getLocalTunnelConfigById(data.id);
234
+ if (!tunnelConfig) throw new Error('Local tunnel config not found');
235
+
236
+ // Add ingress rule
237
+ const config = addLocalTunnelIngress(data.id, data.hostname, data.service);
238
+ if (!config) throw new Error('Failed to add ingress rule');
239
+
240
+ // Auto route DNS using tunnel UUID (more reliable than name)
241
+ let dnsRouted = false;
242
+ let dnsError: string | null = null;
243
+ try {
244
+ await globalTunnelManager.routeDns(tunnelConfig.tunnelId, data.hostname);
245
+ dnsRouted = true;
246
+ debug.log('tunnel', `DNS routed for ${data.hostname} -> tunnel ${tunnelConfig.tunnelId}`);
247
+ } catch (error) {
248
+ dnsError = error instanceof Error ? error.message : String(error);
249
+ debug.warn('tunnel', `Auto route-dns for ${data.hostname} failed:`, dnsError);
250
+ }
251
+
252
+ return { success: true, ingress: config.ingress, dnsRouted, dnsError };
253
+ })
254
+
255
+ .http('tunnel:local:ingress:remove', {
256
+ data: t.Object({
257
+ id: t.String({ minLength: 1 }),
258
+ hostname: t.String({ minLength: 1 })
259
+ }),
260
+ response: t.Object({
261
+ success: t.Boolean(),
262
+ ingress: t.Array(t.Object({
263
+ hostname: t.String(),
264
+ service: t.String()
265
+ }))
266
+ })
267
+ }, async ({ data }) => {
268
+ const config = removeLocalTunnelIngress(data.id, data.hostname);
269
+ if (!config) throw new Error('Local tunnel config not found');
270
+
271
+ // Regenerate config.yml to stay in sync
272
+ globalTunnelManager.writeLocalTunnelConfig(config);
273
+
274
+ return { success: true, ingress: config.ingress };
275
+ })
276
+
277
+ .http('tunnel:local:start', {
278
+ data: t.Object({
279
+ id: t.String({ minLength: 1 })
280
+ }),
281
+ response: t.Any()
282
+ }, async ({ data }) => {
283
+ const config = getLocalTunnelConfigById(data.id);
284
+ if (!config) throw new Error('Local tunnel config not found');
70
285
 
71
- debug.log('tunnel', `[WS] ✅ Tunnel stopped on port ${port}`);
286
+ debug.log('tunnel', `[WS] Starting local tunnel: ${config.name}`);
287
+ const result = await globalTunnelManager.startLocalTunnel(config);
288
+ return result;
289
+ })
72
290
 
291
+ .http('tunnel:local:stop', {
292
+ data: t.Object({
293
+ id: t.String({ minLength: 1 })
294
+ }),
295
+ response: t.Object({ stopped: t.Boolean() })
296
+ }, async ({ data }) => {
297
+ await globalTunnelManager.stopLocalTunnel(data.id);
73
298
  return { stopped: true };
74
299
  })
75
300
 
76
- // Get tunnel status
301
+ // ═══════════════════════════════════════
302
+ // Global Status
303
+ // ═══════════════════════════════════════
304
+
77
305
  .http('tunnel:status', {
78
306
  data: t.Object({}),
79
307
  response: t.Object({
80
308
  tunnels: t.Array(t.Any())
81
309
  })
82
310
  }, async () => {
83
- debug.log('tunnel', '[WS] Get tunnel status request');
311
+ return { tunnels: globalTunnelManager.getActiveTunnels() };
312
+ })
313
+
314
+ // ═══════════════════════════════════════
315
+ // Event declarations (Server → Client)
316
+ // ═══════════════════════════════════════
317
+
318
+ .emit('tunnel:status-changed', t.Object({
319
+ tunnels: t.Array(t.Any())
320
+ }))
321
+
322
+ .emit('tunnel:remote:ingress-update', t.Object({
323
+ configId: t.String(),
324
+ ingress: t.Array(t.Object({
325
+ hostname: t.Optional(t.String()),
326
+ service: t.String()
327
+ }))
328
+ }))
84
329
 
85
- // Get all active tunnels
86
- const tunnels = globalTunnelManager.getActiveTunnels();
330
+ .emit('tunnel:local:login-url', t.Object({
331
+ url: t.String()
332
+ }))
87
333
 
88
- debug.log('tunnel', `[WS] Found ${tunnels.length} active tunnel(s)`);
334
+ .emit('tunnel:local:login-complete', t.Object({}))
89
335
 
90
- return { tunnels };
91
- });
336
+ .emit('tunnel:local:login-error', t.Object({
337
+ message: t.String()
338
+ }));
package/bun.lock CHANGED
@@ -22,7 +22,6 @@
22
22
  "@xterm/headless": "^6.0.0",
23
23
  "@xterm/xterm": "^6.0.0",
24
24
  "bun-pty": "^0.4.2",
25
- "cloudflared": "^0.7.1",
26
25
  "elysia": "^1.4.19",
27
26
  "file-type": "^21.0.0",
28
27
  "is-text-path": "^3.0.0",
@@ -56,7 +55,6 @@
56
55
  },
57
56
  },
58
57
  "trustedDependencies": [
59
- "cloudflared",
60
58
  "puppeteer",
61
59
  ],
62
60
  "packages": {
@@ -434,8 +432,6 @@
434
432
 
435
433
  "clone-deep": ["clone-deep@0.2.4", "", { "dependencies": { "for-own": "^0.1.3", "is-plain-object": "^2.0.1", "kind-of": "^3.0.2", "lazy-cache": "^1.0.3", "shallow-clone": "^0.1.2" } }, "sha512-we+NuQo2DHhSl+DP6jlUiAhyAjBQrYnpOk15rN6c6JSPScjiCLh8IbSU+VTcph6YS3o7mASE8a0+gbZ7ChLpgg=="],
436
434
 
437
- "cloudflared": ["cloudflared@0.7.1", "", { "bin": { "cloudflared": "lib/cloudflared.js" } }, "sha512-jJn1Gu9Tf4qnIu8tfiHZ25Hs8rNcRYSVf8zAd97wvYdOCzftm1CTs1S/RPhijjGi8gUT1p9yzfDi9zYlU/0RwA=="],
438
-
439
435
  "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
440
436
 
441
437
  "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
@@ -36,8 +36,9 @@
36
36
  // Initialize MCP Preview Integration
37
37
  initializeMCPPreview();
38
38
 
39
- // Restore tunnel status
39
+ // Restore tunnel status and listen for realtime updates
40
40
  tunnelStore.checkStatus();
41
+ tunnelStore.initRealtimeListener();
41
42
 
42
43
  // Start periodic update checker
43
44
  startUpdateChecker();
@@ -22,6 +22,7 @@
22
22
  import InviteManagement from './admin/InviteManagement.svelte';
23
23
  import SecuritySettings from './security/SecuritySettings.svelte';
24
24
  import SystemSettings from './system/SystemSettings.svelte';
25
+ import TunnelSettings from './tunnel/TunnelSettings.svelte';
25
26
 
26
27
  // Responsive state
27
28
  let isMobileMenuOpen = $state(false);
@@ -231,6 +232,10 @@
231
232
  <div in:fly={{ x: 20, duration: 200 }}>
232
233
  <NotificationSettings />
233
234
  </div>
235
+ {:else if activeSection === 'tunnel'}
236
+ <div in:fly={{ x: 20, duration: 200 }}>
237
+ <TunnelSettings />
238
+ </div>
234
239
  {:else if activeSection === 'account'}
235
240
  <div in:fly={{ x: 20, duration: 200 }}>
236
241
  <AccountSettings />
@@ -11,6 +11,7 @@
11
11
  import SystemSettings from './system/SystemSettings.svelte';
12
12
  import UserManagement from './admin/UserManagement.svelte';
13
13
  import InviteManagement from './admin/InviteManagement.svelte';
14
+ import TunnelSettings from './tunnel/TunnelSettings.svelte';
14
15
 
15
16
  const isAdmin = $derived(authStore.isAdmin);
16
17
  const isNoAuth = $derived(authStore.isNoAuth);
@@ -32,6 +33,9 @@
32
33
  <!-- Notification Settings -->
33
34
  <NotificationSettings />
34
35
 
36
+ <!-- Tunnel Settings -->
37
+ <TunnelSettings />
38
+
35
39
  <!-- Account (hidden in no-auth mode) -->
36
40
  {#if !isNoAuth}
37
41
  <AccountSettings />