@myrialabs/clopen 0.4.31 → 0.4.33

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 (114) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +31 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -11,9 +11,6 @@ import {
11
11
  fetchAndCacheModelsDevCatalog,
12
12
  getCachedModelsDevCatalog,
13
13
  } from '../../../engine/adapters/opencode/presets';
14
- import { disposeOpenCodeClient } from '../../../engine/adapters/opencode/server';
15
- import { disposeEngine } from '../../../engine';
16
- import { streamManager } from '../../../chat';
17
14
  import { debug } from '$shared/utils/logger';
18
15
 
19
16
  // Shared typebox schemas
@@ -319,53 +316,4 @@ export const openCodeProviderHandler = createRouter()
319
316
  const body = await res.json() as { data?: { id: string; name?: string }[] };
320
317
  const models = (body.data || []).map(m => ({ id: m.id, name: m.name }));
321
318
  return { models };
322
- })
323
-
324
- // ═══════════════════════════════════════
325
- // Server Restart
326
- // ═══════════════════════════════════════
327
-
328
- .http('engine:opencode-server-restart', {
329
- data: t.Object({
330
- force: t.Optional(t.Boolean()),
331
- }),
332
- response: t.Object({
333
- success: t.Boolean(),
334
- activeChats: t.Optional(t.Number()),
335
- needsConfirmation: t.Optional(t.Boolean()),
336
- })
337
- }, async ({ data }) => {
338
- // Check for active opencode streams
339
- const activeStreams = streamManager.getActiveStreams()
340
- .filter(s => s.engine === 'opencode');
341
-
342
- if (activeStreams.length > 0 && !data.force) {
343
- return {
344
- success: false,
345
- activeChats: activeStreams.length,
346
- needsConfirmation: true,
347
- };
348
- }
349
-
350
- // Force: abort all active opencode streams first
351
- if (activeStreams.length > 0) {
352
- debug.log('engine', `Force-aborting ${activeStreams.length} active OpenCode streams before restart`);
353
- for (const stream of activeStreams) {
354
- try {
355
- await streamManager.cancelStream(stream.streamId);
356
- } catch (error) {
357
- debug.warn('engine', `Failed to abort stream ${stream.streamId}:`, error);
358
- }
359
- }
360
- }
361
-
362
- // Dispose global opencode engine + shared client/server.
363
- // forRestart=true ensures the server is killed even if we didn't
364
- // spawn it, and the stored URL is purged so next init() spawns fresh.
365
- await disposeEngine('opencode');
366
- await disposeOpenCodeClient(true);
367
-
368
- debug.log('engine', 'OpenCode server disposed. Will re-initialize on next use.');
369
-
370
- return { success: true };
371
319
  });
@@ -19,7 +19,7 @@ import {
19
19
  } from '../../files/file-reading';
20
20
  import { handlePathBrowsing } from '../../files/path-browsing';
21
21
  import { gitService } from '../../git/git-service';
22
- import { findRepoForFile } from '../../snapshot/gitignore';
22
+ import { findRepoForFile } from '../../git/nested-repos';
23
23
  import { projectQueries } from '../../database/queries/project-queries';
24
24
  import { isAbsolute, relative } from 'node:path';
25
25
  import { requireProjectAccess } from '../access';
@@ -161,8 +161,12 @@ export const watchHandler = createRouter()
161
161
  error: t.String()
162
162
  }))
163
163
 
164
- // Emitted when git state changes (external git operations)
164
+ // Emitted when git state changes (external git operations).
165
+ // `repoPaths` lists the working trees that moved — the project root and/or
166
+ // sub-repo roots — so a client can refresh a sub-repo's view without
167
+ // re-reading every other repo in the project.
165
168
  .emit('git:changed', t.Object({
166
169
  projectId: t.String(),
170
+ repoPaths: t.Optional(t.Array(t.String())),
167
171
  timestamp: t.Number()
168
172
  }));
@@ -6,7 +6,7 @@ import { t } from 'elysia';
6
6
  import path from 'node:path';
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
- import { findNestedRepoPaths, findRepoForFile } from '../../snapshot/gitignore';
9
+ import { findNestedRepoPaths, findRepoForFile } from '../../git/nested-repos';
10
10
  import { requireProjectAccess } from '../access';
11
11
  import { debug } from '$shared/utils/logger';
12
12
 
@@ -6,7 +6,7 @@ import { t } from 'elysia';
6
6
  import path from 'node:path';
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
- import { findRepoForFile } from '../../snapshot/gitignore';
9
+ import { findRepoForFile } from '../../git/nested-repos';
10
10
  import { requireProjectAccess } from '../access';
11
11
  import { debug } from '$shared/utils/logger';
12
12
 
@@ -6,7 +6,7 @@ import { t } from 'elysia';
6
6
  import path from 'node:path';
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
- import { findRepoForFile } from '../../snapshot/gitignore';
9
+ import { findRepoForFile } from '../../git/nested-repos';
10
10
  import { requireProjectAccess } from '../access';
11
11
  import { debug } from '$shared/utils/logger';
12
12
 
@@ -5,7 +5,7 @@
5
5
  import { t } from 'elysia';
6
6
  import { createRouter } from '$shared/utils/ws-server';
7
7
  import { gitService } from '../../git/git-service';
8
- import { findNestedRepoPaths } from '../../snapshot/gitignore';
8
+ import { findNestedRepoPaths } from '../../git/nested-repos';
9
9
  import { requireProjectAccess } from '../access';
10
10
  import { relative as pathRelative } from 'path';
11
11
 
@@ -31,6 +31,7 @@ import { gitRouter } from './git';
31
31
  import { engineRouter } from './engine';
32
32
  import { stackRouter } from './stack';
33
33
  import { dbClientRouter } from './db-client';
34
+ import { sshRouter } from './ssh';
34
35
  import { mcpRouter } from './mcp';
35
36
  import { skillsRouter } from './skills';
36
37
  import { commandsRouter } from './commands';
@@ -84,6 +85,9 @@ export const wsRouter = createRouter()
84
85
  // DB Client (global database management)
85
86
  .merge(dbClientRouter)
86
87
 
88
+ // SSH client (terminal, SFTP, port forwarding)
89
+ .merge(sshRouter)
90
+
87
91
  // External MCP server management (install from the official registry)
88
92
  .merge(mcpRouter)
89
93
 
@@ -0,0 +1,31 @@
1
+ import type { WSConnection } from '$shared/utils/ws-server';
2
+ import { ws } from '$backend/utils/ws';
3
+ import { sshConnectionQueries } from '../../database/queries';
4
+ import { sshPortForwardQueries } from '../../database/queries';
5
+ import type { SshConnection, SshForward } from '$shared/types/ssh';
6
+
7
+ export interface SshPrincipal {
8
+ userId: string;
9
+ isAdmin: boolean;
10
+ }
11
+
12
+ export function getSshPrincipal(conn: WSConnection): SshPrincipal {
13
+ return { userId: ws.getUserId(conn), isAdmin: ws.getRole(conn) === 'admin' };
14
+ }
15
+
16
+ /** Full connection including secrets, after checking the caller owns it. */
17
+ export function requireSshConnection(conn: WSConnection, connectionId: string): SshConnection {
18
+ const { userId, isAdmin } = getSshPrincipal(conn);
19
+ return sshConnectionQueries.ensureAccess(connectionId, userId, isAdmin);
20
+ }
21
+
22
+ /**
23
+ * A forward is reachable exactly when its connection is, so resolve the forward
24
+ * and check the owner of the host it belongs to.
25
+ */
26
+ export function requireSshForward(conn: WSConnection, forwardId: string): SshForward {
27
+ const forward = sshPortForwardQueries.get(forwardId);
28
+ if (!forward) throw new Error('ssh port forward not found');
29
+ requireSshConnection(conn, forward.connectionId);
30
+ return forward;
31
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * ssh-client — connection CRUD, health and host-key trust WS handlers.
3
+ */
4
+
5
+ import { t } from 'elysia';
6
+ import { createRouter } from '$shared/utils/ws-server';
7
+ import { initializeDatabase } from '../../database';
8
+ import { sshConnectionQueries, sshKnownHostQueries } from '../../database/queries';
9
+ import { sshClientPool } from '../../ssh/client-pool';
10
+ import { sshForwardManager } from '../../ssh/forwards';
11
+ import { sshHealthService } from '../../ssh/health';
12
+ import { knownHosts } from '../../ssh/known-hosts';
13
+ import { killSessionsForConnection } from '../../ssh/ptykit';
14
+ import type { SshConnectionInput } from '$shared/types/ssh';
15
+ import { debug } from '$shared/utils/logger';
16
+ import { getSshPrincipal, requireSshConnection } from './access';
17
+
18
+ const authMethodSchema = t.Union([
19
+ t.Literal('password'),
20
+ t.Literal('key'),
21
+ t.Literal('key-file'),
22
+ t.Literal('agent')
23
+ ]);
24
+
25
+ const connectionInputSchema = t.Object({
26
+ name: t.String({ minLength: 1 }),
27
+ host: t.String({ minLength: 1 }),
28
+ port: t.Optional(t.Number()),
29
+ username: t.String({ minLength: 1 }),
30
+ authMethod: t.Optional(authMethodSchema),
31
+ password: t.Optional(t.String()),
32
+ privateKey: t.Optional(t.String()),
33
+ privateKeyPath: t.Optional(t.String()),
34
+ passphrase: t.Optional(t.String()),
35
+ agentSocket: t.Optional(t.String()),
36
+ jumpConnectionId: t.Optional(t.Nullable(t.String())),
37
+ initialPath: t.Optional(t.String()),
38
+ keepaliveSeconds: t.Optional(t.Number()),
39
+ strictHostKey: t.Optional(t.Boolean()),
40
+ color: t.Optional(t.String())
41
+ });
42
+
43
+ const connectionPatchSchema = t.Object({
44
+ name: t.Optional(t.String({ minLength: 1 })),
45
+ host: t.Optional(t.String({ minLength: 1 })),
46
+ port: t.Optional(t.Number()),
47
+ username: t.Optional(t.String({ minLength: 1 })),
48
+ authMethod: t.Optional(authMethodSchema),
49
+ password: t.Optional(t.String()),
50
+ privateKey: t.Optional(t.String()),
51
+ privateKeyPath: t.Optional(t.String()),
52
+ passphrase: t.Optional(t.String()),
53
+ agentSocket: t.Optional(t.String()),
54
+ jumpConnectionId: t.Optional(t.Nullable(t.String())),
55
+ initialPath: t.Optional(t.String()),
56
+ keepaliveSeconds: t.Optional(t.Number()),
57
+ strictHostKey: t.Optional(t.Boolean()),
58
+ color: t.Optional(t.String())
59
+ });
60
+
61
+ const healthSchema = t.Object({
62
+ ok: t.Boolean(),
63
+ latencyMs: t.Nullable(t.Number()),
64
+ serverBanner: t.Nullable(t.String()),
65
+ remoteOs: t.Nullable(t.String()),
66
+ hostKeyFingerprint: t.Nullable(t.String()),
67
+ hostKeyChanged: t.Boolean(),
68
+ suspended: t.Boolean(),
69
+ error: t.Nullable(t.String())
70
+ });
71
+
72
+ const connectionTestSchema = t.Union([t.Object({ id: t.String({ minLength: 1 }) }), connectionInputSchema]);
73
+
74
+ function isInput(value: unknown): value is SshConnectionInput {
75
+ return typeof value === 'object' && value !== null && 'host' in (value as Record<string, unknown>);
76
+ }
77
+
78
+ /**
79
+ * Changing where or how a host is reached invalidates everything riding the old
80
+ * transport, so shells, forwards and the pooled client all go before the write.
81
+ */
82
+ async function tearDownConnection(connectionId: string): Promise<void> {
83
+ killSessionsForConnection(connectionId);
84
+ await sshForwardManager.stopForConnection(connectionId);
85
+ sshClientPool.release(connectionId);
86
+ // Editing or deleting is not "disconnect" — a host suspended earlier should
87
+ // be dialable again once its settings change.
88
+ sshClientPool.resume(connectionId);
89
+ }
90
+
91
+ export const sshConnectionsHandler = createRouter()
92
+ .http('ssh:list', {
93
+ data: t.Object({}),
94
+ response: t.Array(t.Any())
95
+ }, async ({ conn }) => {
96
+ await initializeDatabase();
97
+ const { userId, isAdmin } = getSshPrincipal(conn);
98
+ return sshConnectionQueries.listForUser(userId, isAdmin);
99
+ })
100
+
101
+ .http('ssh:get', {
102
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
103
+ response: t.Any()
104
+ }, async ({ data, conn }) => {
105
+ const { userId, isAdmin } = getSshPrincipal(conn);
106
+ const connection = sshConnectionQueries.getForUser(data.id, userId, isAdmin);
107
+ if (!connection) throw new Error('ssh connection not found');
108
+ return connection;
109
+ })
110
+
111
+ .http('ssh:create', {
112
+ data: connectionInputSchema,
113
+ response: t.Any()
114
+ }, async ({ data, conn }) => {
115
+ await initializeDatabase();
116
+ const { userId } = getSshPrincipal(conn);
117
+ const created = sshConnectionQueries.createForUser(data as SshConnectionInput, userId);
118
+ debug.log('ssh', `created connection ${created.id} (${created.host})`);
119
+ return created;
120
+ })
121
+
122
+ .http('ssh:update', {
123
+ data: t.Object({ id: t.String({ minLength: 1 }), patch: connectionPatchSchema }),
124
+ response: t.Any()
125
+ }, async ({ data, conn }) => {
126
+ const { userId, isAdmin } = getSshPrincipal(conn);
127
+ requireSshConnection(conn, data.id);
128
+ await tearDownConnection(data.id);
129
+ return sshConnectionQueries.updateForUser(
130
+ data.id,
131
+ data.patch as Partial<SshConnectionInput>,
132
+ userId,
133
+ isAdmin
134
+ );
135
+ })
136
+
137
+ .http('ssh:delete', {
138
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
139
+ response: t.Object({ ok: t.Boolean() })
140
+ }, async ({ data, conn }) => {
141
+ const { userId, isAdmin } = getSshPrincipal(conn);
142
+ requireSshConnection(conn, data.id);
143
+ await tearDownConnection(data.id);
144
+ sshConnectionQueries.deleteForUser(data.id, userId, isAdmin);
145
+ return { ok: true };
146
+ })
147
+
148
+ .http('ssh:test', {
149
+ data: connectionTestSchema,
150
+ response: healthSchema
151
+ }, async ({ data, conn }) => {
152
+ await initializeDatabase();
153
+ if (isInput(data)) {
154
+ return sshHealthService.testInput(data as SshConnectionInput);
155
+ }
156
+ const id = (data as { id: string }).id;
157
+ requireSshConnection(conn, id);
158
+ return sshHealthService.testSaved(id);
159
+ })
160
+
161
+ /**
162
+ * Open the host now (and start its auto-start forwards). Called when the user
163
+ * selects a connection, so the sidebar can show a live state before any tab
164
+ * or file listing asks for one.
165
+ */
166
+ .http('ssh:activate', {
167
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
168
+ response: healthSchema
169
+ }, async ({ data, conn }) => {
170
+ requireSshConnection(conn, data.id);
171
+ sshClientPool.resume(data.id);
172
+ const health = await sshHealthService.testSaved(data.id);
173
+ if (health.ok) {
174
+ await sshForwardManager.startAutoForwards(data.id);
175
+ }
176
+ return health;
177
+ })
178
+
179
+ /**
180
+ * Close a host's transport, its shells and its forwards, and keep it closed.
181
+ * Without the suspend the pool would redial on the next keystroke, which is
182
+ * what made this button look like it did nothing.
183
+ */
184
+ .http('ssh:disconnect', {
185
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
186
+ response: healthSchema
187
+ }, async ({ data, conn }) => {
188
+ requireSshConnection(conn, data.id);
189
+ killSessionsForConnection(data.id);
190
+ await sshForwardManager.stopForConnection(data.id);
191
+ sshClientPool.suspend(data.id);
192
+ return sshHealthService.testSaved(data.id);
193
+ })
194
+
195
+ .http('ssh:known-hosts', {
196
+ data: t.Object({}),
197
+ response: t.Array(t.Any())
198
+ }, async () => {
199
+ await initializeDatabase();
200
+ return sshKnownHostQueries.list();
201
+ })
202
+
203
+ /**
204
+ * Accept the key a host is presenting now, replacing the trusted one. The
205
+ * fingerprint is re-read from the live handshake rather than taken from the
206
+ * client, so trusting is always trusting what the host actually sent.
207
+ */
208
+ .http('ssh:trust-host-key', {
209
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
210
+ response: healthSchema
211
+ }, async ({ data, conn }) => {
212
+ const connection = requireSshConnection(conn, data.id);
213
+ knownHosts.forget(connection.host, connection.port);
214
+ await tearDownConnection(data.id);
215
+ return sshHealthService.testSaved(data.id);
216
+ })
217
+
218
+ .http('ssh:forget-host-key', {
219
+ data: t.Object({ host: t.String({ minLength: 1 }), port: t.Number() }),
220
+ response: t.Object({ ok: t.Boolean() })
221
+ }, async ({ data }) => {
222
+ knownHosts.forget(data.host, data.port);
223
+ return { ok: true };
224
+ });
@@ -0,0 +1,109 @@
1
+ /**
2
+ * ssh-client — port forwarding WS handlers.
3
+ */
4
+
5
+ import { t } from 'elysia';
6
+ import { createRouter } from '$shared/utils/ws-server';
7
+ import { sshPortForwardQueries } from '../../database/queries';
8
+ import { sshForwardManager } from '../../ssh/forwards';
9
+ import type { SshForwardInput } from '$shared/types/ssh';
10
+ import { requireSshConnection, requireSshForward } from './access';
11
+
12
+ const forwardTypeSchema = t.Union([t.Literal('local'), t.Literal('remote'), t.Literal('dynamic')]);
13
+
14
+ const forwardInputSchema = t.Object({
15
+ name: t.String({ minLength: 1 }),
16
+ type: forwardTypeSchema,
17
+ listenHost: t.Optional(t.String()),
18
+ listenPort: t.Number({ minimum: 0, maximum: 65535 }),
19
+ destHost: t.Optional(t.String()),
20
+ destPort: t.Optional(t.Number({ minimum: 0, maximum: 65535 })),
21
+ autoStart: t.Optional(t.Boolean())
22
+ });
23
+
24
+ const forwardPatchSchema = t.Object({
25
+ name: t.Optional(t.String({ minLength: 1 })),
26
+ type: t.Optional(forwardTypeSchema),
27
+ listenHost: t.Optional(t.String()),
28
+ listenPort: t.Optional(t.Number({ minimum: 0, maximum: 65535 })),
29
+ destHost: t.Optional(t.String()),
30
+ destPort: t.Optional(t.Number({ minimum: 0, maximum: 65535 })),
31
+ autoStart: t.Optional(t.Boolean())
32
+ });
33
+
34
+ /** A non-dynamic forward is meaningless without somewhere to forward to. */
35
+ function requireDestination(type: string, destHost?: string, destPort?: number): void {
36
+ if (type === 'dynamic') return;
37
+ if (!destHost || !destPort) {
38
+ throw new Error('Local and remote forwards need a destination host and port');
39
+ }
40
+ }
41
+
42
+ export const sshForwardsHandler = createRouter()
43
+ .http('ssh:forward-list', {
44
+ data: t.Object({ connectionId: t.String({ minLength: 1 }) }),
45
+ response: t.Any()
46
+ }, async ({ data, conn }) => {
47
+ requireSshConnection(conn, data.connectionId);
48
+ return {
49
+ forwards: sshPortForwardQueries.listForConnection(data.connectionId),
50
+ statuses: sshForwardManager.statusesForConnection(data.connectionId)
51
+ };
52
+ })
53
+
54
+ .http('ssh:forward-create', {
55
+ data: t.Object({
56
+ connectionId: t.String({ minLength: 1 }),
57
+ input: forwardInputSchema
58
+ }),
59
+ response: t.Any()
60
+ }, async ({ data, conn }) => {
61
+ requireSshConnection(conn, data.connectionId);
62
+ const input = data.input as SshForwardInput;
63
+ requireDestination(input.type, input.destHost, input.destPort);
64
+ return sshPortForwardQueries.create(data.connectionId, input);
65
+ })
66
+
67
+ .http('ssh:forward-update', {
68
+ data: t.Object({ id: t.String({ minLength: 1 }), patch: forwardPatchSchema }),
69
+ response: t.Any()
70
+ }, async ({ data, conn }) => {
71
+ const existing = requireSshForward(conn, data.id);
72
+ const patch = data.patch as Partial<SshForwardInput>;
73
+ requireDestination(
74
+ patch.type ?? existing.type,
75
+ patch.destHost ?? existing.destHost ?? undefined,
76
+ patch.destPort ?? existing.destPort ?? undefined
77
+ );
78
+ // Settings only take effect on a fresh listener, so restart-on-edit is the
79
+ // honest behaviour: stop now, and let the user start it again.
80
+ await sshForwardManager.stop(data.id);
81
+ return sshPortForwardQueries.update(data.id, patch);
82
+ })
83
+
84
+ .http('ssh:forward-delete', {
85
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
86
+ response: t.Object({ ok: t.Boolean() })
87
+ }, async ({ data, conn }) => {
88
+ requireSshForward(conn, data.id);
89
+ await sshForwardManager.stop(data.id);
90
+ sshPortForwardQueries.delete(data.id);
91
+ return { ok: true };
92
+ })
93
+
94
+ .http('ssh:forward-start', {
95
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
96
+ response: t.Any()
97
+ }, async ({ data, conn }) => {
98
+ const forward = requireSshForward(conn, data.id);
99
+ return sshForwardManager.start(forward);
100
+ })
101
+
102
+ .http('ssh:forward-stop', {
103
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
104
+ response: t.Any()
105
+ }, async ({ data, conn }) => {
106
+ const forward = requireSshForward(conn, data.id);
107
+ await sshForwardManager.stop(data.id);
108
+ return sshForwardManager.status(forward);
109
+ });
@@ -0,0 +1,18 @@
1
+ /**
2
+ * ssh-client WebSocket router.
3
+ *
4
+ * Terminal sessions run on their own PtyKit manager and are tunneled over this
5
+ * socket (tunnel.ts); everything else is ordinary request/response.
6
+ */
7
+
8
+ import { createRouter } from '$shared/utils/ws-server';
9
+ import { sshConnectionsHandler } from './connections';
10
+ import { sshSftpHandler } from './sftp';
11
+ import { sshForwardsHandler } from './forwards';
12
+ import { sshTunnelHandler } from './tunnel';
13
+
14
+ export const sshRouter = createRouter()
15
+ .merge(sshConnectionsHandler)
16
+ .merge(sshSftpHandler)
17
+ .merge(sshForwardsHandler)
18
+ .merge(sshTunnelHandler);