@myrialabs/clopen 0.4.32 → 0.4.34

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 (102) hide show
  1. package/backend/auth/permissions.ts +3 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/chat/stream-manager.ts +4 -1
  5. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  8. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  9. package/backend/database/queries/index.ts +3 -0
  10. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  11. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  12. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  13. package/backend/db-client/connection-manager.ts +21 -1
  14. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  15. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  16. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  17. package/backend/engine/adapters/codex/stream.ts +33 -4
  18. package/backend/engine/adapters/copilot/stream.ts +1 -1
  19. package/backend/engine/adapters/cursor/stream.ts +1 -1
  20. package/backend/engine/adapters/qwen/stream.ts +1 -1
  21. package/backend/engine/docs/adapter-contract.md +7 -0
  22. package/backend/files/file-watcher.ts +283 -51
  23. package/backend/files/git-events.test.ts +110 -0
  24. package/backend/git/git-dirs.test.ts +132 -0
  25. package/backend/git/git-dirs.ts +0 -0
  26. package/backend/git/nested-repos.test.ts +108 -5
  27. package/backend/git/nested-repos.ts +103 -18
  28. package/backend/http/audio.ts +5 -32
  29. package/backend/http/bearer-auth.ts +47 -0
  30. package/backend/http/files-download.test.ts +146 -0
  31. package/backend/http/files-download.ts +109 -0
  32. package/backend/http/files-upload.ts +3 -29
  33. package/backend/http/ssh-sftp.ts +133 -0
  34. package/backend/index.ts +25 -2
  35. package/backend/mcp/README.md +34 -6
  36. package/backend/mcp/index.ts +8 -8
  37. package/backend/mcp/internal/config.ts +69 -19
  38. package/backend/mcp/internal/project-context.test.ts +40 -0
  39. package/backend/mcp/internal/project-context.ts +80 -7
  40. package/backend/mcp/internal/remote-server.test.ts +17 -2
  41. package/backend/mcp/internal/remote-server.ts +36 -3
  42. package/backend/mcp/internal/servers/helper.ts +48 -18
  43. package/backend/middleware/security.test.ts +95 -0
  44. package/backend/middleware/security.ts +114 -0
  45. package/backend/ports/attribute.test.ts +231 -0
  46. package/backend/ports/attribute.ts +444 -0
  47. package/backend/ports/kill.ts +203 -0
  48. package/backend/ports/monitor.ts +365 -0
  49. package/backend/ports/processes.test.ts +98 -0
  50. package/backend/ports/processes.ts +374 -0
  51. package/backend/ports/registry.ts +165 -0
  52. package/backend/ports/runner.ts +195 -0
  53. package/backend/ports/scan-host.ts +260 -0
  54. package/backend/ports/scan.test.ts +341 -0
  55. package/backend/ports/scan.ts +687 -0
  56. package/backend/ports/ssh-lineage.ts +318 -0
  57. package/backend/preview/browser/browser-video-capture.ts +51 -4
  58. package/backend/ssh/client-pool.ts +196 -0
  59. package/backend/ssh/connect.ts +375 -0
  60. package/backend/ssh/disk-usage.test.ts +134 -0
  61. package/backend/ssh/disk-usage.ts +214 -0
  62. package/backend/ssh/forwards.ts +340 -0
  63. package/backend/ssh/health.ts +141 -0
  64. package/backend/ssh/known-hosts.ts +96 -0
  65. package/backend/ssh/pty-backend.ts +215 -0
  66. package/backend/ssh/ptykit.ts +66 -0
  67. package/backend/ssh/sftp.test.ts +242 -0
  68. package/backend/ssh/sftp.ts +967 -0
  69. package/backend/ssh/socks5.test.ts +167 -0
  70. package/backend/ssh/socks5.ts +164 -0
  71. package/backend/ssh/tunnel.ts +87 -0
  72. package/backend/ws/auth/device.ts +1 -1
  73. package/backend/ws/auth/login.ts +8 -4
  74. package/backend/ws/db-client/connections.ts +1 -0
  75. package/backend/ws/files/watch.ts +5 -1
  76. package/backend/ws/index.ts +6 -0
  77. package/backend/ws/ports/index.ts +19 -0
  78. package/backend/ws/ports/kill.ts +80 -0
  79. package/backend/ws/ports/list.ts +60 -0
  80. package/backend/ws/ssh/access.ts +31 -0
  81. package/backend/ws/ssh/connections.ts +224 -0
  82. package/backend/ws/ssh/forwards.ts +109 -0
  83. package/backend/ws/ssh/index.ts +18 -0
  84. package/backend/ws/ssh/sftp.ts +259 -0
  85. package/backend/ws/ssh/tunnel.ts +93 -0
  86. package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
  87. package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
  88. package/dist/assets/main-CYCMEbXB.css +1 -0
  89. package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
  90. package/dist/index.html +2 -2
  91. package/package.json +1 -1
  92. package/shared/types/database/schema.ts +49 -0
  93. package/shared/types/db-client/connection.ts +6 -0
  94. package/shared/types/ports/index.ts +5 -0
  95. package/shared/types/ports/port.ts +192 -0
  96. package/shared/types/ssh/connection.ts +80 -0
  97. package/shared/types/ssh/forward.ts +46 -0
  98. package/shared/types/ssh/index.ts +8 -0
  99. package/shared/types/ssh/known-host.ts +19 -0
  100. package/shared/types/ssh/sftp.ts +141 -0
  101. package/shared/utils/logger.ts +2 -0
  102. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -0,0 +1,167 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { EventEmitter } from 'node:events';
3
+ import type { Socket } from 'node:net';
4
+ import { readSocksRequest, socksReply, SOCKS_REPLY_SUCCESS } from './socks5';
5
+
6
+ /**
7
+ * A stub standing in for the accepted TCP socket. Only the surface the parser
8
+ * touches is implemented: `on`/`removeListener` for inbound data, `write` and
9
+ * `end` for the replies it sends back, and `unshift` for the bytes it hands to
10
+ * the tunnel. Inbound data is delivered by emitting, not by writing, so the
11
+ * captured outbound writes stay separate from what the test feeds in.
12
+ */
13
+ function fakeSocket(): {
14
+ socket: Socket;
15
+ feed: (bytes: number[]) => void;
16
+ close: () => void;
17
+ written: () => Buffer;
18
+ unshifted: () => Buffer;
19
+ } {
20
+ const emitter = new EventEmitter();
21
+ const writes: Buffer[] = [];
22
+ const unshifts: Buffer[] = [];
23
+
24
+ const stub = emitter as unknown as Socket & {
25
+ unshift: (chunk: Buffer) => void;
26
+ // `writable` is read-only on the real Socket; widened here so the stub can
27
+ // report itself as writable, which the parser checks before replying.
28
+ writable: boolean;
29
+ };
30
+ stub.writable = true;
31
+ stub.write = ((chunk: Buffer) => {
32
+ writes.push(Buffer.from(chunk));
33
+ return true;
34
+ }) as Socket['write'];
35
+ stub.end = ((chunk?: Buffer) => {
36
+ if (chunk) writes.push(Buffer.from(chunk));
37
+ return stub;
38
+ }) as Socket['end'];
39
+ stub.unshift = (chunk: Buffer): void => {
40
+ unshifts.push(Buffer.from(chunk));
41
+ };
42
+
43
+ return {
44
+ socket: stub,
45
+ feed: (bytes) => emitter.emit('data', Buffer.from(bytes)),
46
+ close: () => emitter.emit('close'),
47
+ written: () => Buffer.concat(writes),
48
+ unshifted: () => Buffer.concat(unshifts)
49
+ };
50
+ }
51
+
52
+ const NO_AUTH_GREETING = [0x05, 0x01, 0x00];
53
+
54
+ describe('readSocksRequest', () => {
55
+ test('parses a CONNECT to a domain name', async () => {
56
+ const { socket, feed, written } = fakeSocket();
57
+ const pending = readSocksRequest(socket);
58
+
59
+ feed(NO_AUTH_GREETING);
60
+ feed([0x05, 0x01, 0x00, 0x03, 0x0b, ...Buffer.from('example.com'), 0x01, 0xbb]);
61
+
62
+ await expect(pending).resolves.toEqual({ host: 'example.com', port: 443 });
63
+ // The greeting is answered with "version 5, no authentication".
64
+ expect([...written()]).toEqual([0x05, 0x00]);
65
+ });
66
+
67
+ test('parses a CONNECT to an IPv4 address', async () => {
68
+ const { socket, feed } = fakeSocket();
69
+ const pending = readSocksRequest(socket);
70
+
71
+ feed(NO_AUTH_GREETING);
72
+ feed([0x05, 0x01, 0x00, 0x01, 10, 0, 0, 7, 0x22, 0xb8]);
73
+
74
+ await expect(pending).resolves.toEqual({ host: '10.0.0.7', port: 8888 });
75
+ });
76
+
77
+ test('parses a CONNECT to an IPv6 address', async () => {
78
+ const { socket, feed } = fakeSocket();
79
+ const pending = readSocksRequest(socket);
80
+
81
+ feed(NO_AUTH_GREETING);
82
+ feed([
83
+ 0x05, 0x01, 0x00, 0x04,
84
+ 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01,
85
+ 0x00, 0x50
86
+ ]);
87
+
88
+ await expect(pending).resolves.toEqual({ host: '2001:db8:0:0:0:0:0:1', port: 80 });
89
+ });
90
+
91
+ test('reassembles a request split across packets', async () => {
92
+ const { socket, feed } = fakeSocket();
93
+ const pending = readSocksRequest(socket);
94
+
95
+ feed([0x05]);
96
+ feed([0x01, 0x00]);
97
+ feed([0x05, 0x01, 0x00, 0x03, 0x03]);
98
+ feed([...Buffer.from('abc')]);
99
+ feed([0x00, 0x16]);
100
+
101
+ await expect(pending).resolves.toEqual({ host: 'abc', port: 22 });
102
+ });
103
+
104
+ test('hands bytes sent after the request back to the socket', async () => {
105
+ const { socket, feed, unshifted } = fakeSocket();
106
+ const pending = readSocksRequest(socket);
107
+
108
+ feed(NO_AUTH_GREETING);
109
+ feed([0x05, 0x01, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50, 0x47, 0x45, 0x54]);
110
+
111
+ await pending;
112
+ expect(unshifted().toString('utf8')).toBe('GET');
113
+ });
114
+
115
+ test('rejects a command other than CONNECT', async () => {
116
+ const { socket, feed, written } = fakeSocket();
117
+ const pending = readSocksRequest(socket);
118
+
119
+ feed(NO_AUTH_GREETING);
120
+ // 0x02 is BIND, which `ssh -D` does not implement either.
121
+ feed([0x05, 0x02, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50]);
122
+
123
+ await expect(pending).rejects.toThrow('CONNECT');
124
+ // The greeting reply, then a failure frame with 0x07 = command not supported.
125
+ expect([...written()]).toEqual([0x05, 0x00, 0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0]);
126
+ });
127
+
128
+ test('rejects a client that will not do no-auth', async () => {
129
+ const { socket, feed, written } = fakeSocket();
130
+ const pending = readSocksRequest(socket);
131
+
132
+ // Offers only username/password (0x02).
133
+ feed([0x05, 0x01, 0x02]);
134
+
135
+ await expect(pending).rejects.toThrow('authentication');
136
+ // 0xff = no acceptable methods, sent as the closing frame.
137
+ expect([...written()]).toEqual([0x05, 0xff]);
138
+ });
139
+
140
+ test('rejects a non-SOCKS5 client', async () => {
141
+ const { socket, feed } = fakeSocket();
142
+ const pending = readSocksRequest(socket);
143
+
144
+ // SOCKS4 announces version 0x04.
145
+ feed([0x04, 0x01]);
146
+
147
+ await expect(pending).rejects.toThrow('SOCKS5');
148
+ });
149
+
150
+ test('rejects a client that disconnects mid-handshake', async () => {
151
+ const { socket, feed, close } = fakeSocket();
152
+ const pending = readSocksRequest(socket);
153
+
154
+ feed(NO_AUTH_GREETING);
155
+ close();
156
+
157
+ await expect(pending).rejects.toThrow('disconnected');
158
+ });
159
+ });
160
+
161
+ describe('socksReply', () => {
162
+ test('reports the bound address as 0.0.0.0:0', () => {
163
+ expect([...socksReply(SOCKS_REPLY_SUCCESS)]).toEqual([
164
+ 0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0
165
+ ]);
166
+ });
167
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * ssh-client — the SOCKS5 half of dynamic port forwarding.
3
+ *
4
+ * `ssh -D` is a SOCKS5 proxy whose CONNECT requests are opened as channels on
5
+ * the SSH transport. This module speaks just enough of RFC 1928 to serve that:
6
+ * the no-auth handshake and the CONNECT command. BIND and UDP ASSOCIATE are
7
+ * rejected — OpenSSH does not implement them for `-D` either.
8
+ */
9
+
10
+ import type { Socket } from 'node:net';
11
+
12
+ const SOCKS_VERSION = 0x05;
13
+ const NO_AUTHENTICATION = 0x00;
14
+ const NO_ACCEPTABLE_METHODS = 0xff;
15
+
16
+ const COMMAND_CONNECT = 0x01;
17
+
18
+ const ADDRESS_IPV4 = 0x01;
19
+ const ADDRESS_DOMAIN = 0x03;
20
+ const ADDRESS_IPV6 = 0x04;
21
+
22
+ export const SOCKS_REPLY_SUCCESS = 0x00;
23
+ export const SOCKS_REPLY_GENERAL_FAILURE = 0x01;
24
+ export const SOCKS_REPLY_HOST_UNREACHABLE = 0x04;
25
+ export const SOCKS_REPLY_COMMAND_NOT_SUPPORTED = 0x07;
26
+
27
+ export interface SocksRequest {
28
+ host: string;
29
+ port: number;
30
+ }
31
+
32
+ /**
33
+ * The reply frame. The bound address is reported as 0.0.0.0:0 — the client is
34
+ * about to be piped into an SSH channel that has no local address of its own,
35
+ * and every SOCKS client tolerates that.
36
+ */
37
+ export function socksReply(code: number): Buffer {
38
+ return Buffer.from([SOCKS_VERSION, code, 0x00, ADDRESS_IPV4, 0, 0, 0, 0, 0, 0]);
39
+ }
40
+
41
+ /**
42
+ * Read the greeting and the CONNECT request from `socket`, answering the
43
+ * greeting along the way. Resolves with where the client wants to go; rejects
44
+ * (after sending the matching failure reply) when the exchange is not a
45
+ * no-auth CONNECT.
46
+ *
47
+ * Data arriving after the request is left unread on the socket, so the caller
48
+ * can pipe it straight into the SSH channel without losing a byte.
49
+ */
50
+ export function readSocksRequest(socket: Socket): Promise<SocksRequest> {
51
+ return new Promise((resolvePromise, rejectPromise) => {
52
+ let buffered = Buffer.alloc(0);
53
+ let greeted = false;
54
+ let settled = false;
55
+
56
+ const cleanup = (): void => {
57
+ socket.removeListener('data', onData);
58
+ socket.removeListener('error', onError);
59
+ socket.removeListener('close', onClose);
60
+ };
61
+
62
+ const fail = (message: string, replyCode: number): void => {
63
+ if (settled) return;
64
+ settled = true;
65
+ cleanup();
66
+ if (replyCode !== SOCKS_REPLY_SUCCESS && socket.writable) {
67
+ socket.write(socksReply(replyCode));
68
+ }
69
+ rejectPromise(new Error(message));
70
+ };
71
+
72
+ const succeed = (request: SocksRequest, consumed: number): void => {
73
+ if (settled) return;
74
+ settled = true;
75
+ cleanup();
76
+ // Anything the client sent past the request belongs to the tunnel.
77
+ const leftover = buffered.subarray(consumed);
78
+ if (leftover.length > 0) socket.unshift(leftover);
79
+ resolvePromise(request);
80
+ };
81
+
82
+ function onData(chunk: Buffer): void {
83
+ buffered = Buffer.concat([buffered, chunk]);
84
+
85
+ if (!greeted) {
86
+ if (buffered.length < 2) return;
87
+ if (buffered[0] !== SOCKS_VERSION) {
88
+ fail('Not a SOCKS5 client', SOCKS_REPLY_GENERAL_FAILURE);
89
+ return;
90
+ }
91
+ const methodCount = buffered[1];
92
+ const greetingLength = 2 + methodCount;
93
+ if (buffered.length < greetingLength) return;
94
+
95
+ const methods = buffered.subarray(2, greetingLength);
96
+ if (!methods.includes(NO_AUTHENTICATION)) {
97
+ settled = true;
98
+ cleanup();
99
+ socket.end(Buffer.from([SOCKS_VERSION, NO_ACCEPTABLE_METHODS]));
100
+ rejectPromise(new Error('SOCKS client requires authentication'));
101
+ return;
102
+ }
103
+
104
+ socket.write(Buffer.from([SOCKS_VERSION, NO_AUTHENTICATION]));
105
+ buffered = buffered.subarray(greetingLength);
106
+ greeted = true;
107
+ }
108
+
109
+ if (buffered.length < 4) return;
110
+ if (buffered[0] !== SOCKS_VERSION) {
111
+ fail('Malformed SOCKS5 request', SOCKS_REPLY_GENERAL_FAILURE);
112
+ return;
113
+ }
114
+ if (buffered[1] !== COMMAND_CONNECT) {
115
+ fail('Only the CONNECT command is supported', SOCKS_REPLY_COMMAND_NOT_SUPPORTED);
116
+ return;
117
+ }
118
+
119
+ const addressType = buffered[3];
120
+ let host: string;
121
+ let cursor: number;
122
+
123
+ if (addressType === ADDRESS_IPV4) {
124
+ if (buffered.length < 10) return;
125
+ host = Array.from(buffered.subarray(4, 8)).join('.');
126
+ cursor = 8;
127
+ } else if (addressType === ADDRESS_DOMAIN) {
128
+ const nameLength = buffered[4];
129
+ if (buffered.length < 5 + nameLength + 2) return;
130
+ host = buffered.subarray(5, 5 + nameLength).toString('utf8');
131
+ cursor = 5 + nameLength;
132
+ } else if (addressType === ADDRESS_IPV6) {
133
+ if (buffered.length < 22) return;
134
+ const groups: string[] = [];
135
+ for (let offset = 4; offset < 20; offset += 2) {
136
+ groups.push(buffered.readUInt16BE(offset).toString(16));
137
+ }
138
+ host = groups.join(':');
139
+ cursor = 20;
140
+ } else {
141
+ fail('Unsupported SOCKS5 address type', SOCKS_REPLY_HOST_UNREACHABLE);
142
+ return;
143
+ }
144
+
145
+ const port = buffered.readUInt16BE(cursor);
146
+ succeed({ host, port }, cursor + 2);
147
+ }
148
+
149
+ function onError(error: Error): void {
150
+ if (settled) return;
151
+ settled = true;
152
+ cleanup();
153
+ rejectPromise(error);
154
+ }
155
+
156
+ function onClose(): void {
157
+ fail('SOCKS client disconnected during the handshake', SOCKS_REPLY_SUCCESS);
158
+ }
159
+
160
+ socket.on('data', onData);
161
+ socket.on('error', onError);
162
+ socket.on('close', onClose);
163
+ });
164
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * ssh-client — local port forwards opened on behalf of other features.
3
+ *
4
+ * The database client reaches a database behind a bastion through one of these.
5
+ * Pointing it at a saved SSH connection (rather than at credentials copied into
6
+ * the database connection) means the host, its jump chain and its trusted host
7
+ * key are configured once and shared.
8
+ *
9
+ * The tunnel holds a pool lease for its whole life, so the transport it rides
10
+ * cannot be swept out from under an open database connection.
11
+ */
12
+
13
+ import net from 'node:net';
14
+ import { sshClientPool, type SshLease } from './client-pool';
15
+ import { debug } from '$shared/utils/logger';
16
+
17
+ export interface SshManagedTunnel {
18
+ localPort: number;
19
+ close(): Promise<void>;
20
+ }
21
+
22
+ /**
23
+ * Open `127.0.0.1:<ephemeral>` forwarding to `remoteHost:remotePort` through
24
+ * the saved SSH connection `connectionId`.
25
+ */
26
+ export async function openTunnelViaSavedConnection(
27
+ connectionId: string,
28
+ remoteHost: string,
29
+ remotePort: number
30
+ ): Promise<SshManagedTunnel> {
31
+ const lease: SshLease = await sshClientPool.acquire(connectionId);
32
+
33
+ const sockets = new Set<net.Socket>();
34
+
35
+ const server = net.createServer((socket) => {
36
+ sockets.add(socket);
37
+ socket.on('close', () => sockets.delete(socket));
38
+
39
+ lease.client.forwardOut(
40
+ socket.remoteAddress ?? '127.0.0.1',
41
+ socket.remotePort ?? 0,
42
+ remoteHost,
43
+ remotePort,
44
+ (error, stream) => {
45
+ if (error) {
46
+ debug.warn('ssh', `tunnel forwardOut failed: ${error.message}`);
47
+ socket.destroy();
48
+ return;
49
+ }
50
+ socket.pipe(stream).pipe(socket);
51
+ stream.on('error', () => socket.destroy());
52
+ socket.on('error', () => stream.destroy());
53
+ }
54
+ );
55
+ });
56
+
57
+ let localPort: number;
58
+ try {
59
+ localPort = await new Promise<number>((resolvePromise, rejectPromise) => {
60
+ server.once('error', rejectPromise);
61
+ server.listen(0, '127.0.0.1', () => {
62
+ server.removeListener('error', rejectPromise);
63
+ const address = server.address();
64
+ if (address && typeof address === 'object') {
65
+ resolvePromise(address.port);
66
+ } else {
67
+ rejectPromise(new Error('Failed to obtain a local port for the SSH tunnel'));
68
+ }
69
+ });
70
+ });
71
+ } catch (error) {
72
+ lease.release();
73
+ throw error;
74
+ }
75
+
76
+ debug.log('ssh', `tunnel up: 127.0.0.1:${localPort} → ${remoteHost}:${remotePort} via saved host`);
77
+
78
+ return {
79
+ localPort,
80
+ async close() {
81
+ for (const socket of sockets) socket.destroy();
82
+ sockets.clear();
83
+ await new Promise<void>((resolvePromise) => server.close(() => resolvePromise()));
84
+ lease.release();
85
+ }
86
+ };
87
+ }
@@ -89,7 +89,7 @@ export const deviceHandler = createRouter()
89
89
  ipAddress: clientIpFromConnection(conn)
90
90
  });
91
91
 
92
- authRateLimiter.recordSuccess(ip);
92
+ authRateLimiter.recordSuccess(ip, 'auth:claim-device-code');
93
93
 
94
94
  auditLogQueries.logEvent({
95
95
  userId: result.user.id,
@@ -174,7 +174,7 @@ export const loginHandler = createRouter()
174
174
 
175
175
  // Success — clear any rate limit record for this IP
176
176
  if (isRateLimited) {
177
- authRateLimiter.recordSuccess(ip);
177
+ authRateLimiter.recordSuccess(ip, 'auth:login');
178
178
  }
179
179
 
180
180
  auditLogQueries.logEvent({
@@ -226,7 +226,7 @@ export const loginHandler = createRouter()
226
226
  try {
227
227
  const result = createUserFromInvite(data.inviteToken, data.name, { userAgent: data.userAgent, ipAddress: clientIpFromConnection(conn) });
228
228
 
229
- authRateLimiter.recordSuccess(ip);
229
+ authRateLimiter.recordSuccess(ip, 'auth:accept-invite');
230
230
 
231
231
  auditLogQueries.logEvent({
232
232
  userId: result.user.id,
@@ -272,8 +272,12 @@ export const loginHandler = createRouter()
272
272
 
273
273
  const result = validateInviteToken(data.inviteToken);
274
274
 
275
- // Record failure if invalid token (probing)
276
- if (!result.valid) {
275
+ // Record failure if invalid token (probing). On a valid token, clear this
276
+ // route's record so someone who mistyped their link a couple of times
277
+ // doesn't carry those failures into a later attempt.
278
+ if (result.valid) {
279
+ authRateLimiter.recordSuccess(ip, 'auth:validate-invite');
280
+ } else {
277
281
  authRateLimiter.recordFailure(ip, 'auth:validate-invite');
278
282
  }
279
283
 
@@ -36,6 +36,7 @@ const sshAuthSchema = t.Union([t.Literal('password'), t.Literal('key')]);
36
36
 
37
37
  const sshInputSchema = t.Object({
38
38
  enabled: t.Optional(t.Boolean()),
39
+ connectionId: t.Optional(t.Nullable(t.String())),
39
40
  host: t.Optional(t.String()),
40
41
  port: t.Optional(t.Number()),
41
42
  username: t.Optional(t.String()),
@@ -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
  }));
@@ -31,6 +31,8 @@ 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';
35
+ import { portsRouter } from './ports';
34
36
  import { mcpRouter } from './mcp';
35
37
  import { skillsRouter } from './skills';
36
38
  import { commandsRouter } from './commands';
@@ -84,6 +86,10 @@ export const wsRouter = createRouter()
84
86
  // DB Client (global database management)
85
87
  .merge(dbClientRouter)
86
88
 
89
+ // SSH client (terminal, SFTP, port forwarding)
90
+ .merge(sshRouter)
91
+ .merge(portsRouter)
92
+
87
93
  // External MCP server management (install from the official registry)
88
94
  .merge(mcpRouter)
89
95
 
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Port manager WebSocket router.
3
+ *
4
+ * Reading the table is open to any signed-in user; `ports:kill` is registered
5
+ * in ADMIN_ONLY_ROUTES and gated there.
6
+ */
7
+
8
+ import { t } from 'elysia';
9
+ import { createRouter } from '$shared/utils/ws-server';
10
+ import { portsListHandler } from './list';
11
+ import { portsKillHandler } from './kill';
12
+
13
+ export const portsRouter = createRouter()
14
+ .merge(portsListHandler)
15
+ .merge(portsKillHandler)
16
+ // Pushed only when a watched host's table actually changed.
17
+ .emit('ports:changed', t.Object({ result: t.Any() }))
18
+ // The sidebar count: ports born in a Clopen terminal session.
19
+ .emit('ports:badge', t.Object({ count: t.Number() }));
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Port manager — stopping a process, admin only.
3
+ *
4
+ * The route is listed in ADMIN_ONLY_ROUTES; this handler re-scans before
5
+ * acting rather than trusting the pid the client sent. A table is up to a
6
+ * second old, and a second is long enough for a pid to be recycled onto an
7
+ * unrelated process — signalling that would be indefensible.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import { createRouter } from '$shared/utils/ws-server';
12
+ import { LOCAL_PORT_HOST } from '$shared/types/ports';
13
+ import { portMonitor } from '../../ports/monitor';
14
+ import { stopPortHolder } from '../../ports/kill';
15
+ import { sshConnectionQueries } from '../../database/queries';
16
+ import { ws } from '../../utils/ws';
17
+ import { debug } from '$shared/utils/logger';
18
+
19
+ export const portsKillHandler = createRouter().http(
20
+ 'ports:kill',
21
+ {
22
+ data: t.Object({
23
+ hostId: t.String({ minLength: 1 }),
24
+ /** Identifies the row the user clicked, so the re-scan can match it. */
25
+ entryKey: t.String({ minLength: 1 })
26
+ }),
27
+ response: t.Any()
28
+ },
29
+ async ({ data, conn }) => {
30
+ const userId = ws.getUserId(conn);
31
+ if (data.hostId !== LOCAL_PORT_HOST) {
32
+ // The route is admin-only, but the host check still runs on the real
33
+ // role rather than a hardcoded one — a gate that trusts its caller is
34
+ // no gate at all.
35
+ sshConnectionQueries.ensureAccess(data.hostId, userId, ws.getRole(conn) === 'admin');
36
+ }
37
+
38
+ const fresh = await portMonitor.scanOnce(data.hostId);
39
+ const entry = fresh.entries.find((candidate) => candidate.key === data.entryKey);
40
+ if (!entry) {
41
+ return {
42
+ result: {
43
+ ok: true,
44
+ killedPids: [],
45
+ stoppedFeature: null,
46
+ error: null
47
+ },
48
+ gone: true
49
+ };
50
+ }
51
+
52
+ if (!entry.canKill || entry.pid === null) {
53
+ return {
54
+ result: {
55
+ ok: false,
56
+ killedPids: [],
57
+ stoppedFeature: null,
58
+ error: 'That port cannot be stopped from here.'
59
+ },
60
+ gone: false
61
+ };
62
+ }
63
+
64
+ debug.log('ports', `stopping ${entry.protocol}/${entry.port} (pid ${entry.pid}) on ${data.hostId}`);
65
+
66
+ const result = await portMonitor.withHost(data.hostId, (runner, platform) =>
67
+ stopPortHolder(
68
+ { pid: entry.pid as number, ownerFeature: entry.origin.ownerFeature, ownerId: entry.origin.ownerId },
69
+ runner,
70
+ platform
71
+ )
72
+ );
73
+
74
+ // Whatever happened, the table moved — push it now rather than at the
75
+ // next tick, so the row disappears as the button is released.
76
+ portMonitor.invalidate(data.hostId);
77
+
78
+ return { result, gone: false };
79
+ }
80
+ );
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Port manager — reading the table.
3
+ *
4
+ * Watching is per connection: a client asks for a host when it opens that tab
5
+ * and is pushed a fresh table whenever the host's ports actually change. The
6
+ * watch is torn down when the socket closes, so a browser tab that vanishes
7
+ * cannot leave a host being polled forever.
8
+ *
9
+ * Reading is open to any signed-in user; stopping a process is not, and lives
10
+ * in kill.ts.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { createRouter } from '$shared/utils/ws-server';
15
+ import { LOCAL_PORT_HOST } from '$shared/types/ports';
16
+ import { portMonitor } from '../../ports/monitor';
17
+ import { sshConnectionQueries } from '../../database/queries';
18
+ import { ws } from '../../utils/ws';
19
+
20
+ /**
21
+ * A member may only watch an SSH host they can already reach. The local
22
+ * machine is watchable by anyone signed in — it is the machine they are
23
+ * already using Clopen on.
24
+ */
25
+ function requireHostAccess(conn: Parameters<typeof ws.getUserId>[0], hostId: string): void {
26
+ if (hostId === LOCAL_PORT_HOST) return;
27
+ const userId = ws.getUserId(conn);
28
+ const isAdmin = ws.getRole(conn) === 'admin';
29
+ sshConnectionQueries.ensureAccess(hostId, userId, isAdmin);
30
+ }
31
+
32
+ const hostSchema = t.Object({ hostId: t.String({ minLength: 1 }) });
33
+
34
+ export const portsListHandler = createRouter()
35
+ .http('ports:watch', { data: hostSchema, response: t.Any() }, async ({ data, conn }) => {
36
+ requireHostAccess(conn, data.hostId);
37
+ const userId = ws.getUserId(conn);
38
+
39
+ const result = await portMonitor.watch(data.hostId, userId);
40
+ // The watch belongs to this socket; a reload must not leave it running.
41
+ ws.addCleanup(conn, () => portMonitor.unwatch(data.hostId, userId));
42
+ return { result };
43
+ })
44
+
45
+ .http('ports:unwatch', { data: hostSchema, response: t.Any() }, async ({ data, conn }) => {
46
+ portMonitor.unwatch(data.hostId, ws.getUserId(conn));
47
+ return { ok: true };
48
+ })
49
+
50
+ /**
51
+ * The sidebar count, on demand.
52
+ *
53
+ * Pushes only carry changes, so a client that has just loaded — or just
54
+ * reconnected — has no way to learn a count that has been steady. Asking for
55
+ * it is how the badge survives a page refresh instead of reading zero until
56
+ * something happens to move it.
57
+ */
58
+ .http('ports:summary', { data: t.Object({}), response: t.Any() }, async () => ({
59
+ count: await portMonitor.refreshBadge()
60
+ }));