@dimchansky/meshpost 0.6.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/dist/nostr.js CHANGED
@@ -1,7 +1,8 @@
1
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';
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';
5
6
  /** Built-in public port-443 Nostr WebSocket relays used by default. */
6
7
  export const defaultNostrRelays = Object.freeze([
7
8
  'wss://relay.damus.io',
@@ -10,12 +11,10 @@ export const defaultNostrRelays = Object.freeze([
10
11
  ]);
11
12
  const wsOpen = 1;
12
13
  const encoder = new TextEncoder();
13
- const decoder = new TextDecoder();
14
14
  const ephemeralKind = 25050;
15
15
  const maxFrameChars = 128 * 1024;
16
16
  const maxContentChars = 96 * 1024;
17
17
  const maxSeenEventIds = 2048;
18
- const maxDecryptQueueDepth = 64;
19
18
  const maxSchnorrVerifiesPerSec = 64;
20
19
  const maxCreatedAtSkewSec = 120;
21
20
  const defaultHandshakeTimeoutMs = 10_000;
@@ -69,35 +68,12 @@ export function nostrSignaling(options = {}) {
69
68
  (typeof options.appId !== 'string' || !appIdPattern.test(options.appId))) {
70
69
  throw new TypeError('Invalid appId');
71
70
  }
72
- if (options.password !== undefined &&
73
- (typeof options.password !== 'string' || options.password.length === 0)) {
74
- throw new TypeError('Invalid password');
75
- }
76
- if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
77
- throw new TypeError('Invalid privateTopic option');
78
- }
79
- if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
80
- throw new TypeError('Invalid WebSocket constructor');
81
- }
71
+ validateCommonSignalingOptions(options);
82
72
  return (discovery) => {
83
- const WsCtor = options.WebSocket ?? globalThis.WebSocket;
84
- if (typeof WsCtor !== 'function') {
85
- throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
86
- }
73
+ const WsCtor = resolveSessionWebSocket(options.WebSocket);
87
74
  const appId = options.appId ?? discovery.appId;
88
- const password = options.password ?? discovery.password;
89
75
  const privateTopic = options.privateTopic ?? false;
90
- if (privateTopic && password === undefined) {
91
- throw new TypeError('privateTopic requires a room password');
92
- }
93
- if (password !== undefined) {
94
- if (typeof password !== 'string' || password.length === 0) {
95
- throw new TypeError('Invalid password');
96
- }
97
- if (!globalThis.crypto?.subtle) {
98
- throw new Error('Password encryption requires a secure context (crypto.subtle)');
99
- }
100
- }
76
+ const { password } = resolveSessionPassword(options.password ?? discovery.password, privateTopic);
101
77
  const { secretKey, pubkeyHex } = generateSessionKeypair();
102
78
  const baseScope = appId + ':' + discovery.room;
103
79
  let roomTag = privateTopic ? '' : 'mp1_' + namespaceHash(baseScope);
@@ -105,15 +81,15 @@ export function nostrSignaling(options = {}) {
105
81
  const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
106
82
  const seenEventIds = new Map();
107
83
  const inFlightEventIds = new Set();
108
- const replayGuard = createReplayGuard();
109
84
  const subIdsBySocket = new Map();
110
- let subMapSnapshot = new Map();
111
- let pendingDecryptCount = 0;
112
85
  let verifyWindowStart = 0;
113
86
  let verifyCount = 0;
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)');
87
+ const envelope = createRelayEnvelope({
88
+ discovery,
89
+ password,
90
+ baseScope,
91
+ transportLabel: 'Nostr'
92
+ });
117
93
  const recordEventId = (eventId, now = Date.now()) => {
118
94
  if (seenEventIds.size >= maxSeenEventIds) {
119
95
  const oldest = seenEventIds.keys().next().value;
@@ -134,20 +110,10 @@ export function nostrSignaling(options = {}) {
134
110
  if (pool.isClosed() || !roomTag)
135
111
  return;
136
112
  const targetTag = body.to ? roomTag + ':' + body.to : roomTag;
137
- const mid = fixedMid ?? pool.nextMid();
138
- const plainJson = JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() });
139
- let content;
140
- try {
141
- const key = await pool.getKey();
142
- content = key
143
- ? toBase64Url(await sealPayload(key, encoder.encode(plainJson), 'meshpost/1/nostr:' + targetTag))
144
- : plainJson;
145
- }
146
- catch {
147
- return;
148
- }
149
- if (pool.isClosed())
113
+ const sealed = await envelope.sealJson(body, 'meshpost/1/nostr:' + targetTag, fixedMid);
114
+ if (!sealed || pool.isClosed())
150
115
  return;
116
+ const content = envelope.isEncrypted ? toBase64Url(sealed.bytes) : sealed.plainJson;
151
117
  const frame = buildSignedFrame(targetTag, content);
152
118
  for (const ws of targetSockets ?? pool.readySockets) {
153
119
  if (ws.readyState === wsOpen) {
@@ -193,59 +159,31 @@ export function nostrSignaling(options = {}) {
193
159
  const sigHex = ev.sig;
194
160
  const peerPubkeyHex = ev.pubkey;
195
161
  const content = ev.content;
196
- if (password !== undefined) {
162
+ if (envelope.isEncrypted) {
197
163
  const boxed = fromBase64Url(content);
198
164
  if (!boxed) {
199
- emitDecryptFailed();
165
+ envelope.emitDecryptFailed();
200
166
  return;
201
167
  }
202
- if (pendingDecryptCount >= maxDecryptQueueDepth)
203
- return;
204
- pendingDecryptCount++;
205
168
  inFlightEventIds.add(eventId);
206
- void (async () => {
207
- try {
208
- const key = await pool.getKey();
209
- if (!key || pool.isClosed() || seenEventIds.has(eventId))
210
- return;
211
- const plain = await openPayload(key, boxed, 'meshpost/1/nostr:' + tTag);
212
- if (pool.isClosed())
213
- return;
214
- if (!plain) {
215
- emitDecryptFailed();
216
- 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;
217
175
  }
218
- if (!verifySchnorr(hexToBytes(sigHex), idBytes, hexToBytes(peerPubkeyHex)))
219
- return;
220
176
  recordEventId(eventId);
221
- let data = null;
222
- try {
223
- data = JSON.parse(decoder.decode(plain));
224
- }
225
- catch {
226
- return;
227
- }
228
- if (!data || !isUuid(data.from) || data.from === discovery.self)
229
- return;
230
- if (data.to !== undefined && data.to !== discovery.self)
231
- return;
232
- const check = replayGuard.checkAuthenticated(data.from, data);
233
- if (check === 'clock-skew') {
234
- emitClockSkew();
235
- return;
236
- }
237
- if (check !== 'ok')
238
- return;
239
- presence.dispatch(data);
240
- }
241
- catch {
242
- // Ignore unexpected errors.
243
- }
244
- finally {
177
+ return true;
178
+ },
179
+ onFinally() {
245
180
  inFlightEventIds.delete(eventId);
246
- pendingDecryptCount--;
247
181
  }
248
- })();
182
+ })
183
+ .then((data) => {
184
+ if (data && !pool.isClosed())
185
+ presence.dispatch(data);
186
+ });
249
187
  return;
250
188
  }
251
189
  const now = Date.now();
@@ -259,34 +197,31 @@ export function nostrSignaling(options = {}) {
259
197
  if (!verifySchnorr(hexToBytes(sigHex), idBytes, hexToBytes(peerPubkeyHex)))
260
198
  return;
261
199
  recordEventId(eventId, now);
262
- let data = null;
200
+ const data = envelope.parsePlaintext(content, now);
201
+ if (data)
202
+ presence.dispatch(data);
203
+ };
204
+ const shutdownSocket = (ws, subId, byeFrame) => {
263
205
  try {
264
- data = JSON.parse(content);
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();
265
213
  }
266
214
  catch {
267
- return;
268
- }
269
- if (!data || !isUuid(data.from) || data.from === discovery.self)
270
- return;
271
- if (data.to !== undefined && data.to !== discovery.self)
272
- return;
273
- if (data.mid !== undefined &&
274
- (typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength)) {
275
- return;
215
+ // Ignore shutdown errors.
276
216
  }
277
- if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid, now)) {
278
- return;
279
- }
280
- presence.dispatch(data);
281
217
  };
282
218
  const pool = createRelayPool({
283
219
  discovery,
284
220
  urls,
285
221
  handshakeTimeoutMs,
286
222
  offlineReason: 'All Nostr relays disconnected',
287
- password,
223
+ envelope,
288
224
  privateTopic,
289
- baseScope,
290
225
  createSocket: (url) => new WsCtor(url),
291
226
  attachSocket(ws, controls) {
292
227
  const subId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
@@ -391,34 +326,39 @@ export function nostrSignaling(options = {}) {
391
326
  if (now - at >= 120_000)
392
327
  seenEventIds.delete(evId);
393
328
  }
394
- replayGuard.prune(now);
329
+ envelope.prune(now);
395
330
  if (hasReadySockets)
396
331
  void publishEvent({ type: 'heartbeat' });
397
332
  },
398
333
  sendSignal(to, signal) {
399
334
  void publishEvent({ type: 'signal', to, signal });
400
335
  },
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);
336
+ onClose(allSockets, readySockets) {
337
+ const subIds = new Map(subIdsBySocket);
406
338
  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();
418
- }
419
- catch {
420
- // Ignore shutdown errors.
339
+ const readySet = new Set(readySockets);
340
+ for (const ws of allSockets) {
341
+ if (!readySet.has(ws))
342
+ shutdownSocket(ws, subIds.get(ws));
421
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
+ });
422
362
  }
423
363
  });
424
364
  return pool.session;