@myrialabs/clopen 0.4.34 → 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 (60) hide show
  1. package/backend/auth/permissions.ts +7 -0
  2. package/backend/containers/actions.ts +316 -0
  3. package/backend/containers/disk-usage.test.ts +68 -0
  4. package/backend/containers/disk-usage.ts +170 -0
  5. package/backend/containers/logs.ts +335 -0
  6. package/backend/containers/monitor.ts +410 -0
  7. package/backend/containers/parse.test.ts +599 -0
  8. package/backend/containers/parse.ts +905 -0
  9. package/backend/containers/port-index.test.ts +91 -0
  10. package/backend/containers/port-index.ts +198 -0
  11. package/backend/containers/prune-job.test.ts +148 -0
  12. package/backend/containers/prune-job.ts +129 -0
  13. package/backend/containers/pty-backend.ts +337 -0
  14. package/backend/containers/pty.ts +114 -0
  15. package/backend/containers/runtime.ts +218 -0
  16. package/backend/containers/scan.ts +293 -0
  17. package/backend/files/file-watcher.test.ts +105 -0
  18. package/backend/files/file-watcher.ts +45 -1
  19. package/backend/git/git-service.test.ts +33 -0
  20. package/backend/git/git-service.ts +7 -3
  21. package/backend/git/nested-repos.test.ts +292 -1
  22. package/backend/git/nested-repos.ts +330 -17
  23. package/backend/{ports → host}/runner.ts +19 -10
  24. package/backend/index.ts +11 -2
  25. package/backend/ports/attribute.ts +1 -1
  26. package/backend/ports/kill.ts +1 -1
  27. package/backend/ports/monitor.ts +1 -1
  28. package/backend/ports/processes.ts +1 -1
  29. package/backend/ports/scan-host.ts +77 -8
  30. package/backend/ports/scan.test.ts +1 -1
  31. package/backend/ports/scan.ts +1 -1
  32. package/backend/ports/ssh-lineage.ts +1 -1
  33. package/backend/preview/browser/browser-video-capture.ts +84 -31
  34. package/backend/ws/containers/actions.ts +156 -0
  35. package/backend/ws/containers/index.ts +43 -0
  36. package/backend/ws/containers/list.ts +146 -0
  37. package/backend/ws/containers/logs.ts +43 -0
  38. package/backend/ws/containers/tunnel.ts +101 -0
  39. package/backend/ws/git/log.ts +3 -1
  40. package/backend/ws/git/status.ts +37 -27
  41. package/backend/ws/index.ts +2 -0
  42. package/backend/ws/message-rate-limiter.test.ts +45 -0
  43. package/backend/ws/message-rate-limiter.ts +34 -3
  44. package/backend/ws/ssh/connections.ts +8 -0
  45. package/backend/ws/system/device-info.ts +99 -43
  46. package/dist/assets/{index-vW2RpdHu.js → index-B0iIhSO9.js} +1 -1
  47. package/dist/assets/{index-gGTMFUa8.js → index-BRJqss6F.js} +1 -1
  48. package/dist/assets/main-Buko4D0t.css +1 -0
  49. package/dist/assets/{main-ZCojSzvW.js → main-C_iGUZyL.js} +467 -449
  50. package/dist/index.html +2 -2
  51. package/dist/manifest.json +9 -2
  52. package/package.json +1 -1
  53. package/shared/types/containers/container.ts +366 -0
  54. package/shared/types/containers/index.ts +5 -0
  55. package/shared/types/host/index.ts +18 -0
  56. package/shared/types/ports/port.ts +47 -9
  57. package/shared/utils/logger.ts +2 -0
  58. package/shared/utils/ws-client.ts +67 -12
  59. package/shared/utils/ws-server.ts +64 -13
  60. package/dist/assets/main-CYCMEbXB.css +0 -1
@@ -24,7 +24,7 @@ import type {
24
24
  PortSocket,
25
25
  PortSocketState
26
26
  } from '$shared/types/ports';
27
- import { posixArgv, type CommandRunner, type ProbePlatform } from './runner';
27
+ import { posixArgv, type CommandRunner, type ProbePlatform } from '../host/runner';
28
28
  import { debug } from '$shared/utils/logger';
29
29
 
30
30
  /** Per-host memory of which probe answered, held by the host's scanner. */
@@ -35,7 +35,7 @@
35
35
  */
36
36
 
37
37
  import type { PortProcess } from '$shared/types/ports';
38
- import { posixArgv, type CommandRunner, type ProbePlatform } from './runner';
38
+ import { posixArgv, type CommandRunner, type ProbePlatform } from '../host/runner';
39
39
  import { parsePsOutput } from './processes';
40
40
  import { debug } from '$shared/utils/logger';
41
41
 
@@ -162,18 +162,23 @@ interface VideoStreamSession {
162
162
  scriptInjected: boolean; // Track if persistent script was injected
163
163
  scriptsPreInjected: boolean; // Track if scripts were pre-injected during tab creation
164
164
  /**
165
- * When the page last reported frames reaching its encoder. A connected
166
- * viewer while this stands still is watching a stream that has stopped
167
- * producing — which looks identical, from the client, to a slow page.
165
+ * When the page last reported ANYTHING, frames or not.
166
+ *
167
+ * This is the liveness signal, and the distinction it draws is the whole
168
+ * point: the page ticks a stats report every two seconds for as long as its
169
+ * encoder loop is alive, whether or not there was anything to encode. Reports
170
+ * arriving with zero frames mean a still picture. Reports stopping mean the
171
+ * loop itself is gone — a navigation that took the injected script with it, a
172
+ * context that was torn down — which is the only thing a repair can fix.
168
173
  */
169
- lastEncodedAt: number;
174
+ lastPageReportAt: number;
170
175
  /** Guards the watchdog against re-entering while a repair is in flight. */
171
176
  repairing: boolean;
172
177
  /**
173
- * Repairs attempted since the stream last produced anything. A repair that
174
- * did not restore frames must escalate rather than be repeated: the cheap
175
- * one asks the page what it thinks, and a page whose own answer is the
176
- * wrong one will give the same answer every time.
178
+ * Repairs attempted since the page last reported in. A repair that did not
179
+ * restore reporting must escalate rather than be repeated: the cheap one asks
180
+ * the page what it thinks, and a page whose own answer is the wrong one will
181
+ * give the same answer every time.
177
182
  */
178
183
  stallRounds: number;
179
184
  /** Codecs every viewer can decode — one encoder serves them all. */
@@ -588,11 +593,18 @@ export class BrowserVideoCapture extends EventEmitter {
588
593
  private static readonly VIEWER_HANDSHAKE_TTL_MS = 45_000;
589
594
 
590
595
  /**
591
- * Silence tolerated from a connected viewer's stream before the watchdog
592
- * repairs it. Two encoder-stat windows plus slack — long enough that a
593
- * genuinely idle page (which still tops off) never trips it.
596
+ * Silence tolerated from the PAGE before the watchdog repairs the stream,
597
+ * and the interval the watchdog itself runs on.
598
+ *
599
+ * The page reports encoder stats every two seconds for as long as its capture
600
+ * loop is alive, so this is three missed reports: late enough that a slow tick
601
+ * or a busy host is never mistaken for a dead page, early enough that a
602
+ * genuinely broken stream is repaired before anyone reaches for reload.
603
+ *
604
+ * This deliberately measures REPORTS, not frames — a still page produces no
605
+ * frames at all and is perfectly healthy. See `checkForStall`.
594
606
  */
595
- private static readonly STREAM_STALL_MS = 6_000;
607
+ private static readonly PAGE_SILENCE_MS = 6_000;
596
608
 
597
609
  /**
598
610
  * Cheap stall repairs before the watchdog stops taking the page's word for
@@ -740,7 +752,7 @@ export class BrowserVideoCapture extends EventEmitter {
740
752
  viewers: new Map(),
741
753
  scriptInjected: false,
742
754
  scriptsPreInjected: false,
743
- lastEncodedAt: 0,
755
+ lastPageReportAt: 0,
744
756
  repairing: false,
745
757
  stallRounds: 0,
746
758
  codecSupport: { ...DEFAULT_CODEC_SUPPORT },
@@ -856,7 +868,10 @@ export class BrowserVideoCapture extends EventEmitter {
856
868
  // for the first mouse move to see anything. Push one refresh
857
869
  // frame as soon as the peer is up.
858
870
  if (state === 'connected' && videoSession.tab) {
859
- videoSession.lastEncodedAt = Date.now();
871
+ // A peer that just reached `connected` is a page that was talking to
872
+ // us a moment ago — give it a fresh silence window rather than
873
+ // judging it on a clock that predates the handshake.
874
+ videoSession.lastPageReportAt = Date.now();
860
875
  void this.requestKeyframe(sessionId, videoSession.tab);
861
876
  }
862
877
 
@@ -1045,7 +1060,8 @@ export class BrowserVideoCapture extends EventEmitter {
1045
1060
  this.reconcileViewers(videoSession, health);
1046
1061
  }
1047
1062
 
1048
- videoSession.lastEncodedAt = Date.now();
1063
+ // `ensureLive` just heard from the page directly, so this IS a report.
1064
+ videoSession.lastPageReportAt = Date.now();
1049
1065
  this.ensureWatchdog();
1050
1066
  return true;
1051
1067
  }
@@ -1561,7 +1577,7 @@ export class BrowserVideoCapture extends EventEmitter {
1561
1577
  if (this.reapStaleViewers(videoSession)) continue;
1562
1578
  this.checkForStall(videoSession);
1563
1579
  }
1564
- }, BrowserVideoCapture.STREAM_STALL_MS);
1580
+ }, BrowserVideoCapture.PAGE_SILENCE_MS);
1565
1581
 
1566
1582
  // Nothing here should hold the process open on its own.
1567
1583
  this.watchdogTimer.unref?.();
@@ -1606,36 +1622,71 @@ export class BrowserVideoCapture extends EventEmitter {
1606
1622
  }
1607
1623
 
1608
1624
  /**
1609
- * Repair a stream that has stopped producing while someone is watching it.
1625
+ * Repair a stream whose PAGE has stopped reporting while someone is watching.
1610
1626
  *
1611
1627
  * Recovery used to live entirely in the viewer: it noticed no first frame,
1612
1628
  * asked for a screencast refresh, then re-handshook. That only works while
1613
1629
  * the *client's* view of the problem is right — and the failures that stuck
1614
1630
  * were the ones where the client did everything correctly and the source
1615
- * was the broken half. Repairing from here closes that gap, and costs
1616
- * nothing on a healthy stream because even an idle page still tops off.
1631
+ * was the broken half. Repairing from here closes that gap.
1632
+ *
1633
+ * WHAT COUNTS AS A STALL, AND WHY IT CHANGED
1634
+ *
1635
+ * This used to key on `lastEncodedAt` — frames reaching the encoder — on the
1636
+ * stated assumption that "even an idle page still tops off". That assumption
1637
+ * was wrong, and the bug it caused was severe.
1638
+ *
1639
+ * Capture is damage-driven: `framesAttempted` is only incremented for motion
1640
+ * frames (see `shouldSkipMotionFrame` in scripts/video-stream.ts), and the
1641
+ * still-page top-off is a one-shot that fires after motion stops, not a
1642
+ * heartbeat. So a page that is simply SITTING THERE — the normal case, a user
1643
+ * looking at their app without touching it — reports zero frames forever, and
1644
+ * every one of those reports was read as "the stream is dead".
1645
+ *
1646
+ * The result was a permanent loop on every idle preview: six seconds of
1647
+ * stillness triggered a repair, twelve seconds triggered a FORCED peer
1648
+ * rebuild, which drops every viewer into a re-handshake — the reload with a
1649
+ * progress bar that users saw arrive every few seconds and could not explain.
1650
+ * The rebuild produced a keyframe, which reset the counters, which started
1651
+ * the same clock again. It also made the failure self-sustaining across the
1652
+ * rest of the app: each rebuild is a burst of CDP work plus handshake round
1653
+ * trips on the shared socket, so the busier the instance, the more of them
1654
+ * were in flight at once.
1655
+ *
1656
+ * The honest signal is whether the PAGE is still talking to us, not whether
1657
+ * it has anything to show. Its stats timer ticks every two seconds for as
1658
+ * long as the encoder loop is alive, so silence there — and only there —
1659
+ * means the loop is genuinely gone. A still picture is not a stall.
1660
+ *
1661
+ * The other real failure, an in-page capture that ends on its own, is already
1662
+ * detected explicitly in `applyEncoderStats` rather than inferred from frame
1663
+ * absence, so nothing is lost by no longer guessing here.
1617
1664
  */
1618
1665
  private checkForStall(videoSession: VideoStreamSession): void {
1619
1666
  if (videoSession.paused || videoSession.repairing || !videoSession.tab) return;
1620
1667
  if (videoSession.viewers.size === 0) return;
1621
1668
  if (!Array.from(videoSession.viewers.values()).some((viewer) => viewer.connected)) return;
1622
1669
 
1623
- const silentFor = Date.now() - videoSession.lastEncodedAt;
1624
- if (videoSession.lastEncodedAt === 0 || silentFor < BrowserVideoCapture.STREAM_STALL_MS) return;
1670
+ // Nothing reported yet: the stream is still coming up and its own
1671
+ // handshake path owns that window.
1672
+ if (videoSession.lastPageReportAt === 0) return;
1673
+
1674
+ const silentFor = Date.now() - videoSession.lastPageReportAt;
1675
+ if (silentFor < BrowserVideoCapture.PAGE_SILENCE_MS) return;
1625
1676
 
1626
1677
  const { sessionId, tab } = videoSession;
1627
1678
  videoSession.stallRounds++;
1628
1679
 
1629
1680
  // The first round asks the page what state it is in and repairs from
1630
1681
  // that answer, which is cheap and keeps every viewer's peer intact. Once
1631
- // that has been tried and the stream is still silent, the page's own
1682
+ // that has been tried and the page is still silent, the page's own
1632
1683
  // account is the thing that cannot be trusted — so rebuild the peer
1633
1684
  // outright. Viewers lose their connection and re-handshake, which is a
1634
1685
  // visible hiccup, but they are looking at a frozen picture either way.
1635
1686
  const force = videoSession.stallRounds > BrowserVideoCapture.STALL_REPAIR_ROUNDS;
1636
1687
  debug.warn(
1637
1688
  'webcodecs',
1638
- `Stream for ${sessionId} produced nothing for ${silentFor}ms — ` +
1689
+ `Page for ${sessionId} stopped reporting for ${silentFor}ms — ` +
1639
1690
  `${force ? 'rebuilding the page peer' : 'repairing'} (round ${videoSession.stallRounds})`
1640
1691
  );
1641
1692
 
@@ -1647,7 +1698,10 @@ export class BrowserVideoCapture extends EventEmitter {
1647
1698
  .catch((error) => debug.warn('webcodecs', `Stall repair failed for ${sessionId}:`, error))
1648
1699
  .finally(() => {
1649
1700
  videoSession.repairing = false;
1650
- videoSession.lastEncodedAt = Date.now();
1701
+ // Give the repaired page a full silence window to report in before
1702
+ // it can be judged again. Without this the next tick would measure
1703
+ // against a clock that never moved and escalate immediately.
1704
+ videoSession.lastPageReportAt = Date.now();
1651
1705
  });
1652
1706
  }
1653
1707
 
@@ -1661,13 +1715,12 @@ export class BrowserVideoCapture extends EventEmitter {
1661
1715
 
1662
1716
  videoSession.captureMode = stats.captureMode || videoSession.captureMode;
1663
1717
 
1664
- // Frames reaching the encoder is the one signal that means the pipeline
1665
- // is genuinely alive end to end. The counter is per-window, so any
1666
- // non-zero report is proof of life for this window.
1667
- if (stats.framesAttempted > 0) {
1668
- videoSession.lastEncodedAt = Date.now();
1669
- videoSession.stallRounds = 0;
1670
- }
1718
+ // THE report arriving is proof the page's capture loop is alive — whether
1719
+ // or not it had anything to encode. This is what the watchdog measures.
1720
+ // Frames are a property of the CONTENT (a still page has none and is
1721
+ // perfectly healthy); reports are a property of the PIPELINE.
1722
+ videoSession.lastPageReportAt = Date.now();
1723
+ videoSession.stallRounds = 0;
1671
1724
 
1672
1725
  // In-page capture can end on its own — the captured surface goes away
1673
1726
  // on some navigations — and the page has no way to start a screencast.
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Containers — changing something. Admin only, all of it.
3
+ *
4
+ * The routes are listed in ADMIN_ONLY_ROUTES; these handlers still check host
5
+ * access against the caller's real role rather than a hardcoded one, because a
6
+ * gate that trusts its caller is no gate at all.
7
+ *
8
+ * Stopping a container takes down whatever it serves, for everyone — the same
9
+ * reason stopping a port is admin-only — and removing an image or a volume
10
+ * takes down something nobody can bring back by pressing start.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { createRouter } from '$shared/utils/ws-server';
15
+ import { LOCAL_HOST_ID } from '$shared/types/host';
16
+ import { removeResource, runContainerAction } from '../../containers/actions';
17
+ import { dismissPrune, pruneJobFor, startPrune } from '../../containers/prune-job';
18
+ import { requireHostAccess } from './list';
19
+ import { containerMonitor } from '../../containers/monitor';
20
+ import { sshConnectionQueries } from '../../database/queries';
21
+ import { ws } from '../../utils/ws';
22
+
23
+ function requireManageAccess(conn: Parameters<typeof ws.getUserId>[0], hostId: string): void {
24
+ if (hostId === LOCAL_HOST_ID) return;
25
+ sshConnectionQueries.ensureAccess(hostId, ws.getUserId(conn), ws.getRole(conn) === 'admin');
26
+ }
27
+
28
+ const ACTIONS = [
29
+ t.Literal('start'),
30
+ t.Literal('stop'),
31
+ t.Literal('restart'),
32
+ t.Literal('pause'),
33
+ t.Literal('unpause'),
34
+ t.Literal('remove'),
35
+ t.Literal('force-remove')
36
+ ];
37
+
38
+ const PRUNE_KINDS = [
39
+ t.Literal('containers'),
40
+ t.Literal('dangling-images'),
41
+ t.Literal('images'),
42
+ t.Literal('volumes'),
43
+ t.Literal('networks'),
44
+ t.Literal('build-cache')
45
+ ];
46
+
47
+ export const containersActionHandler = createRouter()
48
+ .http(
49
+ 'containers:action',
50
+ {
51
+ data: t.Object({
52
+ hostId: t.String({ minLength: 1 }),
53
+ containerId: t.String({ minLength: 12 }),
54
+ action: t.Union(ACTIONS)
55
+ }),
56
+ response: t.Any()
57
+ },
58
+ async ({ data, conn }) => {
59
+ requireManageAccess(conn, data.hostId);
60
+
61
+ // Re-read before acting rather than trusting the row the client clicked:
62
+ // a listing is a second or two old, and a container can be removed and
63
+ // its name reused in that time.
64
+ const container = await containerMonitor.findContainer(data.hostId, data.containerId);
65
+ if (!container) {
66
+ return { result: { ok: false, error: null }, gone: true };
67
+ }
68
+ if (!container.canManage) {
69
+ return {
70
+ result: { ok: false, error: `${container.name} cannot be changed from here right now.` },
71
+ gone: false
72
+ };
73
+ }
74
+
75
+ return {
76
+ result: await runContainerAction(data.hostId, data.containerId, data.action),
77
+ gone: false
78
+ };
79
+ }
80
+ )
81
+
82
+ /**
83
+ * Remove one image, volume or network.
84
+ *
85
+ * Containers go through `containers:action` instead, because removing one is
86
+ * part of its lifecycle and the confirmation has to know whether it is still
87
+ * running. Everything else has no lifecycle — it exists or it does not.
88
+ */
89
+ .http(
90
+ 'containers:remove',
91
+ {
92
+ data: t.Object({
93
+ hostId: t.String({ minLength: 1 }),
94
+ kind: t.Union([t.Literal('image'), t.Literal('volume'), t.Literal('network')]),
95
+ id: t.String({ minLength: 1 }),
96
+ force: t.Optional(t.Boolean())
97
+ }),
98
+ response: t.Any()
99
+ },
100
+ async ({ data, conn }) => {
101
+ requireManageAccess(conn, data.hostId);
102
+ return { result: await removeResource(data.hostId, data.kind, data.id, data.force === true) };
103
+ }
104
+ )
105
+
106
+ /**
107
+ * Clear up whatever is not in use.
108
+ *
109
+ * Takes a list rather than doing everything, because the kinds differ by what
110
+ * they cost to get back: a stopped container is nothing, an unused image is a
111
+ * pull or a build. The caller decides; each kind reports separately.
112
+ *
113
+ * Returns as soon as the sweep has started, not when it ends. A prune runs
114
+ * for minutes and belongs to the host rather than to the dialog that asked
115
+ * for it — the result arrives on `containers:prune-changed`.
116
+ */
117
+ .http(
118
+ 'containers:prune',
119
+ {
120
+ data: t.Object({
121
+ hostId: t.String({ minLength: 1 }),
122
+ kinds: t.Array(t.Union(PRUNE_KINDS), { minItems: 1, maxItems: 6 })
123
+ }),
124
+ response: t.Any()
125
+ },
126
+ async ({ data, conn }) => {
127
+ requireManageAccess(conn, data.hostId);
128
+ return { job: startPrune(data.hostId, data.kinds, ws.getUserId(conn)) };
129
+ }
130
+ )
131
+
132
+ /**
133
+ * The host's current sweep, or the last one nobody has acknowledged.
134
+ *
135
+ * What a dialog reads when it opens, so a sweep started before a refresh —
136
+ * or on another device — is still visible as the thing it is.
137
+ */
138
+ .http(
139
+ 'containers:prune-status',
140
+ { data: t.Object({ hostId: t.String({ minLength: 1 }) }), response: t.Any() },
141
+ async ({ data, conn }) => {
142
+ requireHostAccess(conn, data.hostId);
143
+ return { job: pruneJobFor(data.hostId, ws.getUserId(conn)) };
144
+ }
145
+ )
146
+
147
+ /** Acknowledge a finished sweep, so its report stops being offered. */
148
+ .http(
149
+ 'containers:prune-dismiss',
150
+ { data: t.Object({ hostId: t.String({ minLength: 1 }) }), response: t.Any() },
151
+ async ({ data, conn }) => {
152
+ requireManageAccess(conn, data.hostId);
153
+ dismissPrune(data.hostId);
154
+ return { ok: true };
155
+ }
156
+ );
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Container manager WebSocket router.
3
+ *
4
+ * Reading the list, the detail and the logs is open to any signed-in user who
5
+ * can already reach the host; `containers:action` is registered in
6
+ * ADMIN_ONLY_ROUTES, and opening a shell is gated inside the PtyKit server's
7
+ * own `authorize`.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import { createRouter } from '$shared/utils/ws-server';
12
+ import { containersListHandler } from './list';
13
+ import { containersActionHandler } from './actions';
14
+ import { containersLogsHandler } from './logs';
15
+ import { containersTunnelHandler } from './tunnel';
16
+
17
+ export const containersRouter = createRouter()
18
+ .merge(containersListHandler)
19
+ .merge(containersActionHandler)
20
+ .merge(containersLogsHandler)
21
+ .merge(containersTunnelHandler)
22
+ // Pushed only when a watched host's list actually changed.
23
+ .emit('containers:changed', t.Object({ result: t.Any() }))
24
+ // The sidebar count: containers running on this machine.
25
+ .emit('containers:badge', t.Object({ count: t.Number() }))
26
+ // A disk reading, pushed to whoever asked when it finally lands. It cannot
27
+ // be a response: `system df` takes as long as the host's disk is large.
28
+ .emit('containers:disk-usage-measured', t.Object({ hostId: t.String(), usage: t.Any() }))
29
+ // A cleanup sweep reaching its end, pushed to everyone attached to it — the
30
+ // dialog that started it may be long closed by then.
31
+ .emit('containers:prune-changed', t.Object({ job: t.Any() }))
32
+ // One coalesced push of container output while a log stream is followed.
33
+ .emit(
34
+ 'containers:log-chunk',
35
+ t.Object({
36
+ streamId: t.String(),
37
+ hostId: t.String(),
38
+ containerId: t.String(),
39
+ data: t.String(),
40
+ done: t.Optional(t.Boolean()),
41
+ error: t.Optional(t.Union([t.String(), t.Null()]))
42
+ })
43
+ );
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Containers — reading the list.
3
+ *
4
+ * Watching is per connection: a client asks for a host when it opens that panel
5
+ * and is pushed a fresh listing whenever the host's containers actually change.
6
+ * The 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 who can already reach the host. Acting
10
+ * on a container is not, and lives in actions.ts.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { createRouter } from '$shared/utils/ws-server';
15
+ import { LOCAL_HOST_ID } from '$shared/types/host';
16
+ import { containerMonitor } from '../../containers/monitor';
17
+ import { inspectContainer, readStats } from '../../containers/actions';
18
+ import { requestDiskUsage } from '../../containers/disk-usage';
19
+ import { stopLogStreamsForUser } from '../../containers/logs';
20
+ import { sshConnectionQueries } from '../../database/queries';
21
+ import { ws } from '../../utils/ws';
22
+
23
+ /**
24
+ * A member may only watch an SSH host they can already reach. The local machine
25
+ * is watchable by anyone signed in — it is the machine they are already using
26
+ * Clopen on.
27
+ */
28
+ export function requireHostAccess(conn: Parameters<typeof ws.getUserId>[0], hostId: string): void {
29
+ if (hostId === LOCAL_HOST_ID) return;
30
+ const userId = ws.getUserId(conn);
31
+ const isAdmin = ws.getRole(conn) === 'admin';
32
+ sshConnectionQueries.ensureAccess(hostId, userId, isAdmin);
33
+ }
34
+
35
+ const hostSchema = t.Object({ hostId: t.String({ minLength: 1 }) });
36
+
37
+ export const containersListHandler = createRouter()
38
+ .http('containers:watch', { data: hostSchema, response: t.Any() }, async ({ data, conn }) => {
39
+ requireHostAccess(conn, data.hostId);
40
+ const userId = ws.getUserId(conn);
41
+
42
+ const result = await containerMonitor.watch(data.hostId, userId);
43
+ // The watch belongs to this socket; a reload must not leave it running,
44
+ // and neither must the log streams opened from the same panel.
45
+ ws.addCleanup(conn, () => {
46
+ containerMonitor.unwatch(data.hostId, userId);
47
+ stopLogStreamsForUser(userId);
48
+ });
49
+ return { result };
50
+ })
51
+
52
+ .http('containers:unwatch', { data: hostSchema, response: t.Any() }, async ({ data, conn }) => {
53
+ containerMonitor.unwatch(data.hostId, ws.getUserId(conn));
54
+ return { ok: true };
55
+ })
56
+
57
+ /**
58
+ * The sidebar count, on demand.
59
+ *
60
+ * Pushes only carry changes, so a client that has just loaded — or just
61
+ * reconnected — has no way to learn a count that has been steady. Asking for
62
+ * it is how the badge survives a page refresh instead of reading zero until
63
+ * something happens to move it.
64
+ */
65
+ .http('containers:summary', { data: t.Object({}), response: t.Any() }, async () => ({
66
+ count: await containerMonitor.refreshBadge()
67
+ }))
68
+
69
+ /**
70
+ * Everything `inspect` knows, read only when a detail pane opens.
71
+ *
72
+ * Environment values are stripped for anyone but an admin. A container's env
73
+ * is where its database password lives, and this panel is reachable by every
74
+ * member and through a shared Remote Access link — so the keys are shown,
75
+ * which is what makes the pane useful, and the values are not.
76
+ */
77
+ .http(
78
+ 'containers:inspect',
79
+ {
80
+ data: t.Object({
81
+ hostId: t.String({ minLength: 1 }),
82
+ containerId: t.String({ minLength: 12 })
83
+ }),
84
+ response: t.Any()
85
+ },
86
+ async ({ data, conn }) => {
87
+ requireHostAccess(conn, data.hostId);
88
+ const detail = await inspectContainer(data.hostId, data.containerId);
89
+ if (!detail || ws.getRole(conn) === 'admin') return { detail, envRedacted: false };
90
+
91
+ return {
92
+ detail: {
93
+ ...detail,
94
+ env: detail.env.map((line) => {
95
+ const split = line.indexOf('=');
96
+ return split <= 0 ? line : `${line.slice(0, split)}=`;
97
+ })
98
+ },
99
+ envRedacted: true
100
+ };
101
+ }
102
+ )
103
+
104
+ /**
105
+ * What the host is holding and how much of it is reclaimable.
106
+ *
107
+ * Read-only, so any member may ask — it is the same `system df` they would
108
+ * run in a terminal, and knowing the disk is full is not a privilege.
109
+ *
110
+ * Returns whatever was last measured, immediately, and reports whether a
111
+ * fresh reading is on its way; that one arrives as
112
+ * `containers:disk-usage-measured`. The measurement cannot be awaited here
113
+ * because its duration is set by how much disk the host holds — see
114
+ * `backend/containers/disk-usage.ts`.
115
+ */
116
+ .http(
117
+ 'containers:disk-usage',
118
+ {
119
+ data: t.Object({
120
+ hostId: t.String({ minLength: 1 }),
121
+ /** The Re-check button: measure again even if the cache is fresh. */
122
+ force: t.Optional(t.Boolean())
123
+ }),
124
+ response: t.Any()
125
+ },
126
+ async ({ data, conn }) => {
127
+ requireHostAccess(conn, data.hostId);
128
+ return requestDiskUsage(data.hostId, ws.getUserId(conn), data.force ?? false);
129
+ }
130
+ )
131
+
132
+ /** One live sample of what a container is consuming, when a pane asks. */
133
+ .http(
134
+ 'containers:stats',
135
+ {
136
+ data: t.Object({
137
+ hostId: t.String({ minLength: 1 }),
138
+ containerId: t.String({ minLength: 12 })
139
+ }),
140
+ response: t.Any()
141
+ },
142
+ async ({ data, conn }) => {
143
+ requireHostAccess(conn, data.hostId);
144
+ return { stats: await readStats(data.hostId, data.containerId) };
145
+ }
146
+ );
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Containers — following a container's output.
3
+ *
4
+ * Open to any member who can reach the host: reading a log changes nothing.
5
+ * The stream belongs to the socket that asked for it, so closing the tab stops
6
+ * the `docker logs -f` behind it rather than leaving a process running on
7
+ * someone's machine with nothing listening.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import { createRouter } from '$shared/utils/ws-server';
12
+ import { startLogStream, stopLogStream } from '../../containers/logs';
13
+ import { requireHostAccess } from './list';
14
+ import { ws } from '../../utils/ws';
15
+
16
+ export const containersLogsHandler = createRouter()
17
+ .http(
18
+ 'containers:logs-start',
19
+ {
20
+ data: t.Object({
21
+ hostId: t.String({ minLength: 1 }),
22
+ containerId: t.String({ minLength: 12 })
23
+ }),
24
+ response: t.Any()
25
+ },
26
+ async ({ data, conn }) => {
27
+ requireHostAccess(conn, data.hostId);
28
+ const userId = ws.getUserId(conn);
29
+
30
+ const started = await startLogStream(data.hostId, data.containerId, userId);
31
+ ws.addCleanup(conn, () => stopLogStream(started.streamId, userId));
32
+ return started;
33
+ }
34
+ )
35
+
36
+ .http(
37
+ 'containers:logs-stop',
38
+ { data: t.Object({ streamId: t.String({ minLength: 1 }) }), response: t.Any() },
39
+ async ({ data, conn }) => {
40
+ stopLogStream(data.streamId, ws.getUserId(conn));
41
+ return { ok: true };
42
+ }
43
+ );