herdr-remote-relay 0.2.5 → 0.2.6

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 (2) hide show
  1. package/package.json +1 -1
  2. package/src/relay-server.js +112 -208
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-remote-relay",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Standalone relay server and web terminal for Herdr Remote",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -17,19 +17,9 @@ const VERSION = require('../package.json').version;
17
17
  const { PROTOCOL_VERSION } = require('./stream-frame');
18
18
  const MAX_DIMENSION = 500;
19
19
 
20
- /**
21
- * How much recent PTY output the relay keeps per shared session.
22
- *
23
- * A browser that joins a session already in progress has missed everything
24
- * printed before it arrived. Replaying the tail of the stream is what makes
25
- * "every window shows the same thing" true on the *first* frame rather than
26
- * only after the next repaint.
27
- */
28
- const SESSION_REPLAY_BYTES = 512 * 1024;
29
-
30
- /** Never shrink a shared grid below something a program can still draw in. */
31
- const MIN_SHARED_COLS = 20;
32
- const MIN_SHARED_ROWS = 6;
20
+ /** Never shrink an individual session grid below something a program can still draw in. */
21
+ const MIN_SESSION_COLS = 20;
22
+ const MIN_SESSION_ROWS = 6;
33
23
 
34
24
  function randomId(prefix) {
35
25
  return `${prefix}-${crypto.randomBytes(9).toString('base64url')}`;
@@ -97,6 +87,7 @@ class RelayServer {
97
87
  this.relayMode = config.relay?.mode === 'local' ? 'local' : 'remote';
98
88
  this.hosts = new Map();
99
89
  this.clients = new Map();
90
+ this.streams = new Map();
100
91
  this.pairAttempts = new Map();
101
92
  this.clientHandshakeAttempts = new Map();
102
93
  this.hostHandshakeAttempts = new Map();
@@ -160,6 +151,7 @@ class RelayServer {
160
151
  this.cleanupTimer = null;
161
152
  for (const client of [...this.clients.values()]) this.detachClient(client, { notify: false });
162
153
  for (const host of [...this.hosts.values()]) this.detachHost(host, { notify: false });
154
+ this.streams.clear();
163
155
  this.pairAttempts.clear();
164
156
  this.clientHandshakeAttempts.clear();
165
157
  this.hostHandshakeAttempts.clear();
@@ -516,10 +508,6 @@ class RelayServer {
516
508
  arch: typeof message.arch === 'string' ? message.arch.slice(0, 32) : process.arch,
517
509
  connectedAt: new Date(pending.connectedAt).toISOString(),
518
510
  connectedAtMs: pending.connectedAt,
519
- // One shared terminal per workstation. Every browser attached to this
520
- // host reads and writes the same PTY, so what one of them shows is what
521
- // all of them show.
522
- session: null,
523
511
  terminalPalette: sanitizeTerminalPalette(message.terminalPalette),
524
512
  lastSeenAt: Date.now(),
525
513
  clients,
@@ -555,7 +543,13 @@ class RelayServer {
555
543
  host.lastSeenAt = Date.now();
556
544
  host.load = {};
557
545
  host.ptys = [];
558
- host.session = null;
546
+ for (const clientId of host.clients) {
547
+ const client = this.clients.get(clientId);
548
+ if (client?.session) {
549
+ this.streams.delete(client.session.streamId);
550
+ client.session = null;
551
+ }
552
+ }
559
553
  this.broadcastToClients(host, () => ({ type: 'host_reconnecting', code: reason }));
560
554
  host.reconnectTimer = setTimeout(() => {
561
555
  host.reconnectTimer = null;
@@ -598,10 +592,20 @@ class RelayServer {
598
592
  if (oldHost.reconnectTimer) clearTimeout(oldHost.reconnectTimer);
599
593
  oldHost.reconnectTimer = null;
600
594
  if (handoff) {
601
- if (oldHost.session && isOpen(oldHost.ws)) {
602
- jsonSend(oldHost.ws, { type: 'session_stop', clientId: oldHost.session.streamId, streamId: oldHost.session.streamId });
595
+ for (const clientId of oldHost.clients) {
596
+ const client = this.clients.get(clientId);
597
+ if (client?.session) {
598
+ if (isOpen(oldHost.ws)) {
599
+ jsonSend(oldHost.ws, {
600
+ type: 'session_stop',
601
+ clientId: client.session.streamId,
602
+ streamId: client.session.streamId,
603
+ });
604
+ }
605
+ this.streams.delete(client.session.streamId);
606
+ client.session = null;
607
+ }
603
608
  }
604
- oldHost.session = null;
605
609
  oldHost.load = {};
606
610
  oldHost.ptys = [];
607
611
  this.broadcastToClients(oldHost, () => ({ type: 'host_reconnecting', code: 'host_replaced' }));
@@ -624,7 +628,12 @@ class RelayServer {
624
628
  clientCount: host.clients.size,
625
629
  });
626
630
  this.notifyHostClientCount(host);
627
- if (handoff) this.startSession(host, { restarted: true });
631
+ if (handoff) {
632
+ for (const clientId of host.clients) {
633
+ const client = this.clients.get(clientId);
634
+ if (client) this.startSession(host, client, { restarted: true });
635
+ }
636
+ }
628
637
  return;
629
638
  }
630
639
  this.handleHostMessage(pending.host, raw, isBinary);
@@ -660,16 +669,13 @@ class RelayServer {
660
669
  closeSocket(host.ws, 1003, error.message);
661
670
  return;
662
671
  }
663
- // Output belongs to the workstation's one shared session, so it goes to
664
- // every browser attached to it rather than to a single stream owner.
665
- const session = host.session;
666
- if (frame.type !== 'output' || !session || session.streamId !== frame.streamId) return;
667
- this.rememberOutput(session, frame.payload);
668
- for (const clientId of [...host.clients]) {
669
- const client = this.clients.get(clientId);
670
- if (!client || !isOpen(client.ws)) continue;
671
- this.sendClientBinary(host, client, frame.payload);
672
- }
672
+ // Output is routed to the single client owning the stream rather than broadcast.
673
+ if (frame.type !== 'output') return;
674
+ const clientId = this.streams.get(frame.streamId);
675
+ if (!clientId) return;
676
+ const client = this.clients.get(clientId);
677
+ if (!client || !isOpen(client.ws)) return;
678
+ this.sendClientBinary(host, client, frame.payload);
673
679
  return;
674
680
  }
675
681
  const message = parseJson(raw.toString());
@@ -684,28 +690,29 @@ class RelayServer {
684
690
  if (this.hosts.get(host.id) === host) this.detachHost(host, { notify: true, reason: 'host_shutdown' });
685
691
  return;
686
692
  }
687
- // Session-level news concerns the whole room: the host talks about the one
688
- // shared stream, and every attached browser has to hear it.
689
- const session = host.session;
693
+ // Session events target the single client that owns this stream.
690
694
  const streamId = typeof message.clientId === 'string' ? message.clientId : message.streamId;
691
- if (!session || (streamId && streamId !== session.streamId)) return;
695
+ const clientId = streamId ? this.streams.get(streamId) : null;
696
+ const client = clientId ? this.clients.get(clientId) : null;
697
+ if (!client) return;
698
+
692
699
  if (message.type === 'session_ready') {
693
- session.ready = true;
694
- this.broadcastToClients(host, (client) => ({ type: 'session_ready', clientId: client.id }));
700
+ if (client.session) client.session.ready = true;
701
+ jsonSend(client.ws, { type: 'session_ready', clientId: client.id });
695
702
  } else if (message.type === 'session_exit') {
696
703
  const code = Number.isInteger(message.code) ? message.code : null;
697
- host.session = null;
698
- this.broadcastToClients(host, () => ({ type: 'exit', code }));
699
- for (const clientId of [...host.clients]) {
700
- const client = this.clients.get(clientId);
701
- if (client) this.detachClient(client, { notify: false });
704
+ jsonSend(client.ws, { type: 'exit', code });
705
+ if (client.session) {
706
+ this.streams.delete(client.session.streamId);
707
+ client.session = null;
702
708
  }
709
+ this.detachClient(client, { notify: false });
703
710
  } else if (message.type === 'error') {
704
- this.broadcastToClients(host, () => ({
711
+ jsonSend(client.ws, {
705
712
  type: 'error',
706
713
  code: message.code || 'host_error',
707
714
  message: String(message.message || 'Host connector error'),
708
- }));
715
+ });
709
716
  }
710
717
  }
711
718
 
@@ -749,147 +756,35 @@ class RelayServer {
749
756
  }
750
757
  }
751
758
 
752
- /** Keep the tail of the shared stream so a late joiner can be caught up. */
753
- rememberOutput(session, payload) {
754
- session.replay.push(Buffer.from(payload));
755
- session.replayBytes += payload.length;
756
- while (session.replayBytes > SESSION_REPLAY_BYTES && session.replay.length > 1) {
757
- session.replayBytes -= session.replay.shift().length;
758
- }
759
- }
760
-
761
- /**
762
- * The grid the shared PTY runs at.
763
- *
764
- * The smallest attached window wins, exactly as it does in tmux: a column a
765
- * phone cannot show is a column the program must not paint, or every other
766
- * window sees wrapped rubbish. Nothing else keeps a shared terminal legible
767
- * on two different screens at once.
768
- */
769
- sharedDimensions(host) {
770
- let cols = MAX_DIMENSION;
771
- let rows = MAX_DIMENSION;
772
- let found = false;
773
- for (const clientId of host.clients) {
774
- const client = this.clients.get(clientId);
775
- if (!client) continue;
776
- found = true;
777
- cols = Math.min(cols, client.cols);
778
- rows = Math.min(rows, client.rows);
779
- }
780
- if (!found) return null;
781
- return {
782
- cols: Math.max(MIN_SHARED_COLS, cols),
783
- rows: Math.max(MIN_SHARED_ROWS, rows),
784
- };
785
- }
786
-
787
- /** Start the one shared PTY for a host's currently attached clients. */
788
- startSession(host, { restarted = false } = {}) {
789
- const firstClientId = [...host.clients][0];
790
- const firstClient = firstClientId ? this.clients.get(firstClientId) : null;
791
- if (!firstClient || !isOpen(host.ws)) return;
792
- host.session = {
793
- streamId: randomId('session'),
794
- cols: firstClient.cols,
795
- rows: firstClient.rows,
759
+ /** Start a dedicated PTY session for one attached client. */
760
+ startSession(host, client, { restarted = false } = {}) {
761
+ if (!client || !isOpen(host.ws)) return;
762
+ const streamId = randomId('session');
763
+ client.session = {
764
+ streamId,
765
+ cols: client.cols,
766
+ rows: client.rows,
796
767
  ready: false,
797
- replay: [],
798
- replayBytes: 0,
799
768
  };
800
- const dims = this.sharedDimensions(host) || { cols: firstClient.cols, rows: firstClient.rows };
801
- host.session.cols = dims.cols;
802
- host.session.rows = dims.rows;
769
+ this.streams.set(streamId, client.id);
803
770
  jsonSend(host.ws, {
804
771
  type: 'session_start',
805
- clientId: host.session.streamId,
806
- streamId: host.session.streamId,
807
- cols: dims.cols,
808
- rows: dims.rows,
772
+ clientId: streamId,
773
+ streamId,
774
+ cols: Math.max(MIN_SESSION_COLS, client.cols),
775
+ rows: Math.max(MIN_SESSION_ROWS, client.rows),
809
776
  role: 'controller',
810
777
  });
811
- this.broadcastToClients(host, () => ({ type: 'shared_resize', cols: dims.cols, rows: dims.rows }));
812
778
  if (restarted) {
813
- this.broadcastToClients(host, () => ({
779
+ jsonSend(client.ws, {
814
780
  type: 'session_restarted',
815
- streamId: host.session.streamId,
816
- cols: dims.cols,
817
- rows: dims.rows,
781
+ streamId,
782
+ cols: client.cols,
783
+ rows: client.rows,
818
784
  hostname: host.hostname,
819
785
  terminalPalette: host.terminalPalette || null,
820
- }));
821
- }
822
- }
823
-
824
- /**
825
- * Attach `client` to the workstation's shared terminal, starting it if this
826
- * is the first browser through the door.
827
- *
828
- * A later arrival does not get its own PTY: it is handed the stream already
829
- * running, the output that has been printed so far, and — once the geometry
830
- * has settled — a repaint, so it lands on the same screen everyone else is
831
- * looking at.
832
- */
833
- attachSession(host, client) {
834
- if (!host.session) {
835
- this.startSession(host);
836
- return;
837
- }
838
-
839
- const session = host.session;
840
- if (session.ready) jsonSend(client.ws, { type: 'session_ready', clientId: client.id });
841
- for (const chunk of session.replay) {
842
- if (!isOpen(client.ws)) break;
843
- this.sendClientBinary(host, client, chunk);
844
- }
845
- // Geometry may now be smaller than it was; the resize doubles as the
846
- // repaint that puts the newcomer on the same screen as everyone else.
847
- this.syncDimensions(host, { force: true });
848
- }
849
-
850
- /**
851
- * Push the shared grid to the workstation.
852
- *
853
- * `force` asks for a repaint even when the numbers did not move: a browser
854
- * that just joined needs the program to draw itself again, and a resize is
855
- * the only signal a PTY has for "paint everything".
856
- */
857
- syncDimensions(host, { force = false } = {}) {
858
- const session = host.session;
859
- if (!session) return;
860
- const dims = this.sharedDimensions(host);
861
- if (!dims) return;
862
- const changed = dims.cols !== session.cols || dims.rows !== session.rows;
863
- session.cols = dims.cols;
864
- session.rows = dims.rows;
865
- if (!changed && !force) return;
866
- // Every window has to be told what the shared grid became, not just the
867
- // workstation. A browser that keeps rendering at its own width would wrap
868
- // a stream written for a narrower terminal, which is the one thing a
869
- // shared session must not do: the same bytes have to look the same in
870
- // every window.
871
- this.broadcastToClients(host, () => ({
872
- type: 'shared_resize',
873
- cols: dims.cols,
874
- rows: dims.rows,
875
- }));
876
- if (!changed && force) {
877
- // A no-op resize is ignored by the PTY, so bounce one row and come back.
878
- jsonSend(host.ws, {
879
- type: 'resize',
880
- clientId: session.streamId,
881
- streamId: session.streamId,
882
- cols: dims.cols,
883
- rows: Math.max(MIN_SHARED_ROWS, dims.rows - 1),
884
786
  });
885
787
  }
886
- jsonSend(host.ws, {
887
- type: 'resize',
888
- clientId: session.streamId,
889
- streamId: session.streamId,
890
- cols: dims.cols,
891
- rows: dims.rows,
892
- });
893
788
  }
894
789
 
895
790
  handleClientConnection(ws, req) {
@@ -915,12 +810,9 @@ class RelayServer {
915
810
  const host = this.hosts.get(device.hostId);
916
811
  if (!host || host.reconnecting || !isOpen(host.ws)) return this.rejectHandshake(ws, 'paired Herdr host is offline', host?.reconnecting ? 'host_reconnecting' : 'host_offline');
917
812
 
918
- // Two tabs of one browser are two windows onto the same terminal, not
919
- // rivals. Nothing is retired here: the relay used to close whichever
920
- // session shared this browser's client id, which made two open tabs
921
- // evict each other in a loop that never converged — each eviction
922
- // triggered the other tab's auto-reconnect, which evicted this one
923
- // back, forever.
813
+ // Two tabs of one browser are separate windows with their own PTY sessions,
814
+ // not rivals. Nothing is retired here: each connection gets its own stream
815
+ // without evicting existing clients.
924
816
  if (host.clients.size >= this.config.relay.maxClientsPerHost) return this.rejectHandshake(ws, 'host client limit reached', 'too_many_clients');
925
817
  clearTimeout(deadline);
926
818
  this.finishHandshake(ws);
@@ -934,9 +826,10 @@ class RelayServer {
934
826
  // same browser rather than a genuinely separate viewer.
935
827
  browserClientId: typeof message.clientId === 'string' ? message.clientId.slice(0, 128) : null,
936
828
  handoffCapable: Array.isArray(message.capabilities) && message.capabilities.includes('host_handoff'),
937
- // Every paired window may type. Pairing is the permission boundary;
938
- // once a device is through it, holding a second window read-only
939
- // serves nobody they are all views of one shared terminal.
829
+ session: null,
830
+ // Every paired window gets its own interactive PTY session. Pairing
831
+ // is the permission boundary; once a device is through it, every
832
+ // window can type into its own terminal.
940
833
  role: 'controller',
941
834
  controllerId: null,
942
835
  connectedAt: new Date().toISOString(),
@@ -985,7 +878,7 @@ class RelayServer {
985
878
  terminalPalette: host.terminalPalette || null,
986
879
  clientCount: host.clients.size,
987
880
  });
988
- this.attachSession(host, client);
881
+ this.startSession(host, client);
989
882
  this.broadcastControlState(host);
990
883
  return;
991
884
  }
@@ -1004,11 +897,10 @@ class RelayServer {
1004
897
  if (!host) return this.detachClient(client, { notify: true, reason: 'host_offline' });
1005
898
  if (isBinary) {
1006
899
  if (raw.length > this.config.relay.maxPayloadBytes) return;
1007
- const session = host.session;
1008
- if (!session) return;
1009
- // Every window writes into the one shared terminal, so input is stamped
1010
- // with the session's stream id rather than the sender's.
1011
- const frame = packStreamFrame('input', session.streamId, raw);
900
+ if (!client.session) return;
901
+ // Each window owns its own PTY session, so input is stamped with the
902
+ // client's dedicated stream id.
903
+ const frame = packStreamFrame('input', client.session.streamId, raw);
1012
904
  if (isOpen(host.ws)) {
1013
905
  try {
1014
906
  host.ws.send(frame);
@@ -1029,11 +921,23 @@ class RelayServer {
1029
921
  client.lastPingAt = new Date().toISOString();
1030
922
  jsonSend(client.ws, { type: 'pong' });
1031
923
  } else if (message.type === 'resize') {
1032
- // The shared grid is the smallest attached window, so one client's resize
1033
- // is recomputed across the room rather than applied on its own.
924
+ // Each client owns its own PTY session, so resizing directly forwards
925
+ // the new geometry for this client's stream to the host.
1034
926
  client.cols = clampDimension(message.cols, client.cols);
1035
927
  client.rows = clampDimension(message.rows, client.rows);
1036
- this.syncDimensions(host);
928
+ if (client.session) {
929
+ client.session.cols = client.cols;
930
+ client.session.rows = client.rows;
931
+ if (isOpen(host.ws)) {
932
+ jsonSend(host.ws, {
933
+ type: 'resize',
934
+ clientId: client.session.streamId,
935
+ streamId: client.session.streamId,
936
+ cols: Math.max(MIN_SESSION_COLS, client.cols),
937
+ rows: Math.max(MIN_SESSION_ROWS, client.rows),
938
+ });
939
+ }
940
+ }
1037
941
  } else if (message.type === 'claim_control') {
1038
942
  // Control is no longer a lease. Answering the old request keeps clients
1039
943
  // built against the previous protocol working.
@@ -1089,26 +993,22 @@ class RelayServer {
1089
993
  if (!client || !this.clients.has(client.id)) return;
1090
994
  this.clients.delete(client.id);
1091
995
  const host = this.hosts.get(client.hostId);
996
+ // Each window has its own PTY session. Tearing down the client immediately
997
+ // stops its backing session on the host and cleans up its stream mapping.
998
+ if (client.session) {
999
+ const streamId = client.session.streamId;
1000
+ this.streams.delete(streamId);
1001
+ if (host && isOpen(host.ws)) {
1002
+ jsonSend(host.ws, { type: 'session_stop', clientId: streamId, streamId });
1003
+ }
1004
+ client.session = null;
1005
+ }
1092
1006
  if (host) {
1093
1007
  host.clients.delete(client.id);
1094
- // The shared terminal outlives any one window: it is torn down only when
1095
- // the last of them has gone, so closing a tab never kills the session the
1096
- // other tabs are still watching.
1008
+ this.notifyHostClientCount(host);
1009
+ this.broadcastControlState(host);
1097
1010
  if (host.clients.size === 0) {
1098
- if (host.session) {
1099
- if (isOpen(host.ws)) {
1100
- jsonSend(host.ws, { type: 'session_stop', clientId: host.session.streamId, streamId: host.session.streamId });
1101
- }
1102
- host.session = null;
1103
- }
1104
1011
  host.controllerId = null;
1105
- } else {
1106
- this.notifyHostClientCount(host);
1107
- this.syncDimensions(host);
1108
- this.broadcastControlState(host);
1109
- }
1110
- if (host.clients.size === 0) {
1111
- this.notifyHostClientCount(host);
1112
1012
  if (host.reconnecting) this.detachHost(host, { notify: false, reason: 'no_clients' });
1113
1013
  }
1114
1014
  }
@@ -1126,6 +1026,10 @@ class RelayServer {
1126
1026
  const client = this.clients.get(clientId);
1127
1027
  if (!client) continue;
1128
1028
  this.clients.delete(client.id);
1029
+ if (client.session) {
1030
+ this.streams.delete(client.session.streamId);
1031
+ client.session = null;
1032
+ }
1129
1033
  if (notify) jsonSend(client.ws, { type: 'error', code: reason, message: 'Herdr host disconnected' });
1130
1034
  closeSocket(client.ws, 1012, reason);
1131
1035
  }