@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.
Files changed (49) hide show
  1. package/README.md +66 -544
  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 +44 -45
  6. package/dist/channel.d.ts +4 -0
  7. package/dist/channel.js +19 -44
  8. package/dist/combine.d.ts +9 -2
  9. package/dist/combine.js +40 -57
  10. package/dist/crypto.js +10 -9
  11. package/dist/identity.d.ts +2 -0
  12. package/dist/identity.js +39 -71
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/listeners.js +18 -3
  16. package/dist/mqtt.js +211 -476
  17. package/dist/nostr.js +194 -836
  18. package/dist/peer-link.d.ts +1 -0
  19. package/dist/peer-link.js +983 -0
  20. package/dist/presence.d.ts +1 -0
  21. package/dist/presence.js +74 -0
  22. package/dist/public.d.ts +1 -1
  23. package/dist/public.js +25 -77
  24. package/dist/relay-core.d.ts +1 -0
  25. package/dist/relay-core.js +399 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +115 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +245 -1218
  31. package/dist/rpc.js +25 -28
  32. package/dist/signaling.d.ts +8 -0
  33. package/dist/signaling.js +55 -0
  34. package/dist/state.js +23 -33
  35. package/dist/tabs.js +6 -50
  36. package/dist/voice-mic.d.ts +1 -0
  37. package/dist/voice-mic.js +496 -0
  38. package/dist/voice-remote.d.ts +1 -0
  39. package/dist/voice-remote.js +568 -0
  40. package/dist/voice.d.ts +19 -1
  41. package/dist/voice.js +95 -1036
  42. package/dist/ws.js +56 -197
  43. package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
  44. package/docs/api.md +219 -0
  45. package/docs/behavior.md +14 -8
  46. package/docs/guide.md +404 -0
  47. package/docs/signaling-and-production.md +312 -0
  48. package/docs/voice-and-media.md +193 -0
  49. package/package.json +6 -3
package/dist/combine.d.ts CHANGED
@@ -1,10 +1,17 @@
1
- import type { Signaling } from './signaling.js';
1
+ import { type Signaling, type SignalingState } from './signaling.js';
2
2
  /**
3
3
  * Combine multiple signaling adapters into one composite adapter.
4
4
  * Merges peer rosters across all children, routes signals to reachable children that advertise the target peer,
5
5
  * and stays `'online'` as long as at least one child adapter is `'online'`.
6
6
  */
7
7
  export declare function combineSignaling(...adapters: readonly Signaling[]): Signaling;
8
+ export interface WithLocalTabsOptions {
9
+ /**
10
+ * Optional observer invoked whenever the internal same-browser `tabSignaling()` adapter
11
+ * changes `SignalingState` (skipped when `BroadcastChannel` is unavailable or blocked).
12
+ */
13
+ onTabsState?: (state: SignalingState, reason?: string) => void;
14
+ }
8
15
  /**
9
16
  * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
10
17
  * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
@@ -15,4 +22,4 @@ export declare function combineSignaling(...adapters: readonly Signaling[]): Sig
15
22
  * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
16
23
  * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
17
24
  */
18
- export declare function withLocalTabs(primary: Signaling): Signaling;
25
+ export declare function withLocalTabs(primary: Signaling, options?: WithLocalTabsOptions): Signaling;
package/dist/combine.js CHANGED
@@ -1,8 +1,9 @@
1
+ import { createErrorThrottle } from './presence.js';
2
+ import { observeSignaling } from './signaling.js';
1
3
  import { tabSignaling } from './tabs.js';
2
4
  const maxSeenIcePeers = 256;
3
5
  const maxSeenIceAttemptsPerPeer = 4;
4
6
  const maxSeenIceKeysPerAttempt = 64;
5
- const compositeErrorCooldownMs = 15_000;
6
7
  function iceCandidateKey(item) {
7
8
  return item.candidate + '\0' + (item.sdpMid ?? '') + '\0' + (item.sdpMLineIndex ?? '');
8
9
  }
@@ -34,10 +35,15 @@ function createCompositeSession(discovery, list, primaryIndex) {
34
35
  let closed = false;
35
36
  let aggState = 'connecting';
36
37
  let lastReason;
37
- let lastDecryptErrorAt = -Infinity;
38
- let lastClockSkewErrorAt = -Infinity;
39
38
  let publishedRoster = new Set();
40
39
  let rosterDirty = false;
40
+ const emitThrottledError = createErrorThrottle((code, message) => {
41
+ if (initializing) {
42
+ buffered.push({ kind: 'error', code, message });
43
+ return;
44
+ }
45
+ discovery.error?.(code, message);
46
+ });
41
47
  const computeAggregateState = () => {
42
48
  if (primaryIndex !== null) {
43
49
  return children[primaryIndex].state;
@@ -150,32 +156,13 @@ function createCompositeSession(discovery, list, primaryIndex) {
150
156
  if (closed || next === child.state)
151
157
  return;
152
158
  child.state = next;
153
- if (next === 'closed') {
154
- if (child.peers.size > 0) {
155
- child.peers.clear();
156
- syncRoster();
159
+ if (next === 'closed' || next === 'offline') {
160
+ for (const id of [...child.peers]) {
161
+ if (next === 'closed' || !childCanReach(child, id))
162
+ child.peers.delete(id);
157
163
  }
158
164
  }
159
- else if (next === 'offline') {
160
- if (typeof child.session?.canReach === 'function') {
161
- let removed = false;
162
- for (const id of [...child.peers]) {
163
- if (!child.session.canReach(id)) {
164
- child.peers.delete(id);
165
- removed = true;
166
- }
167
- }
168
- if (removed)
169
- syncRoster();
170
- }
171
- else if (child.peers.size > 0) {
172
- child.peers.clear();
173
- syncRoster();
174
- }
175
- }
176
- else if (next === 'online' && child.peers.size > 0) {
177
- syncRoster();
178
- }
165
+ syncRoster();
179
166
  if (primaryIndex === null || index === primaryIndex) {
180
167
  syncState(reason);
181
168
  }
@@ -207,17 +194,9 @@ function createCompositeSession(discovery, list, primaryIndex) {
207
194
  return;
208
195
  if (primaryIndex !== null && index !== primaryIndex)
209
196
  return;
210
- if (code === 'decrypt-failed') {
211
- const now = Date.now();
212
- if (now - lastDecryptErrorAt < compositeErrorCooldownMs)
213
- return;
214
- lastDecryptErrorAt = now;
215
- }
216
- else if (code === 'clock-skew') {
217
- const now = Date.now();
218
- if (now - lastClockSkewErrorAt < compositeErrorCooldownMs)
219
- return;
220
- lastClockSkewErrorAt = now;
197
+ if (code === 'decrypt-failed' || code === 'clock-skew') {
198
+ emitThrottledError(code, message);
199
+ return;
221
200
  }
222
201
  if (initializing) {
223
202
  buffered.push({ kind: 'error', code, message });
@@ -323,8 +302,28 @@ function canUseLocalTabs() {
323
302
  }
324
303
  return true;
325
304
  }
326
- /** @internal */
327
- export function withLocalTabsInternal(primary, wrapTabs) {
305
+ /**
306
+ * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
307
+ * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
308
+ *
309
+ * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
310
+ * (avoiding a permanently `'online'` indicator when network connectivity is lost).
311
+ * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
312
+ * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
313
+ * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
314
+ */
315
+ export function withLocalTabs(primary, options) {
316
+ if (typeof primary !== 'function') {
317
+ throw new TypeError('Expected a signaling adapter function');
318
+ }
319
+ if (options !== undefined &&
320
+ (!options || typeof options !== 'object' || Array.isArray(options))) {
321
+ throw new TypeError('Invalid withLocalTabs options');
322
+ }
323
+ const onTabsState = options?.onTabsState;
324
+ if (onTabsState !== undefined && typeof onTabsState !== 'function') {
325
+ throw new TypeError('Expected onTabsState to be a function');
326
+ }
328
327
  return (discovery) => {
329
328
  if (!canUseLocalTabs())
330
329
  return primary(discovery);
@@ -338,23 +337,7 @@ export function withLocalTabsInternal(primary, wrapTabs) {
338
337
  return primary(discovery);
339
338
  }
340
339
  const baseTabs = tabSignaling();
341
- const tabs = wrapTabs ? wrapTabs(baseTabs) : baseTabs;
340
+ const tabs = onTabsState ? observeSignaling(baseTabs, onTabsState) : baseTabs;
342
341
  return createCompositeSession(discovery, [tabs, primary], 1);
343
342
  };
344
343
  }
345
- /**
346
- * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
347
- * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
348
- *
349
- * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
350
- * (avoiding a permanently `'online'` indicator when network connectivity is lost).
351
- * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
352
- * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
353
- * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
354
- */
355
- export function withLocalTabs(primary) {
356
- if (typeof primary !== 'function') {
357
- throw new TypeError('Expected a signaling adapter function');
358
- }
359
- return withLocalTabsInternal(primary);
360
- }
package/dist/crypto.js CHANGED
@@ -92,20 +92,14 @@ export function toBase64Url(bytes) {
92
92
  }
93
93
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
94
94
  }
95
- export function fromBase64Url(value, maxChars = maxBoxChars) {
96
- if (typeof value !== 'string' ||
97
- value.length < minBoxChars ||
98
- value.length > maxChars ||
99
- value.length % 4 === 1 ||
100
- !base64UrlPattern.test(value)) {
95
+ /** @internal */
96
+ export function decodeBase64UrlBytes(value) {
97
+ if (value.length % 4 === 1 || !base64UrlPattern.test(value))
101
98
  return null;
102
- }
103
99
  try {
104
100
  const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
105
101
  const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
106
102
  const binary = atob(padded);
107
- if (binary.length < minBoxBytes)
108
- return null;
109
103
  const out = new Uint8Array(binary.length);
110
104
  for (let i = 0; i < binary.length; i++)
111
105
  out[i] = binary.charCodeAt(i);
@@ -115,6 +109,13 @@ export function fromBase64Url(value, maxChars = maxBoxChars) {
115
109
  return null;
116
110
  }
117
111
  }
112
+ export function fromBase64Url(value, maxChars = maxBoxChars) {
113
+ if (typeof value !== 'string' || value.length < minBoxChars || value.length > maxChars) {
114
+ return null;
115
+ }
116
+ const out = decodeBase64UrlBytes(value);
117
+ return out && out.byteLength >= minBoxBytes ? out : null;
118
+ }
118
119
  export function createReplayGuard() {
119
120
  const seenMids = new Map();
120
121
  const recordMid = (scopedMid, now = Date.now()) => {
@@ -53,6 +53,8 @@ export interface IdentityStoreOptions {
53
53
  * with IndexedDB directly.
54
54
  */
55
55
  export interface IdentityStore {
56
+ /** Most recently loaded or rotated identity cached in memory, or `null` before `load()` or after `clear()`. */
57
+ readonly current: PeerIdentity | null;
56
58
  /** Load the stored identity or generate and persist a fresh one (coalesces concurrent calls; self-heals corrupt storage). */
57
59
  load(): Promise<PeerIdentity>;
58
60
  /** Generate a fresh identity, persist it, and supersede any in-flight `load()` or earlier `rotate()`. */
package/dist/identity.js CHANGED
@@ -1,6 +1,5 @@
1
- import { toBase64Url } from './crypto.js';
1
+ import { decodeBase64UrlBytes, toBase64Url } from './crypto.js';
2
2
  const encoder = new TextEncoder();
3
- const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
4
3
  const userIdDomainPrefix = encoder.encode('meshpost/1/userid:');
5
4
  const dtlsFingerprintLinePattern = /^a=fingerprint:(sha-256|sha-384|sha-512)\s+([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2})+)\s*$/i;
6
5
  const expectedFingerprintHexLength = {
@@ -11,25 +10,10 @@ const expectedFingerprintHexLength = {
11
10
  const identityInternals = new WeakMap();
12
11
  /** @internal */
13
12
  export function decodeCanonicalBase64Url(value, expectedChars, expectedBytes) {
14
- if (typeof value !== 'string' ||
15
- value.length !== expectedChars ||
16
- !base64UrlPattern.test(value)) {
13
+ if (typeof value !== 'string' || value.length !== expectedChars)
17
14
  return null;
18
- }
19
- try {
20
- const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
21
- const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
22
- const binary = atob(padded);
23
- if (binary.length !== expectedBytes)
24
- return null;
25
- const out = new Uint8Array(expectedBytes);
26
- for (let i = 0; i < expectedBytes; i++)
27
- out[i] = binary.charCodeAt(i);
28
- return toBase64Url(out) === value ? out : null;
29
- }
30
- catch {
31
- return null;
32
- }
15
+ const out = decodeBase64UrlBytes(value);
16
+ return out && out.byteLength === expectedBytes && toBase64Url(out) === value ? out : null;
33
17
  }
34
18
  async function deriveUserIdFromRawPublicKey(subtle, rawPub) {
35
19
  const input = new Uint8Array(userIdDomainPrefix.byteLength + rawPub.byteLength);
@@ -121,15 +105,17 @@ export function isSerializedIdentity(value) {
121
105
  */
122
106
  export async function importIdentity(data, options) {
123
107
  const extractable = parseExtractableOption(options);
124
- if (!isSerializedIdentity(data)) {
108
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
125
109
  throw new TypeError('Invalid serialized identity');
126
110
  }
127
- const subtle = requireSubtleCrypto();
128
- const xBytes = decodeCanonicalBase64Url(data.x, 43, 32);
129
- const yBytes = decodeCanonicalBase64Url(data.y, 43, 32);
130
- if (!xBytes || !yBytes) {
111
+ const rec = data;
112
+ const xBytes = rec.v === 1 && rec.crv === 'P-256' ? decodeCanonicalBase64Url(rec.x, 43, 32) : null;
113
+ const yBytes = xBytes ? decodeCanonicalBase64Url(rec.y, 43, 32) : null;
114
+ const dBytes = yBytes ? decodeCanonicalBase64Url(rec.d, 43, 32) : null;
115
+ if (!xBytes || !yBytes || !dBytes) {
131
116
  throw new TypeError('Invalid serialized identity');
132
117
  }
118
+ const subtle = requireSubtleCrypto();
133
119
  const rawCandidate = new Uint8Array(65);
134
120
  rawCandidate[0] = 0x04;
135
121
  rawCandidate.set(xBytes, 1);
@@ -139,9 +125,9 @@ export async function importIdentity(data, options) {
139
125
  subtle.importKey('jwk', {
140
126
  kty: 'EC',
141
127
  crv: 'P-256',
142
- x: data.x,
143
- y: data.y,
144
- d: data.d,
128
+ x: rec.x,
129
+ y: rec.y,
130
+ d: rec.d,
145
131
  key_ops: ['sign'],
146
132
  ext: extractable
147
133
  }, { name: 'ECDSA', namedCurve: 'P-256' }, extractable, ['sign']),
@@ -340,7 +326,30 @@ export function createIdentityStore(options) {
340
326
  // Ignore restricted-storage errors.
341
327
  }
342
328
  };
329
+ const resolveStale = (fallback, selfPromise) => {
330
+ if (cached)
331
+ return cached;
332
+ if (inFlightRotate && inFlightRotate !== selfPromise)
333
+ return inFlightRotate;
334
+ return fallback;
335
+ };
336
+ const createAndPersist = async (myEpoch, storage, selfPromise) => {
337
+ const fresh = await createIdentity();
338
+ if (myEpoch !== epoch)
339
+ return resolveStale(fresh, selfPromise?.());
340
+ if (storage) {
341
+ const exported = await exportIdentity(fresh);
342
+ if (myEpoch !== epoch)
343
+ return resolveStale(fresh, selfPromise?.());
344
+ safeWrite(storage, exported);
345
+ }
346
+ cached = fresh;
347
+ return fresh;
348
+ };
343
349
  return {
350
+ get current() {
351
+ return cached;
352
+ },
344
353
  load() {
345
354
  if (cached)
346
355
  return Promise.resolve(cached);
@@ -381,27 +390,7 @@ export function createIdentityStore(options) {
381
390
  }
382
391
  safeRemove(storage);
383
392
  }
384
- const fresh = await createIdentity();
385
- if (myEpoch !== epoch) {
386
- if (cached)
387
- return cached;
388
- if (inFlightRotate)
389
- return inFlightRotate;
390
- return fresh;
391
- }
392
- if (storage) {
393
- const exported = await exportIdentity(fresh);
394
- if (myEpoch !== epoch) {
395
- if (cached)
396
- return cached;
397
- if (inFlightRotate)
398
- return inFlightRotate;
399
- return fresh;
400
- }
401
- safeWrite(storage, exported);
402
- }
403
- cached = fresh;
404
- return fresh;
393
+ return createAndPersist(myEpoch, storage);
405
394
  })().finally(() => {
406
395
  if (inFlightLoad === promise)
407
396
  inFlightLoad = null;
@@ -416,28 +405,7 @@ export function createIdentityStore(options) {
416
405
  let promise = null;
417
406
  promise = (async () => {
418
407
  requireSubtleCrypto();
419
- const storage = resolveStorage();
420
- const fresh = await createIdentity();
421
- if (myEpoch !== epoch) {
422
- if (cached)
423
- return cached;
424
- if (inFlightRotate && inFlightRotate !== promise)
425
- return inFlightRotate;
426
- return fresh;
427
- }
428
- if (storage) {
429
- const exported = await exportIdentity(fresh);
430
- if (myEpoch !== epoch) {
431
- if (cached)
432
- return cached;
433
- if (inFlightRotate && inFlightRotate !== promise)
434
- return inFlightRotate;
435
- return fresh;
436
- }
437
- safeWrite(storage, exported);
438
- }
439
- cached = fresh;
440
- return fresh;
408
+ return createAndPersist(myEpoch, resolveStorage(), () => promise);
441
409
  })().finally(() => {
442
410
  if (inFlightRotate === promise)
443
411
  inFlightRotate = null;
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export type { PeerState, PeerStateChangeReason, PeerStateOptions } from './state
11
11
  export { createBlobChannel } from './blob.js';
12
12
  export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
13
13
  export { createVoice, listAudioInputs, onAudioInputsChange } from './voice.js';
14
- export type { AudioInputDevice, MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
14
+ export type { AudioInputDevice, AudioInputsChangeOptions, MicError, MicErrorCode, MicStatus, MicStopReason, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
15
15
  export { fetchTurnCredentials } from './turn.js';
16
16
  export type { FetchTurnOptions } from './turn.js';
17
17
  export { tabSignaling } from './tabs.js';
@@ -26,5 +26,6 @@ export type { OptionalWsSignalingOptions, WsSignalingOptions } from './ws.js';
26
26
  export { publicSignaling } from './public.js';
27
27
  export type { PublicSignalingOptions, PublicTransportEvent, PublicTransportKind } from './public.js';
28
28
  export { combineSignaling, withLocalTabs } from './combine.js';
29
- export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
29
+ export type { WithLocalTabsOptions } from './combine.js';
30
+ export { isSignal, isUuid, observeSignaling, withLoopbackFallback } from './signaling.js';
30
31
  export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState, WebSocketConstructor } from './signaling.js';
package/dist/index.js CHANGED
@@ -13,4 +13,4 @@ export { defaultNostrRelays, nostrSignaling } from './nostr.js';
13
13
  export { optionalWsSignaling, wsSignaling } from './ws.js';
14
14
  export { publicSignaling } from './public.js';
15
15
  export { combineSignaling, withLocalTabs } from './combine.js';
16
- export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
16
+ export { isSignal, isUuid, observeSignaling, withLoopbackFallback } from './signaling.js';
package/dist/listeners.js CHANGED
@@ -1,4 +1,15 @@
1
1
  const abortHub = new WeakMap();
2
+ /** @internal */
3
+ export function reportAsyncError(error) {
4
+ if (typeof globalThis.reportError === 'function') {
5
+ globalThis.reportError(error);
6
+ }
7
+ else {
8
+ queueMicrotask(() => {
9
+ throw error;
10
+ });
11
+ }
12
+ }
2
13
  /**
3
14
  * Subscribe `fn` to an `AbortSignal` while attaching at most ONE native `'abort'`
4
15
  * listener per `AbortSignal` across all Meshpost primitives (preventing Node.js
@@ -25,7 +36,7 @@ export function bindAbort(signal, fn) {
25
36
  cb();
26
37
  }
27
38
  catch (error) {
28
- globalThis.reportError?.(error);
39
+ reportAsyncError(error);
29
40
  }
30
41
  }
31
42
  };
@@ -50,10 +61,13 @@ export function bindAbort(signal, fn) {
50
61
  };
51
62
  }
52
63
  /** @internal */
53
- export function createListeners() {
64
+ export function createListeners(onRemove) {
54
65
  const entries = new Set();
55
66
  let closed = false;
56
67
  return {
68
+ get size() {
69
+ return entries.size;
70
+ },
57
71
  add(fn, options) {
58
72
  if (typeof fn !== 'function')
59
73
  throw new TypeError('Expected a listener function');
@@ -68,6 +82,7 @@ export function createListeners() {
68
82
  if (!entries.delete(entry))
69
83
  return;
70
84
  unbindAbort?.();
85
+ onRemove?.();
71
86
  }
72
87
  };
73
88
  entries.add(entry);
@@ -84,7 +99,7 @@ export function createListeners() {
84
99
  entry.fn(...args);
85
100
  }
86
101
  catch (error) {
87
- globalThis.reportError?.(error);
102
+ reportAsyncError(error);
88
103
  }
89
104
  }
90
105
  },