freertc 0.1.32 → 0.5.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.
Files changed (60) hide show
  1. package/README.md +204 -12
  2. package/bin/freertc.mjs +38 -633
  3. package/migrations/0001_initial.sql +43 -0
  4. package/migrations/0002_kademlia_overlay.sql +32 -0
  5. package/migrations/0003_announcement_role.sql +4 -0
  6. package/package.json +44 -17
  7. package/public/app.js +746 -169
  8. package/public/icon-180.png +0 -0
  9. package/public/icon-192.png +0 -0
  10. package/public/index.html +200 -799
  11. package/public/pigeonlogo.svg +51 -0
  12. package/scripts/d1-schema.sql +36 -0
  13. package/scripts/deploy-cloudflare.mjs +190 -0
  14. package/scripts/dev-server.mjs +54 -7
  15. package/scripts/generate-relay-identity.mjs +14 -0
  16. package/scripts/name-setup.mjs +332 -0
  17. package/scripts/node-relay.mjs +1128 -0
  18. package/scripts/project-bootstrap.mjs +13 -6
  19. package/scripts/wrangler-install-wizard.mjs +21 -11
  20. package/src/client.js +3468 -0
  21. package/src/direct/cert.js +95 -0
  22. package/src/direct/common.js +187 -0
  23. package/src/direct/dial.js +47 -0
  24. package/src/direct/directory.js +230 -0
  25. package/src/direct/listener.js +201 -0
  26. package/src/direct/lookup.js +75 -0
  27. package/src/direct/names.js +150 -0
  28. package/src/direct/node-relay-direct.js +170 -0
  29. package/src/direct/portmap.js +214 -0
  30. package/src/direct/reachable.js +40 -0
  31. package/src/direct/record.js +188 -0
  32. package/src/index.js +1401 -199
  33. package/src/kademlia.js +133 -0
  34. package/src/node/account-sync.js +98 -0
  35. package/src/node/cost-meter.js +92 -0
  36. package/src/node/d1-sqlite.js +108 -0
  37. package/src/node/data-dir.js +66 -0
  38. package/src/node/durable-object.js +58 -0
  39. package/src/node/lan-beacon.js +55 -0
  40. package/src/node/link-crypto.js +99 -0
  41. package/src/node/relay-links.js +385 -0
  42. package/src/node/relay-name.js +193 -0
  43. package/src/node/relay-pq.js +68 -0
  44. package/src/node/relay-stats.js +276 -0
  45. package/src/node/stats-page.js +281 -0
  46. package/src/node/websocket-pair.js +117 -0
  47. package/src/punch/offer.js +143 -0
  48. package/src/punch/rendezvous.js +124 -0
  49. package/src/punch/transport.js +257 -0
  50. package/src/relay-fetch.js +131 -0
  51. package/src/relay-id.js +74 -0
  52. package/src/relay-identity.js +298 -0
  53. package/src/relay-overlay.js +857 -0
  54. package/src/tunnel/client.js +276 -0
  55. package/src/tunnel/frames.js +64 -0
  56. package/src/tunnel/home.js +271 -0
  57. package/wrangler.template.jsonc +34 -9
  58. package/wrangler.workers-dev.jsonc +20 -3
  59. package/scripts/non-cloudflare-server.mjs +0 -433
  60. package/scripts/postinstall-message.mjs +0 -133
package/src/client.js ADDED
@@ -0,0 +1,3468 @@
1
+ import { sha256 } from 'unsea'
2
+ import { directRelayLan, isDirectRelayUrl } from './direct/common.js'
3
+ import { directRelayChannel } from './direct/dial.js'
4
+ export { directRelayChannel }
5
+ export { isDirectRelayUrl, parseDirectRelayUrl, directoryRecordUrl, directRelayLan } from './direct/common.js'
6
+ export { lookupDirectRelays, DEFAULT_DIRECTORY_NAME } from './direct/lookup.js'
7
+ // Backoff config for reconnect
8
+ const BACKOFF_BASE_MS = 1000
9
+ const BACKOFF_MAX_MS = 30000
10
+ const BACKOFF_FACTOR = 1.5
11
+ const DATA_PING_MS = 1000
12
+ // Relayed links (see createSignalingClient): WebRTC failures before a pair
13
+ // links through the relay, how often its keepalive crosses the relay, and
14
+ // how its link request is repeated.
15
+ const RELAYED_LINK_AFTER_FAILURES = 2
16
+ const RELAYED_LINK_PING_MS = 5000
17
+ const RELAYED_LINK_ASK_MS = 3000
18
+ const RELAYED_LINK_ASKS = 4
19
+ const RELAYED_LINK_TTL_MS = 10000
20
+ // A WebRTC attempt closed after this long without opening counts as failed.
21
+ const RELAYED_LINK_STALL_MS = 8000
22
+ const RELAYED_LINK_OPEN = 'link-open'
23
+ const RELAYED_LINK_ACCEPT = 'link-accept'
24
+ const RELAYED_LINK_DATA = 'link-data'
25
+ const RELAYED_LINK_CLOSE = 'link-close'
26
+ // Twenty seconds, not four. A pong can sit behind the peer's own outbound
27
+ // burst — the GitPigeon index sync moves megabytes in both directions the
28
+ // moment two peers meet, and werift's SCTP is slow — and four seconds
29
+ // executed healthy channels on every connection. A dead channel is still
30
+ // caught; it merely takes twenty seconds instead of four.
31
+ const DATA_PONG_TIMEOUT_MS = 20000
32
+ // A ping is re-sent this often while it stays unanswered. One outstanding
33
+ // ping is the rule, but a single lost frame — the arming ping werift hands to
34
+ // a peer whose channel has not flipped to 'open' yet — must not be a death
35
+ // sentence twenty seconds later; the retry keeps the original clock.
36
+ const DATA_PING_RETRY_MS = 5000
37
+ // A send buffer that stops draining is a dead receiver, however the channel
38
+ // reports itself. Beyond this many queued bytes nothing more is handed to
39
+ // the transport: werift keeps every pending send subscribed to its SCTP
40
+ // flush event and re-subscribes each on every flush, so a few thousand
41
+ // sends stuck behind a peer whose window closed cost the whole process
42
+ // (the watcher sat at a full core doing nothing but that bookkeeping).
43
+ // One megabyte: the cost is per pending send, so the cap has to bound the
44
+ // count, and a few hundred pending frames is already visible in a profile.
45
+ const DATA_MAX_BUFFERED_BYTES = 1024 * 1024
46
+ // A backlog that has not shrunk for this long is stalled, not busy.
47
+ const DATA_BACKLOG_STALL_MS = 20000
48
+ // A pong is proof of a working outbound direction — but only a RECENT one.
49
+ // After a machine suspends and resumes, every frozen channel still holds its
50
+ // pre-suspend pong and every state field still claims health, so an
51
+ // expiry on the proof is what stops the resume-time send burst.
52
+ const DATA_PROOF_FRESH_MS = DATA_PING_MS + DATA_PONG_TIMEOUT_MS + 5000
53
+ // A link whose pings have gone unanswered this long, with nothing at all coming in, is suspect: no
54
+ // frame is sent on it (a refusal callers retry, not a verdict) until a pong comes back or the pong
55
+ // timeout executes it. Safari logs 'Error sending string through RTCDataChannel' for every send
56
+ // into a link that died without closing, and sending on for the whole 20 s filled the console.
57
+ const DATA_SUSPECT_MS = 4000
58
+ // SCTP max-message-size is negotiated and small in WebKit: Safari advertises
59
+ // 64 KiB where Chromium advertises 256 KiB, and a send over the remote's
60
+ // limit fails — in Safari silently, as an uncatchable console error, on a
61
+ // perfectly healthy channel. Gossip anti-entropy digests measured 205 KiB in
62
+ // production. Every string payload above the threshold therefore travels as
63
+ // ordered chunk frames and is reassembled on receive; 8 KiB raw slices keep
64
+ // each JSON-escaped frame safely under the proven 16 KiB interop ceiling.
65
+ const DATA_CHUNK_SLICE = 8192
66
+ const DATA_CHUNK_THRESHOLD = 15000
67
+ const DATA_CHUNK_FRAME = '~fc'
68
+ const DATA_CHUNK_MAX_FRAMES = 4096
69
+ const DATA_CHUNK_STALE_MS = 30000
70
+ // Bytes (an ArrayBuffer or a typed array) travel as binary frames: no base64, no JSON escaping, and
71
+ // 48 KiB a frame (under Safari's 64 KiB max-message-size) where a string goes 8 KiB a frame. A frame
72
+ // is a 12-byte header, then its slice of the bytes:
73
+ // 'p' 'b' 1 0 | transfer id (u32) | slice (u16) | slices (u16) (big-endian)
74
+ // and the receiver hands the whole bytes on as one Uint8Array. Callers send bytes only to a peer that
75
+ // said it reads them (PeerPigeon's storage servers and their clients ask first).
76
+ const DATA_BIN_SLICE = 48 * 1024
77
+ const DATA_BIN_HEADER = 12
78
+ const DATA_BIN_MAX_SLICES = 2048
79
+ // A hidden tab cannot answer pings promptly — Safari throttles its JS — so
80
+ // the 4s pong verdict executed every edge to a napping tab, and each thaw
81
+ // redialed and burst into the corpses. A tab that is about to nap says so;
82
+ // peers PARK that edge: no sends, no pings, no execution, until a wake frame
83
+ // or any traffic revives it. A park older than the cap falls back to normal
84
+ // verdicts so a tab that never returns still gets cleaned up.
85
+ const DATA_DORMANT_FRAME = '~dormant'
86
+ const DATA_DORMANT_MAX_MS = 30 * 60000
87
+ // Relay on demand. A peer with a healthy mesh does not need a relay socket: the relay is for
88
+ // meeting the mesh, and once met, negotiation and liveness travel over the data channels. A few
89
+ // peers per room, the anchors, stay registered so a newcomer still finds a way in; the rest
90
+ // release their socket and wake it only when they need it. Anchors are the peers whose id is
91
+ // closest to the room key, and neighbours tell each other which ids they can vouch for with this
92
+ // frame. Opt-in: see the `relay` option.
93
+ const RELAY_ANCHOR_FRAME = '~anchors'
94
+ const RELAY_DEFAULTS = {
95
+ // Live data-channel neighbours needed before the relay socket can be released.
96
+ // One is the honest threshold: a peer that can reach a neighbour over a data
97
+ // channel is not cut off from the mesh, and the pair below still keeps an
98
+ // anchor registered so a newcomer has a way in.
99
+ minMeshPeers: 1,
100
+ // Peers per room that stay registered with the relay. A room needs one way
101
+ // in, not three: at three, every peer in a room of three or fewer is an
102
+ // anchor, so no peer ever released its socket and this whole feature did
103
+ // nothing in the small rooms that need it most. One anchor dropping leaves
104
+ // the rest isolated, which wakes their relay within evalMs.
105
+ anchors: 1,
106
+ // How long a peer must have been releasable before it lets go, so a flap does not flap the relay.
107
+ settleMs: 30_000,
108
+ // How long the relay stays up once something woke it.
109
+ lingerMs: 60_000,
110
+ // How often the peer re-evaluates whether it needs the relay.
111
+ evalMs: 5_000,
112
+ // How long a neighbour's word that a peer is closest to the room is believed.
113
+ gossipTtlMs: 20_000,
114
+ }
115
+ // A send into a transport that is not positively connected does not throw in
116
+ // WebKit — it logs an uncatchable 'Error sending string through
117
+ // RTCDataChannel' console error per attempt. EVERY channel send must pass
118
+ // this gate; the transient state either recovers (sends resume) or the
119
+ // stalled-negotiation machinery executes the peer.
120
+ const transportReady = (pc) => pc?.connectionState === undefined || pc.connectionState === 'connected'
121
+ let dataChunkCounter = 0
122
+ let dataBinCounter = 0
123
+ // A relay socket is a Durable Object, and every message a peer sends up it is
124
+ // a billable request. At one ping a second that is 86,400 requests a day per
125
+ // socket to say nothing at all — measured on an idle node, 62% of everything
126
+ // it sent, and by itself more than a Cloudflare free tier allows in a day. A
127
+ // watcher runs several nodes, so one quiet machine spent the daily allowance
128
+ // in about three hours and then the whole fleet stopped.
129
+ //
130
+ // Twenty-five seconds still notices a dead relay inside a minute and a half,
131
+ // which nothing here waits on: a peer's liveness to its fleet is the index
132
+ // heartbeat it publishes, not this socket.
133
+ const SIGNAL_PING_MS = 25000
134
+ // Comfortably more than the ping interval, so one lost pong is not a dead
135
+ // relay. A watcher pushing a multi-megabyte index sync over werift stalls its
136
+ // own event loop for seconds at a time; a tight deadline read that as a dead
137
+ // relay, dropped the socket, re-registered, and released every peer in the
138
+ // process.
139
+ const SIGNAL_PONG_TIMEOUT_MS = 60000
140
+ // A machine that sleeps freezes this process with it. Browsers announce the
141
+ // thaw (pageshow, resume); a Node peer — the GitPigeon watcher — has no such
142
+ // event and used to trust a signaling socket and ICE candidates that died
143
+ // during the freeze until every timeout ground through: 46 seconds to get a
144
+ // link back after waking, both sides stalling dials the whole time. The
145
+ // clock is the tell: a one-second tick that fires many seconds late is a
146
+ // suspend, and thawing runs the very same path a browser's resume does.
147
+ // Node only, and a long gap: browsers have real lifecycle events, and a busy
148
+ // Node event loop (a watcher hashing a publish) can legitimately pause for
149
+ // seconds — that must never read as a suspend, which tears every link down.
150
+ const SUSPEND_TICK_MS = 1000
151
+ const SUSPEND_GAP_MS = 20000
152
+ // A gap this long is a real sleep: everything is reset. A shorter one may be a
153
+ // busy machine, and is checked instead (see handleSuspendRestore).
154
+ const SLEEP_GAP_MS = 60000
155
+ // A relay-backed offer normally reaches the destination on its next one-second
156
+ // signaling heartbeat. Five total sends over 2.85s cover that delivery window
157
+ // without pinning an isolated peer to one unreachable candidate for 31.85s.
158
+ // Under two seconds used to be the whole budget for an answer. A watcher
159
+ // that has just restarted, or is publishing a bundle, answers late — its
160
+ // answers arrived after the dial had given up, were queued for a connection
161
+ // that no longer existed, and the pair redialed. Sixteen seconds covers it.
162
+ const OFFER_RETRY_DELAYS_MS = [100, 250, 500, 1000, 2000, 4000, 8000]
163
+ // A negotiation frame is perishable. An offer is retried within two seconds
164
+ // and its negotiation given up within ten; delivered later, from the relay's
165
+ // offline queue, it is a dead offer the receiver answers into nothing — and a
166
+ // tab waking from a long sleep, or re-registering after a resume, received a
167
+ // backlog of exactly those and stalled on each before it could dial. Ten
168
+ // seconds covers the retry burst and a live handshake; the relay drops the
169
+ // rest unread.
170
+ const NEGOTIATION_TTL_MS = 10000
171
+ // The relay forgets an announcement once its TTL lapses, so this heartbeat only
172
+ // has to outpace the TTL — and every beat is a billable request against the
173
+ // relay. So it asks for the longest TTL the relay will honour (both the Worker
174
+ // and the self-hosted relay cap at 120s) and refreshes at a third of it, which
175
+ // leaves room for two lost beats before the peer disappears from the registry.
176
+ const ADVERTISE_TTL_MS = 120000
177
+ const ADVERTISE_HEARTBEAT_MS = ADVERTISE_TTL_MS / 3
178
+ const NEGOTIATION_TYPES = new Set(['offer', 'answer', 'ice_candidate', 'ice_end', 'renegotiate'])
179
+ // Frames addressed to one peer that can travel over an established mesh
180
+ // instead of the relay: everything a negotiation needs, plus the goodbye.
181
+ const MESH_SIGNAL_TYPES = new Set(['offer', 'answer', 'ice_candidate', 'ice_end', 'renegotiate', 'bye'])
182
+ // Sent on a data channel just before this side closes it, so the other side
183
+ // closes its end at once instead of sending into a dead edge.
184
+ const DATA_BYE_FRAME = 'freertc-bye'
185
+ // PSP Revision 3 (19.7) names the link bye `~bye`; both are accepted.
186
+ const DATA_BYE_FRAMES = new Set([DATA_BYE_FRAME, '~bye'])
187
+ // How long a closing channel stays open so its bye frame is flushed first.
188
+ const DATA_BYE_FLUSH_MS = 250
189
+ const ANSWER_BURST_COOLDOWN_MS = 3000
190
+ const ANSWER_BURST_DELAYS_MS = [200, 800, 2000]
191
+ const SDP_DEDUP_WINDOW_MS = 15000
192
+ // The ICE ufrag identifies one negotiation across every retry of its offer.
193
+ const iceUfragOf = (sdp) => /a=ice-ufrag:(\S+)/.exec(String(sdp ?? ''))?.[1] ?? null
194
+ const candidateLinesOf = (sdp) => String(sdp ?? '').split(/\r?\n/).filter((line) => /^a=candidate:/.test(line))
195
+
196
+ /**
197
+ * Remove a previously owned signaling identity without announcing it again.
198
+ * This is intended for reload recovery when the departing document's unload
199
+ * handlers did not get enough time to send their normal withdrawal.
200
+ */
201
+ export function withdrawSignalingIdentity(options = {}) {
202
+ const {
203
+ peerId,
204
+ networkId,
205
+ roomId: configuredRoomId,
206
+ sessionId: legacyRoomId,
207
+ signalUrl,
208
+ reason = 'previous_identity_cleanup',
209
+ } = options
210
+ const roomId = configuredRoomId || legacyRoomId || networkId
211
+
212
+ if (!peerId || !networkId || !roomId || !signalUrl) {
213
+ throw new Error('peerId, networkId, roomId, and signalUrl are required')
214
+ }
215
+
216
+ let socket = null
217
+ let timeoutTimer = null
218
+ let finished = false
219
+
220
+ const finish = () => {
221
+ if (finished) return
222
+ finished = true
223
+ clearTimeout(timeoutTimer)
224
+ timeoutTimer = null
225
+ if (!socket) return
226
+ socket.onopen = null
227
+ socket.onmessage = null
228
+ socket.onerror = null
229
+ socket.onclose = null
230
+ try {
231
+ if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {
232
+ socket.close(1000, 'identity_withdrawn')
233
+ }
234
+ } catch { /* best effort */ }
235
+ }
236
+
237
+ try {
238
+ const wsUrl = new URL(signalUrl, typeof location !== 'undefined' ? location.href : undefined)
239
+ if (!wsUrl.searchParams.get('networkId')) wsUrl.searchParams.set('networkId', networkId)
240
+ if (!wsUrl.searchParams.get('room')) wsUrl.searchParams.set('room', roomId)
241
+
242
+ socket = isDirectRelayUrl(String(signalUrl).split('?')[0])
243
+ ? openRelaySocket(wsUrl.toString(), { punch: false })
244
+ : new WebSocket(wsUrl.toString())
245
+ socket.onopen = () => {
246
+ try {
247
+ const bytes = new Uint8Array(8)
248
+ const webCrypto = globalThis.window?.crypto ?? globalThis.crypto
249
+ webCrypto.getRandomValues(bytes)
250
+ socket.send(JSON.stringify({
251
+ psp_version: '1.0',
252
+ type: 'withdraw',
253
+ network: networkId,
254
+ from: peerId,
255
+ to: null,
256
+ session_id: roomId,
257
+ message_id: Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''),
258
+ timestamp: Date.now(),
259
+ ttl_ms: null,
260
+ reply_to: null,
261
+ body: { reason },
262
+ }))
263
+ } catch { /* best effort */ }
264
+ finish()
265
+ }
266
+ socket.onerror = finish
267
+ socket.onclose = finish
268
+ timeoutTimer = setTimeout(finish, 5000)
269
+ } catch {
270
+ finish()
271
+ }
272
+
273
+ return { close: finish }
274
+ }
275
+
276
+ const DEFAULT_ICE_SERVERS = [
277
+ { urls: 'stun:stun.l.google.com:19302' },
278
+ { urls: 'stun:stun1.l.google.com:19302' },
279
+ { urls: 'stun:stun2.l.google.com:19302' },
280
+ { urls: 'stun:stun3.l.google.com:19302' },
281
+ { urls: 'stun:stun4.l.google.com:19302' },
282
+ { urls: 'stun:global.stun.twilio.com:3478' },
283
+ { urls: 'stun:stun.cloudflare.com:3478' },
284
+ { urls: 'stun:stun.nextcloud.com:443' },
285
+ ]
286
+
287
+ // ── Punched relay sockets ───────────────────────────────────────────────────
288
+ // A relay behind NAT is reached at wss://<home>/t/<node id>/ws, through its
289
+ // tunnel home. Every frame over that socket is a request the home pays for. So
290
+ // when the client has WebRTC, it first asks the relay, through the tunnel, for
291
+ // a direct data channel: one POST of a complete offer to
292
+ // https://<home>/t/<node id>/api/v1/punch/offer, one answer back, and the relay
293
+ // protocol runs over the channel with the home out of the loop. If the punch
294
+ // does not open (no WebRTC there, a NAT that will not punch), the client uses
295
+ // the tunnel socket instead and does not try that relay again for a while.
296
+ const PUNCH_OFFER_TIMEOUT_MS = 12_000
297
+ const PUNCH_GATHER_TIMEOUT_MS = 3_000
298
+ const PUNCH_RETRY_AFTER_MS = 10 * 60_000
299
+ const PUNCH_CHANNEL_LABEL = 'freertc-relay'
300
+ const punchFailures = new Map()
301
+ const SOCKET_CONNECTING = 0
302
+ const SOCKET_OPEN = 1
303
+ const SOCKET_CLOSED = 3
304
+
305
+ /** wss://<home>/t/<node id>/ws → https://<home>/t/<node id>/api/v1/punch/offer, else null. */
306
+ export function punchOfferUrlForRelay(relayUrl) {
307
+ try {
308
+ const url = new URL(relayUrl)
309
+ if (!/^\/t\/[0-9a-f]{64}\/ws$/.test(url.pathname)) return null
310
+ url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
311
+ url.pathname = url.pathname.replace(/\/ws$/, '/api/v1/punch/offer')
312
+ url.search = ''
313
+ url.hash = ''
314
+ return url.toString()
315
+ } catch {
316
+ return null
317
+ }
318
+ }
319
+
320
+ function waitForIceGathering(pc, timeoutMs) {
321
+ if (pc.iceGatheringState === 'complete') return Promise.resolve()
322
+ return new Promise((resolve) => {
323
+ const timer = setTimeout(resolve, timeoutMs)
324
+ const done = () => { clearTimeout(timer); resolve() }
325
+ pc.onicecandidate = (event) => { if (!event?.candidate) done() }
326
+ pc.onicegatheringstatechange = () => { if (pc.iceGatheringState === 'complete') done() }
327
+ })
328
+ }
329
+
330
+ /** Open a data channel to a relay through its punch endpoint. Resolves { pc, channel }. A relay also uses it to link to another relay (label freertc-federation). */
331
+ export async function punchRelayChannel(offerUrl, { PeerConnection, iceServers, fetchImpl, timeoutMs = PUNCH_OFFER_TIMEOUT_MS, label = PUNCH_CHANNEL_LABEL }) {
332
+ const pc = new PeerConnection({ iceServers })
333
+ const channel = pc.createDataChannel(label)
334
+ let openTimer = null
335
+ try {
336
+ const opened = new Promise((resolve, reject) => {
337
+ openTimer = setTimeout(() => reject(new Error('punched channel did not open')), timeoutMs)
338
+ channel.onopen = () => { clearTimeout(openTimer); resolve() }
339
+ })
340
+ // An offer the relay refuses ends this attempt before the channel could
341
+ // open; that later timeout must not surface as an unhandled rejection.
342
+ opened.catch(() => {})
343
+ const gathered = waitForIceGathering(pc, PUNCH_GATHER_TIMEOUT_MS)
344
+ await pc.setLocalDescription(await pc.createOffer())
345
+ await gathered
346
+ // text/plain keeps this a simple request: no CORS preflight, so the home
347
+ // sees exactly one request per introduction.
348
+ const response = await fetchImpl(offerUrl, {
349
+ method: 'POST',
350
+ headers: { 'Content-Type': 'text/plain' },
351
+ body: JSON.stringify({ sdp: pc.localDescription.sdp }),
352
+ })
353
+ const body = await response.json().catch(() => null)
354
+ if (!response.ok || !body?.ok || typeof body.sdp !== 'string') {
355
+ throw new Error(body?.error || `punch offer answered ${response.status}`)
356
+ }
357
+ await pc.setRemoteDescription({ type: 'answer', sdp: body.sdp })
358
+ await opened
359
+ return { pc, channel }
360
+ } catch (error) {
361
+ clearTimeout(openTimer)
362
+ try { channel.close() } catch {}
363
+ try { pc.close() } catch {}
364
+ throw error
365
+ }
366
+ }
367
+
368
+ /**
369
+ * A socket to the relay at relayUrl with the WebSocket surface the client uses
370
+ * (readyState, send, close, onopen/onmessage/onclose/onerror): a punched data
371
+ * channel when the relay is behind NAT and WebRTC is here, else a WebSocket.
372
+ */
373
+ // Direct relays (src/direct): a relay with a public address that browsers reach
374
+ // with a WebRTC data channel and no signaling. URL:
375
+ // webrtc-direct://<ip>:<port>/sha256/<fingerprint>[?tunnel=<its tunnel URL>]
376
+ // A failed direct attempt falls back to the tunnel when the URL names one, and
377
+ // that relay is not tried directly again for a while.
378
+ /** A relay on this machine, this network, or a home relay at its bare public address or direct URL. */
379
+ export function isLocalRelayUrl(url) {
380
+ const text = String(url || '')
381
+ if (isDirectRelayUrl(text.split('?')[0])) return true
382
+ try {
383
+ const host = new URL(text).hostname.replace(/^\[|\]$/g, '').toLowerCase()
384
+ return host === 'localhost' || host.endsWith('.local') || host === '::1'
385
+ || /^\d{1,3}(\.\d{1,3}){3}$/.test(host) || host.includes(':')
386
+ } catch {
387
+ return false
388
+ }
389
+ }
390
+
391
+ // How long a relay connection may take to open before a recovery may cancel it.
392
+ const SOCKET_OPEN_DEADLINE_MS = 45_000
393
+ const directFailures = new Map()
394
+ // How long a direct relay connection may stay 'disconnected' before it counts as gone.
395
+ const DIRECT_DISCONNECTED_GRACE_MS = 5_000
396
+
397
+ function openDirectRelaySocket(relayUrl, { WebSocketImpl, PeerConnection, log }) {
398
+ const [directUrl, query = ''] = String(relayUrl).split('?')
399
+ const tunnelUrl = new URLSearchParams(query).get('tunnel')
400
+ const failedAt = directFailures.get(directUrl)
401
+ if (tunnelUrl && (typeof PeerConnection !== 'function' || (failedAt && Date.now() - failedAt < PUNCH_RETRY_AFTER_MS))) {
402
+ return new WebSocketImpl(tunnelUrl)
403
+ }
404
+
405
+ const socket = {
406
+ readyState: SOCKET_CONNECTING,
407
+ transport: 'direct',
408
+ onopen: null,
409
+ onmessage: null,
410
+ onclose: null,
411
+ onerror: null,
412
+ send(data) {
413
+ if (inner) return inner.send(data)
414
+ if (socket.readyState !== SOCKET_OPEN || !channel) throw new Error('relay socket is not open')
415
+ channel.send(typeof data === 'string' ? data : String(data))
416
+ },
417
+ close(code = 1000, reason = '') {
418
+ if (inner) return inner.close(code, reason)
419
+ if (socket.readyState === SOCKET_CLOSED) return
420
+ closedByUser = true
421
+ finish(code, reason)
422
+ },
423
+ }
424
+ let channel = null
425
+ let pc = null
426
+ let inner = null
427
+ let closedByUser = false
428
+ const finish = (code = 1006, reason = '') => {
429
+ if (socket.readyState === SOCKET_CLOSED) return
430
+ socket.readyState = SOCKET_CLOSED
431
+ try { channel?.close() } catch {}
432
+ try { pc?.close() } catch {}
433
+ socket.onclose?.({ code, reason, wasClean: code === 1000 })
434
+ }
435
+ const fallBack = (why) => {
436
+ if (closedByUser) return
437
+ directFailures.set(directUrl, Date.now())
438
+ if (!tunnelUrl) {
439
+ log(`[relay] no direct channel to ${directUrl} (${why})`)
440
+ finish(1006, `direct: ${why}`)
441
+ return
442
+ }
443
+ log(`[relay] no direct channel to ${directUrl} (${why}); using its tunnel`)
444
+ socket.transport = 'tunnel'
445
+ inner = new WebSocketImpl(tunnelUrl)
446
+ inner.onopen = (event) => { socket.readyState = inner.readyState; socket.onopen?.(event) }
447
+ inner.onmessage = (event) => socket.onmessage?.(event)
448
+ inner.onerror = (event) => socket.onerror?.(event)
449
+ inner.onclose = (event) => { socket.readyState = SOCKET_CLOSED; socket.onclose?.(event) }
450
+ }
451
+
452
+ directRelayChannel(directUrl, { PeerConnection, lan: directRelayLan(relayUrl) })
453
+ .then((opened) => {
454
+ if (closedByUser) { try { opened.channel.close() } catch {} try { opened.pc.close() } catch {} return }
455
+ ;({ pc, channel } = opened)
456
+ directFailures.delete(directUrl)
457
+ log(`[relay] direct channel to ${directUrl}`)
458
+ channel.onmessage = (event) => socket.onmessage?.({ data: typeof event.data === 'string' ? event.data : String(event.data) })
459
+ channel.onclose = () => finish(1006, 'direct channel closed')
460
+ channel.onerror = (event) => socket.onerror?.(event)
461
+ // 'disconnected' that lasts is a relay that is gone (stopped, asleep,
462
+ // off the network). A background tab sends no keepalive, so this is
463
+ // the only sign it gets; waiting for 'failed' could take minutes.
464
+ let disconnectedTimer = null
465
+ pc.onconnectionstatechange = () => {
466
+ const state = pc.connectionState
467
+ if (state === 'failed' || state === 'closed') finish(1006, `connection ${state}`)
468
+ else if (state === 'disconnected') {
469
+ clearTimeout(disconnectedTimer)
470
+ disconnectedTimer = setTimeout(() => { if (pc.connectionState === 'disconnected') finish(1006, 'connection disconnected') }, DIRECT_DISCONNECTED_GRACE_MS)
471
+ } else clearTimeout(disconnectedTimer)
472
+ }
473
+ socket.readyState = SOCKET_OPEN
474
+ socket.onopen?.({})
475
+ })
476
+ .catch((error) => fallBack(error?.message ?? String(error)))
477
+
478
+ return socket
479
+ }
480
+
481
+ export function openRelaySocket(relayUrl, {
482
+ punch = true,
483
+ WebSocketImpl = globalThis.WebSocket,
484
+ PeerConnection = globalThis.RTCPeerConnection,
485
+ iceServers = [],
486
+ fetchImpl = globalThis.fetch,
487
+ log = () => {},
488
+ } = {}) {
489
+ if (isDirectRelayUrl(String(relayUrl).split('?')[0])) {
490
+ return openDirectRelaySocket(relayUrl, { WebSocketImpl, PeerConnection, log })
491
+ }
492
+ const offerUrl = punch && typeof PeerConnection === 'function' && typeof fetchImpl === 'function'
493
+ ? punchOfferUrlForRelay(relayUrl)
494
+ : null
495
+ const failedAt = offerUrl ? punchFailures.get(offerUrl) : null
496
+ if (!offerUrl || (failedAt && Date.now() - failedAt < PUNCH_RETRY_AFTER_MS)) {
497
+ return new WebSocketImpl(relayUrl)
498
+ }
499
+
500
+ const socket = {
501
+ readyState: SOCKET_CONNECTING,
502
+ transport: 'punch',
503
+ onopen: null,
504
+ onmessage: null,
505
+ onclose: null,
506
+ onerror: null,
507
+ send(data) {
508
+ if (inner) return inner.send(data)
509
+ if (socket.readyState !== SOCKET_OPEN || !channel) throw new Error('relay socket is not open')
510
+ channel.send(typeof data === 'string' ? data : String(data))
511
+ },
512
+ close(code = 1000, reason = '') {
513
+ if (inner) return inner.close(code, reason)
514
+ if (socket.readyState === SOCKET_CLOSED) return
515
+ closedByUser = true
516
+ finish(code, reason)
517
+ },
518
+ }
519
+ let channel = null
520
+ let pc = null
521
+ let inner = null
522
+ let closedByUser = false
523
+ const finish = (code = 1006, reason = '') => {
524
+ if (socket.readyState === SOCKET_CLOSED) return
525
+ socket.readyState = SOCKET_CLOSED
526
+ try { channel?.close() } catch {}
527
+ try { pc?.close() } catch {}
528
+ socket.onclose?.({ code, reason, wasClean: code === 1000 })
529
+ }
530
+ const fallBack = (why) => {
531
+ if (closedByUser) return
532
+ punchFailures.set(offerUrl, Date.now())
533
+ log(`[relay] no punched channel to ${relayUrl} (${why}); using the tunnel`)
534
+ socket.transport = 'tunnel'
535
+ inner = new WebSocketImpl(relayUrl)
536
+ inner.onopen = (event) => { socket.readyState = inner.readyState; socket.onopen?.(event) }
537
+ inner.onmessage = (event) => socket.onmessage?.(event)
538
+ inner.onerror = (event) => socket.onerror?.(event)
539
+ inner.onclose = (event) => { socket.readyState = SOCKET_CLOSED; socket.onclose?.(event) }
540
+ }
541
+
542
+ punchRelayChannel(offerUrl, { PeerConnection, iceServers, fetchImpl })
543
+ .then((opened) => {
544
+ if (closedByUser) { try { opened.channel.close() } catch {} try { opened.pc.close() } catch {} return }
545
+ ;({ pc, channel } = opened)
546
+ punchFailures.delete(offerUrl)
547
+ log(`[relay] punched a direct channel to ${relayUrl}`)
548
+ channel.onmessage = (event) => socket.onmessage?.({ data: typeof event.data === 'string' ? event.data : String(event.data) })
549
+ channel.onclose = () => finish(1006, 'punched channel closed')
550
+ channel.onerror = (event) => socket.onerror?.(event)
551
+ const watch = () => { if (['failed', 'closed'].includes(pc.connectionState)) finish(1006, `connection ${pc.connectionState}`) }
552
+ pc.onconnectionstatechange = watch
553
+ socket.readyState = SOCKET_OPEN
554
+ socket.onopen?.({})
555
+ })
556
+ .catch((error) => fallBack(error?.message ?? String(error)))
557
+
558
+ return socket
559
+ }
560
+
561
+ export function createSignalingClient(options = {}) {
562
+ const {
563
+ peerId: initialPeerId,
564
+ networkId,
565
+ roomId: configuredRoomId,
566
+ sessionId: legacyRoomId,
567
+ signalUrl: initialSignalUrl,
568
+ iceServers: configuredIceServers,
569
+ // Reach a relay behind NAT over a punched data channel instead of its
570
+ // tunnel home (see openRelaySocket). On by default where WebRTC exists.
571
+ relayPunch = true,
572
+ trickleIce = true,
573
+ capabilities = {},
574
+ auth,
575
+ autoConnect = true,
576
+ onLog,
577
+ onResume,
578
+ onRegistered,
579
+ onBootstrap,
580
+ onIncomingRelay,
581
+ onNegotiationFailure,
582
+ // A relay said no relay has this peer: ({ peerId }). The peer has left.
583
+ onPeerGone,
584
+ onConnectionStateChange,
585
+ onStatusChange,
586
+ onDataMessage,
587
+ // Optional first-choice path for addressed signaling frames. Called with
588
+ // the complete PSP envelope; returning true means the mesh took it and
589
+ // the relay is not used for that frame. Anything else falls back to the
590
+ // relay socket exactly as before.
591
+ signalTransport = null,
592
+ // Relay on demand (opt-in). { mode: 'on-demand', minMeshPeers, anchors, settleMs, lingerMs,
593
+ // evalMs, gossipTtlMs, hold }. Takes effect only when the host also supplies signalTransport,
594
+ // because a released relay is only safe when the host can carry signaling over the mesh.
595
+ // hold: () => boolean, asked at each evaluation; true keeps (or wakes) the relay socket. A host
596
+ // whose overlay is still missing a link it needs uses it to stay reachable until that forms.
597
+ relay: relayOptions = {},
598
+ // Called with { state: 'up' | 'idle' | 'waking', ts } as the relay socket is released and woken.
599
+ onRelayStateChange,
600
+ // Relays are for signaling only: by default ('never', or false) no peer
601
+ // data ever goes through one, and a pair that cannot reach each other over
602
+ // WebRTC simply does not link. Two peers that cannot (a router that does
603
+ // not loop UDP back, Safari offering only its public address, carrier
604
+ // NAT) may opt in to carrying their link through the relay instead:
605
+ // 'local' only while this peer is on a local relay, 'always' also on a
606
+ // cloud relay. A peer that has not opted in also refuses such a link.
607
+ relayedLinks: relayedLinksOption = 'never',
608
+ } = options
609
+
610
+ const roomId = configuredRoomId || legacyRoomId || networkId
611
+
612
+ // The relay this client signals through. switchRelay() moves it to another
613
+ // relay while every open peer channel stays up.
614
+ let signalUrl = initialSignalUrl
615
+ let socketOpenStartedAt = 0
616
+ // Relay connections in a row that closed before they ever opened.
617
+ let failedOpens = 0
618
+ let openedThisSocket = false
619
+ if (!initialPeerId || !networkId || !roomId || !signalUrl) {
620
+ throw new Error('peerId, networkId, roomId, and signalUrl are required')
621
+ }
622
+
623
+ const mesh = {
624
+ buckets: {},
625
+ connections: new Map(),
626
+ bootstrapCandidates: [],
627
+
628
+ addCandidate(candidate) {
629
+ const existing = mesh.bootstrapCandidates.findIndex((c) => c.peerId === candidate.peerId)
630
+ if (existing >= 0) {
631
+ mesh.bootstrapCandidates[existing] = { ...candidate, localSeenAt: Date.now() }
632
+ } else {
633
+ mesh.bootstrapCandidates.push({ ...candidate, localSeenAt: Date.now() })
634
+ }
635
+ },
636
+
637
+ getFreshCandidates(maxAgeMs = 10 * 60_000) {
638
+ const cutoff = Date.now() - maxAgeMs
639
+ return mesh.bootstrapCandidates.filter((c) => c.localSeenAt > cutoff)
640
+ },
641
+
642
+ markLive(peerId) {
643
+ const conn = mesh.connections.get(peerId)
644
+ if (conn) conn.lastSeen = Date.now()
645
+ },
646
+
647
+ markDead(peerId) {
648
+ const conn = mesh.connections.get(peerId)
649
+ if (conn) {
650
+ conn.state = 'dead'
651
+ }
652
+ },
653
+ }
654
+
655
+ // ── Signaling client state ────────────────────────────────────────────────
656
+ let ws = null
657
+ let peerId = initialPeerId
658
+ let registered = false
659
+ let backoffMs = BACKOFF_BASE_MS
660
+ let reconnectAttempts = 0
661
+ let reconnectTimer = null
662
+ let advertiseHeartbeatTimer = null
663
+ let keepaliveTimer = null
664
+ let suspendWatchTimer = null
665
+ let lastSuspendTick = 0
666
+ let lastTickHidden = false
667
+ let lastSignalPongAt = Date.now()
668
+ let lastSignalPingSentAt = 0
669
+ let intentionalClose = false
670
+ let stoppedByUser = false
671
+ let onConnectionStateChangeCb = onConnectionStateChange
672
+ let lastBootstrapCountLogged = null
673
+
674
+ // ── Relay on demand ───────────────────────────────────────────────────────
675
+ // Off unless the caller asks for it and can carry signaling over the mesh. Everything below
676
+ // is inert in 'always' mode, which is how the client has always behaved.
677
+ const relayMode = relayOptions?.mode === 'on-demand' && typeof signalTransport === 'function' ? 'on-demand' : 'always'
678
+ const relayHold = typeof relayOptions?.hold === 'function' ? relayOptions.hold : null
679
+ const relayConfig = { ...RELAY_DEFAULTS }
680
+ for (const [name, value] of Object.entries(relayOptions ?? {})) {
681
+ if (name in RELAY_DEFAULTS && Number.isFinite(value) && value >= 0) relayConfig[name] = value
682
+ }
683
+ // Zero anchors would leave a room with no way in, and zero neighbours would never be isolated.
684
+ relayConfig.anchors = Math.max(1, Math.floor(relayConfig.anchors))
685
+ relayConfig.minMeshPeers = Math.max(1, Math.floor(relayConfig.minMeshPeers))
686
+ let relayIdle = false
687
+ let relayWakeUntil = 0
688
+ let relayReleasableSince = 0
689
+ let relayWatchTimer = null
690
+ let relayEvaluating = false
691
+ let pendingBootstrapPeerIds = null
692
+ let lastAnchorBroadcast = { key: '', at: 0 }
693
+ const closenessKeys = new Map()
694
+
695
+ // ── Wake Lock ─────────────────────────────────────────────────────────────
696
+ // Acquired while we have active peer connections so the browser doesn't
697
+ // throttle timers or freeze the tab mid-session.
698
+ let _wakeLock = null
699
+
700
+ async function _acquireWakeLock() {
701
+ if (_wakeLock) return
702
+ if (typeof navigator === 'undefined' || !('wakeLock' in navigator)) return
703
+ try {
704
+ _wakeLock = await navigator.wakeLock.request('screen')
705
+ _wakeLock.addEventListener('release', () => {
706
+ _wakeLock = null
707
+ log('[wakelock] screen wake lock released')
708
+ })
709
+ log('[wakelock] screen wake lock acquired')
710
+ } catch {
711
+ // Permission denied or API unavailable — not fatal.
712
+ }
713
+ }
714
+
715
+ function _releaseWakeLock() {
716
+ if (!_wakeLock) return
717
+ try { _wakeLock.release() } catch { /* ignore */ }
718
+ _wakeLock = null
719
+ }
720
+
721
+ // Re-acquire the wake lock whenever the tab becomes visible again, since
722
+ // the browser automatically releases it on tab hide.
723
+ function _reacquireWakeLockIfNeeded() {
724
+ if (typeof document === 'undefined' || document.hidden) return
725
+ if (!stoppedByUser && registered) _acquireWakeLock()
726
+ }
727
+
728
+ // Pending ICE candidate queues — keyed by peerId.
729
+ const pendingCandidates = new Map()
730
+ // Serialize every remote SDP mutation per peer. Browsers may deliver an
731
+ // offer and one or more answers in the same task after a tab resumes; letting
732
+ // those setRemoteDescription calls overlap can leave the peer permanently in
733
+ // "apply in flight".
734
+ const offerProcessingQueues = new Map()
735
+ // Track scheduled answer retransmit bursts per remote peer.
736
+ const answerBurstTimers = new Map()
737
+ // Keep the newest answer if it arrives before local state is ready.
738
+ const pendingAnswers = new Map()
739
+ // Track recent offer/answer SDPs per peer to avoid duplicate processing storms.
740
+ const recentOfferSdp = new Map()
741
+ const recentAnswerSdp = new Map()
742
+ const preferredIceServers = Array.isArray(configuredIceServers) && configuredIceServers.length > 0
743
+ ? configuredIceServers
744
+ : DEFAULT_ICE_SERVERS
745
+
746
+ function resolveIceServers(overrideIceServers = null) {
747
+ return Array.isArray(overrideIceServers) && overrideIceServers.length > 0
748
+ ? overrideIceServers
749
+ : preferredIceServers
750
+ }
751
+
752
+ function notifyNegotiationFailure(details) {
753
+ try {
754
+ onNegotiationFailure?.({ ...details, ts: Date.now() })
755
+ } catch {}
756
+ }
757
+
758
+ // ── Relayed links ─────────────────────────────────────────────────────────
759
+ // Some pairs never connect over WebRTC without a TURN server: two Safari
760
+ // tabs behind a router that does not loop UDP back to itself (Safari offers
761
+ // only its public address), or a phone behind carrier NAT. After a pair has
762
+ // failed twice, the dialer asks for a relayed link instead: an object that
763
+ // looks like an open data channel to everything above it, whose frames
764
+ // travel as `ext` messages through the relay both peers are on. The relay
765
+ // already forwards these between its peers and to the relays it federates
766
+ // with, exactly as it forwards offers.
767
+ const linkFailures = new Map() // peer id -> failed WebRTC attempts in a row
768
+ const dialAttempts = new Map() // peer id -> when the open-pending WebRTC dial started
769
+ const relayedLinks = new Map() // peer id -> link
770
+ // Requests to the relay itself (relayRequest), by request id.
771
+ const relayRequests = new Map()
772
+
773
+ function relayedLinksAllowed() {
774
+ if (relayedLinksOption === false || relayedLinksOption === 'never') return false
775
+ if (relayedLinksOption === 'always') return true
776
+ return isLocalRelayUrl(signalUrl)
777
+ }
778
+
779
+ function noteLinkFailure(remotePeerId, why) {
780
+ const count = (linkFailures.get(remotePeerId) ?? 0) + 1
781
+ linkFailures.set(remotePeerId, count)
782
+ if (count === RELAYED_LINK_AFTER_FAILURES) {
783
+ log(`[webrtc] ${remotePeerId} failed to connect ${count} times (${why}); the next try goes through the relay`)
784
+ }
785
+ }
786
+
787
+ function wantsRelayedLink(remotePeerId) {
788
+ return (linkFailures.get(remotePeerId) ?? 0) >= RELAYED_LINK_AFTER_FAILURES && relayedLinksAllowed()
789
+ }
790
+
791
+ function sendLinkFrame(remotePeerId, body) {
792
+ if (!registered || !ws) return false
793
+ send(pspEnvelope('ext', { to: remotePeerId, ttl_ms: RELAYED_LINK_TTL_MS, body }))
794
+ return true
795
+ }
796
+
797
+ function createRelayedLink(remotePeerId) {
798
+ const listeners = { open: new Set(), close: new Set(), message: new Set(), error: new Set() }
799
+ let lastPingAt = 0
800
+ const emit = (type, extra = {}) => {
801
+ const event = { type, target: channel, ...extra }
802
+ try { channel[`on${type}`]?.(event) } catch (err) { log(`[relayed] ${type} handler failed: ${err}`) }
803
+ for (const listener of [...listeners[type]]) {
804
+ try { listener(event) } catch { /* a host listener must not break the link */ }
805
+ }
806
+ }
807
+ const channel = {
808
+ label: 'freertc-relayed',
809
+ relayed: true,
810
+ readyState: 'connecting',
811
+ bufferedAmount: 0,
812
+ onopen: null,
813
+ onclose: null,
814
+ onmessage: null,
815
+ onerror: null,
816
+ addEventListener(type, listener) { listeners[type]?.add(listener) },
817
+ removeEventListener(type, listener) { listeners[type]?.delete(listener) },
818
+ send(data) {
819
+ if (channel.readyState !== 'open') throw new Error('relayed link is not open')
820
+ if (typeof data !== 'string') throw new Error('relayed links carry text only')
821
+ // Keepalive pings cross the relay like everything else: one every few
822
+ // seconds proves the path as well as one a second does.
823
+ if (data.startsWith('{"type":"ping"')) {
824
+ const now = Date.now()
825
+ if (now - lastPingAt < RELAYED_LINK_PING_MS) return
826
+ lastPingAt = now
827
+ }
828
+ // Not registered (the relay socket is reconnecting): the frame is
829
+ // lost, as on a lossy channel; the keepalive judges the link.
830
+ sendLinkFrame(remotePeerId, { action: RELAYED_LINK_DATA, d: data })
831
+ },
832
+ close() {
833
+ if (channel.readyState === 'closed') return
834
+ const wasUp = channel.readyState === 'open' || channel.readyState === 'connecting'
835
+ channel.readyState = 'closed'
836
+ connection.connectionState = 'closed'
837
+ connection.iceConnectionState = 'closed'
838
+ clearTimeout(link.openTimer)
839
+ if (relayedLinks.get(remotePeerId) === link) relayedLinks.delete(remotePeerId)
840
+ if (wasUp && !link.closedByRemote) sendLinkFrame(remotePeerId, { action: RELAYED_LINK_CLOSE })
841
+ emit('close')
842
+ },
843
+ }
844
+ const connection = {
845
+ relayed: true,
846
+ connectionState: 'connected',
847
+ iceConnectionState: 'connected',
848
+ iceGatheringState: 'complete',
849
+ signalingState: 'stable',
850
+ localDescription: null,
851
+ remoteDescription: { type: 'answer', sdp: '' },
852
+ onconnectionstatechange: null,
853
+ oniceconnectionstatechange: null,
854
+ ondatachannel: null,
855
+ onicecandidate: null,
856
+ addEventListener() {},
857
+ removeEventListener() {},
858
+ addIceCandidate: async () => {},
859
+ getConfiguration: () => ({ iceServers: [] }),
860
+ getStats: async () => new Map(),
861
+ close() { channel.close() },
862
+ }
863
+ const link = {
864
+ channel,
865
+ connection,
866
+ openTimer: null,
867
+ closedByRemote: false,
868
+ open() {
869
+ if (channel.readyState !== 'connecting') return
870
+ clearTimeout(link.openTimer)
871
+ channel.readyState = 'open'
872
+ const entry = mesh.connections.get(remotePeerId)
873
+ if (entry?.connection === connection) {
874
+ entry.state = 'connected'
875
+ entry.lastSeen = Date.now()
876
+ }
877
+ log(`[relayed] link to ${remotePeerId} open through the relay`)
878
+ emit('open')
879
+ },
880
+ deliver(text) {
881
+ if (channel.readyState !== 'open') return
882
+ emit('message', { data: text })
883
+ },
884
+ }
885
+ return link
886
+ }
887
+
888
+ // Put a relayed link where a WebRTC connection would be, so everything that
889
+ // looks a peer up in mesh.connections finds it.
890
+ function installRelayedLink(remotePeerId) {
891
+ const prior = mesh.connections.get(remotePeerId)
892
+ if (prior && !prior.relayed) {
893
+ clearOfferRetryTimer(prior.connection)
894
+ try { prior.channel?.close?.() } catch {}
895
+ try { prior.connection?.close?.() } catch {}
896
+ }
897
+ relayedLinks.get(remotePeerId)?.channel.close()
898
+ const link = createRelayedLink(remotePeerId)
899
+ relayedLinks.set(remotePeerId, link)
900
+ mesh.connections.set(remotePeerId, {
901
+ connection: link.connection,
902
+ channel: null,
903
+ relayed: true,
904
+ state: 'connecting',
905
+ lastSeen: Date.now(),
906
+ createdAt: Date.now(),
907
+ iceServers: null,
908
+ })
909
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'connecting', ts: Date.now() })
910
+ attachDataChannelHandlers(link.channel, remotePeerId, link.connection)
911
+ return link
912
+ }
913
+
914
+ function openRelayedLink(remotePeerId) {
915
+ const link = installRelayedLink(remotePeerId)
916
+ log(`[relayed] asking ${remotePeerId} for a link through the relay`)
917
+ let asks = 0
918
+ const ask = () => {
919
+ if (link.channel.readyState !== 'connecting') return
920
+ if (asks >= RELAYED_LINK_ASKS) {
921
+ log(`[relayed] ${remotePeerId} did not answer the link request`)
922
+ link.channel.close()
923
+ if (mesh.connections.get(remotePeerId)?.connection === link.connection) {
924
+ mesh.markDead(remotePeerId)
925
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'failed', ts: Date.now() })
926
+ }
927
+ return
928
+ }
929
+ asks += 1
930
+ sendLinkFrame(remotePeerId, { action: RELAYED_LINK_OPEN })
931
+ link.openTimer = setTimeout(ask, RELAYED_LINK_ASK_MS)
932
+ }
933
+ ask()
934
+ return link.connection
935
+ }
936
+
937
+ function handleLinkFrame(msg) {
938
+ const from = msg.from
939
+ const action = msg.body?.action
940
+ if (!from || from === peerId) return
941
+ if (msg.session_id && msg.session_id !== roomId) return
942
+ const link = relayedLinks.get(from)
943
+ const entry = mesh.connections.get(from)
944
+ switch (action) {
945
+ case RELAYED_LINK_DATA:
946
+ if (link && entry?.connection === link.connection && typeof msg.body.d === 'string') {
947
+ // Data before the acceptance: the acceptance was lost or overtaken.
948
+ if (link.channel.readyState === 'connecting') link.open()
949
+ link.deliver(msg.body.d)
950
+ }
951
+ break
952
+ case RELAYED_LINK_OPEN: {
953
+ // Not opted in: no data through the relay; the request goes unanswered.
954
+ if (!relayedLinksAllowed()) break
955
+ // A working WebRTC link wins; the asker learns so when the link
956
+ // request goes unanswered and keeps what it has.
957
+ if (entry && !entry.relayed && entry.channel?.readyState === 'open') break
958
+ if (link && entry?.connection === link.connection && link.channel.readyState === 'open') {
959
+ sendLinkFrame(from, { action: RELAYED_LINK_ACCEPT })
960
+ break
961
+ }
962
+ const accepted = installRelayedLink(from)
963
+ sendLinkFrame(from, { action: RELAYED_LINK_ACCEPT })
964
+ accepted.open()
965
+ break
966
+ }
967
+ case RELAYED_LINK_ACCEPT:
968
+ if (link && entry?.connection === link.connection) link.open()
969
+ break
970
+ case RELAYED_LINK_CLOSE:
971
+ if (link) {
972
+ link.closedByRemote = true
973
+ link.channel.close()
974
+ }
975
+ break
976
+ }
977
+ }
978
+
979
+ function enqueuePeerNegotiation(remotePeerId, operation) {
980
+ const previous = offerProcessingQueues.get(remotePeerId) ?? Promise.resolve()
981
+ const queued = previous
982
+ .catch(() => {})
983
+ .then(operation)
984
+ offerProcessingQueues.set(remotePeerId, queued)
985
+ queued.finally(() => {
986
+ if (offerProcessingQueues.get(remotePeerId) === queued) {
987
+ offerProcessingQueues.delete(remotePeerId)
988
+ }
989
+ }).catch(() => {})
990
+ return queued
991
+ }
992
+
993
+ function clearOfferRetryTimer(pc) {
994
+ if (!pc) return
995
+ if (pc.__offerRetryTimer) {
996
+ clearTimeout(pc.__offerRetryTimer)
997
+ pc.__offerRetryTimer = null
998
+ }
999
+ }
1000
+
1001
+ function getOrCreateSessionId() {
1002
+ return roomId
1003
+ }
1004
+
1005
+ function setSessionId(_remotePeerId, sessionId) {
1006
+ return sessionId === roomId
1007
+ }
1008
+
1009
+ function rotateSessionId() {
1010
+ return roomId
1011
+ }
1012
+
1013
+ function clearAnswerBurst(remotePeerId) {
1014
+ const timers = answerBurstTimers.get(remotePeerId)
1015
+ if (!timers) return
1016
+ for (const timerId of timers) {
1017
+ clearTimeout(timerId)
1018
+ }
1019
+ answerBurstTimers.delete(remotePeerId)
1020
+ }
1021
+
1022
+ function startAnswerBurst(remotePeerId, pc, sendRelay, answer, force = false) {
1023
+ const entry = mesh.connections.get(remotePeerId)
1024
+ if (!entry) return
1025
+
1026
+ const now = Date.now()
1027
+ if (!force && now - (entry.lastAnswerBurstAt ?? 0) < ANSWER_BURST_COOLDOWN_MS) {
1028
+ return
1029
+ }
1030
+
1031
+ entry.lastAnswerBurstAt = now
1032
+ clearAnswerBurst(remotePeerId)
1033
+
1034
+ if (
1035
+ pc.signalingState === 'closed' ||
1036
+ pc.connectionState === 'connected' ||
1037
+ pc.connectionState === 'closed'
1038
+ ) {
1039
+ return
1040
+ }
1041
+
1042
+ entry.lastAnswerSentAt = Date.now()
1043
+ sendRelay('answer', answer)
1044
+
1045
+ const scheduled = []
1046
+ for (const delayMs of ANSWER_BURST_DELAYS_MS) {
1047
+ const timerId = setTimeout(() => {
1048
+ const current = mesh.connections.get(remotePeerId)
1049
+ if (!current || current.connection !== pc) return
1050
+ if (
1051
+ pc.signalingState === 'closed' ||
1052
+ pc.connectionState === 'connected' ||
1053
+ pc.connectionState === 'closed'
1054
+ ) {
1055
+ return
1056
+ }
1057
+ current.lastAnswerSentAt = Date.now()
1058
+ sendRelay('answer', answer)
1059
+ }, delayMs)
1060
+ scheduled.push(timerId)
1061
+ }
1062
+
1063
+ answerBurstTimers.set(remotePeerId, scheduled)
1064
+ }
1065
+
1066
+ function log(msg) {
1067
+ onLog?.(msg)
1068
+ }
1069
+
1070
+ function setStatus(status) {
1071
+ onStatusChange?.(status)
1072
+ log(`[signal] status: ${status}`)
1073
+ }
1074
+
1075
+ function send(obj) {
1076
+ if (ws && ws.readyState === WebSocket.OPEN) {
1077
+ ws.send(JSON.stringify(obj))
1078
+ }
1079
+ }
1080
+
1081
+ function generateMessageId() {
1082
+ const bytes = new Uint8Array(8)
1083
+ const webCrypto = globalThis.window?.crypto ?? globalThis.crypto
1084
+ webCrypto.getRandomValues(bytes)
1085
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
1086
+ }
1087
+
1088
+ async function waitForIceGatheringComplete(pc, timeoutMs = 4000) {
1089
+ if (!pc || pc.iceGatheringState === 'complete') return
1090
+ await new Promise((resolve) => {
1091
+ let settled = false
1092
+ const done = () => {
1093
+ if (settled) return
1094
+ settled = true
1095
+ clearTimeout(timer)
1096
+ try { pc.removeEventListener('icegatheringstatechange', onChange) } catch {}
1097
+ resolve()
1098
+ }
1099
+ const onChange = () => {
1100
+ if (pc.iceGatheringState === 'complete') done()
1101
+ }
1102
+ const timer = setTimeout(done, timeoutMs)
1103
+ try { pc.addEventListener('icegatheringstatechange', onChange) } catch { done() }
1104
+ onChange()
1105
+ })
1106
+ }
1107
+
1108
+ function pspEnvelope(type, opts = {}) {
1109
+ return {
1110
+ psp_version: '1.0',
1111
+ type,
1112
+ network: networkId,
1113
+ from: peerId,
1114
+ to: opts.to ?? null,
1115
+ session_id: opts.session_id ?? roomId,
1116
+ message_id: generateMessageId(),
1117
+ timestamp: Date.now(),
1118
+ ttl_ms: opts.ttl_ms ?? null,
1119
+ reply_to: opts.reply_to ?? null,
1120
+ body: opts.body ?? {},
1121
+ }
1122
+ }
1123
+
1124
+ const loudSignalType = (type) => type === 'offer' || type === 'answer' || type === 'renegotiate'
1125
+
1126
+ // Peers that have proven they hear the mesh: one of their frames arrived
1127
+ // through injectSignal. Until a peer is in this set every frame for it
1128
+ // also goes to the relay, so a peer on a build that ignores mesh-carried
1129
+ // signaling still receives the offer, the answer, and the candidates.
1130
+ // After the first mesh frame from it, the relay copy stops.
1131
+ const meshCapablePeers = new Set()
1132
+
1133
+ // The mesh is tried before the relay for every frame addressed to one
1134
+ // peer. A peer already reachable through connected neighbours negotiates
1135
+ // without any relay in the path, so a relay outage, a partial relay view,
1136
+ // or two peers registered on different relays no longer decides whether
1137
+ // they can connect. Registration only gates the relay fallback.
1138
+ function sendViaMesh(toPeerId, type, envelope) {
1139
+ if (!toPeerId || typeof signalTransport !== 'function' || !MESH_SIGNAL_TYPES.has(type)) return false
1140
+ let accepted = false
1141
+ try {
1142
+ accepted = signalTransport(envelope) === true
1143
+ } catch {
1144
+ accepted = false
1145
+ }
1146
+ if (accepted && loudSignalType(type)) log(`[signal] sending ${type} to ${toPeerId} via mesh`)
1147
+ return accepted
1148
+ }
1149
+
1150
+ async function relaySignal(toPeerId, type, body) {
1151
+ const envelope = pspEnvelope(type, {
1152
+ to: toPeerId,
1153
+ session_id: getOrCreateSessionId(toPeerId),
1154
+ body,
1155
+ ...(NEGOTIATION_TYPES.has(type) ? { ttl_ms: NEGOTIATION_TTL_MS } : {}),
1156
+ })
1157
+ const viaMesh = sendViaMesh(toPeerId, type, envelope)
1158
+ if (viaMesh && meshCapablePeers.has(toPeerId)) return
1159
+
1160
+ if (!registered) {
1161
+ // A frame the mesh could not carry, with the relay released on purpose: wake it. This frame
1162
+ // is not queued, but a negotiation retries its frames until it connects or gives up, so the
1163
+ // retry that follows the registration is the one that goes out.
1164
+ if (relayIdle && !viaMesh) wakeRelay(`${type} for a peer the mesh cannot reach`)
1165
+ else if (!viaMesh) log('[signal] not registered yet')
1166
+ return
1167
+ }
1168
+ if (loudSignalType(type)) {
1169
+ log(viaMesh
1170
+ ? `[signal] sending ${type} to ${toPeerId} on the relay as well; it has not answered over the mesh yet`
1171
+ : `[signal] sending ${type} to ${toPeerId}`)
1172
+ }
1173
+
1174
+ send(envelope)
1175
+ }
1176
+
1177
+ // A signaling frame that arrived over the mesh instead of the relay
1178
+ // socket. It is held to the same shape the relay would have delivered:
1179
+ // addressed to this peer, for this network and room, from someone else.
1180
+ function injectSignal(envelope) {
1181
+ if (!envelope || typeof envelope !== 'object') return false
1182
+ if (!MESH_SIGNAL_TYPES.has(envelope.type)) return false
1183
+ if (typeof envelope.from !== 'string' || !envelope.from || envelope.from === peerId) return false
1184
+ if (envelope.to !== peerId) return false
1185
+ if (envelope.network !== networkId) return false
1186
+ if (envelope.session_id !== roomId) return false
1187
+ meshCapablePeers.add(envelope.from)
1188
+ handleMessage(envelope)
1189
+ return true
1190
+ }
1191
+
1192
+ function stopAdvertiseHeartbeat() {
1193
+ clearInterval(advertiseHeartbeatTimer)
1194
+ advertiseHeartbeatTimer = null
1195
+ }
1196
+
1197
+ function stopKeepalive() {
1198
+ clearInterval(keepaliveTimer)
1199
+ keepaliveTimer = null
1200
+ lastSignalPingSentAt = 0
1201
+ lastSignalPongAt = Date.now()
1202
+ }
1203
+
1204
+ function startAdvertiseHeartbeat() {
1205
+ stopAdvertiseHeartbeat()
1206
+ advertiseHeartbeatTimer = setInterval(() => {
1207
+ if (!registered) return
1208
+ // Re-announce to refresh TTL in the server's peer registry.
1209
+ send(pspEnvelope('announce', {
1210
+ ttl_ms: ADVERTISE_TTL_MS,
1211
+ body: { instance_id: networkId, capabilities, hints: { wants_peers: true } },
1212
+ }))
1213
+ }, ADVERTISE_HEARTBEAT_MS)
1214
+ }
1215
+
1216
+ function stopSuspendWatch() {
1217
+ clearInterval(suspendWatchTimer)
1218
+ suspendWatchTimer = null
1219
+ }
1220
+
1221
+ function startSuspendWatch() {
1222
+ stopSuspendWatch()
1223
+ if (typeof document !== 'undefined') return
1224
+ lastSuspendTick = Date.now()
1225
+ lastTickHidden = typeof document !== 'undefined' && document.hidden
1226
+ suspendWatchTimer = setInterval(() => {
1227
+ const now = Date.now()
1228
+ const gap = now - lastSuspendTick
1229
+ lastSuspendTick = now
1230
+ // A hidden tab's timers are throttled to a crawl; that gap is not a
1231
+ // suspend, and the tab's own visibility events cover its thaw.
1232
+ const hidden = typeof document !== 'undefined' && document.hidden
1233
+ const wasHidden = lastTickHidden
1234
+ lastTickHidden = hidden
1235
+ if (hidden || wasHidden || stoppedByUser) return
1236
+ if (gap < SUSPEND_GAP_MS) return
1237
+ log(`[signal] clock jumped ${Math.round(gap / 1000)}s — this peer was suspended; resuming`)
1238
+ handleSuspendRestore('clock_jump', gap)
1239
+ }, SUSPEND_TICK_MS)
1240
+ if (typeof suspendWatchTimer?.unref === 'function') suspendWatchTimer.unref()
1241
+ }
1242
+
1243
+ function startKeepalive() {
1244
+ stopKeepalive()
1245
+ keepaliveTimer = setInterval(() => {
1246
+ if (!registered) return
1247
+ if (typeof document !== 'undefined' && document.hidden) {
1248
+ lastSignalPingSentAt = 0
1249
+ lastSignalPongAt = Date.now()
1250
+ return
1251
+ }
1252
+ const pingInFlight = lastSignalPingSentAt > lastSignalPongAt
1253
+ if (pingInFlight) {
1254
+ if (Date.now() - lastSignalPingSentAt >= SIGNAL_PONG_TIMEOUT_MS) {
1255
+ log('[signal] keepalive timed out; reconnecting immediately')
1256
+ try { ws?.close(4000, 'keepalive_timeout') } catch {}
1257
+ }
1258
+ return
1259
+ }
1260
+ send(pspEnvelope('ping', { body: { nonce: generateMessageId() } }))
1261
+ lastSignalPingSentAt = Date.now()
1262
+ }, SIGNAL_PING_MS)
1263
+ }
1264
+
1265
+ function scheduleReconnect(openSocket, closeCode) {
1266
+ if (closeCode === 1000 || stoppedByUser) return
1267
+ const delayMs = reconnectAttempts === 0 ? 0 : backoffMs
1268
+ log(delayMs === 0 ? '[signal] reconnecting immediately' : `[signal] reconnecting in ${delayMs}ms`)
1269
+ reconnectTimer = setTimeout(() => {
1270
+ openSocket()
1271
+ }, delayMs)
1272
+ reconnectAttempts += 1
1273
+ if (delayMs > 0) backoffMs = Math.min(backoffMs * BACKOFF_FACTOR, BACKOFF_MAX_MS)
1274
+ }
1275
+
1276
+ // A channel can keep reporting 'open' while its connection is anything
1277
+ // but 'connected' — connecting during renegotiation, disconnected on an
1278
+ // ICE blip, failed after one. WebKit fails every such send with an
1279
+ // async console error no catch can see, so the gate must be POSITIVE:
1280
+ // send only over a connection that says 'connected' (or one whose
1281
+ // implementation has no connectionState at all).
1282
+ function isChannelLive(entry) {
1283
+ if (entry?.channel?.readyState !== 'open') return false
1284
+ if (entry.dormantAt && Date.now() - entry.dormantAt < DATA_DORMANT_MAX_MS) return false
1285
+ if (!entry.connection) return false
1286
+ const state = entry.connection.connectionState
1287
+ if (state !== undefined && state !== 'connected') return false
1288
+ // SCTP dies one-way: readyState and connectionState both keep
1289
+ // claiming health while every send fails — and in Safari the
1290
+ // failure does not even throw, so no error path ever fires. The
1291
+ // only trusted signal is the pong round trip: a channel is live
1292
+ // once its first pong has landed, and stops being live when a
1293
+ // ping goes unanswered past the pong timeout.
1294
+ const now = Date.now()
1295
+ if (!(entry.lastPongAt > 0) || now - entry.lastPongAt >= DATA_PROOF_FRESH_MS) return false
1296
+ if (linkSuspect(entry, now)) return false
1297
+ return !(entry.lastPingSentAt > entry.lastPongAt
1298
+ && now - entry.lastPingSentAt >= DATA_PONG_TIMEOUT_MS)
1299
+ }
1300
+
1301
+ function linkSuspect(entry, now = Date.now()) {
1302
+ return entry.lastPingSentAt > (entry.lastPongAt ?? 0)
1303
+ && now - entry.lastPingSentAt >= DATA_SUSPECT_MS
1304
+ && now - Math.max(entry.lastInboundAt ?? 0, entry.lastPongAt ?? 0) >= DATA_SUSPECT_MS
1305
+ }
1306
+
1307
+ // ── Relay on demand: who stays registered, and when the socket is released ─
1308
+ function notifyRelayState(state) {
1309
+ try { onRelayStateChange?.({ state, ts: Date.now() }) } catch { /* a host callback must not break the client */ }
1310
+ }
1311
+
1312
+ // A stable position on a 256-bit ring for a room or a peer. Closeness to the room is what
1313
+ // makes a peer an anchor, so every peer that knows the same ids reaches the same answer.
1314
+ async function closenessKey(text) {
1315
+ let key = closenessKeys.get(text)
1316
+ if (key === undefined) {
1317
+ // unsea's SHA-256: WebCrypto's, or its stand-in on a page without crypto.subtle (plain http).
1318
+ key = BigInt(`0x${await sha256(text)}`)
1319
+ if (closenessKeys.size > 2000) closenessKeys.clear()
1320
+ closenessKeys.set(text, key)
1321
+ }
1322
+ return key
1323
+ }
1324
+
1325
+ async function closestToRoom(roomKey, ids, count) {
1326
+ const scored = await Promise.all([...new Set(ids)].map(async (id) => ({ id, distance: (await closenessKey(id)) ^ roomKey })))
1327
+ scored.sort((a, b) => (a.distance < b.distance ? -1 : a.distance > b.distance ? 1 : a.id < b.id ? -1 : 1))
1328
+ return scored.slice(0, count).map((entry) => entry.id)
1329
+ }
1330
+
1331
+ function liveNeighbourIds() {
1332
+ const ids = []
1333
+ for (const [remotePeerId, entry] of mesh.connections.entries()) {
1334
+ if (isChannelLive(entry)) ids.push(remotePeerId)
1335
+ }
1336
+ return ids
1337
+ }
1338
+
1339
+ // What the neighbours have recently said they can vouch for. A neighbour only vouches for
1340
+ // itself and its own live neighbours, so an id that has gone away stops being repeated as soon
1341
+ // as the last peer that was connected to it notices, and no ghost can keep itself alive by
1342
+ // being passed around.
1343
+ function vouchedIds(neighbourIds) {
1344
+ const now = Date.now()
1345
+ const ids = []
1346
+ for (const remotePeerId of neighbourIds) {
1347
+ const gossip = mesh.connections.get(remotePeerId)?.anchorGossip
1348
+ if (gossip && now - gossip.at < relayConfig.gossipTtlMs) ids.push(...gossip.ids)
1349
+ }
1350
+ return ids
1351
+ }
1352
+
1353
+ // Whether this peer needs the relay right now. It does when it is cut off from the mesh, when it
1354
+ // is one of the room's anchors, or when something has just woken it. `direct` is what it can
1355
+ // vouch for itself (the closest among itself and its live neighbours); `anchors` also counts
1356
+ // what the neighbours vouch for, which is how it learns a closer peer is two hops away.
1357
+ async function relayDecision() {
1358
+ const now = Date.now()
1359
+ const neighbours = liveNeighbourIds()
1360
+ const roomKey = await closenessKey(`${networkId}:${roomId}`)
1361
+ const direct = await closestToRoom(roomKey, [peerId, ...neighbours], relayConfig.anchors)
1362
+ const anchors = await closestToRoom(roomKey, [peerId, ...neighbours, ...vouchedIds(neighbours)], relayConfig.anchors)
1363
+ const isolated = neighbours.length < relayConfig.minMeshPeers
1364
+ const isAnchor = anchors.includes(peerId)
1365
+ const awake = relayWakeUntil > now
1366
+ let held = false
1367
+ try { held = relayHold?.() === true } catch { held = false }
1368
+ // A local relay (reached directly, or at a bare or private address) costs
1369
+ // nothing per connection: stay on it. Letting go only made the room's
1370
+ // relay list come and go, and gave newcomers fewer peers to find.
1371
+ const local = isLocalRelayUrl(signalUrl)
1372
+ return { neighbours, direct, anchors, isolated, isAnchor, awake, held, local, wantRelay: local || isolated || isAnchor || awake || held || relayedLinks.size > 0 }
1373
+ }
1374
+
1375
+ // Tell each live neighbour which ids this peer can vouch for. Sent when the answer changes and
1376
+ // otherwise often enough that it never goes stale at the other end.
1377
+ function broadcastAnchors(neighbourIds, direct) {
1378
+ const key = direct.join(',')
1379
+ const now = Date.now()
1380
+ if (key === lastAnchorBroadcast.key && now - lastAnchorBroadcast.at < relayConfig.gossipTtlMs / 2) return
1381
+ lastAnchorBroadcast = { key, at: now }
1382
+ const frame = JSON.stringify({ type: RELAY_ANCHOR_FRAME, ids: direct })
1383
+ for (const remotePeerId of neighbourIds) {
1384
+ const entry = mesh.connections.get(remotePeerId)
1385
+ try {
1386
+ if (entry?.channel?.readyState === 'open' && transportReady(entry.connection)) entry.channel.send(frame)
1387
+ } catch { /* a broken channel is for the keepalive to judge */ }
1388
+ }
1389
+ }
1390
+
1391
+ // A negotiation that has not finished may be waiting on an answer that can only arrive by relay.
1392
+ function negotiationInFlight() {
1393
+ const now = Date.now()
1394
+ for (const entry of mesh.connections.values()) {
1395
+ if (entry.state === 'connecting' && now - (entry.lastSeen ?? 0) < NEGOTIATION_TTL_MS * 2) return true
1396
+ }
1397
+ return false
1398
+ }
1399
+
1400
+ function releaseRelay() {
1401
+ if (relayIdle || !ws) return
1402
+ log('[relay] the mesh is healthy and this peer is not an anchor: releasing the relay socket')
1403
+ relayIdle = true
1404
+ relayReleasableSince = 0
1405
+ send(pspEnvelope('withdraw', { body: { reason: 'relay_idle' } }))
1406
+ registered = false
1407
+ stopAdvertiseHeartbeat()
1408
+ stopKeepalive()
1409
+ // Detach first: a deliberate release must not look like a drop, or the host's recovery logic
1410
+ // would reopen the socket it was just meant to leave closed.
1411
+ const releasing = ws
1412
+ ws = null
1413
+ releasing.onopen = null
1414
+ releasing.onmessage = null
1415
+ releasing.onerror = null
1416
+ releasing.onclose = null
1417
+ try { releasing.close(1000, 'relay_idle') } catch { /* already closed */ }
1418
+ setStatus('relay-idle')
1419
+ notifyRelayState('idle')
1420
+ }
1421
+
1422
+ function wakeRelay(reason = 'requested', holdMs = relayConfig.lingerMs) {
1423
+ if (relayMode !== 'on-demand' || stoppedByUser) return false
1424
+ relayWakeUntil = Math.max(relayWakeUntil, Date.now() + holdMs)
1425
+ relayReleasableSince = 0
1426
+ if (!relayIdle) return true
1427
+ log(`[relay] waking the relay socket: ${reason}`)
1428
+ notifyRelayState('waking')
1429
+ resetReconnectBackoff()
1430
+ intentionalClose = false
1431
+ openSocket()
1432
+ return true
1433
+ }
1434
+
1435
+ async function evaluateRelay() {
1436
+ if (relayMode !== 'on-demand' || stoppedByUser || relayEvaluating) return null
1437
+ relayEvaluating = true
1438
+ try {
1439
+ const decision = await relayDecision()
1440
+ broadcastAnchors(decision.neighbours, decision.direct)
1441
+ if (decision.wantRelay) {
1442
+ relayReleasableSince = 0
1443
+ if (relayIdle) wakeRelay(decision.isolated ? 'cut off from the mesh' : decision.held ? 'held by the host' : 'anchor')
1444
+ } else if (!relayIdle && registered && !negotiationInFlight()) {
1445
+ const now = Date.now()
1446
+ if (!relayReleasableSince) relayReleasableSince = now
1447
+ if (now - relayReleasableSince >= relayConfig.settleMs) releaseRelay()
1448
+ } else {
1449
+ relayReleasableSince = 0
1450
+ }
1451
+ return decision
1452
+ } finally {
1453
+ relayEvaluating = false
1454
+ }
1455
+ }
1456
+
1457
+ function startRelayWatch() {
1458
+ if (relayMode !== 'on-demand') return
1459
+ clearInterval(relayWatchTimer)
1460
+ relayWatchTimer = setInterval(() => { evaluateRelay().catch((error) => log(`[relay] evaluation failed: ${error?.message ?? error}`)) }, relayConfig.evalMs)
1461
+ if (typeof relayWatchTimer?.unref === 'function') relayWatchTimer.unref()
1462
+ }
1463
+
1464
+ function stopRelayWatch() {
1465
+ clearInterval(relayWatchTimer)
1466
+ relayWatchTimer = null
1467
+ }
1468
+
1469
+ function closeAllPeerConnections() {
1470
+ for (const [remotePeerId, entry] of mesh.connections.entries()) {
1471
+ try {
1472
+ entry.connection?.close()
1473
+ } catch {}
1474
+ clearAnswerBurst(remotePeerId)
1475
+ offerProcessingQueues.delete(remotePeerId)
1476
+ pendingAnswers.delete(remotePeerId)
1477
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'closed', ts: Date.now() })
1478
+ }
1479
+ }
1480
+
1481
+ // A rollback withdraws the local offer but not the data channel created
1482
+ // for it: SCTP opens that channel anyway once the remote offer connects,
1483
+ // and the peers end up holding two 'mesh' channels on one connection. The
1484
+ // channel goes with the offer it was created for.
1485
+ function withdrawChannelOfRolledBackOffer(remotePeerId, pc) {
1486
+ const entry = mesh.connections.get(remotePeerId)
1487
+ if (entry?.connection !== pc || !entry.channel) return
1488
+ const abandoned = entry.channel
1489
+ if (abandoned.readyState === 'open') return
1490
+ entry.channel = null
1491
+ try { abandoned.close() } catch {}
1492
+ }
1493
+
1494
+ function attachDataChannelHandlers(channel, remotePeerId, pc) {
1495
+ let keepaliveTimerId = null
1496
+ let lastPongAt = Date.now()
1497
+ let lastPingSentAt = 0 // 0 = no ping in flight
1498
+ let lastInboundAt = Date.now()
1499
+ let lastPingRetryAt = 0
1500
+ // werift delivers a message on a channel it still reports as
1501
+ // 'connecting': the remote's arming ping lands a beat before our 'open'
1502
+ // fires. Its pong is owed, not skipped — it is the only proof the remote
1503
+ // gets that this direction works, and it sends no second ping while the
1504
+ // first is outstanding.
1505
+ let pongOwed = false
1506
+ // A ping cannot be late while it is still sitting in our own send
1507
+ // buffer, and a channel that keeps delivering messages is not dead. The
1508
+ // watcher's index node pushes megabytes of storage the moment a browser
1509
+ // connects; over werift's SCTP that takes longer than the pong deadline,
1510
+ // the ping queued behind it, and the keepalive executed a channel that
1511
+ // was working flat out — on every peer, on every connection.
1512
+ // Backlogged means BUSY, not merely non-empty: the buffer has to be
1513
+ // shrinking. A buffer that holds or grows for the stall window is a
1514
+ // receiver that stopped reading, and the keepalive verdict must run.
1515
+ let lastBufferedAmount = 0
1516
+ let lastBufferedProgressAt = Date.now()
1517
+ // Progress is also the buffer emptying between two looks (the browser says so: bufferedamountlow at
1518
+ // threshold 0), and an empty buffer at a look. Counting only a smaller amount than at the last look
1519
+ // executed healthy channels: one idle (empty) for the stall window, caught with a message in flight
1520
+ // at the next look, read as stalled since its last shrink 20 s before, and was closed, every 20 s.
1521
+ try {
1522
+ channel.addEventListener?.('bufferedamountlow', () => { lastBufferedProgressAt = Date.now() })
1523
+ } catch { /* no such event here: the looks alone */ }
1524
+ const backlogged = () => {
1525
+ const buffered = Number(channel.bufferedAmount ?? 0)
1526
+ const now = Date.now()
1527
+ if (buffered === 0 || buffered < lastBufferedAmount) lastBufferedProgressAt = now
1528
+ lastBufferedAmount = buffered
1529
+ return buffered > 0 && now - lastBufferedProgressAt < DATA_BACKLOG_STALL_MS
1530
+ }
1531
+ const backlogStalled = () => Number(channel.bufferedAmount ?? 0) > 0
1532
+ && Date.now() - lastBufferedProgressAt >= DATA_BACKLOG_STALL_MS
1533
+ const inboundAlive = () => Date.now() - lastInboundAt < DATA_PONG_TIMEOUT_MS
1534
+
1535
+ // The moment the tab becomes visible, PROBE the channel instead of
1536
+ // assuming it survived: faking a fresh pong here stamped every
1537
+ // suspend-killed channel as healthy, so the resume-time gossip burst
1538
+ // sent straight into corpses. A real ping gives a healthy channel a
1539
+ // fresh pong within one round trip and starts the execution clock on
1540
+ // a dead one.
1541
+ function onVisible() {
1542
+ if (typeof document === 'undefined') return
1543
+ if (document.hidden) {
1544
+ // Going dormant: tell the peer BEFORE the freeze lands so it parks
1545
+ // this edge instead of executing it at the pong timeout.
1546
+ try {
1547
+ if (channel.readyState === 'open' && transportReady(pc)) {
1548
+ channel.send(JSON.stringify({ type: DATA_DORMANT_FRAME }))
1549
+ }
1550
+ } catch { /* the peer's timeout still covers a lost announcement */ }
1551
+ return
1552
+ }
1553
+ lastPongAt = 0
1554
+ const visibleEntry = mesh.connections.get(remotePeerId)
1555
+ const owned = visibleEntry?.connection === pc && visibleEntry.channel === channel
1556
+ try {
1557
+ if (channel.readyState === 'open' && transportReady(pc)) {
1558
+ channel.send(JSON.stringify({ type: 'ping', ts: Date.now() }))
1559
+ lastPingSentAt = Date.now()
1560
+ if (owned) {
1561
+ visibleEntry.lastPongAt = 0
1562
+ visibleEntry.lastPingSentAt = lastPingSentAt
1563
+ }
1564
+ }
1565
+ } catch {
1566
+ closeBrokenChannel('data channel resume probe failed')
1567
+ }
1568
+ }
1569
+
1570
+ function closeBrokenChannel(reason) {
1571
+ const currentEntry = mesh.connections.get(remotePeerId)
1572
+ const ownsCurrentEntry = currentEntry?.connection === pc && currentEntry.channel === channel
1573
+ log(`[webrtc] ${reason} to ${remotePeerId}; closing peer connection`)
1574
+ clearInterval(keepaliveTimerId)
1575
+ keepaliveTimerId = null
1576
+ try { channel.close() } catch {}
1577
+ try { pc.close() } catch {}
1578
+ if (ownsCurrentEntry) mesh.markDead(remotePeerId)
1579
+ }
1580
+
1581
+ const entry = mesh.connections.get(remotePeerId)
1582
+ if (entry?.connection === pc) {
1583
+ entry.channel = channel
1584
+ // The proof bookkeeping belongs to THIS channel. It used to survive a
1585
+ // channel swap on the entry (glare adoption, a redial on the same
1586
+ // connection), so a fresh channel inherited an unanswered ping from
1587
+ // the dead one, the first send was refused as "failed its pong proof"
1588
+ // — a terminal refusal — and the peer was released the instant it
1589
+ // connected. Start unproven with nothing in flight; an already-open
1590
+ // channel is armed here exactly as onopen would have armed it.
1591
+ entry.lastPongAt = 0
1592
+ entry.lastPingSentAt = 0
1593
+ lastPongAt = 0
1594
+ lastPingSentAt = 0
1595
+ if (channel.readyState === 'open' && transportReady(pc)) {
1596
+ try {
1597
+ channel.send(JSON.stringify({ type: 'ping', ts: Date.now() }))
1598
+ entry.lastPingSentAt = Date.now()
1599
+ lastPingSentAt = entry.lastPingSentAt
1600
+ } catch { /* the keepalive verdict handles it */ }
1601
+ }
1602
+ }
1603
+
1604
+ channel.onopen = () => {
1605
+ const currentEntry = mesh.connections.get(remotePeerId)
1606
+ if (currentEntry?.connection !== pc || currentEntry.channel !== channel) {
1607
+ try { channel.close() } catch {}
1608
+ return
1609
+ }
1610
+ log(`[webrtc] data channel open to ${remotePeerId}`)
1611
+ // 0, not now: the channel is unproven until its first pong, and the
1612
+ // keepalive's ping-in-flight timeout must be armed from the start so
1613
+ // a channel that never answers dies at the timeout, not never.
1614
+ lastPongAt = 0
1615
+ _acquireWakeLock()
1616
+
1617
+ if (typeof document !== 'undefined') {
1618
+ document.removeEventListener('visibilitychange', onVisible)
1619
+ document.addEventListener('visibilitychange', onVisible)
1620
+ }
1621
+
1622
+ const openEntry = mesh.connections.get(remotePeerId)
1623
+ if (openEntry?.connection === pc) {
1624
+ openEntry.channel = channel
1625
+ openEntry.lastSeen = Date.now()
1626
+ if (!openEntry.relayed) {
1627
+ linkFailures.delete(remotePeerId)
1628
+ dialAttempts.delete(remotePeerId)
1629
+ }
1630
+ // Round-trip bookkeeping, mirrored onto the entry so sendData can
1631
+ // refuse a channel whose outbound direction is unproven. SCTP can
1632
+ // die one-way: messages keep ARRIVING while every send fails as
1633
+ // WebKit's async console error — readyState and connectionState
1634
+ // both keep lying, and in Safari the failed send does not even
1635
+ // throw. A returned pong is the only send-side truth, so an
1636
+ // 'open' channel starts UNPROVEN (lastPongAt 0): app sends are
1637
+ // refused until the first pong lands, and a channel whose opening
1638
+ // ping stays unanswered dies by the normal timeout instead of
1639
+ // enjoying a grace window it never earned.
1640
+ openEntry.lastPongAt = 0
1641
+ // Only a ping that actually left counts as outstanding. Recording
1642
+ // one that was skipped (transport not yet 'connected') armed a
1643
+ // phantom four-second timeout that the first inbound message
1644
+ // executed as "outbound timeout" on a channel nobody had pinged.
1645
+ try {
1646
+ if (transportReady(pc)) {
1647
+ channel.send(JSON.stringify({ type: 'ping', ts: Date.now() }))
1648
+ openEntry.lastPingSentAt = Date.now()
1649
+ lastPingSentAt = openEntry.lastPingSentAt
1650
+ } else {
1651
+ openEntry.lastPingSentAt = 0
1652
+ lastPingSentAt = 0
1653
+ }
1654
+ } catch {
1655
+ openEntry.lastPingSentAt = 0
1656
+ lastPingSentAt = 0
1657
+ }
1658
+ }
1659
+ if (pongOwed) {
1660
+ pongOwed = false
1661
+ try { channel.send(JSON.stringify({ type: 'pong', ts: Date.now() })) } catch { /* the keepalive verdict handles it */ }
1662
+ }
1663
+ // RTCPeerConnection "connected" may precede data-channel readiness.
1664
+ // Emit again at the exact usable boundary so callers can send immediately.
1665
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'connected', ts: Date.now() })
1666
+
1667
+ clearInterval(keepaliveTimerId)
1668
+ keepaliveTimerId = setInterval(() => {
1669
+ const currentEntry = mesh.connections.get(remotePeerId)
1670
+ if (currentEntry?.connection !== pc || currentEntry.channel !== channel) {
1671
+ clearInterval(keepaliveTimerId)
1672
+ keepaliveTimerId = null
1673
+ return
1674
+ }
1675
+ if (channel.readyState !== 'open') {
1676
+ // WebKit can move a channel to 'closing' without ever firing
1677
+ // onclose — a zombie that skipping here kept alive forever: no
1678
+ // ping, no timeout, never marked dead, while every send into it
1679
+ // spammed 'Error sending string through RTCDataChannel'. A
1680
+ // channel that is not open IS broken; execute it on the spot.
1681
+ closeBrokenChannel(`data channel ${channel.readyState}`)
1682
+ return
1683
+ }
1684
+ if (currentEntry.dormantAt) {
1685
+ if (Date.now() - currentEntry.dormantAt < DATA_DORMANT_MAX_MS) {
1686
+ // Parked: the peer announced a nap. No pings, no verdicts —
1687
+ // pacify the in-flight bookkeeping so nothing ages while parked.
1688
+ lastPingSentAt = 0
1689
+ lastPongAt = Date.now()
1690
+ return
1691
+ }
1692
+ currentEntry.dormantAt = 0
1693
+ }
1694
+ if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
1695
+ // The inverse zombie: the channel still reports 'open' but the
1696
+ // connection under it is dead, so every send fails as the same
1697
+ // uncatchable async console error. Only TERMINAL states execute
1698
+ // here — 'disconnected' is usually a transient ICE blip that
1699
+ // recovers on its own, and executing it turned every blip into a
1700
+ // teardown-and-redial flap; a blip that persists still dies
1701
+ // through the ping timeout below.
1702
+ closeBrokenChannel(`connection ${pc.connectionState}`)
1703
+ return
1704
+ }
1705
+
1706
+ // Browsers throttle timers in hidden tabs — don't falsely time out.
1707
+ // The fake pong here only pacifies THIS timer; the entry mirrors are
1708
+ // left honest so ping-on-receive still proves outbound in hidden
1709
+ // tabs, where a one-way-dead channel used to live forever while
1710
+ // every reactive gossip reply failed.
1711
+ if (typeof document !== 'undefined' && document.hidden) {
1712
+ lastPingSentAt = 0
1713
+ lastPongAt = Date.now()
1714
+ return
1715
+ }
1716
+
1717
+ // Only consider a timeout if we sent a ping that hasn't been answered.
1718
+ const pingInFlight = lastPingSentAt > lastPongAt
1719
+ const busy = backlogged()
1720
+ if (!busy && backlogStalled()) {
1721
+ closeBrokenChannel('data channel backlog stalled')
1722
+ return
1723
+ }
1724
+ if (pingInFlight && busy) {
1725
+ // Still in our buffer: the clock on this ping has not started.
1726
+ lastPingSentAt = Date.now()
1727
+ if (currentEntry.lastPingSentAt > currentEntry.lastPongAt) currentEntry.lastPingSentAt = lastPingSentAt
1728
+ return
1729
+ }
1730
+ if (pingInFlight && Date.now() - lastPingSentAt >= DATA_PONG_TIMEOUT_MS && !inboundAlive()) {
1731
+ closeBrokenChannel('data channel timeout')
1732
+ return
1733
+ }
1734
+
1735
+ // Keep one outstanding ping. Replacing its timestamp on every tick
1736
+ // made a silent channel impossible to time out — so the clock stays,
1737
+ // but the frame itself is re-sent every few seconds: a lost ping is
1738
+ // recovered within one retry instead of executing a live channel.
1739
+ if (pingInFlight) {
1740
+ const now = Date.now()
1741
+ if (now - lastPingSentAt >= DATA_PING_RETRY_MS && now - lastPingRetryAt >= DATA_PING_RETRY_MS
1742
+ && (pc.connectionState === undefined || pc.connectionState === 'connected')) {
1743
+ lastPingRetryAt = now
1744
+ try { channel.send(JSON.stringify({ type: 'ping', ts: now })) } catch { /* verdict below */ }
1745
+ }
1746
+ return
1747
+ }
1748
+
1749
+ // A transient connection state (connecting, disconnected) refuses
1750
+ // application sends already; a ping into it fails the same way —
1751
+ // WebKit logs an uncatchable async console error per attempt, one
1752
+ // every tick through a whole renegotiation window. Skip the ping:
1753
+ // recovery either restores 'connected' (pings resume) or the stalled
1754
+ // negotiation machinery executes the peer.
1755
+ if (pc.connectionState !== undefined && pc.connectionState !== 'connected') return
1756
+
1757
+ try {
1758
+ channel.send(JSON.stringify({ type: 'ping', ts: Date.now() }))
1759
+ lastPingSentAt = Date.now()
1760
+ if (currentEntry.lastPingSentAt <= currentEntry.lastPongAt) {
1761
+ currentEntry.lastPingSentAt = lastPingSentAt
1762
+ }
1763
+ } catch {
1764
+ closeBrokenChannel('data channel keepalive send failed')
1765
+ }
1766
+ }, DATA_PING_MS)
1767
+ }
1768
+
1769
+ // Outbound proof, driven by INCOMING traffic so it works even in hidden
1770
+ // tabs where interval timers are throttled into uselessness: a message
1771
+ // arriving on a channel whose outbound is not recently pong-proven
1772
+ // sends a ping; a ping that stays unanswered past the pong timeout
1773
+ // while messages keep arriving is a one-way-dead channel — execute it.
1774
+ const proveOutbound = () => {
1775
+ const currentEntry = mesh.connections.get(remotePeerId)
1776
+ if (currentEntry?.connection !== pc || currentEntry.channel !== channel) return
1777
+ if (currentEntry.dormantAt) return
1778
+ const now = Date.now()
1779
+ const pingOutstanding = currentEntry.lastPingSentAt > currentEntry.lastPongAt
1780
+ if (pingOutstanding && backlogged()) {
1781
+ currentEntry.lastPingSentAt = now
1782
+ return
1783
+ }
1784
+ if (pingOutstanding && now - currentEntry.lastPingSentAt >= DATA_PONG_TIMEOUT_MS) {
1785
+ closeBrokenChannel('data channel outbound timeout')
1786
+ return
1787
+ }
1788
+ // Same transient-state gate as the timer ping: WebKit turns every send
1789
+ // into a not-connected transport into an uncatchable console error.
1790
+ if (pc.connectionState !== undefined && pc.connectionState !== 'connected') return
1791
+ if (!pingOutstanding && now - currentEntry.lastPongAt > DATA_PING_MS) {
1792
+ try {
1793
+ channel.send(JSON.stringify({ type: 'ping', ts: now }))
1794
+ currentEntry.lastPingSentAt = now
1795
+ } catch {
1796
+ closeBrokenChannel('data channel keepalive send failed')
1797
+ }
1798
+ }
1799
+ }
1800
+
1801
+ // Reassembly state for chunked payloads on this channel. Bounded: a
1802
+ // stale or oversized transfer is dropped, never grown forever.
1803
+ const chunkTransfers = new Map()
1804
+ // Binary frames: ArrayBuffers, not Blobs (a Blob would need an async read, out of order).
1805
+ try { channel.binaryType = 'arraybuffer' } catch { /* not settable: Blobs are read below */ }
1806
+ const binTransfers = new Map()
1807
+ const reassembleBinary = (frame) => {
1808
+ if (frame.byteLength < DATA_BIN_HEADER) return null
1809
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength)
1810
+ if (view.getUint8(0) !== 0x70 || view.getUint8(1) !== 0x62 || view.getUint8(2) !== 1) return null
1811
+ const id = view.getUint32(4), seq = view.getUint16(8), total = view.getUint16(10)
1812
+ if (total < 1 || total > DATA_BIN_MAX_SLICES || seq >= total) return null
1813
+ const part = frame.subarray(DATA_BIN_HEADER)
1814
+ if (total === 1) return part.slice()
1815
+ const now = Date.now()
1816
+ for (const [key, t] of binTransfers) if (now - t.startedAt > DATA_CHUNK_STALE_MS) binTransfers.delete(key)
1817
+ let t = binTransfers.get(id)
1818
+ if (!t) { t = { startedAt: now, total, received: 0, size: 0, parts: new Array(total) }; binTransfers.set(id, t) }
1819
+ if (t.total !== total || t.parts[seq] !== undefined) return null
1820
+ t.parts[seq] = part.slice()
1821
+ t.received++
1822
+ t.size += part.length
1823
+ if (t.received < t.total) return null
1824
+ binTransfers.delete(id)
1825
+ const whole = new Uint8Array(t.size)
1826
+ let at = 0
1827
+ for (const p of t.parts) { whole.set(p, at); at += p.length }
1828
+ return whole
1829
+ }
1830
+ const onBinary = (bytes) => {
1831
+ const currentEntry = mesh.connections.get(remotePeerId)
1832
+ if (!(currentEntry?.connection === pc && currentEntry.channel === channel)) return
1833
+ const whole = reassembleBinary(bytes)
1834
+ if (whole === null) return
1835
+ proveOutbound()
1836
+ onDataMessage?.({ peerId: remotePeerId, data: whole })
1837
+ }
1838
+ const reassembleChunk = (msg) => {
1839
+ const total = Number(msg.n)
1840
+ const seq = Number(msg.s)
1841
+ const id = String(msg.i ?? '')
1842
+ if (!id || !Number.isInteger(total) || !Number.isInteger(seq)
1843
+ || total < 1 || total > DATA_CHUNK_MAX_FRAMES || seq < 0 || seq >= total) return null
1844
+ const now = Date.now()
1845
+ for (const [key, transfer] of chunkTransfers) {
1846
+ if (now - transfer.startedAt > DATA_CHUNK_STALE_MS) chunkTransfers.delete(key)
1847
+ }
1848
+ let transfer = chunkTransfers.get(id)
1849
+ if (!transfer) {
1850
+ transfer = { startedAt: now, total, received: 0, parts: new Array(total) }
1851
+ chunkTransfers.set(id, transfer)
1852
+ }
1853
+ if (transfer.total !== total || transfer.parts[seq] !== undefined) return null
1854
+ transfer.parts[seq] = String(msg.d ?? '')
1855
+ transfer.received++
1856
+ if (transfer.received < transfer.total) return null
1857
+ chunkTransfers.delete(id)
1858
+ return transfer.parts.join('')
1859
+ }
1860
+
1861
+ channel.onmessage = (event) => {
1862
+ lastInboundAt = Date.now()
1863
+ const currentEntry = mesh.connections.get(remotePeerId)
1864
+ const ownsCurrentEntry = currentEntry?.connection === pc && currentEntry.channel === channel
1865
+ if (ownsCurrentEntry) currentEntry.lastInboundAt = lastInboundAt
1866
+ if (ownsCurrentEntry && currentEntry.dormantAt && String(event.data).indexOf(DATA_DORMANT_FRAME) === -1) {
1867
+ currentEntry.dormantAt = 0
1868
+ }
1869
+ if (event.data instanceof ArrayBuffer || ArrayBuffer.isView(event.data)) {
1870
+ onBinary(event.data instanceof ArrayBuffer ? new Uint8Array(event.data) : new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength))
1871
+ return
1872
+ }
1873
+ if (typeof Blob !== 'undefined' && event.data instanceof Blob) {
1874
+ void event.data.arrayBuffer().then((buf) => onBinary(new Uint8Array(buf)), () => {})
1875
+ return
1876
+ }
1877
+ let msg
1878
+ try {
1879
+ msg = JSON.parse(event.data)
1880
+ } catch {
1881
+ if (!ownsCurrentEntry) return
1882
+ proveOutbound()
1883
+ onDataMessage?.({ peerId: remotePeerId, data: event.data })
1884
+ return
1885
+ }
1886
+
1887
+ if (msg?.type === DATA_DORMANT_FRAME) {
1888
+ const dormantEntry = mesh.connections.get(remotePeerId)
1889
+ if (dormantEntry?.connection === pc && dormantEntry.channel === channel) {
1890
+ dormantEntry.dormantAt = Date.now()
1891
+ }
1892
+ return
1893
+ }
1894
+
1895
+ // The other side is closing this edge (closePeerConnection): close ours now.
1896
+ if (DATA_BYE_FRAMES.has(msg?.type)) {
1897
+ const byeEntry = mesh.connections.get(remotePeerId)
1898
+ if (byeEntry?.connection === pc) {
1899
+ const reason = typeof msg.reason === 'string' ? msg.reason.slice(0, 120) : 'remote_close'
1900
+ log(`[webrtc] ${remotePeerId} closed this edge (${reason})`)
1901
+ closePeerConnection(remotePeerId, reason, false)
1902
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'closed', reason, ts: Date.now() })
1903
+ }
1904
+ return
1905
+ }
1906
+
1907
+ // A neighbour's word on which peers it can vouch for as closest to the room. Control
1908
+ // traffic for the relay-on-demand election: never handed to the host as data.
1909
+ if (msg?.type === RELAY_ANCHOR_FRAME) {
1910
+ if (ownsCurrentEntry && Array.isArray(msg.ids)) {
1911
+ currentEntry.anchorGossip = {
1912
+ at: Date.now(),
1913
+ ids: msg.ids.filter((id) => typeof id === 'string' && id.length > 0 && id.length <= 256).slice(0, 16),
1914
+ }
1915
+ }
1916
+ return
1917
+ }
1918
+
1919
+ if (msg?.t === DATA_CHUNK_FRAME) {
1920
+ if (!ownsCurrentEntry) return
1921
+ const full = reassembleChunk(msg)
1922
+ if (full !== null) {
1923
+ proveOutbound()
1924
+ onDataMessage?.({ peerId: remotePeerId, data: full })
1925
+ }
1926
+ return
1927
+ }
1928
+
1929
+ // Keepalives must be answered on the channel they arrived on, even when
1930
+ // simultaneous negotiation left two channels on one peer connection and
1931
+ // this one lost the `entry.channel` slot. The remote pings whichever
1932
+ // channel IT owns; refusing to pong a non-owning channel made the remote
1933
+ // time out a perfectly healthy transport within four seconds — an
1934
+ // open/close/redial flap.
1935
+ if (msg?.type === 'ping') {
1936
+ // Inbound can outlive outbound: WebKit delivers queued pings on a
1937
+ // transport whose sending side is already dead, and the reply was
1938
+ // the last remaining source of the uncatchable send error. A skipped
1939
+ // pong on a transient state is safe — the remote holds its own pings
1940
+ // during transient states too, and a state that never returns to
1941
+ // 'connected' is executed by the stall machinery on both ends.
1942
+ // A ping arriving here PROVES the remote can reach us on this
1943
+ // channel; the reply is the only proof it gets of the other
1944
+ // direction. Gating the pong on pc.connectionState === 'connected'
1945
+ // dropped it whenever a browser reported 'connecting' with the
1946
+ // channel open — a state Chromium and WebKit both pass through
1947
+ // during (re)negotiation — and the remote read the silence as a
1948
+ // one-way-dead channel and executed a healthy transport four
1949
+ // seconds later ("data channel outbound timeout"). Only the
1950
+ // channel's own state gates the reply; a failed send is caught.
1951
+ if (channel.readyState === 'connecting') { pongOwed = true; return }
1952
+ if (channel.readyState !== 'open') return
1953
+ try {
1954
+ channel.send(JSON.stringify({ type: 'pong', ts: Date.now() }))
1955
+ } catch {
1956
+ if (ownsCurrentEntry) {
1957
+ closeBrokenChannel('data channel pong send failed')
1958
+ } else {
1959
+ try { channel.close() } catch { /* already closing */ }
1960
+ }
1961
+ }
1962
+ return
1963
+ }
1964
+
1965
+ if (msg?.type === 'pong') {
1966
+ const pingSentAt = lastPingSentAt
1967
+ lastPongAt = Date.now()
1968
+ lastPingSentAt = 0
1969
+ // Our ping got through, so everything queued before it did too: the send buffer is moving,
1970
+ // whatever bufferedAmount says (WebKit can leave it above 0 on a channel that is working).
1971
+ if (pingSentAt > 0) lastBufferedProgressAt = lastPongAt
1972
+ const pongEntry = mesh.connections.get(remotePeerId)
1973
+ if (pongEntry?.connection === pc && pongEntry.channel === channel) {
1974
+ // Round trip on this link, on our own clock only (smoothed): what a
1975
+ // host can use to estimate how long a frame takes to cross it.
1976
+ const sent = pongEntry.lastPingSentAt || pingSentAt
1977
+ if (sent > 0 && lastPongAt >= sent) {
1978
+ const rtt = lastPongAt - sent
1979
+ pongEntry.rttMs = pongEntry.rttMs > 0 ? Math.round(pongEntry.rttMs * 0.7 + rtt * 0.3) : rtt
1980
+ }
1981
+ pongEntry.lastPongAt = lastPongAt
1982
+ pongEntry.lastPingSentAt = 0
1983
+ }
1984
+ return
1985
+ }
1986
+
1987
+ if (!ownsCurrentEntry) return
1988
+ proveOutbound()
1989
+
1990
+ onDataMessage?.({ peerId: remotePeerId, data: event.data })
1991
+ }
1992
+
1993
+ channel.onclose = () => {
1994
+ log(`[webrtc] data channel closed to ${remotePeerId}`)
1995
+ clearInterval(keepaliveTimerId)
1996
+ keepaliveTimerId = null
1997
+ if (typeof document !== 'undefined') {
1998
+ document.removeEventListener('visibilitychange', onVisible)
1999
+ }
2000
+ const closedEntry = mesh.connections.get(remotePeerId)
2001
+ if (closedEntry?.connection === pc && closedEntry.channel === channel) {
2002
+ closedEntry.channel = null
2003
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'closed', ts: Date.now() })
2004
+ }
2005
+ // Release the wake lock if no more open data channels remain.
2006
+ const anyOpen = [...mesh.connections.values()].some(
2007
+ (e) => e.channel?.readyState === 'open'
2008
+ )
2009
+ if (!anyOpen) _releaseWakeLock()
2010
+ }
2011
+
2012
+ channel.onerror = (evt) => {
2013
+ const currentEntry = mesh.connections.get(remotePeerId)
2014
+ if (currentEntry?.connection !== pc || currentEntry.channel !== channel) return
2015
+ const msg = evt?.error?.message ?? evt?.error ?? evt?.message ?? String(evt)
2016
+ // Closing an RTCDataChannel deliberately causes Safari/WebKit to emit an
2017
+ // error event whose text says the close was user-initiated. It is teardown
2018
+ // confirmation, not a transport failure, and must not feed recovery again.
2019
+ if (/user-initiated abort|close called/i.test(String(msg))) return
2020
+ log(`[webrtc] data channel error to ${remotePeerId}: ${msg}`)
2021
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'failed', ts: Date.now() })
2022
+ }
2023
+ }
2024
+
2025
+ function createPeerConnection(remotePeerId, iceServers, sendRelay) {
2026
+ const pc = new RTCPeerConnection({
2027
+ iceServers,
2028
+ iceTransportPolicy: 'all',
2029
+ iceCandidatePoolSize: 4,
2030
+ })
2031
+
2032
+ mesh.connections.set(remotePeerId, {
2033
+ connection: pc,
2034
+ channel: null,
2035
+ state: 'connecting',
2036
+ lastSeen: Date.now(),
2037
+ lastRemoteOfferSdp: null,
2038
+ lastLocalAnswer: null,
2039
+ lastAppliedAnswerSdp: null,
2040
+ lastAnswerSentAt: 0,
2041
+ lastAnswerBurstAt: 0,
2042
+ localCandidateCount: 0,
2043
+ iceServers,
2044
+ })
2045
+
2046
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'connecting', ts: Date.now() })
2047
+
2048
+ pc.onicecandidate = (event) => {
2049
+ const current = mesh.connections.get(remotePeerId)
2050
+ if (current?.connection !== pc) return
2051
+ if (event.candidate) {
2052
+ current.localCandidateCount = (current.localCandidateCount ?? 0) + 1
2053
+ log(`[webrtc] local candidate to ${remotePeerId}`)
2054
+ sendRelay('ice_candidate', {
2055
+ candidate: {
2056
+ candidate: event.candidate.candidate,
2057
+ sdpMid: event.candidate.sdpMid,
2058
+ sdpMLineIndex: event.candidate.sdpMLineIndex,
2059
+ },
2060
+ })
2061
+ } else {
2062
+ sendRelay('ice_end', {})
2063
+ }
2064
+ }
2065
+
2066
+ pc.onicecandidateerror = (event) => {
2067
+ const current = mesh.connections.get(remotePeerId)
2068
+ if (current?.connection !== pc) return
2069
+ const code = event?.errorCode ?? 'unknown'
2070
+ const text = event?.errorText ?? 'unknown'
2071
+ const url = event?.url ?? 'n/a'
2072
+ const numericCode = Number(code)
2073
+ if (Number.isInteger(numericCode) && numericCode >= 700 && numericCode < 800) {
2074
+ // Browsers emit 7xx candidate diagnostics for individual URL/interface
2075
+ // combinations even while other candidates from the same ICE server
2076
+ // remain usable. They must never mutate ICE configuration or transport
2077
+ // state; the browser's ICE agent remains the sole authority here.
2078
+ log(`[webrtc] non-fatal ICE candidate diagnostic to ${remotePeerId}: code=${code} text=${text} url=${url}`)
2079
+ return
2080
+ }
2081
+ log(`[webrtc] ice candidate error to ${remotePeerId}: code=${code} text=${text} url=${url}`)
2082
+ }
2083
+
2084
+ pc.onconnectionstatechange = () => {
2085
+ if (pc.connectionState === 'closed') clearOfferRetryTimer(pc)
2086
+ const entry = mesh.connections.get(remotePeerId)
2087
+ if (entry?.connection !== pc) return
2088
+ log(`[webrtc] connection to ${remotePeerId}: ${pc.connectionState}`)
2089
+ entry.state = pc.connectionState
2090
+ entry.lastSeen = Date.now()
2091
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: pc.connectionState, ts: Date.now() })
2092
+
2093
+ if (pc.connectionState === 'connected') {
2094
+ mesh.markLive(remotePeerId)
2095
+ clearAnswerBurst(remotePeerId)
2096
+ } else if (pc.connectionState === 'disconnected') {
2097
+ entry.state = 'recovering'
2098
+ } else if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
2099
+ mesh.markDead(remotePeerId)
2100
+ }
2101
+ }
2102
+
2103
+ pc.oniceconnectionstatechange = () => {
2104
+ const entry = mesh.connections.get(remotePeerId)
2105
+ if (entry?.connection !== pc) return
2106
+ log(`[webrtc] ice to ${remotePeerId}: ${pc.iceConnectionState}`)
2107
+ entry.lastSeen = Date.now()
2108
+ if (pc.iceConnectionState === 'failed') {
2109
+ mesh.markDead(remotePeerId)
2110
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'failed', ts: Date.now() })
2111
+ } else if (pc.iceConnectionState === 'disconnected' || pc.iceConnectionState === 'closed') {
2112
+ entry.state = pc.iceConnectionState
2113
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: pc.iceConnectionState, ts: Date.now() })
2114
+ }
2115
+ }
2116
+
2117
+ pc.onicegatheringstatechange = () => {
2118
+ if (mesh.connections.get(remotePeerId)?.connection !== pc) return
2119
+ log(`[webrtc] ice gathering to ${remotePeerId}: ${pc.iceGatheringState}`)
2120
+ }
2121
+
2122
+ pc.onsignalingstatechange = () => {
2123
+ const current = mesh.connections.get(remotePeerId)
2124
+ if (current?.connection !== pc || pc.signalingState !== 'have-local-offer') return
2125
+ const pending = pendingAnswers.get(remotePeerId)
2126
+ if (!pending?.sdp || (pending.connection && pending.connection !== pc)) return
2127
+ Promise.resolve().then(() => {
2128
+ const latest = pendingAnswers.get(remotePeerId)
2129
+ if (!latest?.sdp || (latest.connection && latest.connection !== pc)) return
2130
+ handleIncomingAnswer(remotePeerId, latest.sdp, latest.sessionId)
2131
+ }).catch(() => {})
2132
+ }
2133
+
2134
+ pc.ondatachannel = (event) => {
2135
+ const current = mesh.connections.get(remotePeerId)
2136
+ if (current?.connection !== pc) {
2137
+ try { event.channel?.close?.() } catch {}
2138
+ return
2139
+ }
2140
+ // Glare leaves BOTH peers with a channel on this connection: the one
2141
+ // each created for its own offer, and the one the other created. SCTP
2142
+ // opens both once the winning offer connects. The two peers must keep
2143
+ // the SAME channel — keeping "the one that arrived last" made each
2144
+ // side close exactly the channel the other side was using, and the
2145
+ // close was read as transport death: connect, teardown, redial, glare
2146
+ // again, until quarantine. The impolite peer's channel wins on both
2147
+ // sides, matching the offer that won.
2148
+ const local = current.channel
2149
+ // The rule held only while the local channel was still 'connecting'.
2150
+ // On one host SCTP opens both channels within milliseconds, so the
2151
+ // local one was often already OPEN when the remote's arrived; the
2152
+ // rule was skipped, the remote channel simply replaced the entry's,
2153
+ // and each side ended up owning the channel the OTHER side had
2154
+ // created — every app frame then arrived on a non-owning channel and
2155
+ // was dropped, the PeerPigeon handshake never completed, the stalled-
2156
+ // negotiation watchdog executed the peer, and the pair looped. The
2157
+ // rule now applies to any live local channel.
2158
+ if (local && local !== event.channel && local.readyState !== 'closed' && local.readyState !== 'closing') {
2159
+ const polite = String(peerId) > String(remotePeerId)
2160
+ if (!polite) {
2161
+ log(`[webrtc] duplicate data channel from ${remotePeerId} closed; keeping the local one (impolite peer)`)
2162
+ try { event.channel?.close?.() } catch {}
2163
+ return
2164
+ }
2165
+ log(`[webrtc] local data channel to ${remotePeerId} withdrawn for the remote one (polite peer)`)
2166
+ // Adopt first, withdraw second: whoever watches the entry sees the
2167
+ // old channel close while it is no longer the entry's, so the
2168
+ // withdrawal is not read as the transport dying.
2169
+ current.channel = null
2170
+ attachDataChannelHandlers(event.channel, remotePeerId, pc)
2171
+ try { local.close() } catch {}
2172
+ if (event.channel.readyState === 'open') {
2173
+ // Already open: its onopen will never fire again, so state the
2174
+ // usable boundary now for whoever waits on it.
2175
+ onConnectionStateChangeCb?.({ peerId: remotePeerId, state: 'connected', ts: Date.now() })
2176
+ }
2177
+ return
2178
+ }
2179
+ attachDataChannelHandlers(event.channel, remotePeerId, pc)
2180
+ }
2181
+
2182
+ return pc
2183
+ }
2184
+
2185
+ async function initiateWebRTCConnection(toPeerId, iceServers = null) {
2186
+ return enqueuePeerNegotiation(
2187
+ toPeerId,
2188
+ () => initiateWebRTCConnectionLocked(toPeerId, iceServers),
2189
+ )
2190
+ }
2191
+
2192
+ async function initiateWebRTCConnectionLocked(toPeerId, iceServers = null) {
2193
+ const priorEntry = mesh.connections.get(toPeerId)
2194
+ const prior = priorEntry?.connection
2195
+
2196
+ if (priorEntry?.relayed && priorEntry.channel?.readyState === 'open') return prior
2197
+ // Dialing again after an attempt that never opened: that one failed,
2198
+ // however it ended (ICE, an unanswered offer, the host giving up on it).
2199
+ const priorStillTrying = Boolean(prior && prior.signalingState !== 'closed' && priorEntry?.state !== 'dead'
2200
+ && priorEntry?.channel?.readyState !== 'open')
2201
+ const lastDial = dialAttempts.get(toPeerId)
2202
+ if (lastDial && !priorStillTrying && Date.now() - lastDial >= RELAYED_LINK_STALL_MS) {
2203
+ noteLinkFailure(toPeerId, 'never opened')
2204
+ dialAttempts.delete(toPeerId)
2205
+ }
2206
+ if (wantsRelayedLink(toPeerId) && !priorStillTrying) {
2207
+ dialAttempts.delete(toPeerId)
2208
+ return openRelayedLink(toPeerId)
2209
+ }
2210
+ if (priorEntry?.channel?.readyState !== 'open' && !dialAttempts.has(toPeerId)) dialAttempts.set(toPeerId, Date.now())
2211
+
2212
+ // Don't dial over a connection that is already open OR still being
2213
+ // made. Closing a prior that was mid-negotiation — the remote's offer
2214
+ // answered, ICE checking, channel opening — replaced it with our own
2215
+ // offer, which the remote (already holding that live connection) never
2216
+ // answered; our retries exhausted, marked the peer dead, and tore down
2217
+ // the connection the remote had just completed. Only a prior that is
2218
+ // failed, closed or dead is replaced.
2219
+ if (priorEntry?.channel?.readyState === 'open') {
2220
+ return prior
2221
+ }
2222
+ if (prior && prior.signalingState !== 'closed') {
2223
+ const progressing = priorEntry?.state !== 'dead'
2224
+ && prior.connectionState !== 'failed'
2225
+ && prior.connectionState !== 'closed'
2226
+ && (prior.connectionState === 'connected'
2227
+ || prior.connectionState === 'connecting'
2228
+ || prior.signalingState === 'have-remote-offer'
2229
+ || Boolean(prior.remoteDescription))
2230
+ if (progressing) {
2231
+ log(`[webrtc] not dialing ${toPeerId}: a connection is already in progress`)
2232
+ return prior
2233
+ }
2234
+ try {
2235
+ prior.close()
2236
+ } catch {}
2237
+ mesh.connections.delete(toPeerId)
2238
+ }
2239
+
2240
+ const effectiveIceServers = resolveIceServers(iceServers)
2241
+ const pc = createPeerConnection(toPeerId, effectiveIceServers, (type, body) => {
2242
+ relaySignal(toPeerId, type, body)
2243
+ })
2244
+
2245
+ const dc = pc.createDataChannel('mesh')
2246
+ attachDataChannelHandlers(dc, toPeerId, pc)
2247
+
2248
+ // New dial attempt gets a fresh signaling session.
2249
+ const activeSessionId = rotateSessionId(toPeerId)
2250
+
2251
+ const offer = await pc.createOffer()
2252
+ await pc.setLocalDescription(offer)
2253
+
2254
+ // If an answer arrived before we reached have-local-offer, apply it now.
2255
+ const pendingAnswer = pendingAnswers.get(toPeerId)
2256
+ if (
2257
+ pendingAnswer?.sdp
2258
+ && pendingAnswer?.sessionId === activeSessionId
2259
+ && (!pendingAnswer.connection || pendingAnswer.connection === pc)
2260
+ ) {
2261
+ const current = mesh.connections.get(toPeerId)?.connection
2262
+ if (current === pc && pc.signalingState === 'have-local-offer') {
2263
+ await applyIncomingAnswer(toPeerId, pendingAnswer.sdp, pendingAnswer.sessionId)
2264
+ }
2265
+ }
2266
+ if (!trickleIce) await waitForIceGatheringComplete(pc)
2267
+
2268
+ relaySignal(toPeerId, 'offer', {
2269
+ sdp: pc.localDescription?.sdp ?? offer.sdp,
2270
+ trickle_ice: Boolean(trickleIce),
2271
+ })
2272
+
2273
+ let retryIndex = 0
2274
+ const retryOffer = () => {
2275
+ pc.__offerRetryTimer = null
2276
+ if (mesh.connections.get(toPeerId)?.connection !== pc) return
2277
+ if (pc.signalingState === 'closed' || pc.remoteDescription) {
2278
+ clearOfferRetryTimer(pc)
2279
+ return
2280
+ }
2281
+ if (pc.signalingState !== 'have-local-offer') {
2282
+ clearOfferRetryTimer(pc)
2283
+ return
2284
+ }
2285
+ if (retryIndex >= OFFER_RETRY_DELAYS_MS.length) {
2286
+ clearOfferRetryTimer(pc)
2287
+ log(`[webrtc] offer to ${toPeerId} timed out after ${retryIndex} retries; giving up`)
2288
+ notifyNegotiationFailure({
2289
+ peerId: toPeerId,
2290
+ reason: 'offer_retries_exhausted',
2291
+ retryCount: retryIndex,
2292
+ signalingState: pc.signalingState,
2293
+ connectionState: pc.connectionState,
2294
+ })
2295
+ try { pc.close() } catch {}
2296
+ mesh.markDead(toPeerId)
2297
+ return
2298
+ }
2299
+ retryIndex += 1
2300
+ relaySignal(toPeerId, 'offer', {
2301
+ sdp: pc.localDescription?.sdp ?? offer.sdp,
2302
+ trickle_ice: Boolean(trickleIce),
2303
+ })
2304
+ const nextDelayMs = OFFER_RETRY_DELAYS_MS[Math.min(
2305
+ retryIndex,
2306
+ OFFER_RETRY_DELAYS_MS.length - 1,
2307
+ )]
2308
+ pc.__offerRetryTimer = setTimeout(retryOffer, nextDelayMs)
2309
+ }
2310
+
2311
+ pc.__resetOfferRetryBackoff = () => {
2312
+ clearOfferRetryTimer(pc)
2313
+ if (mesh.connections.get(toPeerId)?.connection !== pc) return
2314
+ if (
2315
+ pc.signalingState !== 'have-local-offer'
2316
+ || pc.remoteDescription
2317
+ ) return
2318
+ retryIndex = 0
2319
+ relaySignal(toPeerId, 'offer', {
2320
+ sdp: pc.localDescription?.sdp ?? offer.sdp,
2321
+ trickle_ice: Boolean(trickleIce),
2322
+ })
2323
+ pc.__offerRetryTimer = setTimeout(retryOffer, OFFER_RETRY_DELAYS_MS[0])
2324
+ }
2325
+
2326
+ pc.__offerRetryTimer = setTimeout(retryOffer, OFFER_RETRY_DELAYS_MS[retryIndex])
2327
+ return pc
2328
+ }
2329
+
2330
+ async function handleIncomingOffer(fromPeerId, offer) {
2331
+ return enqueuePeerNegotiation(fromPeerId, async () => {
2332
+ const sendRelay = (type, body) => {
2333
+ relaySignal(fromPeerId, type, body)
2334
+ }
2335
+
2336
+ const existingEntry = mesh.connections.get(fromPeerId)
2337
+
2338
+ // Already connected. A retry of the offer we answered just needs that
2339
+ // answer again so the remote's retry timer can stop; the live
2340
+ // connection stays. But an offer with NEW ICE credentials on a channel
2341
+ // that still looks open means the other side has lost its end and is
2342
+ // dialing afresh. Our end is dead too, our keepalive just has not said
2343
+ // so yet; ignoring the offer (or answering it with the cached answer
2344
+ // for a connection that no longer exists over there) left the two
2345
+ // sides deaf to each other for twenty seconds, then redialing — the
2346
+ // churn a watcher sees every time a browser wakes. Replace the
2347
+ // connection and answer the new offer.
2348
+ if (existingEntry?.channel?.readyState === 'open') {
2349
+ const openRemoteSdp = existingEntry.lastRemoteOfferSdp
2350
+ ?? existingEntry.connection?.remoteDescription?.sdp
2351
+ ?? null
2352
+ const freshUfrag = iceUfragOf(offer?.sdp ?? null)
2353
+ const openUfrag = iceUfragOf(openRemoteSdp)
2354
+ const sameNegotiation = !freshUfrag || !openUfrag || freshUfrag === openUfrag
2355
+ if (sameNegotiation) {
2356
+ if (existingEntry.lastLocalAnswer) {
2357
+ sendRelay('answer', existingEntry.lastLocalAnswer)
2358
+ }
2359
+ return
2360
+ }
2361
+ log(`[webrtc] fresh offer from ${fromPeerId} (ufrag ${openUfrag} → ${freshUfrag}) on an open channel; the remote restarted, replacing the connection`)
2362
+ const openPc = existingEntry.connection
2363
+ if (openPc) clearOfferRetryTimer(openPc)
2364
+ clearAnswerBurst(fromPeerId)
2365
+ pendingCandidates.delete(fromPeerId)
2366
+ pendingAnswers.delete(fromPeerId)
2367
+ mesh.connections.delete(fromPeerId)
2368
+ try { openPc?.close() } catch {}
2369
+ }
2370
+
2371
+ // If the existing connection is dead/failed (but signalingState not yet
2372
+ // 'closed' because we never called pc.close() on failure), close it now
2373
+ // and start a fresh RTCPeerConnection. Reusing a failed pc causes ICE
2374
+ // re-gathering to run on a broken transport, which never recovers.
2375
+ const existing = existingEntry?.connection
2376
+ if (
2377
+ existing &&
2378
+ existing.signalingState !== 'closed' &&
2379
+ (existing.connectionState === 'failed' ||
2380
+ existing.connectionState === 'closed' ||
2381
+ existingEntry?.state === 'dead')
2382
+ ) {
2383
+ try { existing.close() } catch {}
2384
+ mesh.connections.delete(fromPeerId)
2385
+ clearAnswerBurst(fromPeerId)
2386
+ pendingCandidates.delete(fromPeerId)
2387
+ }
2388
+
2389
+ const freshEntry = mesh.connections.get(fromPeerId)
2390
+ let pc =
2391
+ freshEntry?.connection && freshEntry.connection.signalingState !== 'closed'
2392
+ ? freshEntry.connection
2393
+ : createPeerConnection(fromPeerId, resolveIceServers(freshEntry?.iceServers), sendRelay)
2394
+
2395
+ let entry = mesh.connections.get(fromPeerId)
2396
+ const incomingOfferSdp = offer?.sdp ?? null
2397
+ const cachedAnswer = entry?.lastLocalAnswer ?? null
2398
+ const currentRemoteOfferSdp = entry?.lastRemoteOfferSdp ?? pc.remoteDescription?.sdp ?? null
2399
+ const now = Date.now()
2400
+ const recent = recentOfferSdp.get(fromPeerId)
2401
+
2402
+ if (
2403
+ incomingOfferSdp &&
2404
+ recent?.sdp === incomingOfferSdp &&
2405
+ now - recent.ts < SDP_DEDUP_WINDOW_MS
2406
+ ) {
2407
+ if (cachedAnswer) {
2408
+ startAnswerBurst(fromPeerId, pc, sendRelay, cachedAnswer)
2409
+ }
2410
+ return
2411
+ }
2412
+
2413
+ if (
2414
+ incomingOfferSdp &&
2415
+ cachedAnswer &&
2416
+ currentRemoteOfferSdp === incomingOfferSdp
2417
+ ) {
2418
+ // Duplicate offer for same SDP: do not renegotiate repeatedly.
2419
+ // Re-send cached answer at most once per cooldown window.
2420
+ const shouldResend = Date.now() - (entry?.lastAnswerSentAt ?? 0) > ANSWER_BURST_COOLDOWN_MS
2421
+ if (shouldResend) {
2422
+ entry.lastAnswerSentAt = Date.now()
2423
+ sendRelay('answer', cachedAnswer)
2424
+ }
2425
+ return
2426
+ }
2427
+
2428
+ // The SAME offer, retried. An offer is re-sent on a short burst, and
2429
+ // each retry carries the local description as it stands — with the
2430
+ // candidates gathered since the last send — so the text differs while
2431
+ // the negotiation is the same one. Treating that as a renewed offer
2432
+ // re-answered it with fresh ICE credentials on this side while the
2433
+ // other side had already applied the first answer: every connectivity
2434
+ // check then carried a username the receiver no longer recognized, and
2435
+ // the handshake died on both sides. Two peers that discover each other
2436
+ // at the same instant hit this on every attempt. The ICE ufrag names
2437
+ // the negotiation: same ufrag, same offer — take its new candidates
2438
+ // and re-send the answer already given.
2439
+ const incomingUfrag = iceUfragOf(incomingOfferSdp)
2440
+ if (
2441
+ incomingOfferSdp &&
2442
+ cachedAnswer &&
2443
+ currentRemoteOfferSdp &&
2444
+ currentRemoteOfferSdp !== incomingOfferSdp &&
2445
+ incomingUfrag &&
2446
+ incomingUfrag === iceUfragOf(currentRemoteOfferSdp)
2447
+ ) {
2448
+ const known = new Set(candidateLinesOf(currentRemoteOfferSdp))
2449
+ for (const line of candidateLinesOf(incomingOfferSdp)) {
2450
+ if (known.has(line)) continue
2451
+ const candidate = line.replace(/^a=/, '')
2452
+ await pc.addIceCandidate({ candidate, sdpMid: '0', sdpMLineIndex: 0 }).catch(() => {})
2453
+ }
2454
+ if (entry) entry.lastRemoteOfferSdp = incomingOfferSdp
2455
+ recentOfferSdp.set(fromPeerId, { sdp: incomingOfferSdp, ts: now })
2456
+ if (Date.now() - (entry?.lastAnswerSentAt ?? 0) > ANSWER_BURST_COOLDOWN_MS) {
2457
+ if (entry) entry.lastAnswerSentAt = Date.now()
2458
+ sendRelay('answer', cachedAnswer)
2459
+ }
2460
+ log(`[webrtc] retried offer from ${fromPeerId} (same ufrag); answered again, no renegotiation`)
2461
+ return
2462
+ }
2463
+
2464
+ if (
2465
+ incomingOfferSdp &&
2466
+ pc.remoteDescription &&
2467
+ currentRemoteOfferSdp &&
2468
+ currentRemoteOfferSdp !== incomingOfferSdp
2469
+ ) {
2470
+ const currentUfrag = iceUfragOf(currentRemoteOfferSdp)
2471
+ const channelOpen = entry?.channel?.readyState === 'open'
2472
+ if (!channelOpen && incomingUfrag && currentUfrag && incomingUfrag !== currentUfrag) {
2473
+ // A different ufrag is a different negotiation: the other peer
2474
+ // gave up on the last one and started over with fresh ICE
2475
+ // credentials. Applying that offer to the unfinished connection
2476
+ // as a "renewal" left this side checking with the old password —
2477
+ // every STUN response then failed its integrity check on both
2478
+ // machines, and two watchers on one LAN sat at 'connecting' for
2479
+ // hours. An unfinished connection is replaced; only a connection
2480
+ // with an open channel is renegotiated in place.
2481
+ log(`[webrtc] new negotiation from ${fromPeerId} (ufrag ${currentUfrag} → ${incomingUfrag}); replacing the unfinished connection`)
2482
+ clearOfferRetryTimer(pc)
2483
+ clearAnswerBurst(fromPeerId)
2484
+ pendingCandidates.delete(fromPeerId)
2485
+ try { pc.close() } catch {}
2486
+ mesh.connections.delete(fromPeerId)
2487
+ pc = createPeerConnection(fromPeerId, resolveIceServers(entry?.iceServers), sendRelay)
2488
+ entry = mesh.connections.get(fromPeerId)
2489
+ } else {
2490
+ // A new SDP with the same credentials, or one arriving on a
2491
+ // connection whose channel is already open, is a normal ICE
2492
+ // renegotiation on the existing connection.
2493
+ log(`[webrtc] applying renewed offer from ${fromPeerId} to existing connection`)
2494
+ }
2495
+ }
2496
+
2497
+ if (pc.signalingState === 'closed') return
2498
+
2499
+ const offerCollision = pc.signalingState !== 'stable'
2500
+ if (offerCollision) {
2501
+ // Both peers derive opposite roles from the stable peer IDs. The
2502
+ // lexically later peer is polite and rolls back; the earlier peer
2503
+ // keeps its local offer. Exactly one offer therefore wins glare.
2504
+ const polite = String(peerId) > String(fromPeerId)
2505
+ if (!polite) {
2506
+ log(`[webrtc] ignoring colliding offer from ${fromPeerId} (impolite peer)`)
2507
+ return
2508
+ }
2509
+ if (pc.signalingState !== 'have-local-offer') {
2510
+ log(`[webrtc] ignoring colliding offer from ${fromPeerId} (state=${pc.signalingState})`)
2511
+ return
2512
+ }
2513
+ clearOfferRetryTimer(pc)
2514
+ pendingAnswers.delete(fromPeerId)
2515
+ await pc.setLocalDescription({ type: 'rollback' })
2516
+ log(`[webrtc] rolled back local offer for ${fromPeerId} (polite peer)`)
2517
+ withdrawChannelOfRolledBackOffer(fromPeerId, pc)
2518
+ }
2519
+
2520
+ try {
2521
+ await pc.setRemoteDescription(offer)
2522
+ } catch (error) {
2523
+ const message = String(error?.message || error || '')
2524
+ const isRtpExtensionRemap = error?.name === 'InvalidAccessError'
2525
+ && /remap RTP extension id/i.test(message)
2526
+ if (!isRtpExtensionRemap) throw error
2527
+
2528
+ const replacementIceServers = resolveIceServers(entry?.iceServers)
2529
+ clearOfferRetryTimer(pc)
2530
+ try { pc.close() } catch {}
2531
+ if (mesh.connections.get(fromPeerId)?.connection === pc) {
2532
+ mesh.connections.delete(fromPeerId)
2533
+ }
2534
+ clearAnswerBurst(fromPeerId)
2535
+ pc = createPeerConnection(fromPeerId, replacementIceServers, sendRelay)
2536
+ entry = mesh.connections.get(fromPeerId)
2537
+ log(`[webrtc] retrying offer from ${fromPeerId} on fresh connection after RTP extension remap`)
2538
+ await pc.setRemoteDescription(offer)
2539
+ }
2540
+
2541
+ if (entry) {
2542
+ entry.lastRemoteOfferSdp = incomingOfferSdp
2543
+ }
2544
+
2545
+ const queued = pendingCandidates.get(fromPeerId) ?? []
2546
+ pendingCandidates.delete(fromPeerId)
2547
+ for (const candidate of queued) {
2548
+ await pc.addIceCandidate(candidate).catch(() => {})
2549
+ }
2550
+
2551
+ const answer = await pc.createAnswer()
2552
+ if (pc.signalingState === 'closed') return
2553
+ await pc.setLocalDescription(answer)
2554
+ if (!trickleIce) await waitForIceGatheringComplete(pc)
2555
+ const finalAnswerSdp = pc.localDescription?.sdp ?? answer.sdp
2556
+ if (entry) {
2557
+ entry.lastLocalAnswer = {
2558
+ sdp: finalAnswerSdp,
2559
+ trickle_ice: Boolean(trickleIce),
2560
+ }
2561
+ }
2562
+ if (incomingOfferSdp) {
2563
+ recentOfferSdp.set(fromPeerId, { sdp: incomingOfferSdp, ts: Date.now() })
2564
+ }
2565
+ startAnswerBurst(fromPeerId, pc, sendRelay, {
2566
+ sdp: finalAnswerSdp,
2567
+ trickle_ice: Boolean(trickleIce),
2568
+ }, true)
2569
+ }).catch((err) => {
2570
+ log(`[webrtc] handleIncomingOffer failed: ${err}`)
2571
+ })
2572
+ }
2573
+
2574
+ async function applyIncomingAnswer(fromPeerId, incomingAnswerSdp, sessionId) {
2575
+ const expectedSessionId = roomId
2576
+ if (expectedSessionId && sessionId && sessionId !== expectedSessionId) {
2577
+ log(`[webrtc] ignoring answer from ${fromPeerId} (stale session)`)
2578
+ return
2579
+ }
2580
+
2581
+ const conn = mesh.connections.get(fromPeerId)
2582
+ if (!conn?.connection) {
2583
+ pendingAnswers.set(fromPeerId, {
2584
+ sdp: incomingAnswerSdp,
2585
+ sessionId,
2586
+ ts: Date.now(),
2587
+ connection: null,
2588
+ })
2589
+ log(`[webrtc] queued answer from ${fromPeerId} (no connection yet)`)
2590
+ return
2591
+ }
2592
+
2593
+ const now = Date.now()
2594
+ const recent = recentAnswerSdp.get(fromPeerId)
2595
+ if (recent?.sdp === incomingAnswerSdp && now - recent.ts < SDP_DEDUP_WINDOW_MS) {
2596
+ log(`[webrtc] duplicate answer from ${fromPeerId} already applied (dedup window)`)
2597
+ return
2598
+ }
2599
+ if (conn.lastAppliedAnswerSdp === incomingAnswerSdp) {
2600
+ log(`[webrtc] duplicate answer from ${fromPeerId} already applied`)
2601
+ return
2602
+ }
2603
+
2604
+ const pc = conn.connection
2605
+ if (pc.signalingState !== 'have-local-offer') {
2606
+ const peerIsIsolated = conn.channel?.readyState !== 'open'
2607
+ if (peerIsIsolated) {
2608
+ pendingAnswers.set(fromPeerId, {
2609
+ sdp: incomingAnswerSdp,
2610
+ sessionId,
2611
+ ts: Date.now(),
2612
+ connection: pc,
2613
+ })
2614
+ log(`[webrtc] queued answer from ${fromPeerId} (state=${pc.signalingState}; peer isolated)`)
2615
+ return
2616
+ }
2617
+ log(`[webrtc] ignoring stale answer from connected peer ${fromPeerId} (state=${pc.signalingState})`)
2618
+ return
2619
+ }
2620
+
2621
+ await pc.setRemoteDescription({ type: 'answer', sdp: incomingAnswerSdp })
2622
+ log(`[webrtc] applied answer from ${fromPeerId}`)
2623
+ conn.lastAppliedAnswerSdp = incomingAnswerSdp
2624
+ recentAnswerSdp.set(fromPeerId, { sdp: incomingAnswerSdp, ts: Date.now() })
2625
+ pendingAnswers.delete(fromPeerId)
2626
+ clearOfferRetryTimer(pc)
2627
+
2628
+ const queued = pendingCandidates.get(fromPeerId) ?? []
2629
+ pendingCandidates.delete(fromPeerId)
2630
+ for (const candidate of queued) {
2631
+ await pc.addIceCandidate(candidate).catch(() => {})
2632
+ }
2633
+ }
2634
+
2635
+ async function handleIncomingAnswer(fromPeerId, incomingAnswerSdp, sessionId) {
2636
+ return enqueuePeerNegotiation(
2637
+ fromPeerId,
2638
+ () => applyIncomingAnswer(fromPeerId, incomingAnswerSdp, sessionId),
2639
+ ).catch((err) => {
2640
+ log(`[webrtc] setRemoteDescription(answer) failed: ${err}`)
2641
+ })
2642
+ }
2643
+
2644
+ function closePeerConnection(remotePeerId, reason = 'local_close', notifyRemote = true) {
2645
+ const id = String(remotePeerId || '').trim()
2646
+ if (!id) return false
2647
+ const entry = mesh.connections.get(id)
2648
+
2649
+ // Tell the other owner first so it cancels offer retries and cannot revive
2650
+ // an edge that this side intentionally shed for capacity/topology reasons.
2651
+ //
2652
+ // The bye goes over the mesh when it can, and the mesh route is often this
2653
+ // very edge. It used to be closed in the next line, before the frame was
2654
+ // flushed: the other side never heard, kept the edge open, and everything
2655
+ // it sent into it vanished (one-sided links; routed direct messages lost).
2656
+ // Now the bye also goes on the edge's own channel, and the edge closes a
2657
+ // moment later, so both copies are out first.
2658
+ let byeOnChannel = false
2659
+ if (notifyRemote) {
2660
+ if (entry?.channel?.readyState === 'open') {
2661
+ try {
2662
+ entry.channel.send(JSON.stringify({ type: DATA_BYE_FRAME, reason }))
2663
+ byeOnChannel = true
2664
+ } catch {}
2665
+ }
2666
+ if (registered) relaySignal(id, 'bye', { reason })
2667
+ }
2668
+
2669
+ if (!entry) return false
2670
+ mesh.connections.delete(id)
2671
+ clearOfferRetryTimer(entry.connection)
2672
+ clearAnswerBurst(id)
2673
+ pendingCandidates.delete(id)
2674
+ pendingAnswers.delete(id)
2675
+ offerProcessingQueues.delete(id)
2676
+ const closeTransport = () => {
2677
+ try { entry.channel?.close?.() } catch {}
2678
+ try { entry.connection?.close?.() } catch {}
2679
+ }
2680
+ if (byeOnChannel) setTimeout(closeTransport, DATA_BYE_FLUSH_MS)
2681
+ else closeTransport()
2682
+ return true
2683
+ }
2684
+
2685
+ async function handleSignalingMessage(rawMsg) {
2686
+ const fromPeerId = rawMsg.from
2687
+ log(`[signal] incoming ${rawMsg.type} from ${fromPeerId}`)
2688
+
2689
+ try { onIncomingRelay?.(rawMsg) } catch { /* never let app callback abort signaling */ }
2690
+
2691
+ const msg = rawMsg
2692
+
2693
+ if (msg.session_id !== roomId) {
2694
+ log(`[signal] ignoring ${msg.type} from ${fromPeerId} (different room)`)
2695
+ return
2696
+ }
2697
+
2698
+ const conn = mesh.connections.get(fromPeerId)
2699
+ if (
2700
+ !conn &&
2701
+ (msg.type === 'offer' || msg.type === 'answer' || msg.type === 'ice_candidate' || msg.type === 'renegotiate')
2702
+ ) {
2703
+ onConnectionStateChangeCb?.({ peerId: fromPeerId, state: 'connecting', ts: Date.now() })
2704
+ }
2705
+ if (conn) {
2706
+ conn.lastSeen = Date.now()
2707
+ if (conn.state !== 'connected') conn.state = 'connecting'
2708
+ }
2709
+
2710
+ switch (msg.type) {
2711
+ case 'offer':
2712
+ setSessionId(fromPeerId, msg.session_id)
2713
+ handleIncomingOffer(fromPeerId, { type: 'offer', sdp: msg.body.sdp }).catch((err) => {
2714
+ log(`[webrtc] handleIncomingOffer failed: ${err}`)
2715
+ })
2716
+ break
2717
+
2718
+ case 'answer':
2719
+ if (msg.body?.sdp) {
2720
+ handleIncomingAnswer(fromPeerId, msg.body.sdp, msg.session_id ?? null)
2721
+ }
2722
+ break
2723
+
2724
+ case 'ice_candidate': {
2725
+ const c = msg.body?.candidate
2726
+ if (!c) break
2727
+ const expectedSessionId = roomId
2728
+ if (expectedSessionId && msg.session_id && msg.session_id !== expectedSessionId) {
2729
+ log(`[webrtc] ignoring candidate from ${fromPeerId} (stale session)`)
2730
+ break
2731
+ }
2732
+ log(`[webrtc] remote candidate from ${fromPeerId}`)
2733
+ if (conn?.connection) {
2734
+ if (conn.connection.signalingState === 'closed') break
2735
+ if (conn.connection.remoteDescription) {
2736
+ conn.connection.addIceCandidate(c).catch((err) => {
2737
+ log(`[webrtc] addIceCandidate failed: ${err}`)
2738
+ })
2739
+ } else {
2740
+ if (!pendingCandidates.has(fromPeerId)) pendingCandidates.set(fromPeerId, [])
2741
+ pendingCandidates.get(fromPeerId).push(c)
2742
+ }
2743
+ } else {
2744
+ if (!pendingCandidates.has(fromPeerId)) pendingCandidates.set(fromPeerId, [])
2745
+ pendingCandidates.get(fromPeerId).push(c)
2746
+ }
2747
+ break
2748
+ }
2749
+
2750
+ case 'ice_end':
2751
+ // Remote ICE gathering complete; no further candidates will arrive.
2752
+ break
2753
+
2754
+ case 'bye':
2755
+ closePeerConnection(fromPeerId, msg.body?.reason || 'remote_close', false)
2756
+ onConnectionStateChangeCb?.({
2757
+ peerId: fromPeerId,
2758
+ state: 'closed',
2759
+ reason: msg.body?.reason || 'remote_close',
2760
+ ts: Date.now(),
2761
+ })
2762
+ break
2763
+
2764
+ case 'renegotiate': {
2765
+ if (msg.body?.sdp) {
2766
+ handleIncomingOffer(fromPeerId, { type: 'offer', sdp: msg.body.sdp }).catch((err) => {
2767
+ log(`[webrtc] renegotiate failed: ${err}`)
2768
+ })
2769
+ }
2770
+ break
2771
+ }
2772
+ }
2773
+ }
2774
+
2775
+ function handleMessage(msg) {
2776
+ const completeRegistration = (registrationMessage, source = 'ack') => {
2777
+ if (registered) return
2778
+ registered = true
2779
+ setStatus('registered')
2780
+ log(`[signal] registered as ${peerId} on network ${networkId} (${source})`)
2781
+ startAdvertiseHeartbeat()
2782
+ onRegistered?.(registrationMessage)
2783
+ if (relayMode === 'on-demand') notifyRelayState('up')
2784
+ // A discovery asked for while the relay was released goes out now that it is back.
2785
+ if (pendingBootstrapPeerIds) {
2786
+ const exclude = pendingBootstrapPeerIds
2787
+ pendingBootstrapPeerIds = null
2788
+ client.requestBootstrap(exclude)
2789
+ }
2790
+ }
2791
+
2792
+ switch (msg.type) {
2793
+ case 'ack':
2794
+ if (msg.body?.status === 'ok') completeRegistration(msg)
2795
+ break
2796
+
2797
+ case 'peer_list': {
2798
+ // Older FreeRTC relays broadcast a scoped peer_list after accepting an
2799
+ // announcement but did not send the explicit ACK. Receiving that list
2800
+ // proves registration and keeps new clients compatible with them.
2801
+ completeRegistration(msg, 'peer_list')
2802
+ const rawPeers = msg.body?.peers ?? []
2803
+ if (rawPeers.length !== lastBootstrapCountLogged) {
2804
+ lastBootstrapCountLogged = rawPeers.length
2805
+ log(`[signal] received ${rawPeers.length} peer_list candidates`)
2806
+ }
2807
+ const candidates = rawPeers.map((p) => ({
2808
+ peerId: p.peer_id,
2809
+ networkId: p.network ?? networkId,
2810
+ // What the peer said it is (its announce's capabilities.role), as the relay lists it.
2811
+ capabilities: p.role ? { ...(p.hints ?? {}), role: p.role } : (p.hints ?? {}),
2812
+ role: p.role ?? null,
2813
+ advertisedAt: p.last_seen ?? p.timestamp ?? Date.now(),
2814
+ // When the relay sent this list, on the relay's clock: the age of an
2815
+ // advertisement is judged on one clock, not across two machines.
2816
+ listedAt: Number(msg.timestamp) || null,
2817
+ advisory: true,
2818
+ localSeenAt: Date.now(),
2819
+ }))
2820
+ candidates.forEach((c) => mesh.addCandidate(c))
2821
+ onBootstrap?.(candidates)
2822
+ break
2823
+ }
2824
+
2825
+ case 'offer':
2826
+ case 'answer':
2827
+ case 'ice_candidate':
2828
+ case 'ice_end':
2829
+ case 'bye':
2830
+ case 'renegotiate':
2831
+ handleSignalingMessage(msg).catch((err) => log(`[signal] handleSignalingMessage error: ${err}`))
2832
+ break
2833
+
2834
+ case 'ext':
2835
+ if (msg.body?.relay_response === true) {
2836
+ const pending = relayRequests.get(msg.body.request_id)
2837
+ if (pending) {
2838
+ relayRequests.delete(msg.body.request_id)
2839
+ clearTimeout(pending.timer)
2840
+ const { relay_response: _r, request_id: _id, ...result } = msg.body
2841
+ pending.resolve(result)
2842
+ }
2843
+ } else if (String(msg.body?.action ?? '').startsWith('link-')) handleLinkFrame(msg)
2844
+ break
2845
+
2846
+ case 'pong':
2847
+ lastSignalPongAt = Date.now()
2848
+ lastSignalPingSentAt = 0
2849
+ break
2850
+
2851
+ case 'error':
2852
+ log(`[signal] error: ${msg.body?.code} — ${msg.body?.reason}`)
2853
+ if (msg.body?.code === 'target_not_connected') {
2854
+ log('[signal] target unavailable for relay (offline/disconnected/or other isolate)')
2855
+ // Named peer: no relay has it. Forget it and stop negotiating with it.
2856
+ const gonePeerId = typeof msg.body?.peer_id === 'string' ? msg.body.peer_id : null
2857
+ if (gonePeerId && gonePeerId !== peerId) {
2858
+ mesh.bootstrapCandidates = mesh.bootstrapCandidates.filter((c) => c.peerId !== gonePeerId)
2859
+ const conn = mesh.connections.get(gonePeerId)
2860
+ const channelOpen = conn?.dc?.readyState === 'open' || conn?.channel?.readyState === 'open'
2861
+ if (conn && !channelOpen) closePeerConnection(gonePeerId, 'peer_gone', false)
2862
+ try { onPeerGone?.({ peerId: gonePeerId }) } catch { /* consumer error */ }
2863
+ }
2864
+ }
2865
+ break
2866
+
2867
+ default:
2868
+ log(`[signal] unknown message type: ${msg.type}`)
2869
+ }
2870
+ }
2871
+
2872
+ function openSocket() {
2873
+ if (stoppedByUser) return
2874
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
2875
+ return
2876
+ }
2877
+
2878
+ // Any real open, whoever asked for it (a wake, a resume, a visibility change), ends the idle
2879
+ // state; the next evaluation decides afresh whether the socket is still needed.
2880
+ relayIdle = false
2881
+
2882
+ const wsUrl = new URL(signalUrl, typeof location !== 'undefined' ? location.href : undefined)
2883
+ if (!wsUrl.searchParams.get('networkId')) {
2884
+ wsUrl.searchParams.set('networkId', networkId)
2885
+ }
2886
+ if (!wsUrl.searchParams.get('room')) {
2887
+ wsUrl.searchParams.set('room', roomId)
2888
+ }
2889
+
2890
+ setStatus('connecting')
2891
+ socketOpenStartedAt = Date.now()
2892
+ openedThisSocket = false
2893
+ ws = openRelaySocket(wsUrl.toString(), { punch: relayPunch, iceServers: preferredIceServers, log })
2894
+
2895
+ ws.onopen = () => {
2896
+ if (stoppedByUser) {
2897
+ try {
2898
+ ws?.close(1000, 'stopped')
2899
+ } catch {}
2900
+ return
2901
+ }
2902
+ intentionalClose = false
2903
+ openedThisSocket = true
2904
+ failedOpens = 0
2905
+ setStatus('connected')
2906
+ backoffMs = BACKOFF_BASE_MS
2907
+ reconnectAttempts = 0
2908
+ lastSignalPongAt = Date.now()
2909
+ lastSignalPingSentAt = 0
2910
+
2911
+ send(pspEnvelope('announce', {
2912
+ ttl_ms: 30000,
2913
+ body: {
2914
+ instance_id: networkId,
2915
+ capabilities,
2916
+ hints: { wants_peers: true },
2917
+ ...(auth ? { auth } : {}),
2918
+ },
2919
+ }))
2920
+ startKeepalive()
2921
+ }
2922
+
2923
+ ws.onmessage = (event) => {
2924
+ if (stoppedByUser) return
2925
+ let msg
2926
+ try {
2927
+ msg = JSON.parse(event.data)
2928
+ } catch {
2929
+ log('[signal] received non-JSON message')
2930
+ return
2931
+ }
2932
+ // Any valid relay message proves that the socket is alive, even if a
2933
+ // particular relay version does not emit explicit pong frames.
2934
+ lastSignalPongAt = Date.now()
2935
+ lastSignalPingSentAt = 0
2936
+ handleMessage(msg)
2937
+ }
2938
+
2939
+ ws.onclose = (event) => {
2940
+ if (!openedThisSocket) failedOpens += 1
2941
+ registered = false
2942
+ stopAdvertiseHeartbeat()
2943
+ stopKeepalive()
2944
+ setStatus(`disconnected (${event.code})`)
2945
+ const shouldReconnect = !stoppedByUser && !(intentionalClose && event.code === 1000)
2946
+ if (shouldReconnect) {
2947
+ scheduleReconnect(openSocket, event.code)
2948
+ }
2949
+ }
2950
+
2951
+ ws.onerror = () => {
2952
+ setStatus('error')
2953
+ }
2954
+ }
2955
+
2956
+ function relay(toPeerId, relayType, payload) {
2957
+ if (!registered) {
2958
+ log('[signal] not registered yet')
2959
+ return
2960
+ }
2961
+
2962
+ if (relayType === 'offer' || relayType === 'answer' || relayType === 'renegotiate') {
2963
+ log(`[signal] sending ${relayType} to ${toPeerId}`)
2964
+ }
2965
+
2966
+ send({
2967
+ type: 'relay',
2968
+ toPeerId,
2969
+ relayType,
2970
+ payload,
2971
+ fromPeerId: peerId,
2972
+ messageId: generateMessageId(),
2973
+ timestamp: Date.now(),
2974
+ })
2975
+ }
2976
+
2977
+ const unloadHandler = () => {
2978
+ client.disconnect()
2979
+ }
2980
+
2981
+ const pageHideHandler = (event) => {
2982
+ // A persisted pagehide is entering the back/forward cache rather than
2983
+ // being destroyed. Keep the identity announced and let pageshow rebuild
2984
+ // the transport if the browser closes it while the document is cached.
2985
+ if (event?.persisted) {
2986
+ handleFreeze()
2987
+ return
2988
+ }
2989
+ client.disconnect()
2990
+ }
2991
+
2992
+ function handleFreeze() {
2993
+ // A frozen page is suspended, not departed. Withdrawing here made relay
2994
+ // membership oscillate whenever Safari or a mobile browser throttled a
2995
+ // background tab. Actual teardown still withdraws through pagehide,
2996
+ // beforeunload, unload, and disconnect.
2997
+ // Mark all connected peers as recovering so they are re-verified on resume.
2998
+ for (const entry of mesh.connections.values()) {
2999
+ if (entry.state === 'connected') entry.state = 'recovering'
3000
+ }
3001
+ _releaseWakeLock()
3002
+ }
3003
+
3004
+ function handlePageShow(event) {
3005
+ // bfcache restore: the page is shown from the browser's back/forward cache.
3006
+ // The WebSocket is dead at this point — reconnect exactly as on freeze→resume.
3007
+ if (event.persisted) handleSuspendRestore()
3008
+ }
3009
+
3010
+ function resetReconnectBackoff() {
3011
+ clearTimeout(reconnectTimer)
3012
+ reconnectTimer = null
3013
+ backoffMs = BACKOFF_BASE_MS
3014
+ reconnectAttempts = 0
3015
+ }
3016
+
3017
+ function handleSuspendRestore(reason = 'browser_resume', gapMs = 0) {
3018
+ if (stoppedByUser) return
3019
+
3020
+ // A timer that fired late is not proof the machine slept: a busy process
3021
+ // (a hundred peers on one laptop) sees the same gap. Tearing everything
3022
+ // down then threw away working links and every peer reconnected at once,
3023
+ // which made the machine busier still. Check first: keep what is alive,
3024
+ // close what is dead, and ping the relay instead of replacing it. After
3025
+ // a real sleep the links are dead and are replaced just the same.
3026
+ if (reason === 'clock_jump' && gapMs < SLEEP_GAP_MS) {
3027
+ log(`[signal] timers ran ${Math.round(gapMs / 1000)}s late — checking links and relay instead of resetting them`)
3028
+ for (const [remotePeerId, entry] of [...mesh.connections.entries()]) {
3029
+ const state = entry?.connection?.connectionState
3030
+ if (state === 'failed' || state === 'closed' || entry?.channel?.readyState === 'closed') {
3031
+ closePeerConnection(remotePeerId, 'resume_dead', false)
3032
+ }
3033
+ }
3034
+ if (ws && ws.readyState === 1 && registered) {
3035
+ lastSignalPingSentAt = Date.now()
3036
+ send(pspEnvelope('ping', { body: { nonce: generateMessageId() } }))
3037
+ } else if (!ws || ws.readyState > 1) {
3038
+ resetReconnectBackoff()
3039
+ openSocket()
3040
+ }
3041
+ try { onResume?.({ reason, gapMs }) } catch { /* consumer error must not break resume */ }
3042
+ return
3043
+ }
3044
+
3045
+ log(reason === 'clock_jump'
3046
+ ? '[signal] resumed after suspend — reconnecting immediately'
3047
+ : '[signal] browser resumed — reconnecting immediately')
3048
+ resetReconnectBackoff()
3049
+
3050
+ // A socket can remain OPEN/CONNECTING briefly after the browser thaws even
3051
+ // though its underlying connection was lost. Retire it without letting its
3052
+ // eventual close schedule another retry, then establish a fresh socket now.
3053
+ const staleSocket = ws
3054
+ ws = null
3055
+ if (staleSocket) {
3056
+ staleSocket.onopen = null
3057
+ staleSocket.onmessage = null
3058
+ staleSocket.onerror = null
3059
+ staleSocket.onclose = null
3060
+ try {
3061
+ staleSocket.close(1000, 'browser_resume')
3062
+ } catch { /* ignore */ }
3063
+ }
3064
+
3065
+ registered = false
3066
+ stopAdvertiseHeartbeat()
3067
+ stopKeepalive()
3068
+ closeAllPeerConnections()
3069
+ mesh.connections.clear()
3070
+ intentionalClose = false
3071
+ openSocket()
3072
+ // Consumers hold their own recovery state (backoffs, deadlines, stale
3073
+ // peer sets) that a suspend leaves expired; tell them the same way the
3074
+ // browser lifecycle would.
3075
+ try { onResume?.({ reason, gapMs }) } catch { /* consumer error must not break resume */ }
3076
+ }
3077
+
3078
+ function reconnectSignalingPreservingPeers(reason = 'signaling_refresh', { force = false } = {}) {
3079
+ if (stoppedByUser) return false
3080
+ // A socket still opening is left to finish. On a busy relay, or a busy
3081
+ // machine (a hundred peers on one laptop), opening can take longer than a
3082
+ // recovery probe waits; cancelling it and starting over put each attempt
3083
+ // at the back of the queue again, and the peer never got a relay.
3084
+ if (!force && ws && ws.readyState === 0 && failedOpens < 2 && Date.now() - socketOpenStartedAt < SOCKET_OPEN_DEADLINE_MS) {
3085
+ log(`[signal] ${reason}: relay connection still opening; waiting for it`)
3086
+ return false
3087
+ }
3088
+
3089
+ log(`[signal] ${reason} — reconnecting signaling while preserving open peer channels`)
3090
+ resetReconnectBackoff()
3091
+
3092
+ // WebRTC data channels do not depend on the signaling WebSocket after
3093
+ // negotiation completes. Retire only the socket; disconnect() is a full
3094
+ // client teardown and must never be used as a signaling health probe.
3095
+ const staleSocket = ws
3096
+ ws = null
3097
+ if (staleSocket) {
3098
+ staleSocket.onopen = null
3099
+ staleSocket.onmessage = null
3100
+ staleSocket.onerror = null
3101
+ staleSocket.onclose = null
3102
+ try {
3103
+ staleSocket.close(4002, 'signaling_refresh')
3104
+ } catch { /* ignore */ }
3105
+ }
3106
+
3107
+ registered = false
3108
+ stopAdvertiseHeartbeat()
3109
+ stopKeepalive()
3110
+ intentionalClose = false
3111
+ openSocket()
3112
+ return true
3113
+ }
3114
+
3115
+ function handleVisibilityChange() {
3116
+ if (typeof document === 'undefined' || document.hidden) return
3117
+ // Tab became visible (or resumed from freeze) — check if WebSocket dropped
3118
+ // while the tab was inactive.
3119
+ _reacquireWakeLockIfNeeded()
3120
+ if (!stoppedByUser) {
3121
+ if (!ws || (ws.readyState !== WebSocket.OPEN && ws.readyState !== WebSocket.CONNECTING)) {
3122
+ log('[signal] tab visible — WebSocket dropped while hidden, reconnecting')
3123
+ // Close and purge all stale WebRTC connections so shouldDialCandidate
3124
+ // doesn't think they are alive and block re-dialing after reconnect.
3125
+ closeAllPeerConnections()
3126
+ mesh.connections.clear()
3127
+ resetReconnectBackoff()
3128
+ openSocket()
3129
+ } else if (registered) {
3130
+ // WS still open — close any dead WebRTC connections then refresh peers.
3131
+ for (const [rPeerId, entry] of mesh.connections.entries()) {
3132
+ if (entry.state === 'dead' || entry.state === 'failed') {
3133
+ try { entry.connection?.close() } catch {}
3134
+ mesh.connections.delete(rPeerId)
3135
+ onConnectionStateChangeCb?.({ peerId: rPeerId, state: 'closed', ts: Date.now() })
3136
+ }
3137
+ }
3138
+ client.requestBootstrap([peerId])
3139
+ }
3140
+ }
3141
+ }
3142
+
3143
+ const client = {
3144
+ connect() {
3145
+ stoppedByUser = false
3146
+ intentionalClose = false
3147
+ startSuspendWatch()
3148
+ startRelayWatch()
3149
+ openSocket()
3150
+ },
3151
+
3152
+ requestBootstrap(excludePeerIds = [peerId]) {
3153
+ if (!registered) {
3154
+ // Discovery is what the relay is for: wake it, and ask once it has registered.
3155
+ if (relayIdle) {
3156
+ pendingBootstrapPeerIds = excludePeerIds
3157
+ wakeRelay('discovery')
3158
+ return
3159
+ }
3160
+ log('[signal] not registered yet')
3161
+ return
3162
+ }
3163
+ send(pspEnvelope('discover', {
3164
+ body: { exclude_peers: excludePeerIds, limit: 10 },
3165
+ }))
3166
+ },
3167
+
3168
+ relay: relaySignal,
3169
+
3170
+ // Relay on demand. wakeRelay reopens a released relay socket and keeps it up for the linger
3171
+ // time; evaluateRelay runs the decision now instead of on its timer and returns it. Both do
3172
+ // nothing in the default 'always' mode.
3173
+ wakeRelay: (reason) => wakeRelay(reason),
3174
+ evaluateRelay,
3175
+
3176
+ advertise(nextCapabilities) {
3177
+ if (!registered) return
3178
+ send(pspEnvelope('announce', {
3179
+ ttl_ms: 30000,
3180
+ body: { instance_id: networkId, capabilities: nextCapabilities, hints: { wants_peers: true } },
3181
+ }))
3182
+ },
3183
+
3184
+ resetRecoveryBackoffs() {
3185
+ resetReconnectBackoff()
3186
+ recentOfferSdp.clear()
3187
+ recentAnswerSdp.clear()
3188
+ for (const [remotePeerId, entry] of mesh.connections.entries()) {
3189
+ clearAnswerBurst(remotePeerId)
3190
+ entry.lastAnswerBurstAt = 0
3191
+ entry.lastAnswerSentAt = 0
3192
+ entry.connection?.__resetOfferRetryBackoff?.()
3193
+ }
3194
+ log('[signal] recovery backoffs cleared')
3195
+ },
3196
+
3197
+ get signalUrl() {
3198
+ return signalUrl
3199
+ },
3200
+ /** True while the relay connection is still opening (and not past its deadline). */
3201
+ get signalingOpening() {
3202
+ // Not after two attempts in a row closed without ever opening (a relay
3203
+ // that is gone, such as one whose machine moved to another network):
3204
+ // the caller may then move to another relay instead of waiting on this
3205
+ // one's next attempt, forever.
3206
+ return Boolean(ws && ws.readyState === 0 && failedOpens < 2 && Date.now() - socketOpenStartedAt < SOCKET_OPEN_DEADLINE_MS)
3207
+ },
3208
+ /** Signal through another relay from now on; open peer channels stay up. */
3209
+ switchRelay(nextSignalUrl, reason = 'relay_switch') {
3210
+ if (!nextSignalUrl || nextSignalUrl === signalUrl) return false
3211
+ log(`[signal] ${reason}: moving signaling from ${signalUrl} to ${nextSignalUrl}`)
3212
+ signalUrl = nextSignalUrl
3213
+ failedOpens = 0
3214
+ return reconnectSignalingPreservingPeers(reason, { force: true })
3215
+ },
3216
+ reconnectSignaling(reason = 'signaling_refresh') {
3217
+ return reconnectSignalingPreservingPeers(reason)
3218
+ },
3219
+
3220
+ closePeerConnection(remotePeerId, reason = 'local_close') {
3221
+ return closePeerConnection(remotePeerId, reason, true)
3222
+ },
3223
+
3224
+ disconnect() {
3225
+ stoppedByUser = true
3226
+ clearTimeout(reconnectTimer)
3227
+ reconnectTimer = null
3228
+ stopAdvertiseHeartbeat()
3229
+ stopKeepalive()
3230
+ stopSuspendWatch()
3231
+ stopRelayWatch()
3232
+ relayIdle = false
3233
+ pendingBootstrapPeerIds = null
3234
+ intentionalClose = true
3235
+ closeAllPeerConnections()
3236
+ mesh.connections.clear()
3237
+ mesh.bootstrapCandidates = []
3238
+ pendingCandidates.clear()
3239
+ offerProcessingQueues.clear()
3240
+ for (const remotePeerId of answerBurstTimers.keys()) {
3241
+ clearAnswerBurst(remotePeerId)
3242
+ }
3243
+ pendingAnswers.clear()
3244
+ registered = false
3245
+ _releaseWakeLock()
3246
+
3247
+ if (typeof window !== 'undefined') {
3248
+ window.removeEventListener('beforeunload', unloadHandler)
3249
+ window.removeEventListener('pagehide', pageHideHandler)
3250
+ window.removeEventListener('unload', unloadHandler)
3251
+ window.removeEventListener('pageshow', handlePageShow)
3252
+ }
3253
+
3254
+ if (typeof document !== 'undefined') {
3255
+ document.removeEventListener('visibilitychange', handleVisibilityChange)
3256
+ document.removeEventListener('resume', handleSuspendRestore)
3257
+ document.removeEventListener('freeze', handleFreeze)
3258
+ }
3259
+
3260
+ if (ws) {
3261
+ send(pspEnvelope('withdraw', { body: { reason: 'user_disconnect' } }))
3262
+ ws.onmessage = null
3263
+ ws.onerror = null
3264
+ ws.close(1000, 'user_disconnect')
3265
+ ws = null
3266
+ }
3267
+ },
3268
+
3269
+ async initiateConnection(toPeerId, iceServers = []) {
3270
+ return initiateWebRTCConnection(toPeerId, iceServers)
3271
+ },
3272
+
3273
+ injectSignal,
3274
+
3275
+ /**
3276
+ * Ask the relay this client is registered on to do something itself, such
3277
+ * as a PigeonIdP account lookup ({ action: 'idp-get', ... }). Resolves
3278
+ * with the relay's answer; { ok: false, error: 'unsupported' } from a
3279
+ * relay that does not serve it, and a rejection when not registered or
3280
+ * when no answer comes in time (a relay too old to know the request).
3281
+ */
3282
+ relayRequest(body, { timeoutMs = 5000 } = {}) {
3283
+ if (!registered || !ws) return Promise.reject(new Error('not registered on a relay'))
3284
+ const requestId = generateMessageId()
3285
+ return new Promise((resolve, reject) => {
3286
+ const timer = setTimeout(() => {
3287
+ relayRequests.delete(requestId)
3288
+ reject(new Error('the relay did not answer'))
3289
+ }, timeoutMs)
3290
+ relayRequests.set(requestId, { resolve, reject, timer })
3291
+ try {
3292
+ send(pspEnvelope('ext', { body: { ...body, relay_request: true, request_id: requestId } }))
3293
+ } catch (error) {
3294
+ clearTimeout(timer)
3295
+ relayRequests.delete(requestId)
3296
+ reject(error)
3297
+ }
3298
+ })
3299
+ },
3300
+
3301
+ sendData(data, preferredPeerId) {
3302
+ // The gate is isChannelLive (above, with its reasoning): transient states
3303
+ // throw an error marked transient so callers retry without executing the
3304
+ // peer; terminal states throw plain so callers release it.
3305
+ const channelIsLive = isChannelLive
3306
+
3307
+ let target = null
3308
+
3309
+ if (preferredPeerId) {
3310
+ target = mesh.connections.get(preferredPeerId) ?? null
3311
+ } else {
3312
+ for (const entry of mesh.connections.values()) {
3313
+ if (channelIsLive(entry)) {
3314
+ target = entry
3315
+ break
3316
+ }
3317
+ }
3318
+ }
3319
+
3320
+ if (!target?.channel || target.channel.readyState !== 'open') {
3321
+ // Not open YET is transient by definition: the channel is still
3322
+ // being negotiated or attached. This refusal carried no flag, so a
3323
+ // send that raced the open was read as terminal and the peer was
3324
+ // released the moment it had connected.
3325
+ const error = new Error('WebRTC not yet connected')
3326
+ error.transient = true
3327
+ throw error
3328
+ }
3329
+ if (target.dormantAt && Date.now() - target.dormantAt < DATA_DORMANT_MAX_MS) {
3330
+ const error = new Error('Peer is dormant (hidden tab)')
3331
+ error.transient = true
3332
+ throw error
3333
+ }
3334
+ if (Number(target.channel.bufferedAmount ?? 0) > DATA_MAX_BUFFERED_BYTES) {
3335
+ // Backpressure. The peer is not reading fast enough (or at all); the
3336
+ // keepalive decides which. Nothing more goes into the transport.
3337
+ const error = new Error('WebRTC channel send buffer is full')
3338
+ error.transient = true
3339
+ throw error
3340
+ }
3341
+ if (!channelIsLive(target)) {
3342
+ const now = Date.now()
3343
+ const state = target.connection?.connectionState
3344
+ const unproven = !(target.lastPongAt > 0) || now - target.lastPongAt >= DATA_PROOF_FRESH_MS
3345
+ const pingOutstanding = target.lastPingSentAt > (target.lastPongAt ?? 0)
3346
+ const outboundDead = pingOutstanding && now - target.lastPingSentAt >= DATA_PONG_TIMEOUT_MS
3347
+ && !(Number(target.channel?.bufferedAmount ?? 0) > 0)
3348
+ // A refusal for a stale proof arms its own re-proof: a healthy
3349
+ // channel pongs within one round trip and the next send passes; a
3350
+ // dead one lets this ping age into the execution verdict. Without
3351
+ // this, a quiet channel could stay refused forever.
3352
+ if (unproven && !pingOutstanding && target.channel?.readyState === 'open'
3353
+ && (target.connection?.connectionState === undefined || target.connection.connectionState === 'connected')) {
3354
+ try {
3355
+ target.channel.send(JSON.stringify({ type: 'ping', ts: now }))
3356
+ target.lastPingSentAt = now
3357
+ } catch { /* the keepalive verdict handles it */ }
3358
+ }
3359
+ const error = new Error(outboundDead
3360
+ ? 'WebRTC channel failed its pong proof'
3361
+ : linkSuspect(target, now)
3362
+ ? 'WebRTC channel has gone quiet (waiting for a pong)'
3363
+ : unproven
3364
+ ? 'WebRTC channel is awaiting a fresh pong'
3365
+ : `WebRTC connection is ${state}`)
3366
+ // Awaiting-a-pong resolves within one round trip — retry. A failed
3367
+ // proof or a bad connection state is the edge telling the truth
3368
+ // about being gone.
3369
+ error.transient = !outboundDead
3370
+ && (unproven || linkSuspect(target, now) || state === 'connecting' || state === 'disconnected' || state === 'new')
3371
+ throw error
3372
+ }
3373
+
3374
+ // A channel that reports 'open' can still throw from send(): Safari and
3375
+ // Chrome both do while SCTP is settling right after the channel opens,
3376
+ // and again while it is closing. The gate above already passed, so
3377
+ // this is not proof the edge is gone; the pong round trip decides that.
3378
+ // Surfacing the throw as terminal released a freshly connected peer on
3379
+ // its first frame, both sides redialed, and the pair churned forever.
3380
+ const sendFrame = (frame) => {
3381
+ try {
3382
+ target.channel.send(frame)
3383
+ } catch (err) {
3384
+ const error = new Error(`WebRTC channel refused a frame: ${err?.message ?? err}`)
3385
+ error.transient = true
3386
+ error.cause = err
3387
+ throw error
3388
+ }
3389
+ }
3390
+
3391
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
3392
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
3393
+ const total = Math.max(1, Math.ceil(bytes.length / DATA_BIN_SLICE))
3394
+ if (total > DATA_BIN_MAX_SLICES) throw new Error(`binary payload too large (${bytes.length} bytes)`)
3395
+ const id = (dataBinCounter = (dataBinCounter + 1) >>> 0)
3396
+ for (let seq = 0; seq < total; seq++) {
3397
+ const part = bytes.subarray(seq * DATA_BIN_SLICE, (seq + 1) * DATA_BIN_SLICE)
3398
+ const frame = new Uint8Array(DATA_BIN_HEADER + part.length)
3399
+ const view = new DataView(frame.buffer)
3400
+ view.setUint8(0, 0x70); view.setUint8(1, 0x62); view.setUint8(2, 1); view.setUint8(3, 0)
3401
+ view.setUint32(4, id); view.setUint16(8, seq); view.setUint16(10, total)
3402
+ frame.set(part, DATA_BIN_HEADER)
3403
+ // Node's WebRTC (werift) sends Buffers; a browser, any ArrayBufferView.
3404
+ sendFrame(typeof Buffer === 'function' ? Buffer.from(frame.buffer, 0, frame.byteLength) : frame)
3405
+ }
3406
+ return target
3407
+ }
3408
+
3409
+ if (typeof data === 'string' && data.length > DATA_CHUNK_THRESHOLD) {
3410
+ const id = `${Date.now().toString(36)}-${(dataChunkCounter++).toString(36)}`
3411
+ const total = Math.ceil(data.length / DATA_CHUNK_SLICE)
3412
+ for (let seq = 0; seq < total; seq++) {
3413
+ sendFrame(JSON.stringify({
3414
+ t: DATA_CHUNK_FRAME,
3415
+ i: id,
3416
+ s: seq,
3417
+ n: total,
3418
+ d: data.slice(seq * DATA_CHUNK_SLICE, (seq + 1) * DATA_CHUNK_SLICE),
3419
+ }))
3420
+ }
3421
+ return target
3422
+ }
3423
+
3424
+ sendFrame(data)
3425
+ return target
3426
+ },
3427
+
3428
+ get mesh() {
3429
+ return mesh
3430
+ },
3431
+ get peerId() {
3432
+ return peerId
3433
+ },
3434
+ get isRegistered() {
3435
+ return registered
3436
+ },
3437
+ // True while the relay socket is released on purpose. A host that watches for a missing relay
3438
+ // acknowledgement must not read this as an outage.
3439
+ get relayIdle() {
3440
+ return relayIdle
3441
+ },
3442
+ get relayMode() {
3443
+ return relayMode
3444
+ },
3445
+ }
3446
+
3447
+ if (typeof window !== 'undefined') {
3448
+ window.addEventListener('beforeunload', unloadHandler, { once: true })
3449
+ // pagehide is the reliable teardown event in Safari and on mobile.
3450
+ window.addEventListener('pagehide', pageHideHandler)
3451
+ window.addEventListener('unload', unloadHandler, { once: true })
3452
+ // bfcache: restore from back/forward cache.
3453
+ window.addEventListener('pageshow', handlePageShow)
3454
+ }
3455
+
3456
+ if (typeof document !== 'undefined') {
3457
+ document.addEventListener('visibilitychange', handleVisibilityChange)
3458
+ // Page Lifecycle API: fires when a frozen tab is thawed back to active.
3459
+ // This is distinct from visibilitychange and fires first on resume.
3460
+ document.addEventListener('resume', handleSuspendRestore)
3461
+ // Page Lifecycle API: fires just before the tab CPU is suspended.
3462
+ document.addEventListener('freeze', handleFreeze)
3463
+ }
3464
+
3465
+ if (autoConnect) client.connect()
3466
+
3467
+ return client
3468
+ }