kage-baileys 3.0.6 → 3.2.4

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 (217) hide show
  1. package/Example/connection.cjs +4 -0
  2. package/README.MD +4726 -48
  3. package/README.md +5941 -0
  4. package/WAProto/WAProto.proto +3395 -415
  5. package/WAProto/compat.cjs +12 -0
  6. package/WAProto/index.d.ts +47104 -19888
  7. package/WAProto/index.js +131979 -57361
  8. package/lib/Addon/http-error.js +43 -0
  9. package/lib/Addon/index.js +32 -0
  10. package/lib/Addon/keyed-db.js +250 -0
  11. package/lib/Addon/link-preview.js +82 -0
  12. package/lib/Defaults/baileys-version.json +3 -0
  13. package/lib/Defaults/connection.js +110 -0
  14. package/lib/Defaults/constants.js +156 -0
  15. package/lib/Defaults/history.js +46 -0
  16. package/lib/Defaults/index.js +230 -0
  17. package/lib/Defaults/media.js +104 -0
  18. package/lib/Defaults/phonenumber-mcc.json +223 -0
  19. package/lib/Defaults/prefix.js +44 -0
  20. package/lib/Extensions/business-advanced.js +382 -0
  21. package/lib/Extensions/business.js +159 -0
  22. package/lib/Extensions/chats-advanced.js +1106 -0
  23. package/lib/Extensions/chats.js +349 -0
  24. package/lib/Extensions/communities-advanced.js +430 -0
  25. package/lib/Extensions/community.js +94 -0
  26. package/lib/Extensions/groups-advanced.js +343 -0
  27. package/lib/Extensions/index.js +30 -0
  28. package/lib/Extensions/messages-recv-advanced.js +1690 -0
  29. package/lib/Extensions/messages-send-advanced.js +622 -0
  30. package/lib/Extensions/messages-send.js +1380 -0
  31. package/lib/Extensions/newsletter-advanced.js +228 -0
  32. package/lib/Extensions/newsletter.js +72 -0
  33. package/lib/Extensions/socket.js +389 -0
  34. package/lib/Modded/message_builder.js +2084 -4
  35. package/lib/Signal/Group/ciphertext-message.js +54 -0
  36. package/lib/Signal/Group/group-session-builder.js +124 -0
  37. package/lib/Signal/Group/group_cipher.js +216 -0
  38. package/lib/Signal/Group/index.js +124 -0
  39. package/lib/Signal/Group/keyhelper.js +108 -0
  40. package/lib/Signal/Group/sender-chain-key.js +83 -0
  41. package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
  42. package/lib/Signal/Group/sender-key-message.js +166 -0
  43. package/lib/Signal/Group/sender-key-name.js +130 -0
  44. package/lib/Signal/Group/sender-key-record.js +113 -0
  45. package/lib/Signal/Group/sender-key-state.js +208 -0
  46. package/lib/Signal/Group/sender-message-key.js +82 -0
  47. package/lib/Signal/libsignal.js +935 -0
  48. package/lib/Signal/lid-mapping.js +545 -1
  49. package/lib/Socket/Client/index.js +60 -0
  50. package/lib/Socket/Client/types.js +51 -0
  51. package/lib/Socket/Client/websocket.js +152 -0
  52. package/lib/Socket/business.js +831 -0
  53. package/lib/Socket/chats.js +2535 -49
  54. package/lib/Socket/communities.js +450 -1
  55. package/lib/Socket/community.js +1022 -0
  56. package/lib/Socket/dugong.js +1 -1
  57. package/lib/Socket/groups.js +747 -0
  58. package/lib/Socket/index.js +60 -2
  59. package/lib/Socket/messages-recv.js +3450 -5
  60. package/lib/Socket/messages-send.js +3123 -0
  61. package/lib/Socket/mex.js +126 -1
  62. package/lib/Socket/newsletter.js +465 -0
  63. package/lib/Socket/socket.js +2217 -1
  64. package/lib/Store/index.js +79 -0
  65. package/lib/Store/make-cache-manager-store.js +186 -0
  66. package/lib/Store/make-in-memory-store.js +878 -0
  67. package/lib/Store/make-ordered-dictionary.js +187 -0
  68. package/lib/Store/object-repository.js +78 -0
  69. package/lib/Types/Auth.js +25 -0
  70. package/lib/Types/Bussines.js +25 -1
  71. package/lib/Types/Call.js +25 -0
  72. package/lib/Types/Chat.js +39 -0
  73. package/lib/Types/Contact.js +25 -0
  74. package/lib/Types/Events.js +25 -0
  75. package/lib/Types/GroupMetadata.js +25 -0
  76. package/lib/Types/Label.js +76 -0
  77. package/lib/Types/LabelAssociation.js +40 -0
  78. package/lib/Types/Message.js +57 -0
  79. package/lib/Types/Mex.js +56 -1
  80. package/lib/Types/MexUpdates.js +46 -0
  81. package/lib/Types/Newsletter.js +56 -0
  82. package/lib/Types/Product.js +25 -0
  83. package/lib/Types/RichType.js +23 -0
  84. package/lib/Types/Signal.js +25 -0
  85. package/lib/Types/Socket.js +25 -0
  86. package/lib/Types/State.js +92 -0
  87. package/lib/Types/USync.js +25 -0
  88. package/lib/Types/index.js +133 -0
  89. package/lib/Utils/auth-utils.js +703 -0
  90. package/lib/Utils/automation-tools.js +51 -16
  91. package/lib/Utils/baileys-event-stream.js +146 -0
  92. package/lib/Utils/browser-utils.js +95 -0
  93. package/lib/Utils/business.js +525 -0
  94. package/lib/Utils/chat-utils.js +1861 -0
  95. package/lib/Utils/companion-reg-client-utils.js +55 -1
  96. package/lib/Utils/crypto.js +355 -0
  97. package/lib/Utils/decode-wa-message.js +709 -0
  98. package/lib/Utils/event-buffer.js +1323 -8
  99. package/lib/Utils/generics.js +945 -1
  100. package/lib/Utils/history.js +266 -0
  101. package/lib/Utils/identity-change-handler.js +62 -1
  102. package/lib/Utils/index.js +114 -0
  103. package/lib/Utils/link-preview.js +179 -0
  104. package/lib/Utils/logger.js +42 -0
  105. package/lib/Utils/lt-hash.js +73 -0
  106. package/lib/Utils/make-mutex.js +104 -0
  107. package/lib/Utils/message-inspector.js +110 -0
  108. package/lib/Utils/message-retry-manager.js +507 -2
  109. package/lib/Utils/messages-media.js +1931 -1
  110. package/lib/Utils/messages.js +3748 -0
  111. package/lib/Utils/noise-handler.js +423 -0
  112. package/lib/Utils/offline-node-processor.js +53 -1
  113. package/lib/Utils/pre-key-manager.js +255 -1
  114. package/lib/Utils/process-message.js +1592 -0
  115. package/lib/Utils/reporting-utils.js +272 -1
  116. package/lib/Utils/rich-message-utils.js +377 -0
  117. package/lib/Utils/rich-messages.js +1 -1
  118. package/lib/Utils/signal.js +437 -0
  119. package/lib/Utils/stanza-ack.js +51 -1
  120. package/lib/Utils/status-refresh.js +37 -0
  121. package/lib/Utils/status-tools.js +4 -2
  122. package/lib/Utils/sync-action-utils.js +63 -1
  123. package/lib/Utils/tc-token-utils.js +185 -1
  124. package/lib/Utils/terminal-banner.js +31 -0
  125. package/lib/Utils/use-multi-file-auth-state.js +271 -0
  126. package/lib/Utils/use-single-file-auth-state.js +108 -0
  127. package/lib/Utils/use-sqlite-auth-state.js +142 -0
  128. package/lib/Utils/validate-connection.js +497 -1
  129. package/lib/Utils/view-once-compat.js +13 -5
  130. package/lib/VoIP/audio-feeder.js +150 -0
  131. package/lib/VoIP/index.js +289 -0
  132. package/lib/VoIP/relay-transport.js +608 -0
  133. package/lib/VoIP/signaling.js +583 -0
  134. package/lib/VoIP/types.js +30 -0
  135. package/lib/VoIP/wasm-engine.js +1261 -2
  136. package/lib/VoIP/worker-bootstrap.js +1090 -2
  137. package/lib/WABinary/constants.js +2805 -0
  138. package/lib/WABinary/decode.js +649 -2
  139. package/lib/WABinary/encode.js +564 -2
  140. package/lib/WABinary/generic-utils.js +401 -0
  141. package/lib/WABinary/index.js +82 -0
  142. package/lib/WABinary/jid-utils.js +290 -0
  143. package/lib/WABinary/types.js +25 -0
  144. package/lib/WAM/BinaryInfo.js +50 -0
  145. package/lib/WAM/constants.js +45747 -0
  146. package/lib/WAM/encode.js +393 -0
  147. package/lib/WAM/index.js +78 -0
  148. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
  149. package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
  150. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
  151. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
  152. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
  153. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
  154. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
  155. package/lib/WAUSync/Protocols/index.js +83 -0
  156. package/lib/WAUSync/USyncQuery.js +241 -2
  157. package/lib/WAUSync/USyncUser.js +86 -0
  158. package/lib/WAUSync/index.js +78 -0
  159. package/lib/assets/wasm/loader.js +1875 -1
  160. package/lib/assets/wasm/worker-modules.js +11047 -1
  161. package/lib/index.d.ts +126 -0
  162. package/lib/index.js +53 -21
  163. package/lib/index.mjs +437 -0
  164. package/licenses/upstream-MIT.txt +22 -0
  165. package/maintenance/api-coverage.json +1642 -0
  166. package/maintenance/archivos-sha256.json +207 -0
  167. package/maintenance/consumer-validation.log +3 -0
  168. package/maintenance/dependency-audit.json +4 -4
  169. package/maintenance/extension-inventory.json +57 -0
  170. package/maintenance/protocol-update.json +1101 -0
  171. package/maintenance/protocol-wire-audit.json +4 -0
  172. package/maintenance/reference-socket-surface.json +209 -0
  173. package/maintenance/resumen-validacion.json +50 -0
  174. package/maintenance/validation.log +2725 -0
  175. package/maintenance/verification.json +566 -0
  176. package/package.json +107 -9
  177. package/scripts/check-imports.cjs +10 -0
  178. package/scripts/check-package.cjs +40 -0
  179. package/scripts/check-syntax.cjs +1 -1
  180. package/scripts/generate-protobuf.cjs +6 -1
  181. package/scripts/generate-public-types.cjs +9 -0
  182. package/scripts/kage-base64-fix.cjs +45 -0
  183. package/scripts/maintenance.cjs +10 -0
  184. package/test/advanced.test.cjs +24 -0
  185. package/test/base64-fix.test.cjs +49 -0
  186. package/test/maintenance.test.cjs +1 -1
  187. package/test/npm-publication.test.cjs +141 -0
  188. package/test/recepcion-reparada.test.cjs +98 -0
  189. package/test/resilience-binary.test.cjs +69 -0
  190. package/test/resilience-transport.test.cjs +34 -0
  191. package/test/types.test.ts +5 -0
  192. package/test/upgrade.test.cjs +104 -0
  193. package/tsconfig.json +20 -0
  194. package/WAProto/p.html +0 -1
  195. package/lib/KageExtra/Modded/message_builder.js +0 -2330
  196. package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
  197. package/lib/KageExtra/VoIP/index.js +0 -282
  198. package/lib/KageExtra/VoIP/relay-transport.js +0 -559
  199. package/lib/KageExtra/VoIP/signaling.js +0 -603
  200. package/lib/KageExtra/VoIP/types.js +0 -17
  201. package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
  202. package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
  203. package/lib/KageExtra/assets/wasm/loader.js +0 -5
  204. package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
  205. package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
  206. package/lib/KageExtra/index.js +0 -3
  207. package/lib/KageExtra/package.json +0 -1
  208. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  209. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  210. package/maintenance/revision-full-check.txt +0 -1097
  211. package/maintenance/revision-library-tests.tap +0 -1088
  212. package/maintenance/revision-protobuf.txt +0 -5
  213. package/maintenance/revision-syntax.txt +0 -5
  214. package/maintenance/schema-coverage.json +0 -23
  215. package/maintenance/schema-merge.json +0 -30
  216. package/maintenance/validation-node20.txt +0 -191
  217. package/maintenance/validation-node22.txt +0 -237
@@ -557,3 +557,611 @@ const appendRelayPacketLog = (direction, connection, packet) => {
557
557
  return this.#wrtcPromise;
558
558
  };
559
559
  } exports.RelayRtcTransport = RelayRtcTransport;
560
+
561
+ // Kage: herramientas de Kage.
562
+ const __kageModule105 = (() => {
563
+ const module = { exports: {} }; const exports = module.exports;
564
+ "use strict";
565
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
566
+ if (k2 === undefined) k2 = k;
567
+ var desc = Object.getOwnPropertyDescriptor(m, k);
568
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
569
+ desc = { enumerable: true, get: function() { return m[k]; } };
570
+ }
571
+ Object.defineProperty(o, k2, desc);
572
+ }) : (function(o, m, k, k2) {
573
+ if (k2 === undefined) k2 = k;
574
+ o[k2] = m[k];
575
+ }));
576
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
577
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
578
+ }) : function(o, v) {
579
+ o["default"] = v;
580
+ });
581
+ var __importStar = (this && this.__importStar) || (function () {
582
+ var ownKeys = function(o) {
583
+ ownKeys = Object.getOwnPropertyNames || function (o) {
584
+ var ar = [];
585
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
586
+ return ar;
587
+ };
588
+ return ownKeys(o);
589
+ };
590
+ return function (mod) {
591
+ if (mod && mod.__esModule) return mod;
592
+ var result = {};
593
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
594
+ __setModuleDefault(result, mod);
595
+ return result;
596
+ };
597
+ })();
598
+ Object.defineProperty(exports, "__esModule", { value: true });
599
+ exports.RelayRtcTransport = void 0;
600
+ /**
601
+ * Relay transport.
602
+ *
603
+ * Tunnels UDP traffic to WhatsApp's edge relay servers via WebRTC data
604
+ * channels (using `@roamhq/wrtc`). Mirrors the browser client's behavior:
605
+ * pre-negotiated SCTP, custom DTLS fingerprint, ICE restart on idle.
606
+ *
607
+ * @author ShellTear
608
+ */
609
+ const node_fs_1 = require("node:fs");
610
+ const RELAY_PROTO_UDP = 0;
611
+ const FAUX_WEB_CLIENT_RELAY_PORT = 3478;
612
+ const TRUE_WEB_CLIENT_RELAY_PORT = 3480;
613
+ const CONNECTION_TIMEOUT_MS = 20_000;
614
+ const ICE_RESTART_IDLE_THRESHOLD_MS = 10_000;
615
+ const ICE_RTT_POLL_MS = 1_000;
616
+ const MAX_BUFFER_SIZE = 256 * 1024;
617
+ const RELAY_PACKET_LOG_PATH = process.env.CALL_DUMP_RELAY_PACKETS_PATH ?? "";
618
+ const DISABLE_IPV6 = process.env.CALL_DISABLE_IPV6 !== "0";
619
+ const RELAY_PORT_MODE = process.env.CALL_RELAY_PORT_MODE === "original" ? "original" : "web";
620
+ const USE_ORIGINAL_RELAY_PORTS = RELAY_PORT_MODE === "original";
621
+ const RELAY_DTLS_FINGERPRINT = "F9:CA:0C:98:A3:CC:71:D6:42:CE:5A:E2:53:D2:15:20:D3:1B:BA:D8:57:A4:F0:AF:BE:0B:FB:F3:6B:0C:A0:68";
622
+ const getConnectionIdentifier = (ip, port) => ip.includes(":") ? `[${ip}]:${port}` : `${ip}:${port}`;
623
+ const createEmptyStats = () => ({
624
+ sentPackets: 0,
625
+ receivedPackets: 0,
626
+ sentBytes: 0,
627
+ receivedBytes: 0,
628
+ droppedPackets: 0,
629
+ openConnections: 0,
630
+ });
631
+ const getRelayLookupId = (ip, port) => getConnectionIdentifier(ip, port === TRUE_WEB_CLIENT_RELAY_PORT ? TRUE_WEB_CLIENT_RELAY_PORT : port);
632
+ const getRtcConnectPort = (info) => info.ip === "157.240.24.133" ? FAUX_WEB_CLIENT_RELAY_PORT : info.port;
633
+ const getVoipStackPort = (info) => {
634
+ if (USE_ORIGINAL_RELAY_PORTS)
635
+ return info.originalPort || info.port;
636
+ const sourcePort = info.originalPort || info.port;
637
+ return sourcePort === TRUE_WEB_CLIENT_RELAY_PORT
638
+ ? TRUE_WEB_CLIENT_RELAY_PORT
639
+ : FAUX_WEB_CLIENT_RELAY_PORT;
640
+ };
641
+ const bufferPacket = (connection, packet) => {
642
+ if (packet.byteLength > MAX_BUFFER_SIZE) {
643
+ connection.stats.droppedPackets += 1;
644
+ return false;
645
+ }
646
+ while (connection.packetBuffer.length > 0 &&
647
+ connection.bufferedBytes + packet.byteLength > MAX_BUFFER_SIZE) {
648
+ const dropped = connection.packetBuffer.shift();
649
+ if (dropped) {
650
+ connection.bufferedBytes -= dropped.byteLength;
651
+ connection.stats.droppedPackets += 1;
652
+ }
653
+ }
654
+ connection.packetBuffer.push(packet);
655
+ connection.bufferedBytes += packet.byteLength;
656
+ return true;
657
+ };
658
+ const shiftPacket = (connection) => {
659
+ const packet = connection.packetBuffer.shift() ?? null;
660
+ if (packet)
661
+ connection.bufferedBytes -= packet.byteLength;
662
+ return packet;
663
+ };
664
+ const replaceIceCredentials = (sdp, ufrag, pwd) => sdp
665
+ .replace(/a=ice-ufrag:[^\r\n]+/g, `a=ice-ufrag:${ufrag}`)
666
+ .replace(/a=ice-pwd:[^\r\n]+/g, `a=ice-pwd:${pwd}`);
667
+ const replaceDtlsFingerprint = (sdp, algorithm, fingerprint) => sdp.replace(/a=fingerprint:[^\r\n]+/g, `a=fingerprint:${algorithm} ${fingerprint}`);
668
+ const removeIceCandidates = (sdp) => sdp
669
+ .replace(/a=candidate:[^\r\n]+\r?\n/g, "")
670
+ .replace(/a=end-of-candidates\r?\n?/g, "");
671
+ const appendRelayCandidate = (sdp, ip, port) => {
672
+ const candidate = `a=candidate:2 1 udp 2122262783 ${ip} ${port} typ host generation 0 network-cost 5`;
673
+ return `${removeIceCandidates(sdp)}${candidate}\r\na=end-of-candidates\r\n`;
674
+ };
675
+ const buildRemoteRelayAnswer = (offerSdp, info) => {
676
+ const setupLine = info.enableEdgerayDtlsActiveMode ? "a=setup:active" : "a=setup:passive";
677
+ let answerSdp = offerSdp.replace(/a=setup:actpass/g, setupLine);
678
+ answerSdp = replaceIceCredentials(answerSdp, info.authToken ?? info.token, info.key);
679
+ answerSdp = replaceDtlsFingerprint(answerSdp, "sha-256", RELAY_DTLS_FINGERPRINT);
680
+ answerSdp = answerSdp.replace(/a=ice-options:[^\r\n]+\r\n/g, "");
681
+ answerSdp = answerSdp.replace(/a=max-message-size:[^\r\n]+/g, "a=max-message-size:1200");
682
+ return appendRelayCandidate(answerSdp, info.ip, info.port);
683
+ };
684
+ const toArrayBuffer = (data) => {
685
+ const copy = new Uint8Array(data.byteLength);
686
+ copy.set(data);
687
+ return copy.buffer;
688
+ };
689
+ const toUint8Array = (data) => {
690
+ if (data instanceof Uint8Array)
691
+ return new Uint8Array(data);
692
+ if (Buffer.isBuffer(data))
693
+ return new Uint8Array(data);
694
+ if (data instanceof ArrayBuffer)
695
+ return new Uint8Array(data);
696
+ if (data && typeof data === "object" && "byteLength" in data && "buffer" in data) {
697
+ const view = data;
698
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
699
+ }
700
+ return null;
701
+ };
702
+ const classifyRelayPacket = (packet) => {
703
+ if (packet.byteLength < 2)
704
+ return "non_stun";
705
+ const bytes = new Uint8Array(packet);
706
+ const first = bytes[0];
707
+ const second = bytes[1];
708
+ if ((first & 0xc0) !== 0)
709
+ return "non_stun";
710
+ const stunType = ((first & 0x3f) << 8) | second;
711
+ if (stunType === 0x0001)
712
+ return "stun_bind";
713
+ if (stunType === 0x0003)
714
+ return "stun_alloc";
715
+ return "stun_unknown";
716
+ };
717
+ const appendRelayPacketLog = (direction, connection, packet) => {
718
+ if (!RELAY_PACKET_LOG_PATH)
719
+ return;
720
+ const buffer = packet instanceof ArrayBuffer
721
+ ? Buffer.from(new Uint8Array(packet))
722
+ : Buffer.from(packet.buffer, packet.byteOffset, packet.byteLength);
723
+ (0, node_fs_1.appendFileSync)(RELAY_PACKET_LOG_PATH, JSON.stringify({
724
+ ts: new Date().toISOString(),
725
+ direction,
726
+ id: connection.info.id,
727
+ relayId: connection.info.relayId,
728
+ relayName: connection.info.name,
729
+ ip: connection.info.ip,
730
+ rtcPort: connection.info.port,
731
+ voipPort: getVoipStackPort(connection.info),
732
+ size: buffer.byteLength,
733
+ hex: buffer.toString("hex"),
734
+ }) + "\n");
735
+ };
736
+ class RelayRtcTransport {
737
+ config;
738
+ #relayInfoById = new Map();
739
+ #connections = new Map();
740
+ #totals = createEmptyStats();
741
+ #wrtcPromise = null;
742
+ constructor(config) {
743
+ this.config = config;
744
+ }
745
+ updateRelayList = (update) => {
746
+ const nextInfoById = new Map();
747
+ for (const relay of update.relays ?? []) {
748
+ if (relay.token_id == null || relay.token_id < 0 ||
749
+ relay.token_id >= (update.relay_tokens ?? []).length) {
750
+ continue;
751
+ }
752
+ const authToken = update.auth_tokens && relay.auth_token_id != null && relay.auth_token_id >= 0
753
+ ? update.auth_tokens[relay.auth_token_id]
754
+ : undefined;
755
+ for (const address of relay.addresses ?? []) {
756
+ if (address.protocol !== RELAY_PROTO_UDP)
757
+ continue;
758
+ if (address.ipv4 && address.port != null) {
759
+ const clientPort = USE_ORIGINAL_RELAY_PORTS ? address.port : TRUE_WEB_CLIENT_RELAY_PORT;
760
+ const id = getConnectionIdentifier(address.ipv4, clientPort);
761
+ nextInfoById.set(id, {
762
+ id,
763
+ relayId: relay.relay_id,
764
+ ip: address.ipv4,
765
+ port: clientPort,
766
+ originalPort: address.port,
767
+ isIPv6: false,
768
+ token: update.relay_tokens[relay.token_id],
769
+ authToken,
770
+ key: update.relay_key,
771
+ name: relay.relay_name,
772
+ enableEdgerayDtlsActiveMode: update.enable_edgeray_dtls_active_mode === true,
773
+ });
774
+ }
775
+ if (!DISABLE_IPV6 && address.ipv6 && address.port_v6 != null) {
776
+ const clientPort = USE_ORIGINAL_RELAY_PORTS ? address.port_v6 : TRUE_WEB_CLIENT_RELAY_PORT;
777
+ const id = getConnectionIdentifier(address.ipv6, clientPort);
778
+ nextInfoById.set(id, {
779
+ id,
780
+ relayId: relay.relay_id,
781
+ ip: address.ipv6,
782
+ port: clientPort,
783
+ originalPort: address.port_v6,
784
+ isIPv6: true,
785
+ token: update.relay_tokens[relay.token_id],
786
+ authToken,
787
+ key: update.relay_key,
788
+ name: relay.relay_name,
789
+ enableEdgerayDtlsActiveMode: update.enable_edgeray_dtls_active_mode === true,
790
+ });
791
+ }
792
+ }
793
+ }
794
+ for (const id of this.#relayInfoById.keys()) {
795
+ if (!nextInfoById.has(id))
796
+ this.#closeConnection(id);
797
+ }
798
+ this.#relayInfoById.clear();
799
+ for (const [id, info] of nextInfoById) {
800
+ this.#relayInfoById.set(id, info);
801
+ void this.#ensureConnection(info);
802
+ }
803
+ };
804
+ send = (packet, ip, port) => {
805
+ const requestedId = getConnectionIdentifier(ip, port);
806
+ const preferredPort = USE_ORIGINAL_RELAY_PORTS ? port : TRUE_WEB_CLIENT_RELAY_PORT;
807
+ const candidateIds = [
808
+ requestedId,
809
+ getConnectionIdentifier(ip, preferredPort),
810
+ getRelayLookupId(ip, TRUE_WEB_CLIENT_RELAY_PORT),
811
+ getRelayLookupId(ip, FAUX_WEB_CLIENT_RELAY_PORT),
812
+ ];
813
+ let info;
814
+ for (const candidateId of candidateIds) {
815
+ info = this.#relayInfoById.get(candidateId);
816
+ if (info)
817
+ break;
818
+ }
819
+ if (!info) {
820
+ if (DISABLE_IPV6 && ip.includes(":"))
821
+ return 0;
822
+ const earlyConnection = this.#getOrCreateEarlyConnection(ip, port);
823
+ bufferPacket(earlyConnection, toArrayBuffer(packet));
824
+ return packet.byteLength;
825
+ }
826
+ const connection = this.#getOrCreateConnection(info);
827
+ const arrayBuffer = toArrayBuffer(packet);
828
+ if (classifyRelayPacket(arrayBuffer) === "stun_alloc" &&
829
+ connection.state === "open" &&
830
+ connection.sentMedia &&
831
+ Date.now() - connection.lastRxPacketTime > ICE_RESTART_IDLE_THRESHOLD_MS) {
832
+ connection.packetBuffer = [];
833
+ connection.bufferedBytes = 0;
834
+ bufferPacket(connection, arrayBuffer);
835
+ void this.#restartIce(connection);
836
+ return packet.byteLength;
837
+ }
838
+ if (connection.state === "open" && connection.dataChannel?.readyState === "open") {
839
+ if (!this.#sendBufferedPacket(connection, arrayBuffer)) {
840
+ connection.stats.droppedPackets += 1;
841
+ }
842
+ return packet.byteLength;
843
+ }
844
+ bufferPacket(connection, arrayBuffer);
845
+ void this.#ensureConnection(info);
846
+ return packet.byteLength;
847
+ };
848
+ getStats = () => {
849
+ let openConnections = 0;
850
+ for (const connection of this.#connections.values()) {
851
+ if (connection.state === "open")
852
+ openConnections += 1;
853
+ }
854
+ return { ...this.#totals, openConnections };
855
+ };
856
+ closeAll = async () => {
857
+ for (const id of [...this.#connections.keys()])
858
+ this.#closeConnection(id);
859
+ };
860
+ // ─── private ──────────────────────────────────────────────────────────────
861
+ #getOrCreateConnection = (info) => {
862
+ const existing = this.#connections.get(info.id);
863
+ if (existing) {
864
+ existing.info = info;
865
+ return existing;
866
+ }
867
+ const created = {
868
+ info, state: "none", peerConnection: null, dataChannel: null,
869
+ iceCandidate: null, packetBuffer: [], bufferedBytes: 0,
870
+ connectPromise: null, connectionTimeout: null, iceStatsInterval: null,
871
+ lastIceRttMs: null, hasReceivedFirstPacket: false,
872
+ hasNonStunPacketSent: false, sentMedia: false, lastRxPacketTime: 0,
873
+ isReconnecting: false, stats: createEmptyStats(),
874
+ };
875
+ this.#connections.set(info.id, created);
876
+ return created;
877
+ };
878
+ #getOrCreateEarlyConnection = (ip, port) => {
879
+ const id = getConnectionIdentifier(ip, port);
880
+ const existing = this.#connections.get(id);
881
+ if (existing)
882
+ return existing;
883
+ const placeholderInfo = {
884
+ id, relayId: 0, ip, port, originalPort: port,
885
+ isIPv6: ip.includes(":"), token: "", key: "",
886
+ name: "early-packet", enableEdgerayDtlsActiveMode: false,
887
+ };
888
+ const created = {
889
+ info: placeholderInfo, state: "none", peerConnection: null,
890
+ dataChannel: null, iceCandidate: null, packetBuffer: [],
891
+ bufferedBytes: 0, connectPromise: null, connectionTimeout: null,
892
+ iceStatsInterval: null, lastIceRttMs: null,
893
+ hasReceivedFirstPacket: false, hasNonStunPacketSent: false,
894
+ sentMedia: false, lastRxPacketTime: 0, isReconnecting: false,
895
+ stats: createEmptyStats(),
896
+ };
897
+ this.#connections.set(id, created);
898
+ return created;
899
+ };
900
+ #ensureConnection = async (info) => {
901
+ const connection = this.#getOrCreateConnection(info);
902
+ if (connection.state === "open" || connection.state === "connecting") {
903
+ return connection.connectPromise ?? Promise.resolve();
904
+ }
905
+ const promise = this.#connect(connection);
906
+ connection.connectPromise = promise;
907
+ try {
908
+ await promise;
909
+ }
910
+ finally {
911
+ connection.connectPromise = null;
912
+ }
913
+ };
914
+ #connect = async (connection) => {
915
+ const wrtcModule = await this.#loadWrtc();
916
+ const { RTCPeerConnection } = wrtcModule;
917
+ if (typeof RTCPeerConnection !== "function") {
918
+ throw new Error("RTCPeerConnection unavailable from @roamhq/wrtc");
919
+ }
920
+ this.#closePeerObjects(connection);
921
+ connection.state = "connecting";
922
+ const pc = new RTCPeerConnection();
923
+ const dc = pc.createDataChannel("pre-negotiated", {
924
+ negotiated: true, id: 0, ordered: false, maxRetransmits: 0, priority: "high",
925
+ });
926
+ connection.peerConnection = pc;
927
+ connection.dataChannel = dc;
928
+ dc.binaryType = "arraybuffer";
929
+ dc.onopen = () => {
930
+ connection.state = "open";
931
+ connection.isReconnecting = false;
932
+ if (connection.connectionTimeout) {
933
+ clearTimeout(connection.connectionTimeout);
934
+ connection.connectionTimeout = null;
935
+ }
936
+ this.#flushBufferedPackets(connection);
937
+ this.#startIceRttPolling(connection);
938
+ };
939
+ dc.onclose = () => {
940
+ if (connection.state !== "failed")
941
+ connection.state = "closed";
942
+ };
943
+ dc.onerror = () => {
944
+ connection.state = "failed";
945
+ };
946
+ dc.onmessage = (event) => {
947
+ this.#handleIncomingPacket(connection, event.data);
948
+ };
949
+ pc.onicecandidate = (event) => {
950
+ if (event.candidate?.candidate && !connection.iceCandidate) {
951
+ connection.iceCandidate = event.candidate.candidate;
952
+ }
953
+ };
954
+ pc.oniceconnectionstatechange = () => {
955
+ if (pc.iceConnectionState === "failed" || pc.iceConnectionState === "closed") {
956
+ connection.state = "failed";
957
+ }
958
+ };
959
+ connection.connectionTimeout = setTimeout(() => {
960
+ if (connection.state === "connecting") {
961
+ connection.state = "failed";
962
+ this.#closePeerObjects(connection);
963
+ }
964
+ }, CONNECTION_TIMEOUT_MS);
965
+ const offer = await pc.createOffer();
966
+ await pc.setLocalDescription(offer);
967
+ const remoteSdp = buildRemoteRelayAnswer(offer.sdp ?? "", {
968
+ ...connection.info,
969
+ port: getRtcConnectPort(connection.info),
970
+ });
971
+ await pc.setRemoteDescription({ type: "answer", sdp: remoteSdp });
972
+ };
973
+ #restartIce = async (connection) => {
974
+ if (connection.isReconnecting || !connection.hasNonStunPacketSent)
975
+ return;
976
+ const { RTCPeerConnection } = await this.#loadWrtc();
977
+ if (typeof RTCPeerConnection !== "function")
978
+ return;
979
+ connection.isReconnecting = true;
980
+ try {
981
+ this.#closePeerObjects(connection);
982
+ connection.state = "connecting";
983
+ const pc = new RTCPeerConnection();
984
+ const dc = pc.createDataChannel("pre-negotiated", {
985
+ negotiated: true, id: 0, ordered: false, maxRetransmits: 0, priority: "high",
986
+ });
987
+ connection.peerConnection = pc;
988
+ connection.dataChannel = dc;
989
+ dc.binaryType = "arraybuffer";
990
+ dc.onopen = () => {
991
+ connection.state = "open";
992
+ connection.isReconnecting = false;
993
+ this.#flushBufferedPackets(connection);
994
+ this.#startIceRttPolling(connection);
995
+ };
996
+ dc.onclose = () => {
997
+ if (connection.state !== "failed")
998
+ connection.state = "closed";
999
+ };
1000
+ dc.onerror = () => { connection.state = "failed"; };
1001
+ dc.onmessage = (event) => {
1002
+ this.#handleIncomingPacket(connection, event.data);
1003
+ };
1004
+ pc.onicecandidate = (event) => {
1005
+ if (event.candidate?.candidate && !connection.iceCandidate) {
1006
+ connection.iceCandidate = event.candidate.candidate;
1007
+ }
1008
+ };
1009
+ const offer = await pc.createOffer({ iceRestart: false });
1010
+ let localSdp = offer.sdp ?? "";
1011
+ if (connection.iceCandidate) {
1012
+ localSdp = `${removeIceCandidates(localSdp)}a=${connection.iceCandidate}\r\na=end-of-candidates\r\n`;
1013
+ }
1014
+ await pc.setLocalDescription({ type: "offer", sdp: localSdp });
1015
+ const remoteSdp = buildRemoteRelayAnswer(localSdp, {
1016
+ ...connection.info,
1017
+ port: getRtcConnectPort(connection.info),
1018
+ });
1019
+ await pc.setRemoteDescription({ type: "answer", sdp: remoteSdp });
1020
+ }
1021
+ catch {
1022
+ connection.state = "failed";
1023
+ }
1024
+ finally {
1025
+ connection.isReconnecting = false;
1026
+ }
1027
+ };
1028
+ #handleIncomingPacket = (connection, raw) => {
1029
+ const packet = toUint8Array(raw);
1030
+ if (!packet)
1031
+ return;
1032
+ connection.stats.receivedPackets += 1;
1033
+ connection.stats.receivedBytes += packet.byteLength;
1034
+ connection.hasReceivedFirstPacket = true;
1035
+ connection.lastRxPacketTime = Date.now();
1036
+ this.#totals.receivedPackets += 1;
1037
+ this.#totals.receivedBytes += packet.byteLength;
1038
+ appendRelayPacketLog("recv", connection, packet);
1039
+ this.config.onTransportMessage(packet, connection.info.ip, getVoipStackPort(connection.info));
1040
+ };
1041
+ #flushBufferedPackets = (connection) => {
1042
+ while (connection.state === "open" &&
1043
+ connection.dataChannel?.readyState === "open" &&
1044
+ connection.packetBuffer.length > 0) {
1045
+ const packet = shiftPacket(connection);
1046
+ if (!packet)
1047
+ break;
1048
+ if (!this.#sendBufferedPacket(connection, packet)) {
1049
+ connection.stats.droppedPackets += 1;
1050
+ break;
1051
+ }
1052
+ }
1053
+ };
1054
+ #sendBufferedPacket = (connection, packet) => {
1055
+ try {
1056
+ connection.dataChannel?.send(packet);
1057
+ if (classifyRelayPacket(packet) === "non_stun") {
1058
+ connection.hasNonStunPacketSent = true;
1059
+ connection.sentMedia = true;
1060
+ }
1061
+ connection.stats.sentPackets += 1;
1062
+ connection.stats.sentBytes += packet.byteLength;
1063
+ this.#totals.sentPackets += 1;
1064
+ this.#totals.sentBytes += packet.byteLength;
1065
+ appendRelayPacketLog("send", connection, packet);
1066
+ return true;
1067
+ }
1068
+ catch {
1069
+ return false;
1070
+ }
1071
+ };
1072
+ #startIceRttPolling = (connection) => {
1073
+ this.#stopIceRttPolling(connection);
1074
+ const pc = connection.peerConnection;
1075
+ if (!pc || typeof pc.getStats !== "function" || !this.config.onIceRtt)
1076
+ return;
1077
+ const poll = async () => {
1078
+ const rttMs = await this.#readCurrentRoundTripTimeMs(pc);
1079
+ if (rttMs == null || connection.lastIceRttMs === rttMs)
1080
+ return;
1081
+ connection.lastIceRttMs = rttMs;
1082
+ this.config.onIceRtt?.(rttMs, connection.info.ip, connection.info.port);
1083
+ };
1084
+ void poll();
1085
+ connection.iceStatsInterval = setInterval(() => { void poll(); }, ICE_RTT_POLL_MS);
1086
+ connection.iceStatsInterval.unref?.();
1087
+ };
1088
+ #stopIceRttPolling = (connection) => {
1089
+ if (connection.iceStatsInterval) {
1090
+ clearInterval(connection.iceStatsInterval);
1091
+ connection.iceStatsInterval = null;
1092
+ }
1093
+ connection.lastIceRttMs = null;
1094
+ };
1095
+ #readCurrentRoundTripTimeMs = async (pc) => {
1096
+ try {
1097
+ const stats = await pc.getStats();
1098
+ const reports = stats && typeof stats.values === "function"
1099
+ ? Array.from(stats.values())
1100
+ : Array.isArray(stats) ? stats : Object.values(stats ?? {});
1101
+ if (!reports.length)
1102
+ return null;
1103
+ let selectedCandidatePairId = "";
1104
+ for (const report of reports) {
1105
+ if (report?.type === "transport" && typeof report.selectedCandidatePairId === "string") {
1106
+ selectedCandidatePairId = report.selectedCandidatePairId;
1107
+ break;
1108
+ }
1109
+ }
1110
+ const candidatePairs = reports.filter((r) => r?.type === "candidate-pair");
1111
+ const selectedPair = (selectedCandidatePairId && candidatePairs.find((r) => r?.id === selectedCandidatePairId)) ||
1112
+ candidatePairs.find((r) => r?.selected || r?.nominated) ||
1113
+ candidatePairs[0];
1114
+ const rttSeconds = typeof selectedPair?.currentRoundTripTime === "number"
1115
+ ? selectedPair.currentRoundTripTime
1116
+ : typeof selectedPair?.totalRoundTripTime === "number" &&
1117
+ typeof selectedPair?.responsesReceived === "number" &&
1118
+ selectedPair.responsesReceived > 0
1119
+ ? selectedPair.totalRoundTripTime / selectedPair.responsesReceived
1120
+ : null;
1121
+ if (rttSeconds == null || !Number.isFinite(rttSeconds) || rttSeconds <= 0)
1122
+ return null;
1123
+ return Math.max(1, Math.round(rttSeconds * 1000));
1124
+ }
1125
+ catch {
1126
+ return null;
1127
+ }
1128
+ };
1129
+ #closeConnection = (id) => {
1130
+ const connection = this.#connections.get(id);
1131
+ if (!connection)
1132
+ return;
1133
+ if (connection.connectionTimeout) {
1134
+ clearTimeout(connection.connectionTimeout);
1135
+ connection.connectionTimeout = null;
1136
+ }
1137
+ this.#closePeerObjects(connection);
1138
+ connection.state = "closed";
1139
+ connection.packetBuffer = [];
1140
+ connection.bufferedBytes = 0;
1141
+ this.#connections.delete(id);
1142
+ };
1143
+ #closePeerObjects = (connection) => {
1144
+ this.#stopIceRttPolling(connection);
1145
+ try {
1146
+ connection.dataChannel?.close?.();
1147
+ }
1148
+ catch { }
1149
+ try {
1150
+ connection.peerConnection?.close?.();
1151
+ }
1152
+ catch { }
1153
+ connection.dataChannel = null;
1154
+ connection.peerConnection = null;
1155
+ };
1156
+ #loadWrtc = () => {
1157
+ this.#wrtcPromise ??= Promise.resolve().then(() => __importStar(require("@roamhq/wrtc"))).then((module) => (module.default ?? module));
1158
+ return this.#wrtcPromise;
1159
+ };
1160
+ }
1161
+ exports.RelayRtcTransport = RelayRtcTransport;
1162
+
1163
+ return module.exports;
1164
+ })();
1165
+ for (const key of Object.keys(__kageModule105)) {
1166
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule105[key]});
1167
+ }