@bom0792/herdgate 0.9.20 → 0.9.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
@@ -73,6 +73,7 @@
73
73
  </select>
74
74
  <button type="submit">Pair</button>
75
75
  </form>
76
+ <p id="pair-status" class="muted" role="status" hidden></p>
76
77
  <p id="pair-error" class="error" role="alert" hidden></p>
77
78
  </section>
78
79
  </main>
package/src/web/sw.js CHANGED
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // Bump VERSION when a shell file changes; old caches are dropped on activate.
5
5
 
6
- const VERSION = "herdgate-v11";
6
+ const VERSION = "herdgate-v16";
7
7
  const SHELL = ["/", "/app.css", "/e2e.js", "/app.js", "/app.webmanifest", "/icons/icon.svg"];
8
8
 
9
9
  self.addEventListener("install", (event) => {
@@ -0,0 +1,20 @@
1
+ [Unit]
2
+ Description=Herdgate public SSH TCP edge
3
+ After=network.target
4
+
5
+ [Service]
6
+ Type=simple
7
+ DynamicUser=yes
8
+ WorkingDirectory=/opt/herdgate-tcp-edge
9
+ EnvironmentFile=/etc/herdgate-tcp-edge.env
10
+ ExecStart=/usr/bin/node /opt/herdgate-tcp-edge/ssh-tcp-edge.mjs
11
+ Restart=on-failure
12
+ RestartSec=2s
13
+ NoNewPrivileges=yes
14
+ PrivateTmp=yes
15
+ ProtectHome=yes
16
+ ProtectSystem=strict
17
+ RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
18
+
19
+ [Install]
20
+ WantedBy=multi-user.target
@@ -0,0 +1,48 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const release = realpathSync(fileURLToPath(new URL("../", import.meta.url)));
7
+ const releases = dirname(release);
8
+ const root = dirname(releases);
9
+ 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 use <release-id>`;
12
+
13
+ function run(file, args) {
14
+ const result = spawnSync(process.execPath, [join(release, file), ...args], { stdio: "inherit", windowsHide: true, shell: false });
15
+ if (result.error) throw result.error;
16
+ process.exitCode = result.status ?? 1;
17
+ }
18
+
19
+ try {
20
+ const [cmd, ...args] = process.argv.slice(2);
21
+ if ((!cmd || cmd === "help" || cmd === "--help") && !args.length) {
22
+ console.log(usage);
23
+ } else if (cmd === "version" && !args.length) {
24
+ console.log(readFileSync(join(release, "release.txt"), "utf8").trim());
25
+ } else if (cmd === "versions" && !args.length) {
26
+ for (const entry of readdirSync(releases, { withFileTypes: true })) {
27
+ if (entry.isDirectory() && /^tui-[a-f0-9]{16}$/.test(entry.name)) {
28
+ console.log(`${entry.name}${entry.name === basename(release) ? " (current)" : ""}`);
29
+ }
30
+ }
31
+ } else if (cmd === "use" && args.length === 1) {
32
+ run("windows/install-cli.mjs", ["--root", root, "--use", args[0]]);
33
+ } else if ((cmd === "status" || cmd === "stop") && !args.length) {
34
+ run("plugin/server/publish-tui.mjs", [cmd]);
35
+ } else if (cmd === "start" || cmd === "check") {
36
+ const requested = args[0] && !args[0].startsWith("--") ? args.shift() : null;
37
+ if (args.length && (args.length !== 2 || !["--hc", "--mobile-tui", "--mobile-tui-act"].includes(args[0]) || !args[1])) throw new Error(usage);
38
+ const pilot = process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "HerdrPilot", "v0.9.5", "herdr.exe");
39
+ const bin = requested || process.env.HERDGATE_HERDR_BIN || (pilot && existsSync(pilot) ? pilot : null);
40
+ if (!bin) throw new Error("give the full path to Herdr 0.9.5: herdgate-tui start <path-to-herdr.exe>");
41
+ run("plugin/server/publish-tui.mjs", [cmd, bin, ...args]);
42
+ } else {
43
+ throw new Error(usage);
44
+ }
45
+ } catch (e) {
46
+ console.error(`herdgate-tui: ${e instanceof Error ? e.message : String(e)}`);
47
+ process.exitCode = 1;
48
+ }
@@ -0,0 +1,137 @@
1
+ // Per-user installation. On Windows, directory junctions do not need admin or Developer Mode.
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const source = fileURLToPath(new URL("../", import.meta.url));
8
+ const releasePattern = /^tui-[a-f0-9]{16}$/;
9
+ const stat = (p) => { try { return lstatSync(p); } catch (e) { if (e.code === "ENOENT") return null; throw e; } };
10
+ const pathKey = (p) => process.platform === "win32" ? p.toLowerCase() : p;
11
+ const samePath = (a, b) => pathKey(a) === pathKey(b);
12
+
13
+ function directory(path) {
14
+ mkdirSync(path, { recursive: true });
15
+ if (!lstatSync(path).isDirectory()) throw new Error(`expected a real directory: ${path}`);
16
+ }
17
+
18
+ function inputs() {
19
+ return ["plugin/server", "windows"].flatMap((dir) => readdirSync(join(source, dir), { withFileTypes: true })
20
+ .filter((file) => file.isFile() && file.name.endsWith(".mjs"))
21
+ .map((file) => `${dir}/${file.name}`)).sort();
22
+ }
23
+
24
+ function installRelease(releases) {
25
+ const files = inputs().map((name) => [name, readFileSync(join(source, name))]);
26
+ const hash = createHash("sha256");
27
+ for (const [name, contents] of files) hash.update(`${name}\0${contents.length}\0`).update(contents);
28
+ const id = `tui-${hash.digest("hex").slice(0, 16)}`;
29
+ const dest = join(releases, id);
30
+ if (stat(dest)) {
31
+ if (!lstatSync(dest).isDirectory() || readFileSync(join(dest, "release.txt"), "utf8").trim() !== id) {
32
+ throw new Error(`invalid existing release: ${dest}`);
33
+ }
34
+ return id;
35
+ }
36
+ const stage = mkdtempSync(join(releases, ".stage-"));
37
+ try {
38
+ for (const [name, data] of files) {
39
+ mkdirSync(dirname(join(stage, name)), { recursive: true });
40
+ writeFileSync(join(stage, name), data, { flag: "wx" });
41
+ }
42
+ writeFileSync(join(stage, "release.txt"), `${id}\n`);
43
+ renameSync(stage, dest);
44
+ } finally {
45
+ rmSync(stage, { force: true, recursive: true });
46
+ }
47
+ return id;
48
+ }
49
+
50
+ function selectRelease(root, releases, id) {
51
+ if (!releasePattern.test(id)) throw new Error("invalid release ID");
52
+ const dest = join(releases, id);
53
+ if (!stat(dest)?.isDirectory() || readFileSync(join(dest, "release.txt"), "utf8").trim() !== id) {
54
+ throw new Error(`release not installed: ${id}`);
55
+ }
56
+ const current = join(root, "current");
57
+ const old = stat(current);
58
+ if (old) {
59
+ if (!old.isSymbolicLink()) throw new Error(`refusing to replace a real file or directory: ${current}`);
60
+ const target = realpathSync(current);
61
+ if (!releasePattern.test(basename(target)) || !samePath(dirname(target), realpathSync(releases))) {
62
+ throw new Error(`refusing to replace a link outside the managed releases: ${current}`);
63
+ }
64
+ if (samePath(target, realpathSync(dest))) return;
65
+ }
66
+ const slot = join(root, `.next-${randomUUID()}`);
67
+ const backup = `${slot}.old`;
68
+ symlinkSync(dest, slot, process.platform === "win32" ? "junction" : "dir");
69
+ try {
70
+ if (old) renameSync(current, backup);
71
+ try { renameSync(slot, current); }
72
+ catch (e) {
73
+ if (old) renameSync(backup, current);
74
+ throw e;
75
+ }
76
+ if (old) unlinkSync(backup);
77
+ } finally {
78
+ if (stat(slot)?.isSymbolicLink()) unlinkSync(slot);
79
+ }
80
+ }
81
+
82
+ function installShim(root) {
83
+ const bin = join(root, "bin");
84
+ directory(bin);
85
+ const shim = join(bin, "herdgate-tui.cmd");
86
+ const previous = stat(shim);
87
+ if (previous && (!previous.isFile() || !readFileSync(shim, "utf8").startsWith("@rem Herdgate TUI CLI\r\n"))) {
88
+ throw new Error(`refusing to overwrite an unmanaged shim: ${shim}`);
89
+ }
90
+ const staged = `${shim}.${randomUUID()}`;
91
+ try {
92
+ // Match the Node used for install, not a node.exe from the caller's cwd.
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" });
95
+ renameSync(staged, shim);
96
+ } finally {
97
+ rmSync(staged, { force: true });
98
+ }
99
+ }
100
+
101
+ try {
102
+ if (process.platform === "win32" && typeof globalThis.WebSocket !== "function") throw new Error("run this installer with Node 22+ with WebSocket enabled");
103
+ const args = process.argv.slice(2);
104
+ let root = process.platform === "win32" && process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Herdgate", "cli") : null;
105
+ let use = null;
106
+ let stage = false;
107
+ while (args.length) {
108
+ const flag = args.shift();
109
+ if (flag === "--stage") { stage = true; continue; }
110
+ const value = args.shift();
111
+ if (flag === "--root" && value) root = resolve(value);
112
+ else if (flag === "--use" && value) use = value;
113
+ else throw new Error("usage: node windows/install-cli.mjs [--root <dir>] [--stage | --use <release-id>]");
114
+ }
115
+ if (!root) throw new Error("this installer defaults to %LOCALAPPDATA% on Windows");
116
+ if (stage && use) throw new Error("--stage and --use cannot be combined");
117
+ directory(root);
118
+ const releases = join(root, "releases");
119
+ directory(releases);
120
+ const lock = join(root, ".installing");
121
+ mkdirSync(lock);
122
+ try {
123
+ const id = use ?? installRelease(releases);
124
+ if (stage) {
125
+ console.log(id);
126
+ } else {
127
+ selectRelease(root, releases, id);
128
+ installShim(root);
129
+ console.log(`Herdgate TUI CLI: ${id}\nShim: ${join(root, "bin", "herdgate-tui.cmd")}`);
130
+ }
131
+ } finally {
132
+ rmSync(lock, { force: true, recursive: true });
133
+ }
134
+ } catch (e) {
135
+ console.error(`herdgate install: ${e instanceof Error ? e.message : String(e)}`);
136
+ process.exitCode = 1;
137
+ }
@@ -0,0 +1,110 @@
1
+ // npm entry point: stage a release before stopping the existing publisher.
2
+ import { spawnSync } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+
9
+ const installer = fileURLToPath(new URL("./install-cli.mjs", import.meta.url));
10
+ const releaseId = /^tui-[a-f0-9]{16}$/;
11
+ const normalize = (path) => process.platform === "win32" ? path.toLowerCase() : path;
12
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
13
+ function invoke(file, args) {
14
+ const child = spawnSync(process.execPath, [file, ...args], { encoding: "utf8", shell: false, windowsHide: true, timeout: 30_000 });
15
+ if (child.error) throw child.error;
16
+ if (child.status !== 0) throw new Error(child.stderr.trim() || `${args[0]} failed (${child.status})`);
17
+ return child.stdout.trim();
18
+ }
19
+ function storedProfile(path) {
20
+ if (!existsSync(path)) return null;
21
+ const { args } = JSON.parse(readFileSync(path, "utf8"));
22
+ if (!Array.isArray(args) || args.length > 3 || args.some((v) => typeof v !== "string")) throw new Error("invalid TUI profile; inspect the saved profile before updating");
23
+ return args;
24
+ }
25
+ function writeProfile(path, args) {
26
+ const tmp = `${path}.${randomUUID()}`;
27
+ try {
28
+ writeFileSync(tmp, JSON.stringify({ args }) + "\n", { flag: "wx", mode: 0o600 });
29
+ renameSync(tmp, path);
30
+ } finally { rmSync(tmp, { force: true }); }
31
+ }
32
+
33
+ async function setup() {
34
+ const [cmd, ...requested] = process.argv.slice(2);
35
+ if (cmd === "update" && requested.length) throw new Error("use tui setup to change publisher options");
36
+ if (!["setup", "update"].includes(cmd)) throw new Error("expected tui setup or tui update");
37
+ if (!process.env.LOCALAPPDATA) throw new Error("%LOCALAPPDATA% is required for this installer");
38
+ const root = join(process.env.LOCALAPPDATA, "Herdgate", "cli");
39
+ mkdirSync(root, { recursive: true });
40
+ const lock = join(root, ".setup");
41
+ mkdirSync(lock);
42
+ try {
43
+ const link = join(root, "current");
44
+ const releases = join(root, "releases");
45
+ const profilePath = join(root, "publisher-profile.json");
46
+ const profile = storedProfile(profilePath);
47
+ if (cmd === "update" && !profile) throw new Error("no saved publisher mode; run tui setup with your current options once");
48
+ // 'setup' without arguments on an already configured machine keeps its mode.
49
+ const args = requested.length ? requested : profile ?? [];
50
+ let prior;
51
+ if (existsSync(link)) {
52
+ const target = realpathSync(link);
53
+ prior = basename(target);
54
+ if (!releaseId.test(prior) || normalize(dirname(target)) !== normalize(realpathSync(releases))) {
55
+ throw new Error("current does not point to an installed release");
56
+ }
57
+ }
58
+ const install = (...options) => invoke(installer, ["--root", root, ...options]);
59
+ const cli = (id, ...options) => invoke(join(releases, id, "windows", "cli.mjs"), options);
60
+ const status = (id) => JSON.parse(cli(id, "status"));
61
+ const stop = (id) => {
62
+ if (JSON.parse(cli(id, "stop")).state !== "stopped") throw new Error("publisher did not stop; no Herdr processes were signalled");
63
+ };
64
+ const start = async (id, options) => {
65
+ cli(id, "start", ...options);
66
+ const deadline = Date.now() + 10_000;
67
+ let result;
68
+ do {
69
+ result = status(id);
70
+ if (result.state === "connected") return result;
71
+ if (result.state === "stopped" || result.state === "stale") break;
72
+ await delay(300);
73
+ } while (Date.now() < deadline);
74
+ throw new Error(`publisher did not connect (${result.state})${result.log ? `; see ${result.log}` : ""}`);
75
+ };
76
+ const next = install("--stage");
77
+ if (!releaseId.test(next)) throw new Error("installer did not return a release ID");
78
+ cli(next, "check", ...args); // validate executable, pairing and Herdr before disrupting the old worker
79
+ const oldStatus = status(prior ?? next);
80
+ const running = !["stopped", "stale"].includes(oldStatus.state);
81
+ if (prior === next && profile && JSON.stringify(args) === JSON.stringify(profile) && oldStatus.state === "connected") {
82
+ install("--use", next); // refresh pinned Node shim, no worker restart
83
+ console.log(JSON.stringify({ release: next, ...oldStatus }));
84
+ return;
85
+ }
86
+ if (oldStatus.state !== "stopped") stop(prior ?? next);
87
+ let triedStart = false;
88
+ try {
89
+ install("--use", next);
90
+ triedStart = true;
91
+ const result = await start(next, args);
92
+ writeProfile(profilePath, args);
93
+ console.log(JSON.stringify({ release: next, ...result }));
94
+ } catch (cause) {
95
+ try {
96
+ if (triedStart && status(next).state !== "stopped") stop(next);
97
+ if (prior) {
98
+ install("--use", prior);
99
+ if (running) await start(prior, profile ?? args);
100
+ }
101
+ } catch (recovery) {
102
+ throw new Error(`${errorText(cause)}; could not restore the old publisher: ${errorText(recovery)}`);
103
+ }
104
+ throw new Error(`${errorText(cause)}${prior ? "; previous release restored" : ""}`);
105
+ }
106
+ } finally { rmSync(lock, { force: true, recursive: true }); }
107
+ }
108
+
109
+ try { await setup(); }
110
+ catch (e) { console.error(`herdgate tui: ${errorText(e)}`); process.exitCode = 1; }