@bom0792/herdgate 0.9.36 → 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.
@@ -1,10 +1,12 @@
1
- // Native Herdr terminal controller. Never grants takeover and never interprets a shell command.
1
+ // Native Herdr terminal controller. Never interprets a shell command. --takeover makes the
2
+ // latest viewer own the stream: Herdr allows one controller per terminal, and this way a
3
+ // reconnect or a second viewer (phone, desktop) replaces the old one instead of failing.
2
4
  import { spawn } from "node:child_process";
3
5
 
4
6
  const maxLine = 1024 * 1024;
5
7
 
6
8
  export async function openTerminal(bin, id, cols, rows) {
7
- const child = spawn(bin, ["terminal", "session", "control", id, "--cols", String(cols), "--rows", String(rows)], {
9
+ const child = spawn(bin, ["terminal", "session", "control", id, "--takeover", "--cols", String(cols), "--rows", String(rows)], {
8
10
  stdio: ["pipe", "pipe", "ignore"], windowsHide: true, shell: false,
9
11
  });
10
12
  child.on("error", () => child.stdout.destroy());
@@ -25,6 +25,10 @@ export function scopeFor(cwd) {
25
25
  // journal scope. Reads already scan every scope, so this only converges writes.
26
26
  let real = cwd;
27
27
  try { real = realpathSync(cwd); } catch { /* deleted cwd: keep the raw path */ }
28
+ // Windows realpath preserves the caller's letter casing (D:\Bom vs d:\bom are
29
+ // the same dir on NTFS), so converge scopes case-insensitively there — verified
30
+ // live against the installed release on Windows (docs/herdr-skills validation).
31
+ if (process.platform === 'win32') real = real.toLowerCase();
28
32
  return createHash('sha256').update(real).digest('hex').slice(0, 16);
29
33
  }
30
34
 
@@ -6,6 +6,8 @@ export interface JobRecord {
6
6
  prompt: string;
7
7
  ts: number;
8
8
  state: JobState;
9
+ /** Routing key resolved against the host's workspaces.json allowlist. */
10
+ workspace?: string;
9
11
  sessionId?: string;
10
12
  reason?: string;
11
13
  requestEntryId?: string;
@@ -30,6 +32,11 @@ export const MIN_PI_VERSION: string;
30
32
  export function versionAtLeast(version: string, min?: string): boolean;
31
33
  export function workerBase(env?: Record<string, string | undefined>): string;
32
34
  export function jobsFile(base: string): string;
35
+ /** Routing key a device may reference; paths never cross the wire. */
36
+ export const WORKSPACE_NAME: RegExp;
37
+ export function workspacesFile(base: string): string;
38
+ /** Owner-curated name -> absolute workspace path. Missing/corrupt -> empty map. */
39
+ export function readWorkspaces(base: string): Map<string, string>;
33
40
  export function validJob(job: unknown): JobRecord | null;
34
41
  export function readJobs(file: string): Map<string, JobRecord>;
35
42
  export function appendJob(file: string, job: JobRecord): void;
@@ -5,13 +5,16 @@
5
5
  import { createHash } from 'node:crypto';
6
6
  import { homedir } from 'node:os';
7
7
  import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
8
- import { dirname, join } from 'node:path';
8
+ import { dirname, isAbsolute, join } from 'node:path';
9
9
 
10
10
  export const JOB_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
11
11
  export const MAX_PROMPT = 16 * 1024; // admission bound for one prompt
12
12
  export const MAX_PENDING = 100; // queued + running jobs admitted at once
13
13
  export const JOB_STATES = new Set(['queued', 'running', 'replied', 'failed', 'canceled', 'unknown']);
14
+ /** Routing key a device may reference — resolved against the host's allowlist. */
15
+ export const WORKSPACE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
14
16
  const JOBS = 'jobs.jsonl';
17
+ const WORKSPACES = 'workspaces.json';
15
18
 
16
19
  /** Oldest Pi release the experiments are verified against. Newer Pi releases run
17
20
  * without code changes; only a Pi older than this is refused. */
@@ -43,6 +46,30 @@ export function jobsFile(base) {
43
46
  return join(base, JOBS);
44
47
  }
45
48
 
49
+ export function workspacesFile(base) {
50
+ return join(base, WORKSPACES);
51
+ }
52
+
53
+ /** Owner-curated routing table: name -> absolute workspace path, 0600, optional.
54
+ * A device references a name; the worker resolves it here. No raw paths cross
55
+ * the wire, and a name missing from this file fails closed (never runs). */
56
+ export function readWorkspaces(base) {
57
+ let raw;
58
+ try { raw = readFileSync(workspacesFile(base), 'utf8'); }
59
+ catch (error) { if (error.code === 'ENOENT') return new Map(); throw error; }
60
+ let parsed;
61
+ try { parsed = JSON.parse(raw); }
62
+ catch { return new Map(); } // corrupt allowlist routes nothing new
63
+ const table = parsed?.v === 1 && parsed.workspaces && typeof parsed.workspaces === 'object'
64
+ ? parsed.workspaces : null;
65
+ if (!table) return new Map();
66
+ const out = new Map();
67
+ for (const [name, path] of Object.entries(table)) {
68
+ if (WORKSPACE_NAME.test(name) && typeof path === 'string' && isAbsolute(path)) out.set(name, path);
69
+ }
70
+ return out;
71
+ }
72
+
46
73
  export function validJob(job) {
47
74
  return validJobShape(job) ? job : null;
48
75
  }
@@ -52,6 +79,7 @@ function validJobShape(job) {
52
79
  && JOB_STATES.has(job.state)
53
80
  && typeof job.prompt === 'string' && job.prompt.length <= MAX_PROMPT
54
81
  && typeof job.ts === 'number'
82
+ && (job.workspace === undefined || WORKSPACE_NAME.test(job.workspace))
55
83
  && ['sessionId', 'reason', 'requestEntryId', 'responseEntryId'].every(key =>
56
84
  job[key] === undefined || typeof job[key] === 'string'));
57
85
  }
package/src/cloud/sshd.ts CHANGED
@@ -206,7 +206,7 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
206
206
  /** To the HOST, addressed as the device (the bridge on the host consumes these). */
207
207
  const toHost = (deviceId: string, payload: Record<string, unknown>): boolean => deps.sendAsDevice(deviceId, payload);
208
208
 
209
- const server = new Server({ hostKeys: [hostKey.private] }, (client, info) => {
209
+ const server = new Server({ hostKeys: [hostKey.private], ...(process.env.HERDGATE_SSH_AUTH_DEBUG === "1" ? { debug: (msg: string) => console.error(`ssh2: ${msg}`) } : {}) }, (client, info) => {
210
210
  // ssh2's server-side Client stores the socket supplied to injectSocket as
211
211
  // _sock (1.17). Do not authorize a connection if that transport is unknown.
212
212
  const socket = (client as unknown as { _sock?: Transport })._sock;
@@ -223,19 +223,16 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
223
223
  const id = ctx.username.trim();
224
224
  const rec = /^d_[A-Za-z0-9]+$/.test(id) ? deps.state.deviceById(id) : null;
225
225
  if (ctx.method === "publickey") {
226
- // Non-interactive clients (herdr-core's `machine add` shells out to system ssh,
227
- // which prefers keys and the agent) log in with a registered public key. ssh2
228
- // parses the request; verifying the signature (RFC 4252 §7, `ctx.blob` is the
229
- // exact signed bytes) is ours. A request WITHOUT a signature is the client
230
- // asking "would you take this key?" — accepting answers PK_OK (ssh2 does that).
231
226
  const pk = ctx as unknown as { key?: { algo: string; data: Buffer }; signature?: Buffer; blob?: Buffer; hashAlgo?: string };
232
227
  const key = pk.key;
233
- if (!rec || !key?.data) return reject();
228
+ if (process.env.HERDGATE_SSH_AUTH_DEBUG === "1") deps.log(`ssh-auth-debug: user=${ctx.username} sig=${Boolean(pk.signature)} algo=${key?.algo} blocked=${blocked(ip)}`);
229
+ if (!rec || !key?.data) { if (process.env.HERDGATE_SSH_AUTH_DEBUG === "1") deps.log(`ssh-auth-debug: reject rec=${Boolean(rec)} key=${Boolean(key?.data)}`); return reject(); }
234
230
  const entry = rec.sshKeys?.find((k) => k.algo === key.algo && Buffer.from(k.b64, "base64").equals(key.data));
235
- if (!entry) return reject(); // agent key not for us: no strike, just no
231
+ if (!entry) { if (process.env.HERDGATE_SSH_AUTH_DEBUG === "1") deps.log(`ssh-auth-debug: reject entry (algos=${rec.sshKeys?.map((k) => k.algo).join(",")})`); return reject(); } // agent key not for us: no strike, just no
236
232
  if (!pk.signature) return ctx.accept();
237
233
  const keyObj = sshPubKeyToKeyObject(key.algo, key.data);
238
234
  if (!keyObj || !cryptoVerify(pk.hashAlgo ?? undefined, pk.blob ?? Buffer.alloc(0), keyObj, pk.signature)) {
235
+ if (process.env.HERDGATE_SSH_AUTH_DEBUG === "1") deps.log(`ssh-auth-debug: reject verify keyObj=${Boolean(keyObj)} hashAlgo=${pk.hashAlgo} sigLen=${pk.signature?.length} blobLen=${pk.blob?.length}`);
239
236
  strike(ip);
240
237
  deps.log(`ssh: bad key signature for ${rec.id} from ${ip}`);
241
238
  return reject();
package/src/web/app.css CHANGED
@@ -331,3 +331,26 @@ dialog::backdrop {
331
331
  word-break: break-word;
332
332
  margin: 0;
333
333
  }
334
+
335
+ /* Pi worker panel (experimental) — mirrors the SSH leg's disclosure block. */
336
+ #view details.worker {
337
+ border: 1px solid var(--line, #2a2f3a);
338
+ border-radius: 8px;
339
+ padding: 8px 12px;
340
+ margin: 8px 0;
341
+ }
342
+ #view details.worker summary {
343
+ cursor: pointer;
344
+ font-weight: 600;
345
+ }
346
+ #view details.worker textarea,
347
+ #view details.worker input {
348
+ width: 100%;
349
+ box-sizing: border-box;
350
+ margin: 4px 0 8px;
351
+ }
352
+ #view details.worker pre {
353
+ white-space: pre-wrap;
354
+ overflow-wrap: anywhere;
355
+ margin: 4px 0;
356
+ }
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) };