herdr-remote 0.2.32 → 0.2.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 (135) hide show
  1. package/README.md +3 -1
  2. package/README.zh-CN.md +2 -1
  3. package/dist/connector/agent-watch.js +16 -3
  4. package/dist/connector/herdr-prefix-keys.js +28 -0
  5. package/dist/connector/host-connector.js +6 -20
  6. package/dist/connector/host-hello.js +32 -0
  7. package/dist/herdr-api.js +7 -1
  8. package/dist/herdr-command.js +7 -2
  9. package/dist/i18n/en.js +5 -18
  10. package/dist/i18n/zh.js +5 -18
  11. package/dist/pty-session.js +27 -2
  12. package/dist/socket-discovery.js +16 -6
  13. package/dist/terminal-font/formats.js +26 -6
  14. package/dist/terminal-font/terminals.js +19 -3
  15. package/dist/tui/App.js +3 -25
  16. package/dist/tui/api.js +3 -3
  17. package/dist/tui/screens/About.js +18 -27
  18. package/dist/update-command.js +16 -19
  19. package/dist/updater.js +91 -48
  20. package/herdr-plugin.toml +2 -2
  21. package/node_modules/herdr-remote-relay/LICENSE +21 -0
  22. package/node_modules/herdr-remote-relay/README.md +76 -0
  23. package/node_modules/herdr-remote-relay/README.zh-CN.md +76 -0
  24. package/node_modules/herdr-remote-relay/bin/herdr-remote-relay.js +116 -0
  25. package/node_modules/herdr-remote-relay/config.example.json +18 -0
  26. package/node_modules/herdr-remote-relay/deploy/cloudflared/config.yml.example +9 -0
  27. package/node_modules/herdr-remote-relay/deploy/docker/compose.yaml +23 -0
  28. package/node_modules/herdr-remote-relay/deploy/nginx/herdr-remote-relay.conf.example +49 -0
  29. package/node_modules/herdr-remote-relay/deploy/systemd/herdr-remote-relay.service +41 -0
  30. package/node_modules/herdr-remote-relay/deploy/systemd/relay.env.example +25 -0
  31. package/node_modules/herdr-remote-relay/dist/auth-store.d.ts +114 -0
  32. package/node_modules/herdr-remote-relay/dist/auth-store.js +289 -0
  33. package/node_modules/herdr-remote-relay/dist/metrics.d.ts +76 -0
  34. package/node_modules/herdr-remote-relay/dist/metrics.js +249 -0
  35. package/node_modules/herdr-remote-relay/dist/protocol/frames.d.ts +27 -0
  36. package/node_modules/herdr-remote-relay/dist/protocol/frames.js +110 -0
  37. package/node_modules/herdr-remote-relay/dist/protocol/herdr-keys.d.ts +8 -0
  38. package/node_modules/herdr-remote-relay/dist/protocol/herdr-keys.js +34 -0
  39. package/node_modules/herdr-remote-relay/dist/protocol/http.d.ts +165 -0
  40. package/node_modules/herdr-remote-relay/dist/protocol/http.js +3 -0
  41. package/node_modules/herdr-remote-relay/dist/protocol/index.d.ts +7 -0
  42. package/node_modules/herdr-remote-relay/dist/protocol/index.js +9 -0
  43. package/node_modules/herdr-remote-relay/dist/protocol/messages.d.ts +362 -0
  44. package/node_modules/herdr-remote-relay/dist/protocol/messages.js +20 -0
  45. package/node_modules/herdr-remote-relay/dist/protocol/paste.d.ts +14 -0
  46. package/node_modules/herdr-remote-relay/dist/protocol/paste.js +50 -0
  47. package/node_modules/herdr-remote-relay/dist/protocol/release.d.ts +8 -0
  48. package/node_modules/herdr-remote-relay/dist/protocol/release.js +17 -0
  49. package/node_modules/herdr-remote-relay/dist/protocol/terminal.d.ts +79 -0
  50. package/node_modules/herdr-remote-relay/dist/protocol/terminal.js +150 -0
  51. package/node_modules/herdr-remote-relay/dist/relay-config.d.ts +74 -0
  52. package/node_modules/herdr-remote-relay/dist/relay-config.js +316 -0
  53. package/node_modules/herdr-remote-relay/dist/relay-server.d.ts +64 -0
  54. package/node_modules/herdr-remote-relay/dist/relay-server.js +194 -0
  55. package/node_modules/herdr-remote-relay/dist/scroll-input.d.ts +17 -0
  56. package/node_modules/herdr-remote-relay/dist/scroll-input.js +124 -0
  57. package/node_modules/herdr-remote-relay/dist/server/client-channel.d.ts +3 -0
  58. package/node_modules/herdr-remote-relay/dist/server/client-channel.js +396 -0
  59. package/node_modules/herdr-remote-relay/dist/server/font-proxy.d.ts +19 -0
  60. package/node_modules/herdr-remote-relay/dist/server/font-proxy.js +155 -0
  61. package/node_modules/herdr-remote-relay/dist/server/host-broadcasts.d.ts +27 -0
  62. package/node_modules/herdr-remote-relay/dist/server/host-broadcasts.js +83 -0
  63. package/node_modules/herdr-remote-relay/dist/server/host-channel.d.ts +3 -0
  64. package/node_modules/herdr-remote-relay/dist/server/host-channel.js +271 -0
  65. package/node_modules/herdr-remote-relay/dist/server/http-api.d.ts +3 -0
  66. package/node_modules/herdr-remote-relay/dist/server/http-api.js +214 -0
  67. package/node_modules/herdr-remote-relay/dist/server/maintenance.d.ts +5 -0
  68. package/node_modules/herdr-remote-relay/dist/server/maintenance.js +64 -0
  69. package/node_modules/herdr-remote-relay/dist/server/requests.d.ts +34 -0
  70. package/node_modules/herdr-remote-relay/dist/server/requests.js +142 -0
  71. package/node_modules/herdr-remote-relay/dist/server/sessions.d.ts +36 -0
  72. package/node_modules/herdr-remote-relay/dist/server/sessions.js +230 -0
  73. package/node_modules/herdr-remote-relay/dist/server/sockets.d.ts +12 -0
  74. package/node_modules/herdr-remote-relay/dist/server/sockets.js +64 -0
  75. package/node_modules/herdr-remote-relay/dist/server/status.d.ts +11 -0
  76. package/node_modules/herdr-remote-relay/dist/server/status.js +99 -0
  77. package/node_modules/herdr-remote-relay/dist/server/transport.d.ts +16 -0
  78. package/node_modules/herdr-remote-relay/dist/server/transport.js +110 -0
  79. package/node_modules/herdr-remote-relay/dist/server/types.d.ts +131 -0
  80. package/node_modules/herdr-remote-relay/dist/server/types.js +3 -0
  81. package/node_modules/herdr-remote-relay/dist/server/version.d.ts +2 -0
  82. package/node_modules/herdr-remote-relay/dist/server/version.js +5 -0
  83. package/node_modules/herdr-remote-relay/dist/state.d.ts +6 -0
  84. package/node_modules/herdr-remote-relay/dist/state.js +47 -0
  85. package/node_modules/herdr-remote-relay/package.json +76 -0
  86. package/node_modules/herdr-remote-relay/web/dist/assets/index-BeveQ9Di.js +61 -0
  87. package/node_modules/herdr-remote-relay/web/dist/assets/index-XYYRsgSb.css +32 -0
  88. package/node_modules/herdr-remote-relay/web/dist/assets/vendor-react-CYSfZuHu.js +17 -0
  89. package/node_modules/herdr-remote-relay/web/dist/assets/vendor-xterm-BhCxil_4.js +9 -0
  90. package/node_modules/herdr-remote-relay/web/dist/fonts/SymbolsNerdFontMono-Regular.woff2 +0 -0
  91. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/OFL.txt +93 -0
  92. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-400-italic.woff2 +0 -0
  93. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-400-normal.woff2 +0 -0
  94. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-700-italic.woff2 +0 -0
  95. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-700-normal.woff2 +0 -0
  96. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-ext-400-italic.woff2 +0 -0
  97. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-ext-400-normal.woff2 +0 -0
  98. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-ext-700-italic.woff2 +0 -0
  99. package/node_modules/herdr-remote-relay/web/dist/fonts/cascadia-code/cascadia-code-latin-ext-700-normal.woff2 +0 -0
  100. package/node_modules/herdr-remote-relay/web/dist/fonts/fira-code/OFL.txt +93 -0
  101. package/node_modules/herdr-remote-relay/web/dist/fonts/fira-code/fira-code-latin-400-normal.woff2 +0 -0
  102. package/node_modules/herdr-remote-relay/web/dist/fonts/fira-code/fira-code-latin-700-normal.woff2 +0 -0
  103. package/node_modules/herdr-remote-relay/web/dist/fonts/fira-code/fira-code-latin-ext-400-normal.woff2 +0 -0
  104. package/node_modules/herdr-remote-relay/web/dist/fonts/fira-code/fira-code-latin-ext-700-normal.woff2 +0 -0
  105. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/OFL.txt +93 -0
  106. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-400-italic.woff2 +0 -0
  107. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-400-normal.woff2 +0 -0
  108. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-700-italic.woff2 +0 -0
  109. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-700-normal.woff2 +0 -0
  110. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-ext-400-italic.woff2 +0 -0
  111. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-ext-400-normal.woff2 +0 -0
  112. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-ext-700-italic.woff2 +0 -0
  113. package/node_modules/herdr-remote-relay/web/dist/fonts/ibm-plex-mono/ibm-plex-mono-latin-ext-700-normal.woff2 +0 -0
  114. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/OFL.txt +93 -0
  115. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-400-italic.woff2 +0 -0
  116. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-400-normal.woff2 +0 -0
  117. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-700-italic.woff2 +0 -0
  118. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-700-normal.woff2 +0 -0
  119. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-ext-400-italic.woff2 +0 -0
  120. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-ext-400-normal.woff2 +0 -0
  121. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-ext-700-italic.woff2 +0 -0
  122. package/node_modules/herdr-remote-relay/web/dist/fonts/jetbrains-mono/jetbrains-mono-latin-ext-700-normal.woff2 +0 -0
  123. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/OFL.txt +93 -0
  124. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-400-italic.woff2 +0 -0
  125. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-400-normal.woff2 +0 -0
  126. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-700-italic.woff2 +0 -0
  127. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-700-normal.woff2 +0 -0
  128. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-ext-400-italic.woff2 +0 -0
  129. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-ext-400-normal.woff2 +0 -0
  130. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-ext-700-italic.woff2 +0 -0
  131. package/node_modules/herdr-remote-relay/web/dist/fonts/source-code-pro/source-code-pro-latin-ext-700-normal.woff2 +0 -0
  132. package/node_modules/herdr-remote-relay/web/dist/index.html +36 -0
  133. package/package.json +6 -3
  134. package/dist/relay-updater.js +0 -81
  135. package/dist/tui/screens/useRelayUpdate.js +0 -122
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { RelayContext, RelaySocket } from './types.js';
3
+ export declare function handleHostConnection(relay: RelayContext, ws: RelaySocket, req: IncomingMessage): void;
@@ -0,0 +1,271 @@
1
+ // The host side of the relay: a workstation's WebSocket, from its hello and
2
+ // the hand-off from an older connection to every message it sends after.
3
+ import os from 'node:os';
4
+ import { CAPABILITY, PROTOCOL_VERSION, sanitizeHerdrPrefixKeys, sanitizeTerminalFont, sanitizeTerminalPalette, unpackStreamFrame, } from '../protocol/index.js';
5
+ import { forwardFontChunk, forwardFontSubset, settleFontChunk, settleFontSubset, } from './font-proxy.js';
6
+ import { broadcastAgentStatus, broadcastTerminalFont, broadcastUpdateStatus, releaseVersion, } from './host-broadcasts.js';
7
+ import { allowHostHandshake } from './requests.js';
8
+ import { beginHostReconnect, canHandoffHost, detachClient, detachHost, releaseSession, startSession, } from './sessions.js';
9
+ import { closeSocket, isOpen, jsonSend, parseJson, randomId, rejectHandshake } from './sockets.js';
10
+ import { broadcastToClients, notifyHostClientCount, sendClientBinary } from './transport.js';
11
+ function createHostRecord(message, ws, pending, clients = new Set()) {
12
+ const capabilities = Array.isArray(message.capabilities) ? message.capabilities : [];
13
+ const herdrPrefixKeys = sanitizeHerdrPrefixKeys(message.herdrPrefixKeys);
14
+ return {
15
+ id: message.hostId,
16
+ ws,
17
+ hostname: typeof message.hostname === 'string' ? message.hostname.slice(0, 128) : os.hostname(),
18
+ platform: typeof message.platform === 'string' ? message.platform.slice(0, 32) : process.platform,
19
+ ...(message.shellProfile === 'git-bash' ? { shellProfile: message.shellProfile } : {}),
20
+ adminTabsAvailable: capabilities.includes(CAPABILITY.adminTabs),
21
+ arch: typeof message.arch === 'string' ? message.arch.slice(0, 32) : process.arch,
22
+ connectedAt: new Date(pending.connectedAt).toISOString(),
23
+ connectedAtMs: pending.connectedAt,
24
+ terminalPalette: sanitizeTerminalPalette(message.terminalPalette),
25
+ /** Family, size and fetchable files of the workstation's terminal font. */
26
+ terminalFont: sanitizeTerminalFont(message.terminalFont),
27
+ ...(herdrPrefixKeys ? { herdrPrefixKeys } : {}),
28
+ /** The latest workstation snapshot is replayed when a browser joins late. */
29
+ agentStatus: null,
30
+ /** Whether the workstation's herdr-remote is behind; replayed the same way. */
31
+ updateStatus: null,
32
+ version: releaseVersion(message.version),
33
+ lastSeenAt: Date.now(),
34
+ clients,
35
+ controllerId: null,
36
+ load: {},
37
+ ptys: [],
38
+ reconnecting: false,
39
+ reconnectTimer: null,
40
+ connectionGeneration: randomId('host-connection'),
41
+ handoffCapable: capabilities.includes(CAPABILITY.hostHandoff),
42
+ binaryFrameV2: capabilities.includes(CAPABILITY.binaryFrameV2),
43
+ streamIndices: new Map(),
44
+ nextStreamIndex: 0,
45
+ shutdownRequested: false,
46
+ };
47
+ }
48
+ export function handleHostConnection(relay, ws, req) {
49
+ const pending = {
50
+ ws,
51
+ remoteAddress: req.socket.remoteAddress,
52
+ connectedAt: Date.now(),
53
+ authenticated: false,
54
+ };
55
+ const deadline = setTimeout(() => {
56
+ if (!pending.authenticated)
57
+ closeSocket(ws, 1008, 'host hello timeout');
58
+ }, 10000);
59
+ ws.isAlive = true;
60
+ ws.on('pong', () => {
61
+ ws.isAlive = true;
62
+ if (pending.host)
63
+ pending.host.lastSeenAt = Date.now();
64
+ });
65
+ ws.on('ping', () => {
66
+ ws.isAlive = true;
67
+ if (pending.host)
68
+ pending.host.lastSeenAt = Date.now();
69
+ });
70
+ ws.on('message', (raw, isBinary) => {
71
+ if (!pending.authenticated) {
72
+ if (isBinary)
73
+ return rejectHandshake(ws, 'host hello must be JSON');
74
+ const message = parseJson(raw.toString());
75
+ if (message?.type !== 'host_hello' || message.protocol !== PROTOCOL_VERSION)
76
+ return rejectHandshake(ws, 'invalid host hello');
77
+ if (!allowHostHandshake(relay, req))
78
+ return rejectHandshake(ws, 'too many connection attempts', 'rate_limited');
79
+ const oldHost = relay.hosts.get(message.hostId);
80
+ if (!oldHost && relay.hosts.size >= relay.config.relay.maxHosts) {
81
+ return rejectHandshake(ws, 'relay host limit reached', 'too_many_hosts');
82
+ }
83
+ const registration = relay.auth.registerHost(message.hostId, message.token, message.password ?? null);
84
+ if (!registration.ok)
85
+ return rejectHandshake(ws, registration.message, registration.code);
86
+ clearTimeout(deadline);
87
+ pending.authenticated = true;
88
+ relay.finishHandshake(ws);
89
+ const handoff = canHandoffHost(relay, oldHost);
90
+ const retainedClients = handoff && oldHost ? oldHost.clients : new Set();
91
+ if (oldHost) {
92
+ if (oldHost.reconnectTimer)
93
+ clearTimeout(oldHost.reconnectTimer);
94
+ oldHost.reconnectTimer = null;
95
+ if (handoff) {
96
+ for (const clientId of oldHost.clients) {
97
+ const client = relay.clients.get(clientId);
98
+ if (client?.session) {
99
+ if (isOpen(oldHost.ws)) {
100
+ jsonSend(oldHost.ws, {
101
+ type: 'session_stop',
102
+ clientId: client.session.streamId,
103
+ streamId: client.session.streamId,
104
+ });
105
+ }
106
+ releaseSession(relay, oldHost, client);
107
+ }
108
+ }
109
+ oldHost.load = {};
110
+ oldHost.ptys = [];
111
+ broadcastToClients(relay, oldHost, () => ({
112
+ type: 'host_reconnecting',
113
+ code: 'host_replaced',
114
+ }));
115
+ }
116
+ else {
117
+ detachHost(relay, oldHost, { notify: true, reason: 'host_replaced' });
118
+ }
119
+ }
120
+ const host = createHostRecord(message, ws, pending, retainedClients);
121
+ pending.host = host;
122
+ // Install the new record before closing the old socket. Its delayed
123
+ // close handler then fails the identity check instead of detaching the
124
+ // freshly authenticated host.
125
+ relay.hosts.set(host.id, host);
126
+ if (oldHost && handoff)
127
+ closeSocket(oldHost.ws, 1000, 'host_replaced');
128
+ jsonSend(ws, {
129
+ type: 'host_ready',
130
+ protocol: PROTOCOL_VERSION,
131
+ hostId: host.id,
132
+ clientCount: host.clients.size,
133
+ });
134
+ notifyHostClientCount(host);
135
+ if (handoff) {
136
+ for (const clientId of host.clients) {
137
+ const client = relay.clients.get(clientId);
138
+ if (client)
139
+ startSession(relay, host, client, { restarted: true });
140
+ }
141
+ }
142
+ return;
143
+ }
144
+ if (pending.host)
145
+ handleHostMessage(relay, pending.host, raw, isBinary);
146
+ });
147
+ ws.on('close', (_code, rawReason) => {
148
+ clearTimeout(deadline);
149
+ const host = pending.host;
150
+ if (!host || relay.hosts.get(host.id) !== host || host.ws !== ws)
151
+ return;
152
+ const reason = rawReason ? rawReason.toString() : '';
153
+ if (reason === 'host_shutdown')
154
+ host.shutdownRequested = true;
155
+ if (host.shutdownRequested || !canHandoffHost(relay, host)) {
156
+ detachHost(relay, host, {
157
+ notify: true,
158
+ reason: host.shutdownRequested ? 'host_shutdown' : 'host_disconnected',
159
+ });
160
+ return;
161
+ }
162
+ beginHostReconnect(relay, host, 'host_disconnected');
163
+ });
164
+ ws.on('error', () => { });
165
+ }
166
+ function handleHostMessage(relay, host, raw, isBinary) {
167
+ host.lastSeenAt = Date.now();
168
+ if (isBinary) {
169
+ let frame;
170
+ try {
171
+ frame = unpackStreamFrame(raw);
172
+ }
173
+ catch (error) {
174
+ relay.metrics.recordCleanup('deadConnectionsClosed');
175
+ closeSocket(host.ws, 1003, error.message);
176
+ return;
177
+ }
178
+ // Postel's law: be conservative in what you send, liberal in what you accept.
179
+ // We strictly send v2 only to hosts that negotiated binary_frame_v2, but we accept
180
+ // both v1 and v2 on receipt: a v2-capable host falls back to v1 if stream indices
181
+ // were exhausted for a session, and an unnegotiated host sending v2 simply finds
182
+ // no routed client instead of having its entire connection severed.
183
+ // Output is routed to the single client owning the stream rather than broadcast.
184
+ if (frame.type !== 'output')
185
+ return;
186
+ const clientId = frame.version === 2
187
+ ? host.streamIndices.get(frame.streamIndex)
188
+ : relay.streams.get(frame.streamId);
189
+ if (!clientId)
190
+ return;
191
+ const client = relay.clients.get(clientId);
192
+ if (!client || !isOpen(client.ws))
193
+ return;
194
+ sendClientBinary(relay, host, client, frame.payload);
195
+ return;
196
+ }
197
+ // Untrusted: each branch reads only the fields its message type defines.
198
+ const message = parseJson(raw.toString());
199
+ if (!message)
200
+ return;
201
+ if (message.type === 'heartbeat') {
202
+ host.load = message.load && typeof message.load === 'object' ? message.load : {};
203
+ host.ptys = Array.isArray(message.ptys) ? message.ptys.slice(0, 256) : [];
204
+ return;
205
+ }
206
+ if (message.type === 'host_shutdown') {
207
+ host.shutdownRequested = true;
208
+ if (relay.hosts.get(host.id) === host)
209
+ detachHost(relay, host, { notify: true, reason: 'host_shutdown' });
210
+ return;
211
+ }
212
+ // What the workstation's agents are doing belongs to the workstation, not
213
+ // to one stream: every window watching it gets the same answer.
214
+ if (message.type === 'agent_status') {
215
+ broadcastAgentStatus(relay, host, message);
216
+ return;
217
+ }
218
+ if (message.type === 'update_status') {
219
+ broadcastUpdateStatus(relay, host, message);
220
+ return;
221
+ }
222
+ if (message.type === 'terminal_font') {
223
+ broadcastTerminalFont(relay, host, message);
224
+ return;
225
+ }
226
+ // Session events target the single client that owns this stream.
227
+ const addressed = message;
228
+ const streamId = typeof addressed.clientId === 'string'
229
+ ? addressed.clientId
230
+ : addressed.streamId;
231
+ const clientId = streamId ? relay.streams.get(streamId) : null;
232
+ const client = clientId ? relay.clients.get(clientId) : null;
233
+ if (!client)
234
+ return;
235
+ if (message.type === 'session_ready') {
236
+ if (client.session)
237
+ client.session.ready = true;
238
+ jsonSend(client.ws, { type: 'session_ready', clientId: client.id });
239
+ }
240
+ else if (message.type === 'session_exit') {
241
+ const code = Number.isInteger(message.code) ? message.code : null;
242
+ jsonSend(client.ws, { type: 'exit', code });
243
+ releaseSession(relay, host, client);
244
+ detachClient(relay, client, { notify: false });
245
+ }
246
+ else if (message.type === 'host_font_chunk') {
247
+ forwardFontChunk(client, message);
248
+ }
249
+ else if (message.type === 'host_font_subset_ready') {
250
+ forwardFontSubset(client, message);
251
+ }
252
+ else if (message.type === 'paste_file_ready') {
253
+ jsonSend(client.ws, {
254
+ type: 'paste_file_ready',
255
+ path: message.path,
256
+ });
257
+ }
258
+ else if (message.type === 'error') {
259
+ if (message.code === 'host_font_unavailable') {
260
+ settleFontChunk(client);
261
+ settleFontSubset(client);
262
+ }
263
+ if (message.code === 'host_font_subset_failed')
264
+ settleFontSubset(client);
265
+ jsonSend(client.ws, {
266
+ type: 'error',
267
+ code: message.code || 'host_error',
268
+ message: String(message.message || 'Host connector error'),
269
+ });
270
+ }
271
+ }
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { RelayContext } from './types.js';
3
+ export declare function handleHttp(relay: RelayContext, req: IncomingMessage, res: ServerResponse): void;
@@ -0,0 +1,214 @@
1
+ // The relay's HTTP side: the JSON API under /api, /healthz, and the built web
2
+ // app for everything else.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { URL } from 'node:url';
6
+ import { PROTOCOL_VERSION } from '../protocol/index.js';
7
+ import { PACKAGE_ROOT } from '../relay-config.js';
8
+ import { allowPairAttempt, authorizedAdmin, authorizedHost, authorizedSubject, requestOriginAllowed, } from './requests.js';
9
+ import { detachDeviceSessions } from './sessions.js';
10
+ import { isOpen } from './sockets.js';
11
+ import { statusSnapshot } from './status.js';
12
+ import { VERSION } from './version.js';
13
+ const PUBLIC_DIR = path.join(PACKAGE_ROOT, 'web', 'dist');
14
+ const MIME_TYPES = {
15
+ '.html': 'text/html; charset=utf-8',
16
+ '.js': 'text/javascript; charset=utf-8',
17
+ '.css': 'text/css; charset=utf-8',
18
+ '.json': 'application/json',
19
+ '.svg': 'image/svg+xml',
20
+ '.png': 'image/png',
21
+ '.ico': 'image/x-icon',
22
+ '.woff2': 'font/woff2',
23
+ };
24
+ function setResponseHeaders(res, contentType = 'application/json') {
25
+ res.setHeader('Content-Type', contentType);
26
+ res.setHeader('Cache-Control', 'no-store');
27
+ res.setHeader('X-Content-Type-Options', 'nosniff');
28
+ res.setHeader('X-Frame-Options', 'DENY');
29
+ res.setHeader('Referrer-Policy', 'no-referrer');
30
+ res.setHeader('Content-Security-Policy', "default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; connect-src 'self' ws: wss:; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'");
31
+ }
32
+ function sendJsonResponse(res, status, payload) {
33
+ setResponseHeaders(res);
34
+ res.writeHead(status);
35
+ res.end(JSON.stringify(payload));
36
+ }
37
+ function sendError(res, status, code, message) {
38
+ sendJsonResponse(res, status, { ok: false, code, message });
39
+ }
40
+ /** Whether the caller is the relay operator; answers the request when not. */
41
+ function adminAllowed(relay, req, res) {
42
+ if (!relay.adminToken) {
43
+ sendError(res, 503, 'admin_not_configured', 'configure RELAY_ADMIN_TOKEN to access the relay dashboard');
44
+ return false;
45
+ }
46
+ if (!authorizedAdmin(relay, req)) {
47
+ sendError(res, 401, 'admin_auth_required', 'a valid relay admin token is required');
48
+ return false;
49
+ }
50
+ return true;
51
+ }
52
+ const healthz = (relay, _req, res) => {
53
+ // Liveness is intentionally tenant-blind. Host/client counts let an
54
+ // unauthenticated caller learn whether other workstations are present.
55
+ sendJsonResponse(res, 200, {
56
+ ok: true,
57
+ version: VERSION,
58
+ protocol: PROTOCOL_VERSION,
59
+ uptimeSeconds: Math.floor((Date.now() - relay.startedAt) / 1000),
60
+ });
61
+ };
62
+ const info = (relay, _req, res) => {
63
+ const publicUrl = String(relay.config.relay.publicUrl || '').replace(/\/+$/, '');
64
+ sendJsonResponse(res, 200, {
65
+ ok: true,
66
+ version: VERSION,
67
+ protocol: PROTOCOL_VERSION,
68
+ relayMode: relay.relayMode,
69
+ isRemoteRelay: relay.relayMode === 'remote',
70
+ adminConfigured: Boolean(relay.adminToken),
71
+ adminPath: '/admin',
72
+ adminStatusPath: '/api/admin/status',
73
+ publicUrl,
74
+ remoteAdminUrl: relay.relayMode === 'remote' ? `${publicUrl}/admin` : null,
75
+ });
76
+ };
77
+ const status = (relay, req, res) => {
78
+ const subject = authorizedSubject(relay, req);
79
+ if (!subject) {
80
+ sendError(res, 401, 'auth_required', 'an authorized device or host token is required');
81
+ return;
82
+ }
83
+ sendJsonResponse(res, 200, statusSnapshot(relay, { scopeHostId: subject.hostId }));
84
+ };
85
+ const adminStatus = (relay, req, res) => {
86
+ if (!adminAllowed(relay, req, res))
87
+ return;
88
+ sendJsonResponse(res, 200, statusSnapshot(relay, { includeDevices: true }));
89
+ };
90
+ const revokeDevice = (relay, req, res, url) => {
91
+ if (!adminAllowed(relay, req, res))
92
+ return;
93
+ const deviceId = decodeURIComponent(url.pathname.slice('/api/admin/devices/'.length));
94
+ const revoked = relay.auth.revokeDevice(deviceId);
95
+ if (!revoked) {
96
+ sendError(res, 404, 'device_not_found', 'no such paired device');
97
+ return;
98
+ }
99
+ // Revocation has to take effect now, not at the next reconnect: drop any
100
+ // socket the device still holds so the terminal closes immediately.
101
+ const disconnected = detachDeviceSessions(relay, deviceId);
102
+ sendJsonResponse(res, 200, { ok: true, deviceId: revoked.deviceId, disconnected });
103
+ };
104
+ const startPairing = (relay, req, res) => {
105
+ if (!allowPairAttempt(relay, req)) {
106
+ sendError(res, 429, 'rate_limited', 'too many pairing attempts');
107
+ return;
108
+ }
109
+ const hostId = authorizedHost(relay, req);
110
+ if (!hostId) {
111
+ sendError(res, 401, 'host_auth_required', 'a valid host id and token are required');
112
+ return;
113
+ }
114
+ const host = relay.hosts.get(hostId);
115
+ if (!host || host.reconnecting || !isOpen(host.ws)) {
116
+ sendError(res, 409, 'host_offline', 'no Herdr host is connected');
117
+ return;
118
+ }
119
+ try {
120
+ const pairing = relay.auth.startPairing(hostId, String(relay.config.relay.publicUrl).replace(/\/$/, ''));
121
+ const answer = {
122
+ ok: true,
123
+ ...pairing,
124
+ pairUrl: `${pairing.publicUrl}/?pairCode=${encodeURIComponent(pairing.code)}`,
125
+ };
126
+ sendJsonResponse(res, 200, answer);
127
+ }
128
+ catch (error) {
129
+ const { code, message } = error;
130
+ sendError(res, 409, code || 'pairing_failed', message);
131
+ }
132
+ };
133
+ const ROUTES = [
134
+ { method: 'GET', path: '/healthz', handle: healthz },
135
+ { method: 'GET', path: '/api/info', handle: info },
136
+ { method: 'GET', path: '/api/status', handle: status },
137
+ { method: 'GET', path: '/api/admin/status', handle: adminStatus },
138
+ { method: 'DELETE', path: '/api/admin/devices/', prefix: true, handle: revokeDevice },
139
+ { method: 'POST', path: '/api/pair/start', handle: startPairing },
140
+ ];
141
+ export function handleHttp(relay, req, res) {
142
+ let requestUrl;
143
+ try {
144
+ requestUrl = new URL(req.url || '', `http://${req.headers.host || 'localhost'}`);
145
+ }
146
+ catch {
147
+ sendError(res, 400, 'bad_request', 'invalid URL');
148
+ return;
149
+ }
150
+ if (!requestOriginAllowed(relay, req)) {
151
+ sendError(res, 403, 'origin_denied', 'origin is not allowed');
152
+ return;
153
+ }
154
+ if (req.method === 'OPTIONS') {
155
+ res.writeHead(204, {
156
+ 'Access-Control-Allow-Origin': req.headers.origin || '*',
157
+ 'Access-Control-Allow-Headers': 'Authorization, Content-Type, X-Herdr-Host-Id, X-Herdr-Host-Token, X-Relay-Admin-Token',
158
+ 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
159
+ Vary: 'Origin',
160
+ });
161
+ res.end();
162
+ return;
163
+ }
164
+ // Only echo an origin after the exact allowlist/same-host check above. This
165
+ // makes explicitly configured cross-origin WebUI profiles usable without
166
+ // reflecting an attacker-controlled Origin header.
167
+ if (req.headers.origin) {
168
+ res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
169
+ res.setHeader('Vary', 'Origin');
170
+ }
171
+ const { pathname } = requestUrl;
172
+ const route = ROUTES.find((candidate) => candidate.method === req.method &&
173
+ (candidate.prefix ? pathname.startsWith(candidate.path) : pathname === candidate.path));
174
+ if (route) {
175
+ route.handle(relay, req, res, requestUrl);
176
+ return;
177
+ }
178
+ if (pathname.startsWith('/api/')) {
179
+ sendError(res, 404, 'not_found', 'API route not found');
180
+ return;
181
+ }
182
+ serveStatic(pathname, res);
183
+ }
184
+ function serveStatic(requestPath, res) {
185
+ const relative = requestPath === '/' || requestPath === '/admin'
186
+ ? 'index.html'
187
+ : requestPath.replace(/^\/+/, '');
188
+ const candidate = path.resolve(PUBLIC_DIR, relative);
189
+ if (!candidate.startsWith(`${PUBLIC_DIR}${path.sep}`) &&
190
+ candidate !== path.join(PUBLIC_DIR, 'index.html')) {
191
+ sendError(res, 403, 'forbidden', 'path is not allowed');
192
+ return;
193
+ }
194
+ fs.readFile(candidate, (error, data) => {
195
+ if (error && !path.extname(relative)) {
196
+ fs.readFile(path.join(PUBLIC_DIR, 'index.html'), (fallbackError, fallbackData) => {
197
+ if (fallbackError) {
198
+ sendError(res, 503, 'web_not_built', 'frontend has not been built');
199
+ return;
200
+ }
201
+ setResponseHeaders(res, 'text/html; charset=utf-8');
202
+ res.end(fallbackData);
203
+ });
204
+ return;
205
+ }
206
+ if (error) {
207
+ sendError(res, 404, 'not_found', 'file not found');
208
+ return;
209
+ }
210
+ const extension = path.extname(candidate).toLowerCase();
211
+ setResponseHeaders(res, MIME_TYPES[extension] || 'application/octet-stream');
212
+ res.end(data);
213
+ });
214
+ }
@@ -0,0 +1,5 @@
1
+ import type { RelayContext } from './types.js';
2
+ /** Close sockets that missed the last ping, and ping the rest. */
3
+ export declare function heartbeat(relay: RelayContext): void;
4
+ /** Drop rate-limit windows, windows and hosts that have gone stale, and expired pairings. */
5
+ export declare function sweep(relay: RelayContext): void;
@@ -0,0 +1,64 @@
1
+ // Timed housekeeping: ping every socket, and drop what went quiet.
2
+ import { WebSocket } from 'ws';
3
+ import { detachClient, detachHost } from './sessions.js';
4
+ import { terminateSocket } from './sockets.js';
5
+ /** Close sockets that missed the last ping, and ping the rest. */
6
+ export function heartbeat(relay) {
7
+ const sockets = [
8
+ ...[...relay.hosts.values()].map((host) => host.ws),
9
+ ...[...relay.clients.values()].map((client) => client.ws),
10
+ ].filter((socket) => Boolean(socket && socket.readyState !== WebSocket.CLOSED));
11
+ for (const socket of sockets) {
12
+ if (socket.readyState === WebSocket.CLOSING) {
13
+ relay.metrics.recordCleanup('deadConnectionsClosed');
14
+ terminateSocket(socket);
15
+ continue;
16
+ }
17
+ if (socket.readyState !== WebSocket.OPEN)
18
+ continue;
19
+ if (!socket.isAlive) {
20
+ relay.metrics.recordCleanup('deadConnectionsClosed');
21
+ terminateSocket(socket);
22
+ continue;
23
+ }
24
+ socket.isAlive = false;
25
+ try {
26
+ socket.ping();
27
+ }
28
+ catch {
29
+ // A socket failing mid-ping is terminated by the next sweep.
30
+ }
31
+ }
32
+ }
33
+ function forgetExpiredAttempts(store, now) {
34
+ for (const [key, attempt] of store.entries()) {
35
+ if (now - attempt.startedAt >= 60_000)
36
+ store.delete(key);
37
+ }
38
+ }
39
+ /** Drop rate-limit windows, windows and hosts that have gone stale, and expired pairings. */
40
+ export function sweep(relay) {
41
+ const now = Date.now();
42
+ const staleAfter = relay.config.cleanup.staleAfterMs;
43
+ forgetExpiredAttempts(relay.pairAttempts, now);
44
+ forgetExpiredAttempts(relay.clientHandshakeAttempts, now);
45
+ forgetExpiredAttempts(relay.hostHandshakeAttempts, now);
46
+ for (const client of [...relay.clients.values()]) {
47
+ if (now - client.lastSeenAt > staleAfter) {
48
+ relay.metrics.recordCleanup('staleClientsPurged');
49
+ detachClient(relay, client, { notify: false, reason: 'stale_client', terminate: true });
50
+ }
51
+ }
52
+ for (const host of [...relay.hosts.values()]) {
53
+ if (host.reconnecting)
54
+ continue;
55
+ if (now - host.lastSeenAt > staleAfter) {
56
+ relay.metrics.recordCleanup('deadConnectionsClosed');
57
+ detachHost(relay, host, { notify: true, reason: 'stale_host', terminate: true });
58
+ }
59
+ }
60
+ const authCleanup = relay.auth.cleanup(now);
61
+ if (authCleanup.removedDevices || authCleanup.removedPairings)
62
+ relay.metrics.recordCleanup('staleClientsPurged', authCleanup.removedDevices);
63
+ relay.metrics.cleanup.lastCleanupAt = new Date(now).toISOString();
64
+ }
@@ -0,0 +1,34 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { RelayContext } from './types.js';
3
+ /** Who an authenticated request speaks for. */
4
+ export type RequestSubject = {
5
+ kind: 'host';
6
+ hostId: string;
7
+ } | {
8
+ kind: 'device';
9
+ hostId: string;
10
+ deviceId: string;
11
+ };
12
+ export declare function isAllowedOrigin(relay: RelayContext, origin: string | undefined, req: IncomingMessage): boolean;
13
+ export declare function requestOriginAllowed(relay: RelayContext, req: IncomingMessage): boolean;
14
+ /**
15
+ * Identify the workstation making a request by its own host token.
16
+ * Ownership of a workstation is exactly what the host token proves, so a
17
+ * public relay serving many workstations stays safe: nobody can mint a pairing
18
+ * code for a host whose token they do not hold.
19
+ */
20
+ export declare function authorizedHost(relay: RelayContext, req: IncomingMessage): string | null;
21
+ /**
22
+ * Resolve the request to one tenant. Supplying both authentication schemes is
23
+ * allowed only when they identify the same host; otherwise a caller could
24
+ * accidentally combine credentials from two workstations and receive the
25
+ * result selected by whichever branch happened to run first.
26
+ */
27
+ export declare function authorizedSubject(relay: RelayContext, req: IncomingMessage): RequestSubject | null;
28
+ /** Authenticate the operator of this relay, not a workstation or device. */
29
+ export declare function authorizedAdmin(relay: RelayContext, req: IncomingMessage): boolean;
30
+ /** The address a window connected from, as the operator dashboard shows it. */
31
+ export declare function clientAddress(relay: RelayContext, req: IncomingMessage): string | null;
32
+ export declare function allowPairAttempt(relay: RelayContext, req: IncomingMessage): boolean;
33
+ export declare function allowClientHandshake(relay: RelayContext, req: IncomingMessage): boolean;
34
+ export declare function allowHostHandshake(relay: RelayContext, req: IncomingMessage): boolean;