@dimchansky/meshpost 0.3.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.
@@ -0,0 +1,264 @@
1
+ import { toBase64Url } from './crypto.js';
2
+ const encoder = new TextEncoder();
3
+ const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
4
+ const userIdDomainPrefix = encoder.encode('meshpost/1/userid:');
5
+ const dtlsFingerprintLinePattern = /^a=fingerprint:(sha-256|sha-384|sha-512)\s+([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2})+)\s*$/i;
6
+ const expectedFingerprintHexLength = {
7
+ 'sha-256': 32 * 3 - 1,
8
+ 'sha-384': 48 * 3 - 1,
9
+ 'sha-512': 64 * 3 - 1
10
+ };
11
+ const identityInternals = new WeakMap();
12
+ /** @internal */
13
+ export function decodeCanonicalBase64Url(value, expectedChars, expectedBytes) {
14
+ if (typeof value !== 'string' ||
15
+ value.length !== expectedChars ||
16
+ !base64UrlPattern.test(value)) {
17
+ return null;
18
+ }
19
+ try {
20
+ const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
21
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
22
+ const binary = atob(padded);
23
+ if (binary.length !== expectedBytes)
24
+ return null;
25
+ const out = new Uint8Array(expectedBytes);
26
+ for (let i = 0; i < expectedBytes; i++)
27
+ out[i] = binary.charCodeAt(i);
28
+ return toBase64Url(out) === value ? out : null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ async function deriveUserIdFromRawPublicKey(subtle, rawPub) {
35
+ const input = new Uint8Array(userIdDomainPrefix.byteLength + rawPub.byteLength);
36
+ input.set(userIdDomainPrefix, 0);
37
+ input.set(rawPub, userIdDomainPrefix.byteLength);
38
+ const digest = new Uint8Array(await subtle.digest('SHA-256', input));
39
+ return toBase64Url(digest.subarray(0, 16));
40
+ }
41
+ function parseExtractableOption(options) {
42
+ if (options === undefined)
43
+ return true;
44
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
45
+ throw new TypeError('Invalid identity options');
46
+ }
47
+ const { extractable } = options;
48
+ if (extractable !== undefined && typeof extractable !== 'boolean') {
49
+ throw new TypeError('Invalid extractable option');
50
+ }
51
+ return extractable ?? true;
52
+ }
53
+ function requireSubtleCrypto() {
54
+ const subtle = globalThis.crypto?.subtle;
55
+ if (!subtle) {
56
+ throw new Error('Peer identity requires a secure context (crypto.subtle)');
57
+ }
58
+ return subtle;
59
+ }
60
+ /**
61
+ * Generate a fresh WebCrypto `ECDSA P-256` peer identity with a deterministic 128-bit `userId`.
62
+ */
63
+ export async function createIdentity(options) {
64
+ const extractable = parseExtractableOption(options);
65
+ const subtle = requireSubtleCrypto();
66
+ const pair = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, extractable, [
67
+ 'sign',
68
+ 'verify'
69
+ ]);
70
+ const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));
71
+ const userId = await deriveUserIdFromRawPublicKey(subtle, rawPub);
72
+ const identity = Object.freeze({
73
+ userId,
74
+ publicKey: toBase64Url(rawPub)
75
+ });
76
+ identityInternals.set(identity, { privateKey: pair.privateKey, extractable });
77
+ return identity;
78
+ }
79
+ /**
80
+ * Serialize an extractable `PeerIdentity` to a compact, JSON-safe object suitable for `localStorage`.
81
+ */
82
+ export async function exportIdentity(identity) {
83
+ const internals = typeof identity === 'object' && identity !== null ? identityInternals.get(identity) : undefined;
84
+ if (!internals)
85
+ throw new TypeError('Expected a valid PeerIdentity');
86
+ if (!internals.extractable)
87
+ throw new Error('Identity is not extractable');
88
+ const subtle = requireSubtleCrypto();
89
+ const jwk = await subtle.exportKey('jwk', internals.privateKey);
90
+ if (typeof jwk.x !== 'string' ||
91
+ typeof jwk.y !== 'string' ||
92
+ typeof jwk.d !== 'string' ||
93
+ decodeCanonicalBase64Url(jwk.x, 43, 32) === null ||
94
+ decodeCanonicalBase64Url(jwk.y, 43, 32) === null ||
95
+ decodeCanonicalBase64Url(jwk.d, 43, 32) === null) {
96
+ throw new Error('Failed to export valid P-256 key material');
97
+ }
98
+ return Object.freeze({
99
+ v: 1,
100
+ crv: 'P-256',
101
+ x: jwk.x,
102
+ y: jwk.y,
103
+ d: jwk.d
104
+ });
105
+ }
106
+ /**
107
+ * Type guard checking whether an unknown JSON value has the canonical `SerializedIdentity` shape.
108
+ */
109
+ export function isSerializedIdentity(value) {
110
+ if (!value || typeof value !== 'object' || Array.isArray(value))
111
+ return false;
112
+ const rec = value;
113
+ return (rec.v === 1 &&
114
+ rec.crv === 'P-256' &&
115
+ decodeCanonicalBase64Url(rec.x, 43, 32) !== null &&
116
+ decodeCanonicalBase64Url(rec.y, 43, 32) !== null &&
117
+ decodeCanonicalBase64Url(rec.d, 43, 32) !== null);
118
+ }
119
+ /**
120
+ * Import and cryptographically self-verify a `SerializedIdentity` (`(x, y)` verified against `d`).
121
+ */
122
+ export async function importIdentity(data, options) {
123
+ const extractable = parseExtractableOption(options);
124
+ if (!isSerializedIdentity(data)) {
125
+ throw new TypeError('Invalid serialized identity');
126
+ }
127
+ const subtle = requireSubtleCrypto();
128
+ const xBytes = decodeCanonicalBase64Url(data.x, 43, 32);
129
+ const yBytes = decodeCanonicalBase64Url(data.y, 43, 32);
130
+ if (!xBytes || !yBytes) {
131
+ throw new TypeError('Invalid serialized identity');
132
+ }
133
+ const rawCandidate = new Uint8Array(65);
134
+ rawCandidate[0] = 0x04;
135
+ rawCandidate.set(xBytes, 1);
136
+ rawCandidate.set(yBytes, 33);
137
+ try {
138
+ const [privateKey, publicKey] = await Promise.all([
139
+ subtle.importKey('jwk', {
140
+ kty: 'EC',
141
+ crv: 'P-256',
142
+ x: data.x,
143
+ y: data.y,
144
+ d: data.d,
145
+ key_ops: ['sign'],
146
+ ext: extractable
147
+ }, { name: 'ECDSA', namedCurve: 'P-256' }, extractable, ['sign']),
148
+ subtle.importKey('raw', rawCandidate, { name: 'ECDSA', namedCurve: 'P-256' }, true, [
149
+ 'verify'
150
+ ])
151
+ ]);
152
+ const challenge = crypto.getRandomValues(new Uint8Array(16));
153
+ const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, challenge);
154
+ const consistent = await subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, publicKey, sig, challenge);
155
+ if (!consistent)
156
+ throw new Error('Invalid identity keypair');
157
+ const rawPub = new Uint8Array(await subtle.exportKey('raw', publicKey));
158
+ const userId = await deriveUserIdFromRawPublicKey(subtle, rawPub);
159
+ const identity = Object.freeze({
160
+ userId,
161
+ publicKey: toBase64Url(rawPub)
162
+ });
163
+ identityInternals.set(identity, { privateKey, extractable });
164
+ return identity;
165
+ }
166
+ catch {
167
+ throw new Error('Invalid identity keypair');
168
+ }
169
+ }
170
+ /** @internal */
171
+ export function isValidPeerIdentity(value) {
172
+ return typeof value === 'object' && value !== null && identityInternals.has(value);
173
+ }
174
+ /**
175
+ * Extract the single canonical DTLS certificate fingerprint from an SDP description.
176
+ * Rejects weak hashes (`sha-1`, `md5`), malformed `a=fingerprint:` lines, and RFC 8122 §5
177
+ * multi-fingerprint MitM injections (`unique.size !== 1`).
178
+ * @internal
179
+ */
180
+ export function extractUniqueDtlsFingerprint(sdp) {
181
+ if (typeof sdp !== 'string' || sdp.length === 0)
182
+ return null;
183
+ const unique = new Set();
184
+ const lines = sdp.split(/\r?\n/);
185
+ for (const line of lines) {
186
+ if (!line.startsWith('a=fingerprint:'))
187
+ continue;
188
+ const match = dtlsFingerprintLinePattern.exec(line);
189
+ if (!match)
190
+ return null;
191
+ const algo = match[1].toLowerCase();
192
+ const hex = match[2].toUpperCase();
193
+ if (hex.length !== expectedFingerprintHexLength[algo])
194
+ return null;
195
+ unique.add(`${algo} ${hex}`);
196
+ }
197
+ return unique.size === 1 ? [...unique][0] : null;
198
+ }
199
+ function buildIdentityTranscript(params) {
200
+ const fields = [
201
+ params.appId,
202
+ params.room,
203
+ params.signerId,
204
+ params.verifierId,
205
+ params.signerFp,
206
+ params.verifierFp
207
+ ];
208
+ let text = 'meshpost/1/id-sig\0';
209
+ for (const field of fields) {
210
+ text += `${field.length}:${field}\n`;
211
+ }
212
+ return encoder.encode(text);
213
+ }
214
+ /** @internal */
215
+ export async function signIdentityProof(identity, params) {
216
+ const internals = identityInternals.get(identity);
217
+ if (!internals)
218
+ throw new TypeError('Expected a valid PeerIdentity');
219
+ const subtle = requireSubtleCrypto();
220
+ const transcript = buildIdentityTranscript(params);
221
+ const sig = new Uint8Array(await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, internals.privateKey, transcript.buffer instanceof ArrayBuffer
222
+ ? new Uint8Array(transcript.buffer, transcript.byteOffset, transcript.byteLength)
223
+ : Uint8Array.from(transcript)));
224
+ return {
225
+ pub: identity.publicKey,
226
+ sig: toBase64Url(sig)
227
+ };
228
+ }
229
+ /** @internal */
230
+ export async function verifyIdentityProof(proof, params) {
231
+ const subtle = globalThis.crypto?.subtle;
232
+ if (!subtle)
233
+ return null;
234
+ const rawPub = decodeCanonicalBase64Url(proof.pub, 87, 65);
235
+ if (!rawPub || rawPub[0] !== 0x04)
236
+ return null;
237
+ const rawSig = decodeCanonicalBase64Url(proof.sig, 86, 64);
238
+ if (!rawSig)
239
+ return null;
240
+ try {
241
+ const publicKey = await subtle.importKey('raw', Uint8Array.from(rawPub), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
242
+ const transcript = buildIdentityTranscript(params);
243
+ const ok = await subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, publicKey, Uint8Array.from(rawSig), Uint8Array.from(transcript));
244
+ if (!ok)
245
+ return null;
246
+ return await deriveUserIdFromRawPublicKey(subtle, rawPub);
247
+ }
248
+ catch {
249
+ return null;
250
+ }
251
+ }
252
+ /** @internal */
253
+ export async function sha256Base64Url(input) {
254
+ const subtle = globalThis.crypto?.subtle;
255
+ if (!subtle)
256
+ return null;
257
+ try {
258
+ const digest = await subtle.digest('SHA-256', encoder.encode(input));
259
+ return toBase64Url(new Uint8Array(digest));
260
+ }
261
+ catch {
262
+ return null;
263
+ }
264
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
- export type { Delivery, ListenOptions, PeerRoute, PeerStats, Room, RoomError, RoomErrorCode, RoomOptions, SendOptions, SendResult } from './room.js';
3
- export { createChannel } from './channel.js';
4
- export type { Channel, ChannelOptions, ChannelSendOptions } from './channel.js';
2
+ export { createIdentity, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
+ export type { CreateIdentityOptions, PeerIdentity, SerializedIdentity } from './identity.js';
4
+ export type { AddStreamOptions, Delivery, ListenOptions, PeerRoute, PeerStats, PeerStreamMeta, RemoveStreamOptions, Room, RoomError, RoomErrorCode, RoomOptions, RTCPeerConnectionConstructor, SendOptions, SendResult } from './room.js';
5
+ export { binaryCodec, createChannel, createCodecChannel, jsonCodec, textCodec } from './channel.js';
6
+ export type { Channel, ChannelOptions, ChannelSendOptions, Codec, CodecChannel } from './channel.js';
7
+ export { createRpc, RpcError } from './rpc.js';
8
+ export type { RpcCallOptions, RpcEndpoint, RpcErrorCode, RpcOptions } from './rpc.js';
9
+ export { createPeerState } from './state.js';
10
+ export type { PeerState, PeerStateOptions } from './state.js';
5
11
  export { createBlobChannel } from './blob.js';
6
12
  export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
7
13
  export { createVoice } from './voice.js';
@@ -13,8 +19,10 @@ export { manualSignaling } from './manual.js';
13
19
  export type { ManualSignaling } from './manual.js';
14
20
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
15
21
  export type { MqttSignalingOptions } from './mqtt.js';
22
+ export { defaultNostrRelays, nostrSignaling } from './nostr.js';
23
+ export type { NostrSignalingOptions } from './nostr.js';
16
24
  export { wsSignaling } from './ws.js';
17
25
  export type { WsSignalingOptions } from './ws.js';
18
26
  export { combineSignaling, withLocalTabs } from './combine.js';
19
27
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
20
- export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState } from './signaling.js';
28
+ export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState, WebSocketConstructor } from './signaling.js';
package/dist/index.js CHANGED
@@ -1,11 +1,15 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
- export { createChannel } from './channel.js';
2
+ export { createIdentity, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
+ export { binaryCodec, createChannel, createCodecChannel, jsonCodec, textCodec } from './channel.js';
4
+ export { createRpc, RpcError } from './rpc.js';
5
+ export { createPeerState } from './state.js';
3
6
  export { createBlobChannel } from './blob.js';
4
7
  export { createVoice } from './voice.js';
5
8
  export { fetchTurnCredentials } from './turn.js';
6
9
  export { tabSignaling } from './tabs.js';
7
10
  export { manualSignaling } from './manual.js';
8
11
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
12
+ export { defaultNostrRelays, nostrSignaling } from './nostr.js';
9
13
  export { wsSignaling } from './ws.js';
10
14
  export { combineSignaling, withLocalTabs } from './combine.js';
11
15
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
package/dist/mqtt.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Signaling } from './signaling.js';
1
+ import { type Signaling, type WebSocketConstructor } from './signaling.js';
2
2
  /** Built-in public MQTT-over-WebSocket relay URLs used by default. */
3
3
  export declare const defaultMqttRelays: readonly string[];
4
4
  export interface MqttSignalingOptions {
@@ -8,8 +8,16 @@ export interface MqttSignalingOptions {
8
8
  appId?: string;
9
9
  /** Optional shared password to encrypt signaling payloads with AES-256-GCM (requires secure context). */
10
10
  password?: string;
11
+ /**
12
+ * Derive the MQTT room topic 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;
11
17
  /** Maximum time in milliseconds to wait for CONNECT -> CONNACK -> SUBACK per broker. @default 10000 */
12
18
  handshakeTimeoutMs?: number;
19
+ /** Optional custom `WebSocket` constructor for headless runtimes or custom transports. */
20
+ WebSocket?: WebSocketConstructor;
13
21
  }
14
22
  /**
15
23
  * Zero-backend signaling over public (or custom) MQTT-over-WebSocket brokers.
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 roomTopic = 'meshpost/1/' + namespaceHash(appId + ':' + discovery.room);
197
- const inboxTopic = roomTopic + '/' + discovery.self;
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 seenMids = new Map();
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 keyPromise = password !== undefined
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 ?? (keyPromise ? await keyPromise : undefined);
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 === WebSocket.OPEN) {
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 ?? (keyPromise ? await keyPromise : undefined);
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 >= decryptErrorCooldownMs) {
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
- if (typeof data.mid !== 'string')
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
- if (typeof data.ts !== 'number' || Math.abs(Date.now() - data.ts) > replayWindowMs)
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 WebSocket(url, ['mqtt']);
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 !== WebSocket.OPEN)
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
- for (const [mid, at] of seenMids) {
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
- queueMicrotask(() => {
532
- if (closed)
533
- return;
534
- for (const url of urls)
535
- connectBroker(url);
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 === WebSocket.OPEN) {
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 (!keyPromise) {
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);