@dimchansky/meshpost 0.3.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.
@@ -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/room.d.ts CHANGED
@@ -1,20 +1,17 @@
1
+ import { type PeerIdentity } from './identity.js';
1
2
  import { type Signaling, type SignalingErrorCode, type SignalingState } from './signaling.js';
2
- /** @internal */
3
- export declare function isRoomClosed(room: Room): boolean;
4
- /** @internal */
5
- export declare function onRoomClose(room: Room, fn: () => void): () => void;
6
- /** @internal */
7
- export declare function getRoomRemoteStreams(room: Room): Array<[string, MediaStream]>;
8
3
  /** Built-in Cloudflare and Google public STUN servers used by default. */
9
4
  export declare const defaultIceServers: readonly RTCIceServer[];
10
5
  /** Delivery guarantee for a packet: fast unordered (`'unreliable'`) or ordered reliable (`'reliable'`). */
11
6
  export type Delivery = 'unreliable' | 'reliable';
7
+ /** Constructor signature for custom or headless WebRTC `RTCPeerConnection` implementations. */
8
+ export type RTCPeerConnectionConstructor = new (configuration?: RTCConfiguration) => RTCPeerConnection;
12
9
  export interface RoomOptions {
13
10
  /** Signaling adapter used to discover peers and exchange WebRTC setup messages. */
14
11
  signaling: Signaling;
15
12
  /** Application namespace isolating rooms across different apps. @default 'meshpost' */
16
13
  appId?: string;
17
- /** Optional non-empty shared password isolating (and on MQTT, encrypting) room signaling. */
14
+ /** Optional non-empty shared password isolating and end-to-end encrypting room signaling. */
18
15
  password?: string;
19
16
  /** Custom WebRTC configuration. Keeps `defaultIceServers` unless `iceServers` is specified. */
20
17
  rtcConfig?: RTCConfiguration;
@@ -26,6 +23,10 @@ export interface RoomOptions {
26
23
  iceGatheringTimeoutMs?: number;
27
24
  /** Maximum simultaneous peer connections in this room. @default 32 */
28
25
  maxPeers?: number;
26
+ /** Optional persistent WebCrypto ECDSA P-256 identity proven to peers over each WebRTC link. */
27
+ identity?: PeerIdentity;
28
+ /** Optional custom `RTCPeerConnection` constructor for headless runtimes (Node.js, Bun, Deno) or tests. */
29
+ RTCPeerConnection?: RTCPeerConnectionConstructor;
29
30
  }
30
31
  export interface SendOptions {
31
32
  /** Optional target peer ID. Omit to broadcast to all connected peers. */
@@ -53,7 +54,7 @@ export interface PeerStats {
53
54
  readonly bufferedReliable: number;
54
55
  }
55
56
  /** Structured error codes emitted via `room.onError()`. */
56
- export type RoomErrorCode = 'room-full' | 'ice-failed' | 'media-error' | SignalingErrorCode;
57
+ export type RoomErrorCode = 'room-full' | 'ice-failed' | 'media-error' | 'auth-failed' | SignalingErrorCode;
57
58
  /** Structured diagnostic error emitted via `room.onError()`. */
58
59
  export interface RoomError {
59
60
  readonly code: RoomErrorCode;
@@ -67,13 +68,34 @@ export interface ListenOptions {
67
68
  /** Automatically unsubscribe when the given AbortSignal aborts. */
68
69
  signal?: AbortSignal;
69
70
  }
71
+ /** Options passed to `room.addStream(stream, options)`. */
72
+ export interface AddStreamOptions {
73
+ /** Optional target peer ID. Omit to broadcast to all connected and future peers. */
74
+ to?: string;
75
+ /** Optional semantic stream tag (`1..32` ASCII characters `[a-zA-Z0-9._-]`, e.g. `'voice'`, `'screen'`). */
76
+ tag?: string;
77
+ }
78
+ /** Options passed to `room.removeStream(stream, options)`. */
79
+ export interface RemoveStreamOptions {
80
+ /** Optional target peer ID. Omit to detach from broadcast. */
81
+ to?: string;
82
+ }
83
+ /** Metadata describing an incoming remote `MediaStream` in `onPeerStream` and `onPeerStreamEnd`. */
84
+ export interface PeerStreamMeta {
85
+ /** Semantic tag passed to `addStream(stream, { tag })` by the sender, if any. */
86
+ readonly tag?: string;
87
+ }
70
88
  export interface Room {
71
89
  /** Local peer ID (random UUID v4). A page reload creates a new peer ID. */
72
90
  readonly id: string;
91
+ /** Local verified `userId` when `options.identity` was provided, or `null` if anonymous. */
92
+ readonly userId: string | null;
73
93
  /** Snapshot array of currently connected remote peer IDs. */
74
94
  readonly peers: readonly string[];
75
95
  /** Current state of the signaling adapter. */
76
96
  readonly signalingState: SignalingState;
97
+ /** Return the cryptographically verified `userId` of a connected remote peer, or `null` if anonymous or disconnected. */
98
+ peerUserId(peerId: string): string | null;
77
99
  /** Send a binary packet (max 16 KiB) synchronously. Returns a per-recipient result map. */
78
100
  send(bytes: Uint8Array, options?: SendOptions): ReadonlyMap<string, SendResult>;
79
101
  /** Read current ping, route, byte counts, and buffer sizes for a connected peer, or `null` if unavailable. */
@@ -90,14 +112,16 @@ export interface Room {
90
112
  onSignalingChange(fn: (state: SignalingState, reason?: string) => void, options?: ListenOptions): () => void;
91
113
  /** Subscribe to structured room and signaling errors. Returns an unsubscribe function. */
92
114
  onError(fn: (error: RoomError) => void, options?: ListenOptions): () => void;
93
- /** Attach a local MediaStream to all connected/future peers (broadcast), or selectively to one peer (`to`). Broadcast and per-peer registrations are tracked independently. */
94
- addStream(stream: MediaStream, to?: string): void;
115
+ /** Attach a local MediaStream to all connected/future peers (broadcast), or selectively to one peer (`to`), optionally carrying a semantic `tag`. */
116
+ addStream(stream: MediaStream, toOrOptions?: string | AddStreamOptions): void;
95
117
  /** Detach a previously added local MediaStream from broadcast (`to` omitted) or from one peer (`to`). Does not stop local tracks. */
96
- removeStream(stream: MediaStream, to?: string): void;
118
+ removeStream(stream: MediaStream, toOrOptions?: string | RemoveStreamOptions): void;
119
+ /** Hot-swap a track inside an already-added local MediaStream via `RTCRtpSender.replaceTrack()` without SDP renegotiation. Does not stop `oldTrack`. */
120
+ replaceStreamTrack(stream: MediaStream, oldTrack: MediaStreamTrack, newTrack: MediaStreamTrack): Promise<void>;
97
121
  /** Subscribe to incoming remote MediaStreams. Fires strictly after `onPeerJoin`. */
98
- onPeerStream(fn: (peerId: string, stream: MediaStream) => void, options?: ListenOptions): () => void;
122
+ onPeerStream(fn: (peerId: string, stream: MediaStream, meta: PeerStreamMeta) => void, options?: ListenOptions): () => void;
99
123
  /** Subscribe to remote MediaStream removals (explicit removal or peer disconnect). */
100
- onPeerStreamEnd(fn: (peerId: string, stream: MediaStream) => void, options?: ListenOptions): () => void;
124
+ onPeerStreamEnd(fn: (peerId: string, stream: MediaStream, meta: PeerStreamMeta) => void, options?: ListenOptions): () => void;
101
125
  /** Leave the room, notify peers, and close all connections. Safe to call more than once. */
102
126
  leave(): void;
103
127
  }