@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
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Subset of the Core API for TUI panes. Input requires explicit local opt-in.
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { hostname, homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { promisify, stripVTControlCharacters } from "node:util";
|
|
8
|
+
import { openTerminal, validDimension } from "./mobile-tui-stream.mjs";
|
|
9
|
+
|
|
10
|
+
const invoke = promisify(execFile);
|
|
11
|
+
const herdr = process.env.HERDR_BIN_PATH || join(homedir(), ".local/bin/herdr");
|
|
12
|
+
const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
|
|
13
|
+
const digest = (text) => createHash("sha256").update(text).digest("hex");
|
|
14
|
+
const core = { id: digest(`herdgate-tui:${hostname()}:${name}`).slice(0, 32), name };
|
|
15
|
+
const version = "0.1.21"; // Core wire compatibility target, not a running Core binary.
|
|
16
|
+
const methods = ["hello", "server.status", "terminal.list", "terminal.get", "terminal.read", "events.subscribe", "templates.list", "machine.list", "doc.get"];
|
|
17
|
+
const inputMethods = ["terminal.send", "terminal.keys", "terminal.interrupt"];
|
|
18
|
+
const args = process.argv.slice(2);
|
|
19
|
+
const interactive = args[0] === "--interactive";
|
|
20
|
+
if (interactive) args.shift();
|
|
21
|
+
const mode = interactive ? "interactive" : "read-only";
|
|
22
|
+
const inputText = (text) => typeof text === "string" && text.length > 0 && !text.includes("\0") && Buffer.byteLength(text) <= 8192;
|
|
23
|
+
const frameKind = { data: 0, credit: 1, close: 2, resize: 3 };
|
|
24
|
+
const cap = 128 * 1024;
|
|
25
|
+
const windowBytes = 64 * 1024;
|
|
26
|
+
const maxStreams = 2;
|
|
27
|
+
const pollMs = 1_250;
|
|
28
|
+
const startedAt = Date.now();
|
|
29
|
+
let cache;
|
|
30
|
+
let cacheUntil = 0;
|
|
31
|
+
const run = async (args) => (await invoke(herdr, args, { timeout: 4_000, maxBuffer: 512 * 1024, windowsHide: true, shell: false })).stdout;
|
|
32
|
+
|
|
33
|
+
async function panes() {
|
|
34
|
+
if (cache && Date.now() < cacheUntil) return cache;
|
|
35
|
+
const parsed = JSON.parse(await run(["pane", "list"]));
|
|
36
|
+
if (!Array.isArray(parsed?.result?.panes)) throw new Error("Herdr pane list unavailable");
|
|
37
|
+
cache = parsed.result.panes.filter((p) => typeof p?.pane_id === "string" && /^[a-zA-Z0-9_:.-]{1,128}$/.test(p.pane_id) && !p.pane_id.startsWith("-"))
|
|
38
|
+
.slice(0, 180).map((p) => {
|
|
39
|
+
const title = clip(p.terminal_title_stripped || p.terminal_title || p.pane_id, 120);
|
|
40
|
+
return { id: p.pane_id, target: typeof p.terminal_id === "string" && /^term_[a-zA-Z0-9]{1,96}$/.test(p.terminal_id) ? p.terminal_id : null, terminal: {
|
|
41
|
+
address: "t" + digest(p.pane_id).slice(0, 12), title, name: null, argv: [], cwd: clip(p.cwd, 512),
|
|
42
|
+
state: "live", created_ms: 0, screen: "inexact", cols: 80, rows: 24,
|
|
43
|
+
labels: { where: clip(p.workspace_id, 128) }, turn: 0,
|
|
44
|
+
} };
|
|
45
|
+
});
|
|
46
|
+
cacheUntil = Date.now() + 1_000;
|
|
47
|
+
return cache;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function clip(x, n) { return typeof x === "string" ? x.slice(0, n) : ""; }
|
|
51
|
+
const status = async () => ({ core, version, pid: process.pid, uptime_ms: Date.now() - startedAt, holders: [], live: (await panes()).length, finished: 0, keeps_running_after_logout: true });
|
|
52
|
+
class RpcError extends Error {
|
|
53
|
+
constructor(code, message, kind) { super(message); this.code = code; this.kind = kind; }
|
|
54
|
+
}
|
|
55
|
+
const invalid = () => new RpcError(-32602, "Invalid params", "usage");
|
|
56
|
+
|
|
57
|
+
async function findPane(terminal) {
|
|
58
|
+
if (typeof terminal !== "string") throw invalid();
|
|
59
|
+
const hit = (await panes()).find((x) => x.terminal.address === terminal);
|
|
60
|
+
if (!hit) throw new RpcError(-32000, "No such terminal", "not_found");
|
|
61
|
+
return hit;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function call(method, p, framed, attach) {
|
|
65
|
+
switch (method) {
|
|
66
|
+
case "hello":
|
|
67
|
+
return { core, version, generation: 1, framed, features: framed ? ["framed", "attach", "status", ...(interactive ? ["resize_notifications"] : [])] : ["status"], methods: [...methods, ...(framed ? ["terminal.attach"] : []), ...(interactive ? inputMethods : [])], keeps_running_after_logout: true };
|
|
68
|
+
case "server.status": return status();
|
|
69
|
+
case "terminal.list":
|
|
70
|
+
case "events.subscribe": {
|
|
71
|
+
const filters = p.labels ?? {};
|
|
72
|
+
if (!filters || typeof filters !== "object" || Array.isArray(filters)) throw invalid();
|
|
73
|
+
const terminals = (await panes()).map(({ terminal }) => terminal).filter((t) =>
|
|
74
|
+
(method === "terminal.list" || (!p.children_of && (!p.terminal || p.terminal === t.address))) &&
|
|
75
|
+
Object.entries(filters).every(([k, v]) => Object.hasOwn(t.labels, k) && t.labels[k] === v));
|
|
76
|
+
return method === "terminal.list" ? { terminals, hidden_finished: 0, machines: [] } : { terminals, seq: 0, channel: null };
|
|
77
|
+
}
|
|
78
|
+
case "terminal.send":
|
|
79
|
+
case "terminal.keys":
|
|
80
|
+
case "terminal.interrupt": {
|
|
81
|
+
if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
|
|
82
|
+
const { id, terminal } = await findPane(p.terminal);
|
|
83
|
+
const { turn } = terminal;
|
|
84
|
+
if (method === "terminal.send") {
|
|
85
|
+
if (!inputText(p.text) || p.wait === true || p.if != null) throw invalid();
|
|
86
|
+
// Herdr's pane run takes positional text and submits it with Enter in one API request.
|
|
87
|
+
await run(["pane", "run", id, p.text]);
|
|
88
|
+
return { turn, status: null, started: null, wait: null };
|
|
89
|
+
}
|
|
90
|
+
const keys = method === "terminal.interrupt" ? ["ctrl+c"] : p.keys;
|
|
91
|
+
if (!Array.isArray(keys) || !keys.length || keys.length > 32 || keys.some((key) => typeof key !== "string" || !/^(?:(?:ctrl|alt|shift|super)\+)*[a-z0-9][a-z0-9_-]{0,15}$/i.test(key) || key.length > 32)) throw invalid();
|
|
92
|
+
await run(["pane", "send-keys", id, ...keys]);
|
|
93
|
+
return method === "terminal.interrupt" ? { key: keys[0], outcome: "unknown" } : { turn, status: null };
|
|
94
|
+
}
|
|
95
|
+
case "terminal.get":
|
|
96
|
+
case "terminal.attach":
|
|
97
|
+
case "terminal.read": {
|
|
98
|
+
const hit = await findPane(p.terminal);
|
|
99
|
+
if (method === "terminal.get") return hit.terminal;
|
|
100
|
+
if (method === "terminal.attach") {
|
|
101
|
+
if (!framed) throw new RpcError(-32000, "Framed connection required", "needs_framed");
|
|
102
|
+
if ([p.cols, p.rows].some((n) => n !== undefined && n !== 0 && !validDimension(n))) throw invalid();
|
|
103
|
+
return attach(hit, p);
|
|
104
|
+
}
|
|
105
|
+
const lines = p.lines ?? 0;
|
|
106
|
+
if (!Number.isSafeInteger(lines) || lines < 0) throw invalid();
|
|
107
|
+
const text = await run(["pane", "read", hit.id, "--source", "recent", "--lines", String(Math.max(24, Math.min(120, lines + 24))), "--format", "text", "--raw"]);
|
|
108
|
+
return { text: text.slice(0, 32 * 1024), complete: text.length <= 32 * 1024, how: "screen" };
|
|
109
|
+
}
|
|
110
|
+
case "templates.list": return { templates: [] };
|
|
111
|
+
case "machine.list": return { machines: [] };
|
|
112
|
+
case "doc.get": return { value: null, version: 0 };
|
|
113
|
+
default: throw new RpcError(-32601, "Method not available on this TUI adapter", "forbidden");
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function paint(paneId, rows) {
|
|
118
|
+
const raw = await run(["pane", "read", paneId, "--source", "visible", "--lines", String(rows), "--format", "text", "--raw"]);
|
|
119
|
+
// Do not replay host terminal escapes (clipboard, title, device queries, etc.).
|
|
120
|
+
const text = stripVTControlCharacters(raw.slice(0, 16_000))
|
|
121
|
+
.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, "")
|
|
122
|
+
.replace(/\n/g, "\r\n");
|
|
123
|
+
return Buffer.from("\x1b[2J\x1b[H" + text);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function serve() {
|
|
127
|
+
let framed = false;
|
|
128
|
+
let buffer = Buffer.alloc(0);
|
|
129
|
+
const streams = new Map();
|
|
130
|
+
let nextChannel = 1;
|
|
131
|
+
let timer;
|
|
132
|
+
let polling = false;
|
|
133
|
+
let closed = false;
|
|
134
|
+
|
|
135
|
+
function output(bytes) {
|
|
136
|
+
return new Promise((resolve, reject) => process.stdout.write(bytes, (err) => err ? reject(err) : resolve()));
|
|
137
|
+
}
|
|
138
|
+
function frame(channel, kind, body = Buffer.alloc(0)) {
|
|
139
|
+
const header = Buffer.alloc(9);
|
|
140
|
+
header.writeUInt32LE(channel, 0);
|
|
141
|
+
header[4] = kind;
|
|
142
|
+
header.writeUInt32LE(body.length, 5);
|
|
143
|
+
return output(Buffer.concat([header, body]));
|
|
144
|
+
}
|
|
145
|
+
function write(reply) {
|
|
146
|
+
const body = Buffer.from(JSON.stringify(reply));
|
|
147
|
+
return framed ? frame(0, frameKind.data, body) : output(Buffer.concat([body, Buffer.from("\n")]));
|
|
148
|
+
}
|
|
149
|
+
async function attach(hit, p) {
|
|
150
|
+
if (streams.size >= maxStreams || nextChannel > 0xffff_ffff) throw new RpcError(-32000, "Too many open terminal views", "unavailable");
|
|
151
|
+
const writable = interactive && p.observe !== true;
|
|
152
|
+
if (writable && !hit.target) throw new RpcError(-32000, "This pane has no native terminal stream", "unavailable");
|
|
153
|
+
const native = writable ? await openTerminal(herdr, hit.target, Math.min(500, p.cols || hit.terminal.cols), Math.min(300, p.rows || hit.terminal.rows)) : null;
|
|
154
|
+
const channel = nextChannel++;
|
|
155
|
+
const resize = Boolean(native && p.resize_notifications === true);
|
|
156
|
+
const terminal = native ? { ...hit.terminal, cols: native.first.cols, rows: native.first.rows } : hit.terminal;
|
|
157
|
+
streams.set(channel, { id: hit.id, rows: Math.min(120, p.rows || hit.terminal.rows), credit: windowBytes, last: null, ready: false, native, resize });
|
|
158
|
+
return { channel, terminal, resize_notifications: resize, automatic_input: false };
|
|
159
|
+
}
|
|
160
|
+
function release(channel) {
|
|
161
|
+
const stream = streams.get(channel);
|
|
162
|
+
if (!stream) return false;
|
|
163
|
+
streams.delete(channel);
|
|
164
|
+
stream.native?.close();
|
|
165
|
+
stream.wake?.();
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
async function closeStream(channel) {
|
|
169
|
+
if (release(channel)) await frame(channel, frameKind.close);
|
|
170
|
+
}
|
|
171
|
+
async function pumpNative(channel, stream) {
|
|
172
|
+
async function sendPaint(paint) {
|
|
173
|
+
if (streams.get(channel) !== stream) return false;
|
|
174
|
+
if (stream.resize && (paint.cols !== stream.cols || paint.rows !== stream.nativeRows)) {
|
|
175
|
+
stream.cols = paint.cols;
|
|
176
|
+
stream.nativeRows = paint.rows;
|
|
177
|
+
const size = Buffer.alloc(4);
|
|
178
|
+
size.writeUInt16LE(paint.cols, 0);
|
|
179
|
+
size.writeUInt16LE(paint.rows, 2);
|
|
180
|
+
await frame(channel, frameKind.resize, size);
|
|
181
|
+
}
|
|
182
|
+
for (let offset = 0; offset < paint.bytes.length;) {
|
|
183
|
+
while (streams.get(channel) === stream && stream.credit === 0) await new Promise((resolve) => { stream.wake = resolve; });
|
|
184
|
+
if (streams.get(channel) !== stream) return false;
|
|
185
|
+
const end = Math.min(offset + stream.credit, offset + 32 * 1024, paint.bytes.length);
|
|
186
|
+
stream.credit -= end - offset;
|
|
187
|
+
await frame(channel, frameKind.data, paint.bytes.subarray(offset, end));
|
|
188
|
+
offset = end;
|
|
189
|
+
}
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
if (await sendPaint(stream.native.first)) {
|
|
194
|
+
for await (const paint of stream.native.frames) if (!(await sendPaint(paint))) break;
|
|
195
|
+
}
|
|
196
|
+
} catch { /* Unexpected native close is signalled on this stream. */ }
|
|
197
|
+
finally { await closeStream(channel); }
|
|
198
|
+
}
|
|
199
|
+
function schedule(delay) {
|
|
200
|
+
if (closed || polling || timer || ![...streams.values()].some((s) => !s.native)) return;
|
|
201
|
+
timer = setTimeout(() => {
|
|
202
|
+
timer = undefined;
|
|
203
|
+
void poll().catch(() => process.stdin.destroy());
|
|
204
|
+
}, delay);
|
|
205
|
+
timer.unref();
|
|
206
|
+
}
|
|
207
|
+
async function poll() {
|
|
208
|
+
polling = true;
|
|
209
|
+
try {
|
|
210
|
+
for (const [channel, stream] of [...streams]) {
|
|
211
|
+
// Bound subprocesses and stop reading while a client is not draining this view.
|
|
212
|
+
if (closed || streams.get(channel) !== stream || stream.native || !stream.ready || stream.credit < windowBytes / 2) continue;
|
|
213
|
+
let snapshot;
|
|
214
|
+
try { snapshot = await paint(stream.id, stream.rows); }
|
|
215
|
+
catch {
|
|
216
|
+
if (!closed) await closeStream(channel);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (closed || streams.get(channel) !== stream || snapshot.length > stream.credit || stream.last?.equals(snapshot)) continue;
|
|
220
|
+
stream.credit -= snapshot.length;
|
|
221
|
+
stream.last = snapshot;
|
|
222
|
+
await frame(channel, frameKind.data, snapshot);
|
|
223
|
+
}
|
|
224
|
+
} finally {
|
|
225
|
+
polling = false;
|
|
226
|
+
schedule(pollMs);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
try {
|
|
231
|
+
for await (const chunk of process.stdin) {
|
|
232
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
233
|
+
for (;;) {
|
|
234
|
+
let body;
|
|
235
|
+
if (framed) {
|
|
236
|
+
if (buffer.length < 9) break;
|
|
237
|
+
const size = buffer.readUInt32LE(5);
|
|
238
|
+
if (size > cap) throw new Error("Core frame too large");
|
|
239
|
+
if (buffer.length < 9 + size) break;
|
|
240
|
+
const channel = buffer.readUInt32LE(0);
|
|
241
|
+
const kind = buffer[4];
|
|
242
|
+
body = buffer.subarray(9, 9 + size);
|
|
243
|
+
buffer = buffer.subarray(9 + size);
|
|
244
|
+
if (channel !== 0) {
|
|
245
|
+
const stream = streams.get(channel);
|
|
246
|
+
if (stream && kind === frameKind.credit && size === 4) {
|
|
247
|
+
stream.credit = Math.min(windowBytes, stream.credit + body.readUInt32LE());
|
|
248
|
+
stream.wake?.();
|
|
249
|
+
stream.wake = null;
|
|
250
|
+
}
|
|
251
|
+
if (stream && kind === frameKind.close && size === 0) await closeStream(channel);
|
|
252
|
+
if (stream?.native) {
|
|
253
|
+
try {
|
|
254
|
+
if (kind === frameKind.data && size > 0) {
|
|
255
|
+
if (size > 32 * 1024) throw invalid();
|
|
256
|
+
await stream.native.send({ type: "terminal.input", bytes: body.toString("base64") });
|
|
257
|
+
}
|
|
258
|
+
if (kind === frameKind.resize && size === 4) {
|
|
259
|
+
const cols = body.readUInt16LE(0), rows = body.readUInt16LE(2);
|
|
260
|
+
if (cols > 0 && rows > 0) await stream.native.send({ type: "terminal.resize", cols: Math.min(500, cols), rows: Math.min(300, rows) });
|
|
261
|
+
}
|
|
262
|
+
} catch { await closeStream(channel); }
|
|
263
|
+
}
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (kind !== frameKind.data) continue;
|
|
267
|
+
} else {
|
|
268
|
+
const end = buffer.indexOf(10);
|
|
269
|
+
if (end > cap || (end < 0 && buffer.length > cap)) throw new Error("Core line too large");
|
|
270
|
+
if (end < 0) break;
|
|
271
|
+
body = buffer.subarray(0, end);
|
|
272
|
+
buffer = buffer.subarray(end + 1);
|
|
273
|
+
if (!body.length) continue;
|
|
274
|
+
}
|
|
275
|
+
let msg;
|
|
276
|
+
try { msg = JSON.parse(body.toString("utf8")); }
|
|
277
|
+
catch { await write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); continue; }
|
|
278
|
+
if (!msg || msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || !Object.hasOwn(msg, "id")) continue;
|
|
279
|
+
if (msg.id !== null && typeof msg.id !== "number" && typeof msg.id !== "string") continue;
|
|
280
|
+
const reply = { jsonrpc: "2.0", id: msg.id };
|
|
281
|
+
const nextFramed = framed || (msg.method === "hello" && msg.params?.framed === true);
|
|
282
|
+
let result;
|
|
283
|
+
try {
|
|
284
|
+
if (msg.params != null && (typeof msg.params !== "object" || Array.isArray(msg.params))) throw invalid();
|
|
285
|
+
result = await call(msg.method, msg.params ?? {}, nextFramed, attach);
|
|
286
|
+
} catch (err) {
|
|
287
|
+
const error = err instanceof RpcError ? { code: err.code, message: err.message, data: { kind: err.kind } } : { code: -32000, message: "Herdr TUI unavailable", data: { kind: "unavailable" } };
|
|
288
|
+
await write({ ...reply, error });
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
await write({ ...reply, result });
|
|
292
|
+
framed = nextFramed;
|
|
293
|
+
if (msg.method === "terminal.attach") {
|
|
294
|
+
const stream = streams.get(result.channel);
|
|
295
|
+
stream.ready = true;
|
|
296
|
+
if (stream.native) void pumpNative(result.channel, stream).catch(() => process.stdin.destroy());
|
|
297
|
+
else schedule(0);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
} finally {
|
|
302
|
+
closed = true;
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
for (const channel of streams.keys()) release(channel);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const command = args.join(" ");
|
|
309
|
+
try {
|
|
310
|
+
if (command === "--version" || command === "-V") console.log(`hc ${version} (Herdgate ${mode} TUI adapter)`);
|
|
311
|
+
else if (command === "server status" || command === "server status --json") console.log(JSON.stringify(await status()));
|
|
312
|
+
else if (command === "connect" || command === "connect --json") {
|
|
313
|
+
await serve();
|
|
314
|
+
} else {
|
|
315
|
+
console.error("herdgate: TUI adapter supports only connect, --version, and server status");
|
|
316
|
+
process.exitCode = 111;
|
|
317
|
+
}
|
|
318
|
+
} catch {
|
|
319
|
+
console.error("herdgate: could not query the local Herdr TUI");
|
|
320
|
+
process.exitCode = 111;
|
|
321
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Native Herdr terminal controller. Never grants takeover and never interprets a shell command.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
|
|
4
|
+
const maxLine = 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
export async function openTerminal(bin, id, cols, rows) {
|
|
7
|
+
const child = spawn(bin, ["terminal", "session", "control", id, "--cols", String(cols), "--rows", String(rows)], {
|
|
8
|
+
stdio: ["pipe", "pipe", "ignore"], windowsHide: true, shell: false,
|
|
9
|
+
});
|
|
10
|
+
child.on("error", () => child.stdout.destroy());
|
|
11
|
+
child.stdin.on("error", () => child.stdout.destroy());
|
|
12
|
+
const frames = readFrames(child.stdout);
|
|
13
|
+
let closed = false;
|
|
14
|
+
function close() {
|
|
15
|
+
if (closed) return;
|
|
16
|
+
closed = true;
|
|
17
|
+
child.stdin.end(); // EOF asks Herdr to release the controller.
|
|
18
|
+
const kill = setTimeout(() => child.kill(), 750);
|
|
19
|
+
kill.unref();
|
|
20
|
+
child.once("close", () => clearTimeout(kill));
|
|
21
|
+
}
|
|
22
|
+
const deadline = setTimeout(() => child.stdout.destroy(new Error("Herdr attach timed out")), 4000);
|
|
23
|
+
try {
|
|
24
|
+
const first = await frames.next();
|
|
25
|
+
if (first.done) throw new Error("Herdr declined terminal attach");
|
|
26
|
+
return {
|
|
27
|
+
first: first.value, frames, close,
|
|
28
|
+
send: (message) => new Promise((resolve, reject) => {
|
|
29
|
+
if (closed || !child.stdin.writable) return reject(new Error("Herdr terminal closed"));
|
|
30
|
+
child.stdin.write(JSON.stringify(message) + "\n", (err) => err ? reject(err) : resolve());
|
|
31
|
+
}),
|
|
32
|
+
};
|
|
33
|
+
} catch (err) {
|
|
34
|
+
close();
|
|
35
|
+
throw err;
|
|
36
|
+
} finally {
|
|
37
|
+
clearTimeout(deadline);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function* readFrames(stdout) {
|
|
42
|
+
let pending = Buffer.alloc(0);
|
|
43
|
+
for await (const chunk of stdout) {
|
|
44
|
+
pending = Buffer.concat([pending, chunk]);
|
|
45
|
+
for (;;) {
|
|
46
|
+
const end = pending.indexOf(10);
|
|
47
|
+
if (end > maxLine || (end < 0 && pending.length > maxLine)) throw new Error("Herdr terminal frame too large");
|
|
48
|
+
if (end < 0) break;
|
|
49
|
+
const msg = JSON.parse(pending.subarray(0, end).toString("utf8"));
|
|
50
|
+
pending = pending.subarray(end + 1);
|
|
51
|
+
if (msg.type === "terminal.closed") return;
|
|
52
|
+
if (msg.type !== "terminal.frame" || msg.encoding !== "ansi" || typeof msg.bytes !== "string") continue;
|
|
53
|
+
if (!validDimension(msg.width) || !validDimension(msg.height)) throw new Error("Invalid Herdr terminal geometry");
|
|
54
|
+
yield { cols: msg.width, rows: msg.height, bytes: Buffer.from(msg.bytes, "base64") };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function validDimension(value) {
|
|
60
|
+
return Number.isInteger(value) && value > 0 && value <= 65535;
|
|
61
|
+
}
|
|
@@ -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/scripts/deploy-vps.sh
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
2
|
# herdgate → VPS: dựng gateway trực tiếp trên VPS (không Cloudflare tunnel).
|
|
3
|
-
# Dùng: bash scripts/deploy-vps.sh root@<VPS-IP>
|
|
3
|
+
# Dùng: bash scripts/deploy-vps.sh root@<VPS-IP> <gate-hostname>
|
|
4
4
|
# Yêu cầu bên VPS : Ubuntu/Debian, root (qua key herdgate_deploy), port 80/443/2299 mở.
|
|
5
5
|
# Yêu cầu bên DNS : gate. + ssh. trỏ A → VPS (mây xám) — làm TRƯỚC khi chạy để Caddy xin cert được.
|
|
6
6
|
set -euo pipefail
|
|
7
|
-
TARGET="${1:?dùng: deploy-vps.sh root@<vps-ip>}"
|
|
7
|
+
TARGET="${1:?dùng: deploy-vps.sh root@<vps-ip> <gate-hostname>}"
|
|
8
|
+
GATE_HOST="${2:?dùng: deploy-vps.sh root@<vps-ip> <gate-hostname>}"
|
|
9
|
+
if [[ ! "$GATE_HOST" =~ ^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$ ]] || (( ${#GATE_HOST} > 253 )); then
|
|
10
|
+
echo "gate-hostname phải là tên DNS, không có giao thức hay cổng" >&2
|
|
11
|
+
exit 2
|
|
12
|
+
fi
|
|
8
13
|
KEY="$HOME/.ssh/herdgate_deploy"
|
|
9
14
|
DIR=$(cd "$(dirname "$0")/.." && pwd)
|
|
10
15
|
|
|
@@ -52,7 +57,7 @@ TOKEN_B64=$(printf %s "$TOKEN" | base64 -w0)
|
|
|
52
57
|
ssh -i "$KEY" "$TARGET" "python3 -c \"import base64; tok=base64.b64decode('$TOKEN_B64').decode(); p=open('/etc/systemd/system/herdgate.service').read().replace('__TOKEN__',tok); open('/etc/systemd/system/herdgate.service','w').write(p)\""
|
|
53
58
|
|
|
54
59
|
echo "==> 4/5 caddy (TLS tự động) + firewall"
|
|
55
|
-
ssh -i "$KEY" "$TARGET" 'set -e
|
|
60
|
+
ssh -i "$KEY" "$TARGET" "GATE_HOST=$GATE_HOST "'set -e
|
|
56
61
|
if ! command -v caddy >/dev/null; then
|
|
57
62
|
apt-get update -qq && apt-get install -y -qq debian-keyring debian-archive-keyring apt-transport-https curl >/dev/null
|
|
58
63
|
curl -1sLf https://dl.cloudsmith.io/public/caddy/stable/gpg.key | gpg --batch --yes --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
|
|
@@ -60,7 +65,7 @@ ssh -i "$KEY" "$TARGET" 'set -e
|
|
|
60
65
|
apt-get update -qq && apt-get install -y -qq caddy >/dev/null
|
|
61
66
|
fi
|
|
62
67
|
cat > /etc/caddy/Caddyfile <<EOF2
|
|
63
|
-
|
|
68
|
+
$GATE_HOST {
|
|
64
69
|
reverse_proxy 127.0.0.1:8833
|
|
65
70
|
}
|
|
66
71
|
EOF2
|
|
@@ -71,4 +76,4 @@ EOF2
|
|
|
71
76
|
echo "==> 5/5 start herdgate"
|
|
72
77
|
ssh -i "$KEY" "$TARGET" 'systemctl daemon-reload && systemctl enable --now herdgate && sleep 3 && systemctl is-active herdgate'
|
|
73
78
|
|
|
74
|
-
echo "OK — kiểm tra: curl https
|
|
79
|
+
echo "OK — kiểm tra: curl https://$GATE_HOST/healthz (sau khi DNS đã trỏ)"
|