@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/blob.js +36 -36
- package/dist/channel.d.ts +4 -0
- package/dist/channel.js +4 -0
- package/dist/combine.d.ts +9 -2
- package/dist/combine.js +35 -33
- package/dist/index.d.ts +2 -1
- package/dist/mqtt.js +59 -109
- package/dist/nostr.js +71 -131
- package/dist/peer-link.js +983 -0
- package/dist/presence.js +74 -0
- package/dist/public.js +16 -23
- package/dist/relay-core.js +219 -143
- package/dist/room-reclaim.js +5 -1
- package/dist/room.js +300 -463
- package/dist/rpc.js +25 -28
- package/dist/signaling.js +2 -11
- package/dist/state.js +22 -31
- package/dist/tabs.js +6 -50
- package/dist/voice-mic.js +496 -0
- package/dist/voice-remote.js +568 -0
- package/dist/voice.d.ts +8 -0
- package/dist/voice.js +71 -816
- package/dist/ws.js +20 -58
- package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
- package/docs/api.md +6 -4
- package/docs/behavior.md +4 -4
- package/package.json +4 -2
- package/dist/room-hello.js +0 -129
- package/dist/room-ice.js +0 -115
- package/dist/room-media.js +0 -477
- package/dist/voice-helpers.js +0 -100
- package/dist/voice-meter.d.ts +0 -1
- package/dist/voice-meter.js +0 -79
- /package/dist/{room-hello.d.ts → peer-link.d.ts} +0 -0
- /package/dist/{room-ice.d.ts → presence.d.ts} +0 -0
- /package/dist/{room-media.d.ts → voice-mic.d.ts} +0 -0
- /package/dist/{voice-helpers.d.ts → voice-remote.d.ts} +0 -0
package/dist/ws.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { createReplayGuard, deriveSignalingKeys, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
|
|
2
|
-
import { createErrorThrottle
|
|
2
|
+
import { createErrorThrottle } from './presence.js';
|
|
3
|
+
import { maxDecryptQueueDepth, normalizeWsRelayUrl, resolveSessionPassword, resolveSessionWebSocket, safeCloseSocket, startKeyDerivation, validateCommonSignalingOptions, validatePositiveTimeout } from './relay-core.js';
|
|
3
4
|
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
4
5
|
const wsOpen = 1;
|
|
5
6
|
const defaultOptionalHandshakeTimeoutMs = 4_000;
|
|
6
7
|
const maxFrameBytes = 128 * 1024;
|
|
7
8
|
const maxPeers = 256;
|
|
8
9
|
const maxEncryptQueueDepth = 128;
|
|
9
|
-
const maxDecryptQueueDepth = 64;
|
|
10
10
|
const defaultHandshakeTimeoutMs = 10_000;
|
|
11
11
|
const defaultPingIntervalMs = 25_000;
|
|
12
12
|
const insecureWsMessage = 'Password encryption requires a secure context (crypto.subtle); pass encrypt: false for plaintext LAN testing';
|
|
@@ -21,42 +21,19 @@ function createWsSignaling(url, options, optional) {
|
|
|
21
21
|
if (options.encrypt !== undefined && typeof options.encrypt !== 'boolean') {
|
|
22
22
|
throw new TypeError('Invalid encrypt option');
|
|
23
23
|
}
|
|
24
|
-
|
|
25
|
-
throw new TypeError('Invalid privateTopic option');
|
|
26
|
-
}
|
|
27
|
-
if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
|
|
28
|
-
throw new TypeError('Invalid WebSocket constructor');
|
|
29
|
-
}
|
|
24
|
+
validateCommonSignalingOptions(options);
|
|
30
25
|
return (discovery) => {
|
|
31
|
-
const WsCtor = options.WebSocket
|
|
32
|
-
if (typeof WsCtor !== 'function') {
|
|
33
|
-
throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
|
|
34
|
-
}
|
|
35
|
-
const password = discovery.password;
|
|
26
|
+
const WsCtor = resolveSessionWebSocket(options.WebSocket);
|
|
36
27
|
const encrypt = options.encrypt ?? true;
|
|
37
28
|
const privateTopic = options.privateTopic ?? false;
|
|
38
|
-
|
|
39
|
-
throw new TypeError('privateTopic requires a room password');
|
|
40
|
-
}
|
|
41
|
-
if (privateTopic && !encrypt) {
|
|
42
|
-
throw new Error('privateTopic requires encrypt: true');
|
|
43
|
-
}
|
|
44
|
-
const useEncryption = password !== undefined && encrypt;
|
|
45
|
-
if (password !== undefined) {
|
|
46
|
-
if (typeof password !== 'string' || password.length === 0) {
|
|
47
|
-
throw new TypeError('Invalid password');
|
|
48
|
-
}
|
|
49
|
-
if (useEncryption && !globalThis.crypto?.subtle) {
|
|
50
|
-
throw new Error(insecureWsMessage);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
29
|
+
const { password, useEncryption } = resolveSessionPassword(discovery.password, privateTopic, encrypt, insecureWsMessage);
|
|
53
30
|
const baseScope = discovery.appId + ':' + discovery.room;
|
|
54
31
|
let roomKey = privateTopic
|
|
55
32
|
? ''
|
|
56
33
|
: namespaceHash(baseScope + (!useEncryption && password !== undefined ? ':' + password : ''));
|
|
57
34
|
const knownPeers = new Set();
|
|
58
35
|
const replayGuard = createReplayGuard();
|
|
59
|
-
const emitError = createErrorThrottle(discovery);
|
|
36
|
+
const emitError = createErrorThrottle((code, message) => discovery.error?.(code, message));
|
|
60
37
|
let ws;
|
|
61
38
|
let closed = false;
|
|
62
39
|
let reportedOnline = false;
|
|
@@ -70,7 +47,7 @@ function createWsSignaling(url, options, optional) {
|
|
|
70
47
|
let sendChain = Promise.resolve();
|
|
71
48
|
let recvChain = Promise.resolve();
|
|
72
49
|
let resolvedKey;
|
|
73
|
-
const keysPromise = useEncryption
|
|
50
|
+
const keysPromise = useEncryption && password !== undefined
|
|
74
51
|
? deriveSignalingKeys(password, baseScope, insecureWsMessage)
|
|
75
52
|
: undefined;
|
|
76
53
|
let handshakeTimer;
|
|
@@ -349,37 +326,22 @@ function createWsSignaling(url, options, optional) {
|
|
|
349
326
|
scheduleReconnect();
|
|
350
327
|
};
|
|
351
328
|
};
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
329
|
+
startKeyDerivation({
|
|
330
|
+
keysPromise,
|
|
331
|
+
privateTopic,
|
|
332
|
+
isClosed: () => closed,
|
|
333
|
+
onResolvedKey(key) {
|
|
334
|
+
resolvedKey = key;
|
|
335
|
+
},
|
|
336
|
+
onPrivateKeys(keys) {
|
|
357
337
|
roomKey = 'p_' + keys.privateId;
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
.catch(() => {
|
|
362
|
-
if (closed)
|
|
363
|
-
return;
|
|
338
|
+
},
|
|
339
|
+
onConnect: connect,
|
|
340
|
+
onError() {
|
|
364
341
|
reportOffline('WebSocket signaling key derivation failed');
|
|
365
|
-
|
|
366
|
-
}
|
|
367
|
-
else {
|
|
368
|
-
if (keysPromise) {
|
|
369
|
-
void keysPromise
|
|
370
|
-
.then((keys) => {
|
|
371
|
-
resolvedKey = keys.aeadKey;
|
|
372
|
-
})
|
|
373
|
-
.catch(() => {
|
|
374
|
-
if (closed)
|
|
375
|
-
return;
|
|
376
|
-
reportOffline('WebSocket signaling key derivation failed');
|
|
377
|
-
safeCloseSocket(ws);
|
|
378
|
-
});
|
|
342
|
+
safeCloseSocket(ws);
|
|
379
343
|
}
|
|
380
|
-
|
|
381
|
-
queueMicrotask(connect);
|
|
382
|
-
}
|
|
344
|
+
});
|
|
383
345
|
return {
|
|
384
346
|
trickle: true,
|
|
385
347
|
send(to, signal) {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# ADR-0001: Public `Channel.maxPayloadBytes` vs Internal `Room` Lifecycle Hooks
|
|
2
|
+
|
|
3
|
+
- **Status:** Accepted
|
|
4
|
+
- **Date:** 2026-12-06
|
|
5
|
+
|
|
6
|
+
## Context
|
|
7
|
+
|
|
8
|
+
Higher-level protocol modules built on top of `Room` (`src/channel.ts`, `src/state.ts`, `src/rpc.ts`, `src/blob.ts`, and `src/voice.ts`) share two cross-cutting needs:
|
|
9
|
+
|
|
10
|
+
1. **Packet budget accounting:** `Room` enforces a `16,384`-byte (16 KiB) per-packet limit, and `createChannel()` reserves `1 + utf8(name).length` bytes for its framing header. Previously, `src/peer-link.ts`, `src/state.ts`, and `src/blob.ts` each hardcoded `16 * 1024`, and `state.ts` and `blob.ts` independently re-encoded `name` to compute remaining payload bytes. Application authors writing custom binary protocols over `Channel` had no public way to query the exact usable payload budget either.
|
|
11
|
+
2. **Lifecycle and stream coordination:** Protocol helpers must clean up timers, pending promises, and listeners automatically when `room.leave()` is called—without closing prematurely when a signaling adapter transitions to `'closed'` while live WebRTC links remain open. Additionally, `createVoice()` must discover already-active remote `MediaStream`s when attached after peers have joined.
|
|
12
|
+
|
|
13
|
+
This raised an API design question: should we promote `onRoomClose` / `getRemoteStreams` onto the public `Room` interface, or keep them internal while exposing `maxPayloadBytes` on `Channel`?
|
|
14
|
+
|
|
15
|
+
## Decision
|
|
16
|
+
|
|
17
|
+
1. **Expose `readonly maxPayloadBytes: number` publicly on `Channel` and `CodecChannel<T>`.**
|
|
18
|
+
- Computed once from the single internal constant `maxPacketBytes` (`16 * 1024` in `src/peer-link.ts`) minus the channel prefix (`1 + utf8(name).length`).
|
|
19
|
+
- Internal protocol modules (`src/state.ts`, `src/blob.ts`) derive their payload/chunk caps directly from `channel.maxPayloadBytes`, eliminating duplicated `16 * 1024` constants and UTF-8 framing math.
|
|
20
|
+
- Publicly useful to downstream applications building custom framing over `createChannel()` or `createCodecChannel()`, and 100% additive/backward-compatible because consumers create channels via `createChannel()` rather than hand-implementing the `Channel` interface.
|
|
21
|
+
2. **Keep `isRoomClosed`, `onRoomClose`, `bindRoomLifecycle`, and `getRoomRemoteStreams` internal (backed by `WeakMap<Room, RoomInternals>`).**
|
|
22
|
+
- Consolidate duplicated `closed` + `AbortController` + `onRoomClose` teardown ceremony across `state.ts`, `rpc.ts`, and `blob.ts` into a single internal `bindRoomLifecycle(room, onShutdown)` helper in `src/room.ts`.
|
|
23
|
+
- Retain the fallback to `room.signalingState === 'closed'` / `room.onSignalingChange` when a caller passes a duck-typed mock `Room` in unit tests.
|
|
24
|
+
- Do **not** add new required methods to the public `Room` interface.
|
|
25
|
+
|
|
26
|
+
## Consequences
|
|
27
|
+
|
|
28
|
+
- **Zero breaking changes for downstream TypeScript consumers:** Projects that write duck-typed mock `Room` objects in their own test suites (such as `netwars` or Meshpost's own `tests/unit/helpers/mock-room.mjs`) continue to compile without implementing extra lifecycle/introspection methods, while still receiving automatic teardown on `leave()` via `bindRoomLifecycle`.
|
|
29
|
+
- **Single source of truth for framing limits:** `maxPacketBytes` lives once in `src/peer-link.ts`, `Channel.maxPayloadBytes` computes the channel overhead once in `src/channel.ts`, and `PeerState` / `BlobChannel` subtract only their own header size.
|
|
30
|
+
- **Minimal public `Room` surface:** `Room` remains focused on peer connectivity, binary packets, and media tracks, keeping the mental model small for library users.
|
|
31
|
+
- **Trade-off:** Third-party custom helpers outside Meshpost that need `room.leave()` detection still rely on `room.onSignalingChange((s) => s === 'closed')` or explicit `.close()` calls; if a strong ecosystem use case emerges in `v1.0`, a public `room.closed` or `room.signal` (`AbortSignal`) can be considered as a planned major-version enhancement.
|
package/docs/api.md
CHANGED
|
@@ -68,10 +68,10 @@
|
|
|
68
68
|
- `createChannel(room: Room, name: string, options?: ChannelOptions): Channel`
|
|
69
69
|
- Multiplexes a named channel (`1..64` UTF-8 bytes) over the room's existing data channels in `O(1)` dispatch time.
|
|
70
70
|
- `ChannelOptions = { delivery?: Delivery }` (default `'unreliable'`).
|
|
71
|
-
- `Channel`: `name`, `delivery`, `send(bytes, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onPacket(fn, options?)`.
|
|
71
|
+
- `Channel`: `name`, `delivery`, `maxPayloadBytes` (`16384 - 1 - utf8(name).length`), `send(bytes, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onPacket(fn, options?)`.
|
|
72
72
|
- `createCodecChannel<T>(room: Room, name: string, codec: Codec<T>, options?: ChannelOptions): CodecChannel<T>`
|
|
73
73
|
- `Codec<T> = { encode(value: T): Uint8Array, decode(bytes: Uint8Array): T }`.
|
|
74
|
-
- `CodecChannel<T>`: `name`, `delivery`, `send(value, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onMessage(fn, options?)`. Malformed frames are dropped without consuming `{ once: true }`.
|
|
74
|
+
- `CodecChannel<T>`: `name`, `delivery`, `maxPayloadBytes`, `send(value, options?: { to?: string }): ReadonlyMap<string, SendResult>`, `onMessage(fn, options?)`. Malformed frames are dropped without consuming `{ once: true }`.
|
|
75
75
|
- Built-in codecs:
|
|
76
76
|
- `binaryCodec: Codec<Uint8Array>` (zero-copy identity)
|
|
77
77
|
- `textCodec: Codec<string>` (strict UTF-8)
|
|
@@ -116,9 +116,10 @@
|
|
|
116
116
|
|
|
117
117
|
- `createVoice(room: Room, options?: VoiceOptions): Voice`
|
|
118
118
|
- Options: `volume` (`1`), `deafened` (`false`), `deviceId` (`null`), `fallbackToDefaultOnNotFound` (`false`), `audioConstraints` (`{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }`), `autoUnlock` (`true`), `speakingDetection` (`true`), `speakingThreshold` (`0.03`), `speakingIntervalMs` (`180`), `to`, `streamTag` (`'voice'`), `strictStreamTag` (`false`).
|
|
119
|
-
- Snapshot fields (also exposed directly as readonly properties on `Voice`): `micStatus: MicStatus`, `micError: MicError | null`, `deviceId: string | null`, `autoplayBlocked: boolean`, `deafened: boolean`, `volume: number`, `selfSpeaking: boolean`, `remotePeers: readonly string[]`, `speakingPeers: readonly string[]`, `mutedPeers: readonly string[]`, `peerVolumes: Readonly<Record<string, number>>`.
|
|
119
|
+
- Snapshot fields (also exposed directly as readonly properties on `Voice`): `micStatus: MicStatus`, `micError: MicError | null`, `micStopReason: MicStopReason | null`, `deviceId: string | null`, `autoplayBlocked: boolean`, `deafened: boolean`, `volume: number`, `selfSpeaking: boolean`, `remotePeers: readonly string[]`, `speakingPeers: readonly string[]`, `mutedPeers: readonly string[]`, `peerVolumes: Readonly<Record<string, number>>`.
|
|
120
120
|
- Methods: `getSnapshot()`, `toggleMic()`, `startMic()`, `setMuted(muted)`, `stopMic()`, `switchDevice(deviceId?)`, `setVolume(volume)`, `setPeerVolume(peerId, volume)`, `getPeerVolume(peerId)`, `setDeafened(deafened)`, `setPeerMuted(peerId, muted)`, `isPeerMuted(peerId)`, `unlockAudio()`, `onChange(fn, options?)`, `close()` (also runs automatically on `room.leave()`).
|
|
121
121
|
- `MicStatus = 'off' | 'requesting' | 'live' | 'muted' | 'error'`.
|
|
122
|
+
- `MicStopReason = 'stopped' | 'ended'` (`'stopped'` after local `stopMic()`/`close()`, `'ended'` after unexpected hardware `track.onended`, `null` before first stop or while active/errored).
|
|
122
123
|
- `MicErrorCode = 'permission-denied' | 'not-found' | 'in-use' | 'insecure-context' | 'room-closed' | 'unknown'`.
|
|
123
124
|
- `listAudioInputs(): Promise<readonly AudioInputDevice[]>` — Safe cross-runtime audio input enumeration (`{ deviceId, label, groupId }`).
|
|
124
125
|
- `onAudioInputsChange(fn: (devices: readonly AudioInputDevice[]) => void, options?: AudioInputsChangeOptions): () => void`
|
|
@@ -195,7 +196,8 @@
|
|
|
195
196
|
## `@dimchansky/meshpost/combine`
|
|
196
197
|
|
|
197
198
|
- `combineSignaling(...adapters: readonly Signaling[]): Signaling`
|
|
198
|
-
- `withLocalTabs(primary: Signaling): Signaling`
|
|
199
|
+
- `withLocalTabs(primary: Signaling, options?: WithLocalTabsOptions): Signaling`
|
|
200
|
+
- `WithLocalTabsOptions = { onTabsState?: (state: SignalingState, reason?: string) => void }`.
|
|
199
201
|
|
|
200
202
|
---
|
|
201
203
|
|
package/docs/behavior.md
CHANGED
|
@@ -84,10 +84,10 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
|
|
|
84
84
|
- `createCodecChannel()` throws `TypeError` for an invalid `codec`, non-`Uint8Array` `encode()` return, or non-function `onMessage` listener; `jsonCodec()` throws `TypeError` for a non-function `validate` or unserializable value (`undefined`).
|
|
85
85
|
- `createRpc()` throws `TypeError` for an invalid `room`, `requestCodec`, `responseCodec`, or `handle` callback, `Error` if a second active `handle()` is registered on the same `RpcEndpoint`, and `RangeError` for out-of-range `timeoutMs`, `maxPendingCalls`, or `maxConcurrentPerPeer`. `rpc.call()` rejects with `TypeError`/`RangeError` for invalid `peerId`/`timeoutMs`, or with `RpcError`.
|
|
86
86
|
- `createPeerState()` throws `TypeError` for an invalid `room`, `delivery`, `coalesce`, `codec`, `undefined` state value, or non-function `onChange` listener; `RangeError` if `initial` or `set(value)` encodes past the 16 KiB packet limit; and `Error` when calling `set()` or `clear()` after `close()` or `room.leave()`.
|
|
87
|
-
- `createBlobChannel()` throws `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
|
|
87
|
+
- `createBlobChannel()` throws `TypeError` for an invalid `room`, and `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
|
|
88
88
|
- `wsSignaling()` and `optionalWsSignaling()` throw `TypeError` for non-`ws:`/`wss:` URLs, non-boolean `encrypt`/`privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option; `Error` if `privateTopic: true` is combined with `encrypt: false` or if `WebSocket` is unavailable at session startup; and `RangeError` for invalid `handshakeTimeoutMs` or `pingIntervalMs`.
|
|
89
89
|
- `publicSignaling()` throws `TypeError` for invalid options, non-`ws:`/`wss:` or empty-string `wsUrls`, non-boolean `localTabs`/`wsEncrypt`/`privateTopic`, invalid `mqtt`/`nostr`/`appId`, a non-function `WebSocket` option, or a non-function `onTransportChange` callback; and `RangeError` when both `mqtt: false` and `nostr: false`, when `mqtt`/`nostr` is an empty array, when `wsUrls` exceeds `8` unique (`64` raw) entries, or when `wsHandshakeTimeoutMs` / `handshakeTimeoutMs` is out of range.
|
|
90
|
-
- `combineSignaling()` throws `RangeError` when given 0 adapters and `TypeError` if any argument is not a function; `withLocalTabs()` throws `TypeError` if `primary` is not a function.
|
|
90
|
+
- `combineSignaling()` throws `RangeError` when given 0 adapters and `TypeError` if any argument is not a function; `withLocalTabs()` throws `TypeError` if `primary` is not a function or `options` / `options.onTabsState` is invalid.
|
|
91
91
|
- `mqttSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, `TypeError` for an empty `password`, non-boolean `privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option, and `Error` if `WebSocket` is unavailable at session startup.
|
|
92
92
|
- `nostrSignaling()` throws `RangeError` for empty `urls` or invalid `handshakeTimeoutMs`, `TypeError` for non-`ws:`/`wss:` `urls`, invalid `appId`, empty `password`, non-boolean `privateTopic`, `privateTopic: true` without `password`, or a non-function `WebSocket` option, and `Error` if `WebSocket` is unavailable at session startup.
|
|
93
93
|
- `createVoice()` throws `TypeError` for invalid `room`, `deviceId`, `fallbackToDefaultOnNotFound`, `audioConstraints`, `to`, `streamTag`, or `strictStreamTag`, and `RangeError` for out-of-range `volume`, `speakingThreshold`, or `speakingIntervalMs`. `onAudioInputsChange()` throws `TypeError` for a non-function listener or a non-boolean `immediate` option. `voice.setVolume()` and `voice.setPeerVolume()` throw `RangeError` for non-finite numbers; `voice.setPeerVolume()` and `voice.setPeerMuted()` throw `TypeError` for invalid `peerId` strings (`1..128` chars); `voice.switchDevice()` rejects with `TypeError` for whitespace-only/non-string `deviceId` values.
|
|
@@ -174,7 +174,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
174
174
|
|
|
175
175
|
### Logical channels (`createChannel` & `createCodecChannel`)
|
|
176
176
|
|
|
177
|
-
- `createChannel(room, name, { delivery })` frames packets as `[nameLen (1 byte), ...utf8(name), ...payload]
|
|
177
|
+
- `createChannel(room, name, { delivery })` frames packets as `[nameLen (1 byte), ...utf8(name), ...payload]` and exposes `maxPayloadBytes` (`16,384 - 1 - nameLen`) so callers and higher-level helpers do not hardcode framing overhead.
|
|
178
178
|
- `nameLen` is `1–64` bytes. A lazy per-`Room` `WeakMap` router attaches a single shared `room.onPacket` listener while at least one channel subscriber is active, decodes `name` once with strict UTF-8 (`fatal: true`), dispatches in `O(1)` time to matching subscribers (isolating each callback with `try/catch` + `reportError`), and passes a zero-copy `subarray` view of the original `Uint8Array`.
|
|
179
179
|
- `createCodecChannel(room, name, codec, options?)` wraps `createChannel` with synchronous `codec.encode(value)` on `send()` (preserving synchronous `ReadonlyMap<string, SendResult>`) and guarded `codec.decode(bytes)` on `onMessage` (dropping malformed frames without consuming `{ once: true }`).
|
|
180
180
|
|
|
@@ -235,7 +235,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
235
235
|
- Zero-dependency MQTT 3.1.1 client over WebSocket connecting to `urls` (default `defaultMqttRelays`) in parallel.
|
|
236
236
|
- Waits for `CONNACK` and `SUBACK` within `handshakeTimeoutMs` (`10 s`), monitors `PINGRESP` every 20 s, and caps incoming buffers at `128 KiB`.
|
|
237
237
|
- Splits traffic across two topics: `${roomTopic}` for presence (`hello`, `heartbeat`, `bye`) and `${roomTopic}/${peerId}` for targeted `present` and `signal` messages (`roomTopic` is `'meshpost/1/' + namespaceHash(appId:room)` by default, or `'meshpost/1/p/' + privateId` after key derivation when `privateTopic: true`).
|
|
238
|
-
- Deduplicates messages across brokers using `${from}:${mid}` with a `120 s` TTL (and reuses one startup `mid` for initial `hello`)
|
|
238
|
+
- Deduplicates messages across brokers using `${from}:${mid}` with a `120 s` TTL (and reuses one startup `mid` for initial `hello`), caps pending async `AES-256-GCM` decrypts at `64`, and emits rate-limited `'clock-skew'` for valid AEAD frames outside `±60 s` without polluting `seenMids` or the peer roster.
|
|
239
239
|
- Transitions to `'offline'` if all brokers fail on startup or disconnect later, then reconnects with jittered backoff.
|
|
240
240
|
|
|
241
241
|
### `nostrSignaling(options?)`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dimchansky/meshpost",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"author": "Dmitrij Koniajev",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -121,7 +121,9 @@
|
|
|
121
121
|
"check:readme": "node scripts/check-readme.mjs",
|
|
122
122
|
"check:pkg": "publint && npm run check:readme",
|
|
123
123
|
"demo": "npm run build && node examples/build.mjs",
|
|
124
|
-
"test": "
|
|
124
|
+
"test:unit": "node --test tests/unit/*.test.mjs",
|
|
125
|
+
"test:e2e": "npm run demo && playwright test",
|
|
126
|
+
"test": "npm run demo && npm run test:unit && playwright test",
|
|
125
127
|
"demo:tabs": "npm run demo && node examples/serve.mjs",
|
|
126
128
|
"prepack": "npm run clean && npm run build",
|
|
127
129
|
"format": "prettier --write .",
|
package/dist/room-hello.js
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/room-ice.js
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
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
|
-
}
|