@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/public.d.ts CHANGED
@@ -1,4 +1,12 @@
1
- import type { Signaling, WebSocketConstructor } from './signaling.js';
1
+ import { type Signaling, type SignalingState, type WebSocketConstructor } from './signaling.js';
2
+ export type PublicTransportKind = 'ws' | 'mqtt' | 'nostr' | 'tabs';
3
+ export interface PublicTransportEvent {
4
+ readonly transport: PublicTransportKind;
5
+ /** Normalized WebSocket relay URL when `transport === 'ws'`. */
6
+ readonly url?: string;
7
+ readonly state: SignalingState;
8
+ readonly reason?: string;
9
+ }
2
10
  export interface PublicSignalingOptions {
3
11
  /**
4
12
  * Optional opportunistic WebSocket signaling URL(s) (`ws://` or `wss://`, max 8 unique URLs)
@@ -43,6 +51,16 @@ export interface PublicSignalingOptions {
43
51
  handshakeTimeoutMs?: number;
44
52
  /** Optional custom `WebSocket` constructor forwarded to WS, MQTT, and Nostr transports. */
45
53
  WebSocket?: WebSocketConstructor;
54
+ /**
55
+ * Optional per-transport lifecycle observer (`'ws'`, `'mqtt'`, `'nostr'`, and `'tabs'` when
56
+ * `localTabs: true` and `BroadcastChannel` is available). Fires on each child transport's state
57
+ * transitions (`'connecting'`, `'online'`, `'offline'`, `'closed'`).
58
+ *
59
+ * Note: Per the WHATWG WebSocket specification, browsers intentionally hide HTTP status codes
60
+ * (such as `403` origin rejections) and TLS handshake details behind opaque close code `1006`;
61
+ * client-side handshake timeouts and non-`1006` close codes are reported in `reason`.
62
+ */
63
+ onTransportChange?: (event: PublicTransportEvent) => void;
46
64
  }
47
65
  /**
48
66
  * Out-of-the-box composite signaling combining public MQTT + port-443 Nostr relays,
package/dist/public.js CHANGED
@@ -1,6 +1,7 @@
1
- import { combineSignaling, withLocalTabs } from './combine.js';
1
+ import { combineSignaling, withLocalTabsInternal } from './combine.js';
2
2
  import { mqttSignaling } from './mqtt.js';
3
3
  import { nostrSignaling } from './nostr.js';
4
+ import { observeSignaling } from './signaling.js';
4
5
  import { optionalWsSignaling } from './ws.js';
5
6
  const maxOptionalWsUrls = 8;
6
7
  const maxRawWsUrlItems = 64;
@@ -11,6 +12,16 @@ function validateTimeoutMs(value, label) {
11
12
  throw new RangeError(`Invalid ${label}`);
12
13
  }
13
14
  }
15
+ function observeTransport(adapter, transport, onTransportChange, url) {
16
+ return observeSignaling(adapter, (state, reason) => {
17
+ onTransportChange(Object.freeze({
18
+ transport,
19
+ ...(url !== undefined ? { url } : {}),
20
+ state,
21
+ ...(reason !== undefined ? { reason } : {})
22
+ }));
23
+ });
24
+ }
14
25
  function normalizeWsUrls(raw) {
15
26
  if (raw === undefined)
16
27
  return [];
@@ -56,7 +67,7 @@ export function publicSignaling(options = {}) {
56
67
  if (!options || typeof options !== 'object' || Array.isArray(options)) {
57
68
  throw new TypeError('Invalid publicSignaling options');
58
69
  }
59
- const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor } = options;
70
+ const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor, onTransportChange } = options;
60
71
  if (typeof localTabs !== 'boolean')
61
72
  throw new TypeError('Invalid localTabs option');
62
73
  if (typeof wsEncrypt !== 'boolean')
@@ -69,6 +80,9 @@ export function publicSignaling(options = {}) {
69
80
  if (WsCtor !== undefined && typeof WsCtor !== 'function') {
70
81
  throw new TypeError('Invalid WebSocket constructor');
71
82
  }
83
+ if (onTransportChange !== undefined && typeof onTransportChange !== 'function') {
84
+ throw new TypeError('Invalid onTransportChange callback');
85
+ }
72
86
  if (mqtt !== true && mqtt !== false && !Array.isArray(mqtt)) {
73
87
  throw new TypeError('mqtt option must be a boolean or an array of broker URLs');
74
88
  }
@@ -82,31 +96,32 @@ export function publicSignaling(options = {}) {
82
96
  validateTimeoutMs(handshakeTimeoutMs, 'handshakeTimeoutMs');
83
97
  const normalizedWsUrls = normalizeWsUrls(wsUrls);
84
98
  const adapters = [];
99
+ const maybeObserve = (adapter, kind, url) => onTransportChange ? observeTransport(adapter, kind, onTransportChange, url) : adapter;
85
100
  for (const url of normalizedWsUrls) {
86
- adapters.push(optionalWsSignaling(url, {
101
+ adapters.push(maybeObserve(optionalWsSignaling(url, {
87
102
  handshakeTimeoutMs: wsHandshakeTimeoutMs,
88
103
  encrypt: wsEncrypt,
89
104
  privateTopic,
90
105
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
91
- }));
106
+ }), 'ws', url));
92
107
  }
93
108
  if (mqtt !== false) {
94
- adapters.push(mqttSignaling({
109
+ adapters.push(maybeObserve(mqttSignaling({
95
110
  ...(Array.isArray(mqtt) ? { urls: mqtt } : {}),
96
111
  ...(appId !== undefined ? { appId } : {}),
97
112
  privateTopic,
98
113
  handshakeTimeoutMs,
99
114
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
100
- }));
115
+ }), 'mqtt'));
101
116
  }
102
117
  if (nostr !== false) {
103
- adapters.push(nostrSignaling({
118
+ adapters.push(maybeObserve(nostrSignaling({
104
119
  ...(Array.isArray(nostr) ? { urls: nostr } : {}),
105
120
  ...(appId !== undefined ? { appId } : {}),
106
121
  privateTopic,
107
122
  handshakeTimeoutMs,
108
123
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
109
- }));
124
+ }), 'nostr'));
110
125
  }
111
126
  const network = combineSignaling(...adapters);
112
127
  const pooledNetwork = (discovery) => {
@@ -129,5 +144,7 @@ export function publicSignaling(options = {}) {
129
144
  }
130
145
  });
131
146
  };
132
- return localTabs ? withLocalTabs(pooledNetwork) : pooledNetwork;
147
+ return localTabs
148
+ ? withLocalTabsInternal(pooledNetwork, onTransportChange ? (tabs) => observeTransport(tabs, 'tabs', onTransportChange) : undefined)
149
+ : pooledNetwork;
133
150
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,323 @@
1
+ import { deriveSignalingKeys, errorCooldownMs, sealPayload } from './crypto.js';
2
+ import { isSignal } from './signaling.js';
3
+ const maxSeenPeers = 256;
4
+ const leaseTtlMs = 30_000;
5
+ const leaseSweepIntervalMs = 5_000;
6
+ const byeFlushTimeoutMs = 250;
7
+ /** @internal */
8
+ export function safeCloseSocket(ws) {
9
+ if (!ws)
10
+ return;
11
+ try {
12
+ ws.close();
13
+ }
14
+ catch {
15
+ // Ignore close errors.
16
+ }
17
+ }
18
+ /** @internal */
19
+ export function validatePositiveTimeout(value, errorMessage) {
20
+ if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {
21
+ throw new RangeError(errorMessage);
22
+ }
23
+ }
24
+ /** @internal */
25
+ export function normalizeWsRelayUrl(raw, invalidMessage, protocolMessage) {
26
+ if (typeof raw !== 'string' || raw.length === 0)
27
+ throw new TypeError(invalidMessage);
28
+ let parsed;
29
+ try {
30
+ parsed = new URL(raw);
31
+ }
32
+ catch {
33
+ throw new TypeError(invalidMessage);
34
+ }
35
+ if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
36
+ throw new TypeError(protocolMessage);
37
+ }
38
+ return parsed.toString();
39
+ }
40
+ /** @internal */
41
+ export function createErrorThrottle(discovery, cooldownMs = errorCooldownMs) {
42
+ const lastAt = new Map();
43
+ return (code, message) => {
44
+ const now = Date.now();
45
+ const prev = lastAt.get(code) ?? -Infinity;
46
+ if (now - prev >= cooldownMs) {
47
+ lastAt.set(code, now);
48
+ discovery.error?.(code, message);
49
+ }
50
+ };
51
+ }
52
+ /** @internal */
53
+ export function createPresenceTracker(discovery, sendPresent) {
54
+ const seen = new Map();
55
+ const roster = () => discovery.roster([...seen.keys()]);
56
+ const touch = (id) => {
57
+ const known = seen.has(id);
58
+ if (!known && seen.size >= maxSeenPeers) {
59
+ const oldest = seen.keys().next().value;
60
+ if (oldest !== undefined)
61
+ seen.delete(oldest);
62
+ }
63
+ seen.delete(id);
64
+ seen.set(id, Date.now());
65
+ if (!known)
66
+ roster();
67
+ return known;
68
+ };
69
+ return {
70
+ touch,
71
+ dispatch(data) {
72
+ const from = data.from;
73
+ switch (data.type) {
74
+ case 'hello':
75
+ touch(from);
76
+ sendPresent(from);
77
+ break;
78
+ case 'heartbeat':
79
+ if (!touch(from))
80
+ sendPresent(from);
81
+ break;
82
+ case 'present':
83
+ touch(from);
84
+ break;
85
+ case 'bye':
86
+ if (seen.delete(from))
87
+ roster();
88
+ break;
89
+ case 'signal':
90
+ if (isSignal(data.signal)) {
91
+ touch(from);
92
+ discovery.receive(from, data.signal);
93
+ }
94
+ break;
95
+ }
96
+ },
97
+ prune(now = Date.now()) {
98
+ let changed = false;
99
+ for (const [id, last] of seen) {
100
+ if (now - last > leaseTtlMs) {
101
+ seen.delete(id);
102
+ changed = true;
103
+ }
104
+ }
105
+ if (changed)
106
+ roster();
107
+ }
108
+ };
109
+ }
110
+ const encoder = new TextEncoder();
111
+ /** @internal */
112
+ export function createRelayPool(config) {
113
+ const { discovery, urls, handshakeTimeoutMs, offlineReason, password, privateTopic, baseScope } = config;
114
+ const readySockets = new Set();
115
+ const allSockets = new Set();
116
+ const reconnectTimers = new Set();
117
+ let closed = false;
118
+ let reportedOnline = false;
119
+ let reportedOffline = false;
120
+ let initialPending = urls.length;
121
+ let msgSeq = 0;
122
+ let resolvedKey;
123
+ const keysPromise = password !== undefined ? deriveSignalingKeys(password, baseScope) : undefined;
124
+ const updateStatus = () => {
125
+ if (closed)
126
+ return;
127
+ const online = readySockets.size > 0;
128
+ if (online && !reportedOnline) {
129
+ reportedOnline = true;
130
+ reportedOffline = false;
131
+ discovery.status('online');
132
+ }
133
+ else if (!online && (reportedOnline || (initialPending === 0 && !reportedOffline))) {
134
+ reportedOnline = false;
135
+ reportedOffline = true;
136
+ discovery.status('offline', offlineReason);
137
+ discovery.error?.('signaling-error', offlineReason);
138
+ }
139
+ };
140
+ const connectUrl = (url, attempt = 0, isInitial = true) => {
141
+ if (closed)
142
+ return;
143
+ let settledInitial = !isInitial;
144
+ const settleInitial = () => {
145
+ if (!settledInitial) {
146
+ settledInitial = true;
147
+ initialPending = Math.max(0, initialPending - 1);
148
+ }
149
+ };
150
+ let ws;
151
+ try {
152
+ ws = config.createSocket(url);
153
+ }
154
+ catch {
155
+ settleInitial();
156
+ updateStatus();
157
+ return;
158
+ }
159
+ allSockets.add(ws);
160
+ let ready = false;
161
+ let cleaned = false;
162
+ const abort = () => safeCloseSocket(ws);
163
+ let handshakeTimer = setTimeout(() => {
164
+ if (!ready)
165
+ abort();
166
+ }, handshakeTimeoutMs);
167
+ const detach = config.attachSocket(ws, {
168
+ isInitial,
169
+ abort,
170
+ markReady() {
171
+ if (closed || ready)
172
+ return;
173
+ ready = true;
174
+ clearTimeout(handshakeTimer);
175
+ handshakeTimer = undefined;
176
+ attempt = 0;
177
+ settleInitial();
178
+ readySockets.add(ws);
179
+ updateStatus();
180
+ config.onReady(ws, isInitial);
181
+ }
182
+ });
183
+ const cleanup = () => {
184
+ if (cleaned)
185
+ return;
186
+ cleaned = true;
187
+ clearTimeout(handshakeTimer);
188
+ handshakeTimer = undefined;
189
+ detach();
190
+ allSockets.delete(ws);
191
+ const wasReady = readySockets.delete(ws);
192
+ settleInitial();
193
+ if (wasReady || initialPending === 0)
194
+ updateStatus();
195
+ if (!closed) {
196
+ const base = Math.min(15_000, 1_000 * 2 ** Math.min(attempt, 4));
197
+ const delay = Math.round(base * (0.75 + Math.random() * 0.5));
198
+ const timer = setTimeout(() => {
199
+ reconnectTimers.delete(timer);
200
+ connectUrl(url, attempt + 1, false);
201
+ }, delay);
202
+ reconnectTimers.add(timer);
203
+ }
204
+ };
205
+ ws.onerror = abort;
206
+ ws.onclose = cleanup;
207
+ };
208
+ const leaseTimer = setInterval(() => {
209
+ if (closed)
210
+ return;
211
+ config.onSweep?.(Date.now(), readySockets.size > 0);
212
+ }, leaseSweepIntervalMs);
213
+ if (keysPromise && privateTopic) {
214
+ void keysPromise
215
+ .then((keys) => {
216
+ if (closed)
217
+ return;
218
+ resolvedKey = keys.aeadKey;
219
+ config.onPrivateKeys?.(keys);
220
+ for (const url of urls)
221
+ connectUrl(url);
222
+ })
223
+ .catch(() => {
224
+ if (closed)
225
+ return;
226
+ initialPending = 0;
227
+ updateStatus();
228
+ });
229
+ }
230
+ else {
231
+ if (keysPromise) {
232
+ void keysPromise
233
+ .then((keys) => {
234
+ resolvedKey = keys.aeadKey;
235
+ })
236
+ .catch(() => {
237
+ if (closed)
238
+ return;
239
+ initialPending = 0;
240
+ for (const ws of [...allSockets])
241
+ safeCloseSocket(ws);
242
+ updateStatus();
243
+ });
244
+ }
245
+ queueMicrotask(() => {
246
+ if (closed)
247
+ return;
248
+ for (const url of urls)
249
+ connectUrl(url);
250
+ });
251
+ }
252
+ const nextMid = () => discovery.self.slice(0, 8) + ':' + ++msgSeq;
253
+ const session = {
254
+ trickle: true,
255
+ send(to, signal) {
256
+ if (closed || readySockets.size === 0)
257
+ return false;
258
+ config.sendSignal(to, signal);
259
+ return true;
260
+ },
261
+ close() {
262
+ if (closed)
263
+ return;
264
+ closed = true;
265
+ clearInterval(leaseTimer);
266
+ for (const timer of reconnectTimers)
267
+ clearTimeout(timer);
268
+ reconnectTimers.clear();
269
+ config.onBeforeClose?.();
270
+ const socketsToClose = [...allSockets];
271
+ const readyToNotify = [...readySockets];
272
+ allSockets.clear();
273
+ readySockets.clear();
274
+ const byeJson = JSON.stringify({
275
+ type: 'bye',
276
+ from: discovery.self,
277
+ mid: nextMid(),
278
+ ts: Date.now()
279
+ });
280
+ if (!keysPromise) {
281
+ const byeFrame = config.buildPlainBye(byeJson);
282
+ for (const ws of socketsToClose) {
283
+ config.shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
284
+ }
285
+ return;
286
+ }
287
+ const aad = config.byeAad();
288
+ if (resolvedKey && aad && readyToNotify.length > 0) {
289
+ for (const ws of socketsToClose) {
290
+ if (!readyToNotify.includes(ws))
291
+ config.shutdownSocket(ws);
292
+ }
293
+ const fallbackTimer = setTimeout(() => {
294
+ for (const ws of readyToNotify)
295
+ config.shutdownSocket(ws);
296
+ }, byeFlushTimeoutMs);
297
+ void sealPayload(resolvedKey, encoder.encode(byeJson), aad)
298
+ .then((boxed) => {
299
+ clearTimeout(fallbackTimer);
300
+ const byeFrame = config.buildEncryptedBye(boxed);
301
+ for (const ws of readyToNotify)
302
+ config.shutdownSocket(ws, byeFrame);
303
+ })
304
+ .catch(() => {
305
+ clearTimeout(fallbackTimer);
306
+ for (const ws of readyToNotify)
307
+ config.shutdownSocket(ws);
308
+ });
309
+ }
310
+ else {
311
+ for (const ws of socketsToClose)
312
+ config.shutdownSocket(ws);
313
+ }
314
+ }
315
+ };
316
+ return {
317
+ isClosed: () => closed,
318
+ readySockets,
319
+ getKey: async () => resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined),
320
+ nextMid,
321
+ session
322
+ };
323
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,129 @@
1
+ import { decodeCanonicalBase64Url, extractUniqueDtlsFingerprint, sha256Base64Url, signIdentityProof, verifyIdentityProof } from './identity.js';
2
+ import { parseIncomingStreamTags } from './room-media.js';
3
+ import { isUuid } from './signaling.js';
4
+ /** @internal */
5
+ export const helloPrefix = 'meshpost/1/hello:';
6
+ const maxHelloBytes = 4096;
7
+ /** @internal */
8
+ export async function buildHelloFrame(params) {
9
+ const { localReclaimCommitPromise, initialTags, pendingReclaim, identity, appId, roomName, self, peerId, pc } = params;
10
+ const rc = await localReclaimCommitPromise;
11
+ const payload = { v: 1 };
12
+ if (rc)
13
+ payload.rc = rc;
14
+ if (initialTags)
15
+ payload.st = initialTags;
16
+ if (pendingReclaim) {
17
+ payload.reclaim = { id: pendingReclaim.id, secret: pendingReclaim.secret };
18
+ }
19
+ if (identity) {
20
+ const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
21
+ const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
22
+ const localFp = extractUniqueDtlsFingerprint(localSdp);
23
+ const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
24
+ if (!localFp || !remoteFp) {
25
+ throw new Error('Missing unique DTLS fingerprint for identity binding');
26
+ }
27
+ payload.id = await signIdentityProof(identity, {
28
+ appId,
29
+ room: roomName,
30
+ signerId: self,
31
+ verifierId: peerId,
32
+ signerFp: localFp,
33
+ verifierFp: remoteFp
34
+ });
35
+ }
36
+ return helloPrefix + JSON.stringify(payload);
37
+ }
38
+ /** @internal */
39
+ export function parseHelloFrame(data, self, peerId) {
40
+ if (data.length > maxHelloBytes) {
41
+ return { ok: false, error: 'Peer handshake frame exceeded size limit' };
42
+ }
43
+ let parsed = null;
44
+ try {
45
+ const raw = JSON.parse(data.slice(helloPrefix.length));
46
+ parsed =
47
+ raw && typeof raw === 'object' && !Array.isArray(raw)
48
+ ? raw
49
+ : null;
50
+ }
51
+ catch {
52
+ parsed = null;
53
+ }
54
+ if (!parsed || parsed.v !== 1) {
55
+ return { ok: false, error: 'Invalid peer handshake frame' };
56
+ }
57
+ let rc = null;
58
+ if (parsed.rc !== undefined) {
59
+ if (decodeCanonicalBase64Url(parsed.rc, 43, 32) === null) {
60
+ return { ok: false, error: 'Invalid peer handshake commitment' };
61
+ }
62
+ rc = parsed.rc;
63
+ }
64
+ let reclaimCandidate = null;
65
+ if (parsed.reclaim !== undefined) {
66
+ const rec = parsed.reclaim && typeof parsed.reclaim === 'object' && !Array.isArray(parsed.reclaim)
67
+ ? parsed.reclaim
68
+ : null;
69
+ if (!rec ||
70
+ typeof rec.id !== 'string' ||
71
+ !isUuid(rec.id) ||
72
+ rec.id === self ||
73
+ rec.id === peerId ||
74
+ decodeCanonicalBase64Url(rec.secret, 22, 16) === null) {
75
+ return { ok: false, error: 'Invalid peer session reclaim proof' };
76
+ }
77
+ reclaimCandidate = { id: rec.id, secret: rec.secret };
78
+ }
79
+ let initialStreamTags = null;
80
+ if (parsed.st !== undefined) {
81
+ initialStreamTags = parseIncomingStreamTags(parsed.st);
82
+ if (!initialStreamTags) {
83
+ return { ok: false, error: 'Invalid peer stream metadata' };
84
+ }
85
+ }
86
+ let idProof = null;
87
+ if (parsed.id !== undefined) {
88
+ if (!parsed.id || typeof parsed.id !== 'object' || Array.isArray(parsed.id)) {
89
+ return { ok: false, error: 'Invalid peer identity proof' };
90
+ }
91
+ idProof = parsed.id;
92
+ }
93
+ return {
94
+ ok: true,
95
+ parsed: { rc, reclaimCandidate, initialStreamTags, idProof }
96
+ };
97
+ }
98
+ /** @internal */
99
+ export async function verifyHelloFrame(parsed, params) {
100
+ const { appId, roomName, self, peerId, pc } = params;
101
+ let verifiedUserId = null;
102
+ if (parsed.idProof) {
103
+ const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
104
+ const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
105
+ const localFp = extractUniqueDtlsFingerprint(localSdp);
106
+ const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
107
+ if (!localFp || !remoteFp) {
108
+ return { ok: false, error: 'Missing unique DTLS fingerprint for identity verification' };
109
+ }
110
+ verifiedUserId = await verifyIdentityProof(parsed.idProof, {
111
+ appId,
112
+ room: roomName,
113
+ signerId: peerId,
114
+ verifierId: self,
115
+ signerFp: remoteFp,
116
+ verifierFp: localFp
117
+ });
118
+ if (!verifiedUserId) {
119
+ return { ok: false, error: 'Peer identity verification failed' };
120
+ }
121
+ }
122
+ let reclaimMatch = null;
123
+ if (parsed.reclaimCandidate) {
124
+ const commit = await sha256Base64Url(`meshpost/1/reclaim:${parsed.reclaimCandidate.id}:${parsed.reclaimCandidate.secret}`);
125
+ if (commit)
126
+ reclaimMatch = { id: parsed.reclaimCandidate.id, commit };
127
+ }
128
+ return { ok: true, verifiedUserId, reclaimMatch };
129
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,115 @@
1
+ const trickleBatchMs = 50;
2
+ const trickleBatchSize = 16;
3
+ /** @internal */
4
+ export const maxTrickleCandidates = 64;
5
+ /** @internal */
6
+ export async function setAndPublishLocalDescription(params) {
7
+ const { link, description, useTrickle, needsRelay, hasTurn, gatherTimeout, extendedGather, isCurrent, isStopped, onPublishSdp, onSendIce } = params;
8
+ const { pc } = link;
9
+ const publish = (force = false) => {
10
+ if (link.published || !isCurrent())
11
+ return;
12
+ if (!force && pc.iceGatheringState !== 'complete')
13
+ return;
14
+ const local = pc.localDescription;
15
+ if (!local || (local.type !== 'offer' && local.type !== 'answer'))
16
+ return;
17
+ clearTimeout(link.gather);
18
+ delete link.gather;
19
+ link.published = true;
20
+ onPublishSdp(local.type, local.sdp);
21
+ };
22
+ if (useTrickle) {
23
+ const outgoing = [];
24
+ let totalQueued = 0;
25
+ let gatheringDone = false;
26
+ const flushIce = () => {
27
+ clearTimeout(link.iceFlush);
28
+ delete link.iceFlush;
29
+ if (!link.published || !isCurrent() || link.ready || isStopped())
30
+ return;
31
+ while (outgoing.length > 0) {
32
+ onSendIce(outgoing.splice(0, trickleBatchSize));
33
+ }
34
+ };
35
+ const scheduleFlush = (immediate = false) => {
36
+ if (!link.published || !isCurrent() || link.ready || isStopped())
37
+ return;
38
+ if (immediate || outgoing.length >= trickleBatchSize) {
39
+ flushIce();
40
+ }
41
+ else if (!link.iceFlush) {
42
+ link.iceFlush = setTimeout(flushIce, trickleBatchMs);
43
+ }
44
+ };
45
+ pc.onicecandidate = (event) => {
46
+ if (!isCurrent() || link.ready || isStopped())
47
+ return;
48
+ if (!event.candidate) {
49
+ gatheringDone = true;
50
+ if (totalQueued < maxTrickleCandidates) {
51
+ outgoing.push({ candidate: '' });
52
+ totalQueued++;
53
+ }
54
+ scheduleFlush(true);
55
+ return;
56
+ }
57
+ if (totalQueued >= maxTrickleCandidates)
58
+ return;
59
+ outgoing.push({
60
+ candidate: event.candidate.candidate,
61
+ ...(event.candidate.sdpMid !== null ? { sdpMid: event.candidate.sdpMid } : {}),
62
+ ...(event.candidate.sdpMLineIndex !== null
63
+ ? { sdpMLineIndex: event.candidate.sdpMLineIndex }
64
+ : {})
65
+ });
66
+ totalQueued++;
67
+ scheduleFlush(false);
68
+ };
69
+ await pc.setLocalDescription(description);
70
+ if (!isCurrent())
71
+ return;
72
+ publish(true);
73
+ if (outgoing.length > 0)
74
+ scheduleFlush(gatheringDone);
75
+ return;
76
+ }
77
+ // Send one complete SDP. Publish early after gatherTimeout so unreachable STUN never stalls,
78
+ // while allowing extra time when relay/TURN candidates are required or configured.
79
+ let hasRelay = false;
80
+ let hasSrflx = false;
81
+ let softExpired = false;
82
+ pc.onicecandidate = (event) => {
83
+ if (!isCurrent() || link.published)
84
+ return;
85
+ if (!event.candidate) {
86
+ publish(true);
87
+ return;
88
+ }
89
+ const type = event.candidate.type;
90
+ if (type === 'relay')
91
+ hasRelay = true;
92
+ else if (type === 'srflx')
93
+ hasSrflx = true;
94
+ if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
95
+ publish(true);
96
+ }
97
+ };
98
+ pc.onicegatheringstatechange = () => publish(false);
99
+ await pc.setLocalDescription(description);
100
+ if (!isCurrent())
101
+ return;
102
+ publish(false);
103
+ if (!link.published) {
104
+ link.gather = setTimeout(() => {
105
+ softExpired = true;
106
+ const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
107
+ if (waitingForRelay && extendedGather > gatherTimeout) {
108
+ link.gather = setTimeout(() => publish(true), extendedGather - gatherTimeout);
109
+ }
110
+ else {
111
+ publish(true);
112
+ }
113
+ }, gatherTimeout);
114
+ }
115
+ }