freertc 0.1.33 → 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 +205 -13
  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 -172
  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,25 +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
- if (session.startsWith("sess:")) {
121
- return session.slice(5);
122
- }
123
- return `room:${session}`;
124
- }
125
-
126
- function deriveSessionFromNetwork(networkValue) {
127
- const network = normalizeText(networkValue);
128
- if (!network || !isSpecToken(network)) {
129
- return "room:test";
130
- }
131
- return `sess:${network}`;
132
- }
133
-
134
169
  createApp({
135
170
  setup() {
136
171
  const host = window.location.host;
@@ -140,7 +175,7 @@ createApp({
140
175
  const status = ref("disconnected");
141
176
  const socket = ref(null);
142
177
 
143
- const network = ref("room:test");
178
+ const network = ref("network:test");
144
179
 
145
180
  function normalizedWsUrlValue() {
146
181
  const trimmed = normalizeText(wsUrl.value);
@@ -149,7 +184,15 @@ createApp({
149
184
 
150
185
  function normalizedNetworkValue() {
151
186
  const trimmed = normalizeText(network.value);
152
- 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";
153
196
  }
154
197
 
155
198
  // Keep peer identity in-memory per tab so duplicate tabs cannot share IDs.
@@ -163,8 +206,10 @@ createApp({
163
206
  const appliedFromPeer = ref(fromPeer.value);
164
207
  const toPeer = ref("");
165
208
  const sessionId = ref("");
166
- let sessionIdExplicit = false;
167
- 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());
168
213
 
169
214
  const activeView = ref("webrtc");
170
215
  const relayType = ref("announce");
@@ -204,6 +249,7 @@ createApp({
204
249
  let manualDisconnect = false;
205
250
  let stoppingRtc = false;
206
251
  let reconnectLockedByBye = false;
252
+ let _wakeLock = null;
207
253
  const CONNECT_REQUEST_TIMEOUT_MS = 10000; // 10 second timeout
208
254
  const DISCOVER_SYNC_INTERVAL_MS = 10000;
209
255
  const FAILED_PEER_COOLDOWN_MS = 5000;
@@ -214,6 +260,21 @@ createApp({
214
260
  const byeCooldowns = new Map();
215
261
  const meshLinks = new Map();
216
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
+
217
278
  const logs = ref([]);
218
279
 
219
280
  const isConnected = computed(() => status.value === "connected");
@@ -320,11 +381,11 @@ createApp({
320
381
  warnings.push("Signaling Server URL must be a valid absolute WebSocket URL");
321
382
  }
322
383
 
323
- const topic = normalizeText(network.value);
324
- if (!topic) {
325
- warnings.push("Room / Topic is required");
326
- } else if (!isSpecToken(topic)) {
327
- 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, . _ : / -");
328
389
  }
329
390
 
330
391
  const localPeer = normalizePeerId(fromPeer.value);
@@ -337,18 +398,11 @@ createApp({
337
398
  warnings.push("To Peer must be empty or a token-safe, fingerprint-like peer ID");
338
399
  }
339
400
 
340
- const sess = normalizeText(sessionId.value);
341
- if (!sess) {
342
- warnings.push("Session ID is required");
343
- } else if (!isSpecToken(sess)) {
344
- warnings.push("Session ID should be 1-128 chars using A-Z, a-z, 0-9, . _ : / -");
345
- }
346
-
347
- const inst = normalizeText(instanceId.value);
348
- if (!inst) {
349
- warnings.push("Instance ID is required");
350
- } else if (!isSpecToken(inst)) {
351
- 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, . _ : / -");
352
406
  }
353
407
 
354
408
  return warnings;
@@ -560,6 +614,8 @@ createApp({
560
614
  offerWaitTime: 0, // Tracks when responder started waiting for offer
561
615
  answerWaitTime: 0, // Tracks when initiator started waiting for answer
562
616
  pendingCandidates: [],
617
+ pendingAnswer: null,
618
+ pendingAnswerPc: null,
563
619
  lastSignalAt: now()
564
620
  };
565
621
  meshLinks.set(peerId, link);
@@ -691,64 +747,79 @@ createApp({
691
747
 
692
748
  function initSharedIds() {
693
749
  const params = new URLSearchParams(window.location.search);
694
- const sessionParam = normalizeText(params.get("session_id") || params.get("sessionId"));
695
- 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
+ );
696
757
  const networkParam = normalizeText(
697
758
  params.get("network") ||
698
759
  params.get("network_id") ||
699
- params.get("networkId")
760
+ params.get("networkId") ||
761
+ params.get("instance_id") ||
762
+ params.get("instanceId")
700
763
  );
701
764
 
702
- const hasValidUrlSession = isSpecToken(sessionParam);
703
- const hasValidUrlInstance = isSpecToken(instanceParam);
765
+ const hasValidUrlRoom = isSpecToken(roomParam);
704
766
  const hasValidUrlNetwork = isSpecToken(networkParam);
705
767
 
706
- if (sessionParam && !hasValidUrlSession) {
707
- pushLog("ids:error", "Ignoring invalid URL session_id");
708
- }
709
- if (instanceParam && !hasValidUrlInstance) {
710
- pushLog("ids:error", "Ignoring invalid URL instance_id");
768
+ if (roomParam && !hasValidUrlRoom) {
769
+ pushLog("room:error", "Ignoring invalid URL room");
711
770
  }
712
771
  if (networkParam && !hasValidUrlNetwork) {
713
772
  pushLog("network:error", "Ignoring invalid URL network");
714
773
  }
715
774
 
716
- sessionIdExplicit = hasValidUrlSession;
717
- instanceId.value = hasValidUrlInstance ? instanceParam : `inst-${Math.random().toString(36).slice(2, 10)}`;
718
-
719
- // Cross-domain links should land in the same room even when each origin has
720
- // different sessionStorage UI state. URL network wins; otherwise derive from session_id.
721
- const derivedNetwork = hasValidUrlSession ? deriveNetworkFromSession(sessionParam) : "";
722
- 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)}`;
723
777
  if (nextNetwork && nextNetwork !== network.value) {
724
778
  network.value = nextNetwork;
725
779
  }
726
780
  if (nextNetwork && nextNetwork !== appliedNetwork.value) {
727
781
  appliedNetwork.value = nextNetwork;
728
782
  }
729
-
730
- sessionId.value = hasValidUrlSession ? sessionParam : deriveSessionFromNetwork(nextNetwork || normalizedNetworkValue());
783
+ sessionId.value = nextRoom;
784
+ appliedSessionId.value = nextRoom;
731
785
 
732
786
  persistSharedIds();
733
787
  }
734
788
 
735
789
  function persistSharedIds() {
790
+ const canonicalNetwork = normalizedNetworkValue();
791
+ const canonicalRoom = normalizeText(sessionId.value) || "room:test";
792
+ network.value = canonicalNetwork;
793
+ sessionId.value = canonicalRoom;
794
+
736
795
  localStorage.setItem(
737
796
  SHARED_IDS_KEY,
738
797
  JSON.stringify({
739
- session_id: sessionId.value,
740
- instance_id: instanceId.value
798
+ network: canonicalNetwork,
799
+ room: canonicalRoom,
800
+ instance_id: canonicalNetwork,
801
+ session_id: canonicalRoom
741
802
  })
742
803
  );
743
804
 
744
805
  const url = new URL(window.location.href);
745
- url.searchParams.set("session_id", sessionId.value);
746
- 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");
747
816
  window.history.replaceState(null, "", url);
748
817
 
749
- pushLog("ids", {
750
- session_id: sessionId.value,
751
- instance_id: instanceId.value
818
+ pushLog("scope", {
819
+ network: canonicalNetwork,
820
+ room: canonicalRoom,
821
+ instance_id: canonicalNetwork,
822
+ session_id: canonicalRoom
752
823
  });
753
824
  }
754
825
 
@@ -769,6 +840,7 @@ createApp({
769
840
  network: normalizedNetworkValue(),
770
841
  partial_mesh: Boolean(partialMesh.value),
771
842
  partial_mesh_max_peers: normalizeMeshLimit(partialMeshMaxPeers.value),
843
+ relay_on_demand: Boolean(relayOnDemand.value),
772
844
  chat_send_mode: chatSendMode.value === "target" ? "target" : "broadcast",
773
845
  active_view: activeView.value === "console" ? "console" : "webrtc"
774
846
  })
@@ -807,6 +879,10 @@ createApp({
807
879
 
808
880
  partialMeshMaxPeers.value = normalizeMeshLimit(saved.partial_mesh_max_peers);
809
881
 
882
+ if (typeof saved.relay_on_demand === "boolean") {
883
+ relayOnDemand.value = saved.relay_on_demand;
884
+ }
885
+
810
886
  if (saved.chat_send_mode === "target" || saved.chat_send_mode === "broadcast") {
811
887
  chatSendMode.value = saved.chat_send_mode;
812
888
  }
@@ -819,45 +895,36 @@ createApp({
819
895
  }
820
896
  }
821
897
 
822
- function regenerateSharedIds() {
823
- sessionIdExplicit = true;
824
- sessionId.value = `sess-${Math.random().toString(36).slice(2, 10)}`;
825
- instanceId.value = `inst-${Math.random().toString(36).slice(2, 10)}`;
826
- persistSharedIds();
827
- pushLog("ids", "Generated new shared session_id and instance_id");
828
- }
829
-
830
- function applySessionIdChange() {
831
- sessionIdExplicit = true;
832
- persistSharedIds();
833
- }
834
-
835
- function regeneratePeerId() {
836
- fromPeer.value = randomHex();
837
- appliedFromPeer.value = fromPeer.value;
838
- toPeer.value = "";
839
- stopRtc();
840
- pushLog("ids", { peer_id: fromPeer.value });
841
-
842
- if (isConnected.value) {
843
- sendAnnounce({ feedback: false });
844
- sendDiscover({ feedback: false });
845
- }
846
- }
847
-
848
- function applyNetworkChange() {
849
- const next = normalizeText(network.value) || "room:test";
850
- const changed = next !== appliedNetwork.value;
851
- 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;
852
904
 
853
905
  if (!changed) {
906
+ network.value = nextNetwork;
907
+ sessionId.value = nextRoom;
908
+ persistSharedIds();
854
909
  return;
855
910
  }
856
- appliedNetwork.value = next;
857
911
 
858
- if (!sessionIdExplicit) {
859
- sessionId.value = deriveSessionFromNetwork(next);
860
- 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();
861
928
  }
862
929
 
863
930
  reconnectLockedByBye = false;
@@ -865,19 +932,55 @@ createApp({
865
932
  failedPeerCooldowns.clear();
866
933
  toPeer.value = "";
867
934
  discoveredPeers.value = [];
868
-
869
935
  stopAutomation();
870
936
  stopRtc();
871
937
  meshLinks.clear();
938
+
939
+ network.value = nextNetwork;
940
+ sessionId.value = nextRoom;
941
+ appliedNetwork.value = nextNetwork;
942
+ appliedSessionId.value = nextRoom;
943
+ persistSharedIds();
872
944
  refreshMeshStats();
873
945
  refreshSelectedPeerSnapshot();
874
- pushLog("network", `Switched to ${network.value}`);
946
+ pushLog("scope", message || `Switched to network ${nextNetwork}, room ${nextRoom}`);
875
947
 
876
948
  if (isConnected.value) {
877
949
  void beginRtc();
878
950
  }
879
951
  }
880
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
+
881
984
  function applyWsUrlChange() {
882
985
  const next = normalizeText(wsUrl.value);
883
986
  const resolved = next || `${wsScheme}://${host}/ws`;
@@ -936,26 +1039,91 @@ createApp({
936
1039
  }
937
1040
  }
938
1041
 
939
- function sendEnvelope(envelope) {
940
- if (!socket.value || socket.value.readyState !== WebSocket.OPEN) {
941
- 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") {
942
1046
  return false;
943
1047
  }
1048
+ return !["failed", "closed"].includes(link.rtcState);
1049
+ }
944
1050
 
945
- // Keep network token stable even if the editable field has trailing spaces.
946
- const stableNetwork = normalizedNetworkValue();
947
- if (stableNetwork !== network.value) {
948
- 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;
949
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();
950
1101
 
951
1102
  const outbound = {
952
1103
  ...envelope,
953
1104
  network: stableNetwork
954
1105
  };
955
1106
 
956
- socket.value.send(JSON.stringify(outbound));
957
- pushLog("client:send", outbound);
958
- 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;
959
1127
  }
960
1128
 
961
1129
  function sendRelayEnvelope(type, body, override = {}) {
@@ -973,7 +1141,7 @@ createApp({
973
1141
  network: network.value,
974
1142
  from: fromPeer.value,
975
1143
  to: target,
976
- session_id: sessionId.value,
1144
+ session_id: normalizedAppliedRoomValue(),
977
1145
  message_id: newId(type),
978
1146
  timestamp: now(),
979
1147
  ttl_ms: 30000,
@@ -1001,7 +1169,10 @@ createApp({
1001
1169
  socket.value = null;
1002
1170
  }
1003
1171
 
1004
- 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
+ }
1005
1176
  const resolvedWsUrl = normalizedWsUrlValue();
1006
1177
  if (resolvedWsUrl !== wsUrl.value) {
1007
1178
  wsUrl.value = resolvedWsUrl;
@@ -1011,7 +1182,11 @@ createApp({
1011
1182
  try {
1012
1183
  ws = new WebSocket(resolvedWsUrl);
1013
1184
  } catch (error) {
1014
- status.value = "disconnected";
1185
+ if (relayIdle) {
1186
+ relayState.value = "idle";
1187
+ } else {
1188
+ status.value = "disconnected";
1189
+ }
1015
1190
  socket.value = null;
1016
1191
  pushLog("socket:error", error?.message || "failed to create websocket");
1017
1192
  return;
@@ -1020,9 +1195,14 @@ createApp({
1020
1195
 
1021
1196
  ws.onopen = () => {
1022
1197
  status.value = "connected";
1198
+ relayIdle = false;
1199
+ relayState.value = "up";
1200
+ relayReleasableSince = 0;
1023
1201
  pushLog("socket", `connected to ${resolvedWsUrl}`);
1024
1202
  // Auto-start handshake on connect
1025
1203
  void beginRtc();
1204
+ flushRelayQueue();
1205
+ startRelayWatch();
1026
1206
  };
1027
1207
 
1028
1208
  ws.onmessage = (event) => {
@@ -1037,14 +1217,24 @@ createApp({
1037
1217
 
1038
1218
  ws.onerror = () => {
1039
1219
  pushLog("socket:error", "WebSocket error");
1040
- if (ws.readyState !== WebSocket.OPEN) {
1220
+ if (ws.readyState !== WebSocket.OPEN && !relayIdle) {
1041
1221
  status.value = "disconnected";
1042
1222
  }
1043
1223
  };
1044
1224
 
1045
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
+ }
1046
1235
  status.value = "disconnected";
1047
1236
  socket.value = null;
1237
+ stopRelayWatch();
1048
1238
  pendingPingStartedAt = 0;
1049
1239
  pingButtonText.value = "ping";
1050
1240
  pingFlash.value = false;
@@ -1070,6 +1260,7 @@ createApp({
1070
1260
  clearTimeout(reconnectTimer);
1071
1261
  reconnectTimer = null;
1072
1262
  }
1263
+ resetRelayState();
1073
1264
 
1074
1265
  if (!socket.value) {
1075
1266
  status.value = "disconnected";
@@ -1087,15 +1278,145 @@ createApp({
1087
1278
  stopRtc();
1088
1279
  }
1089
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
+
1090
1410
  function sendAnnounce(options = {}) {
1091
1411
  const { feedback = true } = options;
1412
+ lastAnnounceAt = now();
1092
1413
  const sent = sendEnvelope({
1093
1414
  psp_version: PSP_VERSION,
1094
1415
  type: "announce",
1095
1416
  network: network.value,
1096
1417
  from: fromPeer.value,
1097
1418
  to: null,
1098
- session_id: sessionId.value,
1419
+ session_id: normalizedAppliedRoomValue(),
1099
1420
  message_id: newId("announce"),
1100
1421
  timestamp: now(),
1101
1422
  ttl_ms: 30000,
@@ -1119,19 +1440,19 @@ createApp({
1119
1440
  return sent;
1120
1441
  }
1121
1442
 
1122
- function sendWithdraw() {
1443
+ function sendWithdraw(reason = "peer_offline") {
1123
1444
  sendEnvelope({
1124
1445
  psp_version: PSP_VERSION,
1125
1446
  type: "withdraw",
1126
1447
  network: network.value,
1127
1448
  from: fromPeer.value,
1128
1449
  to: null,
1129
- session_id: null,
1450
+ session_id: normalizedAppliedRoomValue(),
1130
1451
  message_id: newId("withdraw"),
1131
1452
  timestamp: now(),
1132
1453
  ttl_ms: 30000,
1133
1454
  body: {
1134
- reason: "peer_offline"
1455
+ reason
1135
1456
  }
1136
1457
  });
1137
1458
  }
@@ -1144,7 +1465,7 @@ createApp({
1144
1465
  network: network.value,
1145
1466
  from: fromPeer.value,
1146
1467
  to: null,
1147
- session_id: null,
1468
+ session_id: normalizedAppliedRoomValue(),
1148
1469
  message_id: newId("discover"),
1149
1470
  timestamp: now(),
1150
1471
  ttl_ms: 30000,
@@ -1160,7 +1481,7 @@ createApp({
1160
1481
  }
1161
1482
 
1162
1483
  function isMatchingSessionId(value) {
1163
- return normalizeText(value) === normalizeText(sessionId.value);
1484
+ return normalizeText(value) === normalizedAppliedRoomValue();
1164
1485
  }
1165
1486
 
1166
1487
  function sendPing(peerId = toPeer.value || null) {
@@ -1180,7 +1501,7 @@ createApp({
1180
1501
  network: network.value,
1181
1502
  from: fromPeer.value,
1182
1503
  to: peerId,
1183
- session_id: null,
1504
+ session_id: normalizedAppliedRoomValue(),
1184
1505
  message_id: newId("ping"),
1185
1506
  timestamp: now(),
1186
1507
  ttl_ms: 30000,
@@ -1414,12 +1735,18 @@ createApp({
1414
1735
  meshLinks.delete(peerId);
1415
1736
  }
1416
1737
 
1417
- // Re-announce every 3s to keep D1 TTL alive. Server suppresses peer_list broadcasts
1418
- // for heartbeat re-announces, so this is cheap and ensures continuous peer discovery.
1419
- 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
+ }
1420
1747
 
1421
1748
  // Low-frequency discover keeps peer_list timestamps fresh when heartbeat broadcasts are suppressed.
1422
- if (autoDiscovery.value && now() - lastDiscoverSyncAt >= DISCOVER_SYNC_INTERVAL_MS) {
1749
+ if (relayHeld && autoDiscovery.value && now() - lastDiscoverSyncAt >= DISCOVER_SYNC_INTERVAL_MS) {
1423
1750
  sendDiscover({ feedback: false });
1424
1751
  lastDiscoverSyncAt = now();
1425
1752
  }
@@ -1660,16 +1987,79 @@ createApp({
1660
1987
  refreshSelectedPeerSnapshot();
1661
1988
  }
1662
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
+
1663
2010
  function setupDataChannel(peerId, channel, source) {
1664
2011
  const link = getMeshLink(peerId);
1665
2012
  link.dc = channel;
1666
2013
  link.dataState = channel.readyState;
1667
2014
  pushLog("rtc:datachannel", `${peerId} attached (${source})`);
1668
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
+
1669
2056
  if (channel.readyState === "open") {
1670
2057
  link.phase = "connected";
1671
2058
  pushLog("rtc:datachannel", `${peerId} open`);
1672
2059
  refreshMeshStats();
2060
+ acquireWakeLock();
2061
+ document.addEventListener("visibilitychange", onTabVisible);
2062
+ startDcKeepalive();
1673
2063
  }
1674
2064
 
1675
2065
  channel.onopen = () => {
@@ -1677,15 +2067,25 @@ createApp({
1677
2067
  link.phase = "connected";
1678
2068
  link.connectRequested = false;
1679
2069
  link.connectRequestTime = 0;
2070
+ lastPongAt = Date.now();
1680
2071
  pushLog("rtc:datachannel", `${peerId} open`);
1681
2072
  refreshMeshStats();
1682
2073
  refreshSelectedPeerSnapshot();
2074
+ acquireWakeLock();
2075
+ document.addEventListener("visibilitychange", onTabVisible);
2076
+ startDcKeepalive();
1683
2077
  };
1684
2078
 
1685
2079
  channel.onclose = () => {
1686
2080
  link.dataState = channel.readyState;
2081
+ clearInterval(dcKeepaliveTimer);
2082
+ dcKeepaliveTimer = null;
2083
+ document.removeEventListener("visibilitychange", onTabVisible);
1687
2084
  pushLog("rtc:datachannel", `${peerId} closed`);
1688
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();
1689
2089
  if (!stoppingRtc && autoConnect.value && link.phase === "connected") {
1690
2090
  failoverFromCurrentPeer(peerId, "datachannel-closed");
1691
2091
  }
@@ -1697,6 +2097,22 @@ createApp({
1697
2097
  };
1698
2098
 
1699
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
+ }
1700
2116
  pushChatMessage(event.data, "incoming");
1701
2117
  };
1702
2118
 
@@ -1709,13 +2125,7 @@ createApp({
1709
2125
  return link.pc;
1710
2126
  }
1711
2127
 
1712
- const peerPc = new RTCPeerConnection(RTC_CONFIG);
1713
- // Firefox can gather candidates more reliably with at least one media transceiver.
1714
- try {
1715
- peerPc.addTransceiver("audio", { direction: "recvonly" });
1716
- } catch {
1717
- // Ignore browser support differences.
1718
- }
2128
+ const peerPc = new RTCPeerConnection(activeRtcConfig());
1719
2129
  link.pc = peerPc;
1720
2130
  link.rtcState = peerPc.connectionState;
1721
2131
  link.phase = "ready";
@@ -1762,7 +2172,24 @@ createApp({
1762
2172
  peerPc.onicecandidateerror = (event) => {
1763
2173
  const code = event?.errorCode ?? "unknown";
1764
2174
  const text = event?.errorText ?? "unknown";
1765
- 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);
1766
2193
  };
1767
2194
 
1768
2195
  peerPc.ondatachannel = (event) => {
@@ -2278,7 +2705,12 @@ createApp({
2278
2705
  // Responder received the offer, stop waiting timeout (PSP Section 11.2)
2279
2706
  link.offerWaitTime = 0;
2280
2707
 
2281
- 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
+ }
2282
2714
  if (!["stable", "have-local-offer"].includes(peerPc.signalingState)) {
2283
2715
  pushLog("rtc", `Ignored stale offer from ${peerId} while in ${peerPc.signalingState}`);
2284
2716
  return;
@@ -2304,10 +2736,26 @@ createApp({
2304
2736
  try {
2305
2737
  await peerPc.setRemoteDescription({ type: "offer", sdp: message.body.sdp });
2306
2738
  } catch (error) {
2307
- pushLog("rtc:error", error?.message || `failed to apply offer from ${peerId}`);
2308
- 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
+ }
2309
2748
  closeMeshLink(peerId);
2310
- 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
+ }
2311
2759
  }
2312
2760
 
2313
2761
  await flushPendingIceCandidates(peerId, link);
@@ -2338,8 +2786,8 @@ createApp({
2338
2786
  if (peerId === fromPeer.value) {
2339
2787
  return;
2340
2788
  }
2341
- const link = getMeshLink(peerId, false);
2342
- if (!link?.pc || link.phase === "connected") {
2789
+ const link = getMeshLink(peerId);
2790
+ if (link.phase === "connected") {
2343
2791
  return;
2344
2792
  }
2345
2793
 
@@ -2352,11 +2800,26 @@ createApp({
2352
2800
  return;
2353
2801
  }
2354
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
+
2355
2810
  if (link.pc.signalingState !== "have-local-offer") {
2356
- 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}`);
2357
2818
  return;
2358
2819
  }
2359
2820
 
2821
+ link.pendingAnswer = null;
2822
+ link.pendingAnswerPc = null;
2360
2823
  try {
2361
2824
  await link.pc.setRemoteDescription({ type: "answer", sdp: message.body.sdp });
2362
2825
  } catch (error) {
@@ -2476,16 +2939,118 @@ createApp({
2476
2939
  }
2477
2940
 
2478
2941
  watch(
2479
- [wsUrl, network, partialMesh, partialMeshMaxPeers, chatSendMode, activeView],
2942
+ [wsUrl, network, partialMesh, partialMeshMaxPeers, chatSendMode, activeView, relayOnDemand],
2480
2943
  () => {
2481
2944
  persistUiPrefs();
2482
2945
  },
2483
2946
  { flush: "sync" }
2484
2947
  );
2485
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
+
2486
2957
  loadUiPrefs();
2487
2958
  initSharedIds();
2488
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
+
2489
3054
  onMounted(() => {
2490
3055
  // Withdraw on page unload/reload using both beforeunload and pagehide to cover all cases.
2491
3056
  // Use fetch with keepalive to guarantee delivery even if socket closes immediately.
@@ -2496,7 +3061,7 @@ createApp({
2496
3061
  network: network.value || "room:test",
2497
3062
  from: fromPeer.value,
2498
3063
  to: null,
2499
- session_id: null,
3064
+ session_id: normalizedAppliedRoomValue(),
2500
3065
  message_id: crypto.randomUUID(),
2501
3066
  timestamp: Date.now(),
2502
3067
  ttl_ms: 30000,
@@ -2518,6 +3083,14 @@ createApp({
2518
3083
  }
2519
3084
  });
2520
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
+
2521
3094
  // No-click behavior: boot socket + auto-handshake loop on load.
2522
3095
  connect();
2523
3096
  });
@@ -2538,7 +3111,6 @@ createApp({
2538
3111
  fromPeer,
2539
3112
  toPeer,
2540
3113
  sessionId,
2541
- instanceId,
2542
3114
  relayType,
2543
3115
  relayBody,
2544
3116
  discoveredPeers,
@@ -2546,6 +3118,8 @@ createApp({
2546
3118
  autoConnect,
2547
3119
  partialMesh,
2548
3120
  partialMeshMaxPeers,
3121
+ relayOnDemand,
3122
+ relayState,
2549
3123
  debugExpanded,
2550
3124
  logsText,
2551
3125
  logCount,
@@ -2578,6 +3152,7 @@ createApp({
2578
3152
  disconnect,
2579
3153
  applyWsUrlChange,
2580
3154
  applyNetworkChange,
3155
+ applyRoomChange,
2581
3156
  applyFromPeerChange,
2582
3157
  sendAnnounce,
2583
3158
  sendDiscover,
@@ -2590,8 +3165,7 @@ createApp({
2590
3165
  sendChat,
2591
3166
  hangup,
2592
3167
  regeneratePeerId,
2593
- regenerateSharedIds,
2594
- persistSharedIds,
3168
+ regenerateNetworkAndRoom,
2595
3169
  selectPeer,
2596
3170
  selectPeerFromUi,
2597
3171
  handleSpecLinkClick
@@ -2604,16 +3178,16 @@ createApp({
2604
3178
  <div class="brand-lockup">
2605
3179
  <span class="logo-badge" aria-hidden="true">
2606
3180
  <svg class="brand-icon" viewBox="0 0 48 48" role="img" aria-label="freertc logo">
2607
- <circle cx="24" cy="24" r="18" fill="none" stroke="#8b5cf6" stroke-width="2.8" />
2608
- <circle cx="24" cy="24" r="10" fill="none" stroke="#8b5cf6" stroke-width="2.4" />
2609
- <circle cx="24" cy="24" r="3.2" fill="#8b5cf6" />
2610
- <path d="M24 7.4v6.2" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" />
2611
- <path d="M24 34.4v6.2" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" />
2612
- <path d="M7.4 24h6.2" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" />
2613
- <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" />
2614
3188
  </svg>
2615
3189
  </span>
2616
- <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>
2617
3191
  </div>
2618
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>
2619
3193
  </div>
@@ -2654,8 +3228,12 @@ createApp({
2654
3228
  <input class="stat-input mono" v-model="wsUrl" @change="applyWsUrlChange" placeholder="wss://peer.ooo/ws">
2655
3229
  </div>
2656
3230
  <div class="stat-card">
2657
- <div class="stat-label">Room / Topic</div>
2658
- <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">
2659
3237
  </div>
2660
3238
  <div class="stat-card">
2661
3239
  <div class="stat-label">Your Peer ID</div>
@@ -2667,7 +3245,7 @@ createApp({
2667
3245
  <button @click="connect" :disabled="!canConnect">Connect</button>
2668
3246
  <button class="secondary" @click="disconnect" :disabled="!canDisconnect">Disconnect</button>
2669
3247
  <button class="secondary" @click="regeneratePeerId">New Peer ID</button>
2670
- <button class="secondary" @click="regenerateSharedIds">Regenerate Session + Instance IDs</button>
3248
+ <button class="secondary" @click="regenerateNetworkAndRoom">New Network + Room</button>
2671
3249
  </div>
2672
3250
 
2673
3251
  <div class="metrics">
@@ -2699,24 +3277,16 @@ createApp({
2699
3277
  </label>
2700
3278
  <label>
2701
3279
  Network
2702
- <input v-model="network" placeholder="room:abc" @change="applyNetworkChange">
3280
+ <input v-model="network" placeholder="network:abc" @change="applyNetworkChange">
2703
3281
  </label>
2704
- </div>
2705
- <div class="row">
2706
- <span class="pill"><strong>mesh</strong> {{ meshConnectedCount }}/{{ meshTargetCount }} connected</span>
2707
- </div>
2708
- <div class="field-grid">
2709
3282
  <label>
2710
- Session ID
2711
- <input v-model="sessionId" @change="applySessionIdChange">
2712
- </label>
2713
- <label>
2714
- Instance ID
2715
- <input v-model="instanceId" @change="persistSharedIds">
3283
+ Room
3284
+ <input v-model="sessionId" placeholder="room:abc" @change="applyRoomChange">
2716
3285
  </label>
2717
3286
  </div>
2718
3287
  <div class="row">
2719
- <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>
2720
3290
  </div>
2721
3291
  <div class="row">
2722
3292
  <button :class="{ active: announceFlash }" @click="sendAnnounce" :disabled="!isConnected">{{ announceButtonLabel }}</button>
@@ -2810,6 +3380,10 @@ createApp({
2810
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" />
2811
3381
  </div>
2812
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>
2813
3387
  <article class="runtime-chip selected">
2814
3388
  <div class="runtime-label">Send Route</div>
2815
3389
  <div class="runtime-value mono runtime-route-value" :title="sendRouteTooltip">{{ sendRouteDisplay }}</div>