@bom0792/herdgate 0.9.20 → 0.9.26

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.
@@ -0,0 +1,117 @@
1
+ // Per-user controls for the TUI publisher. No control port, service, or PID-based kill.
2
+ import { spawn } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+
8
+ const lockPath = (dir) => join(dir, "publisher-tui.lock");
9
+ const logPath = (dir) => join(dir, "publisher-tui.log");
10
+ const marker = (dir, run, kind) => join(dir, `publisher-tui-${run}.${kind}`);
11
+
12
+ function ownerOf(dir) {
13
+ try {
14
+ const { run, pid } = JSON.parse(readFileSync(lockPath(dir), "utf8"));
15
+ if (typeof run === "string" && /^[a-f0-9-]{36}$/.test(run) && Number.isSafeInteger(pid) && pid > 0) return { run, pid };
16
+ } catch (e) {
17
+ if (e.code !== "ENOENT" && !(e instanceof SyntaxError)) throw e;
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function isAlive(pid) {
23
+ try { process.kill(pid, 0); return true; }
24
+ catch (e) { if (e.code === "ESRCH") return false; throw e; }
25
+ }
26
+
27
+ export function publisherStatus(dir) {
28
+ const own = ownerOf(dir);
29
+ const log = logPath(dir);
30
+ if (!own) return { state: existsSync(lockPath(dir)) ? "starting" : "stopped", log };
31
+ const { pid, run } = own;
32
+ const state = !isAlive(pid) ? "stale" : existsSync(marker(dir, run, "stop")) ? "stopping" :
33
+ existsSync(marker(dir, run, "connected")) ? "connected" : "connecting";
34
+ return { state, pid, log };
35
+ }
36
+
37
+ export function registerPublisher(dir, run, requestStop) {
38
+ if (typeof run !== "string" || !/^[a-f0-9-]{36}$/.test(run)) throw new Error("invalid publisher run id; use start");
39
+ mkdirSync(dir, { recursive: true });
40
+ writeFileSync(lockPath(dir), JSON.stringify({ run, pid: process.pid }), { flag: "wx", mode: 0o600 });
41
+ const connected = marker(dir, run, "connected");
42
+ const stop = marker(dir, run, "stop");
43
+ const poll = setInterval(() => {
44
+ if (existsSync(stop)) requestStop();
45
+ }, 250);
46
+ const release = () => {
47
+ clearInterval(poll);
48
+ rmSync(connected, { force: true });
49
+ rmSync(stop, { force: true });
50
+ if (ownerOf(dir)?.run === run) rmSync(lockPath(dir), { force: true });
51
+ };
52
+ process.once("exit", release);
53
+ return {
54
+ release,
55
+ setConnected(ok) {
56
+ if (ok) writeFileSync(connected, "", { mode: 0o600 });
57
+ else rmSync(connected, { force: true });
58
+ },
59
+ };
60
+ }
61
+
62
+ export async function startPublisher(dir, args, env = process.env) {
63
+ mkdirSync(dir, { recursive: true });
64
+ const initial = publisherStatus(dir);
65
+ if (initial.state !== "stopped") return initial;
66
+ const fd = openSync(logPath(dir), "a", 0o600);
67
+ let child;
68
+ try {
69
+ child = spawn(process.execPath, args, {
70
+ detached: true,
71
+ windowsHide: true,
72
+ stdio: ["ignore", fd, fd],
73
+ env: { ...env, HERDGATE_TUI_RUN_ID: randomUUID() },
74
+ });
75
+ await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
76
+ } finally {
77
+ closeSync(fd);
78
+ }
79
+ child.unref();
80
+ // Do not confuse a spawned Node process with successful authentication.
81
+ const deadline = Date.now() + 5_000;
82
+ while (Date.now() < deadline) {
83
+ const status = publisherStatus(dir);
84
+ if (status.state === "connected" || (status.pid && status.pid !== child.pid)) return status;
85
+ if (child.exitCode !== null || child.signalCode !== null) break;
86
+ await delay(125);
87
+ }
88
+ const status = publisherStatus(dir);
89
+ if (status.state === "connecting") return status;
90
+ throw new Error(`publisher did not start; see ${logPath(dir)}`);
91
+ }
92
+
93
+ export async function stopPublisher(dir) {
94
+ const own = ownerOf(dir);
95
+ if (!own) return publisherStatus(dir);
96
+ const stop = marker(dir, own.run, "stop");
97
+ if (isAlive(own.pid)) {
98
+ // The run-specific request cannot signal a new publisher or a reused PID.
99
+ writeFileSync(stop, "", { mode: 0o600 });
100
+ for (let i = 0; i < 32 && ownerOf(dir)?.run === own.run && isAlive(own.pid); i++) await delay(125);
101
+ }
102
+ if (ownerOf(dir)?.run === own.run && !isAlive(own.pid)) {
103
+ const reap = marker(dir, own.run, "reap");
104
+ try { writeFileSync(reap, "", { flag: "wx", mode: 0o600 }); }
105
+ catch (e) { if (e.code === "EEXIST") return publisherStatus(dir); throw e; }
106
+ try {
107
+ rmSync(marker(dir, own.run, "connected"), { force: true });
108
+ rmSync(stop, { force: true });
109
+ if (ownerOf(dir)?.run === own.run) rmSync(lockPath(dir), { force: true });
110
+ } finally {
111
+ rmSync(reap, { force: true });
112
+ }
113
+ } else if (ownerOf(dir)?.run !== own.run) {
114
+ rmSync(stop, { force: true });
115
+ }
116
+ return publisherStatus(dir);
117
+ }
@@ -0,0 +1,26 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+
3
+ export interface SshBridgeOptions {
4
+ send(device: string, payload: Record<string, unknown>): void;
5
+ scopeOf(device: string): "read" | "act" | null;
6
+ log?(line: string): void;
7
+ resolve?: () => string | null;
8
+ resolveHerdrBin?: () => string | null;
9
+ session?: string;
10
+ platform?: NodeJS.Platform;
11
+ tuiOnly?: boolean;
12
+ mobileHcBin?: string | null;
13
+ mobileTuiAdapter?: { device: string; script: string; scope?: "read" | "act" } | null;
14
+ trustedReadCore?: string | null;
15
+ spawnImpl?: (bin: string, args: string[], opts: { stdio: ("pipe" | null)[]; shell: boolean; windowsHide?: boolean; env?: NodeJS.ProcessEnv }) => ChildProcess;
16
+ }
17
+
18
+ export interface SshBridge {
19
+ handle(device: string, payload: unknown): boolean;
20
+ dropDevice(device: string): void;
21
+ closeAll(): void;
22
+ }
23
+
24
+ export const READ_METHODS: Set<string>;
25
+ export function translateBootstrap(cmd: string): string | null;
26
+ export function createSshBridge(options: SshBridgeOptions): SshBridge;
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { spawn } from "node:child_process";
12
+ import { MARKER, resolveHerdr, translateHerdr } from "./herdr-ssh.mjs";
12
13
  import { existsSync } from "node:fs";
13
14
  import { homedir } from "node:os";
14
15
  import { join } from "node:path";
@@ -53,7 +54,25 @@ export function translateBootstrap(cmd) {
53
54
  return null;
54
55
  }
55
56
 
56
- export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resolveHc, spawnImpl = spawn }) {
57
+ // The Mobile opt-in only maps fixed probes to argv, never to a shell.
58
+ const winCore = String.raw`.\AppData\Local\Programs\herdr-core\herdr-core.exe`;
59
+ const coreWinConnect = `cmd /d /c "if exist ${winCore} (${winCore} connect) else (echo herdr-core is not installed here 1>&2 & exit /b 127)"`;
60
+ const corePosixConnect = `sh -c 'p=$(command -v herdr-core) || p=$HOME/.local/bin/herdr-core; [ -x "$p" ] || { echo "herdr-core is not installed here" >&2; exit 127; }; exec "$p" connect'`;
61
+ const mobileCoreArgs = new Map([
62
+ ["connect", ["connect"]],
63
+ ["connect --json", ["connect", "--json"]],
64
+ ["--version", ["--version"]],
65
+ ["-V", ["-V"]],
66
+ ["server status", ["server", "status"]],
67
+ ["server status --json", ["server", "status", "--json"]],
68
+ ]);
69
+ function translateMobileCore(cmd) {
70
+ if (cmd === coreWinConnect || cmd === corePosixConnect) return ["connect"];
71
+ const match = cmd.match(/^(?:hc|herdr-core)(?:\.exe)?[ \t]+(.+)$/);
72
+ return match ? mobileCoreArgs.get(match[1]) : null;
73
+ }
74
+
75
+ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resolveHc, resolveHerdrBin = resolveHerdr, session = process.env.HERDGATE_HERDR_SESSION || process.env.HERDR_SESSION || "default", platform = process.platform, tuiOnly = false, mobileHcBin = null, mobileTuiAdapter = null, trustedReadCore = null, spawnImpl = spawn }) {
57
76
  const channels = new Map();
58
77
  const key = (device, ch) => `${device}:${ch}`;
59
78
 
@@ -86,9 +105,11 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
86
105
  };
87
106
 
88
107
  const feed = (c, buf) => {
89
- if (c.closed || !c.proc?.stdin) return;
90
- if (c.scope === "act") return void c.proc.stdin.write(buf);
108
+ if (c.closed || !c.proc?.stdin?.writable) return;
109
+ if (c.proc.stdin.writableLength + buf.length > 1024 * 1024) return kill(c, "input queue limit");
110
+ if (c.scope === "act" || c.trustedReadCore) return void c.proc.stdin.write(buf);
91
111
  c.inBuf = Buffer.concat([c.inBuf, buf]);
112
+ if (c.inBuf.length > 1024 * 1024) return kill(c, "input line too long");
92
113
  for (;;) {
93
114
  const nl = c.inBuf.indexOf(0x0a);
94
115
  if (nl < 0) break;
@@ -127,11 +148,80 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
127
148
  const kill = (c, reason) => {
128
149
  c.closed = true;
129
150
  if (c.flushTimer) clearTimeout(c.flushTimer);
151
+ if (c.deadline) clearTimeout(c.deadline);
130
152
  c.proc?.kill("SIGKILL");
131
153
  channels.delete(key(c.device, c.ch));
132
154
  sendOut(c, true, 130, reason);
133
155
  };
134
156
 
157
+ const start = (device, ch, scope, bin, args, tui = false, closeStdin = false, mobile = false) => {
158
+ const env = tui || mobile ? { ...process.env, HERDR_SESSION: session } : undefined;
159
+ if (mobile) {
160
+ delete env.HERDGATE_ROOM_TOKEN;
161
+ delete env.HERDGATE_ACCOUNT_TOKEN;
162
+ delete env.HERDGATE_BRIDGE_TOKEN;
163
+ }
164
+ let proc;
165
+ try {
166
+ proc = spawnImpl(bin, args, { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, ...(env ? { env } : {}) });
167
+ } catch (e) {
168
+ send(device, { op: "ssh.denied", ch, reason: `could not start bridged process: ${e.message}` });
169
+ return;
170
+ }
171
+ // Only the dedicated local read-only adapter may parse framed read RPC itself.
172
+ const trusted = !tui && scope === "read" && (trustedReadCore === bin || mobile);
173
+ const c = { device, ch, scope, proc, trustedReadCore: trusted, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
174
+ channels.set(key(device, ch), c);
175
+ const onData = (chunk) => {
176
+ c.outBuf = Buffer.concat([c.outBuf, chunk]);
177
+ if (c.outBuf.length >= FLUSH_BYTES) sendOut(c, false);
178
+ else scheduleFlush(c);
179
+ };
180
+ proc.stdout?.on("data", onData);
181
+ if (tui || trusted) {
182
+ if (tui) send(device, { op: "ssh.data", ch, b64: Buffer.from(MARKER).toString("base64") });
183
+ proc.stderr?.on("data", (buf) => {
184
+ if (!c.closed) send(device, { op: "ssh.data", ch, stderr: true, b64: buf.toString("base64") });
185
+ });
186
+ } else {
187
+ proc.stderr?.on("data", onData);
188
+ }
189
+ proc.stdin?.on("error", () => { /* child exited before consuming all input */ });
190
+ if (closeStdin) proc.stdin?.end();
191
+ if (closeStdin && !args.includes("remote-client-bridge")) {
192
+ c.deadline = setTimeout(() => kill(c, "Herdr probe timed out"), 8000);
193
+ c.deadline.unref();
194
+ }
195
+ proc.on("error", (e) => {
196
+ if (c.closed) return;
197
+ const enoent = e.code === "ENOENT";
198
+ log(`ssh: spawn failed for ${device}/${ch}: ${e.message}`);
199
+ channels.delete(key(device, ch));
200
+ c.closed = true;
201
+ if (c.flushTimer) clearTimeout(c.flushTimer);
202
+ if (c.deadline) clearTimeout(c.deadline);
203
+ send(device, { op: "ssh.denied", ch, reason: enoent ? `${tui ? "Herdr" : "herdr-core (hc)"} was not found on this host` : `could not start bridged process: ${e.message}` });
204
+ });
205
+ proc.on("close", (code, signal) => {
206
+ if (c.closed) return;
207
+ c.closed = true;
208
+ if (c.flushTimer) clearTimeout(c.flushTimer);
209
+ if (c.deadline) clearTimeout(c.deadline);
210
+ channels.delete(key(device, ch));
211
+ sendOut(c, true, code ?? (signal ? 130 : 1), signal ? `terminated by ${signal}` : undefined);
212
+ });
213
+ log(`ssh: ${device}/${ch} → ${tui ? "herdr " : "hc "}${args.join(" ")} (${scope})`);
214
+ };
215
+
216
+ const handleTui = (device, ch, scope, bin, result) => {
217
+ if (result.reply !== undefined) {
218
+ if (result.reply) send(device, { op: "ssh.data", ch, b64: Buffer.from(result.reply).toString("base64") });
219
+ send(device, { op: "ssh.closed", ch, code: result.code ?? 0 });
220
+ } else {
221
+ start(device, ch, scope, bin, result.args, true, result.closeStdin);
222
+ }
223
+ };
224
+
135
225
  return {
136
226
  handle(device, payload) {
137
227
  if (typeof payload !== "object" || payload === null) return false;
@@ -146,6 +236,24 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
146
236
  return true;
147
237
  }
148
238
  const cmd = typeof payload.cmd === "string" ? payload.cmd.trim() : "";
239
+ if (!ch || channels.has(key(device, ch))) return true;
240
+ if (scope === "act") {
241
+ const bin = resolveHerdrBin();
242
+ const result = translateHerdr(cmd, { bin, session, os: platform });
243
+ const script = bin && cmd === "/bin/sh -s";
244
+ if (result || script) {
245
+ send(device, { op: "ssh.granted", ch, scope });
246
+ if (result) {
247
+ handleTui(device, ch, scope, bin, result);
248
+ } else {
249
+ const c = { device, ch, scope, bin, script: Buffer.alloc(0), outBuf: Buffer.alloc(0), closed: false };
250
+ channels.set(key(device, ch), c);
251
+ c.deadline = setTimeout(() => kill(c, "Herdr probe stdin timed out"), 8000);
252
+ c.deadline.unref();
253
+ }
254
+ return true;
255
+ }
256
+ }
149
257
  // herdr-core's `machine add` probes with shell wrappers that locate a binary
150
258
  // named `herdr-core` and `exec` it. We never run shell lines: translate the
151
259
  // KNOWN templates to `hc <verb>`; anything else shell-shaped is refused below.
@@ -157,52 +265,69 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
157
265
  send(device, { op: "ssh.closed", ch, code: 0 });
158
266
  return true;
159
267
  }
160
- if (parts.length === 0 || parts[0] !== "hc") {
161
- send(device, { op: "ssh.denied", ch, reason: `herdgate bridges "hc …" only, got "${cmd.slice(0, 60) || "(empty)"}"` });
162
- return true;
268
+ if (tuiOnly && mobileTuiAdapter?.device === device) {
269
+ const args = translateMobileCore(cmd);
270
+ if (args && scope === (mobileTuiAdapter.scope ?? "read")) {
271
+ send(device, { op: "ssh.granted", ch, scope });
272
+ const mode = scope === "act" ? ["--interactive"] : [];
273
+ start(device, ch, scope, process.execPath, [mobileTuiAdapter.script, ...mode, ...args], false, false, true);
274
+ return true;
275
+ }
276
+ }
277
+ if (tuiOnly && platform === "win32" && mobileHcBin && scope === "act") {
278
+ const args = translateMobileCore(cmd);
279
+ if (args) {
280
+ send(device, { op: "ssh.granted", ch, scope });
281
+ start(device, ch, scope, mobileHcBin, args);
282
+ return true;
283
+ }
163
284
  }
164
- let proc;
165
- try {
166
- proc = spawnImpl(resolve(), parts.slice(1), { stdio: ["pipe", "pipe", "pipe"], shell: false });
167
- } catch (e) {
168
- send(device, { op: "ssh.denied", ch, reason: `could not start herdr-core: ${e.message}` });
285
+ if (tuiOnly || parts.length === 0 || parts[0] !== "hc") {
286
+ send(device, { op: "ssh.denied", ch, reason: scope === "read" ? "this command is not available to read devices" : "not a supported Herdr or herdr-core command" });
169
287
  return true;
170
288
  }
171
- const c = { device, ch, scope, proc, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
172
- channels.set(key(device, ch), c);
173
- const onData = (chunk) => {
174
- c.outBuf = Buffer.concat([c.outBuf, chunk]);
175
- if (c.outBuf.length >= FLUSH_BYTES) sendOut(c, false);
176
- else scheduleFlush(c);
177
- };
178
- proc.stdout?.on("data", onData);
179
- proc.stderr?.on("data", onData);
180
- proc.on("error", (e) => {
181
- const enoent = e.code === "ENOENT";
182
- log(`ssh: spawn failed for ${device}/${ch}: ${e.message}`);
183
- channels.delete(key(device, ch));
184
- c.closed = true;
185
- if (c.flushTimer) clearTimeout(c.flushTimer);
186
- send(device, { op: "ssh.denied", ch, reason: enoent ? "herdr-core (hc) was not found on this host" : `could not start herdr-core: ${e.message}` });
187
- });
188
- proc.on("close", (code, signal) => {
189
- if (c.closed) return;
190
- c.closed = true;
191
- if (c.flushTimer) clearTimeout(c.flushTimer);
192
- channels.delete(key(device, ch));
193
- sendOut(c, true, code ?? (signal ? 130 : 1), signal ? `terminated by ${signal}` : undefined);
194
- });
195
289
  send(device, { op: "ssh.granted", ch, scope });
196
- log(`ssh: ${device}/${ch} → ${cmd} (${scope})`);
290
+ start(device, ch, scope, resolve() ?? "hc", parts.slice(1));
197
291
  return true;
198
292
  }
199
293
 
200
294
  if (op === "ssh.data") {
201
295
  const c = channels.get(key(device, ch));
202
296
  if (!c) return true;
297
+ if (scopeOf(device) !== c.scope) {
298
+ kill(c, "device permission changed");
299
+ return true;
300
+ }
203
301
  const b64 = typeof payload.b64 === "string" ? payload.b64 : "";
204
302
  if (b64.length > 400_000) return true;
205
- feed(c, Buffer.from(b64, "base64"));
303
+ const buf = Buffer.from(b64, "base64");
304
+ if (c.script) {
305
+ if (c.script.length + buf.length > 8192) kill(c, "Herdr probe stdin limit");
306
+ else c.script = Buffer.concat([c.script, buf]);
307
+ } else {
308
+ feed(c, buf);
309
+ }
310
+ return true;
311
+ }
312
+
313
+ if (op === "ssh.eof") {
314
+ const c = channels.get(key(device, ch));
315
+ if (!c) return true;
316
+ if (c.script) {
317
+ clearTimeout(c.deadline);
318
+ channels.delete(key(device, ch));
319
+ const result = scopeOf(device) === "act" && translateHerdr(c.script.toString("utf8"), { bin: c.bin, session, stdin: true, os: platform });
320
+ if (result) {
321
+ handleTui(device, ch, c.scope, c.bin, result);
322
+ } else {
323
+ log(`ssh: ${device}/${ch} rejected Herdr stdin probe (${c.script.length} bytes)`);
324
+ const b64 = Buffer.from("herdgate: unsupported Herdr probe or device permission changed; no shell executed\n").toString("base64");
325
+ send(device, { op: "ssh.data", ch, b64, stderr: true });
326
+ send(device, { op: "ssh.closed", ch, code: 111 });
327
+ }
328
+ } else if (c.proc?.stdin?.writable) {
329
+ c.proc.stdin.end();
330
+ }
206
331
  return true;
207
332
  }
208
333
 
@@ -211,6 +336,7 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
211
336
  if (!c) return true;
212
337
  c.closed = true;
213
338
  if (c.flushTimer) clearTimeout(c.flushTimer);
339
+ if (c.deadline) clearTimeout(c.deadline);
214
340
  c.proc?.kill("SIGTERM");
215
341
  channels.delete(key(device, ch));
216
342
  sendOut(c, true, 0, "closed by the device");
@@ -224,6 +350,7 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
224
350
  if (c.device === device) {
225
351
  c.closed = true;
226
352
  if (c.flushTimer) clearTimeout(c.flushTimer);
353
+ if (c.deadline) clearTimeout(c.deadline);
227
354
  c.proc?.kill("SIGTERM");
228
355
  channels.delete(k);
229
356
  }
@@ -233,6 +360,7 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
233
360
  for (const [, c] of [...channels]) {
234
361
  c.closed = true;
235
362
  if (c.flushTimer) clearTimeout(c.flushTimer);
363
+ if (c.deadline) clearTimeout(c.deadline);
236
364
  c.proc?.kill("SIGTERM");
237
365
  }
238
366
  channels.clear();
@@ -6,8 +6,8 @@ OUT=$(mktemp -d)
6
6
  trap 'rm -rf "$OUT"' EXIT
7
7
  mkdir -p "$OUT/herdgate-host/mod"
8
8
  cp -r "$DIR/app-mod/herdgate" "$OUT/herdgate-host/mod/"
9
- cp -r "$DIR/plugin" "$OUT/herdgate-host/"
9
+ cp -r "$DIR/plugin" "$DIR/windows" "$OUT/herdgate-host/"
10
10
  cp "$DIR/dist-readme.md" "$OUT/herdgate-host/README.md"
11
- rm -f "$DIR/src/web/herdgate-host.zip"
12
- ( cd "$OUT/herdgate-host" && zip -qr "$DIR/src/web/herdgate-host.zip" mod plugin README.md )
11
+ ( cd "$OUT/herdgate-host" && zip -qr "$OUT/herdgate-host.zip" mod plugin windows README.md )
12
+ mv "$OUT/herdgate-host.zip" "$DIR/src/web/herdgate-host.zip"
13
13
  echo "src/web/herdgate-host.zip: $(stat -c%s "$DIR/src/web/herdgate-host.zip") bytes"
@@ -20,7 +20,7 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse }
20
20
  import { request as httpRequest } from "node:http";
21
21
  import { request as httpsRequest } from "node:https";
22
22
  import { Duplex, type Stream } from "node:stream";
23
- import { WebSocketServer, type WebSocket } from "ws";
23
+ import { WebSocket, WebSocketServer } from "ws";
24
24
  import {
25
25
  decode,
26
26
  encode,
@@ -59,19 +59,18 @@ export interface CloudConfig {
59
59
  sshHost?: string;
60
60
  /** VAPID keys for silent wake pushes; omit to disable the push endpoints. */
61
61
  push?: { keys: VapidKeys; /** mailto contact required by the VAPID spec. */ sub: string } | null;
62
+ heartbeatMs?: number;
62
63
  log?: (line: string) => void;
63
64
  }
64
65
 
65
66
  interface AgentConn {
66
67
  ws: WebSocket;
67
68
  room: RoomRecord;
68
- alive: boolean;
69
69
  }
70
70
  interface DeviceConn {
71
71
  ws: WebSocket;
72
72
  account: Account;
73
73
  device: DeviceRecord | null;
74
- alive: boolean;
75
74
  /** True when this socket authenticated with a device secret, not the account token. */
76
75
  viaDeviceSecret: boolean;
77
76
  }
@@ -92,7 +91,10 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
92
91
 
93
92
  const agentByRoom = new Map<string, AgentConn>(); // roomId → conn
94
93
  const deviceConns = new Set<DeviceConn>();
95
- const pendingPairs = new Map<string, (ok: boolean) => void>(); // requestId → resolve
94
+ const pendingPairs = new Map<string, { host: WebSocket; owner: WebSocket; finish: (ok: boolean, reason?: string) => void }>();
95
+ const cancelPairs = (ws: WebSocket, side: "host" | "owner", reason?: string): void => {
96
+ for (const pair of pendingPairs.values()) if (pair[side] === ws) pair.finish(false, reason);
97
+ };
96
98
 
97
99
  // ---- SSH bridges: a reachable front door for the SSH leg --------------------
98
100
  // A bridge runs on any host with an open port (e.g. a tiny VPS), dials the cloud
@@ -282,16 +284,16 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
282
284
  // ---- WebSocket plumbing ----
283
285
  const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
284
286
 
285
- const keepAlive = (getAlive: () => boolean, ws: WebSocket): NodeJS.Timeout => {
287
+ const keepAlive = (ws: WebSocket): void => {
288
+ let alive = true;
289
+ ws.on("pong", () => { alive = true; });
286
290
  const iv = setInterval(() => {
287
- if (!getAlive()) {
288
- ws.terminate();
289
- return;
290
- }
291
- ws.ping();
292
- }, 30_000);
291
+ if (!alive) return ws.terminate();
292
+ alive = false;
293
+ if (ws.readyState === WebSocket.OPEN) ws.ping();
294
+ }, cfg.heartbeatMs ?? 8_000);
293
295
  iv.unref?.();
294
- return iv;
296
+ ws.once("close", () => clearInterval(iv));
295
297
  };
296
298
 
297
299
  /** Token bucket: returns false when over the rate (the caller closes 1008). */
@@ -330,11 +332,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
330
332
  const helloTimer = setTimeout(() => {
331
333
  if (!done) ws.close(4001, "hello timeout");
332
334
  }, HELLO_TIMEOUT_MS);
333
- const iv = keepAlive(() => conn?.alive ?? true, ws);
334
-
335
- ws.on("pong", () => {
336
- if (conn) conn.alive = true;
337
- });
335
+ keepAlive(ws);
338
336
  ws.on("message", (data, isBinary) => {
339
337
  if (isBinary) return ws.close(1003, "text only");
340
338
  // Size is enforced by `maxPayload` on the server; decode still guards shape.
@@ -356,10 +354,11 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
356
354
  clearTimeout(helloTimer);
357
355
  const old = agentByRoom.get(room.id);
358
356
  if (old) {
357
+ cancelPairs(old.ws, "host", "host reconnected; try Pair again");
359
358
  send(old.ws, { t: "error", code: "superseded", message: "another connection took this room" });
360
359
  old.ws.close(4000, "superseded");
361
360
  }
362
- conn = { ws, room, alive: true };
361
+ conn = { ws, room };
363
362
  agentByRoom.set(room.id, conn);
364
363
  log(`agent ${room.id} (${room.name}) connected`);
365
364
  send(ws, { t: "hello", roomId: room.id, roomName: room.name, devices: deviceViews(room.id), resumed: false });
@@ -377,7 +376,8 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
377
376
  // Host→device ssh.* frames also feed the sshd, which writes them into the
378
377
  // phone's SSH channel; the payload stays opaque to this layer either way.
379
378
  if (isSsh) {
380
- sshd?.onHostFrame(device, payload as Record<string, unknown>);
379
+ if (state.deviceById(device)?.roomId !== room.id) return;
380
+ if (sshd?.onHostFrame(device, payload as Record<string, unknown>)) return;
381
381
  // Ephemeral: raw, unstamped, never buffered (see room streams above).
382
382
  const text = encode({ t: "frame", payload });
383
383
  for (const c of deviceConns) {
@@ -399,10 +399,9 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
399
399
  }
400
400
  case "pair.response": {
401
401
  const requestId = typeof m.requestId === "string" ? m.requestId : null;
402
- const resolve = requestId ? pendingPairs.get(requestId) : null;
403
- if (!requestId || !resolve) return fail(ws, "bad-message", "unknown requestId");
404
- pendingPairs.delete(requestId);
405
- resolve(m.ok === true);
402
+ const pair = requestId ? pendingPairs.get(requestId) : null;
403
+ if (!pair || pair.host !== ws) return fail(ws, "bad-message", "unknown requestId");
404
+ pair.finish(m.ok === true);
406
405
  return;
407
406
  }
408
407
  case "wake": {
@@ -425,7 +424,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
425
424
  });
426
425
  ws.on("close", () => {
427
426
  clearTimeout(helloTimer);
428
- clearInterval(iv);
427
+ cancelPairs(ws, "host", "host disconnected; try Pair again once it is online");
429
428
  if (conn && agentByRoom.get(conn.room.id)?.ws === ws) {
430
429
  agentByRoom.delete(conn.room.id);
431
430
  log(`agent ${conn.room.id} disconnected`);
@@ -448,10 +447,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
448
447
  const helloTimer = setTimeout(() => {
449
448
  if (!done) ws.close(4001, "hello timeout");
450
449
  }, HELLO_TIMEOUT_MS);
451
- const iv = keepAlive(() => conn !== null, ws);
452
- ws.on("pong", () => {
453
- /* conn presence is the liveness marker for bridges */
454
- });
450
+ keepAlive(ws);
455
451
 
456
452
  ws.on("message", (data, isBinary) => {
457
453
  if (isBinary) return ws.close(1003, "text only");
@@ -527,7 +523,6 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
527
523
 
528
524
  ws.on("close", () => {
529
525
  clearTimeout(helloTimer);
530
- clearInterval(iv);
531
526
  for (const sock of sessions.values()) sock.destroy();
532
527
  sessions.clear();
533
528
  if (conn && bridges.has(conn)) {
@@ -556,6 +551,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
556
551
  return;
557
552
  }
558
553
  sshTunnels.set(ip, n + 1);
554
+ keepAlive(ws);
559
555
  const sock = new VirtualSshSocket(ip);
560
556
  let closed = false;
561
557
  const bye = (): void => {
@@ -594,11 +590,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
594
590
  const helloTimer = setTimeout(() => {
595
591
  if (!done) ws.close(4001, "hello timeout");
596
592
  }, HELLO_TIMEOUT_MS);
597
- const iv = keepAlive(() => conn?.alive ?? true, ws);
598
-
599
- ws.on("pong", () => {
600
- if (conn) conn.alive = true;
601
- });
593
+ keepAlive(ws);
602
594
  ws.on("message", (data, isBinary) => {
603
595
  if (isBinary) return ws.close(1003, "text only");
604
596
  // Size is enforced by `maxPayload` on the server; decode still guards shape.
@@ -642,7 +634,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
642
634
  }
643
635
  done = true;
644
636
  clearTimeout(helloTimer);
645
- conn = { ws, account: account!, device, alive: true, viaDeviceSecret };
637
+ conn = { ws, account: account!, device, viaDeviceSecret };
646
638
  deviceConns.add(conn);
647
639
  log(`device ${device ? device.id : "?"} (${account!.name}${viaDeviceSecret ? ", device key" : ""}) connected`);
648
640
  const agents = state.roomsOfAccount(account!.id).map((r) => {
@@ -719,6 +711,8 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
719
711
  case "frame": {
720
712
  const device = conn.device;
721
713
  if (!device) return fail(ws, "not-paired", "pair.begin first");
714
+ const op = (m.payload as { op?: unknown } | null)?.op;
715
+ if (typeof op === "string" && op.startsWith("ssh.")) return fail(ws, "bad-message", "SSH frames require an authenticated SSH channel");
722
716
  const agent = agentByRoom.get(device.roomId);
723
717
  if (!agent) return fail(ws, "host-offline", "the host is not connected");
724
718
  send(agent.ws, { t: "frame", device: device.id, payload: m.payload });
@@ -744,7 +738,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
744
738
  });
745
739
  ws.on("close", () => {
746
740
  clearTimeout(helloTimer);
747
- clearInterval(iv);
741
+ cancelPairs(ws, "owner");
748
742
  if (conn) {
749
743
  deviceConns.delete(conn);
750
744
  if (conn.device) pushRoomUpdate(conn.device.roomId);
@@ -769,17 +763,17 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
769
763
  };
770
764
  if (scope === "read") return finish();
771
765
  const agent = agentByRoom.get(room.id);
772
- if (!agent) return send(conn.ws, { t: "pair.denied", reason: "host offline" });
766
+ if (agent?.ws.readyState !== WebSocket.OPEN) return send(conn.ws, { t: "pair.denied", reason: "host offline" });
773
767
  const requestId = randomId("pr");
774
- const timer = setTimeout(() => {
775
- pendingPairs.delete(requestId);
776
- send(conn.ws, { t: "pair.denied", reason: "host did not answer" });
777
- }, PAIR_ANSWER_MS);
778
- pendingPairs.set(requestId, (ok) => {
768
+ const complete = (ok: boolean, reason = "denied on the host"): void => {
779
769
  clearTimeout(timer);
770
+ pendingPairs.delete(requestId);
771
+ if (conn.ws.readyState !== WebSocket.OPEN) return;
780
772
  if (ok) finish();
781
- else send(conn.ws, { t: "pair.denied", reason: "denied on the host" });
782
- });
773
+ else send(conn.ws, { t: "pair.denied", reason });
774
+ };
775
+ const timer = setTimeout(() => complete(false, "host did not answer"), PAIR_ANSWER_MS);
776
+ pendingPairs.set(requestId, { host: agent.ws, owner: conn.ws, finish: complete });
783
777
  send(agent.ws, { t: "pair.request", requestId, device: { name }, scope });
784
778
  };
785
779
 
@@ -1025,8 +1019,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
1025
1019
  },
1026
1020
  close: () =>
1027
1021
  new Promise<void>((done) => {
1028
- for (const a of agentByRoom.values()) a.ws.close(1001, "server shutdown");
1029
- for (const d of deviceConns) d.ws.close(1001, "server shutdown");
1022
+ for (const ws of wss.clients) ws.terminate();
1030
1023
  void sshd?.close();
1031
1024
  server.close(() => done());
1032
1025
  }),