@bom0792/herdgate 0.9.20 → 0.9.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/host/ssh.ts CHANGED
@@ -1,317 +1,7 @@
1
- /**
2
- * The host side of the SSH leg: turn a phone's SSH session into a real `hc` process.
3
- *
4
- * The cloud relays `ssh.*` payloads opaquely; THIS module is the trusted decision point:
5
- *
6
- * - a channel runs exactly one command, and only `hc …` (argv split, `shell: false`) —
7
- * never a shell, never anything else;
8
- * - a `read` device gets a filtered plain-mode channel: mutating JSON-RPC methods are
9
- * refused AT THIS GATE (the phone sees an honest JSON-RPC error; herdr-core never
10
- * sees the call), a `framed: true` hello is downgraded to plain mode, and a stream
11
- * of garbage is cut off;
12
- * - an `act` device (approved by a human on this host) gets byte-transparent access —
13
- * framed mode, attach, everything herdr-core offers;
14
- * - output back to the phone is coalesced (~20 ms) so a chatty terminal stays under
15
- * the wire's frame-rate limits.
16
- */
1
+ // The standalone host and self-contained plugin enforce the same SSH policy.
2
+ import { createSshBridge as create, type SshBridgeOptions } from "../../plugin/server/ssh.mjs";
3
+ export { READ_METHODS, translateBootstrap, type SshBridge } from "../../plugin/server/ssh.mjs";
17
4
 
18
- import { spawn, type ChildProcess } from "node:child_process";
19
- import { existsSync } from "node:fs";
20
- import { homedir } from "node:os";
21
- import { join } from "node:path";
22
-
23
- /** Methods a `read` device may call on herdr-core. Everything else is refused here. */
24
- export const READ_METHODS = new Set([
25
- "hello",
26
- "rpc.discover",
27
- "server.status",
28
- "terminal.list",
29
- "terminal.get",
30
- "terminal.read",
31
- "terminal.wait",
32
- "templates.list",
33
- "events.subscribe",
34
- "doc.get",
35
- "machine.list",
36
- ]);
37
-
38
- const FLUSH_MS = 20;
39
- const FLUSH_BYTES = 64 * 1024;
40
- const MAX_MALFORMED = 50;
41
-
42
- export interface SshBridgeOptions {
43
- /** Route an opaque payload to one device. */
44
- send(device: string, payload: Record<string, unknown>): void;
45
- /** The device's scope in this room (`null` when unknown). */
46
- scopeOf(device: string): "read" | "act" | null;
47
- log?(line: string): void;
48
- /** Where herdr-core is; resolved once per channel by default. */
49
- resolveHc?: () => string | null;
50
- spawnImpl?: (bin: string, args: string[], opts: { stdio: ("pipe" | null)[]; shell: boolean }) => ChildProcess;
51
- }
52
-
53
- interface HostChannel {
54
- device: string;
55
- ch: string;
56
- scope: "read" | "act";
57
- proc: ChildProcess | null;
58
- /** Bytes from the phone awaiting a newline (read scope parses line by line). */
59
- inBuf: Buffer;
60
- /** Bytes from hc awaiting the next flush. */
61
- outBuf: Buffer;
62
- flushTimer: NodeJS.Timeout | null;
63
- malformed: number;
64
- closed: boolean;
65
- }
66
-
67
- export interface SshBridge {
68
- /** Handle one frame payload; returns true when it was an ssh.* op this module owns. */
69
- handle(device: string, payload: unknown): boolean;
70
- /** Drop every channel of a device (device disconnected from the cloud). */
71
- dropDevice(device: string): void;
72
- closeAll(): void;
73
- }
74
-
75
-
76
- /** Extract `hc <verb>` from herdr-core's known machine-add probes (null = not one). */
77
- export function translateBootstrap(cmd: string): string | null {
78
- // POSIX: sh -c 'p=$(command -v herdr-core) …; exec "$p" connect'
79
- const posix = cmd.match(/exec "\$p"\s+([^'"\n]+?)['"]?\s*$/);
80
- if (posix) {
81
- const args = posix[1].trim();
82
- // Strict whitelist: flags, words, equals — never shell metacharacters.
83
- if (/^[-a-z0-9][-a-z0-9 =]*$/i.test(args)) return `hc ${args}`;
84
- }
85
- // Windows: cmd /d /c "…herdr-core.exe connect) …"
86
- const win = cmd.match(/herdr-core\.exe\)?\s+\(?([a-z][a-z0-9-]*)\)/);
87
- if (win) return `hc ${win[1]}`;
88
- return null;
89
- }
90
-
91
- export function createSshBridge(o: SshBridgeOptions): SshBridge {
92
- const log = o.log ?? (() => {});
93
- const spawnFn = o.spawnImpl ?? spawn;
94
- const channels = new Map<string, HostChannel>();
95
- const key = (device: string, ch: string): string => `${device}:${ch}`;
96
-
97
- const resolveHc =
98
- o.resolveHc ??
99
- ((): string | null => {
100
- const env = process.env.HERDGATE_HC_BIN?.trim();
101
- if (env && existsSync(env)) return env;
102
- const local = join(homedir(), ".local", "bin", "hc");
103
- if (existsSync(local)) return local;
104
- return existsSync("/usr/bin/hc") ? "/usr/bin/hc" : "hc"; // let spawn report ENOENT honestly
105
- });
106
-
107
- const sendOut = (c: HostChannel, final: boolean, code?: number, reason?: string): void => {
108
- if (c.outBuf.length > 0) {
109
- o.send(c.device, { op: "ssh.data", ch: c.ch, b64: c.outBuf.toString("base64") });
110
- c.outBuf = Buffer.alloc(0);
111
- }
112
- if (final) {
113
- o.send(c.device, { op: "ssh.closed", ch: c.ch, ...(code !== undefined ? { code } : {}), ...(reason ? { reason } : {}) });
114
- }
115
- };
116
-
117
- const scheduleFlush = (c: HostChannel): void => {
118
- if (c.flushTimer) return;
119
- c.flushTimer = setTimeout(() => {
120
- c.flushTimer = null;
121
- if (!c.closed) sendOut(c, false);
122
- }, FLUSH_MS);
123
- c.flushTimer.unref?.();
124
- };
125
-
126
- const deny = (c: HostChannel, reason: string): void => {
127
- o.send(c.device, { op: "ssh.denied", ch: c.ch, reason });
128
- };
129
-
130
- /** A refused call never reaches herdr-core: the phone gets a real JSON-RPC error. */
131
- const refuseCall = (c: HostChannel, id: unknown, method: string): void => {
132
- const err = JSON.stringify({
133
- jsonrpc: "2.0",
134
- id: id ?? null,
135
- error: { code: -32600, message: `herdgate: "${method}" needs the act scope (this device is read-only)`, data: { kind: "forbidden", method } },
136
- });
137
- c.outBuf = Buffer.concat([c.outBuf, Buffer.from(`${err}\n`)]);
138
- scheduleFlush(c);
139
- };
140
-
141
- /** Feed phone bytes into the channel; `read` scope parses, `act` pipes blind. */
142
- const feed = (c: HostChannel, buf: Buffer): void => {
143
- if (c.closed || !c.proc?.stdin) return;
144
- if (c.scope === "act") {
145
- c.proc.stdin.write(buf);
146
- return;
147
- }
148
- c.inBuf = Buffer.concat([c.inBuf, buf]);
149
- for (;;) {
150
- const nl = c.inBuf.indexOf(0x0a);
151
- if (nl < 0) break;
152
- const line = c.inBuf.subarray(0, nl);
153
- c.inBuf = c.inBuf.subarray(nl + 1);
154
- const text = line.toString("utf8").trim();
155
- if (!text) continue;
156
- let msg: { method?: unknown; id?: unknown; params?: Record<string, unknown> } | null = null;
157
- try {
158
- msg = JSON.parse(text);
159
- } catch {
160
- msg = null;
161
- }
162
- if (!msg || typeof msg !== "object" || typeof msg.method !== "string") {
163
- c.malformed += 1;
164
- if (c.malformed > MAX_MALFORMED) {
165
- log(`ssh: ${c.device}/${c.ch} cut off after ${c.malformed} malformed lines`);
166
- kill(c, "too much malformed input");
167
- return;
168
- }
169
- continue;
170
- }
171
- const method = msg.method;
172
- if (method === "hello" && msg.params && typeof msg.params === "object") {
173
- // Live terminals (framed attach) are byte streams a read-only device must not
174
- // write into; downgrade to plain mode so list/read still work honestly.
175
- if (msg.params.framed === true) {
176
- msg.params.framed = false;
177
- log(`ssh: ${c.device}/${c.ch} hello framed:true downgraded (read scope)`);
178
- }
179
- }
180
- if (!READ_METHODS.has(method)) {
181
- refuseCall(c, msg.id, method);
182
- continue;
183
- }
184
- c.proc.stdin.write(`${JSON.stringify(msg)}\n`);
185
- }
186
- };
187
-
188
- const kill = (c: HostChannel, reason: string): void => {
189
- c.closed = true;
190
- if (c.flushTimer) clearTimeout(c.flushTimer);
191
- c.proc?.kill("SIGKILL");
192
- channels.delete(key(c.device, c.ch));
193
- sendOut(c, true, 130, reason);
194
- };
195
-
196
- const handle = (device: string, payload: unknown): boolean => {
197
- if (typeof payload !== "object" || payload === null) return false;
198
- const op = (payload as { op?: unknown }).op;
199
- if (typeof op !== "string" || !op.startsWith("ssh.")) return false;
200
- const p = payload as Record<string, unknown>;
201
- const ch = typeof p.ch === "string" ? p.ch : "";
202
-
203
- if (op === "ssh.open") {
204
- const scope = o.scopeOf(device);
205
- if (!scope) {
206
- o.send(device, { op: "ssh.denied", ch, reason: "this device is not paired to this room" });
207
- return true;
208
- }
209
- const cmd = typeof p.cmd === "string" ? p.cmd.trim() : "";
210
- // herdr-core's `machine add` probes with shell wrappers that locate a binary
211
- // named `herdr-core` and `exec` it (POSIX and Windows templates). We never run
212
- // shell lines: translate the KNOWN templates to the equivalent `hc <verb>` and
213
- // let the normal path spawn it. Anything else shell-shaped is refused below.
214
- const bootstrap = cmd.includes("herdr-core") ? translateBootstrap(cmd) : null;
215
- const parts = (bootstrap ?? cmd).split(/\s+/).filter(Boolean);
216
- if (parts.length > 0 && parts[0] === "exit" && (parts.length === 1 || parts[1] === "0")) {
217
- // SSH clients end probe sessions with `exit` — acknowledge and close clean.
218
- o.send(device, { op: "ssh.granted", ch, scope });
219
- o.send(device, { op: "ssh.closed", ch, code: 0 });
220
- return true;
221
- }
222
- if (parts.length === 0 || parts[0] !== "hc") {
223
- // One command family only: the phone speaks herdr-core through this leg.
224
- o.send(device, { op: "ssh.denied", ch, reason: `herdgate bridges "hc …" only, got "${cmd.slice(0, 60) || "(empty)"}"` });
225
- return true;
226
- }
227
- const bin = resolveHc();
228
- const args = parts.slice(1);
229
- let proc: ChildProcess;
230
- try {
231
- proc = spawnFn(bin ?? "hc", args, { stdio: ["pipe", "pipe", "pipe"], shell: false });
232
- } catch (e) {
233
- o.send(device, { op: "ssh.denied", ch, reason: `could not start herdr-core: ${e instanceof Error ? e.message : String(e)}` });
234
- return true;
235
- }
236
- const c: HostChannel = { device, ch, scope, proc, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
237
- channels.set(key(device, ch), c);
238
-
239
- proc.stdout?.on("data", (chunk: Buffer) => {
240
- c.outBuf = Buffer.concat([c.outBuf, chunk]);
241
- scheduleFlush(c);
242
- });
243
- proc.stderr?.on("data", (chunk: Buffer) => {
244
- // herdr-core writes diagnostics to stderr; the phone shows them as output too.
245
- c.outBuf = Buffer.concat([c.outBuf, chunk]);
246
- scheduleFlush(c);
247
- });
248
- proc.on("error", (e) => {
249
- const enoent = (e as NodeJS.ErrnoException).code === "ENOENT";
250
- log(`ssh: spawn failed for ${device}/${ch}: ${e.message}`);
251
- channels.delete(key(device, ch));
252
- c.closed = true;
253
- if (c.flushTimer) clearTimeout(c.flushTimer);
254
- o.send(device, {
255
- op: "ssh.denied",
256
- ch,
257
- reason: enoent ? "herdr-core (hc) was not found on this host" : `could not start herdr-core: ${e.message}`,
258
- });
259
- });
260
- proc.on("close", (code, signal) => {
261
- if (c.closed) return;
262
- c.closed = true;
263
- if (c.flushTimer) clearTimeout(c.flushTimer);
264
- channels.delete(key(device, ch));
265
- sendOut(c, true, code ?? (signal ? 130 : 1), signal ? `terminated by ${signal}` : undefined);
266
- });
267
-
268
- o.send(device, { op: "ssh.granted", ch, scope });
269
- log(`ssh: ${device}/${ch} → ${cmd} (${scope})`);
270
- return true;
271
- }
272
-
273
- if (op === "ssh.data") {
274
- const c = channels.get(key(device, ch));
275
- if (!c) return true; // unknown or already closed: drop
276
- const b64 = typeof p.b64 === "string" ? p.b64 : "";
277
- if (b64.length > 400_000) return true;
278
- feed(c, Buffer.from(b64, "base64"));
279
- return true;
280
- }
281
-
282
- if (op === "ssh.close") {
283
- const c = channels.get(key(device, ch));
284
- if (!c) return true;
285
- c.closed = true;
286
- if (c.flushTimer) clearTimeout(c.flushTimer);
287
- c.proc?.kill("SIGTERM");
288
- channels.delete(key(device, ch));
289
- sendOut(c, true, 0, "closed by the device");
290
- return true;
291
- }
292
-
293
- return false; // an ssh.* op we don't know: tell the adapter layer it's not ours to read
294
- };
295
-
296
- return {
297
- handle,
298
- dropDevice(device: string): void {
299
- for (const [k, c] of [...channels]) {
300
- if (c.device === device) {
301
- c.closed = true;
302
- if (c.flushTimer) clearTimeout(c.flushTimer);
303
- c.proc?.kill("SIGTERM");
304
- channels.delete(k);
305
- }
306
- }
307
- },
308
- closeAll(): void {
309
- for (const [, c] of [...channels]) {
310
- c.closed = true;
311
- if (c.flushTimer) clearTimeout(c.flushTimer);
312
- c.proc?.kill("SIGTERM");
313
- }
314
- channels.clear();
315
- },
316
- };
5
+ export function createSshBridge(options: Omit<SshBridgeOptions, "resolve"> & { resolveHc?: SshBridgeOptions["resolve"] }) {
6
+ return create({ ...options, resolve: options.resolveHc });
317
7
  }
package/src/web/app.css CHANGED
@@ -301,6 +301,8 @@ dialog::backdrop {
301
301
  }
302
302
 
303
303
  /* SSH public-key management inside the device's SSH section */
304
+ .ssh-user-select { display: block; width: 100%; margin-top: 4px; }
305
+ #view details.ssh .keyrow[hidden] { display: none; }
304
306
  .sshkeys .pubkey-input {
305
307
  flex: 1;
306
308
  min-width: 0;