@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,119 @@
1
+ // Public TCP edge for native SSH clients. One connection = one SSH-over-WSS
2
+ // tunnel to the gate. No credentials, SSH termination, or room selection here.
3
+ import { createServer, type Socket } from "node:net";
4
+ import { pathToFileURL } from "node:url";
5
+ import { WebSocket } from "ws";
6
+
7
+ interface EdgeOptions {
8
+ gate: string;
9
+ host?: string;
10
+ port?: number;
11
+ perIp?: number;
12
+ total?: number;
13
+ }
14
+
15
+ function integer(label: string, value: number, min: number, max: number): number {
16
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(`${label} must be an integer in ${min}..${max}`);
17
+ return value;
18
+ }
19
+
20
+ export async function startTcpEdge(options: EdgeOptions) {
21
+ const host = options.host ?? "127.0.0.1";
22
+ const gate = new URL(options.gate);
23
+ const localTest = gate.protocol === "http:" && gate.hostname === "127.0.0.1" && host === "127.0.0.1";
24
+ if ((!localTest && gate.protocol !== "https:") || gate.username || gate.password || gate.pathname !== "/" || gate.search || gate.hash) {
25
+ throw new Error("HERDGATE_URL must be a credential-free HTTPS origin");
26
+ }
27
+ const url = new URL("/v1/ssh/ws", gate);
28
+ url.protocol = localTest ? "ws:" : "wss:";
29
+ const port = integer("port", options.port ?? 2299, 0, 65_535);
30
+ const total = integer("total", options.total ?? 6, 1, 6); // the gate limits tunnels per source
31
+ const perIp = integer("per-IP", options.perIp ?? Math.min(3, total), 1, total);
32
+ const byIp = new Map<string, number>();
33
+ const clients = new Set<Socket>();
34
+ const maxBuffered = 512 * 1024;
35
+
36
+ const server = createServer({ pauseOnConnect: true }, (sock) => {
37
+ const ip = sock.remoteAddress;
38
+ if (!ip || clients.size >= total || (byIp.get(ip) ?? 0) >= perIp) return sock.destroy();
39
+ byIp.set(ip, (byIp.get(ip) ?? 0) + 1);
40
+ clients.add(sock);
41
+ sock.setNoDelay(true);
42
+ sock.setKeepAlive(true, 15_000);
43
+
44
+ const ws = new WebSocket(url, { handshakeTimeout: 8_000, maxPayload: 256 * 1024, perMessageDeflate: false });
45
+ let alive = true;
46
+ const heartbeat = setInterval(() => {
47
+ if (ws.readyState !== WebSocket.OPEN) return;
48
+ if (!alive) return sock.destroy();
49
+ alive = false;
50
+ ws.ping();
51
+ }, 12_000);
52
+ heartbeat.unref();
53
+ ws.on("pong", () => { alive = true; });
54
+ ws.on("error", () => sock.destroy());
55
+ ws.on("close", () => {
56
+ if (sock.destroyed) return;
57
+ // Flush any final SSH bytes, but never let a peer that stopped reading
58
+ // keep a public connection slot after the upstream has gone away.
59
+ const deadline = setTimeout(() => sock.destroy(), 2_000).unref();
60
+ sock.once("close", () => clearTimeout(deadline));
61
+ sock.end(() => sock.destroy());
62
+ });
63
+ ws.on("open", () => sock.resume());
64
+ ws.on("message", (data, binary) => {
65
+ if (sock.destroyed || !sock.writable) return;
66
+ if (!binary || !Buffer.isBuffer(data) || sock.writableLength + data.length > maxBuffered) return sock.destroy();
67
+ if (!sock.write(data)) ws.pause();
68
+ });
69
+ sock.on("drain", () => { if (ws.readyState === WebSocket.OPEN) ws.resume(); });
70
+ sock.on("error", () => sock.destroy());
71
+ sock.on("data", (data) => {
72
+ if (ws.readyState !== WebSocket.OPEN) return;
73
+ sock.pause();
74
+ ws.send(data, { binary: true }, (err) => { if (err) sock.destroy(); else sock.resume(); });
75
+ });
76
+ sock.once("close", () => {
77
+ clearInterval(heartbeat);
78
+ clients.delete(sock);
79
+ const left = (byIp.get(ip) ?? 1) - 1;
80
+ if (left) byIp.set(ip, left);
81
+ else byIp.delete(ip);
82
+ ws.terminate();
83
+ });
84
+ });
85
+
86
+ await new Promise<void>((resolve, reject) => {
87
+ server.once("error", reject);
88
+ server.listen(port, host, () => {
89
+ server.removeListener("error", reject);
90
+ resolve();
91
+ });
92
+ });
93
+ const addr = server.address();
94
+ if (!addr || typeof addr === "string") throw new Error("no TCP listener");
95
+ return {
96
+ port: addr.port,
97
+ close: () => new Promise<void>((resolve) => {
98
+ for (const sock of clients) sock.destroy();
99
+ server.close(() => resolve());
100
+ }),
101
+ };
102
+ }
103
+
104
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
105
+ try {
106
+ const env = process.env;
107
+ if (!env.HERDGATE_URL) throw new Error("set HERDGATE_URL to the public HTTPS gate origin");
108
+ const opt = (name: string) => env[name] === undefined ? undefined : Number(env[name]);
109
+ const host = env.HERDGATE_TCP_EDGE_BIND ?? "127.0.0.1";
110
+ const edge = await startTcpEdge({ gate: env.HERDGATE_URL, host, port: opt("HERDGATE_TCP_EDGE_PORT"), perIp: opt("HERDGATE_TCP_EDGE_PER_IP"), total: opt("HERDGATE_TCP_EDGE_TOTAL") });
111
+ console.error(`herdgate-tcp-edge: listening on ${host}:${edge.port}`);
112
+ const stop = () => { void edge.close(); };
113
+ process.once("SIGTERM", stop);
114
+ process.once("SIGINT", stop);
115
+ } catch (err) {
116
+ console.error(`herdgate-tcp-edge: ${err instanceof Error ? err.message : String(err)}`);
117
+ process.exitCode = 1;
118
+ }
119
+ }
package/src/cloud/sshd.ts CHANGED
@@ -133,13 +133,14 @@ export interface SshHandle {
133
133
  inject(socket: import("node:stream").Duplex & { remoteAddress?: string }): void;
134
134
  close(): Promise<void>;
135
135
  /** Gateway calls this when a HOST sends an `ssh.*` frame to a device. */
136
- onHostFrame(deviceId: string, payload: Record<string, unknown>): void;
136
+ onHostFrame(deviceId: string, payload: Record<string, unknown>): boolean;
137
137
  }
138
138
 
139
139
  interface ChannelStream {
140
140
  write(chunk: Buffer): boolean;
141
141
  end(chunk?: Buffer): void;
142
142
  exit(code: number): void;
143
+ stderr: { write(chunk: Buffer): boolean };
143
144
  }
144
145
 
145
146
  interface Channel {
@@ -193,6 +194,10 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
193
194
  let dev: DeviceRecord | null = null; // narrowed alias for the closures below
194
195
  client.on("authentication", (ctx) => {
195
196
  if (blocked(ip)) return ctx.reject();
197
+ // The initial `none` request discovers supported methods. An empty list
198
+ // can make clients stop before offering a key. Keep the list independent
199
+ // of whether this username is registered.
200
+ const reject = () => ctx.reject(["publickey", "password"]);
196
201
  const id = ctx.username.trim();
197
202
  const rec = /^d_[A-Za-z0-9]+$/.test(id) ? deps.state.deviceById(id) : null;
198
203
  if (ctx.method === "publickey") {
@@ -203,15 +208,15 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
203
208
  // asking "would you take this key?" — accepting answers PK_OK (ssh2 does that).
204
209
  const pk = ctx as unknown as { key?: { algo: string; data: Buffer }; signature?: Buffer; blob?: Buffer; hashAlgo?: string };
205
210
  const key = pk.key;
206
- if (!rec || !key?.data) return ctx.reject();
211
+ if (!rec || !key?.data) return reject();
207
212
  const entry = rec.sshKeys?.find((k) => k.algo === key.algo && Buffer.from(k.b64, "base64").equals(key.data));
208
- if (!entry) return ctx.reject(); // agent key not for us: no strike, just no
213
+ if (!entry) return reject(); // agent key not for us: no strike, just no
209
214
  if (!pk.signature) return ctx.accept();
210
215
  const keyObj = sshPubKeyToKeyObject(key.algo, key.data);
211
216
  if (!keyObj || !cryptoVerify(pk.hashAlgo ?? undefined, pk.blob ?? Buffer.alloc(0), keyObj, pk.signature)) {
212
217
  strike(ip);
213
218
  deps.log(`ssh: bad key signature for ${rec.id} from ${ip}`);
214
- return ctx.reject();
219
+ return reject();
215
220
  }
216
221
  device = rec;
217
222
  dev = rec;
@@ -220,13 +225,13 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
220
225
  }
221
226
  if (ctx.method !== "password") {
222
227
  // Per-device passwords (and registered public keys) are the only ways in.
223
- return ctx.reject();
228
+ return reject();
224
229
  }
225
230
  const ok = rec ? deps.state.deviceByCredentials(id, ctx.password ?? "") : null;
226
231
  if (!ok) {
227
232
  strike(ip);
228
233
  deps.log(`ssh: auth failed for "${id.slice(0, 12)}" from ${ip}`);
229
- return ctx.reject();
234
+ return reject();
230
235
  }
231
236
  device = ok;
232
237
  dev = ok;
@@ -234,6 +239,14 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
234
239
  ctx.accept();
235
240
  });
236
241
 
242
+ const owned = new Map<string, Channel>();
243
+ const closeChannel = (channel: Channel) => {
244
+ const { deviceId, ch } = channel;
245
+ owned.delete(ch);
246
+ if (!channels.delete(channelKey(deviceId, ch))) return;
247
+ toHost(deviceId, { op: "ssh.close", ch });
248
+ };
249
+
237
250
  client.on("ready", () => {
238
251
  client.on("session", (accept, reject) => {
239
252
  const session = accept();
@@ -258,12 +271,13 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
258
271
  const stream = acceptExec();
259
272
  const channel: Channel = { deviceId: dvc.id, ch, stream, closing: false };
260
273
  channels.set(channelKey(dvc.id, ch), channel);
274
+ owned.set(ch, channel);
261
275
 
262
276
  // Ask the host to run it. The command travels inside the opaque payload; the
263
277
  // host's bridge decides whether to run it and answers ssh.granted / ssh.denied.
264
278
  const opened = toHost(dvc.id, { op: "ssh.open", ch, cmd: String(info.command ?? "") });
265
279
  if (!opened) {
266
- channels.delete(channelKey(dvc.id, ch));
280
+ closeChannel(channel);
267
281
  stream.exit(111);
268
282
  stream.end(Buffer.from("herdgate: the host is not connected\r\n"));
269
283
  return;
@@ -273,10 +287,12 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
273
287
  if (channel.closing) return;
274
288
  toHost(dvc.id, { op: "ssh.data", ch, b64: buf.toString("base64") });
275
289
  });
276
- stream.on("close", () => {
277
- channels.delete(channelKey(dvc.id, ch));
278
- toHost(dvc.id, { op: "ssh.close", ch });
290
+ stream.on("end", () => {
291
+ // The client closed its stdin (an exec script is complete): tell the
292
+ // host, so script channels can match and spawned processes see EOF.
293
+ if (!channel.closing) toHost(dvc.id, { op: "ssh.eof", ch });
279
294
  });
295
+ stream.on("close", () => closeChannel(channel));
280
296
  stream.stderr?.on?.("data", () => {
281
297
  /* stderr is merged by the phone side in exec mode; drop duplicates */
282
298
  });
@@ -285,14 +301,8 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
285
301
  });
286
302
 
287
303
  client.on("close", () => {
288
- const dvc = dev;
289
- if (dvc) {
290
- for (const c of deviceChannels(dvc.id)) {
291
- channels.delete(channelKey(c.deviceId, c.ch));
292
- toHost(dvc.id, { op: "ssh.close", ch: c.ch });
293
- }
294
- if (deviceChannels(dvc.id).length === 0) deps.log(`ssh: device ${dvc.id} disconnected`);
295
- }
304
+ for (const c of owned.values()) closeChannel(c);
305
+ if (dev && deviceChannels(dev.id).length === 0) deps.log(`ssh: device ${dev.id} disconnected`);
296
306
  });
297
307
  });
298
308
 
@@ -319,12 +329,9 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
319
329
  const op = typeof payload.op === "string" ? payload.op : "";
320
330
  const ch = typeof payload.ch === "string" ? payload.ch : "";
321
331
  const channel = channels.get(channelKey(deviceId, ch));
322
- if (!channel) return;
332
+ if (!channel) return false;
323
333
 
324
- if (op === "ssh.granted") {
325
- channel.closing = false;
326
- return;
327
- }
334
+ if (op === "ssh.granted") return true;
328
335
  if (op === "ssh.denied") {
329
336
  // The host refused (scope, command, no hc): close the channel honestly.
330
337
  const reason = typeof payload.reason === "string" ? payload.reason : "refused by the host";
@@ -333,18 +340,19 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
333
340
  channel.stream?.exit(111);
334
341
  channel.stream?.end();
335
342
  channels.delete(channelKey(deviceId, ch));
336
- return;
343
+ return true;
337
344
  }
338
345
  if (op === "ssh.data") {
339
346
  const b64 = typeof payload.b64 === "string" ? payload.b64 : "";
340
- if (b64.length > 400_000) return; // over the frame budget; the rate limiter catches floods
347
+ if (b64.length > 400_000) return true; // over the frame budget
341
348
  const buf = Buffer.from(b64, "base64");
342
349
  try {
343
- channel.stream?.write(buf);
350
+ if (payload.stderr === true) channel.stream?.stderr.write(buf);
351
+ else channel.stream?.write(buf);
344
352
  } catch {
345
353
  /* the phone vanished mid-write; close carries it */
346
354
  }
347
- return;
355
+ return true;
348
356
  }
349
357
  if (op === "ssh.closed") {
350
358
  channel.closing = true;
@@ -354,8 +362,8 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
354
362
  channel.stream?.exit(code);
355
363
  channel.stream?.end();
356
364
  channels.delete(channelKey(deviceId, ch));
357
- return;
358
365
  }
366
+ return true;
359
367
  },
360
368
  async close() {
361
369
  for (const c of channels.values()) {
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // Keep the Linux standalone entry point; the adapter is also in the Windows bundle.
3
+ import "../../plugin/server/mobile-tui-core.mjs";
@@ -0,0 +1,72 @@
1
+ // Standalone Mobile -> TUI publisher. Use a dedicated room for each mode.
2
+ import { existsSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { HerdGateAgent } from "../agent/index.ts";
5
+ import { createSshBridge, translateBootstrap } from "./ssh.ts";
6
+
7
+ const url = new URL(process.env.HERDGATE_URL ?? "https://gate.phuongnb.io.vn");
8
+ if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
9
+ throw new Error("HERDGATE_URL must be an HTTPS origin");
10
+ }
11
+ const token = process.env.HERDGATE_ROOM_TOKEN;
12
+ if (!token) throw new Error("configure a dedicated room token for the TUI mobile pilot");
13
+ const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
14
+ const controller = process.env.HERDGATE_MOBILE_TUI_ACT_DEVICE;
15
+ if (controller !== undefined && !/^d_[A-Za-z0-9]{1,32}$/.test(controller)) throw new Error("invalid Mobile TUI act device ID");
16
+ const allows = (device: string, scope: "read" | "act" | null) =>
17
+ controller ? device === controller && scope === "act" : scope === "read";
18
+ const core = fileURLToPath(new URL("./mobile-tui-core.mjs", import.meta.url));
19
+ if (!existsSync(core)) throw new Error("missing TUI Core adapter");
20
+ const log = (line: string) => console.error(`herdgate-mobile-tui: ${line}`);
21
+ const coreCommands = new Set(["connect", "connect --json", "--version", "-V", "server status", "server status --json"]);
22
+ const bridge = createSshBridge({
23
+ send: (device, payload) => agent.send(device, payload),
24
+ resolveHc: () => core,
25
+ trustedReadCore: core,
26
+ tuiOnly: Boolean(controller),
27
+ mobileTuiAdapter: controller ? { device: controller, scope: "act", script: core } : null,
28
+ resolveHerdrBin: () => null,
29
+ scopeOf: (device) => {
30
+ const scope = agent.scopeOf(device);
31
+ return allows(device, scope) ? scope : null;
32
+ },
33
+ log,
34
+ });
35
+
36
+ const agent = new HerdGateAgent({
37
+ endpoint: `wss://${url.host}/v1/agent/ws`, roomToken: token, log,
38
+ adapter: {
39
+ info: () => ({ name, version: "tui-core-pilot", capabilities: [controller ? "interactive" : "read-only"] }),
40
+ onPairAsk: () => false,
41
+ onDevices: (devices) => {
42
+ const next = new Set(devices.filter((d) => allows(d.id, d.scope)).map((d) => d.id));
43
+ for (const id of allowedDevices) if (!next.has(id)) bridge.dropDevice(id);
44
+ allowedDevices = next;
45
+ },
46
+ onFrame(device, payload) {
47
+ if (!payload || typeof payload !== "object" || !("op" in payload) || typeof payload.op !== "string" || !payload.op.startsWith("ssh.")) return;
48
+ const p = payload as Record<string, unknown>;
49
+ if (controller || p.op !== "ssh.open") { bridge.handle(device, p); return; }
50
+ const cmd = typeof p.cmd === "string" ? p.cmd.trim() : "";
51
+ if (cmd === "exit" || cmd === "exit 0") { bridge.handle(device, { ...p, cmd }); return; }
52
+ const direct = cmd.match(/^(?:hc|herdr-core)[ \t]+(.+)$/)?.[1];
53
+ const translated = !direct && cmd.includes("herdr-core") ? translateBootstrap(cmd)?.slice(3) : undefined;
54
+ const args = direct || translated || "";
55
+ if (coreCommands.has(args)) bridge.handle(device, { ...p, cmd: `hc ${args}` });
56
+ else {
57
+ log(`unsupported SSH command from ${device} (${cmd.length} bytes)`);
58
+ agent.send(device, { op: "ssh.denied", ch: p.ch, reason: "unsupported command on read-only Herdr TUI pilot" });
59
+ }
60
+ },
61
+ },
62
+ });
63
+ let allowedDevices = new Set<string>();
64
+ // Do not let a scoped child command inherit any room or account credential.
65
+ delete process.env.HERDGATE_ROOM_TOKEN;
66
+ delete process.env.HERDGATE_ACCOUNT_TOKEN;
67
+ delete process.env.HERDGATE_BRIDGE_TOKEN;
68
+ const stop = () => { bridge.closeAll(); agent.stop(); };
69
+ process.once("SIGINT", stop);
70
+ process.once("SIGTERM", stop);
71
+ agent.start();
72
+ await agent.firstHello.catch(() => {});