@dimchansky/meshpost 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/nostr.js ADDED
@@ -0,0 +1,1008 @@
1
+ import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, fromBase64Url, maxMidLength, openPayload, sealPayload, toBase64Url } from './crypto.js';
2
+ import { isSignal, isUuid, namespaceHash } from './signaling.js';
3
+ /** Built-in public port-443 Nostr WebSocket relays used by default. */
4
+ export const defaultNostrRelays = Object.freeze([
5
+ 'wss://relay.damus.io',
6
+ 'wss://nos.lol',
7
+ 'wss://relay.primal.net'
8
+ ]);
9
+ const wsOpen = 1;
10
+ const encoder = new TextEncoder();
11
+ const decoder = new TextDecoder();
12
+ const ephemeralKind = 25050;
13
+ const maxFrameChars = 128 * 1024;
14
+ const maxContentChars = 96 * 1024;
15
+ const maxSeenPeers = 256;
16
+ const maxSeenEventIds = 2048;
17
+ const maxDecryptQueueDepth = 64;
18
+ const maxSchnorrVerifiesPerSec = 64;
19
+ const maxCreatedAtSkewSec = 120;
20
+ const defaultHandshakeTimeoutMs = 10_000;
21
+ const keepaliveIntervalMs = 25_000;
22
+ 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
+ /** @internal */
364
+ export function createSignedNostrEvent(secretKey, pubkeyHex, kind, tags, content, createdAt = Math.floor(Date.now() / 1000)) {
365
+ const commitment = JSON.stringify([0, pubkeyHex, createdAt, kind, tags, content]);
366
+ const idBytes = sha256(encoder.encode(commitment));
367
+ const sigBytes = schnorrSign(idBytes, secretKey);
368
+ return {
369
+ id: bytesToHex(idBytes),
370
+ pubkey: pubkeyHex,
371
+ created_at: createdAt,
372
+ kind,
373
+ tags,
374
+ content,
375
+ sig: bytesToHex(sigBytes)
376
+ };
377
+ }
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
+ function extractMatchingTags(rawTags) {
392
+ if (!Array.isArray(rawTags) || rawTags.length === 0 || rawTags.length > 8)
393
+ return null;
394
+ let foundTag = null;
395
+ for (const item of rawTags) {
396
+ if (!Array.isArray(item) || item.length === 0 || item.length > 4)
397
+ return null;
398
+ for (const elem of item) {
399
+ if (typeof elem !== 'string' || elem.length > 256)
400
+ return null;
401
+ }
402
+ if (item[0] === 't' && typeof item[1] === 'string' && foundTag === null) {
403
+ foundTag = item[1];
404
+ }
405
+ }
406
+ return foundTag;
407
+ }
408
+ /**
409
+ * Zero-backend port-443 signaling over public (or custom) NIP-01 Nostr relays.
410
+ * Uses ephemeral events (`kind: 25050` — never persisted to disk by relays), pure-TS BIP-340 Schnorr
411
+ * signatures, multi-relay redundancy, and `AES-256-GCM` E2E encryption when `password` is provided.
412
+ */
413
+ export function nostrSignaling(options = {}) {
414
+ const rawUrls = [...(options.urls ?? defaultNostrRelays)];
415
+ if (rawUrls.length === 0)
416
+ throw new RangeError('At least one Nostr relay URL is required');
417
+ const urls = rawUrls.map(normalizeWsUrl);
418
+ 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
+ }
424
+ if (options.appId !== undefined &&
425
+ (typeof options.appId !== 'string' || !appIdPattern.test(options.appId))) {
426
+ throw new TypeError('Invalid appId');
427
+ }
428
+ if (options.password !== undefined &&
429
+ (typeof options.password !== 'string' || options.password.length === 0)) {
430
+ throw new TypeError('Invalid password');
431
+ }
432
+ if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
433
+ throw new TypeError('Invalid privateTopic option');
434
+ }
435
+ if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
436
+ throw new TypeError('Invalid WebSocket constructor');
437
+ }
438
+ return (discovery) => {
439
+ const WsCtor = options.WebSocket ?? globalThis.WebSocket;
440
+ if (typeof WsCtor !== 'function') {
441
+ throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
442
+ }
443
+ const appId = options.appId ?? discovery.appId;
444
+ const password = options.password ?? discovery.password;
445
+ const privateTopic = options.privateTopic ?? false;
446
+ if (privateTopic && password === undefined) {
447
+ throw new TypeError('privateTopic requires a room password');
448
+ }
449
+ if (password !== undefined) {
450
+ if (typeof password !== 'string' || password.length === 0) {
451
+ throw new TypeError('Invalid password');
452
+ }
453
+ if (!globalThis.crypto?.subtle) {
454
+ throw new Error('Password encryption requires a secure context (crypto.subtle)');
455
+ }
456
+ }
457
+ const { secretKey, pubkeyHex } = generateSessionKeypair();
458
+ const baseScope = appId + ':' + discovery.room;
459
+ let roomTag = privateTopic ? '' : 'mp1_' + namespaceHash(baseScope);
460
+ let inboxTag = privateTopic ? '' : roomTag + ':' + discovery.self;
461
+ const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
462
+ const seen = new Map();
463
+ const seenEventIds = new Map();
464
+ const inFlightEventIds = new Set();
465
+ const replayGuard = createReplayGuard();
466
+ const readySockets = new Set();
467
+ const allSockets = new Set();
468
+ 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;
475
+ let pendingDecryptCount = 0;
476
+ let verifyWindowStart = 0;
477
+ let verifyCount = 0;
478
+ let lastDecryptErrorAt = -Infinity;
479
+ let lastClockSkewErrorAt = -Infinity;
480
+ let resolvedKey;
481
+ const keysPromise = password !== undefined ? deriveSignalingKeys(password, baseScope) : undefined;
482
+ const recordEventId = (eventId, now = Date.now()) => {
483
+ if (seenEventIds.size >= maxSeenEventIds) {
484
+ const oldest = seenEventIds.keys().next().value;
485
+ if (oldest !== undefined)
486
+ seenEventIds.delete(oldest);
487
+ }
488
+ seenEventIds.delete(eventId);
489
+ seenEventIds.set(eventId, now);
490
+ };
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
+ };
536
+ const publishEvent = async (body, targetSockets, fixedMid) => {
537
+ if (closed || !roomTag)
538
+ return;
539
+ const targetTag = body.to ? roomTag + ':' + body.to : roomTag;
540
+ const mid = fixedMid ?? discovery.self.slice(0, 8) + ':' + ++msgSeq;
541
+ const plainJson = JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() });
542
+ let content;
543
+ 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
+ }
552
+ }
553
+ catch {
554
+ return;
555
+ }
556
+ if (closed)
557
+ 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) {
561
+ if (ws.readyState === wsOpen) {
562
+ try {
563
+ ws.send(frame);
564
+ }
565
+ catch {
566
+ // Socket closing; reconnect loop handles recovery.
567
+ }
568
+ }
569
+ }
570
+ };
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
+ const handleIncomingEvent = (rawEv) => {
597
+ if (closed || !roomTag || !rawEv || typeof rawEv !== 'object')
598
+ return;
599
+ const ev = rawEv;
600
+ if (ev.kind !== ephemeralKind ||
601
+ typeof ev.id !== 'string' ||
602
+ !hex64Pattern.test(ev.id) ||
603
+ typeof ev.pubkey !== 'string' ||
604
+ !hex64Pattern.test(ev.pubkey) ||
605
+ ev.pubkey === pubkeyHex ||
606
+ typeof ev.sig !== 'string' ||
607
+ !hex128Pattern.test(ev.sig) ||
608
+ typeof ev.created_at !== 'number' ||
609
+ !Number.isSafeInteger(ev.created_at) ||
610
+ Math.abs(Math.floor(Date.now() / 1000) - ev.created_at) > maxCreatedAtSkewSec ||
611
+ typeof ev.content !== 'string' ||
612
+ ev.content.length === 0 ||
613
+ ev.content.length > maxContentChars) {
614
+ return;
615
+ }
616
+ const tTag = extractMatchingTags(ev.tags);
617
+ if (tTag !== roomTag && tTag !== inboxTag)
618
+ return;
619
+ if (seenEventIds.has(ev.id) || inFlightEventIds.has(ev.id))
620
+ return;
621
+ const commitment = JSON.stringify([0, ev.pubkey, ev.created_at, ev.kind, ev.tags, ev.content]);
622
+ const idBytes = sha256(encoder.encode(commitment));
623
+ if (bytesToHex(idBytes) !== ev.id)
624
+ return;
625
+ const eventId = ev.id;
626
+ const sigHex = ev.sig;
627
+ const peerPubkeyHex = ev.pubkey;
628
+ const content = ev.content;
629
+ if (keysPromise) {
630
+ const boxed = fromBase64Url(content);
631
+ if (!boxed) {
632
+ emitDecryptFailed();
633
+ return;
634
+ }
635
+ if (pendingDecryptCount >= maxDecryptQueueDepth)
636
+ return;
637
+ pendingDecryptCount++;
638
+ inFlightEventIds.add(eventId);
639
+ void (async () => {
640
+ try {
641
+ const key = resolvedKey ?? (await keysPromise).aeadKey;
642
+ if (closed || seenEventIds.has(eventId))
643
+ return;
644
+ const plain = await openPayload(key, boxed, 'meshpost/1/nostr:' + tTag);
645
+ if (closed)
646
+ return;
647
+ if (!plain) {
648
+ emitDecryptFailed();
649
+ return;
650
+ }
651
+ if (!verifySchnorr(hexToBytes(sigHex), idBytes, hexToBytes(peerPubkeyHex)))
652
+ return;
653
+ recordEventId(eventId);
654
+ let data = null;
655
+ try {
656
+ data = JSON.parse(decoder.decode(plain));
657
+ }
658
+ catch {
659
+ return;
660
+ }
661
+ if (!data || !isUuid(data.from) || data.from === discovery.self)
662
+ return;
663
+ if (data.to !== undefined && data.to !== discovery.self)
664
+ return;
665
+ const check = replayGuard.checkAuthenticated(data.from, data);
666
+ if (check === 'clock-skew') {
667
+ emitClockSkew();
668
+ return;
669
+ }
670
+ if (check !== 'ok')
671
+ return;
672
+ dispatchVerifiedData(data);
673
+ }
674
+ catch {
675
+ // Ignore unexpected errors.
676
+ }
677
+ finally {
678
+ inFlightEventIds.delete(eventId);
679
+ pendingDecryptCount--;
680
+ }
681
+ })();
682
+ return;
683
+ }
684
+ const now = Date.now();
685
+ if (now - verifyWindowStart >= 1_000) {
686
+ verifyWindowStart = now;
687
+ verifyCount = 0;
688
+ }
689
+ if (verifyCount >= maxSchnorrVerifiesPerSec)
690
+ return;
691
+ verifyCount++;
692
+ if (!verifySchnorr(hexToBytes(sigHex), idBytes, hexToBytes(peerPubkeyHex)))
693
+ return;
694
+ recordEventId(eventId, now);
695
+ let data = null;
696
+ try {
697
+ data = JSON.parse(content);
698
+ }
699
+ catch {
700
+ return;
701
+ }
702
+ if (!data || !isUuid(data.from) || data.from === discovery.self)
703
+ return;
704
+ if (data.to !== undefined && data.to !== discovery.self)
705
+ return;
706
+ if (data.mid !== undefined &&
707
+ (typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength)) {
708
+ return;
709
+ }
710
+ if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid, now)) {
711
+ return;
712
+ }
713
+ dispatchVerifiedData(data);
714
+ };
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
800
+ }
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);
849
+ }
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)
909
+ return;
910
+ initialPending = 0;
911
+ for (const ws of [...allSockets]) {
912
+ try {
913
+ ws.close();
914
+ }
915
+ catch {
916
+ // Ignore close errors.
917
+ }
918
+ }
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]));
959
+ }
960
+ ws.close();
961
+ }
962
+ catch {
963
+ // Ignore shutdown errors.
964
+ }
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);
977
+ }
978
+ }
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
+ });
1000
+ }
1001
+ else {
1002
+ for (const ws of socketsToClose)
1003
+ shutdownSocket(ws);
1004
+ }
1005
+ }
1006
+ };
1007
+ };
1008
+ }