@myrialabs/clopen 0.3.19 → 0.3.20
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/backend/database/migrations/039_create_file_audit_log.ts +45 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
- package/backend/database/queries/file-audit-log-queries.ts +184 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/db-client/drivers/mysql.ts +28 -10
- package/backend/db-client/drivers/postgres.ts +34 -18
- package/backend/engine/install-recipes.ts +1 -109
- package/backend/http/files-upload.ts +84 -3
- package/backend/tunnel/tunnel-config.ts +76 -209
- package/backend/utils/client-ip.test.ts +55 -0
- package/backend/utils/client-ip.ts +42 -0
- package/backend/utils/ws.ts +6 -3
- package/backend/ws/auth/login.test.ts +271 -0
- package/backend/ws/auth/login.ts +36 -3
- package/backend/ws/auth/users.ts +3 -2
- package/backend/ws/files/path-access.test.ts +60 -1
- package/backend/ws/files/path-access.ts +21 -0
- package/backend/ws/system-tools/install.ts +0 -1
- package/backend/ws/system-tools/status.ts +3 -4
- package/backend/ws/tunnel/config.ts +17 -25
- package/backend/ws/tunnel/operations.ts +63 -68
- package/dist/assets/{main-BOUXyIaW.js → main-72Z_L-nD.js} +199 -199
- package/dist/index.html +1 -1
- package/package.json +2 -1
- package/shared/utils/ws-client.ts +188 -38
- package/backend/tunnel/cloudflared/binary.ts +0 -171
- package/backend/tunnel/cloudflared/index.ts +0 -24
- package/backend/tunnel/cloudflared/tunnel.ts +0 -444
- package/backend/tunnel/global-tunnel-manager.ts +0 -687
- package/backend/tunnel/project-tunnel-manager.ts +0 -264
|
@@ -1,687 +0,0 @@
|
|
|
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
|
-
|
|
10
|
-
import { debug } from '$shared/utils/logger';
|
|
11
|
-
import { existsSync, mkdirSync, renameSync, writeFileSync, unlinkSync, rmSync } from 'fs';
|
|
12
|
-
import { homedir } from 'os';
|
|
13
|
-
import { join } from 'path';
|
|
14
|
-
import { getTunnelDir, getLocalTunnelConfigs } from './tunnel-config';
|
|
15
|
-
import type { RemoteTunnelConfig, LocalTunnelConfig } from './tunnel-config';
|
|
16
|
-
import { resolveCloudflaredBinary, CloudflaredTunnel, CloudflaredMissingError, type LoginHandle } from './cloudflared';
|
|
17
|
-
|
|
18
|
-
// --- Types ---
|
|
19
|
-
|
|
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';
|
|
35
|
-
publicUrl: string;
|
|
36
|
-
localPort: number;
|
|
37
|
-
autoStopMinutes: number;
|
|
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[];
|
|
53
|
-
}
|
|
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
|
-
function isTunnelNameConflict(error: unknown): boolean {
|
|
61
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
62
|
-
return /tunnel with name already exists/i.test(message);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// --- Manager ---
|
|
66
|
-
|
|
67
|
-
class GlobalTunnelManager {
|
|
68
|
-
private quickTunnels = new Map<number, QuickTunnelInstance>();
|
|
69
|
-
private remoteTunnels = new Map<string, RemoteTunnelInstance>();
|
|
70
|
-
private localTunnels = new Map<string, LocalTunnelInstance>();
|
|
71
|
-
private loginHandle: LoginHandle | null = null;
|
|
72
|
-
|
|
73
|
-
// Callback for pushing ingress updates to connected clients
|
|
74
|
-
private onRemoteIngressUpdate?: (configId: string, ingress: IngressInfo[]) => void;
|
|
75
|
-
// Callback for pushing tunnel list changes
|
|
76
|
-
private onStatusChanged?: () => void;
|
|
77
|
-
|
|
78
|
-
setRemoteIngressUpdateCallback(cb: (configId: string, ingress: IngressInfo[]) => void): void {
|
|
79
|
-
this.onRemoteIngressUpdate = cb;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
setStatusChangedCallback(cb: () => void): void {
|
|
83
|
-
this.onStatusChanged = cb;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
private notifyStatusChanged(): void {
|
|
87
|
-
this.onStatusChanged?.();
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// --- Binary management ---
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Verify cloudflared is available before a tunnel operation. Never
|
|
94
|
-
* downloads — installation is user-initiated through Settings → System
|
|
95
|
-
* Tools. Throws CloudflaredMissingError when nothing is resolvable.
|
|
96
|
-
*/
|
|
97
|
-
private ensureBinaryAvailable(
|
|
98
|
-
onProgress?: (stage: string, data?: any) => void
|
|
99
|
-
): void {
|
|
100
|
-
const resolved = resolveCloudflaredBinary();
|
|
101
|
-
if (!resolved) {
|
|
102
|
-
debug.warn('tunnel', 'Cloudflared binary not available; install via Settings → System Tools');
|
|
103
|
-
throw new CloudflaredMissingError();
|
|
104
|
-
}
|
|
105
|
-
debug.log('tunnel', 'Cloudflared binary available at:', resolved);
|
|
106
|
-
onProgress?.('binary-ready', { cached: true });
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// --- Quick tunnel ---
|
|
110
|
-
|
|
111
|
-
async startQuickTunnel(
|
|
112
|
-
port: number,
|
|
113
|
-
autoStopMinutes: number = 60,
|
|
114
|
-
onProgress?: (stage: string, data?: any) => void
|
|
115
|
-
): Promise<{ publicUrl: string; timings: Record<string, number> }> {
|
|
116
|
-
onProgress?.('checking-binary');
|
|
117
|
-
this.ensureBinaryAvailable(onProgress);
|
|
118
|
-
const timings: Record<string, number> = {};
|
|
119
|
-
|
|
120
|
-
if (this.quickTunnels.has(port)) {
|
|
121
|
-
const existing = this.quickTunnels.get(port)!;
|
|
122
|
-
return { publicUrl: existing.publicUrl, timings };
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
onProgress?.('starting-tunnel', { port });
|
|
126
|
-
const tunnelStartTime = Date.now();
|
|
127
|
-
|
|
128
|
-
try {
|
|
129
|
-
const tunnel = CloudflaredTunnel.quick(`http://localhost:${port}`);
|
|
130
|
-
|
|
131
|
-
tunnel.on('error', (error: Error) => debug.error('tunnel', `[quick:${port}] error:`, error));
|
|
132
|
-
tunnel.on('exit', (code: number | null) => {
|
|
133
|
-
debug.log('tunnel', `[quick:${port}] exit code ${code}`);
|
|
134
|
-
this.quickTunnels.delete(port);
|
|
135
|
-
this.notifyStatusChanged();
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
onProgress?.('generating-url');
|
|
139
|
-
|
|
140
|
-
const publicUrl: string = await new Promise((resolve, reject) => {
|
|
141
|
-
const timeout = setTimeout(() => {
|
|
142
|
-
tunnel.stop();
|
|
143
|
-
reject(new Error(`Tunnel connection timeout (30s). Please check if port ${port} is accessible.`));
|
|
144
|
-
}, 30000);
|
|
145
|
-
|
|
146
|
-
tunnel.on('url', (url: string) => {
|
|
147
|
-
if (url.includes('api.trycloudflare.com')) return;
|
|
148
|
-
clearTimeout(timeout);
|
|
149
|
-
resolve(url);
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
tunnel.on('error', (error: Error) => {
|
|
153
|
-
clearTimeout(timeout);
|
|
154
|
-
reject(error);
|
|
155
|
-
});
|
|
156
|
-
|
|
157
|
-
tunnel.once('exit', (code: number | null) => {
|
|
158
|
-
if (code !== 0 && code !== null) {
|
|
159
|
-
clearTimeout(timeout);
|
|
160
|
-
reject(new Error(`Tunnel failed to start (exit code ${code}).`));
|
|
161
|
-
}
|
|
162
|
-
});
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
timings.tunnelStart = Date.now() - tunnelStartTime;
|
|
166
|
-
|
|
167
|
-
let autoStopTimer: ReturnType<typeof setTimeout> | undefined;
|
|
168
|
-
if (autoStopMinutes > 0) {
|
|
169
|
-
autoStopTimer = setTimeout(async () => {
|
|
170
|
-
debug.log('tunnel', `Auto-stopping quick tunnel on port ${port}`);
|
|
171
|
-
await this.stopQuickTunnel(port);
|
|
172
|
-
}, autoStopMinutes * 60 * 1000);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
this.quickTunnels.set(port, {
|
|
176
|
-
tunnel,
|
|
177
|
-
publicUrl,
|
|
178
|
-
localPort: port,
|
|
179
|
-
type: 'quick',
|
|
180
|
-
startedAt: new Date(),
|
|
181
|
-
autoStopMinutes,
|
|
182
|
-
autoStopTimer
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
debug.log('tunnel', `Quick tunnel started on port ${port}: ${publicUrl}`);
|
|
186
|
-
onProgress?.('connected', { publicUrl, timings });
|
|
187
|
-
this.notifyStatusChanged();
|
|
188
|
-
|
|
189
|
-
return { publicUrl, timings };
|
|
190
|
-
} catch (error) {
|
|
191
|
-
debug.error('tunnel', `Failed to start quick tunnel on port ${port}:`, error);
|
|
192
|
-
throw error;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
async stopQuickTunnel(port: number): Promise<void> {
|
|
197
|
-
const instance = this.quickTunnels.get(port);
|
|
198
|
-
if (!instance) return;
|
|
199
|
-
|
|
200
|
-
if (instance.autoStopTimer) clearTimeout(instance.autoStopTimer);
|
|
201
|
-
try {
|
|
202
|
-
instance.tunnel.stop();
|
|
203
|
-
} catch (err) {
|
|
204
|
-
debug.warn('tunnel', `Failed to stop quick tunnel on port ${port}:`, err);
|
|
205
|
-
}
|
|
206
|
-
this.quickTunnels.delete(port);
|
|
207
|
-
debug.log('tunnel', `Quick tunnel stopped on port ${port}`);
|
|
208
|
-
this.notifyStatusChanged();
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
// --- Remote tunnel (dashboard-managed) ---
|
|
212
|
-
|
|
213
|
-
async startRemoteTunnel(
|
|
214
|
-
config: RemoteTunnelConfig,
|
|
215
|
-
onProgress?: (stage: string, data?: any) => void
|
|
216
|
-
): Promise<{ timings: Record<string, number> }> {
|
|
217
|
-
onProgress?.('checking-binary');
|
|
218
|
-
this.ensureBinaryAvailable(onProgress);
|
|
219
|
-
const timings: Record<string, number> = {};
|
|
220
|
-
|
|
221
|
-
if (this.remoteTunnels.has(config.id)) {
|
|
222
|
-
return { timings };
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
onProgress?.('starting-tunnel', { label: config.label });
|
|
226
|
-
const tunnelStartTime = Date.now();
|
|
227
|
-
|
|
228
|
-
try {
|
|
229
|
-
const tunnel = CloudflaredTunnel.withToken(config.token);
|
|
230
|
-
|
|
231
|
-
const instance: RemoteTunnelInstance = {
|
|
232
|
-
tunnel,
|
|
233
|
-
type: 'remote',
|
|
234
|
-
configId: config.id,
|
|
235
|
-
label: config.label,
|
|
236
|
-
startedAt: new Date(),
|
|
237
|
-
ingress: []
|
|
238
|
-
};
|
|
239
|
-
|
|
240
|
-
// Sync ingress from config events (emitted by the tunnel's built-in config handler)
|
|
241
|
-
tunnel.on('config', (data: { config: any; version: number }) => {
|
|
242
|
-
if (data.config?.ingress && Array.isArray(data.config.ingress)) {
|
|
243
|
-
instance.ingress = data.config.ingress.map((rule: any) => ({
|
|
244
|
-
hostname: rule.hostname,
|
|
245
|
-
service: rule.service
|
|
246
|
-
}));
|
|
247
|
-
debug.log('tunnel', `[remote:${config.label}] Config synced, ${instance.ingress.length} ingress rules`);
|
|
248
|
-
this.onRemoteIngressUpdate?.(config.id, instance.ingress);
|
|
249
|
-
}
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
tunnel.on('error', (error: Error) => debug.error('tunnel', `[remote:${config.label}] error:`, error));
|
|
253
|
-
tunnel.on('exit', (code: number | null) => {
|
|
254
|
-
debug.log('tunnel', `[remote:${config.label}] exit code ${code}`);
|
|
255
|
-
this.remoteTunnels.delete(config.id);
|
|
256
|
-
this.notifyStatusChanged();
|
|
257
|
-
});
|
|
258
|
-
|
|
259
|
-
onProgress?.('generating-url');
|
|
260
|
-
|
|
261
|
-
// Wait for first connection
|
|
262
|
-
await new Promise<void>((resolve, reject) => {
|
|
263
|
-
const timeout = setTimeout(() => {
|
|
264
|
-
tunnel.stop();
|
|
265
|
-
reject(new Error('Remote tunnel connection timeout (60s). Please check your token.'));
|
|
266
|
-
}, 60000);
|
|
267
|
-
|
|
268
|
-
tunnel.once('connected', () => {
|
|
269
|
-
clearTimeout(timeout);
|
|
270
|
-
resolve();
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
tunnel.once('error', (error: Error) => {
|
|
274
|
-
clearTimeout(timeout);
|
|
275
|
-
tunnel.stop();
|
|
276
|
-
reject(error);
|
|
277
|
-
});
|
|
278
|
-
|
|
279
|
-
tunnel.once('exit', (code: number | null) => {
|
|
280
|
-
if (code !== 0 && code !== null) {
|
|
281
|
-
clearTimeout(timeout);
|
|
282
|
-
reject(new Error(`Remote tunnel failed (exit code ${code}). Please verify your token.`));
|
|
283
|
-
}
|
|
284
|
-
});
|
|
285
|
-
});
|
|
286
|
-
|
|
287
|
-
timings.tunnelStart = Date.now() - tunnelStartTime;
|
|
288
|
-
this.remoteTunnels.set(config.id, instance);
|
|
289
|
-
|
|
290
|
-
debug.log('tunnel', `Remote tunnel started: ${config.label}`);
|
|
291
|
-
onProgress?.('connected', { timings });
|
|
292
|
-
this.notifyStatusChanged();
|
|
293
|
-
|
|
294
|
-
return { timings };
|
|
295
|
-
} catch (error) {
|
|
296
|
-
debug.error('tunnel', `Failed to start remote tunnel ${config.label}:`, error);
|
|
297
|
-
throw error;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
async stopRemoteTunnel(configId: string): Promise<void> {
|
|
302
|
-
const instance = this.remoteTunnels.get(configId);
|
|
303
|
-
if (!instance) return;
|
|
304
|
-
|
|
305
|
-
try {
|
|
306
|
-
instance.tunnel.stop();
|
|
307
|
-
} catch (err) {
|
|
308
|
-
debug.warn('tunnel', `Failed to stop remote tunnel ${instance.label}:`, err);
|
|
309
|
-
}
|
|
310
|
-
this.remoteTunnels.delete(configId);
|
|
311
|
-
debug.log('tunnel', `Remote tunnel stopped: ${instance.label}`);
|
|
312
|
-
this.notifyStatusChanged();
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
getRemoteTunnelIngress(configId: string): IngressInfo[] {
|
|
316
|
-
return this.remoteTunnels.get(configId)?.ingress ?? [];
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
isRemoteTunnelActive(configId: string): boolean {
|
|
320
|
-
return this.remoteTunnels.has(configId);
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
// --- Local tunnel (locally-managed) ---
|
|
324
|
-
|
|
325
|
-
checkCloudflaredAuth(): { authenticated: boolean; certPath: string } {
|
|
326
|
-
// Migrate cert from default cloudflared location if it exists there but not in our dir
|
|
327
|
-
if (!existsSync(CERT_PATH) && existsSync(DEFAULT_CLOUDFLARED_CERT)) {
|
|
328
|
-
this.moveCertToTunnelDir();
|
|
329
|
-
}
|
|
330
|
-
const authenticated = existsSync(CERT_PATH);
|
|
331
|
-
return { authenticated, certPath: CERT_PATH };
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
async loginCloudflared(
|
|
335
|
-
onUrl?: (url: string) => void,
|
|
336
|
-
onComplete?: () => void,
|
|
337
|
-
onError?: (error: string) => void
|
|
338
|
-
): Promise<void> {
|
|
339
|
-
this.ensureBinaryAvailable();
|
|
340
|
-
|
|
341
|
-
if (this.loginHandle) {
|
|
342
|
-
onError?.('Login process already running');
|
|
343
|
-
return;
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
debug.log('tunnel', 'Starting cloudflared login...');
|
|
347
|
-
|
|
348
|
-
this.loginHandle = CloudflaredTunnel.login({
|
|
349
|
-
onUrl: (url) => {
|
|
350
|
-
debug.log('tunnel', `[login] Auth URL: ${url}`);
|
|
351
|
-
onUrl?.(url);
|
|
352
|
-
},
|
|
353
|
-
onComplete: () => {
|
|
354
|
-
this.loginHandle = null;
|
|
355
|
-
// Move cert.pem from ~/.cloudflared/ to our tunnel dir
|
|
356
|
-
this.moveCertToTunnelDir();
|
|
357
|
-
debug.log('tunnel', 'Cloudflared login successful');
|
|
358
|
-
onComplete?.();
|
|
359
|
-
},
|
|
360
|
-
onError: (message) => {
|
|
361
|
-
this.loginHandle = null;
|
|
362
|
-
debug.error('tunnel', `Cloudflared login failed: ${message}`);
|
|
363
|
-
onError?.(message);
|
|
364
|
-
}
|
|
365
|
-
});
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
private moveCertToTunnelDir(): void {
|
|
369
|
-
if (existsSync(DEFAULT_CLOUDFLARED_CERT)) {
|
|
370
|
-
const tunnelDir = getTunnelDir();
|
|
371
|
-
if (!existsSync(tunnelDir)) {
|
|
372
|
-
mkdirSync(tunnelDir, { recursive: true });
|
|
373
|
-
}
|
|
374
|
-
renameSync(DEFAULT_CLOUDFLARED_CERT, CERT_PATH);
|
|
375
|
-
debug.log('tunnel', `Cert moved: ${DEFAULT_CLOUDFLARED_CERT} -> ${CERT_PATH}`);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
cancelLogin(): void {
|
|
380
|
-
if (this.loginHandle) {
|
|
381
|
-
debug.log('tunnel', 'Cloudflared login cancelled by user');
|
|
382
|
-
this.loginHandle.cancel();
|
|
383
|
-
this.loginHandle = null;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
logoutCloudflared(): { success: boolean } {
|
|
388
|
-
try {
|
|
389
|
-
if (existsSync(CERT_PATH)) {
|
|
390
|
-
unlinkSync(CERT_PATH);
|
|
391
|
-
debug.log('tunnel', 'Cloudflared cert.pem removed (logged out)');
|
|
392
|
-
}
|
|
393
|
-
return { success: true };
|
|
394
|
-
} catch (error) {
|
|
395
|
-
debug.error('tunnel', 'Failed to remove cert.pem:', error);
|
|
396
|
-
return { success: false };
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
async createLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
|
|
401
|
-
this.ensureBinaryAvailable();
|
|
402
|
-
|
|
403
|
-
try {
|
|
404
|
-
return await this.runCreateLocalTunnel(name);
|
|
405
|
-
} catch (error) {
|
|
406
|
-
if (!isTunnelNameConflict(error)) throw error;
|
|
407
|
-
|
|
408
|
-
// Name collides on Cloudflare. Auto-recover only when it's a true orphan,
|
|
409
|
-
// then retry once. Anything else surfaces a clear, actionable message.
|
|
410
|
-
await this.resolveTunnelNameConflict(name);
|
|
411
|
-
return await this.runCreateLocalTunnel(name);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
private async runCreateLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
|
|
416
|
-
// Write credentials directly to our dir (not ~/.cloudflared/)
|
|
417
|
-
const tunnelBaseDir = getTunnelDir();
|
|
418
|
-
if (!existsSync(tunnelBaseDir)) {
|
|
419
|
-
mkdirSync(tunnelBaseDir, { recursive: true });
|
|
420
|
-
}
|
|
421
|
-
const tempCredentials = join(tunnelBaseDir, `${name}.json`);
|
|
422
|
-
const result = await CloudflaredTunnel.createTunnel(name, { credentialsFile: tempCredentials, origincert: CERT_PATH });
|
|
423
|
-
|
|
424
|
-
// Organize into {tunnelId}/ subdirectory
|
|
425
|
-
const tunnelDir = join(tunnelBaseDir, result.tunnelId);
|
|
426
|
-
if (!existsSync(tunnelDir)) {
|
|
427
|
-
mkdirSync(tunnelDir, { recursive: true });
|
|
428
|
-
}
|
|
429
|
-
const finalCredentials = join(tunnelDir, 'credentials.json');
|
|
430
|
-
renameSync(tempCredentials, finalCredentials);
|
|
431
|
-
|
|
432
|
-
debug.log('tunnel', `Local tunnel created: ${name} (${result.tunnelId})`);
|
|
433
|
-
return { tunnelId: result.tunnelId, credentialsFile: finalCredentials };
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
/**
|
|
437
|
-
* Handle a "tunnel with name already exists" conflict. A tunnel that exists on
|
|
438
|
-
* Cloudflare but isn't tracked locally and has no active connections is an orphan
|
|
439
|
-
* (usually a half-failed create) and is safe to delete so the create can retry.
|
|
440
|
-
* Everything else throws a clear message instead.
|
|
441
|
-
*/
|
|
442
|
-
private async resolveTunnelNameConflict(name: string): Promise<void> {
|
|
443
|
-
let existing;
|
|
444
|
-
try {
|
|
445
|
-
existing = await CloudflaredTunnel.listTunnels({ origincert: CERT_PATH });
|
|
446
|
-
} catch (listError) {
|
|
447
|
-
debug.warn('tunnel', 'Could not list tunnels to resolve name conflict:', listError);
|
|
448
|
-
throw new Error(`A Cloudflare tunnel named "${name}" already exists on your account. Choose a different name, or remove it from the Cloudflare dashboard.`);
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const match = existing.find((t) => t.name === name);
|
|
452
|
-
if (!match) {
|
|
453
|
-
throw new Error(`A Cloudflare tunnel named "${name}" already exists on your account. Choose a different name, or remove it from the Cloudflare dashboard.`);
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
if (getLocalTunnelConfigs().some((c) => c.tunnelId === match.id)) {
|
|
457
|
-
throw new Error(`A tunnel named "${name}" already exists. Choose a different name, or delete the existing tunnel first.`);
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
if (match.connections.length > 0) {
|
|
461
|
-
throw new Error(`A Cloudflare tunnel named "${name}" already exists and has active connections. Choose a different name, or remove it from the Cloudflare dashboard.`);
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
debug.warn('tunnel', `Orphaned tunnel "${name}" (${match.id}) found on Cloudflare; deleting before recreate`);
|
|
465
|
-
await CloudflaredTunnel.deleteTunnel(match.id, { force: true, origincert: CERT_PATH });
|
|
466
|
-
this.cleanupLocalTunnelFiles(match.id);
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
async deleteLocalTunnel(tunnelId: string, credentialsFile?: string): Promise<void> {
|
|
470
|
-
this.ensureBinaryAvailable();
|
|
471
|
-
|
|
472
|
-
await CloudflaredTunnel.deleteTunnel(tunnelId, { credentialsFile, origincert: CERT_PATH });
|
|
473
|
-
debug.log('tunnel', `Local tunnel deleted: ${tunnelId}`);
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
cleanupLocalTunnelFiles(tunnelId: string): void {
|
|
477
|
-
const configDir = join(getTunnelDir(), tunnelId);
|
|
478
|
-
if (existsSync(configDir)) {
|
|
479
|
-
rmSync(configDir, { recursive: true });
|
|
480
|
-
debug.log('tunnel', `Tunnel config directory removed: ${configDir}`);
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
async routeDns(tunnelName: string, hostname: string): Promise<{ alreadyExists: boolean }> {
|
|
485
|
-
this.ensureBinaryAvailable();
|
|
486
|
-
|
|
487
|
-
const result = await CloudflaredTunnel.routeDns(tunnelName, hostname, { overwriteDns: true, origincert: CERT_PATH });
|
|
488
|
-
debug.log('tunnel', `DNS route ${result.alreadyExists ? 'updated' : 'added'}: ${hostname} -> ${tunnelName}`);
|
|
489
|
-
return result;
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
writeLocalTunnelConfig(config: LocalTunnelConfig): string {
|
|
493
|
-
const configDir = join(getTunnelDir(), config.tunnelId);
|
|
494
|
-
if (!existsSync(configDir)) {
|
|
495
|
-
mkdirSync(configDir, { recursive: true });
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
const configPath = join(configDir, 'config.yml');
|
|
499
|
-
|
|
500
|
-
const ingressRules = [
|
|
501
|
-
...config.ingress.map((r) => ` - hostname: ${r.hostname}\n service: ${r.service}`),
|
|
502
|
-
' - service: http_status:404'
|
|
503
|
-
];
|
|
504
|
-
|
|
505
|
-
const yml = [
|
|
506
|
-
`tunnel: ${config.tunnelId}`,
|
|
507
|
-
`credentials-file: ${config.credentialsFile}`,
|
|
508
|
-
'ingress:',
|
|
509
|
-
...ingressRules
|
|
510
|
-
].join('\n');
|
|
511
|
-
|
|
512
|
-
writeFileSync(configPath, yml, 'utf-8');
|
|
513
|
-
debug.log('tunnel', `Config file written: ${configPath}`);
|
|
514
|
-
return configPath;
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
async startLocalTunnel(
|
|
518
|
-
config: LocalTunnelConfig,
|
|
519
|
-
onProgress?: (stage: string, data?: any) => void
|
|
520
|
-
): Promise<{ timings: Record<string, number> }> {
|
|
521
|
-
onProgress?.('checking-binary');
|
|
522
|
-
this.ensureBinaryAvailable(onProgress);
|
|
523
|
-
const timings: Record<string, number> = {};
|
|
524
|
-
|
|
525
|
-
if (this.localTunnels.has(config.id)) {
|
|
526
|
-
return { timings };
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
if (config.ingress.length === 0) {
|
|
530
|
-
throw new Error('Cannot start tunnel without ingress rules. Add at least one hostname mapping.');
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// Write config file
|
|
534
|
-
const configPath = this.writeLocalTunnelConfig(config);
|
|
535
|
-
|
|
536
|
-
onProgress?.('starting-tunnel', { name: config.name });
|
|
537
|
-
const tunnelStartTime = Date.now();
|
|
538
|
-
|
|
539
|
-
try {
|
|
540
|
-
const tunnel = CloudflaredTunnel.withConfig(configPath);
|
|
541
|
-
|
|
542
|
-
tunnel.on('error', (error: Error) => debug.error('tunnel', `[local:${config.name}] error:`, error));
|
|
543
|
-
tunnel.on('exit', (code: number | null) => {
|
|
544
|
-
debug.log('tunnel', `[local:${config.name}] exit code ${code}`);
|
|
545
|
-
this.localTunnels.delete(config.id);
|
|
546
|
-
this.notifyStatusChanged();
|
|
547
|
-
});
|
|
548
|
-
|
|
549
|
-
onProgress?.('generating-url');
|
|
550
|
-
|
|
551
|
-
// Wait for first connection
|
|
552
|
-
await new Promise<void>((resolve, reject) => {
|
|
553
|
-
const timeout = setTimeout(() => {
|
|
554
|
-
tunnel.stop();
|
|
555
|
-
reject(new Error('Local tunnel connection timeout (60s). Check your config and credentials.'));
|
|
556
|
-
}, 60000);
|
|
557
|
-
|
|
558
|
-
tunnel.once('connected', () => {
|
|
559
|
-
clearTimeout(timeout);
|
|
560
|
-
resolve();
|
|
561
|
-
});
|
|
562
|
-
|
|
563
|
-
tunnel.once('error', (error: Error) => {
|
|
564
|
-
clearTimeout(timeout);
|
|
565
|
-
tunnel.stop();
|
|
566
|
-
reject(error);
|
|
567
|
-
});
|
|
568
|
-
|
|
569
|
-
tunnel.once('exit', (code: number | null) => {
|
|
570
|
-
if (code !== 0 && code !== null) {
|
|
571
|
-
clearTimeout(timeout);
|
|
572
|
-
reject(new Error(`Local tunnel failed (exit code ${code}).`));
|
|
573
|
-
}
|
|
574
|
-
});
|
|
575
|
-
});
|
|
576
|
-
|
|
577
|
-
timings.tunnelStart = Date.now() - tunnelStartTime;
|
|
578
|
-
|
|
579
|
-
const instance: LocalTunnelInstance = {
|
|
580
|
-
tunnel,
|
|
581
|
-
type: 'local',
|
|
582
|
-
configId: config.id,
|
|
583
|
-
name: config.name,
|
|
584
|
-
startedAt: new Date(),
|
|
585
|
-
ingress: config.ingress.map((r) => ({ hostname: r.hostname, service: r.service }))
|
|
586
|
-
};
|
|
587
|
-
|
|
588
|
-
this.localTunnels.set(config.id, instance);
|
|
589
|
-
debug.log('tunnel', `Local tunnel started: ${config.name}`);
|
|
590
|
-
onProgress?.('connected', { timings });
|
|
591
|
-
this.notifyStatusChanged();
|
|
592
|
-
|
|
593
|
-
return { timings };
|
|
594
|
-
} catch (error) {
|
|
595
|
-
debug.error('tunnel', `Failed to start local tunnel ${config.name}:`, error);
|
|
596
|
-
throw error;
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
async stopLocalTunnel(configId: string): Promise<void> {
|
|
601
|
-
const instance = this.localTunnels.get(configId);
|
|
602
|
-
if (!instance) return;
|
|
603
|
-
|
|
604
|
-
try {
|
|
605
|
-
instance.tunnel.stop();
|
|
606
|
-
} catch (err) {
|
|
607
|
-
debug.warn('tunnel', `Failed to stop local tunnel ${instance.name}:`, err);
|
|
608
|
-
}
|
|
609
|
-
this.localTunnels.delete(configId);
|
|
610
|
-
debug.log('tunnel', `Local tunnel stopped: ${instance.name}`);
|
|
611
|
-
this.notifyStatusChanged();
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
isLocalTunnelActive(configId: string): boolean {
|
|
615
|
-
return this.localTunnels.has(configId);
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
// --- Status / global ---
|
|
619
|
-
|
|
620
|
-
getActiveTunnels(): Array<{
|
|
621
|
-
port: number;
|
|
622
|
-
publicUrl: string;
|
|
623
|
-
startedAt: string;
|
|
624
|
-
autoStopMinutes: number;
|
|
625
|
-
type: TunnelType;
|
|
626
|
-
label?: string;
|
|
627
|
-
configId?: string;
|
|
628
|
-
ingress?: IngressInfo[];
|
|
629
|
-
}> {
|
|
630
|
-
const tunnels: ReturnType<typeof this.getActiveTunnels> = [];
|
|
631
|
-
|
|
632
|
-
for (const [port, instance] of this.quickTunnels) {
|
|
633
|
-
tunnels.push({
|
|
634
|
-
port,
|
|
635
|
-
publicUrl: instance.publicUrl,
|
|
636
|
-
startedAt: instance.startedAt.toISOString(),
|
|
637
|
-
autoStopMinutes: instance.autoStopMinutes,
|
|
638
|
-
type: 'quick'
|
|
639
|
-
});
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
for (const [, instance] of this.remoteTunnels) {
|
|
643
|
-
const firstHostname = instance.ingress.find((r) => r.hostname)?.hostname;
|
|
644
|
-
tunnels.push({
|
|
645
|
-
port: 0,
|
|
646
|
-
publicUrl: firstHostname ? `https://${firstHostname}` : '',
|
|
647
|
-
startedAt: instance.startedAt.toISOString(),
|
|
648
|
-
autoStopMinutes: 0,
|
|
649
|
-
type: 'remote',
|
|
650
|
-
label: instance.label,
|
|
651
|
-
configId: instance.configId,
|
|
652
|
-
ingress: instance.ingress
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
for (const [, instance] of this.localTunnels) {
|
|
657
|
-
const firstHostname = instance.ingress.find((r) => r.hostname)?.hostname;
|
|
658
|
-
tunnels.push({
|
|
659
|
-
port: 0,
|
|
660
|
-
publicUrl: firstHostname ? `https://${firstHostname}` : '',
|
|
661
|
-
startedAt: instance.startedAt.toISOString(),
|
|
662
|
-
autoStopMinutes: 0,
|
|
663
|
-
type: 'local',
|
|
664
|
-
label: instance.name,
|
|
665
|
-
configId: instance.configId,
|
|
666
|
-
ingress: instance.ingress
|
|
667
|
-
});
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
return tunnels;
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
async stopAllTunnels(): Promise<void> {
|
|
674
|
-
debug.log('tunnel', 'Stopping all tunnels...');
|
|
675
|
-
|
|
676
|
-
const ops: Promise<void>[] = [];
|
|
677
|
-
for (const port of this.quickTunnels.keys()) ops.push(this.stopQuickTunnel(port));
|
|
678
|
-
for (const id of this.remoteTunnels.keys()) ops.push(this.stopRemoteTunnel(id));
|
|
679
|
-
for (const id of this.localTunnels.keys()) ops.push(this.stopLocalTunnel(id));
|
|
680
|
-
|
|
681
|
-
await Promise.all(ops);
|
|
682
|
-
debug.log('tunnel', 'All tunnels stopped');
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
// Singleton
|
|
687
|
-
export const globalTunnelManager = new GlobalTunnelManager();
|