@bom0792/herdgate 0.0.0-stage → 0.9.5
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 +92 -0
- package/dist-readme.md +48 -0
- package/package.json +36 -3
- package/plugin/herdr-plugin.toml +36 -0
- package/plugin/server/common.mjs +79 -0
- package/plugin/server/e2e.d.mts +43 -0
- package/plugin/server/e2e.mjs +268 -0
- package/plugin/server/index.mjs +454 -0
- package/plugin/server/ssh.mjs +241 -0
- package/scripts/build-host-bundle.sh +12 -0
- package/scripts/deploy-vps.sh +74 -0
- package/scripts/patch-ssh2.mjs +32 -0
- package/src/agent/adapter.ts +23 -0
- package/src/agent/index.ts +183 -0
- package/src/cloud/gateway.ts +946 -0
- package/src/cloud/main.ts +88 -0
- package/src/cloud/pairing.ts +81 -0
- package/src/cloud/ssh-bridge.ts +212 -0
- package/src/cloud/sshd.ts +412 -0
- package/src/cloud/static.ts +142 -0
- package/src/cloud/stores.ts +180 -0
- package/src/cloud/util.ts +47 -0
- package/src/cloud/vapid.ts +105 -0
- package/src/dev/edge-sim.ts +99 -0
- package/src/dev/main.ts +33 -0
- package/src/host/herdr.ts +316 -0
- package/src/host/main.ts +105 -0
- package/src/host/ssh.ts +317 -0
- package/src/index.ts +5 -0
- package/src/protocol/agent.ts +84 -0
- package/src/protocol/device.ts +90 -0
- package/src/protocol/envelope.ts +58 -0
- package/src/protocol/index.ts +3 -0
- package/src/web/app.css +312 -0
- package/src/web/app.js +835 -0
- package/src/web/app.webmanifest +15 -0
- package/src/web/e2e.js +268 -0
- package/src/web/herdgate-host.zip +0 -0
- package/src/web/icons/icon-192.png +0 -0
- package/src/web/icons/icon-512.png +0 -0
- package/src/web/icons/icon.svg +6 -0
- package/src/web/index.html +99 -0
- package/src/web/sw.js +98 -0
package/src/host/ssh.ts
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
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
|
+
*/
|
|
17
|
+
|
|
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
|
+
};
|
|
317
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { startCloud, type CloudConfig, type Cloud } from "./cloud/gateway.ts";
|
|
2
|
+
export { State, type Account, type RoomRecord, type DeviceRecord } from "./cloud/stores.ts";
|
|
3
|
+
export { AgentCodes } from "./cloud/pairing.ts";
|
|
4
|
+
export { HerdGateAgent, provision } from "./agent/index.ts";
|
|
5
|
+
export type { AgentAdapter, PairAsk } from "./agent/adapter.ts";
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host-agent leg: one outbound WebSocket per host via `GET /v1/agent/ws`.
|
|
3
|
+
*
|
|
4
|
+
* The agent authenticates with a long-lived **room token** (minted by the
|
|
5
|
+
* device-flow in `provision`, see the agent SDK). One live agent connection per
|
|
6
|
+
* room: a second connection supersedes the first.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Scope } from "./envelope.ts";
|
|
10
|
+
|
|
11
|
+
export interface DeviceView {
|
|
12
|
+
id: string;
|
|
13
|
+
name: string;
|
|
14
|
+
scope: Scope;
|
|
15
|
+
connected: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// ---- agent → cloud ----
|
|
19
|
+
|
|
20
|
+
export interface AgentHello {
|
|
21
|
+
t: "hello";
|
|
22
|
+
roomToken: string;
|
|
23
|
+
info: { name: string; version: string; capabilities?: string[] };
|
|
24
|
+
}
|
|
25
|
+
export interface AgentFrame {
|
|
26
|
+
t: "frame";
|
|
27
|
+
device: string;
|
|
28
|
+
payload: unknown;
|
|
29
|
+
}
|
|
30
|
+
export interface AgentPresence {
|
|
31
|
+
t: "presence";
|
|
32
|
+
online: boolean;
|
|
33
|
+
detail?: string;
|
|
34
|
+
}
|
|
35
|
+
export interface PairResponse {
|
|
36
|
+
t: "pair.response";
|
|
37
|
+
requestId: string;
|
|
38
|
+
ok: boolean;
|
|
39
|
+
}
|
|
40
|
+
export interface AgentPing {
|
|
41
|
+
t: "ping";
|
|
42
|
+
n: number;
|
|
43
|
+
}
|
|
44
|
+
export interface AgentWake {
|
|
45
|
+
t: "wake";
|
|
46
|
+
device: string;
|
|
47
|
+
}
|
|
48
|
+
export type AgentToCloud = AgentHello | AgentFrame | AgentPresence | PairResponse | AgentPing | AgentWake;
|
|
49
|
+
|
|
50
|
+
// ---- cloud → agent ----
|
|
51
|
+
|
|
52
|
+
export interface CloudHelloAgent {
|
|
53
|
+
t: "hello";
|
|
54
|
+
roomId: string;
|
|
55
|
+
roomName: string;
|
|
56
|
+
devices: DeviceView[];
|
|
57
|
+
resumed: boolean;
|
|
58
|
+
}
|
|
59
|
+
export interface CloudFrameAgent {
|
|
60
|
+
t: "frame";
|
|
61
|
+
device: string;
|
|
62
|
+
payload: unknown;
|
|
63
|
+
}
|
|
64
|
+
export interface RoomUpdate {
|
|
65
|
+
t: "room.update";
|
|
66
|
+
devices: DeviceView[];
|
|
67
|
+
}
|
|
68
|
+
/** Approve-on-host: a device asked to pair with scope `act`; the host decides. */
|
|
69
|
+
export interface PairRequest {
|
|
70
|
+
t: "pair.request";
|
|
71
|
+
requestId: string;
|
|
72
|
+
device: { name: string };
|
|
73
|
+
scope: Scope;
|
|
74
|
+
}
|
|
75
|
+
export interface PongMsg {
|
|
76
|
+
t: "pong";
|
|
77
|
+
n: number;
|
|
78
|
+
}
|
|
79
|
+
export interface ErrMsg {
|
|
80
|
+
t: "error";
|
|
81
|
+
code: string;
|
|
82
|
+
message?: string;
|
|
83
|
+
}
|
|
84
|
+
export type CloudToAgent = CloudHelloAgent | CloudFrameAgent | RoomUpdate | PairRequest | PongMsg | ErrMsg;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The device leg: browsers/PWAs (and anything else) → `GET /v1/device/ws`.
|
|
3
|
+
*
|
|
4
|
+
* v0 identity: the device authenticates with an **account token**; pairing
|
|
5
|
+
* creates a device record inside one room, and the client re-presents its device
|
|
6
|
+
* id on reconnect. Per-device secrets (so a leaked account token is not every
|
|
7
|
+
* device) are on the roadmap — see DESIGN.md §6.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Scope } from "./envelope.ts";
|
|
11
|
+
|
|
12
|
+
// ---- device → cloud ----
|
|
13
|
+
|
|
14
|
+
export interface DeviceHello {
|
|
15
|
+
t: "hello";
|
|
16
|
+
/** The account token: the owner, who can pair devices and manage rooms. */
|
|
17
|
+
accountToken?: string;
|
|
18
|
+
/** A paired device re-attaching with the secret `pair.granted` issued once. */
|
|
19
|
+
device?: string;
|
|
20
|
+
deviceSecret?: string;
|
|
21
|
+
name?: string;
|
|
22
|
+
/** "phone" | "tablet-portrait" | ... — opaque to the cloud, passed to the host. */
|
|
23
|
+
deviceClass?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface DeviceFrame {
|
|
26
|
+
t: "frame";
|
|
27
|
+
payload: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** Ask to pair this device to one room. `act` needs the host's approval. */
|
|
30
|
+
export interface PairBegin {
|
|
31
|
+
t: "pair.begin";
|
|
32
|
+
roomId: string;
|
|
33
|
+
name: string;
|
|
34
|
+
scope: Scope;
|
|
35
|
+
}
|
|
36
|
+
export interface DevicePing {
|
|
37
|
+
t: "ping";
|
|
38
|
+
n: number;
|
|
39
|
+
}
|
|
40
|
+
export type DeviceToCloud = DeviceHello | DeviceFrame | PairBegin | DevicePing;
|
|
41
|
+
|
|
42
|
+
// ---- cloud → device ----
|
|
43
|
+
|
|
44
|
+
export interface AgentView {
|
|
45
|
+
roomId: string;
|
|
46
|
+
name: string;
|
|
47
|
+
online: boolean;
|
|
48
|
+
/** This device's scope in that room; `null` when not paired there. */
|
|
49
|
+
scope: Scope | null;
|
|
50
|
+
}
|
|
51
|
+
export interface DeviceSelfView {
|
|
52
|
+
id: string;
|
|
53
|
+
name: string;
|
|
54
|
+
scope: Scope;
|
|
55
|
+
roomId: string;
|
|
56
|
+
}
|
|
57
|
+
export interface CloudHelloDevice {
|
|
58
|
+
t: "hello";
|
|
59
|
+
session: string;
|
|
60
|
+
resumed: boolean;
|
|
61
|
+
device: DeviceSelfView | null;
|
|
62
|
+
agents: AgentView[];
|
|
63
|
+
}
|
|
64
|
+
export interface CloudFrameDevice {
|
|
65
|
+
t: "frame";
|
|
66
|
+
payload: unknown;
|
|
67
|
+
}
|
|
68
|
+
export interface PairGranted {
|
|
69
|
+
t: "pair.granted";
|
|
70
|
+
device: DeviceSelfView;
|
|
71
|
+
/** This device's own credential (SSH leg + reconnect). Shown/stored once. */
|
|
72
|
+
deviceSecret?: string;
|
|
73
|
+
}
|
|
74
|
+
export interface PairDenied {
|
|
75
|
+
t:"pair.denied";
|
|
76
|
+
reason: string;
|
|
77
|
+
}
|
|
78
|
+
export interface PresenceUpdate {
|
|
79
|
+
t: "presence";
|
|
80
|
+
roomId: string;
|
|
81
|
+
online: boolean;
|
|
82
|
+
}
|
|
83
|
+
export type CloudToDevice =
|
|
84
|
+
| CloudHelloDevice
|
|
85
|
+
| CloudFrameDevice
|
|
86
|
+
| PairGranted
|
|
87
|
+
| PairDenied
|
|
88
|
+
| PresenceUpdate
|
|
89
|
+
| { t: "pong"; n: number }
|
|
90
|
+
| { t: "error"; code: string; message?: string };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The herdgate envelope: every WebSocket text frame on every leg is one JSON object
|
|
3
|
+
* `{v, t, ...}`. `v` is the protocol version; a peer that receives another `v`
|
|
4
|
+
* closes the socket. Messages are discriminated by the string `t`.
|
|
5
|
+
*
|
|
6
|
+
* Rule of the house: **payload fields are opaque.** The cloud routes them between
|
|
7
|
+
* legs and never inspects, logs or persists them. This keeps the door open for
|
|
8
|
+
* end-to-end encryption later (the payload becomes a ciphertext string and the
|
|
9
|
+
* cloud does not change).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const PROTOCOL_VERSION = 1;
|
|
13
|
+
|
|
14
|
+
/** A frame larger than this (bytes, UTF-8) closes the socket (1009). */
|
|
15
|
+
export const MAX_FRAME_BYTES = 256 * 1024;
|
|
16
|
+
|
|
17
|
+
/** A socket that has not sent a valid `hello` by then is closed (4001). */
|
|
18
|
+
export const HELLO_TIMEOUT_MS = 10_000;
|
|
19
|
+
|
|
20
|
+
/** Message-rate ceiling per socket: sustained msgs/s and burst capacity. */
|
|
21
|
+
export const RATE_MSG_PER_S = 60;
|
|
22
|
+
export const RATE_BURST = 120;
|
|
23
|
+
|
|
24
|
+
/** An agent pairing code lives this long (device-flow). */
|
|
25
|
+
export const AGENT_CODE_TTL_MS = 10 * 60_000;
|
|
26
|
+
|
|
27
|
+
/** A device pair request (approve-on-host) waits this long for the host. */
|
|
28
|
+
export const PAIR_ANSWER_MS = 60_000;
|
|
29
|
+
|
|
30
|
+
export type Scope = "read" | "act";
|
|
31
|
+
|
|
32
|
+
export interface Envelope {
|
|
33
|
+
v: number;
|
|
34
|
+
t: string;
|
|
35
|
+
[k: string]: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function encode(msg: Record<string, unknown>): string {
|
|
39
|
+
return JSON.stringify({ v: PROTOCOL_VERSION, ...msg });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A syntactically valid envelope of this version, or `null`. */
|
|
43
|
+
export function decode(text: string): Envelope | null {
|
|
44
|
+
let m: unknown;
|
|
45
|
+
try {
|
|
46
|
+
m = JSON.parse(text);
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (typeof m !== "object" || m === null) return null;
|
|
51
|
+
const e = m as Record<string, unknown>;
|
|
52
|
+
if (e.v !== PROTOCOL_VERSION || typeof e.t !== "string" || e.t === "") return null;
|
|
53
|
+
return e as Envelope;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function isScope(v: unknown): v is Scope {
|
|
57
|
+
return v === "read" || v === "act";
|
|
58
|
+
}
|