@myrialabs/clopen 0.4.32 → 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 (78) hide show
  1. package/backend/chat/stream-manager.ts +4 -1
  2. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  5. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  6. package/backend/database/queries/index.ts +3 -0
  7. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  8. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  9. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  10. package/backend/db-client/connection-manager.ts +8 -1
  11. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  12. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  13. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  14. package/backend/engine/adapters/codex/stream.ts +33 -4
  15. package/backend/engine/adapters/copilot/stream.ts +1 -1
  16. package/backend/engine/adapters/cursor/stream.ts +1 -1
  17. package/backend/engine/adapters/qwen/stream.ts +1 -1
  18. package/backend/engine/docs/adapter-contract.md +7 -0
  19. package/backend/files/file-watcher.ts +283 -51
  20. package/backend/files/git-events.test.ts +110 -0
  21. package/backend/git/git-dirs.test.ts +132 -0
  22. package/backend/git/git-dirs.ts +0 -0
  23. package/backend/git/nested-repos.test.ts +108 -5
  24. package/backend/git/nested-repos.ts +103 -18
  25. package/backend/http/audio.ts +5 -32
  26. package/backend/http/bearer-auth.ts +47 -0
  27. package/backend/http/files-download.test.ts +146 -0
  28. package/backend/http/files-download.ts +109 -0
  29. package/backend/http/files-upload.ts +3 -29
  30. package/backend/http/ssh-sftp.ts +133 -0
  31. package/backend/index.ts +16 -2
  32. package/backend/mcp/README.md +34 -6
  33. package/backend/mcp/index.ts +8 -8
  34. package/backend/mcp/internal/config.ts +69 -19
  35. package/backend/mcp/internal/project-context.test.ts +40 -0
  36. package/backend/mcp/internal/project-context.ts +80 -7
  37. package/backend/mcp/internal/remote-server.test.ts +17 -2
  38. package/backend/mcp/internal/remote-server.ts +36 -3
  39. package/backend/mcp/internal/servers/helper.ts +48 -18
  40. package/backend/preview/browser/browser-video-capture.ts +51 -4
  41. package/backend/ssh/client-pool.ts +196 -0
  42. package/backend/ssh/connect.ts +375 -0
  43. package/backend/ssh/disk-usage.test.ts +134 -0
  44. package/backend/ssh/disk-usage.ts +214 -0
  45. package/backend/ssh/forwards.ts +309 -0
  46. package/backend/ssh/health.ts +141 -0
  47. package/backend/ssh/known-hosts.ts +96 -0
  48. package/backend/ssh/pty-backend.ts +215 -0
  49. package/backend/ssh/ptykit.ts +66 -0
  50. package/backend/ssh/sftp.test.ts +242 -0
  51. package/backend/ssh/sftp.ts +967 -0
  52. package/backend/ssh/socks5.test.ts +167 -0
  53. package/backend/ssh/socks5.ts +164 -0
  54. package/backend/ssh/tunnel.ts +87 -0
  55. package/backend/ws/db-client/connections.ts +1 -0
  56. package/backend/ws/files/watch.ts +5 -1
  57. package/backend/ws/index.ts +4 -0
  58. package/backend/ws/ssh/access.ts +31 -0
  59. package/backend/ws/ssh/connections.ts +224 -0
  60. package/backend/ws/ssh/forwards.ts +109 -0
  61. package/backend/ws/ssh/index.ts +18 -0
  62. package/backend/ws/ssh/sftp.ts +259 -0
  63. package/backend/ws/ssh/tunnel.ts +93 -0
  64. package/dist/assets/{index-DSvGoxp2.js → index-BF4buYmI.js} +1 -1
  65. package/dist/assets/{index-hu17G6tX.js → index-BW0DA8NV.js} +1 -1
  66. package/dist/assets/{main-BccclZsC.js → main-BbwWLJRN.js} +499 -473
  67. package/dist/assets/main-CCvRMXlP.css +1 -0
  68. package/dist/index.html +2 -2
  69. package/package.json +1 -1
  70. package/shared/types/database/schema.ts +49 -0
  71. package/shared/types/db-client/connection.ts +6 -0
  72. package/shared/types/ssh/connection.ts +80 -0
  73. package/shared/types/ssh/forward.ts +46 -0
  74. package/shared/types/ssh/index.ts +8 -0
  75. package/shared/types/ssh/known-host.ts +19 -0
  76. package/shared/types/ssh/sftp.ts +141 -0
  77. package/shared/utils/logger.ts +1 -0
  78. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -439,7 +439,10 @@ class StreamManager extends EventEmitter {
439
439
  // Register session -> projectId mapping for MCP context
440
440
  if (request.projectId) {
441
441
  projectContextService.registerSession(request.chatSessionId, request.projectId);
442
- projectContextService.registerStream(streamId, request.projectId, request.chatSessionId);
442
+ // The engine goes with it: the remote HTTP MCP bridge cannot always
443
+ // name the calling stream, and knowing which engine asked is what
444
+ // keeps a fallback from reaching across into another engine's project.
445
+ projectContextService.registerStream(streamId, request.projectId, request.chatSessionId, request.engine.type);
443
446
  }
444
447
  // Hand the AbortSignal to MCP so tool handlers can fast-fail on
445
448
  // cancellation. Without this, the engine subprocess dies on cancel
@@ -0,0 +1,116 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create ssh_connections, ssh_known_hosts and ssh_port_forwards tables';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating ssh_connections table...');
8
+
9
+ // `jump_connection_id` self-references: a saved host can be reached through
10
+ // another saved host (ProxyJump). ON DELETE SET NULL rather than CASCADE —
11
+ // deleting a bastion must not silently delete everything behind it.
12
+ db.exec(`
13
+ CREATE TABLE IF NOT EXISTS ssh_connections (
14
+ id TEXT PRIMARY KEY,
15
+ name TEXT NOT NULL,
16
+ host TEXT NOT NULL,
17
+ port INTEGER NOT NULL DEFAULT 22,
18
+ username TEXT NOT NULL,
19
+ auth_method TEXT NOT NULL DEFAULT 'password'
20
+ CHECK (auth_method IN ('password','key','key-file','agent')),
21
+ password TEXT,
22
+ private_key TEXT,
23
+ private_key_path TEXT,
24
+ passphrase TEXT,
25
+ agent_socket TEXT,
26
+ jump_connection_id TEXT REFERENCES ssh_connections(id) ON DELETE SET NULL,
27
+ initial_path TEXT,
28
+ keepalive_seconds INTEGER NOT NULL DEFAULT 30,
29
+ strict_host_key INTEGER NOT NULL DEFAULT 1,
30
+ color TEXT,
31
+ owner_user_id TEXT,
32
+ created_at TEXT NOT NULL,
33
+ updated_at TEXT NOT NULL,
34
+ last_used_at TEXT
35
+ )
36
+ `);
37
+
38
+ db.exec(`
39
+ CREATE INDEX IF NOT EXISTS idx_ssh_conn_last_used
40
+ ON ssh_connections(last_used_at DESC)
41
+ `);
42
+
43
+ db.exec(`
44
+ CREATE INDEX IF NOT EXISTS idx_ssh_conn_owner
45
+ ON ssh_connections(owner_user_id)
46
+ `);
47
+
48
+ debug.log('migration', 'Creating ssh_known_hosts table...');
49
+
50
+ // One trusted key per (host, port) — the same rule OpenSSH's known_hosts
51
+ // enforces, so a rotated key is an update rather than a second row.
52
+ db.exec(`
53
+ CREATE TABLE IF NOT EXISTS ssh_known_hosts (
54
+ id TEXT PRIMARY KEY,
55
+ host TEXT NOT NULL,
56
+ port INTEGER NOT NULL DEFAULT 22,
57
+ key_type TEXT NOT NULL,
58
+ fingerprint TEXT NOT NULL,
59
+ added_at TEXT NOT NULL,
60
+ last_seen_at TEXT,
61
+ UNIQUE (host, port)
62
+ )
63
+ `);
64
+
65
+ debug.log('migration', 'Creating ssh_port_forwards table...');
66
+
67
+ db.exec(`
68
+ CREATE TABLE IF NOT EXISTS ssh_port_forwards (
69
+ id TEXT PRIMARY KEY,
70
+ connection_id TEXT NOT NULL,
71
+ name TEXT NOT NULL,
72
+ type TEXT NOT NULL CHECK (type IN ('local','remote','dynamic')),
73
+ listen_host TEXT NOT NULL DEFAULT '127.0.0.1',
74
+ listen_port INTEGER NOT NULL,
75
+ dest_host TEXT,
76
+ dest_port INTEGER,
77
+ auto_start INTEGER NOT NULL DEFAULT 0,
78
+ created_at TEXT NOT NULL,
79
+ updated_at TEXT NOT NULL,
80
+ FOREIGN KEY (connection_id) REFERENCES ssh_connections(id) ON DELETE CASCADE
81
+ )
82
+ `);
83
+
84
+ db.exec(`
85
+ CREATE INDEX IF NOT EXISTS idx_ssh_forward_connection
86
+ ON ssh_port_forwards(connection_id)
87
+ `);
88
+
89
+ // Let a database connection reuse a saved SSH host instead of repeating the
90
+ // host, credentials and key inline. The inline columns stay: existing
91
+ // connections keep working untouched, and this is simply the other mode.
92
+ const dbClientColumns = db.prepare(`PRAGMA table_info(db_client_connections)`).all() as Array<{ name: string }>;
93
+ if (dbClientColumns.length > 0 && !dbClientColumns.some((column) => column.name === 'ssh_connection_id')) {
94
+ debug.log('migration', 'Adding ssh_connection_id to db_client_connections...');
95
+ db.exec(`
96
+ ALTER TABLE db_client_connections
97
+ ADD COLUMN ssh_connection_id TEXT REFERENCES ssh_connections(id) ON DELETE SET NULL
98
+ `);
99
+ }
100
+
101
+ debug.log('migration', 'ssh-client tables created');
102
+ };
103
+
104
+ export const down = (db: DatabaseConnection): void => {
105
+ debug.log('migration', 'Dropping ssh-client tables...');
106
+ db.exec('DROP INDEX IF EXISTS idx_ssh_forward_connection');
107
+ db.exec('DROP TABLE IF EXISTS ssh_port_forwards');
108
+ db.exec('DROP TABLE IF EXISTS ssh_known_hosts');
109
+ db.exec('DROP INDEX IF EXISTS idx_ssh_conn_owner');
110
+ db.exec('DROP INDEX IF EXISTS idx_ssh_conn_last_used');
111
+ db.exec('DROP TABLE IF EXISTS ssh_connections');
112
+ // db_client_connections.ssh_connection_id is deliberately left in place —
113
+ // SQLite cannot drop a column without rebuilding the table, and an orphaned
114
+ // nullable column is harmless.
115
+ debug.log('migration', 'ssh-client tables dropped');
116
+ };
@@ -67,6 +67,7 @@ import * as migration065 from './065_add_session_reasoning_effort';
67
67
  import * as migration066 from './066_create_memory_graph';
68
68
  import * as migration067 from './067_add_memory_graph_layout';
69
69
  import * as migration068 from './068_create_engine_config_revision';
70
+ import * as migration069 from './069_create_ssh_client_tables';
70
71
 
71
72
  // Export all migrations in order
72
73
  export const migrations = [
@@ -477,6 +478,12 @@ export const migrations = [
477
478
  description: migration068.description,
478
479
  up: migration068.up,
479
480
  down: migration068.down
481
+ },
482
+ {
483
+ id: '069',
484
+ description: migration069.description,
485
+ up: migration069.up,
486
+ down: migration069.down
480
487
  }
481
488
  ];
482
489
 
@@ -11,6 +11,7 @@ import type {
11
11
 
12
12
  const DEFAULT_SSH: DbClientSshConfig = {
13
13
  enabled: false,
14
+ connectionId: null,
14
15
  host: '',
15
16
  port: 22,
16
17
  username: '',
@@ -35,6 +36,7 @@ function rowToConnection(row: DBDbClientConnectionRow): DbClientConnection {
35
36
 
36
37
  const ssh: DbClientSshConfig = {
37
38
  enabled: row.ssh_enabled === 1,
39
+ connectionId: row.ssh_connection_id,
38
40
  host: row.ssh_host ?? '',
39
41
  port: row.ssh_port ?? 22,
40
42
  username: row.ssh_username ?? '',
@@ -151,7 +153,7 @@ function insertConnection(input: DbClientConnectionInput, ownerUserId: string |
151
153
  host, port, username, password, database,
152
154
  ssl_mode, ssl_ca,
153
155
  ssh_enabled, ssh_host, ssh_port, ssh_username, ssh_auth_method,
154
- ssh_password, ssh_private_key, ssh_passphrase,
156
+ ssh_password, ssh_private_key, ssh_passphrase, ssh_connection_id,
155
157
  options_json, color,
156
158
  owner_user_id,
157
159
  created_at, updated_at, last_used_at
@@ -160,7 +162,7 @@ function insertConnection(input: DbClientConnectionInput, ownerUserId: string |
160
162
  ?, ?, ?, ?, ?,
161
163
  ?, ?,
162
164
  ?, ?, ?, ?, ?,
163
- ?, ?, ?,
165
+ ?, ?, ?, ?,
164
166
  ?, ?,
165
167
  ?,
166
168
  ?, ?, ?
@@ -177,6 +179,7 @@ function insertConnection(input: DbClientConnectionInput, ownerUserId: string |
177
179
  params.ssh.password || null,
178
180
  params.ssh.privateKey || null,
179
181
  params.ssh.passphrase || null,
182
+ params.ssh.connectionId || null,
180
183
  JSON.stringify(params.options),
181
184
  params.color,
182
185
  params.ownerUserId,
@@ -275,6 +278,7 @@ export const dbClientConnectionQueries = {
275
278
  if (patch.ssh !== undefined) {
276
279
  const merged: DbClientSshConfig = {
277
280
  enabled: existing.ssh_enabled === 1,
281
+ connectionId: existing.ssh_connection_id,
278
282
  host: existing.ssh_host ?? '',
279
283
  port: existing.ssh_port ?? 22,
280
284
  username: existing.ssh_username ?? '',
@@ -296,6 +300,7 @@ export const dbClientConnectionQueries = {
296
300
  push('ssh_password', sshPassword);
297
301
  push('ssh_private_key', sshPrivateKey);
298
302
  push('ssh_passphrase', sshPassphrase);
303
+ push('ssh_connection_id', merged.connectionId || null);
299
304
  }
300
305
 
301
306
  push('updated_at', new Date().toISOString());
@@ -26,6 +26,7 @@ export interface FileAuditLogEntry {
26
26
 
27
27
  export type FileAuditAction =
28
28
  | 'upload'
29
+ | 'download'
29
30
  | 'delete'
30
31
  | 'move'
31
32
  | 'rename'
@@ -10,6 +10,9 @@ export { engineQueries } from './engine-queries';
10
10
  export { authQueries } from './auth-queries';
11
11
  export { dbClientConnectionQueries } from './db-client-connection-queries';
12
12
  export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
+ export { sshConnectionQueries } from './ssh-connection-queries';
14
+ export { sshKnownHostQueries } from './ssh-known-host-queries';
15
+ export { sshPortForwardQueries } from './ssh-port-forward-queries';
13
16
  export { auditLogQueries } from './audit-log-queries';
14
17
  export { fileAuditLogQueries } from './file-audit-log-queries';
15
18
  export { mcpServerQueries } from './mcp-server-queries';
@@ -0,0 +1,244 @@
1
+ import { getDatabase } from '../index';
2
+ import type { DBSshConnectionRow } from '$shared/types/database/schema';
3
+ import type { SshAuthMethod, SshConnection, SshConnectionInput } from '$shared/types/ssh';
4
+
5
+ function rowToConnection(row: DBSshConnectionRow): SshConnection {
6
+ return {
7
+ id: row.id,
8
+ name: row.name,
9
+ host: row.host,
10
+ port: row.port,
11
+ username: row.username,
12
+ authMethod: row.auth_method as SshAuthMethod,
13
+ password: row.password,
14
+ privateKey: row.private_key,
15
+ privateKeyPath: row.private_key_path,
16
+ passphrase: row.passphrase,
17
+ agentSocket: row.agent_socket,
18
+ jumpConnectionId: row.jump_connection_id,
19
+ initialPath: row.initial_path,
20
+ keepaliveSeconds: row.keepalive_seconds,
21
+ strictHostKey: row.strict_host_key === 1,
22
+ color: row.color,
23
+ createdAt: row.created_at,
24
+ updatedAt: row.updated_at,
25
+ lastUsedAt: row.last_used_at
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Strip every secret before a connection leaves the server. The client only
31
+ * ever needs to know *whether* a credential is set, which it infers from the
32
+ * auth method — mirrors db-client's redactConnectionSecrets.
33
+ */
34
+ function redactConnectionSecrets(connection: SshConnection): SshConnection {
35
+ return {
36
+ ...connection,
37
+ password: null,
38
+ privateKey: null,
39
+ passphrase: null
40
+ };
41
+ }
42
+
43
+ function hasConnectionAccess(row: DBSshConnectionRow, userId: string, isAdmin: boolean): boolean {
44
+ if (isAdmin) return true;
45
+ return row.owner_user_id === userId;
46
+ }
47
+
48
+ /**
49
+ * An empty string in a patch means "the form did not re-send this secret",
50
+ * not "clear it" — otherwise editing the name of a key-authenticated host
51
+ * would wipe the key.
52
+ */
53
+ function preserveExistingSecret(patchValue: string | undefined, existingValue: string | null): string | null {
54
+ if (patchValue === undefined || patchValue === '') return existingValue;
55
+ return patchValue;
56
+ }
57
+
58
+ function getRowById(id: string): DBSshConnectionRow | null {
59
+ const db = getDatabase();
60
+ return db.prepare('SELECT * FROM ssh_connections WHERE id = ?').get(id) as DBSshConnectionRow | null;
61
+ }
62
+
63
+ /**
64
+ * True when adding `jumpConnectionId` as `connectionId`'s bastion would create
65
+ * a cycle (A jumps through B which jumps back through A). Walking the chain is
66
+ * cheap and stops an unbounded connect loop at save time rather than at dial time.
67
+ */
68
+ function wouldCycle(connectionId: string, jumpConnectionId: string | null): boolean {
69
+ let cursor = jumpConnectionId;
70
+ const visited = new Set<string>([connectionId]);
71
+ while (cursor) {
72
+ if (visited.has(cursor)) return true;
73
+ visited.add(cursor);
74
+ cursor = getRowById(cursor)?.jump_connection_id ?? null;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ function insertConnection(input: SshConnectionInput, ownerUserId: string | null): SshConnection {
80
+ const db = getDatabase();
81
+ const id = crypto.randomUUID();
82
+ const now = new Date().toISOString();
83
+
84
+ db.prepare(`
85
+ INSERT INTO ssh_connections (
86
+ id, name, host, port, username, auth_method,
87
+ password, private_key, private_key_path, passphrase, agent_socket,
88
+ jump_connection_id, initial_path, keepalive_seconds, strict_host_key,
89
+ color, owner_user_id, created_at, updated_at, last_used_at
90
+ ) VALUES (
91
+ ?, ?, ?, ?, ?, ?,
92
+ ?, ?, ?, ?, ?,
93
+ ?, ?, ?, ?,
94
+ ?, ?, ?, ?, ?
95
+ )
96
+ `).run(
97
+ id,
98
+ input.name,
99
+ input.host,
100
+ input.port ?? 22,
101
+ input.username,
102
+ input.authMethod ?? 'password',
103
+ input.password || null,
104
+ input.privateKey || null,
105
+ input.privateKeyPath || null,
106
+ input.passphrase || null,
107
+ input.agentSocket || null,
108
+ input.jumpConnectionId || null,
109
+ input.initialPath || null,
110
+ input.keepaliveSeconds ?? 30,
111
+ input.strictHostKey === false ? 0 : 1,
112
+ input.color || null,
113
+ ownerUserId,
114
+ now,
115
+ now,
116
+ null
117
+ );
118
+
119
+ const row = getRowById(id);
120
+ if (!row) throw new Error('ssh connection not found');
121
+ return rowToConnection(row);
122
+ }
123
+
124
+ export const sshConnectionQueries = {
125
+ listForUser(userId: string, isAdmin: boolean): SshConnection[] {
126
+ const db = getDatabase();
127
+ const rows = (isAdmin
128
+ ? db.prepare(`
129
+ SELECT * FROM ssh_connections
130
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
131
+ `).all()
132
+ : db.prepare(`
133
+ SELECT * FROM ssh_connections
134
+ WHERE owner_user_id = ?
135
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
136
+ `).all(userId)) as DBSshConnectionRow[];
137
+
138
+ return rows.map((row) => redactConnectionSecrets(rowToConnection(row)));
139
+ },
140
+
141
+ getForUser(id: string, userId: string, isAdmin: boolean): SshConnection | null {
142
+ const row = getRowById(id);
143
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) return null;
144
+ return redactConnectionSecrets(rowToConnection(row));
145
+ },
146
+
147
+ /** Full connection including secrets — server-side callers only. Throws on denial. */
148
+ ensureAccess(id: string, userId: string, isAdmin: boolean): SshConnection {
149
+ const row = getRowById(id);
150
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) {
151
+ throw new Error('ssh connection not found');
152
+ }
153
+ return rowToConnection(row);
154
+ },
155
+
156
+ get(id: string): SshConnection | null {
157
+ const row = getRowById(id);
158
+ return row ? rowToConnection(row) : null;
159
+ },
160
+
161
+ createForUser(input: SshConnectionInput, ownerUserId: string): SshConnection {
162
+ if (input.jumpConnectionId && !getRowById(input.jumpConnectionId)) {
163
+ throw new Error('Jump host not found');
164
+ }
165
+ return redactConnectionSecrets(insertConnection(input, ownerUserId));
166
+ },
167
+
168
+ update(id: string, patch: Partial<SshConnectionInput>): SshConnection {
169
+ const db = getDatabase();
170
+ const existing = getRowById(id);
171
+ if (!existing) throw new Error('ssh connection not found');
172
+
173
+ const sets: string[] = [];
174
+ const values: unknown[] = [];
175
+ const push = (column: string, value: unknown): void => {
176
+ sets.push(`${column} = ?`);
177
+ values.push(value);
178
+ };
179
+
180
+ if (patch.name !== undefined) push('name', patch.name);
181
+ if (patch.host !== undefined) push('host', patch.host);
182
+ if (patch.port !== undefined) push('port', patch.port ?? 22);
183
+ if (patch.username !== undefined) push('username', patch.username);
184
+ if (patch.authMethod !== undefined) push('auth_method', patch.authMethod);
185
+ if (patch.privateKeyPath !== undefined) push('private_key_path', patch.privateKeyPath || null);
186
+ if (patch.agentSocket !== undefined) push('agent_socket', patch.agentSocket || null);
187
+ if (patch.initialPath !== undefined) push('initial_path', patch.initialPath || null);
188
+ if (patch.keepaliveSeconds !== undefined) push('keepalive_seconds', patch.keepaliveSeconds ?? 30);
189
+ if (patch.strictHostKey !== undefined) push('strict_host_key', patch.strictHostKey ? 1 : 0);
190
+ if (patch.color !== undefined) push('color', patch.color || null);
191
+
192
+ if (patch.jumpConnectionId !== undefined) {
193
+ const jumpConnectionId = patch.jumpConnectionId || null;
194
+ if (jumpConnectionId && !getRowById(jumpConnectionId)) {
195
+ throw new Error('Jump host not found');
196
+ }
197
+ if (jumpConnectionId === id) {
198
+ throw new Error('A host cannot jump through itself');
199
+ }
200
+ if (wouldCycle(id, jumpConnectionId)) {
201
+ throw new Error('That jump host would create a loop');
202
+ }
203
+ push('jump_connection_id', jumpConnectionId);
204
+ }
205
+
206
+ if (patch.password !== undefined) push('password', preserveExistingSecret(patch.password, existing.password));
207
+ if (patch.privateKey !== undefined) push('private_key', preserveExistingSecret(patch.privateKey, existing.private_key));
208
+ if (patch.passphrase !== undefined) push('passphrase', preserveExistingSecret(patch.passphrase, existing.passphrase));
209
+
210
+ push('updated_at', new Date().toISOString());
211
+
212
+ values.push(id);
213
+ db.prepare(`UPDATE ssh_connections SET ${sets.join(', ')} WHERE id = ?`).run(...values);
214
+
215
+ const row = getRowById(id);
216
+ if (!row) throw new Error('ssh connection not found');
217
+ return rowToConnection(row);
218
+ },
219
+
220
+ updateForUser(
221
+ id: string,
222
+ patch: Partial<SshConnectionInput>,
223
+ userId: string,
224
+ isAdmin: boolean
225
+ ): SshConnection {
226
+ this.ensureAccess(id, userId, isAdmin);
227
+ return redactConnectionSecrets(this.update(id, patch));
228
+ },
229
+
230
+ delete(id: string): void {
231
+ const db = getDatabase();
232
+ db.prepare('DELETE FROM ssh_connections WHERE id = ?').run(id);
233
+ },
234
+
235
+ deleteForUser(id: string, userId: string, isAdmin: boolean): void {
236
+ this.ensureAccess(id, userId, isAdmin);
237
+ this.delete(id);
238
+ },
239
+
240
+ markUsed(id: string): void {
241
+ const db = getDatabase();
242
+ db.prepare('UPDATE ssh_connections SET last_used_at = ? WHERE id = ?').run(new Date().toISOString(), id);
243
+ }
244
+ };
@@ -0,0 +1,67 @@
1
+ import { getDatabase } from '../index';
2
+ import type { DBSshKnownHostRow } from '$shared/types/database/schema';
3
+ import type { SshKnownHost } from '$shared/types/ssh';
4
+
5
+ function rowToKnownHost(row: DBSshKnownHostRow): SshKnownHost {
6
+ return {
7
+ id: row.id,
8
+ host: row.host,
9
+ port: row.port,
10
+ keyType: row.key_type,
11
+ fingerprint: row.fingerprint,
12
+ addedAt: row.added_at,
13
+ lastSeenAt: row.last_seen_at
14
+ };
15
+ }
16
+
17
+ export const sshKnownHostQueries = {
18
+ list(): SshKnownHost[] {
19
+ const db = getDatabase();
20
+ const rows = db.prepare(`
21
+ SELECT * FROM ssh_known_hosts ORDER BY host ASC, port ASC
22
+ `).all() as DBSshKnownHostRow[];
23
+ return rows.map(rowToKnownHost);
24
+ },
25
+
26
+ find(host: string, port: number): SshKnownHost | null {
27
+ const db = getDatabase();
28
+ const row = db.prepare(`
29
+ SELECT * FROM ssh_known_hosts WHERE host = ? AND port = ?
30
+ `).get(host, port) as DBSshKnownHostRow | null;
31
+ return row ? rowToKnownHost(row) : null;
32
+ },
33
+
34
+ /**
35
+ * Record the key a host presented, replacing any previous one. Used both for
36
+ * trust-on-first-use and for an explicit "trust the new key" after a change.
37
+ */
38
+ trust(host: string, port: number, keyType: string, fingerprint: string): SshKnownHost {
39
+ const db = getDatabase();
40
+ const now = new Date().toISOString();
41
+ db.prepare(`
42
+ INSERT INTO ssh_known_hosts (id, host, port, key_type, fingerprint, added_at, last_seen_at)
43
+ VALUES (?, ?, ?, ?, ?, ?, ?)
44
+ ON CONFLICT (host, port) DO UPDATE SET
45
+ key_type = excluded.key_type,
46
+ fingerprint = excluded.fingerprint,
47
+ added_at = excluded.added_at,
48
+ last_seen_at = excluded.last_seen_at
49
+ `).run(crypto.randomUUID(), host, port, keyType, fingerprint, now, now);
50
+
51
+ const saved = this.find(host, port);
52
+ if (!saved) throw new Error('Failed to record host key');
53
+ return saved;
54
+ },
55
+
56
+ markSeen(host: string, port: number): void {
57
+ const db = getDatabase();
58
+ db.prepare(`
59
+ UPDATE ssh_known_hosts SET last_seen_at = ? WHERE host = ? AND port = ?
60
+ `).run(new Date().toISOString(), host, port);
61
+ },
62
+
63
+ forget(host: string, port: number): void {
64
+ const db = getDatabase();
65
+ db.prepare('DELETE FROM ssh_known_hosts WHERE host = ? AND port = ?').run(host, port);
66
+ }
67
+ };
@@ -0,0 +1,113 @@
1
+ import { getDatabase } from '../index';
2
+ import type { DBSshPortForwardRow } from '$shared/types/database/schema';
3
+ import type { SshForward, SshForwardInput, SshForwardType } from '$shared/types/ssh';
4
+
5
+ function rowToForward(row: DBSshPortForwardRow): SshForward {
6
+ return {
7
+ id: row.id,
8
+ connectionId: row.connection_id,
9
+ name: row.name,
10
+ type: row.type as SshForwardType,
11
+ listenHost: row.listen_host,
12
+ listenPort: row.listen_port,
13
+ destHost: row.dest_host,
14
+ destPort: row.dest_port,
15
+ autoStart: row.auto_start === 1,
16
+ createdAt: row.created_at,
17
+ updatedAt: row.updated_at
18
+ };
19
+ }
20
+
21
+ function getRowById(id: string): DBSshPortForwardRow | null {
22
+ const db = getDatabase();
23
+ return db.prepare('SELECT * FROM ssh_port_forwards WHERE id = ?').get(id) as DBSshPortForwardRow | null;
24
+ }
25
+
26
+ export const sshPortForwardQueries = {
27
+ listForConnection(connectionId: string): SshForward[] {
28
+ const db = getDatabase();
29
+ const rows = db.prepare(`
30
+ SELECT * FROM ssh_port_forwards WHERE connection_id = ? ORDER BY created_at ASC
31
+ `).all(connectionId) as DBSshPortForwardRow[];
32
+ return rows.map(rowToForward);
33
+ },
34
+
35
+ get(id: string): SshForward | null {
36
+ const row = getRowById(id);
37
+ return row ? rowToForward(row) : null;
38
+ },
39
+
40
+ create(connectionId: string, input: SshForwardInput): SshForward {
41
+ const db = getDatabase();
42
+ const id = crypto.randomUUID();
43
+ const now = new Date().toISOString();
44
+
45
+ db.prepare(`
46
+ INSERT INTO ssh_port_forwards (
47
+ id, connection_id, name, type,
48
+ listen_host, listen_port, dest_host, dest_port,
49
+ auto_start, created_at, updated_at
50
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
51
+ `).run(
52
+ id,
53
+ connectionId,
54
+ input.name,
55
+ input.type,
56
+ input.listenHost || '127.0.0.1',
57
+ input.listenPort,
58
+ input.type === 'dynamic' ? null : (input.destHost || null),
59
+ input.type === 'dynamic' ? null : (input.destPort ?? null),
60
+ input.autoStart ? 1 : 0,
61
+ now,
62
+ now
63
+ );
64
+
65
+ const created = this.get(id);
66
+ if (!created) throw new Error('ssh port forward not found');
67
+ return created;
68
+ },
69
+
70
+ update(id: string, patch: Partial<SshForwardInput>): SshForward {
71
+ const db = getDatabase();
72
+ const existing = getRowById(id);
73
+ if (!existing) throw new Error('ssh port forward not found');
74
+
75
+ const sets: string[] = [];
76
+ const values: unknown[] = [];
77
+ const push = (column: string, value: unknown): void => {
78
+ sets.push(`${column} = ?`);
79
+ values.push(value);
80
+ };
81
+
82
+ const type = (patch.type ?? existing.type) as SshForwardType;
83
+
84
+ if (patch.name !== undefined) push('name', patch.name);
85
+ if (patch.type !== undefined) push('type', patch.type);
86
+ if (patch.listenHost !== undefined) push('listen_host', patch.listenHost || '127.0.0.1');
87
+ if (patch.listenPort !== undefined) push('listen_port', patch.listenPort);
88
+ // A dynamic forward has no fixed destination; clear it so a type switch
89
+ // never leaves a stale host:port behind.
90
+ if (type === 'dynamic') {
91
+ push('dest_host', null);
92
+ push('dest_port', null);
93
+ } else {
94
+ if (patch.destHost !== undefined) push('dest_host', patch.destHost || null);
95
+ if (patch.destPort !== undefined) push('dest_port', patch.destPort ?? null);
96
+ }
97
+ if (patch.autoStart !== undefined) push('auto_start', patch.autoStart ? 1 : 0);
98
+
99
+ push('updated_at', new Date().toISOString());
100
+
101
+ values.push(id);
102
+ db.prepare(`UPDATE ssh_port_forwards SET ${sets.join(', ')} WHERE id = ?`).run(...values);
103
+
104
+ const updated = this.get(id);
105
+ if (!updated) throw new Error('ssh port forward not found');
106
+ return updated;
107
+ },
108
+
109
+ delete(id: string): void {
110
+ const db = getDatabase();
111
+ db.prepare('DELETE FROM ssh_port_forwards WHERE id = ?').run(id);
112
+ }
113
+ };
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { dbClientConnectionQueries } from '../database/queries';
10
10
  import { openSshTunnel, type SshTunnel } from './ssh-tunnel';
11
+ import { openTunnelViaSavedConnection } from '../ssh/tunnel';
11
12
  import { MysqlAdapter } from './drivers/mysql';
12
13
  import { PostgresAdapter } from './drivers/postgres';
13
14
  import { SqliteAdapter } from './drivers/sqlite';
@@ -72,7 +73,12 @@ class ConnectionManager {
72
73
  if (conn.ssh.enabled && conn.driver !== 'sqlite') {
73
74
  const remoteHost = conn.host || '127.0.0.1';
74
75
  const remotePort = conn.port ?? defaultPortFor(conn.driver);
75
- tunnel = await openSshTunnel(conn.ssh, remoteHost, remotePort);
76
+ // Two modes: a saved SSH host from the SSH client (shared credentials,
77
+ // jump chain and trusted host key), or the credentials stored inline on
78
+ // this connection. The inline path is what every existing connection uses.
79
+ tunnel = conn.ssh.connectionId
80
+ ? await openTunnelViaSavedConnection(conn.ssh.connectionId, remoteHost, remotePort)
81
+ : await openSshTunnel(conn.ssh, remoteHost, remotePort);
76
82
  }
77
83
 
78
84
  try {
@@ -250,6 +256,7 @@ function inputToConnection(input: DbClientConnectionInput): DbClientConnection {
250
256
  sslCa: input.sslCa ?? null,
251
257
  ssh: {
252
258
  enabled: input.ssh?.enabled ?? false,
259
+ connectionId: input.ssh?.connectionId ?? null,
253
260
  host: input.ssh?.host ?? '',
254
261
  port: input.ssh?.port ?? 22,
255
262
  username: input.ssh?.username ?? '',