@bom0792/herdgate 0.9.35 → 0.9.37

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
@@ -37,7 +37,7 @@ function clearLegacyPair() {
37
37
  localStorage.removeItem(DEVICE_SECRET_KEY);
38
38
  }
39
39
 
40
- import { DeviceChannel, generateKeyPair } from "/e2e.js";
40
+ import { DeviceChannel, generateKeyPair, needsRekey } from "/e2e.js";
41
41
 
42
42
  // E2E payloads: this device's Noise_XX identity (kept locally, never sent to the cloud
43
43
  // in the clear) and the host fingerprints it has pinned (TOFU per room).
@@ -104,6 +104,19 @@ async function e2eBegin() {
104
104
  }
105
105
  }
106
106
 
107
+ /** Rotate the Noise session when a lifetime bound is hit (Paseo: handshake
108
+ * lifetime). A fresh handshake swaps both directional keys and resets the
109
+ * counters, fencing forward secrecy to the slice since the last rotation.
110
+ * Runs after sends; the receive path checks on every inbound ciphertext. */
111
+ function maybeRotateE2e() {
112
+ if (!e2e.ready || e2e.initing || e2e.keyChanged) return;
113
+ const ch = e2e.ch;
114
+ if (!ch?.ready() || !needsRekey(ch)) return;
115
+ console.info("e2e: rotating session (lifetime bound)");
116
+ e2eReset();
117
+ void e2eBegin();
118
+ }
119
+
107
120
  // Resume bookkeeping: where this device stopped reading each room's stream, so a
108
121
  // reconnect can replay what it missed. Keyed per room; cleared when the cloud
109
122
  // says the stream's generation moved (gateway restart) or the state went stale.
@@ -146,6 +159,7 @@ const state = {
146
159
  termBody: null,
147
160
  termPre: null,
148
161
  retry: 0,
162
+ worker: { health: null, jobs: new Map(), error: null },
149
163
  };
150
164
 
151
165
  /** The cloud base: an explicit setting, else this page's origin (same-origin deployment). */
@@ -245,10 +259,12 @@ function renderRoom() {
245
259
  if (!state.roomUi) {
246
260
  const summary = document.createElement("div");
247
261
  const live = document.createElement("div");
262
+ const worker = document.createElement("div");
248
263
  const controls = document.createElement("div");
249
- $("view").replaceChildren(summary, live, controls);
264
+ $("view").replaceChildren(summary, live, worker, controls);
250
265
  const updateSshHint = renderRoomControls(controls);
251
- state.roomUi = { summary, live, updateSshHint };
266
+ const updateWorker = renderWorkerBox(worker);
267
+ state.roomUi = { summary, live, worker, controls, updateSshHint, updateWorker };
252
268
  }
253
269
  const ui = state.roomUi;
254
270
  const online = Boolean(room?.online);
@@ -259,8 +275,9 @@ function renderRoom() {
259
275
  ui.summary.replaceChildren();
260
276
  renderHostView(ui.summary, room);
261
277
  }
262
- const { live, updateSshHint } = ui;
278
+ const { live, updateSshHint, updateWorker } = ui;
263
279
  renderLiveTerminals(live, online);
280
+ updateWorker?.(online);
264
281
  updateSshHint?.();
265
282
  }
266
283
 
@@ -340,6 +357,126 @@ function renderLiveTerminals(box, online) {
340
357
  }
341
358
  }
342
359
 
360
+ // ---- Pi worker panel (experimental) -----------------------------------------
361
+ // Submit/health/status against the host's opt-in worker queue (HERDGATE_PI_WORKER=1)
362
+ // plus per-request receipt watches: the settle report pushes back, no polling loop.
363
+
364
+ const WORKER_ERROR_CODES = new Set([
365
+ "pi_worker_disabled", "requires-act", "bad-prompt", "bad-workspace", "queue-full", "worker-queue",
366
+ "receipt.watch", "pi_receipts_disabled", "pi_receipt_body_disabled",
367
+ ]);
368
+
369
+ function renderWorkerBox(box) {
370
+ const details = document.createElement("details");
371
+ details.className = "worker";
372
+ const summary = document.createElement("summary");
373
+ summary.textContent = "Pi worker (experimental)";
374
+ const health = document.createElement("p");
375
+ health.className = "muted small";
376
+ const refresh = document.createElement("button");
377
+ refresh.type = "button";
378
+ refresh.className = "link";
379
+ refresh.textContent = "refresh";
380
+ const form = document.createElement("form");
381
+ form.autocomplete = "off";
382
+ const promptLabel = document.createElement("label");
383
+ promptLabel.textContent = "Prompt for a fresh worker run (one job, one session)";
384
+ const prompt = document.createElement("textarea");
385
+ prompt.rows = 3;
386
+ prompt.maxLength = 16384;
387
+ prompt.required = true;
388
+ prompt.placeholder = "e.g. summarize today's commits in 5 bullets";
389
+ const wsLabel = document.createElement("label");
390
+ wsLabel.textContent = "Workspace (optional name from the host allowlist)";
391
+ const workspace = document.createElement("input");
392
+ workspace.type = "text";
393
+ workspace.maxLength = 64;
394
+ workspace.placeholder = "default";
395
+ workspace.pattern = "[a-z0-9][a-z0-9-]{0,63}";
396
+ const submit = document.createElement("button");
397
+ submit.type = "submit";
398
+ submit.textContent = "Submit job";
399
+ const formError = document.createElement("p");
400
+ formError.className = "error small";
401
+ formError.hidden = true;
402
+ form.append(promptLabel, prompt, wsLabel, workspace, submit, formError);
403
+ const jobs = document.createElement("ul");
404
+ jobs.className = "list";
405
+ details.append(summary, health, refresh, form, formError, jobs);
406
+ box.append(details);
407
+
408
+ const askHealth = () => sendPayload({ op: "worker.health" });
409
+ refresh.addEventListener("click", askHealth);
410
+ details.addEventListener("toggle", () => { if (details.open) askHealth(); });
411
+ form.addEventListener("submit", (event) => {
412
+ event.preventDefault();
413
+ formError.hidden = true;
414
+ const text = prompt.value.trim();
415
+ if (!text) return;
416
+ sendPayload({ op: "worker.submit", prompt: text, ...(workspace.value.trim() ? { workspace: workspace.value.trim() } : {}) });
417
+ prompt.value = "";
418
+ });
419
+
420
+ const ui = { details, health, jobs, formError, asked: false };
421
+ const update = (online) => {
422
+ const w = state.worker;
423
+ form.hidden = !online;
424
+ if (online && details.open && !ui.asked) { ui.asked = true; askHealth(); }
425
+ const h = w.health;
426
+ if (!online) {
427
+ health.textContent = "host offline";
428
+ } else if (!h) {
429
+ health.textContent = h === null ? "asking the host…" : "";
430
+ } else if (!h.enabled) {
431
+ health.textContent = "worker queue disabled on this host (HERDGATE_PI_WORKER)";
432
+ } else {
433
+ const beat = h.heartbeat ? ` · heartbeat ${h.heartbeat.source} ${h.heartbeat.ageSeconds}s ago` : " · no heartbeat";
434
+ health.textContent = `queue ${h.queued ?? "?"} waiting, ${h.running ?? "?"} running${beat}`;
435
+ }
436
+ formError.hidden = !w.error;
437
+ formError.textContent = w.error ?? "";
438
+ jobs.replaceChildren();
439
+ for (const job of [...w.jobs.values()].slice(-12).reverse()) {
440
+ const row = document.createElement("li");
441
+ row.className = "row";
442
+ const head = document.createElement("span");
443
+ head.textContent = `${job.id.slice(0, 8)} · ${job.status}${job.reason ? ` (${job.reason})` : ""}${job.duplicate ? " · duplicate" : ""}`;
444
+ row.append(head);
445
+ if (job.status === "replied" && job.hasBody) {
446
+ const view = document.createElement("button");
447
+ view.type = "button";
448
+ view.className = "link";
449
+ view.textContent = job.body === undefined ? "view report" : "hide report";
450
+ view.addEventListener("click", () => {
451
+ if (job.body === undefined) sendPayload({ op: "receipt.body", id: job.id });
452
+ else job.body = undefined;
453
+ update(online);
454
+ });
455
+ row.append(" ", view);
456
+ if (typeof job.body === "string") {
457
+ const pre = document.createElement("pre");
458
+ pre.textContent = job.body;
459
+ row.append(pre);
460
+ } else if (job.body && typeof job.body === "object") {
461
+ const why = document.createElement("span");
462
+ why.className = "muted small";
463
+ why.textContent = `report not available (${job.body.reason ?? "unavailable"})`;
464
+ row.append(why);
465
+ }
466
+ }
467
+ jobs.append(row);
468
+ }
469
+ };
470
+ return update;
471
+ }
472
+
473
+ function workerJobTouched(id, fields) {
474
+ const job = state.worker.jobs.get(id);
475
+ if (!job) return;
476
+ Object.assign(job, fields);
477
+ state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
478
+ }
479
+
343
480
  function renderRoomControls(box) {
344
481
  let updateSshHint;
345
482
  // The SSH leg: this device's own key dials the gate. In the Herdr phone app, add a
@@ -951,7 +1088,9 @@ async function onMessage(m, ws) {
951
1088
  applyPayload(inner);
952
1089
  } catch {
953
1090
  if (state.ws === ws && e2e.ch === ch) restartEncryptedRoom();
1091
+ return;
954
1092
  }
1093
+ maybeRotateE2e();
955
1094
  return;
956
1095
  }
957
1096
  if (e2e.keyChanged) return;
@@ -1019,6 +1158,7 @@ async function sendPayload(message) {
1019
1158
  } catch {
1020
1159
  if (state.ws === ws && e2e.ch === ch) restartEncryptedRoom();
1021
1160
  }
1161
+ maybeRotateE2e();
1022
1162
  return;
1023
1163
  }
1024
1164
  void e2eBegin();
@@ -1043,8 +1183,39 @@ function applyPayload(payload) {
1043
1183
  paintTerm();
1044
1184
  }
1045
1185
  return;
1186
+ } else if (payload && typeof payload === "object" && payload.op === "worker.health.result") {
1187
+ state.worker.health = payload;
1188
+ state.worker.error = payload.enabled === false ? payload.message ?? "worker queue disabled on this host" : null;
1189
+ state.roomUi?.updateWorker?.(true);
1190
+ return;
1191
+ } else if (payload && typeof payload === "object" && payload.op === "worker.submitted") {
1192
+ state.worker.jobs.set(payload.id, { id: payload.id, status: payload.state, duplicate: payload.duplicate === true, hasBody: false });
1193
+ sendPayload({ op: "receipt.watch", id: payload.id, wantBody: true });
1194
+ state.roomUi?.updateWorker?.(true);
1195
+ return;
1196
+ } else if (payload && typeof payload === "object" && payload.op === "worker.status.result") {
1197
+ workerJobTouched(payload.id, { status: payload.state, ...(payload.reason ? { reason: payload.reason } : {}) });
1198
+ return;
1199
+ } else if (payload && typeof payload === "object" && payload.op === "receipt.watched") {
1200
+ workerJobTouched(payload.id, payload.pending ? { status: "pending" } : { status: payload.status, ...(payload.reason ? { reason: payload.reason } : {}) });
1201
+ return;
1202
+ } else if (payload && typeof payload === "object" && payload.op === "receipt.push") {
1203
+ workerJobTouched(payload.id, { status: payload.status, ...(payload.reason ? { reason: payload.reason } : {}), hasBody: payload.hasBody === true });
1204
+ sendPayload({ op: "receipt.ack", id: payload.id }); // displayed — retire the intent
1205
+ return;
1206
+ } else if (payload && typeof payload === "object" && payload.op === "receipt.body.result") {
1207
+ workerJobTouched(payload.id, payload.text !== undefined
1208
+ ? { body: payload.text }
1209
+ : { body: { reason: payload.reason ?? "unavailable" } });
1210
+ return;
1046
1211
  } else if (payload && typeof payload === "object" && payload.op === "error" && payload.code === "busy") {
1047
1212
  return; // our poll raced the host's 1/s throttle — the next tick catches up
1213
+ } else if (payload && typeof payload === "object" && payload.op === "error" && WORKER_ERROR_CODES.has(payload.code)) {
1214
+ // Scoped to the worker panel: a refused submit/watch must not blank the room view.
1215
+ state.worker.error = payload.message ?? payload.code ?? "the host refused";
1216
+ state.worker.health = null;
1217
+ state.roomUi?.updateWorker?.(true);
1218
+ return;
1048
1219
  } else if (payload && typeof payload === "object" && payload.op === "error") {
1049
1220
  // The host refused or could not answer: an op we may not use, or its Herdr is down.
1050
1221
  state.viewError = payload.message ?? payload.code ?? "the host refused";
package/src/web/e2e.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * herdgate E2E payloads — Noise_XX over the opaque payload channel.
3
3
  *
4
- * The PWA copy of `plugin/server/e2e.mjs` (verbatim; a test asserts the two never
5
- * drift). Everything
4
+ * One canonical implementation, two runtimes: this file is copied verbatim to
5
+ * `src/web/e2e.js` for the PWA (a test asserts the two never drift). Everything
6
6
  * runs on WebCrypto (`globalThis.crypto.subtle` — Node ≥ 20 exposes the same
7
7
  * object globally), so the plugin and the browser execute identical logic.
8
8
  *
@@ -22,6 +22,21 @@ export const NOISE_NAME = "Noise_XX_P256_AESGCM_SHA256";
22
22
  export const KEY_LEN = 32;
23
23
  export const PUB_LEN = 65; // uncompressed P-256 point: 0x04 ‖ X ‖ Y
24
24
 
25
+ /** Session lifetime (Paseo lesson: handshake lifetime). A transport key that lives
26
+ * forever erodes forward secrecy — compromising it exposes the WHOLE session since
27
+ * the handshake. Rotation fences exposure to the slice since the last handshake.
28
+ * Bounds: messages per direction (far under nonce exhaustion at 2^32) or wall time,
29
+ * whichever comes first. The device initiates; the host's `e2e.init` handler swaps
30
+ * the session in place, so rotation is just a fresh handshake. */
31
+ export const REKEY_AFTER_MESSAGES = 2 ** 24;
32
+ export const REKEY_AFTER_MS = 24 * 60 * 60 * 1000;
33
+
34
+ /** True when a READY channel has reached either lifetime bound. */
35
+ export function needsRekey(ch, now = Date.now()) {
36
+ if (!ch?.ready()) return false;
37
+ return ch.usage() >= REKEY_AFTER_MESSAGES || now - ch.handshakeAt >= REKEY_AFTER_MS;
38
+ }
39
+
25
40
  // ---- byte helpers (kept dependency-free; typed arrays only) ----------------
26
41
 
27
42
  export function b64e(u8) {
@@ -189,6 +204,7 @@ export class DeviceChannel {
189
204
  sendCs = null;
190
205
  recvCs = null;
191
206
  hostFingerprint = null;
207
+ handshakeAt = 0; // set when Split() runs — the rotation clock starts at ready
192
208
  constructor(self) {
193
209
  this.#self = self;
194
210
  }
@@ -218,12 +234,17 @@ export class DeviceChannel {
218
234
  const [c1, c2] = await this.#hs.split();
219
235
  this.sendCs = c1; // device → host
220
236
  this.recvCs = c2; // host → device
237
+ this.handshakeAt = Date.now();
221
238
  this.#e = null;
222
239
  return { c: b64e(c) };
223
240
  }
224
241
  ready() {
225
242
  return Boolean(this.sendCs && this.recvCs);
226
243
  }
244
+ /** Messages carried under the current keys (max of both directions). */
245
+ usage() {
246
+ return Math.max(this.sendCs?.n ?? 0, this.recvCs?.n ?? 0);
247
+ }
227
248
  async send(obj) {
228
249
  const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
229
250
  return { op: "e2e", n, c: b64e(ct) };
@@ -241,6 +262,7 @@ export class HostChannel {
241
262
  sendCs = null;
242
263
  recvCs = null;
243
264
  deviceFingerprint = null;
265
+ handshakeAt = 0; // set when Split() runs — the rotation clock starts at ready
244
266
  constructor(self) {
245
267
  this.#self = self;
246
268
  }
@@ -266,11 +288,16 @@ export class HostChannel {
266
288
  const [c1, c2] = await this.#hs.split();
267
289
  this.recvCs = c1; // device → host (c1 encrypts initiator→responder)
268
290
  this.sendCs = c2; // host → device
291
+ this.handshakeAt = Date.now();
269
292
  this.#e = null;
270
293
  }
271
294
  ready() {
272
295
  return Boolean(this.sendCs && this.recvCs);
273
296
  }
297
+ /** Messages carried under the current keys (max of both directions). */
298
+ usage() {
299
+ return Math.max(this.sendCs?.n ?? 0, this.recvCs?.n ?? 0);
300
+ }
274
301
  async send(obj) {
275
302
  const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
276
303
  return { op: "e2e", n, c: b64e(ct) };