@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.
@@ -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
@@ -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
- const usage = `herdgate-tui start [path-to-herdr.exe]
10
- herdgate-tui status | stop | version | versions
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]
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, [join(release, file), ...args], { stdio: "inherit", windowsHide: true, shell: false });
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) {
@@ -32,11 +47,13 @@ try {
32
47
  run("windows/install-cli.mjs", ["--root", root, "--use", args[0]]);
33
48
  } else if ((cmd === "status" || cmd === "stop") && !args.length) {
34
49
  run("plugin/server/publish-tui.mjs", [cmd]);
35
- } else if (cmd === "start" && args.length <= 1) {
50
+ } else if (cmd === "start" || cmd === "check") {
51
+ const requested = args[0] && !args[0].startsWith("--") ? args.shift() : null;
52
+ if (args.length && (args.length !== 2 || !["--hc", "--mobile-tui", "--mobile-tui-act"].includes(args[0]) || !args[1])) throw new Error(usage);
36
53
  const pilot = process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "HerdrPilot", "v0.9.5", "herdr.exe");
37
- const bin = args[0] || process.env.HERDGATE_HERDR_BIN || (pilot && existsSync(pilot) ? pilot : null);
54
+ const bin = requested || process.env.HERDGATE_HERDR_BIN || (pilot && existsSync(pilot) ? pilot : null);
38
55
  if (!bin) throw new Error("give the full path to Herdr 0.9.5: herdgate-tui start <path-to-herdr.exe>");
39
- run("plugin/server/publish-tui.mjs", [cmd, bin]);
56
+ run("plugin/server/publish-tui.mjs", [cmd, bin, ...args]);
40
57
  } else {
41
58
  throw new Error(usage);
42
59
  }
@@ -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
- // 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" });
97
+ writeFileSync(staged, content, { flag: "wx" });
95
98
  renameSync(staged, shim);
96
99
  } finally {
97
100
  rmSync(staged, { force: true });
@@ -99,17 +102,21 @@ function installShim(root) {
99
102
  }
100
103
 
101
104
  try {
105
+ if (process.platform === "win32" && typeof globalThis.WebSocket !== "function") throw new Error("run this installer with Node 22+ with WebSocket enabled");
102
106
  const args = process.argv.slice(2);
103
107
  let root = process.platform === "win32" && process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Herdgate", "cli") : null;
104
108
  let use = null;
109
+ let stage = false;
105
110
  while (args.length) {
106
111
  const flag = args.shift();
112
+ if (flag === "--stage") { stage = true; continue; }
107
113
  const value = args.shift();
108
114
  if (flag === "--root" && value) root = resolve(value);
109
115
  else if (flag === "--use" && value) use = value;
110
- else throw new Error("usage: node windows/install-cli.mjs [--root <dir>] [--use <release-id>]");
116
+ else throw new Error("usage: node windows/install-cli.mjs [--root <dir>] [--stage | --use <release-id>]");
111
117
  }
112
118
  if (!root) throw new Error("this installer defaults to %LOCALAPPDATA% on Windows");
119
+ if (stage && use) throw new Error("--stage and --use cannot be combined");
113
120
  directory(root);
114
121
  const releases = join(root, "releases");
115
122
  directory(releases);
@@ -117,9 +124,13 @@ try {
117
124
  mkdirSync(lock);
118
125
  try {
119
126
  const id = use ?? installRelease(releases);
120
- selectRelease(root, releases, id);
121
- installShim(root);
122
- console.log(`Herdgate TUI CLI: ${id}\nShim: ${join(root, "bin", "herdgate-tui.cmd")}`);
127
+ if (stage) {
128
+ console.log(id);
129
+ } else {
130
+ selectRelease(root, releases, id);
131
+ installShim(root);
132
+ console.log(`Herdgate TUI CLI: ${id}\nShim: ${join(root, "bin", "herdgate-tui.cmd")}`);
133
+ }
123
134
  } finally {
124
135
  rmSync(lock, { force: true, recursive: true });
125
136
  }
@@ -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
+ }
@@ -0,0 +1,115 @@
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 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");
39
+ if (!process.env.LOCALAPPDATA) throw new Error("%LOCALAPPDATA% is required for this installer");
40
+ const root = join(process.env.LOCALAPPDATA, "Herdgate", "cli");
41
+ mkdirSync(root, { recursive: true });
42
+ const lock = join(root, ".setup");
43
+ mkdirSync(lock);
44
+ try {
45
+ const link = join(root, "current");
46
+ const releases = join(root, "releases");
47
+ const profilePath = join(root, "publisher-profile.json");
48
+ const profile = storedProfile(profilePath);
49
+ if (cmd === "update" && !profile) throw new Error("no saved publisher mode; run herdgate migrate with your current options once");
50
+ // 'setup' without arguments on an already configured machine keeps its mode.
51
+ const args = plain ? [] : requested.length ? requested : profile ?? [];
52
+ let prior;
53
+ if (existsSync(link)) {
54
+ const target = realpathSync(link);
55
+ prior = basename(target);
56
+ if (!releaseId.test(prior) || normalize(dirname(target)) !== normalize(realpathSync(releases))) {
57
+ throw new Error("current does not point to an installed release");
58
+ }
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
+ }
63
+ const install = (...options) => invoke(installer, ["--root", root, ...options]);
64
+ const cli = (id, ...options) => invoke(join(releases, id, "windows", "cli.mjs"), options);
65
+ const status = (id) => JSON.parse(cli(id, "status"));
66
+ const stop = (id) => {
67
+ if (JSON.parse(cli(id, "stop")).state !== "stopped") throw new Error("publisher did not stop; no Herdr processes were signalled");
68
+ };
69
+ const start = async (id, options) => {
70
+ cli(id, "start", ...options);
71
+ const deadline = Date.now() + 10_000;
72
+ let result;
73
+ do {
74
+ result = status(id);
75
+ if (result.state === "connected") return result;
76
+ if (result.state === "stopped" || result.state === "stale") break;
77
+ await delay(300);
78
+ } while (Date.now() < deadline);
79
+ throw new Error(`publisher did not connect (${result.state})${result.log ? `; see ${result.log}` : ""}`);
80
+ };
81
+ const next = install("--stage");
82
+ if (!releaseId.test(next)) throw new Error("installer did not return a release ID");
83
+ cli(next, "check", ...args); // validate executable, pairing and Herdr before disrupting the old worker
84
+ const oldStatus = status(prior ?? next);
85
+ const running = !["stopped", "stale"].includes(oldStatus.state);
86
+ if (prior === next && profile && JSON.stringify(args) === JSON.stringify(profile) && oldStatus.state === "connected") {
87
+ install("--use", next); // refresh pinned Node shim, no worker restart
88
+ console.log(JSON.stringify({ release: next, ...oldStatus }));
89
+ return;
90
+ }
91
+ if (oldStatus.state !== "stopped") stop(prior ?? next);
92
+ let triedStart = false;
93
+ try {
94
+ install("--use", next);
95
+ triedStart = true;
96
+ const result = await start(next, args);
97
+ writeProfile(profilePath, args);
98
+ console.log(JSON.stringify({ release: next, ...result }));
99
+ } catch (cause) {
100
+ try {
101
+ if (triedStart && status(next).state !== "stopped") stop(next);
102
+ if (prior) {
103
+ install("--use", prior);
104
+ if (running) await start(prior, profile ?? args);
105
+ }
106
+ } catch (recovery) {
107
+ throw new Error(`${errorText(cause)}; could not restore the old publisher: ${errorText(recovery)}`);
108
+ }
109
+ throw new Error(`${errorText(cause)}${prior ? "; previous release restored" : ""}`);
110
+ }
111
+ } finally { rmSync(lock, { force: true, recursive: true }); }
112
+ }
113
+
114
+ try { await setup(); }
115
+ catch (e) { console.error(`herdgate tui: ${errorText(e)}`); process.exitCode = 1; }