@bom0792/herdgate 0.9.21 → 0.9.27
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/README.md +97 -3
- package/bin/cloud-config.mjs +65 -0
- package/bin/herdgate.mjs +108 -22
- package/bin/home-tui.mjs +154 -0
- package/dist-readme.md +2 -2
- package/package.json +3 -1
- package/plugin/server/index.mjs +7 -0
- package/plugin/server/mobile-tui-core.mjs +321 -0
- package/plugin/server/mobile-tui-stream.mjs +61 -0
- package/plugin/server/publish-tui.mjs +29 -5
- package/plugin/server/ssh.d.mts +3 -0
- package/plugin/server/ssh.mjs +50 -7
- package/scripts/deploy-vps.sh +10 -5
- package/src/cloud/gateway.ts +35 -45
- package/src/cloud/ssh-tcp-edge.ts +119 -0
- package/src/cloud/sshd.ts +9 -5
- package/src/host/mobile-tui-core.mjs +3 -0
- package/src/host/mobile-tui.ts +73 -0
- package/src/web/app.css +2 -0
- package/src/web/app.js +365 -183
- package/src/web/index.html +1 -0
- package/src/web/sw.js +1 -1
- package/templates/herdgate-tcp-edge.service +20 -0
- package/templates/herdgate-via.mjs +12 -2
- package/windows/cli.mjs +24 -7
- package/windows/install-cli.mjs +18 -7
- package/windows/npm-update.mjs +26 -0
- package/windows/setup-tui.mjs +115 -0
package/src/cloud/gateway.ts
CHANGED
|
@@ -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 {
|
|
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>();
|
|
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 = (
|
|
287
|
+
const keepAlive = (ws: WebSocket): void => {
|
|
288
|
+
let alive = true;
|
|
289
|
+
ws.on("pong", () => { alive = true; });
|
|
286
290
|
const iv = setInterval(() => {
|
|
287
|
-
if (!
|
|
288
|
-
|
|
289
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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 });
|
|
@@ -400,10 +399,9 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
400
399
|
}
|
|
401
400
|
case "pair.response": {
|
|
402
401
|
const requestId = typeof m.requestId === "string" ? m.requestId : null;
|
|
403
|
-
const
|
|
404
|
-
if (!
|
|
405
|
-
|
|
406
|
-
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);
|
|
407
405
|
return;
|
|
408
406
|
}
|
|
409
407
|
case "wake": {
|
|
@@ -426,7 +424,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
426
424
|
});
|
|
427
425
|
ws.on("close", () => {
|
|
428
426
|
clearTimeout(helloTimer);
|
|
429
|
-
|
|
427
|
+
cancelPairs(ws, "host", "host disconnected; try Pair again once it is online");
|
|
430
428
|
if (conn && agentByRoom.get(conn.room.id)?.ws === ws) {
|
|
431
429
|
agentByRoom.delete(conn.room.id);
|
|
432
430
|
log(`agent ${conn.room.id} disconnected`);
|
|
@@ -449,10 +447,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
449
447
|
const helloTimer = setTimeout(() => {
|
|
450
448
|
if (!done) ws.close(4001, "hello timeout");
|
|
451
449
|
}, HELLO_TIMEOUT_MS);
|
|
452
|
-
|
|
453
|
-
ws.on("pong", () => {
|
|
454
|
-
/* conn presence is the liveness marker for bridges */
|
|
455
|
-
});
|
|
450
|
+
keepAlive(ws);
|
|
456
451
|
|
|
457
452
|
ws.on("message", (data, isBinary) => {
|
|
458
453
|
if (isBinary) return ws.close(1003, "text only");
|
|
@@ -528,7 +523,6 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
528
523
|
|
|
529
524
|
ws.on("close", () => {
|
|
530
525
|
clearTimeout(helloTimer);
|
|
531
|
-
clearInterval(iv);
|
|
532
526
|
for (const sock of sessions.values()) sock.destroy();
|
|
533
527
|
sessions.clear();
|
|
534
528
|
if (conn && bridges.has(conn)) {
|
|
@@ -557,6 +551,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
557
551
|
return;
|
|
558
552
|
}
|
|
559
553
|
sshTunnels.set(ip, n + 1);
|
|
554
|
+
keepAlive(ws);
|
|
560
555
|
const sock = new VirtualSshSocket(ip);
|
|
561
556
|
let closed = false;
|
|
562
557
|
const bye = (): void => {
|
|
@@ -595,11 +590,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
595
590
|
const helloTimer = setTimeout(() => {
|
|
596
591
|
if (!done) ws.close(4001, "hello timeout");
|
|
597
592
|
}, HELLO_TIMEOUT_MS);
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
ws.on("pong", () => {
|
|
601
|
-
if (conn) conn.alive = true;
|
|
602
|
-
});
|
|
593
|
+
keepAlive(ws);
|
|
603
594
|
ws.on("message", (data, isBinary) => {
|
|
604
595
|
if (isBinary) return ws.close(1003, "text only");
|
|
605
596
|
// Size is enforced by `maxPayload` on the server; decode still guards shape.
|
|
@@ -643,7 +634,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
643
634
|
}
|
|
644
635
|
done = true;
|
|
645
636
|
clearTimeout(helloTimer);
|
|
646
|
-
conn = { ws, account: account!, device,
|
|
637
|
+
conn = { ws, account: account!, device, viaDeviceSecret };
|
|
647
638
|
deviceConns.add(conn);
|
|
648
639
|
log(`device ${device ? device.id : "?"} (${account!.name}${viaDeviceSecret ? ", device key" : ""}) connected`);
|
|
649
640
|
const agents = state.roomsOfAccount(account!.id).map((r) => {
|
|
@@ -747,7 +738,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
747
738
|
});
|
|
748
739
|
ws.on("close", () => {
|
|
749
740
|
clearTimeout(helloTimer);
|
|
750
|
-
|
|
741
|
+
cancelPairs(ws, "owner");
|
|
751
742
|
if (conn) {
|
|
752
743
|
deviceConns.delete(conn);
|
|
753
744
|
if (conn.device) pushRoomUpdate(conn.device.roomId);
|
|
@@ -772,17 +763,17 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
772
763
|
};
|
|
773
764
|
if (scope === "read") return finish();
|
|
774
765
|
const agent = agentByRoom.get(room.id);
|
|
775
|
-
if (
|
|
766
|
+
if (agent?.ws.readyState !== WebSocket.OPEN) return send(conn.ws, { t: "pair.denied", reason: "host offline" });
|
|
776
767
|
const requestId = randomId("pr");
|
|
777
|
-
const
|
|
778
|
-
pendingPairs.delete(requestId);
|
|
779
|
-
send(conn.ws, { t: "pair.denied", reason: "host did not answer" });
|
|
780
|
-
}, PAIR_ANSWER_MS);
|
|
781
|
-
pendingPairs.set(requestId, (ok) => {
|
|
768
|
+
const complete = (ok: boolean, reason = "denied on the host"): void => {
|
|
782
769
|
clearTimeout(timer);
|
|
770
|
+
pendingPairs.delete(requestId);
|
|
771
|
+
if (conn.ws.readyState !== WebSocket.OPEN) return;
|
|
783
772
|
if (ok) finish();
|
|
784
|
-
else send(conn.ws, { t: "pair.denied", reason
|
|
785
|
-
}
|
|
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 });
|
|
786
777
|
send(agent.ws, { t: "pair.request", requestId, device: { name }, scope });
|
|
787
778
|
};
|
|
788
779
|
|
|
@@ -1028,8 +1019,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
1028
1019
|
},
|
|
1029
1020
|
close: () =>
|
|
1030
1021
|
new Promise<void>((done) => {
|
|
1031
|
-
for (const
|
|
1032
|
-
for (const d of deviceConns) d.ws.close(1001, "server shutdown");
|
|
1022
|
+
for (const ws of wss.clients) ws.terminate();
|
|
1033
1023
|
void sshd?.close();
|
|
1034
1024
|
server.close(() => done());
|
|
1035
1025
|
}),
|
|
@@ -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
|
@@ -194,6 +194,10 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
194
194
|
let dev: DeviceRecord | null = null; // narrowed alias for the closures below
|
|
195
195
|
client.on("authentication", (ctx) => {
|
|
196
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"]);
|
|
197
201
|
const id = ctx.username.trim();
|
|
198
202
|
const rec = /^d_[A-Za-z0-9]+$/.test(id) ? deps.state.deviceById(id) : null;
|
|
199
203
|
if (ctx.method === "publickey") {
|
|
@@ -204,15 +208,15 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
204
208
|
// asking "would you take this key?" — accepting answers PK_OK (ssh2 does that).
|
|
205
209
|
const pk = ctx as unknown as { key?: { algo: string; data: Buffer }; signature?: Buffer; blob?: Buffer; hashAlgo?: string };
|
|
206
210
|
const key = pk.key;
|
|
207
|
-
if (!rec || !key?.data) return
|
|
211
|
+
if (!rec || !key?.data) return reject();
|
|
208
212
|
const entry = rec.sshKeys?.find((k) => k.algo === key.algo && Buffer.from(k.b64, "base64").equals(key.data));
|
|
209
|
-
if (!entry) return
|
|
213
|
+
if (!entry) return reject(); // agent key not for us: no strike, just no
|
|
210
214
|
if (!pk.signature) return ctx.accept();
|
|
211
215
|
const keyObj = sshPubKeyToKeyObject(key.algo, key.data);
|
|
212
216
|
if (!keyObj || !cryptoVerify(pk.hashAlgo ?? undefined, pk.blob ?? Buffer.alloc(0), keyObj, pk.signature)) {
|
|
213
217
|
strike(ip);
|
|
214
218
|
deps.log(`ssh: bad key signature for ${rec.id} from ${ip}`);
|
|
215
|
-
return
|
|
219
|
+
return reject();
|
|
216
220
|
}
|
|
217
221
|
device = rec;
|
|
218
222
|
dev = rec;
|
|
@@ -221,13 +225,13 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
|
|
|
221
225
|
}
|
|
222
226
|
if (ctx.method !== "password") {
|
|
223
227
|
// Per-device passwords (and registered public keys) are the only ways in.
|
|
224
|
-
return
|
|
228
|
+
return reject();
|
|
225
229
|
}
|
|
226
230
|
const ok = rec ? deps.state.deviceByCredentials(id, ctx.password ?? "") : null;
|
|
227
231
|
if (!ok) {
|
|
228
232
|
strike(ip);
|
|
229
233
|
deps.log(`ssh: auth failed for "${id.slice(0, 12)}" from ${ip}`);
|
|
230
|
-
return
|
|
234
|
+
return reject();
|
|
231
235
|
}
|
|
232
236
|
device = ok;
|
|
233
237
|
dev = ok;
|
|
@@ -0,0 +1,73 @@
|
|
|
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
|
+
if (!process.env.HERDGATE_URL) throw new Error("configure HERDGATE_URL for this mobile publisher");
|
|
8
|
+
const url = new URL(process.env.HERDGATE_URL);
|
|
9
|
+
if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
10
|
+
throw new Error("HERDGATE_URL must be an HTTPS origin");
|
|
11
|
+
}
|
|
12
|
+
const token = process.env.HERDGATE_ROOM_TOKEN;
|
|
13
|
+
if (!token) throw new Error("configure a dedicated room token for the TUI mobile pilot");
|
|
14
|
+
const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
|
|
15
|
+
const controller = process.env.HERDGATE_MOBILE_TUI_ACT_DEVICE;
|
|
16
|
+
if (controller !== undefined && !/^d_[A-Za-z0-9]{1,32}$/.test(controller)) throw new Error("invalid Mobile TUI act device ID");
|
|
17
|
+
const allows = (device: string, scope: "read" | "act" | null) =>
|
|
18
|
+
controller ? device === controller && scope === "act" : scope === "read";
|
|
19
|
+
const core = fileURLToPath(new URL("./mobile-tui-core.mjs", import.meta.url));
|
|
20
|
+
if (!existsSync(core)) throw new Error("missing TUI Core adapter");
|
|
21
|
+
const log = (line: string) => console.error(`herdgate-mobile-tui: ${line}`);
|
|
22
|
+
const coreCommands = new Set(["connect", "connect --json", "--version", "-V", "server status", "server status --json"]);
|
|
23
|
+
const bridge = createSshBridge({
|
|
24
|
+
send: (device, payload) => agent.send(device, payload),
|
|
25
|
+
resolveHc: () => core,
|
|
26
|
+
trustedReadCore: core,
|
|
27
|
+
tuiOnly: Boolean(controller),
|
|
28
|
+
mobileTuiAdapter: controller ? { device: controller, scope: "act", script: core } : null,
|
|
29
|
+
resolveHerdrBin: () => null,
|
|
30
|
+
scopeOf: (device) => {
|
|
31
|
+
const scope = agent.scopeOf(device);
|
|
32
|
+
return allows(device, scope) ? scope : null;
|
|
33
|
+
},
|
|
34
|
+
log,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const agent = new HerdGateAgent({
|
|
38
|
+
endpoint: `wss://${url.host}/v1/agent/ws`, roomToken: token, log,
|
|
39
|
+
adapter: {
|
|
40
|
+
info: () => ({ name, version: "tui-core-pilot", capabilities: [controller ? "interactive" : "read-only"] }),
|
|
41
|
+
onPairAsk: () => false,
|
|
42
|
+
onDevices: (devices) => {
|
|
43
|
+
const next = new Set(devices.filter((d) => allows(d.id, d.scope)).map((d) => d.id));
|
|
44
|
+
for (const id of allowedDevices) if (!next.has(id)) bridge.dropDevice(id);
|
|
45
|
+
allowedDevices = next;
|
|
46
|
+
},
|
|
47
|
+
onFrame(device, payload) {
|
|
48
|
+
if (!payload || typeof payload !== "object" || !("op" in payload) || typeof payload.op !== "string" || !payload.op.startsWith("ssh.")) return;
|
|
49
|
+
const p = payload as Record<string, unknown>;
|
|
50
|
+
if (controller || p.op !== "ssh.open") { bridge.handle(device, p); return; }
|
|
51
|
+
const cmd = typeof p.cmd === "string" ? p.cmd.trim() : "";
|
|
52
|
+
if (cmd === "exit" || cmd === "exit 0") { bridge.handle(device, { ...p, cmd }); return; }
|
|
53
|
+
const direct = cmd.match(/^(?:hc|herdr-core)[ \t]+(.+)$/)?.[1];
|
|
54
|
+
const translated = !direct && cmd.includes("herdr-core") ? translateBootstrap(cmd)?.slice(3) : undefined;
|
|
55
|
+
const args = direct || translated || "";
|
|
56
|
+
if (coreCommands.has(args)) bridge.handle(device, { ...p, cmd: `hc ${args}` });
|
|
57
|
+
else {
|
|
58
|
+
log(`unsupported SSH command from ${device} (${cmd.length} bytes)`);
|
|
59
|
+
agent.send(device, { op: "ssh.denied", ch: p.ch, reason: "unsupported command on read-only Herdr TUI pilot" });
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
let allowedDevices = new Set<string>();
|
|
65
|
+
// Do not let a scoped child command inherit any room or account credential.
|
|
66
|
+
delete process.env.HERDGATE_ROOM_TOKEN;
|
|
67
|
+
delete process.env.HERDGATE_ACCOUNT_TOKEN;
|
|
68
|
+
delete process.env.HERDGATE_BRIDGE_TOKEN;
|
|
69
|
+
const stop = () => { bridge.closeAll(); agent.stop(); };
|
|
70
|
+
process.once("SIGINT", stop);
|
|
71
|
+
process.once("SIGTERM", stop);
|
|
72
|
+
agent.start();
|
|
73
|
+
await agent.firstHello.catch(() => {});
|
package/src/web/app.css
CHANGED
|
@@ -301,6 +301,8 @@ dialog::backdrop {
|
|
|
301
301
|
}
|
|
302
302
|
|
|
303
303
|
/* SSH public-key management inside the device's SSH section */
|
|
304
|
+
.ssh-user-select { display: block; width: 100%; margin-top: 4px; }
|
|
305
|
+
#view details.ssh .keyrow[hidden] { display: none; }
|
|
304
306
|
.sshkeys .pubkey-input {
|
|
305
307
|
flex: 1;
|
|
306
308
|
min-width: 0;
|