@myrialabs/clopen 0.4.33 → 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 (36) 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/db-client/connection-manager.ts +13 -0
  5. package/backend/index.ts +9 -0
  6. package/backend/middleware/security.test.ts +95 -0
  7. package/backend/middleware/security.ts +114 -0
  8. package/backend/ports/attribute.test.ts +231 -0
  9. package/backend/ports/attribute.ts +444 -0
  10. package/backend/ports/kill.ts +203 -0
  11. package/backend/ports/monitor.ts +365 -0
  12. package/backend/ports/processes.test.ts +98 -0
  13. package/backend/ports/processes.ts +374 -0
  14. package/backend/ports/registry.ts +165 -0
  15. package/backend/ports/runner.ts +195 -0
  16. package/backend/ports/scan-host.ts +260 -0
  17. package/backend/ports/scan.test.ts +341 -0
  18. package/backend/ports/scan.ts +687 -0
  19. package/backend/ports/ssh-lineage.ts +318 -0
  20. package/backend/ssh/forwards.ts +31 -0
  21. package/backend/ws/auth/device.ts +1 -1
  22. package/backend/ws/auth/login.ts +8 -4
  23. package/backend/ws/index.ts +2 -0
  24. package/backend/ws/ports/index.ts +19 -0
  25. package/backend/ws/ports/kill.ts +80 -0
  26. package/backend/ws/ports/list.ts +60 -0
  27. package/dist/assets/{index-BW0DA8NV.js → index-gGTMFUa8.js} +1 -1
  28. package/dist/assets/{index-BF4buYmI.js → index-vW2RpdHu.js} +1 -1
  29. package/dist/assets/main-CYCMEbXB.css +1 -0
  30. package/dist/assets/{main-BbwWLJRN.js → main-ZCojSzvW.js} +409 -406
  31. package/dist/index.html +2 -2
  32. package/package.json +1 -1
  33. package/shared/types/ports/index.ts +5 -0
  34. package/shared/types/ports/port.ts +192 -0
  35. package/shared/utils/logger.ts +1 -0
  36. package/dist/assets/main-CCvRMXlP.css +0 -1
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Port manager — recognising Clopen's own work on an SSH host.
3
+ *
4
+ * On the machine Clopen runs on, a port is traced to Clopen by walking parent
5
+ * pids up to a Clopen process. A remote host needs the same fact established
6
+ * from the other end: PtyKit addresses remote shells through an internal id,
7
+ * and ssh2 never learns what the far side numbered anything.
8
+ *
9
+ * The answer is in the environment, not the process tree. sshd sets
10
+ * `SSH_CONNECTION` for every session it opens, holding the client address and
11
+ * source port of the TCP connection behind it. Every channel Clopen opens —
12
+ * shells, SFTP, forwards, the probes in this file — rides one connection, so
13
+ * they all carry the same value, and every process started from any of them
14
+ * inherits it. Reading it back off a listening process therefore says whether
15
+ * Clopen started it, with no privileges and no guesswork.
16
+ *
17
+ * Two earlier attempts are worth not repeating:
18
+ *
19
+ * - Matching `SSH_CONNECTION` against the host's *socket table* to find the
20
+ * sshd holding the connection. That socket belongs to root's sshd, so an
21
+ * unprivileged account never sees its pid.
22
+ * - Walking up from a probe's `$PPID` to the outermost process calling itself
23
+ * `sshd:`. That depends on how a host labels its sshd processes and on where
24
+ * the daemon sits in the tree, and it found nothing on a real cPanel host.
25
+ *
26
+ * Both tried to identify a process Clopen has no right to see. Asking what
27
+ * connection a process belongs to sidesteps that entirely.
28
+ *
29
+ * macOS is the exception, and only because it cannot answer the question:
30
+ * `ps -E` returns no environment there at all under SIP, verified rather than
31
+ * assumed. A macOS host therefore falls back to the process-tree walk, which
32
+ * is sound there — its sshd labels sessions the same way. This mirrors how the
33
+ * port probes already differ per platform: one question, asked the way each
34
+ * operating system will answer it.
35
+ */
36
+
37
+ import type { PortProcess } from '$shared/types/ports';
38
+ import { posixArgv, type CommandRunner, type ProbePlatform } from './runner';
39
+ import { parsePsOutput } from './processes';
40
+ import { debug } from '$shared/utils/logger';
41
+
42
+ /** `SSH_CONNECTION` is `<client ip> <client port> <server ip> <server port>`. */
43
+ export function parseSshConnection(value: string): { address: string; port: number } | null {
44
+ const parts = value.trim().split(/\s+/);
45
+ if (parts.length < 2) return null;
46
+ const port = Number.parseInt(parts[1], 10);
47
+ if (!Number.isFinite(port) || port <= 0) return null;
48
+ return { address: parts[0], port };
49
+ }
50
+
51
+ /**
52
+ * Two `SSH_CONNECTION` values describing the same connection.
53
+ *
54
+ * The source port carries the match: it is unique per connection for as long
55
+ * as that connection is open. The address is compared only as a guard against
56
+ * a port number colliding across interfaces.
57
+ */
58
+ export function sameConnection(a: string, b: string): boolean {
59
+ const left = parseSshConnection(a);
60
+ const right = parseSshConnection(b);
61
+ if (!left || !right) return false;
62
+ return left.port === right.port && left.address === right.address;
63
+ }
64
+
65
+ /** Pids are interpolated into a shell script, so they must be exactly numbers. */
66
+ function safePids(pids: number[]): number[] {
67
+ return pids.filter((pid) => Number.isInteger(pid) && pid > 0 && pid < 4_294_967_296);
68
+ }
69
+
70
+ /**
71
+ * Read `SSH_CONNECTION` out of each process's environment.
72
+ *
73
+ * On Linux that is `/proc/<pid>/environ`, a NUL-separated blob readable for
74
+ * one's own processes — which is exactly the set that could have come from
75
+ * Clopen. macOS exposes the same thing through `ps -E`. Neither needs any
76
+ * privilege beyond owning the process.
77
+ */
78
+ function environProbeArgv(pids: number[]): string[] | null {
79
+ if (pids.length === 0) return null;
80
+ const list = pids.join(' ');
81
+
82
+ // A fixed script; only vetted integers are interpolated into it.
83
+ return posixArgv([
84
+ 'sh',
85
+ '-c',
86
+ // `cat` rather than a `<` redirect: a redirect that fails is reported by
87
+ // the shell itself, before `2>/dev/null` on that command can apply.
88
+ `for p in ${list}; do printf '@%s ' "$p"; cat /proc/$p/environ 2>/dev/null | ` +
89
+ `tr '\\0' '\\n' | grep '^SSH_CONNECTION=' || printf '\\n'; done`
90
+ ]);
91
+ }
92
+
93
+ /** `@42802 SSH_CONNECTION=1.2.3.4 55 5.6.7.8 22` → pid and value. */
94
+ export function parseEnvironProbe(stdout: string): Map<number, string> {
95
+ const found = new Map<number, string>();
96
+
97
+ for (const line of stdout.split('\n')) {
98
+ const marked = line.match(/^@(\d+)\s*(.*)$/);
99
+ if (!marked) continue;
100
+ const pid = Number.parseInt(marked[1], 10);
101
+ const value = marked[2].replace(/^.*?SSH_CONNECTION=/, '');
102
+ if (Number.isFinite(pid) && value && marked[2].includes('SSH_CONNECTION=')) {
103
+ found.set(pid, value.trim());
104
+ }
105
+ }
106
+
107
+ return found;
108
+ }
109
+
110
+ /**
111
+ * A per-connection sshd, which announces itself as `sshd: user@ttys000`,
112
+ * `sshd: user@pts/0` or `sshd: user [priv]`. The listening daemon
113
+ * (`/usr/sbin/sshd -D`) deliberately does not match: it parents every session
114
+ * on the host, so treating it as the root would hand Clopen credit for every
115
+ * other user's processes.
116
+ */
117
+ function isSessionSshd(process: PortProcess | null): boolean {
118
+ return process ? /(^|\s)sshd:\s/.test(process.command) : false;
119
+ }
120
+
121
+ /**
122
+ * From the sshd serving one channel, the sshd serving the whole connection.
123
+ *
124
+ * sshd forks a child per channel, so the chain from a command runs shell →
125
+ * channel sshd → connection sshd → listening daemon. The outermost link still
126
+ * calling itself `sshd:` is the one every channel shares, which makes it the
127
+ * root of everything Clopen does on that host.
128
+ */
129
+ export function findConnectionSshd(
130
+ execParentPid: number,
131
+ processes: Map<number, PortProcess>
132
+ ): number | null {
133
+ let best: number | null = null;
134
+ let current: number | null = execParentPid;
135
+ const seen = new Set<number>();
136
+
137
+ for (let depth = 0; depth < 20 && current !== null && current > 1; depth++) {
138
+ if (seen.has(current)) break;
139
+ seen.add(current);
140
+
141
+ const process = processes.get(current);
142
+ if (!process || !isSessionSshd(process)) break;
143
+
144
+ best = current;
145
+ current = process.parentPid;
146
+ }
147
+
148
+ return best;
149
+ }
150
+
151
+ /**
152
+ * The pid and the process list must come from the *same* command: sshd reaps
153
+ * the exec channel's child the moment the command exits, so a pid read by one
154
+ * exec is already gone before a second could run `ps` against it.
155
+ */
156
+ async function probeTreeRoot(runner: CommandRunner): Promise<number | null> {
157
+ try {
158
+ const result = await runner.run(
159
+ posixArgv(['sh', '-c', 'echo "$PPID"; ps -eo pid=,ppid=,user=,lstart=,args=']),
160
+ 10_000
161
+ );
162
+
163
+ const newline = result.stdout.indexOf('\n');
164
+ if (newline === -1) return null;
165
+
166
+ const execParentPid = Number.parseInt(result.stdout.slice(0, newline).trim(), 10);
167
+ if (!Number.isFinite(execParentPid) || execParentPid <= 1) return null;
168
+
169
+ const processes = new Map<number, PortProcess>();
170
+ for (const entry of parsePsOutput(result.stdout.slice(newline + 1))) processes.set(entry.pid, entry);
171
+
172
+ return findConnectionSshd(execParentPid, processes);
173
+ } catch (error) {
174
+ debug.log('ports', `SSH tree probe failed on ${runner.label}:`, error);
175
+ return null;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * What connection Clopen's own commands run on. Cached per host: it cannot
181
+ * change while the pooled transport lives, and re-asking would spend a round
182
+ * trip per tick on a constant.
183
+ */
184
+ const ownConnections = new Map<string, string>();
185
+
186
+ async function readOwnConnection(
187
+ hostId: string,
188
+ runner: CommandRunner,
189
+ platform: ProbePlatform
190
+ ): Promise<string | null> {
191
+ const cached = ownConnections.get(hostId);
192
+ if (cached) return cached;
193
+ if (platform === 'win32') return null;
194
+
195
+ try {
196
+ const result = await runner.run(posixArgv(['sh', '-c', 'printf %s "$SSH_CONNECTION"']), 5_000);
197
+ const value = result.stdout.trim();
198
+ // Judged on output, not exit status: a restricted shell can report a
199
+ // non-zero status and still have answered the question.
200
+ if (!parseSshConnection(value)) return null;
201
+ ownConnections.set(hostId, value);
202
+ return value;
203
+ } catch (error) {
204
+ debug.log('ports', `could not read SSH_CONNECTION on ${runner.label}:`, error);
205
+ return null;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Which of these listening processes belong to Clopen's own SSH connection.
211
+ *
212
+ * Answers per pid rather than by finding one root process, so a server that
213
+ * was disowned or reparented is still recognised — the environment survives
214
+ * what the process tree does not.
215
+ */
216
+ /**
217
+ * What has already been decided about a process, keyed by pid *and* start time
218
+ * so a recycled pid is judged afresh. A live process's environment does not
219
+ * change, so re-reading it every tick would be a round trip spent confirming a
220
+ * constant.
221
+ */
222
+ const verdicts = new Map<string, Map<string, boolean>>();
223
+
224
+ function verdictKey(pid: number, processes: Map<number, PortProcess>): string {
225
+ return `${pid}:${processes.get(pid)?.startedAt ?? ''}`;
226
+ }
227
+
228
+ export async function resolveClopenPids(
229
+ hostId: string,
230
+ runner: CommandRunner,
231
+ platform: ProbePlatform,
232
+ pids: number[],
233
+ processes: Map<number, PortProcess>
234
+ ): Promise<Set<number>> {
235
+ const ours = new Set<number>();
236
+ if (platform === 'win32') return ours;
237
+
238
+ // macOS will not report a process's environment, so its connection has to
239
+ // be identified through the process tree instead. Adding the session sshd
240
+ // is enough: the ancestry walk downstream reaches it from every descendant.
241
+ if (platform === 'darwin') {
242
+ const root = await resolveTreeRoot(hostId, runner);
243
+ if (root !== null) ours.add(root);
244
+ return ours;
245
+ }
246
+
247
+ const own = await readOwnConnection(hostId, runner, platform);
248
+ if (!own) return ours;
249
+
250
+ // Ancestors count too: a process that cleared its own environment is still
251
+ // ours if the shell that spawned it is.
252
+ const candidates = new Set<number>();
253
+ for (const pid of pids) {
254
+ let current: number | null = pid;
255
+ const seen = new Set<number>();
256
+ for (let depth = 0; depth < 20 && current !== null && current > 1; depth++) {
257
+ if (seen.has(current)) break;
258
+ seen.add(current);
259
+ candidates.add(current);
260
+ current = processes.get(current)?.parentPid ?? null;
261
+ }
262
+ }
263
+
264
+ let known = verdicts.get(hostId);
265
+ if (!known) {
266
+ known = new Map();
267
+ verdicts.set(hostId, known);
268
+ }
269
+
270
+ // Only ask about processes never judged before; the rest are already settled.
271
+ const unknown: number[] = [];
272
+ for (const pid of candidates) {
273
+ const decided = known.get(verdictKey(pid, processes));
274
+ if (decided === undefined) unknown.push(pid);
275
+ else if (decided) ours.add(pid);
276
+ }
277
+
278
+ const argv = environProbeArgv(safePids(unknown));
279
+ if (!argv) return ours;
280
+
281
+ try {
282
+ const result = await runner.run(argv, 10_000);
283
+ const values = parseEnvironProbe(result.stdout);
284
+
285
+ for (const pid of unknown) {
286
+ const value = values.get(pid);
287
+ // A process whose environment could not be read is recorded as not
288
+ // ours, so it is not asked about again — unreadable will not become
289
+ // readable while it lives.
290
+ const mine = value !== undefined && sameConnection(value, own);
291
+ known.set(verdictKey(pid, processes), mine);
292
+ if (mine) ours.add(pid);
293
+ }
294
+ } catch (error) {
295
+ debug.log('ports', `environment probe failed on ${runner.label}:`, error);
296
+ }
297
+
298
+ return ours;
299
+ }
300
+
301
+ /** Resolved once per host; a failure is not cached, so a later tick retries. */
302
+ const treeRoots = new Map<string, number>();
303
+
304
+ async function resolveTreeRoot(hostId: string, runner: CommandRunner): Promise<number | null> {
305
+ const cached = treeRoots.get(hostId);
306
+ if (cached !== undefined) return cached;
307
+
308
+ const root = await probeTreeRoot(runner);
309
+ if (root !== null) treeRoots.set(hostId, root);
310
+ return root;
311
+ }
312
+
313
+ /** Drop a host's cached connection identity when its transport goes away. */
314
+ export function forgetClopenRootPid(hostId: string): void {
315
+ ownConnections.delete(hostId);
316
+ treeRoots.delete(hostId);
317
+ verdicts.delete(hostId);
318
+ }
@@ -74,6 +74,37 @@ class SshForwardManager {
74
74
  };
75
75
  }
76
76
 
77
+ /**
78
+ * Forwards holding a listener on the machine Clopen runs on, for the port
79
+ * manager. `server` is the local `net.Server`, so its presence is what makes
80
+ * a forward local — remote forwards bind on the far host and are reported by
81
+ * `remoteListeners` instead.
82
+ */
83
+ localListeners(): Array<{ forward: SshForward; boundPort: number }> {
84
+ const listeners: Array<{ forward: SshForward; boundPort: number }> = [];
85
+ for (const active of this.running.values()) {
86
+ if (!active.server) continue;
87
+ listeners.push({ forward: active.forward, boundPort: active.boundPort });
88
+ }
89
+ return listeners;
90
+ }
91
+
92
+ /**
93
+ * Forwards holding a listener on a given SSH host. A remote forward asks the
94
+ * host's sshd to bind a port on Clopen's behalf, so that port is every bit as
95
+ * much Clopen's doing as a local one — the port manager names it the same way
96
+ * when looking at that host.
97
+ */
98
+ remoteListeners(connectionId: string): Array<{ forward: SshForward; boundPort: number }> {
99
+ const listeners: Array<{ forward: SshForward; boundPort: number }> = [];
100
+ for (const active of this.running.values()) {
101
+ if (active.server) continue;
102
+ if (active.forward.connectionId !== connectionId) continue;
103
+ listeners.push({ forward: active.forward, boundPort: active.boundPort });
104
+ }
105
+ return listeners;
106
+ }
107
+
77
108
  statusesForConnection(connectionId: string): SshForwardStatus[] {
78
109
  return sshPortForwardQueries.listForConnection(connectionId).map((forward) => this.status(forward));
79
110
  }
@@ -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
 
@@ -32,6 +32,7 @@ import { engineRouter } from './engine';
32
32
  import { stackRouter } from './stack';
33
33
  import { dbClientRouter } from './db-client';
34
34
  import { sshRouter } from './ssh';
35
+ import { portsRouter } from './ports';
35
36
  import { mcpRouter } from './mcp';
36
37
  import { skillsRouter } from './skills';
37
38
  import { commandsRouter } from './commands';
@@ -87,6 +88,7 @@ export const wsRouter = createRouter()
87
88
 
88
89
  // SSH client (terminal, SFTP, port forwarding)
89
90
  .merge(sshRouter)
91
+ .merge(portsRouter)
90
92
 
91
93
  // External MCP server management (install from the official registry)
92
94
  .merge(mcpRouter)
@@ -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
+ }));