@bom0792/herdgate 0.0.0-stage → 0.9.6
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 +167 -2
- package/app-mod/herdgate/main.js +395 -0
- package/app-mod/herdgate/mod.json +5 -0
- package/bin/herdgate.mjs +91 -0
- package/dist-readme.md +48 -0
- package/package.json +36 -3
- package/plugin/herdr-plugin.toml +36 -0
- package/plugin/server/common.mjs +79 -0
- package/plugin/server/e2e.d.mts +43 -0
- package/plugin/server/e2e.mjs +268 -0
- package/plugin/server/index.mjs +454 -0
- package/plugin/server/ssh.mjs +241 -0
- package/scripts/build-host-bundle.sh +12 -0
- package/scripts/deploy-vps.sh +74 -0
- package/scripts/patch-ssh2.mjs +32 -0
- package/src/agent/adapter.ts +23 -0
- package/src/agent/index.ts +183 -0
- package/src/cloud/gateway.ts +946 -0
- package/src/cloud/main.ts +88 -0
- package/src/cloud/pairing.ts +81 -0
- package/src/cloud/ssh-bridge.ts +212 -0
- package/src/cloud/sshd.ts +412 -0
- package/src/cloud/static.ts +142 -0
- package/src/cloud/stores.ts +180 -0
- package/src/cloud/util.ts +47 -0
- package/src/cloud/vapid.ts +105 -0
- package/src/dev/edge-sim.ts +99 -0
- package/src/dev/main.ts +33 -0
- package/src/host/herdr.ts +316 -0
- package/src/host/main.ts +105 -0
- package/src/host/ssh.ts +317 -0
- package/src/index.ts +5 -0
- package/src/protocol/agent.ts +84 -0
- package/src/protocol/device.ts +90 -0
- package/src/protocol/envelope.ts +58 -0
- package/src/protocol/index.ts +3 -0
- package/src/web/app.css +312 -0
- package/src/web/app.js +835 -0
- package/src/web/app.webmanifest +15 -0
- package/src/web/e2e.js +268 -0
- package/src/web/herdgate-host.zip +0 -0
- package/src/web/icons/icon-192.png +0 -0
- package/src/web/icons/icon-512.png +0 -0
- package/src/web/icons/icon.svg +6 -0
- package/src/web/index.html +99 -0
- package/src/web/sw.js +98 -0
package/README.md
CHANGED
|
@@ -1,3 +1,168 @@
|
|
|
1
|
-
#
|
|
1
|
+
# herdgate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**A cloud relay hub: host agents and devices meet behind one gate.**
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
Herdr (herdr.dev) ──local── herdgate agent ──WSS──▶ cloud gate ◀──WSS── browser/PWA
|
|
7
|
+
owns host policy Cloudflare Tunnel
|
|
8
|
+
|
|
9
|
+
Both remote connections are outbound; the cloud gateway binds loopback.
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
- **One gate, three identities** — accounts (people), rooms (hosts), devices (browsers). Hosts pair by a
|
|
13
|
+
GitHub-style device flow; devices pair into a room; `act` scope needs the host's own approval.
|
|
14
|
+
- **Opaque payloads** — the cloud routes frames between legs and never inspects, logs or persists them.
|
|
15
|
+
End-to-end encryption can be added later without changing the cloud.
|
|
16
|
+
- **No inbound ports on your machines** — publishers dial out over wss; the gate is published through
|
|
17
|
+
`cloudflared`; and the phone app's SSH leg reaches machines with no open port at all via the
|
|
18
|
+
one-file [`ssh-bridge`](DEPLOY.md#the-ssh-leg-is-not-a-cloudflare-tcp-leg--three-ways-in) on any
|
|
19
|
+
reachable host — auth and the read-only allowlist stay in the cloud, the bridge carries no secrets;
|
|
20
|
+
identity provider (no Cloudflare Access needed, none of its headers trusted).
|
|
21
|
+
|
|
22
|
+
## Status
|
|
23
|
+
|
|
24
|
+
v0.6.0 — gateway (HTTP + 2 WS legs), pairing flows, routing, presence, rate limits, state persistence; agent
|
|
25
|
+
SDK with reconnect; **a real Herdr plugin** (`plugin/`) using Herdr's official extension surface; an app mod,
|
|
26
|
+
a PWA, an SSH leg for the Herdr phone app, **room-stream resume** — a phone that drops off wifi replays
|
|
27
|
+
what it missed (frames + presence) instead of losing them — **end-to-end payloads** — Noise_XX between
|
|
28
|
+
device and host inside the opaque channel, so the cloud routes ciphertext it cannot read — and **push
|
|
29
|
+
wake**: VAPID-signed silent pings that raise a phone from its sleep when the host has news; 28 tests. All
|
|
30
|
+
of it verified live through a real Cloudflare Tunnel (gate.phuongnb.io.vn), push subscription and all, and systemd user units (gateway, tunnel, publisher) keeping it alive.
|
|
31
|
+
|
|
32
|
+
The Herdr adapter is read-only: it runs `herdr api snapshot` and serves workspaces/tabs/panes/agents/status to
|
|
33
|
+
paired devices. It never reads a pane, sends a keystroke, or prompts an agent. Terminal content is a later
|
|
34
|
+
slice, by design. No third-party plugin or relay is a dependency — only Herdr's own CLI.
|
|
35
|
+
|
|
36
|
+
## Layout
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
src/protocol/ the wire contract (envelope, agent leg, device leg)
|
|
40
|
+
src/cloud/ the gateway: stores, pairing, routing, HTTP/WS, CLI (main.ts)
|
|
41
|
+
src/agent/ HerdGateAgent SDK + AgentAdapter (what a host app implements)
|
|
42
|
+
src/host/ standalone host CLI (no Herdr needed) + the `herdr api snapshot` adapter
|
|
43
|
+
plugin/ the Herdr TUI plugin: herdr-plugin.toml + server/ (what `herdr plugin link` loads)
|
|
44
|
+
app-mod/ the Herdr app mod: mods/herdgate/ (what `herdr-app check` validates)
|
|
45
|
+
src/web/ the PWA a device opens — served by the cloud, same origin as the WS legs
|
|
46
|
+
test/ e2e relay, the adapter, and the plugin's own commands
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Quickstart
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
npm install
|
|
53
|
+
npm test # e2e: one cloud, one host, three devices
|
|
54
|
+
|
|
55
|
+
# run the cloud (state persists to ./herdgate-state.json)
|
|
56
|
+
HERDGATE_ACCOUNT_TOKEN=$(openssl rand -base64 32) \
|
|
57
|
+
HERDGATE_STATE=./herdgate-state.json \
|
|
58
|
+
npm start
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Pair a host (on the host machine, or from a test script):
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
curl -XPOST localhost:8787/v1/agent/code -d '{"name":"bom-mac"}' # → {code, url}
|
|
65
|
+
curl -XPOST localhost:8787/v1/agent/approve \
|
|
66
|
+
-H "Authorization: Bearer $HERDGATE_ACCOUNT_TOKEN" -d '{"code":"XXXX"}'
|
|
67
|
+
curl localhost:8787/v1/agent/code/XXXX/status # → {roomToken} (once)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
A device opens `ws://…/v1/device/ws`, sends `hello {accountToken}`, calls `pair.begin` — `read` pairs at once,
|
|
71
|
+
`act` waits for the host to answer `pair.request`.
|
|
72
|
+
|
|
73
|
+
**Install as a Herdr plugin** (the supported surface — `herdr plugin link` validates the manifest):
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
herdr plugin link /home/bom/source/herdgate/plugin
|
|
77
|
+
herdr plugin action list --plugin dev.herdgate.host
|
|
78
|
+
herdr plugin action invoke dev.herdgate.host.pair # prints the code; approve it
|
|
79
|
+
herdr plugin pane open --plugin dev.herdgate.host --entrypoint status
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Install as a Herdr app mod** (the desktop app's own surface — `herdr-app check` validates it):
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
cp -r /home/bom/source/herdgate/app-mod/herdgate ~/.config/herdr-app/mods/
|
|
86
|
+
herdr-app check ~/.config/herdr-app/mods/herdgate # → check passed
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The panel docks on the right: set the cloud URL and the herdgate folder, press **Pair**, approve the code in
|
|
90
|
+
your dashboard, then **Publish**. The token goes to `~/.config/herdr-app/herdgate/config/herdgate.env` (0600).
|
|
91
|
+
The mod has `fetch` and `exec` but **no Node globals** (no `process`, `require`, `setTimeout`) — verified in a
|
|
92
|
+
real window.
|
|
93
|
+
|
|
94
|
+
Herdr then runs the `[[startup]]` hook itself: one publisher per server, read-only, reconnecting on its own.
|
|
95
|
+
Credentials live in `HERDR_PLUGIN_CONFIG_DIR/herdgate.env` (mode 0600), never in the plugin root — the plugin
|
|
96
|
+
uses only env Herdr injects (`HERDR_BIN_PATH`, `HERDR_PLUGIN_CONFIG_DIR`, `HERDR_PLUGIN_STATE_DIR`, …) and
|
|
97
|
+
needs no `node_modules` (Node's global `WebSocket`).
|
|
98
|
+
|
|
99
|
+
**Or run the host standalone** (no Herdr, its own process):
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
HERDGATE_URL=https://herd.example.com HERDGATE_PROVISION=1 npm run host
|
|
103
|
+
# → prints HERDGATE_ROOM_TOKEN=… store it, then:
|
|
104
|
+
HERDGATE_URL=https://herd.example.com HERDGATE_ROOM_TOKEN=… npm run host
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Devices pair into the room and ask for `{op:"view"}`; the host answers with the current Herdr metadata.
|
|
108
|
+
|
|
109
|
+
## The SSH leg (the Herdr phone app)
|
|
110
|
+
|
|
111
|
+
The phone app adds machines over SSH — herdgate terminates that SSH itself, so "add a machine" points at the
|
|
112
|
+
gate and the session lands on the host's real `herdr-core`:
|
|
113
|
+
|
|
114
|
+
```sh
|
|
115
|
+
ssh -p 2222 d_xxxxxxxx@your-gate # password = the device key shown once at pair time
|
|
116
|
+
# then the phone speaks the hc API: hello, terminal.list, terminal.read, events.subscribe…
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- Auth is **per device** (id + its one-time key), never the account token; wrong keys strike the IP out.
|
|
120
|
+
- **Public keys too**: `hc machine add` uses the system `ssh`, which prefers keys/agent and answers no
|
|
121
|
+
prompts without a terminal. Register the adding machine's `~/.ssh/id_ed25519.pub` in the PWA (SSH →
|
|
122
|
+
*Public keys*, or `POST /v1/device/sshkey`) and the add is passwordless — Ed25519/RSA/ECDSA, signatures
|
|
123
|
+
verified per RFC 4252 §7.
|
|
124
|
+
- `read` devices get a filtered channel: mutating calls (`terminal.send`, `file.write`, …) are refused **on
|
|
125
|
+
the host** with a real JSON-RPC error, and live-terminal mode is downgraded. `act` devices (approved on the
|
|
126
|
+
host) get byte-transparent access.
|
|
127
|
+
- Only `hc …` runs — no shell, no sftp, no port forwarding.
|
|
128
|
+
- The host needs `herdr-core` (`hc`) on PATH or `HERDGATE_HC_BIN`.
|
|
129
|
+
|
|
130
|
+
**Note:** ssh2 1.17.0 has a malformed `server-sig-algs` EXT_INFO (a missing comma garbles the
|
|
131
|
+
algorithm list) that makes real OpenSSH clients silently abandon publickey auth right after
|
|
132
|
+
`PK_OK`. `scripts/patch-ssh2.mjs` (wired as `postinstall`) fixes the literal in place until
|
|
133
|
+
an upstream release carries the fix; the system-ssh test below guards the regression.
|
|
134
|
+
|
|
135
|
+
Gateway flags: `HERDGATE_SSH_PORT` (default 2222, `0` disables), `HERDGATE_SSH_BIND` (loopback; `0.0.0.0` for
|
|
136
|
+
LAN phones), `HERDGATE_SSH_KEY` (host key file). Verified against real herdr-core 0.1.21.
|
|
137
|
+
Anything that is not `view`/`ping` is refused **on the host** with `read-only` — the cloud cannot see payloads,
|
|
138
|
+
so the host is the last trusted decision point. `act` scope is denied unless `HERDGATE_ALLOW_ACT=1`.
|
|
139
|
+
|
|
140
|
+
## The PWA (the device side)
|
|
141
|
+
|
|
142
|
+
The cloud serves the PWA itself (`src/web/`, `HERDGATE_WEB_ROOT`, `HERDGATE_NO_WEB=1` to disable). A phone
|
|
143
|
+
opens the public hostname, pastes the account token once, sees its machines, pairs into one, and reads the
|
|
144
|
+
view the host publishes.
|
|
145
|
+
|
|
146
|
+
```sh
|
|
147
|
+
HERDGATE_ACCOUNT_TOKEN=… npm start # → http://127.0.0.1:8787/ is the app
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Safety properties, all asserted in `test/web.test.ts`:
|
|
151
|
+
|
|
152
|
+
- **no HTML from the wire** — every string is `textContent`; no `innerHTML`, no `document.write`;
|
|
153
|
+
- **one op** — the client only ever asks a host for `{op:"view"}`; the host, not the cloud, decides the rest;
|
|
154
|
+
- **a locked-down CSP** — `default-src 'self'`, no inline script or style, `frame-ancestors 'none'`;
|
|
155
|
+
- **static can't escape** — `realpath`-pinned root, dotfiles and traversal refused (including `%2e%2e`);
|
|
156
|
+
- **API precedence** — `/v1/*` and `/healthz` are routed before static, so no file can shadow them.
|
|
157
|
+
|
|
158
|
+
Verified live: real Herdr → publisher → cloud → **headless Chrome** signed in, saw the machine, paired
|
|
159
|
+
`read`, and rendered the view (7 spaces, 1 agent, 0 page errors).
|
|
160
|
+
|
|
161
|
+
Going public: [DEPLOY.md](DEPLOY.md) (cloudflared, on this machine).
|
|
162
|
+
|
|
163
|
+
## Herdr-relay lineage
|
|
164
|
+
|
|
165
|
+
herdgate borrows its *ideas* from [herdr-relay](https://github.com/Lapis0875/herdr-relay) — hello-first token
|
|
166
|
+
auth, one-time tickets, scope checks, opaque trees — but shares no code and no protocol. Where herdr-relay is a
|
|
167
|
+
Mac-local bridge over Tailscale, herdgate is the cloud in the middle: identity moves from the tailnet into the
|
|
168
|
+
gate itself. Herdr integration code belongs to herdgate; reference projects are not runtime dependencies.
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
// herdgate for the Herdr app — a docked panel that pairs this machine to a herdgate
|
|
2
|
+
// cloud and shows honest publish state.
|
|
3
|
+
//
|
|
4
|
+
// Official mod surface only (docs/mods.md, defaults/AGENTS.md "### UI" and
|
|
5
|
+
// "### The `herdr` module"):
|
|
6
|
+
// - a mod is `mods/<name>/` with mod.json + main.js, written in gpui-kit — JS that
|
|
7
|
+
// describes native GPUI elements (no HTML, no DOM, no Node APIs);
|
|
8
|
+
// - `herdr` gives the app's data and commands (exec, appHome, readTextFile, notify,
|
|
9
|
+
// theme, props); `fetch` and `localStorage` are available to a mod;
|
|
10
|
+
// - timers are `cx.timer.after(ms, fn)` and `cx.timer.every(ms, (cx) => …)`;
|
|
11
|
+
// - `herdr-app check <mod folder>` loads it once and reports errors.
|
|
12
|
+
//
|
|
13
|
+
// Division of labour: this panel owns the pairing conversation (mint a code with
|
|
14
|
+
// `fetch`, poll it, write the room token) and delegates long-lived publishing to the
|
|
15
|
+
// same publisher the TUI plugin ships (`<root>/plugin/server/index.mjs serve`).
|
|
16
|
+
// One implementation, two surfaces.
|
|
17
|
+
//
|
|
18
|
+
// What it reaches: the network (the herdgate cloud), programs (`sh`, `node`), and files
|
|
19
|
+
// under ~/.config/herdr-app only. It never reads a terminal.
|
|
20
|
+
|
|
21
|
+
import { View, div } from "gpui-kit";
|
|
22
|
+
import { v_flex, h_flex, InputState, Input } from "gpui-base";
|
|
23
|
+
import { exec, appHome, readTextFile, notify, theme, props } from "herdr";
|
|
24
|
+
|
|
25
|
+
const BASE = `${appHome()}/herdgate`;
|
|
26
|
+
const SETTINGS = `${BASE}/settings.json`;
|
|
27
|
+
const ENV_FILE = `${BASE}/config/herdgate.env`;
|
|
28
|
+
const STATE_FILE = `${BASE}/state/pairing.json`;
|
|
29
|
+
const PID_FILE = `${BASE}/state/publisher.pid`;
|
|
30
|
+
|
|
31
|
+
const POLL_MS = 2_500;
|
|
32
|
+
const REFRESH_MS = 4_000;
|
|
33
|
+
|
|
34
|
+
/** `sh` with argv passed positionally: no value is ever interpolated into a script. */
|
|
35
|
+
const sh = (script, args = []) => exec("sh", ["-c", script, "sh", ...args]).catch(() => null);
|
|
36
|
+
|
|
37
|
+
const dirOf = (path) => (path.lastIndexOf("/") > 0 ? path.slice(0, path.lastIndexOf("/")) : ".");
|
|
38
|
+
|
|
39
|
+
/** The token is a secret: write it 0600, which `writeTextFile` cannot express. */
|
|
40
|
+
const writeSecret = (path, text) =>
|
|
41
|
+
sh('umask 077; mkdir -p "$1"; printf "%s\\n" "$2" > "$3"', [dirOf(path), text, path]);
|
|
42
|
+
|
|
43
|
+
/** POSIX liveness probe — no Node APIs in this runtime. */
|
|
44
|
+
async function alive(pid) {
|
|
45
|
+
if (!pid) return false;
|
|
46
|
+
const r = await sh('kill -0 "$1" 2>/dev/null && printf alive', [String(pid)]);
|
|
47
|
+
return r?.stdout === "alive";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function parseEnv(text) {
|
|
51
|
+
const out = {};
|
|
52
|
+
for (const line of (text ?? "").split("\n")) {
|
|
53
|
+
const t = line.trim();
|
|
54
|
+
if (!t || t.startsWith("#")) continue;
|
|
55
|
+
const i = t.indexOf("=");
|
|
56
|
+
if (i > 0) out[t.slice(0, i).trim()] = t.slice(i + 1).trim();
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function readJson(path) {
|
|
62
|
+
const text = await readTextFile(path).catch(() => null);
|
|
63
|
+
if (!text) return null;
|
|
64
|
+
try {
|
|
65
|
+
return JSON.parse(text);
|
|
66
|
+
} catch {
|
|
67
|
+
return null; // a half-written file must never take the panel down
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export default class Herdgate extends View {
|
|
72
|
+
init(_props, cx) {
|
|
73
|
+
this.h = cx.focus_handle();
|
|
74
|
+
this.settings = { cloud: "", root: "", name: "" };
|
|
75
|
+
this.paired = false;
|
|
76
|
+
this.cloud = "";
|
|
77
|
+
this.publisher = { pid: null, running: false };
|
|
78
|
+
this.lastPublish = null;
|
|
79
|
+
|
|
80
|
+
this.pending = null; // { code, url, expiresAt } while a code is waiting
|
|
81
|
+
this.phase = "idle"; // idle | waiting | saving | error
|
|
82
|
+
this.message = "";
|
|
83
|
+
this.notified = false;
|
|
84
|
+
|
|
85
|
+
this.cloudInput = InputState.new({ placeholder: "https://herd.example.com" });
|
|
86
|
+
this.rootInput = InputState.new({ placeholder: "~/src/herdgate" });
|
|
87
|
+
this.nameInput = InputState.new({ placeholder: "this-machine" });
|
|
88
|
+
|
|
89
|
+
cx.spawn(async (cx) => {
|
|
90
|
+
await this.load();
|
|
91
|
+
cx.notify();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// A light poll keeps the panel honest; the mod stays alive while its block shows.
|
|
95
|
+
cx.timer.every(REFRESH_MS, (cx) => {
|
|
96
|
+
cx.spawn(async (cx) => {
|
|
97
|
+
await this.refresh();
|
|
98
|
+
cx.notify();
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async load() {
|
|
104
|
+
const s = await readJson(SETTINGS);
|
|
105
|
+
if (s) this.settings = { cloud: s.cloud ?? "", root: s.root ?? "", name: s.name ?? "" };
|
|
106
|
+
await this.refresh();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Everything shown is read back from disk or the cloud — never assumed. */
|
|
110
|
+
async refresh() {
|
|
111
|
+
const env = parseEnv(await readTextFile(ENV_FILE).catch(() => null));
|
|
112
|
+
this.paired = Boolean(env.HERDGATE_ROOM_TOKEN);
|
|
113
|
+
this.cloud = env.HERDGATE_URL ?? this.settings.cloud ?? "";
|
|
114
|
+
const pidText = (await readTextFile(PID_FILE).catch(() => null))?.trim();
|
|
115
|
+
const pid = pidText ? Number(pidText) : null;
|
|
116
|
+
this.publisher = { pid, running: await alive(pid) };
|
|
117
|
+
const state = await readJson(STATE_FILE);
|
|
118
|
+
this.lastPublish = state?.lastPublish ?? null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async saveSettings(cx) {
|
|
122
|
+
const cloud = (this.cloudInput.value() ?? "").trim().replace(/\/$/, "");
|
|
123
|
+
const root = (this.rootInput.value() ?? "").trim().replace(/\/$/, "");
|
|
124
|
+
const name = (this.nameInput.value() ?? "").trim();
|
|
125
|
+
this.settings = { cloud, root, name };
|
|
126
|
+
const body = JSON.stringify(this.settings, null, 2);
|
|
127
|
+
await sh('umask 077; mkdir -p "$1"; printf "%s" "$2" > "$3"', [BASE, body, SETTINGS]);
|
|
128
|
+
await this.refresh();
|
|
129
|
+
this.message = cloud ? "saved" : "a cloud URL is required";
|
|
130
|
+
cx?.notify?.();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---- pairing: mint, show, poll, write the token --------------------------
|
|
134
|
+
|
|
135
|
+
pair(cx) {
|
|
136
|
+
if (this.phase === "waiting" || this.phase === "saving") return;
|
|
137
|
+
const cloud = (this.settings.cloud || this.cloudInput.value() || "").replace(/\/$/, "");
|
|
138
|
+
if (!cloud) {
|
|
139
|
+
this.phase = "error";
|
|
140
|
+
this.message = "set the herdgate cloud URL first";
|
|
141
|
+
cx?.notify?.();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
this.phase = "waiting";
|
|
145
|
+
this.message = "asking the cloud for a code…";
|
|
146
|
+
cx?.notify?.();
|
|
147
|
+
cx.spawn(async (cx) => {
|
|
148
|
+
try {
|
|
149
|
+
const res = await fetch(`${cloud}/v1/agent/code`, {
|
|
150
|
+
method: "POST",
|
|
151
|
+
headers: { "content-type": "application/json" },
|
|
152
|
+
body: JSON.stringify({ name: this.settings.name || "herdr-app" }),
|
|
153
|
+
});
|
|
154
|
+
if (!res.ok) throw new Error(`the cloud answered HTTP ${res.status}`);
|
|
155
|
+
const minted = await res.json();
|
|
156
|
+
this.pending = { code: minted.code, url: minted.url, expiresAt: Date.now() + (minted.expiresIn ?? 600) * 1000 };
|
|
157
|
+
this.message = "approve this code in your herdgate dashboard";
|
|
158
|
+
this.notified = false;
|
|
159
|
+
cx.notify();
|
|
160
|
+
this.poll(cx, cloud, minted.code);
|
|
161
|
+
} catch (e) {
|
|
162
|
+
this.phase = "error";
|
|
163
|
+
this.message = e instanceof Error ? e.message : String(e);
|
|
164
|
+
cx.notify();
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
poll(cx, cloud, code) {
|
|
170
|
+
cx.timer.after(POLL_MS, (cx) => {
|
|
171
|
+
if (!this.pending || this.pending.code !== code || this.phase !== "waiting") return;
|
|
172
|
+
if (Date.now() > this.pending.expiresAt) {
|
|
173
|
+
this.pending = null;
|
|
174
|
+
this.phase = "error";
|
|
175
|
+
this.message = "the code expired — press Pair again";
|
|
176
|
+
cx.notify();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
cx.spawn(async (cx) => {
|
|
180
|
+
try {
|
|
181
|
+
const st = await (await fetch(`${cloud}/v1/agent/code/${code}/status`)).json();
|
|
182
|
+
if (st.status === "approved" && st.roomToken) {
|
|
183
|
+
this.phase = "saving";
|
|
184
|
+
await writeSecret(ENV_FILE, `HERDGATE_URL=${cloud}\nHERDGATE_ROOM_TOKEN=${st.roomToken}`);
|
|
185
|
+
this.pending = null;
|
|
186
|
+
this.phase = "idle";
|
|
187
|
+
this.message = `paired (room ${st.roomId}) — press Publish to connect`;
|
|
188
|
+
if (!this.notified) {
|
|
189
|
+
this.notified = true;
|
|
190
|
+
notify({ title: "herdgate", body: "This Herdr is paired. Press Publish to connect.", level: "success" });
|
|
191
|
+
}
|
|
192
|
+
await this.refresh();
|
|
193
|
+
cx.notify();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (st.status === "unknown") {
|
|
197
|
+
this.pending = null;
|
|
198
|
+
this.phase = "error";
|
|
199
|
+
this.message = "the code expired — press Pair again";
|
|
200
|
+
cx.notify();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
cx.notify();
|
|
204
|
+
this.poll(cx, cloud, code); // still pending
|
|
205
|
+
} catch {
|
|
206
|
+
this.poll(cx, cloud, code); // a blip: try again
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
cancel(cx) {
|
|
213
|
+
this.pending = null;
|
|
214
|
+
this.phase = "idle";
|
|
215
|
+
this.message = "cancelled";
|
|
216
|
+
cx.notify();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---- publishing: delegate to the shared herdgate publisher ---------------
|
|
220
|
+
|
|
221
|
+
publisherPath() {
|
|
222
|
+
return this.settings.root ? `${this.settings.root}/plugin/server/index.mjs` : "";
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
startPublisher(cx) {
|
|
226
|
+
if (!this.paired) {
|
|
227
|
+
this.phase = "error";
|
|
228
|
+
this.message = "pair this machine first";
|
|
229
|
+
cx.notify();
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const index = this.publisherPath();
|
|
233
|
+
if (!index) {
|
|
234
|
+
this.phase = "error";
|
|
235
|
+
this.message = "set the herdgate folder so the publisher can be found";
|
|
236
|
+
cx.notify();
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
this.message = "starting…";
|
|
240
|
+
cx.notify();
|
|
241
|
+
cx.spawn(async (cx) => {
|
|
242
|
+
const found = await sh('[ -f "$1" ] && command -v node >/dev/null && printf yes', [index]);
|
|
243
|
+
if (found?.stdout !== "yes") {
|
|
244
|
+
this.phase = "error";
|
|
245
|
+
this.message = `needs node and ${index}`;
|
|
246
|
+
cx.notify();
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
// Detached, so closing the panel or the app does not end publishing.
|
|
250
|
+
await sh(
|
|
251
|
+
'HERDR_PLUGIN_ID=$1 HERDR_PLUGIN_CONFIG_DIR=$2 HERDR_PLUGIN_STATE_DIR=$3 nohup node "$4" serve >/dev/null 2>&1 &',
|
|
252
|
+
["dev.herdgate.host", `${BASE}/config`, `${BASE}/state`, index],
|
|
253
|
+
);
|
|
254
|
+
// The publisher writes its own pid file; give it a moment, then read the truth.
|
|
255
|
+
cx.timer.after(1_200, (cx) => {
|
|
256
|
+
cx.spawn(async (cx) => {
|
|
257
|
+
await this.refresh();
|
|
258
|
+
this.message = this.publisher.running ? "publisher started" : "the publisher did not start";
|
|
259
|
+
this.phase = this.publisher.running ? "idle" : "error";
|
|
260
|
+
cx.notify();
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
stopPublisher(cx) {
|
|
267
|
+
cx.spawn(async (cx) => {
|
|
268
|
+
if (this.publisher.pid) await sh('kill "$1" 2>/dev/null; true', [String(this.publisher.pid)]);
|
|
269
|
+
await sh('rm -f "$1"', [PID_FILE]);
|
|
270
|
+
await this.refresh();
|
|
271
|
+
this.message = "publisher stopped";
|
|
272
|
+
cx.notify();
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ---- view ----------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
render(cx) {
|
|
279
|
+
const t = theme();
|
|
280
|
+
const line = (label, value, color) =>
|
|
281
|
+
h_flex()
|
|
282
|
+
.gap(6)
|
|
283
|
+
.items_center()
|
|
284
|
+
.child(div().text_size(11.5).text_color(t.dim).child(label))
|
|
285
|
+
.child(div().flex_1().truncate().text_size(12).text_color(color ?? t.foreground).child(value));
|
|
286
|
+
|
|
287
|
+
return v_flex()
|
|
288
|
+
.id("herdgate-panel")
|
|
289
|
+
.track_focus(this.h)
|
|
290
|
+
.size_full()
|
|
291
|
+
.min_h(0)
|
|
292
|
+
.p(12)
|
|
293
|
+
.gap(8)
|
|
294
|
+
.bg(t.chrome)
|
|
295
|
+
.text_color(t.foreground)
|
|
296
|
+
.child(
|
|
297
|
+
h_flex()
|
|
298
|
+
.items_center()
|
|
299
|
+
.gap(6)
|
|
300
|
+
.child(div().flex_1().text_size(13).font_semibold().child("herdgate"))
|
|
301
|
+
.child(
|
|
302
|
+
div()
|
|
303
|
+
.px(6)
|
|
304
|
+
.py(2)
|
|
305
|
+
.rounded(5)
|
|
306
|
+
.text_size(10.5)
|
|
307
|
+
.bg(t.background)
|
|
308
|
+
.text_color(this.paired ? t.working : t.dim)
|
|
309
|
+
.child(this.paired ? "paired" : "not paired"),
|
|
310
|
+
),
|
|
311
|
+
)
|
|
312
|
+
.child(line("cloud", this.cloud || "—"))
|
|
313
|
+
.child(line("publisher", this.publisher.running ? `running · ${this.publisher.pid}` : "stopped", this.publisher.running ? t.working : t.muted))
|
|
314
|
+
.when(Boolean(this.lastPublish?.summary), (el) =>
|
|
315
|
+
el.child(
|
|
316
|
+
div()
|
|
317
|
+
.text_size(11)
|
|
318
|
+
.text_color(t.dim)
|
|
319
|
+
.child(`${this.lastPublish.summary.workspaces} spaces · ${this.lastPublish.summary.agents} agents · ${this.lastPublish.summary.herdr}`),
|
|
320
|
+
),
|
|
321
|
+
)
|
|
322
|
+
.child(div().h(1).bg(t.border).my(2))
|
|
323
|
+
.child(this.pairingBlock(t, cx))
|
|
324
|
+
.child(div().h(1).bg(t.border).my(2))
|
|
325
|
+
.child(this.settingsBlock(t, cx));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
pairingBlock(t, cx) {
|
|
329
|
+
if (this.pending) {
|
|
330
|
+
return v_flex()
|
|
331
|
+
.id("hg-code")
|
|
332
|
+
.gap(5)
|
|
333
|
+
.child(div().text_size(11.5).text_color(t.muted).child("approve in your dashboard"))
|
|
334
|
+
.child(div().text_size(22).font_semibold().text_color(t.accent).child(this.pending.code.replace(/^(.{4})/, "$1 ")))
|
|
335
|
+
.child(div().text_size(10.5).text_color(t.dim).truncate().child(this.pending.url ?? ""))
|
|
336
|
+
.child(this.button(t, "hg-cancel", "Cancel", t.input, t.foreground, (cx) => this.cancel(cx), true));
|
|
337
|
+
}
|
|
338
|
+
return h_flex()
|
|
339
|
+
.id("hg-actions")
|
|
340
|
+
.gap(6)
|
|
341
|
+
.child(this.button(t, "hg-pair", this.paired ? "Pair again" : "Pair", t.solid, t.solid_foreground, (cx) => this.pair(cx), true))
|
|
342
|
+
.child(this.button(t, "hg-publish", "Publish", t.input, t.foreground, (cx) => this.startPublisher(cx), this.paired && !this.publisher.running))
|
|
343
|
+
.child(this.button(t, "hg-stop", "Stop", t.input, t.foreground, (cx) => this.stopPublisher(cx), this.publisher.running));
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
settingsBlock(t, cx) {
|
|
347
|
+
const field = (id, input, label) =>
|
|
348
|
+
v_flex()
|
|
349
|
+
.gap(2)
|
|
350
|
+
.child(div().text_size(10).text_color(t.dim).child(label))
|
|
351
|
+
.child(
|
|
352
|
+
Input.new(input)
|
|
353
|
+
.id(id)
|
|
354
|
+
.h(26)
|
|
355
|
+
.px(8)
|
|
356
|
+
.gap(6)
|
|
357
|
+
.items_center()
|
|
358
|
+
.rounded(6)
|
|
359
|
+
.border(1)
|
|
360
|
+
.border_color(t.input)
|
|
361
|
+
.bg(t.background)
|
|
362
|
+
.text_size(11.5)
|
|
363
|
+
.text_color(t.foreground),
|
|
364
|
+
);
|
|
365
|
+
return v_flex()
|
|
366
|
+
.id("hg-settings")
|
|
367
|
+
.gap(6)
|
|
368
|
+
.child(field("hg-cloud", this.cloudInput, "cloud URL"))
|
|
369
|
+
.child(field("hg-root", this.rootInput, "herdgate folder"))
|
|
370
|
+
.child(field("hg-name", this.nameInput, "this machine's name"))
|
|
371
|
+
.child(
|
|
372
|
+
h_flex().justify_between().items_center().child(
|
|
373
|
+
div().text_size(9.5).text_color(t.dim).child("token → config dir, mode 0600"),
|
|
374
|
+
).child(this.button(t, "hg-save", "Save", t.input, t.foreground, (c) => this.saveSettings(c), true)),
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
button(t, id, label, bg, fg, onClick, enabled) {
|
|
379
|
+
return h_flex()
|
|
380
|
+
.id(id)
|
|
381
|
+
.h(26)
|
|
382
|
+
.px(10)
|
|
383
|
+
.items_center()
|
|
384
|
+
.rounded(6)
|
|
385
|
+
.bg(bg)
|
|
386
|
+
.text_color(fg)
|
|
387
|
+
.text_size(11.5)
|
|
388
|
+
.when(!enabled, (el) => el.opacity(0.4))
|
|
389
|
+
.cursor_pointer()
|
|
390
|
+
.on_click((_e, cx) => {
|
|
391
|
+
if (enabled) onClick(cx);
|
|
392
|
+
})
|
|
393
|
+
.child(label);
|
|
394
|
+
}
|
|
395
|
+
}
|
package/bin/herdgate.mjs
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// herdgate CLI — brings a machine into the herd.
|
|
3
|
+
//
|
|
4
|
+
// npx @bom0792/herdgate setup-host --cloud https://gate.example.com
|
|
5
|
+
//
|
|
6
|
+
// Installs the herdr-app mod and the publisher into the app's home, and
|
|
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";
|
|
10
|
+
import { homedir, hostname } from "node:os";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
const HERE = dirname(fileURLToPath(import.meta.url)); // <pkg>/bin
|
|
14
|
+
const ROOT = dirname(HERE); // <pkg>
|
|
15
|
+
|
|
16
|
+
const help = `herdgate — every machine, one herd
|
|
17
|
+
|
|
18
|
+
herdgate setup-host [--cloud <url>] [--name <machine-name>] [--app-home <dir>]
|
|
19
|
+
Install the herdr-app mod + publisher and prefill the panel settings.
|
|
20
|
+
--cloud your gate, e.g. https://gate.phuongnb.io.vn (required)
|
|
21
|
+
--name how this machine shows up on the phone (default: hostname)
|
|
22
|
+
--app-home herdr-app home (default: the platform's usual one)
|
|
23
|
+
|
|
24
|
+
Everything else lives in the app's herdgate panel: Pair, then Publish.`;
|
|
25
|
+
|
|
26
|
+
function arg(name, fallback = undefined) {
|
|
27
|
+
const i = process.argv.indexOf(`--${name}`);
|
|
28
|
+
return (i > 0 && process.argv[i + 1]) || fallback;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function appHome() {
|
|
32
|
+
const forced = arg("app-home");
|
|
33
|
+
if (forced) return forced;
|
|
34
|
+
if (process.env.HERDR_APP_HOME) return process.env.HERDR_APP_HOME;
|
|
35
|
+
// herdr-app keeps the same home everywhere: ~/.config/herdr-app ("Home:" line in
|
|
36
|
+
// `herdr-app --help`) — Windows included.
|
|
37
|
+
return join(homedir(), ".config", "herdr-app");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function setupHost() {
|
|
41
|
+
const cloud = arg("cloud");
|
|
42
|
+
if (!cloud) {
|
|
43
|
+
console.error(help);
|
|
44
|
+
process.exit(1);
|
|
45
|
+
}
|
|
46
|
+
const home = appHome();
|
|
47
|
+
const name = arg("name") ?? hostname();
|
|
48
|
+
|
|
49
|
+
const modSrc = join(ROOT, "app-mod", "herdgate");
|
|
50
|
+
const pluginSrc = join(ROOT, "plugin");
|
|
51
|
+
if (!existsSync(modSrc) || !existsSync(pluginSrc)) {
|
|
52
|
+
console.error("herdgate: package assets missing (app-mod/, plugin/) — install the package, not a checkout");
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
mkdirSync(join(home, "mods"), { recursive: true });
|
|
57
|
+
cpSync(modSrc, join(home, "mods", "herdgate"), { recursive: true });
|
|
58
|
+
const base = join(home, "herdgate");
|
|
59
|
+
mkdirSync(base, { recursive: true });
|
|
60
|
+
cpSync(pluginSrc, join(base, "plugin"), { recursive: true });
|
|
61
|
+
|
|
62
|
+
// Prefill what the panel would otherwise ask for. The publisher is spawned from
|
|
63
|
+
// <root>/plugin/server/index.mjs — keep root pinned to where we just put it.
|
|
64
|
+
const settingsPath = join(base, "settings.json");
|
|
65
|
+
let settings = {};
|
|
66
|
+
try {
|
|
67
|
+
settings = JSON.parse(readFileSync(settingsPath, "utf8"));
|
|
68
|
+
} catch {
|
|
69
|
+
/* first install */
|
|
70
|
+
}
|
|
71
|
+
settings.cloud = cloud;
|
|
72
|
+
settings.root = base;
|
|
73
|
+
settings.name = name;
|
|
74
|
+
writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
75
|
+
|
|
76
|
+
console.log(`herdgate: installed for herdr-app at ${home}
|
|
77
|
+
mod → ${join(home, "mods", "herdgate")}
|
|
78
|
+
publisher → ${join(base, "plugin", "server", "index.mjs")}
|
|
79
|
+
settings → ${settingsPath} (cloud: ${cloud}, name: ${name})
|
|
80
|
+
|
|
81
|
+
Next: open (or restart) herdr-app → herdgate panel → Pair, then approve the
|
|
82
|
+
code in the PWA (${cloud}) and click Publish. Requires node >= 22 on PATH
|
|
83
|
+
for the publisher (node -v).`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const cmd = process.argv[2];
|
|
87
|
+
if (cmd === "setup-host") setupHost();
|
|
88
|
+
else {
|
|
89
|
+
console.log(help);
|
|
90
|
+
process.exit(cmd === "help" || cmd === "--help" ? 0 : 1);
|
|
91
|
+
}
|