@dimchansky/meshpost 0.4.2 → 0.6.0

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 +66 -550
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +25 -39
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +45 -0
  10. package/dist/identity.js +188 -28
  11. package/dist/index.d.ts +6 -6
  12. package/dist/index.js +3 -3
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +19 -1
  17. package/dist/public.js +26 -9
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +41 -0
  39. package/dist/voice.js +205 -273
  40. package/dist/ws.js +60 -146
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +16 -9
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
package/dist/nostr.js CHANGED
@@ -1,5 +1,7 @@
1
- import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, fromBase64Url, maxMidLength, openPayload, sealPayload, toBase64Url } from './crypto.js';
2
- import { isSignal, isUuid, namespaceHash } from './signaling.js';
1
+ import { bytesToHex, generateSessionKeypair, hex128Pattern, hex64Pattern, hexToBytes, schnorrSign, sha256, verifySchnorr } from './bip340.js';
2
+ import { createReplayGuard, fromBase64Url, maxMidLength, openPayload, sealPayload, toBase64Url } from './crypto.js';
3
+ import { createErrorThrottle, createPresenceTracker, createRelayPool, normalizeWsRelayUrl, validatePositiveTimeout } from './relay-core.js';
4
+ import { isUuid, namespaceHash } from './signaling.js';
3
5
  /** Built-in public port-443 Nostr WebSocket relays used by default. */
4
6
  export const defaultNostrRelays = Object.freeze([
5
7
  'wss://relay.damus.io',
@@ -12,7 +14,6 @@ const decoder = new TextDecoder();
12
14
  const ephemeralKind = 25050;
13
15
  const maxFrameChars = 128 * 1024;
14
16
  const maxContentChars = 96 * 1024;
15
- const maxSeenPeers = 256;
16
17
  const maxSeenEventIds = 2048;
17
18
  const maxDecryptQueueDepth = 64;
18
19
  const maxSchnorrVerifiesPerSec = 64;
@@ -20,346 +21,6 @@ const maxCreatedAtSkewSec = 120;
20
21
  const defaultHandshakeTimeoutMs = 10_000;
21
22
  const keepaliveIntervalMs = 25_000;
22
23
  const appIdPattern = /^[a-zA-Z0-9._-]{1,64}$/;
23
- const hex64Pattern = /^[0-9a-f]{64}$/;
24
- const hex128Pattern = /^[0-9a-f]{128}$/;
25
- // =============================================================================
26
- // Pure-TS Zero-Dependency SHA-256 & BIP-340 Schnorr (secp256k1)
27
- // Lazily initialized so bundlers drop 100% of this module when unused.
28
- // =============================================================================
29
- const secpP = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;
30
- const secpN = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
31
- const secpGx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n;
32
- const secpGy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;
33
- const sqrtExp = (secpP + 1n) >> 2n;
34
- let cachedSha256K;
35
- let cachedTagHashes;
36
- function getSha256K() {
37
- cachedSha256K ??= new Uint32Array([
38
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
39
- 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
40
- 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
41
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
42
- 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
43
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
44
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
45
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
46
- ]);
47
- return cachedSha256K;
48
- }
49
- /** @internal */
50
- export function sha256(data) {
51
- const K = getSha256K();
52
- let h0 = 0x6a09e667;
53
- let h1 = 0xbb67ae85;
54
- let h2 = 0x3c6ef372;
55
- let h3 = 0xa54ff53a;
56
- let h4 = 0x510e527f;
57
- let h5 = 0x9b05688c;
58
- let h6 = 0x1f83d9ab;
59
- let h7 = 0x5be0cd19;
60
- const len = data.byteLength;
61
- const paddedLen = (len + 9 + 63) & ~63;
62
- const padded = new Uint8Array(paddedLen);
63
- padded.set(data);
64
- padded[len] = 0x80;
65
- const dv = new DataView(padded.buffer);
66
- dv.setUint32(paddedLen - 8, Math.floor(len / 0x20000000) >>> 0, false);
67
- dv.setUint32(paddedLen - 4, (len << 3) >>> 0, false);
68
- const w = new Uint32Array(64);
69
- for (let off = 0; off < paddedLen; off += 64) {
70
- for (let i = 0; i < 16; i++)
71
- w[i] = dv.getUint32(off + i * 4, false);
72
- for (let i = 16; i < 64; i++) {
73
- const w15 = w[i - 15];
74
- const w2 = w[i - 2];
75
- const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
76
- const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
77
- w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
78
- }
79
- let a = h0;
80
- let b = h1;
81
- let c = h2;
82
- let d = h3;
83
- let e = h4;
84
- let f = h5;
85
- let g = h6;
86
- let h = h7;
87
- for (let i = 0; i < 64; i++) {
88
- const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
89
- const ch = (e & f) ^ (~e & g);
90
- const temp1 = (h + S1 + ch + K[i] + w[i]) >>> 0;
91
- const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
92
- const maj = (a & b) ^ (a & c) ^ (b & c);
93
- const temp2 = (S0 + maj) >>> 0;
94
- h = g;
95
- g = f;
96
- f = e;
97
- e = (d + temp1) >>> 0;
98
- d = c;
99
- c = b;
100
- b = a;
101
- a = (temp1 + temp2) >>> 0;
102
- }
103
- h0 = (h0 + a) >>> 0;
104
- h1 = (h1 + b) >>> 0;
105
- h2 = (h2 + c) >>> 0;
106
- h3 = (h3 + d) >>> 0;
107
- h4 = (h4 + e) >>> 0;
108
- h5 = (h5 + f) >>> 0;
109
- h6 = (h6 + g) >>> 0;
110
- h7 = (h7 + h) >>> 0;
111
- }
112
- const out = new Uint8Array(32);
113
- const outDv = new DataView(out.buffer);
114
- outDv.setUint32(0, h0, false);
115
- outDv.setUint32(4, h1, false);
116
- outDv.setUint32(8, h2, false);
117
- outDv.setUint32(12, h3, false);
118
- outDv.setUint32(16, h4, false);
119
- outDv.setUint32(20, h5, false);
120
- outDv.setUint32(24, h6, false);
121
- outDv.setUint32(28, h7, false);
122
- return out;
123
- }
124
- function getTagHashes() {
125
- if (!cachedTagHashes) {
126
- cachedTagHashes = {
127
- aux: sha256(encoder.encode('BIP0340/aux')),
128
- nonce: sha256(encoder.encode('BIP0340/nonce')),
129
- challenge: sha256(encoder.encode('BIP0340/challenge'))
130
- };
131
- }
132
- return cachedTagHashes;
133
- }
134
- function taggedHash(tagHash, ...parts) {
135
- let total = 64;
136
- for (const p of parts)
137
- total += p.byteLength;
138
- const buf = new Uint8Array(total);
139
- buf.set(tagHash, 0);
140
- buf.set(tagHash, 32);
141
- let off = 64;
142
- for (const p of parts) {
143
- buf.set(p, off);
144
- off += p.byteLength;
145
- }
146
- return sha256(buf);
147
- }
148
- function bytesToHex(bytes) {
149
- let out = '';
150
- for (let i = 0; i < bytes.length; i++)
151
- out += bytes[i].toString(16).padStart(2, '0');
152
- return out;
153
- }
154
- function hexToBytes(hex) {
155
- const out = new Uint8Array(hex.length >>> 1);
156
- for (let i = 0; i < out.length; i++) {
157
- out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
158
- }
159
- return out;
160
- }
161
- function bytesToBigInt(bytes) {
162
- let res = 0n;
163
- for (let i = 0; i < bytes.length; i++)
164
- res = (res << 8n) | BigInt(bytes[i]);
165
- return res;
166
- }
167
- function bigIntTo32Bytes(num) {
168
- const out = new Uint8Array(32);
169
- let n = num;
170
- for (let i = 31; i >= 0; i--) {
171
- out[i] = Number(n & 0xffn);
172
- n >>= 8n;
173
- }
174
- return out;
175
- }
176
- function modP(a) {
177
- const r = a % secpP;
178
- return r >= 0n ? r : r + secpP;
179
- }
180
- function modN(a) {
181
- const r = a % secpN;
182
- return r >= 0n ? r : r + secpN;
183
- }
184
- function modPow(base, exp, m) {
185
- let res = 1n;
186
- let b = ((base % m) + m) % m;
187
- let e = exp;
188
- while (e > 0n) {
189
- if ((e & 1n) === 1n)
190
- res = (res * b) % m;
191
- b = (b * b) % m;
192
- e >>= 1n;
193
- }
194
- return res;
195
- }
196
- function modInvP(a) {
197
- let t = 0n;
198
- let newT = 1n;
199
- let r = secpP;
200
- let newR = modP(a);
201
- while (newR !== 0n) {
202
- const q = r / newR;
203
- const tmpT = t - q * newT;
204
- t = newT;
205
- newT = tmpT;
206
- const tmpR = r - q * newR;
207
- r = newR;
208
- newR = tmpR;
209
- }
210
- return t < 0n ? t + secpP : t;
211
- }
212
- const jacInfinity = { x: 0n, y: 1n, z: 0n };
213
- const jacG = { x: secpGx, y: secpGy, z: 1n };
214
- function pointDouble(p) {
215
- if (p.z === 0n || p.y === 0n)
216
- return jacInfinity;
217
- const y2 = modP(p.y * p.y);
218
- const s = modP(4n * p.x * y2);
219
- const m = modP(3n * modP(p.x * p.x));
220
- const x3 = modP(m * m - 2n * s);
221
- const y3 = modP(m * (s - x3) - 8n * modP(y2 * y2));
222
- const z3 = modP(2n * modP(p.y * p.z));
223
- return { x: x3, y: y3, z: z3 };
224
- }
225
- function pointAdd(p, q) {
226
- if (p.z === 0n)
227
- return q;
228
- if (q.z === 0n)
229
- return p;
230
- const z1z1 = modP(p.z * p.z);
231
- const z2z2 = modP(q.z * q.z);
232
- const u1 = modP(p.x * z2z2);
233
- const u2 = modP(q.x * z1z1);
234
- const s1 = modP(p.y * modP(q.z * z2z2));
235
- const s2 = modP(q.y * modP(p.z * z1z1));
236
- if (u1 === u2) {
237
- return s1 !== s2 ? jacInfinity : pointDouble(p);
238
- }
239
- const h = modP(u2 - u1);
240
- const r = modP(s2 - s1);
241
- const h2 = modP(h * h);
242
- const h3 = modP(h * h2);
243
- const u1h2 = modP(u1 * h2);
244
- const x3 = modP(r * r - h3 - 2n * u1h2);
245
- const y3 = modP(r * (u1h2 - x3) - modP(s1 * h3));
246
- const z3 = modP(h * modP(p.z * q.z));
247
- return { x: x3, y: y3, z: z3 };
248
- }
249
- function pointMul(base, scalar) {
250
- let res = jacInfinity;
251
- let addend = base;
252
- let k = scalar;
253
- while (k > 0n) {
254
- if ((k & 1n) === 1n)
255
- res = pointAdd(res, addend);
256
- addend = pointDouble(addend);
257
- k >>= 1n;
258
- }
259
- return res;
260
- }
261
- function toAffine(p) {
262
- if (p.z === 0n)
263
- return null;
264
- const invZ = modInvP(p.z);
265
- const invZ2 = modP(invZ * invZ);
266
- const invZ3 = modP(invZ2 * invZ);
267
- return { x: modP(p.x * invZ2), y: modP(p.y * invZ3) };
268
- }
269
- /** @internal */
270
- export function schnorrPublicKey(secretKey32) {
271
- if (secretKey32.byteLength !== 32)
272
- throw new RangeError('Expected 32-byte secret key');
273
- const d0 = bytesToBigInt(secretKey32);
274
- if (d0 <= 0n || d0 >= secpN)
275
- throw new RangeError('Secret key out of range');
276
- const p = toAffine(pointMul(jacG, d0));
277
- if (!p)
278
- throw new Error('Invalid point');
279
- return bigIntTo32Bytes(p.x);
280
- }
281
- /** @internal */
282
- export function schnorrSign(msg32, secretKey32, auxRand32 = crypto.getRandomValues(new Uint8Array(32))) {
283
- if (msg32.byteLength !== 32 || secretKey32.byteLength !== 32 || auxRand32.byteLength !== 32) {
284
- throw new RangeError('Expected 32-byte inputs for BIP-340 schnorrSign');
285
- }
286
- const d0 = bytesToBigInt(secretKey32);
287
- if (d0 <= 0n || d0 >= secpN)
288
- throw new RangeError('Secret key out of range');
289
- const p = toAffine(pointMul(jacG, d0));
290
- if (!p)
291
- throw new Error('Invalid public point');
292
- const d = (p.y & 1n) === 0n ? d0 : secpN - d0;
293
- const pkBytes = bigIntTo32Bytes(p.x);
294
- const dBytes = bigIntTo32Bytes(d);
295
- const tags = getTagHashes();
296
- let aux = auxRand32;
297
- for (let attempt = 0; attempt < 8; attempt++) {
298
- const tHash = taggedHash(tags.aux, aux);
299
- const t = new Uint8Array(32);
300
- for (let i = 0; i < 32; i++)
301
- t[i] = dBytes[i] ^ tHash[i];
302
- const rand = taggedHash(tags.nonce, t, pkBytes, msg32);
303
- const k0 = bytesToBigInt(rand) % secpN;
304
- if (k0 === 0n) {
305
- aux = crypto.getRandomValues(new Uint8Array(32));
306
- continue;
307
- }
308
- const rPoint = toAffine(pointMul(jacG, k0));
309
- if (!rPoint) {
310
- aux = crypto.getRandomValues(new Uint8Array(32));
311
- continue;
312
- }
313
- const k = (rPoint.y & 1n) === 0n ? k0 : secpN - k0;
314
- const rBytes = bigIntTo32Bytes(rPoint.x);
315
- const e = bytesToBigInt(taggedHash(tags.challenge, rBytes, pkBytes, msg32)) % secpN;
316
- const s = modN(k + modN(e * d));
317
- const sig = new Uint8Array(64);
318
- sig.set(rBytes, 0);
319
- sig.set(bigIntTo32Bytes(s), 32);
320
- return sig;
321
- }
322
- throw new Error('Failed to derive non-zero BIP-340 nonce');
323
- }
324
- /** @internal */
325
- export function verifySchnorr(sig64, msg32, pubkey32) {
326
- if (sig64.byteLength !== 64 || msg32.byteLength !== 32 || pubkey32.byteLength !== 32) {
327
- return false;
328
- }
329
- const px = bytesToBigInt(pubkey32);
330
- if (px >= secpP)
331
- return false;
332
- const r = bytesToBigInt(sig64.subarray(0, 32));
333
- if (r >= secpP)
334
- return false;
335
- const s = bytesToBigInt(sig64.subarray(32, 64));
336
- if (s >= secpN)
337
- return false;
338
- const c = modP(modP(px * modP(px * px)) + 7n);
339
- let py = modPow(c, sqrtExp, secpP);
340
- if (modP(py * py) !== c)
341
- return false;
342
- if ((py & 1n) === 1n)
343
- py = secpP - py;
344
- const tags = getTagHashes();
345
- const e = bytesToBigInt(taggedHash(tags.challenge, sig64.subarray(0, 32), pubkey32, msg32)) % secpN;
346
- const sG = pointMul(jacG, s);
347
- const negE = e === 0n ? 0n : secpN - e;
348
- const negEP = pointMul({ x: px, y: py, z: 1n }, negE);
349
- const rPoint = toAffine(pointAdd(sG, negEP));
350
- if (!rPoint || (rPoint.y & 1n) === 1n)
351
- return false;
352
- return rPoint.x === r;
353
- }
354
- function generateSessionKeypair() {
355
- for (;;) {
356
- const sk = crypto.getRandomValues(new Uint8Array(32));
357
- const d0 = bytesToBigInt(sk);
358
- if (d0 > 0n && d0 < secpN) {
359
- return { secretKey: sk, pubkeyHex: bytesToHex(schnorrPublicKey(sk)) };
360
- }
361
- }
362
- }
363
24
  /** @internal */
364
25
  export function createSignedNostrEvent(secretKey, pubkeyHex, kind, tags, content, createdAt = Math.floor(Date.now() / 1000)) {
365
26
  const commitment = JSON.stringify([0, pubkeyHex, createdAt, kind, tags, content]);
@@ -375,19 +36,6 @@ export function createSignedNostrEvent(secretKey, pubkeyHex, kind, tags, content
375
36
  sig: bytesToHex(sigBytes)
376
37
  };
377
38
  }
378
- function normalizeWsUrl(raw) {
379
- let parsed;
380
- try {
381
- parsed = new URL(raw);
382
- }
383
- catch {
384
- throw new TypeError('Invalid Nostr relay URL');
385
- }
386
- if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
387
- throw new TypeError('Nostr relay URL must use ws: or wss:');
388
- }
389
- return parsed.toString();
390
- }
391
39
  function extractMatchingTags(rawTags) {
392
40
  if (!Array.isArray(rawTags) || rawTags.length === 0 || rawTags.length > 8)
393
41
  return null;
@@ -414,13 +62,9 @@ export function nostrSignaling(options = {}) {
414
62
  const rawUrls = [...(options.urls ?? defaultNostrRelays)];
415
63
  if (rawUrls.length === 0)
416
64
  throw new RangeError('At least one Nostr relay URL is required');
417
- const urls = rawUrls.map(normalizeWsUrl);
65
+ const urls = rawUrls.map((u) => normalizeWsRelayUrl(u, 'Invalid Nostr relay URL', 'Nostr relay URL must use ws: or wss:'));
418
66
  const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultHandshakeTimeoutMs;
419
- if (!Number.isSafeInteger(handshakeTimeoutMs) ||
420
- handshakeTimeoutMs <= 0 ||
421
- handshakeTimeoutMs > 2_147_483_647) {
422
- throw new RangeError('Invalid Nostr handshake timeout');
423
- }
67
+ validatePositiveTimeout(handshakeTimeoutMs, 'Invalid Nostr handshake timeout');
424
68
  if (options.appId !== undefined &&
425
69
  (typeof options.appId !== 'string' || !appIdPattern.test(options.appId))) {
426
70
  throw new TypeError('Invalid appId');
@@ -459,26 +103,17 @@ export function nostrSignaling(options = {}) {
459
103
  let roomTag = privateTopic ? '' : 'mp1_' + namespaceHash(baseScope);
460
104
  let inboxTag = privateTopic ? '' : roomTag + ':' + discovery.self;
461
105
  const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
462
- const seen = new Map();
463
106
  const seenEventIds = new Map();
464
107
  const inFlightEventIds = new Set();
465
108
  const replayGuard = createReplayGuard();
466
- const readySockets = new Set();
467
- const allSockets = new Set();
468
109
  const subIdsBySocket = new Map();
469
- const reconnectTimers = new Set();
470
- let closed = false;
471
- let reportedOnline = false;
472
- let reportedOffline = false;
473
- let initialPending = urls.length;
474
- let msgSeq = 0;
110
+ let subMapSnapshot = new Map();
475
111
  let pendingDecryptCount = 0;
476
112
  let verifyWindowStart = 0;
477
113
  let verifyCount = 0;
478
- let lastDecryptErrorAt = -Infinity;
479
- let lastClockSkewErrorAt = -Infinity;
480
- let resolvedKey;
481
- const keysPromise = password !== undefined ? deriveSignalingKeys(password, baseScope) : undefined;
114
+ const emitError = createErrorThrottle(discovery);
115
+ const emitDecryptFailed = () => emitError('decrypt-failed', 'Failed to decrypt Nostr signaling message');
116
+ const emitClockSkew = () => emitError('clock-skew', 'Nostr signaling message rejected due to system clock skew (>60s)');
482
117
  const recordEventId = (eventId, now = Date.now()) => {
483
118
  if (seenEventIds.size >= maxSeenEventIds) {
484
119
  const oldest = seenEventIds.keys().next().value;
@@ -488,76 +123,33 @@ export function nostrSignaling(options = {}) {
488
123
  seenEventIds.delete(eventId);
489
124
  seenEventIds.set(eventId, now);
490
125
  };
491
- const emitDecryptFailed = () => {
492
- const now = Date.now();
493
- if (now - lastDecryptErrorAt >= errorCooldownMs) {
494
- lastDecryptErrorAt = now;
495
- discovery.error?.('decrypt-failed', 'Failed to decrypt Nostr signaling message');
496
- }
497
- };
498
- const emitClockSkew = () => {
499
- const now = Date.now();
500
- if (now - lastClockSkewErrorAt >= errorCooldownMs) {
501
- lastClockSkewErrorAt = now;
502
- discovery.error?.('clock-skew', 'Nostr signaling message rejected due to system clock skew (>60s)');
503
- }
504
- };
505
- const roster = () => discovery.roster([...seen.keys()]);
506
- const touch = (id) => {
507
- const known = seen.has(id);
508
- if (!known && seen.size >= maxSeenPeers) {
509
- const oldest = seen.keys().next().value;
510
- if (oldest !== undefined)
511
- seen.delete(oldest);
512
- }
513
- seen.delete(id);
514
- seen.set(id, Date.now());
515
- if (!known)
516
- roster();
517
- return known;
518
- };
519
- const updateStatus = () => {
520
- if (closed)
521
- return;
522
- const online = readySockets.size > 0;
523
- if (online && !reportedOnline) {
524
- reportedOnline = true;
525
- reportedOffline = false;
526
- discovery.status('online');
527
- }
528
- else if (!online && (reportedOnline || (initialPending === 0 && !reportedOffline))) {
529
- reportedOnline = false;
530
- reportedOffline = true;
531
- const reason = 'All Nostr relays disconnected';
532
- discovery.status('offline', reason);
533
- discovery.error?.('signaling-error', reason);
534
- }
535
- };
126
+ const buildSignedFrame = (tag, content) => JSON.stringify([
127
+ 'EVENT',
128
+ createSignedNostrEvent(secretKey, pubkeyHex, ephemeralKind, [['t', tag]], content)
129
+ ]);
130
+ const presence = createPresenceTracker(discovery, (to) => {
131
+ void publishEvent({ type: 'present', to });
132
+ });
536
133
  const publishEvent = async (body, targetSockets, fixedMid) => {
537
- if (closed || !roomTag)
134
+ if (pool.isClosed() || !roomTag)
538
135
  return;
539
136
  const targetTag = body.to ? roomTag + ':' + body.to : roomTag;
540
- const mid = fixedMid ?? discovery.self.slice(0, 8) + ':' + ++msgSeq;
137
+ const mid = fixedMid ?? pool.nextMid();
541
138
  const plainJson = JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() });
542
139
  let content;
543
140
  try {
544
- const key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
545
- if (key) {
546
- const boxed = await sealPayload(key, encoder.encode(plainJson), 'meshpost/1/nostr:' + targetTag);
547
- content = toBase64Url(boxed);
548
- }
549
- else {
550
- content = plainJson;
551
- }
141
+ const key = await pool.getKey();
142
+ content = key
143
+ ? toBase64Url(await sealPayload(key, encoder.encode(plainJson), 'meshpost/1/nostr:' + targetTag))
144
+ : plainJson;
552
145
  }
553
146
  catch {
554
147
  return;
555
148
  }
556
- if (closed)
149
+ if (pool.isClosed())
557
150
  return;
558
- const event = createSignedNostrEvent(secretKey, pubkeyHex, ephemeralKind, [['t', targetTag]], content);
559
- const frame = JSON.stringify(['EVENT', event]);
560
- for (const ws of targetSockets ?? readySockets) {
151
+ const frame = buildSignedFrame(targetTag, content);
152
+ for (const ws of targetSockets ?? pool.readySockets) {
561
153
  if (ws.readyState === wsOpen) {
562
154
  try {
563
155
  ws.send(frame);
@@ -568,33 +160,8 @@ export function nostrSignaling(options = {}) {
568
160
  }
569
161
  }
570
162
  };
571
- const dispatchVerifiedData = (data) => {
572
- switch (data.type) {
573
- case 'hello':
574
- touch(data.from);
575
- void publishEvent({ type: 'present', to: data.from });
576
- break;
577
- case 'heartbeat':
578
- if (!touch(data.from))
579
- void publishEvent({ type: 'present', to: data.from });
580
- break;
581
- case 'present':
582
- touch(data.from);
583
- break;
584
- case 'bye':
585
- if (seen.delete(data.from))
586
- roster();
587
- break;
588
- case 'signal':
589
- if (isSignal(data.signal)) {
590
- touch(data.from);
591
- discovery.receive(data.from, data.signal);
592
- }
593
- break;
594
- }
595
- };
596
163
  const handleIncomingEvent = (rawEv) => {
597
- if (closed || !roomTag || !rawEv || typeof rawEv !== 'object')
164
+ if (pool.isClosed() || !roomTag || !rawEv || typeof rawEv !== 'object')
598
165
  return;
599
166
  const ev = rawEv;
600
167
  if (ev.kind !== ephemeralKind ||
@@ -626,7 +193,7 @@ export function nostrSignaling(options = {}) {
626
193
  const sigHex = ev.sig;
627
194
  const peerPubkeyHex = ev.pubkey;
628
195
  const content = ev.content;
629
- if (keysPromise) {
196
+ if (password !== undefined) {
630
197
  const boxed = fromBase64Url(content);
631
198
  if (!boxed) {
632
199
  emitDecryptFailed();
@@ -638,11 +205,11 @@ export function nostrSignaling(options = {}) {
638
205
  inFlightEventIds.add(eventId);
639
206
  void (async () => {
640
207
  try {
641
- const key = resolvedKey ?? (await keysPromise).aeadKey;
642
- if (closed || seenEventIds.has(eventId))
208
+ const key = await pool.getKey();
209
+ if (!key || pool.isClosed() || seenEventIds.has(eventId))
643
210
  return;
644
211
  const plain = await openPayload(key, boxed, 'meshpost/1/nostr:' + tTag);
645
- if (closed)
212
+ if (pool.isClosed())
646
213
  return;
647
214
  if (!plain) {
648
215
  emitDecryptFailed();
@@ -669,7 +236,7 @@ export function nostrSignaling(options = {}) {
669
236
  }
670
237
  if (check !== 'ok')
671
238
  return;
672
- dispatchVerifiedData(data);
239
+ presence.dispatch(data);
673
240
  }
674
241
  catch {
675
242
  // Ignore unexpected errors.
@@ -710,299 +277,150 @@ export function nostrSignaling(options = {}) {
710
277
  if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid, now)) {
711
278
  return;
712
279
  }
713
- dispatchVerifiedData(data);
280
+ presence.dispatch(data);
714
281
  };
715
- const connectRelay = (url, attempt = 0, isInitial = true) => {
716
- if (closed || !roomTag)
717
- return;
718
- let settledInitial = !isInitial;
719
- const settleInitial = () => {
720
- if (!settledInitial) {
721
- settledInitial = true;
722
- initialPending = Math.max(0, initialPending - 1);
723
- }
724
- };
725
- let ws;
726
- try {
727
- ws = new WsCtor(url);
728
- }
729
- catch {
730
- settleInitial();
731
- updateStatus();
732
- return;
733
- }
734
- allSockets.add(ws);
735
- const subId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
736
- subIdsBySocket.set(ws, subId);
737
- let handshakeTimer;
738
- let keepaliveTimer;
739
- let subscribed = false;
740
- let awaitingKeepalive = false;
741
- let lastFrameAt = Date.now();
742
- const abortSocket = () => {
743
- try {
744
- ws.close();
745
- }
746
- catch {
747
- // Ignore close errors.
748
- }
749
- };
750
- const sendJson = (payload) => {
751
- if (ws.readyState !== wsOpen)
752
- return false;
753
- try {
754
- ws.send(JSON.stringify(payload));
755
- return true;
756
- }
757
- catch {
758
- abortSocket();
759
- return false;
760
- }
761
- };
762
- handshakeTimer = setTimeout(() => {
763
- if (!subscribed)
764
- abortSocket();
765
- }, handshakeTimeoutMs);
766
- const cleanup = () => {
767
- if (handshakeTimer)
768
- clearTimeout(handshakeTimer);
769
- if (keepaliveTimer)
770
- clearInterval(keepaliveTimer);
771
- allSockets.delete(ws);
772
- subIdsBySocket.delete(ws);
773
- const wasReady = readySockets.delete(ws);
774
- settleInitial();
775
- if (wasReady || initialPending === 0)
776
- updateStatus();
777
- if (!closed) {
778
- const base = Math.min(15_000, 1_000 * 2 ** Math.min(attempt, 4));
779
- const delay = Math.round(base * (0.75 + Math.random() * 0.5));
780
- const timer = setTimeout(() => {
781
- reconnectTimers.delete(timer);
782
- connectRelay(url, attempt + 1, false);
783
- }, delay);
784
- reconnectTimers.add(timer);
785
- }
786
- };
787
- ws.onopen = () => {
788
- if (closed) {
789
- abortSocket();
790
- return;
791
- }
792
- lastFrameAt = Date.now();
793
- sendJson([
794
- 'REQ',
795
- subId,
796
- {
797
- kinds: [ephemeralKind],
798
- '#t': [roomTag, inboxTag],
799
- since: Math.floor(Date.now() / 1000) - 60
282
+ const pool = createRelayPool({
283
+ discovery,
284
+ urls,
285
+ handshakeTimeoutMs,
286
+ offlineReason: 'All Nostr relays disconnected',
287
+ password,
288
+ privateTopic,
289
+ baseScope,
290
+ createSocket: (url) => new WsCtor(url),
291
+ attachSocket(ws, controls) {
292
+ const subId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
293
+ subIdsBySocket.set(ws, subId);
294
+ let keepaliveTimer;
295
+ let subscribed = false;
296
+ let awaitingKeepalive = false;
297
+ let lastFrameAt = Date.now();
298
+ const sendJson = (payload) => {
299
+ if (ws.readyState !== wsOpen)
300
+ return false;
301
+ try {
302
+ ws.send(JSON.stringify(payload));
303
+ return true;
800
304
  }
801
- ]);
802
- };
803
- ws.onmessage = ({ data }) => {
804
- if (closed || typeof data !== 'string' || data.length > maxFrameChars)
805
- return;
806
- lastFrameAt = Date.now();
807
- awaitingKeepalive = false;
808
- let msg;
809
- try {
810
- msg = JSON.parse(data);
811
- }
812
- catch {
813
- return;
814
- }
815
- if (!Array.isArray(msg) || typeof msg[0] !== 'string')
816
- return;
817
- const kind = msg[0];
818
- if (kind === 'EOSE' && msg[1] === subId) {
819
- if (!subscribed) {
820
- subscribed = true;
821
- if (handshakeTimer)
822
- clearTimeout(handshakeTimer);
823
- handshakeTimer = undefined;
824
- attempt = 0;
825
- settleInitial();
826
- readySockets.add(ws);
827
- updateStatus();
828
- void publishEvent({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
829
- keepaliveTimer = setInterval(() => {
830
- if (ws.readyState !== wsOpen)
831
- return;
832
- if (awaitingKeepalive) {
833
- abortSocket();
834
- return;
835
- }
836
- if (Date.now() - lastFrameAt >= keepaliveIntervalMs) {
837
- awaitingKeepalive = true;
838
- sendJson([
839
- 'REQ',
840
- subId,
841
- {
842
- kinds: [ephemeralKind],
843
- '#t': [roomTag, inboxTag],
844
- since: Math.floor(Date.now() / 1000)
845
- }
846
- ]);
847
- }
848
- }, keepaliveIntervalMs);
305
+ catch {
306
+ controls.abort();
307
+ return false;
849
308
  }
850
- }
851
- else if (kind === 'EVENT' && msg[1] === subId) {
852
- if (subscribed)
853
- handleIncomingEvent(msg[2]);
854
- }
855
- else if (kind === 'CLOSED' && msg[1] === subId) {
856
- abortSocket();
857
- }
858
- };
859
- ws.onerror = abortSocket;
860
- ws.onclose = cleanup;
861
- };
862
- const leaseTimer = setInterval(() => {
863
- if (closed)
864
- return;
865
- const now = Date.now();
866
- let changed = false;
867
- for (const [id, last] of seen) {
868
- if (now - last > 30_000) {
869
- seen.delete(id);
870
- changed = true;
871
- }
872
- }
873
- if (changed)
874
- roster();
875
- for (const [evId, at] of seenEventIds) {
876
- if (now - at >= 120_000)
877
- seenEventIds.delete(evId);
878
- }
879
- replayGuard.prune(now);
880
- if (readySockets.size > 0)
881
- void publishEvent({ type: 'heartbeat' });
882
- }, 5_000);
883
- if (keysPromise && privateTopic) {
884
- void keysPromise
885
- .then((keys) => {
886
- if (closed)
887
- return;
888
- roomTag = 'mp1_p_' + keys.privateId;
889
- inboxTag = roomTag + ':' + discovery.self;
890
- resolvedKey = keys.aeadKey;
891
- for (const url of urls)
892
- connectRelay(url);
893
- })
894
- .catch(() => {
895
- if (closed)
896
- return;
897
- initialPending = 0;
898
- updateStatus();
899
- });
900
- }
901
- else {
902
- if (keysPromise) {
903
- void keysPromise
904
- .then((keys) => {
905
- resolvedKey = keys.aeadKey;
906
- })
907
- .catch(() => {
908
- if (closed)
309
+ };
310
+ ws.onopen = () => {
311
+ if (pool.isClosed()) {
312
+ controls.abort();
909
313
  return;
910
- initialPending = 0;
911
- for (const ws of [...allSockets]) {
912
- try {
913
- ws.close();
914
- }
915
- catch {
916
- // Ignore close errors.
917
- }
918
314
  }
919
- updateStatus();
920
- });
921
- }
922
- queueMicrotask(() => {
923
- if (closed)
924
- return;
925
- for (const url of urls)
926
- connectRelay(url);
927
- });
928
- }
929
- return {
930
- trickle: true,
931
- send(to, signal) {
932
- if (closed || readySockets.size === 0)
933
- return false;
934
- void publishEvent({ type: 'signal', to, signal });
935
- return true;
936
- },
937
- close() {
938
- if (closed)
939
- return;
940
- closed = true;
941
- clearInterval(leaseTimer);
942
- for (const timer of reconnectTimers)
943
- clearTimeout(timer);
944
- reconnectTimers.clear();
945
- const socketsToClose = [...allSockets];
946
- const readyToNotify = [...readySockets];
947
- const subMapSnapshot = new Map(subIdsBySocket);
948
- allSockets.clear();
949
- readySockets.clear();
950
- subIdsBySocket.clear();
951
- const shutdownSocket = (ws, byeFrame) => {
952
- try {
953
- if (ws.readyState === wsOpen) {
954
- if (byeFrame)
955
- ws.send(byeFrame);
956
- const subId = subMapSnapshot.get(ws);
957
- if (subId)
958
- ws.send(JSON.stringify(['CLOSE', subId]));
315
+ lastFrameAt = Date.now();
316
+ sendJson([
317
+ 'REQ',
318
+ subId,
319
+ {
320
+ kinds: [ephemeralKind],
321
+ '#t': [roomTag, inboxTag],
322
+ since: Math.floor(Date.now() / 1000) - 60
959
323
  }
960
- ws.close();
324
+ ]);
325
+ };
326
+ ws.onmessage = ({ data }) => {
327
+ if (pool.isClosed() || typeof data !== 'string' || data.length > maxFrameChars)
328
+ return;
329
+ lastFrameAt = Date.now();
330
+ awaitingKeepalive = false;
331
+ let msg;
332
+ try {
333
+ msg = JSON.parse(data);
961
334
  }
962
335
  catch {
963
- // Ignore shutdown errors.
336
+ return;
964
337
  }
965
- };
966
- const byePlainJson = JSON.stringify({
967
- type: 'bye',
968
- from: discovery.self,
969
- mid: discovery.self.slice(0, 8) + ':' + ++msgSeq,
970
- ts: Date.now()
971
- });
972
- if (!keysPromise && roomTag) {
973
- const byeEv = createSignedNostrEvent(secretKey, pubkeyHex, ephemeralKind, [['t', roomTag]], byePlainJson);
974
- const byeFrame = JSON.stringify(['EVENT', byeEv]);
975
- for (const ws of socketsToClose) {
976
- shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
338
+ if (!Array.isArray(msg) || typeof msg[0] !== 'string')
339
+ return;
340
+ const kind = msg[0];
341
+ if (kind === 'EOSE' && msg[1] === subId) {
342
+ if (!subscribed) {
343
+ subscribed = true;
344
+ controls.markReady();
345
+ keepaliveTimer = setInterval(() => {
346
+ if (ws.readyState !== wsOpen)
347
+ return;
348
+ if (awaitingKeepalive) {
349
+ controls.abort();
350
+ return;
351
+ }
352
+ if (Date.now() - lastFrameAt >= keepaliveIntervalMs) {
353
+ awaitingKeepalive = true;
354
+ sendJson([
355
+ 'REQ',
356
+ subId,
357
+ {
358
+ kinds: [ephemeralKind],
359
+ '#t': [roomTag, inboxTag],
360
+ since: Math.floor(Date.now() / 1000)
361
+ }
362
+ ]);
363
+ }
364
+ }, keepaliveIntervalMs);
365
+ }
366
+ }
367
+ else if (kind === 'EVENT' && msg[1] === subId) {
368
+ if (subscribed)
369
+ handleIncomingEvent(msg[2]);
977
370
  }
371
+ else if (kind === 'CLOSED' && msg[1] === subId) {
372
+ controls.abort();
373
+ }
374
+ };
375
+ return () => {
376
+ if (keepaliveTimer)
377
+ clearInterval(keepaliveTimer);
378
+ subIdsBySocket.delete(ws);
379
+ };
380
+ },
381
+ onReady(ws, isInitial) {
382
+ void publishEvent({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
383
+ },
384
+ onPrivateKeys(keys) {
385
+ roomTag = 'mp1_p_' + keys.privateId;
386
+ inboxTag = roomTag + ':' + discovery.self;
387
+ },
388
+ onSweep(now, hasReadySockets) {
389
+ presence.prune(now);
390
+ for (const [evId, at] of seenEventIds) {
391
+ if (now - at >= 120_000)
392
+ seenEventIds.delete(evId);
978
393
  }
979
- else if (resolvedKey && roomTag && readyToNotify.length > 0) {
980
- const nonReady = socketsToClose.filter((ws) => !readyToNotify.includes(ws));
981
- for (const ws of nonReady)
982
- shutdownSocket(ws);
983
- const fallbackTimer = setTimeout(() => {
984
- for (const ws of readyToNotify)
985
- shutdownSocket(ws);
986
- }, 250);
987
- void sealPayload(resolvedKey, encoder.encode(byePlainJson), 'meshpost/1/nostr:' + roomTag)
988
- .then((boxed) => {
989
- clearTimeout(fallbackTimer);
990
- const byeEv = createSignedNostrEvent(secretKey, pubkeyHex, ephemeralKind, [['t', roomTag]], toBase64Url(boxed));
991
- const byeFrame = JSON.stringify(['EVENT', byeEv]);
992
- for (const ws of readyToNotify)
993
- shutdownSocket(ws, byeFrame);
994
- })
995
- .catch(() => {
996
- clearTimeout(fallbackTimer);
997
- for (const ws of readyToNotify)
998
- shutdownSocket(ws);
999
- });
394
+ replayGuard.prune(now);
395
+ if (hasReadySockets)
396
+ void publishEvent({ type: 'heartbeat' });
397
+ },
398
+ sendSignal(to, signal) {
399
+ void publishEvent({ type: 'signal', to, signal });
400
+ },
401
+ buildPlainBye: (byeJson) => (roomTag ? buildSignedFrame(roomTag, byeJson) : undefined),
402
+ buildEncryptedBye: (boxed) => roomTag ? buildSignedFrame(roomTag, toBase64Url(boxed)) : undefined,
403
+ byeAad: () => (roomTag ? 'meshpost/1/nostr:' + roomTag : undefined),
404
+ onBeforeClose() {
405
+ subMapSnapshot = new Map(subIdsBySocket);
406
+ subIdsBySocket.clear();
407
+ },
408
+ shutdownSocket(ws, byeFrame) {
409
+ try {
410
+ if (ws.readyState === wsOpen) {
411
+ if (byeFrame)
412
+ ws.send(byeFrame);
413
+ const subId = subMapSnapshot.get(ws);
414
+ if (subId)
415
+ ws.send(JSON.stringify(['CLOSE', subId]));
416
+ }
417
+ ws.close();
1000
418
  }
1001
- else {
1002
- for (const ws of socketsToClose)
1003
- shutdownSocket(ws);
419
+ catch {
420
+ // Ignore shutdown errors.
1004
421
  }
1005
422
  }
1006
- };
423
+ });
424
+ return pool.session;
1007
425
  };
1008
426
  }