@dimchansky/meshpost 0.6.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.
@@ -0,0 +1,74 @@
1
+ import { isSignal } from './signaling.js';
2
+ const maxSeenPeers = 256;
3
+ const leaseTtlMs = 30_000;
4
+ const defaultErrorCooldownMs = 15_000;
5
+ /** @internal */
6
+ export function createErrorThrottle(emit, cooldownMs = defaultErrorCooldownMs) {
7
+ const lastAt = new Map();
8
+ return (code, message) => {
9
+ const now = Date.now();
10
+ const prev = lastAt.get(code) ?? -Infinity;
11
+ if (now - prev >= cooldownMs) {
12
+ lastAt.set(code, now);
13
+ emit(code, message);
14
+ }
15
+ };
16
+ }
17
+ /** @internal */
18
+ export function createPresenceTracker(discovery, sendPresent) {
19
+ const seen = new Map();
20
+ const roster = () => discovery.roster([...seen.keys()]);
21
+ const touch = (id) => {
22
+ const known = seen.has(id);
23
+ if (!known && seen.size >= maxSeenPeers) {
24
+ const oldest = seen.keys().next().value;
25
+ if (oldest !== undefined)
26
+ seen.delete(oldest);
27
+ }
28
+ seen.delete(id);
29
+ seen.set(id, Date.now());
30
+ if (!known)
31
+ roster();
32
+ return known;
33
+ };
34
+ return {
35
+ touch,
36
+ dispatch(data) {
37
+ const from = data.from;
38
+ switch (data.type) {
39
+ case 'hello':
40
+ touch(from);
41
+ sendPresent(from);
42
+ break;
43
+ case 'heartbeat':
44
+ if (!touch(from))
45
+ sendPresent(from);
46
+ break;
47
+ case 'present':
48
+ touch(from);
49
+ break;
50
+ case 'bye':
51
+ if (seen.delete(from))
52
+ roster();
53
+ break;
54
+ case 'signal':
55
+ if (isSignal(data.signal)) {
56
+ touch(from);
57
+ discovery.receive(from, data.signal);
58
+ }
59
+ break;
60
+ }
61
+ },
62
+ prune(now = Date.now()) {
63
+ let changed = false;
64
+ for (const [id, last] of seen) {
65
+ if (now - last > leaseTtlMs) {
66
+ seen.delete(id);
67
+ changed = true;
68
+ }
69
+ }
70
+ if (changed)
71
+ roster();
72
+ }
73
+ };
74
+ }
package/dist/public.js CHANGED
@@ -1,17 +1,13 @@
1
- import { combineSignaling, withLocalTabsInternal } from './combine.js';
1
+ import { combineSignaling, withLocalTabs } from './combine.js';
2
2
  import { mqttSignaling } from './mqtt.js';
3
3
  import { nostrSignaling } from './nostr.js';
4
+ import { normalizeWsRelayUrl, validatePositiveTimeout } from './relay-core.js';
4
5
  import { observeSignaling } from './signaling.js';
5
6
  import { optionalWsSignaling } from './ws.js';
6
7
  const maxOptionalWsUrls = 8;
7
8
  const maxRawWsUrlItems = 64;
8
9
  const defaultWsHandshakeTimeoutMs = 4_000;
9
10
  const defaultPublicHandshakeTimeoutMs = 10_000;
10
- function validateTimeoutMs(value, label) {
11
- if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {
12
- throw new RangeError(`Invalid ${label}`);
13
- }
14
- }
15
11
  function observeTransport(adapter, transport, onTransportChange, url) {
16
12
  return observeSignaling(adapter, (state, reason) => {
17
13
  onTransportChange(Object.freeze({
@@ -38,20 +34,7 @@ function normalizeWsUrls(raw) {
38
34
  }
39
35
  const deduped = new Set();
40
36
  for (const item of raw) {
41
- if (typeof item !== 'string' || item.length === 0) {
42
- throw new TypeError('Invalid WebSocket signaling URL');
43
- }
44
- let parsed;
45
- try {
46
- parsed = new URL(item);
47
- }
48
- catch {
49
- throw new TypeError('Invalid WebSocket signaling URL');
50
- }
51
- if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
52
- throw new TypeError('WebSocket signaling URL must use ws: or wss:');
53
- }
54
- deduped.add(parsed.toString());
37
+ deduped.add(normalizeWsRelayUrl(item, 'Invalid WebSocket signaling URL', 'WebSocket signaling URL must use ws: or wss:'));
55
38
  if (deduped.size > maxOptionalWsUrls) {
56
39
  throw new RangeError(`Too many wsUrls (max ${maxOptionalWsUrls} unique URLs)`);
57
40
  }
@@ -92,8 +75,8 @@ export function publicSignaling(options = {}) {
92
75
  if (mqtt === false && nostr === false) {
93
76
  throw new RangeError('publicSignaling requires at least one public relay transport (mqtt or nostr)');
94
77
  }
95
- validateTimeoutMs(wsHandshakeTimeoutMs, 'wsHandshakeTimeoutMs');
96
- validateTimeoutMs(handshakeTimeoutMs, 'handshakeTimeoutMs');
78
+ validatePositiveTimeout(wsHandshakeTimeoutMs, 'Invalid wsHandshakeTimeoutMs');
79
+ validatePositiveTimeout(handshakeTimeoutMs, 'Invalid handshakeTimeoutMs');
97
80
  const normalizedWsUrls = normalizeWsUrls(wsUrls);
98
81
  const adapters = [];
99
82
  const maybeObserve = (adapter, kind, url) => onTransportChange ? observeTransport(adapter, kind, onTransportChange, url) : adapter;
@@ -145,6 +128,16 @@ export function publicSignaling(options = {}) {
145
128
  });
146
129
  };
147
130
  return localTabs
148
- ? withLocalTabsInternal(pooledNetwork, onTransportChange ? (tabs) => observeTransport(tabs, 'tabs', onTransportChange) : undefined)
131
+ ? withLocalTabs(pooledNetwork, onTransportChange
132
+ ? {
133
+ onTabsState(state, reason) {
134
+ onTransportChange(Object.freeze({
135
+ transport: 'tabs',
136
+ state,
137
+ ...(reason !== undefined ? { reason } : {})
138
+ }));
139
+ }
140
+ }
141
+ : undefined)
149
142
  : pooledNetwork;
150
143
  }
@@ -1,9 +1,12 @@
1
- import { deriveSignalingKeys, errorCooldownMs, sealPayload } from './crypto.js';
2
- import { isSignal } from './signaling.js';
3
- const maxSeenPeers = 256;
4
- const leaseTtlMs = 30_000;
1
+ import { createReplayGuard, deriveSignalingKeys, maxMidLength, openPayload, sealPayload } from './crypto.js';
2
+ import { createErrorThrottle } from './presence.js';
3
+ import { isUuid } from './signaling.js';
5
4
  const leaseSweepIntervalMs = 5_000;
6
5
  const byeFlushTimeoutMs = 250;
6
+ const encoder = new TextEncoder();
7
+ const decoder = new TextDecoder();
8
+ /** @internal */
9
+ export const maxDecryptQueueDepth = 64;
7
10
  /** @internal */
8
11
  export function safeCloseSocket(ws) {
9
12
  if (!ws)
@@ -38,79 +41,220 @@ export function normalizeWsRelayUrl(raw, invalidMessage, protocolMessage) {
38
41
  return parsed.toString();
39
42
  }
40
43
  /** @internal */
41
- export function createErrorThrottle(discovery, cooldownMs = errorCooldownMs) {
42
- const lastAt = new Map();
43
- return (code, message) => {
44
- const now = Date.now();
45
- const prev = lastAt.get(code) ?? -Infinity;
46
- if (now - prev >= cooldownMs) {
47
- lastAt.set(code, now);
48
- discovery.error?.(code, message);
44
+ export function validateCommonSignalingOptions(options) {
45
+ if (options.password !== undefined &&
46
+ (typeof options.password !== 'string' || options.password.length === 0)) {
47
+ throw new TypeError('Invalid password');
48
+ }
49
+ if (options.privateTopic !== undefined && typeof options.privateTopic !== 'boolean') {
50
+ throw new TypeError('Invalid privateTopic option');
51
+ }
52
+ if (options.WebSocket !== undefined && typeof options.WebSocket !== 'function') {
53
+ throw new TypeError('Invalid WebSocket constructor');
54
+ }
55
+ }
56
+ /** @internal */
57
+ export function resolveSessionWebSocket(custom) {
58
+ const WsCtor = custom ?? globalThis.WebSocket;
59
+ if (typeof WsCtor !== 'function') {
60
+ throw new Error('WebSocket is not available in this runtime; pass options.WebSocket');
61
+ }
62
+ return WsCtor;
63
+ }
64
+ /** @internal */
65
+ export function resolveSessionPassword(password, privateTopic, encrypt = true, insecureMessage = 'Password encryption requires a secure context (crypto.subtle)') {
66
+ if (privateTopic && password === undefined) {
67
+ throw new TypeError('privateTopic requires a room password');
68
+ }
69
+ if (privateTopic && !encrypt) {
70
+ throw new Error('privateTopic requires encrypt: true');
71
+ }
72
+ const useEncryption = password !== undefined && encrypt;
73
+ if (password !== undefined) {
74
+ if (typeof password !== 'string' || password.length === 0) {
75
+ throw new TypeError('Invalid password');
49
76
  }
50
- };
77
+ if (useEncryption && !globalThis.crypto?.subtle) {
78
+ throw new Error(insecureMessage);
79
+ }
80
+ }
81
+ return { password, useEncryption };
51
82
  }
52
83
  /** @internal */
53
- export function createPresenceTracker(discovery, sendPresent) {
54
- const seen = new Map();
55
- const roster = () => discovery.roster([...seen.keys()]);
56
- const touch = (id) => {
57
- const known = seen.has(id);
58
- if (!known && seen.size >= maxSeenPeers) {
59
- const oldest = seen.keys().next().value;
60
- if (oldest !== undefined)
61
- seen.delete(oldest);
84
+ export function startKeyDerivation(options) {
85
+ const { keysPromise, privateTopic, isClosed, onResolvedKey, onPrivateKeys, onConnect, onError } = options;
86
+ if (keysPromise && privateTopic) {
87
+ void keysPromise
88
+ .then((keys) => {
89
+ if (isClosed())
90
+ return;
91
+ onResolvedKey(keys.aeadKey);
92
+ onPrivateKeys?.(keys);
93
+ onConnect();
94
+ })
95
+ .catch(() => {
96
+ if (isClosed())
97
+ return;
98
+ onError();
99
+ });
100
+ return;
101
+ }
102
+ if (keysPromise) {
103
+ void keysPromise
104
+ .then((keys) => {
105
+ onResolvedKey(keys.aeadKey);
106
+ })
107
+ .catch(() => {
108
+ if (isClosed())
109
+ return;
110
+ onError();
111
+ });
112
+ }
113
+ // Defer initial connect so synchronous errors never fire before callers attach listeners.
114
+ queueMicrotask(() => {
115
+ if (!isClosed())
116
+ onConnect();
117
+ });
118
+ }
119
+ /** @internal */
120
+ export function createRelayEnvelope(options) {
121
+ const { discovery, password, baseScope, transportLabel } = options;
122
+ const replayGuard = createReplayGuard();
123
+ const emitError = createErrorThrottle((code, message) => discovery.error?.(code, message));
124
+ const keysPromise = password !== undefined ? deriveSignalingKeys(password, baseScope) : undefined;
125
+ let resolvedKey;
126
+ let msgSeq = 0;
127
+ let pendingDecryptCount = 0;
128
+ const emitDecryptFailed = () => emitError('decrypt-failed', `Failed to decrypt ${transportLabel} signaling message`);
129
+ const emitClockSkew = () => emitError('clock-skew', `${transportLabel} signaling message rejected due to system clock skew (>60s)`);
130
+ const nextMid = () => discovery.self.slice(0, 8) + ':' + ++msgSeq;
131
+ const buildJson = (body, fixedMid) => JSON.stringify({ ...body, from: discovery.self, mid: fixedMid ?? nextMid(), ts: Date.now() });
132
+ const getKey = async () => resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined);
133
+ const parseAndVerifyMessage = (raw, authenticated, now = Date.now()) => {
134
+ let data = null;
135
+ try {
136
+ const text = typeof raw === 'string' ? raw : decoder.decode(raw);
137
+ data = JSON.parse(text);
62
138
  }
63
- seen.delete(id);
64
- seen.set(id, Date.now());
65
- if (!known)
66
- roster();
67
- return known;
139
+ catch {
140
+ return null;
141
+ }
142
+ if (!data || !isUuid(data.from) || data.from === discovery.self)
143
+ return null;
144
+ if (data.to !== undefined && data.to !== discovery.self)
145
+ return null;
146
+ if (authenticated) {
147
+ const check = replayGuard.checkAuthenticated(data.from, data, now);
148
+ if (check === 'clock-skew') {
149
+ emitClockSkew();
150
+ return null;
151
+ }
152
+ if (check !== 'ok')
153
+ return null;
154
+ return data;
155
+ }
156
+ if (data.mid !== undefined &&
157
+ (typeof data.mid !== 'string' || data.mid.length === 0 || data.mid.length > maxMidLength)) {
158
+ return null;
159
+ }
160
+ if (typeof data.mid === 'string' && !replayGuard.recordMid(data.from + ':' + data.mid, now)) {
161
+ return null;
162
+ }
163
+ return data;
68
164
  };
69
165
  return {
70
- touch,
71
- dispatch(data) {
72
- const from = data.from;
73
- switch (data.type) {
74
- case 'hello':
75
- touch(from);
76
- sendPresent(from);
77
- break;
78
- case 'heartbeat':
79
- if (!touch(from))
80
- sendPresent(from);
81
- break;
82
- case 'present':
83
- touch(from);
84
- break;
85
- case 'bye':
86
- if (seen.delete(from))
87
- roster();
88
- break;
89
- case 'signal':
90
- if (isSignal(data.signal)) {
91
- touch(from);
92
- discovery.receive(from, data.signal);
93
- }
94
- break;
166
+ keysPromise,
167
+ isEncrypted: keysPromise !== undefined,
168
+ setResolvedKey(key) {
169
+ resolvedKey = key;
170
+ },
171
+ getKey,
172
+ nextMid,
173
+ buildJson,
174
+ async sealJson(body, aad, fixedMid) {
175
+ const plainJson = buildJson(body, fixedMid);
176
+ const plainBytes = encoder.encode(plainJson);
177
+ try {
178
+ const key = await getKey();
179
+ const bytes = key ? await sealPayload(key, plainBytes, aad) : plainBytes;
180
+ return { plainJson, bytes };
181
+ }
182
+ catch {
183
+ return null;
95
184
  }
96
185
  },
97
- prune(now = Date.now()) {
98
- let changed = false;
99
- for (const [id, last] of seen) {
100
- if (now - last > leaseTtlMs) {
101
- seen.delete(id);
102
- changed = true;
186
+ async openEncrypted(boxed, aad, opts) {
187
+ if (pendingDecryptCount >= maxDecryptQueueDepth) {
188
+ opts?.onFinally?.();
189
+ return null;
190
+ }
191
+ pendingDecryptCount++;
192
+ try {
193
+ const key = await getKey();
194
+ if (!key || opts?.isClosed?.())
195
+ return null;
196
+ const plain = await openPayload(key, boxed, aad);
197
+ if (opts?.isClosed?.())
198
+ return null;
199
+ if (!plain) {
200
+ emitDecryptFailed();
201
+ return null;
103
202
  }
203
+ if (opts?.afterDecrypt && !opts.afterDecrypt())
204
+ return null;
205
+ return parseAndVerifyMessage(plain, true);
206
+ }
207
+ catch {
208
+ return null;
209
+ }
210
+ finally {
211
+ pendingDecryptCount--;
212
+ opts?.onFinally?.();
104
213
  }
105
- if (changed)
106
- roster();
214
+ },
215
+ parsePlaintext(raw, now) {
216
+ return parseAndVerifyMessage(raw, false, now);
217
+ },
218
+ flushBye({ aad, hasReadyTargets, onPlain, onEncrypted, onDoneNoBye }) {
219
+ const byeJson = buildJson({ type: 'bye' });
220
+ if (!keysPromise) {
221
+ onPlain(byeJson);
222
+ return;
223
+ }
224
+ if (!resolvedKey || !aad || !hasReadyTargets) {
225
+ onDoneNoBye();
226
+ return;
227
+ }
228
+ let settled = false;
229
+ const finishNoBye = () => {
230
+ if (settled)
231
+ return;
232
+ settled = true;
233
+ onDoneNoBye();
234
+ };
235
+ const fallbackTimer = setTimeout(finishNoBye, byeFlushTimeoutMs);
236
+ void sealPayload(resolvedKey, encoder.encode(byeJson), aad)
237
+ .then((boxed) => {
238
+ clearTimeout(fallbackTimer);
239
+ if (settled)
240
+ return;
241
+ settled = true;
242
+ onEncrypted(boxed);
243
+ })
244
+ .catch(() => {
245
+ clearTimeout(fallbackTimer);
246
+ finishNoBye();
247
+ });
248
+ },
249
+ emitDecryptFailed,
250
+ prune(now) {
251
+ replayGuard.prune(now);
107
252
  }
108
253
  };
109
254
  }
110
- const encoder = new TextEncoder();
111
255
  /** @internal */
112
256
  export function createRelayPool(config) {
113
- const { discovery, urls, handshakeTimeoutMs, offlineReason, password, privateTopic, baseScope } = config;
257
+ const { discovery, urls, handshakeTimeoutMs, offlineReason, envelope, privateTopic } = config;
114
258
  const readySockets = new Set();
115
259
  const allSockets = new Set();
116
260
  const reconnectTimers = new Set();
@@ -118,9 +262,6 @@ export function createRelayPool(config) {
118
262
  let reportedOnline = false;
119
263
  let reportedOffline = false;
120
264
  let initialPending = urls.length;
121
- let msgSeq = 0;
122
- let resolvedKey;
123
- const keysPromise = password !== undefined ? deriveSignalingKeys(password, baseScope) : undefined;
124
265
  const updateStatus = () => {
125
266
  if (closed)
126
267
  return;
@@ -210,46 +351,23 @@ export function createRelayPool(config) {
210
351
  return;
211
352
  config.onSweep?.(Date.now(), readySockets.size > 0);
212
353
  }, leaseSweepIntervalMs);
213
- if (keysPromise && privateTopic) {
214
- void keysPromise
215
- .then((keys) => {
216
- if (closed)
217
- return;
218
- resolvedKey = keys.aeadKey;
219
- config.onPrivateKeys?.(keys);
354
+ startKeyDerivation({
355
+ keysPromise: envelope.keysPromise,
356
+ privateTopic,
357
+ isClosed: () => closed,
358
+ onResolvedKey: envelope.setResolvedKey,
359
+ ...(config.onPrivateKeys ? { onPrivateKeys: config.onPrivateKeys } : {}),
360
+ onConnect() {
220
361
  for (const url of urls)
221
362
  connectUrl(url);
222
- })
223
- .catch(() => {
224
- if (closed)
225
- return;
363
+ },
364
+ onError() {
226
365
  initialPending = 0;
366
+ for (const ws of [...allSockets])
367
+ safeCloseSocket(ws);
227
368
  updateStatus();
228
- });
229
- }
230
- else {
231
- if (keysPromise) {
232
- void keysPromise
233
- .then((keys) => {
234
- resolvedKey = keys.aeadKey;
235
- })
236
- .catch(() => {
237
- if (closed)
238
- return;
239
- initialPending = 0;
240
- for (const ws of [...allSockets])
241
- safeCloseSocket(ws);
242
- updateStatus();
243
- });
244
369
  }
245
- queueMicrotask(() => {
246
- if (closed)
247
- return;
248
- for (const url of urls)
249
- connectUrl(url);
250
- });
251
- }
252
- const nextMid = () => discovery.self.slice(0, 8) + ':' + ++msgSeq;
370
+ });
253
371
  const session = {
254
372
  trickle: true,
255
373
  send(to, signal) {
@@ -266,58 +384,16 @@ export function createRelayPool(config) {
266
384
  for (const timer of reconnectTimers)
267
385
  clearTimeout(timer);
268
386
  reconnectTimers.clear();
269
- config.onBeforeClose?.();
270
387
  const socketsToClose = [...allSockets];
271
388
  const readyToNotify = [...readySockets];
272
389
  allSockets.clear();
273
390
  readySockets.clear();
274
- const byeJson = JSON.stringify({
275
- type: 'bye',
276
- from: discovery.self,
277
- mid: nextMid(),
278
- ts: Date.now()
279
- });
280
- if (!keysPromise) {
281
- const byeFrame = config.buildPlainBye(byeJson);
282
- for (const ws of socketsToClose) {
283
- config.shutdownSocket(ws, readyToNotify.includes(ws) ? byeFrame : undefined);
284
- }
285
- return;
286
- }
287
- const aad = config.byeAad();
288
- if (resolvedKey && aad && readyToNotify.length > 0) {
289
- for (const ws of socketsToClose) {
290
- if (!readyToNotify.includes(ws))
291
- config.shutdownSocket(ws);
292
- }
293
- const fallbackTimer = setTimeout(() => {
294
- for (const ws of readyToNotify)
295
- config.shutdownSocket(ws);
296
- }, byeFlushTimeoutMs);
297
- void sealPayload(resolvedKey, encoder.encode(byeJson), aad)
298
- .then((boxed) => {
299
- clearTimeout(fallbackTimer);
300
- const byeFrame = config.buildEncryptedBye(boxed);
301
- for (const ws of readyToNotify)
302
- config.shutdownSocket(ws, byeFrame);
303
- })
304
- .catch(() => {
305
- clearTimeout(fallbackTimer);
306
- for (const ws of readyToNotify)
307
- config.shutdownSocket(ws);
308
- });
309
- }
310
- else {
311
- for (const ws of socketsToClose)
312
- config.shutdownSocket(ws);
313
- }
391
+ config.onClose(socketsToClose, readyToNotify);
314
392
  }
315
393
  };
316
394
  return {
317
395
  isClosed: () => closed,
318
396
  readySockets,
319
- getKey: async () => resolvedKey ?? (keysPromise ? (await keysPromise).aeadKey : undefined),
320
- nextMid,
321
397
  session
322
398
  };
323
399
  }
@@ -4,6 +4,10 @@ import { isUuid } from './signaling.js';
4
4
  const reclaimTtlMs = 60_000;
5
5
  const maxSupersededPeers = 128;
6
6
  /** @internal */
7
+ export function computeReclaimCommit(id, secret) {
8
+ return sha256Base64Url(`meshpost/1/reclaim:${id}:${secret}`);
9
+ }
10
+ /** @internal */
7
11
  export function createSessionReclaim(params) {
8
12
  const { appId, roomName, self, isStopped, sendUnloadLeaveNotices } = params;
9
13
  const supersededPeers = new Set();
@@ -35,7 +39,7 @@ export function createSessionReclaim(params) {
35
39
  ? toBase64Url(crypto.getRandomValues(new Uint8Array(16)))
36
40
  : null;
37
41
  const localCommitPromise = localSecret
38
- ? sha256Base64Url(`meshpost/1/reclaim:${self}:${localSecret}`)
42
+ ? computeReclaimCommit(self, localSecret)
39
43
  : Promise.resolve(null);
40
44
  const hasWindowEvents = typeof window !== 'undefined' &&
41
45
  typeof window.addEventListener === 'function' &&