@zero-server/sdk 0.9.6 → 0.9.8

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 (94) hide show
  1. package/README.md +54 -53
  2. package/index.js +116 -4
  3. package/lib/app.js +22 -22
  4. package/lib/auth/authorize.js +11 -11
  5. package/lib/auth/enrollment.js +5 -5
  6. package/lib/auth/jwt.js +9 -9
  7. package/lib/auth/oauth.js +1 -1
  8. package/lib/auth/session.js +5 -5
  9. package/lib/auth/trustedDevice.js +2 -2
  10. package/lib/auth/twoFactor.js +11 -11
  11. package/lib/auth/webauthn.js +6 -6
  12. package/lib/body/json.js +1 -1
  13. package/lib/body/raw.js +1 -1
  14. package/lib/body/rawBuffer.js +1 -1
  15. package/lib/body/text.js +1 -1
  16. package/lib/body/urlencoded.js +3 -3
  17. package/lib/cli.js +43 -28
  18. package/lib/cluster.js +3 -3
  19. package/lib/debug.js +10 -10
  20. package/lib/env/index.js +11 -11
  21. package/lib/errors.js +131 -16
  22. package/lib/fetch/index.js +1 -1
  23. package/lib/grpc/call.js +14 -14
  24. package/lib/grpc/client.js +4 -4
  25. package/lib/grpc/codec.js +7 -7
  26. package/lib/grpc/credentials.js +2 -2
  27. package/lib/grpc/frame.js +2 -2
  28. package/lib/grpc/health.js +3 -3
  29. package/lib/grpc/index.js +3 -3
  30. package/lib/grpc/metadata.js +3 -3
  31. package/lib/grpc/proto.js +5 -5
  32. package/lib/grpc/reflection.js +2 -2
  33. package/lib/grpc/server.js +3 -3
  34. package/lib/grpc/status.js +2 -2
  35. package/lib/grpc/watch.js +1 -1
  36. package/lib/http/request.js +13 -13
  37. package/lib/http/response.js +2 -2
  38. package/lib/lifecycle.js +5 -5
  39. package/lib/middleware/compress.js +4 -4
  40. package/lib/observe/health.js +1 -1
  41. package/lib/observe/index.js +1 -1
  42. package/lib/observe/logger.js +3 -3
  43. package/lib/observe/metrics.js +4 -4
  44. package/lib/observe/tracing.js +4 -4
  45. package/lib/orm/adapters/json.js +1 -1
  46. package/lib/orm/adapters/memory.js +2 -2
  47. package/lib/orm/adapters/mongo.js +2 -2
  48. package/lib/orm/adapters/mysql.js +2 -2
  49. package/lib/orm/adapters/postgres.js +2 -2
  50. package/lib/orm/adapters/sqlite.js +3 -3
  51. package/lib/orm/audit.js +1 -1
  52. package/lib/orm/index.js +7 -7
  53. package/lib/orm/migrate.js +1 -1
  54. package/lib/orm/model.js +15 -15
  55. package/lib/orm/procedures.js +1 -1
  56. package/lib/orm/profiler.js +1 -1
  57. package/lib/orm/query.js +9 -9
  58. package/lib/orm/schema.js +1 -1
  59. package/lib/orm/seed/data/person.js +1 -1
  60. package/lib/orm/seed/fake.js +10 -10
  61. package/lib/orm/seed/index.js +4 -4
  62. package/lib/orm/seed/rng.js +1 -1
  63. package/lib/orm/snapshot.js +3 -3
  64. package/lib/orm/tenancy.js +6 -6
  65. package/lib/orm/views.js +1 -1
  66. package/lib/router/index.js +9 -9
  67. package/lib/webrtc/bot.js +405 -0
  68. package/lib/webrtc/cli.js +182 -0
  69. package/lib/webrtc/cluster.js +338 -0
  70. package/lib/webrtc/e2ee.js +274 -0
  71. package/lib/webrtc/ice.js +363 -0
  72. package/lib/webrtc/index.js +212 -0
  73. package/lib/webrtc/joinToken.js +171 -0
  74. package/lib/webrtc/observe.js +260 -0
  75. package/lib/webrtc/peer.js +143 -0
  76. package/lib/webrtc/room.js +184 -0
  77. package/lib/webrtc/sdp.js +503 -0
  78. package/lib/webrtc/sfu/index.js +251 -0
  79. package/lib/webrtc/sfu/livekit.js +304 -0
  80. package/lib/webrtc/sfu/mediasoup.js +357 -0
  81. package/lib/webrtc/sfu/memory.js +221 -0
  82. package/lib/webrtc/signaling.js +590 -0
  83. package/lib/webrtc/stun.js +484 -0
  84. package/lib/webrtc/turn/codec.js +370 -0
  85. package/lib/webrtc/turn/credentials.js +156 -0
  86. package/lib/webrtc/turn/server.js +648 -0
  87. package/package.json +2 -2
  88. package/types/body.d.ts +82 -14
  89. package/types/cli.d.ts +40 -2
  90. package/types/index.d.ts +19 -6
  91. package/types/middleware.d.ts +18 -72
  92. package/types/orm.d.ts +4 -13
  93. package/types/request.d.ts +3 -3
  94. package/types/webrtc.d.ts +501 -0
@@ -0,0 +1,338 @@
1
+ /**
2
+ * @module webrtc/cluster
3
+ * @description Cluster adapter for the signaling hub. `useCluster(hub,
4
+ * adapter)` glues a `SignalingHub` to any `{ publish, subscribe }`
5
+ * pub/sub bus so joins, leaves, broadcasts, and direct frames flow
6
+ * across nodes. Ships with `MemoryClusterAdapter`; wire to Redis, NATS,
7
+ * Kafka, or any in-house bus in production.
8
+ *
9
+ * @section Cluster
10
+ */
11
+
12
+ 'use strict';
13
+
14
+ const crypto = require('node:crypto');
15
+
16
+ // --- Channel naming ---
17
+
18
+ const CH_ANNOUNCE = 'zs:rtc:announce';
19
+ const chRoom = (name) => `zs:rtc:room:${name}`;
20
+ const chNode = (id) => `zs:rtc:node:${id}`;
21
+
22
+ // --- ClusterCoordinator ---
23
+
24
+ /**
25
+ * Per-hub cluster glue. Created by {@link useCluster} and parked on
26
+ * `hub._cluster`. Owns the directory of remote peers and the set of
27
+ * pub/sub subscriptions.
28
+ *
29
+ * @class
30
+ * @section Cluster
31
+ */
32
+ class ClusterCoordinator
33
+ {
34
+ /**
35
+ * @constructor
36
+ * @param {import('./signaling').SignalingHub} hub
37
+ * @param {{publish:Function, subscribe:Function}} adapter
38
+ * @param {object} [opts]
39
+ * @param {string} [opts.nodeId] - Stable id for this node. Defaults to
40
+ * a random 8-byte hex string.
41
+ */
42
+ constructor(hub, adapter, opts = {})
43
+ {
44
+ /** @type {import('./signaling').SignalingHub} */
45
+ this.hub = hub;
46
+ /** @type {{publish:Function, subscribe:Function}} */
47
+ this.adapter = adapter;
48
+ /** @type {string} */
49
+ this.nodeId = opts.nodeId || crypto.randomBytes(8).toString('hex');
50
+
51
+ /**
52
+ * Remote peer directory. `peerId -> { nodeId, room }`.
53
+ * @type {Map<string, {nodeId: string, room: string}>}
54
+ */
55
+ this._remotePeers = new Map();
56
+
57
+ /** @type {Map<string, Function|null>} */
58
+ this._roomSubs = new Map();
59
+
60
+ /** @type {Function[]} */
61
+ this._unsubs = [];
62
+
63
+ /** @type {boolean} */
64
+ this._closed = false;
65
+
66
+ this._wire();
67
+ }
68
+
69
+ /** @private */
70
+ _wire()
71
+ {
72
+ const offAnnounce = this.adapter.subscribe(CH_ANNOUNCE, (m) => this._onAnnounce(m));
73
+ const offNode = this.adapter.subscribe(chNode(this.nodeId), (m) => this._onNodeMsg(m));
74
+ if (typeof offAnnounce === 'function') this._unsubs.push(offAnnounce);
75
+ if (typeof offNode === 'function') this._unsubs.push(offNode);
76
+
77
+ this._onJoin = ({ peer, room }) =>
78
+ {
79
+ this._ensureRoomSub(room.name);
80
+ this._safePub(CH_ANNOUNCE, {
81
+ kind: 'join', nodeId: this.nodeId, peerId: peer.id, room: room.name,
82
+ });
83
+ };
84
+ this._onLeave = ({ peer, room }) =>
85
+ {
86
+ this._safePub(CH_ANNOUNCE, {
87
+ kind: 'leave', nodeId: this.nodeId, peerId: peer.id, room: room.name,
88
+ });
89
+ };
90
+ this.hub.on('join', this._onJoin);
91
+ this.hub.on('leave', this._onLeave);
92
+
93
+ // Ask existing nodes to rebroadcast their directory.
94
+ this._safePub(CH_ANNOUNCE, { kind: 'hello', nodeId: this.nodeId });
95
+ }
96
+
97
+ /** @private */
98
+ _ensureRoomSub(roomName)
99
+ {
100
+ if (this._roomSubs.has(roomName)) return;
101
+ const off = this.adapter.subscribe(chRoom(roomName), (m) => this._onRoomMsg(roomName, m));
102
+ this._roomSubs.set(roomName, typeof off === 'function' ? off : null);
103
+ }
104
+
105
+ /** @private */
106
+ _onAnnounce(m)
107
+ {
108
+ if (!m || m.nodeId === this.nodeId || this._closed) return;
109
+ if (m.kind === 'join')
110
+ {
111
+ this._remotePeers.set(m.peerId, { nodeId: m.nodeId, room: m.room });
112
+ this._ensureRoomSub(m.room);
113
+ }
114
+ else if (m.kind === 'leave')
115
+ {
116
+ const entry = this._remotePeers.get(m.peerId);
117
+ if (entry && entry.nodeId === m.nodeId) this._remotePeers.delete(m.peerId);
118
+ }
119
+ else if (m.kind === 'hello')
120
+ {
121
+ // Replay our local directory so the newcomer learns about us.
122
+ for (const peer of this.hub._peers.values())
123
+ {
124
+ if (peer.room)
125
+ {
126
+ this._safePub(CH_ANNOUNCE, {
127
+ kind: 'join', nodeId: this.nodeId, peerId: peer.id, room: peer.room.name,
128
+ });
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ /** @private */
135
+ _onNodeMsg(m)
136
+ {
137
+ if (!m || m.nodeId === this.nodeId || this._closed) return;
138
+ const target = this.hub._peers.get(m.target);
139
+ if (!target) return;
140
+ target.send(m.type, m.payload);
141
+ }
142
+
143
+ /** @private */
144
+ _onRoomMsg(roomName, m)
145
+ {
146
+ if (!m || m.nodeId === this.nodeId || this._closed) return;
147
+ const room = this.hub._rooms.get(roomName);
148
+ if (!room) return;
149
+ for (const p of room._peers)
150
+ {
151
+ if (m.exclude && p.id === m.exclude) continue;
152
+ p.send(m.type, m.payload);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Look up the node that owns a remote peer, if any.
158
+ * @param {string} peerId
159
+ * @returns {{nodeId:string, room:string}|null}
160
+ */
161
+ locate(peerId)
162
+ {
163
+ return this._remotePeers.get(peerId) || null;
164
+ }
165
+
166
+ /**
167
+ * Forward a direct frame to a peer on another node. Called by the
168
+ * hub when a routed message (`offer` / `answer` / `ice`) targets a
169
+ * peer id that is not in the local registry.
170
+ *
171
+ * @param {string} toPeerId
172
+ * @param {string} type
173
+ * @param {object} payload
174
+ * @returns {boolean} `true` if a remote node was addressed.
175
+ */
176
+ routeDirect(toPeerId, type, payload)
177
+ {
178
+ const entry = this._remotePeers.get(toPeerId);
179
+ if (!entry) return false;
180
+ this._safePub(chNode(entry.nodeId), {
181
+ nodeId: this.nodeId, target: toPeerId, type, payload,
182
+ });
183
+ return true;
184
+ }
185
+
186
+ /**
187
+ * Mirror a `room.broadcast(...)` to peers in the same room on other
188
+ * nodes. Called automatically from `Room#broadcast`.
189
+ *
190
+ * @param {string} roomName
191
+ * @param {string} type
192
+ * @param {object} payload
193
+ * @param {string} [excludeId]
194
+ */
195
+ fanoutRoom(roomName, type, payload, excludeId)
196
+ {
197
+ this._safePub(chRoom(roomName), {
198
+ nodeId: this.nodeId, type, payload, exclude: excludeId || null,
199
+ });
200
+ }
201
+
202
+ /** Tear down all subscriptions and clear remote state. */
203
+ close()
204
+ {
205
+ if (this._closed) return;
206
+ this._closed = true;
207
+ try { this.hub.off('join', this._onJoin); } catch { /* ignore */ }
208
+ try { this.hub.off('leave', this._onLeave); } catch { /* ignore */ }
209
+ for (const off of this._unsubs) { try { off(); } catch { /* ignore */ } }
210
+ for (const off of this._roomSubs.values())
211
+ {
212
+ if (typeof off === 'function') { try { off(); } catch { /* ignore */ } }
213
+ }
214
+ this._unsubs.length = 0;
215
+ this._roomSubs.clear();
216
+ this._remotePeers.clear();
217
+ if (this.hub._cluster === this) this.hub._cluster = null;
218
+ }
219
+
220
+ /** @private */
221
+ _safePub(channel, message)
222
+ {
223
+ try
224
+ {
225
+ const result = this.adapter.publish(channel, message);
226
+ if (result && typeof result.catch === 'function')
227
+ result.catch((err) => this.hub.emit('clusterError', err));
228
+ }
229
+ catch (err)
230
+ {
231
+ this.hub.emit('clusterError', err);
232
+ }
233
+ }
234
+ }
235
+
236
+ // --- useCluster ---
237
+
238
+ /**
239
+ * Attach a cluster adapter to a `SignalingHub`.
240
+ *
241
+ * @param {import('./signaling').SignalingHub} hub
242
+ * @param {{publish:Function, subscribe:Function}} adapter
243
+ * @param {object} [opts]
244
+ * @param {string} [opts.nodeId]
245
+ * @returns {ClusterCoordinator}
246
+ *
247
+ * @section Cluster
248
+ *
249
+ * @example | In-memory cluster (tests / single-process simulation)
250
+ * const { SignalingHub, useCluster, MemoryClusterAdapter } = require('@zero-server/webrtc');
251
+ * const adapter = new MemoryClusterAdapter();
252
+ * const a = new SignalingHub(); useCluster(a, adapter, { nodeId: 'a' });
253
+ * const b = new SignalingHub(); useCluster(b, adapter, { nodeId: 'b' });
254
+ *
255
+ * @example | Redis adapter (BYO ioredis)
256
+ * const Redis = require('ioredis');
257
+ * const pub = new Redis(), sub = new Redis();
258
+ * const adapter = {
259
+ * publish: (ch, msg) => pub.publish(ch, JSON.stringify(msg)),
260
+ * subscribe: (ch, cb) => {
261
+ * sub.subscribe(ch);
262
+ * const on = (c, raw) => { if (c === ch) cb(JSON.parse(raw)); };
263
+ * sub.on('message', on);
264
+ * return () => { sub.off('message', on); sub.unsubscribe(ch); };
265
+ * },
266
+ * };
267
+ * useCluster(hub, adapter);
268
+ */
269
+ function useCluster(hub, adapter, opts)
270
+ {
271
+ if (!adapter || typeof adapter.publish !== 'function' || typeof adapter.subscribe !== 'function')
272
+ throw new TypeError('useCluster: adapter must implement { publish, subscribe }');
273
+ const coord = new ClusterCoordinator(hub, adapter, opts);
274
+ hub._cluster = coord;
275
+ return coord;
276
+ }
277
+
278
+ // --- MemoryClusterAdapter ---
279
+
280
+ /**
281
+ * In-memory pub/sub adapter for tests and single-process simulations.
282
+ * Delivers synchronously to all subscribers on the same channel.
283
+ *
284
+ * @class
285
+ * @section Cluster
286
+ *
287
+ * @example
288
+ * const adapter = new MemoryClusterAdapter();
289
+ * useCluster(hubA, adapter); useCluster(hubB, adapter);
290
+ */
291
+ class MemoryClusterAdapter
292
+ {
293
+ constructor()
294
+ {
295
+ /** @type {Map<string, Function[]>} */
296
+ this._channels = new Map();
297
+ }
298
+
299
+ /**
300
+ * @param {string} channel
301
+ * @param {*} message
302
+ */
303
+ publish(channel, message)
304
+ {
305
+ const list = this._channels.get(channel);
306
+ if (!list || list.length === 0) return;
307
+ for (const fn of list.slice())
308
+ {
309
+ try { fn(message); } catch { /* swallow subscriber errors */ }
310
+ }
311
+ }
312
+
313
+ /**
314
+ * @param {string} channel
315
+ * @param {(msg:*) => void} fn
316
+ * @returns {() => void} unsubscribe
317
+ */
318
+ subscribe(channel, fn)
319
+ {
320
+ let list = this._channels.get(channel);
321
+ if (!list) { list = []; this._channels.set(channel, list); }
322
+ list.push(fn);
323
+ return () =>
324
+ {
325
+ const cur = this._channels.get(channel);
326
+ if (!cur) return;
327
+ const i = cur.indexOf(fn);
328
+ if (i >= 0) cur.splice(i, 1);
329
+ if (cur.length === 0) this._channels.delete(channel);
330
+ };
331
+ }
332
+ }
333
+
334
+ module.exports = {
335
+ useCluster,
336
+ ClusterCoordinator,
337
+ MemoryClusterAdapter,
338
+ };
@@ -0,0 +1,274 @@
1
+ /**
2
+ * @module webrtc/e2ee
3
+ * @description End-to-end-encrypted key relay for WebRTC. Publishers wrap
4
+ * SFrame/Insertable-Streams keys in sealed envelopes (X25519 + HKDF-SHA-256
5
+ * + AES-256-GCM) and broadcast via `e2ee-key`; the hub stays opaque.
6
+ * `E2eeChannel` accepts any opaque `Buffer`, so libsignal or NaCl-sealed
7
+ * payloads work out of the box.
8
+ *
9
+ * @section E2EE
10
+ */
11
+
12
+ 'use strict';
13
+
14
+ const {
15
+ createPublicKey, createPrivateKey,
16
+ generateKeyPairSync,
17
+ diffieHellman,
18
+ hkdfSync,
19
+ createCipheriv, createDecipheriv,
20
+ randomBytes,
21
+ } = require('node:crypto');
22
+
23
+ const { WebRTCError } = require('../errors');
24
+
25
+ // --- Envelope constants ---
26
+
27
+ /** Envelope version byte. */
28
+ const ENVELOPE_VERSION = 0x01;
29
+
30
+ /** Raw X25519 key length, bytes. */
31
+ const X25519_RAW_LEN = 32;
32
+
33
+ /** AES-256-GCM nonce length, bytes. */
34
+ const GCM_NONCE_LEN = 12;
35
+
36
+ /** AES-256-GCM auth tag length, bytes. */
37
+ const GCM_TAG_LEN = 16;
38
+
39
+ /** HKDF salt - a short constant tying the envelope to this project. */
40
+ const HKDF_INFO = Buffer.from('zs-webrtc/e2ee/v1');
41
+
42
+ // --- Raw <-> KeyObject helpers ---
43
+
44
+ function _rawFromPublicKey(pub)
45
+ {
46
+ if (Buffer.isBuffer(pub) && pub.length === X25519_RAW_LEN) return pub;
47
+ const jwk = pub.export({ format: 'jwk' });
48
+ return Buffer.from(jwk.x, 'base64url');
49
+ }
50
+
51
+ function _publicKeyFromRaw(raw)
52
+ {
53
+ return createPublicKey({
54
+ key: { kty: 'OKP', crv: 'X25519', x: raw.toString('base64url') },
55
+ format: 'jwk',
56
+ });
57
+ }
58
+
59
+ // --- Public crypto helpers ---
60
+
61
+ /**
62
+ * Generate a fresh X25519 keypair suitable for {@link sealKey} /
63
+ * {@link openSealedKey}.
64
+ *
65
+ * @returns {{publicKey: KeyObject, privateKey: KeyObject}}
66
+ *
67
+ * @example
68
+ * const { publicKey, privateKey } = generateE2eeKeyPair();
69
+ * const wireKey = publicKey.export({ format: 'jwk' }).x; // base64url
70
+ */
71
+ function generateE2eeKeyPair()
72
+ {
73
+ return generateKeyPairSync('x25519');
74
+ }
75
+
76
+ /**
77
+ * Seal an opaque byte string for a single recipient using the project's
78
+ * default envelope (X25519 ECDH + HKDF-SHA-256 + AES-256-GCM).
79
+ *
80
+ * Envelope layout:
81
+ *
82
+ * `[ver:1] [ephPubRaw:32] [nonce:12] [ciphertext:N] [tag:16]`
83
+ *
84
+ * @param {Buffer|Uint8Array} plaintext - The bytes to encrypt.
85
+ * @param {KeyObject|Buffer} recipientPubKey - Recipient's X25519 public
86
+ * key (KeyObject or 32-byte raw).
87
+ * @returns {Buffer} The sealed envelope.
88
+ *
89
+ * @example
90
+ * const sealed = sealKey(Buffer.from(sframeKey), bob.publicKey);
91
+ * peer.e2ee.publish(epoch, sealed);
92
+ */
93
+ function sealKey(plaintext, recipientPubKey)
94
+ {
95
+ const pt = Buffer.isBuffer(plaintext) ? plaintext : Buffer.from(plaintext);
96
+ const pubKO = Buffer.isBuffer(recipientPubKey) ? _publicKeyFromRaw(recipientPubKey) : recipientPubKey;
97
+
98
+ const eph = generateKeyPairSync('x25519');
99
+ const shared = diffieHellman({ privateKey: eph.privateKey, publicKey: pubKO });
100
+ const ephRaw = _rawFromPublicKey(eph.publicKey);
101
+ const recRaw = _rawFromPublicKey(pubKO);
102
+
103
+ const salt = Buffer.concat([ephRaw, recRaw]);
104
+ const aesKey = Buffer.from(hkdfSync('sha256', shared, salt, HKDF_INFO, 32));
105
+
106
+ const nonce = randomBytes(GCM_NONCE_LEN);
107
+ const cipher = createCipheriv('aes-256-gcm', aesKey, nonce);
108
+ const ct = Buffer.concat([cipher.update(pt), cipher.final()]);
109
+ const tag = cipher.getAuthTag();
110
+
111
+ return Buffer.concat([Buffer.from([ENVELOPE_VERSION]), ephRaw, nonce, ct, tag]);
112
+ }
113
+
114
+ /**
115
+ * Open an envelope produced by {@link sealKey} with the recipient's private
116
+ * key. Throws if the envelope is malformed, was sealed for a different
117
+ * recipient, or was tampered with in flight.
118
+ *
119
+ * @param {Buffer|Uint8Array} sealed - Sealed envelope.
120
+ * @param {KeyObject|Buffer} recipientPrivKey - Recipient's X25519 private key.
121
+ * @returns {Buffer} Decrypted plaintext.
122
+ * @throws {WebRTCError} `code='E2EE_OPEN_FAILED'` on any failure.
123
+ *
124
+ * @example
125
+ * const sframeKey = openSealedKey(received.key, bob.privateKey);
126
+ */
127
+ function openSealedKey(sealed, recipientPrivKey)
128
+ {
129
+ const buf = Buffer.isBuffer(sealed) ? sealed : Buffer.from(sealed);
130
+ const minLen = 1 + X25519_RAW_LEN + GCM_NONCE_LEN + GCM_TAG_LEN;
131
+ if (buf.length < minLen)
132
+ throw new WebRTCError('sealed envelope too short', { code: 'E2EE_OPEN_FAILED' });
133
+ if (buf[0] !== ENVELOPE_VERSION)
134
+ throw new WebRTCError(`unsupported envelope version 0x${buf[0].toString(16)}`, { code: 'E2EE_OPEN_FAILED' });
135
+
136
+ const ephRaw = buf.subarray(1, 1 + X25519_RAW_LEN);
137
+ const nonce = buf.subarray(1 + X25519_RAW_LEN, 1 + X25519_RAW_LEN + GCM_NONCE_LEN);
138
+ const tag = buf.subarray(buf.length - GCM_TAG_LEN);
139
+ const ct = buf.subarray(1 + X25519_RAW_LEN + GCM_NONCE_LEN, buf.length - GCM_TAG_LEN);
140
+
141
+ try
142
+ {
143
+ const privKO = Buffer.isBuffer(recipientPrivKey) ? createPrivateKey({ key: recipientPrivKey, format: 'der', type: 'pkcs8' }) : recipientPrivKey;
144
+ const ephPub = _publicKeyFromRaw(ephRaw);
145
+ const shared = diffieHellman({ privateKey: privKO, publicKey: ephPub });
146
+
147
+ const recPubRaw = _rawFromPublicKey(createPublicKey(privKO));
148
+ const salt = Buffer.concat([ephRaw, recPubRaw]);
149
+ const aesKey = Buffer.from(hkdfSync('sha256', shared, salt, HKDF_INFO, 32));
150
+
151
+ const decipher = createDecipheriv('aes-256-gcm', aesKey, nonce);
152
+ decipher.setAuthTag(tag);
153
+ return Buffer.concat([decipher.update(ct), decipher.final()]);
154
+ }
155
+ catch (err)
156
+ {
157
+ throw new WebRTCError(`failed to open sealed envelope: ${err.message}`, { code: 'E2EE_OPEN_FAILED' });
158
+ }
159
+ }
160
+
161
+ // --- E2eeChannel ---
162
+
163
+ /**
164
+ * Per-peer view of the room's E2EE key channel. Created by
165
+ * {@link attachE2ee} and parked on `peer.e2ee`.
166
+ *
167
+ * Maintains a monotonically increasing `epoch` that callers may either
168
+ * supply explicitly or let the channel allocate. Every `publish()` is
169
+ * relayed by the hub to all other peers in the same room as an opaque
170
+ * `e2ee-key` frame - the hub never inspects or decrypts the payload.
171
+ *
172
+ * @class
173
+ * @section E2EE
174
+ */
175
+ class E2eeChannel
176
+ {
177
+ /**
178
+ * @constructor
179
+ * @param {Peer} peer
180
+ * @param {SignalingHub} hub
181
+ */
182
+ constructor(peer, hub)
183
+ {
184
+ /** @type {Peer} */
185
+ this.peer = peer;
186
+ /** @type {SignalingHub} */
187
+ this.hub = hub;
188
+ /** @type {number} Last published or observed epoch. */
189
+ this.epoch = 0;
190
+ }
191
+
192
+ /**
193
+ * Broadcast a sealed key to the rest of the peer's room.
194
+ *
195
+ * @param {number|null} epoch - Explicit epoch, or `null` to auto-increment.
196
+ * @param {Buffer|Uint8Array|string} key - Sealed bytes (or wire-ready string).
197
+ * @returns {number} The epoch the key was published under.
198
+ *
199
+ * @example
200
+ * const sealed = sealKey(sframeKey, bob.publicKey);
201
+ * const epoch = peer.e2ee.publish(null, sealed);
202
+ */
203
+ publish(epoch, key)
204
+ {
205
+ const ep = (typeof epoch === 'number') ? epoch : (this.epoch + 1);
206
+ if (ep > this.epoch) this.epoch = ep;
207
+
208
+ let wire;
209
+ if (typeof key === 'string') wire = key;
210
+ else if (Buffer.isBuffer(key)) wire = key.toString('base64');
211
+ else wire = Buffer.from(key).toString('base64');
212
+
213
+ // Route through the hub's authoritative handler so all the usual
214
+ // validation, broadcast, and observability hooks fire.
215
+ this.hub._handleE2eeKey(this.peer, { type: 'e2ee-key', epoch: ep, key: wire });
216
+ return ep;
217
+ }
218
+
219
+ /**
220
+ * Receive sealed keys published by *other* peers in the same room.
221
+ *
222
+ * @param {(ev: {from: string, epoch: number, key: Buffer}) => void} fn
223
+ * @returns {() => void} Unsubscribe function.
224
+ *
225
+ * @example
226
+ * peer.e2ee.subscribe(({ from, epoch, key }) => {
227
+ * const sframeKey = openSealedKey(key, myPrivKey);
228
+ * sframeContext.setKey(epoch, sframeKey);
229
+ * });
230
+ */
231
+ subscribe(fn)
232
+ {
233
+ const listener = (ev) =>
234
+ {
235
+ if (!ev || ev.peer === this.peer) return;
236
+ if (this.peer.room && ev.peer.room !== this.peer.room) return;
237
+ if (ev.epoch > this.epoch) this.epoch = ev.epoch;
238
+ const keyBuf = Buffer.isBuffer(ev.key) ? ev.key : Buffer.from(ev.key, 'base64');
239
+ try { fn({ from: ev.peer.id, epoch: ev.epoch, key: keyBuf }); }
240
+ catch { /* don't let subscriber errors break the hub */ }
241
+ };
242
+ this.hub.on('e2eeKey', listener);
243
+ return () => this.hub.off('e2eeKey', listener);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Install an {@link E2eeChannel} on a peer as `peer.e2ee`. Idempotent: a
249
+ * second call returns the existing channel.
250
+ *
251
+ * @param {Peer} peer
252
+ * @param {SignalingHub} hub
253
+ * @returns {E2eeChannel}
254
+ *
255
+ * @section E2EE
256
+ *
257
+ * @example | Attach E2EE on every join
258
+ * hub.on('join', ({ peer }) => attachE2ee(peer, hub));
259
+ */
260
+ function attachE2ee(peer, hub)
261
+ {
262
+ if (peer.e2ee instanceof E2eeChannel) return peer.e2ee;
263
+ peer.e2ee = new E2eeChannel(peer, hub);
264
+ return peer.e2ee;
265
+ }
266
+
267
+ module.exports = {
268
+ ENVELOPE_VERSION,
269
+ E2eeChannel,
270
+ attachE2ee,
271
+ generateE2eeKeyPair,
272
+ sealKey,
273
+ openSealedKey,
274
+ };