@myrialabs/clopen 0.3.18 → 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.
Files changed (44) hide show
  1. package/backend/chat/stream-manager.ts +11 -1
  2. package/backend/database/migrations/039_create_file_audit_log.ts +45 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
  5. package/backend/database/queries/file-audit-log-queries.ts +184 -0
  6. package/backend/database/queries/index.ts +2 -1
  7. package/backend/db-client/drivers/mongodb.ts +52 -0
  8. package/backend/db-client/drivers/mysql.ts +168 -11
  9. package/backend/db-client/drivers/postgres.ts +182 -19
  10. package/backend/db-client/drivers/redis.ts +27 -0
  11. package/backend/db-client/drivers/sqlite.ts +66 -0
  12. package/backend/db-client/drivers/types.ts +13 -0
  13. package/backend/engine/install-recipes.ts +1 -109
  14. package/backend/http/files-upload.ts +84 -3
  15. package/backend/preview/browser/browser-preview-service.ts +44 -11
  16. package/backend/snapshot/snapshot-service.ts +82 -52
  17. package/backend/tunnel/tunnel-config.ts +76 -209
  18. package/backend/utils/client-ip.test.ts +55 -0
  19. package/backend/utils/client-ip.ts +42 -0
  20. package/backend/utils/ws.ts +6 -3
  21. package/backend/ws/auth/login.test.ts +271 -0
  22. package/backend/ws/auth/login.ts +36 -3
  23. package/backend/ws/auth/users.ts +3 -2
  24. package/backend/ws/db-client/schema.ts +14 -0
  25. package/backend/ws/db-client/structure.ts +120 -0
  26. package/backend/ws/files/path-access.test.ts +60 -1
  27. package/backend/ws/files/path-access.ts +21 -0
  28. package/backend/ws/snapshot/restore.ts +34 -29
  29. package/backend/ws/system-tools/install.ts +0 -1
  30. package/backend/ws/system-tools/status.ts +3 -4
  31. package/backend/ws/tunnel/config.ts +17 -25
  32. package/backend/ws/tunnel/operations.ts +63 -68
  33. package/dist/assets/{main-CaqEjA6B.js → main-72Z_L-nD.js} +224 -223
  34. package/dist/assets/main-ClADBkFf.css +1 -0
  35. package/dist/index.html +2 -2
  36. package/package.json +2 -1
  37. package/shared/types/db-client/query.ts +9 -0
  38. package/shared/utils/ws-client.ts +188 -38
  39. package/backend/tunnel/cloudflared/binary.ts +0 -171
  40. package/backend/tunnel/cloudflared/index.ts +0 -24
  41. package/backend/tunnel/cloudflared/tunnel.ts +0 -444
  42. package/backend/tunnel/global-tunnel-manager.ts +0 -687
  43. package/backend/tunnel/project-tunnel-manager.ts +0 -264
  44. package/dist/assets/main-6cCq8H0w.css +0 -1
@@ -10,6 +10,7 @@ import { t } from 'elysia';
10
10
  import { createRouter } from '$shared/utils/ws-server';
11
11
  import { messageQueries, sessionQueries, projectQueries, checkpointQueries } from '../../database/queries';
12
12
  import { snapshotService } from '../../snapshot/snapshot-service';
13
+ import { streamManager } from '../../chat/stream-manager';
13
14
  import { debug } from '$shared/utils/logger';
14
15
  import type { UnifiedMessage } from '$shared/types/unified';
15
16
  import {
@@ -40,7 +41,8 @@ export const restoreHandler = createRouter()
40
41
  modifiedBySnapshotId: t.String(),
41
42
  modifiedAt: t.String(),
42
43
  restoreContent: t.Optional(t.String()),
43
- currentContent: t.Optional(t.String())
44
+ currentContent: t.Optional(t.String()),
45
+ reason: t.Optional(t.Union([t.Literal('cross-session'), t.Literal('local')]))
44
46
  })),
45
47
  checkpointsToUndo: t.Array(t.String())
46
48
  })
@@ -111,7 +113,16 @@ export const restoreHandler = createRouter()
111
113
  })
112
114
  }, async ({ data, conn }) => {
113
115
  const { messageId, sessionId, conflictResolutions } = data;
114
- requireSessionAccess(conn, sessionId);
116
+ const session = requireSessionAccess(conn, sessionId);
117
+
118
+ // Refuse to restore while this session is still generating. Restore rewrites
119
+ // the working tree and resets the in-memory baseline; doing that mid-stream
120
+ // would corrupt the end-of-turn snapshot and race the engine's own writes.
121
+ const activeStream = streamManager.getSessionStream(sessionId, session.project_id);
122
+ if (activeStream?.status === 'active') {
123
+ throw new Error('Cannot restore while the chat is still generating. Stop the stream first, then try again.');
124
+ }
125
+
115
126
  const isInitialRestore = messageId === INITIAL_NODE_ID;
116
127
 
117
128
  debug.log('snapshot', `RESTORE - ${isInitialRestore ? 'Restoring to initial state' : 'Moving HEAD to checkpoint'}`);
@@ -136,19 +147,16 @@ export const restoreHandler = createRouter()
136
147
  let filesRestored = 0;
137
148
  let filesSkipped = 0;
138
149
 
139
- const session = sessionQueries.getById(sessionId);
140
- if (session) {
141
- const project = projectQueries.getById(session.project_id);
142
- if (project) {
143
- const result = await snapshotService.restoreSessionScoped(
144
- project.path,
145
- sessionId,
146
- null, // null = restore to initial (before all snapshots)
147
- conflictResolutions
148
- );
149
- filesRestored = result.restoredFiles;
150
- filesSkipped = result.skippedFiles;
151
- }
150
+ const project = projectQueries.getById(session.project_id);
151
+ if (project) {
152
+ const result = await snapshotService.restoreSessionScoped(
153
+ project.path,
154
+ sessionId,
155
+ null, // null = restore to initial (before all snapshots)
156
+ conflictResolutions
157
+ );
158
+ filesRestored = result.restoredFiles;
159
+ filesSkipped = result.skippedFiles;
152
160
  }
153
161
 
154
162
  // Broadcast messages-changed
@@ -285,20 +293,17 @@ export const restoreHandler = createRouter()
285
293
  let filesRestored = 0;
286
294
  let filesSkipped = 0;
287
295
 
288
- const session = sessionQueries.getById(sessionId);
289
- if (session) {
290
- const project = projectQueries.getById(session.project_id);
291
- if (project) {
292
- const result = await snapshotService.restoreSessionScoped(
293
- project.path,
294
- sessionId,
295
- resolvedCheckpointId,
296
- conflictResolutions,
297
- checkpointPath.length > 0 ? checkpointPath : undefined
298
- );
299
- filesRestored = result.restoredFiles;
300
- filesSkipped = result.skippedFiles;
301
- }
296
+ const project = projectQueries.getById(session.project_id);
297
+ if (project) {
298
+ const result = await snapshotService.restoreSessionScoped(
299
+ project.path,
300
+ sessionId,
301
+ resolvedCheckpointId,
302
+ conflictResolutions,
303
+ checkpointPath.length > 0 ? checkpointPath : undefined
304
+ );
305
+ filesRestored = result.restoredFiles;
306
+ filesSkipped = result.skippedFiles;
302
307
  }
303
308
 
304
309
  // 8. Broadcast messages-changed
@@ -27,7 +27,6 @@ const TOOL_UNION = t.Union([
27
27
  t.Literal('codex'),
28
28
  t.Literal('qwen'),
29
29
  t.Literal('chrome'),
30
- t.Literal('cloudflared')
31
30
  ]);
32
31
 
33
32
  const STATUS_UNION = t.Union([
@@ -10,7 +10,7 @@
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { debug } from '$shared/utils/logger';
13
- import { getToolStatus, resolveRecipe } from '$backend/engine/install-recipes';
13
+ import { getToolStatus, resolveRecipe, type ToolId } from '$backend/engine/install-recipes';
14
14
  import { getActiveSessionForTool } from '$backend/engine/install-runner';
15
15
 
16
16
  const TOOL_UNION = t.Union([
@@ -21,7 +21,6 @@ const TOOL_UNION = t.Union([
21
21
  t.Literal('codex'),
22
22
  t.Literal('qwen'),
23
23
  t.Literal('chrome'),
24
- t.Literal('cloudflared')
25
24
  ]);
26
25
 
27
26
  const RECIPE_SCHEMA = t.Object({
@@ -70,7 +69,7 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
70
69
  })
71
70
  ]);
72
71
 
73
- function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome' | 'cloudflared', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
72
+ function toRecipeDTO(tool: ToolId, recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
74
73
  return {
75
74
  tool,
76
75
  autoInstallable: recipe.autoInstallable,
@@ -113,7 +112,7 @@ export const systemToolsStatusHandler = createRouter()
113
112
  })
114
113
  }, async () => {
115
114
  debug.log('path', 'system-tools:status-all');
116
- const ids = ['git', 'claude', 'opencode', 'copilot', 'codex', 'qwen', 'chrome', 'cloudflared'] as const;
115
+ const ids = ['git', 'claude', 'opencode', 'copilot', 'codex', 'qwen', 'chrome'] as const;
117
116
  const tools = await Promise.all(ids.map(async (id) => {
118
117
  const [status, recipe] = await Promise.all([
119
118
  getToolStatus(id),
@@ -2,19 +2,13 @@
2
2
  * Tunnel Config Endpoints
3
3
  *
4
4
  * HTTP endpoints for managing tunnel configurations:
5
- * - Remote: list, add (token+label), remove
5
+ * - Remote: list, add (token+name), remove
6
6
  * - Local: list configs
7
7
  */
8
8
 
9
9
  import { t } from 'elysia';
10
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';
11
+ import { tunnelKit, tunnelStore, namedIngress } from '../../tunnel/tunnel-config';
18
12
 
19
13
  export const configHandler = createRouter()
20
14
 
@@ -27,7 +21,7 @@ export const configHandler = createRouter()
27
21
  response: t.Object({
28
22
  configs: t.Array(t.Object({
29
23
  id: t.String(),
30
- label: t.String(),
24
+ name: t.String(),
31
25
  isActive: t.Boolean(),
32
26
  ingress: t.Array(t.Object({
33
27
  hostname: t.Optional(t.String()),
@@ -36,30 +30,30 @@ export const configHandler = createRouter()
36
30
  }))
37
31
  })
38
32
  }, async () => {
39
- const configs = getRemoteTunnelConfigs();
33
+ const configs = tunnelStore.getRemotes();
40
34
  return {
41
35
  // Never expose tokens to the frontend
42
36
  configs: configs.map((c) => ({
43
37
  id: c.id,
44
- label: c.label,
45
- isActive: globalTunnelManager.isRemoteTunnelActive(c.id),
46
- ingress: globalTunnelManager.getRemoteTunnelIngress(c.id)
38
+ name: c.name,
39
+ isActive: tunnelKit.remote.isActive(c.id),
40
+ ingress: tunnelKit.remote.ingress(c.id)
47
41
  }))
48
42
  };
49
43
  })
50
44
 
51
45
  .http('tunnel:remote:config:add', {
52
46
  data: t.Object({
53
- label: t.String({ minLength: 1 }),
47
+ name: t.String({ minLength: 1 }),
54
48
  token: t.String({ minLength: 1 })
55
49
  }),
56
50
  response: t.Object({
57
51
  id: t.String(),
58
- label: t.String()
52
+ name: t.String()
59
53
  })
60
54
  }, async ({ data }) => {
61
- const entry = addRemoteTunnelConfig(data.label, data.token);
62
- return { id: entry.id, label: entry.label };
55
+ const entry = tunnelStore.addRemote(data.name, data.token);
56
+ return { id: entry.id, name: entry.name };
63
57
  })
64
58
 
65
59
  .http('tunnel:remote:config:remove', {
@@ -68,11 +62,9 @@ export const configHandler = createRouter()
68
62
  }),
69
63
  response: t.Object({ success: t.Boolean() })
70
64
  }, 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);
65
+ // Stop if running (tunnelKit.stop is a no-op for unknown ids).
66
+ await tunnelKit.stop(data.id);
67
+ const removed = tunnelStore.removeRemote(data.id);
76
68
  return { success: removed };
77
69
  })
78
70
 
@@ -95,14 +87,14 @@ export const configHandler = createRouter()
95
87
  }))
96
88
  })
97
89
  }, async () => {
98
- const configs = getLocalTunnelConfigs();
90
+ const configs = tunnelStore.getLocals();
99
91
  return {
100
92
  configs: configs.map((c) => ({
101
93
  id: c.id,
102
94
  name: c.name,
103
95
  tunnelId: c.tunnelId,
104
- ingress: c.ingress,
105
- isActive: globalTunnelManager.isLocalTunnelActive(c.id)
96
+ ingress: namedIngress(c.ingress),
97
+ isActive: tunnelKit.local.isActive(c.id)
106
98
  }))
107
99
  };
108
100
  });
@@ -5,34 +5,27 @@
5
5
  * - Quick tunnel: start/stop with random URL
6
6
  * - Remote tunnel: start/stop dashboard-managed tunnels
7
7
  * - Local tunnel: auth, create, delete, ingress, route-dns, start/stop
8
+ *
9
+ * Each handler that needs cloudflared calls `tunnelKit.bin.ensure()` first
10
+ * (it resolves from the managed dir or PATH, downloading on first use); the
11
+ * remaining calls are direct passthroughs to `tunnelKit.*` and the singleton
12
+ * `tunnelStore` for persistence.
8
13
  */
9
14
 
10
15
  import { t } from 'elysia';
11
16
  import { createRouter } from '$shared/utils/ws-server';
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';
17
+ import { tunnelKit, tunnelStore, namedIngress, mapActiveTunnel } from '../../tunnel/tunnel-config';
24
18
  import { debug } from '$shared/utils/logger';
25
19
  import { ws } from '$backend/utils/ws';
26
20
 
27
21
  // Wire up ingress update callback to push via WS
28
- globalTunnelManager.setRemoteIngressUpdateCallback((configId, ingress) => {
29
- ws.emit.global('tunnel:remote:ingress-update', { configId, ingress });
22
+ tunnelKit.on('ingress-update', ({ id, ingress }) => {
23
+ ws.emit.global('tunnel:remote:ingress-update', { id, ingress });
30
24
  });
31
25
 
32
26
  // 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 });
27
+ tunnelKit.on('status-changed', () => {
28
+ ws.emit.global('tunnel:status-changed', { tunnels: tunnelKit.list().map(mapActiveTunnel) });
36
29
  });
37
30
 
38
31
  export const operationsHandler = createRouter()
@@ -51,8 +44,9 @@ export const operationsHandler = createRouter()
51
44
  const { port, autoStopMinutes = 60 } = data;
52
45
  debug.log('tunnel', `[WS] Quick tunnel start: port=${port}, autoStop=${autoStopMinutes}`);
53
46
 
54
- const result = await globalTunnelManager.startQuickTunnel(port, autoStopMinutes);
55
- return result;
47
+ await tunnelKit.bin.ensure();
48
+ const { publicUrl, timings } = await tunnelKit.quick.start({ service: port, autoStopMinutes });
49
+ return { publicUrl, timings };
56
50
  })
57
51
 
58
52
  .http('tunnel:quick:stop', {
@@ -61,7 +55,7 @@ export const operationsHandler = createRouter()
61
55
  }),
62
56
  response: t.Object({ stopped: t.Boolean() })
63
57
  }, async ({ data }) => {
64
- await globalTunnelManager.stopQuickTunnel(data.port);
58
+ await tunnelKit.quick.stop(data.port);
65
59
  return { stopped: true };
66
60
  })
67
61
 
@@ -71,31 +65,34 @@ export const operationsHandler = createRouter()
71
65
 
72
66
  .http('tunnel:remote:start', {
73
67
  data: t.Object({
74
- configId: t.String({ minLength: 1 })
68
+ id: t.String({ minLength: 1 })
75
69
  }),
76
70
  response: t.Any()
77
71
  }, async ({ data }) => {
78
- const config = getRemoteTunnelConfigById(data.configId);
72
+ const config = tunnelStore.getRemote(data.id);
79
73
  if (!config) throw new Error('Remote tunnel config not found');
80
74
 
81
- debug.log('tunnel', `[WS] Remote tunnel start: ${config.label}`);
82
- const result = await globalTunnelManager.startRemoteTunnel(config);
83
- return result;
75
+ debug.log('tunnel', `[WS] Remote tunnel start: ${config.name}`);
76
+ await tunnelKit.bin.ensure();
77
+ const { timings } = await tunnelKit.remote.start(
78
+ { id: config.id, token: config.token, name: config.name }
79
+ );
80
+ return { timings };
84
81
  })
85
82
 
86
83
  .http('tunnel:remote:stop', {
87
84
  data: t.Object({
88
- configId: t.String({ minLength: 1 })
85
+ id: t.String({ minLength: 1 })
89
86
  }),
90
87
  response: t.Object({ stopped: t.Boolean() })
91
88
  }, async ({ data }) => {
92
- await globalTunnelManager.stopRemoteTunnel(data.configId);
89
+ await tunnelKit.stop(data.id);
93
90
  return { stopped: true };
94
91
  })
95
92
 
96
93
  .http('tunnel:remote:ingress', {
97
94
  data: t.Object({
98
- configId: t.String({ minLength: 1 })
95
+ id: t.String({ minLength: 1 })
99
96
  }),
100
97
  response: t.Object({
101
98
  ingress: t.Array(t.Object({
@@ -104,8 +101,7 @@ export const operationsHandler = createRouter()
104
101
  }))
105
102
  })
106
103
  }, async ({ data }) => {
107
- const ingress = globalTunnelManager.getRemoteTunnelIngress(data.configId);
108
- return { ingress };
104
+ return { ingress: tunnelKit.remote.ingress(data.id) };
109
105
  })
110
106
 
111
107
  // ═══════════════════════════════════════
@@ -120,17 +116,15 @@ export const operationsHandler = createRouter()
120
116
  zone: t.Nullable(t.String())
121
117
  })
122
118
  }, async () => {
123
- const auth = globalTunnelManager.checkCloudflaredAuth();
124
- const zone = getAuthorizedZone();
125
- return { ...auth, zone };
119
+ return { ...tunnelKit.local.checkAuth(), zone: tunnelStore.getZone() };
126
120
  })
127
121
 
128
122
  .http('tunnel:local:logout', {
129
123
  data: t.Object({}),
130
124
  response: t.Object({ success: t.Boolean() })
131
125
  }, async () => {
132
- globalTunnelManager.logoutCloudflared();
133
- clearAuthorizedZone();
126
+ tunnelKit.local.logout();
127
+ tunnelStore.clearZone();
134
128
  return { success: true };
135
129
  })
136
130
 
@@ -140,7 +134,7 @@ export const operationsHandler = createRouter()
140
134
  }),
141
135
  response: t.Object({ success: t.Boolean(), zone: t.String() })
142
136
  }, async ({ data }) => {
143
- setAuthorizedZone(data.zone);
137
+ tunnelStore.setZone(data.zone);
144
138
  return { success: true, zone: data.zone };
145
139
  })
146
140
 
@@ -150,23 +144,24 @@ export const operationsHandler = createRouter()
150
144
  }, async ({ conn }) => {
151
145
  const userId = ws.getUserId(conn);
152
146
 
153
- await globalTunnelManager.loginCloudflared(
154
- (url) => {
147
+ await tunnelKit.bin.ensure();
148
+ tunnelKit.local.login({
149
+ onUrl: (url) => {
155
150
  ws.emit.user(userId, 'tunnel:local:login-url', { url });
156
151
  },
157
- () => {
152
+ onComplete: () => {
158
153
  ws.emit.user(userId, 'tunnel:local:login-complete', {});
159
154
  },
160
- (error) => {
161
- ws.emit.user(userId, 'tunnel:local:login-error', { message: error });
155
+ onError: (message) => {
156
+ ws.emit.user(userId, 'tunnel:local:login-error', { message });
162
157
  }
163
- );
158
+ });
164
159
  })
165
160
 
166
161
  .on('tunnel:local:login-cancel', {
167
162
  data: t.Object({})
168
163
  }, async () => {
169
- globalTunnelManager.cancelLogin();
164
+ tunnelKit.local.cancelLogin();
170
165
  })
171
166
 
172
167
  .http('tunnel:local:create', {
@@ -181,8 +176,9 @@ export const operationsHandler = createRouter()
181
176
  }, async ({ data }) => {
182
177
  debug.log('tunnel', `[WS] Creating local tunnel: ${data.name}`);
183
178
 
184
- const result = await globalTunnelManager.createLocalTunnel(data.name);
185
- const config = addLocalTunnelConfig(data.name, result.tunnelId, result.credentialsFile);
179
+ await tunnelKit.bin.ensure();
180
+ const result = await tunnelKit.local.create(data.name);
181
+ const config = tunnelStore.addLocal(data.name, result.tunnelId, result.credentialsFile);
186
182
 
187
183
  return { id: config.id, name: config.name, tunnelId: config.tunnelId };
188
184
  })
@@ -193,24 +189,22 @@ export const operationsHandler = createRouter()
193
189
  }),
194
190
  response: t.Object({ success: t.Boolean() })
195
191
  }, async ({ data }) => {
196
- const config = getLocalTunnelConfigById(data.id);
192
+ const config = tunnelStore.getLocal(data.id);
197
193
  if (!config) throw new Error('Local tunnel config not found');
198
194
 
199
- // Stop if running
200
- if (globalTunnelManager.isLocalTunnelActive(data.id)) {
201
- await globalTunnelManager.stopLocalTunnel(data.id);
202
- }
195
+ // Stop if running (tunnelKit.stop is a no-op for unknown ids).
196
+ await tunnelKit.stop(data.id);
203
197
 
204
198
  // Delete from Cloudflare
205
199
  try {
206
- await globalTunnelManager.deleteLocalTunnel(config.tunnelId, config.credentialsFile);
200
+ await tunnelKit.bin.ensure();
201
+ await tunnelKit.local.delete(config.tunnelId, config.credentialsFile);
207
202
  } catch (error) {
208
203
  debug.warn('tunnel', `Could not delete tunnel from Cloudflare (may already be deleted):`, error);
209
204
  }
210
205
 
211
- // Remove from config and cleanup files
212
- removeLocalTunnelConfig(data.id);
213
- globalTunnelManager.cleanupLocalTunnelFiles(config.tunnelId);
206
+ tunnelStore.removeLocal(data.id);
207
+ tunnelKit.local.cleanupFiles(config.tunnelId);
214
208
  return { success: true };
215
209
  })
216
210
 
@@ -230,18 +224,18 @@ export const operationsHandler = createRouter()
230
224
  dnsError: t.Nullable(t.String())
231
225
  })
232
226
  }, async ({ data }) => {
233
- const tunnelConfig = getLocalTunnelConfigById(data.id);
227
+ const tunnelConfig = tunnelStore.getLocal(data.id);
234
228
  if (!tunnelConfig) throw new Error('Local tunnel config not found');
235
229
 
236
- // Add ingress rule
237
- const config = addLocalTunnelIngress(data.id, data.hostname, data.service);
230
+ const config = tunnelStore.addLocalIngress(data.id, data.hostname, data.service);
238
231
  if (!config) throw new Error('Failed to add ingress rule');
239
232
 
240
233
  // Auto route DNS using tunnel UUID (more reliable than name)
241
234
  let dnsRouted = false;
242
235
  let dnsError: string | null = null;
243
236
  try {
244
- await globalTunnelManager.routeDns(tunnelConfig.tunnelId, data.hostname);
237
+ await tunnelKit.bin.ensure();
238
+ await tunnelKit.local.routeDns(tunnelConfig.tunnelId, data.hostname);
245
239
  dnsRouted = true;
246
240
  debug.log('tunnel', `DNS routed for ${data.hostname} -> tunnel ${tunnelConfig.tunnelId}`);
247
241
  } catch (error) {
@@ -249,7 +243,7 @@ export const operationsHandler = createRouter()
249
243
  debug.warn('tunnel', `Auto route-dns for ${data.hostname} failed:`, dnsError);
250
244
  }
251
245
 
252
- return { success: true, ingress: config.ingress, dnsRouted, dnsError };
246
+ return { success: true, ingress: namedIngress(config.ingress), dnsRouted, dnsError };
253
247
  })
254
248
 
255
249
  .http('tunnel:local:ingress:remove', {
@@ -265,13 +259,13 @@ export const operationsHandler = createRouter()
265
259
  }))
266
260
  })
267
261
  }, async ({ data }) => {
268
- const config = removeLocalTunnelIngress(data.id, data.hostname);
262
+ const config = tunnelStore.removeLocalIngress(data.id, data.hostname);
269
263
  if (!config) throw new Error('Local tunnel config not found');
270
264
 
271
265
  // Regenerate config.yml to stay in sync
272
- globalTunnelManager.writeLocalTunnelConfig(config);
266
+ tunnelKit.local.writeConfig(config);
273
267
 
274
- return { success: true, ingress: config.ingress };
268
+ return { success: true, ingress: namedIngress(config.ingress) };
275
269
  })
276
270
 
277
271
  .http('tunnel:local:start', {
@@ -280,12 +274,13 @@ export const operationsHandler = createRouter()
280
274
  }),
281
275
  response: t.Any()
282
276
  }, async ({ data }) => {
283
- const config = getLocalTunnelConfigById(data.id);
277
+ const config = tunnelStore.getLocal(data.id);
284
278
  if (!config) throw new Error('Local tunnel config not found');
285
279
 
286
280
  debug.log('tunnel', `[WS] Starting local tunnel: ${config.name}`);
287
- const result = await globalTunnelManager.startLocalTunnel(config);
288
- return result;
281
+ await tunnelKit.bin.ensure();
282
+ const { timings } = await tunnelKit.local.start(config);
283
+ return { timings };
289
284
  })
290
285
 
291
286
  .http('tunnel:local:stop', {
@@ -294,7 +289,7 @@ export const operationsHandler = createRouter()
294
289
  }),
295
290
  response: t.Object({ stopped: t.Boolean() })
296
291
  }, async ({ data }) => {
297
- await globalTunnelManager.stopLocalTunnel(data.id);
292
+ await tunnelKit.stop(data.id);
298
293
  return { stopped: true };
299
294
  })
300
295
 
@@ -308,7 +303,7 @@ export const operationsHandler = createRouter()
308
303
  tunnels: t.Array(t.Any())
309
304
  })
310
305
  }, async () => {
311
- return { tunnels: globalTunnelManager.getActiveTunnels() };
306
+ return { tunnels: tunnelKit.list().map(mapActiveTunnel) };
312
307
  })
313
308
 
314
309
  // ═══════════════════════════════════════
@@ -320,7 +315,7 @@ export const operationsHandler = createRouter()
320
315
  }))
321
316
 
322
317
  .emit('tunnel:remote:ingress-update', t.Object({
323
- configId: t.String(),
318
+ id: t.String(),
324
319
  ingress: t.Array(t.Object({
325
320
  hostname: t.Optional(t.String()),
326
321
  service: t.String()