@bom0792/herdgate 0.9.26 → 0.9.28
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 +31 -1
- package/bin/cloud-config.mjs +65 -0
- package/bin/herdgate.mjs +110 -23
- package/bin/home-tui.mjs +47 -14
- package/dist-readme.md +2 -2
- package/package.json +1 -1
- package/scripts/deploy-vps.sh +10 -5
- package/src/host/mobile-tui.ts +2 -1
- package/templates/herdgate-via.mjs +12 -2
- package/windows/cli.mjs +18 -3
- package/windows/install-cli.mjs +6 -3
- package/windows/node-runtime.mjs +26 -0
- package/windows/npm-update.mjs +26 -0
- package/windows/setup-tui.mjs +9 -4
package/README.md
CHANGED
|
@@ -178,6 +178,36 @@ 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.
|
|
@@ -194,7 +224,7 @@ migration from a manual install needs the desired mode once; it is saved
|
|
|
194
224
|
locally only after the publisher connects. For subsequent updates:
|
|
195
225
|
|
|
196
226
|
```powershell
|
|
197
|
-
|
|
227
|
+
herdgate update
|
|
198
228
|
```
|
|
199
229
|
|
|
200
230
|
The update validates the new release before touching the old publisher. It
|
|
@@ -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,20 +5,35 @@
|
|
|
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";
|
|
16
|
+
import { windowsNode } from "../windows/node-runtime.mjs";
|
|
13
17
|
|
|
14
18
|
const HERE = dirname(fileURLToPath(import.meta.url)); // <pkg>/bin
|
|
15
19
|
const ROOT = dirname(HERE); // <pkg>
|
|
16
20
|
|
|
17
21
|
const help = `herdgate — every machine, one herd
|
|
18
22
|
|
|
23
|
+
herdgate cloud add <name> <https-url>
|
|
24
|
+
herdgate cloud list
|
|
25
|
+
herdgate pair --cloud <name> Pair this machine with owner approval.
|
|
26
|
+
herdgate setup [--cloud <name>] [--mobile-act <device-id>]
|
|
27
|
+
Install/configure the publisher for this OS.
|
|
28
|
+
herdgate migrate [--mobile-act <device-id> | --plain]
|
|
29
|
+
Adopt an existing publisher without changing its cloud or pairing.
|
|
30
|
+
herdgate start | stop | status | update
|
|
31
|
+
Manage the publisher. Update fetches the latest npm release.
|
|
32
|
+
|
|
33
|
+
Compatibility commands:
|
|
19
34
|
herdgate setup-host [--cloud <url>] [--name <machine-name>] [--app-home <dir>]
|
|
20
35
|
Install the herdr-app mod + publisher and prefill the panel settings.
|
|
21
|
-
--cloud your gate, e.g. https://gate.
|
|
36
|
+
--cloud your gate, e.g. https://gate.example.com (required)
|
|
22
37
|
--name how this machine shows up on the phone (default: hostname)
|
|
23
38
|
--app-home herdr-app home (default: the platform's usual one)
|
|
24
39
|
--no-integrate skip the tab-bar panel integration (pane.split still works)
|
|
@@ -50,11 +65,8 @@ function appHome() {
|
|
|
50
65
|
}
|
|
51
66
|
|
|
52
67
|
function setupHost() {
|
|
53
|
-
const cloud = arg("cloud");
|
|
54
|
-
|
|
55
|
-
console.error(help);
|
|
56
|
-
process.exit(1);
|
|
57
|
-
}
|
|
68
|
+
const cloud = resolveCloud(arg("cloud"));
|
|
69
|
+
checkCloud(cloud);
|
|
58
70
|
const home = appHome();
|
|
59
71
|
const name = arg("name") ?? hostname();
|
|
60
72
|
|
|
@@ -248,13 +260,13 @@ function integrate(home) {
|
|
|
248
260
|
console.log(" the shipped layout `main` stays untouched (layout.switch main goes back).");
|
|
249
261
|
}
|
|
250
262
|
|
|
251
|
-
function runNode(file, args) {
|
|
252
|
-
const child = spawnSync(process.execPath, [file, ...args], { stdio: "inherit", shell: false, windowsHide: true });
|
|
263
|
+
function runNode(file, args, env = process.env) {
|
|
264
|
+
const child = spawnSync(process.execPath, [file, ...args], { env, stdio: "inherit", shell: false, windowsHide: true });
|
|
253
265
|
if (child.error) throw child.error;
|
|
254
266
|
process.exitCode = child.status ?? 1;
|
|
255
267
|
}
|
|
256
268
|
|
|
257
|
-
function runInstalledTui(args) {
|
|
269
|
+
function runInstalledTui(args, useSavedProfile = false) {
|
|
258
270
|
if (!process.env.LOCALAPPDATA) throw new Error("the TUI publisher CLI is for Windows (%LOCALAPPDATA% is unset)");
|
|
259
271
|
const root = join(process.env.LOCALAPPDATA, "Herdgate", "cli");
|
|
260
272
|
const current = join(root, "current");
|
|
@@ -265,22 +277,97 @@ function runInstalledTui(args) {
|
|
|
265
277
|
if (!/^tui-[a-f0-9]{16}$/.test(basename(release)) || key(dirname(release)) !== key(releases)) {
|
|
266
278
|
throw new Error("current does not point to an installed release; rerun install-tui");
|
|
267
279
|
}
|
|
268
|
-
runNode(join(release, "windows", "cli.mjs"), args);
|
|
280
|
+
runNode(join(release, "windows", useSavedProfile ? "setup-tui.mjs" : "cli.mjs"), args);
|
|
269
281
|
}
|
|
270
282
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
283
|
+
function pairedConfig() {
|
|
284
|
+
const base = join(appHome(), "herdgate");
|
|
285
|
+
const config = join(base, "config");
|
|
286
|
+
return { base, config, current: readConfig(join(config, "herdgate.env")) };
|
|
287
|
+
}
|
|
288
|
+
function checkCloud(origin) {
|
|
289
|
+
const { current } = pairedConfig();
|
|
290
|
+
if (current.HERDGATE_ROOM_TOKEN && origin && resolveCloud(current.HERDGATE_URL) !== origin) {
|
|
291
|
+
throw new Error("this machine is already paired to another cloud; adding a cloud does not move a pairing");
|
|
292
|
+
}
|
|
293
|
+
return Boolean(current.HERDGATE_ROOM_TOKEN);
|
|
294
|
+
}
|
|
295
|
+
function cloudOption(args) {
|
|
296
|
+
const out = [...args];
|
|
297
|
+
const i = out.indexOf("--cloud");
|
|
298
|
+
if (i < 0) return { options: out };
|
|
299
|
+
const value = out[i + 1];
|
|
300
|
+
if (!value || value.startsWith("--")) throw new Error("--cloud requires a configured name or HTTPS URL");
|
|
301
|
+
out.splice(i, 2);
|
|
302
|
+
if (out.includes("--cloud")) throw new Error("only one --cloud value is allowed");
|
|
303
|
+
return { options: out, origin: resolveCloud(value) };
|
|
304
|
+
}
|
|
305
|
+
function pairHost(args) {
|
|
306
|
+
const { options, origin } = cloudOption(args);
|
|
307
|
+
if (!origin || options.length) throw new Error("usage: herdgate pair --cloud <name>");
|
|
308
|
+
const { base, config } = pairedConfig();
|
|
309
|
+
mkdirSync(config, { recursive: true, mode: 0o700 });
|
|
310
|
+
const lock = join(config, ".pairing");
|
|
311
|
+
mkdirSync(lock);
|
|
274
312
|
try {
|
|
275
|
-
if (
|
|
276
|
-
|
|
277
|
-
|
|
313
|
+
if (checkCloud(origin)) { console.log("herdgate: already paired to this cloud"); return; }
|
|
314
|
+
// Pairing is explicit and still needs approval; the room token stays in host config.
|
|
315
|
+
runNode(join(ROOT, "plugin", "server", "index.mjs"), ["pair"], {
|
|
316
|
+
...process.env, HERDGATE_URL: origin,
|
|
317
|
+
HERDR_PLUGIN_CONFIG_DIR: config, HERDR_PLUGIN_STATE_DIR: join(base, "state"),
|
|
318
|
+
});
|
|
319
|
+
} finally { rmdirSync(lock); }
|
|
320
|
+
}
|
|
321
|
+
function managePublisher(cmd, args) {
|
|
322
|
+
const { origin, options } = cloudOption(args);
|
|
323
|
+
if (!["setup", "migrate"].includes(cmd) && origin) throw new Error("--cloud is only used with setup, migrate or pair");
|
|
324
|
+
if (["setup", "migrate"].includes(cmd) && !checkCloud(origin)) {
|
|
325
|
+
throw new Error("this machine is not paired; run herdgate pair --cloud <name> first");
|
|
326
|
+
}
|
|
327
|
+
const win = process.platform === "win32";
|
|
328
|
+
if (!win && process.platform !== "linux") throw new Error("publisher management requires Windows or Linux with systemd");
|
|
329
|
+
if (cmd === "update") {
|
|
330
|
+
if (options.length) throw new Error("usage: herdgate update");
|
|
331
|
+
return withLatest((pkg) => runNode(join(pkg, "bin", "herdgate.mjs"), win ? ["tui", "update"] : ["home-tui", "setup"]));
|
|
332
|
+
}
|
|
333
|
+
if (win) {
|
|
334
|
+
const flags = options.map(flag => flag === "--mobile-act" ? "--mobile-tui-act" : flag === "--mobile-read" ? "--mobile-tui" : flag);
|
|
335
|
+
if (cmd === "setup" || cmd === "migrate") return runNode(join(ROOT, "windows", "setup-tui.mjs"), [cmd, ...flags]);
|
|
336
|
+
// Starting must not reinstall an older globally installed npm package.
|
|
337
|
+
if (cmd === "start") return runInstalledTui(["setup", ...flags], true);
|
|
338
|
+
return runInstalledTui([cmd, ...flags]);
|
|
339
|
+
}
|
|
340
|
+
if (cmd === "migrate") {
|
|
341
|
+
if (options.length) throw new Error("usage: herdgate migrate [--cloud <name>]");
|
|
342
|
+
return runNode(join(HERE, "home-tui.mjs"), ["setup", "--adopt"]);
|
|
343
|
+
}
|
|
344
|
+
return runNode(join(HERE, "home-tui.mjs"), [cmd, ...options]);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
348
|
+
try {
|
|
349
|
+
if (cmd === "setup-host") setupHost();
|
|
350
|
+
else if (cmd === "cloud") manageCloud(args);
|
|
351
|
+
else if (cmd === "pair") pairHost(args);
|
|
352
|
+
else if (process.platform === "win32" && (
|
|
353
|
+
["setup", "migrate", "start", "update", "install-tui"].includes(cmd) ||
|
|
354
|
+
(cmd === "tui" && ["setup", "migrate", "start", "update"].includes(args[0]))
|
|
355
|
+
) && (Number(process.versions.node.split(".")[0]) < 22 || typeof globalThis.WebSocket !== "function")) {
|
|
356
|
+
const node = windowsNode();
|
|
357
|
+
const r = spawnSync(node, [fileURLToPath(import.meta.url), cmd, ...args], { stdio: "inherit", shell: false, windowsHide: true });
|
|
358
|
+
if (r.error) throw r.error;
|
|
359
|
+
process.exitCode = r.status ?? 1;
|
|
360
|
+
} else if (["setup", "migrate", "start", "stop", "status", "update"].includes(cmd)) managePublisher(cmd, args);
|
|
361
|
+
else if (cmd === "home-tui") runNode(join(HERE, "home-tui.mjs"), args);
|
|
362
|
+
else if (cmd === "install-tui") runNode(join(ROOT, "windows", "install-cli.mjs"), args);
|
|
363
|
+
else if (cmd === "tui") {
|
|
364
|
+
if (["setup", "migrate", "update"].includes(args[0])) runNode(join(ROOT, "windows", "setup-tui.mjs"), args);
|
|
278
365
|
else runInstalledTui(args);
|
|
279
|
-
}
|
|
280
|
-
console.
|
|
281
|
-
process.exitCode = 1;
|
|
366
|
+
} else {
|
|
367
|
+
console.log(help);
|
|
368
|
+
process.exitCode = !cmd || cmd === "help" || cmd === "--help" ? 0 : 1;
|
|
282
369
|
}
|
|
283
|
-
}
|
|
284
|
-
console.
|
|
285
|
-
process.
|
|
370
|
+
} catch (e) {
|
|
371
|
+
console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
|
|
372
|
+
process.exitCode = 1;
|
|
286
373
|
}
|
package/bin/home-tui.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { createRequire } from 'node:module';
|
|
|
6
6
|
import { homedir } from 'node:os';
|
|
7
7
|
import { dirname, isAbsolute, join } from 'node:path';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
10
|
import { readConfig } from '../plugin/server/common.mjs';
|
|
10
11
|
|
|
11
12
|
const unit = 'herdgate-home-tui.service';
|
|
@@ -16,6 +17,28 @@ const appHome = process.env.HERDR_APP_HOME || join(homedir(), '.config', 'herdr-
|
|
|
16
17
|
const root = join(dataHome, 'herdgate', 'home-tui');
|
|
17
18
|
const unitFile = join(configHome, 'systemd', 'user', unit);
|
|
18
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
|
+
}
|
|
19
42
|
function replace(path, value) {
|
|
20
43
|
const tmp = `${path}.${randomUUID()}`;
|
|
21
44
|
try {
|
|
@@ -79,7 +102,9 @@ async function setup(args) {
|
|
|
79
102
|
const cfg = readConfig(join(config, 'herdgate.env'));
|
|
80
103
|
if (!cfg.HERDGATE_ROOM_TOKEN || !cfg.HERDGATE_URL) throw new Error('pair the home room first; herdgate.env is missing or incomplete');
|
|
81
104
|
const gate = new URL(cfg.HERDGATE_URL);
|
|
82
|
-
if (gate.protocol !== 'https:' || gate.username || gate.password
|
|
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
|
+
}
|
|
83
108
|
for (const path of [herdr, socket, config, state, root]) sysPath(path);
|
|
84
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' } }));
|
|
85
110
|
if (!status.running || status.compatible !== true) throw new Error('start a compatible Herdr TUI server before running setup');
|
|
@@ -88,33 +113,41 @@ async function setup(args) {
|
|
|
88
113
|
const lines = Object.entries(env).map(([k, v]) => `Environment=${isAbsolute(v) ? sysPath(`${v}`).replace(/^"/, `"${k}=`) : `${k}=${v}`}`).join('\n');
|
|
89
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`;
|
|
90
115
|
mkdirSync(dirname(unitFile), { recursive: true });
|
|
91
|
-
|
|
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);
|
|
92
120
|
try {
|
|
93
|
-
if (
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
} else systemctl('enable', '--now', unit);
|
|
121
|
+
if (changed) systemctl('daemon-reload');
|
|
122
|
+
systemctl(changed && wasActive ? 'restart' : 'start', unit);
|
|
123
|
+
await waitForGate(gate.origin, previous);
|
|
124
|
+
systemctl('enable', unit);
|
|
98
125
|
} catch (error) {
|
|
99
|
-
if (
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
+
}
|
|
103
136
|
}
|
|
104
137
|
throw error;
|
|
105
138
|
}
|
|
106
|
-
console.log('Herdgate
|
|
139
|
+
console.log('Herdgate publisher connected to Gate; no Herdr process was restarted.');
|
|
107
140
|
} finally { rmSync(lock, { recursive: true, force: true }); }
|
|
108
141
|
}
|
|
109
142
|
try {
|
|
110
143
|
const [action, ...args] = process.argv.slice(2);
|
|
111
144
|
if (process.platform !== 'linux') throw new Error('home-tui requires Linux with a systemd user manager');
|
|
112
145
|
if (action === 'setup') await setup(args);
|
|
113
|
-
else if (!args.length && ['status', 'restart', 'stop'].includes(action)) {
|
|
146
|
+
else if (!args.length && ['start', 'status', 'restart', 'stop'].includes(action)) {
|
|
114
147
|
const existing = installedUnit();
|
|
115
148
|
if (!existing || !(existing.startsWith(marker) || legacyUnit(existing))) throw new Error('run herdgate home-tui setup first');
|
|
116
149
|
systemctl(action, ...(action === 'status' ? ['--no-pager'] : []), unit);
|
|
117
|
-
} else throw new Error('usage: herdgate home-tui setup [--adopt] | status | restart | stop');
|
|
150
|
+
} else throw new Error('usage: herdgate home-tui setup [--adopt] | start | status | restart | stop');
|
|
118
151
|
} catch (error) {
|
|
119
152
|
console.error('herdgate home-tui: ' + error.message);
|
|
120
153
|
process.exitCode = 1;
|
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
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ỏ)"
|
package/src/host/mobile-tui.ts
CHANGED
|
@@ -4,7 +4,8 @@ import { fileURLToPath } from "node:url";
|
|
|
4
4
|
import { HerdGateAgent } from "../agent/index.ts";
|
|
5
5
|
import { createSshBridge, translateBootstrap } from "./ssh.ts";
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
if (!process.env.HERDGATE_URL) throw new Error("configure HERDGATE_URL for this mobile publisher");
|
|
8
|
+
const url = new URL(process.env.HERDGATE_URL);
|
|
8
9
|
if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
9
10
|
throw new Error("HERDGATE_URL must be an HTTPS origin");
|
|
10
11
|
}
|
|
@@ -34,8 +34,6 @@ const flag = (name) => {
|
|
|
34
34
|
const i = argv.indexOf(name);
|
|
35
35
|
return i >= 0 && i + 1 < argv.length ? argv[i + 1] : null;
|
|
36
36
|
};
|
|
37
|
-
const GATE = (flag("--gate") ?? process.env.HERDGATE_URL ?? "https://gate.phuongnb.io.vn").replace(/\/$/, "");
|
|
38
|
-
const wsUrl = GATE.replace(/^http/, "ws") + "/v1/ssh/ws";
|
|
39
37
|
const MODE = argv.includes("--tunnel") ? "tunnel" : argv.includes("--probe") ? "probe" : "via";
|
|
40
38
|
|
|
41
39
|
const die = (msg) => {
|
|
@@ -43,6 +41,18 @@ const die = (msg) => {
|
|
|
43
41
|
process.exit(2);
|
|
44
42
|
};
|
|
45
43
|
|
|
44
|
+
const configuredGate = flag("--gate") ?? process.env.HERDGATE_URL;
|
|
45
|
+
if (!configuredGate) die("configure --gate <url> or HERDGATE_URL");
|
|
46
|
+
let origin;
|
|
47
|
+
try { origin = new URL(configuredGate); }
|
|
48
|
+
catch { die("invalid Gate URL"); }
|
|
49
|
+
if (origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash ||
|
|
50
|
+
(origin.protocol !== "https:" && !(origin.protocol === "http:" && ["127.0.0.1", "::1", "[::1]", "localhost"].includes(origin.hostname)))) {
|
|
51
|
+
die("Gate URL must be an HTTPS origin (HTTP only for local development)");
|
|
52
|
+
}
|
|
53
|
+
const GATE = origin.origin;
|
|
54
|
+
const wsUrl = GATE.replace(/^http/, "ws") + "/v1/ssh/ws";
|
|
55
|
+
|
|
46
56
|
const toBuf = (data) => {
|
|
47
57
|
if (Buffer.isBuffer(data)) return data;
|
|
48
58
|
if (data instanceof ArrayBuffer) return Buffer.from(data);
|
package/windows/cli.mjs
CHANGED
|
@@ -1,25 +1,40 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
|
|
3
|
-
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { withLatest } from "./npm-update.mjs";
|
|
5
6
|
|
|
6
7
|
const release = realpathSync(fileURLToPath(new URL("../", import.meta.url)));
|
|
7
8
|
const releases = dirname(release);
|
|
8
9
|
const root = dirname(releases);
|
|
9
10
|
const usage = `herdgate-tui start [path-to-herdr.exe] [--hc path-to-herdr-core.exe | --mobile-tui d_read | --mobile-tui-act d_act]
|
|
10
|
-
herdgate-tui status | stop | version | versions
|
|
11
|
+
herdgate-tui update | status | stop | version | versions
|
|
11
12
|
herdgate-tui use <release-id>`;
|
|
12
13
|
|
|
13
14
|
function run(file, args) {
|
|
14
|
-
const result = spawnSync(process.execPath, [
|
|
15
|
+
const result = spawnSync(process.execPath, [resolve(release, file), ...args], { stdio: "inherit", windowsHide: true, shell: false });
|
|
15
16
|
if (result.error) throw result.error;
|
|
16
17
|
process.exitCode = result.status ?? 1;
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
function update() {
|
|
21
|
+
const defaultRoot = process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Herdgate", "cli");
|
|
22
|
+
const pathKey = (p) => process.platform === "win32" ? p.toLowerCase() : p;
|
|
23
|
+
if (!defaultRoot || !existsSync(defaultRoot) || pathKey(realpathSync(defaultRoot)) !== pathKey(root)) {
|
|
24
|
+
throw new Error("update requires the default per-user install location");
|
|
25
|
+
}
|
|
26
|
+
if (!existsSync(join(root, "publisher-profile.json"))) {
|
|
27
|
+
throw new Error("no saved publisher mode; run npx --yes @bom0792/herdgate@latest tui setup with your current options once");
|
|
28
|
+
}
|
|
29
|
+
withLatest((pkg) => run(join(pkg, "bin", "herdgate.mjs"), ["tui", "update"]));
|
|
30
|
+
}
|
|
31
|
+
|
|
19
32
|
try {
|
|
20
33
|
const [cmd, ...args] = process.argv.slice(2);
|
|
21
34
|
if ((!cmd || cmd === "help" || cmd === "--help") && !args.length) {
|
|
22
35
|
console.log(usage);
|
|
36
|
+
} else if (cmd === "update" && !args.length) {
|
|
37
|
+
update();
|
|
23
38
|
} else if (cmd === "version" && !args.length) {
|
|
24
39
|
console.log(readFileSync(join(release, "release.txt"), "utf8").trim());
|
|
25
40
|
} else if (cmd === "versions" && !args.length) {
|
package/windows/install-cli.mjs
CHANGED
|
@@ -87,11 +87,14 @@ function installShim(root) {
|
|
|
87
87
|
if (previous && (!previous.isFile() || !readFileSync(shim, "utf8").startsWith("@rem Herdgate TUI CLI\r\n"))) {
|
|
88
88
|
throw new Error(`refusing to overwrite an unmanaged shim: ${shim}`);
|
|
89
89
|
}
|
|
90
|
+
// Match the Node used for install, not a node.exe from the caller's cwd.
|
|
91
|
+
const node = process.execPath.replaceAll("%", "%%");
|
|
92
|
+
const content = `@rem Herdgate TUI CLI\r\n@echo off\r\nsetlocal DisableDelayedExpansion\r\n"${node}" "%~dp0..\\current\\windows\\cli.mjs" %*\r\nexit /b %errorlevel%\r\n`;
|
|
93
|
+
// Self-update is running from this batch file; never rewrite an unchanged shim.
|
|
94
|
+
if (previous && readFileSync(shim, "utf8") === content) return;
|
|
90
95
|
const staged = `${shim}.${randomUUID()}`;
|
|
91
96
|
try {
|
|
92
|
-
|
|
93
|
-
const node = process.execPath.replaceAll("%", "%%");
|
|
94
|
-
writeFileSync(staged, `@rem Herdgate TUI CLI\r\n@echo off\r\nsetlocal DisableDelayedExpansion\r\n"${node}" "%~dp0..\\current\\windows\\cli.mjs" %*\r\nexit /b %errorlevel%\r\n`, { flag: "wx" });
|
|
97
|
+
writeFileSync(staged, content, { flag: "wx" });
|
|
95
98
|
renameSync(staged, shim);
|
|
96
99
|
} finally {
|
|
97
100
|
rmSync(staged, { force: true });
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// An npm-launched CLI can be running under a different Node from npm itself.
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { isAbsolute, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const major = (version) => Number(/^v?(\d+)\./.exec(version)?.[1] || 0);
|
|
6
|
+
const working = (version, webSocket) => major(version) >= 22 && webSocket;
|
|
7
|
+
|
|
8
|
+
/** Return an absolute alternate runtime, or null when the current runtime is usable. */
|
|
9
|
+
export function windowsNode({ version = process.version, webSocket = typeof globalThis.WebSocket === 'function', env = process.env } = {}) {
|
|
10
|
+
if (working(version, webSocket)) return null;
|
|
11
|
+
// Do not work around flags disabling WebSocket on an already compatible Node installation.
|
|
12
|
+
if (major(version) >= 22) throw new Error(`WebSocket is disabled or unavailable in Node ${version}; check NODE_OPTIONS and the Node installation`);
|
|
13
|
+
for (const base of new Set([env.ProgramW6432, env.ProgramFiles])) {
|
|
14
|
+
if (!base || !isAbsolute(base)) continue;
|
|
15
|
+
const candidate = join(base, 'nodejs', 'node.exe');
|
|
16
|
+
const result = spawnSync(candidate, ['-p', 'JSON.stringify([process.version,typeof(WebSocket)])'], {
|
|
17
|
+
cwd: join(base, 'nodejs'), env, encoding: 'utf8', windowsHide: true, shell: false, timeout: 3000,
|
|
18
|
+
});
|
|
19
|
+
if (result.status !== 0) continue;
|
|
20
|
+
try {
|
|
21
|
+
const [found, ws] = JSON.parse(result.stdout);
|
|
22
|
+
if (working(found, ws === 'function')) return candidate;
|
|
23
|
+
} catch { /* not a usable Node runtime */ }
|
|
24
|
+
}
|
|
25
|
+
throw new Error(`Herdgate was launched with Node ${String(version).replace(/^v/, '')}; install Node 22+ with WebSocket enabled or run the CLI directly with that Node`);
|
|
26
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Fetch the npm release using npm bundled with the same Node, without running install hooks.
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
export function withLatest(run) {
|
|
8
|
+
const nodeDir = dirname(process.execPath);
|
|
9
|
+
const npm = [
|
|
10
|
+
join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
|
|
11
|
+
...(process.platform === 'win32' ? [] : [join(nodeDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')]),
|
|
12
|
+
...(nodeDir === '/usr/bin' ? ['/usr/share/nodejs/npm/bin/npm-cli.js'] : []),
|
|
13
|
+
].find(existsSync);
|
|
14
|
+
if (!npm) throw new Error('npm was not found beside Node; use a Node 22+ distribution with npm');
|
|
15
|
+
const work = mkdtempSync(join(tmpdir(), 'herdgate-update-'));
|
|
16
|
+
try {
|
|
17
|
+
const result = spawnSync(process.execPath, [npm, 'install', '--prefix', work, '--global=false', '--no-save', '--package-lock=false',
|
|
18
|
+
'--ignore-scripts', '--no-audit', '--no-fund', '--prefer-online', '@bom0792/herdgate@latest'],
|
|
19
|
+
{ cwd: work, stdio: 'inherit', shell: false, windowsHide: true, timeout: 120_000 });
|
|
20
|
+
if (result.error) throw result.error;
|
|
21
|
+
if (result.status !== 0) throw new Error('could not download Herdgate from npm; current publisher not changed');
|
|
22
|
+
return run(join(work, 'node_modules', '@bom0792', 'herdgate'));
|
|
23
|
+
} finally {
|
|
24
|
+
rmSync(work, { recursive: true, force: true, maxRetries: 3 });
|
|
25
|
+
}
|
|
26
|
+
}
|
package/windows/setup-tui.mjs
CHANGED
|
@@ -32,8 +32,10 @@ function writeProfile(path, args) {
|
|
|
32
32
|
|
|
33
33
|
async function setup() {
|
|
34
34
|
const [cmd, ...requested] = process.argv.slice(2);
|
|
35
|
-
if (cmd === "update" && requested.length) throw new Error("use
|
|
36
|
-
if (!["setup", "update"].includes(cmd)) throw new Error("expected
|
|
35
|
+
if (cmd === "update" && requested.length) throw new Error("use herdgate setup to change publisher options");
|
|
36
|
+
if (!["setup", "migrate", "update"].includes(cmd)) throw new Error("expected setup, migrate, or update");
|
|
37
|
+
const plain = requested.includes("--plain");
|
|
38
|
+
if (plain && requested.length !== 1) throw new Error("--plain cannot be combined with other publisher options");
|
|
37
39
|
if (!process.env.LOCALAPPDATA) throw new Error("%LOCALAPPDATA% is required for this installer");
|
|
38
40
|
const root = join(process.env.LOCALAPPDATA, "Herdgate", "cli");
|
|
39
41
|
mkdirSync(root, { recursive: true });
|
|
@@ -44,9 +46,9 @@ async function setup() {
|
|
|
44
46
|
const releases = join(root, "releases");
|
|
45
47
|
const profilePath = join(root, "publisher-profile.json");
|
|
46
48
|
const profile = storedProfile(profilePath);
|
|
47
|
-
if (cmd === "update" && !profile) throw new Error("no saved publisher mode; run
|
|
49
|
+
if (cmd === "update" && !profile) throw new Error("no saved publisher mode; run herdgate migrate with your current options once");
|
|
48
50
|
// 'setup' without arguments on an already configured machine keeps its mode.
|
|
49
|
-
const args = requested.length ? requested : profile ?? [];
|
|
51
|
+
const args = plain ? [] : requested.length ? requested : profile ?? [];
|
|
50
52
|
let prior;
|
|
51
53
|
if (existsSync(link)) {
|
|
52
54
|
const target = realpathSync(link);
|
|
@@ -55,6 +57,9 @@ async function setup() {
|
|
|
55
57
|
throw new Error("current does not point to an installed release");
|
|
56
58
|
}
|
|
57
59
|
}
|
|
60
|
+
if (!profile && !requested.length && (prior || cmd === "migrate")) {
|
|
61
|
+
throw new Error("the old publisher did not save its mode; run herdgate migrate --mobile-act <id>, --mobile-read <id>, --hc <path>, or --plain if Mobile was off");
|
|
62
|
+
}
|
|
58
63
|
const install = (...options) => invoke(installer, ["--root", root, ...options]);
|
|
59
64
|
const cli = (id, ...options) => invoke(join(releases, id, "windows", "cli.mjs"), options);
|
|
60
65
|
const status = (id) => JSON.parse(cli(id, "status"));
|