@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/README.md
CHANGED
|
@@ -178,16 +178,60 @@ Herdgate does not install, update or stop Herdr remotely. Upgrade the host local
|
|
|
178
178
|
if its running server is incompatible. SSH terminates at the gate; this is not
|
|
179
179
|
client-to-publisher Noise E2E. No third-party relay or inbound client port is needed.
|
|
180
180
|
|
|
181
|
+
### Manage a paired publisher from one CLI
|
|
182
|
+
|
|
183
|
+
Install the command once with `npm install -g @bom0792/herdgate` (Node 22+).
|
|
184
|
+
Use your own cloud URL; there is no built-in Gate address.
|
|
185
|
+
|
|
186
|
+
```sh
|
|
187
|
+
herdgate cloud add work https://gate.example.com
|
|
188
|
+
herdgate cloud list
|
|
189
|
+
herdgate pair --cloud work
|
|
190
|
+
herdgate setup
|
|
191
|
+
herdgate status
|
|
192
|
+
herdgate update
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Skip `pair` on already-paired machines. Adding a cloud does not route an
|
|
196
|
+
existing pairing or its room token to that cloud. Pairing still requires
|
|
197
|
+
the cloud owner to approve the code. `setup`, `start`, `stop`, `status` and
|
|
198
|
+
`update` select the local Windows or Linux publisher implementation.
|
|
199
|
+
When upgrading an existing installation, run `herdgate migrate` once.
|
|
200
|
+
It keeps the configured cloud, pairing and device keys. On Windows, if an
|
|
201
|
+
older CLI did not save its publisher mode, supply the existing mode once:
|
|
202
|
+
`herdgate migrate --mobile-act d_device`, `--mobile-read d_device`,
|
|
203
|
+
`--hc <path>`, or `--plain` if Mobile was off. Do not change scope during
|
|
204
|
+
migration. On Linux it adopts the known legacy Herdgate service, waits for
|
|
205
|
+
a Gate hello from the new invocation, and restores the previous service
|
|
206
|
+
file on failure. It will not adopt an unrelated custom unit.
|
|
207
|
+
Migration or update may briefly disconnect remote clients, but never
|
|
208
|
+
restarts Herdr. The main publisher commands do not merge standalone Mobile
|
|
209
|
+
rooms or upgrade the VPS.
|
|
210
|
+
|
|
181
211
|
### Windows as a TUI host
|
|
182
212
|
|
|
183
213
|
Use this only where remote control is approved by the machine's owner/IT.
|
|
184
|
-
With Node 22+ on Windows
|
|
214
|
+
With Node 22+ on Windows and an existing Gate pairing, use one command to
|
|
215
|
+
install and start the TUI publisher (add the relevant Mobile flag if enabled):
|
|
185
216
|
|
|
186
217
|
```powershell
|
|
187
|
-
npx --yes @bom0792/herdgate@latest
|
|
218
|
+
npx --yes @bom0792/herdgate@latest tui setup --mobile-tui-act d_device
|
|
188
219
|
npx --yes @bom0792/herdgate@latest tui status
|
|
189
220
|
```
|
|
190
221
|
|
|
222
|
+
Omit `--mobile-tui-act d_device` for TUI-only setup. The first setup or
|
|
223
|
+
migration from a manual install needs the desired mode once; it is saved
|
|
224
|
+
locally only after the publisher connects. For subsequent updates:
|
|
225
|
+
|
|
226
|
+
```powershell
|
|
227
|
+
herdgate update
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
The update validates the new release before touching the old publisher. It
|
|
231
|
+
preserves the device ID and mode, restarts only the publisher if needed, and
|
|
232
|
+
tries to restore the old release if the new worker cannot connect. Pairing
|
|
233
|
+
and SSH keys are not rewritten. Use `install-tui` for install without starting.
|
|
234
|
+
|
|
191
235
|
The ZIP remains an alternative: extract it and run `node .\windows\install-cli.mjs`.
|
|
192
236
|
|
|
193
237
|
The installer stores each build under `%LOCALAPPDATA%\Herdgate\cli\releases`.
|
|
@@ -206,7 +250,57 @@ When `herdgate-tui status` shows `connected`, you can close PowerShell.
|
|
|
206
250
|
port, no Windows SSH server. The publisher reuses the existing laptop pairing.
|
|
207
251
|
The controlling machine still needs its own approved `act` device and SSH key.
|
|
208
252
|
Add the saved machine with `herdr machine add <alias> --label laptop --remote-session default`.
|
|
209
|
-
|
|
253
|
+
The default publisher does not expose `hc`. If remote control is approved, opt
|
|
254
|
+
in to Herdr Mobile support with the installed Core executable:
|
|
255
|
+
|
|
256
|
+
```powershell
|
|
257
|
+
$hc = (Get-Command herdr-core.exe -ErrorAction Stop).Source
|
|
258
|
+
& $hc server status --json
|
|
259
|
+
herdgate-tui stop
|
|
260
|
+
herdgate-tui start --hc "$hc"
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
If Core is not running, start it locally with `& $hc server start`. The `--hc`
|
|
264
|
+
flag keeps the TUI bridge enabled and adds Core access for `act` devices only.
|
|
265
|
+
The publisher restart interrupts remote connections, not the local TUI server.
|
|
266
|
+
In `--hc` mode, Herdr Mobile sees Core terminals, not TUI panes.
|
|
267
|
+
To expose TUI panes directly instead, use `herdgate-tui start --mobile-tui d_device`
|
|
268
|
+
with the ID of a paired `read` device in this laptop’s room. This opt-in mode
|
|
269
|
+
serves only that device with a read-only Core protocol adapter, needs no `hc`
|
|
270
|
+
binary, and leaves the normal TUI bridge and its existing `act` devices intact.
|
|
271
|
+
Opening an individual pane in Herdr Mobile shows a periodically refreshed
|
|
272
|
+
text snapshot of its visible screen. The adapter does not forward keystrokes,
|
|
273
|
+
resize the pane, or reproduce its full ANSI rendering or scrollback.
|
|
274
|
+
|
|
275
|
+
For a phone explicitly approved to control this laptop, start the publisher
|
|
276
|
+
with `--mobile-tui-act d_device` instead. The device must already have `act`
|
|
277
|
+
scope, and the setting only enables the Core adapter for that device ID.
|
|
278
|
+
Non-observe attach uses Herdr's native terminal session to forward ANSI output,
|
|
279
|
+
keys and viewport resize. Resize changes the pane's real terminal size while
|
|
280
|
+
the controller is attached. Send (paste + Enter), named keys and Interrupt are
|
|
281
|
+
also mapped to TUI actions. The adapter does not implement Core-only features
|
|
282
|
+
such as templates, task lifecycle or file operations. Enable this mode only
|
|
283
|
+
where executing commands in existing panes from the phone is authorized.
|
|
284
|
+
|
|
285
|
+
For the Linux home TUI bridge (laptop → home), the paired host can run:
|
|
286
|
+
|
|
287
|
+
```sh
|
|
288
|
+
npx --yes @bom0792/herdgate@latest home-tui setup
|
|
289
|
+
npx --yes @bom0792/herdgate@latest home-tui status
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Use `home-tui setup --adopt` to migrate the previous home unit created by
|
|
293
|
+
Herdgate; other custom units are not overwritten. The command installs a
|
|
294
|
+
persistent systemd user service, reuses the existing room and TUI socket,
|
|
295
|
+
and does not restart Herdr. Repeat `setup` to update the publisher.
|
|
296
|
+
|
|
297
|
+
On Linux, use `npm run mobile-tui` (or `node src/host/mobile-tui.ts`) as the
|
|
298
|
+
user running Herdr, with
|
|
299
|
+
`HERDGATE_URL`, a dedicated `HERDGATE_ROOM_TOKEN`, and `HERDR_BIN_PATH` set.
|
|
300
|
+
Set `HERDR_SOCKET_PATH` if needed to select the existing TUI session. Without
|
|
301
|
+
`HERDGATE_MOBILE_TUI_ACT_DEVICE`, this publisher is read-only. For interactive
|
|
302
|
+
mode, use a separate room and set that variable to the exact existing `act`
|
|
303
|
+
device ID. The publisher never auto-approves new `act` pairings.
|
|
210
304
|
|
|
211
305
|
## The PWA (the device side)
|
|
212
306
|
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const dir = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'herdgate');
|
|
7
|
+
const path = join(dir, 'clouds.json');
|
|
8
|
+
const validName = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
9
|
+
|
|
10
|
+
export function cloudOrigin(raw) {
|
|
11
|
+
if (typeof raw !== 'string' || /[\s?#@]/.test(raw)) throw new Error('cloud must be a credential-free HTTPS origin');
|
|
12
|
+
let url;
|
|
13
|
+
try { url = new URL(raw); }
|
|
14
|
+
catch { throw new Error('cloud must be a credential-free HTTPS origin'); }
|
|
15
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
|
|
16
|
+
throw new Error('cloud must be a credential-free HTTPS origin');
|
|
17
|
+
}
|
|
18
|
+
return url.origin;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function load() {
|
|
22
|
+
let parsed;
|
|
23
|
+
try { parsed = JSON.parse(readFileSync(path, 'utf8')); }
|
|
24
|
+
catch (e) { if (e.code === 'ENOENT') return new Map(); throw e; }
|
|
25
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('invalid cloud config');
|
|
26
|
+
return new Map(Object.entries(parsed).map(([name, origin]) => {
|
|
27
|
+
if (!validName.test(name)) throw new Error('invalid name in cloud config');
|
|
28
|
+
return [name, cloudOrigin(origin)];
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function resolveCloud(input) {
|
|
33
|
+
if (validName.test(input)) {
|
|
34
|
+
const origin = load().get(input);
|
|
35
|
+
if (!origin) throw new Error(`cloud '${input}' not found; use herdgate cloud add <name> <url>`);
|
|
36
|
+
return origin;
|
|
37
|
+
}
|
|
38
|
+
return cloudOrigin(input);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function manageCloud([action, name, value, ...rest]) {
|
|
42
|
+
if (action === 'list' && !name) {
|
|
43
|
+
for (const [alias, origin] of load()) console.log(`${alias}\t${origin}`);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (action !== 'add' || !name || !validName.test(name) || !value || rest.length) {
|
|
47
|
+
throw new Error('usage: herdgate cloud add <lowercase-name> <https-url> | herdgate cloud list');
|
|
48
|
+
}
|
|
49
|
+
const origin = cloudOrigin(value);
|
|
50
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
51
|
+
const lock = join(dir, '.clouds-lock');
|
|
52
|
+
mkdirSync(lock);
|
|
53
|
+
const temp = `${path}.${randomUUID()}`;
|
|
54
|
+
try {
|
|
55
|
+
const clouds = load();
|
|
56
|
+
if (clouds.has(name) && clouds.get(name) !== origin) throw new Error('cloud name already points to a different origin; choose another name');
|
|
57
|
+
clouds.set(name, origin);
|
|
58
|
+
writeFileSync(temp, `${JSON.stringify(Object.fromEntries(clouds), null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
59
|
+
renameSync(temp, path);
|
|
60
|
+
} finally {
|
|
61
|
+
rmSync(temp, { force: true });
|
|
62
|
+
rmSync(lock, { force: true, recursive: true });
|
|
63
|
+
}
|
|
64
|
+
console.log(`${name}\t${origin}`);
|
|
65
|
+
}
|
package/bin/herdgate.mjs
CHANGED
|
@@ -5,29 +5,49 @@
|
|
|
5
5
|
//
|
|
6
6
|
// Installs the herdr-app mod and the publisher into the app's home, and
|
|
7
7
|
// prefills the panel's settings so the only thing left is Pair → Publish.
|
|
8
|
-
import { cpSync, mkdirSync, writeFileSync, existsSync, readFileSync, realpathSync } from "node:fs";
|
|
8
|
+
import { cpSync, mkdirSync, writeFileSync, existsSync, readFileSync, realpathSync, rmdirSync } from "node:fs";
|
|
9
9
|
import { join, dirname, basename } from "node:path";
|
|
10
10
|
import { homedir, hostname } from "node:os";
|
|
11
11
|
import { spawnSync } from "node:child_process";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { manageCloud, resolveCloud } from "./cloud-config.mjs";
|
|
14
|
+
import { readConfig } from "../plugin/server/common.mjs";
|
|
15
|
+
import { withLatest } from "../windows/npm-update.mjs";
|
|
13
16
|
|
|
14
17
|
const HERE = dirname(fileURLToPath(import.meta.url)); // <pkg>/bin
|
|
15
18
|
const ROOT = dirname(HERE); // <pkg>
|
|
16
19
|
|
|
17
20
|
const help = `herdgate — every machine, one herd
|
|
18
21
|
|
|
22
|
+
herdgate cloud add <name> <https-url>
|
|
23
|
+
herdgate cloud list
|
|
24
|
+
herdgate pair --cloud <name> Pair this machine with owner approval.
|
|
25
|
+
herdgate setup [--cloud <name>] [--mobile-act <device-id>]
|
|
26
|
+
Install/configure the publisher for this OS.
|
|
27
|
+
herdgate migrate [--mobile-act <device-id> | --plain]
|
|
28
|
+
Adopt an existing publisher without changing its cloud or pairing.
|
|
29
|
+
herdgate start | stop | status | update
|
|
30
|
+
Manage the publisher. Update fetches the latest npm release.
|
|
31
|
+
|
|
32
|
+
Compatibility commands:
|
|
19
33
|
herdgate setup-host [--cloud <url>] [--name <machine-name>] [--app-home <dir>]
|
|
20
34
|
Install the herdr-app mod + publisher and prefill the panel settings.
|
|
21
|
-
--cloud your gate, e.g. https://gate.
|
|
35
|
+
--cloud your gate, e.g. https://gate.example.com (required)
|
|
22
36
|
--name how this machine shows up on the phone (default: hostname)
|
|
23
37
|
--app-home herdr-app home (default: the platform's usual one)
|
|
24
38
|
--no-integrate skip the tab-bar panel integration (pane.split still works)
|
|
25
39
|
|
|
26
40
|
herdgate install-tui
|
|
27
41
|
Install or update the per-user Windows TUI publisher. Does not start it.
|
|
42
|
+
herdgate tui setup [path-to-herdr.exe] [--mobile-tui d_read | --mobile-tui-act d_act | --hc <exe>]
|
|
43
|
+
Install, start and save the selected publisher mode (existing pairing required).
|
|
44
|
+
herdgate tui update
|
|
45
|
+
Install this npm version and restart only the publisher, preserving its mode.
|
|
28
46
|
herdgate tui start [path-to-herdr.exe]
|
|
29
47
|
herdgate tui status | stop | version | versions | use <release-id>
|
|
30
|
-
Manage the installed publisher without adding it to PATH
|
|
48
|
+
Manage the installed publisher without adding it to PATH.
|
|
49
|
+
herdgate home-tui setup [--adopt] | status | restart | stop
|
|
50
|
+
Manage the Linux TUI publisher as a systemd user service.`;
|
|
31
51
|
|
|
32
52
|
function arg(name, fallback = undefined) {
|
|
33
53
|
const i = process.argv.indexOf(`--${name}`);
|
|
@@ -44,11 +64,8 @@ function appHome() {
|
|
|
44
64
|
}
|
|
45
65
|
|
|
46
66
|
function setupHost() {
|
|
47
|
-
const cloud = arg("cloud");
|
|
48
|
-
|
|
49
|
-
console.error(help);
|
|
50
|
-
process.exit(1);
|
|
51
|
-
}
|
|
67
|
+
const cloud = resolveCloud(arg("cloud"));
|
|
68
|
+
checkCloud(cloud);
|
|
52
69
|
const home = appHome();
|
|
53
70
|
const name = arg("name") ?? hostname();
|
|
54
71
|
|
|
@@ -242,13 +259,13 @@ function integrate(home) {
|
|
|
242
259
|
console.log(" the shipped layout `main` stays untouched (layout.switch main goes back).");
|
|
243
260
|
}
|
|
244
261
|
|
|
245
|
-
function runNode(file, args) {
|
|
246
|
-
const child = spawnSync(process.execPath, [file, ...args], { stdio: "inherit", shell: false, windowsHide: true });
|
|
262
|
+
function runNode(file, args, env = process.env) {
|
|
263
|
+
const child = spawnSync(process.execPath, [file, ...args], { env, stdio: "inherit", shell: false, windowsHide: true });
|
|
247
264
|
if (child.error) throw child.error;
|
|
248
265
|
process.exitCode = child.status ?? 1;
|
|
249
266
|
}
|
|
250
267
|
|
|
251
|
-
function runInstalledTui(args) {
|
|
268
|
+
function runInstalledTui(args, useSavedProfile = false) {
|
|
252
269
|
if (!process.env.LOCALAPPDATA) throw new Error("the TUI publisher CLI is for Windows (%LOCALAPPDATA% is unset)");
|
|
253
270
|
const root = join(process.env.LOCALAPPDATA, "Herdgate", "cli");
|
|
254
271
|
const current = join(root, "current");
|
|
@@ -259,20 +276,89 @@ function runInstalledTui(args) {
|
|
|
259
276
|
if (!/^tui-[a-f0-9]{16}$/.test(basename(release)) || key(dirname(release)) !== key(releases)) {
|
|
260
277
|
throw new Error("current does not point to an installed release; rerun install-tui");
|
|
261
278
|
}
|
|
262
|
-
runNode(join(release, "windows", "cli.mjs"), args);
|
|
279
|
+
runNode(join(release, "windows", useSavedProfile ? "setup-tui.mjs" : "cli.mjs"), args);
|
|
263
280
|
}
|
|
264
281
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
282
|
+
function pairedConfig() {
|
|
283
|
+
const base = join(appHome(), "herdgate");
|
|
284
|
+
const config = join(base, "config");
|
|
285
|
+
return { base, config, current: readConfig(join(config, "herdgate.env")) };
|
|
286
|
+
}
|
|
287
|
+
function checkCloud(origin) {
|
|
288
|
+
const { current } = pairedConfig();
|
|
289
|
+
if (current.HERDGATE_ROOM_TOKEN && origin && resolveCloud(current.HERDGATE_URL) !== origin) {
|
|
290
|
+
throw new Error("this machine is already paired to another cloud; adding a cloud does not move a pairing");
|
|
291
|
+
}
|
|
292
|
+
return Boolean(current.HERDGATE_ROOM_TOKEN);
|
|
293
|
+
}
|
|
294
|
+
function cloudOption(args) {
|
|
295
|
+
const out = [...args];
|
|
296
|
+
const i = out.indexOf("--cloud");
|
|
297
|
+
if (i < 0) return { options: out };
|
|
298
|
+
const value = out[i + 1];
|
|
299
|
+
if (!value || value.startsWith("--")) throw new Error("--cloud requires a configured name or HTTPS URL");
|
|
300
|
+
out.splice(i, 2);
|
|
301
|
+
if (out.includes("--cloud")) throw new Error("only one --cloud value is allowed");
|
|
302
|
+
return { options: out, origin: resolveCloud(value) };
|
|
303
|
+
}
|
|
304
|
+
function pairHost(args) {
|
|
305
|
+
const { options, origin } = cloudOption(args);
|
|
306
|
+
if (!origin || options.length) throw new Error("usage: herdgate pair --cloud <name>");
|
|
307
|
+
const { base, config } = pairedConfig();
|
|
308
|
+
mkdirSync(config, { recursive: true, mode: 0o700 });
|
|
309
|
+
const lock = join(config, ".pairing");
|
|
310
|
+
mkdirSync(lock);
|
|
268
311
|
try {
|
|
269
|
-
if (
|
|
312
|
+
if (checkCloud(origin)) { console.log("herdgate: already paired to this cloud"); return; }
|
|
313
|
+
// Pairing is explicit and still needs approval; the room token stays in host config.
|
|
314
|
+
runNode(join(ROOT, "plugin", "server", "index.mjs"), ["pair"], {
|
|
315
|
+
...process.env, HERDGATE_URL: origin,
|
|
316
|
+
HERDR_PLUGIN_CONFIG_DIR: config, HERDR_PLUGIN_STATE_DIR: join(base, "state"),
|
|
317
|
+
});
|
|
318
|
+
} finally { rmdirSync(lock); }
|
|
319
|
+
}
|
|
320
|
+
function managePublisher(cmd, args) {
|
|
321
|
+
const { origin, options } = cloudOption(args);
|
|
322
|
+
if (!["setup", "migrate"].includes(cmd) && origin) throw new Error("--cloud is only used with setup, migrate or pair");
|
|
323
|
+
if (["setup", "migrate"].includes(cmd) && !checkCloud(origin)) {
|
|
324
|
+
throw new Error("this machine is not paired; run herdgate pair --cloud <name> first");
|
|
325
|
+
}
|
|
326
|
+
const win = process.platform === "win32";
|
|
327
|
+
if (!win && process.platform !== "linux") throw new Error("publisher management requires Windows or Linux with systemd");
|
|
328
|
+
if (cmd === "update") {
|
|
329
|
+
if (options.length) throw new Error("usage: herdgate update");
|
|
330
|
+
return withLatest((pkg) => runNode(join(pkg, "bin", "herdgate.mjs"), win ? ["tui", "update"] : ["home-tui", "setup"]));
|
|
331
|
+
}
|
|
332
|
+
if (win) {
|
|
333
|
+
const flags = options.map(flag => flag === "--mobile-act" ? "--mobile-tui-act" : flag === "--mobile-read" ? "--mobile-tui" : flag);
|
|
334
|
+
if (cmd === "setup" || cmd === "migrate") return runNode(join(ROOT, "windows", "setup-tui.mjs"), [cmd, ...flags]);
|
|
335
|
+
// Starting must not reinstall an older globally installed npm package.
|
|
336
|
+
if (cmd === "start") return runInstalledTui(["setup", ...flags], true);
|
|
337
|
+
return runInstalledTui([cmd, ...flags]);
|
|
338
|
+
}
|
|
339
|
+
if (cmd === "migrate") {
|
|
340
|
+
if (options.length) throw new Error("usage: herdgate migrate [--cloud <name>]");
|
|
341
|
+
return runNode(join(HERE, "home-tui.mjs"), ["setup", "--adopt"]);
|
|
342
|
+
}
|
|
343
|
+
return runNode(join(HERE, "home-tui.mjs"), [cmd, ...options]);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
347
|
+
try {
|
|
348
|
+
if (cmd === "setup-host") setupHost();
|
|
349
|
+
else if (cmd === "cloud") manageCloud(args);
|
|
350
|
+
else if (cmd === "pair") pairHost(args);
|
|
351
|
+
else if (["setup", "migrate", "start", "stop", "status", "update"].includes(cmd)) managePublisher(cmd, args);
|
|
352
|
+
else if (cmd === "home-tui") runNode(join(HERE, "home-tui.mjs"), args);
|
|
353
|
+
else if (cmd === "install-tui") runNode(join(ROOT, "windows", "install-cli.mjs"), args);
|
|
354
|
+
else if (cmd === "tui") {
|
|
355
|
+
if (["setup", "migrate", "update"].includes(args[0])) runNode(join(ROOT, "windows", "setup-tui.mjs"), args);
|
|
270
356
|
else runInstalledTui(args);
|
|
271
|
-
}
|
|
272
|
-
console.
|
|
273
|
-
process.exitCode = 1;
|
|
357
|
+
} else {
|
|
358
|
+
console.log(help);
|
|
359
|
+
process.exitCode = !cmd || cmd === "help" || cmd === "--help" ? 0 : 1;
|
|
274
360
|
}
|
|
275
|
-
}
|
|
276
|
-
console.
|
|
277
|
-
process.
|
|
361
|
+
} catch (e) {
|
|
362
|
+
console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
|
|
363
|
+
process.exitCode = 1;
|
|
278
364
|
}
|
package/bin/home-tui.mjs
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Linux user service, with a durable release outside npm's cache.
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
|
+
import { readConfig } from '../plugin/server/common.mjs';
|
|
11
|
+
|
|
12
|
+
const unit = 'herdgate-home-tui.service';
|
|
13
|
+
const marker = '# Managed by Herdgate CLI\n';
|
|
14
|
+
const configHome = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
|
|
15
|
+
const dataHome = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
|
|
16
|
+
const appHome = process.env.HERDR_APP_HOME || join(homedir(), '.config', 'herdr-app');
|
|
17
|
+
const root = join(dataHome, 'herdgate', 'home-tui');
|
|
18
|
+
const unitFile = join(configHome, 'systemd', 'user', unit);
|
|
19
|
+
const systemctl = (...args) => execFileSync('systemctl', ['--user', ...args], { stdio: 'inherit', timeout: 25_000 });
|
|
20
|
+
function capture(file, args) {
|
|
21
|
+
try { return execFileSync(file, args, { encoding: 'utf8', timeout: 2_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim(); }
|
|
22
|
+
catch { return ''; }
|
|
23
|
+
}
|
|
24
|
+
const invocation = () => capture('systemctl', ['--user', 'show', '--property=InvocationID', '--value', unit]);
|
|
25
|
+
async function waitForGate(origin, previous) {
|
|
26
|
+
const deadline = Date.now() + 8_000;
|
|
27
|
+
do {
|
|
28
|
+
const id = invocation();
|
|
29
|
+
if (/^[a-f0-9]{32}$/.test(id) && id !== '0'.repeat(32) && id !== previous) {
|
|
30
|
+
const events = capture('journalctl', ['--user', '--unit', unit, '--no-pager', '--output=cat',
|
|
31
|
+
'--grep=^herdgate: (connected to |(disconnected|ws error);)', '-n', '1', `_SYSTEMD_INVOCATION_ID=${id}`]);
|
|
32
|
+
const endpoint = events.match(/^herdgate: connected to (\S+) /)?.[1];
|
|
33
|
+
if (endpoint) {
|
|
34
|
+
try { if (new URL(endpoint).origin === origin && invocation() === id) return; }
|
|
35
|
+
catch { /* wait for a valid hello */ }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
await delay(250);
|
|
39
|
+
} while (Date.now() < deadline);
|
|
40
|
+
throw new Error('the new publisher did not receive a Gate hello; check its systemd journal');
|
|
41
|
+
}
|
|
42
|
+
function replace(path, value) {
|
|
43
|
+
const tmp = `${path}.${randomUUID()}`;
|
|
44
|
+
try {
|
|
45
|
+
writeFileSync(tmp, value, { flag: 'wx', mode: 0o600 });
|
|
46
|
+
renameSync(tmp, path);
|
|
47
|
+
} finally { rmSync(tmp, { force: true }); }
|
|
48
|
+
}
|
|
49
|
+
function installedUnit() {
|
|
50
|
+
if (!existsSync(unitFile)) return null;
|
|
51
|
+
if (!lstatSync(unitFile).isFile()) throw new Error(`refusing to use a non-regular unit: ${unitFile}`);
|
|
52
|
+
return readFileSync(unitFile, 'utf8');
|
|
53
|
+
}
|
|
54
|
+
function legacyUnit(text) {
|
|
55
|
+
return text.startsWith('[Unit]\nDescription=Herdgate publisher for the home Herdr TUI\n') &&
|
|
56
|
+
text.includes('Environment=HERDR_PLUGIN_CONFIG_DIR=%h/.config/herdr-app/herdgate/config\n') &&
|
|
57
|
+
/^ExecStart=%h\/\.nvm\/versions\/node\/v\d+\.\d+\.\d+\/bin\/node %h\/source\/herdgate\/plugin\/server\/index\.mjs serve$/m.test(text);
|
|
58
|
+
}
|
|
59
|
+
const sysPath = (value) => {
|
|
60
|
+
if (!isAbsolute(value) || /[\r\n\0]/.test(value)) throw new Error('systemd paths must be absolute and on one line');
|
|
61
|
+
return '"' + value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%') + '"';
|
|
62
|
+
};
|
|
63
|
+
function release() {
|
|
64
|
+
const server = fileURLToPath(new URL('../plugin/server/', import.meta.url));
|
|
65
|
+
const require = createRequire(import.meta.url);
|
|
66
|
+
const wsManifest = require.resolve('ws/package.json');
|
|
67
|
+
const runtime = readdirSync(server).filter(n => n.endsWith('.mjs')).sort();
|
|
68
|
+
const hash = createHash('sha256').update(readFileSync(wsManifest));
|
|
69
|
+
for (const name of runtime) hash.update(name + '\0').update(readFileSync(join(server, name)));
|
|
70
|
+
const releases = join(root, 'releases');
|
|
71
|
+
mkdirSync(releases, { recursive: true, mode: 0o700 });
|
|
72
|
+
const dest = join(releases, hash.digest('hex').slice(0, 24));
|
|
73
|
+
if (!existsSync(dest)) {
|
|
74
|
+
const stage = mkdtempSync(join(releases, '.stage-'));
|
|
75
|
+
try {
|
|
76
|
+
const plugin = join(stage, 'plugin', 'server');
|
|
77
|
+
mkdirSync(plugin, { recursive: true });
|
|
78
|
+
for (const name of runtime) cpSync(join(server, name), join(plugin, name));
|
|
79
|
+
mkdirSync(join(stage, 'node_modules'));
|
|
80
|
+
cpSync(dirname(wsManifest), join(stage, 'node_modules', 'ws'), { recursive: true });
|
|
81
|
+
renameSync(stage, dest);
|
|
82
|
+
} finally { rmSync(stage, { force: true, recursive: true }); }
|
|
83
|
+
}
|
|
84
|
+
if (!lstatSync(dest).isDirectory()) throw new Error('invalid installed TUI release');
|
|
85
|
+
return dest;
|
|
86
|
+
}
|
|
87
|
+
async function setup(args) {
|
|
88
|
+
const adopt = args.includes('--adopt');
|
|
89
|
+
if (args.some(a => a !== '--adopt')) throw new Error('usage: herdgate home-tui setup [--adopt]');
|
|
90
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
91
|
+
const lock = join(root, '.installing');
|
|
92
|
+
mkdirSync(lock);
|
|
93
|
+
try {
|
|
94
|
+
const old = installedUnit();
|
|
95
|
+
if (old && !old.startsWith(marker) && !(adopt && legacyUnit(old))) {
|
|
96
|
+
throw new Error('existing service is not CLI-managed; only the previous Herdgate home service can be migrated with --adopt');
|
|
97
|
+
}
|
|
98
|
+
const herdr = process.env.HERDR_BIN_PATH || join(homedir(), '.local', 'bin', 'herdr');
|
|
99
|
+
const socket = process.env.HERDR_SOCKET_PATH || join(configHome, 'herdr', 'herdr.sock');
|
|
100
|
+
const config = join(appHome, 'herdgate', 'config');
|
|
101
|
+
const state = join(appHome, 'herdgate', 'state');
|
|
102
|
+
const cfg = readConfig(join(config, 'herdgate.env'));
|
|
103
|
+
if (!cfg.HERDGATE_ROOM_TOKEN || !cfg.HERDGATE_URL) throw new Error('pair the home room first; herdgate.env is missing or incomplete');
|
|
104
|
+
const gate = new URL(cfg.HERDGATE_URL);
|
|
105
|
+
if (gate.protocol !== 'https:' || gate.username || gate.password || gate.pathname !== '/' || gate.search || gate.hash) {
|
|
106
|
+
throw new Error('a credential-free HTTPS Gate origin is required');
|
|
107
|
+
}
|
|
108
|
+
for (const path of [herdr, socket, config, state, root]) sysPath(path);
|
|
109
|
+
const status = JSON.parse(execFileSync(herdr, ['status', 'server', '--json'], { encoding: 'utf8', timeout: 5_000, env: { ...process.env, HERDR_SOCKET_PATH: socket, HERDR_SESSION: 'default' } }));
|
|
110
|
+
if (!status.running || status.compatible !== true) throw new Error('start a compatible Herdr TUI server before running setup');
|
|
111
|
+
const runtime = release();
|
|
112
|
+
const env = { HERDGATE_PUBLISHER_CHILD:'1', HERDR_PLUGIN_ID:'dev.herdgate.host', HERDR_PLUGIN_CONFIG_DIR:config, HERDR_PLUGIN_STATE_DIR:state, HERDR_BIN_PATH:herdr, HERDR_SOCKET_PATH:socket, HERDGATE_HERDR_SESSION:'default' };
|
|
113
|
+
const lines = Object.entries(env).map(([k, v]) => `Environment=${isAbsolute(v) ? sysPath(`${v}`).replace(/^"/, `"${k}=`) : `${k}=${v}`}`).join('\n');
|
|
114
|
+
const next = `${marker}[Unit]\nDescription=Herdgate publisher for the home Herdr TUI\nAfter=network.target herdgate.service\n\n[Service]\nType=simple\n${lines}\nExecStart=:${sysPath(process.execPath)} ${sysPath(join(runtime,'plugin/server/index.mjs'))} serve\nRestart=always\nRestartSec=2\nUMask=0077\nNoNewPrivileges=true\n\n[Install]\nWantedBy=default.target\n`;
|
|
115
|
+
mkdirSync(dirname(unitFile), { recursive: true });
|
|
116
|
+
const wasActive = capture('systemctl', ['--user', 'is-active', unit]) === 'active';
|
|
117
|
+
const changed = old !== next;
|
|
118
|
+
const previous = changed && wasActive ? invocation() : '';
|
|
119
|
+
if (changed) replace(unitFile, next);
|
|
120
|
+
try {
|
|
121
|
+
if (changed) systemctl('daemon-reload');
|
|
122
|
+
systemctl(changed && wasActive ? 'restart' : 'start', unit);
|
|
123
|
+
await waitForGate(gate.origin, previous);
|
|
124
|
+
systemctl('enable', unit);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (changed) {
|
|
127
|
+
try {
|
|
128
|
+
systemctl('stop', unit);
|
|
129
|
+
if (!old) systemctl('disable', unit);
|
|
130
|
+
if (old) replace(unitFile, old); else rmSync(unitFile, { force: true });
|
|
131
|
+
systemctl('daemon-reload');
|
|
132
|
+
if (old && wasActive) systemctl('start', unit);
|
|
133
|
+
} catch (rollback) {
|
|
134
|
+
throw new Error(`${error.message}; rollback could not finish: ${rollback.message}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
console.log('Herdgate publisher connected to Gate; no Herdr process was restarted.');
|
|
140
|
+
} finally { rmSync(lock, { recursive: true, force: true }); }
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const [action, ...args] = process.argv.slice(2);
|
|
144
|
+
if (process.platform !== 'linux') throw new Error('home-tui requires Linux with a systemd user manager');
|
|
145
|
+
if (action === 'setup') await setup(args);
|
|
146
|
+
else if (!args.length && ['start', 'status', 'restart', 'stop'].includes(action)) {
|
|
147
|
+
const existing = installedUnit();
|
|
148
|
+
if (!existing || !(existing.startsWith(marker) || legacyUnit(existing))) throw new Error('run herdgate home-tui setup first');
|
|
149
|
+
systemctl(action, ...(action === 'status' ? ['--no-pager'] : []), unit);
|
|
150
|
+
} else throw new Error('usage: herdgate home-tui setup [--adopt] | start | status | restart | stop');
|
|
151
|
+
} catch (error) {
|
|
152
|
+
console.error('herdgate home-tui: ' + error.message);
|
|
153
|
+
process.exitCode = 1;
|
|
154
|
+
}
|
package/dist-readme.md
CHANGED
|
@@ -28,10 +28,10 @@ phone/PWA của bạn.
|
|
|
28
28
|
|
|
29
29
|
3. Mở (hoặc restart) herdr app → panel **herdgate** xuất hiện.
|
|
30
30
|
4. Trong panel điền:
|
|
31
|
-
- **cloud**: `https://gate.
|
|
31
|
+
- **cloud**: `https://gate.example.com`
|
|
32
32
|
- **herdgate folder**: đường dẫn tới thư mục `plugin` của bộ này (chứa `server/index.mjs`)
|
|
33
33
|
- **name**: tên máy (hiện trên PWA)
|
|
34
|
-
5. **Pair** → panel hiện mã code → mở PWA
|
|
34
|
+
5. **Pair** → panel hiện mã code → mở PWA địa chỉ Gate đã cấu hình trên phone/browser bất kỳ,
|
|
35
35
|
Approve → xong. Nhấn **Publish**.
|
|
36
36
|
|
|
37
37
|
Máy giờ hiện trong PWA; phone pair thiết bị riêng để xem terminal.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bom0792/herdgate",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.27",
|
|
4
4
|
"description": "Cloud relay hub for herdr-core: every machine dials out, phones and browsers follow (PWA + SSH leg, E2E payloads).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
"test": "node --test test/*.test.ts",
|
|
14
14
|
"check": "tsc -p tsconfig.json",
|
|
15
15
|
"ssh-bridge": "node src/cloud/ssh-bridge.ts",
|
|
16
|
+
"ssh-tcp-edge": "node src/cloud/ssh-tcp-edge.ts",
|
|
17
|
+
"mobile-tui": "node src/host/mobile-tui.ts",
|
|
16
18
|
"postinstall": "node scripts/patch-ssh2.mjs"
|
|
17
19
|
},
|
|
18
20
|
"dependencies": {
|
package/plugin/server/index.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { spawn } from "node:child_process";
|
|
|
10
10
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
|
|
11
11
|
import { join, dirname } from "node:path";
|
|
12
12
|
import { hostname, homedir } from "node:os";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
13
14
|
import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize, herdrPanes, herdrRead } from "./common.mjs";
|
|
14
15
|
import { createSshBridge } from "./ssh.mjs";
|
|
15
16
|
import { registerPublisher } from "./publisher-tui-lifecycle.mjs";
|
|
@@ -259,6 +260,12 @@ async function publisherLoop() {
|
|
|
259
260
|
const ssh = createSshBridge({
|
|
260
261
|
session: cfg.HERDGATE_HERDR_SESSION || undefined,
|
|
261
262
|
tuiOnly: process.env.HERDGATE_TUI_ONLY === "1",
|
|
263
|
+
mobileHcBin: process.env.HERDGATE_MOBILE_HC_BIN || null,
|
|
264
|
+
mobileTuiAdapter: process.env.HERDGATE_MOBILE_TUI_DEVICE ? {
|
|
265
|
+
device: process.env.HERDGATE_MOBILE_TUI_DEVICE,
|
|
266
|
+
scope: process.env.HERDGATE_MOBILE_TUI_SCOPE === "act" ? "act" : "read",
|
|
267
|
+
script: fileURLToPath(new URL("./mobile-tui-core.mjs", import.meta.url)),
|
|
268
|
+
} : null,
|
|
262
269
|
send: (device, payload) => {
|
|
263
270
|
// sshd is the SSH endpoint; a concurrent PWA session must not seal these frames.
|
|
264
271
|
if (wsRef?.readyState === 1) wsRef.send(JSON.stringify({ v: 1, t: "frame", device, payload }));
|