@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
@@ -278,6 +278,23 @@ export class WSClient<TAPI extends { client: any; server: any }> {
278
278
  /** Prevents a heal-reconnect stampede when many requests time out at once. */
279
279
  private healingReconnect = false;
280
280
 
281
+ /**
282
+ * When the socket last delivered ANYTHING from the server.
283
+ *
284
+ * This is the evidence that separates the two failures a stalled request can
285
+ * mean, which the recovery path used to conflate. A socket that is still
286
+ * handing us other traffic is demonstrably alive, so a request that has not
287
+ * come back is slow or was lost in transit — re-sending it is the whole fix.
288
+ * A socket that has gone completely silent is the black-holed case reconnect
289
+ * exists for.
290
+ *
291
+ * Treating both as "the connection is dead" is what turned one slow read into
292
+ * a full teardown, and a teardown re-runs every panel's reconnect handler at
293
+ * once — a burst far more expensive than the request that triggered it, and
294
+ * one that made the next timeout more likely rather than less.
295
+ */
296
+ private lastInboundAt = 0;
297
+
281
298
  /** Current context (synced with server) */
282
299
  private context: {
283
300
  userId: string | null;
@@ -376,8 +393,11 @@ export class WSClient<TAPI extends { client: any; server: any }> {
376
393
  }
377
394
 
378
395
  // A fresh socket is live again — clear the heal guard so future
379
- // dead-connection recoveries can fire.
396
+ // dead-connection recoveries can fire, and count the open itself as
397
+ // proof of life so a quiet-but-healthy connection is never mistaken
398
+ // for a black-holed one on its first request.
380
399
  this.healingReconnect = false;
400
+ this.lastInboundAt = Date.now();
381
401
 
382
402
  // Flush queued fire-and-forget messages AFTER context + room
383
403
  // re-joins are synced. Drain into a local array first so a send
@@ -407,6 +427,10 @@ export class WSClient<TAPI extends { client: any; server: any }> {
407
427
  };
408
428
 
409
429
  this.ws.onmessage = (event) => {
430
+ // Proof of life for the recovery path, recorded before anything can
431
+ // throw: what matters is that a frame ARRIVED, not that we managed
432
+ // to handle it.
433
+ this.lastInboundAt = Date.now();
410
434
  try {
411
435
  if (event.data instanceof ArrayBuffer) {
412
436
  // Binary message
@@ -889,7 +913,7 @@ export class WSClient<TAPI extends { client: any; server: any }> {
889
913
  // Reads can be safely re-sent; mutations can only be re-sent if they were
890
914
  // never delivered (tracked via `entry.sent`).
891
915
  const idempotent = isIdempotentHttpAction(actionStr);
892
- // Up to this many automatic heal-reconnect retries for idempotent reads.
916
+ // Up to this many automatic recovery attempts for idempotent reads.
893
917
  const MAX_HEAL_ATTEMPTS = 2;
894
918
 
895
919
  return new Promise((resolve, reject) => {
@@ -920,23 +944,54 @@ export class WSClient<TAPI extends { client: any; server: any }> {
920
944
  }
921
945
  };
922
946
 
923
- // Timeout handler — for idempotent reads, try to heal a dead-but-open
924
- // socket and retry instead of failing outright.
947
+ // Timeout handler — for idempotent reads, recover and retry instead of
948
+ // failing outright.
949
+ //
950
+ // The recovery is now proportionate to the evidence, which it was not
951
+ // before: ANY stalled read forced a full reconnect, so one slow answer
952
+ // from a busy server tore down a connection that was working perfectly
953
+ // and made all fifteen `onWsReconnect` subscribers refetch at once. On a
954
+ // loaded instance that burst is what caused the NEXT timeout, and the
955
+ // loop sustained itself — panels re-showing their skeletons every few
956
+ // seconds for as long as the instance stayed busy.
957
+ //
958
+ // So the socket is only rebuilt when it has actually stopped speaking.
959
+ // While other traffic is still arriving the connection is known-good and
960
+ // re-sending the one request costs a single frame.
925
961
  const onTimeout = () => {
926
962
  if (idempotent && entry.attempts < MAX_HEAL_ATTEMPTS) {
927
963
  entry.attempts++;
928
- debug.warn(
929
- 'websocket',
930
- `Request stalled, healing connection and retrying: ${actionStr} (attempt ${entry.attempts})`
931
- );
932
964
  entry.arm();
933
- // If the socket still claims to be open, it is likely black-holed
934
- // — force a reconnect (guarded against a stampede). The onopen
935
- // resend loop will re-send this request on the fresh socket.
936
- if (this.isSocketOpen() && !this.healingReconnect) {
965
+
966
+ // Silent for a whole timeout window means nothing at all is
967
+ // coming through — a stream, an event, another response — which
968
+ // is the black-hole signature reconnect exists for. Anything
969
+ // less is a connection that works and a request that did not.
970
+ const silentFor = Date.now() - this.lastInboundAt;
971
+ const socketIsBlackHoled = this.isSocketOpen() && silentFor >= timeout;
972
+
973
+ if (socketIsBlackHoled && !this.healingReconnect) {
974
+ debug.warn(
975
+ 'websocket',
976
+ `Socket silent for ${silentFor}ms — reconnecting and retrying: ${actionStr} (attempt ${entry.attempts})`
977
+ );
937
978
  this.healingReconnect = true;
979
+ // The onopen resend loop re-sends this request on the fresh
980
+ // socket, so nothing extra is needed here.
938
981
  this.reconnect();
982
+ return;
983
+ }
984
+
985
+ debug.warn(
986
+ 'websocket',
987
+ `Request stalled but connection is live — re-sending: ${actionStr} (attempt ${entry.attempts})`
988
+ );
989
+ if (this.isSocketOpen()) {
990
+ entry.sent = true;
991
+ this.sendRaw(entry.action, entry.payload);
939
992
  }
993
+ // A socket that is not open needs no action: the request stays in
994
+ // `pendingHttpRequests` and the onopen resend loop delivers it.
940
995
  return;
941
996
  }
942
997
  entry.cleanup();
@@ -281,7 +281,12 @@ export class WSRouter<
281
281
 
282
282
  /** Optional auth middleware — called before every route handler */
283
283
  private authMiddleware: ((conn: WSConnection, action: string) => Promise<{ allowed: boolean; error?: string }>) | null = null;
284
- private rateLimiter: ((conn: WSConnection, action: string) => boolean) | null = null;
284
+ /**
285
+ * Optional rate limiter. `isRequest` tells it whether a caller is blocked
286
+ * waiting on a reply, so throttling can shed fire-and-forget floods without
287
+ * killing the low-volume calls panels depend on.
288
+ */
289
+ private rateLimiter: ((conn: WSConnection, action: string, isRequest: boolean) => boolean) | null = null;
285
290
 
286
291
  constructor() {
287
292
  this.registerContextHandler();
@@ -291,7 +296,7 @@ export class WSRouter<
291
296
  this.authMiddleware = fn;
292
297
  }
293
298
 
294
- setRateLimiter(fn: (conn: WSConnection, action: string) => boolean): void {
299
+ setRateLimiter(fn: (conn: WSConnection, action: string, isRequest: boolean) => boolean): void {
295
300
  this.rateLimiter = fn;
296
301
  }
297
302
 
@@ -531,16 +536,30 @@ export class WSRouter<
531
536
  data: validatedData
532
537
  });
533
538
 
534
- // Validate response data schema
535
- let validatedResponse;
536
- try {
537
- validatedResponse = Value.Decode(route.responseSchema, result);
538
- } catch (err) {
539
- debug.error('websocket', `Response validation failed for ${action}:`, err);
540
- throw new Error(
541
- `Response validation failed: ${err instanceof Error ? err.message : 'Unknown error'}`
542
- );
543
- }
539
+ // The response is NOT re-validated.
540
+ //
541
+ // `route.responseSchema` stays declared because it is what gives
542
+ // `ws.http()` its return type on the client — but checking the value
543
+ // against it at runtime bought nothing and cost the whole server.
544
+ // A response is produced by our own handler, not by a peer: it is not
545
+ // untrusted input, so the only thing validation could catch is a bug
546
+ // we would rather surface as a wrong field than as a route that fails
547
+ // outright for the user.
548
+ //
549
+ // The cost was not theoretical. `Value.Decode` walks the entire value
550
+ // synchronously on the main thread, and the worst offender is exactly
551
+ // the biggest payload: `files:list-tree` declares a RECURSIVE UNION
552
+ // (backend/ws/files/read.ts), so TypeBox tries both branches at every
553
+ // node of the tree. On a large project that locked the event loop for
554
+ // hundreds of milliseconds per load — during which every other panel's
555
+ // request, every other project's, and the preview watchdog all waited.
556
+ // That is what made one slow Files load feel like the whole app hanging.
557
+ //
558
+ // Measured against what it protects: `Value.Decode` returns the very
559
+ // same object reference and strips nothing (there is not one
560
+ // `t.Transform` in the codebase), so removing it cannot change a
561
+ // successful response by even one byte.
562
+ const validatedResponse = result;
544
563
 
545
564
  // Check if response contains binary data
546
565
  if (isBinaryAction(responseAction, validatedResponse)) {
@@ -628,7 +647,39 @@ export class WSRouter<
628
647
  // ═══ END AUTH GATE ═══
629
648
 
630
649
  // ═══ RATE LIMIT GATE ═══
631
- if (this.rateLimiter && !this.rateLimiter(conn, action)) {
650
+ // A request-response route has a caller blocked on its reply; an event
651
+ // does not. The limiter needs that distinction to shed the right half
652
+ // of a flood, and the answer below needs it to know whether anyone is
653
+ // listening for one.
654
+ const isRequest = this.httpRoutes.has(action);
655
+ if (this.rateLimiter && !this.rateLimiter(conn, action, isRequest)) {
656
+ // A dropped request must still be ANSWERED. Returning silently here
657
+ // left `ws.http()` waiting on a reply that was never coming, so the
658
+ // caller hung for its full 30s timeout and then tore the whole
659
+ // socket down to "heal" it — which re-ran every panel's reconnect
660
+ // handler at once, producing the very burst that tripped the limiter
661
+ // again. Telling the client no is what breaks that loop: the request
662
+ // fails immediately, the caller retries on its own terms, and the
663
+ // connection survives.
664
+ //
665
+ // The auth gate directly above has always done this; the two gates
666
+ // only differed because this one was written to `return` on a path
667
+ // where nothing was waiting for an answer. Fire-and-forget events
668
+ // have no requestId and still just drop.
669
+ if (isRequest) {
670
+ try {
671
+ conn.send(JSON.stringify({
672
+ action: `${action}:response`,
673
+ payload: {
674
+ success: false,
675
+ error: 'Rate limit exceeded — request dropped',
676
+ requestId: payload?.requestId
677
+ }
678
+ }));
679
+ } catch {
680
+ // Connection may already be closing.
681
+ }
682
+ }
632
683
  return;
633
684
  }
634
685
  // ═══ END RATE LIMIT GATE ═══