@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,6 +1,5 @@
1
- import { Tunnel, bin, install } from 'cloudflared';
2
1
  import { debug } from '$shared/utils/logger';
3
- import { existsSync } from 'fs';
2
+ import { getBinaryPath, isBinaryInstalled, installBinary, CloudflaredTunnel } from './cloudflared';
4
3
 
5
4
  interface TunnelInstance {
6
5
  tunnel: any;
@@ -45,7 +44,7 @@ class ProjectTunnelManager {
45
44
  }
46
45
 
47
46
  // Check if binary file exists
48
- if (!existsSync(bin)) {
47
+ if (!isBinaryInstalled()) {
49
48
  debug.log('tunnel', '[PROGRESS:DOWNLOADING_BINARY] Cloudflared binary not found, downloading...');
50
49
  debug.log('tunnel', 'This may take 30-60 seconds on first use (downloading ~66MB)');
51
50
  onProgress?.('downloading-binary', { size: '~66MB' });
@@ -53,17 +52,10 @@ class ProjectTunnelManager {
53
52
  const startTime = Date.now();
54
53
 
55
54
  try {
56
- // Call install() from cloudflared package
57
- // This downloads the binary from Cloudflare's CDN
58
- await install(bin);
55
+ await installBinary();
59
56
 
60
57
  const downloadTime = Date.now() - startTime;
61
- debug.log('tunnel', `[PROGRESS:BINARY_READY] Cloudflared binary installed successfully in ${downloadTime}ms at: ${bin}`);
62
-
63
- // Verify the binary was actually created
64
- if (!existsSync(bin)) {
65
- throw new Error('Binary file was not created after installation');
66
- }
58
+ debug.log('tunnel', `[PROGRESS:BINARY_READY] Cloudflared binary installed successfully in ${downloadTime}ms at: ${getBinaryPath()}`);
67
59
 
68
60
  this.binaryInstalled = true;
69
61
  onProgress?.('binary-ready', { downloaded: true, time: downloadTime });
@@ -76,7 +68,7 @@ class ProjectTunnelManager {
76
68
  );
77
69
  }
78
70
  } else {
79
- debug.log('tunnel', '[PROGRESS:BINARY_READY] Cloudflared binary already installed at:', bin);
71
+ debug.log('tunnel', '[PROGRESS:BINARY_READY] Cloudflared binary already installed at:', getBinaryPath());
80
72
  this.binaryInstalled = true;
81
73
  onProgress?.('binary-ready', { cached: true });
82
74
  return { needsDownload: false };
@@ -116,7 +108,7 @@ class ProjectTunnelManager {
116
108
 
117
109
  // Create quick tunnel pointing to localhost:port
118
110
  // Use Tunnel.quick() method for quick tunnels
119
- const tunnel = Tunnel.quick(`http://localhost:${port}`);
111
+ const tunnel = CloudflaredTunnel.quick(`http://localhost:${port}`);
120
112
 
121
113
  // Log ALL events for debugging
122
114
  tunnel.on('url', (url: string) => debug.log('tunnel', `[EVENT] url: ${url}`));
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Tunnel Config Manager
3
+ *
4
+ * Manages Cloudflare Tunnel configurations:
5
+ * - Remote (dashboard-managed): token + label
6
+ * - Local (locally-managed): tunnel name, ID, credentials, ingress rules
7
+ *
8
+ * Config stored in ~/.clopen/tunnel/config.json
9
+ */
10
+
11
+ import { join } from 'path';
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
13
+ import { getClopenDir } from '../utils/paths';
14
+ import { debug } from '$shared/utils/logger';
15
+ import { randomUUID } from 'crypto';
16
+
17
+ // --- Types ---
18
+
19
+ export interface RemoteTunnelConfig {
20
+ id: string;
21
+ label: string;
22
+ token: string;
23
+ }
24
+
25
+ export interface LocalTunnelIngressRule {
26
+ hostname: string;
27
+ service: string;
28
+ }
29
+
30
+ export interface LocalTunnelConfig {
31
+ id: string;
32
+ name: string;
33
+ tunnelId: string;
34
+ credentialsFile: string;
35
+ ingress: LocalTunnelIngressRule[];
36
+ }
37
+
38
+ interface TunnelConfigFile {
39
+ remotes: RemoteTunnelConfig[];
40
+ locals: LocalTunnelConfig[];
41
+ authorizedZone?: string;
42
+ }
43
+
44
+ // --- Paths ---
45
+
46
+ const TUNNEL_DIR = join(getClopenDir(), 'tunnel');
47
+ const CONFIG_FILE = join(TUNNEL_DIR, 'config.json');
48
+
49
+ export function getTunnelDir(): string {
50
+ return TUNNEL_DIR;
51
+ }
52
+
53
+ // --- Internal helpers ---
54
+
55
+ function ensureDir(): void {
56
+ if (!existsSync(TUNNEL_DIR)) {
57
+ mkdirSync(TUNNEL_DIR, { recursive: true });
58
+ }
59
+ }
60
+
61
+ function readConfigFile(): TunnelConfigFile {
62
+ try {
63
+ if (!existsSync(CONFIG_FILE)) {
64
+ return { remotes: [], locals: [] };
65
+ }
66
+ const raw = readFileSync(CONFIG_FILE, 'utf-8');
67
+ const data = JSON.parse(raw);
68
+
69
+ // Migration: old format { configs: [{ id, token, domain }] }
70
+ if (data.configs && !data.remotes) {
71
+ const migrated: TunnelConfigFile = {
72
+ remotes: data.configs.map((c: { id: string; token: string; domain: string }) => ({
73
+ id: c.id,
74
+ label: c.domain,
75
+ token: c.token
76
+ })),
77
+ locals: []
78
+ };
79
+ writeConfigFile(migrated);
80
+ debug.log('tunnel', 'Migrated old tunnel config to remote/local format');
81
+ return migrated;
82
+ }
83
+
84
+ // Migration: single entry format { token, domain }
85
+ if (data.token && data.domain && !data.remotes && !data.configs) {
86
+ const migrated: TunnelConfigFile = {
87
+ remotes: [{ id: randomUUID(), label: data.domain, token: data.token }],
88
+ locals: []
89
+ };
90
+ writeConfigFile(migrated);
91
+ debug.log('tunnel', 'Migrated single tunnel config to remote/local format');
92
+ return migrated;
93
+ }
94
+
95
+ return {
96
+ remotes: data.remotes ?? [],
97
+ locals: data.locals ?? [],
98
+ authorizedZone: data.authorizedZone
99
+ };
100
+ } catch (error) {
101
+ debug.error('tunnel', 'Failed to read tunnel config:', error);
102
+ return { remotes: [], locals: [] };
103
+ }
104
+ }
105
+
106
+ function writeConfigFile(data: TunnelConfigFile): void {
107
+ ensureDir();
108
+ writeFileSync(CONFIG_FILE, JSON.stringify(data, null, '\t'), 'utf-8');
109
+ }
110
+
111
+ // --- Remote tunnel config ---
112
+
113
+ export function getRemoteTunnelConfigs(): RemoteTunnelConfig[] {
114
+ return readConfigFile().remotes;
115
+ }
116
+
117
+ export function getRemoteTunnelConfigById(id: string): RemoteTunnelConfig | null {
118
+ return readConfigFile().remotes.find((c) => c.id === id) ?? null;
119
+ }
120
+
121
+ export function addRemoteTunnelConfig(label: string, token: string): RemoteTunnelConfig {
122
+ const data = readConfigFile();
123
+ const entry: RemoteTunnelConfig = { id: randomUUID(), label, token };
124
+ data.remotes.push(entry);
125
+ writeConfigFile(data);
126
+ debug.log('tunnel', `Remote tunnel config added: ${label}`);
127
+ return entry;
128
+ }
129
+
130
+ export function removeRemoteTunnelConfig(id: string): boolean {
131
+ const data = readConfigFile();
132
+ const before = data.remotes.length;
133
+ data.remotes = data.remotes.filter((c) => c.id !== id);
134
+ if (data.remotes.length < before) {
135
+ writeConfigFile(data);
136
+ debug.log('tunnel', `Remote tunnel config removed: ${id}`);
137
+ return true;
138
+ }
139
+ return false;
140
+ }
141
+
142
+ // --- Local tunnel config ---
143
+
144
+ export function getLocalTunnelConfigs(): LocalTunnelConfig[] {
145
+ return readConfigFile().locals;
146
+ }
147
+
148
+ export function getLocalTunnelConfigById(id: string): LocalTunnelConfig | null {
149
+ return readConfigFile().locals.find((c) => c.id === id) ?? null;
150
+ }
151
+
152
+ export function addLocalTunnelConfig(
153
+ name: string,
154
+ tunnelId: string,
155
+ credentialsFile: string
156
+ ): LocalTunnelConfig {
157
+ const data = readConfigFile();
158
+ const entry: LocalTunnelConfig = {
159
+ id: randomUUID(),
160
+ name,
161
+ tunnelId,
162
+ credentialsFile,
163
+ ingress: []
164
+ };
165
+ data.locals.push(entry);
166
+ writeConfigFile(data);
167
+ debug.log('tunnel', `Local tunnel config added: ${name} (${tunnelId})`);
168
+ return entry;
169
+ }
170
+
171
+ export function removeLocalTunnelConfig(id: string): boolean {
172
+ const data = readConfigFile();
173
+ const before = data.locals.length;
174
+ data.locals = data.locals.filter((c) => c.id !== id);
175
+ if (data.locals.length < before) {
176
+ writeConfigFile(data);
177
+ debug.log('tunnel', `Local tunnel config removed: ${id}`);
178
+ return true;
179
+ }
180
+ return false;
181
+ }
182
+
183
+ export function addLocalTunnelIngress(
184
+ id: string,
185
+ hostname: string,
186
+ service: string
187
+ ): LocalTunnelConfig | null {
188
+ const data = readConfigFile();
189
+ const config = data.locals.find((c) => c.id === id);
190
+ if (!config) return null;
191
+
192
+ // Update existing or add new
193
+ const existing = config.ingress.findIndex((r) => r.hostname === hostname);
194
+ if (existing >= 0) {
195
+ config.ingress[existing].service = service;
196
+ } else {
197
+ config.ingress.push({ hostname, service });
198
+ }
199
+
200
+ writeConfigFile(data);
201
+ debug.log('tunnel', `Ingress rule added/updated for ${config.name}: ${hostname} -> ${service}`);
202
+ return config;
203
+ }
204
+
205
+ export function removeLocalTunnelIngress(id: string, hostname: string): LocalTunnelConfig | null {
206
+ const data = readConfigFile();
207
+ const config = data.locals.find((c) => c.id === id);
208
+ if (!config) return null;
209
+
210
+ config.ingress = config.ingress.filter((r) => r.hostname !== hostname);
211
+ writeConfigFile(data);
212
+ debug.log('tunnel', `Ingress rule removed for ${config.name}: ${hostname}`);
213
+ return config;
214
+ }
215
+
216
+ // --- Authorized zone ---
217
+
218
+ export function getAuthorizedZone(): string | null {
219
+ return readConfigFile().authorizedZone ?? null;
220
+ }
221
+
222
+ export function setAuthorizedZone(zone: string): void {
223
+ const data = readConfigFile();
224
+ data.authorizedZone = zone;
225
+ writeConfigFile(data);
226
+ debug.log('tunnel', `Authorized zone set: ${zone}`);
227
+ }
228
+
229
+ export function clearAuthorizedZone(): void {
230
+ const data = readConfigFile();
231
+ delete data.authorizedZone;
232
+ writeConfigFile(data);
233
+ debug.log('tunnel', 'Authorized zone cleared');
234
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Tunnel Config Endpoints
3
+ *
4
+ * HTTP endpoints for managing tunnel configurations:
5
+ * - Remote: list, add (token+label), remove
6
+ * - Local: list configs
7
+ */
8
+
9
+ import { t } from 'elysia';
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import {
12
+ getRemoteTunnelConfigs,
13
+ addRemoteTunnelConfig,
14
+ removeRemoteTunnelConfig,
15
+ getLocalTunnelConfigs
16
+ } from '../../tunnel/tunnel-config';
17
+ import { globalTunnelManager } from '../../tunnel/global-tunnel-manager';
18
+
19
+ export const configHandler = createRouter()
20
+
21
+ // ═══════════════════════════════════════
22
+ // Remote Tunnel Configs
23
+ // ═══════════════════════════════════════
24
+
25
+ .http('tunnel:remote:config:list', {
26
+ data: t.Object({}),
27
+ response: t.Object({
28
+ configs: t.Array(t.Object({
29
+ id: t.String(),
30
+ label: t.String(),
31
+ isActive: t.Boolean(),
32
+ ingress: t.Array(t.Object({
33
+ hostname: t.Optional(t.String()),
34
+ service: t.String()
35
+ }))
36
+ }))
37
+ })
38
+ }, async () => {
39
+ const configs = getRemoteTunnelConfigs();
40
+ return {
41
+ // Never expose tokens to the frontend
42
+ configs: configs.map((c) => ({
43
+ id: c.id,
44
+ label: c.label,
45
+ isActive: globalTunnelManager.isRemoteTunnelActive(c.id),
46
+ ingress: globalTunnelManager.getRemoteTunnelIngress(c.id)
47
+ }))
48
+ };
49
+ })
50
+
51
+ .http('tunnel:remote:config:add', {
52
+ data: t.Object({
53
+ label: t.String({ minLength: 1 }),
54
+ token: t.String({ minLength: 1 })
55
+ }),
56
+ response: t.Object({
57
+ id: t.String(),
58
+ label: t.String()
59
+ })
60
+ }, async ({ data }) => {
61
+ const entry = addRemoteTunnelConfig(data.label, data.token);
62
+ return { id: entry.id, label: entry.label };
63
+ })
64
+
65
+ .http('tunnel:remote:config:remove', {
66
+ data: t.Object({
67
+ id: t.String({ minLength: 1 })
68
+ }),
69
+ response: t.Object({ success: t.Boolean() })
70
+ }, async ({ data }) => {
71
+ // Stop if running
72
+ if (globalTunnelManager.isRemoteTunnelActive(data.id)) {
73
+ await globalTunnelManager.stopRemoteTunnel(data.id);
74
+ }
75
+ const removed = removeRemoteTunnelConfig(data.id);
76
+ return { success: removed };
77
+ })
78
+
79
+ // ═══════════════════════════════════════
80
+ // Local Tunnel Configs
81
+ // ═══════════════════════════════════════
82
+
83
+ .http('tunnel:local:config:list', {
84
+ data: t.Object({}),
85
+ response: t.Object({
86
+ configs: t.Array(t.Object({
87
+ id: t.String(),
88
+ name: t.String(),
89
+ tunnelId: t.String(),
90
+ ingress: t.Array(t.Object({
91
+ hostname: t.String(),
92
+ service: t.String()
93
+ })),
94
+ isActive: t.Boolean()
95
+ }))
96
+ })
97
+ }, async () => {
98
+ const configs = getLocalTunnelConfigs();
99
+ return {
100
+ configs: configs.map((c) => ({
101
+ id: c.id,
102
+ name: c.name,
103
+ tunnelId: c.tunnelId,
104
+ ingress: c.ingress,
105
+ isActive: globalTunnelManager.isLocalTunnelActive(c.id)
106
+ }))
107
+ };
108
+ });
@@ -9,6 +9,8 @@
9
9
 
10
10
  import { createRouter } from '$shared/utils/ws-server';
11
11
  import { operationsHandler } from './operations';
12
+ import { configHandler } from './config';
12
13
 
13
14
  export const tunnelRouter = createRouter()
14
- .merge(operationsHandler);
15
+ .merge(operationsHandler)
16
+ .merge(configHandler);