@bom0792/herdgate 0.9.21 → 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.
- package/README.md +67 -3
- package/bin/herdgate.mjs +11 -3
- package/bin/home-tui.mjs +121 -0
- 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/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 +72 -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/windows/cli.mjs +6 -4
- package/windows/install-cli.mjs +12 -4
- package/windows/setup-tui.mjs +110 -0
|
@@ -14,22 +14,28 @@ try {
|
|
|
14
14
|
const appHome = process.env.HERDR_APP_HOME || join(homedir(), ".config", "herdr-app");
|
|
15
15
|
const base = join(appHome, "herdgate");
|
|
16
16
|
const state = join(base, "state");
|
|
17
|
-
const [action, exe] = process.argv.slice(2);
|
|
17
|
+
const [action, exe, ...args] = process.argv.slice(2);
|
|
18
18
|
if (action === "status" || action === "stop") {
|
|
19
|
+
if (exe || args.length) throw new Error(`usage: publish-tui.mjs ${action}`);
|
|
19
20
|
const result = action === "status" ? publisherStatus(state) : await stopPublisher(state);
|
|
20
21
|
console.log(JSON.stringify(result));
|
|
21
22
|
if (action === "stop" && result.state !== "stopped") process.exitCode = 1;
|
|
22
23
|
} else {
|
|
23
|
-
const bin =
|
|
24
|
-
|
|
24
|
+
const bin = ["start", "check", "--worker"].includes(action) ? exe : action;
|
|
25
|
+
if (args.length && (args.length !== 2 || !["--hc", "--mobile-tui", "--mobile-tui-act"].includes(args[0]) || !args[1])) throw new Error("expected --hc <path to herdr-core.exe>, --mobile-tui <read device ID>, or --mobile-tui-act <act device ID>");
|
|
26
|
+
const mobile = args[0] === "--mobile-tui" || args[0] === "--mobile-tui-act" ? args[1] : "";
|
|
27
|
+
const mobileScope = args[0] === "--mobile-tui-act" ? "act" : "read";
|
|
28
|
+
if (mobile && !/^d_[A-Za-z0-9]{1,32}$/.test(mobile)) throw new Error(`the Mobile TUI option requires a paired ${mobileScope} device ID (d_…)`);
|
|
29
|
+
await launch({ action, bin, hc: args[0] === "--hc" ? args[1] : undefined, mobile, mobileScope, base, state });
|
|
25
30
|
}
|
|
26
31
|
} catch (e) {
|
|
27
32
|
console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
|
|
28
33
|
process.exitCode = 1;
|
|
29
34
|
}
|
|
30
35
|
|
|
31
|
-
async function launch({ action, bin, base, state }) {
|
|
36
|
+
async function launch({ action, bin, hc, mobile, mobileScope, base, state }) {
|
|
32
37
|
if (process.platform !== "win32") throw new Error("this publisher launcher is for Windows");
|
|
38
|
+
if (typeof globalThis.WebSocket !== "function") throw new Error("use Node 22+ with WebSocket enabled to install and run the publisher");
|
|
33
39
|
if (!bin || !/^[a-z]:[\\/]/i.test(bin) || !/\.exe$/i.test(bin) || !statSync(bin).isFile()) {
|
|
34
40
|
throw new Error("usage: node publish-tui.mjs start <absolute path to herdr.exe> | status | stop");
|
|
35
41
|
}
|
|
@@ -45,8 +51,24 @@ async function launch({ action, bin, base, state }) {
|
|
|
45
51
|
throw new Error("this pilot exposes only the default TUI session");
|
|
46
52
|
}
|
|
47
53
|
|
|
54
|
+
let mobileHcBin = "";
|
|
55
|
+
if (hc !== undefined) {
|
|
56
|
+
if (!/^[a-z]:[\\/]/i.test(hc) || !/\.exe$/i.test(hc) || !statSync(hc).isFile()) {
|
|
57
|
+
throw new Error("--hc needs the absolute path to herdr-core.exe on a local drive");
|
|
58
|
+
}
|
|
59
|
+
mobileHcBin = realpathSync.native(hc);
|
|
60
|
+
if (!/^[a-z]:[\\/]/i.test(mobileHcBin) || !/\.exe$/i.test(mobileHcBin)) throw new Error("herdr-core must be a local executable");
|
|
61
|
+
const result = await run(mobileHcBin, ["--version"], { timeout: 5_000, shell: false, windowsHide: true });
|
|
62
|
+
if (!/\bhc\s+\d+\.\d+\.\d+\b|\bherdr-core\s+\d+\.\d+\.\d+\b/i.test(result.stdout)) {
|
|
63
|
+
throw new Error("--hc did not identify itself as herdr-core");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
48
66
|
const env = {
|
|
49
67
|
...process.env,
|
|
68
|
+
HERDGATE_MOBILE_HC_BIN: mobileHcBin,
|
|
69
|
+
HERDGATE_MOBILE_TUI_DEVICE: mobile,
|
|
70
|
+
HERDGATE_MOBILE_TUI_SCOPE: mobileScope,
|
|
71
|
+
...(mobile ? { HERDGATE_HOST_NAME: `${process.env.COMPUTERNAME || "windows"}-TUI` } : {}),
|
|
50
72
|
HERDR_BIN_PATH: bin,
|
|
51
73
|
HERDGATE_HERDR_BIN: bin,
|
|
52
74
|
HERDR_SESSION: "default",
|
|
@@ -72,8 +94,10 @@ async function launch({ action, bin, base, state }) {
|
|
|
72
94
|
if (server.version !== client.version) {
|
|
73
95
|
throw new Error(`the running Herdr server reports ${server.version}, expected ${client.version}; finish work in live panes before restarting Herdr`);
|
|
74
96
|
}
|
|
97
|
+
if (action === "check") return;
|
|
75
98
|
if (action === "start") {
|
|
76
|
-
const
|
|
99
|
+
const mode = mobile ? [mobileScope === "act" ? "--mobile-tui-act" : "--mobile-tui", mobile] : mobileHcBin ? ["--hc", mobileHcBin] : [];
|
|
100
|
+
const result = await startPublisher(state, [fileURLToPath(import.meta.url), "--worker", bin, ...mode], env);
|
|
77
101
|
console.log(JSON.stringify(result));
|
|
78
102
|
if (!["connected", "connecting", "starting"].includes(result.state)) process.exitCode = 1;
|
|
79
103
|
return;
|
package/plugin/server/ssh.d.mts
CHANGED
|
@@ -9,6 +9,9 @@ export interface SshBridgeOptions {
|
|
|
9
9
|
session?: string;
|
|
10
10
|
platform?: NodeJS.Platform;
|
|
11
11
|
tuiOnly?: boolean;
|
|
12
|
+
mobileHcBin?: string | null;
|
|
13
|
+
mobileTuiAdapter?: { device: string; script: string; scope?: "read" | "act" } | null;
|
|
14
|
+
trustedReadCore?: string | null;
|
|
12
15
|
spawnImpl?: (bin: string, args: string[], opts: { stdio: ("pipe" | null)[]; shell: boolean; windowsHide?: boolean; env?: NodeJS.ProcessEnv }) => ChildProcess;
|
|
13
16
|
}
|
|
14
17
|
|
package/plugin/server/ssh.mjs
CHANGED
|
@@ -54,7 +54,25 @@ export function translateBootstrap(cmd) {
|
|
|
54
54
|
return null;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
|
|
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 }) {
|
|
58
76
|
const channels = new Map();
|
|
59
77
|
const key = (device, ch) => `${device}:${ch}`;
|
|
60
78
|
|
|
@@ -89,7 +107,7 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
|
|
|
89
107
|
const feed = (c, buf) => {
|
|
90
108
|
if (c.closed || !c.proc?.stdin?.writable) return;
|
|
91
109
|
if (c.proc.stdin.writableLength + buf.length > 1024 * 1024) return kill(c, "input queue limit");
|
|
92
|
-
if (c.scope === "act") return void c.proc.stdin.write(buf);
|
|
110
|
+
if (c.scope === "act" || c.trustedReadCore) return void c.proc.stdin.write(buf);
|
|
93
111
|
c.inBuf = Buffer.concat([c.inBuf, buf]);
|
|
94
112
|
if (c.inBuf.length > 1024 * 1024) return kill(c, "input line too long");
|
|
95
113
|
for (;;) {
|
|
@@ -136,15 +154,23 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
|
|
|
136
154
|
sendOut(c, true, 130, reason);
|
|
137
155
|
};
|
|
138
156
|
|
|
139
|
-
const start = (device, ch, scope, bin, args, tui = false, closeStdin = false) => {
|
|
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
|
+
}
|
|
140
164
|
let proc;
|
|
141
165
|
try {
|
|
142
|
-
proc = spawnImpl(bin, args, { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, ...(
|
|
166
|
+
proc = spawnImpl(bin, args, { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, ...(env ? { env } : {}) });
|
|
143
167
|
} catch (e) {
|
|
144
168
|
send(device, { op: "ssh.denied", ch, reason: `could not start bridged process: ${e.message}` });
|
|
145
169
|
return;
|
|
146
170
|
}
|
|
147
|
-
|
|
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 };
|
|
148
174
|
channels.set(key(device, ch), c);
|
|
149
175
|
const onData = (chunk) => {
|
|
150
176
|
c.outBuf = Buffer.concat([c.outBuf, chunk]);
|
|
@@ -152,8 +178,8 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
|
|
|
152
178
|
else scheduleFlush(c);
|
|
153
179
|
};
|
|
154
180
|
proc.stdout?.on("data", onData);
|
|
155
|
-
if (tui) {
|
|
156
|
-
send(device, { op: "ssh.data", ch, b64: Buffer.from(MARKER).toString("base64") });
|
|
181
|
+
if (tui || trusted) {
|
|
182
|
+
if (tui) send(device, { op: "ssh.data", ch, b64: Buffer.from(MARKER).toString("base64") });
|
|
157
183
|
proc.stderr?.on("data", (buf) => {
|
|
158
184
|
if (!c.closed) send(device, { op: "ssh.data", ch, stderr: true, b64: buf.toString("base64") });
|
|
159
185
|
});
|
|
@@ -239,6 +265,23 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
|
|
|
239
265
|
send(device, { op: "ssh.closed", ch, code: 0 });
|
|
240
266
|
return true;
|
|
241
267
|
}
|
|
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
|
+
}
|
|
284
|
+
}
|
|
242
285
|
if (tuiOnly || parts.length === 0 || parts[0] !== "hc") {
|
|
243
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" });
|
|
244
287
|
return true;
|
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,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(() => {});
|
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;
|