@bom0792/herdgate 0.0.0-stage → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +92 -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/dist-readme.md ADDED
@@ -0,0 +1,48 @@
1
+ # herdgate host bundle — biến máy này thành một "máy trong đàn"
2
+
3
+ Bộ này dùng cho máy đã cài **herdr** (app desktop hoặc TUI): cài mod + publisher,
4
+ máy sẽ tự kết nối **out** tới gate (không mở port, không VPN) và xuất hiện trên
5
+ phone/PWA của bạn.
6
+
7
+ ## Yêu cầu
8
+
9
+ - herdr desktop app (per-user, không cần admin) hoặc herdr TUI
10
+ - `node` >= 22 trong PATH (kiểm tra: `node -v`)
11
+ - **Hệ điều hành: Linux hoặc macOS.** Panel hiện dùng `sh`/`kill`/`nohup` —
12
+ bản Windows đang được port; theo dõi bản mới.
13
+
14
+ ## Cài (Linux / macOS)
15
+
16
+ 1. Giải nén bộ này ở một chỗ cố định, ví dụ `~/herdgate` (cả máy lẫn user thường đều được).
17
+
18
+ unzip herdgate-host.zip -d ~/herdgate-host
19
+
20
+ 2. Copy mod vào app:
21
+
22
+ # Linux
23
+ mkdir -p ~/.config/herdr-app/mods
24
+ cp -r ~/herdgate-host/mod/herdgate ~/.config/herdr-app/mods/
25
+
26
+ # macOS
27
+ mkdir -p ~/Library/Application Support/herdr-app/mods
28
+ cp -r ~/herdgate-host/mod/herdgate ~/Library/Application\ Support/herdr-app/mods/
29
+
30
+ 3. Mở (hoặc restart) herdr app → panel **herdgate** xuất hiện.
31
+ 4. Trong panel điền:
32
+ - **cloud**: `https://gate.phuongnb.io.vn`
33
+ - **herdgate folder**: đường dẫn tới thư mục `plugin` của bộ này (chứa `server/index.mjs`)
34
+ - **name**: tên máy (hiện trên PWA)
35
+ 5. **Pair** → panel hiện mã code → mở PWA `gate.phuongnb.io.vn` trên phone/browser bất kỳ,
36
+ Approve → xong. Nhấn **Publish**.
37
+
38
+ Máy giờ hiện trong PWA; phone pair thiết bị riêng để xem terminal.
39
+
40
+ ## Bộ gồm
41
+
42
+ mod/herdgate/ → copy vào mods/ của herdr-app
43
+ plugin/server/*.mjs → publisher (mod tự spawn bằng node)
44
+ plugin/herdr-plugin.toml → nếu bạn dùng herdr TUI thay vì app
45
+
46
+ ## Gỡ
47
+
48
+ rm -rf ~/.config/herdr-app/mods/herdgate ~/.config/herdr-app/herdgate
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.9.5",
4
+ "description": "Cloud relay hub for herdr-core: every machine dials out, phones and browsers follow (PWA + SSH leg, E2E payloads).",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22"
8
+ },
9
+ "scripts": {
10
+ "start": "node src/cloud/main.ts",
11
+ "host": "node src/host/main.ts",
12
+ "edge": "node src/dev/main.ts",
13
+ "test": "node --test test/*.test.ts",
14
+ "check": "tsc -p tsconfig.json",
15
+ "ssh-bridge": "node src/cloud/ssh-bridge.ts",
16
+ "postinstall": "node scripts/patch-ssh2.mjs"
17
+ },
18
+ "dependencies": {
19
+ "ssh2": "^1.17.0",
20
+ "ws": "^8.18.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^22.10.0",
24
+ "@types/ssh2": "^1.15.6",
25
+ "@types/ws": "^8.5.13",
26
+ "typescript": "^5.7.0"
27
+ },
28
+ "bin": {
29
+ "herdgate": "bin/herdgate.mjs"
30
+ },
31
+ "files": [
32
+ "bin",
33
+ "src",
34
+ "app-mod",
35
+ "plugin",
36
+ "scripts",
37
+ "dist-readme.md"
38
+ ]
6
39
  }
@@ -0,0 +1,36 @@
1
+ id = "dev.herdgate.host"
2
+ name = "herdgate"
3
+ version = "0.1.0"
4
+ min_herdr_version = "0.9.0"
5
+ description = "Publish this Herdr session to your own devices through a herdgate cloud relay (read-only by default)."
6
+ platforms = ["linux", "macos"]
7
+
8
+ # One long-lived publisher per Herdr server. Herdr runs startup hooks once the
9
+ # socket API is ready, and again after a live handoff; the process reconnects on
10
+ # its own if the network drops. `idempotent` keeps a second invocation from
11
+ # starting a competing publisher (one agent per room on the cloud side).
12
+ [[startup]]
13
+ command = ["node", "server/index.mjs", "serve"]
14
+
15
+ [[actions]]
16
+ id = "status"
17
+ title = "herdgate: show pairing status"
18
+ command = ["node", "server/index.mjs", "status"]
19
+
20
+ [[actions]]
21
+ id = "pair"
22
+ title = "herdgate: pair this Herdr to a cloud"
23
+ command = ["node", "server/index.mjs", "pair"]
24
+
25
+ [[actions]]
26
+ id = "stop"
27
+ title = "herdgate: stop publishing"
28
+ command = ["node", "server/index.mjs", "stop"]
29
+
30
+ # The pane is the surface inside Herdr: honest state of the publish lane, and
31
+ # the pairing code when one is waiting to be approved.
32
+ [[panes]]
33
+ id = "status"
34
+ title = "herdgate"
35
+ placement = "split"
36
+ command = ["node", "server/index.mjs", "pane"]
@@ -0,0 +1,79 @@
1
+ /** Shared pieces of the herdgate plugin: config, state, the Herdr CLI lane. */
2
+
3
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { execFile } from "node:child_process";
6
+ import { promisify } from "node:util";
7
+
8
+ const run = promisify(execFile);
9
+
10
+ export function dirs(env = process.env) {
11
+ return {
12
+ pluginId: env.HERDR_PLUGIN_ID ?? "dev.herdgate.host",
13
+ configDir: env.HERDR_PLUGIN_CONFIG_DIR ?? "",
14
+ stateDir: env.HERDR_PLUGIN_STATE_DIR ?? "",
15
+ herdrBin: env.HERDR_BIN_PATH ?? "herdr",
16
+ configPath: env.HERDR_PLUGIN_CONFIG_DIR ? join(env.HERDR_PLUGIN_CONFIG_DIR, "herdgate.env") : "",
17
+ statePath: env.HERDR_PLUGIN_STATE_DIR ? join(env.HERDR_PLUGIN_STATE_DIR, "pairing.json") : "",
18
+ };
19
+ }
20
+
21
+ /** `key=value` lines. Credentials live here, mode 0600, never in the plugin root. */
22
+ export function readConfig(path) {
23
+ const out = {};
24
+ if (!path || !existsSync(path)) return out;
25
+ for (const line of readFileSync(path, "utf8").split("\n")) {
26
+ const t = line.trim();
27
+ if (!t || t.startsWith("#")) continue;
28
+ const i = t.indexOf("=");
29
+ if (i > 0) out[t.slice(0, i).trim()] = t.slice(i + 1).trim();
30
+ }
31
+ return out;
32
+ }
33
+
34
+ export function writeConfig(path, cfg) {
35
+ if (!path) throw new Error("HERDR_PLUGIN_CONFIG_DIR is not set");
36
+ mkdirSync(join(path, ".."), { recursive: true });
37
+ writeFileSync(path, Object.entries(cfg).map(([k, v]) => `${k}=${v}`).join("\n") + "\n", { mode: 0o600 });
38
+ try {
39
+ chmodSync(path, 0o600);
40
+ } catch {
41
+ /* filesystems without modes */
42
+ }
43
+ }
44
+
45
+ export function readState(path) {
46
+ if (!path || !existsSync(path)) return {};
47
+ try {
48
+ return JSON.parse(readFileSync(path, "utf8"));
49
+ } catch {
50
+ return {};
51
+ }
52
+ }
53
+
54
+ export function writeState(path, state) {
55
+ if (!path) return;
56
+ mkdirSync(join(path, ".."), { recursive: true });
57
+ writeFileSync(path, JSON.stringify(state, null, 2), { mode: 0o600 });
58
+ }
59
+
60
+ /** The Herdr CLI is the plugin API: `HERDR_BIN_PATH` keeps it portable. */
61
+ export async function herdrSnapshot(bin, timeoutMs = 8_000) {
62
+ const { stdout } = await run(bin, ["api", "snapshot"], { timeout: timeoutMs, maxBuffer: 8 << 20 });
63
+ const parsed = JSON.parse(stdout);
64
+ return parsed?.result?.snapshot ?? parsed?.snapshot ?? parsed;
65
+ }
66
+
67
+ export function summarize(snap) {
68
+ const ws = Array.isArray(snap?.workspaces) ? snap.workspaces : [];
69
+ const agents = Array.isArray(snap?.agents) ? snap.agents : [];
70
+ const count = (s) => agents.filter((a) => a?.agent_status === s).length;
71
+ return {
72
+ herdr: `${snap?.version ?? "?"} (protocol ${snap?.protocol ?? "?"})`,
73
+ workspaces: ws.length,
74
+ agents: agents.length,
75
+ working: count("working"),
76
+ blocked: count("blocked"),
77
+ labels: ws.map((w) => w?.label).filter((l) => typeof l === "string"),
78
+ };
79
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Types for the E2E crypto module (plugin/server/e2e.mjs — plain JS on WebCrypto).
3
+ * The PWA copy (src/web/e2e.js) is byte-identical; both share this declaration.
4
+ */
5
+
6
+ export declare const NOISE_NAME: string;
7
+ export declare const KEY_LEN: number;
8
+ export declare const PUB_LEN: number;
9
+
10
+ export declare function b64e(u8: Uint8Array): string;
11
+ export declare function b64d(s: string): Uint8Array;
12
+ export declare function utf8e(s: string): Uint8Array;
13
+ export declare function utf8d(u8: Uint8Array): string;
14
+ export declare function concat(...parts: Uint8Array[]): Uint8Array;
15
+ export declare function fingerprint(pub: Uint8Array): string;
16
+ export declare function generateKeyPair(): Promise<{ jwk: JsonWebKey; pub: Uint8Array }>;
17
+
18
+ export interface NoiseWire {
19
+ op: string;
20
+ n?: number;
21
+ c?: string;
22
+ e?: string;
23
+ }
24
+
25
+ export declare class DeviceChannel {
26
+ constructor(self: { jwk: JsonWebKey; pub: Uint8Array });
27
+ begin(): Promise<{ e: string }>;
28
+ acceptReply(msg: { e: string; c: string }): Promise<{ c: string }>;
29
+ ready(): boolean;
30
+ hostFingerprint: string | null;
31
+ send(obj: unknown): Promise<{ op: string; n: number; c: string }>;
32
+ recv(msg: { op: string; n?: number; c: string }): Promise<Record<string, unknown>>;
33
+ }
34
+
35
+ export declare class HostChannel {
36
+ constructor(self: { jwk: JsonWebKey; pub: Uint8Array });
37
+ acceptInit(msg: { e: string }): Promise<{ e: string; c: string }>;
38
+ acceptFinish(msg: { c: string }): Promise<void>;
39
+ ready(): boolean;
40
+ deviceFingerprint: string | null;
41
+ send(obj: unknown): Promise<{ op: string; n: number; c: string }>;
42
+ recv(msg: { op: string; n?: number; c: string }): Promise<Record<string, unknown>>;
43
+ }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * herdgate E2E payloads — Noise_XX over the opaque payload channel.
3
+ *
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
+ * runs on WebCrypto (`globalThis.crypto.subtle` — Node ≥ 20 exposes the same
7
+ * object globally), so the plugin and the browser execute identical logic.
8
+ *
9
+ * Scheme: Noise_XX with P-256 ECDH, SHA-256 and AES-256-GCM
10
+ * (Noise_XX_P256_AESGCM_SHA256). The device initiates after pairing; the host
11
+ * answers with its long-lived static key (TOFU — the device learns its
12
+ * fingerprint from the decrypted handshake and compares it on every later
13
+ * session). After handshake, payloads travel as `{op:"e2e", n:<u64>, c:<b64>}`;
14
+ * the cloud keeps routing them blind.
15
+ *
16
+ * The cloud never sees any of this: the handshake and all ciphertext travel
17
+ * inside `frame.payload`, which the gateway does not parse (DESIGN.md §3).
18
+ */
19
+
20
+ /** The Noise protocol name; its hash seeds the chaining state (spec §5.1). */
21
+ export const NOISE_NAME = "Noise_XX_P256_AESGCM_SHA256";
22
+ export const KEY_LEN = 32;
23
+ export const PUB_LEN = 65; // uncompressed P-256 point: 0x04 ‖ X ‖ Y
24
+
25
+ // ---- byte helpers (kept dependency-free; typed arrays only) ----------------
26
+
27
+ export function b64e(u8) {
28
+ let s = "";
29
+ for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode(...u8.subarray(i, i + 0x8000));
30
+ return btoa(s);
31
+ }
32
+ export function b64d(s) {
33
+ const bin = atob(s);
34
+ const u8 = new Uint8Array(bin.length);
35
+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
36
+ return u8;
37
+ }
38
+ export const utf8e = (s) => new TextEncoder().encode(s);
39
+ export const utf8d = (u8) => new TextDecoder().decode(u8);
40
+ export function concat(...parts) {
41
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
42
+ let o = 0;
43
+ for (const p of parts) {
44
+ out.set(p, o);
45
+ o += p.length;
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /** Short human-checkable fingerprint of a static public key (8 bytes, url-safe). */
51
+ export function fingerprint(pub) {
52
+ return b64e(pub.slice(0, 8)).replace(/[^A-Za-z0-9]/g, "").toLowerCase().slice(0, 12);
53
+ }
54
+
55
+ // ---- WebCrypto plumbing ----------------------------------------------------
56
+
57
+ const subtle = globalThis.crypto.subtle;
58
+
59
+ async function sha256(data) {
60
+ return new Uint8Array(await subtle.digest("SHA-256", data));
61
+ }
62
+ async function hmac(keyBytes, data) {
63
+ const key = await subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
64
+ return new Uint8Array(await subtle.sign("HMAC", key, data));
65
+ }
66
+ /** Noise's HKDF: two outputs (ck', k) from a chaining key and input key material. */
67
+ async function hkdf2(chainingKey, ikm) {
68
+ const temp = await hmac(chainingKey, ikm);
69
+ const o1 = await hmac(temp, new Uint8Array([0x01]));
70
+ const o2 = await hmac(temp, concat(o1, new Uint8Array([0x02])));
71
+ return [o1, o2];
72
+ }
73
+
74
+ /** ECDH over P-256; returns the 32-byte shared secret (the X coordinate). */
75
+ async function dh(privJwk, peerPubRaw) {
76
+ const priv = await subtle.importKey("jwk", privJwk, { name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
77
+ const pub = await subtle.importKey("raw", peerPubRaw, { name: "ECDH", namedCurve: "P-256" }, false, []);
78
+ return new Uint8Array(await subtle.deriveBits({ name: "ECDH", public: pub }, priv, 256));
79
+ }
80
+
81
+ export async function generateKeyPair() {
82
+ const pair = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
83
+ const jwk = await subtle.exportKey("jwk", pair.privateKey);
84
+ const pub = new Uint8Array(await subtle.exportKey("raw", pair.publicKey));
85
+ return { jwk, pub };
86
+ }
87
+
88
+ // ---- CipherState (Noise spec §5.2) ------------------------------------------
89
+
90
+ class CipherState {
91
+ k = null;
92
+ n = 0;
93
+ setKey(k) {
94
+ this.k = k;
95
+ }
96
+ nonce() {
97
+ // 96-bit: 4 zero bytes ‖ BE64(n) — n stays below 2^32 for our lifetimes.
98
+ const iv = new Uint8Array(12);
99
+ new DataView(iv.buffer).setUint32(8, this.n);
100
+ return iv;
101
+ }
102
+ async encrypt(ad, plaintext) {
103
+ if (this.n >= 0xffffffff) throw new Error("e2e: nonce exhausted");
104
+ const key = await subtle.importKey("raw", this.k, "AES-GCM", false, ["encrypt"]);
105
+ const ct = new Uint8Array(
106
+ await subtle.encrypt({ name: "AES-GCM", iv: this.nonce(), additionalData: ad, tagLength: 128 }, key, plaintext),
107
+ );
108
+ this.n += 1;
109
+ return ct;
110
+ }
111
+ async decrypt(ad, ciphertext) {
112
+ const key = await subtle.importKey("raw", this.k, "AES-GCM", false, ["decrypt"]);
113
+ const pt = new Uint8Array(
114
+ await subtle.decrypt({ name: "AES-GCM", iv: this.nonce(), additionalData: ad, tagLength: 128 }, key, ciphertext),
115
+ );
116
+ this.n += 1;
117
+ return pt;
118
+ }
119
+ }
120
+
121
+ // ---- the handshake ----------------------------------------------------------
122
+ //
123
+ // device → e_dev (msg1: 65 B raw)
124
+ // host → e_host ‖ ENC0(s_host) (msg2: ENC0 = plaintext when k unset)
125
+ // device → ENC0(s_dev) (msg3)
126
+ //
127
+ // tokens: -> e <- e, ee, s, es -> s, se
128
+ // ee = DH(e_dev, e_host) es = DH(e_dev, s_host) se = DH(e_host, s_dev)
129
+ //
130
+ // then Split() gives one CipherState per direction; every transport message is
131
+ // AES-GCM under it with the final handshake hash as associated data.
132
+
133
+ class Handshake {
134
+ h = null;
135
+ ck = null;
136
+ cs = new CipherState();
137
+ async reset() {
138
+ const nameBytes = utf8e(NOISE_NAME);
139
+ this.h = nameBytes.length === KEY_LEN ? nameBytes : await sha256(nameBytes);
140
+ this.ck = this.h;
141
+ this.cs = new CipherState();
142
+ }
143
+ async mixHash(data) {
144
+ this.h = await sha256(concat(this.h, data));
145
+ }
146
+ async mixKey(ikm) {
147
+ const [ck, k] = await hkdf2(this.ck, ikm);
148
+ this.ck = ck;
149
+ this.cs = new CipherState();
150
+ this.cs.setKey(k);
151
+ }
152
+ /** The `s` token: transport under the current key, else in the clear (ENC0). */
153
+ async writeTokenStatic(pubRaw) {
154
+ const out = this.cs.k ? await this.cs.encrypt(this.h, pubRaw) : pubRaw;
155
+ await this.mixHash(out);
156
+ return out;
157
+ }
158
+ async readTokenStatic(bytes) {
159
+ const pt = this.cs.k ? await this.cs.decrypt(this.h, bytes) : bytes;
160
+ await this.mixHash(bytes);
161
+ return pt;
162
+ }
163
+ async split() {
164
+ const [k1, k2] = await hkdf2(this.ck, new Uint8Array(0));
165
+ const c1 = new CipherState();
166
+ const c2 = new CipherState();
167
+ c1.setKey(k1);
168
+ c2.setKey(k2);
169
+ return [c1, c2];
170
+ }
171
+ }
172
+
173
+ /** The device side (initiator). `self` is {jwk, pub} from generateKeyPair(). */
174
+ export class DeviceChannel {
175
+ #hs = new Handshake();
176
+ #self = null;
177
+ #e = null;
178
+ sendCs = null;
179
+ recvCs = null;
180
+ hostFingerprint = null;
181
+ constructor(self) {
182
+ this.#self = self;
183
+ }
184
+ /** msg1 payload for `{op:"e2e.init", e}`. */
185
+ async begin() {
186
+ await this.#hs.reset();
187
+ this.#e = await generateKeyPair();
188
+ await this.#hs.mixHash(this.#e.pub);
189
+ return { e: b64e(this.#e.pub) };
190
+ }
191
+ /** Feed the host's `{op:"e2e.reply", e, c}`; returns the msg3 payload. */
192
+ async acceptReply(msg) {
193
+ const eHost = b64d(msg.e);
194
+ if (eHost.length !== PUB_LEN) throw new Error("e2e: bad host ephemeral");
195
+ await this.#hs.mixHash(eHost);
196
+ await this.#hs.mixKey(await dh(this.#e.jwk, eHost)); // ee
197
+ const sHost = await this.#hs.readTokenStatic(b64d(msg.c)); // s
198
+ if (sHost.length !== PUB_LEN) throw new Error("e2e: bad host static");
199
+ this.hostFingerprint = fingerprint(sHost);
200
+ await this.#hs.mixKey(await dh(this.#e.jwk, sHost)); // es (e_dev × s_host)
201
+ const c = await this.#hs.writeTokenStatic(this.#self.pub); // s_dev
202
+ await this.#hs.mixKey(await dh(this.#self.jwk, eHost)); // se (e_host × s_dev)
203
+ const [c1, c2] = await this.#hs.split();
204
+ this.sendCs = c1; // device → host
205
+ this.recvCs = c2; // host → device
206
+ this.#e = null;
207
+ return { c: b64e(c) };
208
+ }
209
+ ready() {
210
+ return Boolean(this.sendCs && this.recvCs);
211
+ }
212
+ async send(obj) {
213
+ const ct = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
214
+ return { op: "e2e", n: this.sendCs.n - 1, c: b64e(ct) };
215
+ }
216
+ async recv(msg) {
217
+ const pt = await this.recvCs.decrypt(this.#hs.h, b64d(msg.c));
218
+ return JSON.parse(utf8d(pt));
219
+ }
220
+ }
221
+
222
+ /** The host side (responder): one instance per device. */
223
+ export class HostChannel {
224
+ #hs = new Handshake();
225
+ #self = null;
226
+ #e = null;
227
+ sendCs = null;
228
+ recvCs = null;
229
+ deviceFingerprint = null;
230
+ constructor(self) {
231
+ this.#self = self;
232
+ }
233
+ /** Feed the device's `{op:"e2e.init", e}`; returns the msg2 payload. */
234
+ async acceptInit(msg) {
235
+ await this.#hs.reset();
236
+ const eDev = b64d(msg.e);
237
+ if (eDev.length !== PUB_LEN) throw new Error("e2e: bad device ephemeral");
238
+ await this.#hs.mixHash(eDev);
239
+ this.#e = await generateKeyPair();
240
+ await this.#hs.mixHash(this.#e.pub);
241
+ await this.#hs.mixKey(await dh(this.#e.jwk, eDev)); // ee (e_dev × e_host)
242
+ const c = await this.#hs.writeTokenStatic(this.#self.pub); // s_host
243
+ await this.#hs.mixKey(await dh(this.#self.jwk, eDev)); // es (e_dev × s_host)
244
+ return { e: b64e(this.#e.pub), c: b64e(c) };
245
+ }
246
+ /** Feed the device's `{op:"e2e.finish", c}`; the channel is ready afterwards. */
247
+ async acceptFinish(msg) {
248
+ const sDev = await this.#hs.readTokenStatic(b64d(msg.c)); // s_dev
249
+ if (sDev.length !== PUB_LEN) throw new Error("e2e: bad device static");
250
+ this.deviceFingerprint = fingerprint(sDev);
251
+ await this.#hs.mixKey(await dh(this.#e.jwk, sDev)); // se (e_host × s_dev)
252
+ const [c1, c2] = await this.#hs.split();
253
+ this.recvCs = c1; // device → host (c1 encrypts initiator→responder)
254
+ this.sendCs = c2; // host → device
255
+ this.#e = null;
256
+ }
257
+ ready() {
258
+ return Boolean(this.sendCs && this.recvCs);
259
+ }
260
+ async send(obj) {
261
+ const ct = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
262
+ return { op: "e2e", n: this.sendCs.n - 1, c: b64e(ct) };
263
+ }
264
+ async recv(msg) {
265
+ const pt = await this.recvCs.decrypt(this.#hs.h, b64d(msg.c));
266
+ return JSON.parse(utf8d(pt));
267
+ }
268
+ }