@dimchansky/meshpost 0.2.0 → 0.4.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/README.md +330 -96
- package/dist/channel.d.ts +37 -2
- package/dist/channel.js +226 -12
- package/dist/combine.d.ts +12 -1
- package/dist/combine.js +304 -213
- package/dist/crypto.d.ts +34 -0
- package/dist/crypto.js +158 -0
- package/dist/identity.d.ts +45 -0
- package/dist/identity.js +264 -0
- package/dist/index.d.ts +17 -5
- package/dist/index.js +8 -2
- package/dist/mqtt.d.ts +9 -1
- package/dist/mqtt.js +95 -87
- package/dist/nostr.d.ts +27 -0
- package/dist/nostr.js +1008 -0
- package/dist/room.d.ts +37 -7
- package/dist/room.js +656 -65
- package/dist/rpc.d.ts +48 -0
- package/dist/rpc.js +382 -0
- package/dist/signaling.d.ts +9 -8
- package/dist/signaling.js +10 -2
- package/dist/state.d.ts +56 -0
- package/dist/state.js +305 -0
- package/dist/tabs.js +8 -1
- package/dist/turn.d.ts +13 -0
- package/dist/turn.js +213 -0
- package/dist/voice.d.ts +108 -0
- package/dist/voice.js +1160 -0
- package/dist/ws.d.ts +17 -2
- package/dist/ws.js +248 -33
- package/docs/behavior.md +107 -54
- package/package.json +67 -2
package/dist/mqtt.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, maxMidLength, openPayload, sealPayload } from './crypto.js';
|
|
1
2
|
import { isSignal, isUuid, namespaceHash } from './signaling.js';
|
|
2
3
|
/** Built-in public MQTT-over-WebSocket relay URLs used by default. */
|
|
3
4
|
export const defaultMqttRelays = Object.freeze([
|
|
@@ -5,16 +6,12 @@ export const defaultMqttRelays = Object.freeze([
|
|
|
5
6
|
'wss://broker.hivemq.com:8884/mqtt',
|
|
6
7
|
'wss://test.mosquitto.org:8081/mqtt'
|
|
7
8
|
]);
|
|
9
|
+
const wsOpen = 1;
|
|
8
10
|
const encoder = new TextEncoder();
|
|
9
11
|
const decoder = new TextDecoder();
|
|
10
12
|
const maxMqttBuffer = 128 * 1024;
|
|
11
13
|
const maxSeenPeers = 256;
|
|
12
|
-
const maxSeenMids = 2048;
|
|
13
|
-
const maxMidLength = 64;
|
|
14
|
-
const replayWindowMs = 60_000;
|
|
15
|
-
const midTtlMs = replayWindowMs * 2;
|
|
16
14
|
const defaultMqttHandshakeTimeoutMs = 10_000;
|
|
17
|
-
const decryptErrorCooldownMs = 15_000;
|
|
18
15
|
function encodeRemainingLength(length) {
|
|
19
16
|
const bytes = [];
|
|
20
17
|
let n = length;
|
|
@@ -137,34 +134,6 @@ function parseMqttFrames(buffer, handlers) {
|
|
|
137
134
|
? new Uint8Array(0)
|
|
138
135
|
: buffer.subarray(offset);
|
|
139
136
|
}
|
|
140
|
-
async function deriveKey(password, salt) {
|
|
141
|
-
const subtle = globalThis.crypto?.subtle;
|
|
142
|
-
if (!subtle)
|
|
143
|
-
throw new Error('Password encryption requires a secure context (crypto.subtle)');
|
|
144
|
-
const base = await subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, [
|
|
145
|
-
'deriveKey'
|
|
146
|
-
]);
|
|
147
|
-
return subtle.deriveKey({ name: 'PBKDF2', salt: encoder.encode(salt), iterations: 100_000, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
148
|
-
}
|
|
149
|
-
async function sealPayload(key, plain, aad) {
|
|
150
|
-
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
151
|
-
const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, plain.buffer instanceof ArrayBuffer
|
|
152
|
-
? new Uint8Array(plain.buffer, plain.byteOffset, plain.byteLength)
|
|
153
|
-
: Uint8Array.from(plain)));
|
|
154
|
-
return concatBytes(iv, cipher);
|
|
155
|
-
}
|
|
156
|
-
async function openPayload(key, boxed, aad) {
|
|
157
|
-
if (boxed.length < 28)
|
|
158
|
-
return null;
|
|
159
|
-
try {
|
|
160
|
-
const iv = Uint8Array.from(boxed.subarray(0, 12));
|
|
161
|
-
const cipher = Uint8Array.from(boxed.subarray(12));
|
|
162
|
-
return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, cipher));
|
|
163
|
-
}
|
|
164
|
-
catch {
|
|
165
|
-
return null;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
137
|
/**
|
|
169
138
|
* Zero-backend signaling over public (or custom) MQTT-over-WebSocket brokers.
|
|
170
139
|
* Connects to multiple brokers in parallel for redundancy, splits presence and unicast topics,
|
|
@@ -183,9 +152,23 @@ export function mqttSignaling(options = {}) {
|
|
|
183
152
|
if (options.password !== undefined &&
|
|
184
153
|
(typeof options.password !== 'string' || options.password.length === 0))
|
|
185
154
|
throw new TypeError('Invalid password');
|
|
155
|
+
if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
|
|
156
|
+
throw new TypeError('Invalid privateTopic option');
|
|
157
|
+
}
|
|
158
|
+
if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
|
|
159
|
+
throw new TypeError('Invalid WebSocket constructor');
|
|
160
|
+
}
|
|
186
161
|
return (discovery) => {
|
|
162
|
+
const WsCtor = options.WebSocket ?? globalThis.WebSocket;
|
|
163
|
+
if (typeof WsCtor !== 'function') {
|
|
164
|
+
throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
|
|
165
|
+
}
|
|
187
166
|
const appId = options.appId ?? discovery.appId;
|
|
188
167
|
const password = options.password ?? discovery.password;
|
|
168
|
+
const privateTopic = options.privateTopic ?? false;
|
|
169
|
+
if (privateTopic && password === undefined) {
|
|
170
|
+
throw new TypeError('privateTopic requires a room password');
|
|
171
|
+
}
|
|
189
172
|
if (password !== undefined) {
|
|
190
173
|
if (typeof password !== 'string' || password.length === 0)
|
|
191
174
|
throw new TypeError('Invalid password');
|
|
@@ -193,11 +176,12 @@ export function mqttSignaling(options = {}) {
|
|
|
193
176
|
throw new Error('Password encryption requires a secure context (crypto.subtle)');
|
|
194
177
|
}
|
|
195
178
|
}
|
|
196
|
-
const
|
|
197
|
-
|
|
179
|
+
const baseScope = appId + ':' + discovery.room;
|
|
180
|
+
let roomTopic = privateTopic ? '' : 'meshpost/1/' + namespaceHash(baseScope);
|
|
181
|
+
let inboxTopic = privateTopic ? '' : roomTopic + '/' + discovery.self;
|
|
198
182
|
const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
|
|
199
183
|
const seen = new Map();
|
|
200
|
-
const
|
|
184
|
+
const replayGuard = createReplayGuard();
|
|
201
185
|
const readySockets = new Set();
|
|
202
186
|
const allSockets = new Set();
|
|
203
187
|
const reconnectTimers = new Set();
|
|
@@ -208,13 +192,9 @@ export function mqttSignaling(options = {}) {
|
|
|
208
192
|
let nextPacketId = 1;
|
|
209
193
|
let msgSeq = 0;
|
|
210
194
|
let lastDecryptErrorAt = -Infinity;
|
|
195
|
+
let lastClockSkewErrorAt = -Infinity;
|
|
211
196
|
let resolvedKey;
|
|
212
|
-
const
|
|
213
|
-
? deriveKey(password, roomTopic).then((k) => {
|
|
214
|
-
resolvedKey = k;
|
|
215
|
-
return k;
|
|
216
|
-
})
|
|
217
|
-
: undefined;
|
|
197
|
+
const keysPromise = password !== undefined ? deriveSignalingKeys(password, baseScope) : undefined;
|
|
218
198
|
const roster = () => discovery.roster([...seen.keys()]);
|
|
219
199
|
const touch = (id) => {
|
|
220
200
|
const known = seen.has(id);
|
|
@@ -229,24 +209,6 @@ export function mqttSignaling(options = {}) {
|
|
|
229
209
|
roster();
|
|
230
210
|
return known;
|
|
231
211
|
};
|
|
232
|
-
const recordMid = (mid) => {
|
|
233
|
-
const now = Date.now();
|
|
234
|
-
const prev = seenMids.get(mid);
|
|
235
|
-
if (prev !== undefined && now - prev < midTtlMs)
|
|
236
|
-
return false;
|
|
237
|
-
if (seenMids.size >= maxSeenMids) {
|
|
238
|
-
for (const [key, at] of seenMids) {
|
|
239
|
-
if (now - at >= midTtlMs || seenMids.size >= maxSeenMids) {
|
|
240
|
-
seenMids.delete(key);
|
|
241
|
-
if (seenMids.size < maxSeenMids)
|
|
242
|
-
break;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
seenMids.delete(mid);
|
|
247
|
-
seenMids.set(mid, now);
|
|
248
|
-
return true;
|
|
249
|
-
};
|
|
250
212
|
const updateStatus = () => {
|
|
251
213
|
if (closed)
|
|
252
214
|
return;
|
|
@@ -265,14 +227,14 @@ export function mqttSignaling(options = {}) {
|
|
|
265
227
|
}
|
|
266
228
|
};
|
|
267
229
|
const publishRaw = async (body, targetSockets, fixedMid) => {
|
|
268
|
-
if (closed)
|
|
230
|
+
if (closed || !roomTopic)
|
|
269
231
|
return;
|
|
270
232
|
const targetTopic = body.to ? roomTopic + '/' + body.to : roomTopic;
|
|
271
233
|
const mid = fixedMid ?? discovery.self.slice(0, 8) + ':' + ++msgSeq;
|
|
272
234
|
const plain = encoder.encode(JSON.stringify({ ...body, from: discovery.self, mid, ts: Date.now() }));
|
|
273
235
|
let payload;
|
|
274
236
|
try {
|
|
275
|
-
const key = resolvedKey ?? (
|
|
237
|
+
const key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
|
|
276
238
|
payload = key ? await sealPayload(key, plain, targetTopic) : plain;
|
|
277
239
|
}
|
|
278
240
|
catch {
|
|
@@ -282,7 +244,7 @@ export function mqttSignaling(options = {}) {
|
|
|
282
244
|
return;
|
|
283
245
|
const frame = buildPublish(targetTopic, payload);
|
|
284
246
|
for (const ws of targetSockets ?? readySockets) {
|
|
285
|
-
if (ws.readyState ===
|
|
247
|
+
if (ws.readyState === wsOpen) {
|
|
286
248
|
try {
|
|
287
249
|
ws.send(frame);
|
|
288
250
|
}
|
|
@@ -297,7 +259,7 @@ export function mqttSignaling(options = {}) {
|
|
|
297
259
|
return;
|
|
298
260
|
let key;
|
|
299
261
|
try {
|
|
300
|
-
key = resolvedKey ?? (
|
|
262
|
+
key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
|
|
301
263
|
}
|
|
302
264
|
catch {
|
|
303
265
|
return;
|
|
@@ -316,7 +278,7 @@ export function mqttSignaling(options = {}) {
|
|
|
316
278
|
if (!plain) {
|
|
317
279
|
if (key) {
|
|
318
280
|
const now = Date.now();
|
|
319
|
-
if (now - lastDecryptErrorAt >=
|
|
281
|
+
if (now - lastDecryptErrorAt >= errorCooldownMs) {
|
|
320
282
|
lastDecryptErrorAt = now;
|
|
321
283
|
discovery.error?.('decrypt-failed', 'Failed to decrypt MQTT signaling message');
|
|
322
284
|
}
|
|
@@ -334,17 +296,26 @@ export function mqttSignaling(options = {}) {
|
|
|
334
296
|
return;
|
|
335
297
|
if (data.to !== undefined && data.to !== discovery.self)
|
|
336
298
|
return;
|
|
337
|
-
if (data.mid !== undefined &&
|
|
338
|
-
(typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength))
|
|
339
|
-
return;
|
|
340
299
|
if (key) {
|
|
341
|
-
|
|
300
|
+
const check = replayGuard.checkAuthenticated(data.from, data);
|
|
301
|
+
if (check === 'clock-skew') {
|
|
302
|
+
const now = Date.now();
|
|
303
|
+
if (now - lastClockSkewErrorAt >= errorCooldownMs) {
|
|
304
|
+
lastClockSkewErrorAt = now;
|
|
305
|
+
discovery.error?.('clock-skew', 'MQTT signaling message rejected due to system clock skew (>60s)');
|
|
306
|
+
}
|
|
342
307
|
return;
|
|
343
|
-
|
|
308
|
+
}
|
|
309
|
+
if (check !== 'ok')
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
if (data.mid !== undefined &&
|
|
314
|
+
(typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength))
|
|
315
|
+
return;
|
|
316
|
+
if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid))
|
|
344
317
|
return;
|
|
345
318
|
}
|
|
346
|
-
if (typeof data.mid === 'string' && !recordMid(data.from + ':' + data.mid))
|
|
347
|
-
return;
|
|
348
319
|
switch (data.type) {
|
|
349
320
|
case 'hello':
|
|
350
321
|
touch(data.from);
|
|
@@ -381,7 +352,7 @@ export function mqttSignaling(options = {}) {
|
|
|
381
352
|
};
|
|
382
353
|
let ws;
|
|
383
354
|
try {
|
|
384
|
-
ws = new
|
|
355
|
+
ws = new WsCtor(url, ['mqtt']);
|
|
385
356
|
}
|
|
386
357
|
catch {
|
|
387
358
|
settleInitial();
|
|
@@ -480,7 +451,7 @@ export function mqttSignaling(options = {}) {
|
|
|
480
451
|
updateStatus();
|
|
481
452
|
void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
|
|
482
453
|
pingTimer = setInterval(() => {
|
|
483
|
-
if (ws.readyState !==
|
|
454
|
+
if (ws.readyState !== wsOpen)
|
|
484
455
|
return;
|
|
485
456
|
if (awaitingPong) {
|
|
486
457
|
abortSocket();
|
|
@@ -521,19 +492,56 @@ export function mqttSignaling(options = {}) {
|
|
|
521
492
|
}
|
|
522
493
|
if (changed)
|
|
523
494
|
roster();
|
|
524
|
-
|
|
525
|
-
if (now - at >= midTtlMs)
|
|
526
|
-
seenMids.delete(mid);
|
|
527
|
-
}
|
|
495
|
+
replayGuard.prune(now);
|
|
528
496
|
if (readySockets.size > 0)
|
|
529
497
|
void publishRaw({ type: 'heartbeat' });
|
|
530
498
|
}, 5_000);
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
499
|
+
if (keysPromise && privateTopic) {
|
|
500
|
+
void keysPromise
|
|
501
|
+
.then((keys) => {
|
|
502
|
+
if (closed)
|
|
503
|
+
return;
|
|
504
|
+
roomTopic = 'meshpost/1/p/' + keys.privateId;
|
|
505
|
+
inboxTopic = roomTopic + '/' + discovery.self;
|
|
506
|
+
resolvedKey = keys.aeadKey;
|
|
507
|
+
for (const url of urls)
|
|
508
|
+
connectBroker(url);
|
|
509
|
+
})
|
|
510
|
+
.catch(() => {
|
|
511
|
+
if (closed)
|
|
512
|
+
return;
|
|
513
|
+
initialPending = 0;
|
|
514
|
+
updateStatus();
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
else {
|
|
518
|
+
if (keysPromise) {
|
|
519
|
+
void keysPromise
|
|
520
|
+
.then((keys) => {
|
|
521
|
+
resolvedKey = keys.aeadKey;
|
|
522
|
+
})
|
|
523
|
+
.catch(() => {
|
|
524
|
+
if (closed)
|
|
525
|
+
return;
|
|
526
|
+
initialPending = 0;
|
|
527
|
+
for (const ws of [...allSockets]) {
|
|
528
|
+
try {
|
|
529
|
+
ws.close();
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
// Ignore close errors.
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
updateStatus();
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
queueMicrotask(() => {
|
|
539
|
+
if (closed)
|
|
540
|
+
return;
|
|
541
|
+
for (const url of urls)
|
|
542
|
+
connectBroker(url);
|
|
543
|
+
});
|
|
544
|
+
}
|
|
537
545
|
return {
|
|
538
546
|
trickle: true,
|
|
539
547
|
send(to, signal) {
|
|
@@ -556,7 +564,7 @@ export function mqttSignaling(options = {}) {
|
|
|
556
564
|
readySockets.clear();
|
|
557
565
|
const shutdownSocket = (ws, byeFrame) => {
|
|
558
566
|
try {
|
|
559
|
-
if (ws.readyState ===
|
|
567
|
+
if (ws.readyState === wsOpen) {
|
|
560
568
|
if (byeFrame)
|
|
561
569
|
ws.send(byeFrame);
|
|
562
570
|
ws.send(disconnectPkt);
|
|
@@ -573,13 +581,13 @@ export function mqttSignaling(options = {}) {
|
|
|
573
581
|
mid: discovery.self.slice(0, 8) + ':' + ++msgSeq,
|
|
574
582
|
ts: Date.now()
|
|
575
583
|
}));
|
|
576
|
-
if (!
|
|
584
|
+
if (!keysPromise && roomTopic) {
|
|
577
585
|
const byeFrame = buildPublish(roomTopic, byePlain);
|
|
578
586
|
for (const ws of socketsToClose) {
|
|
579
587
|
shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
|
|
580
588
|
}
|
|
581
589
|
}
|
|
582
|
-
else if (resolvedKey && readyToNotify.length > 0) {
|
|
590
|
+
else if (resolvedKey && roomTopic && readyToNotify.length > 0) {
|
|
583
591
|
const nonReady = socketsToClose.filter((ws) => !readyToNotify.includes(ws));
|
|
584
592
|
for (const ws of nonReady)
|
|
585
593
|
shutdownSocket(ws);
|
package/dist/nostr.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Signaling, type WebSocketConstructor } from './signaling.js';
|
|
2
|
+
/** Built-in public port-443 Nostr WebSocket relays used by default. */
|
|
3
|
+
export declare const defaultNostrRelays: readonly string[];
|
|
4
|
+
export interface NostrSignalingOptions {
|
|
5
|
+
/** Nostr relay URLs (`wss://` or `ws://`) to connect to in parallel for redundancy. @default defaultNostrRelays */
|
|
6
|
+
urls?: readonly string[];
|
|
7
|
+
/** Application namespace mixed into the hashed room tag. */
|
|
8
|
+
appId?: string;
|
|
9
|
+
/** Optional shared password to encrypt signaling payloads with AES-256-GCM (requires secure context). */
|
|
10
|
+
password?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Derive the Nostr room tag cryptographically from `password` so room activity is hidden from outsiders
|
|
13
|
+
* (disables `'decrypt-failed'` detection when a peer enters the wrong password).
|
|
14
|
+
* @default false
|
|
15
|
+
*/
|
|
16
|
+
privateTopic?: boolean;
|
|
17
|
+
/** Maximum time in milliseconds to wait for WebSocket open -> REQ -> EOSE per relay. @default 10000 */
|
|
18
|
+
handshakeTimeoutMs?: number;
|
|
19
|
+
/** Optional custom `WebSocket` constructor for headless runtimes or custom transports. */
|
|
20
|
+
WebSocket?: WebSocketConstructor;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Zero-backend port-443 signaling over public (or custom) NIP-01 Nostr relays.
|
|
24
|
+
* Uses ephemeral events (`kind: 25050` — never persisted to disk by relays), pure-TS BIP-340 Schnorr
|
|
25
|
+
* signatures, multi-relay redundancy, and `AES-256-GCM` E2E encryption when `password` is provided.
|
|
26
|
+
*/
|
|
27
|
+
export declare function nostrSignaling(options?: NostrSignalingOptions): Signaling;
|