@bom0792/herdgate 0.9.21 → 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/web/app.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // herdgate PWA — the device side of the gate.
2
2
  //
3
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
4
+ // has, manages a separate pairing per machine, and shows
5
5
  // the read-only view the host publishes.
6
6
  //
7
7
  // House rules it respects:
@@ -11,13 +11,31 @@
11
11
  // - the token lives in localStorage on this device and is never sent anywhere but the
12
12
  // cloud's own WS endpoint.
13
13
 
14
- const BUILD = "v0.9.20";
14
+ const BUILD = "v0.9.20-web.5";
15
15
 
16
16
  const $ = (id) => document.getElementById(id);
17
17
  const TOKEN_KEY = "herdgate.token";
18
18
  const CLOUD_KEY = "herdgate.cloud";
19
19
  const DEVICE_KEY = "herdgate.device";
20
20
  const DEVICE_SECRET_KEY = "herdgate.deviceSecret";
21
+ const PAIRS_KEY = "herdgate.roomPairs";
22
+
23
+ function roomPairs() {
24
+ try { return new Map(JSON.parse(localStorage.getItem(PAIRS_KEY) ?? "[]")); }
25
+ catch { return new Map(); }
26
+ }
27
+
28
+ function savePair(roomId, pair) {
29
+ const pairs = roomPairs();
30
+ if (pair) pairs.set(roomId, pair);
31
+ else pairs.delete(roomId);
32
+ localStorage.setItem(PAIRS_KEY, JSON.stringify([...pairs]));
33
+ }
34
+
35
+ function clearLegacyPair() {
36
+ localStorage.removeItem(DEVICE_KEY);
37
+ localStorage.removeItem(DEVICE_SECRET_KEY);
38
+ }
21
39
 
22
40
  import { DeviceChannel, generateKeyPair, fingerprint } from "/e2e.js";
23
41
 
@@ -52,8 +70,9 @@ function e2eB64d(s) {
52
70
  // Per-room channel state; reset when the socket drops. The channel only carries
53
71
  // traffic after the host's `e2e.ready` ack — nothing may race the handshake's
54
72
  // last step, or the transport counters desync for good.
55
- const e2e = { ch: null, initing: false, ready: false };
73
+ const e2e = { ch: null, initing: false, ready: false, epoch: 0 };
56
74
  function e2eReset() {
75
+ e2e.epoch++;
57
76
  e2e.ch = null;
58
77
  e2e.initing = false;
59
78
  e2e.ready = false;
@@ -64,15 +83,17 @@ async function e2eBegin() {
64
83
  if (e2e.ch?.ready() || e2e.initing) return;
65
84
  if (!(state.deviceSecret && state.deviceId && state.roomId)) return;
66
85
  if (state.ws?.readyState !== WebSocket.OPEN) return;
86
+ const epoch = e2e.epoch;
67
87
  e2e.initing = true;
68
88
  try {
69
89
  const self = await e2eSelfKey();
70
90
  const ch = new DeviceChannel(self);
71
91
  const init = await ch.begin();
92
+ if (epoch !== e2e.epoch) return;
72
93
  e2e.ch = ch;
73
94
  send({ t: "frame", payload: { op: "e2e.init", e: init.e } });
74
95
  } finally {
75
- e2e.initing = false;
96
+ if (epoch === e2e.epoch) e2e.initing = false;
76
97
  }
77
98
  }
78
99
 
@@ -102,11 +123,15 @@ const state = {
102
123
  cloud: localStorage.getItem(CLOUD_KEY) ?? "",
103
124
  deviceId: localStorage.getItem(DEVICE_KEY) ?? "",
104
125
  deviceSecret: localStorage.getItem(DEVICE_SECRET_KEY) ?? "",
126
+ deviceRoom: null,
127
+ pairRoom: null,
128
+ pairSocket: null,
105
129
  ws: null,
106
130
  hello: null,
107
131
  roomId: null,
108
132
  view: null,
109
133
  viewError: null,
134
+ roomUi: null,
110
135
  terms: null,
111
136
  termTarget: null,
112
137
  termAnsi: null,
@@ -114,7 +139,6 @@ const state = {
114
139
  termBody: null,
115
140
  termPre: null,
116
141
  retry: 0,
117
- closedByUs: false,
118
142
  };
119
143
 
120
144
  /** The cloud base: an explicit setting, else this page's origin (same-origin deployment). */
@@ -157,8 +181,8 @@ function showError(id, message) {
157
181
  function render() {
158
182
  const signedIn = Boolean(state.token);
159
183
  show("signin", !signedIn);
160
- show("rooms", signedIn && !state.roomId);
161
- show("room", signedIn && Boolean(state.roomId));
184
+ show("rooms", signedIn && !state.roomId && !state.pairRoom);
185
+ show("room", signedIn && Boolean(state.roomId) && !state.pairRoom);
162
186
 
163
187
  if (signedIn && !state.roomId) renderRooms();
164
188
  if (state.roomId) renderRoom();
@@ -168,6 +192,7 @@ function renderRooms() {
168
192
  const list = $("room-list");
169
193
  list.replaceChildren();
170
194
  const agents = state.hello?.agents ?? [];
195
+ const pairs = roomPairs();
171
196
  show("rooms-empty", agents.length === 0);
172
197
 
173
198
  for (const room of agents) {
@@ -175,26 +200,21 @@ function renderRooms() {
175
200
  node.querySelector(".name").textContent = room.name || room.roomId;
176
201
  const meta = [];
177
202
  meta.push(room.online ? "online" : "offline");
178
- if (room.scope) meta.push(`paired · ${room.scope}`);
203
+ const scope = pairs.get(room.roomId)?.scope;
204
+ if (scope) meta.push(`paired · ${scope}`);
179
205
  node.querySelector(".meta").textContent = meta.join(" · ");
180
206
  node.querySelector(".row").dataset.roomId = room.roomId;
181
207
  node.querySelector(".rowbtn").addEventListener("click", () => {
182
- const mine = (state.hello?.agents ?? []).find((r) => r.roomId === room.roomId);
183
- if (mine?.scope) {
184
- state.roomId = room.roomId;
185
- state.view = null;
186
- state.viewError = null;
187
- render();
188
- askView();
189
- } else {
190
- openPair(room.roomId);
191
- }
208
+ const pairing = roomPairs().get(room.roomId);
209
+ if (pairing) selectRoom(room.roomId, pairing);
210
+ else openPair(room.roomId);
192
211
  });
193
212
  list.append(node);
194
213
  }
195
214
  }
196
215
 
197
216
  function renderRoom() {
217
+ if (!state.roomId) return;
198
218
  const room = (state.hello?.agents ?? []).find((r) => r.roomId === state.roomId);
199
219
  text("room-name", room?.name || state.roomId);
200
220
  text("room-state", room ? (room.online ? "host online" : "host offline") : "unknown room");
@@ -216,9 +236,29 @@ function renderRoom() {
216
236
  e2eNote.hidden = true;
217
237
  }
218
238
 
219
- const box = $("view");
220
- box.replaceChildren();
239
+ if (!state.roomUi) {
240
+ const summary = document.createElement("div");
241
+ const live = document.createElement("div");
242
+ const controls = document.createElement("div");
243
+ $("view").replaceChildren(summary, live, controls);
244
+ const updateSshHint = renderRoomControls(controls);
245
+ state.roomUi = { summary, live, updateSshHint };
246
+ }
247
+ const ui = state.roomUi;
248
+ const online = Boolean(room?.online);
249
+ if (ui.online !== online || ui.view !== state.view || ui.error !== state.viewError) {
250
+ ui.online = online;
251
+ ui.view = state.view;
252
+ ui.error = state.viewError;
253
+ ui.summary.replaceChildren();
254
+ renderHostView(ui.summary, room);
255
+ }
256
+ const { live, updateSshHint } = ui;
257
+ renderLiveTerminals(live, online);
258
+ updateSshHint?.();
259
+ }
221
260
 
261
+ function renderHostView(box, room) {
222
262
  if (!room?.online) {
223
263
  box.append(note("The host is not connected. Start its publisher — in Herdr, press Publish."));
224
264
  return;
@@ -272,10 +312,11 @@ function renderRoom() {
272
312
  p.textContent = `as of ${new Date(v.takenAt).toLocaleTimeString()}`;
273
313
  box.append(p);
274
314
  }
315
+ }
275
316
 
276
- // Live terminals (read-only): the host's own panes — pick one and watch its
277
- // ANSI screen. Everything rides the same frames (E2E when paired), no new trust.
278
- if (room?.online) {
317
+ function renderLiveTerminals(box, online) {
318
+ box.hidden = !online;
319
+ if (online && !state.termBody) {
279
320
  const tblock = document.createElement("details");
280
321
  tblock.className = "terms";
281
322
  const ts = document.createElement("summary");
@@ -290,25 +331,18 @@ function renderRoom() {
290
331
  box.append(tblock);
291
332
  state.termBody = tbody;
292
333
  renderTerms();
293
- if (state.termTarget) {
294
- // The view rebuilds this node; keep the live pane ticking without a new poll.
295
- paintTerm();
296
- if (!state.termTimer) startTerm(state.termTarget);
297
- }
298
334
  }
335
+ }
299
336
 
337
+ function renderRoomControls(box) {
338
+ let updateSshHint;
300
339
  // The SSH leg: this device's own key dials the gate. In the Herdr phone app, add a
301
340
  // machine with this host/port and the key shown once at pair time.
302
341
  if (state.deviceSecret && state.deviceId) {
303
342
  const details = document.createElement("details");
304
343
  details.className = "ssh";
305
- // Fresh from pairing: the section opens itself and STAYS open across the
306
- // re-renders that follow (the view frame rebuilds this node) until the person
307
- // closes it — the key is the one thing they must not miss.
308
- if (state.showSecretOnce) details.open = true;
309
- details.addEventListener("toggle", () => {
310
- if (!details.open) state.showSecretOnce = false;
311
- });
344
+ // Open after pairing; live frames never replace the user's controls.
345
+ details.open = state.showSecretOnce === true;
312
346
  const summary = document.createElement("summary");
313
347
  summary.textContent = "SSH for the Herdr app";
314
348
  const pre = document.createElement("pre");
@@ -317,33 +351,41 @@ function renderRoom() {
317
351
  // person typed to reach this page. The cloud advertises the SSH hostname it
318
352
  // wants phones to use (bridge / AAAA name); only without one do we fall back
319
353
  // to this page's host.
320
- const port = state.sshPort ?? 2222;
321
- const sshHost = state.sshHost || host;
322
- pre.textContent = `ssh -p ${port} ${state.deviceId}@${sshHost}`;
323
- details.append(summary, pre);
324
-
325
- // The device key lives in this browser's localStorage (the cloud returns it
326
- // once and keeps only a hash). It IS the SSH password — show it, on demand.
327
- // `keyShown` lives in state so the reveal survives the room re-renders that
328
- // rebuild this whole node whenever a frame arrives.
354
+ const { deviceId, deviceSecret, roomId, token } = state;
355
+ const base = cloudBase();
356
+ let selected = deviceId;
357
+ const allowed = new Set([deviceId]);
358
+ const chooser = document.createElement("label");
359
+ chooser.textContent = "SSH username ";
360
+ const picker = document.createElement("select");
361
+ picker.className = "ssh-user-select";
362
+ const option = (id, label) => {
363
+ const item = document.createElement("option");
364
+ item.value = id;
365
+ item.textContent = label;
366
+ return item;
367
+ };
368
+ picker.append(option(deviceId, `${deviceId} (this browser)`));
369
+ picker.value = deviceId;
370
+ picker.disabled = true;
371
+ chooser.append(picker);
372
+ details.append(summary, chooser, pre);
373
+
374
+ // The device secret is the SSH password. Reveal only on request and only
375
+ // for the device that owns this panel.
329
376
  const keyRow = document.createElement("div");
330
377
  keyRow.className = "keyrow";
331
- if (state.keyShown && state.deviceSecret) {
378
+ const reveal = document.createElement("button");
379
+ reveal.type = "button";
380
+ reveal.className = "link";
381
+ reveal.textContent = "Show this device's key";
382
+ reveal.addEventListener("click", () => {
332
383
  const keyEl = document.createElement("pre");
333
- keyEl.textContent = state.deviceSecret;
384
+ keyEl.textContent = deviceSecret;
334
385
  keyEl.setAttribute("aria-label", "device key");
335
- keyRow.append(keyEl);
336
- } else {
337
- const reveal = document.createElement("button");
338
- reveal.type = "button";
339
- reveal.className = "link";
340
- reveal.textContent = "Show this device's key";
341
- reveal.addEventListener("click", () => {
342
- state.keyShown = true;
343
- renderRoom();
344
- });
345
- keyRow.append(reveal);
346
- }
386
+ keyRow.replaceChildren(keyEl);
387
+ });
388
+ keyRow.append(reveal);
347
389
  details.append(keyRow);
348
390
 
349
391
  // Registered SSH PUBLIC keys: the machine that runs `hc machine add` can then log
@@ -373,11 +415,25 @@ function renderRoom() {
373
415
  keysBlock.append(addRow);
374
416
  const cfgHint = document.createElement("p");
375
417
  cfgHint.className = "muted small";
376
- 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)`;
418
+ updateSshHint = () => {
419
+ const port = state.sshPort ?? 2222;
420
+ const sshHost = state.sshHost || host;
421
+ const command = `ssh -p ${port} ${selected}@${sshHost}`;
422
+ if (pre.textContent === command) return;
423
+ pre.textContent = command;
424
+ cfgHint.textContent = `Herdr Mobile: SSH username ${selected}, port ${port}. Register the public key shown by the phone for this username.`;
425
+ };
377
426
  keysBlock.append(cfgHint);
378
427
  details.append(keysBlock);
379
428
 
380
- const renderKeys = (keys) => {
429
+ const status = document.createElement("p");
430
+ status.className = "muted small";
431
+ status.setAttribute("role", "status");
432
+ keysBlock.append(status);
433
+ const keyAuth = (id) => id === deviceId ? { "x-herdgate-secret": deviceSecret } : { authorization: `Bearer ${token}` };
434
+ let keyRequest = 0;
435
+
436
+ const renderKeys = (keys, owner) => {
381
437
  keyList.replaceChildren();
382
438
  for (const k of keys) {
383
439
  const row = document.createElement("div");
@@ -390,12 +446,20 @@ function renderRoom() {
390
446
  rm.className = "link";
391
447
  rm.textContent = "remove";
392
448
  rm.addEventListener("click", async () => {
393
- await fetch(`${cloudBase()}/v1/device/sshkey`, {
394
- method: "DELETE",
395
- headers: { "content-type": "application/json" },
396
- body: JSON.stringify({ device: state.deviceId, deviceSecret: state.deviceSecret, b64: k.b64 }),
397
- });
398
- loadKeys();
449
+ if (selected !== owner) return;
450
+ try {
451
+ const response = await fetch(`${base}/v1/device/sshkey`, {
452
+ method: "DELETE",
453
+ headers: { "content-type": "application/json", ...keyAuth(owner) },
454
+ body: JSON.stringify({ device: owner, b64: k.b64 }),
455
+ });
456
+ if (selected === owner) {
457
+ if (response.ok) void loadKeys();
458
+ else status.textContent = `Could not remove key (HTTP ${response.status}).`;
459
+ }
460
+ } catch {
461
+ if (selected === owner) status.textContent = "Could not reach the gate.";
462
+ }
399
463
  });
400
464
  row.append(rm);
401
465
  keyList.append(row);
@@ -403,39 +467,86 @@ function renderRoom() {
403
467
  if (!keys.length) {
404
468
  const none = document.createElement("p");
405
469
  none.className = "muted small";
406
- none.textContent = "none yet — password login still works";
470
+ none.textContent = "No public key registered for this username.";
407
471
  keyList.append(none);
408
472
  }
409
473
  };
410
474
  const loadKeys = async () => {
475
+ const target = selected;
476
+ const request = ++keyRequest;
411
477
  try {
412
- const r = await fetch(`${cloudBase()}/v1/device/sshkey?device=${encodeURIComponent(state.deviceId)}`, {
413
- method: "GET",
414
- headers: { "content-type": "application/json", "x-herdgate-secret": state.deviceSecret },
415
- });
416
- if (r.ok) renderKeys((await r.json()).keys ?? []);
478
+ const r = await fetch(`${base}/v1/device/sshkey?device=${encodeURIComponent(target)}`, { headers: keyAuth(target) });
479
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
480
+ const { keys = [] } = await r.json();
481
+ if (request === keyRequest) renderKeys(keys, target);
417
482
  } catch {
418
- /* offline: the section just stays as-is */
483
+ if (request === keyRequest) status.textContent = "Could not load public keys.";
419
484
  }
420
485
  };
486
+ const selectUsername = (id) => {
487
+ if (!allowed.has(id) || id === selected) return;
488
+ selected = id;
489
+ keyRow.hidden = id !== deviceId;
490
+ // Require a fresh paste when switching recipients to avoid granting access to the wrong device.
491
+ addInput.value = "";
492
+ status.textContent = "";
493
+ keyList.replaceChildren();
494
+ updateSshHint();
495
+ void loadKeys();
496
+ };
497
+ picker.addEventListener("change", () => selectUsername(picker.value));
498
+ let pickerRequest = 0;
499
+ const loadUsernames = async () => {
500
+ if (!token || !roomId) return;
501
+ const request = ++pickerRequest;
502
+ try {
503
+ const r = await fetch(`${base}/v1/devices?room=${encodeURIComponent(roomId)}`, { headers: { authorization: `Bearer ${token}` } });
504
+ if (!r.ok) return;
505
+ const { devices = [] } = await r.json();
506
+ if (request !== pickerRequest) return;
507
+ allowed.clear();
508
+ allowed.add(deviceId);
509
+ const options = [option(deviceId, `${deviceId} (this browser)`)];
510
+ for (const d of devices) {
511
+ if (allowed.has(d.id)) continue;
512
+ allowed.add(d.id);
513
+ options.push(option(d.id, `${d.name} · ${d.scope} · ${d.id}`));
514
+ }
515
+ if (!allowed.has(selected)) selectUsername(deviceId);
516
+ picker.replaceChildren(...options);
517
+ picker.value = selected;
518
+ picker.disabled = options.length === 1;
519
+ } catch { /* existing pairing still works */ }
520
+ };
521
+ details.addEventListener("toggle", () => { if (details.open) void loadUsernames(); });
421
522
  addBtn.addEventListener("click", async () => {
422
523
  const pubkey = addInput.value.trim();
423
- if (!pubkey) return;
424
- const r = await fetch(`${cloudBase()}/v1/device/sshkey`, {
425
- method: "POST",
426
- headers: { "content-type": "application/json" },
427
- body: JSON.stringify({ device: state.deviceId, deviceSecret: state.deviceSecret, pubkey }),
428
- });
429
- if (!r.ok) {
430
- addInput.value = "";
431
- addInput.placeholder = await r.json().then((b) => b.error ?? "rejected").catch(() => "rejected");
432
- return;
524
+ const target = selected;
525
+ if (!pubkey || !allowed.has(target)) return;
526
+ status.textContent = "";
527
+ try {
528
+ const r = await fetch(`${base}/v1/device/sshkey`, {
529
+ method: "POST",
530
+ headers: { "content-type": "application/json", ...keyAuth(target) },
531
+ body: JSON.stringify({ device: target, pubkey }),
532
+ });
533
+ const result = await r.json().catch(() => ({}));
534
+ if (selected !== target) return;
535
+ if (!r.ok) {
536
+ status.textContent = result.error ?? `Could not add key (HTTP ${r.status}).`;
537
+ return;
538
+ }
539
+ if (addInput.value.trim() === pubkey) addInput.value = "";
540
+ status.textContent = `Key saved for ${target}.`;
541
+ void loadKeys();
542
+ } catch {
543
+ if (selected === target) status.textContent = "Could not reach the gate.";
433
544
  }
434
- addInput.value = "";
435
- loadKeys();
436
545
  });
437
- loadKeys();
546
+ void loadKeys();
547
+ void loadUsernames();
438
548
  details.append(keysBlock);
549
+ box.append(details);
439
550
  }
440
551
 
441
552
  // The owner's roster for this machine: every paired device, its scope, live dot,
@@ -478,19 +589,14 @@ function renderRoom() {
478
589
  rm.textContent = "revoke";
479
590
  rm.addEventListener("click", async () => {
480
591
  if (!confirm(`Revoke ${d.name}? Its key and access die immediately.`)) return;
481
- await fetch(`${cloudBase()}/v1/device/revoke`, {
592
+ const result = await fetch(`${cloudBase()}/v1/device/revoke`, {
482
593
  method: "POST",
483
594
  headers: { "content-type": "application/json", authorization: `Bearer ${state.token}` },
484
595
  body: JSON.stringify({ device: d.id }),
485
596
  });
486
- if (d.id === state.deviceId) {
487
- // This browser just un-paired itself: back to the machine list.
488
- state.deviceId = null;
489
- state.deviceSecret = null;
490
- localStorage.removeItem(DEVICE_KEY);
491
- localStorage.removeItem(DEVICE_SECRET_KEY);
492
- }
493
- loadDevices();
597
+ if (!result.ok) return;
598
+ if (d.id === state.deviceId) dropDevice();
599
+ else loadDevices();
494
600
  });
495
601
  row.append(rm);
496
602
  roster.append(row);
@@ -500,8 +606,9 @@ function renderRoom() {
500
606
  /* offline: the section stays as-is */
501
607
  }
502
608
  };
503
- loadDevices();
609
+ block.addEventListener("toggle", () => { if (block.open) void loadDevices(); });
504
610
  }
611
+ return updateSshHint;
505
612
  }
506
613
 
507
614
  // ---- live terminals (read-only) ---------------------------------------------
@@ -667,11 +774,45 @@ function note(message, kind) {
667
774
  return p;
668
775
  }
669
776
 
670
- // ---- the socket ------------------------------------------------------------
777
+ // ---- the room socket -------------------------------------------------------
778
+
779
+ function disconnect() {
780
+ const ws = state.ws;
781
+ state.ws = null;
782
+ ws?.close();
783
+ e2eReset();
784
+ }
785
+
786
+ function selectRoom(roomId, pair, fresh = false) {
787
+ resetRoomView();
788
+ state.roomId = roomId;
789
+ state.showSecretOnce = fresh;
790
+ if (state.deviceRoom !== roomId || state.deviceId !== pair.id) {
791
+ disconnect();
792
+ state.deviceRoom = roomId;
793
+ state.deviceId = pair.id;
794
+ state.deviceSecret = pair.secret;
795
+ state.retry = 0;
796
+ connect();
797
+ }
798
+ render();
799
+ if (state.hello && state.ws?.readyState === WebSocket.OPEN) askView();
800
+ }
801
+
802
+ function dropDevice() {
803
+ const roomId = state.deviceRoom;
804
+ if (roomId && roomPairs().get(roomId)?.id === state.deviceId) savePair(roomId, null);
805
+ clearLegacyPair();
806
+ disconnect();
807
+ state.deviceRoom = null;
808
+ state.deviceId = "";
809
+ state.deviceSecret = "";
810
+ goMachines();
811
+ connect();
812
+ }
671
813
 
672
814
  function connect() {
673
- if (!state.token) return;
674
- state.closedByUs = false;
815
+ if (!state.token || state.ws) return;
675
816
  let ws;
676
817
  try {
677
818
  ws = new WebSocket(wsUrl());
@@ -685,20 +826,22 @@ function connect() {
685
826
  // A paired device re-attaches with its own key; the account token is the owner path
686
827
  // (first sign-in, pairing, management). A device that knows where it stopped reading
687
828
  // also asks to resume its room's stream.
829
+ if (state.ws !== ws) return;
688
830
  const hello = state.deviceSecret && state.deviceId
689
831
  ? { device: state.deviceId, deviceSecret: state.deviceSecret }
690
- : { accountToken: state.token, ...(state.deviceId ? { device: state.deviceId } : {}) };
691
- const resume = state.deviceSecret && state.deviceId ? loadStream(state.roomId) : null;
832
+ : { accountToken: state.token };
833
+ const resume = loadStream(state.deviceRoom);
692
834
  ws.send(JSON.stringify({
693
835
  v: 1,
694
836
  t: "hello",
695
837
  ...hello,
696
838
  name: deviceName(),
697
- ...(resume ? { resume: { room: state.roomId, gen: resume.gen, seq: resume.seq } } : {}),
839
+ ...(resume ? { resume: { room: state.deviceRoom, gen: resume.gen, seq: resume.seq } } : {}),
698
840
  }));
699
841
  });
700
842
 
701
843
  ws.addEventListener("message", (event) => {
844
+ if (state.ws !== ws) return;
702
845
  let m;
703
846
  try {
704
847
  m = JSON.parse(event.data);
@@ -709,12 +852,14 @@ function connect() {
709
852
  });
710
853
 
711
854
  ws.addEventListener("close", (event) => {
855
+ if (state.ws !== ws) return;
712
856
  state.ws = null;
713
- state.hello = null;
714
857
  e2eReset();
715
- if (state.closedByUs) return;
716
- if (event.code === 4001) {
717
- // The cloud refused the token: do not hammer it, send the person back to sign-in.
858
+ if (event.code === 4001 && ["unknown device credentials", "revoked"].includes(event.reason)) {
859
+ dropDevice();
860
+ return;
861
+ }
862
+ if (event.code === 4001 && event.reason === "unknown account token") {
718
863
  setStatus("signed out", "bad");
719
864
  forgetToken();
720
865
  return;
@@ -731,7 +876,7 @@ function connect() {
731
876
  async function onMessage(m, ws) {
732
877
  // Track the room stream so the next reconnect resumes from here.
733
878
  if (typeof m.seq === "number" && (m.t === "frame" || m.t === "presence")) {
734
- const rid = m.t === "presence" ? m.roomId : state.roomId;
879
+ const rid = m.t === "presence" ? m.roomId : state.deviceRoom;
735
880
  const cur = loadStream(rid);
736
881
  if (cur && m.seq > cur.seq) saveStream(rid, cur.gen, m.seq);
737
882
  }
@@ -740,12 +885,15 @@ async function onMessage(m, ws) {
740
885
  state.retry = 0;
741
886
  state.hello = { agents: Array.isArray(m.agents) ? m.agents : [] };
742
887
  if (m.device?.id) {
743
- state.deviceId = m.device.id;
744
- localStorage.setItem(DEVICE_KEY, m.device.id);
745
- if (!state.roomId) state.roomId = m.device.roomId;
888
+ const { roomId, id, scope } = m.device;
889
+ if (!state.deviceRoom) {
890
+ // Migrate the legacy single pairing only after the gate identifies its room.
891
+ savePair(roomId, { id, secret: state.deviceSecret, scope });
892
+ clearLegacyPair();
893
+ state.roomId = roomId;
894
+ }
895
+ state.deviceRoom = roomId;
746
896
  }
747
- // Keep the chosen room only while it is still visible to this account/device.
748
- if (state.roomId && !state.hello.agents.some((r) => r.roomId === state.roomId)) state.roomId = null;
749
897
  // Resume outcome: the stream header carries the cloud's position; when the
750
898
  // replay had a hole (too long away), askView() below re-fetches the state.
751
899
  const rid = m.device?.roomId ?? null;
@@ -785,12 +933,14 @@ async function onMessage(m, ws) {
785
933
  try {
786
934
  inner = await e2e.ch.recv(payload);
787
935
  } catch {
788
- // Wrong key or tampered frame: start over rather than show nonsense.
789
- e2eReset();
790
- void e2eBegin();
936
+ if (state.ws === ws) {
937
+ // Wrong key or tampered frame: start over rather than show nonsense.
938
+ e2eReset();
939
+ void e2eBegin();
940
+ }
791
941
  return;
792
942
  }
793
- applyPayload(inner);
943
+ if (state.ws === ws) applyPayload(inner);
794
944
  return;
795
945
  }
796
946
  if (payload && typeof payload === "object" && payload.code === "e2e" && e2e.ch) {
@@ -810,27 +960,6 @@ async function onMessage(m, ws) {
810
960
  applyPayload(payload);
811
961
  return;
812
962
  }
813
- case "pair.granted": {
814
- state.deviceId = m.device?.id ?? state.deviceId;
815
- if (state.deviceId) localStorage.setItem(DEVICE_KEY, state.deviceId);
816
- // Shown once and kept only on this device: it is this phone's SSH key on the gate.
817
- if (typeof m.deviceSecret === "string" && m.deviceSecret) {
818
- state.deviceSecret = m.deviceSecret;
819
- localStorage.setItem(DEVICE_SECRET_KEY, m.deviceSecret);
820
- state.showSecretOnce = true;
821
- }
822
- state.roomId = m.device?.roomId ?? state.roomId;
823
- closePair();
824
- render();
825
- void e2eBegin();
826
- askView();
827
- void subscribePush();
828
- return;
829
- }
830
- case "pair.denied": {
831
- showError("pair-error", m.reason ? `Denied: ${m.reason}` : "Denied");
832
- return;
833
- }
834
963
  case "presence": {
835
964
  const room = (state.hello?.agents ?? []).find((r) => r.roomId === m.roomId);
836
965
  if (room) room.online = m.online === true;
@@ -863,7 +992,10 @@ function retryLater() {
863
992
  async function askView() {
864
993
  if (state.ws?.readyState !== WebSocket.OPEN || !state.roomId) return;
865
994
  if (e2e.ch?.ready() && e2e.ready) {
866
- send({ t: "frame", payload: await e2e.ch.send({ op: "view" }) });
995
+ const ws = state.ws;
996
+ const ch = e2e.ch;
997
+ const payload = await ch.send({ op: "view" });
998
+ if (state.ws === ws && e2e.ch === ch) send({ t: "frame", payload });
867
999
  return;
868
1000
  }
869
1001
  void e2eBegin(); // establish in the background; the ack path asks again over it
@@ -890,33 +1022,36 @@ function applyPayload(payload) {
890
1022
  // The host refused or could not answer: an op we may not use, or its Herdr is down.
891
1023
  state.viewError = payload.message ?? payload.code ?? "the host refused";
892
1024
  state.view = null;
1025
+ } else {
1026
+ return;
893
1027
  }
894
- if (state.roomId) renderRoom();
1028
+ renderRoom();
895
1029
  }
896
1030
 
897
1031
  // ---- push wake ---------------------------------------------------------------
898
1032
 
899
1033
  /** Subscribe this device to silent wake pushes; ask for permission only once paired. */
900
1034
  async function subscribePush() {
901
- if (!(state.deviceSecret && state.deviceId)) return; // paired devices only
1035
+ const { deviceId, deviceSecret } = state;
1036
+ const base = cloudBase();
1037
+ if (!(deviceSecret && deviceId)) return; // paired devices only
902
1038
  if (!("serviceWorker" in navigator) || !("PushManager" in window)) return;
903
1039
  try {
904
1040
  const reg = await navigator.serviceWorker.ready;
905
1041
  let sub = await reg.pushManager.getSubscription();
906
1042
  if (!sub) {
907
- const keyRes = await fetch(`${cloudBase()}/v1/push/key`);
1043
+ const keyRes = await fetch(`${base}/v1/push/key`);
908
1044
  if (!keyRes.ok) return; // push disabled on this cloud
909
1045
  const { publicKey } = await keyRes.json();
910
1046
  const raw = Uint8Array.from(atob(publicKey.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
911
1047
  sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: raw });
912
1048
  }
913
1049
  const endpoint = sub.endpoint;
914
- if (state.pushEndpoint === endpoint) return;
915
- state.pushEndpoint = endpoint;
916
- await fetch(`${cloudBase()}/v1/device/push`, {
1050
+ if (cloudBase() !== base || state.deviceId !== deviceId) return;
1051
+ await fetch(`${base}/v1/device/push`, {
917
1052
  method: "POST",
918
1053
  headers: { "content-type": "application/json" },
919
- body: JSON.stringify({ device: state.deviceId, deviceSecret: state.deviceSecret, endpoint }),
1054
+ body: JSON.stringify({ device: deviceId, deviceSecret, endpoint }),
920
1055
  });
921
1056
  } catch {
922
1057
  /* permission denied or push unavailable: the gate still works without it */
@@ -926,19 +1061,21 @@ async function subscribePush() {
926
1061
  /** The host answered our handshake: finish it, pin its fingerprint (TOFU). */
927
1062
  async function onE2eReply(payload) {
928
1063
  const ch = e2e.ch;
929
- if (!ch) return;
1064
+ const roomId = state.deviceRoom;
1065
+ if (!ch || !roomId) return;
930
1066
  try {
931
1067
  const finish = await ch.acceptReply(payload);
1068
+ if (e2e.ch !== ch) return;
932
1069
  send({ t: "frame", payload: { op: "e2e.finish", c: finish.c } });
933
1070
  } catch {
934
- e2eReset();
1071
+ if (e2e.ch === ch) e2eReset();
935
1072
  return;
936
1073
  }
937
1074
  const fp = ch.hostFingerprint;
938
- if (fp && state.roomId) {
939
- const stored = localStorage.getItem(e2eFpKey(state.roomId));
940
- if (!stored) localStorage.setItem(e2eFpKey(state.roomId), fp);
941
- renderRoom();
1075
+ if (fp) {
1076
+ const stored = localStorage.getItem(e2eFpKey(roomId));
1077
+ if (!stored) localStorage.setItem(e2eFpKey(roomId), fp);
1078
+ if (state.roomId === roomId) renderRoom();
942
1079
  }
943
1080
  // The channel is up: ask for the view over it.
944
1081
  askView();
@@ -965,30 +1102,79 @@ function openPair(roomId) {
965
1102
  state.pairRoom = roomId;
966
1103
  show("pair", true);
967
1104
  show("rooms", false);
1105
+ show("room", false);
968
1106
  showError("pair-error", null);
969
1107
  const name = $("pair-name");
970
1108
  if (!name.value) name.value = deviceName();
971
1109
  name.focus();
972
1110
  }
973
1111
 
1112
+ function pairStatus(message = "") {
1113
+ text("pair-status", message);
1114
+ show("pair-status", Boolean(message));
1115
+ }
1116
+
974
1117
  function closePair() {
1118
+ state.pairSocket?.cancel();
1119
+ pairStatus();
1120
+ state.pairRoom = null;
975
1121
  show("pair", false);
976
1122
  showError("pair-error", null);
977
1123
  }
978
1124
 
979
1125
  $("pair-form").addEventListener("submit", (event) => {
980
1126
  event.preventDefault();
1127
+ if (state.pairSocket || !state.pairRoom || !state.token) return;
981
1128
  showError("pair-error", null);
1129
+ const { pairRoom: roomId, token: accountToken } = state;
982
1130
  const name = $("pair-name").value.trim() || deviceName();
983
1131
  const scope = $("pair-scope").value === "act" ? "act" : "read";
984
- const ok = send({ t: "pair.begin", roomId: state.pairRoom, name, scope });
985
- if (!ok) return showError("pair-error", "not connected to the cloud");
986
- // `act` waits for a human on the host; read is immediate.
987
- $("pair-form").querySelector("button").disabled = true;
988
- setTimeout(() => {
989
- const b = $("pair-form").querySelector("button");
990
- if (b) b.disabled = false;
991
- }, 3_000);
1132
+ // Pairing is an owner operation. Do not promote or replace the room socket.
1133
+ let ws;
1134
+ try { ws = new WebSocket(wsUrl()); }
1135
+ catch { return showError("pair-error", "Could not connect to the gate"); }
1136
+ const button = $("pair-form").querySelector("button");
1137
+ button.disabled = true;
1138
+ pairStatus("Connecting to the gate…");
1139
+ let requested = false;
1140
+ const operation = { cancel: () => finish() };
1141
+ state.pairSocket = operation;
1142
+ const timeout = setTimeout(() => finish("Pairing timed out"), 70_000);
1143
+ function finish(error) {
1144
+ if (state.pairSocket !== operation) return;
1145
+ state.pairSocket = null;
1146
+ button.disabled = false;
1147
+ pairStatus();
1148
+ clearTimeout(timeout);
1149
+ ws.close();
1150
+ if (error) showError("pair-error", error);
1151
+ }
1152
+ const sendPair = (message) => ws.send(JSON.stringify({ v: 1, ...message }));
1153
+ ws.addEventListener("open", () => {
1154
+ if (state.pairSocket === operation) sendPair({ t: "hello", accountToken, name: deviceName() });
1155
+ });
1156
+ ws.addEventListener("close", (event) => finish(event.reason || "Pairing connection closed"));
1157
+ ws.addEventListener("message", (event) => {
1158
+ if (state.pairSocket !== operation) return;
1159
+ let m;
1160
+ try { m = JSON.parse(event.data); } catch { return; }
1161
+ if (m?.t === "hello" && !requested) {
1162
+ requested = true;
1163
+ pairStatus(scope === "act" ? "Waiting for the host to approve control…" : "Pairing…");
1164
+ sendPair({ t: "pair.begin", roomId, name, scope });
1165
+ } else if (m?.t === "pair.denied" || m?.t === "error") {
1166
+ finish(m.reason || m.message || "Pairing refused");
1167
+ } else if (m?.t === "pair.granted" && requested) {
1168
+ if (m.device?.roomId !== roomId || m.device.scope !== scope || typeof m.device.id !== "string" || typeof m.deviceSecret !== "string") {
1169
+ return finish("Invalid pairing reply");
1170
+ }
1171
+ const pairing = { id: m.device.id, secret: m.deviceSecret, scope };
1172
+ savePair(roomId, pairing);
1173
+ closePair();
1174
+ selectRoom(roomId, pairing, true);
1175
+ void subscribePush();
1176
+ }
1177
+ });
992
1178
  });
993
1179
 
994
1180
  // ---- sign-in, settings -----------------------------------------------------
@@ -1023,8 +1209,7 @@ $("addmachine").addEventListener("submit", async (event) => {
1023
1209
  $("addmachine-code").value = "";
1024
1210
  noteEl.textContent = "approved — the machine appears when its publisher connects";
1025
1211
  // A fresh hello lists the new room (rooms come from hello).
1026
- state.closedByUs = true;
1027
- state.ws?.close();
1212
+ disconnect();
1028
1213
  connect();
1029
1214
  } catch (e) {
1030
1215
  noteEl.className = "error small";
@@ -1040,17 +1225,11 @@ $("menu").addEventListener("click", () => {
1040
1225
  $("settings-form").addEventListener("submit", () => {
1041
1226
  const value = $("cloud").value.trim().replace(/\/$/, "");
1042
1227
  if (value !== state.cloud) {
1228
+ // Never forward credentials from one cloud to another.
1229
+ forgetToken();
1043
1230
  state.cloud = value;
1044
1231
  if (value) localStorage.setItem(CLOUD_KEY, value);
1045
1232
  else localStorage.removeItem(CLOUD_KEY);
1046
- // A different cloud is a different account: reconnect from scratch.
1047
- state.hello = null;
1048
- state.roomId = null;
1049
- if (state.ws) {
1050
- state.closedByUs = true;
1051
- state.ws.close();
1052
- }
1053
- connect();
1054
1233
  }
1055
1234
  });
1056
1235
 
@@ -1059,16 +1238,22 @@ $("signout").addEventListener("click", () => forgetToken());
1059
1238
  /** Back to the machine list — from the pair screen or the room screen.
1060
1239
  * Delegated at the document level so it works no matter what rebuilt the DOM
1061
1240
  * (and with a generous tap target; see .backbtn in the CSS). */
1062
- const goMachines = () => {
1063
- state.roomId = null;
1241
+ function resetRoomView() {
1242
+ stopTerm(false);
1243
+ state.terms = null;
1244
+ state.termBody = null;
1245
+ state.termPre = null;
1064
1246
  state.view = null;
1065
1247
  state.viewError = null;
1066
- state.keyShown = false;
1248
+ state.roomUi = null;
1249
+ $("view").replaceChildren();
1250
+ }
1251
+
1252
+ const goMachines = () => {
1253
+ resetRoomView();
1254
+ state.roomId = null;
1067
1255
  closePair();
1068
- show("pair", false);
1069
- show("room", false);
1070
1256
  render();
1071
- if (state.hello) renderRooms();
1072
1257
  };
1073
1258
  document.addEventListener("click", (event) => {
1074
1259
  const target = event.target instanceof Element ? event.target.closest("#back, #pair-back") : null;
@@ -1079,17 +1264,14 @@ function forgetToken() {
1079
1264
  state.token = "";
1080
1265
  state.deviceId = "";
1081
1266
  state.deviceSecret = "";
1082
- localStorage.removeItem(DEVICE_SECRET_KEY);
1083
- state.roomId = null;
1267
+ state.deviceRoom = null;
1084
1268
  state.hello = null;
1085
1269
  localStorage.removeItem(TOKEN_KEY);
1086
- localStorage.removeItem(DEVICE_KEY);
1087
- if (state.ws) {
1088
- state.closedByUs = true;
1089
- state.ws.close();
1090
- }
1270
+ localStorage.removeItem(PAIRS_KEY);
1271
+ clearLegacyPair();
1272
+ disconnect();
1273
+ goMachines();
1091
1274
  $("settings").close();
1092
- render();
1093
1275
  }
1094
1276
 
1095
1277
  // ---- boot ------------------------------------------------------------------