@bom0792/herdgate 0.9.20 → 0.9.21

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 CHANGED
@@ -124,7 +124,7 @@ ssh -p 2222 d_xxxxxxxx@your-gate # password = the device key shown once a
124
124
  - `read` devices get a filtered channel: mutating calls (`terminal.send`, `file.write`, …) are refused **on
125
125
  the host** with a real JSON-RPC error, and live-terminal mode is downgraded. `act` devices (approved on the
126
126
  host) get byte-transparent access.
127
- - Only `hc …` runs — no shell, no sftp, no port forwarding.
127
+ - Only `hc …` and the fixed Herdr TUI bridge commands below run — no remote shell, SFTP or SSH port forwarding.
128
128
  - The host needs `herdr-core` (`hc`) on PATH or `HERDGATE_HC_BIN`.
129
129
 
130
130
  **Note:** ssh2 1.17.0 has a malformed `server-sig-algs` EXT_INFO (a missing comma garbles the
@@ -137,6 +137,77 @@ LAN phones), `HERDGATE_SSH_KEY` (host key file). Verified against real herdr-cor
137
137
  Anything that is not `view`/`ping` is refused **on the host** with `read-only` — the cloud cannot see payloads,
138
138
  so the host is the last trusted decision point. `act` scope is denied unless `HERDGATE_ALLOW_ACT=1`.
139
139
 
140
+ ## Herdr TUI → an existing Herdr session
141
+
142
+ This is separate from `hc machine add` and the PWA. On the client use the official
143
+ [Herdr v0.9.5 release](https://github.com/herdrdev/herdr/releases/tag/v0.9.5), including the native Windows ZIP if applicable. On the host run the matching Herdr server and the updated Herdgate publisher. The publisher exposes one session (`default`, or `HERDGATE_HERDR_SESSION` in its environment/config); the SSH device must have **act** scope and its own registered SSH key. `act` can type into panes and control Herdr as the host user.
144
+
145
+ Add an alias to the user's `~/.ssh/config` (`%USERPROFILE%\.ssh\config` on Windows). Use your actual gate, device ID, key and tunnel-script path; example for Windows:
146
+
147
+ ```sshconfig
148
+ Host herdgate-home
149
+ HostName herdgate-home
150
+ User d_xxxxxxxx
151
+ HostKeyAlias herdgate
152
+ IdentityFile ~/.ssh/herdgate
153
+ IdentitiesOnly yes
154
+ ProxyCommand node C:\Users\you\.config\herdr-app\herdgate\bin\herdgate-via.mjs --tunnel --gate https://gate.example.org
155
+ ServerAliveInterval 15
156
+ ```
157
+
158
+ Use the private key matching the public key registered to the device. On Windows OpenSSH 8.6,
159
+ use an unquoted, space-free path to the tunnel script as shown above.
160
+ `HostKeyAlias herdgate` reuses the pin from `herdgate-via` **for the same gate**.
161
+ For a new pin, compare the fingerprint against the one provided by the gate owner
162
+ before accepting it. Then, from a normal terminal, not from inside another Herdr pane:
163
+
164
+ ```sh
165
+ ssh herdgate-home exit
166
+ herdr --remote herdgate-home
167
+ ```
168
+
169
+ Or add the machine to the local TUI sidebar:
170
+
171
+ ```sh
172
+ herdr machine add herdgate-home --label home --remote-session default
173
+ herdr
174
+ ```
175
+
176
+ Use the publisher's configured session for `--remote-session` if not `default`.
177
+ Herdgate does not install, update or stop Herdr remotely. Upgrade the host locally
178
+ if its running server is incompatible. SSH terminates at the gate; this is not
179
+ client-to-publisher Noise E2E. No third-party relay or inbound client port is needed.
180
+
181
+ ### Windows as a TUI host
182
+
183
+ Use this only where remote control is approved by the machine's owner/IT.
184
+ With Node 22+ on Windows:
185
+
186
+ ```powershell
187
+ npx --yes @bom0792/herdgate@latest install-tui
188
+ npx --yes @bom0792/herdgate@latest tui status
189
+ ```
190
+
191
+ The ZIP remains an alternative: extract it and run `node .\windows\install-cli.mjs`.
192
+
193
+ The installer stores each build under `%LOCALAPPDATA%\Herdgate\cli\releases`.
194
+ The directory junction `current` selects the build used by the stable
195
+ `bin\herdgate-tui.cmd` shim. Rerun `npx --yes @bom0792/herdgate@latest install-tui`
196
+ to switch builds. The `tui` subcommand forwards to the installed build; use
197
+ `tui versions` and `tui use <release-id>` to list/select existing builds.
198
+ If you add `%LOCALAPPDATA%\Herdgate\cli\bin` to User PATH, you can also run
199
+ `herdgate-tui` directly. The installer does not change PATH.
200
+
201
+ After pairing the laptop and starting its default session with the official
202
+ Herdr Windows 0.9.5 package, run `herdgate-tui start <path-to-herdr.exe>`.
203
+ You can omit the path if the exe is in `%LOCALAPPDATA%\HerdrPilot\v0.9.5`.
204
+ When `herdgate-tui status` shows `connected`, you can close PowerShell.
205
+ `herdgate-tui stop` stops only the publisher. No login persistence, no inbound
206
+ port, no Windows SSH server. The publisher reuses the existing laptop pairing.
207
+ The controlling machine still needs its own approved `act` device and SSH key.
208
+ Add the saved machine with `herdr machine add <alias> --label laptop --remote-session default`.
209
+ This does not enable Windows APP/HC hosting.
210
+
140
211
  ## The PWA (the device side)
141
212
 
142
213
  The cloud serves the PWA itself (`src/web/`, `HERDGATE_WEB_ROOT`, `HERDGATE_NO_WEB=1` to disable). A phone
package/bin/herdgate.mjs CHANGED
@@ -5,8 +5,8 @@
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 } from "node:fs";
9
- import { join, dirname } from "node:path";
8
+ import { cpSync, mkdirSync, writeFileSync, existsSync, readFileSync, realpathSync } from "node:fs";
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";
@@ -23,7 +23,11 @@ const help = `herdgate — every machine, one herd
23
23
  --app-home herdr-app home (default: the platform's usual one)
24
24
  --no-integrate skip the tab-bar panel integration (pane.split still works)
25
25
 
26
- Everything else lives in the app's herdgate panel: Pair, then Publish.`;
26
+ herdgate install-tui
27
+ Install or update the per-user Windows TUI publisher. Does not start it.
28
+ herdgate tui start [path-to-herdr.exe]
29
+ herdgate tui status | stop | version | versions | use <release-id>
30
+ Manage the installed publisher without adding it to PATH.`;
27
31
 
28
32
  function arg(name, fallback = undefined) {
29
33
  const i = process.argv.indexOf(`--${name}`);
@@ -238,9 +242,37 @@ function integrate(home) {
238
242
  console.log(" the shipped layout `main` stays untouched (layout.switch main goes back).");
239
243
  }
240
244
 
241
- const cmd = process.argv[2];
245
+ function runNode(file, args) {
246
+ const child = spawnSync(process.execPath, [file, ...args], { stdio: "inherit", shell: false, windowsHide: true });
247
+ if (child.error) throw child.error;
248
+ process.exitCode = child.status ?? 1;
249
+ }
250
+
251
+ function runInstalledTui(args) {
252
+ if (!process.env.LOCALAPPDATA) throw new Error("the TUI publisher CLI is for Windows (%LOCALAPPDATA% is unset)");
253
+ const root = join(process.env.LOCALAPPDATA, "Herdgate", "cli");
254
+ const current = join(root, "current");
255
+ if (!existsSync(current)) throw new Error("run herdgate install-tui first");
256
+ const release = realpathSync(current);
257
+ const releases = realpathSync(join(root, "releases"));
258
+ const key = (p) => process.platform === "win32" ? p.toLowerCase() : p;
259
+ if (!/^tui-[a-f0-9]{16}$/.test(basename(release)) || key(dirname(release)) !== key(releases)) {
260
+ throw new Error("current does not point to an installed release; rerun install-tui");
261
+ }
262
+ runNode(join(release, "windows", "cli.mjs"), args);
263
+ }
264
+
265
+ const [cmd, ...args] = process.argv.slice(2);
242
266
  if (cmd === "setup-host") setupHost();
243
- else {
267
+ else if (cmd === "install-tui" || cmd === "tui") {
268
+ try {
269
+ if (cmd === "install-tui") runNode(join(ROOT, "windows", "install-cli.mjs"), args);
270
+ else runInstalledTui(args);
271
+ } catch (e) {
272
+ console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
273
+ process.exitCode = 1;
274
+ }
275
+ } else {
244
276
  console.log(help);
245
277
  process.exit(cmd === "help" || cmd === "--help" ? 0 : 1);
246
278
  }
package/dist-readme.md CHANGED
@@ -8,8 +8,7 @@ phone/PWA của bạn.
8
8
 
9
9
  - herdr desktop app (per-user, không cần admin) hoặc herdr TUI
10
10
  - `node` >= 22 trong PATH (kiểm tra: `node -v`)
11
- - **Hệ điều hành: Linux hoặc macOS.** Panel hiện dùng `sh`/`kill`/`nohup` —
12
- bản Windows đang được port; theo dõi bản mới.
11
+ - Nút **Publish** trong panel yêu cầu Linux/macOS. Với Windows, dùng thử publisher TUI chạy nền bên dưới.
13
12
 
14
13
  ## Cài (Linux / macOS)
15
14
 
@@ -37,6 +36,32 @@ phone/PWA của bạn.
37
36
 
38
37
  Máy giờ hiện trong PWA; phone pair thiết bị riêng để xem terminal.
39
38
 
39
+ ## Thử Windows làm host TUI (không cần sshd)
40
+
41
+ Chỉ bật nếu chính sách của máy cho phép điều khiển từ xa. Laptop phải đã pair
42
+ trong Herdgate. Có thể cài từ npm bằng `npx --yes @bom0792/herdgate@latest install-tui`.
43
+ Nếu dùng ZIP, mở PowerShell ở thư mục vừa giải nén:
44
+
45
+ ```powershell
46
+ node .\windows\install-cli.mjs
47
+ $bin = Join-Path $env:LOCALAPPDATA 'Herdgate\cli\bin'
48
+ $env:Path = "$bin;$env:Path"
49
+ herdgate-tui status
50
+ ```
51
+
52
+ Bộ cài dùng junction `current` trỏ vào `releases` dưới
53
+ `%LOCALAPPDATA%\Herdgate\cli`. Cài ZIP mới bằng cách chạy lại installer;
54
+ `herdgate-tui versions` liệt kê các bản, `herdgate-tui use <release-id>`
55
+ chọn bản khác. Muốn có lệnh ở mọi cửa sổ, thêm thư mục `bin` trên vào User
56
+ PATH; bộ cài không tự sửa PATH.
57
+
58
+ Mở session `default` bằng Herdr TUI v0.9.5 trước khi chạy `herdgate-tui start`.
59
+ Nếu không cài `herdr.exe` trong `%LOCALAPPDATA%\HerdrPilot\v0.9.5`, truyền đường
60
+ dẫn đầy đủ sau `start`. Khi `status` báo `connected`, có thể đóng PowerShell.
61
+ `herdgate-tui stop` chỉ dừng publisher. Không tự khởi động khi đăng nhập.
62
+ Máy điều khiển vẫn cần quyền `act` và SSH key riêng cho room của laptop.
63
+ Gói này chỉ phục vụ TUI, không dùng luồng APP/`hc`.
64
+
40
65
  ## Bộ gồm
41
66
 
42
67
  mod/herdgate/ → copy vào mods/ của herdr-app
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.20",
3
+ "version": "0.9.21",
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": {
@@ -35,6 +35,7 @@
35
35
  "plugin",
36
36
  "scripts",
37
37
  "dist-readme.md",
38
- "templates"
38
+ "templates",
39
+ "windows"
39
40
  ]
40
41
  }
@@ -0,0 +1,43 @@
1
+ // Exact Herdr v0.9.5 command templates from upstream src/remote/attach.rs.
2
+ // PowerShell is never invoked. The only child is the locally configured Herdr.
3
+ const ENCODED = "powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ";
4
+ const HEADER = "[Console]::Out.WriteLine(); [Console]::Out.WriteLine('herdr-remote-output-ready:1'); [Console]::Out.Flush(); $ProgressPreference = 'SilentlyContinue'; ";
5
+ const PLATFORM = "$arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }; [Console]::Out.WriteLine('herdr-windows:' + $arch); exit 0";
6
+ const DISCOVERY = String.raw`function Emit-HerdrPath([string]$CandidatePath) { if ([string]::IsNullOrWhiteSpace($CandidatePath) -or -not (Test-Path -LiteralPath $CandidatePath -PathType Leaf)) { return }; $candidateFullPath = [System.IO.Path]::GetFullPath($CandidatePath); $encodedCandidate = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($candidateFullPath)); [Console]::Out.WriteLine('herdr-remote-path:1:' + $encodedCandidate) }; $pathCommand = Get-Command herdr.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1; if ($null -ne $pathCommand) { Emit-HerdrPath $pathCommand.Source }; $userSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; Get-CimInstance Win32_Process -Filter "Name = 'herdr.exe' OR Name = 'herdr-dev.exe'" -ErrorAction SilentlyContinue | ForEach-Object { $owner = Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid -ErrorAction SilentlyContinue; if ($owner.ReturnValue -eq 0 -and $owner.Sid -eq $userSid) { Emit-HerdrPath $_.ExecutablePath } }; $herdrHome = if ([string]::IsNullOrWhiteSpace($env:HERDR_HOME)) { Join-Path $env:USERPROFILE '.herdr' } else { $env:HERDR_HOME }; $activeJunction = Get-Item -LiteralPath (Join-Path $herdrHome 'packages\standalone\current') -Force -ErrorAction SilentlyContinue; if ($null -ne $activeJunction -and -not [string]::IsNullOrWhiteSpace([string]$activeJunction.Target)) { Emit-HerdrPath (Join-Path ([string]$activeJunction.Target) 'herdr.exe') }; exit 0`;
7
+ const q = (s) => /^(?!-)[a-zA-Z0-9_./:+=-]+$/.test(s) ? s : `'${s.replaceAll("'", "''")}'`;
8
+ const status = (bin, args) => `& ${[bin, ...args].map(q).join(" ")}; exit $LASTEXITCODE`;
9
+ const bridge = (bin, args) => `$process = Start-Process -FilePath ${q(bin)} -ArgumentList ${q(args.join(" "))} -NoNewWindow -PassThru -ErrorAction Stop; $null = $process.Handle; $process.WaitForExit(); exit $process.ExitCode`;
10
+
11
+ export function translateWindowsHerdr(input, { bin, session, stdin, arch }, marker, posixHead) {
12
+ // Only a local, absolute drive path selected by the owner; no UNC targets.
13
+ if (!/^[a-z]:[\\/]/i.test(bin) || /[\x00-\x1f\x7f]/.test(bin) || !/\.exe$/i.test(bin)) return null;
14
+ if (stdin) {
15
+ // A real Windows host cannot run uname; Herdr then tries the Windows probe.
16
+ return input.replace(/\n+$/, "") === posixHead + "uname -s\nuname -m" ? { reply: "", code: 1 } : null;
17
+ }
18
+ if (input.length > 8192 || !input.startsWith(ENCODED)) return null;
19
+ const encoded = input.slice(ENCODED.length);
20
+ const bytes = Buffer.from(encoded, "base64");
21
+ if (bytes.length % 2 || bytes.toString("base64") !== encoded) return null;
22
+ const script = bytes.toString("utf16le");
23
+ if (!script.startsWith(HEADER)) return null;
24
+ const body = script.slice(HEADER.length);
25
+ if (body === PLATFORM) {
26
+ const name = { x64: "AMD64", arm64: "ARM64", ia32: "x86" }[arch];
27
+ return name ? { reply: marker + `herdr-windows:${name}\n` } : null;
28
+ }
29
+ if (body === DISCOVERY) {
30
+ return { reply: marker + `herdr-remote-path:1:${Buffer.from(bin).toString("base64")}\n` };
31
+ }
32
+ const sessionArgs = session === "default" ? [] : ["--session", session];
33
+ for (const args of [["status", "client", "--json"], [...sessionArgs, "status", "server", "--json"]]) {
34
+ if (body === status(bin, args)) return { args, closeStdin: true };
35
+ }
36
+ const clientArgs = [...sessionArgs, "remote-client-bridge"];
37
+ if (body === bridge(bin, clientArgs)) return { args: clientArgs };
38
+ const apiArgs = ["--session", session, "remote-api-bridge"];
39
+ const probe = `$capability = & ${q(bin)} --session ${q(session)} remote-api-bridge --check 2>$null; if ($LASTEXITCODE -ne 0 -or $capability -ne 'herdr-api-bridge-v1') { [Console]::Error.WriteLine('herdr-machine-metadata-stale-v1'); exit 78 }; `;
40
+ if (body === bridge(bin, [...apiArgs, "--check"])) return { args: [...apiArgs, "--check"], closeStdin: true };
41
+ if (body === bridge(bin, apiArgs) || body === probe + bridge(bin, apiArgs)) return { args: apiArgs };
42
+ return null;
43
+ }
@@ -0,0 +1,102 @@
1
+ // Herdr v0.9.5 remote host protocol. Compare generated command templates; none
2
+ // of the received shell text is executed. Only the publisher's chosen binary
3
+ // and session can be used. See upstream src/remote/attach.rs.
4
+ import { accessSync, constants, statSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { isAbsolute, join } from "node:path";
7
+ import { translateWindowsHerdr } from "./herdr-ssh-win.mjs";
8
+
9
+ export const MARKER = "\nherdr-remote-output-ready:1\n";
10
+ const HEAD = "printf '\n%s\n' 'herdr-remote-output-ready:1'\n";
11
+ const q = (s) => /^[a-zA-Z0-9@%_+=:,./-]+$/.test(s) ? s : `'${s.replaceAll("'", "'\\''")}'`;
12
+ const sh = (script) => `/bin/sh -c ${q(script)}`;
13
+
14
+ function executable(bin) {
15
+ try {
16
+ if (!isAbsolute(bin) || /[\r\n\0]/.test(bin) || !statSync(bin).isFile()) return false;
17
+ accessSync(bin, constants.X_OK);
18
+ return true;
19
+ } catch {
20
+ return false;
21
+ }
22
+ }
23
+
24
+ export function resolveHerdr(env = process.env) {
25
+ const explicit = env.HERDGATE_HERDR_BIN?.trim();
26
+ if (explicit) return executable(explicit) ? explicit : null;
27
+ if (process.platform === "win32") {
28
+ const bin = env.HERDR_BIN_PATH?.trim();
29
+ return bin && executable(bin) ? bin : null;
30
+ }
31
+ return [env.HERDR_BIN_PATH ?? "", join(homedir(), ".local/bin/herdr"), "/usr/local/bin/herdr", "/usr/bin/herdr"].find(executable) ?? null;
32
+ }
33
+
34
+ function candidates(os) {
35
+ return `home=\${HOME:-}
36
+ user=\${USER:-}
37
+ version=<client-version>
38
+ emit() {
39
+ path=$1
40
+ if [ -n "$path" ] && [ -x "$path" ]; then
41
+ printf '%s\\n' "$path"
42
+ fi
43
+ }
44
+ if [ -n "$home" ]; then
45
+ emit "$home/.local/bin/herdr"
46
+ fi
47
+ ${os === "darwin" ? ' emit "/opt/homebrew/bin/herdr"\n emit "/usr/local/bin/herdr"' : ' emit "/home/linuxbrew/.linuxbrew/bin/herdr"'}
48
+ if [ -n "$home" ]; then
49
+ emit "$home/.local/share/mise/installs/herdr/$version/bin/herdr"
50
+ emit "$home/.local/share/mise/installs/herdr/$version/herdr"
51
+ emit "$home/.local/share/mise/installs/github-ogulcancelik-herdr/$version/herdr"
52
+ emit "$home/.nix-profile/bin/herdr"
53
+ fi
54
+ if [ -n "$user" ]; then
55
+ emit "/etc/profiles/per-user/$user/bin/herdr"
56
+ fi
57
+ emit "/nix/var/nix/profiles/default/bin/herdr"
58
+ emit "/run/current-system/sw/bin/herdr"
59
+ `;
60
+ }
61
+
62
+ export function translateHerdr(input, { bin, session = "default", stdin = false, os = process.platform, arch = process.arch }) {
63
+ if (!bin || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(session)) return null;
64
+ // Interpret only the probe text, never the bridge data. Windows clients can send CRLF.
65
+ input = input.replaceAll("\r\n", "\n");
66
+ if (os === "win32") return translateWindowsHerdr(input, { bin, session, stdin, arch }, MARKER, HEAD);
67
+ if (!["linux", "darwin"].includes(os)) return null;
68
+ const body = input.startsWith(HEAD) ? input.slice(HEAD.length).replace(/\n+$/, "") : null;
69
+ const path = q(bin);
70
+ const sessionArgs = session === "default" ? [] : ["--session", session];
71
+ const prefix = [path, ...sessionArgs].join(" ");
72
+ const reply = (s) => ({ reply: MARKER + s });
73
+ const run = (args, closeStdin = stdin) => ({ args, closeStdin });
74
+ if (body === "command -v herdr") return reply(`${bin}\n`);
75
+ if (stdin) {
76
+ if (body === "uname -s\nuname -m") {
77
+ return reply(`${os === "linux" ? "Linux" : "Darwin"}\n${{ x64: "x86_64", arm64: "aarch64" }[arch] ?? arch}\n`);
78
+ }
79
+ // Herdr embeds the client build ID in the probe. Ignore just that token;
80
+ // the rest of the script must match and the result is always the host binary.
81
+ const discovery = body?.replace(/^version=\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][a-zA-Z0-9.+-]{1,64})?$/m, "version=<client-version>");
82
+ if (discovery !== body && discovery === candidates(os).trimEnd()) return reply(`${bin}\n`);
83
+ if (body === `test -x ${path} && ${path} status client --json`) return run(["status", "client", "--json"]);
84
+ if (body === `${prefix} status server --json`) return run([...sessionArgs, "status", "server", "--json"]);
85
+ if (body === `exec ${prefix} remote-client-bridge </dev/null`) return run([...sessionArgs, "remote-client-bridge"]);
86
+ } else {
87
+ for (const option of ["", " --idle-timeout-v1"]) {
88
+ if (body === `exec ${prefix} remote-client-bridge${option}`) {
89
+ return run([...sessionArgs, "remote-client-bridge", ...(option ? [option.trim()] : [])]);
90
+ }
91
+ }
92
+ const api = `${path} --session ${session} remote-api-bridge`;
93
+ const cached = `if capability=$(${api} --check </dev/null 2>/dev/null) && [ "$capability" = herdr-api-bridge-v1 ]; then
94
+ ${HEAD}exec ${api}
95
+ else
96
+ printf '%s\\n' 'herdr-machine-metadata-stale-v1' >&2
97
+ exit 78
98
+ fi`;
99
+ if (input === sh(cached) || body === `exec ${api}`) return run(["--session", session, "remote-api-bridge"]);
100
+ }
101
+ return null;
102
+ }
@@ -2,8 +2,8 @@
2
2
  * herdgate plugin for Herdr — commands behind the manifest.
3
3
  *
4
4
  * The plugin calls Herdr through `HERDR_BIN_PATH` (the official CLI) and publishes the
5
- * resulting metadata to a herdgate cloud over one outbound WebSocket. Read-only: the
6
- * plugin never sends a keystroke, reads a pane's content, or runs an agent.
5
+ * resulting metadata to a herdgate cloud over one outbound WebSocket. Device
6
+ * permissions are checked before dispatching any interactive bridge commands.
7
7
  */
8
8
 
9
9
  import { spawn } from "node:child_process";
@@ -12,6 +12,7 @@ import { join, dirname } from "node:path";
12
12
  import { hostname, homedir } from "node:os";
13
13
  import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize, herdrPanes, herdrRead } from "./common.mjs";
14
14
  import { createSshBridge } from "./ssh.mjs";
15
+ import { registerPublisher } from "./publisher-tui-lifecycle.mjs";
15
16
  import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
16
17
 
17
18
  const D = dirs();
@@ -139,13 +140,28 @@ async function serve() {
139
140
 
140
141
  /**
141
142
  * The long-lived publisher: read Herdr metadata and push it to every paired device.
142
- * Reconnects with bounded backoff. Uses Node's global WebSocket so the plugin needs no
143
- * node_modules — `herdr plugin install` checks out the manifest directory alone.
143
+ * Reconnects with bounded backoff. The default transport uses Node's global
144
+ * WebSocket, so a standalone `herdr plugin install` needs no node_modules.
144
145
  */
145
146
  async function publisherLoop() {
146
147
  const cfg = readConfig(D.configPath);
147
148
  const url = cfg.HERDGATE_URL.replace(/\/$/, "");
148
149
  const wsUrl = url.replace(/^http/, "ws") + "/v1/agent/ws";
150
+ let openSocket = () => new WebSocket(wsUrl);
151
+ const loopbackPort = cfg.HERDGATE_AGENT_LOOPBACK_PORT;
152
+ if (loopbackPort) {
153
+ if (!/^[1-9]\d{0,4}$/.test(loopbackPort) || Number(loopbackPort) > 65_535) {
154
+ throw new Error("HERDGATE_AGENT_LOOPBACK_PORT must be a port from 1 to 65535");
155
+ }
156
+ // Only for co-located publisher/gate deployments. Node's native WebSocket
157
+ // won't set Host; use the gateway's existing ws dependency for this mode.
158
+ const { default: LocalWebSocket } = await import("ws");
159
+ const host = new URL(url).host;
160
+ const endpoint = `ws://127.0.0.1:${loopbackPort}/v1/agent/ws`;
161
+ openSocket = () => new LocalWebSocket(endpoint, {
162
+ headers: { Host: host }, agent: false, handshakeTimeout: 5_000, perMessageDeflate: false,
163
+ });
164
+ }
149
165
  const token = cfg.HERDGATE_ROOM_TOKEN;
150
166
  let backoff = 1_000;
151
167
  let lastSig = "";
@@ -241,12 +257,11 @@ async function publisherLoop() {
241
257
  };
242
258
 
243
259
  const ssh = createSshBridge({
260
+ session: cfg.HERDGATE_HERDR_SESSION || undefined,
261
+ tuiOnly: process.env.HERDGATE_TUI_ONLY === "1",
244
262
  send: (device, payload) => {
245
- void (async () => {
246
- if (wsRef && wsRef.readyState === 1) {
247
- wsRef.send(JSON.stringify({ v: 1, t: "frame", device, payload: await e2eToDevice(device, payload) }));
248
- }
249
- })();
263
+ // sshd is the SSH endpoint; a concurrent PWA session must not seal these frames.
264
+ if (wsRef?.readyState === 1) wsRef.send(JSON.stringify({ v: 1, t: "frame", device, payload }));
250
265
  },
251
266
  scopeOf: (device) => devices.find((d) => d.id === device)?.scope ?? null,
252
267
  log,
@@ -274,8 +289,18 @@ async function publisherLoop() {
274
289
  }
275
290
  };
276
291
 
292
+ const shutdown = () => {
293
+ ssh.closeAll();
294
+ if (wsRef?.readyState === 1) wsRef.close();
295
+ process.exit(0);
296
+ };
297
+ const tuiOnly = process.env.HERDGATE_TUI_ONLY === "1";
298
+ const lifecycle = tuiOnly && process.env.HERDGATE_TUI_RUN_ID
299
+ ? registerPublisher(D.stateDir, process.env.HERDGATE_TUI_RUN_ID, shutdown)
300
+ : null;
301
+
277
302
  const connect = () => {
278
- const ws = new WebSocket(wsUrl);
303
+ const ws = openSocket();
279
304
  wsRef = ws;
280
305
  let helloed = false;
281
306
  ws.onopen = () => {
@@ -297,7 +322,8 @@ async function publisherLoop() {
297
322
  helloed = true;
298
323
  backoff = 1_000;
299
324
  devices = m.devices ?? [];
300
- log(`connected to ${url} (room ${m.roomId}, ${devices.length} device(s))`);
325
+ lifecycle?.setConnected(true);
326
+ log(`connected to ${url}${loopbackPort ? ` via loopback 127.0.0.1:${loopbackPort}` : ""} (room ${m.roomId}, ${devices.length} device(s))`);
301
327
  void publish(ws);
302
328
  if (timer) clearInterval(timer);
303
329
  timer = setInterval(() => void publish(ws), 30_000);
@@ -305,7 +331,9 @@ async function publisherLoop() {
305
331
  return;
306
332
  }
307
333
  if (m.t === "room.update") {
308
- devices = m.devices ?? [];
334
+ const next = m.devices ?? [];
335
+ for (const d of devices) if (!next.some((n) => n.id === d.id && n.scope === d.scope)) ssh.dropDevice(d.id);
336
+ devices = next;
309
337
  void publish(ws);
310
338
  return;
311
339
  }
@@ -392,6 +420,7 @@ async function publisherLoop() {
392
420
  const retry = (why) => {
393
421
  if (retried) return;
394
422
  retried = true;
423
+ lifecycle?.setConnected(false);
395
424
  if (timer) clearInterval(timer);
396
425
  timer = null;
397
426
  ssh.closeAll();
@@ -404,6 +433,7 @@ async function publisherLoop() {
404
433
  ws.onclose = () => retry("disconnected");
405
434
  ws.onerror = () => retry("ws error");
406
435
  };
436
+ if (tuiOnly) for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, shutdown);
407
437
  connect();
408
438
  // Keep the child alive while the socket reconnects.
409
439
  setInterval(() => {}, 1 << 30);
@@ -0,0 +1,89 @@
1
+ // Opt-in Windows pilot. Run as the same user as the local Herdr TUI.
2
+ import { execFile } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { realpathSync, statSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { promisify } from "node:util";
9
+ import { readConfig } from "./common.mjs";
10
+ import { publisherStatus, startPublisher, stopPublisher } from "./publisher-tui-lifecycle.mjs";
11
+
12
+ const run = promisify(execFile);
13
+ try {
14
+ const appHome = process.env.HERDR_APP_HOME || join(homedir(), ".config", "herdr-app");
15
+ const base = join(appHome, "herdgate");
16
+ const state = join(base, "state");
17
+ const [action, exe] = process.argv.slice(2);
18
+ if (action === "status" || action === "stop") {
19
+ const result = action === "status" ? publisherStatus(state) : await stopPublisher(state);
20
+ console.log(JSON.stringify(result));
21
+ if (action === "stop" && result.state !== "stopped") process.exitCode = 1;
22
+ } else {
23
+ const bin = action === "start" || action === "--worker" ? exe : action;
24
+ await launch({ action, bin, base, state });
25
+ }
26
+ } catch (e) {
27
+ console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
28
+ process.exitCode = 1;
29
+ }
30
+
31
+ async function launch({ action, bin, base, state }) {
32
+ if (process.platform !== "win32") throw new Error("this publisher launcher is for Windows");
33
+ if (!bin || !/^[a-z]:[\\/]/i.test(bin) || !/\.exe$/i.test(bin) || !statSync(bin).isFile()) {
34
+ throw new Error("usage: node publish-tui.mjs start <absolute path to herdr.exe> | status | stop");
35
+ }
36
+ const real = realpathSync.native(bin);
37
+ if (!/^[a-z]:[\\/]/i.test(real)) throw new Error("Herdr must be installed on a local drive");
38
+ const cfg = readConfig(join(base, "config", "herdgate.env"));
39
+ if (!cfg.HERDGATE_URL || !cfg.HERDGATE_ROOM_TOKEN) throw new Error("pair this laptop in the Herdgate panel first");
40
+ const gate = new URL(cfg.HERDGATE_URL);
41
+ if (gate.protocol !== "https:" || gate.username || gate.password || cfg.HERDGATE_AGENT_LOOPBACK_PORT) {
42
+ throw new Error("the Windows pilot requires an HTTPS gate and does not use loopback mode");
43
+ }
44
+ if (cfg.HERDGATE_HERDR_SESSION && cfg.HERDGATE_HERDR_SESSION !== "default") {
45
+ throw new Error("this pilot exposes only the default TUI session");
46
+ }
47
+
48
+ const env = {
49
+ ...process.env,
50
+ HERDR_BIN_PATH: bin,
51
+ HERDGATE_HERDR_BIN: bin,
52
+ HERDR_SESSION: "default",
53
+ HERDGATE_HERDR_SESSION: "default",
54
+ HERDR_PLUGIN_ID: "dev.herdgate.host",
55
+ HERDR_PLUGIN_CONFIG_DIR: join(base, "config"),
56
+ HERDR_PLUGIN_STATE_DIR: state,
57
+ HERDGATE_SETTINGS: join(base, "settings.json"),
58
+ HERDGATE_TUI_ONLY: "1",
59
+ HERDGATE_PUBLISHER_CHILD: "1",
60
+ };
61
+ const status = async (target) => JSON.parse((await run(bin, ["status", target, "--json"], {
62
+ env, timeout: 5_000, shell: false, windowsHide: true,
63
+ })).stdout);
64
+ const client = await status("client");
65
+ if (client.version !== "0.9.5" || client.remote_host_bridge !== true) {
66
+ throw new Error("use the standalone Herdr v0.9.5 Windows package with its bundled ConPTY support");
67
+ }
68
+ const server = await status("server");
69
+ if (!server.running || !server.capabilities?.detached_server_daemon) {
70
+ throw new Error("start the local Herdr 0.9.5 TUI (default session) before publishing");
71
+ }
72
+ if (server.version !== client.version) {
73
+ throw new Error(`the running Herdr server reports ${server.version}, expected ${client.version}; finish work in live panes before restarting Herdr`);
74
+ }
75
+ if (action === "start") {
76
+ const result = await startPublisher(state, [fileURLToPath(import.meta.url), "--worker", bin], env);
77
+ console.log(JSON.stringify(result));
78
+ if (!["connected", "connecting", "starting"].includes(result.state)) process.exitCode = 1;
79
+ return;
80
+ }
81
+ if (action === "--worker" && !env.HERDGATE_TUI_RUN_ID) throw new Error("use start to launch the background publisher");
82
+ if (action !== "--worker") {
83
+ env.HERDGATE_TUI_RUN_ID = randomUUID();
84
+ console.error("herdgate: publishing in the foreground; Ctrl+C stops publishing");
85
+ }
86
+ Object.assign(process.env, env);
87
+ process.argv[2] = "serve";
88
+ await import("./index.mjs");
89
+ }