@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
@@ -0,0 +1,214 @@
1
+ /**
2
+ * ssh-client — how much space the account actually has.
3
+ *
4
+ * `df` answers a different question from the one the user is asking. On shared
5
+ * hosting it reports the whole underlying filesystem: a cPanel account capped
6
+ * at 5 GB sits on a 762 GB volume, so `df` cheerfully reports ~195 GB free
7
+ * while the account is at 74% and about to stop accepting writes.
8
+ *
9
+ * So the account's own limit is asked for first, and `df` is only the fallback
10
+ * — and whichever answered is reported alongside the numbers, because "3.7 of
11
+ * 5 GB used (account quota)" and "195 GB free (filesystem)" are both true and
12
+ * only one of them is useful.
13
+ */
14
+
15
+ import type { Client as SshClient } from 'ssh2';
16
+ import { runCommandDetailed, shellQuote } from './connect';
17
+ import type { SftpDiskUsage, SftpUsageSource } from '$shared/types/ssh';
18
+ import { debug } from '$shared/utils/logger';
19
+
20
+ const MEGABYTE = 1024 * 1024;
21
+ const KILOBYTE = 1024;
22
+
23
+ function emptyUsage(path: string): SftpDiskUsage {
24
+ return {
25
+ path,
26
+ totalBytes: null,
27
+ usedBytes: null,
28
+ availableBytes: null,
29
+ source: 'unknown',
30
+ sourceLabel: 'Unknown',
31
+ inodesUsed: null,
32
+ inodeLimit: null
33
+ };
34
+ }
35
+
36
+ function labelFor(source: SftpUsageSource): string {
37
+ switch (source) {
38
+ case 'account-quota':
39
+ return 'Account quota';
40
+ case 'user-quota':
41
+ return 'User quota';
42
+ case 'filesystem':
43
+ return 'Filesystem';
44
+ default:
45
+ return 'Unknown';
46
+ }
47
+ }
48
+
49
+ function finite(value: unknown): number | null {
50
+ const asNumber = typeof value === 'string' ? Number(value) : value;
51
+ return typeof asNumber === 'number' && Number.isFinite(asNumber) ? asNumber : null;
52
+ }
53
+
54
+ /**
55
+ * cPanel's UAPI, which every cPanel account can call as itself. This is the
56
+ * number cPanel's own disk-usage widget shows, so matching it means Clopen and
57
+ * the control panel never disagree.
58
+ */
59
+ export function parseCpanelQuota(output: string, path: string): SftpDiskUsage | null {
60
+ if (!output) return null;
61
+ try {
62
+ const parsed = JSON.parse(output) as {
63
+ result?: {
64
+ status?: number;
65
+ data?: {
66
+ megabytes_used?: number | string;
67
+ megabyte_limit?: number | string;
68
+ megabytes_remain?: number | string;
69
+ inodes_used?: number | string;
70
+ inode_limit?: number | string;
71
+ };
72
+ };
73
+ };
74
+ const data = parsed.result?.data;
75
+ if (!data || parsed.result?.status !== 1) return null;
76
+
77
+ const usedMegabytes = finite(data.megabytes_used);
78
+ const limitMegabytes = finite(data.megabyte_limit);
79
+ if (usedMegabytes === null) return null;
80
+
81
+ // A limit of 0 means unlimited in cPanel, which is not a total we can
82
+ // render as a percentage — report the usage without one.
83
+ const hasLimit = limitMegabytes !== null && limitMegabytes > 0;
84
+ const remainMegabytes = finite(data.megabytes_remain);
85
+ const inodeLimit = finite(data.inode_limit);
86
+
87
+ return {
88
+ path,
89
+ usedBytes: Math.round(usedMegabytes * MEGABYTE),
90
+ totalBytes: hasLimit ? Math.round(limitMegabytes * MEGABYTE) : null,
91
+ availableBytes:
92
+ remainMegabytes !== null && hasLimit ? Math.round(remainMegabytes * MEGABYTE) : null,
93
+ source: 'account-quota',
94
+ sourceLabel: labelFor('account-quota'),
95
+ inodesUsed: finite(data.inodes_used),
96
+ inodeLimit: inodeLimit !== null && inodeLimit > 0 ? inodeLimit : null
97
+ };
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * POSIX filesystem quota, for a plain Linux box that has the `quota` tool.
105
+ * `-w` forces one line per filesystem, which is what makes this parseable.
106
+ */
107
+ export function parsePosixQuota(output: string, path: string): SftpDiskUsage | null {
108
+ if (!output) return null;
109
+ for (const line of output.split('\n')) {
110
+ // A data line starts with a device path; headers and the "Disk quotas for
111
+ // user…" preamble do not.
112
+ const trimmed = line.trim();
113
+ if (!trimmed.startsWith('/')) continue;
114
+
115
+ // filesystem blocks quota limit [grace] files quota limit [grace]
116
+ //
117
+ // The grace columns are printed only while over quota, so the position of
118
+ // everything after `limit` shifts depending on state. The block figures are
119
+ // before that ambiguity and are safe to read; the file count is not, and is
120
+ // left unreported rather than guessed at.
121
+ const columns = trimmed.replace(/\*/g, '').split(/\s+/);
122
+ if (columns.length < 4) continue;
123
+
124
+ const usedBlocks = finite(columns[1]);
125
+ const hardLimitBlocks = finite(columns[3]);
126
+ const softLimitBlocks = finite(columns[2]);
127
+ if (usedBlocks === null) continue;
128
+
129
+ // The hard limit is the real ceiling; fall back to the soft one, and treat
130
+ // 0 as "no limit set" exactly as the quota tools do.
131
+ const limitBlocks =
132
+ hardLimitBlocks && hardLimitBlocks > 0
133
+ ? hardLimitBlocks
134
+ : softLimitBlocks && softLimitBlocks > 0
135
+ ? softLimitBlocks
136
+ : null;
137
+ if (limitBlocks === null) return null;
138
+
139
+ const usedBytes = usedBlocks * KILOBYTE;
140
+ const totalBytes = limitBlocks * KILOBYTE;
141
+ return {
142
+ path,
143
+ usedBytes,
144
+ totalBytes,
145
+ availableBytes: Math.max(0, totalBytes - usedBytes),
146
+ source: 'user-quota',
147
+ sourceLabel: labelFor('user-quota'),
148
+ inodesUsed: null,
149
+ inodeLimit: null
150
+ };
151
+ }
152
+ return null;
153
+ }
154
+
155
+ /** The underlying filesystem. Right for a VPS, misleading on shared hosting. */
156
+ export function parseFilesystemUsage(output: string, path: string): SftpDiskUsage | null {
157
+ const dataLine = output.split('\n')[1];
158
+ if (!dataLine) return null;
159
+
160
+ const columns = dataLine.trim().split(/\s+/);
161
+ if (columns.length < 4) return null;
162
+
163
+ const totalBlocks = finite(columns[1]);
164
+ const usedBlocks = finite(columns[2]);
165
+ const availableBlocks = finite(columns[3]);
166
+ if (totalBlocks === null) return null;
167
+
168
+ return {
169
+ path,
170
+ totalBytes: totalBlocks * KILOBYTE,
171
+ usedBytes: usedBlocks === null ? null : usedBlocks * KILOBYTE,
172
+ availableBytes: availableBlocks === null ? null : availableBlocks * KILOBYTE,
173
+ source: 'filesystem',
174
+ sourceLabel: labelFor('filesystem'),
175
+ inodesUsed: null,
176
+ inodeLimit: null
177
+ };
178
+ }
179
+
180
+ /** A command to run and the parser that reads its output. */
181
+ interface UsageProbe {
182
+ command: string;
183
+ parse: (output: string, path: string) => SftpDiskUsage | null;
184
+ }
185
+
186
+ /**
187
+ * Ask each source in order of how well it answers the user's question, and
188
+ * return the first that does. A host where none of them work reports nulls
189
+ * rather than a number that is wrong.
190
+ */
191
+ export async function readDiskUsage(client: SshClient, path: string): Promise<SftpDiskUsage> {
192
+ const probes: UsageProbe[] = [
193
+ { command: 'uapi --output=json Quota get_quota_info', parse: parseCpanelQuota },
194
+ { command: 'quota -w 2>/dev/null', parse: parsePosixQuota },
195
+ { command: `df -Pk ${shellQuote(path)}`, parse: parseFilesystemUsage }
196
+ ];
197
+
198
+ for (const probe of probes) {
199
+ try {
200
+ const result = await runCommandDetailed(client, probe.command, 15_000);
201
+ // A non-zero exit is normal here: `uapi` and `quota` simply do not exist
202
+ // on most hosts, and that is the signal to try the next source.
203
+ if (result.code !== 0) continue;
204
+ const usage = probe.parse(result.stdout, path);
205
+ if (usage) return usage;
206
+ } catch (error) {
207
+ debug.warn(
208
+ 'ssh',
209
+ `disk usage probe failed: ${error instanceof Error ? error.message : String(error)}`
210
+ );
211
+ }
212
+ }
213
+ return emptyUsage(path);
214
+ }
@@ -0,0 +1,309 @@
1
+ /**
2
+ * ssh-client — port forwarding, in all three shapes OpenSSH offers.
3
+ *
4
+ * - local (-L) a TCP listener here; each connection becomes a channel to
5
+ * `dest` opened from the remote host.
6
+ * - remote (-R) the remote host listens; what arrives there is piped to a
7
+ * socket this process opens to `dest`.
8
+ * - dynamic (-D) a SOCKS5 listener here; the destination comes per request.
9
+ *
10
+ * A running forward holds a pool lease, so the shared transport stays up for as
11
+ * long as any forward on it is running, and stops being held the moment it is.
12
+ */
13
+
14
+ import net, { type Socket } from 'node:net';
15
+ import type { Client as SshClient } from 'ssh2';
16
+ import { sshPortForwardQueries } from '../database/queries';
17
+ import { sshClientPool, type SshLease } from './client-pool';
18
+ import { readSocksRequest, socksReply, SOCKS_REPLY_HOST_UNREACHABLE, SOCKS_REPLY_SUCCESS } from './socks5';
19
+ import type { SshForward, SshForwardStatus } from '$shared/types/ssh';
20
+ import { debug } from '$shared/utils/logger';
21
+
22
+ interface RunningForward {
23
+ forward: SshForward;
24
+ lease: SshLease;
25
+ /** Present for local and dynamic forwards; remote forwards listen remotely. */
26
+ server: net.Server | null;
27
+ boundPort: number;
28
+ connectionCount: number;
29
+ error: string | null;
30
+ /** Sockets currently piped, so stopping a forward also drops its traffic. */
31
+ sockets: Set<Socket>;
32
+ }
33
+
34
+ /**
35
+ * ssh2 emits one `tcp connection` event per client for every remote forward on
36
+ * it, so a shared transport needs a dispatcher rather than one listener per
37
+ * forward. Keyed by connection id; the inner map is keyed by remote port.
38
+ */
39
+ type RemoteRouter = Map<number, RunningForward>;
40
+
41
+ function pipeSockets(local: NodeJS.ReadWriteStream, remote: NodeJS.ReadWriteStream): void {
42
+ local.pipe(remote);
43
+ remote.pipe(local);
44
+ const drop = (): void => {
45
+ // Destroying both ends on either failure avoids a half-open pair that
46
+ // holds a channel open forever.
47
+ (local as Socket).destroy?.();
48
+ (remote as Socket).destroy?.();
49
+ };
50
+ local.on('error', drop);
51
+ remote.on('error', drop);
52
+ }
53
+
54
+ class SshForwardManager {
55
+ private running = new Map<string, RunningForward>();
56
+ private remoteRouters = new Map<string, RemoteRouter>();
57
+ private remoteListenerInstalled = new Set<string>();
58
+
59
+ isRunning(forwardId: string): boolean {
60
+ return this.running.has(forwardId);
61
+ }
62
+
63
+ status(forward: SshForward): SshForwardStatus {
64
+ const active = this.running.get(forward.id);
65
+ if (!active) {
66
+ return { id: forward.id, running: false, boundPort: null, connectionCount: 0, error: null };
67
+ }
68
+ return {
69
+ id: forward.id,
70
+ running: true,
71
+ boundPort: active.boundPort,
72
+ connectionCount: active.connectionCount,
73
+ error: active.error
74
+ };
75
+ }
76
+
77
+ statusesForConnection(connectionId: string): SshForwardStatus[] {
78
+ return sshPortForwardQueries.listForConnection(connectionId).map((forward) => this.status(forward));
79
+ }
80
+
81
+ /** Start every forward on a host that is marked auto-start and is not up yet. */
82
+ async startAutoForwards(connectionId: string): Promise<void> {
83
+ const forwards = sshPortForwardQueries.listForConnection(connectionId);
84
+ for (const forward of forwards) {
85
+ if (!forward.autoStart || this.isRunning(forward.id)) continue;
86
+ try {
87
+ await this.start(forward);
88
+ } catch (error) {
89
+ debug.warn(
90
+ 'ssh',
91
+ `auto-start failed for forward ${forward.name}: ${error instanceof Error ? error.message : String(error)}`
92
+ );
93
+ }
94
+ }
95
+ }
96
+
97
+ async start(forward: SshForward): Promise<SshForwardStatus> {
98
+ if (this.running.has(forward.id)) {
99
+ return this.status(forward);
100
+ }
101
+
102
+ const lease = await sshClientPool.acquire(forward.connectionId);
103
+ const active: RunningForward = {
104
+ forward,
105
+ lease,
106
+ server: null,
107
+ boundPort: forward.listenPort,
108
+ connectionCount: 0,
109
+ error: null,
110
+ sockets: new Set()
111
+ };
112
+
113
+ try {
114
+ if (forward.type === 'remote') {
115
+ await this.startRemote(active, lease.client);
116
+ } else {
117
+ await this.startLocalListener(active, lease.client);
118
+ }
119
+ } catch (error) {
120
+ lease.release();
121
+ throw error;
122
+ }
123
+
124
+ this.running.set(forward.id, active);
125
+ debug.log('ssh', `forward ${forward.name} (${forward.type}) started on port ${active.boundPort}`);
126
+ return this.status(forward);
127
+ }
128
+
129
+ /** Local and dynamic both listen here; only what happens per socket differs. */
130
+ private async startLocalListener(active: RunningForward, client: SshClient): Promise<void> {
131
+ const { forward } = active;
132
+
133
+ const server = net.createServer((socket) => {
134
+ active.sockets.add(socket);
135
+ socket.on('close', () => active.sockets.delete(socket));
136
+
137
+ if (forward.type === 'dynamic') {
138
+ void this.handleSocksSocket(active, client, socket);
139
+ return;
140
+ }
141
+
142
+ active.connectionCount++;
143
+ client.forwardOut(
144
+ socket.remoteAddress ?? '127.0.0.1',
145
+ socket.remotePort ?? 0,
146
+ forward.destHost ?? '127.0.0.1',
147
+ forward.destPort ?? 0,
148
+ (error, stream) => {
149
+ if (error) {
150
+ active.error = error.message;
151
+ socket.destroy();
152
+ return;
153
+ }
154
+ pipeSockets(socket, stream);
155
+ }
156
+ );
157
+ });
158
+
159
+ server.on('error', (error: Error) => {
160
+ active.error = error.message;
161
+ });
162
+
163
+ await new Promise<void>((resolvePromise, rejectPromise) => {
164
+ server.once('error', rejectPromise);
165
+ server.listen(forward.listenPort, forward.listenHost || '127.0.0.1', () => {
166
+ server.removeListener('error', rejectPromise);
167
+ const address = server.address();
168
+ if (address && typeof address === 'object') {
169
+ active.boundPort = address.port;
170
+ }
171
+ resolvePromise();
172
+ });
173
+ });
174
+
175
+ active.server = server;
176
+ }
177
+
178
+ private async handleSocksSocket(active: RunningForward, client: SshClient, socket: Socket): Promise<void> {
179
+ let request;
180
+ try {
181
+ request = await readSocksRequest(socket);
182
+ } catch (error) {
183
+ active.error = error instanceof Error ? error.message : String(error);
184
+ socket.destroy();
185
+ return;
186
+ }
187
+
188
+ active.connectionCount++;
189
+ client.forwardOut(
190
+ socket.remoteAddress ?? '127.0.0.1',
191
+ socket.remotePort ?? 0,
192
+ request.host,
193
+ request.port,
194
+ (error, stream) => {
195
+ if (error) {
196
+ active.error = error.message;
197
+ if (socket.writable) socket.end(socksReply(SOCKS_REPLY_HOST_UNREACHABLE));
198
+ return;
199
+ }
200
+ socket.write(socksReply(SOCKS_REPLY_SUCCESS));
201
+ pipeSockets(socket, stream);
202
+ }
203
+ );
204
+ }
205
+
206
+ private async startRemote(active: RunningForward, client: SshClient): Promise<void> {
207
+ const { forward } = active;
208
+ this.installRemoteListener(forward.connectionId, client);
209
+
210
+ const boundPort = await new Promise<number>((resolvePromise, rejectPromise) => {
211
+ client.forwardIn(forward.listenHost || '127.0.0.1', forward.listenPort, (error, port) => {
212
+ if (error) {
213
+ rejectPromise(new Error(`The host refused to listen on ${forward.listenPort}: ${error.message}`));
214
+ return;
215
+ }
216
+ // Port 0 asks the host to choose; it reports the real one back.
217
+ resolvePromise(forward.listenPort === 0 ? port : forward.listenPort);
218
+ });
219
+ });
220
+
221
+ active.boundPort = boundPort;
222
+
223
+ const router = this.remoteRouters.get(forward.connectionId) ?? new Map<number, RunningForward>();
224
+ router.set(boundPort, active);
225
+ this.remoteRouters.set(forward.connectionId, router);
226
+ }
227
+
228
+ /**
229
+ * One `tcp connection` handler per transport, dispatching by the port the
230
+ * remote side accepted on. Installed once — a second `client.on` per forward
231
+ * would deliver every connection to every forward.
232
+ */
233
+ private installRemoteListener(connectionId: string, client: SshClient): void {
234
+ if (this.remoteListenerInstalled.has(connectionId)) return;
235
+ this.remoteListenerInstalled.add(connectionId);
236
+
237
+ client.on('tcp connection', (info, accept, reject) => {
238
+ const router = this.remoteRouters.get(connectionId);
239
+ const active = router?.get(info.destPort);
240
+ if (!active) {
241
+ reject();
242
+ return;
243
+ }
244
+
245
+ active.connectionCount++;
246
+ const stream = accept();
247
+ const socket = net.connect(
248
+ active.forward.destPort ?? 0,
249
+ active.forward.destHost ?? '127.0.0.1',
250
+ () => pipeSockets(socket, stream)
251
+ );
252
+ active.sockets.add(socket);
253
+ socket.on('close', () => active.sockets.delete(socket));
254
+ socket.on('error', (error: Error) => {
255
+ active.error = error.message;
256
+ stream.destroy();
257
+ });
258
+ });
259
+
260
+ // The transport can drop underneath us; forget the bookkeeping so a later
261
+ // start reinstalls the handler on the new client.
262
+ const forget = (): void => {
263
+ this.remoteListenerInstalled.delete(connectionId);
264
+ this.remoteRouters.delete(connectionId);
265
+ };
266
+ client.on('close', forget);
267
+ client.on('end', forget);
268
+ }
269
+
270
+ async stop(forwardId: string): Promise<void> {
271
+ const active = this.running.get(forwardId);
272
+ if (!active) return;
273
+ this.running.delete(forwardId);
274
+
275
+ for (const socket of active.sockets) socket.destroy();
276
+ active.sockets.clear();
277
+
278
+ if (active.server) {
279
+ await new Promise<void>((resolvePromise) => active.server?.close(() => resolvePromise()));
280
+ }
281
+
282
+ if (active.forward.type === 'remote') {
283
+ const router = this.remoteRouters.get(active.forward.connectionId);
284
+ router?.delete(active.boundPort);
285
+ try {
286
+ active.lease.client.unforwardIn(active.forward.listenHost || '127.0.0.1', active.boundPort);
287
+ } catch {
288
+ // The transport may already be gone; the remote listener dies with it.
289
+ }
290
+ }
291
+
292
+ active.lease.release();
293
+ debug.log('ssh', `forward ${active.forward.name} stopped`);
294
+ }
295
+
296
+ /** Stop every forward belonging to a host. Used on edit, delete and shutdown. */
297
+ async stopForConnection(connectionId: string): Promise<void> {
298
+ const ids = [...this.running.values()]
299
+ .filter((active) => active.forward.connectionId === connectionId)
300
+ .map((active) => active.forward.id);
301
+ for (const id of ids) await this.stop(id);
302
+ }
303
+
304
+ async stopAll(): Promise<void> {
305
+ for (const id of [...this.running.keys()]) await this.stop(id);
306
+ }
307
+ }
308
+
309
+ export const sshForwardManager = new SshForwardManager();
@@ -0,0 +1,141 @@
1
+ /**
2
+ * ssh-client — the "does this host actually work" probe behind the Test button.
3
+ *
4
+ * A saved connection is probed on its pooled transport so Test doubles as a
5
+ * live status check. Unsaved form input is dialed once and dropped, which is
6
+ * what makes Test useful before the first save.
7
+ */
8
+
9
+ import type { Client as SshClient } from 'ssh2';
10
+ import { sshConnectionQueries } from '../database/queries';
11
+ import { sshClientPool } from './client-pool';
12
+ import { closeChain, dial, HostKeyChangedError, runCommand } from './connect';
13
+ import { knownHosts } from './known-hosts';
14
+ import type { SshConnection, SshConnectionInput, SshHealth } from '$shared/types/ssh';
15
+ import { debug } from '$shared/utils/logger';
16
+
17
+ function failure(error: unknown, hostKeyFingerprint: string | null): SshHealth {
18
+ const changed = error instanceof HostKeyChangedError;
19
+ return {
20
+ ok: false,
21
+ latencyMs: null,
22
+ serverBanner: null,
23
+ remoteOs: null,
24
+ hostKeyFingerprint: changed ? error.verdict.identity.fingerprint : hostKeyFingerprint,
25
+ hostKeyChanged: changed,
26
+ suspended: false,
27
+ error: error instanceof Error ? error.message : String(error)
28
+ };
29
+ }
30
+
31
+ /** Shape unsaved form input as a connection so one dial path serves both. */
32
+ export function inputToConnection(input: SshConnectionInput): SshConnection {
33
+ const now = new Date().toISOString();
34
+ return {
35
+ id: 'transient',
36
+ name: input.name,
37
+ host: input.host,
38
+ port: input.port ?? 22,
39
+ username: input.username,
40
+ authMethod: input.authMethod ?? 'password',
41
+ password: input.password ?? null,
42
+ privateKey: input.privateKey ?? null,
43
+ privateKeyPath: input.privateKeyPath ?? null,
44
+ passphrase: input.passphrase ?? null,
45
+ agentSocket: input.agentSocket ?? null,
46
+ jumpConnectionId: input.jumpConnectionId ?? null,
47
+ initialPath: input.initialPath ?? null,
48
+ keepaliveSeconds: input.keepaliveSeconds ?? 30,
49
+ strictHostKey: input.strictHostKey !== false,
50
+ color: input.color ?? null,
51
+ createdAt: now,
52
+ updatedAt: now,
53
+ lastUsedAt: null
54
+ };
55
+ }
56
+
57
+ /** `uname -sr`, best effort — a host that refuses `exec` still counts as healthy. */
58
+ async function probeRemoteOs(client: SshClient): Promise<string | null> {
59
+ try {
60
+ const output = await runCommand(client, 'uname -sr');
61
+ return output || null;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ async function testTransient(connection: SshConnection): Promise<SshHealth> {
68
+ const known = knownHosts.find(connection.host, connection.port);
69
+ const startedAt = Date.now();
70
+ let dialed = null;
71
+ try {
72
+ dialed = await dial(connection);
73
+ const latencyMs = Date.now() - startedAt;
74
+ const remoteOs = await probeRemoteOs(dialed.client);
75
+ return {
76
+ ok: true,
77
+ latencyMs,
78
+ serverBanner: dialed.serverBanner,
79
+ remoteOs,
80
+ hostKeyFingerprint: dialed.hostKey.identity.fingerprint,
81
+ hostKeyChanged: false,
82
+ suspended: false,
83
+ error: null
84
+ };
85
+ } catch (error) {
86
+ debug.warn('ssh', `test failed for ${connection.host}: ${error instanceof Error ? error.message : error}`);
87
+ return failure(error, known?.fingerprint ?? null);
88
+ } finally {
89
+ if (dialed) closeChain(dialed.chain);
90
+ }
91
+ }
92
+
93
+ export const sshHealthService = {
94
+ /** Probe a saved host over its pooled transport. */
95
+ async testSaved(connectionId: string): Promise<SshHealth> {
96
+ const connection = sshConnectionQueries.get(connectionId);
97
+ if (!connection) {
98
+ return failure(new Error('ssh connection not found'), null);
99
+ }
100
+ // A host the user disconnected is reported as such rather than redialed —
101
+ // probing it would defeat the Disconnect button.
102
+ if (sshClientPool.isSuspended(connectionId)) {
103
+ return {
104
+ ok: false,
105
+ latencyMs: null,
106
+ serverBanner: null,
107
+ remoteOs: null,
108
+ hostKeyFingerprint: knownHosts.find(connection.host, connection.port)?.fingerprint ?? null,
109
+ hostKeyChanged: false,
110
+ suspended: true,
111
+ error: null
112
+ };
113
+ }
114
+
115
+ const known = knownHosts.find(connection.host, connection.port);
116
+ const startedAt = Date.now();
117
+ try {
118
+ return await sshClientPool.use(connectionId, async (client) => {
119
+ const latencyMs = Date.now() - startedAt;
120
+ const remoteOs = await probeRemoteOs(client);
121
+ return {
122
+ ok: true,
123
+ latencyMs,
124
+ serverBanner: null,
125
+ remoteOs,
126
+ hostKeyFingerprint: knownHosts.find(connection.host, connection.port)?.fingerprint ?? null,
127
+ hostKeyChanged: false,
128
+ suspended: false,
129
+ error: null
130
+ };
131
+ });
132
+ } catch (error) {
133
+ return failure(error, known?.fingerprint ?? null);
134
+ }
135
+ },
136
+
137
+ /** Probe unsaved form input, without touching the pool. */
138
+ testInput(input: SshConnectionInput): Promise<SshHealth> {
139
+ return testTransient(inputToConnection(input));
140
+ }
141
+ };