@bom0792/herdgate 0.9.14 → 0.9.15

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.
package/bin/herdgate.mjs CHANGED
@@ -60,6 +60,14 @@ function setupHost() {
60
60
  const base = join(home, "herdgate");
61
61
  mkdirSync(base, { recursive: true });
62
62
  cpSync(pluginSrc, join(base, "plugin"), { recursive: true });
63
+ // The --via transport for `hc machine add` when the SSH leg's TCP host is
64
+ // unreachable from THIS machine (e.g. IPv4-only network vs an AAAA record):
65
+ // it pipes the system ssh through wss on port 443. One stable path for --via.
66
+ const viaSrc = join(ROOT, "templates", "herdgate-via.mjs");
67
+ if (existsSync(viaSrc)) {
68
+ mkdirSync(join(base, "bin"), { recursive: true });
69
+ cpSync(viaSrc, join(base, "bin", "herdgate-via.mjs"));
70
+ }
63
71
 
64
72
  // Prefill what the panel would otherwise ask for. The publisher is spawned from
65
73
  // <root>/plugin/server/index.mjs — keep root pinned to where we just put it.
@@ -78,12 +86,24 @@ function setupHost() {
78
86
  console.log(`herdgate: installed for herdr-app at ${home}
79
87
  mod → ${join(home, "mods", "herdgate")}
80
88
  publisher → ${join(base, "plugin", "server", "index.mjs")}
89
+ via → ${join(base, "bin", "herdgate-via.mjs")}
81
90
  settings → ${settingsPath} (cloud: ${cloud}, name: ${name})
82
91
 
83
92
  Next: open (or restart) herdr-app → herdgate panel → Pair, then approve the
84
93
  code in the PWA (${cloud}) and click Publish. Requires node >= 22 on PATH
85
94
  for the publisher (node -v).`);
86
95
  if (!arg("no-integrate")) integrate(home);
96
+ // The other direction — THIS machine controlling one that is already paired —
97
+ // needs one command. Print it ready to paste (cmd expands %USERPROFILE%).
98
+ const viaPath = join(base, "bin", "herdgate-via.mjs");
99
+ if (existsSync(viaPath)) {
100
+ console.log(`
101
+ To connect FROM this machine to another machine in the herd (no admin,
102
+ works on IPv4-only networks — ssh over wss/443), first:
103
+ ssh-keygen -t ed25519 -f "%USERPROFILE%\\.ssh\\herdgate" -N "" -q
104
+ and register the printed key in the PWA (machine → Public keys). Then:
105
+ hc machine add <device-id>@herdgate --name home --via "node ${viaPath} --gate ${cloud} --user <device-id>"`);
106
+ }
87
107
  }
88
108
 
89
109
  // ---- first-class panel: clone the main layout + tabs mod, add herdgate to both ----
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.14",
3
+ "version": "0.9.15",
4
4
  "description": "Cloud relay hub for herdr-core: every machine dials out, phones and browsers follow (PWA + SSH leg, E2E payloads).",
5
5
  "type": "module",
6
6
  "engines": {
@@ -34,6 +34,7 @@
34
34
  "app-mod",
35
35
  "plugin",
36
36
  "scripts",
37
- "dist-readme.md"
37
+ "dist-readme.md",
38
+ "templates"
38
39
  ]
39
40
  }
@@ -109,11 +109,12 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
109
109
 
110
110
  /** A virtual SSH client socket: bytes arrive from / leave to a bridged wss frame. */
111
111
  class VirtualSshSocket extends Duplex {
112
- readonly remoteAddress = "bridge"; // the sshd's strike map sees one source — documented
112
+ readonly remoteAddress: string; // the sshd's strike map sees this source — documented
113
113
  readonly remoteFamily = "IPv4";
114
114
  readonly remotePort = 0;
115
- constructor() {
115
+ constructor(addr: string) {
116
116
  super({ allowHalfOpen: false });
117
+ this.remoteAddress = addr;
117
118
  }
118
119
  // ssh2 (isWritable) also reads these — Duplex provides writable/_readableState.
119
120
  _write(chunk: Buffer, _enc: string, cb: (err?: Error | null) => void): void {
@@ -307,7 +308,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
307
308
  };
308
309
  };
309
310
 
310
- const upgrade = (req: IncomingMessage, socket: import("node:stream").Duplex, head: Buffer, leg: "agent" | "device" | "bridge"): void => {
311
+ const upgrade = (req: IncomingMessage, socket: import("node:stream").Duplex, head: Buffer, leg: "agent" | "device" | "bridge" | "ssh-ws"): void => {
311
312
  const ip = ipOf(req);
312
313
  if (blocked(ip)) {
313
314
  socket.write("HTTP/1.1 429 Too Many Requests\r\n\r\n");
@@ -317,6 +318,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
317
318
  wss.handleUpgrade(req, socket, head, (ws) => {
318
319
  if (leg === "agent") attachAgent(ws, ip);
319
320
  else if (leg === "bridge") attachBridge(ws, ip);
321
+ else if (leg === "ssh-ws") attachSshTunnel(ws, ip);
320
322
  else attachDevice(ws, ip);
321
323
  });
322
324
  };
@@ -490,7 +492,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
490
492
  const sid = typeof m.sid === "string" ? m.sid : "";
491
493
  if (!sid || sessions.has(sid)) return fail(ws, "bad-message", "bridge.open.sid");
492
494
  if (!sshd) return fail(ws, "no-ssh", "ssh leg disabled");
493
- const sock = new VirtualSshSocket();
495
+ const sock = new VirtualSshSocket("bridge");
494
496
  sessions.set(sid, sock);
495
497
  sock.on("tobytes", (chunk: Buffer) => send(ws, { t: "bridge.data", sid, b64: chunk.toString("base64") }));
496
498
  sock.on("close", () => {
@@ -535,6 +537,56 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
535
537
  });
536
538
  };
537
539
 
540
+ /**
541
+ * The ssh-ws leg (`/v1/ssh/ws`): one WebSocket = one raw SSH connection, piped
542
+ * into the sshd via `inject`. For clients whose network cannot reach the TCP
543
+ * leg (IPv4-only vs an AAAA-only host) — the tunnel rides port 443 like the
544
+ * web app. No pre-auth: the SSH protocol itself authenticates (device id +
545
+ * publickey/password) and the sshd's strike map keys on the socket's address —
546
+ * which, behind a CDN, is the edge IP; documented, and bounded here.
547
+ */
548
+ const sshTunnels = new Map<string, number>();
549
+ const SSH_TUNNELS_PER_IP = 6;
550
+ const SSH_TUNNELS_TOTAL = 64;
551
+ const attachSshTunnel = (ws: WebSocket, ip: string): void => {
552
+ const n = sshTunnels.get(ip) ?? 0;
553
+ const total = [...sshTunnels.values()].reduce((a, b) => a + b, 0);
554
+ if (!sshd || n >= SSH_TUNNELS_PER_IP || total >= SSH_TUNNELS_TOTAL) {
555
+ ws.close(1013, !sshd ? "ssh leg disabled" : "busy");
556
+ return;
557
+ }
558
+ sshTunnels.set(ip, n + 1);
559
+ const sock = new VirtualSshSocket(ip);
560
+ let closed = false;
561
+ const bye = (): void => {
562
+ if (closed) return;
563
+ closed = true;
564
+ const left = (sshTunnels.get(ip) ?? 1) - 1;
565
+ if (left > 0) sshTunnels.set(ip, left);
566
+ else sshTunnels.delete(ip);
567
+ };
568
+ ws.on("message", (data, isBinary) => {
569
+ if (!isBinary) return ws.close(1003, "binary only");
570
+ if (!sock.push(Buffer.from(data as Buffer))) return; // sshd not reading: leave the buffering to ws
571
+ });
572
+ ws.on("close", () => {
573
+ bye();
574
+ sock.push(null); // EOF: the sshd hangs up cleanly
575
+ sock.destroy();
576
+ });
577
+ ws.on("error", () => { /* onclose follows */ });
578
+ sock.on("tobytes", (chunk: Buffer) => {
579
+ if (ws.readyState === WebSocket.OPEN) ws.send(chunk);
580
+ });
581
+ sock.on("close", () => {
582
+ bye();
583
+ if (ws.readyState === WebSocket.OPEN) {
584
+ try { ws.close(1000); } catch { /* undici: some codes throw */ }
585
+ }
586
+ });
587
+ sshd.inject(sock as unknown as import("node:net").Socket);
588
+ };
589
+
538
590
  const attachDevice = (ws: WebSocket, ip: string): void => {
539
591
  let conn: DeviceConn | null = null;
540
592
  let done = false;
@@ -888,6 +940,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
888
940
  if (path === "/v1/agent/ws") return upgrade(req, socket, head, "agent");
889
941
  if (path === "/v1/device/ws") return upgrade(req, socket, head, "device");
890
942
  if (path === "/v1/bridge/ws") return upgrade(req, socket, head, "bridge");
943
+ if (path === "/v1/ssh/ws") return upgrade(req, socket, head, "ssh-ws");
891
944
  socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
892
945
  socket.destroy();
893
946
  });
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * herdgate-via — the `--via` transport for `hc machine add` when the gate's SSH
4
+ * leg is not TCP-reachable from this machine (IPv4-only network vs an AAAA-only
5
+ * host, locked-down proxy, etc).
6
+ *
7
+ * It wraps the system `ssh` and gives it a ProxyCommand that pipes the raw SSH
8
+ * stream through a WebSocket to the gate (`/v1/ssh/ws`, port 443 — the same
9
+ * road the web app already uses). Every check stays in the gate's sshd: device
10
+ * auth, the read-only allowlist, brute-force strikes. This file carries no
11
+ * secrets and needs no admin rights.
12
+ *
13
+ * Modes:
14
+ * (default) herdgate-via --gate URL --user d_xxx [--key PATH] "remote line…"
15
+ * → spawns ssh over the tunnel; used as herdr's `--via` command
16
+ * (herdr appends the remote line as the last argument).
17
+ * --tunnel herdgate-via --tunnel --gate URL
18
+ * → stdin/stdout ↔ the WebSocket (a ProxyCommand body itself).
19
+ * --probe herdgate-via --probe --gate URL
20
+ * → opens the tunnel and prints the first SSH banner bytes (a
21
+ * one-shot connectivity check).
22
+ *
23
+ * Zero dependencies; Node ≥ 22 (global WebSocket). Standalone: ships alone.
24
+ */
25
+
26
+ import { spawn, spawnSync } from "node:child_process";
27
+ import { existsSync, readFileSync } from "node:fs";
28
+ import { homedir } from "node:os";
29
+ import { join } from "node:path";
30
+ import { fileURLToPath } from "node:url";
31
+
32
+ const argv = process.argv.slice(2);
33
+ const flag = (name) => {
34
+ const i = argv.indexOf(name);
35
+ return i >= 0 && i + 1 < argv.length ? argv[i + 1] : null;
36
+ };
37
+ const GATE = (flag("--gate") ?? process.env.HERDGATE_URL ?? "https://gate.phuongnb.io.vn").replace(/\/$/, "");
38
+ const wsUrl = GATE.replace(/^http/, "ws") + "/v1/ssh/ws";
39
+ const MODE = argv.includes("--tunnel") ? "tunnel" : argv.includes("--probe") ? "probe" : "via";
40
+
41
+ const die = (msg) => {
42
+ console.error(`herdgate-via: ${msg}`);
43
+ process.exit(2);
44
+ };
45
+
46
+ const toBuf = (data) => {
47
+ if (Buffer.isBuffer(data)) return data;
48
+ if (data instanceof ArrayBuffer) return Buffer.from(data);
49
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
50
+ return Buffer.from(String(data), "utf8");
51
+ };
52
+
53
+ /** stdin/stdout ↔ the gate's SSH-over-WebSocket leg. */
54
+ function tunnel() {
55
+ let ws;
56
+ try {
57
+ ws = new WebSocket(wsUrl);
58
+ ws.binaryType = "arraybuffer"; // undici hands binary frames as Blob otherwise — SSH bytes would garble
59
+ } catch (e) {
60
+ die(`cannot build ${wsUrl}: ${e?.message ?? e}`);
61
+ }
62
+ const pump = () => process.stdin.on("data", (d) => {
63
+ if (ws.readyState === WebSocket.OPEN) ws.send(d);
64
+ });
65
+ ws.onopen = () => pump();
66
+ ws.onmessage = (ev) => process.stdout.write(toBuf(ev.data));
67
+ ws.onclose = () => process.exit(0);
68
+ ws.onerror = () => {
69
+ // Undici quirk: a failure while CONNECTING never fires `close` — ssh would
70
+ // sit on a dead pipe forever. Exit on our own; if close does follow, it is a no-op.
71
+ console.error(`herdgate-via: tunnel to ${wsUrl} failed`);
72
+ process.exit(2);
73
+ };
74
+ process.stdin.on("end", () => {
75
+ // Half-close: tell the sshd we are done writing; it closes the rest.
76
+ try { ws.close(1000); } catch { process.exit(0); }
77
+ });
78
+ process.stdin.on("error", () => { /* ssh went away; onclose ends us */ });
79
+ }
80
+
81
+ if (MODE === "tunnel") tunnel();
82
+ else if (MODE === "probe") {
83
+ const ws = new WebSocket(wsUrl);
84
+ ws.binaryType = "arraybuffer";
85
+ const t = setTimeout(() => die(`no SSH banner from ${GATE} in 8s — is the gate up?`), 8_000);
86
+ ws.onmessage = (ev) => {
87
+ clearTimeout(t);
88
+ const s = toBuf(ev.data).toString("latin1");
89
+ console.log(s.startsWith("SSH-") ? `ok: ${GATE} speaks ${s.slice(0, s.indexOf("\n") >= 0 ? s.indexOf("\n") : s.length).trim()}` : `connected, but first bytes are not an SSH banner: ${JSON.stringify(s.slice(0, 32))}`);
90
+ try { ws.close(1000); } catch { /* fine */ }
91
+ setTimeout(() => process.exit(0), 250);
92
+ };
93
+ ws.onerror = () => { clearTimeout(t); die(`cannot reach ${wsUrl}`); };
94
+ ws.onclose = () => { /* covered by the timeout */ };
95
+ } else {
96
+ // ---- via: wrap system ssh around the tunnel -------------------------------
97
+ const line = argv[argv.length - 1];
98
+ const user = flag("--user");
99
+ if (!user || !line || line.startsWith("--")) {
100
+ die("usage: herdgate-via --gate URL --user d_xxx [--key PATH] \"remote line\" (herdr passes the line)");
101
+ }
102
+ const keyArg = flag("--key") ?? [join(homedir(), ".ssh", "herdgate"), join(homedir(), ".ssh", "id_ed25519")]
103
+ .find((p) => existsSync(p)) ?? null;
104
+ const self = fileURLToPath(import.meta.url);
105
+ const known = flag("--known-hosts");
106
+ // OpenSSH runs ProxyCommand as a command line: keep it free of quotes and
107
+ // shell metacharacters (paths without spaces, no redirections).
108
+ const proxy = `node ${self} --tunnel --gate ${GATE}`;
109
+ const args = [
110
+ "-o", `ProxyCommand=${proxy}`,
111
+ "-o", "StrictHostKeyChecking=accept-new", // first connect learns the host key, later ones pin it
112
+ ...(known ? ["-o", `UserKnownHostsFile=${known}`] : []),
113
+ "-o", "IdentitiesOnly=yes",
114
+ ...(keyArg ? ["-o", `IdentityFile=${keyArg}`] : []),
115
+ "-o", "BatchMode=yes", // the app's world: no prompts, ever
116
+ "-o", "ServerAliveInterval=15",
117
+ "-o", "ConnectTimeout=15",
118
+ "-p", "22",
119
+ `${user}@herdgate`,
120
+ "--",
121
+ line,
122
+ ];
123
+ // Windows has OpenSSH's ssh.exe on PATH next to node; Unix just `ssh`.
124
+ const sshBin = process.platform === "win32" ? "ssh" : "ssh";
125
+ const check = spawnSync(sshBin, ["-V"], { stdio: "ignore", shell: process.platform === "win32" });
126
+ if (check.error) die(`system ssh not found — OpenSSH client must be on PATH (${check.error.message})`);
127
+ const p = spawn(sshBin, args, { stdio: "inherit" });
128
+ p.on("error", (e) => die(`cannot start ssh: ${e.message}`));
129
+ p.on("exit", (c) => process.exit(c ?? 0));
130
+ process.on("SIGINT", () => p.kill("SIGINT"));
131
+ process.on("SIGTERM", () => p.kill("SIGTERM"));
132
+ }
133
+
134
+ export {};