@bom0792/herdgate 0.9.19 → 0.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ // Per-user controls for the TUI publisher. No control port, service, or PID-based kill.
2
+ import { spawn } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+
8
+ const lockPath = (dir) => join(dir, "publisher-tui.lock");
9
+ const logPath = (dir) => join(dir, "publisher-tui.log");
10
+ const marker = (dir, run, kind) => join(dir, `publisher-tui-${run}.${kind}`);
11
+
12
+ function ownerOf(dir) {
13
+ try {
14
+ const { run, pid } = JSON.parse(readFileSync(lockPath(dir), "utf8"));
15
+ if (typeof run === "string" && /^[a-f0-9-]{36}$/.test(run) && Number.isSafeInteger(pid) && pid > 0) return { run, pid };
16
+ } catch (e) {
17
+ if (e.code !== "ENOENT" && !(e instanceof SyntaxError)) throw e;
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function isAlive(pid) {
23
+ try { process.kill(pid, 0); return true; }
24
+ catch (e) { if (e.code === "ESRCH") return false; throw e; }
25
+ }
26
+
27
+ export function publisherStatus(dir) {
28
+ const own = ownerOf(dir);
29
+ const log = logPath(dir);
30
+ if (!own) return { state: existsSync(lockPath(dir)) ? "starting" : "stopped", log };
31
+ const { pid, run } = own;
32
+ const state = !isAlive(pid) ? "stale" : existsSync(marker(dir, run, "stop")) ? "stopping" :
33
+ existsSync(marker(dir, run, "connected")) ? "connected" : "connecting";
34
+ return { state, pid, log };
35
+ }
36
+
37
+ export function registerPublisher(dir, run, requestStop) {
38
+ if (typeof run !== "string" || !/^[a-f0-9-]{36}$/.test(run)) throw new Error("invalid publisher run id; use start");
39
+ mkdirSync(dir, { recursive: true });
40
+ writeFileSync(lockPath(dir), JSON.stringify({ run, pid: process.pid }), { flag: "wx", mode: 0o600 });
41
+ const connected = marker(dir, run, "connected");
42
+ const stop = marker(dir, run, "stop");
43
+ const poll = setInterval(() => {
44
+ if (existsSync(stop)) requestStop();
45
+ }, 250);
46
+ const release = () => {
47
+ clearInterval(poll);
48
+ rmSync(connected, { force: true });
49
+ rmSync(stop, { force: true });
50
+ if (ownerOf(dir)?.run === run) rmSync(lockPath(dir), { force: true });
51
+ };
52
+ process.once("exit", release);
53
+ return {
54
+ release,
55
+ setConnected(ok) {
56
+ if (ok) writeFileSync(connected, "", { mode: 0o600 });
57
+ else rmSync(connected, { force: true });
58
+ },
59
+ };
60
+ }
61
+
62
+ export async function startPublisher(dir, args, env = process.env) {
63
+ mkdirSync(dir, { recursive: true });
64
+ const initial = publisherStatus(dir);
65
+ if (initial.state !== "stopped") return initial;
66
+ const fd = openSync(logPath(dir), "a", 0o600);
67
+ let child;
68
+ try {
69
+ child = spawn(process.execPath, args, {
70
+ detached: true,
71
+ windowsHide: true,
72
+ stdio: ["ignore", fd, fd],
73
+ env: { ...env, HERDGATE_TUI_RUN_ID: randomUUID() },
74
+ });
75
+ await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
76
+ } finally {
77
+ closeSync(fd);
78
+ }
79
+ child.unref();
80
+ // Do not confuse a spawned Node process with successful authentication.
81
+ const deadline = Date.now() + 5_000;
82
+ while (Date.now() < deadline) {
83
+ const status = publisherStatus(dir);
84
+ if (status.state === "connected" || (status.pid && status.pid !== child.pid)) return status;
85
+ if (child.exitCode !== null || child.signalCode !== null) break;
86
+ await delay(125);
87
+ }
88
+ const status = publisherStatus(dir);
89
+ if (status.state === "connecting") return status;
90
+ throw new Error(`publisher did not start; see ${logPath(dir)}`);
91
+ }
92
+
93
+ export async function stopPublisher(dir) {
94
+ const own = ownerOf(dir);
95
+ if (!own) return publisherStatus(dir);
96
+ const stop = marker(dir, own.run, "stop");
97
+ if (isAlive(own.pid)) {
98
+ // The run-specific request cannot signal a new publisher or a reused PID.
99
+ writeFileSync(stop, "", { mode: 0o600 });
100
+ for (let i = 0; i < 32 && ownerOf(dir)?.run === own.run && isAlive(own.pid); i++) await delay(125);
101
+ }
102
+ if (ownerOf(dir)?.run === own.run && !isAlive(own.pid)) {
103
+ const reap = marker(dir, own.run, "reap");
104
+ try { writeFileSync(reap, "", { flag: "wx", mode: 0o600 }); }
105
+ catch (e) { if (e.code === "EEXIST") return publisherStatus(dir); throw e; }
106
+ try {
107
+ rmSync(marker(dir, own.run, "connected"), { force: true });
108
+ rmSync(stop, { force: true });
109
+ if (ownerOf(dir)?.run === own.run) rmSync(lockPath(dir), { force: true });
110
+ } finally {
111
+ rmSync(reap, { force: true });
112
+ }
113
+ } else if (ownerOf(dir)?.run !== own.run) {
114
+ rmSync(stop, { force: true });
115
+ }
116
+ return publisherStatus(dir);
117
+ }
@@ -0,0 +1,23 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+
3
+ export interface SshBridgeOptions {
4
+ send(device: string, payload: Record<string, unknown>): void;
5
+ scopeOf(device: string): "read" | "act" | null;
6
+ log?(line: string): void;
7
+ resolve?: () => string | null;
8
+ resolveHerdrBin?: () => string | null;
9
+ session?: string;
10
+ platform?: NodeJS.Platform;
11
+ tuiOnly?: boolean;
12
+ spawnImpl?: (bin: string, args: string[], opts: { stdio: ("pipe" | null)[]; shell: boolean; windowsHide?: boolean; env?: NodeJS.ProcessEnv }) => ChildProcess;
13
+ }
14
+
15
+ export interface SshBridge {
16
+ handle(device: string, payload: unknown): boolean;
17
+ dropDevice(device: string): void;
18
+ closeAll(): void;
19
+ }
20
+
21
+ export const READ_METHODS: Set<string>;
22
+ export function translateBootstrap(cmd: string): string | null;
23
+ export function createSshBridge(options: SshBridgeOptions): SshBridge;
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { spawn } from "node:child_process";
12
+ import { MARKER, resolveHerdr, translateHerdr } from "./herdr-ssh.mjs";
12
13
  import { existsSync } from "node:fs";
13
14
  import { homedir } from "node:os";
14
15
  import { join } from "node:path";
@@ -53,7 +54,7 @@ export function translateBootstrap(cmd) {
53
54
  return null;
54
55
  }
55
56
 
56
- export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resolveHc, spawnImpl = spawn }) {
57
+ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resolveHc, resolveHerdrBin = resolveHerdr, session = process.env.HERDGATE_HERDR_SESSION || process.env.HERDR_SESSION || "default", platform = process.platform, tuiOnly = false, spawnImpl = spawn }) {
57
58
  const channels = new Map();
58
59
  const key = (device, ch) => `${device}:${ch}`;
59
60
 
@@ -86,9 +87,11 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
86
87
  };
87
88
 
88
89
  const feed = (c, buf) => {
89
- if (c.closed || !c.proc?.stdin) return;
90
+ if (c.closed || !c.proc?.stdin?.writable) return;
91
+ if (c.proc.stdin.writableLength + buf.length > 1024 * 1024) return kill(c, "input queue limit");
90
92
  if (c.scope === "act") return void c.proc.stdin.write(buf);
91
93
  c.inBuf = Buffer.concat([c.inBuf, buf]);
94
+ if (c.inBuf.length > 1024 * 1024) return kill(c, "input line too long");
92
95
  for (;;) {
93
96
  const nl = c.inBuf.indexOf(0x0a);
94
97
  if (nl < 0) break;
@@ -127,11 +130,72 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
127
130
  const kill = (c, reason) => {
128
131
  c.closed = true;
129
132
  if (c.flushTimer) clearTimeout(c.flushTimer);
133
+ if (c.deadline) clearTimeout(c.deadline);
130
134
  c.proc?.kill("SIGKILL");
131
135
  channels.delete(key(c.device, c.ch));
132
136
  sendOut(c, true, 130, reason);
133
137
  };
134
138
 
139
+ const start = (device, ch, scope, bin, args, tui = false, closeStdin = false) => {
140
+ let proc;
141
+ try {
142
+ proc = spawnImpl(bin, args, { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, ...(tui ? { env: { ...process.env, HERDR_SESSION: session } } : {}) });
143
+ } catch (e) {
144
+ send(device, { op: "ssh.denied", ch, reason: `could not start bridged process: ${e.message}` });
145
+ return;
146
+ }
147
+ const c = { device, ch, scope, proc, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
148
+ channels.set(key(device, ch), c);
149
+ const onData = (chunk) => {
150
+ c.outBuf = Buffer.concat([c.outBuf, chunk]);
151
+ if (c.outBuf.length >= FLUSH_BYTES) sendOut(c, false);
152
+ else scheduleFlush(c);
153
+ };
154
+ proc.stdout?.on("data", onData);
155
+ if (tui) {
156
+ send(device, { op: "ssh.data", ch, b64: Buffer.from(MARKER).toString("base64") });
157
+ proc.stderr?.on("data", (buf) => {
158
+ if (!c.closed) send(device, { op: "ssh.data", ch, stderr: true, b64: buf.toString("base64") });
159
+ });
160
+ } else {
161
+ proc.stderr?.on("data", onData);
162
+ }
163
+ proc.stdin?.on("error", () => { /* child exited before consuming all input */ });
164
+ if (closeStdin) proc.stdin?.end();
165
+ if (closeStdin && !args.includes("remote-client-bridge")) {
166
+ c.deadline = setTimeout(() => kill(c, "Herdr probe timed out"), 8000);
167
+ c.deadline.unref();
168
+ }
169
+ proc.on("error", (e) => {
170
+ if (c.closed) return;
171
+ const enoent = e.code === "ENOENT";
172
+ log(`ssh: spawn failed for ${device}/${ch}: ${e.message}`);
173
+ channels.delete(key(device, ch));
174
+ c.closed = true;
175
+ if (c.flushTimer) clearTimeout(c.flushTimer);
176
+ if (c.deadline) clearTimeout(c.deadline);
177
+ send(device, { op: "ssh.denied", ch, reason: enoent ? `${tui ? "Herdr" : "herdr-core (hc)"} was not found on this host` : `could not start bridged process: ${e.message}` });
178
+ });
179
+ proc.on("close", (code, signal) => {
180
+ if (c.closed) return;
181
+ c.closed = true;
182
+ if (c.flushTimer) clearTimeout(c.flushTimer);
183
+ if (c.deadline) clearTimeout(c.deadline);
184
+ channels.delete(key(device, ch));
185
+ sendOut(c, true, code ?? (signal ? 130 : 1), signal ? `terminated by ${signal}` : undefined);
186
+ });
187
+ log(`ssh: ${device}/${ch} → ${tui ? "herdr " : "hc "}${args.join(" ")} (${scope})`);
188
+ };
189
+
190
+ const handleTui = (device, ch, scope, bin, result) => {
191
+ if (result.reply !== undefined) {
192
+ if (result.reply) send(device, { op: "ssh.data", ch, b64: Buffer.from(result.reply).toString("base64") });
193
+ send(device, { op: "ssh.closed", ch, code: result.code ?? 0 });
194
+ } else {
195
+ start(device, ch, scope, bin, result.args, true, result.closeStdin);
196
+ }
197
+ };
198
+
135
199
  return {
136
200
  handle(device, payload) {
137
201
  if (typeof payload !== "object" || payload === null) return false;
@@ -146,6 +210,24 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
146
210
  return true;
147
211
  }
148
212
  const cmd = typeof payload.cmd === "string" ? payload.cmd.trim() : "";
213
+ if (!ch || channels.has(key(device, ch))) return true;
214
+ if (scope === "act") {
215
+ const bin = resolveHerdrBin();
216
+ const result = translateHerdr(cmd, { bin, session, os: platform });
217
+ const script = bin && cmd === "/bin/sh -s";
218
+ if (result || script) {
219
+ send(device, { op: "ssh.granted", ch, scope });
220
+ if (result) {
221
+ handleTui(device, ch, scope, bin, result);
222
+ } else {
223
+ const c = { device, ch, scope, bin, script: Buffer.alloc(0), outBuf: Buffer.alloc(0), closed: false };
224
+ channels.set(key(device, ch), c);
225
+ c.deadline = setTimeout(() => kill(c, "Herdr probe stdin timed out"), 8000);
226
+ c.deadline.unref();
227
+ }
228
+ return true;
229
+ }
230
+ }
149
231
  // herdr-core's `machine add` probes with shell wrappers that locate a binary
150
232
  // named `herdr-core` and `exec` it. We never run shell lines: translate the
151
233
  // KNOWN templates to `hc <verb>`; anything else shell-shaped is refused below.
@@ -157,52 +239,52 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
157
239
  send(device, { op: "ssh.closed", ch, code: 0 });
158
240
  return true;
159
241
  }
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)"}"` });
242
+ if (tuiOnly || parts.length === 0 || parts[0] !== "hc") {
243
+ send(device, { op: "ssh.denied", ch, reason: scope === "read" ? "this command is not available to read devices" : "not a supported Herdr or herdr-core command" });
162
244
  return true;
163
245
  }
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
246
  send(device, { op: "ssh.granted", ch, scope });
196
- log(`ssh: ${device}/${ch} → ${cmd} (${scope})`);
247
+ start(device, ch, scope, resolve() ?? "hc", parts.slice(1));
197
248
  return true;
198
249
  }
199
250
 
200
251
  if (op === "ssh.data") {
201
252
  const c = channels.get(key(device, ch));
202
253
  if (!c) return true;
254
+ if (scopeOf(device) !== c.scope) {
255
+ kill(c, "device permission changed");
256
+ return true;
257
+ }
203
258
  const b64 = typeof payload.b64 === "string" ? payload.b64 : "";
204
259
  if (b64.length > 400_000) return true;
205
- feed(c, Buffer.from(b64, "base64"));
260
+ const buf = Buffer.from(b64, "base64");
261
+ if (c.script) {
262
+ if (c.script.length + buf.length > 8192) kill(c, "Herdr probe stdin limit");
263
+ else c.script = Buffer.concat([c.script, buf]);
264
+ } else {
265
+ feed(c, buf);
266
+ }
267
+ return true;
268
+ }
269
+
270
+ if (op === "ssh.eof") {
271
+ const c = channels.get(key(device, ch));
272
+ if (!c) return true;
273
+ if (c.script) {
274
+ clearTimeout(c.deadline);
275
+ channels.delete(key(device, ch));
276
+ const result = scopeOf(device) === "act" && translateHerdr(c.script.toString("utf8"), { bin: c.bin, session, stdin: true, os: platform });
277
+ if (result) {
278
+ handleTui(device, ch, c.scope, c.bin, result);
279
+ } else {
280
+ log(`ssh: ${device}/${ch} rejected Herdr stdin probe (${c.script.length} bytes)`);
281
+ const b64 = Buffer.from("herdgate: unsupported Herdr probe or device permission changed; no shell executed\n").toString("base64");
282
+ send(device, { op: "ssh.data", ch, b64, stderr: true });
283
+ send(device, { op: "ssh.closed", ch, code: 111 });
284
+ }
285
+ } else if (c.proc?.stdin?.writable) {
286
+ c.proc.stdin.end();
287
+ }
206
288
  return true;
207
289
  }
208
290
 
@@ -211,6 +293,7 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
211
293
  if (!c) return true;
212
294
  c.closed = true;
213
295
  if (c.flushTimer) clearTimeout(c.flushTimer);
296
+ if (c.deadline) clearTimeout(c.deadline);
214
297
  c.proc?.kill("SIGTERM");
215
298
  channels.delete(key(device, ch));
216
299
  sendOut(c, true, 0, "closed by the device");
@@ -224,6 +307,7 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
224
307
  if (c.device === device) {
225
308
  c.closed = true;
226
309
  if (c.flushTimer) clearTimeout(c.flushTimer);
310
+ if (c.deadline) clearTimeout(c.deadline);
227
311
  c.proc?.kill("SIGTERM");
228
312
  channels.delete(k);
229
313
  }
@@ -233,6 +317,7 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
233
317
  for (const [, c] of [...channels]) {
234
318
  c.closed = true;
235
319
  if (c.flushTimer) clearTimeout(c.flushTimer);
320
+ if (c.deadline) clearTimeout(c.deadline);
236
321
  c.proc?.kill("SIGTERM");
237
322
  }
238
323
  channels.clear();
@@ -6,8 +6,8 @@ OUT=$(mktemp -d)
6
6
  trap 'rm -rf "$OUT"' EXIT
7
7
  mkdir -p "$OUT/herdgate-host/mod"
8
8
  cp -r "$DIR/app-mod/herdgate" "$OUT/herdgate-host/mod/"
9
- cp -r "$DIR/plugin" "$OUT/herdgate-host/"
9
+ cp -r "$DIR/plugin" "$DIR/windows" "$OUT/herdgate-host/"
10
10
  cp "$DIR/dist-readme.md" "$OUT/herdgate-host/README.md"
11
- rm -f "$DIR/src/web/herdgate-host.zip"
12
- ( cd "$OUT/herdgate-host" && zip -qr "$DIR/src/web/herdgate-host.zip" mod plugin README.md )
11
+ ( cd "$OUT/herdgate-host" && zip -qr "$OUT/herdgate-host.zip" mod plugin windows README.md )
12
+ mv "$OUT/herdgate-host.zip" "$DIR/src/web/herdgate-host.zip"
13
13
  echo "src/web/herdgate-host.zip: $(stat -c%s "$DIR/src/web/herdgate-host.zip") bytes"
@@ -377,7 +377,8 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
377
377
  // Host→device ssh.* frames also feed the sshd, which writes them into the
378
378
  // phone's SSH channel; the payload stays opaque to this layer either way.
379
379
  if (isSsh) {
380
- sshd?.onHostFrame(device, payload as Record<string, unknown>);
380
+ if (state.deviceById(device)?.roomId !== room.id) return;
381
+ if (sshd?.onHostFrame(device, payload as Record<string, unknown>)) return;
381
382
  // Ephemeral: raw, unstamped, never buffered (see room streams above).
382
383
  const text = encode({ t: "frame", payload });
383
384
  for (const c of deviceConns) {
@@ -719,6 +720,8 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
719
720
  case "frame": {
720
721
  const device = conn.device;
721
722
  if (!device) return fail(ws, "not-paired", "pair.begin first");
723
+ const op = (m.payload as { op?: unknown } | null)?.op;
724
+ if (typeof op === "string" && op.startsWith("ssh.")) return fail(ws, "bad-message", "SSH frames require an authenticated SSH channel");
722
725
  const agent = agentByRoom.get(device.roomId);
723
726
  if (!agent) return fail(ws, "host-offline", "the host is not connected");
724
727
  send(agent.ws, { t: "frame", device: device.id, payload: m.payload });
package/src/cloud/sshd.ts CHANGED
@@ -133,13 +133,14 @@ export interface SshHandle {
133
133
  inject(socket: import("node:stream").Duplex & { remoteAddress?: string }): void;
134
134
  close(): Promise<void>;
135
135
  /** Gateway calls this when a HOST sends an `ssh.*` frame to a device. */
136
- onHostFrame(deviceId: string, payload: Record<string, unknown>): void;
136
+ onHostFrame(deviceId: string, payload: Record<string, unknown>): boolean;
137
137
  }
138
138
 
139
139
  interface ChannelStream {
140
140
  write(chunk: Buffer): boolean;
141
141
  end(chunk?: Buffer): void;
142
142
  exit(code: number): void;
143
+ stderr: { write(chunk: Buffer): boolean };
143
144
  }
144
145
 
145
146
  interface Channel {
@@ -234,6 +235,14 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
234
235
  ctx.accept();
235
236
  });
236
237
 
238
+ const owned = new Map<string, Channel>();
239
+ const closeChannel = (channel: Channel) => {
240
+ const { deviceId, ch } = channel;
241
+ owned.delete(ch);
242
+ if (!channels.delete(channelKey(deviceId, ch))) return;
243
+ toHost(deviceId, { op: "ssh.close", ch });
244
+ };
245
+
237
246
  client.on("ready", () => {
238
247
  client.on("session", (accept, reject) => {
239
248
  const session = accept();
@@ -258,12 +267,13 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
258
267
  const stream = acceptExec();
259
268
  const channel: Channel = { deviceId: dvc.id, ch, stream, closing: false };
260
269
  channels.set(channelKey(dvc.id, ch), channel);
270
+ owned.set(ch, channel);
261
271
 
262
272
  // Ask the host to run it. The command travels inside the opaque payload; the
263
273
  // host's bridge decides whether to run it and answers ssh.granted / ssh.denied.
264
274
  const opened = toHost(dvc.id, { op: "ssh.open", ch, cmd: String(info.command ?? "") });
265
275
  if (!opened) {
266
- channels.delete(channelKey(dvc.id, ch));
276
+ closeChannel(channel);
267
277
  stream.exit(111);
268
278
  stream.end(Buffer.from("herdgate: the host is not connected\r\n"));
269
279
  return;
@@ -273,10 +283,12 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
273
283
  if (channel.closing) return;
274
284
  toHost(dvc.id, { op: "ssh.data", ch, b64: buf.toString("base64") });
275
285
  });
276
- stream.on("close", () => {
277
- channels.delete(channelKey(dvc.id, ch));
278
- toHost(dvc.id, { op: "ssh.close", ch });
286
+ stream.on("end", () => {
287
+ // The client closed its stdin (an exec script is complete): tell the
288
+ // host, so script channels can match and spawned processes see EOF.
289
+ if (!channel.closing) toHost(dvc.id, { op: "ssh.eof", ch });
279
290
  });
291
+ stream.on("close", () => closeChannel(channel));
280
292
  stream.stderr?.on?.("data", () => {
281
293
  /* stderr is merged by the phone side in exec mode; drop duplicates */
282
294
  });
@@ -285,14 +297,8 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
285
297
  });
286
298
 
287
299
  client.on("close", () => {
288
- const dvc = dev;
289
- if (dvc) {
290
- for (const c of deviceChannels(dvc.id)) {
291
- channels.delete(channelKey(c.deviceId, c.ch));
292
- toHost(dvc.id, { op: "ssh.close", ch: c.ch });
293
- }
294
- if (deviceChannels(dvc.id).length === 0) deps.log(`ssh: device ${dvc.id} disconnected`);
295
- }
300
+ for (const c of owned.values()) closeChannel(c);
301
+ if (dev && deviceChannels(dev.id).length === 0) deps.log(`ssh: device ${dev.id} disconnected`);
296
302
  });
297
303
  });
298
304
 
@@ -319,12 +325,9 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
319
325
  const op = typeof payload.op === "string" ? payload.op : "";
320
326
  const ch = typeof payload.ch === "string" ? payload.ch : "";
321
327
  const channel = channels.get(channelKey(deviceId, ch));
322
- if (!channel) return;
328
+ if (!channel) return false;
323
329
 
324
- if (op === "ssh.granted") {
325
- channel.closing = false;
326
- return;
327
- }
330
+ if (op === "ssh.granted") return true;
328
331
  if (op === "ssh.denied") {
329
332
  // The host refused (scope, command, no hc): close the channel honestly.
330
333
  const reason = typeof payload.reason === "string" ? payload.reason : "refused by the host";
@@ -333,18 +336,19 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
333
336
  channel.stream?.exit(111);
334
337
  channel.stream?.end();
335
338
  channels.delete(channelKey(deviceId, ch));
336
- return;
339
+ return true;
337
340
  }
338
341
  if (op === "ssh.data") {
339
342
  const b64 = typeof payload.b64 === "string" ? payload.b64 : "";
340
- if (b64.length > 400_000) return; // over the frame budget; the rate limiter catches floods
343
+ if (b64.length > 400_000) return true; // over the frame budget
341
344
  const buf = Buffer.from(b64, "base64");
342
345
  try {
343
- channel.stream?.write(buf);
346
+ if (payload.stderr === true) channel.stream?.stderr.write(buf);
347
+ else channel.stream?.write(buf);
344
348
  } catch {
345
349
  /* the phone vanished mid-write; close carries it */
346
350
  }
347
- return;
351
+ return true;
348
352
  }
349
353
  if (op === "ssh.closed") {
350
354
  channel.closing = true;
@@ -354,8 +358,8 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
354
358
  channel.stream?.exit(code);
355
359
  channel.stream?.end();
356
360
  channels.delete(channelKey(deviceId, ch));
357
- return;
358
361
  }
362
+ return true;
359
363
  },
360
364
  async close() {
361
365
  for (const c of channels.values()) {
package/src/host/herdr.ts CHANGED
@@ -155,6 +155,46 @@ export async function readHerdrView(o: HerdrReadOptions = {}): Promise<HerdrView
155
155
  return mapSnapshot(parsed);
156
156
  }
157
157
 
158
+ export interface HerdrPane {
159
+ id: string;
160
+ workspace: string;
161
+ agent: string | null;
162
+ status: string;
163
+ cwd: string;
164
+ title: string;
165
+ }
166
+
167
+ /** Live panes (`herdr pane list`), mapped for the term.list op. */
168
+ export async function readHerdrPanes(o: HerdrReadOptions = {}): Promise<HerdrPane[]> {
169
+ const bin = o.bin ?? process.env.HERDGATE_HERDR_BIN ?? "herdr";
170
+ const { stdout } = await run(bin, ["pane", "list"], { timeout: o.timeoutMs ?? 5_000, maxBuffer: MAX_SNAPSHOT_BYTES, env: o.env ?? process.env });
171
+ const parsed = JSON.parse(stdout) as { result?: { panes?: unknown[] }; panes?: unknown[] };
172
+ const panes = parsed?.result?.panes ?? parsed?.panes ?? [];
173
+ return panes
174
+ .filter((p): p is Record<string, unknown> => Boolean(p) && typeof (p as Record<string, unknown>).pane_id === "string")
175
+ .map((p) => ({
176
+ id: String(p.pane_id),
177
+ workspace: typeof p.workspace_id === "string" ? p.workspace_id : "",
178
+ agent: typeof p.agent === "string" ? p.agent : null,
179
+ status: typeof p.agent_status === "string" ? p.agent_status : "unknown",
180
+ cwd: typeof p.cwd === "string" ? p.cwd : "",
181
+ title: typeof p.terminal_title_stripped === "string" ? p.terminal_title_stripped : typeof p.terminal_title === "string" ? p.terminal_title : "",
182
+ }));
183
+ }
184
+
185
+ /** One pane's visible screen as ANSI (`herdr agent read --format ansi`). */
186
+ export async function readHerdrTerm(target: string, lines = 40, o: HerdrReadOptions = {}): Promise<string> {
187
+ const bin = o.bin ?? process.env.HERDGATE_HERDR_BIN ?? "herdr";
188
+ if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) throw new Error("bad pane id");
189
+ const n = Math.max(10, Math.min(120, Math.trunc(lines) || 40));
190
+ const { stdout } = await run(bin, ["agent", "read", target, "--source", "visible", "--lines", String(n), "--format", "ansi"], {
191
+ timeout: o.timeoutMs ?? 5_000,
192
+ maxBuffer: MAX_SNAPSHOT_BYTES,
193
+ env: o.env ?? process.env,
194
+ });
195
+ return stdout;
196
+ }
197
+
158
198
  /** What the host can push/drive; the agent supplies it (see `HerdrAdapter.attach`). */
159
199
  export interface HostLink {
160
200
  send(device: string, payload: unknown): void;
@@ -191,6 +231,8 @@ export class HerdrAdapter implements AgentAdapter {
191
231
  readonly #log: (line: string) => void;
192
232
  #link: HostLink | null = null;
193
233
  #view: HerdrView | null = null;
234
+ /** Per-device last-call times for the subprocess-backed term.* ops (1/s each). */
235
+ #termThrottle = new Map<string, number>();
194
236
  #sig = "";
195
237
  #lastError: string | null = null;
196
238
  #timer: NodeJS.Timeout | null = null;
@@ -257,6 +299,30 @@ export class HerdrAdapter implements AgentAdapter {
257
299
  }
258
300
  case "ping":
259
301
  return link.send(device, { op: "pong", n: (payload as { n?: unknown }).n ?? null, at: (this.#o.now?.() ?? new Date()).toISOString() });
302
+ case "term.list": {
303
+ // Subprocess-backed: throttle per device so a poll loop cannot fork herdr hot.
304
+ const now = this.#o.now?.() ?? new Date();
305
+ const last = this.#termThrottle.get(`list:${device}`) ?? 0;
306
+ if (now.getTime() - last < 1_000) return link.send(device, { op: "error", code: "busy", message: "term.list is throttled (1/s)" });
307
+ this.#termThrottle.set(`list:${device}`, now.getTime());
308
+ readHerdrPanes()
309
+ .then((panes) => link.send(device, { op: "term.list", panes }))
310
+ .catch((e: unknown) => link.send(device, { op: "error", code: "herdr", message: `pane list failed: ${e instanceof Error ? e.message : String(e)}` }));
311
+ return;
312
+ }
313
+ case "term.read": {
314
+ const target = typeof (payload as { target?: unknown }).target === "string" ? (payload as { target: string }).target : "";
315
+ if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) return link.send(device, { op: "error", code: "bad-target", message: "term.read needs a pane id" });
316
+ const lines = Math.max(10, Math.min(120, Number((payload as { lines?: unknown }).lines) || 40));
317
+ const nowT = this.#o.now?.() ?? new Date();
318
+ const lastT = this.#termThrottle.get(`read:${device}`) ?? 0;
319
+ if (nowT.getTime() - lastT < 1_000) return link.send(device, { op: "error", code: "busy", message: "term.read is throttled (1/s)" });
320
+ this.#termThrottle.set(`read:${device}`, nowT.getTime());
321
+ readHerdrTerm(target, lines)
322
+ .then((ansi) => link.send(device, { op: "term.read", target, ansi }))
323
+ .catch((e: unknown) => link.send(device, { op: "error", code: "herdr", message: `read failed: ${e instanceof Error ? e.message : String(e)}` }));
324
+ return;
325
+ }
260
326
  default:
261
327
  // The read-only invariant lives HERE: the cloud cannot inspect payloads, so the
262
328
  // host is the last trusted decision point for "this device may not do that".