@myrialabs/clopen 0.3.6 → 0.3.8

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.
Files changed (54) hide show
  1. package/README.md +4 -4
  2. package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
  3. package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
  4. package/backend/database/migrations/index.ts +14 -0
  5. package/backend/database/queries/db-client-connection-queries.ts +237 -0
  6. package/backend/database/queries/db-client-query-history-queries.ts +113 -0
  7. package/backend/database/queries/index.ts +3 -1
  8. package/backend/database/queries/project-queries.ts +23 -0
  9. package/backend/db-client/connection-manager.ts +257 -0
  10. package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
  11. package/backend/db-client/drivers/mongodb.ts +358 -0
  12. package/backend/db-client/drivers/mysql.ts +385 -0
  13. package/backend/db-client/drivers/postgres.ts +446 -0
  14. package/backend/db-client/drivers/redis.ts +267 -0
  15. package/backend/db-client/drivers/sql-builders.ts +215 -0
  16. package/backend/db-client/drivers/sqlite.ts +346 -0
  17. package/backend/db-client/drivers/types.ts +92 -0
  18. package/backend/db-client/query-executor.ts +126 -0
  19. package/backend/db-client/ssh-tunnel.ts +122 -0
  20. package/backend/engine/install-recipes.ts +216 -137
  21. package/backend/engine/install-runner.ts +39 -0
  22. package/backend/git/git-service.ts +12 -0
  23. package/backend/mcp/servers/browser-automation/index.ts +6 -6
  24. package/backend/preview/browser/browser-pool.ts +10 -9
  25. package/backend/preview/browser/scripts/video-stream.ts +9 -3
  26. package/backend/tunnel/cloudflared/binary.ts +22 -4
  27. package/backend/tunnel/cloudflared/index.ts +2 -1
  28. package/backend/tunnel/cloudflared/tunnel.ts +17 -4
  29. package/backend/tunnel/global-tunnel-manager.ts +29 -51
  30. package/backend/tunnel/project-tunnel-manager.ts +14 -53
  31. package/backend/ws/db-client/connections.ts +180 -0
  32. package/backend/ws/db-client/index.ts +17 -0
  33. package/backend/ws/db-client/io.ts +458 -0
  34. package/backend/ws/db-client/query.ts +162 -0
  35. package/backend/ws/db-client/schema.ts +76 -0
  36. package/backend/ws/db-client/structure.ts +218 -0
  37. package/backend/ws/files/index.ts +5 -1
  38. package/backend/ws/files/read.ts +32 -0
  39. package/backend/ws/files/state.ts +39 -0
  40. package/backend/ws/index.ts +6 -2
  41. package/backend/ws/system-tools/install.ts +2 -1
  42. package/backend/ws/system-tools/status.ts +5 -4
  43. package/dist/assets/{index-BU8wB4Fg.js → index-DqAGCTFT.js} +2 -2
  44. package/dist/assets/{main-cQx6vfxB.js → main-DsED0rLr.js} +244 -192
  45. package/dist/assets/main-eWY9R8g9.css +1 -0
  46. package/dist/index.html +2 -2
  47. package/package.json +4 -2
  48. package/shared/constants/preview.ts +48 -4
  49. package/shared/types/database/schema.ts +48 -1
  50. package/shared/types/db-client/connection.ts +60 -0
  51. package/shared/types/db-client/index.ts +6 -0
  52. package/shared/types/db-client/query.ts +77 -0
  53. package/shared/utils/logger.ts +1 -0
  54. package/dist/assets/main-B3tMwjjU.css +0 -1
@@ -19,7 +19,7 @@ import type { Browser, BrowserContext, Page } from 'puppeteer';
19
19
  import { debug } from '$shared/utils/logger';
20
20
  import puppeteer from 'puppeteer-extra';
21
21
  import StealthPlugin from 'puppeteer-extra-plugin-stealth';
22
- import { getChromiumExecutablePath } from '$backend/engine/install-recipes';
22
+ import { getChromeExecutablePath } from '$backend/engine/install-recipes';
23
23
 
24
24
  puppeteer.use(StealthPlugin());
25
25
 
@@ -45,9 +45,9 @@ const DEFAULT_CONFIG: PoolConfig = {
45
45
  };
46
46
 
47
47
  /**
48
- * Chromium launch arguments for stealth (matches test-cf.ts exactly)
48
+ * Chrome launch arguments for stealth (matches test-cf.ts exactly)
49
49
  */
50
- const CHROMIUM_ARGS = [
50
+ const CHROME_ARGS = [
51
51
  '--no-sandbox',
52
52
  '--disable-blink-features=AutomationControlled',
53
53
  '--window-size=1366,768',
@@ -99,18 +99,19 @@ class BrowserPool {
99
99
  private async launchBrowser(): Promise<Browser> {
100
100
  debug.log('preview', '🚀 Launching browser with puppeteer-extra + StealthPlugin...');
101
101
 
102
- // Use the clopen-managed Chromium under ~/.clopen/bin (macOS/Windows)
103
- // or the system Chromium installed via the distro package manager (Linux).
104
- const executablePath = getChromiumExecutablePath();
102
+ // Use the clopen-managed Chrome for Testing under ~/.clopen/bin
103
+ // (macOS/Windows) or the system Google Chrome / chromium installed
104
+ // via the distro package manager (Linux).
105
+ const executablePath = getChromeExecutablePath();
105
106
  if (!executablePath) {
106
- throw new Error('Chromium not installed. Go to Settings → System Tools and click Install.');
107
+ throw new Error('Chrome not installed. Go to Settings → System Tools and click Install.');
107
108
  }
108
- debug.log('preview', ` using Chromium at: ${executablePath}`);
109
+ debug.log('preview', ` using Chrome at: ${executablePath}`);
109
110
 
110
111
  const browser = await puppeteer.launch({
111
112
  headless: true,
112
113
  executablePath,
113
- args: CHROMIUM_ARGS
114
+ args: CHROME_ARGS
114
115
  }) as unknown as Browser;
115
116
 
116
117
  debug.log('preview', '✅ Browser launched successfully');
@@ -34,9 +34,15 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
34
34
  let lastCursor = 'default';
35
35
  let cursorCheckInterval: any = null;
36
36
 
37
- // ICE servers - empty for local connections (both peers on same machine)
38
- // STUN servers are unnecessary for localhost and add 100-500ms ICE gathering latency
39
- const iceServers: { urls: string }[] = [];
37
+ // Public STUN lets the headless browser discover its public IP via srflx
38
+ // candidates. Required when peers are on different machines/networks
39
+ // (e.g. clopen deployed to Railway/VPS with the client browser elsewhere).
40
+ // Host candidates still resolve first on same-machine setups, so the
41
+ // happy path is not slowed.
42
+ const iceServers: { urls: string }[] = [
43
+ { urls: 'stun:stun.l.google.com:19302' },
44
+ { urls: 'stun:stun1.l.google.com:19302' }
45
+ ];
40
46
 
41
47
  // Create a loopback (127.0.0.1) copy of a host ICE candidate.
42
48
  // Ensures WebRTC connects via loopback when VPN (e.g. Cloudflare WARP)
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * Cloudflared Binary Manager
3
3
  *
4
- * Handles downloading and managing the cloudflared binary.
5
- * Replaces the `cloudflared` npm package for binary management.
4
+ * Handles resolving and managing the cloudflared binary.
6
5
  *
7
- * Binary is stored in ~/.clopen/bin/cloudflared (or .clopen-dev for dev)
8
- * Downloads from GitHub releases: https://github.com/cloudflare/cloudflared/releases
6
+ * Primary install path is ~/.clopen/bin/cloudflared (.clopen-dev in dev), which
7
+ * the System Tools installer downloads from GitHub releases. A system-wide
8
+ * cloudflared (e.g. brew, apt) is also honored via PATH so users who already
9
+ * have it on their machine don't have to install through clopen.
10
+ *
11
+ * installBinary() is kept for programmatic use (CLI, one-off scripts) but
12
+ * the server never auto-downloads — tunnel flows fail with a pointer to
13
+ * Settings → System Tools when the binary is missing.
9
14
  */
10
15
 
11
16
  import { existsSync, mkdirSync, createWriteStream, chmodSync, unlinkSync, renameSync } from 'fs';
@@ -13,6 +18,7 @@ import { join, dirname } from 'path';
13
18
  import { platform, arch } from 'os';
14
19
  import { execSync } from 'child_process';
15
20
  import { getClopenDir } from '../../utils/paths';
21
+ import { resolveBinary } from '../../utils/cli';
16
22
  import { debug } from '$shared/utils/logger';
17
23
 
18
24
  const RELEASE_BASE = 'https://github.com/cloudflare/cloudflared/releases/';
@@ -47,6 +53,18 @@ export function isBinaryInstalled(): boolean {
47
53
  return existsSync(getBinaryPath());
48
54
  }
49
55
 
56
+ /**
57
+ * Resolve an executable cloudflared binary. Prefers the System Tools install
58
+ * under ~/.clopen/bin; falls back to any cloudflared on PATH so users who
59
+ * installed it via brew/apt/winget don't have to reinstall via clopen.
60
+ * Returns null when nothing is found.
61
+ */
62
+ export function resolveCloudflaredBinary(): string | null {
63
+ const managed = getBinaryPath();
64
+ if (existsSync(managed)) return managed;
65
+ return resolveBinary('cloudflared');
66
+ }
67
+
50
68
  /** Download a file via HTTPS, following redirects */
51
69
  function download(url: string, to: string, redirect = 0): Promise<string> {
52
70
  if (redirect > 10) {
@@ -5,9 +5,10 @@
5
5
  * Provides binary management and tunnel process control.
6
6
  */
7
7
 
8
- export { getBinaryPath, isBinaryInstalled, installBinary } from './binary';
8
+ export { getBinaryPath, isBinaryInstalled, installBinary, resolveCloudflaredBinary } from './binary';
9
9
  export {
10
10
  CloudflaredTunnel,
11
+ CloudflaredMissingError,
11
12
  type ConnectionInfo,
12
13
  type LoginHandle,
13
14
  type LoginCallbacks,
@@ -20,7 +20,20 @@ import { EventEmitter } from 'events';
20
20
  import { existsSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
21
21
  import { tmpdir, platform } from 'os';
22
22
  import { join } from 'path';
23
- import { getBinaryPath } from './binary';
23
+ import { resolveCloudflaredBinary } from './binary';
24
+
25
+ export class CloudflaredMissingError extends Error {
26
+ constructor() {
27
+ super('Cloudflared binary is not installed. Install it from Settings → System Tools, or install cloudflared system-wide and restart clopen.');
28
+ this.name = 'CloudflaredMissingError';
29
+ }
30
+ }
31
+
32
+ function requireBinary(): string {
33
+ const resolved = resolveCloudflaredBinary();
34
+ if (!resolved) throw new CloudflaredMissingError();
35
+ return resolved;
36
+ }
24
37
 
25
38
  // --- Output parsing regexes (from cloudflared npm package) ---
26
39
 
@@ -167,7 +180,7 @@ export class CloudflaredTunnel extends EventEmitter {
167
180
  env = { ...process.env, BROWSER: 'false', PATH: `${fakeOpenDir}:${process.env.PATH ?? ''}` };
168
181
  }
169
182
 
170
- const proc = spawn(getBinaryPath(), ['tunnel', 'login'], {
183
+ const proc = spawn(requireBinary(), ['tunnel', 'login'], {
171
184
  stdio: ['ignore', 'pipe', 'pipe'],
172
185
  env
173
186
  });
@@ -280,7 +293,7 @@ export class CloudflaredTunnel extends EventEmitter {
280
293
  /** Run a one-shot cloudflared command and collect all output. */
281
294
  private static run(args: string[]): Promise<{ output: string; exitCode: number }> {
282
295
  return new Promise((resolve, reject) => {
283
- const proc = spawn(getBinaryPath(), args, {
296
+ const proc = spawn(requireBinary(), args, {
284
297
  stdio: ['ignore', 'pipe', 'pipe']
285
298
  });
286
299
 
@@ -360,7 +373,7 @@ export class CloudflaredTunnel extends EventEmitter {
360
373
  }
361
374
 
362
375
  private createProcess(args: string[]): ChildProcess {
363
- const binPath = getBinaryPath();
376
+ const binPath = requireBinary();
364
377
  const child = spawn(binPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
365
378
 
366
379
  child.on('error', (error) => this.emit('error', error));
@@ -13,7 +13,7 @@ import { homedir } from 'os';
13
13
  import { join } from 'path';
14
14
  import { getTunnelDir } from './tunnel-config';
15
15
  import type { RemoteTunnelConfig, LocalTunnelConfig } from './tunnel-config';
16
- import { getBinaryPath, isBinaryInstalled, installBinary, CloudflaredTunnel, type LoginHandle } from './cloudflared';
16
+ import { resolveCloudflaredBinary, CloudflaredTunnel, CloudflaredMissingError, type LoginHandle } from './cloudflared';
17
17
 
18
18
  // --- Types ---
19
19
 
@@ -63,7 +63,6 @@ class GlobalTunnelManager {
63
63
  private quickTunnels = new Map<number, QuickTunnelInstance>();
64
64
  private remoteTunnels = new Map<string, RemoteTunnelInstance>();
65
65
  private localTunnels = new Map<string, LocalTunnelInstance>();
66
- private binaryInstalled = false;
67
66
  private loginHandle: LoginHandle | null = null;
68
67
 
69
68
  // Callback for pushing ingress updates to connected clients
@@ -85,39 +84,21 @@ class GlobalTunnelManager {
85
84
 
86
85
  // --- Binary management ---
87
86
 
88
- private async ensureBinaryInstalled(
87
+ /**
88
+ * Verify cloudflared is available before a tunnel operation. Never
89
+ * downloads — installation is user-initiated through Settings → System
90
+ * Tools. Throws CloudflaredMissingError when nothing is resolvable.
91
+ */
92
+ private ensureBinaryAvailable(
89
93
  onProgress?: (stage: string, data?: any) => void
90
- ): Promise<{ needsDownload: boolean; downloadTime?: number }> {
91
- if (this.binaryInstalled) {
92
- onProgress?.('binary-ready', { cached: true });
93
- return { needsDownload: false };
94
+ ): void {
95
+ const resolved = resolveCloudflaredBinary();
96
+ if (!resolved) {
97
+ debug.warn('tunnel', 'Cloudflared binary not available; install via Settings → System Tools');
98
+ throw new CloudflaredMissingError();
94
99
  }
95
-
96
- if (!isBinaryInstalled()) {
97
- debug.log('tunnel', 'Cloudflared binary not found, downloading...');
98
- onProgress?.('downloading-binary', { size: '~66MB' });
99
-
100
- const startTime = Date.now();
101
- try {
102
- await installBinary();
103
- const downloadTime = Date.now() - startTime;
104
- debug.log('tunnel', `Cloudflared binary installed in ${downloadTime}ms at: ${getBinaryPath()}`);
105
-
106
- this.binaryInstalled = true;
107
- onProgress?.('binary-ready', { downloaded: true, time: downloadTime });
108
- return { needsDownload: true, downloadTime };
109
- } catch (error) {
110
- debug.error('tunnel', 'Failed to install cloudflared binary:', error);
111
- throw new Error(
112
- 'Failed to download cloudflared binary. Please check your internet connection and try again.'
113
- );
114
- }
115
- }
116
-
117
- debug.log('tunnel', 'Cloudflared binary already installed at:', getBinaryPath());
118
- this.binaryInstalled = true;
100
+ debug.log('tunnel', 'Cloudflared binary available at:', resolved);
119
101
  onProgress?.('binary-ready', { cached: true });
120
- return { needsDownload: false };
121
102
  }
122
103
 
123
104
  // --- Quick tunnel ---
@@ -126,15 +107,14 @@ class GlobalTunnelManager {
126
107
  port: number,
127
108
  autoStopMinutes: number = 60,
128
109
  onProgress?: (stage: string, data?: any) => void
129
- ): Promise<{ publicUrl: string; binaryDownloaded: boolean; timings: Record<string, number> }> {
110
+ ): Promise<{ publicUrl: string; timings: Record<string, number> }> {
130
111
  onProgress?.('checking-binary');
131
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
112
+ this.ensureBinaryAvailable(onProgress);
132
113
  const timings: Record<string, number> = {};
133
- if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
134
114
 
135
115
  if (this.quickTunnels.has(port)) {
136
116
  const existing = this.quickTunnels.get(port)!;
137
- return { publicUrl: existing.publicUrl, binaryDownloaded: binaryInfo.needsDownload, timings };
117
+ return { publicUrl: existing.publicUrl, timings };
138
118
  }
139
119
 
140
120
  onProgress?.('starting-tunnel', { port });
@@ -201,7 +181,7 @@ class GlobalTunnelManager {
201
181
  onProgress?.('connected', { publicUrl, timings });
202
182
  this.notifyStatusChanged();
203
183
 
204
- return { publicUrl, binaryDownloaded: binaryInfo.needsDownload, timings };
184
+ return { publicUrl, timings };
205
185
  } catch (error) {
206
186
  debug.error('tunnel', `Failed to start quick tunnel on port ${port}:`, error);
207
187
  throw error;
@@ -226,14 +206,13 @@ class GlobalTunnelManager {
226
206
  async startRemoteTunnel(
227
207
  config: RemoteTunnelConfig,
228
208
  onProgress?: (stage: string, data?: any) => void
229
- ): Promise<{ binaryDownloaded: boolean; timings: Record<string, number> }> {
209
+ ): Promise<{ timings: Record<string, number> }> {
230
210
  onProgress?.('checking-binary');
231
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
211
+ this.ensureBinaryAvailable(onProgress);
232
212
  const timings: Record<string, number> = {};
233
- if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
234
213
 
235
214
  if (this.remoteTunnels.has(config.id)) {
236
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
215
+ return { timings };
237
216
  }
238
217
 
239
218
  onProgress?.('starting-tunnel', { label: config.label });
@@ -305,7 +284,7 @@ class GlobalTunnelManager {
305
284
  onProgress?.('connected', { timings });
306
285
  this.notifyStatusChanged();
307
286
 
308
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
287
+ return { timings };
309
288
  } catch (error) {
310
289
  debug.error('tunnel', `Failed to start remote tunnel ${config.label}:`, error);
311
290
  throw error;
@@ -348,7 +327,7 @@ class GlobalTunnelManager {
348
327
  onComplete?: () => void,
349
328
  onError?: (error: string) => void
350
329
  ): Promise<void> {
351
- await this.ensureBinaryInstalled();
330
+ this.ensureBinaryAvailable();
352
331
 
353
332
  if (this.loginHandle) {
354
333
  onError?.('Login process already running');
@@ -410,7 +389,7 @@ class GlobalTunnelManager {
410
389
  }
411
390
 
412
391
  async createLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
413
- await this.ensureBinaryInstalled();
392
+ this.ensureBinaryAvailable();
414
393
 
415
394
  // Write credentials directly to our dir (not ~/.cloudflared/)
416
395
  const tunnelBaseDir = getTunnelDir();
@@ -433,7 +412,7 @@ class GlobalTunnelManager {
433
412
  }
434
413
 
435
414
  async deleteLocalTunnel(tunnelId: string, credentialsFile?: string): Promise<void> {
436
- await this.ensureBinaryInstalled();
415
+ this.ensureBinaryAvailable();
437
416
 
438
417
  await CloudflaredTunnel.deleteTunnel(tunnelId, { credentialsFile, origincert: CERT_PATH });
439
418
  debug.log('tunnel', `Local tunnel deleted: ${tunnelId}`);
@@ -448,7 +427,7 @@ class GlobalTunnelManager {
448
427
  }
449
428
 
450
429
  async routeDns(tunnelName: string, hostname: string): Promise<{ alreadyExists: boolean }> {
451
- await this.ensureBinaryInstalled();
430
+ this.ensureBinaryAvailable();
452
431
 
453
432
  const result = await CloudflaredTunnel.routeDns(tunnelName, hostname, { overwriteDns: true, origincert: CERT_PATH });
454
433
  debug.log('tunnel', `DNS route ${result.alreadyExists ? 'updated' : 'added'}: ${hostname} -> ${tunnelName}`);
@@ -483,14 +462,13 @@ class GlobalTunnelManager {
483
462
  async startLocalTunnel(
484
463
  config: LocalTunnelConfig,
485
464
  onProgress?: (stage: string, data?: any) => void
486
- ): Promise<{ binaryDownloaded: boolean; timings: Record<string, number> }> {
465
+ ): Promise<{ timings: Record<string, number> }> {
487
466
  onProgress?.('checking-binary');
488
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
467
+ this.ensureBinaryAvailable(onProgress);
489
468
  const timings: Record<string, number> = {};
490
- if (binaryInfo.downloadTime) timings.binaryDownload = binaryInfo.downloadTime;
491
469
 
492
470
  if (this.localTunnels.has(config.id)) {
493
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
471
+ return { timings };
494
472
  }
495
473
 
496
474
  if (config.ingress.length === 0) {
@@ -557,7 +535,7 @@ class GlobalTunnelManager {
557
535
  onProgress?.('connected', { timings });
558
536
  this.notifyStatusChanged();
559
537
 
560
- return { binaryDownloaded: binaryInfo.needsDownload, timings };
538
+ return { timings };
561
539
  } catch (error) {
562
540
  debug.error('tunnel', `Failed to start local tunnel ${config.name}:`, error);
563
541
  throw error;
@@ -1,5 +1,5 @@
1
1
  import { debug } from '$shared/utils/logger';
2
- import { getBinaryPath, isBinaryInstalled, installBinary, CloudflaredTunnel } from './cloudflared';
2
+ import { resolveCloudflaredBinary, CloudflaredTunnel, CloudflaredMissingError } from './cloudflared';
3
3
 
4
4
  interface TunnelInstance {
5
5
  tunnel: any;
@@ -18,7 +18,6 @@ interface TunnelConnection {
18
18
  class ProjectTunnelManager {
19
19
  // Key format: "projectId:port" to support multiple tunnels per project
20
20
  private activeTunnels = new Map<string, TunnelInstance>();
21
- private binaryInstalled = false;
22
21
 
23
22
  /**
24
23
  * Generate unique key for tunnel
@@ -28,51 +27,19 @@ class ProjectTunnelManager {
28
27
  }
29
28
 
30
29
  /**
31
- * Ensure cloudflared binary is installed
32
- * Downloads binary on first use (~66MB, takes 30-60 seconds)
30
+ * Verify cloudflared is available. Installation is user-initiated via
31
+ * Settings → System Tools; this manager never auto-downloads.
33
32
  */
34
- private async ensureBinaryInstalled(
33
+ private ensureBinaryAvailable(
35
34
  onProgress?: (stage: string, data?: any) => void
36
- ): Promise<{
37
- needsDownload: boolean;
38
- downloadTime?: number;
39
- }> {
40
- // Check if already verified in this session
41
- if (this.binaryInstalled) {
42
- onProgress?.('binary-ready', { cached: true });
43
- return { needsDownload: false };
44
- }
45
-
46
- // Check if binary file exists
47
- if (!isBinaryInstalled()) {
48
- debug.log('tunnel', '[PROGRESS:DOWNLOADING_BINARY] Cloudflared binary not found, downloading...');
49
- debug.log('tunnel', 'This may take 30-60 seconds on first use (downloading ~66MB)');
50
- onProgress?.('downloading-binary', { size: '~66MB' });
51
-
52
- const startTime = Date.now();
53
-
54
- try {
55
- await installBinary();
56
-
57
- const downloadTime = Date.now() - startTime;
58
- debug.log('tunnel', `[PROGRESS:BINARY_READY] Cloudflared binary installed successfully in ${downloadTime}ms at: ${getBinaryPath()}`);
59
-
60
- this.binaryInstalled = true;
61
- onProgress?.('binary-ready', { downloaded: true, time: downloadTime });
62
- return { needsDownload: true, downloadTime };
63
- } catch (error) {
64
- debug.error('tunnel', 'Failed to install cloudflared binary:', error);
65
- throw new Error(
66
- 'Failed to download cloudflared binary. Please check your internet connection and try again. ' +
67
- 'The tunnel feature requires downloading ~66MB on first use.'
68
- );
69
- }
70
- } else {
71
- debug.log('tunnel', '[PROGRESS:BINARY_READY] Cloudflared binary already installed at:', getBinaryPath());
72
- this.binaryInstalled = true;
73
- onProgress?.('binary-ready', { cached: true });
74
- return { needsDownload: false };
35
+ ): void {
36
+ const resolved = resolveCloudflaredBinary();
37
+ if (!resolved) {
38
+ debug.warn('tunnel', 'Cloudflared binary not available; install via Settings → System Tools');
39
+ throw new CloudflaredMissingError();
75
40
  }
41
+ debug.log('tunnel', '[PROGRESS:BINARY_READY] Cloudflared binary available at:', resolved);
42
+ onProgress?.('binary-ready', { cached: true });
76
43
  }
77
44
 
78
45
  /**
@@ -83,18 +50,13 @@ class ProjectTunnelManager {
83
50
  port: number,
84
51
  autoStopMinutes: number = 60,
85
52
  onProgress?: (stage: string, data?: any) => void
86
- ): Promise<{ publicUrl: string; status: 'active'; binaryDownloaded: boolean; timings: any }> {
87
- debug.log('tunnel', '[PROGRESS:CHECKING_BINARY] Checking if binary is installed...');
53
+ ): Promise<{ publicUrl: string; status: 'active'; timings: any }> {
54
+ debug.log('tunnel', '[PROGRESS:CHECKING_BINARY] Checking if binary is available...');
88
55
  onProgress?.('checking-binary');
89
56
 
90
- // Ensure binary is installed
91
- const binaryInfo = await this.ensureBinaryInstalled(onProgress);
57
+ this.ensureBinaryAvailable(onProgress);
92
58
  const timings: any = {};
93
59
 
94
- if (binaryInfo.needsDownload) {
95
- timings.binaryDownload = binaryInfo.downloadTime;
96
- }
97
-
98
60
  // Check if tunnel already exists for this port
99
61
  const tunnelKey = this.getTunnelKey(projectId, port);
100
62
  if (this.activeTunnels.has(tunnelKey)) {
@@ -209,7 +171,6 @@ class ProjectTunnelManager {
209
171
  return {
210
172
  publicUrl,
211
173
  status: 'active',
212
- binaryDownloaded: binaryInfo.needsDownload,
213
174
  timings
214
175
  };
215
176
  }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * db-client — connection CRUD + health WS handlers.
3
+ */
4
+
5
+ import { t } from 'elysia';
6
+ import { createRouter } from '$shared/utils/ws-server';
7
+ import { initializeDatabase } from '../../database';
8
+ import { dbClientConnectionQueries } from '../../database/queries';
9
+ import { connectionManager } from '../../db-client/connection-manager';
10
+ import type {
11
+ DbClientConnectionInput,
12
+ DbDriver,
13
+ DbSshAuthMethod,
14
+ DbSslMode
15
+ } from '$shared/types/db-client';
16
+ import { debug } from '$shared/utils/logger';
17
+
18
+ const driverSchema = t.Union([
19
+ t.Literal('mysql'),
20
+ t.Literal('postgres'),
21
+ t.Literal('sqlite'),
22
+ t.Literal('mongodb'),
23
+ t.Literal('redis')
24
+ ]);
25
+
26
+ const sslModeSchema = t.Union([
27
+ t.Literal('disable'),
28
+ t.Literal('require'),
29
+ t.Literal('verify-ca'),
30
+ t.Literal('verify-full')
31
+ ]);
32
+
33
+ const sshAuthSchema = t.Union([t.Literal('password'), t.Literal('key')]);
34
+
35
+ const sshInputSchema = t.Object({
36
+ enabled: t.Optional(t.Boolean()),
37
+ host: t.Optional(t.String()),
38
+ port: t.Optional(t.Number()),
39
+ username: t.Optional(t.String()),
40
+ authMethod: t.Optional(sshAuthSchema),
41
+ password: t.Optional(t.String()),
42
+ privateKey: t.Optional(t.String()),
43
+ passphrase: t.Optional(t.String())
44
+ });
45
+
46
+ const connectionInputSchema = t.Object({
47
+ name: t.String({ minLength: 1 }),
48
+ driver: driverSchema,
49
+ host: t.Optional(t.String()),
50
+ port: t.Optional(t.Number()),
51
+ username: t.Optional(t.String()),
52
+ password: t.Optional(t.String()),
53
+ database: t.Optional(t.String()),
54
+ sslMode: t.Optional(sslModeSchema),
55
+ sslCa: t.Optional(t.String()),
56
+ ssh: t.Optional(sshInputSchema),
57
+ options: t.Optional(t.Record(t.String(), t.Any())),
58
+ color: t.Optional(t.String())
59
+ });
60
+
61
+ const connectionPatchSchema = t.Object({
62
+ name: t.Optional(t.String({ minLength: 1 })),
63
+ driver: t.Optional(driverSchema),
64
+ host: t.Optional(t.String()),
65
+ port: t.Optional(t.Number()),
66
+ username: t.Optional(t.String()),
67
+ password: t.Optional(t.String()),
68
+ database: t.Optional(t.String()),
69
+ sslMode: t.Optional(sslModeSchema),
70
+ sslCa: t.Optional(t.String()),
71
+ ssh: t.Optional(sshInputSchema),
72
+ options: t.Optional(t.Record(t.String(), t.Any())),
73
+ color: t.Optional(t.String())
74
+ });
75
+
76
+ const healthSchema = t.Object({
77
+ ok: t.Boolean(),
78
+ latencyMs: t.Nullable(t.Number()),
79
+ serverVersion: t.Nullable(t.String()),
80
+ sshOk: t.Nullable(t.Boolean()),
81
+ error: t.Nullable(t.String())
82
+ });
83
+
84
+ const connectionTestSchema = t.Union([
85
+ t.Object({ id: t.String({ minLength: 1 }) }),
86
+ connectionInputSchema
87
+ ]);
88
+
89
+ function isInput(v: unknown): v is DbClientConnectionInput {
90
+ return typeof v === 'object' && v !== null && 'driver' in (v as Record<string, unknown>);
91
+ }
92
+
93
+ function normalizeSshPatch(input: DbClientConnectionInput['ssh']): DbClientConnectionInput['ssh'] {
94
+ if (!input) return undefined;
95
+ return {
96
+ ...input,
97
+ authMethod: (input.authMethod ?? 'password') as DbSshAuthMethod
98
+ };
99
+ }
100
+
101
+ function ensureInputDefaults(input: DbClientConnectionInput): DbClientConnectionInput {
102
+ return {
103
+ ...input,
104
+ driver: input.driver as DbDriver,
105
+ sslMode: (input.sslMode ?? 'disable') as DbSslMode,
106
+ ssh: normalizeSshPatch(input.ssh)
107
+ };
108
+ }
109
+
110
+ export const connectionsHandler = createRouter()
111
+ .http('db-client:list', {
112
+ data: t.Object({}),
113
+ response: t.Array(t.Any())
114
+ }, async () => {
115
+ await initializeDatabase();
116
+ return dbClientConnectionQueries.list();
117
+ })
118
+
119
+ .http('db-client:get', {
120
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
121
+ response: t.Any()
122
+ }, async ({ data }) => {
123
+ const conn = dbClientConnectionQueries.get(data.id);
124
+ if (!conn) throw new Error('db-client connection not found');
125
+ return conn;
126
+ })
127
+
128
+ .http('db-client:create', {
129
+ data: connectionInputSchema,
130
+ response: t.Any()
131
+ }, async ({ data }) => {
132
+ await initializeDatabase();
133
+ const conn = dbClientConnectionQueries.create(ensureInputDefaults(data as DbClientConnectionInput));
134
+ debug.log('db-client', `created connection ${conn.id} (${conn.driver})`);
135
+ return conn;
136
+ })
137
+
138
+ .http('db-client:update', {
139
+ data: t.Object({
140
+ id: t.String({ minLength: 1 }),
141
+ patch: connectionPatchSchema
142
+ }),
143
+ response: t.Any()
144
+ }, async ({ data }) => {
145
+ const patch = data.patch as Partial<DbClientConnectionInput>;
146
+ const normalized: Partial<DbClientConnectionInput> = {
147
+ ...patch,
148
+ ssh: patch.ssh ? normalizeSshPatch(patch.ssh) : undefined
149
+ };
150
+ // Drop the live adapter so the next access re-opens with new settings.
151
+ await connectionManager.release(data.id);
152
+ return dbClientConnectionQueries.update(data.id, normalized);
153
+ })
154
+
155
+ .http('db-client:delete', {
156
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
157
+ response: t.Object({ ok: t.Boolean() })
158
+ }, async ({ data }) => {
159
+ await connectionManager.release(data.id);
160
+ dbClientConnectionQueries.delete(data.id);
161
+ return { ok: true };
162
+ })
163
+
164
+ .http('db-client:test', {
165
+ data: connectionTestSchema,
166
+ response: healthSchema
167
+ }, async ({ data }) => {
168
+ await initializeDatabase();
169
+ if (isInput(data)) {
170
+ return connectionManager.test(ensureInputDefaults(data as DbClientConnectionInput));
171
+ }
172
+ return connectionManager.test({ id: (data as { id: string }).id });
173
+ })
174
+
175
+ .http('db-client:health', {
176
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
177
+ response: healthSchema
178
+ }, async ({ data }) => {
179
+ return connectionManager.test({ id: data.id });
180
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * db-client WebSocket router.
3
+ */
4
+
5
+ import { createRouter } from '$shared/utils/ws-server';
6
+ import { connectionsHandler } from './connections';
7
+ import { schemaHandler } from './schema';
8
+ import { queryHandler } from './query';
9
+ import { structureHandler } from './structure';
10
+ import { ioHandler } from './io';
11
+
12
+ export const dbClientRouter = createRouter()
13
+ .merge(connectionsHandler)
14
+ .merge(schemaHandler)
15
+ .merge(queryHandler)
16
+ .merge(structureHandler)
17
+ .merge(ioHandler);