@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
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* herdgate plugin for Herdr — commands behind the manifest.
|
|
3
|
+
*
|
|
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.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
|
|
11
|
+
import { join, dirname } from "node:path";
|
|
12
|
+
import { hostname } from "node:os";
|
|
13
|
+
import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize } from "./common.mjs";
|
|
14
|
+
import { createSshBridge } from "./ssh.mjs";
|
|
15
|
+
import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
|
|
16
|
+
|
|
17
|
+
const D = dirs();
|
|
18
|
+
const NAME = process.env.HERDGATE_HOST_NAME || hostname();
|
|
19
|
+
const log = (line) => console.error(`herdgate: ${line}`);
|
|
20
|
+
|
|
21
|
+
/** The publisher runs as a detached child of `serve`, recording its pid in state. */
|
|
22
|
+
const pidPath = D.stateDir ? join(D.stateDir, "publisher.pid") : "";
|
|
23
|
+
|
|
24
|
+
async function cloudUrl() {
|
|
25
|
+
const cfg = readConfig(D.configPath);
|
|
26
|
+
const url = process.env.HERDGATE_URL || cfg.HERDGATE_URL || "";
|
|
27
|
+
if (!url) throw new Error("no cloud configured — set HERDGATE_URL in the plugin config");
|
|
28
|
+
return url.replace(/\/$/, "");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function roomToken() {
|
|
32
|
+
const cfg = readConfig(D.configPath);
|
|
33
|
+
const t = process.env.HERDGATE_ROOM_TOKEN || cfg.HERDGATE_ROOM_TOKEN || "";
|
|
34
|
+
if (!t) throw new Error("not paired — run the 'pair' action first");
|
|
35
|
+
return t;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** --- pair: device flow through the herdgate cloud, then save the room token. --- */
|
|
39
|
+
async function pair() {
|
|
40
|
+
const url = await cloudUrl();
|
|
41
|
+
const res = await fetch(`${url}/v1/agent/code`, {
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: { "content-type": "application/json" },
|
|
44
|
+
body: JSON.stringify({ name: NAME }),
|
|
45
|
+
});
|
|
46
|
+
if (!res.ok) throw new Error(`cloud refused the pairing code: HTTP ${res.status}`);
|
|
47
|
+
const minted = await res.json();
|
|
48
|
+
console.log(`Approve this Herdr host in your herdgate dashboard:`);
|
|
49
|
+
console.log(` ${minted.url}`);
|
|
50
|
+
console.log(` code: ${minted.code} (expires in ${Math.round((minted.expiresIn ?? 600) / 60)} min)`);
|
|
51
|
+
console.log("");
|
|
52
|
+
console.log("Waiting for approval… (Ctrl+C to cancel; the code expires on its own)");
|
|
53
|
+
|
|
54
|
+
const deadline = Date.now() + (minted.expiresIn ?? 600) * 1000;
|
|
55
|
+
while (Date.now() < deadline) {
|
|
56
|
+
await new Promise((r) => setTimeout(r, 3_000));
|
|
57
|
+
const st = await (await fetch(`${url}/v1/agent/code/${minted.code}/status`)).json();
|
|
58
|
+
if (st.status === "approved" && st.roomToken) {
|
|
59
|
+
const cfg = readConfig(D.configPath);
|
|
60
|
+
cfg.HERDGATE_URL = url;
|
|
61
|
+
cfg.HERDGATE_ROOM_TOKEN = st.roomToken;
|
|
62
|
+
writeConfig(D.configPath, cfg);
|
|
63
|
+
console.log(`Paired. Room ${st.roomId} saved to the plugin config (mode 0600).`);
|
|
64
|
+
console.log(`The publisher starts at the next Herdr server start, or run the 'stop' then 'serve' action.`);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (st.status === "unknown") throw new Error("the pairing code expired before it was approved");
|
|
68
|
+
}
|
|
69
|
+
throw new Error("pairing timed out");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** --- status: what is configured, what the cloud would see, is it running. --- */
|
|
73
|
+
async function status() {
|
|
74
|
+
const cfg = readConfig(D.configPath);
|
|
75
|
+
const state = readState(D.statePath);
|
|
76
|
+
const out = {
|
|
77
|
+
plugin: D.pluginId,
|
|
78
|
+
config: {
|
|
79
|
+
path: D.configPath || "(HERDR_PLUGIN_CONFIG_DIR unset)",
|
|
80
|
+
cloud: cfg.HERDGATE_URL ?? "(not set)",
|
|
81
|
+
paired: Boolean(cfg.HERDGATE_ROOM_TOKEN),
|
|
82
|
+
},
|
|
83
|
+
publisher: { pid: runningPid() ?? null, running: Boolean(runningPid()) },
|
|
84
|
+
lastPublish: state.lastPublish ?? null,
|
|
85
|
+
herdr: null,
|
|
86
|
+
error: null,
|
|
87
|
+
};
|
|
88
|
+
try {
|
|
89
|
+
out.herdr = summarize(await herdrSnapshot(D.herdrBin));
|
|
90
|
+
} catch (e) {
|
|
91
|
+
out.error = e instanceof Error ? e.message : String(e);
|
|
92
|
+
}
|
|
93
|
+
console.log(JSON.stringify(out, null, 2));
|
|
94
|
+
if (out.error) process.exitCode = 1;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function runningPid() {
|
|
98
|
+
if (!pidPath || !existsSync(pidPath)) return null;
|
|
99
|
+
const pid = Number(readFileSync(pidPath, "utf8").trim());
|
|
100
|
+
if (!pid) return null;
|
|
101
|
+
try {
|
|
102
|
+
process.kill(pid, 0);
|
|
103
|
+
return pid;
|
|
104
|
+
} catch {
|
|
105
|
+
return null; // stale
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** --- serve: the startup hook. Start the publisher once, then exit (Herdr's hook is one-shot). --- */
|
|
110
|
+
async function serve() {
|
|
111
|
+
if (process.env.HERDGATE_PUBLISHER_CHILD === "1") return publisherLoop(); // the child
|
|
112
|
+
const pid = runningPid();
|
|
113
|
+
if (pid) {
|
|
114
|
+
log(`publisher already running (pid ${pid}); nothing to do`);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const cfg = readConfig(D.configPath);
|
|
118
|
+
if (!cfg.HERDGATE_URL || !cfg.HERDGATE_ROOM_TOKEN) {
|
|
119
|
+
// Not paired yet: the startup hook must not fail the server.
|
|
120
|
+
log("not paired — run the 'pair' action to publish this Herdr");
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const child = spawn(process.execPath, [new URL("./index.mjs", import.meta.url).pathname, "serve"], {
|
|
124
|
+
env: { ...process.env, HERDGATE_PUBLISHER_CHILD: "1" },
|
|
125
|
+
detached: true,
|
|
126
|
+
stdio: "ignore",
|
|
127
|
+
});
|
|
128
|
+
child.unref();
|
|
129
|
+
if (pidPath) {
|
|
130
|
+
mkdirSync(dirname(pidPath), { recursive: true });
|
|
131
|
+
writeFileSync(pidPath, String(child.pid));
|
|
132
|
+
}
|
|
133
|
+
log(`publisher started (pid ${child.pid})`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The long-lived publisher: read Herdr metadata and push it to every paired device.
|
|
138
|
+
* Reconnects with bounded backoff. Uses Node's global WebSocket so the plugin needs no
|
|
139
|
+
* node_modules — `herdr plugin install` checks out the manifest directory alone.
|
|
140
|
+
*/
|
|
141
|
+
async function publisherLoop() {
|
|
142
|
+
const cfg = readConfig(D.configPath);
|
|
143
|
+
const url = cfg.HERDGATE_URL.replace(/\/$/, "");
|
|
144
|
+
const wsUrl = url.replace(/^http/, "ws") + "/v1/agent/ws";
|
|
145
|
+
const token = cfg.HERDGATE_ROOM_TOKEN;
|
|
146
|
+
let backoff = 1_000;
|
|
147
|
+
let lastSig = "";
|
|
148
|
+
let devices = [];
|
|
149
|
+
let timer = null;
|
|
150
|
+
|
|
151
|
+
const snapshotPayload = async () => {
|
|
152
|
+
let snap;
|
|
153
|
+
try {
|
|
154
|
+
snap = await herdrSnapshot(D.herdrBin);
|
|
155
|
+
} catch (e) {
|
|
156
|
+
log(`herdr read failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
const sig = JSON.stringify([snap?.workspaces, snap?.agents, snap?.focused_workspace_id]);
|
|
160
|
+
const summary = summarize(snap);
|
|
161
|
+
let changed = false;
|
|
162
|
+
if (sig !== lastSig) {
|
|
163
|
+
changed = true;
|
|
164
|
+
lastSig = sig;
|
|
165
|
+
writeState(D.statePath, { lastPublish: { at: new Date().toISOString(), summary } });
|
|
166
|
+
}
|
|
167
|
+
if (changed) wakeAway(true);
|
|
168
|
+
return { op: "view", view: { v: 1, source: "herdr", takenAt: new Date().toISOString(), summary } };
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
let wsRef = null;
|
|
172
|
+
|
|
173
|
+
// ---- E2E payloads: the host speaks Noise_XX to every paired device ----
|
|
174
|
+
// Handshake + transport live inside frame.payload; the cloud routes them blind.
|
|
175
|
+
// A device that has not completed the handshake keeps working in the clear —
|
|
176
|
+
// the plaintext path stays the compat fallback.
|
|
177
|
+
const e2eKeyPath = D.stateDir ? join(D.stateDir, "e2e-host.json") : "";
|
|
178
|
+
let e2eSelf = null;
|
|
179
|
+
const e2eSelfKey = async () => {
|
|
180
|
+
if (e2eSelf) return e2eSelf;
|
|
181
|
+
try {
|
|
182
|
+
const j = JSON.parse(readFileSync(e2eKeyPath, "utf8"));
|
|
183
|
+
e2eSelf = { jwk: j.jwk, pub: b64d(j.pub) };
|
|
184
|
+
return e2eSelf;
|
|
185
|
+
} catch {
|
|
186
|
+
/* mint a fresh identity below */
|
|
187
|
+
}
|
|
188
|
+
e2eSelf = await generateKeyPair();
|
|
189
|
+
try {
|
|
190
|
+
mkdirSync(dirname(e2eKeyPath), { recursive: true });
|
|
191
|
+
writeFileSync(e2eKeyPath, JSON.stringify({ jwk: e2eSelf.jwk, pub: b64e(e2eSelf.pub) }), { mode: 0o600 });
|
|
192
|
+
} catch (e) {
|
|
193
|
+
log(`e2e: could not persist host key (${e instanceof Error ? e.message : String(e)})`);
|
|
194
|
+
}
|
|
195
|
+
return e2eSelf;
|
|
196
|
+
};
|
|
197
|
+
const e2eSessions = new Map(); // deviceId → HostChannel
|
|
198
|
+
/** null = not an e2e payload; {reply} = handshake answer to send; {inner} = decrypted device payload. */
|
|
199
|
+
const e2eOnDevice = async (device, payload) => {
|
|
200
|
+
if (payload && typeof payload === "object" && typeof payload.op === "string" && payload.op.startsWith("e2e")) log(`e2e: op ${payload.op} from ${device}`);
|
|
201
|
+
if (!payload || typeof payload !== "object") return null;
|
|
202
|
+
if (payload.op === "e2e.init") {
|
|
203
|
+
const ch = new HostChannel(await e2eSelfKey());
|
|
204
|
+
e2eSessions.set(device, ch);
|
|
205
|
+
return { reply: { op: "e2e.reply", ...(await ch.acceptInit(payload)) } };
|
|
206
|
+
}
|
|
207
|
+
if (payload.op === "e2e.finish") {
|
|
208
|
+
const ch = e2eSessions.get(device);
|
|
209
|
+
if (!ch) return { reply: { op: "error", code: "e2e", message: "no handshake in progress" } };
|
|
210
|
+
await ch.acceptFinish(payload);
|
|
211
|
+
log(`e2e: session up with ${device} (host fp ${fingerprint((await e2eSelfKey()).pub)})`);
|
|
212
|
+
// The ack is the start signal: the device encrypts nothing before it, so no
|
|
213
|
+
// transport frame can race the handshake's last step and desync the counters.
|
|
214
|
+
return { reply: { op: "e2e.ready" } };
|
|
215
|
+
}
|
|
216
|
+
if (payload.op === "e2e") {
|
|
217
|
+
const ch = e2eSessions.get(device);
|
|
218
|
+
if (!ch?.ready()) return { reply: { op: "error", code: "e2e", message: "no session" } };
|
|
219
|
+
try {
|
|
220
|
+
return { inner: await ch.recv(payload) };
|
|
221
|
+
} catch {
|
|
222
|
+
// A decrypt failure means the counters can never resync: drop the session and
|
|
223
|
+
// make the device renegotiate.
|
|
224
|
+
e2eSessions.delete(device);
|
|
225
|
+
log(`e2e: dropped session with ${device} (decrypt failed — renegotiate)`);
|
|
226
|
+
return { reply: { op: "error", code: "e2e", message: "session dropped — renegotiate" } };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
};
|
|
231
|
+
/** Encrypt for this device when a session exists; passthrough otherwise. */
|
|
232
|
+
const e2eToDevice = async (device, payload) => {
|
|
233
|
+
const ch = e2eSessions.get(device);
|
|
234
|
+
return ch?.ready() ? ch.send(payload) : payload;
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const ssh = createSshBridge({
|
|
238
|
+
send: (device, payload) => {
|
|
239
|
+
void (async () => {
|
|
240
|
+
if (wsRef && wsRef.readyState === 1) {
|
|
241
|
+
wsRef.send(JSON.stringify({ v: 1, t: "frame", device, payload: await e2eToDevice(device, payload) }));
|
|
242
|
+
}
|
|
243
|
+
})();
|
|
244
|
+
},
|
|
245
|
+
scopeOf: (device) => devices.find((d) => d.id === device)?.scope ?? null,
|
|
246
|
+
log,
|
|
247
|
+
});
|
|
248
|
+
const publish = async (ws) => {
|
|
249
|
+
if (ws.readyState !== 1 || devices.length === 0) return;
|
|
250
|
+
const payload = await snapshotPayload();
|
|
251
|
+
if (!payload) return;
|
|
252
|
+
for (const d of devices) {
|
|
253
|
+
ws.send(JSON.stringify({ v: 1, t: "frame", device: d.id, payload: await e2eToDevice(d.id, payload) }));
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/** Wake phones that are away when something actually changed (throttled per device). */
|
|
258
|
+
const lastWake = new Map(); // deviceId → epoch ms
|
|
259
|
+
const wakeAway = (changed) => {
|
|
260
|
+
if (!changed) return;
|
|
261
|
+
const now = Date.now();
|
|
262
|
+
for (const d of devices) {
|
|
263
|
+
if (d.connected !== false) continue;
|
|
264
|
+
const at = lastWake.get(d.id) ?? 0;
|
|
265
|
+
if (now - at < 5 * 60_000) continue;
|
|
266
|
+
lastWake.set(d.id, now);
|
|
267
|
+
if (wsRef && wsRef.readyState === 1) wsRef.send(JSON.stringify({ v: 1, t: "wake", device: d.id }));
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const connect = () => {
|
|
272
|
+
const ws = new WebSocket(wsUrl);
|
|
273
|
+
wsRef = ws;
|
|
274
|
+
let helloed = false;
|
|
275
|
+
ws.onopen = () => {
|
|
276
|
+
ws.send(JSON.stringify({ v: 1, t: "hello", roomToken: token, info: { name: NAME, version: "0.1.0", capabilities: ["dev.herdgate.host", "read-only"] } }));
|
|
277
|
+
};
|
|
278
|
+
ws.onmessage = (ev) => {
|
|
279
|
+
void (async () => {
|
|
280
|
+
try {
|
|
281
|
+
let m;
|
|
282
|
+
try {
|
|
283
|
+
m = JSON.parse(typeof ev.data === "string" ? ev.data : String(ev.data));
|
|
284
|
+
} catch {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (!helloed && m.t === "hello") {
|
|
288
|
+
helloed = true;
|
|
289
|
+
backoff = 1_000;
|
|
290
|
+
devices = m.devices ?? [];
|
|
291
|
+
log(`connected to ${url} (room ${m.roomId}, ${devices.length} device(s))`);
|
|
292
|
+
void publish(ws);
|
|
293
|
+
if (timer) clearInterval(timer);
|
|
294
|
+
timer = setInterval(() => void publish(ws), 30_000);
|
|
295
|
+
timer.unref?.();
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (m.t === "room.update") {
|
|
299
|
+
devices = m.devices ?? [];
|
|
300
|
+
void publish(ws);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
if (m.t === "frame") {
|
|
304
|
+
// SSH-leg ops are the bridge's; e2e ops are the crypto bridge's; everything
|
|
305
|
+
// else: only `view` and `ping` exist. Encrypted devices unwrap first.
|
|
306
|
+
const rawOp = m.payload && typeof m.payload === "object" ? m.payload.op : undefined;
|
|
307
|
+
if (typeof rawOp === "string" && rawOp.startsWith("ssh.")) {
|
|
308
|
+
ssh.handle(m.device, m.payload);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const unwrapped = await e2eOnDevice(m.device, m.payload);
|
|
312
|
+
if (unwrapped) {
|
|
313
|
+
if (unwrapped.reply !== null && unwrapped.reply !== undefined) {
|
|
314
|
+
ws.send(JSON.stringify({ v: 1, t: "frame", device: m.device, payload: unwrapped.reply }));
|
|
315
|
+
}
|
|
316
|
+
if (unwrapped.inner === undefined) return; // handshake bookkeeping
|
|
317
|
+
}
|
|
318
|
+
const payload = unwrapped?.inner ?? m.payload;
|
|
319
|
+
const op = payload && typeof payload === "object" ? payload.op : undefined;
|
|
320
|
+
const replyTo = async (out) => {
|
|
321
|
+
ws.send(JSON.stringify({ v: 1, t: "frame", device: m.device, payload: await e2eToDevice(m.device, out) }));
|
|
322
|
+
};
|
|
323
|
+
if (op === "ping") return void replyTo({ op: "pong", n: payload.n ?? null, at: new Date().toISOString() });
|
|
324
|
+
if (op === "view") {
|
|
325
|
+
// Answer this device now, even if the view has not changed since the last push.
|
|
326
|
+
lastSig = "";
|
|
327
|
+
return void publish(ws);
|
|
328
|
+
}
|
|
329
|
+
return void replyTo({ op: "error", code: "read-only", message: `dev.herdgate.host has no op ${String(op)}` });
|
|
330
|
+
}
|
|
331
|
+
if (m.t === "pair.request") {
|
|
332
|
+
// Read-only plugin: `act` is never granted.
|
|
333
|
+
ws.send(JSON.stringify({ v: 1, t: "pair.response", requestId: m.requestId, ok: false }));
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (m.t === "ping") ws.send(JSON.stringify({ v: 1, t: "pong", n: m.n ?? 0 }));
|
|
337
|
+
} catch (e) {
|
|
338
|
+
log(`frame handler: ${e instanceof Error ? e.message : String(e)}`);
|
|
339
|
+
}
|
|
340
|
+
})().catch(() => {});
|
|
341
|
+
};
|
|
342
|
+
// One retry per socket: an error while still CONNECTING (e.g. the cloud is
|
|
343
|
+
// restarting and refuses) never produces a close event on this WebSocket
|
|
344
|
+
// implementation — waiting for onclose alone stalled the publisher forever.
|
|
345
|
+
let retried = false;
|
|
346
|
+
const retry = (why) => {
|
|
347
|
+
if (retried) return;
|
|
348
|
+
retried = true;
|
|
349
|
+
if (timer) clearInterval(timer);
|
|
350
|
+
timer = null;
|
|
351
|
+
ssh.closeAll();
|
|
352
|
+
devices = [];
|
|
353
|
+
const wait = Math.min(30_000, backoff) + Math.random() * 500;
|
|
354
|
+
backoff *= 2;
|
|
355
|
+
log(`${why}; retrying in ${Math.round(wait)}ms`);
|
|
356
|
+
setTimeout(connect, wait).unref?.();
|
|
357
|
+
};
|
|
358
|
+
ws.onclose = () => retry("disconnected");
|
|
359
|
+
ws.onerror = () => retry("ws error");
|
|
360
|
+
};
|
|
361
|
+
connect();
|
|
362
|
+
// Keep the child alive while the socket reconnects.
|
|
363
|
+
setInterval(() => {}, 1 << 30);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** --- stop: end the publisher. --- */
|
|
367
|
+
async function stop() {
|
|
368
|
+
const pid = runningPid();
|
|
369
|
+
if (!pid) {
|
|
370
|
+
log("publisher is not running");
|
|
371
|
+
} else {
|
|
372
|
+
try {
|
|
373
|
+
process.kill(pid, "SIGTERM");
|
|
374
|
+
log(`stopped publisher (pid ${pid})`);
|
|
375
|
+
} catch (e) {
|
|
376
|
+
log(`could not stop pid ${pid}: ${e instanceof Error ? e.message : String(e)}`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (pidPath && existsSync(pidPath)) rmSync(pidPath, { force: true });
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** --- pane: the surface inside Herdr. Honest lines, refreshed on a light poll. --- */
|
|
383
|
+
async function pane() {
|
|
384
|
+
const draw = async () => {
|
|
385
|
+
const cfg = readConfig(D.configPath);
|
|
386
|
+
const state = readState(D.statePath);
|
|
387
|
+
const pid = runningPid();
|
|
388
|
+
const lines = [];
|
|
389
|
+
lines.push(`herdgate · ${NAME}`);
|
|
390
|
+
lines.push(`cloud: ${cfg.HERDGATE_URL ?? "not configured"}`);
|
|
391
|
+
lines.push(`pairing: ${cfg.HERDGATE_ROOM_TOKEN ? "paired" : "not paired"}`);
|
|
392
|
+
lines.push(`publisher: ${pid ? `running (pid ${pid})` : "stopped"}`);
|
|
393
|
+
if (state.lastPublish) {
|
|
394
|
+
const s = state.lastPublish.summary;
|
|
395
|
+
lines.push(`last publish: ${state.lastPublish.at}`);
|
|
396
|
+
lines.push(` herdr ${s.herdr} · ${s.workspaces} workspaces · ${s.agents} agents`);
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
const s = summarize(await herdrSnapshot(D.herdrBin));
|
|
400
|
+
lines.push(`herdr now: ${s.workspaces} workspaces · ${s.agents} agents (${s.working} working, ${s.blocked} blocked)`);
|
|
401
|
+
} catch (e) {
|
|
402
|
+
lines.push(`herdr now: unreadable — ${e instanceof Error ? e.message : String(e)}`);
|
|
403
|
+
}
|
|
404
|
+
lines.push("");
|
|
405
|
+
lines.push(cfg.HERDGATE_ROOM_TOKEN ? "press q to close" : "run the 'pair' action to publish this Herdr");
|
|
406
|
+
return lines;
|
|
407
|
+
};
|
|
408
|
+
let closed = false;
|
|
409
|
+
const paint = async () => {
|
|
410
|
+
if (closed) return;
|
|
411
|
+
const lines = await draw();
|
|
412
|
+
process.stdout.write("\x1b[2J\x1b[H" + lines.join("\n") + "\n");
|
|
413
|
+
};
|
|
414
|
+
await paint();
|
|
415
|
+
const iv = setInterval(() => void paint(), 10_000);
|
|
416
|
+
if (process.stdin.isTTY) {
|
|
417
|
+
process.stdin.setRawMode?.(true);
|
|
418
|
+
process.stdin.resume();
|
|
419
|
+
process.stdin.on("data", (b) => {
|
|
420
|
+
const k = String(b);
|
|
421
|
+
if (k === "q" || k === "\u0003") {
|
|
422
|
+
closed = true;
|
|
423
|
+
clearInterval(iv);
|
|
424
|
+
process.stdin.setRawMode?.(false);
|
|
425
|
+
process.exit(0);
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Dispatch — the manifest's commands map onto these. */
|
|
432
|
+
const commands = { pair, status, serve, stop, pane };
|
|
433
|
+
const cmd = process.argv[2] ?? "";
|
|
434
|
+
if (cmd === "" || cmd === "--help" || cmd === "-h" || cmd === "help") {
|
|
435
|
+
console.log(`herdgate ${D.pluginId} — plugin commands (Herdr launches these from herdr-plugin.toml)
|
|
436
|
+
|
|
437
|
+
pair pair this Herdr to a cloud (device flow), storing the room token in the config dir
|
|
438
|
+
status JSON: config, publisher pid, last publish, current Herdr summary
|
|
439
|
+
serve start the publisher once (the [[startup]] hook); exits after spawning it
|
|
440
|
+
stop stop the publisher
|
|
441
|
+
pane the split-pane surface (light 10s poll, q closes)`);
|
|
442
|
+
process.exit(0);
|
|
443
|
+
}
|
|
444
|
+
try {
|
|
445
|
+
const handler = commands[cmd];
|
|
446
|
+
if (!handler) {
|
|
447
|
+
console.error(`herdgate: unknown command "${cmd}"`);
|
|
448
|
+
process.exit(2);
|
|
449
|
+
}
|
|
450
|
+
await handler();
|
|
451
|
+
} catch (e) {
|
|
452
|
+
log(e instanceof Error ? e.message : String(e));
|
|
453
|
+
process.exit(1);
|
|
454
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host side of the SSH leg for the plugin publisher — the same rules as
|
|
3
|
+
* src/host/ssh.ts, self-contained (a Herdr plugin ships this directory alone).
|
|
4
|
+
*
|
|
5
|
+
* The cloud relays `ssh.*` payloads opaquely; this module is the trusted decision point:
|
|
6
|
+
* only `hc …` runs (argv, shell:false); a `read` device gets a filtered plain-mode
|
|
7
|
+
* channel (mutating JSON-RPC methods refused here, framed downgraded, garbage cut off);
|
|
8
|
+
* an `act` device approved on this host gets byte-transparent access.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { existsSync } from "node:fs";
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
|
|
16
|
+
export const READ_METHODS = new Set([
|
|
17
|
+
"hello",
|
|
18
|
+
"rpc.discover",
|
|
19
|
+
"server.status",
|
|
20
|
+
"terminal.list",
|
|
21
|
+
"terminal.get",
|
|
22
|
+
"terminal.read",
|
|
23
|
+
"terminal.wait",
|
|
24
|
+
"templates.list",
|
|
25
|
+
"events.subscribe",
|
|
26
|
+
"doc.get",
|
|
27
|
+
"machine.list",
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
const FLUSH_MS = 20;
|
|
31
|
+
const FLUSH_BYTES = 64 * 1024;
|
|
32
|
+
const MAX_MALFORMED = 50;
|
|
33
|
+
|
|
34
|
+
export function resolveHc(env = process.env) {
|
|
35
|
+
const bin = (env.HERDGATE_HC_BIN ?? "").trim();
|
|
36
|
+
if (bin && existsSync(bin)) return bin;
|
|
37
|
+
const local = join(homedir(), ".local", "bin", "hc");
|
|
38
|
+
if (existsSync(local)) return local;
|
|
39
|
+
return existsSync("/usr/bin/hc") ? "/usr/bin/hc" : "hc";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
/** Extract `hc <verb>` from herdr-core's known machine-add probes (null = not one). */
|
|
44
|
+
export function translateBootstrap(cmd) {
|
|
45
|
+
const posix = cmd.match(/exec "\$p"\s+([^'"\n]+?)['"]?\s*$/);
|
|
46
|
+
if (posix) {
|
|
47
|
+
const args = posix[1].trim();
|
|
48
|
+
// Strict whitelist: flags, words, equals — never shell metacharacters.
|
|
49
|
+
if (/^[-a-z0-9][-a-z0-9 =]*$/i.test(args)) return `hc ${args}`;
|
|
50
|
+
}
|
|
51
|
+
const win = cmd.match(/herdr-core\.exe\)?\s+\(?([a-z][a-z0-9-]*)\)/);
|
|
52
|
+
if (win) return `hc ${win[1]}`;
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resolveHc, spawnImpl = spawn }) {
|
|
57
|
+
const channels = new Map();
|
|
58
|
+
const key = (device, ch) => `${device}:${ch}`;
|
|
59
|
+
|
|
60
|
+
const sendOut = (c, final, code, reason) => {
|
|
61
|
+
if (c.outBuf.length > 0) {
|
|
62
|
+
send(c.device, { op: "ssh.data", ch: c.ch, b64: c.outBuf.toString("base64") });
|
|
63
|
+
c.outBuf = Buffer.alloc(0);
|
|
64
|
+
}
|
|
65
|
+
if (final) {
|
|
66
|
+
send(c.device, { op: "ssh.closed", ch: c.ch, ...(code !== undefined ? { code } : {}), ...(reason ? { reason } : {}) });
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const scheduleFlush = (c) => {
|
|
70
|
+
if (c.flushTimer) return;
|
|
71
|
+
c.flushTimer = setTimeout(() => {
|
|
72
|
+
c.flushTimer = null;
|
|
73
|
+
if (!c.closed) sendOut(c, false);
|
|
74
|
+
}, FLUSH_MS);
|
|
75
|
+
c.flushTimer.unref?.();
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const refuseCall = (c, id, method) => {
|
|
79
|
+
const err = JSON.stringify({
|
|
80
|
+
jsonrpc: "2.0",
|
|
81
|
+
id: id ?? null,
|
|
82
|
+
error: { code: -32600, message: `herdgate: "${method}" needs the act scope (this device is read-only)`, data: { kind: "forbidden", method } },
|
|
83
|
+
});
|
|
84
|
+
c.outBuf = Buffer.concat([c.outBuf, Buffer.from(err + "\n")]);
|
|
85
|
+
scheduleFlush(c);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const feed = (c, buf) => {
|
|
89
|
+
if (c.closed || !c.proc?.stdin) return;
|
|
90
|
+
if (c.scope === "act") return void c.proc.stdin.write(buf);
|
|
91
|
+
c.inBuf = Buffer.concat([c.inBuf, buf]);
|
|
92
|
+
for (;;) {
|
|
93
|
+
const nl = c.inBuf.indexOf(0x0a);
|
|
94
|
+
if (nl < 0) break;
|
|
95
|
+
const line = c.inBuf.subarray(0, nl);
|
|
96
|
+
c.inBuf = c.inBuf.subarray(nl + 1);
|
|
97
|
+
const text = line.toString("utf8").trim();
|
|
98
|
+
if (!text) continue;
|
|
99
|
+
let msg = null;
|
|
100
|
+
try {
|
|
101
|
+
msg = JSON.parse(text);
|
|
102
|
+
} catch {
|
|
103
|
+
msg = null;
|
|
104
|
+
}
|
|
105
|
+
if (!msg || typeof msg !== "object" || typeof msg.method !== "string") {
|
|
106
|
+
c.malformed += 1;
|
|
107
|
+
if (c.malformed > MAX_MALFORMED) {
|
|
108
|
+
log(`ssh: ${c.device}/${c.ch} cut off after ${c.malformed} malformed lines`);
|
|
109
|
+
kill(c, "too much malformed input");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const { method } = msg;
|
|
115
|
+
if (method === "hello" && msg.params && typeof msg.params === "object" && msg.params.framed === true) {
|
|
116
|
+
msg.params.framed = false; // live terminals are write streams; read stays plain
|
|
117
|
+
log(`ssh: ${c.device}/${c.ch} hello framed:true downgraded (read scope)`);
|
|
118
|
+
}
|
|
119
|
+
if (!READ_METHODS.has(method)) {
|
|
120
|
+
refuseCall(c, msg.id, method);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
c.proc.stdin.write(JSON.stringify(msg) + "\n");
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const kill = (c, reason) => {
|
|
128
|
+
c.closed = true;
|
|
129
|
+
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
130
|
+
c.proc?.kill("SIGKILL");
|
|
131
|
+
channels.delete(key(c.device, c.ch));
|
|
132
|
+
sendOut(c, true, 130, reason);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
handle(device, payload) {
|
|
137
|
+
if (typeof payload !== "object" || payload === null) return false;
|
|
138
|
+
const op = payload.op;
|
|
139
|
+
if (typeof op !== "string" || !op.startsWith("ssh.")) return false;
|
|
140
|
+
const ch = typeof payload.ch === "string" ? payload.ch : "";
|
|
141
|
+
|
|
142
|
+
if (op === "ssh.open") {
|
|
143
|
+
const scope = scopeOf(device);
|
|
144
|
+
if (!scope) {
|
|
145
|
+
send(device, { op: "ssh.denied", ch, reason: "this device is not paired to this room" });
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
const cmd = typeof payload.cmd === "string" ? payload.cmd.trim() : "";
|
|
149
|
+
// herdr-core's `machine add` probes with shell wrappers that locate a binary
|
|
150
|
+
// named `herdr-core` and `exec` it. We never run shell lines: translate the
|
|
151
|
+
// KNOWN templates to `hc <verb>`; anything else shell-shaped is refused below.
|
|
152
|
+
const bootstrap = cmd.includes("herdr-core") ? translateBootstrap(cmd) : null;
|
|
153
|
+
const parts = (bootstrap ?? cmd).split(/\s+/).filter(Boolean);
|
|
154
|
+
if (parts.length > 0 && parts[0] === "exit" && (parts.length === 1 || parts[1] === "0")) {
|
|
155
|
+
// SSH clients end probe sessions with `exit` — acknowledge and close clean.
|
|
156
|
+
send(device, { op: "ssh.granted", ch, scope });
|
|
157
|
+
send(device, { op: "ssh.closed", ch, code: 0 });
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
160
|
+
if (parts.length === 0 || parts[0] !== "hc") {
|
|
161
|
+
send(device, { op: "ssh.denied", ch, reason: `herdgate bridges "hc …" only, got "${cmd.slice(0, 60) || "(empty)"}"` });
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
let proc;
|
|
165
|
+
try {
|
|
166
|
+
proc = spawnImpl(resolve(), parts.slice(1), { stdio: ["pipe", "pipe", "pipe"], shell: false });
|
|
167
|
+
} catch (e) {
|
|
168
|
+
send(device, { op: "ssh.denied", ch, reason: `could not start herdr-core: ${e.message}` });
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
const c = { device, ch, scope, proc, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
|
|
172
|
+
channels.set(key(device, ch), c);
|
|
173
|
+
const onData = (chunk) => {
|
|
174
|
+
c.outBuf = Buffer.concat([c.outBuf, chunk]);
|
|
175
|
+
if (c.outBuf.length >= FLUSH_BYTES) sendOut(c, false);
|
|
176
|
+
else scheduleFlush(c);
|
|
177
|
+
};
|
|
178
|
+
proc.stdout?.on("data", onData);
|
|
179
|
+
proc.stderr?.on("data", onData);
|
|
180
|
+
proc.on("error", (e) => {
|
|
181
|
+
const enoent = e.code === "ENOENT";
|
|
182
|
+
log(`ssh: spawn failed for ${device}/${ch}: ${e.message}`);
|
|
183
|
+
channels.delete(key(device, ch));
|
|
184
|
+
c.closed = true;
|
|
185
|
+
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
186
|
+
send(device, { op: "ssh.denied", ch, reason: enoent ? "herdr-core (hc) was not found on this host" : `could not start herdr-core: ${e.message}` });
|
|
187
|
+
});
|
|
188
|
+
proc.on("close", (code, signal) => {
|
|
189
|
+
if (c.closed) return;
|
|
190
|
+
c.closed = true;
|
|
191
|
+
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
192
|
+
channels.delete(key(device, ch));
|
|
193
|
+
sendOut(c, true, code ?? (signal ? 130 : 1), signal ? `terminated by ${signal}` : undefined);
|
|
194
|
+
});
|
|
195
|
+
send(device, { op: "ssh.granted", ch, scope });
|
|
196
|
+
log(`ssh: ${device}/${ch} → ${cmd} (${scope})`);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (op === "ssh.data") {
|
|
201
|
+
const c = channels.get(key(device, ch));
|
|
202
|
+
if (!c) return true;
|
|
203
|
+
const b64 = typeof payload.b64 === "string" ? payload.b64 : "";
|
|
204
|
+
if (b64.length > 400_000) return true;
|
|
205
|
+
feed(c, Buffer.from(b64, "base64"));
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (op === "ssh.close") {
|
|
210
|
+
const c = channels.get(key(device, ch));
|
|
211
|
+
if (!c) return true;
|
|
212
|
+
c.closed = true;
|
|
213
|
+
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
214
|
+
c.proc?.kill("SIGTERM");
|
|
215
|
+
channels.delete(key(device, ch));
|
|
216
|
+
sendOut(c, true, 0, "closed by the device");
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return false;
|
|
221
|
+
},
|
|
222
|
+
dropDevice(device) {
|
|
223
|
+
for (const [k, c] of [...channels]) {
|
|
224
|
+
if (c.device === device) {
|
|
225
|
+
c.closed = true;
|
|
226
|
+
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
227
|
+
c.proc?.kill("SIGTERM");
|
|
228
|
+
channels.delete(k);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
closeAll() {
|
|
233
|
+
for (const [, c] of [...channels]) {
|
|
234
|
+
c.closed = true;
|
|
235
|
+
if (c.flushTimer) clearTimeout(c.flushTimer);
|
|
236
|
+
c.proc?.kill("SIGTERM");
|
|
237
|
+
}
|
|
238
|
+
channels.clear();
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|