@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.
Files changed (46) hide show
  1. package/README.md +167 -2
  2. package/app-mod/herdgate/main.js +395 -0
  3. package/app-mod/herdgate/mod.json +5 -0
  4. package/bin/herdgate.mjs +91 -0
  5. package/dist-readme.md +48 -0
  6. package/package.json +36 -3
  7. package/plugin/herdr-plugin.toml +36 -0
  8. package/plugin/server/common.mjs +79 -0
  9. package/plugin/server/e2e.d.mts +43 -0
  10. package/plugin/server/e2e.mjs +268 -0
  11. package/plugin/server/index.mjs +454 -0
  12. package/plugin/server/ssh.mjs +241 -0
  13. package/scripts/build-host-bundle.sh +12 -0
  14. package/scripts/deploy-vps.sh +74 -0
  15. package/scripts/patch-ssh2.mjs +32 -0
  16. package/src/agent/adapter.ts +23 -0
  17. package/src/agent/index.ts +183 -0
  18. package/src/cloud/gateway.ts +946 -0
  19. package/src/cloud/main.ts +88 -0
  20. package/src/cloud/pairing.ts +81 -0
  21. package/src/cloud/ssh-bridge.ts +212 -0
  22. package/src/cloud/sshd.ts +412 -0
  23. package/src/cloud/static.ts +142 -0
  24. package/src/cloud/stores.ts +180 -0
  25. package/src/cloud/util.ts +47 -0
  26. package/src/cloud/vapid.ts +105 -0
  27. package/src/dev/edge-sim.ts +99 -0
  28. package/src/dev/main.ts +33 -0
  29. package/src/host/herdr.ts +316 -0
  30. package/src/host/main.ts +105 -0
  31. package/src/host/ssh.ts +317 -0
  32. package/src/index.ts +5 -0
  33. package/src/protocol/agent.ts +84 -0
  34. package/src/protocol/device.ts +90 -0
  35. package/src/protocol/envelope.ts +58 -0
  36. package/src/protocol/index.ts +3 -0
  37. package/src/web/app.css +312 -0
  38. package/src/web/app.js +835 -0
  39. package/src/web/app.webmanifest +15 -0
  40. package/src/web/e2e.js +268 -0
  41. package/src/web/herdgate-host.zip +0 -0
  42. package/src/web/icons/icon-192.png +0 -0
  43. package/src/web/icons/icon-512.png +0 -0
  44. package/src/web/icons/icon.svg +6 -0
  45. package/src/web/index.html +99 -0
  46. package/src/web/sw.js +98 -0
package/src/web/app.js ADDED
@@ -0,0 +1,835 @@
1
+ // herdgate PWA — the device side of the gate.
2
+ //
3
+ // What it does: signs in with an account token, lists the machines (rooms) that account
4
+ // has, pairs this device into one (scope read, or act with the host's approval), and shows
5
+ // the read-only view the host publishes.
6
+ //
7
+ // House rules it respects:
8
+ // - the cloud routes opaque payloads, so the *host* decides what an op means; this client
9
+ // only ever asks for `{op:"view"}` and `{op:"ping"}`, and shows what comes back;
10
+ // - every string from the wire is rendered with `textContent`, never `innerHTML`;
11
+ // - the token lives in localStorage on this device and is never sent anywhere but the
12
+ // cloud's own WS endpoint.
13
+
14
+ const BUILD = "v0.9.2";
15
+
16
+ const $ = (id) => document.getElementById(id);
17
+ const TOKEN_KEY = "herdgate.token";
18
+ const CLOUD_KEY = "herdgate.cloud";
19
+ const DEVICE_KEY = "herdgate.device";
20
+ const DEVICE_SECRET_KEY = "herdgate.deviceSecret";
21
+
22
+ import { DeviceChannel, generateKeyPair, fingerprint } from "/e2e.js";
23
+
24
+ // E2E payloads: this device's Noise_XX identity (kept locally, never sent to the cloud
25
+ // in the clear) and the host fingerprints it has pinned (TOFU per room).
26
+ const E2E_KEY = "herdgate.e2ekey";
27
+ const e2eFpKey = (roomId) => `herdgate.e2efp.${roomId}`;
28
+
29
+ async function e2eSelfKey() {
30
+ try {
31
+ const v = JSON.parse(localStorage.getItem(E2E_KEY) ?? "null");
32
+ if (v?.jwk?.kty === "EC" && typeof v.pub === "string") return { jwk: v.jwk, pub: e2eB64d(v.pub) };
33
+ } catch {
34
+ /* mint below */
35
+ }
36
+ const self = await generateKeyPair();
37
+ localStorage.setItem(E2E_KEY, JSON.stringify({ jwk: self.jwk, pub: e2eB64e(self.pub) }));
38
+ return self;
39
+ }
40
+ function e2eB64e(u8) {
41
+ let s = "";
42
+ for (const b of u8) s += String.fromCharCode(b);
43
+ return btoa(s);
44
+ }
45
+ function e2eB64d(s) {
46
+ const bin = atob(s);
47
+ const u8 = new Uint8Array(bin.length);
48
+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
49
+ return u8;
50
+ }
51
+
52
+ // Per-room channel state; reset when the socket drops. The channel only carries
53
+ // traffic after the host's `e2e.ready` ack — nothing may race the handshake's
54
+ // last step, or the transport counters desync for good.
55
+ const e2e = { ch: null, initing: false, ready: false };
56
+ function e2eReset() {
57
+ e2e.ch = null;
58
+ e2e.initing = false;
59
+ e2e.ready = false;
60
+ }
61
+
62
+ /** Begin (or restart) the Noise_XX handshake with this room's host. */
63
+ async function e2eBegin() {
64
+ if (e2e.ch?.ready() || e2e.initing) return;
65
+ if (!(state.deviceSecret && state.deviceId && state.roomId)) return;
66
+ if (state.ws?.readyState !== WebSocket.OPEN) return;
67
+ e2e.initing = true;
68
+ try {
69
+ const self = await e2eSelfKey();
70
+ const ch = new DeviceChannel(self);
71
+ const init = await ch.begin();
72
+ e2e.ch = ch;
73
+ send({ t: "frame", payload: { op: "e2e.init", e: init.e } });
74
+ } finally {
75
+ e2e.initing = false;
76
+ }
77
+ }
78
+
79
+ // Resume bookkeeping: where this device stopped reading each room's stream, so a
80
+ // reconnect can replay what it missed. Keyed per room; cleared when the cloud
81
+ // says the stream's generation moved (gateway restart) or the state went stale.
82
+ const streamKey = (roomId) => `herdgate.stream.${roomId}`;
83
+ function loadStream(roomId) {
84
+ if (!roomId) return null;
85
+ try {
86
+ const v = JSON.parse(localStorage.getItem(streamKey(roomId)) ?? "null");
87
+ return v && typeof v.gen === "string" && typeof v.seq === "number" && v.seq >= 0 ? v : null;
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+ function saveStream(roomId, gen, seq) {
93
+ if (!roomId || typeof gen !== "string" || typeof seq !== "number" || seq < 0) return;
94
+ localStorage.setItem(streamKey(roomId), JSON.stringify({ gen, seq }));
95
+ }
96
+ function clearStream(roomId) {
97
+ if (roomId) localStorage.removeItem(streamKey(roomId));
98
+ }
99
+
100
+ const state = {
101
+ token: localStorage.getItem(TOKEN_KEY) ?? "",
102
+ cloud: localStorage.getItem(CLOUD_KEY) ?? "",
103
+ deviceId: localStorage.getItem(DEVICE_KEY) ?? "",
104
+ deviceSecret: localStorage.getItem(DEVICE_SECRET_KEY) ?? "",
105
+ ws: null,
106
+ hello: null,
107
+ roomId: null,
108
+ view: null,
109
+ viewError: null,
110
+ retry: 0,
111
+ closedByUs: false,
112
+ };
113
+
114
+ /** The cloud base: an explicit setting, else this page's origin (same-origin deployment). */
115
+ function cloudBase() {
116
+ const raw = (state.cloud || location.origin).replace(/\/$/, "");
117
+ return raw;
118
+ }
119
+
120
+ function wsUrl() {
121
+ return `${cloudBase().replace(/^http/, "ws")}/v1/device/ws`;
122
+ }
123
+
124
+ // ---- tiny DOM helpers (no innerHTML anywhere) ------------------------------
125
+
126
+ function show(id, on) {
127
+ $(id).hidden = !on;
128
+ }
129
+ function text(id, value) {
130
+ $(id).textContent = value ?? "";
131
+ }
132
+ function setStatus(label, kind) {
133
+ const el = $("status");
134
+ el.textContent = label;
135
+ el.dataset.kind = kind ?? "";
136
+ }
137
+
138
+ function showError(id, message) {
139
+ const el = $(id);
140
+ if (!message) {
141
+ el.hidden = true;
142
+ el.textContent = "";
143
+ return;
144
+ }
145
+ el.hidden = false;
146
+ el.textContent = message;
147
+ }
148
+
149
+ // ---- screens ---------------------------------------------------------------
150
+
151
+ function render() {
152
+ const signedIn = Boolean(state.token);
153
+ show("signin", !signedIn);
154
+ show("rooms", signedIn && !state.roomId);
155
+ show("room", signedIn && Boolean(state.roomId));
156
+
157
+ if (signedIn && !state.roomId) renderRooms();
158
+ if (state.roomId) renderRoom();
159
+ }
160
+
161
+ function renderRooms() {
162
+ const list = $("room-list");
163
+ list.replaceChildren();
164
+ const agents = state.hello?.agents ?? [];
165
+ show("rooms-empty", agents.length === 0);
166
+
167
+ for (const room of agents) {
168
+ const node = $("room-row").content.cloneNode(true);
169
+ node.querySelector(".name").textContent = room.name || room.roomId;
170
+ const meta = [];
171
+ meta.push(room.online ? "online" : "offline");
172
+ if (room.scope) meta.push(`paired · ${room.scope}`);
173
+ node.querySelector(".meta").textContent = meta.join(" · ");
174
+ node.querySelector(".row").dataset.roomId = room.roomId;
175
+ node.querySelector(".rowbtn").addEventListener("click", () => {
176
+ const mine = (state.hello?.agents ?? []).find((r) => r.roomId === room.roomId);
177
+ if (mine?.scope) {
178
+ state.roomId = room.roomId;
179
+ state.view = null;
180
+ state.viewError = null;
181
+ render();
182
+ askView();
183
+ } else {
184
+ openPair(room.roomId);
185
+ }
186
+ });
187
+ list.append(node);
188
+ }
189
+ }
190
+
191
+ function renderRoom() {
192
+ const room = (state.hello?.agents ?? []).find((r) => r.roomId === state.roomId);
193
+ text("room-name", room?.name || state.roomId);
194
+ text("room-state", room ? (room.online ? "host online" : "host offline") : "unknown room");
195
+
196
+ // E2E status: the pinned host fingerprint, or a loud note when it changed.
197
+ const e2eNote = $("e2e-note");
198
+ const pinned = state.roomId ? localStorage.getItem(e2eFpKey(state.roomId)) : null;
199
+ const current = e2e.ch?.ready() && e2e.ready ? e2e.ch.hostFingerprint : null;
200
+ const shown = current ?? pinned;
201
+ if (pinned && current && current !== pinned) {
202
+ e2eNote.hidden = false;
203
+ e2eNote.className = "error small";
204
+ e2eNote.textContent = `The host key changed (was ${pinned}, now ${current}). Re-pair if you did not do this.`;
205
+ } else if (shown) {
206
+ e2eNote.hidden = false;
207
+ e2eNote.className = "muted small";
208
+ e2eNote.textContent = `end-to-end encrypted · host key ${shown}`;
209
+ } else {
210
+ e2eNote.hidden = true;
211
+ }
212
+
213
+ const box = $("view");
214
+ box.replaceChildren();
215
+
216
+ if (!room?.online) {
217
+ box.append(note("The host is not connected. Start its publisher — in Herdr, press Publish."));
218
+ return;
219
+ }
220
+ if (state.viewError) {
221
+ box.append(note(state.viewError, "error"));
222
+ return;
223
+ }
224
+ if (!state.view) {
225
+ box.append(note("Waiting for the host…"));
226
+ return;
227
+ }
228
+
229
+ const v = state.view;
230
+ const summary = v.summary ?? v;
231
+ if (!summary || typeof summary !== "object") {
232
+ box.append(note("The host answered something this app does not understand."));
233
+ return;
234
+ }
235
+
236
+ const grid = document.createElement("dl");
237
+ grid.className = "grid";
238
+ const add = (label, value) => {
239
+ if (value === undefined || value === null || value === "") return;
240
+ const dt = document.createElement("dt");
241
+ dt.textContent = label;
242
+ const dd = document.createElement("dd");
243
+ dd.textContent = String(value);
244
+ grid.append(dt, dd);
245
+ };
246
+ add("herdr", summary.herdr);
247
+ add("spaces", summary.workspaces);
248
+ add("agents", summary.agents);
249
+ add("working", summary.working);
250
+ add("blocked", summary.blocked);
251
+ box.append(grid);
252
+
253
+ if (Array.isArray(summary.labels) && summary.labels.length > 0) {
254
+ const list = document.createElement("ul");
255
+ list.className = "chips";
256
+ for (const label of summary.labels) {
257
+ const li = document.createElement("li");
258
+ li.textContent = String(label);
259
+ list.append(li);
260
+ }
261
+ box.append(list);
262
+ }
263
+ if (v.takenAt) {
264
+ const p = document.createElement("p");
265
+ p.className = "muted small";
266
+ p.textContent = `as of ${new Date(v.takenAt).toLocaleTimeString()}`;
267
+ box.append(p);
268
+ }
269
+
270
+ // The SSH leg: this device's own key dials the gate. In the Herdr phone app, add a
271
+ // machine with this host/port and the key shown once at pair time.
272
+ if (state.deviceSecret && state.deviceId) {
273
+ const details = document.createElement("details");
274
+ details.className = "ssh";
275
+ // Fresh from pairing: the section opens itself and STAYS open across the
276
+ // re-renders that follow (the view frame rebuilds this node) until the person
277
+ // closes it — the key is the one thing they must not miss.
278
+ if (state.showSecretOnce) details.open = true;
279
+ details.addEventListener("toggle", () => {
280
+ if (!details.open) state.showSecretOnce = false;
281
+ });
282
+ const summary = document.createElement("summary");
283
+ summary.textContent = "SSH for the Herdr app";
284
+ const pre = document.createElement("pre");
285
+ const host = location.hostname || "your-gate";
286
+ // The port comes from the cloud's hello (its SSH leg); the host is whatever the
287
+ // person typed to reach this page. The cloud advertises the SSH hostname it
288
+ // wants phones to use (bridge / AAAA name); only without one do we fall back
289
+ // to this page's host.
290
+ const port = state.sshPort ?? 2222;
291
+ const sshHost = state.sshHost || host;
292
+ pre.textContent = `ssh -p ${port} ${state.deviceId}@${sshHost}`;
293
+ details.append(summary, pre);
294
+
295
+ // The device key lives in this browser's localStorage (the cloud returns it
296
+ // once and keeps only a hash). It IS the SSH password — show it, on demand.
297
+ // `keyShown` lives in state so the reveal survives the room re-renders that
298
+ // rebuild this whole node whenever a frame arrives.
299
+ const keyRow = document.createElement("div");
300
+ keyRow.className = "keyrow";
301
+ if (state.keyShown && state.deviceSecret) {
302
+ const keyEl = document.createElement("pre");
303
+ keyEl.textContent = state.deviceSecret;
304
+ keyEl.setAttribute("aria-label", "device key");
305
+ keyRow.append(keyEl);
306
+ } else {
307
+ const reveal = document.createElement("button");
308
+ reveal.type = "button";
309
+ reveal.className = "link";
310
+ reveal.textContent = "Show this device's key";
311
+ reveal.addEventListener("click", () => {
312
+ state.keyShown = true;
313
+ renderRoom();
314
+ });
315
+ keyRow.append(reveal);
316
+ }
317
+ details.append(keyRow);
318
+
319
+ // Registered SSH PUBLIC keys: the machine that runs `hc machine add` can then log
320
+ // in with its key (system ssh prefers keys/agent) — no password prompt, which the
321
+ // app's non-interactive add screen requires.
322
+ const keysBlock = document.createElement("div");
323
+ keysBlock.className = "sshkeys";
324
+ const keysTitle = document.createElement("p");
325
+ keysTitle.className = "muted small";
326
+ keysTitle.textContent = "Public keys — paste the output of `cat ~/.ssh/id_ed25519.pub` from the machine that will add this one:";
327
+ keysBlock.append(keysTitle);
328
+ const keyList = document.createElement("div");
329
+ keysBlock.append(keyList);
330
+ const addRow = document.createElement("div");
331
+ addRow.className = "keyrow";
332
+ const addInput = document.createElement("input");
333
+ addInput.type = "text";
334
+ addInput.placeholder = "ssh-ed25519 AAAA… your@machine";
335
+ addInput.setAttribute("autocomplete", "off");
336
+ addInput.setAttribute("spellcheck", "false");
337
+ addInput.className = "pubkey-input";
338
+ const addBtn = document.createElement("button");
339
+ addBtn.type = "button";
340
+ addBtn.textContent = "Add key";
341
+ addBtn.className = "primary";
342
+ addRow.append(addInput, addBtn);
343
+ keysBlock.append(addRow);
344
+ const cfgHint = document.createElement("p");
345
+ cfgHint.className = "muted small";
346
+ cfgHint.textContent = `then on that machine: hc machine add ${state.deviceId}@${sshHost}:${port} (add “StrictHostKeyChecking accept-new” for ${sshHost} in ~/.ssh/config to skip the host-key question)`;
347
+ keysBlock.append(cfgHint);
348
+ details.append(keysBlock);
349
+
350
+ const renderKeys = (keys) => {
351
+ keyList.replaceChildren();
352
+ for (const k of keys) {
353
+ const row = document.createElement("div");
354
+ row.className = "keyrow";
355
+ const pre = document.createElement("pre");
356
+ pre.textContent = `${k.fp} ${k.comment}`.trim();
357
+ row.append(pre);
358
+ const rm = document.createElement("button");
359
+ rm.type = "button";
360
+ rm.className = "link";
361
+ rm.textContent = "remove";
362
+ rm.addEventListener("click", async () => {
363
+ await fetch(`${cloudBase()}/v1/device/sshkey`, {
364
+ method: "DELETE",
365
+ headers: { "content-type": "application/json" },
366
+ body: JSON.stringify({ device: state.deviceId, deviceSecret: state.deviceSecret, b64: k.b64 }),
367
+ });
368
+ loadKeys();
369
+ });
370
+ row.append(rm);
371
+ keyList.append(row);
372
+ }
373
+ if (!keys.length) {
374
+ const none = document.createElement("p");
375
+ none.className = "muted small";
376
+ none.textContent = "none yet — password login still works";
377
+ keyList.append(none);
378
+ }
379
+ };
380
+ const loadKeys = async () => {
381
+ try {
382
+ const r = await fetch(`${cloudBase()}/v1/device/sshkey?device=${encodeURIComponent(state.deviceId)}`, {
383
+ method: "GET",
384
+ headers: { "content-type": "application/json", "x-herdgate-secret": state.deviceSecret },
385
+ });
386
+ if (r.ok) renderKeys((await r.json()).keys ?? []);
387
+ } catch {
388
+ /* offline: the section just stays as-is */
389
+ }
390
+ };
391
+ addBtn.addEventListener("click", async () => {
392
+ const pubkey = addInput.value.trim();
393
+ if (!pubkey) return;
394
+ const r = await fetch(`${cloudBase()}/v1/device/sshkey`, {
395
+ method: "POST",
396
+ headers: { "content-type": "application/json" },
397
+ body: JSON.stringify({ device: state.deviceId, deviceSecret: state.deviceSecret, pubkey }),
398
+ });
399
+ if (!r.ok) {
400
+ addInput.value = "";
401
+ addInput.placeholder = await r.json().then((b) => b.error ?? "rejected").catch(() => "rejected");
402
+ return;
403
+ }
404
+ addInput.value = "";
405
+ loadKeys();
406
+ });
407
+ loadKeys();
408
+ box.append(details);
409
+ }
410
+ }
411
+
412
+ function note(message, kind) {
413
+ const p = document.createElement("p");
414
+ p.className = kind === "error" ? "error" : "muted";
415
+ p.textContent = message;
416
+ return p;
417
+ }
418
+
419
+ // ---- the socket ------------------------------------------------------------
420
+
421
+ function connect() {
422
+ if (!state.token) return;
423
+ state.closedByUs = false;
424
+ let ws;
425
+ try {
426
+ ws = new WebSocket(wsUrl());
427
+ } catch {
428
+ return retryLater();
429
+ }
430
+ state.ws = ws;
431
+ setStatus("connecting", "wait");
432
+
433
+ ws.addEventListener("open", () => {
434
+ // A paired device re-attaches with its own key; the account token is the owner path
435
+ // (first sign-in, pairing, management). A device that knows where it stopped reading
436
+ // also asks to resume its room's stream.
437
+ const hello = state.deviceSecret && state.deviceId
438
+ ? { device: state.deviceId, deviceSecret: state.deviceSecret }
439
+ : { accountToken: state.token, ...(state.deviceId ? { device: state.deviceId } : {}) };
440
+ const resume = state.deviceSecret && state.deviceId ? loadStream(state.roomId) : null;
441
+ ws.send(JSON.stringify({
442
+ v: 1,
443
+ t: "hello",
444
+ ...hello,
445
+ name: deviceName(),
446
+ ...(resume ? { resume: { room: state.roomId, gen: resume.gen, seq: resume.seq } } : {}),
447
+ }));
448
+ });
449
+
450
+ ws.addEventListener("message", (event) => {
451
+ let m;
452
+ try {
453
+ m = JSON.parse(event.data);
454
+ } catch {
455
+ return;
456
+ }
457
+ void onMessage(m, ws);
458
+ });
459
+
460
+ ws.addEventListener("close", (event) => {
461
+ state.ws = null;
462
+ state.hello = null;
463
+ e2eReset();
464
+ if (state.closedByUs) return;
465
+ if (event.code === 4001) {
466
+ // The cloud refused the token: do not hammer it, send the person back to sign-in.
467
+ setStatus("signed out", "bad");
468
+ forgetToken();
469
+ return;
470
+ }
471
+ setStatus("offline", "bad");
472
+ retryLater();
473
+ });
474
+
475
+ ws.addEventListener("error", () => {
476
+ /* close carries the retry */
477
+ });
478
+ }
479
+
480
+ async function onMessage(m, ws) {
481
+ // Track the room stream so the next reconnect resumes from here.
482
+ if (typeof m.seq === "number" && (m.t === "frame" || m.t === "presence")) {
483
+ const rid = m.t === "presence" ? m.roomId : state.roomId;
484
+ const cur = loadStream(rid);
485
+ if (cur && m.seq > cur.seq) saveStream(rid, cur.gen, m.seq);
486
+ }
487
+ switch (m.t) {
488
+ case "hello": {
489
+ state.retry = 0;
490
+ state.hello = { agents: Array.isArray(m.agents) ? m.agents : [] };
491
+ if (m.device?.id) {
492
+ state.deviceId = m.device.id;
493
+ localStorage.setItem(DEVICE_KEY, m.device.id);
494
+ if (!state.roomId) state.roomId = m.device.roomId;
495
+ }
496
+ // Keep the chosen room only while it is still visible to this account/device.
497
+ if (state.roomId && !state.hello.agents.some((r) => r.roomId === state.roomId)) state.roomId = null;
498
+ // Resume outcome: the stream header carries the cloud's position; when the
499
+ // replay had a hole (too long away), askView() below re-fetches the state.
500
+ const rid = m.device?.roomId ?? null;
501
+ if (m.ssh && typeof m.ssh.port === "number") {
502
+ state.sshPort = m.ssh.port;
503
+ if (typeof m.ssh.host === "string") state.sshHost = m.ssh.host;
504
+ }
505
+ if (m.resumed === true && m.stream && typeof m.stream.seq === "number") {
506
+ saveStream(rid, m.stream.gen, m.stream.seq);
507
+ } else if (rid) {
508
+ if (m.stream && typeof m.stream.seq === "number") saveStream(rid, m.stream.gen, m.stream.seq);
509
+ else clearStream(rid);
510
+ }
511
+ setStatus("online", "good");
512
+ render();
513
+ if (state.roomId) {
514
+ void e2eBegin();
515
+ askView();
516
+ }
517
+ return;
518
+ }
519
+ case "frame": {
520
+ const payload = m.payload;
521
+ if (payload && typeof payload === "object" && payload.op === "e2e.reply") {
522
+ await onE2eReply(payload);
523
+ return;
524
+ }
525
+ if (payload && typeof payload === "object" && payload.op === "e2e.ready") {
526
+ e2e.ready = true;
527
+ renderRoom();
528
+ askView(); // now over the encrypted channel
529
+ return;
530
+ }
531
+ if (payload && typeof payload === "object" && payload.op === "e2e") {
532
+ if (!e2e.ch?.ready()) return; // ciphertext for a session we do not have
533
+ let inner;
534
+ try {
535
+ inner = await e2e.ch.recv(payload);
536
+ } catch {
537
+ // Wrong key or tampered frame: start over rather than show nonsense.
538
+ e2eReset();
539
+ void e2eBegin();
540
+ return;
541
+ }
542
+ applyPayload(inner);
543
+ return;
544
+ }
545
+ if (payload && typeof payload === "object" && payload.code === "e2e" && e2e.ch) {
546
+ // The host dropped our session (decrypt failed there): renegotiate.
547
+ e2eReset();
548
+ void e2eBegin();
549
+ return;
550
+ }
551
+ if (payload && typeof payload === "object" && payload.op === "view" && e2e.ch?.ready() && e2e.ready) {
552
+ // Plaintext view while an encrypted session is up: the host lost its side —
553
+ // renegotiate (its publisher restarted).
554
+ e2eReset();
555
+ void e2eBegin();
556
+ applyPayload(payload);
557
+ return;
558
+ }
559
+ applyPayload(payload);
560
+ return;
561
+ }
562
+ case "pair.granted": {
563
+ state.deviceId = m.device?.id ?? state.deviceId;
564
+ if (state.deviceId) localStorage.setItem(DEVICE_KEY, state.deviceId);
565
+ // Shown once and kept only on this device: it is this phone's SSH key on the gate.
566
+ if (typeof m.deviceSecret === "string" && m.deviceSecret) {
567
+ state.deviceSecret = m.deviceSecret;
568
+ localStorage.setItem(DEVICE_SECRET_KEY, m.deviceSecret);
569
+ state.showSecretOnce = true;
570
+ }
571
+ state.roomId = m.device?.roomId ?? state.roomId;
572
+ closePair();
573
+ render();
574
+ void e2eBegin();
575
+ askView();
576
+ void subscribePush();
577
+ return;
578
+ }
579
+ case "pair.denied": {
580
+ showError("pair-error", m.reason ? `Denied: ${m.reason}` : "Denied");
581
+ return;
582
+ }
583
+ case "presence": {
584
+ const room = (state.hello?.agents ?? []).find((r) => r.roomId === m.roomId);
585
+ if (room) room.online = m.online === true;
586
+ if (state.roomId === m.roomId) {
587
+ renderRoom();
588
+ if (m.online === true) askView();
589
+ } else {
590
+ renderRooms();
591
+ }
592
+ return;
593
+ }
594
+ case "error": {
595
+ // A protocol-level complaint (bad message, not paired, …).
596
+ if (m.code === "not-paired") state.roomId = null;
597
+ render();
598
+ return;
599
+ }
600
+ default:
601
+ return;
602
+ }
603
+ }
604
+
605
+ function retryLater() {
606
+ const wait = Math.min(30_000, 1_000 * 2 ** state.retry) + Math.random() * 500;
607
+ state.retry += 1;
608
+ setTimeout(connect, wait);
609
+ }
610
+
611
+ /** Ask the host for its view: the only op this app ever sends (encrypted when up). */
612
+ async function askView() {
613
+ if (state.ws?.readyState !== WebSocket.OPEN || !state.roomId) return;
614
+ if (e2e.ch?.ready() && e2e.ready) {
615
+ send({ t: "frame", payload: await e2e.ch.send({ op: "view" }) });
616
+ return;
617
+ }
618
+ void e2eBegin(); // establish in the background; the ack path asks again over it
619
+ send({ t: "frame", payload: { op: "view" } });
620
+ }
621
+ function applyPayload(payload) {
622
+ // The plaintext (or decrypted) payload from the host lands here.
623
+ if (payload && typeof payload === "object" && payload.op === "view") {
624
+ state.view = payload.view;
625
+ state.viewError = null;
626
+ } else if (payload && typeof payload === "object" && payload.op === "error") {
627
+ // The host refused or could not answer: an op we may not use, or its Herdr is down.
628
+ state.viewError = payload.message ?? payload.code ?? "the host refused";
629
+ state.view = null;
630
+ }
631
+ if (state.roomId) renderRoom();
632
+ }
633
+
634
+ // ---- push wake ---------------------------------------------------------------
635
+
636
+ /** Subscribe this device to silent wake pushes; ask for permission only once paired. */
637
+ async function subscribePush() {
638
+ if (!(state.deviceSecret && state.deviceId)) return; // paired devices only
639
+ if (!("serviceWorker" in navigator) || !("PushManager" in window)) return;
640
+ try {
641
+ const reg = await navigator.serviceWorker.ready;
642
+ let sub = await reg.pushManager.getSubscription();
643
+ if (!sub) {
644
+ const keyRes = await fetch(`${cloudBase()}/v1/push/key`);
645
+ if (!keyRes.ok) return; // push disabled on this cloud
646
+ const { publicKey } = await keyRes.json();
647
+ const raw = Uint8Array.from(atob(publicKey.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
648
+ sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: raw });
649
+ }
650
+ const endpoint = sub.endpoint;
651
+ if (state.pushEndpoint === endpoint) return;
652
+ state.pushEndpoint = endpoint;
653
+ await fetch(`${cloudBase()}/v1/device/push`, {
654
+ method: "POST",
655
+ headers: { "content-type": "application/json" },
656
+ body: JSON.stringify({ device: state.deviceId, deviceSecret: state.deviceSecret, endpoint }),
657
+ });
658
+ } catch {
659
+ /* permission denied or push unavailable: the gate still works without it */
660
+ }
661
+ }
662
+
663
+ /** The host answered our handshake: finish it, pin its fingerprint (TOFU). */
664
+ async function onE2eReply(payload) {
665
+ const ch = e2e.ch;
666
+ if (!ch) return;
667
+ try {
668
+ const finish = await ch.acceptReply(payload);
669
+ send({ t: "frame", payload: { op: "e2e.finish", c: finish.c } });
670
+ } catch {
671
+ e2eReset();
672
+ return;
673
+ }
674
+ const fp = ch.hostFingerprint;
675
+ if (fp && state.roomId) {
676
+ const stored = localStorage.getItem(e2eFpKey(state.roomId));
677
+ if (!stored) localStorage.setItem(e2eFpKey(state.roomId), fp);
678
+ renderRoom();
679
+ }
680
+ // The channel is up: ask for the view over it.
681
+ askView();
682
+ }
683
+
684
+ function send(message) {
685
+ if (state.ws?.readyState !== WebSocket.OPEN) return false;
686
+ state.ws.send(JSON.stringify({ v: 1, ...message }));
687
+ return true;
688
+ }
689
+
690
+ function deviceName() {
691
+ const ua = navigator.userAgent;
692
+ if (/iPhone/.test(ua)) return "iPhone";
693
+ if (/iPad/.test(ua)) return "iPad";
694
+ if (/Android/.test(ua)) return "Android";
695
+ if (/Macintosh/.test(ua)) return "Mac browser";
696
+ return "browser";
697
+ }
698
+
699
+ // ---- pairing ---------------------------------------------------------------
700
+
701
+ function openPair(roomId) {
702
+ state.pairRoom = roomId;
703
+ show("pair", true);
704
+ show("rooms", false);
705
+ showError("pair-error", null);
706
+ const name = $("pair-name");
707
+ if (!name.value) name.value = deviceName();
708
+ name.focus();
709
+ }
710
+
711
+ function closePair() {
712
+ show("pair", false);
713
+ showError("pair-error", null);
714
+ }
715
+
716
+ $("pair-form").addEventListener("submit", (event) => {
717
+ event.preventDefault();
718
+ showError("pair-error", null);
719
+ const name = $("pair-name").value.trim() || deviceName();
720
+ const scope = $("pair-scope").value === "act" ? "act" : "read";
721
+ const ok = send({ t: "pair.begin", roomId: state.pairRoom, name, scope });
722
+ if (!ok) return showError("pair-error", "not connected to the cloud");
723
+ // `act` waits for a human on the host; read is immediate.
724
+ $("pair-form").querySelector("button").disabled = true;
725
+ setTimeout(() => {
726
+ const b = $("pair-form").querySelector("button");
727
+ if (b) b.disabled = false;
728
+ }, 3_000);
729
+ });
730
+
731
+ // ---- sign-in, settings -----------------------------------------------------
732
+
733
+ $("signin-form").addEventListener("submit", (event) => {
734
+ event.preventDefault();
735
+ const token = $("token").value.trim();
736
+ if (!token) return showError("signin-error", "a token is required");
737
+ state.token = token;
738
+ localStorage.setItem(TOKEN_KEY, token);
739
+ showError("signin-error", null);
740
+ $("token").value = "";
741
+ render();
742
+ connect();
743
+ });
744
+
745
+ $("menu").addEventListener("click", () => {
746
+ $("cloud").value = state.cloud;
747
+ $("settings").showModal();
748
+ });
749
+
750
+ $("settings-form").addEventListener("submit", () => {
751
+ const value = $("cloud").value.trim().replace(/\/$/, "");
752
+ if (value !== state.cloud) {
753
+ state.cloud = value;
754
+ if (value) localStorage.setItem(CLOUD_KEY, value);
755
+ else localStorage.removeItem(CLOUD_KEY);
756
+ // A different cloud is a different account: reconnect from scratch.
757
+ state.hello = null;
758
+ state.roomId = null;
759
+ if (state.ws) {
760
+ state.closedByUs = true;
761
+ state.ws.close();
762
+ }
763
+ connect();
764
+ }
765
+ });
766
+
767
+ $("signout").addEventListener("click", () => forgetToken());
768
+
769
+ /** Back to the machine list — from the pair screen or the room screen.
770
+ * Delegated at the document level so it works no matter what rebuilt the DOM
771
+ * (and with a generous tap target; see .backbtn in the CSS). */
772
+ const goMachines = () => {
773
+ state.roomId = null;
774
+ state.view = null;
775
+ state.viewError = null;
776
+ state.keyShown = false;
777
+ closePair();
778
+ show("pair", false);
779
+ show("room", false);
780
+ render();
781
+ if (state.hello) renderRooms();
782
+ };
783
+ document.addEventListener("click", (event) => {
784
+ const target = event.target instanceof Element ? event.target.closest("#back, #pair-back") : null;
785
+ if (target) goMachines();
786
+ });
787
+
788
+ function forgetToken() {
789
+ state.token = "";
790
+ state.deviceId = "";
791
+ state.deviceSecret = "";
792
+ localStorage.removeItem(DEVICE_SECRET_KEY);
793
+ state.roomId = null;
794
+ state.hello = null;
795
+ localStorage.removeItem(TOKEN_KEY);
796
+ localStorage.removeItem(DEVICE_KEY);
797
+ if (state.ws) {
798
+ state.closedByUs = true;
799
+ state.ws.close();
800
+ }
801
+ $("settings").close();
802
+ render();
803
+ }
804
+
805
+ // ---- boot ------------------------------------------------------------------
806
+
807
+ // Which build is this? Shown in the machine list so a stale phone install is
808
+ // obvious at a glance (the service worker updates on the second launch).
809
+ {
810
+ const el = document.getElementById("build");
811
+ if (el) el.textContent = "herdgate " + BUILD;
812
+ }
813
+
814
+ render();
815
+ if (state.token) connect();
816
+
817
+ // A phone that wakes up should not show a dead screen.
818
+ document.addEventListener("visibilitychange", () => {
819
+ if (document.visibilityState !== "visible") return;
820
+ if (state.ws?.readyState === WebSocket.OPEN) {
821
+ if (state.roomId) askView();
822
+ } else {
823
+ state.retry = 0;
824
+ connect();
825
+ }
826
+ });
827
+
828
+ // Installable shell (offline start). Registered late so it never delays first paint.
829
+ if ("serviceWorker" in navigator && location.protocol !== "file:") {
830
+ addEventListener("load", () => {
831
+ navigator.serviceWorker.register("/sw.js").catch(() => {
832
+ /* an app without offline start is still an app */
833
+ });
834
+ });
835
+ }