@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.
- package/README.md +136 -1
- package/bin/herdgate.mjs +45 -5
- package/bin/home-tui.mjs +121 -0
- package/dist-readme.md +27 -2
- package/package.json +5 -2
- package/plugin/server/herdr-ssh-win.mjs +43 -0
- package/plugin/server/herdr-ssh.mjs +102 -0
- package/plugin/server/index.mjs +49 -12
- package/plugin/server/mobile-tui-core.mjs +321 -0
- package/plugin/server/mobile-tui-stream.mjs +61 -0
- package/plugin/server/publish-tui.mjs +113 -0
- package/plugin/server/publisher-tui-lifecycle.mjs +117 -0
- package/plugin/server/ssh.d.mts +26 -0
- package/plugin/server/ssh.mjs +165 -37
- package/scripts/build-host-bundle.sh +3 -3
- package/src/cloud/gateway.ts +39 -46
- package/src/cloud/ssh-tcp-edge.ts +119 -0
- package/src/cloud/sshd.ts +36 -28
- package/src/host/mobile-tui-core.mjs +3 -0
- package/src/host/mobile-tui.ts +72 -0
- package/src/host/ssh.ts +5 -315
- package/src/web/app.css +2 -0
- package/src/web/app.js +365 -183
- package/src/web/herdgate-host.zip +0 -0
- package/src/web/index.html +1 -0
- package/src/web/sw.js +1 -1
- package/templates/herdgate-tcp-edge.service +20 -0
- package/windows/cli.mjs +48 -0
- package/windows/install-cli.mjs +137 -0
- package/windows/setup-tui.mjs +110 -0
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 …`
|
|
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,141 @@ 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 and an existing Gate pairing, use one command to
|
|
185
|
+
install and start the TUI publisher (add the relevant Mobile flag if enabled):
|
|
186
|
+
|
|
187
|
+
```powershell
|
|
188
|
+
npx --yes @bom0792/herdgate@latest tui setup --mobile-tui-act d_device
|
|
189
|
+
npx --yes @bom0792/herdgate@latest tui status
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Omit `--mobile-tui-act d_device` for TUI-only setup. The first setup or
|
|
193
|
+
migration from a manual install needs the desired mode once; it is saved
|
|
194
|
+
locally only after the publisher connects. For subsequent updates:
|
|
195
|
+
|
|
196
|
+
```powershell
|
|
197
|
+
npx --yes @bom0792/herdgate@latest tui update
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The update validates the new release before touching the old publisher. It
|
|
201
|
+
preserves the device ID and mode, restarts only the publisher if needed, and
|
|
202
|
+
tries to restore the old release if the new worker cannot connect. Pairing
|
|
203
|
+
and SSH keys are not rewritten. Use `install-tui` for install without starting.
|
|
204
|
+
|
|
205
|
+
The ZIP remains an alternative: extract it and run `node .\windows\install-cli.mjs`.
|
|
206
|
+
|
|
207
|
+
The installer stores each build under `%LOCALAPPDATA%\Herdgate\cli\releases`.
|
|
208
|
+
The directory junction `current` selects the build used by the stable
|
|
209
|
+
`bin\herdgate-tui.cmd` shim. Rerun `npx --yes @bom0792/herdgate@latest install-tui`
|
|
210
|
+
to switch builds. The `tui` subcommand forwards to the installed build; use
|
|
211
|
+
`tui versions` and `tui use <release-id>` to list/select existing builds.
|
|
212
|
+
If you add `%LOCALAPPDATA%\Herdgate\cli\bin` to User PATH, you can also run
|
|
213
|
+
`herdgate-tui` directly. The installer does not change PATH.
|
|
214
|
+
|
|
215
|
+
After pairing the laptop and starting its default session with the official
|
|
216
|
+
Herdr Windows 0.9.5 package, run `herdgate-tui start <path-to-herdr.exe>`.
|
|
217
|
+
You can omit the path if the exe is in `%LOCALAPPDATA%\HerdrPilot\v0.9.5`.
|
|
218
|
+
When `herdgate-tui status` shows `connected`, you can close PowerShell.
|
|
219
|
+
`herdgate-tui stop` stops only the publisher. No login persistence, no inbound
|
|
220
|
+
port, no Windows SSH server. The publisher reuses the existing laptop pairing.
|
|
221
|
+
The controlling machine still needs its own approved `act` device and SSH key.
|
|
222
|
+
Add the saved machine with `herdr machine add <alias> --label laptop --remote-session default`.
|
|
223
|
+
The default publisher does not expose `hc`. If remote control is approved, opt
|
|
224
|
+
in to Herdr Mobile support with the installed Core executable:
|
|
225
|
+
|
|
226
|
+
```powershell
|
|
227
|
+
$hc = (Get-Command herdr-core.exe -ErrorAction Stop).Source
|
|
228
|
+
& $hc server status --json
|
|
229
|
+
herdgate-tui stop
|
|
230
|
+
herdgate-tui start --hc "$hc"
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
If Core is not running, start it locally with `& $hc server start`. The `--hc`
|
|
234
|
+
flag keeps the TUI bridge enabled and adds Core access for `act` devices only.
|
|
235
|
+
The publisher restart interrupts remote connections, not the local TUI server.
|
|
236
|
+
In `--hc` mode, Herdr Mobile sees Core terminals, not TUI panes.
|
|
237
|
+
To expose TUI panes directly instead, use `herdgate-tui start --mobile-tui d_device`
|
|
238
|
+
with the ID of a paired `read` device in this laptop’s room. This opt-in mode
|
|
239
|
+
serves only that device with a read-only Core protocol adapter, needs no `hc`
|
|
240
|
+
binary, and leaves the normal TUI bridge and its existing `act` devices intact.
|
|
241
|
+
Opening an individual pane in Herdr Mobile shows a periodically refreshed
|
|
242
|
+
text snapshot of its visible screen. The adapter does not forward keystrokes,
|
|
243
|
+
resize the pane, or reproduce its full ANSI rendering or scrollback.
|
|
244
|
+
|
|
245
|
+
For a phone explicitly approved to control this laptop, start the publisher
|
|
246
|
+
with `--mobile-tui-act d_device` instead. The device must already have `act`
|
|
247
|
+
scope, and the setting only enables the Core adapter for that device ID.
|
|
248
|
+
Non-observe attach uses Herdr's native terminal session to forward ANSI output,
|
|
249
|
+
keys and viewport resize. Resize changes the pane's real terminal size while
|
|
250
|
+
the controller is attached. Send (paste + Enter), named keys and Interrupt are
|
|
251
|
+
also mapped to TUI actions. The adapter does not implement Core-only features
|
|
252
|
+
such as templates, task lifecycle or file operations. Enable this mode only
|
|
253
|
+
where executing commands in existing panes from the phone is authorized.
|
|
254
|
+
|
|
255
|
+
For the Linux home TUI bridge (laptop → home), the paired host can run:
|
|
256
|
+
|
|
257
|
+
```sh
|
|
258
|
+
npx --yes @bom0792/herdgate@latest home-tui setup
|
|
259
|
+
npx --yes @bom0792/herdgate@latest home-tui status
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Use `home-tui setup --adopt` to migrate the previous home unit created by
|
|
263
|
+
Herdgate; other custom units are not overwritten. The command installs a
|
|
264
|
+
persistent systemd user service, reuses the existing room and TUI socket,
|
|
265
|
+
and does not restart Herdr. Repeat `setup` to update the publisher.
|
|
266
|
+
|
|
267
|
+
On Linux, use `npm run mobile-tui` (or `node src/host/mobile-tui.ts`) as the
|
|
268
|
+
user running Herdr, with
|
|
269
|
+
`HERDGATE_URL`, a dedicated `HERDGATE_ROOM_TOKEN`, and `HERDR_BIN_PATH` set.
|
|
270
|
+
Set `HERDR_SOCKET_PATH` if needed to select the existing TUI session. Without
|
|
271
|
+
`HERDGATE_MOBILE_TUI_ACT_DEVICE`, this publisher is read-only. For interactive
|
|
272
|
+
mode, use a separate room and set that variable to the exact existing `act`
|
|
273
|
+
device ID. The publisher never auto-approves new `act` pairings.
|
|
274
|
+
|
|
140
275
|
## The PWA (the device side)
|
|
141
276
|
|
|
142
277
|
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,17 @@ 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
|
-
|
|
26
|
+
herdgate install-tui
|
|
27
|
+
Install or update the per-user Windows TUI publisher. Does not start it.
|
|
28
|
+
herdgate tui setup [path-to-herdr.exe] [--mobile-tui d_read | --mobile-tui-act d_act | --hc <exe>]
|
|
29
|
+
Install, start and save the selected publisher mode (existing pairing required).
|
|
30
|
+
herdgate tui update
|
|
31
|
+
Install this npm version and restart only the publisher, preserving its mode.
|
|
32
|
+
herdgate tui start [path-to-herdr.exe]
|
|
33
|
+
herdgate tui status | stop | version | versions | use <release-id>
|
|
34
|
+
Manage the installed publisher without adding it to PATH.
|
|
35
|
+
herdgate home-tui setup [--adopt] | status | restart | stop
|
|
36
|
+
Manage the Linux TUI publisher as a systemd user service.`;
|
|
27
37
|
|
|
28
38
|
function arg(name, fallback = undefined) {
|
|
29
39
|
const i = process.argv.indexOf(`--${name}`);
|
|
@@ -238,9 +248,39 @@ function integrate(home) {
|
|
|
238
248
|
console.log(" the shipped layout `main` stays untouched (layout.switch main goes back).");
|
|
239
249
|
}
|
|
240
250
|
|
|
241
|
-
|
|
251
|
+
function runNode(file, args) {
|
|
252
|
+
const child = spawnSync(process.execPath, [file, ...args], { stdio: "inherit", shell: false, windowsHide: true });
|
|
253
|
+
if (child.error) throw child.error;
|
|
254
|
+
process.exitCode = child.status ?? 1;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function runInstalledTui(args) {
|
|
258
|
+
if (!process.env.LOCALAPPDATA) throw new Error("the TUI publisher CLI is for Windows (%LOCALAPPDATA% is unset)");
|
|
259
|
+
const root = join(process.env.LOCALAPPDATA, "Herdgate", "cli");
|
|
260
|
+
const current = join(root, "current");
|
|
261
|
+
if (!existsSync(current)) throw new Error("run herdgate install-tui first");
|
|
262
|
+
const release = realpathSync(current);
|
|
263
|
+
const releases = realpathSync(join(root, "releases"));
|
|
264
|
+
const key = (p) => process.platform === "win32" ? p.toLowerCase() : p;
|
|
265
|
+
if (!/^tui-[a-f0-9]{16}$/.test(basename(release)) || key(dirname(release)) !== key(releases)) {
|
|
266
|
+
throw new Error("current does not point to an installed release; rerun install-tui");
|
|
267
|
+
}
|
|
268
|
+
runNode(join(release, "windows", "cli.mjs"), args);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
242
272
|
if (cmd === "setup-host") setupHost();
|
|
243
|
-
else {
|
|
273
|
+
else if (["install-tui", "tui", "home-tui"].includes(cmd)) {
|
|
274
|
+
try {
|
|
275
|
+
if (cmd === "home-tui") runNode(join(HERE, "home-tui.mjs"), args);
|
|
276
|
+
else if (cmd === "install-tui") runNode(join(ROOT, "windows", "install-cli.mjs"), args);
|
|
277
|
+
else if (["setup", "update"].includes(args[0])) runNode(join(ROOT, "windows", "setup-tui.mjs"), args);
|
|
278
|
+
else runInstalledTui(args);
|
|
279
|
+
} catch (e) {
|
|
280
|
+
console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
|
|
281
|
+
process.exitCode = 1;
|
|
282
|
+
}
|
|
283
|
+
} else {
|
|
244
284
|
console.log(help);
|
|
245
285
|
process.exit(cmd === "help" || cmd === "--help" ? 0 : 1);
|
|
246
286
|
}
|
package/bin/home-tui.mjs
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Linux user service, with a durable release outside npm's cache.
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { readConfig } from '../plugin/server/common.mjs';
|
|
10
|
+
|
|
11
|
+
const unit = 'herdgate-home-tui.service';
|
|
12
|
+
const marker = '# Managed by Herdgate CLI\n';
|
|
13
|
+
const configHome = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
|
|
14
|
+
const dataHome = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
|
|
15
|
+
const appHome = process.env.HERDR_APP_HOME || join(homedir(), '.config', 'herdr-app');
|
|
16
|
+
const root = join(dataHome, 'herdgate', 'home-tui');
|
|
17
|
+
const unitFile = join(configHome, 'systemd', 'user', unit);
|
|
18
|
+
const systemctl = (...args) => execFileSync('systemctl', ['--user', ...args], { stdio: 'inherit', timeout: 25_000 });
|
|
19
|
+
function replace(path, value) {
|
|
20
|
+
const tmp = `${path}.${randomUUID()}`;
|
|
21
|
+
try {
|
|
22
|
+
writeFileSync(tmp, value, { flag: 'wx', mode: 0o600 });
|
|
23
|
+
renameSync(tmp, path);
|
|
24
|
+
} finally { rmSync(tmp, { force: true }); }
|
|
25
|
+
}
|
|
26
|
+
function installedUnit() {
|
|
27
|
+
if (!existsSync(unitFile)) return null;
|
|
28
|
+
if (!lstatSync(unitFile).isFile()) throw new Error(`refusing to use a non-regular unit: ${unitFile}`);
|
|
29
|
+
return readFileSync(unitFile, 'utf8');
|
|
30
|
+
}
|
|
31
|
+
function legacyUnit(text) {
|
|
32
|
+
return text.startsWith('[Unit]\nDescription=Herdgate publisher for the home Herdr TUI\n') &&
|
|
33
|
+
text.includes('Environment=HERDR_PLUGIN_CONFIG_DIR=%h/.config/herdr-app/herdgate/config\n') &&
|
|
34
|
+
/^ExecStart=%h\/\.nvm\/versions\/node\/v\d+\.\d+\.\d+\/bin\/node %h\/source\/herdgate\/plugin\/server\/index\.mjs serve$/m.test(text);
|
|
35
|
+
}
|
|
36
|
+
const sysPath = (value) => {
|
|
37
|
+
if (!isAbsolute(value) || /[\r\n\0]/.test(value)) throw new Error('systemd paths must be absolute and on one line');
|
|
38
|
+
return '"' + value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%') + '"';
|
|
39
|
+
};
|
|
40
|
+
function release() {
|
|
41
|
+
const server = fileURLToPath(new URL('../plugin/server/', import.meta.url));
|
|
42
|
+
const require = createRequire(import.meta.url);
|
|
43
|
+
const wsManifest = require.resolve('ws/package.json');
|
|
44
|
+
const runtime = readdirSync(server).filter(n => n.endsWith('.mjs')).sort();
|
|
45
|
+
const hash = createHash('sha256').update(readFileSync(wsManifest));
|
|
46
|
+
for (const name of runtime) hash.update(name + '\0').update(readFileSync(join(server, name)));
|
|
47
|
+
const releases = join(root, 'releases');
|
|
48
|
+
mkdirSync(releases, { recursive: true, mode: 0o700 });
|
|
49
|
+
const dest = join(releases, hash.digest('hex').slice(0, 24));
|
|
50
|
+
if (!existsSync(dest)) {
|
|
51
|
+
const stage = mkdtempSync(join(releases, '.stage-'));
|
|
52
|
+
try {
|
|
53
|
+
const plugin = join(stage, 'plugin', 'server');
|
|
54
|
+
mkdirSync(plugin, { recursive: true });
|
|
55
|
+
for (const name of runtime) cpSync(join(server, name), join(plugin, name));
|
|
56
|
+
mkdirSync(join(stage, 'node_modules'));
|
|
57
|
+
cpSync(dirname(wsManifest), join(stage, 'node_modules', 'ws'), { recursive: true });
|
|
58
|
+
renameSync(stage, dest);
|
|
59
|
+
} finally { rmSync(stage, { force: true, recursive: true }); }
|
|
60
|
+
}
|
|
61
|
+
if (!lstatSync(dest).isDirectory()) throw new Error('invalid installed TUI release');
|
|
62
|
+
return dest;
|
|
63
|
+
}
|
|
64
|
+
async function setup(args) {
|
|
65
|
+
const adopt = args.includes('--adopt');
|
|
66
|
+
if (args.some(a => a !== '--adopt')) throw new Error('usage: herdgate home-tui setup [--adopt]');
|
|
67
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
68
|
+
const lock = join(root, '.installing');
|
|
69
|
+
mkdirSync(lock);
|
|
70
|
+
try {
|
|
71
|
+
const old = installedUnit();
|
|
72
|
+
if (old && !old.startsWith(marker) && !(adopt && legacyUnit(old))) {
|
|
73
|
+
throw new Error('existing service is not CLI-managed; only the previous Herdgate home service can be migrated with --adopt');
|
|
74
|
+
}
|
|
75
|
+
const herdr = process.env.HERDR_BIN_PATH || join(homedir(), '.local', 'bin', 'herdr');
|
|
76
|
+
const socket = process.env.HERDR_SOCKET_PATH || join(configHome, 'herdr', 'herdr.sock');
|
|
77
|
+
const config = join(appHome, 'herdgate', 'config');
|
|
78
|
+
const state = join(appHome, 'herdgate', 'state');
|
|
79
|
+
const cfg = readConfig(join(config, 'herdgate.env'));
|
|
80
|
+
if (!cfg.HERDGATE_ROOM_TOKEN || !cfg.HERDGATE_URL) throw new Error('pair the home room first; herdgate.env is missing or incomplete');
|
|
81
|
+
const gate = new URL(cfg.HERDGATE_URL);
|
|
82
|
+
if (gate.protocol !== 'https:' || gate.username || gate.password) throw new Error('a credential-free HTTPS Gate URL is required');
|
|
83
|
+
for (const path of [herdr, socket, config, state, root]) sysPath(path);
|
|
84
|
+
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
|
+
if (!status.running || status.compatible !== true) throw new Error('start a compatible Herdr TUI server before running setup');
|
|
86
|
+
const runtime = release();
|
|
87
|
+
const env = { HERDGATE_PUBLISHER_CHILD:'1', HERDR_PLUGIN_ID:'dev.herdgate.host', HERDR_PLUGIN_CONFIG_DIR:config, HERDR_PLUGIN_STATE_DIR:state, HERDR_BIN_PATH:herdr, HERDR_SOCKET_PATH:socket, HERDGATE_HERDR_SESSION:'default' };
|
|
88
|
+
const lines = Object.entries(env).map(([k, v]) => `Environment=${isAbsolute(v) ? sysPath(`${v}`).replace(/^"/, `"${k}=`) : `${k}=${v}`}`).join('\n');
|
|
89
|
+
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
|
+
mkdirSync(dirname(unitFile), { recursive: true });
|
|
91
|
+
if (old !== next) replace(unitFile, next);
|
|
92
|
+
try {
|
|
93
|
+
if (old !== next) systemctl('daemon-reload');
|
|
94
|
+
if (old && old !== next) {
|
|
95
|
+
systemctl('enable', unit);
|
|
96
|
+
systemctl('restart', unit);
|
|
97
|
+
} else systemctl('enable', '--now', unit);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (old !== next) {
|
|
100
|
+
if (old) replace(unitFile, old); else rmSync(unitFile, { force: true });
|
|
101
|
+
systemctl('daemon-reload');
|
|
102
|
+
if (old) systemctl('restart', unit);
|
|
103
|
+
}
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
console.log('Herdgate home publisher service started; no Herdr process was restarted.');
|
|
107
|
+
} finally { rmSync(lock, { recursive: true, force: true }); }
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
const [action, ...args] = process.argv.slice(2);
|
|
111
|
+
if (process.platform !== 'linux') throw new Error('home-tui requires Linux with a systemd user manager');
|
|
112
|
+
if (action === 'setup') await setup(args);
|
|
113
|
+
else if (!args.length && ['status', 'restart', 'stop'].includes(action)) {
|
|
114
|
+
const existing = installedUnit();
|
|
115
|
+
if (!existing || !(existing.startsWith(marker) || legacyUnit(existing))) throw new Error('run herdgate home-tui setup first');
|
|
116
|
+
systemctl(action, ...(action === 'status' ? ['--no-pager'] : []), unit);
|
|
117
|
+
} else throw new Error('usage: herdgate home-tui setup [--adopt] | status | restart | stop');
|
|
118
|
+
} catch (error) {
|
|
119
|
+
console.error('herdgate home-tui: ' + error.message);
|
|
120
|
+
process.exitCode = 1;
|
|
121
|
+
}
|
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
|
-
- **
|
|
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.
|
|
3
|
+
"version": "0.9.26",
|
|
4
4
|
"description": "Cloud relay hub for herdr-core: every machine dials out, phones and browsers follow (PWA + SSH leg, E2E payloads).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
"test": "node --test test/*.test.ts",
|
|
14
14
|
"check": "tsc -p tsconfig.json",
|
|
15
15
|
"ssh-bridge": "node src/cloud/ssh-bridge.ts",
|
|
16
|
+
"ssh-tcp-edge": "node src/cloud/ssh-tcp-edge.ts",
|
|
17
|
+
"mobile-tui": "node src/host/mobile-tui.ts",
|
|
16
18
|
"postinstall": "node scripts/patch-ssh2.mjs"
|
|
17
19
|
},
|
|
18
20
|
"dependencies": {
|
|
@@ -35,6 +37,7 @@
|
|
|
35
37
|
"plugin",
|
|
36
38
|
"scripts",
|
|
37
39
|
"dist-readme.md",
|
|
38
|
-
"templates"
|
|
40
|
+
"templates",
|
|
41
|
+
"windows"
|
|
39
42
|
]
|
|
40
43
|
}
|
|
@@ -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
|
+
}
|