@dimchansky/meshpost 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -544
- package/dist/bip340.d.ts +1 -0
- package/dist/bip340.js +346 -0
- package/dist/blob.d.ts +1 -1
- package/dist/blob.js +44 -45
- package/dist/channel.d.ts +4 -0
- package/dist/channel.js +19 -44
- package/dist/combine.d.ts +9 -2
- package/dist/combine.js +40 -57
- package/dist/crypto.js +10 -9
- package/dist/identity.d.ts +2 -0
- package/dist/identity.js +39 -71
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/listeners.js +18 -3
- package/dist/mqtt.js +211 -476
- package/dist/nostr.js +194 -836
- package/dist/peer-link.d.ts +1 -0
- package/dist/peer-link.js +983 -0
- package/dist/presence.d.ts +1 -0
- package/dist/presence.js +74 -0
- package/dist/public.d.ts +1 -1
- package/dist/public.js +25 -77
- package/dist/relay-core.d.ts +1 -0
- package/dist/relay-core.js +399 -0
- package/dist/room-reclaim.d.ts +1 -0
- package/dist/room-reclaim.js +115 -0
- package/dist/room-stats.d.ts +1 -0
- package/dist/room-stats.js +75 -0
- package/dist/room.js +245 -1218
- package/dist/rpc.js +25 -28
- package/dist/signaling.d.ts +8 -0
- package/dist/signaling.js +55 -0
- package/dist/state.js +23 -33
- package/dist/tabs.js +6 -50
- package/dist/voice-mic.d.ts +1 -0
- package/dist/voice-mic.js +496 -0
- package/dist/voice-remote.d.ts +1 -0
- package/dist/voice-remote.js +568 -0
- package/dist/voice.d.ts +19 -1
- package/dist/voice.js +95 -1036
- package/dist/ws.js +56 -197
- package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
- package/docs/api.md +219 -0
- package/docs/behavior.md +14 -8
- package/docs/guide.md +404 -0
- package/docs/signaling-and-production.md +312 -0
- package/docs/voice-and-media.md +193 -0
- package/package.json +6 -3
package/dist/mqtt.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { createPresenceTracker } from './presence.js';
|
|
2
|
+
import { createRelayEnvelope, createRelayPool, normalizeWsRelayUrl, resolveSessionPassword, resolveSessionWebSocket, validateCommonSignalingOptions, validatePositiveTimeout } from './relay-core.js';
|
|
3
|
+
import { namespaceHash } from './signaling.js';
|
|
3
4
|
/** Built-in public MQTT-over-WebSocket relay URLs used by default. */
|
|
4
5
|
export const defaultMqttRelays = Object.freeze([
|
|
5
6
|
'wss://broker.emqx.io:8084/mqtt',
|
|
@@ -10,7 +11,6 @@ const wsOpen = 1;
|
|
|
10
11
|
const encoder = new TextEncoder();
|
|
11
12
|
const decoder = new TextDecoder();
|
|
12
13
|
const maxMqttBuffer = 128 * 1024;
|
|
13
|
-
const maxSeenPeers = 256;
|
|
14
14
|
const defaultMqttHandshakeTimeoutMs = 10_000;
|
|
15
15
|
function encodeRemainingLength(length) {
|
|
16
16
|
const bytes = [];
|
|
@@ -24,54 +24,53 @@ function encodeRemainingLength(length) {
|
|
|
24
24
|
} while (n > 0);
|
|
25
25
|
return bytes;
|
|
26
26
|
}
|
|
27
|
-
function
|
|
28
|
-
const
|
|
29
|
-
const out = new Uint8Array(2 +
|
|
30
|
-
out[0] = (
|
|
31
|
-
out[1] =
|
|
32
|
-
out.set(
|
|
27
|
+
function encodeString(text) {
|
|
28
|
+
const body = encoder.encode(text);
|
|
29
|
+
const out = new Uint8Array(2 + body.length);
|
|
30
|
+
out[0] = (body.length >>> 8) & 0xff;
|
|
31
|
+
out[1] = body.length & 0xff;
|
|
32
|
+
out.set(body, 2);
|
|
33
33
|
return out;
|
|
34
34
|
}
|
|
35
35
|
function concatBytes(...parts) {
|
|
36
36
|
let total = 0;
|
|
37
|
-
for (const
|
|
38
|
-
total +=
|
|
37
|
+
for (const part of parts)
|
|
38
|
+
total += part.length;
|
|
39
39
|
const out = new Uint8Array(total);
|
|
40
40
|
let offset = 0;
|
|
41
|
-
for (const
|
|
42
|
-
out.set(
|
|
43
|
-
offset +=
|
|
41
|
+
for (const part of parts) {
|
|
42
|
+
out.set(part, offset);
|
|
43
|
+
offset += part.length;
|
|
44
44
|
}
|
|
45
45
|
return out;
|
|
46
46
|
}
|
|
47
|
-
function
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
47
|
+
function buildPacket(typeAndFlags, ...parts) {
|
|
48
|
+
let bodyLength = 0;
|
|
49
|
+
for (const part of parts)
|
|
50
|
+
bodyLength += part.length;
|
|
51
|
+
const rem = encodeRemainingLength(bodyLength);
|
|
52
|
+
const out = new Uint8Array(1 + rem.length + bodyLength);
|
|
53
|
+
out[0] = typeAndFlags;
|
|
51
54
|
out.set(rem, 1);
|
|
52
|
-
|
|
55
|
+
let offset = 1 + rem.length;
|
|
56
|
+
for (const part of parts) {
|
|
57
|
+
out.set(part, offset);
|
|
58
|
+
offset += part.length;
|
|
59
|
+
}
|
|
53
60
|
return out;
|
|
54
61
|
}
|
|
55
62
|
function buildConnect(clientId) {
|
|
56
|
-
|
|
57
|
-
const flags = new Uint8Array([
|
|
58
|
-
4, // Protocol level 4 (MQTT 3.1.1)
|
|
59
|
-
0x02, // Clean Session
|
|
60
|
-
0,
|
|
61
|
-
30 // Keep Alive = 30s
|
|
62
|
-
]);
|
|
63
|
-
return mqttPacket(0x10, concatBytes(proto, flags, encodeMqttString(clientId)));
|
|
63
|
+
return buildPacket(0x10, encodeString('MQTT'), new Uint8Array([0x04, 0x02, 0x00, 60]), encodeString(clientId));
|
|
64
64
|
}
|
|
65
65
|
function buildSubscribe(packetId, topics) {
|
|
66
66
|
const parts = [new Uint8Array([(packetId >>> 8) & 0xff, packetId & 0xff])];
|
|
67
|
-
const qos = new Uint8Array([0]);
|
|
68
67
|
for (const topic of topics) {
|
|
69
|
-
parts.push(
|
|
68
|
+
parts.push(encodeString(topic), new Uint8Array([0x00]));
|
|
70
69
|
}
|
|
71
|
-
return
|
|
70
|
+
return buildPacket(0x82, ...parts);
|
|
72
71
|
}
|
|
73
72
|
function buildPublish(topic, payload) {
|
|
74
|
-
return
|
|
73
|
+
return buildPacket(0x30, encodeString(topic), payload);
|
|
75
74
|
}
|
|
76
75
|
const pingReq = new Uint8Array([0xc0, 0x00]);
|
|
77
76
|
const disconnectPkt = new Uint8Array([0xe0, 0x00]);
|
|
@@ -79,43 +78,44 @@ function parseMqttFrames(buffer, handlers) {
|
|
|
79
78
|
let offset = 0;
|
|
80
79
|
while (offset + 2 <= buffer.length) {
|
|
81
80
|
const header = buffer[offset];
|
|
82
|
-
const type = header >>> 4;
|
|
83
81
|
let multiplier = 1;
|
|
84
|
-
let
|
|
82
|
+
let remLen = 0;
|
|
85
83
|
let pos = offset + 1;
|
|
86
|
-
let
|
|
84
|
+
let complete = false;
|
|
85
|
+
let malformed = false;
|
|
87
86
|
while (pos < buffer.length) {
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
if ((
|
|
91
|
-
|
|
87
|
+
const digit = buffer[pos++];
|
|
88
|
+
remLen += (digit & 0x7f) * multiplier;
|
|
89
|
+
if ((digit & 0x80) === 0) {
|
|
90
|
+
complete = true;
|
|
92
91
|
break;
|
|
93
92
|
}
|
|
94
93
|
multiplier *= 128;
|
|
95
94
|
if (multiplier > 128 * 128 * 128) {
|
|
96
|
-
|
|
97
|
-
|
|
95
|
+
malformed = true;
|
|
96
|
+
break;
|
|
98
97
|
}
|
|
99
98
|
}
|
|
100
|
-
if (
|
|
101
|
-
break;
|
|
102
|
-
if (remaining > maxMqttBuffer) {
|
|
99
|
+
if (malformed) {
|
|
103
100
|
handlers.onError();
|
|
104
101
|
return new Uint8Array(0);
|
|
105
102
|
}
|
|
106
|
-
if (
|
|
103
|
+
if (!complete)
|
|
107
104
|
break;
|
|
108
|
-
const end = pos +
|
|
109
|
-
if (
|
|
105
|
+
const end = pos + remLen;
|
|
106
|
+
if (end > buffer.length)
|
|
107
|
+
break;
|
|
108
|
+
const type = header >>> 4;
|
|
109
|
+
if (type === 2 && remLen >= 2) {
|
|
110
110
|
handlers.onConnAck(buffer[pos + 1]);
|
|
111
111
|
}
|
|
112
|
-
else if (type === 9 &&
|
|
112
|
+
else if (type === 9 && remLen >= 2) {
|
|
113
113
|
handlers.onSubAck(buffer.subarray(pos + 2, end));
|
|
114
114
|
}
|
|
115
115
|
else if (type === 13) {
|
|
116
116
|
handlers.onPingResp();
|
|
117
117
|
}
|
|
118
|
-
else if (type === 3 &&
|
|
118
|
+
else if (type === 3 && remLen >= 2) {
|
|
119
119
|
const topicLen = (buffer[pos] << 8) | buffer[pos + 1];
|
|
120
120
|
let bodyStart = pos + 2 + topicLen;
|
|
121
121
|
const qos = (header >>> 1) & 0x03;
|
|
@@ -141,109 +141,41 @@ function parseMqttFrames(buffer, handlers) {
|
|
|
141
141
|
* handshakes with AES-256-GCM (+ topic AAD and timestamp anti-replay) when `password` is provided.
|
|
142
142
|
*/
|
|
143
143
|
export function mqttSignaling(options = {}) {
|
|
144
|
-
const
|
|
145
|
-
if (
|
|
144
|
+
const rawUrls = [...(options.urls ?? defaultMqttRelays)];
|
|
145
|
+
if (rawUrls.length === 0)
|
|
146
146
|
throw new RangeError('At least one MQTT relay URL is required');
|
|
147
|
+
const urls = rawUrls.map((u) => normalizeWsRelayUrl(u, 'Invalid MQTT relay URL', 'MQTT relay URL must use ws: or wss:'));
|
|
147
148
|
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? defaultMqttHandshakeTimeoutMs;
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
handshakeTimeoutMs > 2_147_483_647)
|
|
151
|
-
throw new RangeError('Invalid MQTT handshake timeout');
|
|
152
|
-
if (options.password !== undefined &&
|
|
153
|
-
(typeof options.password !== 'string' || options.password.length === 0))
|
|
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
|
-
}
|
|
149
|
+
validatePositiveTimeout(handshakeTimeoutMs, 'Invalid MQTT handshake timeout');
|
|
150
|
+
validateCommonSignalingOptions(options);
|
|
161
151
|
return (discovery) => {
|
|
162
|
-
const WsCtor = options.WebSocket
|
|
163
|
-
if (typeof WsCtor !== 'function') {
|
|
164
|
-
throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
|
|
165
|
-
}
|
|
152
|
+
const WsCtor = resolveSessionWebSocket(options.WebSocket);
|
|
166
153
|
const appId = options.appId ?? discovery.appId;
|
|
167
|
-
const password = options.password ?? discovery.password;
|
|
168
154
|
const privateTopic = options.privateTopic ?? false;
|
|
169
|
-
|
|
170
|
-
throw new TypeError('privateTopic requires a room password');
|
|
171
|
-
}
|
|
172
|
-
if (password !== undefined) {
|
|
173
|
-
if (typeof password !== 'string' || password.length === 0)
|
|
174
|
-
throw new TypeError('Invalid password');
|
|
175
|
-
if (!globalThis.crypto?.subtle) {
|
|
176
|
-
throw new Error('Password encryption requires a secure context (crypto.subtle)');
|
|
177
|
-
}
|
|
178
|
-
}
|
|
155
|
+
const { password } = resolveSessionPassword(options.password ?? discovery.password, privateTopic);
|
|
179
156
|
const baseScope = appId + ':' + discovery.room;
|
|
180
157
|
let roomTopic = privateTopic ? '' : 'meshpost/1/' + namespaceHash(baseScope);
|
|
181
158
|
let inboxTopic = privateTopic ? '' : roomTopic + '/' + discovery.self;
|
|
182
159
|
const initialHelloMid = discovery.self.slice(0, 8) + ':h0';
|
|
183
|
-
const seen = new Map();
|
|
184
|
-
const replayGuard = createReplayGuard();
|
|
185
|
-
const readySockets = new Set();
|
|
186
|
-
const allSockets = new Set();
|
|
187
|
-
const reconnectTimers = new Set();
|
|
188
|
-
let closed = false;
|
|
189
|
-
let reportedOnline = false;
|
|
190
|
-
let reportedOffline = false;
|
|
191
|
-
let initialPending = urls.length;
|
|
192
160
|
let nextPacketId = 1;
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
const oldest = seen.keys().next().value;
|
|
203
|
-
if (oldest !== undefined)
|
|
204
|
-
seen.delete(oldest);
|
|
205
|
-
}
|
|
206
|
-
seen.delete(id);
|
|
207
|
-
seen.set(id, Date.now());
|
|
208
|
-
if (!known)
|
|
209
|
-
roster();
|
|
210
|
-
return known;
|
|
211
|
-
};
|
|
212
|
-
const updateStatus = () => {
|
|
213
|
-
if (closed)
|
|
214
|
-
return;
|
|
215
|
-
const online = readySockets.size > 0;
|
|
216
|
-
if (online && !reportedOnline) {
|
|
217
|
-
reportedOnline = true;
|
|
218
|
-
reportedOffline = false;
|
|
219
|
-
discovery.status('online');
|
|
220
|
-
}
|
|
221
|
-
else if (!online && (reportedOnline || (initialPending === 0 && !reportedOffline))) {
|
|
222
|
-
reportedOnline = false;
|
|
223
|
-
reportedOffline = true;
|
|
224
|
-
const reason = 'All MQTT relays disconnected';
|
|
225
|
-
discovery.status('offline', reason);
|
|
226
|
-
discovery.error?.('signaling-error', reason);
|
|
227
|
-
}
|
|
228
|
-
};
|
|
161
|
+
const envelope = createRelayEnvelope({
|
|
162
|
+
discovery,
|
|
163
|
+
password,
|
|
164
|
+
baseScope,
|
|
165
|
+
transportLabel: 'MQTT'
|
|
166
|
+
});
|
|
167
|
+
const presence = createPresenceTracker(discovery, (to) => {
|
|
168
|
+
void publishRaw({ type: 'present', to });
|
|
169
|
+
});
|
|
229
170
|
const publishRaw = async (body, targetSockets, fixedMid) => {
|
|
230
|
-
if (
|
|
171
|
+
if (pool.isClosed() || !roomTopic)
|
|
231
172
|
return;
|
|
232
173
|
const targetTopic = body.to ? roomTopic + '/' + body.to : roomTopic;
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
let payload;
|
|
236
|
-
try {
|
|
237
|
-
const key = resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
|
|
238
|
-
payload = key ? await sealPayload(key, plain, targetTopic) : plain;
|
|
239
|
-
}
|
|
240
|
-
catch {
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
if (closed)
|
|
174
|
+
const sealed = await envelope.sealJson(body, targetTopic, fixedMid);
|
|
175
|
+
if (!sealed || pool.isClosed())
|
|
244
176
|
return;
|
|
245
|
-
const frame = buildPublish(targetTopic,
|
|
246
|
-
for (const ws of targetSockets ?? readySockets) {
|
|
177
|
+
const frame = buildPublish(targetTopic, sealed.bytes);
|
|
178
|
+
for (const ws of targetSockets ?? pool.readySockets) {
|
|
247
179
|
if (ws.readyState === wsOpen) {
|
|
248
180
|
try {
|
|
249
181
|
ws.send(frame);
|
|
@@ -254,365 +186,168 @@ export function mqttSignaling(options = {}) {
|
|
|
254
186
|
}
|
|
255
187
|
}
|
|
256
188
|
};
|
|
257
|
-
const handlePayload =
|
|
258
|
-
if (
|
|
189
|
+
const handlePayload = (msgTopic, raw) => {
|
|
190
|
+
if (pool.isClosed())
|
|
259
191
|
return;
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
catch {
|
|
192
|
+
if (!envelope.isEncrypted) {
|
|
193
|
+
const data = envelope.parsePlaintext(raw);
|
|
194
|
+
if (data)
|
|
195
|
+
presence.dispatch(data);
|
|
265
196
|
return;
|
|
266
197
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
198
|
+
void envelope.openEncrypted(raw, msgTopic, { isClosed: pool.isClosed }).then((data) => {
|
|
199
|
+
if (data && !pool.isClosed())
|
|
200
|
+
presence.dispatch(data);
|
|
201
|
+
});
|
|
202
|
+
};
|
|
203
|
+
const shutdownSocket = (ws, byeFrame) => {
|
|
270
204
|
try {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
}
|
|
276
|
-
if (closed)
|
|
277
|
-
return;
|
|
278
|
-
if (!plain) {
|
|
279
|
-
if (key) {
|
|
280
|
-
const now = Date.now();
|
|
281
|
-
if (now - lastDecryptErrorAt >= errorCooldownMs) {
|
|
282
|
-
lastDecryptErrorAt = now;
|
|
283
|
-
discovery.error?.('decrypt-failed', 'Failed to decrypt MQTT signaling message');
|
|
284
|
-
}
|
|
205
|
+
if (ws.readyState === wsOpen) {
|
|
206
|
+
if (byeFrame)
|
|
207
|
+
ws.send(byeFrame);
|
|
208
|
+
ws.send(disconnectPkt);
|
|
285
209
|
}
|
|
286
|
-
|
|
287
|
-
}
|
|
288
|
-
let data = null;
|
|
289
|
-
try {
|
|
290
|
-
data = JSON.parse(decoder.decode(plain));
|
|
210
|
+
ws.close();
|
|
291
211
|
}
|
|
292
212
|
catch {
|
|
293
|
-
|
|
213
|
+
// Ignore shutdown errors.
|
|
294
214
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
215
|
+
};
|
|
216
|
+
const pool = createRelayPool({
|
|
217
|
+
discovery,
|
|
218
|
+
urls,
|
|
219
|
+
handshakeTimeoutMs,
|
|
220
|
+
offlineReason: 'All MQTT relays disconnected',
|
|
221
|
+
envelope,
|
|
222
|
+
privateTopic,
|
|
223
|
+
createSocket(url) {
|
|
224
|
+
const ws = new WsCtor(url, ['mqtt']);
|
|
225
|
+
ws.binaryType = 'arraybuffer';
|
|
226
|
+
return ws;
|
|
227
|
+
},
|
|
228
|
+
attachSocket(ws, controls) {
|
|
229
|
+
let buffer = new Uint8Array(0);
|
|
230
|
+
let pingTimer;
|
|
231
|
+
let awaitingPong = false;
|
|
232
|
+
let subscribed = false;
|
|
233
|
+
const sendFrame = (frame) => {
|
|
234
|
+
try {
|
|
235
|
+
ws.send(frame);
|
|
306
236
|
}
|
|
307
|
-
|
|
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))
|
|
317
|
-
return;
|
|
318
|
-
}
|
|
319
|
-
switch (data.type) {
|
|
320
|
-
case 'hello':
|
|
321
|
-
touch(data.from);
|
|
322
|
-
void publishRaw({ type: 'present', to: data.from });
|
|
323
|
-
break;
|
|
324
|
-
case 'heartbeat':
|
|
325
|
-
if (!touch(data.from))
|
|
326
|
-
void publishRaw({ type: 'present', to: data.from });
|
|
327
|
-
break;
|
|
328
|
-
case 'present':
|
|
329
|
-
touch(data.from);
|
|
330
|
-
break;
|
|
331
|
-
case 'bye':
|
|
332
|
-
if (seen.delete(data.from))
|
|
333
|
-
roster();
|
|
334
|
-
break;
|
|
335
|
-
case 'signal':
|
|
336
|
-
if (isSignal(data.signal)) {
|
|
337
|
-
touch(data.from);
|
|
338
|
-
discovery.receive(data.from, data.signal);
|
|
237
|
+
catch {
|
|
238
|
+
controls.abort();
|
|
339
239
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
ws.binaryType = 'arraybuffer';
|
|
363
|
-
allSockets.add(ws);
|
|
364
|
-
let buffer = new Uint8Array(0);
|
|
365
|
-
let pingTimer;
|
|
366
|
-
let handshakeTimer;
|
|
367
|
-
let awaitingPong = false;
|
|
368
|
-
let subscribed = false;
|
|
369
|
-
const abortSocket = () => {
|
|
370
|
-
try {
|
|
371
|
-
ws.close();
|
|
372
|
-
}
|
|
373
|
-
catch {
|
|
374
|
-
// Ignore close errors.
|
|
375
|
-
}
|
|
376
|
-
};
|
|
377
|
-
const sendFrame = (frame) => {
|
|
378
|
-
try {
|
|
379
|
-
ws.send(frame);
|
|
380
|
-
}
|
|
381
|
-
catch {
|
|
382
|
-
abortSocket();
|
|
383
|
-
}
|
|
384
|
-
};
|
|
385
|
-
handshakeTimer = setTimeout(() => {
|
|
386
|
-
if (!subscribed)
|
|
387
|
-
abortSocket();
|
|
388
|
-
}, handshakeTimeoutMs);
|
|
389
|
-
const cleanup = () => {
|
|
390
|
-
if (handshakeTimer)
|
|
391
|
-
clearTimeout(handshakeTimer);
|
|
392
|
-
if (pingTimer)
|
|
393
|
-
clearInterval(pingTimer);
|
|
394
|
-
allSockets.delete(ws);
|
|
395
|
-
const wasReady = readySockets.delete(ws);
|
|
396
|
-
settleInitial();
|
|
397
|
-
if (wasReady || initialPending === 0)
|
|
398
|
-
updateStatus();
|
|
399
|
-
if (!closed) {
|
|
400
|
-
const base = Math.min(15_000, 1_000 * 2 ** Math.min(attempt, 4));
|
|
401
|
-
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
402
|
-
const timer = setTimeout(() => {
|
|
403
|
-
reconnectTimers.delete(timer);
|
|
404
|
-
connectBroker(url, attempt + 1, false);
|
|
405
|
-
}, delay);
|
|
406
|
-
reconnectTimers.add(timer);
|
|
407
|
-
}
|
|
408
|
-
};
|
|
409
|
-
ws.onopen = () => {
|
|
410
|
-
if (closed) {
|
|
411
|
-
abortSocket();
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
const clientId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
|
|
415
|
-
sendFrame(buildConnect(clientId));
|
|
416
|
-
};
|
|
417
|
-
ws.onmessage = ({ data }) => {
|
|
418
|
-
if (closed || !(data instanceof ArrayBuffer))
|
|
419
|
-
return;
|
|
420
|
-
if (buffer.length + data.byteLength > maxMqttBuffer) {
|
|
421
|
-
abortSocket();
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
buffer = concatBytes(buffer, new Uint8Array(data));
|
|
425
|
-
buffer = parseMqttFrames(buffer, {
|
|
426
|
-
onConnAck(code) {
|
|
427
|
-
if (closed)
|
|
428
|
-
return;
|
|
429
|
-
if (code !== 0) {
|
|
430
|
-
abortSocket();
|
|
431
|
-
return;
|
|
432
|
-
}
|
|
433
|
-
const id = nextPacketId;
|
|
434
|
-
nextPacketId = (nextPacketId % 65535) + 1;
|
|
435
|
-
sendFrame(buildSubscribe(id, [roomTopic, inboxTopic]));
|
|
436
|
-
},
|
|
437
|
-
onSubAck(codes) {
|
|
438
|
-
if (closed || subscribed)
|
|
439
|
-
return;
|
|
440
|
-
if (codes.length < 2 || codes.some((c) => c === 0x80)) {
|
|
441
|
-
abortSocket();
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
subscribed = true;
|
|
445
|
-
if (handshakeTimer)
|
|
446
|
-
clearTimeout(handshakeTimer);
|
|
447
|
-
handshakeTimer = undefined;
|
|
448
|
-
attempt = 0;
|
|
449
|
-
settleInitial();
|
|
450
|
-
readySockets.add(ws);
|
|
451
|
-
updateStatus();
|
|
452
|
-
void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
|
|
453
|
-
pingTimer = setInterval(() => {
|
|
454
|
-
if (ws.readyState !== wsOpen)
|
|
240
|
+
};
|
|
241
|
+
ws.onopen = () => {
|
|
242
|
+
if (pool.isClosed()) {
|
|
243
|
+
controls.abort();
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
const clientId = 'mp-' + discovery.self.slice(0, 8) + '-' + Math.random().toString(36).slice(2, 6);
|
|
247
|
+
sendFrame(buildConnect(clientId));
|
|
248
|
+
};
|
|
249
|
+
ws.onmessage = ({ data }) => {
|
|
250
|
+
if (pool.isClosed() || !(data instanceof ArrayBuffer))
|
|
251
|
+
return;
|
|
252
|
+
if (buffer.length + data.byteLength > maxMqttBuffer) {
|
|
253
|
+
controls.abort();
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
buffer = concatBytes(buffer, new Uint8Array(data));
|
|
257
|
+
buffer = parseMqttFrames(buffer, {
|
|
258
|
+
onConnAck(code) {
|
|
259
|
+
if (pool.isClosed())
|
|
455
260
|
return;
|
|
456
|
-
if (
|
|
457
|
-
|
|
261
|
+
if (code !== 0) {
|
|
262
|
+
controls.abort();
|
|
458
263
|
return;
|
|
459
264
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
265
|
+
const id = nextPacketId;
|
|
266
|
+
nextPacketId = (nextPacketId % 65535) + 1;
|
|
267
|
+
sendFrame(buildSubscribe(id, [roomTopic, inboxTopic]));
|
|
268
|
+
},
|
|
269
|
+
onSubAck(codes) {
|
|
270
|
+
if (pool.isClosed() || subscribed)
|
|
271
|
+
return;
|
|
272
|
+
if (codes.length < 2 || codes.some((c) => c === 0x80)) {
|
|
273
|
+
controls.abort();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
subscribed = true;
|
|
277
|
+
controls.markReady();
|
|
278
|
+
pingTimer = setInterval(() => {
|
|
279
|
+
if (ws.readyState !== wsOpen)
|
|
280
|
+
return;
|
|
281
|
+
if (awaitingPong) {
|
|
282
|
+
controls.abort();
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
awaitingPong = true;
|
|
286
|
+
sendFrame(pingReq);
|
|
287
|
+
}, 20_000);
|
|
288
|
+
},
|
|
289
|
+
onPingResp() {
|
|
290
|
+
awaitingPong = false;
|
|
291
|
+
},
|
|
292
|
+
onPublish(msg) {
|
|
293
|
+
if (!subscribed)
|
|
294
|
+
return;
|
|
295
|
+
if (msg.topic === roomTopic || msg.topic === inboxTopic) {
|
|
296
|
+
handlePayload(msg.topic, msg.payload);
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
onError() {
|
|
300
|
+
controls.abort();
|
|
472
301
|
}
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
ws
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
return;
|
|
485
|
-
const now = Date.now();
|
|
486
|
-
let changed = false;
|
|
487
|
-
for (const [id, last] of seen) {
|
|
488
|
-
if (now - last > 30_000) {
|
|
489
|
-
seen.delete(id);
|
|
490
|
-
changed = true;
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
if (changed)
|
|
494
|
-
roster();
|
|
495
|
-
replayGuard.prune(now);
|
|
496
|
-
if (readySockets.size > 0)
|
|
497
|
-
void publishRaw({ type: 'heartbeat' });
|
|
498
|
-
}, 5_000);
|
|
499
|
-
if (keysPromise && privateTopic) {
|
|
500
|
-
void keysPromise
|
|
501
|
-
.then((keys) => {
|
|
502
|
-
if (closed)
|
|
503
|
-
return;
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
return () => {
|
|
305
|
+
if (pingTimer)
|
|
306
|
+
clearInterval(pingTimer);
|
|
307
|
+
};
|
|
308
|
+
},
|
|
309
|
+
onReady(ws, isInitial) {
|
|
310
|
+
void publishRaw({ type: 'hello' }, [ws], isInitial ? initialHelloMid : undefined);
|
|
311
|
+
},
|
|
312
|
+
onPrivateKeys(keys) {
|
|
504
313
|
roomTopic = 'meshpost/1/p/' + keys.privateId;
|
|
505
314
|
inboxTopic = roomTopic + '/' + discovery.self;
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
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
|
-
}
|
|
545
|
-
return {
|
|
546
|
-
trickle: true,
|
|
547
|
-
send(to, signal) {
|
|
548
|
-
if (closed || readySockets.size === 0)
|
|
549
|
-
return false;
|
|
315
|
+
},
|
|
316
|
+
onSweep(now, hasReadySockets) {
|
|
317
|
+
presence.prune(now);
|
|
318
|
+
envelope.prune(now);
|
|
319
|
+
if (hasReadySockets)
|
|
320
|
+
void publishRaw({ type: 'heartbeat' });
|
|
321
|
+
},
|
|
322
|
+
sendSignal(to, signal) {
|
|
550
323
|
void publishRaw({ type: 'signal', to, signal });
|
|
551
|
-
return true;
|
|
552
324
|
},
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
clearInterval(leaseTimer);
|
|
558
|
-
for (const timer of reconnectTimers)
|
|
559
|
-
clearTimeout(timer);
|
|
560
|
-
reconnectTimers.clear();
|
|
561
|
-
const socketsToClose = [...allSockets];
|
|
562
|
-
const readyToNotify = [...readySockets];
|
|
563
|
-
allSockets.clear();
|
|
564
|
-
readySockets.clear();
|
|
565
|
-
const shutdownSocket = (ws, byeFrame) => {
|
|
566
|
-
try {
|
|
567
|
-
if (ws.readyState === wsOpen) {
|
|
568
|
-
if (byeFrame)
|
|
569
|
-
ws.send(byeFrame);
|
|
570
|
-
ws.send(disconnectPkt);
|
|
571
|
-
}
|
|
572
|
-
ws.close();
|
|
573
|
-
}
|
|
574
|
-
catch {
|
|
575
|
-
// Ignore shutdown errors.
|
|
576
|
-
}
|
|
577
|
-
};
|
|
578
|
-
const byePlain = encoder.encode(JSON.stringify({
|
|
579
|
-
type: 'bye',
|
|
580
|
-
from: discovery.self,
|
|
581
|
-
mid: discovery.self.slice(0, 8) + ':' + ++msgSeq,
|
|
582
|
-
ts: Date.now()
|
|
583
|
-
}));
|
|
584
|
-
if (!keysPromise && roomTopic) {
|
|
585
|
-
const byeFrame = buildPublish(roomTopic, byePlain);
|
|
586
|
-
for (const ws of socketsToClose) {
|
|
587
|
-
shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
else if (resolvedKey && roomTopic && readyToNotify.length > 0) {
|
|
591
|
-
const nonReady = socketsToClose.filter((ws) => !readyToNotify.includes(ws));
|
|
592
|
-
for (const ws of nonReady)
|
|
593
|
-
shutdownSocket(ws);
|
|
594
|
-
const fallbackTimer = setTimeout(() => {
|
|
595
|
-
for (const ws of readyToNotify)
|
|
596
|
-
shutdownSocket(ws);
|
|
597
|
-
}, 250);
|
|
598
|
-
void sealPayload(resolvedKey, byePlain, roomTopic)
|
|
599
|
-
.then((boxed) => {
|
|
600
|
-
clearTimeout(fallbackTimer);
|
|
601
|
-
const byeFrame = buildPublish(roomTopic, boxed);
|
|
602
|
-
for (const ws of readyToNotify)
|
|
603
|
-
shutdownSocket(ws, byeFrame);
|
|
604
|
-
})
|
|
605
|
-
.catch(() => {
|
|
606
|
-
clearTimeout(fallbackTimer);
|
|
607
|
-
for (const ws of readyToNotify)
|
|
608
|
-
shutdownSocket(ws);
|
|
609
|
-
});
|
|
610
|
-
}
|
|
611
|
-
else {
|
|
612
|
-
for (const ws of socketsToClose)
|
|
325
|
+
onClose(allSockets, readySockets) {
|
|
326
|
+
const readySet = new Set(readySockets);
|
|
327
|
+
for (const ws of allSockets) {
|
|
328
|
+
if (!readySet.has(ws))
|
|
613
329
|
shutdownSocket(ws);
|
|
614
330
|
}
|
|
331
|
+
envelope.flushBye({
|
|
332
|
+
aad: roomTopic || undefined,
|
|
333
|
+
hasReadyTargets: readySockets.length > 0,
|
|
334
|
+
onPlain(byeJson) {
|
|
335
|
+
const frame = roomTopic ? buildPublish(roomTopic, encoder.encode(byeJson)) : undefined;
|
|
336
|
+
for (const ws of readySockets)
|
|
337
|
+
shutdownSocket(ws, frame);
|
|
338
|
+
},
|
|
339
|
+
onEncrypted(boxed) {
|
|
340
|
+
const frame = roomTopic ? buildPublish(roomTopic, boxed) : undefined;
|
|
341
|
+
for (const ws of readySockets)
|
|
342
|
+
shutdownSocket(ws, frame);
|
|
343
|
+
},
|
|
344
|
+
onDoneNoBye() {
|
|
345
|
+
for (const ws of readySockets)
|
|
346
|
+
shutdownSocket(ws);
|
|
347
|
+
}
|
|
348
|
+
});
|
|
615
349
|
}
|
|
616
|
-
};
|
|
350
|
+
});
|
|
351
|
+
return pool.session;
|
|
617
352
|
};
|
|
618
353
|
}
|