@dimchansky/meshpost 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -15
- package/dist/combine.js +15 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -1
- package/dist/public.d.ts +52 -0
- package/dist/public.js +133 -0
- package/dist/ws.d.ts +29 -0
- package/dist/ws.js +59 -0
- package/docs/behavior.md +10 -2
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -32,15 +32,16 @@ Meshpost connects peers directly over WebRTC to exchange binary packets, typed m
|
|
|
32
32
|
2. Import `joinRoom` and a signaling adapter (used only to help browsers find each other) in your browser app (use `@dimchansky/meshpost` if installed as a package, or `./dist/index.js` from a local build):
|
|
33
33
|
|
|
34
34
|
```ts
|
|
35
|
-
import { joinRoom,
|
|
35
|
+
import { joinRoom, publicSignaling } from '@dimchansky/meshpost'
|
|
36
36
|
|
|
37
37
|
const encoder = new TextEncoder()
|
|
38
38
|
const decoder = new TextDecoder()
|
|
39
39
|
|
|
40
|
-
// Join a room. Browsers with the same appId and room name connect automatically
|
|
40
|
+
// Join a room. Browsers with the same appId and room name connect automatically
|
|
41
|
+
// over local tabs + public MQTT + port-443 Nostr relays (plus optional wsUrls).
|
|
41
42
|
const room = joinRoom('lobby', {
|
|
42
43
|
appId: 'my-chat-app',
|
|
43
|
-
signaling:
|
|
44
|
+
signaling: publicSignaling()
|
|
44
45
|
})
|
|
45
46
|
|
|
46
47
|
room.onPeerJoin((peerId) => console.log('Joined:', peerId))
|
|
@@ -92,16 +93,18 @@ Meshpost connects peers directly over WebRTC to exchange binary packets, typed m
|
|
|
92
93
|
|
|
93
94
|
Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
|
|
94
95
|
|
|
95
|
-
| Adapter
|
|
96
|
-
|
|
|
97
|
-
| `
|
|
98
|
-
| `
|
|
99
|
-
| `
|
|
100
|
-
| `
|
|
101
|
-
| `
|
|
102
|
-
| `
|
|
103
|
-
| `
|
|
104
|
-
|
|
|
96
|
+
| Adapter | Best for | Server needed? |
|
|
97
|
+
| --------------------------------- | ------------------------------------------------------------------------------------- | ------------------- |
|
|
98
|
+
| `publicSignaling(options?)` | All-in-one preset: local tabs + MQTT + port-443 Nostr + optional fast `wsUrls` | No (optional WS) |
|
|
99
|
+
| `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
|
|
100
|
+
| `nostrSignaling(options?)` | Corporate/school Wi-Fi blocking MQTT ports (runs over port-443 `wss://`) | No (public relays) |
|
|
101
|
+
| `wsSignaling(url, options?)` | Production apps with a primary WebSocket relay (see `examples/ws-worker/`) | Your WS / CF Worker |
|
|
102
|
+
| `optionalWsSignaling(url, opts?)` | Opportunistic WS fast-path inside `combineSignaling` (silent fallback if unreachable) | Optional WS |
|
|
103
|
+
| `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
|
|
104
|
+
| `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
|
|
105
|
+
| `withLocalTabs(primary)` | Instant same-browser tabs + remote MQTT/Nostr/WS with accurate network state | Same as `primary` |
|
|
106
|
+
| `combineSignaling(...list)` | Composing multiple network adapters (e.g. `mqttSignaling` + `nostrSignaling`) | Depends on list |
|
|
107
|
+
| Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
|
|
105
108
|
|
|
106
109
|
### Local tabs (`tabSignaling`)
|
|
107
110
|
|
|
@@ -442,15 +445,17 @@ const results = await files.send(fileBytes, {
|
|
|
442
445
|
|
|
443
446
|
### Signaling exports
|
|
444
447
|
|
|
448
|
+
- `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket? })` — Ready-made URL-agnostic composite adapter combining `mqttSignaling()` + port-443 `nostrSignaling()`, wrapped in `withLocalTabs(...)` (defaults: `mqtt: true`, `nostr: true`, `localTabs: true`, `wsEncrypt: true`, `privateTopic: false`, `wsHandshakeTimeoutMs: 4_000`, `handshakeTimeoutMs: 10_000`), plus zero or more app-supplied opportunistic WebSocket relays (`wsUrls?: string | readonly string[]`, max `8` unique URLs). Any unreachable or `403`-rejected `wsUrls` entry closes silently without reconnect storms while public relays carry the room.
|
|
445
449
|
- `mqttSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`), with optional `AES-256-GCM` E2E encryption, `privateTopic` topic hiding, and optional custom `WebSocket` constructor injection.
|
|
446
450
|
- `nostrSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Zero-server signaling over public **port-443** NIP-01 Nostr relays (`defaultNostrRelays`) using ephemeral `kind: 25050` events (never persisted by relays), pure-TS BIP-340 Schnorr signatures (0 dependencies, tree-shakeable), optional `AES-256-GCM` E2E encryption + `privateTopic` tag hiding, and optional custom `WebSocket` constructor injection.
|
|
447
451
|
- `wsSignaling(url, { reconnect?, handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Connects browsers through your own WebSocket (`ws://` / `wss://`) signaling server (defaults: `reconnect: true`, `handshakeTimeoutMs: 10_000`, `pingIntervalMs: 25_000`, `encrypt: true`, `privateTopic: false`). Automatically appends `?room=<roomKey>` for stateless per-room sharding and E2E-encrypts signaling (`box` envelopes) when `password` is set. See [examples/ws-worker/](examples/ws-worker/README.md) for a ready-to-deploy Cloudflare Worker + Durable Object (WebSocket Hibernation) relay, or [examples/serve.mjs](examples/serve.mjs) for Node.js.
|
|
452
|
+
- `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
448
453
|
- `withLocalTabs(primary)` — Decorates a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant same-browser `BroadcastChannel` discovery (`tabSignaling()`) while **preserving `primary`'s `SignalingState`** for `room.signalingState` / `room.onSignalingChange` (avoiding a stuck `'online'` state when internet connectivity drops, while still connecting local tabs offline). Safely falls back to `primary` on `file:` / opaque origins or when `BroadcastChannel` is unavailable.
|
|
449
454
|
- `combineSignaling(...adapters)` — Combines multiple `Signaling` adapters, merging peer rosters and keeping discovery online as long as any child adapter is online (e.g. `combineSignaling(wsSignaling('wss://primary.example/ws'), mqttSignaling())`).
|
|
450
455
|
- `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
|
|
451
456
|
- `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
|
|
452
457
|
- `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
|
|
453
|
-
- Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
|
|
458
|
+
- Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `PublicSignalingOptions`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
|
|
454
459
|
|
|
455
460
|
## Connecting through strict firewalls (TURN)
|
|
456
461
|
|
|
@@ -474,7 +479,7 @@ const room = joinRoom('lobby', {
|
|
|
474
479
|
|
|
475
480
|
### Subpath exports & bundler-free `<script type="importmap">`
|
|
476
481
|
|
|
477
|
-
Every feature module is available as a dedicated subpath export (`@dimchansky/meshpost/room`, `/channel`, `/rpc`, `/state`, `/blob`, `/voice`, `/turn`, `/identity`, `/mqtt`, `/nostr`, `/ws`, `/tabs`, `/manual`, `/combine`, `/signaling`) so bundler-free `<script type="importmap">` apps only download the modules they actually import:
|
|
482
|
+
Every feature module is available as a dedicated subpath export (`@dimchansky/meshpost/room`, `/channel`, `/rpc`, `/state`, `/blob`, `/voice`, `/turn`, `/identity`, `/public`, `/mqtt`, `/nostr`, `/ws`, `/tabs`, `/manual`, `/combine`, `/signaling`) so bundler-free `<script type="importmap">` apps only download the modules they actually import:
|
|
478
483
|
|
|
479
484
|
```html
|
|
480
485
|
<script type="importmap">
|
package/dist/combine.js
CHANGED
|
@@ -2,6 +2,7 @@ import { tabSignaling } from './tabs.js';
|
|
|
2
2
|
const maxSeenIcePeers = 256;
|
|
3
3
|
const maxSeenIceAttemptsPerPeer = 4;
|
|
4
4
|
const maxSeenIceKeysPerAttempt = 64;
|
|
5
|
+
const compositeErrorCooldownMs = 15_000;
|
|
5
6
|
function iceCandidateKey(item) {
|
|
6
7
|
return item.candidate + '\0' + (item.sdpMid ?? '') + '\0' + (item.sdpMLineIndex ?? '');
|
|
7
8
|
}
|
|
@@ -33,6 +34,8 @@ function createCompositeSession(discovery, list, primaryIndex) {
|
|
|
33
34
|
let closed = false;
|
|
34
35
|
let aggState = 'connecting';
|
|
35
36
|
let lastReason;
|
|
37
|
+
let lastDecryptErrorAt = -Infinity;
|
|
38
|
+
let lastClockSkewErrorAt = -Infinity;
|
|
36
39
|
let publishedRoster = new Set();
|
|
37
40
|
let rosterDirty = false;
|
|
38
41
|
const computeAggregateState = () => {
|
|
@@ -204,6 +207,18 @@ function createCompositeSession(discovery, list, primaryIndex) {
|
|
|
204
207
|
return;
|
|
205
208
|
if (primaryIndex !== null && index !== primaryIndex)
|
|
206
209
|
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;
|
|
221
|
+
}
|
|
207
222
|
if (initializing) {
|
|
208
223
|
buffered.push({ kind: 'error', code, message });
|
|
209
224
|
return;
|
package/dist/index.d.ts
CHANGED
|
@@ -21,8 +21,10 @@ export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
|
|
|
21
21
|
export type { MqttSignalingOptions } from './mqtt.js';
|
|
22
22
|
export { defaultNostrRelays, nostrSignaling } from './nostr.js';
|
|
23
23
|
export type { NostrSignalingOptions } from './nostr.js';
|
|
24
|
-
export { wsSignaling } from './ws.js';
|
|
25
|
-
export type { WsSignalingOptions } from './ws.js';
|
|
24
|
+
export { optionalWsSignaling, wsSignaling } from './ws.js';
|
|
25
|
+
export type { OptionalWsSignalingOptions, WsSignalingOptions } from './ws.js';
|
|
26
|
+
export { publicSignaling } from './public.js';
|
|
27
|
+
export type { PublicSignalingOptions } from './public.js';
|
|
26
28
|
export { combineSignaling, withLocalTabs } from './combine.js';
|
|
27
29
|
export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
|
|
28
30
|
export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState, WebSocketConstructor } from './signaling.js';
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,7 @@ export { tabSignaling } from './tabs.js';
|
|
|
10
10
|
export { manualSignaling } from './manual.js';
|
|
11
11
|
export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
|
|
12
12
|
export { defaultNostrRelays, nostrSignaling } from './nostr.js';
|
|
13
|
-
export { wsSignaling } from './ws.js';
|
|
13
|
+
export { optionalWsSignaling, wsSignaling } from './ws.js';
|
|
14
|
+
export { publicSignaling } from './public.js';
|
|
14
15
|
export { combineSignaling, withLocalTabs } from './combine.js';
|
|
15
16
|
export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
|
package/dist/public.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Signaling, WebSocketConstructor } from './signaling.js';
|
|
2
|
+
export interface PublicSignalingOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Optional opportunistic WebSocket signaling URL(s) (`ws://` or `wss://`, max 8 unique URLs)
|
|
5
|
+
* tried in parallel alongside public relays for low-latency discovery and instant rosters.
|
|
6
|
+
* Empty array `[]` or `undefined` skips WebSocket relays.
|
|
7
|
+
* Any unreachable or rejected (`403` / quota / blocked) URL closes silently without reconnect storms.
|
|
8
|
+
*/
|
|
9
|
+
wsUrls?: string | readonly string[];
|
|
10
|
+
/**
|
|
11
|
+
* Public MQTT-over-WebSocket broker URLs, `true` for `defaultMqttRelays`, or `false` to disable MQTT.
|
|
12
|
+
* @default true
|
|
13
|
+
*/
|
|
14
|
+
mqtt?: boolean | readonly string[];
|
|
15
|
+
/**
|
|
16
|
+
* Public port-443 Nostr relay URLs, `true` for `defaultNostrRelays`, or `false` to disable Nostr.
|
|
17
|
+
* @default true
|
|
18
|
+
*/
|
|
19
|
+
nostr?: boolean | readonly string[];
|
|
20
|
+
/**
|
|
21
|
+
* Wrap the network transports with `withLocalTabs(...)` for instant same-browser tab discovery
|
|
22
|
+
* while keeping `room.signalingState` tied to network connectivity.
|
|
23
|
+
* @default true
|
|
24
|
+
*/
|
|
25
|
+
localTabs?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Encrypt `wsUrls` signaling payloads end-to-end with AES-256-GCM when a room `password` is set.
|
|
28
|
+
* (MQTT and Nostr always require `crypto.subtle` encryption when `password` is set.)
|
|
29
|
+
* @default true
|
|
30
|
+
*/
|
|
31
|
+
wsEncrypt?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Derive room topics/keys cryptographically from `password` across all enabled transports
|
|
34
|
+
* so room activity is hidden on relays (requires a room `password`).
|
|
35
|
+
* @default false
|
|
36
|
+
*/
|
|
37
|
+
privateTopic?: boolean;
|
|
38
|
+
/** Optional application namespace override forwarded to MQTT and Nostr relays. */
|
|
39
|
+
appId?: string;
|
|
40
|
+
/** Handshake timeout in milliseconds for opportunistic `wsUrls` relays. @default 4000 */
|
|
41
|
+
wsHandshakeTimeoutMs?: number;
|
|
42
|
+
/** Handshake timeout in milliseconds for MQTT and Nostr relays. @default 10000 */
|
|
43
|
+
handshakeTimeoutMs?: number;
|
|
44
|
+
/** Optional custom `WebSocket` constructor forwarded to WS, MQTT, and Nostr transports. */
|
|
45
|
+
WebSocket?: WebSocketConstructor;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Out-of-the-box composite signaling combining public MQTT + port-443 Nostr relays,
|
|
49
|
+
* same-browser `BroadcastChannel` local tabs (`withLocalTabs`), and zero or more
|
|
50
|
+
* app-supplied opportunistic WebSocket relays (`wsUrls`).
|
|
51
|
+
*/
|
|
52
|
+
export declare function publicSignaling(options?: PublicSignalingOptions): Signaling;
|
package/dist/public.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { combineSignaling, withLocalTabs } from './combine.js';
|
|
2
|
+
import { mqttSignaling } from './mqtt.js';
|
|
3
|
+
import { nostrSignaling } from './nostr.js';
|
|
4
|
+
import { optionalWsSignaling } from './ws.js';
|
|
5
|
+
const maxOptionalWsUrls = 8;
|
|
6
|
+
const maxRawWsUrlItems = 64;
|
|
7
|
+
const defaultWsHandshakeTimeoutMs = 4_000;
|
|
8
|
+
const defaultPublicHandshakeTimeoutMs = 10_000;
|
|
9
|
+
function validateTimeoutMs(value, label) {
|
|
10
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {
|
|
11
|
+
throw new RangeError(`Invalid ${label}`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function normalizeWsUrls(raw) {
|
|
15
|
+
if (raw === undefined)
|
|
16
|
+
return [];
|
|
17
|
+
if (typeof raw === 'string') {
|
|
18
|
+
if (raw.length === 0)
|
|
19
|
+
throw new TypeError('Invalid WebSocket signaling URL');
|
|
20
|
+
return normalizeWsUrls([raw]);
|
|
21
|
+
}
|
|
22
|
+
if (!Array.isArray(raw)) {
|
|
23
|
+
throw new TypeError('wsUrls must be a URL string or an array of URL strings');
|
|
24
|
+
}
|
|
25
|
+
if (raw.length > maxRawWsUrlItems) {
|
|
26
|
+
throw new RangeError(`Too many wsUrls (max ${maxOptionalWsUrls} unique URLs)`);
|
|
27
|
+
}
|
|
28
|
+
const deduped = new Set();
|
|
29
|
+
for (const item of raw) {
|
|
30
|
+
if (typeof item !== 'string' || item.length === 0) {
|
|
31
|
+
throw new TypeError('Invalid WebSocket signaling URL');
|
|
32
|
+
}
|
|
33
|
+
let parsed;
|
|
34
|
+
try {
|
|
35
|
+
parsed = new URL(item);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw new TypeError('Invalid WebSocket signaling URL');
|
|
39
|
+
}
|
|
40
|
+
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
|
|
41
|
+
throw new TypeError('WebSocket signaling URL must use ws: or wss:');
|
|
42
|
+
}
|
|
43
|
+
deduped.add(parsed.toString());
|
|
44
|
+
if (deduped.size > maxOptionalWsUrls) {
|
|
45
|
+
throw new RangeError(`Too many wsUrls (max ${maxOptionalWsUrls} unique URLs)`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return [...deduped];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Out-of-the-box composite signaling combining public MQTT + port-443 Nostr relays,
|
|
52
|
+
* same-browser `BroadcastChannel` local tabs (`withLocalTabs`), and zero or more
|
|
53
|
+
* app-supplied opportunistic WebSocket relays (`wsUrls`).
|
|
54
|
+
*/
|
|
55
|
+
export function publicSignaling(options = {}) {
|
|
56
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) {
|
|
57
|
+
throw new TypeError('Invalid publicSignaling options');
|
|
58
|
+
}
|
|
59
|
+
const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor } = options;
|
|
60
|
+
if (typeof localTabs !== 'boolean')
|
|
61
|
+
throw new TypeError('Invalid localTabs option');
|
|
62
|
+
if (typeof wsEncrypt !== 'boolean')
|
|
63
|
+
throw new TypeError('Invalid wsEncrypt option');
|
|
64
|
+
if (typeof privateTopic !== 'boolean')
|
|
65
|
+
throw new TypeError('Invalid privateTopic option');
|
|
66
|
+
if (appId !== undefined && (typeof appId !== 'string' || appId.length === 0)) {
|
|
67
|
+
throw new TypeError('Invalid appId option');
|
|
68
|
+
}
|
|
69
|
+
if (WsCtor !== undefined && typeof WsCtor !== 'function') {
|
|
70
|
+
throw new TypeError('Invalid WebSocket constructor');
|
|
71
|
+
}
|
|
72
|
+
if (mqtt !== true && mqtt !== false && !Array.isArray(mqtt)) {
|
|
73
|
+
throw new TypeError('mqtt option must be a boolean or an array of broker URLs');
|
|
74
|
+
}
|
|
75
|
+
if (nostr !== true && nostr !== false && !Array.isArray(nostr)) {
|
|
76
|
+
throw new TypeError('nostr option must be a boolean or an array of relay URLs');
|
|
77
|
+
}
|
|
78
|
+
if (mqtt === false && nostr === false) {
|
|
79
|
+
throw new RangeError('publicSignaling requires at least one public relay transport (mqtt or nostr)');
|
|
80
|
+
}
|
|
81
|
+
validateTimeoutMs(wsHandshakeTimeoutMs, 'wsHandshakeTimeoutMs');
|
|
82
|
+
validateTimeoutMs(handshakeTimeoutMs, 'handshakeTimeoutMs');
|
|
83
|
+
const normalizedWsUrls = normalizeWsUrls(wsUrls);
|
|
84
|
+
const adapters = [];
|
|
85
|
+
for (const url of normalizedWsUrls) {
|
|
86
|
+
adapters.push(optionalWsSignaling(url, {
|
|
87
|
+
handshakeTimeoutMs: wsHandshakeTimeoutMs,
|
|
88
|
+
encrypt: wsEncrypt,
|
|
89
|
+
privateTopic,
|
|
90
|
+
...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
if (mqtt !== false) {
|
|
94
|
+
adapters.push(mqttSignaling({
|
|
95
|
+
...(Array.isArray(mqtt) ? { urls: mqtt } : {}),
|
|
96
|
+
...(appId !== undefined ? { appId } : {}),
|
|
97
|
+
privateTopic,
|
|
98
|
+
handshakeTimeoutMs,
|
|
99
|
+
...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
|
|
100
|
+
}));
|
|
101
|
+
}
|
|
102
|
+
if (nostr !== false) {
|
|
103
|
+
adapters.push(nostrSignaling({
|
|
104
|
+
...(Array.isArray(nostr) ? { urls: nostr } : {}),
|
|
105
|
+
...(appId !== undefined ? { appId } : {}),
|
|
106
|
+
privateTopic,
|
|
107
|
+
handshakeTimeoutMs,
|
|
108
|
+
...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
const network = combineSignaling(...adapters);
|
|
112
|
+
const pooledNetwork = (discovery) => {
|
|
113
|
+
let lastErrorMessage;
|
|
114
|
+
return network({
|
|
115
|
+
...discovery,
|
|
116
|
+
status(state, reason) {
|
|
117
|
+
discovery.status(state, reason);
|
|
118
|
+
if (state === 'offline') {
|
|
119
|
+
discovery.error?.('signaling-error', reason ?? lastErrorMessage ?? 'Public signaling disconnected');
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
error(code, message) {
|
|
123
|
+
if (code === 'signaling-error') {
|
|
124
|
+
if (message)
|
|
125
|
+
lastErrorMessage = message;
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
discovery.error?.(code, message);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
return localTabs ? withLocalTabs(pooledNetwork) : pooledNetwork;
|
|
133
|
+
}
|
package/dist/ws.d.ts
CHANGED
|
@@ -22,8 +22,37 @@ export interface WsSignalingOptions {
|
|
|
22
22
|
/** Optional custom `WebSocket` constructor for headless runtimes or custom transports. */
|
|
23
23
|
WebSocket?: WebSocketConstructor;
|
|
24
24
|
}
|
|
25
|
+
export interface OptionalWsSignalingOptions {
|
|
26
|
+
/** Maximum time in milliseconds to wait for the WebSocket handshake before abandoning it. @default 4000 */
|
|
27
|
+
handshakeTimeoutMs?: number;
|
|
28
|
+
/** Interval in milliseconds for client keepalive pings (`{ type: 'ping' }`). @default 25000 */
|
|
29
|
+
pingIntervalMs?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Encrypt signaling payloads end-to-end with AES-256-GCM when a room `password` is set
|
|
32
|
+
* so the WebSocket server sees only opaque `box` ciphertexts.
|
|
33
|
+
* Set `false` only for plain HTTP LAN testing where `crypto.subtle` is unavailable.
|
|
34
|
+
* @default true
|
|
35
|
+
*/
|
|
36
|
+
encrypt?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Derive the WebSocket room key cryptographically from `password` so room membership is isolated on the server
|
|
39
|
+
* (disables `'decrypt-failed'` detection when a peer enters the wrong password).
|
|
40
|
+
* @default false
|
|
41
|
+
*/
|
|
42
|
+
privateTopic?: boolean;
|
|
43
|
+
/** Optional custom `WebSocket` constructor for headless runtimes or custom transports. */
|
|
44
|
+
WebSocket?: WebSocketConstructor;
|
|
45
|
+
}
|
|
25
46
|
/**
|
|
26
47
|
* Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
|
|
27
48
|
* When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
|
|
28
49
|
*/
|
|
29
50
|
export declare function wsSignaling(url: string, options?: WsSignalingOptions): Signaling;
|
|
51
|
+
/**
|
|
52
|
+
* Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
|
|
53
|
+
* - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
|
|
54
|
+
* transitions cleanly to `'closed'` without reconnect storms.
|
|
55
|
+
* - Suppresses `'signaling-error'` so sibling relays (`tabSignaling`, `mqttSignaling`, `nostrSignaling`) carry
|
|
56
|
+
* the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
57
|
+
*/
|
|
58
|
+
export declare function optionalWsSignaling(url: string, options?: OptionalWsSignalingOptions): Signaling;
|
package/dist/ws.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
|
|
2
2
|
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
3
3
|
const wsOpen = 1;
|
|
4
|
+
const defaultOptionalHandshakeTimeoutMs = 4_000;
|
|
4
5
|
const maxFrameBytes = 128 * 1024;
|
|
5
6
|
const maxPeers = 256;
|
|
6
7
|
const maxEncryptQueueDepth = 128;
|
|
@@ -485,3 +486,61 @@ export function wsSignaling(url, options = {}) {
|
|
|
485
486
|
};
|
|
486
487
|
};
|
|
487
488
|
}
|
|
489
|
+
/**
|
|
490
|
+
* Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
|
|
491
|
+
* - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
|
|
492
|
+
* transitions cleanly to `'closed'` without reconnect storms.
|
|
493
|
+
* - Suppresses `'signaling-error'` so sibling relays (`tabSignaling`, `mqttSignaling`, `nostrSignaling`) carry
|
|
494
|
+
* the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
495
|
+
*/
|
|
496
|
+
export function optionalWsSignaling(url, options = {}) {
|
|
497
|
+
const baseWs = wsSignaling(url, {
|
|
498
|
+
handshakeTimeoutMs: options.handshakeTimeoutMs ?? defaultOptionalHandshakeTimeoutMs,
|
|
499
|
+
...(options.pingIntervalMs !== undefined ? { pingIntervalMs: options.pingIntervalMs } : {}),
|
|
500
|
+
...(options.encrypt !== undefined ? { encrypt: options.encrypt } : {}),
|
|
501
|
+
...(options.privateTopic !== undefined ? { privateTopic: options.privateTopic } : {}),
|
|
502
|
+
...(options.WebSocket !== undefined ? { WebSocket: options.WebSocket } : {}),
|
|
503
|
+
reconnect: false
|
|
504
|
+
});
|
|
505
|
+
return (discovery) => {
|
|
506
|
+
let abandoned = false;
|
|
507
|
+
let session;
|
|
508
|
+
session = baseWs({
|
|
509
|
+
...discovery,
|
|
510
|
+
status(state, reason) {
|
|
511
|
+
if (abandoned)
|
|
512
|
+
return;
|
|
513
|
+
if (state === 'online') {
|
|
514
|
+
discovery.status('online', reason);
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
abandoned = true;
|
|
518
|
+
session?.close();
|
|
519
|
+
discovery.status('closed');
|
|
520
|
+
}
|
|
521
|
+
},
|
|
522
|
+
error(code, message) {
|
|
523
|
+
if (abandoned)
|
|
524
|
+
return;
|
|
525
|
+
if (code === 'decrypt-failed' || code === 'clock-skew') {
|
|
526
|
+
discovery.error?.(code, message);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
if (abandoned) {
|
|
531
|
+
session.close();
|
|
532
|
+
}
|
|
533
|
+
return {
|
|
534
|
+
...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
|
|
535
|
+
send(to, signal) {
|
|
536
|
+
if (abandoned)
|
|
537
|
+
return false;
|
|
538
|
+
return session.send(to, signal);
|
|
539
|
+
},
|
|
540
|
+
close() {
|
|
541
|
+
abandoned = true;
|
|
542
|
+
session.close();
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
};
|
|
546
|
+
}
|
package/docs/behavior.md
CHANGED
|
@@ -85,7 +85,8 @@ Note: when `privateTopic` is `false` (default), `mqttSignaling()`, `nostrSignali
|
|
|
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
87
|
- `createBlobChannel()` throws `RangeError` for invalid `maxReceiveBytes`, `chunkSize`, `receiveTimeoutMs`, or `maxConcurrentPerPeer`. `blobChannel.send()` rejects with `Error` when closed and `TypeError` for non-`Uint8Array` payloads.
|
|
88
|
-
- `wsSignaling()`
|
|
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
|
+
- `publicSignaling()` throws `TypeError` for invalid options, non-`ws:`/`wss:` or empty-string `wsUrls`, non-boolean `localTabs`/`wsEncrypt`/`privateTopic`, invalid `mqtt`/`nostr`/`appId`, or a non-function `WebSocket` option; 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.
|
|
89
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
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.
|
|
91
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.
|
|
@@ -251,13 +252,20 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
|
|
|
251
252
|
- Server sends `{ type: 'roster', peers: string[] }` (validated UUIDs, capped at `256`), `{ type: 'signal', from, signal | box }`, and `{ type: 'pong' }`. Incoming frames larger than `128 KiB` are ignored.
|
|
252
253
|
- Tracks `awaitingPong`: if no `{ type: 'pong' }` (or other valid server message) arrives before the next ping interval, the socket is closed to trigger reconnect.
|
|
253
254
|
- Reconnects with jittered exponential backoff (`500 ms` to `10 s`, `±25%` jitter) when `reconnect` is `true` (default), emitting `'offline'` and `'signaling-error'` once per offline transition.
|
|
255
|
+
- `optionalWsSignaling(url, options?)` wraps `wsSignaling` with `reconnect: false` and a `4,000 ms` default `handshakeTimeoutMs`, forwarding `'online'` while healthy and transitioning cleanly to `'closed'` (closing the underlying session and suppressing `'signaling-error'`) on any non-`'online'` transition while still forwarding `'decrypt-failed'` and `'clock-skew'`.
|
|
256
|
+
|
|
257
|
+
### `publicSignaling(options?)`
|
|
258
|
+
|
|
259
|
+
- Flattens zero or more `optionalWsSignaling(url, ...)` children (`wsUrls?: string | readonly string[]`, validated `ws:`/`wss:`, deduplicated, capped at `8` unique URLs and `64` raw entries) together with `mqttSignaling()` (`mqtt: true` default) and `nostrSignaling()` (`nostr: true` default) into a single `combineSignaling(...)` instance, wrapped in `withLocalTabs(...)` when `localTabs` is `true` (default).
|
|
260
|
+
- Treats enabled transports as a single redundant pool: suppresses per-transport `'signaling-error'` while any sibling transport is `'online'` or `'connecting'` (e.g. when corporate Wi-Fi blocks MQTT ports while port-443 Nostr or `wsUrls` succeeds) and emits `'signaling-error'` once per aggregate `'offline'` transition, while forwarding `'decrypt-failed'` and `'clock-skew'`.
|
|
261
|
+
- Requires at least one persistent public relay transport (`mqtt !== false || nostr !== false`).
|
|
254
262
|
|
|
255
263
|
### `combineSignaling(...adapters)`
|
|
256
264
|
|
|
257
265
|
- Composes one or more `Signaling` adapters into a single adapter (returning the single adapter directly when given one).
|
|
258
266
|
- Pre-initializes all child states as `'connecting'` and buffers synchronous startup callbacks until every child factory returns without throwing (closing already-started children if any factory throws).
|
|
259
267
|
- Aggregate `SignalingState` is `'online'` if any child is `'online'`, `'connecting'` if none is `'online'` and any is `'connecting'`, `'offline'` if none is `'online'`/`'connecting'` and any is `'offline'`, and `'closed'` when all children are `'closed'`.
|
|
260
|
-
- Maintains per-child peer sets, publishes their union to `Discovery.roster`, clears unreachable entries when a child goes `'offline'`/`'closed'` (preserving already-open WebRTC links and any peers still reachable via nested `canReach`), routes `send(to, signal)` to every reachable child advertising `to`, and forwards child `error` reports.
|
|
268
|
+
- Maintains per-child peer sets, publishes their union to `Discovery.roster`, clears unreachable entries when a child goes `'offline'`/`'closed'` (preserving already-open WebRTC links and any peers still reachable via nested `canReach`), routes `send(to, signal)` to every reachable child advertising `to`, and forwards child `error` reports (throttling `'decrypt-failed'` and `'clock-skew'` across children to at most one event per `15 s` each).
|
|
261
269
|
- Advertises `trickle: true` only when every child session advertises `trickle === true`, and deduplicates incoming `{ kind: 'ice' }` candidates per `(from, attempt)` across child adapters.
|
|
262
270
|
|
|
263
271
|
### `withLocalTabs(primary)`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dimchansky/meshpost",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"author": "Dmitrij Koniajev",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -99,6 +99,10 @@
|
|
|
99
99
|
"types": "./dist/combine.d.ts",
|
|
100
100
|
"import": "./dist/combine.js"
|
|
101
101
|
},
|
|
102
|
+
"./public": {
|
|
103
|
+
"types": "./dist/public.d.ts",
|
|
104
|
+
"import": "./dist/public.js"
|
|
105
|
+
},
|
|
102
106
|
"./signaling": {
|
|
103
107
|
"types": "./dist/signaling.d.ts",
|
|
104
108
|
"import": "./dist/signaling.js"
|