@myrialabs/clopen 0.4.33 → 0.4.35

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 (75) hide show
  1. package/backend/auth/permissions.ts +10 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/db-client/connection-manager.ts +13 -0
  20. package/backend/files/file-watcher.test.ts +105 -0
  21. package/backend/files/file-watcher.ts +45 -1
  22. package/backend/git/git-service.test.ts +33 -0
  23. package/backend/git/git-service.ts +7 -3
  24. package/backend/git/nested-repos.test.ts +292 -1
  25. package/backend/git/nested-repos.ts +330 -17
  26. package/backend/host/runner.ts +204 -0
  27. package/backend/index.ts +20 -2
  28. package/backend/middleware/security.test.ts +95 -0
  29. package/backend/middleware/security.ts +114 -0
  30. package/backend/ports/attribute.test.ts +231 -0
  31. package/backend/ports/attribute.ts +444 -0
  32. package/backend/ports/kill.ts +203 -0
  33. package/backend/ports/monitor.ts +365 -0
  34. package/backend/ports/processes.test.ts +98 -0
  35. package/backend/ports/processes.ts +374 -0
  36. package/backend/ports/registry.ts +165 -0
  37. package/backend/ports/scan-host.ts +329 -0
  38. package/backend/ports/scan.test.ts +341 -0
  39. package/backend/ports/scan.ts +687 -0
  40. package/backend/ports/ssh-lineage.ts +318 -0
  41. package/backend/preview/browser/browser-video-capture.ts +84 -31
  42. package/backend/ssh/forwards.ts +31 -0
  43. package/backend/ws/auth/device.ts +1 -1
  44. package/backend/ws/auth/login.ts +8 -4
  45. package/backend/ws/containers/actions.ts +156 -0
  46. package/backend/ws/containers/index.ts +43 -0
  47. package/backend/ws/containers/list.ts +146 -0
  48. package/backend/ws/containers/logs.ts +43 -0
  49. package/backend/ws/containers/tunnel.ts +101 -0
  50. package/backend/ws/git/log.ts +3 -1
  51. package/backend/ws/git/status.ts +37 -27
  52. package/backend/ws/index.ts +4 -0
  53. package/backend/ws/message-rate-limiter.test.ts +45 -0
  54. package/backend/ws/message-rate-limiter.ts +34 -3
  55. package/backend/ws/ports/index.ts +19 -0
  56. package/backend/ws/ports/kill.ts +80 -0
  57. package/backend/ws/ports/list.ts +60 -0
  58. package/backend/ws/ssh/connections.ts +8 -0
  59. package/backend/ws/system/device-info.ts +99 -43
  60. package/dist/assets/{index-BF4buYmI.js → index-B0iIhSO9.js} +1 -1
  61. package/dist/assets/{index-BW0DA8NV.js → index-BRJqss6F.js} +1 -1
  62. package/dist/assets/main-Buko4D0t.css +1 -0
  63. package/dist/assets/{main-BbwWLJRN.js → main-C_iGUZyL.js} +468 -447
  64. package/dist/index.html +2 -2
  65. package/dist/manifest.json +9 -2
  66. package/package.json +1 -1
  67. package/shared/types/containers/container.ts +366 -0
  68. package/shared/types/containers/index.ts +5 -0
  69. package/shared/types/host/index.ts +18 -0
  70. package/shared/types/ports/index.ts +5 -0
  71. package/shared/types/ports/port.ts +230 -0
  72. package/shared/utils/logger.ts +3 -0
  73. package/shared/utils/ws-client.ts +67 -12
  74. package/shared/utils/ws-server.ts +64 -13
  75. package/dist/assets/main-CCvRMXlP.css +0 -1
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Containers — keeping the list live.
3
+ *
4
+ * The same contract the port table runs on, for the same reason: neither Docker
5
+ * nor Podman offers a portable way to be *told* that a container's state
6
+ * changed. Docker has an event stream, Podman has a different one, neither
7
+ * exists on a host that has only the other, and both would need a channel held
8
+ * open per host. Polling a `ps` is one cheap command, works identically on both
9
+ * runtimes and over both transports, and earns its keep by being quiet:
10
+ *
11
+ * - A watched host is listed every two seconds locally, every four over SSH,
12
+ * where each scan is a round trip on the connection the terminal and file
13
+ * browser are also using.
14
+ * - Results are diffed server-side and pushed only when something actually
15
+ * changed, so a host whose containers are steady costs no traffic at all.
16
+ * - With no panel open, the only work is the sidebar count on this machine, and
17
+ * only when this machine has a runtime at all.
18
+ * - A remote host is scanned only while its tab is open, on a lease borrowed
19
+ * from the pool the terminal and file browser already keep warm.
20
+ */
21
+
22
+ import type { ContainerScanResult } from '$shared/types/containers';
23
+ import { LOCAL_HOST_ID } from '$shared/types/host';
24
+ import { HostContainerScanner } from './scan';
25
+ import { forgetContainerPortIndex, noteContainerScan } from './port-index';
26
+ import { containerArgv, detectRuntime, forgetRuntime, tryRun } from './runtime';
27
+ import {
28
+ LocalCommandRunner,
29
+ SshCommandRunner,
30
+ detectRemotePlatform,
31
+ localPlatform,
32
+ type CommandRunner,
33
+ type ProbePlatform
34
+ } from '../host/runner';
35
+ import { sshClientPool, type SshLease } from '../ssh/client-pool';
36
+ import { sshConnectionQueries } from '../database/queries';
37
+ import { ws } from '../utils/ws';
38
+ import { debug } from '$shared/utils/logger';
39
+
40
+ /**
41
+ * Panel open on this machine.
42
+ *
43
+ * Slower than the port table's one second, on purpose. A listing costs more —
44
+ * on a machine with a few dozen containers it is well over a hundred
45
+ * milliseconds, where a warm port scan is tens — and containers change state
46
+ * far less often than sockets do. Two seconds still reads as live.
47
+ */
48
+ const WATCH_INTERVAL_MS = 2_000;
49
+ /** Panel open on an SSH host, paced to stay out of the terminal's way. */
50
+ const REMOTE_WATCH_INTERVAL_MS = 4_000;
51
+ /** Panel closed: only the sidebar count on this machine. */
52
+ const BADGE_INTERVAL_MS = 15_000;
53
+
54
+ interface HostState {
55
+ scanner: HostContainerScanner;
56
+ runner: CommandRunner;
57
+ platform: ProbePlatform;
58
+ lease: SshLease | null;
59
+ /** User ids currently looking at this host. */
60
+ watchers: Set<string>;
61
+ timer: ReturnType<typeof setInterval> | null;
62
+ last: ContainerScanResult | null;
63
+ signature: string;
64
+ scanning: boolean;
65
+ }
66
+
67
+ /**
68
+ * What a client would notice changing. Excludes the timestamp and the status
69
+ * text's own clock — `Up 3 minutes` becomes `Up 4 minutes` on its own — so an
70
+ * idle host produces an identical signature tick after tick and nothing is sent.
71
+ */
72
+ function signatureOf(result: ContainerScanResult): string {
73
+ if (result.error) return `error:${result.error}`;
74
+ const containers = result.entries
75
+ .map(
76
+ (entry) =>
77
+ `${entry.id}|${entry.state}|${entry.health}|${entry.name}|${entry.image}|${entry.ports
78
+ .map((port) => `${port.protocol}${port.hostPort ?? '-'}:${port.containerPort}`)
79
+ .join('/')}`
80
+ )
81
+ .join('\n');
82
+ const images = result.images.map((image) => image.key).join(',');
83
+ const volumes = result.volumes.map((volume) => `${volume.key}:${volume.usedBy.length}`).join(',');
84
+ return `${result.runtime ?? 'none'}:${result.runtimeProblem}\n${containers}\n${images}\n${volumes}`;
85
+ }
86
+
87
+ class ContainerMonitor {
88
+ private hosts = new Map<string, HostState>();
89
+ /**
90
+ * Hosts being set up right now. Creating a host acquires an SSH lease, so two
91
+ * concurrent callers would each take one and only the last would be kept —
92
+ * the other then leaks for the life of the process.
93
+ */
94
+ private opening = new Map<string, Promise<HostState>>();
95
+ private badgeTimer: ReturnType<typeof setInterval> | null = null;
96
+ private badgeCount = 0;
97
+
98
+ // -- host lifecycle ------------------------------------------------------
99
+
100
+ private async ensureHost(hostId: string): Promise<HostState> {
101
+ const existing = this.hosts.get(hostId);
102
+ if (existing) return existing;
103
+
104
+ const opening = this.opening.get(hostId);
105
+ if (opening) return opening;
106
+
107
+ const created = this.createHost(hostId)
108
+ .then((state) => {
109
+ // Another caller may have finished first; keep theirs and let this
110
+ // one's lease go rather than overwriting it.
111
+ const settled = this.hosts.get(hostId);
112
+ if (settled) {
113
+ state.lease?.release();
114
+ return settled;
115
+ }
116
+ this.hosts.set(hostId, state);
117
+ return state;
118
+ })
119
+ .finally(() => {
120
+ this.opening.delete(hostId);
121
+ });
122
+
123
+ this.opening.set(hostId, created);
124
+ return created;
125
+ }
126
+
127
+ private async createHost(hostId: string): Promise<HostState> {
128
+ if (hostId === LOCAL_HOST_ID) {
129
+ const runner = new LocalCommandRunner();
130
+ const platform = localPlatform();
131
+ return {
132
+ scanner: new HostContainerScanner(hostId, 'this machine', runner, platform),
133
+ runner,
134
+ platform,
135
+ lease: null,
136
+ watchers: new Set(),
137
+ timer: null,
138
+ last: null,
139
+ signature: '',
140
+ scanning: false
141
+ };
142
+ }
143
+
144
+ const connection = sshConnectionQueries.get(hostId);
145
+ if (!connection) throw new Error('That SSH host no longer exists.');
146
+
147
+ const lease = await sshClientPool.acquire(hostId);
148
+ try {
149
+ const runner = new SshCommandRunner(connection.name, lease.client);
150
+ const platform = await detectRemotePlatform(hostId, runner);
151
+ return {
152
+ scanner: new HostContainerScanner(hostId, connection.name, runner, platform),
153
+ runner,
154
+ platform,
155
+ lease,
156
+ watchers: new Set(),
157
+ timer: null,
158
+ last: null,
159
+ signature: '',
160
+ scanning: false
161
+ };
162
+ } catch (error) {
163
+ lease.release();
164
+ throw error;
165
+ }
166
+ }
167
+
168
+ private disposeHost(hostId: string): void {
169
+ const state = this.hosts.get(hostId);
170
+ if (!state) return;
171
+ if (state.timer) clearInterval(state.timer);
172
+ state.lease?.release();
173
+ this.hosts.delete(hostId);
174
+ if (hostId !== LOCAL_HOST_ID) {
175
+ forgetRuntime(hostId);
176
+ forgetContainerPortIndex(hostId);
177
+ }
178
+ }
179
+
180
+ // -- scanning ------------------------------------------------------------
181
+
182
+ /**
183
+ * Run one scan and push it to watchers if anything changed. Overlapping ticks
184
+ * are dropped rather than queued: a slow host would otherwise build a backlog
185
+ * of listings that are all stale by the time they run.
186
+ */
187
+ private async tick(hostId: string): Promise<void> {
188
+ const state = this.hosts.get(hostId);
189
+ if (!state || state.scanning) return;
190
+
191
+ state.scanning = true;
192
+ try {
193
+ const result = await state.scanner.scan();
194
+ state.last = result;
195
+ // The port table reads this for free while a Containers panel is open.
196
+ noteContainerScan(result);
197
+
198
+ if (hostId === LOCAL_HOST_ID) this.publishBadge(countRunning(result));
199
+
200
+ const signature = signatureOf(result);
201
+ if (signature === state.signature) return;
202
+ state.signature = signature;
203
+
204
+ for (const userId of state.watchers) {
205
+ ws.emit.user(userId, 'containers:changed', { result });
206
+ }
207
+ } catch (error) {
208
+ debug.warn('containers', `scan failed for ${hostId}:`, error);
209
+ } finally {
210
+ state.scanning = false;
211
+ }
212
+ }
213
+
214
+ private ensureTimer(hostId: string): void {
215
+ const state = this.hosts.get(hostId);
216
+ if (!state || state.timer) return;
217
+ state.timer = setInterval(
218
+ () => {
219
+ void this.tick(hostId);
220
+ },
221
+ hostId === LOCAL_HOST_ID ? WATCH_INTERVAL_MS : REMOTE_WATCH_INTERVAL_MS
222
+ );
223
+ // A poll for a panel nobody is looking at must not hold the process open.
224
+ state.timer.unref?.();
225
+ }
226
+
227
+ // -- public API ----------------------------------------------------------
228
+
229
+ /** Start watching a host for a user, and return the first listing immediately. */
230
+ async watch(hostId: string, userId: string): Promise<ContainerScanResult> {
231
+ const state = await this.ensureHost(hostId);
232
+
233
+ state.watchers.add(userId);
234
+
235
+ // Scan through the scanner's own guard, so this first read cannot run
236
+ // alongside a tick on the same connection.
237
+ const result = state.last ?? (await state.scanner.scan());
238
+ state.last = result;
239
+ state.signature = signatureOf(result);
240
+ noteContainerScan(result);
241
+ if (hostId === LOCAL_HOST_ID) this.publishBadge(countRunning(result));
242
+
243
+ this.ensureTimer(hostId);
244
+ return result;
245
+ }
246
+
247
+ /** Stop watching. The host is torn down once nobody is left looking. */
248
+ unwatch(hostId: string, userId: string): void {
249
+ const state = this.hosts.get(hostId);
250
+ if (!state) return;
251
+
252
+ state.watchers.delete(userId);
253
+ if (state.watchers.size > 0) return;
254
+
255
+ // The local host keeps its scanner: the badge ticker reuses it, and the
256
+ // image catalogue would otherwise be re-read from scratch on every open.
257
+ if (hostId === LOCAL_HOST_ID) {
258
+ if (state.timer) clearInterval(state.timer);
259
+ state.timer = null;
260
+ return;
261
+ }
262
+ this.disposeHost(hostId);
263
+ }
264
+
265
+ /** A one-shot listing, for a host the caller is not watching. */
266
+ async scanOnce(hostId: string): Promise<ContainerScanResult> {
267
+ const existing = this.hosts.get(hostId);
268
+ if (existing) return existing.scanner.scan();
269
+
270
+ const state = await this.createHost(hostId);
271
+ try {
272
+ return await state.scanner.scan();
273
+ } finally {
274
+ // The lease goes back, but the runtime answer stays: it is keyed by host
275
+ // with its own expiry, and an action that lists then acts would
276
+ // otherwise re-probe the host twice for something that cannot have
277
+ // changed in between.
278
+ state.lease?.release();
279
+ }
280
+ }
281
+
282
+ /** The runner and platform for a host, so an action can reuse the transport. */
283
+ async withHost<T>(
284
+ hostId: string,
285
+ fn: (runner: CommandRunner, platform: ProbePlatform) => Promise<T>
286
+ ): Promise<T> {
287
+ const existing = this.hosts.get(hostId);
288
+ if (existing) {
289
+ // Take a lease of this operation's own, rather than riding the watch's.
290
+ // A prune or a disk reading outlives the panel that started it — that is
291
+ // the point of them — and closing that panel ends the watch, releases
292
+ // its lease, and leaves the pool free to sweep the connection out from
293
+ // under a command that is still running. Refcounting the transport for
294
+ // the length of the operation is what makes closing the panel harmless.
295
+ const lease = existing.lease ? await sshClientPool.acquire(hostId) : null;
296
+ try {
297
+ return await fn(existing.runner, existing.platform);
298
+ } finally {
299
+ lease?.release();
300
+ }
301
+ }
302
+
303
+ const state = await this.createHost(hostId);
304
+ try {
305
+ return await fn(state.runner, state.platform);
306
+ } finally {
307
+ state.lease?.release();
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Force the next tick to push, after an action that changed the list. The
313
+ * image and volume catalogue is dropped too: starting a container is exactly
314
+ * when a volume's "in use" answer changes.
315
+ */
316
+ invalidate(hostId: string): void {
317
+ const state = this.hosts.get(hostId);
318
+ if (!state) return;
319
+ state.signature = '';
320
+ state.scanner.invalidateCatalog();
321
+ void this.tick(hostId);
322
+ }
323
+
324
+ /** Whether a container exists on a host — the check before exec or logs. */
325
+ async findContainer(hostId: string, containerId: string) {
326
+ const result = await this.scanOnce(hostId);
327
+ return result.entries.find((entry) => entry.id === containerId) ?? null;
328
+ }
329
+
330
+ // -- sidebar count -------------------------------------------------------
331
+
332
+ private publishBadge(count: number): void {
333
+ if (count === this.badgeCount) return;
334
+ this.badgeCount = count;
335
+ ws.emit.global('containers:badge', { count });
336
+ }
337
+
338
+ /**
339
+ * The count behind the sidebar dot: containers running on this machine.
340
+ *
341
+ * Deliberately not a scan. The badge runs forever, whether or not anyone ever
342
+ * opens the panel, and a scan reads the image and volume catalogues too — on
343
+ * a developer's machine that is hundreds of volumes listed every fifteen
344
+ * seconds to produce a single number. `ps --quiet` answers the actual
345
+ * question and nothing else.
346
+ *
347
+ * Returned as well as published, because a client that has just loaded needs
348
+ * the current number and pushes only carry changes — a page refresh would
349
+ * otherwise sit at zero until something happened to move it.
350
+ */
351
+ async refreshBadge(): Promise<number> {
352
+ const local = this.hosts.get(LOCAL_HOST_ID);
353
+ // A watched panel is already listing; reuse what it last saw.
354
+ if (local?.timer && local.last) return countRunning(local.last);
355
+
356
+ try {
357
+ const state = await this.ensureHost(LOCAL_HOST_ID);
358
+ const info = await detectRuntime(LOCAL_HOST_ID, state.runner, state.platform);
359
+ // No runtime is a real answer, and a cached one: zero costs no command.
360
+ if (info.problem !== 'none' || !info.runtime) {
361
+ this.publishBadge(0);
362
+ return 0;
363
+ }
364
+
365
+ const result = await tryRun(
366
+ state.runner,
367
+ containerArgv(info.runtime, state.platform, ['ps', '--quiet', '--filter', 'status=running']),
368
+ 10_000
369
+ );
370
+ if (result.code !== 0) return this.badgeCount;
371
+
372
+ const count = result.stdout.split('\n').filter((line) => line.trim().length > 0).length;
373
+ this.publishBadge(count);
374
+ return count;
375
+ } catch (error) {
376
+ debug.warn('containers', 'badge count failed:', error);
377
+ return this.badgeCount;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * The periodic count. A machine with no runtime costs one cached lookup and
383
+ * no command at all, because the runtime probe remembers that answer.
384
+ */
385
+ private async badgeTick(): Promise<void> {
386
+ const local = this.hosts.get(LOCAL_HOST_ID);
387
+ if (local?.timer) return; // A watched panel already refreshes the count.
388
+ await this.refreshBadge();
389
+ }
390
+
391
+ start(): void {
392
+ if (this.badgeTimer) return;
393
+ this.badgeTimer = setInterval(() => {
394
+ void this.badgeTick();
395
+ }, BADGE_INTERVAL_MS);
396
+ this.badgeTimer.unref?.();
397
+ }
398
+
399
+ stop(): void {
400
+ if (this.badgeTimer) clearInterval(this.badgeTimer);
401
+ this.badgeTimer = null;
402
+ for (const hostId of [...this.hosts.keys()]) this.disposeHost(hostId);
403
+ }
404
+ }
405
+
406
+ function countRunning(result: ContainerScanResult): number {
407
+ return result.entries.filter((entry) => entry.state === 'running').length;
408
+ }
409
+
410
+ export const containerMonitor = new ContainerMonitor();