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/public/app.js CHANGED
@@ -10,8 +10,55 @@ const RTC_CONFIG = {
10
10
  { urls: "stun:global.stun.twilio.com:3478" }
11
11
  ]
12
12
  };
13
- const SHARED_IDS_KEY = "freertc.shared.ids.v1";
13
+ const SHARED_IDS_KEY = "freertc.scopes.v2";
14
14
  const UI_PREFS_KEY = "freertc.ui.prefs.v1";
15
+ const DATA_PING_MS = 3000;
16
+ const DATA_PONG_TIMEOUT_MS = 12000;
17
+
18
+ // Relay on demand (PSP 19.4 - 19.7). A peer with a healthy mesh lets go of its relay socket;
19
+ // the peers closest to the room stay as anchors so a newcomer can still find a way in.
20
+ const ANNOUNCE_REFRESH_MS = 12000;
21
+ const RELAY_MIN_MESH_PEERS = 2;
22
+ const RELAY_ANCHORS = 3;
23
+ const RELAY_SETTLE_MS = 30000;
24
+ const RELAY_LINGER_MS = 60000;
25
+ const RELAY_EVAL_MS = 5000;
26
+ const RELAY_GOSSIP_TTL_MS = 20000;
27
+ const RELAY_QUEUE_LIMIT = 50;
28
+ const ANCHOR_GOSSIP_MAX_IDS = 16;
29
+ const ANCHOR_GOSSIP_MAX_ID_CHARS = 256;
30
+ const FRAME_SIGNAL = "~signal";
31
+ const FRAME_ANCHORS = "~anchors";
32
+ // Negotiation messages may travel over a data channel instead of the relay.
33
+ const MESH_SIGNAL_TYPES = new Set(["connect_request", "connect_accept", "connect_reject", "offer", "answer", "ice_candidate", "ice_end", "renegotiate", "bye"]);
34
+
35
+ const closenessKeys = new Map();
36
+
37
+ /** A stable position on a 256-bit ring for a room or a peer: SHA-256 of the text as an unsigned integer. */
38
+ async function closenessKey(text) {
39
+ let key = closenessKeys.get(text);
40
+ if (key === undefined) {
41
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
42
+ key = BigInt(`0x${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`);
43
+ if (closenessKeys.size > 2000) {
44
+ closenessKeys.clear();
45
+ }
46
+ closenessKeys.set(text, key);
47
+ }
48
+ return key;
49
+ }
50
+
51
+ /** The `count` ids closest to the room by XOR distance; ties go to the lexicographically smaller id. */
52
+ async function closestToRoom(roomKey, ids, count) {
53
+ const scored = await Promise.all([...new Set(ids)].map(async (id) => ({ id, distance: (await closenessKey(id)) ^ roomKey })));
54
+ scored.sort((a, b) => {
55
+ if (a.distance !== b.distance) {
56
+ return a.distance < b.distance ? -1 : 1;
57
+ }
58
+ return a.id < b.id ? -1 : 1;
59
+ });
60
+ return scored.slice(0, count).map((entry) => entry.id);
61
+ }
15
62
 
16
63
  function newId(prefix = "msg") {
17
64
  return `${prefix}-${crypto.randomUUID()}`;
@@ -21,6 +68,13 @@ function now() {
21
68
  return Date.now();
22
69
  }
23
70
 
71
+ function activeRtcConfig() {
72
+ return {
73
+ ...RTC_CONFIG,
74
+ iceServers: RTC_CONFIG.iceServers
75
+ };
76
+ }
77
+
24
78
  async function waitForIceGatheringComplete(pc, timeoutMs = 4000) {
25
79
  if (!pc || pc.iceGatheringState === "complete") {
26
80
  return;
@@ -112,22 +166,6 @@ function normalizeText(value) {
112
166
  return String(value).trim();
113
167
  }
114
168
 
115
- function deriveNetworkFromSession(sessionIdValue) {
116
- const session = normalizeText(sessionIdValue);
117
- if (!session || !isSpecToken(session)) {
118
- return "";
119
- }
120
- return `room:${session}`;
121
- }
122
-
123
- function deriveSessionFromNetwork(networkValue) {
124
- const network = normalizeText(networkValue);
125
- if (!network || !isSpecToken(network)) {
126
- return "room:test";
127
- }
128
- return network;
129
- }
130
-
131
169
  createApp({
132
170
  setup() {
133
171
  const host = window.location.host;
@@ -137,7 +175,7 @@ createApp({
137
175
  const status = ref("disconnected");
138
176
  const socket = ref(null);
139
177
 
140
- const network = ref("room:test");
178
+ const network = ref("network:test");
141
179
 
142
180
  function normalizedWsUrlValue() {
143
181
  const trimmed = normalizeText(wsUrl.value);
@@ -146,7 +184,15 @@ createApp({
146
184
 
147
185
  function normalizedNetworkValue() {
148
186
  const trimmed = normalizeText(network.value);
149
- return trimmed || "room:test";
187
+ return trimmed || "network:test";
188
+ }
189
+
190
+ function normalizedAppliedNetworkValue() {
191
+ return normalizeText(appliedNetwork.value) || normalizedNetworkValue();
192
+ }
193
+
194
+ function normalizedAppliedRoomValue() {
195
+ return normalizeText(appliedSessionId.value) || normalizeText(sessionId.value) || "room:test";
150
196
  }
151
197
 
152
198
  // Keep peer identity in-memory per tab so duplicate tabs cannot share IDs.
@@ -160,8 +206,10 @@ createApp({
160
206
  const appliedFromPeer = ref(fromPeer.value);
161
207
  const toPeer = ref("");
162
208
  const sessionId = ref("");
163
- let sessionIdExplicit = false;
164
- const instanceId = ref("");
209
+ const appliedSessionId = ref("");
210
+ // PSP instance_id is the network scope; keep one canonical value so they
211
+ // can never drift apart in the UI or on the wire.
212
+ const instanceId = computed(() => normalizedAppliedNetworkValue());
165
213
 
166
214
  const activeView = ref("webrtc");
167
215
  const relayType = ref("announce");
@@ -201,6 +249,7 @@ createApp({
201
249
  let manualDisconnect = false;
202
250
  let stoppingRtc = false;
203
251
  let reconnectLockedByBye = false;
252
+ let _wakeLock = null;
204
253
  const CONNECT_REQUEST_TIMEOUT_MS = 10000; // 10 second timeout
205
254
  const DISCOVER_SYNC_INTERVAL_MS = 10000;
206
255
  const FAILED_PEER_COOLDOWN_MS = 5000;
@@ -211,6 +260,21 @@ createApp({
211
260
  const byeCooldowns = new Map();
212
261
  const meshLinks = new Map();
213
262
 
263
+ // Relay on demand. `relayState` is what the page shows: up, idle (released on purpose) or waking.
264
+ const relayOnDemand = ref(true);
265
+ const relayState = ref("up");
266
+ let relayIdle = false;
267
+ let relayWakeUntil = 0;
268
+ let relayReleasableSince = 0;
269
+ let relayWatchTimer = null;
270
+ let relayEvaluating = false;
271
+ let lastAnnounceAt = 0;
272
+ let lastAnchorBroadcast = { key: "", at: 0 };
273
+ // Peers that have sent a signaling frame over the mesh: the relay copy to them can stop.
274
+ const meshCapablePeers = new Set();
275
+ // Frames that needed the relay while it was released, sent once it is back.
276
+ let pendingRelayEnvelopes = [];
277
+
214
278
  const logs = ref([]);
215
279
 
216
280
  const isConnected = computed(() => status.value === "connected");
@@ -317,11 +381,11 @@ createApp({
317
381
  warnings.push("Signaling Server URL must be a valid absolute WebSocket URL");
318
382
  }
319
383
 
320
- const topic = normalizeText(network.value);
321
- if (!topic) {
322
- warnings.push("Room / Topic is required");
323
- } else if (!isSpecToken(topic)) {
324
- warnings.push("Room / Topic should be 1-128 chars using A-Z, a-z, 0-9, . _ : / -");
384
+ const networkScope = normalizeText(network.value);
385
+ if (!networkScope) {
386
+ warnings.push("Network is required");
387
+ } else if (!isSpecToken(networkScope)) {
388
+ warnings.push("Network should be 1-128 chars using A-Z, a-z, 0-9, . _ : / -");
325
389
  }
326
390
 
327
391
  const localPeer = normalizePeerId(fromPeer.value);
@@ -334,18 +398,11 @@ createApp({
334
398
  warnings.push("To Peer must be empty or a token-safe, fingerprint-like peer ID");
335
399
  }
336
400
 
337
- const sess = normalizeText(sessionId.value);
338
- if (!sess) {
339
- warnings.push("Session ID is required");
340
- } else if (!isSpecToken(sess)) {
341
- warnings.push("Session ID should be 1-128 chars using A-Z, a-z, 0-9, . _ : / -");
342
- }
343
-
344
- const inst = normalizeText(instanceId.value);
345
- if (!inst) {
346
- warnings.push("Instance ID is required");
347
- } else if (!isSpecToken(inst)) {
348
- warnings.push("Instance ID should be 1-128 chars using A-Z, a-z, 0-9, . _ : / -");
401
+ const roomScope = normalizeText(sessionId.value);
402
+ if (!roomScope) {
403
+ warnings.push("Room is required");
404
+ } else if (!isSpecToken(roomScope)) {
405
+ warnings.push("Room should be 1-128 chars using A-Z, a-z, 0-9, . _ : / -");
349
406
  }
350
407
 
351
408
  return warnings;
@@ -557,6 +614,8 @@ createApp({
557
614
  offerWaitTime: 0, // Tracks when responder started waiting for offer
558
615
  answerWaitTime: 0, // Tracks when initiator started waiting for answer
559
616
  pendingCandidates: [],
617
+ pendingAnswer: null,
618
+ pendingAnswerPc: null,
560
619
  lastSignalAt: now()
561
620
  };
562
621
  meshLinks.set(peerId, link);
@@ -688,64 +747,79 @@ createApp({
688
747
 
689
748
  function initSharedIds() {
690
749
  const params = new URLSearchParams(window.location.search);
691
- const sessionParam = normalizeText(params.get("session_id") || params.get("sessionId"));
692
- const instanceParam = normalizeText(params.get("instance_id") || params.get("instanceId"));
750
+ const roomParam = normalizeText(
751
+ params.get("room") ||
752
+ params.get("room_id") ||
753
+ params.get("roomId") ||
754
+ params.get("session_id") ||
755
+ params.get("sessionId")
756
+ );
693
757
  const networkParam = normalizeText(
694
758
  params.get("network") ||
695
759
  params.get("network_id") ||
696
- params.get("networkId")
760
+ params.get("networkId") ||
761
+ params.get("instance_id") ||
762
+ params.get("instanceId")
697
763
  );
698
764
 
699
- const hasValidUrlSession = isSpecToken(sessionParam);
700
- const hasValidUrlInstance = isSpecToken(instanceParam);
765
+ const hasValidUrlRoom = isSpecToken(roomParam);
701
766
  const hasValidUrlNetwork = isSpecToken(networkParam);
702
767
 
703
- if (sessionParam && !hasValidUrlSession) {
704
- pushLog("ids:error", "Ignoring invalid URL session_id");
705
- }
706
- if (instanceParam && !hasValidUrlInstance) {
707
- pushLog("ids:error", "Ignoring invalid URL instance_id");
768
+ if (roomParam && !hasValidUrlRoom) {
769
+ pushLog("room:error", "Ignoring invalid URL room");
708
770
  }
709
771
  if (networkParam && !hasValidUrlNetwork) {
710
772
  pushLog("network:error", "Ignoring invalid URL network");
711
773
  }
712
774
 
713
- sessionIdExplicit = hasValidUrlSession;
714
- instanceId.value = hasValidUrlInstance ? instanceParam : `inst-${Math.random().toString(36).slice(2, 10)}`;
715
-
716
- // Cross-domain links should land in the same room even when each origin has
717
- // different sessionStorage UI state. URL network wins; otherwise derive from session_id.
718
- const derivedNetwork = hasValidUrlSession ? deriveNetworkFromSession(sessionParam) : "";
719
- const nextNetwork = hasValidUrlNetwork ? networkParam : (derivedNetwork || normalizedNetworkValue());
775
+ const nextNetwork = hasValidUrlNetwork ? networkParam : normalizedNetworkValue();
776
+ const nextRoom = hasValidUrlRoom ? roomParam : `room-${Math.random().toString(36).slice(2, 10)}`;
720
777
  if (nextNetwork && nextNetwork !== network.value) {
721
778
  network.value = nextNetwork;
722
779
  }
723
780
  if (nextNetwork && nextNetwork !== appliedNetwork.value) {
724
781
  appliedNetwork.value = nextNetwork;
725
782
  }
726
-
727
- sessionId.value = hasValidUrlSession ? sessionParam : deriveSessionFromNetwork(nextNetwork || normalizedNetworkValue());
783
+ sessionId.value = nextRoom;
784
+ appliedSessionId.value = nextRoom;
728
785
 
729
786
  persistSharedIds();
730
787
  }
731
788
 
732
789
  function persistSharedIds() {
790
+ const canonicalNetwork = normalizedNetworkValue();
791
+ const canonicalRoom = normalizeText(sessionId.value) || "room:test";
792
+ network.value = canonicalNetwork;
793
+ sessionId.value = canonicalRoom;
794
+
733
795
  localStorage.setItem(
734
796
  SHARED_IDS_KEY,
735
797
  JSON.stringify({
736
- session_id: sessionId.value,
737
- instance_id: instanceId.value
798
+ network: canonicalNetwork,
799
+ room: canonicalRoom,
800
+ instance_id: canonicalNetwork,
801
+ session_id: canonicalRoom
738
802
  })
739
803
  );
740
804
 
741
805
  const url = new URL(window.location.href);
742
- url.searchParams.set("session_id", sessionId.value);
743
- url.searchParams.set("instance_id", instanceId.value);
806
+ url.searchParams.set("network", canonicalNetwork);
807
+ url.searchParams.set("room", canonicalRoom);
808
+ url.searchParams.delete("network_id");
809
+ url.searchParams.delete("networkId");
810
+ url.searchParams.delete("room_id");
811
+ url.searchParams.delete("roomId");
812
+ url.searchParams.delete("session_id");
813
+ url.searchParams.delete("sessionId");
814
+ url.searchParams.delete("instance_id");
815
+ url.searchParams.delete("instanceId");
744
816
  window.history.replaceState(null, "", url);
745
817
 
746
- pushLog("ids", {
747
- session_id: sessionId.value,
748
- instance_id: instanceId.value
818
+ pushLog("scope", {
819
+ network: canonicalNetwork,
820
+ room: canonicalRoom,
821
+ instance_id: canonicalNetwork,
822
+ session_id: canonicalRoom
749
823
  });
750
824
  }
751
825
 
@@ -766,6 +840,7 @@ createApp({
766
840
  network: normalizedNetworkValue(),
767
841
  partial_mesh: Boolean(partialMesh.value),
768
842
  partial_mesh_max_peers: normalizeMeshLimit(partialMeshMaxPeers.value),
843
+ relay_on_demand: Boolean(relayOnDemand.value),
769
844
  chat_send_mode: chatSendMode.value === "target" ? "target" : "broadcast",
770
845
  active_view: activeView.value === "console" ? "console" : "webrtc"
771
846
  })
@@ -804,6 +879,10 @@ createApp({
804
879
 
805
880
  partialMeshMaxPeers.value = normalizeMeshLimit(saved.partial_mesh_max_peers);
806
881
 
882
+ if (typeof saved.relay_on_demand === "boolean") {
883
+ relayOnDemand.value = saved.relay_on_demand;
884
+ }
885
+
807
886
  if (saved.chat_send_mode === "target" || saved.chat_send_mode === "broadcast") {
808
887
  chatSendMode.value = saved.chat_send_mode;
809
888
  }
@@ -816,45 +895,36 @@ createApp({
816
895
  }
817
896
  }
818
897
 
819
- function regenerateSharedIds() {
820
- sessionIdExplicit = true;
821
- sessionId.value = `sess-${Math.random().toString(36).slice(2, 10)}`;
822
- instanceId.value = `inst-${Math.random().toString(36).slice(2, 10)}`;
823
- persistSharedIds();
824
- pushLog("ids", "Generated new shared session_id and instance_id");
825
- }
826
-
827
- function applySessionIdChange() {
828
- sessionIdExplicit = true;
829
- persistSharedIds();
830
- }
831
-
832
- function regeneratePeerId() {
833
- fromPeer.value = randomHex();
834
- appliedFromPeer.value = fromPeer.value;
835
- toPeer.value = "";
836
- stopRtc();
837
- pushLog("ids", { peer_id: fromPeer.value });
838
-
839
- if (isConnected.value) {
840
- sendAnnounce({ feedback: false });
841
- sendDiscover({ feedback: false });
842
- }
843
- }
844
-
845
- function applyNetworkChange() {
846
- const next = normalizeText(network.value) || "room:test";
847
- const changed = next !== appliedNetwork.value;
848
- network.value = next;
898
+ function switchScope(nextNetworkValue, nextRoomValue, message) {
899
+ const nextNetwork = normalizeText(nextNetworkValue) || "network:test";
900
+ const nextRoom = normalizeText(nextRoomValue) || "room:test";
901
+ const previousNetwork = appliedNetwork.value || normalizedNetworkValue();
902
+ const previousRoom = appliedSessionId.value || normalizeText(sessionId.value);
903
+ const changed = nextNetwork !== previousNetwork || nextRoom !== previousRoom;
849
904
 
850
905
  if (!changed) {
906
+ network.value = nextNetwork;
907
+ sessionId.value = nextRoom;
908
+ persistSharedIds();
851
909
  return;
852
910
  }
853
- appliedNetwork.value = next;
854
911
 
855
- if (!sessionIdExplicit) {
856
- sessionId.value = deriveSessionFromNetwork(next);
857
- persistSharedIds();
912
+ // Leave using the previously applied scope before changing the values on
913
+ // the wire. This prevents an existing direct channel from surviving a
914
+ // Network or Room change.
915
+ network.value = previousNetwork;
916
+ sessionId.value = previousRoom;
917
+ if (isConnected.value) {
918
+ const peers = new Set([
919
+ ...Array.from(meshLinks.keys()),
920
+ ...discoveredPeers.value.map((peer) => peer?.peer_id).filter((peerId) => typeof peerId === "string")
921
+ ]);
922
+ for (const peerId of peers) {
923
+ if (peerId && peerId !== fromPeer.value) {
924
+ sendRelayEnvelope("bye", { reason: "scope_changed" }, { to: peerId });
925
+ }
926
+ }
927
+ sendWithdraw();
858
928
  }
859
929
 
860
930
  reconnectLockedByBye = false;
@@ -862,19 +932,55 @@ createApp({
862
932
  failedPeerCooldowns.clear();
863
933
  toPeer.value = "";
864
934
  discoveredPeers.value = [];
865
-
866
935
  stopAutomation();
867
936
  stopRtc();
868
937
  meshLinks.clear();
938
+
939
+ network.value = nextNetwork;
940
+ sessionId.value = nextRoom;
941
+ appliedNetwork.value = nextNetwork;
942
+ appliedSessionId.value = nextRoom;
943
+ persistSharedIds();
869
944
  refreshMeshStats();
870
945
  refreshSelectedPeerSnapshot();
871
- pushLog("network", `Switched to ${network.value}`);
946
+ pushLog("scope", message || `Switched to network ${nextNetwork}, room ${nextRoom}`);
872
947
 
873
948
  if (isConnected.value) {
874
949
  void beginRtc();
875
950
  }
876
951
  }
877
952
 
953
+ function regenerateNetworkAndRoom() {
954
+ switchScope(
955
+ `network-${Math.random().toString(36).slice(2, 10)}`,
956
+ `room-${Math.random().toString(36).slice(2, 10)}`,
957
+ "Generated a new Network and Room"
958
+ );
959
+ }
960
+
961
+ function regeneratePeerId() {
962
+ fromPeer.value = randomHex();
963
+ appliedFromPeer.value = fromPeer.value;
964
+ toPeer.value = "";
965
+ stopRtc();
966
+ pushLog("ids", { peer_id: fromPeer.value });
967
+
968
+ if (isConnected.value) {
969
+ sendAnnounce({ feedback: false });
970
+ sendDiscover({ feedback: false });
971
+ }
972
+ }
973
+
974
+ function applyNetworkChange() {
975
+ const next = normalizeText(network.value) || "network:test";
976
+ switchScope(next, sessionId.value, `Switched network to ${next}`);
977
+ }
978
+
979
+ function applyRoomChange() {
980
+ const next = normalizeText(sessionId.value) || "room:test";
981
+ switchScope(network.value, next, `Switched room to ${next}`);
982
+ }
983
+
878
984
  function applyWsUrlChange() {
879
985
  const next = normalizeText(wsUrl.value);
880
986
  const resolved = next || `${wsScheme}://${host}/ws`;
@@ -933,26 +1039,91 @@ createApp({
933
1039
  }
934
1040
  }
935
1041
 
936
- function sendEnvelope(envelope) {
937
- if (!socket.value || socket.value.readyState !== WebSocket.OPEN) {
938
- pushLog("client:error", "Socket is not connected");
1042
+ // A neighbour: a peer with an open data channel on a connection that has not failed.
1043
+ function isLiveNeighbour(peerId) {
1044
+ const link = meshLinks.get(peerId);
1045
+ if (!link || link.dc?.readyState !== "open") {
939
1046
  return false;
940
1047
  }
1048
+ return !["failed", "closed"].includes(link.rtcState);
1049
+ }
941
1050
 
942
- // Keep network token stable even if the editable field has trailing spaces.
943
- const stableNetwork = normalizedNetworkValue();
944
- if (stableNetwork !== network.value) {
945
- network.value = stableNetwork;
1051
+ function liveNeighbourIds() {
1052
+ return Array.from(meshLinks.keys()).filter(isLiveNeighbour);
1053
+ }
1054
+
1055
+ // A negotiation frame for a neighbour goes over the data channel (PSP 19.4).
1056
+ function sendViaMesh(outbound) {
1057
+ if (!relayOnDemand.value || !MESH_SIGNAL_TYPES.has(outbound.type) || !outbound.to || !isLiveNeighbour(outbound.to)) {
1058
+ return false;
946
1059
  }
1060
+ try {
1061
+ meshLinks.get(outbound.to).dc.send(JSON.stringify({ type: FRAME_SIGNAL, envelope: outbound }));
1062
+ } catch {
1063
+ // A channel that refuses the frame is for the keepalive to judge; the relay carries it instead.
1064
+ return false;
1065
+ }
1066
+ pushLog("mesh:send", outbound);
1067
+ return true;
1068
+ }
1069
+
1070
+ // Broadcast frames replace each other in the queue; a withdraw is never sent late.
1071
+ function queueForRelay(outbound) {
1072
+ if (outbound.type === "withdraw") {
1073
+ return;
1074
+ }
1075
+ const replaces = outbound.type === "announce" || outbound.type === "discover";
1076
+ pendingRelayEnvelopes = pendingRelayEnvelopes.filter((queued) => !(replaces && queued.type === outbound.type));
1077
+ pendingRelayEnvelopes.push(outbound);
1078
+ pendingRelayEnvelopes = pendingRelayEnvelopes.slice(-RELAY_QUEUE_LIMIT);
1079
+ }
1080
+
1081
+ function flushRelayQueue() {
1082
+ const queued = pendingRelayEnvelopes;
1083
+ pendingRelayEnvelopes = [];
1084
+ for (const outbound of queued) {
1085
+ // A frame outlives its own ttl_ms for nobody.
1086
+ if (now() - Number(outbound.timestamp || 0) <= Number(outbound.ttl_ms || 30000)) {
1087
+ sendOnSocket(outbound);
1088
+ }
1089
+ }
1090
+ }
1091
+
1092
+ function sendOnSocket(outbound) {
1093
+ socket.value.send(JSON.stringify(outbound));
1094
+ pushLog("client:send", outbound);
1095
+ return true;
1096
+ }
1097
+
1098
+ function sendEnvelope(envelope) {
1099
+ // Keep network token stable even if the editable field has trailing spaces.
1100
+ const stableNetwork = normalizedAppliedNetworkValue();
947
1101
 
948
1102
  const outbound = {
949
1103
  ...envelope,
950
1104
  network: stableNetwork
951
1105
  };
952
1106
 
953
- socket.value.send(JSON.stringify(outbound));
954
- pushLog("client:send", outbound);
955
- return true;
1107
+ const viaMesh = sendViaMesh(outbound);
1108
+ const socketOpen = Boolean(socket.value) && socket.value.readyState === WebSocket.OPEN;
1109
+ // Until a peer has answered over the mesh, the relay copy goes too: it may not carry the mesh.
1110
+ if (viaMesh && (meshCapablePeers.has(outbound.to) || !socketOpen)) {
1111
+ return true;
1112
+ }
1113
+ if (socketOpen) {
1114
+ return sendOnSocket(outbound);
1115
+ }
1116
+ if (relayIdle && relayOnDemand.value) {
1117
+ // The mesh could not carry this: wake the relay and send it once it is back.
1118
+ queueForRelay(outbound);
1119
+ wakeRelay(`${outbound.type} needs the relay`);
1120
+ return true;
1121
+ }
1122
+ if (viaMesh) {
1123
+ return true;
1124
+ }
1125
+ pushLog("client:error", "Socket is not connected");
1126
+ return false;
956
1127
  }
957
1128
 
958
1129
  function sendRelayEnvelope(type, body, override = {}) {
@@ -970,7 +1141,7 @@ createApp({
970
1141
  network: network.value,
971
1142
  from: fromPeer.value,
972
1143
  to: target,
973
- session_id: sessionId.value,
1144
+ session_id: normalizedAppliedRoomValue(),
974
1145
  message_id: newId(type),
975
1146
  timestamp: now(),
976
1147
  ttl_ms: 30000,
@@ -998,7 +1169,10 @@ createApp({
998
1169
  socket.value = null;
999
1170
  }
1000
1171
 
1001
- status.value = "connecting";
1172
+ // Waking a released relay is not a reconnect: the mesh is still up and the page stays connected.
1173
+ if (!relayIdle) {
1174
+ status.value = "connecting";
1175
+ }
1002
1176
  const resolvedWsUrl = normalizedWsUrlValue();
1003
1177
  if (resolvedWsUrl !== wsUrl.value) {
1004
1178
  wsUrl.value = resolvedWsUrl;
@@ -1008,7 +1182,11 @@ createApp({
1008
1182
  try {
1009
1183
  ws = new WebSocket(resolvedWsUrl);
1010
1184
  } catch (error) {
1011
- status.value = "disconnected";
1185
+ if (relayIdle) {
1186
+ relayState.value = "idle";
1187
+ } else {
1188
+ status.value = "disconnected";
1189
+ }
1012
1190
  socket.value = null;
1013
1191
  pushLog("socket:error", error?.message || "failed to create websocket");
1014
1192
  return;
@@ -1017,9 +1195,14 @@ createApp({
1017
1195
 
1018
1196
  ws.onopen = () => {
1019
1197
  status.value = "connected";
1198
+ relayIdle = false;
1199
+ relayState.value = "up";
1200
+ relayReleasableSince = 0;
1020
1201
  pushLog("socket", `connected to ${resolvedWsUrl}`);
1021
1202
  // Auto-start handshake on connect
1022
1203
  void beginRtc();
1204
+ flushRelayQueue();
1205
+ startRelayWatch();
1023
1206
  };
1024
1207
 
1025
1208
  ws.onmessage = (event) => {
@@ -1034,14 +1217,24 @@ createApp({
1034
1217
 
1035
1218
  ws.onerror = () => {
1036
1219
  pushLog("socket:error", "WebSocket error");
1037
- if (ws.readyState !== WebSocket.OPEN) {
1220
+ if (ws.readyState !== WebSocket.OPEN && !relayIdle) {
1038
1221
  status.value = "disconnected";
1039
1222
  }
1040
1223
  };
1041
1224
 
1042
1225
  ws.onclose = () => {
1226
+ // A socket released on purpose, or a wake that did not get through, is not a lost
1227
+ // relay: the mesh does not depend on it, so nothing is torn down and nothing reconnects
1228
+ // until the next time the relay is needed.
1229
+ if (relayIdle) {
1230
+ socket.value = null;
1231
+ relayState.value = "idle";
1232
+ pushLog("socket", "relay idle");
1233
+ return;
1234
+ }
1043
1235
  status.value = "disconnected";
1044
1236
  socket.value = null;
1237
+ stopRelayWatch();
1045
1238
  pendingPingStartedAt = 0;
1046
1239
  pingButtonText.value = "ping";
1047
1240
  pingFlash.value = false;
@@ -1067,6 +1260,7 @@ createApp({
1067
1260
  clearTimeout(reconnectTimer);
1068
1261
  reconnectTimer = null;
1069
1262
  }
1263
+ resetRelayState();
1070
1264
 
1071
1265
  if (!socket.value) {
1072
1266
  status.value = "disconnected";
@@ -1084,15 +1278,145 @@ createApp({
1084
1278
  stopRtc();
1085
1279
  }
1086
1280
 
1281
+ // What the neighbours have recently said they can vouch for (PSP 19.7). A neighbour vouches
1282
+ // only for itself and its own live neighbours, so no id outlives the peers connected to it.
1283
+ function vouchedIds(neighbourIds) {
1284
+ const ids = [];
1285
+ for (const peerId of neighbourIds) {
1286
+ const gossip = meshLinks.get(peerId)?.anchorGossip;
1287
+ if (gossip && now() - gossip.at < RELAY_GOSSIP_TTL_MS) {
1288
+ ids.push(...gossip.ids);
1289
+ }
1290
+ }
1291
+ return ids;
1292
+ }
1293
+
1294
+ // Whether this peer needs the relay right now: it is cut off from the mesh, it is one of the
1295
+ // room's anchors, or something has just woken it (PSP 19.5, 19.6).
1296
+ async function relayDecision() {
1297
+ const neighbours = liveNeighbourIds();
1298
+ const roomKey = await closenessKey(`${normalizedAppliedNetworkValue()}:${normalizedAppliedRoomValue()}`);
1299
+ const self = fromPeer.value;
1300
+ const direct = await closestToRoom(roomKey, [self, ...neighbours], RELAY_ANCHORS);
1301
+ const anchors = await closestToRoom(roomKey, [self, ...neighbours, ...vouchedIds(neighbours)], RELAY_ANCHORS);
1302
+ const isolated = neighbours.length < RELAY_MIN_MESH_PEERS;
1303
+ const isAnchor = anchors.includes(self);
1304
+ const awake = relayWakeUntil > now();
1305
+ return { neighbours, direct, isolated, isAnchor, awake, wantRelay: isolated || isAnchor || awake };
1306
+ }
1307
+
1308
+ // Tell each live neighbour who this peer can vouch for: when the answer changes, and often
1309
+ // enough that it never goes stale at the other end.
1310
+ function broadcastAnchors(neighbourIds, direct) {
1311
+ const key = direct.join(",");
1312
+ if (key === lastAnchorBroadcast.key && now() - lastAnchorBroadcast.at < RELAY_GOSSIP_TTL_MS / 2) {
1313
+ return;
1314
+ }
1315
+ lastAnchorBroadcast = { key, at: now() };
1316
+ const frame = JSON.stringify({ type: FRAME_ANCHORS, ids: direct });
1317
+ for (const peerId of neighbourIds) {
1318
+ try {
1319
+ meshLinks.get(peerId).dc.send(frame);
1320
+ } catch {
1321
+ // A channel that refuses the frame is for the keepalive to judge.
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ // A negotiation that has not finished may be waiting on an answer that can only come by relay.
1327
+ function negotiationInFlight() {
1328
+ return Array.from(meshLinks.values()).some((link) => isNegotiatingPhase(link.phase) && now() - Number(link.lastSignalAt || 0) < CONNECT_REQUEST_TIMEOUT_MS * 2);
1329
+ }
1330
+
1331
+ function releaseRelay() {
1332
+ const ws = socket.value;
1333
+ if (relayIdle || !ws || ws.readyState !== WebSocket.OPEN) {
1334
+ return;
1335
+ }
1336
+ pushLog("relay", "the mesh is healthy and this peer is not an anchor: releasing the relay socket");
1337
+ sendWithdraw("relay_idle");
1338
+ relayIdle = true;
1339
+ relayReleasableSince = 0;
1340
+ relayState.value = "idle";
1341
+ ws.close(1000, "relay_idle");
1342
+ }
1343
+
1344
+ function wakeRelay(reason, holdMs = RELAY_LINGER_MS) {
1345
+ if (!relayOnDemand.value || manualDisconnect) {
1346
+ return false;
1347
+ }
1348
+ relayWakeUntil = Math.max(relayWakeUntil, now() + holdMs);
1349
+ relayReleasableSince = 0;
1350
+ if (!relayIdle || relayState.value === "waking") {
1351
+ return true;
1352
+ }
1353
+ pushLog("relay", `waking the relay socket: ${reason}`);
1354
+ relayState.value = "waking";
1355
+ connect();
1356
+ return true;
1357
+ }
1358
+
1359
+ async function evaluateRelay() {
1360
+ if (!relayOnDemand.value || manualDisconnect || relayEvaluating || !isConnected.value) {
1361
+ return;
1362
+ }
1363
+ relayEvaluating = true;
1364
+ try {
1365
+ const decision = await relayDecision();
1366
+ broadcastAnchors(decision.neighbours, decision.direct);
1367
+ if (decision.wantRelay) {
1368
+ relayReleasableSince = 0;
1369
+ if (relayIdle) {
1370
+ wakeRelay(decision.isolated ? "cut off from the mesh" : "anchor");
1371
+ }
1372
+ } else if (!relayIdle && socket.value?.readyState === WebSocket.OPEN && !negotiationInFlight()) {
1373
+ if (!relayReleasableSince) {
1374
+ relayReleasableSince = now();
1375
+ }
1376
+ if (now() - relayReleasableSince >= RELAY_SETTLE_MS) {
1377
+ releaseRelay();
1378
+ }
1379
+ } else {
1380
+ relayReleasableSince = 0;
1381
+ }
1382
+ } finally {
1383
+ relayEvaluating = false;
1384
+ }
1385
+ }
1386
+
1387
+ function startRelayWatch() {
1388
+ clearInterval(relayWatchTimer);
1389
+ relayWatchTimer = setInterval(() => {
1390
+ evaluateRelay().catch((error) => pushLog("relay:error", error?.message || "relay evaluation failed"));
1391
+ }, RELAY_EVAL_MS);
1392
+ }
1393
+
1394
+ function stopRelayWatch() {
1395
+ clearInterval(relayWatchTimer);
1396
+ relayWatchTimer = null;
1397
+ }
1398
+
1399
+ function resetRelayState() {
1400
+ stopRelayWatch();
1401
+ relayIdle = false;
1402
+ relayWakeUntil = 0;
1403
+ relayReleasableSince = 0;
1404
+ relayState.value = "up";
1405
+ pendingRelayEnvelopes = [];
1406
+ meshCapablePeers.clear();
1407
+ lastAnchorBroadcast = { key: "", at: 0 };
1408
+ }
1409
+
1087
1410
  function sendAnnounce(options = {}) {
1088
1411
  const { feedback = true } = options;
1412
+ lastAnnounceAt = now();
1089
1413
  const sent = sendEnvelope({
1090
1414
  psp_version: PSP_VERSION,
1091
1415
  type: "announce",
1092
1416
  network: network.value,
1093
1417
  from: fromPeer.value,
1094
1418
  to: null,
1095
- session_id: sessionId.value,
1419
+ session_id: normalizedAppliedRoomValue(),
1096
1420
  message_id: newId("announce"),
1097
1421
  timestamp: now(),
1098
1422
  ttl_ms: 30000,
@@ -1116,19 +1440,19 @@ createApp({
1116
1440
  return sent;
1117
1441
  }
1118
1442
 
1119
- function sendWithdraw() {
1443
+ function sendWithdraw(reason = "peer_offline") {
1120
1444
  sendEnvelope({
1121
1445
  psp_version: PSP_VERSION,
1122
1446
  type: "withdraw",
1123
1447
  network: network.value,
1124
1448
  from: fromPeer.value,
1125
1449
  to: null,
1126
- session_id: null,
1450
+ session_id: normalizedAppliedRoomValue(),
1127
1451
  message_id: newId("withdraw"),
1128
1452
  timestamp: now(),
1129
1453
  ttl_ms: 30000,
1130
1454
  body: {
1131
- reason: "peer_offline"
1455
+ reason
1132
1456
  }
1133
1457
  });
1134
1458
  }
@@ -1141,7 +1465,7 @@ createApp({
1141
1465
  network: network.value,
1142
1466
  from: fromPeer.value,
1143
1467
  to: null,
1144
- session_id: null,
1468
+ session_id: normalizedAppliedRoomValue(),
1145
1469
  message_id: newId("discover"),
1146
1470
  timestamp: now(),
1147
1471
  ttl_ms: 30000,
@@ -1157,7 +1481,7 @@ createApp({
1157
1481
  }
1158
1482
 
1159
1483
  function isMatchingSessionId(value) {
1160
- return normalizeText(value) === normalizeText(sessionId.value);
1484
+ return normalizeText(value) === normalizedAppliedRoomValue();
1161
1485
  }
1162
1486
 
1163
1487
  function sendPing(peerId = toPeer.value || null) {
@@ -1177,7 +1501,7 @@ createApp({
1177
1501
  network: network.value,
1178
1502
  from: fromPeer.value,
1179
1503
  to: peerId,
1180
- session_id: null,
1504
+ session_id: normalizedAppliedRoomValue(),
1181
1505
  message_id: newId("ping"),
1182
1506
  timestamp: now(),
1183
1507
  ttl_ms: 30000,
@@ -1411,12 +1735,18 @@ createApp({
1411
1735
  meshLinks.delete(peerId);
1412
1736
  }
1413
1737
 
1414
- // Re-announce every 3s to keep D1 TTL alive. Server suppresses peer_list broadcasts
1415
- // for heartbeat re-announces, so this is cheap and ensures continuous peer discovery.
1416
- sendAnnounce({ feedback: false });
1738
+ // A released relay has nothing to renew: the registration was withdrawn on purpose, and
1739
+ // an announce here would reopen the socket that was just let go (PSP 19.5).
1740
+ const relayHeld = !relayIdle && relayState.value !== "waking";
1741
+
1742
+ // Re-announce before the 30s lease ends (PSP 9.1, 26). The relay suppresses peer_list
1743
+ // broadcasts for heartbeat re-announces and leaves a lease with most of its life alone.
1744
+ if (relayHeld && now() - lastAnnounceAt >= ANNOUNCE_REFRESH_MS) {
1745
+ sendAnnounce({ feedback: false });
1746
+ }
1417
1747
 
1418
1748
  // Low-frequency discover keeps peer_list timestamps fresh when heartbeat broadcasts are suppressed.
1419
- if (autoDiscovery.value && now() - lastDiscoverSyncAt >= DISCOVER_SYNC_INTERVAL_MS) {
1749
+ if (relayHeld && autoDiscovery.value && now() - lastDiscoverSyncAt >= DISCOVER_SYNC_INTERVAL_MS) {
1420
1750
  sendDiscover({ feedback: false });
1421
1751
  lastDiscoverSyncAt = now();
1422
1752
  }
@@ -1657,16 +1987,79 @@ createApp({
1657
1987
  refreshSelectedPeerSnapshot();
1658
1988
  }
1659
1989
 
1990
+ function handlePeerControlFrame(peerId, link, frame) {
1991
+ if (frame.type === FRAME_SIGNAL) {
1992
+ const envelope = frame.envelope;
1993
+ // Without forwarding, a frame on this channel can only come from the peer at the other end.
1994
+ if (!envelope || typeof envelope !== "object" || envelope.from !== peerId || !MESH_SIGNAL_TYPES.has(envelope.type)) {
1995
+ return;
1996
+ }
1997
+ meshCapablePeers.add(peerId);
1998
+ pushLog("mesh:recv", envelope);
1999
+ void onServerEnvelope(envelope);
2000
+ return;
2001
+ }
2002
+ if (frame.type === FRAME_ANCHORS && Array.isArray(frame.ids)) {
2003
+ const ids = frame.ids
2004
+ .filter((id) => typeof id === "string" && id.length > 0 && id.length <= ANCHOR_GOSSIP_MAX_ID_CHARS)
2005
+ .slice(0, ANCHOR_GOSSIP_MAX_IDS);
2006
+ link.anchorGossip = { at: now(), ids };
2007
+ }
2008
+ }
2009
+
1660
2010
  function setupDataChannel(peerId, channel, source) {
1661
2011
  const link = getMeshLink(peerId);
1662
2012
  link.dc = channel;
1663
2013
  link.dataState = channel.readyState;
1664
2014
  pushLog("rtc:datachannel", `${peerId} attached (${source})`);
1665
2015
 
2016
+ let dcKeepaliveTimer = null;
2017
+ let lastPongAt = Date.now();
2018
+ let lastPingSentAt = 0;
2019
+
2020
+ function onTabVisible() {
2021
+ if (typeof document !== "undefined" && document.hidden) return;
2022
+ // Any ping sent while hidden can't have been answered — don't count the gap.
2023
+ lastPingSentAt = 0;
2024
+ lastPongAt = Date.now();
2025
+ }
2026
+
2027
+ function startDcKeepalive() {
2028
+ clearInterval(dcKeepaliveTimer);
2029
+ dcKeepaliveTimer = setInterval(() => {
2030
+ if (channel.readyState !== "open") return;
2031
+
2032
+ // Browser throttles timers in hidden tabs — skip timeout check while hidden.
2033
+ if (typeof document !== "undefined" && document.hidden) {
2034
+ lastPingSentAt = 0;
2035
+ lastPongAt = Date.now();
2036
+ return;
2037
+ }
2038
+
2039
+ const pingInFlight = lastPingSentAt > lastPongAt;
2040
+ if (pingInFlight && Date.now() - lastPingSentAt > DATA_PONG_TIMEOUT_MS) {
2041
+ pushLog("rtc:datachannel", `${peerId} keepalive timeout`);
2042
+ clearInterval(dcKeepaliveTimer);
2043
+ dcKeepaliveTimer = null;
2044
+ try { channel.close(); } catch { /* no-op */ }
2045
+ try { link.pc?.close(); } catch { /* no-op */ }
2046
+ return;
2047
+ }
2048
+
2049
+ try {
2050
+ channel.send(JSON.stringify({ type: "ping", ts: Date.now() }));
2051
+ lastPingSentAt = Date.now();
2052
+ } catch { /* ignore transient errors */ }
2053
+ }, DATA_PING_MS);
2054
+ }
2055
+
1666
2056
  if (channel.readyState === "open") {
1667
2057
  link.phase = "connected";
1668
2058
  pushLog("rtc:datachannel", `${peerId} open`);
1669
2059
  refreshMeshStats();
2060
+ acquireWakeLock();
2061
+ document.addEventListener("visibilitychange", onTabVisible);
2062
+ startDcKeepalive();
1670
2063
  }
1671
2064
 
1672
2065
  channel.onopen = () => {
@@ -1674,15 +2067,25 @@ createApp({
1674
2067
  link.phase = "connected";
1675
2068
  link.connectRequested = false;
1676
2069
  link.connectRequestTime = 0;
2070
+ lastPongAt = Date.now();
1677
2071
  pushLog("rtc:datachannel", `${peerId} open`);
1678
2072
  refreshMeshStats();
1679
2073
  refreshSelectedPeerSnapshot();
2074
+ acquireWakeLock();
2075
+ document.addEventListener("visibilitychange", onTabVisible);
2076
+ startDcKeepalive();
1680
2077
  };
1681
2078
 
1682
2079
  channel.onclose = () => {
1683
2080
  link.dataState = channel.readyState;
2081
+ clearInterval(dcKeepaliveTimer);
2082
+ dcKeepaliveTimer = null;
2083
+ document.removeEventListener("visibilitychange", onTabVisible);
1684
2084
  pushLog("rtc:datachannel", `${peerId} closed`);
1685
2085
  refreshMeshStats();
2086
+ // Release wake lock if no more open channels remain.
2087
+ const anyOpen = [...meshLinks.values()].some((l) => l.dc?.readyState === "open");
2088
+ if (!anyOpen) releaseWakeLock();
1686
2089
  if (!stoppingRtc && autoConnect.value && link.phase === "connected") {
1687
2090
  failoverFromCurrentPeer(peerId, "datachannel-closed");
1688
2091
  }
@@ -1694,6 +2097,22 @@ createApp({
1694
2097
  };
1695
2098
 
1696
2099
  channel.onmessage = (event) => {
2100
+ let msg;
2101
+ try { msg = JSON.parse(event.data); } catch { /* not JSON */ }
2102
+ if (msg?.type === "ping") {
2103
+ try { channel.send(JSON.stringify({ type: "pong", ts: Date.now() })); } catch { /* no-op */ }
2104
+ return;
2105
+ }
2106
+ if (msg?.type === "pong") {
2107
+ lastPongAt = Date.now();
2108
+ lastPingSentAt = 0;
2109
+ return;
2110
+ }
2111
+ // Frames that start with "~" belong to the protocol, never to the chat (PSP 19.7).
2112
+ if (typeof msg?.type === "string" && msg.type.startsWith("~")) {
2113
+ handlePeerControlFrame(peerId, link, msg);
2114
+ return;
2115
+ }
1697
2116
  pushChatMessage(event.data, "incoming");
1698
2117
  };
1699
2118
 
@@ -1706,13 +2125,7 @@ createApp({
1706
2125
  return link.pc;
1707
2126
  }
1708
2127
 
1709
- const peerPc = new RTCPeerConnection(RTC_CONFIG);
1710
- // Firefox can gather candidates more reliably with at least one media transceiver.
1711
- try {
1712
- peerPc.addTransceiver("audio", { direction: "recvonly" });
1713
- } catch {
1714
- // Ignore browser support differences.
1715
- }
2128
+ const peerPc = new RTCPeerConnection(activeRtcConfig());
1716
2129
  link.pc = peerPc;
1717
2130
  link.rtcState = peerPc.connectionState;
1718
2131
  link.phase = "ready";
@@ -1759,7 +2172,24 @@ createApp({
1759
2172
  peerPc.onicecandidateerror = (event) => {
1760
2173
  const code = event?.errorCode ?? "unknown";
1761
2174
  const text = event?.errorText ?? "unknown";
1762
- pushLog("rtc:ice-error", `${peerId} ice candidate error code=${code} text=${text}`);
2175
+ const url = event?.url ?? "n/a";
2176
+ const numericCode = Number(code);
2177
+ if (Number.isInteger(numericCode) && numericCode >= 700 && numericCode < 800) {
2178
+ pushLog("rtc:ice", `${peerId} non-fatal ICE candidate diagnostic code=${code} text=${text} url=${url}`);
2179
+ return;
2180
+ }
2181
+ pushLog("rtc:ice-error", `${peerId} ice candidate error code=${code} text=${text} url=${url}`);
2182
+ };
2183
+
2184
+ peerPc.onsignalingstatechange = () => {
2185
+ if (link.pc !== peerPc || peerPc.signalingState !== "have-local-offer") {
2186
+ return;
2187
+ }
2188
+ const pendingAnswer = link.pendingAnswer;
2189
+ if (!pendingAnswer || (link.pendingAnswerPc && link.pendingAnswerPc !== peerPc)) {
2190
+ return;
2191
+ }
2192
+ void onAnswer(pendingAnswer);
1763
2193
  };
1764
2194
 
1765
2195
  peerPc.ondatachannel = (event) => {
@@ -2275,7 +2705,12 @@ createApp({
2275
2705
  // Responder received the offer, stop waiting timeout (PSP Section 11.2)
2276
2706
  link.offerWaitTime = 0;
2277
2707
 
2278
- const peerPc = ensurePeerConnection(peerId);
2708
+ let peerPc = ensurePeerConnection(peerId);
2709
+ if (peerPc.remoteDescription?.sdp && peerPc.remoteDescription.sdp !== message.body.sdp) {
2710
+ closeMeshLink(peerId);
2711
+ peerPc = ensurePeerConnection(peerId);
2712
+ pushLog("rtc", `Replaced stale connection for new offer from ${peerId}`);
2713
+ }
2279
2714
  if (!["stable", "have-local-offer"].includes(peerPc.signalingState)) {
2280
2715
  pushLog("rtc", `Ignored stale offer from ${peerId} while in ${peerPc.signalingState}`);
2281
2716
  return;
@@ -2301,10 +2736,26 @@ createApp({
2301
2736
  try {
2302
2737
  await peerPc.setRemoteDescription({ type: "offer", sdp: message.body.sdp });
2303
2738
  } catch (error) {
2304
- pushLog("rtc:error", error?.message || `failed to apply offer from ${peerId}`);
2305
- markPeerFailed(peerId, "offer-apply-failed");
2739
+ const messageText = String(error?.message || error || "");
2740
+ const isRtpExtensionRemap = error?.name === "InvalidAccessError"
2741
+ && /remap RTP extension id/i.test(messageText);
2742
+ if (!isRtpExtensionRemap) {
2743
+ pushLog("rtc:error", messageText || `failed to apply offer from ${peerId}`);
2744
+ markPeerFailed(peerId, "offer-apply-failed");
2745
+ closeMeshLink(peerId);
2746
+ return;
2747
+ }
2306
2748
  closeMeshLink(peerId);
2307
- return;
2749
+ peerPc = ensurePeerConnection(peerId);
2750
+ pushLog("rtc", `Retrying offer from ${peerId} on fresh connection after RTP extension remap`);
2751
+ try {
2752
+ await peerPc.setRemoteDescription({ type: "offer", sdp: message.body.sdp });
2753
+ } catch (retryError) {
2754
+ pushLog("rtc:error", retryError?.message || `failed to apply offer from ${peerId}`);
2755
+ markPeerFailed(peerId, "offer-apply-failed");
2756
+ closeMeshLink(peerId);
2757
+ return;
2758
+ }
2308
2759
  }
2309
2760
 
2310
2761
  await flushPendingIceCandidates(peerId, link);
@@ -2335,8 +2786,8 @@ createApp({
2335
2786
  if (peerId === fromPeer.value) {
2336
2787
  return;
2337
2788
  }
2338
- const link = getMeshLink(peerId, false);
2339
- if (!link?.pc || link.phase === "connected") {
2789
+ const link = getMeshLink(peerId);
2790
+ if (link.phase === "connected") {
2340
2791
  return;
2341
2792
  }
2342
2793
 
@@ -2349,11 +2800,26 @@ createApp({
2349
2800
  return;
2350
2801
  }
2351
2802
 
2803
+ if (!link.pc) {
2804
+ link.pendingAnswer = message;
2805
+ link.pendingAnswerPc = null;
2806
+ pushLog("rtc", `Queued answer from isolated peer ${peerId} until a local offer is ready`);
2807
+ return;
2808
+ }
2809
+
2352
2810
  if (link.pc.signalingState !== "have-local-offer") {
2353
- pushLog("rtc", `Ignored stale answer from ${peerId} while in ${link.pc.signalingState}`);
2811
+ if (!link.dc || link.dc.readyState !== "open") {
2812
+ link.pendingAnswer = message;
2813
+ link.pendingAnswerPc = link.pc;
2814
+ pushLog("rtc", `Queued answer from isolated peer ${peerId} while in ${link.pc.signalingState}`);
2815
+ return;
2816
+ }
2817
+ pushLog("rtc", `Ignored stale answer from connected peer ${peerId} while in ${link.pc.signalingState}`);
2354
2818
  return;
2355
2819
  }
2356
2820
 
2821
+ link.pendingAnswer = null;
2822
+ link.pendingAnswerPc = null;
2357
2823
  try {
2358
2824
  await link.pc.setRemoteDescription({ type: "answer", sdp: message.body.sdp });
2359
2825
  } catch (error) {
@@ -2473,16 +2939,118 @@ createApp({
2473
2939
  }
2474
2940
 
2475
2941
  watch(
2476
- [wsUrl, network, partialMesh, partialMeshMaxPeers, chatSendMode, activeView],
2942
+ [wsUrl, network, partialMesh, partialMeshMaxPeers, chatSendMode, activeView, relayOnDemand],
2477
2943
  () => {
2478
2944
  persistUiPrefs();
2479
2945
  },
2480
2946
  { flush: "sync" }
2481
2947
  );
2482
2948
 
2949
+ // Turning it off while the relay is released brings the relay back at once.
2950
+ watch(relayOnDemand, (enabled) => {
2951
+ if (!enabled && relayIdle && relayState.value !== "waking") {
2952
+ relayState.value = "waking";
2953
+ connect();
2954
+ }
2955
+ });
2956
+
2483
2957
  loadUiPrefs();
2484
2958
  initSharedIds();
2485
2959
 
2960
+ function acquireWakeLock() {
2961
+ if (_wakeLock) return;
2962
+ if (typeof navigator === "undefined" || !("wakeLock" in navigator)) return;
2963
+ navigator.wakeLock.request("screen").then((lock) => {
2964
+ _wakeLock = lock;
2965
+ lock.addEventListener("release", () => { _wakeLock = null; });
2966
+ pushLog("wakelock", "acquired");
2967
+ }).catch(() => { /* permission denied or unavailable — not fatal */ });
2968
+ }
2969
+
2970
+ function releaseWakeLock() {
2971
+ if (!_wakeLock) return;
2972
+ try { _wakeLock.release(); } catch { /* no-op */ }
2973
+ _wakeLock = null;
2974
+ }
2975
+
2976
+ function handleTabVisible() {
2977
+ if (typeof document !== "undefined" && document.hidden) return;
2978
+ failedPeerCooldowns.clear();
2979
+ byeCooldowns.clear();
2980
+ lastDiscoverSyncAt = 0;
2981
+ // Re-acquire wake lock lost while hidden.
2982
+ const anyOpen = [...meshLinks.values()].some((l) => l.dc?.readyState === "open");
2983
+ if (anyOpen) acquireWakeLock();
2984
+ // Reconnect WebSocket if it dropped while the tab was inactive.
2985
+ if (!manualDisconnect) {
2986
+ const ws = socket.value;
2987
+ if (!ws || (ws.readyState !== WebSocket.OPEN && ws.readyState !== WebSocket.CONNECTING)) {
2988
+ pushLog("socket", "tab visible — WebSocket dropped while hidden, reconnecting");
2989
+ // Purge stale peer connections before reconnect so they don't block re-dialing.
2990
+ for (const peerId of meshLinks.keys()) closeMeshLink(peerId);
2991
+ meshLinks.clear();
2992
+ discoveredPeers.value = [];
2993
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
2994
+ connect();
2995
+ }
2996
+ }
2997
+ }
2998
+
2999
+ function handleSuspendRestore() {
3000
+ if (manualDisconnect) return;
3001
+
3002
+ pushLog("socket", "browser resumed — reconnecting immediately");
3003
+ failedPeerCooldowns.clear();
3004
+ byeCooldowns.clear();
3005
+ lastDiscoverSyncAt = 0;
3006
+ if (reconnectTimer) {
3007
+ clearTimeout(reconnectTimer);
3008
+ reconnectTimer = null;
3009
+ }
3010
+
3011
+ // A thawed browser can briefly report a dead socket as OPEN/CONNECTING.
3012
+ // Detach it so its delayed close cannot schedule a duplicate reconnect.
3013
+ const staleSocket = socket.value;
3014
+ socket.value = null;
3015
+ if (staleSocket) {
3016
+ staleSocket.onopen = null;
3017
+ staleSocket.onmessage = null;
3018
+ staleSocket.onerror = null;
3019
+ staleSocket.onclose = null;
3020
+ try { staleSocket.close(1000, "browser_resume"); } catch { /* no-op */ }
3021
+ }
3022
+
3023
+ for (const peerId of meshLinks.keys()) closeMeshLink(peerId);
3024
+ meshLinks.clear();
3025
+ discoveredPeers.value = [];
3026
+ status.value = "disconnected";
3027
+ stopAutoLoop();
3028
+ stopRtc();
3029
+ connect();
3030
+ }
3031
+
3032
+ function handleFreeze() {
3033
+ // Tab is about to be CPU-suspended — proactively withdraw from signaling.
3034
+ const ws = socket.value;
3035
+ if (ws && ws.readyState === WebSocket.OPEN) {
3036
+ try {
3037
+ ws.send(JSON.stringify({
3038
+ psp_version: PSP_VERSION,
3039
+ type: "withdraw",
3040
+ network: network.value || "room:test",
3041
+ from: fromPeer.value,
3042
+ to: null,
3043
+ session_id: normalizedAppliedRoomValue(),
3044
+ message_id: crypto.randomUUID(),
3045
+ timestamp: Date.now(),
3046
+ ttl_ms: 30000,
3047
+ body: { reason: "tab_freeze" }
3048
+ }));
3049
+ } catch { /* ignore */ }
3050
+ }
3051
+ releaseWakeLock();
3052
+ }
3053
+
2486
3054
  onMounted(() => {
2487
3055
  // Withdraw on page unload/reload using both beforeunload and pagehide to cover all cases.
2488
3056
  // Use fetch with keepalive to guarantee delivery even if socket closes immediately.
@@ -2493,7 +3061,7 @@ createApp({
2493
3061
  network: network.value || "room:test",
2494
3062
  from: fromPeer.value,
2495
3063
  to: null,
2496
- session_id: null,
3064
+ session_id: normalizedAppliedRoomValue(),
2497
3065
  message_id: crypto.randomUUID(),
2498
3066
  timestamp: Date.now(),
2499
3067
  ttl_ms: 30000,
@@ -2515,6 +3083,14 @@ createApp({
2515
3083
  }
2516
3084
  });
2517
3085
 
3086
+ // Inactive-tab resilience: reconnect when the tab becomes visible again.
3087
+ document.addEventListener("visibilitychange", handleTabVisible);
3088
+ // Page Lifecycle API: fires on freeze (CPU-suspend) and resume (thaw).
3089
+ document.addEventListener("freeze", handleFreeze);
3090
+ document.addEventListener("resume", handleSuspendRestore);
3091
+ // bfcache restore: browser shows page from back/forward cache (WS is dead).
3092
+ window.addEventListener("pageshow", (e) => { if (e.persisted) handleSuspendRestore(); });
3093
+
2518
3094
  // No-click behavior: boot socket + auto-handshake loop on load.
2519
3095
  connect();
2520
3096
  });
@@ -2535,7 +3111,6 @@ createApp({
2535
3111
  fromPeer,
2536
3112
  toPeer,
2537
3113
  sessionId,
2538
- instanceId,
2539
3114
  relayType,
2540
3115
  relayBody,
2541
3116
  discoveredPeers,
@@ -2543,6 +3118,8 @@ createApp({
2543
3118
  autoConnect,
2544
3119
  partialMesh,
2545
3120
  partialMeshMaxPeers,
3121
+ relayOnDemand,
3122
+ relayState,
2546
3123
  debugExpanded,
2547
3124
  logsText,
2548
3125
  logCount,
@@ -2575,6 +3152,7 @@ createApp({
2575
3152
  disconnect,
2576
3153
  applyWsUrlChange,
2577
3154
  applyNetworkChange,
3155
+ applyRoomChange,
2578
3156
  applyFromPeerChange,
2579
3157
  sendAnnounce,
2580
3158
  sendDiscover,
@@ -2587,8 +3165,7 @@ createApp({
2587
3165
  sendChat,
2588
3166
  hangup,
2589
3167
  regeneratePeerId,
2590
- regenerateSharedIds,
2591
- persistSharedIds,
3168
+ regenerateNetworkAndRoom,
2592
3169
  selectPeer,
2593
3170
  selectPeerFromUi,
2594
3171
  handleSpecLinkClick
@@ -2601,16 +3178,16 @@ createApp({
2601
3178
  <div class="brand-lockup">
2602
3179
  <span class="logo-badge" aria-hidden="true">
2603
3180
  <svg class="brand-icon" viewBox="0 0 48 48" role="img" aria-label="freertc logo">
2604
- <circle cx="24" cy="24" r="18" fill="none" stroke="#8b5cf6" stroke-width="2.8" />
2605
- <circle cx="24" cy="24" r="10" fill="none" stroke="#8b5cf6" stroke-width="2.4" />
2606
- <circle cx="24" cy="24" r="3.2" fill="#8b5cf6" />
2607
- <path d="M24 7.4v6.2" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" />
2608
- <path d="M24 34.4v6.2" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" />
2609
- <path d="M7.4 24h6.2" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" />
2610
- <path d="M34.4 24h6.2" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" />
3181
+ <circle cx="24" cy="24" r="18" fill="none" stroke="#bee6ee" stroke-width="2.8" />
3182
+ <circle cx="24" cy="24" r="10" fill="none" stroke="#bee6ee" stroke-width="2.4" />
3183
+ <circle cx="24" cy="24" r="3.2" fill="#bee6ee" />
3184
+ <path d="M24 7.4v6.2" stroke="#bee6ee" stroke-width="2" stroke-linecap="round" />
3185
+ <path d="M24 34.4v6.2" stroke="#bee6ee" stroke-width="2" stroke-linecap="round" />
3186
+ <path d="M7.4 24h6.2" stroke="#bee6ee" stroke-width="2" stroke-linecap="round" />
3187
+ <path d="M34.4 24h6.2" stroke="#bee6ee" stroke-width="2" stroke-linecap="round" />
2611
3188
  </svg>
2612
3189
  </span>
2613
- <h1 class="brand-wordmark"><span class="brand-free">free</span><span class="brand-rtc">rtc</span></h1>
3190
+ <h1 class="brand-wordmark"><span class="brand-free">Free</span><span class="brand-rtc">RTC</span></h1>
2614
3191
  </div>
2615
3192
  <div class="hero-copy"><a class="inline-link" :href="pspSpecUrl" target="_blank" rel="noopener noreferrer" @click="handleSpecLinkClick">PSP</a> signaling and WebRTC data-channel mesh primitives for real-time peer networking.</div>
2616
3193
  </div>
@@ -2651,8 +3228,12 @@ createApp({
2651
3228
  <input class="stat-input mono" v-model="wsUrl" @change="applyWsUrlChange" placeholder="wss://peer.ooo/ws">
2652
3229
  </div>
2653
3230
  <div class="stat-card">
2654
- <div class="stat-label">Room / Topic</div>
2655
- <input class="stat-input mono" v-model="network" @change="applyNetworkChange" placeholder="room:abc">
3231
+ <div class="stat-label">Network</div>
3232
+ <input class="stat-input mono" v-model="network" @change="applyNetworkChange" placeholder="network:abc">
3233
+ </div>
3234
+ <div class="stat-card">
3235
+ <div class="stat-label">Room</div>
3236
+ <input class="stat-input mono" v-model="sessionId" @change="applyRoomChange" placeholder="room:abc">
2656
3237
  </div>
2657
3238
  <div class="stat-card">
2658
3239
  <div class="stat-label">Your Peer ID</div>
@@ -2664,7 +3245,7 @@ createApp({
2664
3245
  <button @click="connect" :disabled="!canConnect">Connect</button>
2665
3246
  <button class="secondary" @click="disconnect" :disabled="!canDisconnect">Disconnect</button>
2666
3247
  <button class="secondary" @click="regeneratePeerId">New Peer ID</button>
2667
- <button class="secondary" @click="regenerateSharedIds">Regenerate Session + Instance IDs</button>
3248
+ <button class="secondary" @click="regenerateNetworkAndRoom">New Network + Room</button>
2668
3249
  </div>
2669
3250
 
2670
3251
  <div class="metrics">
@@ -2696,24 +3277,16 @@ createApp({
2696
3277
  </label>
2697
3278
  <label>
2698
3279
  Network
2699
- <input v-model="network" placeholder="room:abc" @change="applyNetworkChange">
3280
+ <input v-model="network" placeholder="network:abc" @change="applyNetworkChange">
2700
3281
  </label>
2701
- </div>
2702
- <div class="row">
2703
- <span class="pill"><strong>mesh</strong> {{ meshConnectedCount }}/{{ meshTargetCount }} connected</span>
2704
- </div>
2705
- <div class="field-grid">
2706
3282
  <label>
2707
- Session ID
2708
- <input v-model="sessionId" @change="applySessionIdChange">
2709
- </label>
2710
- <label>
2711
- Instance ID
2712
- <input v-model="instanceId" @change="persistSharedIds">
3283
+ Room
3284
+ <input v-model="sessionId" placeholder="room:abc" @change="applyRoomChange">
2713
3285
  </label>
2714
3286
  </div>
2715
3287
  <div class="row">
2716
- <button class="secondary" @click="regenerateSharedIds">Regenerate Session + Instance IDs</button>
3288
+ <span class="pill"><strong>mesh</strong> {{ meshConnectedCount }}/{{ meshTargetCount }} connected</span>
3289
+ <button class="secondary" @click="regenerateNetworkAndRoom">New Network + Room</button>
2717
3290
  </div>
2718
3291
  <div class="row">
2719
3292
  <button :class="{ active: announceFlash }" @click="sendAnnounce" :disabled="!isConnected">{{ announceButtonLabel }}</button>
@@ -2807,6 +3380,10 @@ createApp({
2807
3380
  <input v-if="partialMesh" type="number" min="1" max="99" :value="partialMeshMaxPeers" @input.stop="partialMeshMaxPeers = Math.max(1, parseInt($event.target.value) || 1)" @click.stop style="width:3em;font-size:0.85em;background:transparent;border:1px solid currentColor;border-radius:4px;padding:0 3px;color:inherit;text-align:center" title="Max peers" />
2808
3381
  </div>
2809
3382
  </article>
3383
+ <article class="runtime-chip" :class="relayOnDemand ? (relayState === 'idle' ? 'ok' : 'idle') : 'idle'" style="cursor:pointer" @click="relayOnDemand = !relayOnDemand" title="With a healthy mesh, a peer that is not an anchor lets go of its relay socket and signals over the mesh; it reopens the relay when it needs it (PSP 19.5)">
3384
+ <div class="runtime-label">Relay On Demand</div>
3385
+ <div class="runtime-value">{{ relayOnDemand ? 'On · relay ' + relayState : 'Off · relay up' }}</div>
3386
+ </article>
2810
3387
  <article class="runtime-chip selected">
2811
3388
  <div class="runtime-label">Send Route</div>
2812
3389
  <div class="runtime-value mono runtime-route-value" :title="sendRouteTooltip">{{ sendRouteDisplay }}</div>