@bom0792/herdgate 0.9.34 → 0.9.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -148,6 +148,17 @@ so the host is the last trusted decision point. `act` scope is denied unless `HE
148
148
 
149
149
  ## Herdr TUI → an existing Herdr session
150
150
 
151
+ On the controlling machine, `herdgate connect` does the whole client side in one
152
+ command: device pairing (read or act), one SSH key per cloud, and the matching
153
+ `~/.ssh/config` blocks. The owner token is asked once on a hidden prompt and is
154
+ never stored; afterwards only per-device SSH keys remain on that machine.
155
+
156
+ ```sh
157
+ herdgate connect --cloud <name> --room home --scope act
158
+ ```
159
+
160
+ The manual equivalent, kept for reference and for non-CLI clients:
161
+
151
162
  This is separate from `hc machine add` and the PWA. On the client use the official
152
163
  [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.
153
164
 
@@ -12,8 +12,11 @@ export function cloudOrigin(raw) {
12
12
  let url;
13
13
  try { url = new URL(raw); }
14
14
  catch { throw new Error('cloud must be a credential-free HTTPS origin'); }
15
- if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
16
- throw new Error('cloud must be a credential-free HTTPS origin');
15
+ // Plain HTTP only for local development against a loopback gate (same rule as templates/herdgate-via.mjs).
16
+ const loopbackHttp = url.protocol === 'http:' && ['127.0.0.1', 'localhost', '::1'].includes(url.hostname);
17
+ if (url.username || url.password || url.pathname !== '/' || url.search || url.hash ||
18
+ (url.protocol !== 'https:' && !loopbackHttp)) {
19
+ throw new Error('cloud must be a credential-free HTTPS origin (HTTP only for local development)');
17
20
  }
18
21
  return url.origin;
19
22
  }
@@ -29,6 +32,10 @@ function load() {
29
32
  }));
30
33
  }
31
34
 
35
+ export function listClouds() {
36
+ return [...load()];
37
+ }
38
+
32
39
  export function resolveCloud(input) {
33
40
  if (validName.test(input)) {
34
41
  const origin = load().get(input);
package/bin/herdgate.mjs CHANGED
@@ -6,11 +6,12 @@
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
8
  import { cpSync, mkdirSync, writeFileSync, existsSync, readFileSync, realpathSync, rmdirSync } from "node:fs";
9
+ import readline from "node:readline";
9
10
  import { join, dirname, basename } from "node:path";
10
11
  import { homedir, hostname } from "node:os";
11
12
  import { spawnSync } from "node:child_process";
12
13
  import { fileURLToPath } from "node:url";
13
- import { manageCloud, resolveCloud } from "./cloud-config.mjs";
14
+ import { listClouds, manageCloud, resolveCloud } from "./cloud-config.mjs";
14
15
  import { trySyncPiSkills } from "./pi-skills.mjs";
15
16
  import { readConfig } from "../plugin/server/common.mjs";
16
17
  import { withLatest } from "../windows/npm-update.mjs";
@@ -26,6 +27,10 @@ const help = `herdgate — every machine, one herd
26
27
  herdgate cloud add <name> <https-url>
27
28
  herdgate cloud list
28
29
  herdgate cloud serve Run a self-hosted Gate from the full npm package (uses HERDGATE_* env).
30
+ herdgate connect [--cloud <name>] [--room <id|name>]... [--scope read|act]
31
+ Pair THIS machine as a controller of machines already in the herd: one SSH
32
+ key per cloud, one ~/.ssh/config Host per machine. Asks for the owner token
33
+ once on a hidden prompt; the token and device secrets are never stored.
29
34
  herdgate pair --cloud <name> Pair this machine with owner approval.
30
35
  herdgate setup [--cloud <name>] [--mobile-act <device-id>]
31
36
  Install/configure the publisher for this OS.
@@ -120,15 +125,16 @@ code in the PWA (${cloud}) and click Publish. Requires node >= 22 on PATH
120
125
  for the publisher (node -v).`);
121
126
  if (!arg("no-integrate")) integrate(home);
122
127
  // The other direction — THIS machine controlling one that is already paired —
123
- // needs one command. Print it ready to paste (cmd expands %USERPROFILE%).
128
+ // is one command:
124
129
  const viaPath = join(base, "bin", "herdgate-via.mjs");
125
130
  if (existsSync(viaPath)) {
126
131
  console.log(`
127
132
  To connect FROM this machine to another machine in the herd (no admin,
128
- works on IPv4-only networks — ssh over wss/443), first:
129
- ssh-keygen -t ed25519 -f "%USERPROFILE%\\.ssh\\herdgate" -N "" -q
130
- and register the printed key in the PWA (machine → Public keys). Then:
131
- hc machine add --name home --via "node ${viaPath} --gate ${cloud} --user <device-id>"`);
133
+ works on IPv4-only networks — ssh over wss/443), run instead:
134
+ herdgate connect --room <name> --scope act
135
+ It pairs the device, keeps one SSH key per cloud and writes the
136
+ ~/.ssh/config blocks; the owner token is asked on a hidden prompt and never
137
+ stored. (Add --cloud <name> when more than one cloud is configured.)`);
132
138
  }
133
139
  }
134
140
 
@@ -348,6 +354,202 @@ function managePublisher(cmd, args) {
348
354
  return runNode(join(HERE, "home-tui.mjs"), [cmd, ...options]);
349
355
  }
350
356
 
357
+ // ---- connect: this machine as a CONTROLLER of machines already in the herd ----
358
+ //
359
+ // `pair`/`setup` publish this machine's own TUI; `connect` is the other
360
+ // direction in one command: pair this machine as a device into other machines'
361
+ // rooms, register one SSH key per cloud, and write the matching ~/.ssh/config
362
+ // Host blocks. The owner token is asked for once on a hidden prompt and never
363
+ // stored — afterwards this machine holds only per-device SSH keys, each
364
+ // independently revocable from the PWA roster.
365
+
366
+ const connectUsage = "usage: herdgate connect [--cloud <name>] [--room <id|name>]... [--scope read|act] [--name <label>]";
367
+
368
+ function repeatArg(name) {
369
+ const out = [];
370
+ for (let i = 2; i < process.argv.length - 1; i++) {
371
+ if (process.argv[i] === `--${name}` && process.argv[i + 1]) out.push(process.argv[i + 1]);
372
+ }
373
+ return out;
374
+ }
375
+
376
+ /** Hidden prompt on a terminal; plain stdin read when piped. Never a flag/env value. */
377
+ function promptSecret(question) {
378
+ return new Promise((resolve, reject) => {
379
+ let rl;
380
+ try { rl = readline.createInterface({ input: process.stdin, output: process.stdout }); }
381
+ catch (e) { return reject(e); }
382
+ process.stdout.write(question);
383
+ if (process.stdout.isTTY) rl._writeToOutput = () => {};
384
+ rl.question("", (answer) => { try { rl.close(); } catch { /* already gone */ } resolve(answer.trim()); });
385
+ });
386
+ }
387
+
388
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
389
+
390
+ function gateWs(origin) {
391
+ const url = origin.replace(/^http/, "ws") + "/v1/device/ws";
392
+ const ws = new WebSocket(url);
393
+ const opened = new Promise((resolve, reject) => {
394
+ const timer = setTimeout(() => reject(new Error(`cannot reach ${url} in time`)), 8_000);
395
+ ws.addEventListener("open", () => { clearTimeout(timer); resolve(); }, { once: true });
396
+ ws.addEventListener("error", () => { clearTimeout(timer); reject(new Error(`cannot reach ${url}`)); }, { once: true });
397
+ });
398
+ return { ws, opened };
399
+ }
400
+
401
+ function gateNext(ws, wanted, timeoutMs = 70_000) {
402
+ const want = Array.isArray(wanted) ? wanted : [wanted];
403
+ return new Promise((resolve, reject) => {
404
+ const timer = setTimeout(() => done(new Error(`the gate did not answer (${want.join("/")}) in time`)), timeoutMs);
405
+ const onMessage = (ev) => {
406
+ let m;
407
+ try { m = JSON.parse(String(ev.data)); } catch { return; }
408
+ if (m.t === "error") return done(new Error(`the gate refused: ${m.message ?? m.code}`));
409
+ if (want.includes(m.t)) done(null, m);
410
+ };
411
+ const onClose = () => done(new Error("the gate closed the connection"));
412
+ function done(err, m) {
413
+ clearTimeout(timer);
414
+ ws.removeEventListener("message", onMessage);
415
+ ws.removeEventListener("close", onClose);
416
+ if (err) reject(err);
417
+ else resolve(m);
418
+ }
419
+ ws.addEventListener("message", onMessage);
420
+ ws.addEventListener("close", onClose);
421
+ });
422
+ }
423
+
424
+ /** Replace (or add) this room's managed block; returns the previous alias if any. */
425
+ function upsertSshBlock({ sshConfig, cloudKey, roomId, alias, deviceId, keyFile, viaPath, origin }) {
426
+ const begin = `# herdgate connect:begin ${cloudKey} ${roomId}`;
427
+ const end = `# herdgate connect:end ${cloudKey} ${roomId}`;
428
+ let text = existsSync(sshConfig) ? readFileSync(sshConfig, "utf8") : "";
429
+ let previousAlias = null;
430
+ text = text.replace(new RegExp(`${escapeRe(begin)}\\n([\\s\\S]*?)${escapeRe(end)}\\n?`, "g"), (_all, body) => {
431
+ const hit = body.match(/^Host\s+(\\S+)/m);
432
+ if (hit) previousAlias = hit[1];
433
+ return "";
434
+ });
435
+ const taken = new Set((text.match(/^Host\s+(\\S+)/gm) ?? []).map((l) => l.replace(/^Host\s+/, "").split(/\\s+/)[0]));
436
+ let chosen = previousAlias && !taken.has(previousAlias) ? previousAlias : alias;
437
+ let n = 2;
438
+ while (taken.has(chosen)) chosen = `${alias}-${n++}`;
439
+ const block = [
440
+ `Host ${chosen}`,
441
+ ` HostName ${chosen}`,
442
+ ` User ${deviceId}`,
443
+ ` IdentityFile ${keyFile}`,
444
+ ` HostKeyAlias herdgate-${cloudKey}`,
445
+ ` ProxyCommand node ${viaPath} --tunnel --gate ${origin}`,
446
+ ].join("\n");
447
+ const trimmed = text.replace(/\n*$/, "");
448
+ mkdirSync(dirname(sshConfig), { recursive: true, mode: 0o700 });
449
+ writeFileSync(sshConfig, `${trimmed ? trimmed + "\n\n" : ""}${begin}\n${block}\n${end}\n`, { mode: 0o600 });
450
+ return chosen;
451
+ }
452
+
453
+ async function connectController() {
454
+ const clouds = listClouds();
455
+ const cloudInput = arg("cloud") ?? (clouds.length === 1 ? clouds[0][0] : null);
456
+ if (!cloudInput) throw new Error(`${connectUsage}\n no --cloud given and ${clouds.length} clouds configured; see herdgate cloud list`);
457
+ const origin = resolveCloud(cloudInput);
458
+ const cloudKey = (/^[a-z0-9][a-z0-9_-]{0,31}$/.test(cloudInput) ? cloudInput : new URL(origin).hostname)
459
+ .toLowerCase().replace(/[^a-z0-9-]+/g, "-");
460
+ const scope = arg("scope") ?? "read";
461
+ if (scope !== "read" && scope !== "act") throw new Error("--scope must be read or act");
462
+ const deviceName = (arg("name") ?? hostname()).slice(0, 64);
463
+
464
+ const token = await promptSecret(`Owner token for ${origin} (hidden, not stored): `);
465
+ if (!token) throw new Error("an owner token is required to pair this machine");
466
+
467
+ const { ws, opened } = gateWs(origin);
468
+ await opened;
469
+ try {
470
+ ws.send(JSON.stringify({ v: 1, t: "hello", accountToken: token }));
471
+ const hello = await gateNext(ws, "hello", 10_000);
472
+ const agents = Array.isArray(hello.agents) ? hello.agents : [];
473
+ if (!agents.length) throw new Error("this account has no machines to manage yet; pair a host first (herdgate pair)");
474
+
475
+ const wanted = repeatArg("room");
476
+ const rooms = [];
477
+ if (wanted.length) {
478
+ for (const w of wanted) {
479
+ const hit = agents.find((a) => a.roomId === w || String(a.name ?? "").toLowerCase() === w.toLowerCase());
480
+ if (!hit) throw new Error(`no machine matches --room '${w}'; available: ${agents.map((a) => `${a.name} (${a.roomId})`).join(", ")}`);
481
+ if (!rooms.includes(hit)) rooms.push(hit);
482
+ }
483
+ } else if (process.stdin.isTTY) {
484
+ console.log("Machines in this herd:");
485
+ agents.forEach((a, i) => console.log(` ${i + 1}. ${a.name} (${a.roomId})${a.online ? "" : " — host offline"}`));
486
+ const answer = await new Promise((resolve) => {
487
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
488
+ rl.question("Connect to (numbers or names, comma-separated): ", (a) => { rl.close(); resolve(a); });
489
+ });
490
+ for (const part of answer.split(/[\s,]+/).filter(Boolean)) {
491
+ const n = Number(part);
492
+ const hit = (Number.isInteger(n) && n >= 1 && n <= agents.length) ? agents[n - 1]
493
+ : agents.find((a) => a.roomId === part || String(a.name ?? "").toLowerCase() === part.toLowerCase());
494
+ if (!hit) throw new Error(`nothing selected matches '${part}'`);
495
+ if (!rooms.includes(hit)) rooms.push(hit);
496
+ }
497
+ if (!rooms.length) throw new Error("no machine selected");
498
+ } else {
499
+ throw new Error(`${connectUsage}\n stdin is not a terminal; pass --room per machine`);
500
+ }
501
+
502
+ // One key per cloud on this machine. The same public key may serve several
503
+ // devices (like the phone app does); each device stays independently revocable.
504
+ const sshDir = join(homedir(), ".ssh");
505
+ mkdirSync(sshDir, { recursive: true, mode: 0o700 });
506
+ const keyFile = join(sshDir, `herdgate_${cloudKey}`);
507
+ if (!existsSync(keyFile)) {
508
+ const r = spawnSync("ssh-keygen", ["-t", "ed25519", "-N", "", "-q", "-f", keyFile], { shell: false });
509
+ if (r.status !== 0) throw new Error(`could not create ${keyFile} with ssh-keygen; create an ed25519 key there and re-run`);
510
+ }
511
+ const pubKey = readFileSync(`${keyFile}.pub`, "utf8").trim();
512
+
513
+ // The --via transport ships with this package; keep a copy beside the key.
514
+ const viaPath = join(sshDir, `herdgate-via-${cloudKey}.mjs`);
515
+ cpSync(join(ROOT, "templates", "herdgate-via.mjs"), viaPath);
516
+ if (/\s/.test(viaPath)) {
517
+ console.error(`herdgate: warning: ${viaPath} contains spaces; OpenSSH's ProxyCommand cannot quote it — move the profile or configure Host manually`);
518
+ }
519
+
520
+ const sshConfig = join(sshDir, "config");
521
+ const results = [];
522
+ for (const room of rooms) {
523
+ ws.send(JSON.stringify({ v: 1, t: "pair.begin", roomId: room.roomId, scope, name: `${deviceName} (cli)` }));
524
+ const answer = await gateNext(ws, ["pair.granted", "pair.denied"], 70_000);
525
+ if (answer.t === "pair.denied") throw new Error(`pairing with ${room.name} was denied: ${answer.reason ?? "denied"}`);
526
+ const deviceId = answer.device?.id;
527
+ const deviceSecret = answer.deviceSecret;
528
+ if (!deviceId || !deviceSecret) throw new Error("the gate granted the pair without device credentials");
529
+ const res = await fetch(`${origin}/v1/device/sshkey`, {
530
+ method: "POST",
531
+ headers: { "content-type": "application/json" },
532
+ body: JSON.stringify({ device: deviceId, deviceSecret, pubkey: pubKey }),
533
+ });
534
+ const out = await res.json().catch(() => ({}));
535
+ if (!res.ok || out.ok !== true) throw new Error(`registering the SSH key for ${room.name} failed (HTTP ${res.status})`);
536
+ const base = String(room.name || room.roomId).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "herd";
537
+ const alias = upsertSshBlock({ sshConfig, cloudKey, roomId: room.roomId, alias: base, deviceId, keyFile, viaPath, origin });
538
+ results.push({ room, alias, deviceId, fp: out.fp });
539
+ }
540
+ console.log(`paired this machine with ${results.length} machine(s) on ${origin} (scope ${scope}):`);
541
+ for (const r of results) {
542
+ console.log(` ${r.room.name} → ssh host '${r.alias}' (device ${r.deviceId}, key ${r.fp})`);
543
+ console.log(` herdr machine add ${r.alias} --label ${JSON.stringify(String(r.room.name))} --remote-session default`);
544
+ }
545
+ console.log("The owner token and device secrets were not stored. The first ssh connection pins the gate's host key.");
546
+ console.log("If this machine was connected before, revoke its previous device in the PWA roster.");
547
+ } finally {
548
+ try { ws.close(); } catch { /* already gone */ }
549
+ }
550
+ process.exit(0);
551
+ }
552
+
351
553
  const [cmd, ...args] = process.argv.slice(2);
352
554
  try {
353
555
  if (cmd === "setup-host") {
@@ -359,9 +561,10 @@ try {
359
561
  if (!existsSync(entry)) throw new Error("cloud serve requires the full npm package; use the Cloud archive for Docker or systemd");
360
562
  runNode(entry, []);
361
563
  } else if (cmd === "cloud") manageCloud(args);
564
+ else if (cmd === "connect") await connectController();
362
565
  else if (cmd === "pair") pairHost(args);
363
566
  else if (process.platform === "win32" && (
364
- ["install", "setup", "migrate", "start", "update", "install-tui"].includes(cmd) ||
567
+ ["install", "setup", "migrate", "start", "update", "install-tui", "connect"].includes(cmd) ||
365
568
  (cmd === "tui" && ["setup", "migrate", "start", "update"].includes(args[0]))
366
569
  ) && (Number(process.versions.node.split(".")[0]) < 22 || typeof globalThis.WebSocket !== "function")) {
367
570
  const node = windowsNode();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.34",
3
+ "version": "0.9.35",
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": {
@@ -71,4 +71,4 @@
71
71
  "tsconfig.cloud.json",
72
72
  "windows/*.mjs"
73
73
  ]
74
- }
74
+ }