@dimchansky/meshpost 0.5.0 → 0.7.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.
- package/README.md +66 -544
- package/dist/bip340.d.ts +1 -0
- package/dist/bip340.js +346 -0
- package/dist/blob.d.ts +1 -1
- package/dist/blob.js +44 -45
- package/dist/channel.d.ts +4 -0
- package/dist/channel.js +19 -44
- package/dist/combine.d.ts +9 -2
- package/dist/combine.js +40 -57
- package/dist/crypto.js +10 -9
- package/dist/identity.d.ts +2 -0
- package/dist/identity.js +39 -71
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/listeners.js +18 -3
- package/dist/mqtt.js +211 -476
- package/dist/nostr.js +194 -836
- package/dist/peer-link.d.ts +1 -0
- package/dist/peer-link.js +983 -0
- package/dist/presence.d.ts +1 -0
- package/dist/presence.js +74 -0
- package/dist/public.d.ts +1 -1
- package/dist/public.js +25 -77
- package/dist/relay-core.d.ts +1 -0
- package/dist/relay-core.js +399 -0
- package/dist/room-reclaim.d.ts +1 -0
- package/dist/room-reclaim.js +115 -0
- package/dist/room-stats.d.ts +1 -0
- package/dist/room-stats.js +75 -0
- package/dist/room.js +245 -1218
- package/dist/rpc.js +25 -28
- package/dist/signaling.d.ts +8 -0
- package/dist/signaling.js +55 -0
- package/dist/state.js +23 -33
- package/dist/tabs.js +6 -50
- package/dist/voice-mic.d.ts +1 -0
- package/dist/voice-mic.js +496 -0
- package/dist/voice-remote.d.ts +1 -0
- package/dist/voice-remote.js +568 -0
- package/dist/voice.d.ts +19 -1
- package/dist/voice.js +95 -1036
- package/dist/ws.js +56 -197
- package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
- package/docs/api.md +219 -0
- package/docs/behavior.md +14 -8
- package/docs/guide.md +404 -0
- package/docs/signaling-and-production.md +312 -0
- package/docs/voice-and-media.md +193 -0
- package/package.json +6 -3
package/dist/nostr.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { bytesToHex, generateSessionKeypair, hex128Pattern, hex64Pattern, hexToBytes, schnorrSign, sha256, verifySchnorr } from './bip340.js';
|
|
2
|
+
import { fromBase64Url, toBase64Url } from './crypto.js';
|
|
3
|
+
import { createPresenceTracker } from './presence.js';
|
|
4
|
+
import { createRelayEnvelope, createRelayPool, normalizeWsRelayUrl, resolveSessionPassword, resolveSessionWebSocket, validateCommonSignalingOptions, validatePositiveTimeout } from './relay-core.js';
|
|
5
|
+
import { namespaceHash } from './signaling.js';
|
|
3
6
|
/** Built-in public port-443 Nostr WebSocket relays used by default. */
|
|
4
7
|
export const defaultNostrRelays = Object.freeze([
|
|
5
8
|
'wss://relay.damus.io',
|
|
@@ -8,358 +11,15 @@ export const defaultNostrRelays = Object.freeze([
|
|
|
8
11
|
]);
|
|
9
12
|
const wsOpen = 1;
|
|
10
13
|
const encoder = new TextEncoder();
|
|
11
|
-
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
|
-
const maxDecryptQueueDepth = 64;
|
|
18
18
|
const maxSchnorrVerifiesPerSec = 64;
|
|
19
19
|
const maxCreatedAtSkewSec = 120;
|
|
20
20
|
const defaultHandshakeTimeoutMs = 10_000;
|
|
21
21
|
const keepaliveIntervalMs = 25_000;
|
|
22
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
23
|
/** @internal */
|
|
364
24
|
export function createSignedNostrEvent(secretKey, pubkeyHex, kind, tags, content, createdAt = Math.floor(Date.now() / 1000)) {
|
|
365
25
|
const commitment = JSON.stringify([0, pubkeyHex, createdAt, kind, tags, content]);
|
|
@@ -375,19 +35,6 @@ export function createSignedNostrEvent(secretKey, pubkeyHex, kind, tags, content
|
|
|
375
35
|
sig: bytesToHex(sigBytes)
|
|
376
36
|
};
|
|
377
37
|
}
|
|
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
38
|
function extractMatchingTags(rawTags) {
|
|
392
39
|
if (!Array.isArray(rawTags) || rawTags.length === 0 || rawTags.length > 8)
|
|
393
40
|
return null;
|
|
@@ -414,71 +61,35 @@ export function nostrSignaling(options = {}) {
|
|
|
414
61
|
const rawUrls = [...(options.urls ?? defaultNostrRelays)];
|
|
415
62
|
if (rawUrls.length === 0)
|
|
416
63
|
throw new RangeError('At least one Nostr relay URL is required');
|
|
417
|
-
const urls = rawUrls.map(
|
|
64
|
+
const urls = rawUrls.map((u) => normalizeWsRelayUrl(u, 'Invalid Nostr relay URL', 'Nostr relay URL must use ws: or wss:'));
|
|
418
65
|
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultHandshakeTimeoutMs;
|
|
419
|
-
|
|
420
|
-
handshakeTimeoutMs <= 0 ||
|
|
421
|
-
handshakeTimeoutMs > 2_147_483_647) {
|
|
422
|
-
throw new RangeError('Invalid Nostr handshake timeout');
|
|
423
|
-
}
|
|
66
|
+
validatePositiveTimeout(handshakeTimeoutMs, 'Invalid Nostr handshake timeout');
|
|
424
67
|
if (options.appId !== undefined &&
|
|
425
68
|
(typeof options.appId !== 'string' || !appIdPattern.test(options.appId))) {
|
|
426
69
|
throw new TypeError('Invalid appId');
|
|
427
70
|
}
|
|
428
|
-
|
|
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
|
-
}
|
|
71
|
+
validateCommonSignalingOptions(options);
|
|
438
72
|
return (discovery) => {
|
|
439
|
-
const WsCtor = options.WebSocket
|
|
440
|
-
if (typeof WsCtor !== 'function') {
|
|
441
|
-
throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
|
|
442
|
-
}
|
|
73
|
+
const WsCtor = resolveSessionWebSocket(options.WebSocket);
|
|
443
74
|
const appId = options.appId ?? discovery.appId;
|
|
444
|
-
const password = options.password ?? discovery.password;
|
|
445
75
|
const privateTopic = options.privateTopic ?? false;
|
|
446
|
-
|
|
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
|
-
}
|
|
76
|
+
const { password } = resolveSessionPassword(options.password ?? discovery.password, privateTopic);
|
|
457
77
|
const { secretKey, pubkeyHex } = generateSessionKeypair();
|
|
458
78
|
const baseScope = appId + ':' + discovery.room;
|
|
459
79
|
let roomTag = privateTopic ? '' : 'mp1_' + namespaceHash(baseScope);
|
|
460
80
|
let inboxTag = privateTopic ? '' : roomTag + ':' + discovery.self;
|
|
461
81
|
const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
|
|
462
|
-
const seen = new Map();
|
|
463
82
|
const seenEventIds = new Map();
|
|
464
83
|
const inFlightEventIds = new Set();
|
|
465
|
-
const replayGuard = createReplayGuard();
|
|
466
|
-
const readySockets = new Set();
|
|
467
|
-
const allSockets = new Set();
|
|
468
84
|
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
85
|
let verifyWindowStart = 0;
|
|
477
86
|
let verifyCount = 0;
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
87
|
+
const envelope = createRelayEnvelope({
|
|
88
|
+
discovery,
|
|
89
|
+
password,
|
|
90
|
+
baseScope,
|
|
91
|
+
transportLabel: 'Nostr'
|
|
92
|
+
});
|
|
482
93
|
const recordEventId = (eventId, now = Date.now()) => {
|
|
483
94
|
if (seenEventIds.size >= maxSeenEventIds) {
|
|
484
95
|
const oldest = seenEventIds.keys().next().value;
|
|
@@ -488,76 +99,23 @@ export function nostrSignaling(options = {}) {
|
|
|
488
99
|
seenEventIds.delete(eventId);
|
|
489
100
|
seenEventIds.set(eventId, now);
|
|
490
101
|
};
|
|
491
|
-
const
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
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
|
-
};
|
|
102
|
+
const buildSignedFrame = (tag, content) => JSON.stringify([
|
|
103
|
+
'EVENT',
|
|
104
|
+
createSignedNostrEvent(secretKey, pubkeyHex, ephemeralKind, [['t', tag]], content)
|
|
105
|
+
]);
|
|
106
|
+
const presence = createPresenceTracker(discovery, (to) => {
|
|
107
|
+
void publishEvent({ type: 'present', to });
|
|
108
|
+
});
|
|
536
109
|
const publishEvent = async (body, targetSockets, fixedMid) => {
|
|
537
|
-
if (
|
|
110
|
+
if (pool.isClosed() || !roomTag)
|
|
538
111
|
return;
|
|
539
112
|
const targetTag = body.to ? roomTag + ':' + body.to : roomTag;
|
|
540
|
-
const
|
|
541
|
-
|
|
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)
|
|
113
|
+
const sealed = await envelope.sealJson(body, 'meshpost/1/nostr:' + targetTag, fixedMid);
|
|
114
|
+
if (!sealed || pool.isClosed())
|
|
557
115
|
return;
|
|
558
|
-
const
|
|
559
|
-
const frame =
|
|
560
|
-
for (const ws of targetSockets ?? readySockets) {
|
|
116
|
+
const content = envelope.isEncrypted ? toBase64Url(sealed.bytes) : sealed.plainJson;
|
|
117
|
+
const frame = buildSignedFrame(targetTag, content);
|
|
118
|
+
for (const ws of targetSockets ?? pool.readySockets) {
|
|
561
119
|
if (ws.readyState === wsOpen) {
|
|
562
120
|
try {
|
|
563
121
|
ws.send(frame);
|
|
@@ -568,33 +126,8 @@ export function nostrSignaling(options = {}) {
|
|
|
568
126
|
}
|
|
569
127
|
}
|
|
570
128
|
};
|
|
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
129
|
const handleIncomingEvent = (rawEv) => {
|
|
597
|
-
if (
|
|
130
|
+
if (pool.isClosed() || !roomTag || !rawEv || typeof rawEv !== 'object')
|
|
598
131
|
return;
|
|
599
132
|
const ev = rawEv;
|
|
600
133
|
if (ev.kind !== ephemeralKind ||
|
|
@@ -626,59 +159,31 @@ export function nostrSignaling(options = {}) {
|
|
|
626
159
|
const sigHex = ev.sig;
|
|
627
160
|
const peerPubkeyHex = ev.pubkey;
|
|
628
161
|
const content = ev.content;
|
|
629
|
-
if (
|
|
162
|
+
if (envelope.isEncrypted) {
|
|
630
163
|
const boxed = fromBase64Url(content);
|
|
631
164
|
if (!boxed) {
|
|
632
|
-
emitDecryptFailed();
|
|
165
|
+
envelope.emitDecryptFailed();
|
|
633
166
|
return;
|
|
634
167
|
}
|
|
635
|
-
if (pendingDecryptCount >= maxDecryptQueueDepth)
|
|
636
|
-
return;
|
|
637
|
-
pendingDecryptCount++;
|
|
638
168
|
inFlightEventIds.add(eventId);
|
|
639
|
-
void
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
if (closed)
|
|
646
|
-
return;
|
|
647
|
-
if (!plain) {
|
|
648
|
-
emitDecryptFailed();
|
|
649
|
-
return;
|
|
169
|
+
void envelope
|
|
170
|
+
.openEncrypted(boxed, 'meshpost/1/nostr:' + tTag, {
|
|
171
|
+
isClosed: () => pool.isClosed() || seenEventIds.has(eventId),
|
|
172
|
+
afterDecrypt() {
|
|
173
|
+
if (!verifySchnorr(hexToBytes(sigHex), idBytes, hexToBytes(peerPubkeyHex))) {
|
|
174
|
+
return false;
|
|
650
175
|
}
|
|
651
|
-
if (!verifySchnorr(hexToBytes(sigHex), idBytes, hexToBytes(peerPubkeyHex)))
|
|
652
|
-
return;
|
|
653
176
|
recordEventId(eventId);
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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 {
|
|
177
|
+
return true;
|
|
178
|
+
},
|
|
179
|
+
onFinally() {
|
|
678
180
|
inFlightEventIds.delete(eventId);
|
|
679
|
-
pendingDecryptCount--;
|
|
680
181
|
}
|
|
681
|
-
})
|
|
182
|
+
})
|
|
183
|
+
.then((data) => {
|
|
184
|
+
if (data && !pool.isClosed())
|
|
185
|
+
presence.dispatch(data);
|
|
186
|
+
});
|
|
682
187
|
return;
|
|
683
188
|
}
|
|
684
189
|
const now = Date.now();
|
|
@@ -692,317 +197,170 @@ export function nostrSignaling(options = {}) {
|
|
|
692
197
|
if (!verifySchnorr(hexToBytes(sigHex), idBytes, hexToBytes(peerPubkeyHex)))
|
|
693
198
|
return;
|
|
694
199
|
recordEventId(eventId, now);
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
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);
|
|
200
|
+
const data = envelope.parsePlaintext(content, now);
|
|
201
|
+
if (data)
|
|
202
|
+
presence.dispatch(data);
|
|
714
203
|
};
|
|
715
|
-
const
|
|
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;
|
|
204
|
+
const shutdownSocket = (ws, subId, byeFrame) => {
|
|
726
205
|
try {
|
|
727
|
-
ws
|
|
206
|
+
if (ws.readyState === wsOpen) {
|
|
207
|
+
if (byeFrame)
|
|
208
|
+
ws.send(byeFrame);
|
|
209
|
+
if (subId)
|
|
210
|
+
ws.send(JSON.stringify(['CLOSE', subId]));
|
|
211
|
+
}
|
|
212
|
+
ws.close();
|
|
728
213
|
}
|
|
729
214
|
catch {
|
|
730
|
-
|
|
731
|
-
updateStatus();
|
|
732
|
-
return;
|
|
215
|
+
// Ignore shutdown errors.
|
|
733
216
|
}
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
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
|
|
217
|
+
};
|
|
218
|
+
const pool = createRelayPool({
|
|
219
|
+
discovery,
|
|
220
|
+
urls,
|
|
221
|
+
handshakeTimeoutMs,
|
|
222
|
+
offlineReason: 'All Nostr relays disconnected',
|
|
223
|
+
envelope,
|
|
224
|
+
privateTopic,
|
|
225
|
+
createSocket: (url) => new WsCtor(url),
|
|
226
|
+
attachSocket(ws, controls) {
|
|
227
|
+
const subId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
|
|
228
|
+
subIdsBySocket.set(ws, subId);
|
|
229
|
+
let keepaliveTimer;
|
|
230
|
+
let subscribed = false;
|
|
231
|
+
let awaitingKeepalive = false;
|
|
232
|
+
let lastFrameAt = Date.now();
|
|
233
|
+
const sendJson = (payload) => {
|
|
234
|
+
if (ws.readyState !== wsOpen)
|
|
235
|
+
return false;
|
|
236
|
+
try {
|
|
237
|
+
ws.send(JSON.stringify(payload));
|
|
238
|
+
return true;
|
|
800
239
|
}
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
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);
|
|
240
|
+
catch {
|
|
241
|
+
controls.abort();
|
|
242
|
+
return false;
|
|
849
243
|
}
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
if (
|
|
853
|
-
|
|
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)
|
|
244
|
+
};
|
|
245
|
+
ws.onopen = () => {
|
|
246
|
+
if (pool.isClosed()) {
|
|
247
|
+
controls.abort();
|
|
909
248
|
return;
|
|
910
|
-
initialPending = 0;
|
|
911
|
-
for (const ws of [...allSockets]) {
|
|
912
|
-
try {
|
|
913
|
-
ws.close();
|
|
914
|
-
}
|
|
915
|
-
catch {
|
|
916
|
-
// Ignore close errors.
|
|
917
|
-
}
|
|
918
249
|
}
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
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]));
|
|
250
|
+
lastFrameAt = Date.now();
|
|
251
|
+
sendJson([
|
|
252
|
+
'REQ',
|
|
253
|
+
subId,
|
|
254
|
+
{
|
|
255
|
+
kinds: [ephemeralKind],
|
|
256
|
+
'#t': [roomTag, inboxTag],
|
|
257
|
+
since: Math.floor(Date.now() / 1000) - 60
|
|
959
258
|
}
|
|
960
|
-
|
|
259
|
+
]);
|
|
260
|
+
};
|
|
261
|
+
ws.onmessage = ({ data }) => {
|
|
262
|
+
if (pool.isClosed() || typeof data !== 'string' || data.length > maxFrameChars)
|
|
263
|
+
return;
|
|
264
|
+
lastFrameAt = Date.now();
|
|
265
|
+
awaitingKeepalive = false;
|
|
266
|
+
let msg;
|
|
267
|
+
try {
|
|
268
|
+
msg = JSON.parse(data);
|
|
961
269
|
}
|
|
962
270
|
catch {
|
|
963
|
-
|
|
271
|
+
return;
|
|
964
272
|
}
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
273
|
+
if (!Array.isArray(msg) || typeof msg[0] !== 'string')
|
|
274
|
+
return;
|
|
275
|
+
const kind = msg[0];
|
|
276
|
+
if (kind === 'EOSE' && msg[1] === subId) {
|
|
277
|
+
if (!subscribed) {
|
|
278
|
+
subscribed = true;
|
|
279
|
+
controls.markReady();
|
|
280
|
+
keepaliveTimer = setInterval(() => {
|
|
281
|
+
if (ws.readyState !== wsOpen)
|
|
282
|
+
return;
|
|
283
|
+
if (awaitingKeepalive) {
|
|
284
|
+
controls.abort();
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (Date.now() - lastFrameAt >= keepaliveIntervalMs) {
|
|
288
|
+
awaitingKeepalive = true;
|
|
289
|
+
sendJson([
|
|
290
|
+
'REQ',
|
|
291
|
+
subId,
|
|
292
|
+
{
|
|
293
|
+
kinds: [ephemeralKind],
|
|
294
|
+
'#t': [roomTag, inboxTag],
|
|
295
|
+
since: Math.floor(Date.now() / 1000)
|
|
296
|
+
}
|
|
297
|
+
]);
|
|
298
|
+
}
|
|
299
|
+
}, keepaliveIntervalMs);
|
|
300
|
+
}
|
|
977
301
|
}
|
|
302
|
+
else if (kind === 'EVENT' && msg[1] === subId) {
|
|
303
|
+
if (subscribed)
|
|
304
|
+
handleIncomingEvent(msg[2]);
|
|
305
|
+
}
|
|
306
|
+
else if (kind === 'CLOSED' && msg[1] === subId) {
|
|
307
|
+
controls.abort();
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
return () => {
|
|
311
|
+
if (keepaliveTimer)
|
|
312
|
+
clearInterval(keepaliveTimer);
|
|
313
|
+
subIdsBySocket.delete(ws);
|
|
314
|
+
};
|
|
315
|
+
},
|
|
316
|
+
onReady(ws, isInitial) {
|
|
317
|
+
void publishEvent({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
|
|
318
|
+
},
|
|
319
|
+
onPrivateKeys(keys) {
|
|
320
|
+
roomTag = 'mp1_p_' + keys.privateId;
|
|
321
|
+
inboxTag = roomTag + ':' + discovery.self;
|
|
322
|
+
},
|
|
323
|
+
onSweep(now, hasReadySockets) {
|
|
324
|
+
presence.prune(now);
|
|
325
|
+
for (const [evId, at] of seenEventIds) {
|
|
326
|
+
if (now - at >= 120_000)
|
|
327
|
+
seenEventIds.delete(evId);
|
|
978
328
|
}
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
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);
|
|
329
|
+
envelope.prune(now);
|
|
330
|
+
if (hasReadySockets)
|
|
331
|
+
void publishEvent({ type: 'heartbeat' });
|
|
332
|
+
},
|
|
333
|
+
sendSignal(to, signal) {
|
|
334
|
+
void publishEvent({ type: 'signal', to, signal });
|
|
335
|
+
},
|
|
336
|
+
onClose(allSockets, readySockets) {
|
|
337
|
+
const subIds = new Map(subIdsBySocket);
|
|
338
|
+
subIdsBySocket.clear();
|
|
339
|
+
const readySet = new Set(readySockets);
|
|
340
|
+
for (const ws of allSockets) {
|
|
341
|
+
if (!readySet.has(ws))
|
|
342
|
+
shutdownSocket(ws, subIds.get(ws));
|
|
1004
343
|
}
|
|
344
|
+
envelope.flushBye({
|
|
345
|
+
aad: roomTag ? 'meshpost/1/nostr:' + roomTag : undefined,
|
|
346
|
+
hasReadyTargets: readySockets.length > 0,
|
|
347
|
+
onPlain(byeJson) {
|
|
348
|
+
const frame = roomTag ? buildSignedFrame(roomTag, byeJson) : undefined;
|
|
349
|
+
for (const ws of readySockets)
|
|
350
|
+
shutdownSocket(ws, subIds.get(ws), frame);
|
|
351
|
+
},
|
|
352
|
+
onEncrypted(boxed) {
|
|
353
|
+
const frame = roomTag ? buildSignedFrame(roomTag, toBase64Url(boxed)) : undefined;
|
|
354
|
+
for (const ws of readySockets)
|
|
355
|
+
shutdownSocket(ws, subIds.get(ws), frame);
|
|
356
|
+
},
|
|
357
|
+
onDoneNoBye() {
|
|
358
|
+
for (const ws of readySockets)
|
|
359
|
+
shutdownSocket(ws, subIds.get(ws));
|
|
360
|
+
}
|
|
361
|
+
});
|
|
1005
362
|
}
|
|
1006
|
-
};
|
|
363
|
+
});
|
|
364
|
+
return pool.session;
|
|
1007
365
|
};
|
|
1008
366
|
}
|