werift 0.25.2 → 0.26.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 (314) hide show
  1. package/lib/common/src/asn1.d.ts +42 -0
  2. package/lib/common/src/asn1.js +163 -0
  3. package/lib/common/src/asn1.js.map +1 -0
  4. package/lib/common/src/binaryData.js.map +1 -1
  5. package/lib/common/src/index.d.ts +6 -5
  6. package/lib/common/src/index.js +6 -5
  7. package/lib/common/src/index.js.map +1 -1
  8. package/lib/common/src/log.d.ts +12 -1
  9. package/lib/common/src/log.js +137 -5
  10. package/lib/common/src/log.js.map +1 -1
  11. package/lib/common/src/network.js.map +1 -1
  12. package/lib/common/src/queue.d.ts +41 -0
  13. package/lib/common/src/queue.js +146 -0
  14. package/lib/common/src/queue.js.map +1 -0
  15. package/lib/common/src/transport.d.ts +15 -2
  16. package/lib/common/src/transport.js +98 -14
  17. package/lib/common/src/transport.js.map +1 -1
  18. package/lib/dtls/src/cipher/create.js.map +1 -1
  19. package/lib/dtls/src/cipher/ec.js +8 -8
  20. package/lib/dtls/src/cipher/ec.js.map +1 -1
  21. package/lib/dtls/src/cipher/namedCurve.js +6 -7
  22. package/lib/dtls/src/cipher/namedCurve.js.map +1 -1
  23. package/lib/dtls/src/cipher/prf.d.ts +2 -2
  24. package/lib/dtls/src/cipher/prf.js +29 -8
  25. package/lib/dtls/src/cipher/prf.js.map +1 -1
  26. package/lib/dtls/src/cipher/suites/aead.d.ts +1 -1
  27. package/lib/dtls/src/context/certificate.d.ts +32 -0
  28. package/lib/dtls/src/context/certificate.js +54 -0
  29. package/lib/dtls/src/context/certificate.js.map +1 -0
  30. package/lib/dtls/src/context/cipher.d.ts +12 -6
  31. package/lib/dtls/src/context/cipher.js +52 -103
  32. package/lib/dtls/src/context/cipher.js.map +1 -1
  33. package/lib/dtls/src/context/transport.d.ts +4 -0
  34. package/lib/dtls/src/context/transport.js +14 -0
  35. package/lib/dtls/src/context/transport.js.map +1 -1
  36. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  37. package/lib/dtls/src/flight/flight.js +8 -1
  38. package/lib/dtls/src/flight/flight.js.map +1 -1
  39. package/lib/dtls/src/flight/server/flight2.js.map +1 -1
  40. package/lib/dtls/src/flight/server/flight4.d.ts +2 -1
  41. package/lib/dtls/src/flight/server/flight4.js +8 -2
  42. package/lib/dtls/src/flight/server/flight4.js.map +1 -1
  43. package/lib/dtls/src/handshake/extensions/signature.d.ts +1 -1
  44. package/lib/dtls/src/handshake/extensions/signature.js.map +1 -1
  45. package/lib/dtls/src/handshake/message/alert.js +1 -1
  46. package/lib/dtls/src/handshake/message/alert.js.map +1 -1
  47. package/lib/dtls/src/handshake/message/certificate.js +1 -1
  48. package/lib/dtls/src/handshake/message/certificate.js.map +1 -1
  49. package/lib/dtls/src/handshake/message/changeCipherSpec.js +2 -3
  50. package/lib/dtls/src/handshake/message/changeCipherSpec.js.map +1 -1
  51. package/lib/dtls/src/handshake/message/client/certificateVerify.d.ts +1 -1
  52. package/lib/dtls/src/handshake/message/client/certificateVerify.js +1 -1
  53. package/lib/dtls/src/handshake/message/client/certificateVerify.js.map +1 -1
  54. package/lib/dtls/src/handshake/message/client/hello.js +1 -1
  55. package/lib/dtls/src/handshake/message/client/hello.js.map +1 -1
  56. package/lib/dtls/src/handshake/message/client/keyExchange.js +1 -1
  57. package/lib/dtls/src/handshake/message/client/keyExchange.js.map +1 -1
  58. package/lib/dtls/src/handshake/message/server/certificateRequest.d.ts +1 -1
  59. package/lib/dtls/src/handshake/message/server/certificateRequest.js +1 -1
  60. package/lib/dtls/src/handshake/message/server/certificateRequest.js.map +1 -1
  61. package/lib/dtls/src/handshake/message/server/hello.d.ts +1 -1
  62. package/lib/dtls/src/handshake/message/server/hello.js +2 -2
  63. package/lib/dtls/src/handshake/message/server/hello.js.map +1 -1
  64. package/lib/dtls/src/handshake/message/server/helloDone.js +1 -1
  65. package/lib/dtls/src/handshake/message/server/helloDone.js.map +1 -1
  66. package/lib/dtls/src/handshake/message/server/helloVerifyRequest.js +1 -1
  67. package/lib/dtls/src/handshake/message/server/helloVerifyRequest.js.map +1 -1
  68. package/lib/dtls/src/handshake/message/server/keyExchange.d.ts +1 -1
  69. package/lib/dtls/src/handshake/message/server/keyExchange.js +1 -1
  70. package/lib/dtls/src/handshake/message/server/keyExchange.js.map +1 -1
  71. package/lib/dtls/src/handshake/random.d.ts +2 -2
  72. package/lib/dtls/src/handshake/random.js +2 -2
  73. package/lib/dtls/src/handshake/random.js.map +1 -1
  74. package/lib/dtls/src/imports/common.d.ts +1 -0
  75. package/lib/dtls/src/imports/common.js +1 -0
  76. package/lib/dtls/src/imports/common.js.map +1 -1
  77. package/lib/dtls/src/index.d.ts +2 -2
  78. package/lib/dtls/src/index.js +2 -2
  79. package/lib/dtls/src/index.js.map +1 -1
  80. package/lib/dtls/src/record/message/fragment.d.ts +1 -1
  81. package/lib/dtls/src/record/message/fragment.js +3 -3
  82. package/lib/dtls/src/record/message/fragment.js.map +1 -1
  83. package/lib/dtls/src/record/message/header.js +2 -2
  84. package/lib/dtls/src/record/message/header.js.map +1 -1
  85. package/lib/dtls/src/server.js +1 -1
  86. package/lib/dtls/src/server.js.map +1 -1
  87. package/lib/dtls/src/socket.d.ts +2 -2
  88. package/lib/dtls/src/socket.js +2 -2
  89. package/lib/dtls/src/socket.js.map +1 -1
  90. package/lib/ice/src/exceptions.d.ts +30 -0
  91. package/lib/ice/src/exceptions.js +43 -1
  92. package/lib/ice/src/exceptions.js.map +1 -1
  93. package/lib/ice/src/helper.d.ts +1 -1
  94. package/lib/ice/src/ice.d.ts +142 -0
  95. package/lib/ice/src/ice.js +809 -53
  96. package/lib/ice/src/ice.js.map +1 -1
  97. package/lib/ice/src/iceBase.d.ts +49 -0
  98. package/lib/ice/src/iceBase.js.map +1 -1
  99. package/lib/ice/src/index.d.ts +5 -5
  100. package/lib/ice/src/index.js +5 -5
  101. package/lib/ice/src/index.js.map +1 -1
  102. package/lib/ice/src/internal/resolveHostAddresses.d.ts +26 -0
  103. package/lib/ice/src/internal/resolveHostAddresses.js +45 -0
  104. package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -0
  105. package/lib/ice/src/stun/protocol.d.ts +3 -1
  106. package/lib/ice/src/stun/protocol.js +16 -0
  107. package/lib/ice/src/stun/protocol.js.map +1 -1
  108. package/lib/ice/src/stun/tcpProtocol.d.ts +2 -0
  109. package/lib/ice/src/stun/tcpProtocol.js +16 -1
  110. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  111. package/lib/ice/src/stun/transaction.d.ts +5 -0
  112. package/lib/ice/src/stun/transaction.js +7 -1
  113. package/lib/ice/src/stun/transaction.js.map +1 -1
  114. package/lib/ice/src/turn/protocol.d.ts +73 -4
  115. package/lib/ice/src/turn/protocol.js +241 -12
  116. package/lib/ice/src/turn/protocol.js.map +1 -1
  117. package/lib/ice/src/utils.js.map +1 -1
  118. package/lib/ice-server/src/stun/message.d.ts +5 -1
  119. package/lib/ice-server/src/stun/message.js +33 -2
  120. package/lib/ice-server/src/stun/message.js.map +1 -1
  121. package/lib/ice-server/src/turn/auth.d.ts +1 -1
  122. package/lib/index.mjs +16273 -10807
  123. package/lib/nonstandard/index.mjs +8644 -7911
  124. package/lib/polyfill/dom.mjs +22435 -16965
  125. package/lib/polyfill/index.mjs +22435 -16965
  126. package/lib/rtp/src/codec/h264.d.ts +1 -1
  127. package/lib/rtp/src/codec/h264.js.map +1 -1
  128. package/lib/rtp/src/extra/container/webm/container.d.ts +1 -1
  129. package/lib/rtp/src/extra/container/webm/ebml/ebml.d.ts +6 -0
  130. package/lib/rtp/src/extra/container/webm/ebml/ebml.js +20 -1
  131. package/lib/rtp/src/extra/container/webm/ebml/ebml.js.map +1 -1
  132. package/lib/rtp/src/extra/processor/depacketizer.d.ts +1 -1
  133. package/lib/rtp/src/extra/processor/depacketizer.js +1 -1
  134. package/lib/rtp/src/extra/processor/depacketizer.js.map +1 -1
  135. package/lib/rtp/src/extra/processor/depacketizerCallback.d.ts +1 -11
  136. package/lib/rtp/src/extra/processor/depacketizerTransformer.d.ts +1 -1
  137. package/lib/rtp/src/extra/processor/dtxCallback.d.ts +1 -11
  138. package/lib/rtp/src/extra/processor/interface.d.ts +16 -11
  139. package/lib/rtp/src/extra/processor/interface.js.map +1 -1
  140. package/lib/rtp/src/extra/processor/jitterBufferCallback.d.ts +1 -11
  141. package/lib/rtp/src/extra/processor/jitterBufferTransformer.d.ts +1 -1
  142. package/lib/rtp/src/extra/processor/mp4.js +1 -1
  143. package/lib/rtp/src/extra/processor/mp4.js.map +1 -1
  144. package/lib/rtp/src/extra/processor/nack.d.ts +1 -1
  145. package/lib/rtp/src/extra/processor/nack.js +1 -1
  146. package/lib/rtp/src/extra/processor/nack.js.map +1 -1
  147. package/lib/rtp/src/extra/processor/nackHandlerCallback.d.ts +1 -11
  148. package/lib/rtp/src/extra/processor/ntpTime.js.map +1 -1
  149. package/lib/rtp/src/extra/processor/ntpTimeCallback.d.ts +1 -11
  150. package/lib/rtp/src/extra/processor/rtcpCallback.d.ts +1 -1
  151. package/lib/rtp/src/extra/processor/rtcpCallback.js.map +1 -1
  152. package/lib/rtp/src/extra/processor/rtpCallback.d.ts +1 -1
  153. package/lib/rtp/src/extra/processor/rtpCallback.js +1 -1
  154. package/lib/rtp/src/extra/processor/rtpCallback.js.map +1 -1
  155. package/lib/rtp/src/extra/processor/rtpStream.d.ts +2 -2
  156. package/lib/rtp/src/extra/processor/rtpStream.js.map +1 -1
  157. package/lib/rtp/src/extra/processor/rtpTime.js.map +1 -1
  158. package/lib/rtp/src/extra/processor/rtpTimeCallback.d.ts +1 -11
  159. package/lib/rtp/src/extra/processor/webm.d.ts +27 -0
  160. package/lib/rtp/src/extra/processor/webm.js +43 -16
  161. package/lib/rtp/src/extra/processor/webm.js.map +1 -1
  162. package/lib/rtp/src/extra/processor/webmCallback.js +6 -1
  163. package/lib/rtp/src/extra/processor/webmCallback.js.map +1 -1
  164. package/lib/rtp/src/extra/processor/webmStream.js.map +1 -1
  165. package/lib/rtp/src/helper.d.ts +2 -2
  166. package/lib/rtp/src/helper.js +2 -6
  167. package/lib/rtp/src/helper.js.map +1 -1
  168. package/lib/rtp/src/index.d.ts +3 -2
  169. package/lib/rtp/src/index.js +3 -2
  170. package/lib/rtp/src/index.js.map +1 -1
  171. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js +2 -1
  172. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js.map +1 -1
  173. package/lib/rtp/src/rtcp/rtcp.js +2 -1
  174. package/lib/rtp/src/rtcp/rtcp.js.map +1 -1
  175. package/lib/rtp/src/rtcp/sr.d.ts +4 -3
  176. package/lib/rtp/src/rtcp/sr.js +3 -2
  177. package/lib/rtp/src/rtcp/sr.js.map +1 -1
  178. package/lib/rtp/src/srtp/cipher/ctr.d.ts +2 -2
  179. package/lib/rtp/src/srtp/cipher/ctr.js +1 -1
  180. package/lib/rtp/src/srtp/cipher/ctr.js.map +1 -1
  181. package/lib/rtp/src/srtp/cipher/gcm.d.ts +1 -1
  182. package/lib/rtp/src/srtp/cipher/gcm.js +1 -1
  183. package/lib/rtp/src/srtp/cipher/gcm.js.map +1 -1
  184. package/lib/rtp/src/srtp/context/context.d.ts +29 -1
  185. package/lib/rtp/src/srtp/context/context.js +78 -24
  186. package/lib/rtp/src/srtp/context/context.js.map +1 -1
  187. package/lib/rtp/src/srtp/context/srtp.js +23 -15
  188. package/lib/rtp/src/srtp/context/srtp.js.map +1 -1
  189. package/lib/sctp/src/index.d.ts +4 -3
  190. package/lib/sctp/src/index.js +10 -8
  191. package/lib/sctp/src/index.js.map +1 -1
  192. package/lib/sctp/src/sctp.d.ts +11 -2
  193. package/lib/sctp/src/sctp.js +47 -28
  194. package/lib/sctp/src/sctp.js.map +1 -1
  195. package/lib/webrtc/src/api/peerConfig.d.ts +264 -0
  196. package/lib/webrtc/src/api/peerConfig.js +250 -0
  197. package/lib/webrtc/src/api/peerConfig.js.map +1 -0
  198. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +36 -0
  199. package/lib/webrtc/src/api/peerConnectionEvents.js +44 -0
  200. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -0
  201. package/lib/webrtc/src/dataChannel.d.ts +1 -1
  202. package/lib/webrtc/src/dataChannel.js +1 -1
  203. package/lib/webrtc/src/dataChannel.js.map +1 -1
  204. package/lib/webrtc/src/index.d.ts +2 -2
  205. package/lib/webrtc/src/index.js +2 -2
  206. package/lib/webrtc/src/index.js.map +1 -1
  207. package/lib/webrtc/src/media/index.d.ts +1 -1
  208. package/lib/webrtc/src/media/index.js +1 -1
  209. package/lib/webrtc/src/media/index.js.map +1 -1
  210. package/lib/webrtc/src/media/receiver/nack.js +3 -4
  211. package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
  212. package/lib/webrtc/src/media/receiver/receiverTwcc.js.map +1 -1
  213. package/lib/webrtc/src/media/router.d.ts +116 -5
  214. package/lib/webrtc/src/media/router.js +281 -29
  215. package/lib/webrtc/src/media/router.js.map +1 -1
  216. package/lib/webrtc/src/media/rtpReceiver.d.ts +107 -12
  217. package/lib/webrtc/src/media/rtpReceiver.js +255 -28
  218. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  219. package/lib/webrtc/src/media/rtpSender.d.ts +56 -3
  220. package/lib/webrtc/src/media/rtpSender.js +180 -21
  221. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  222. package/lib/webrtc/src/media/rtpTransceiver.d.ts +94 -1
  223. package/lib/webrtc/src/media/rtpTransceiver.js +111 -2
  224. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  225. package/lib/webrtc/src/media/sender/senderBWE.d.ts +2 -1
  226. package/lib/webrtc/src/media/sender/senderBWE.js +22 -10
  227. package/lib/webrtc/src/media/sender/senderBWE.js.map +1 -1
  228. package/lib/webrtc/src/media/track.d.ts +1 -1
  229. package/lib/webrtc/src/media/track.js +1 -1
  230. package/lib/webrtc/src/media/track.js.map +1 -1
  231. package/lib/webrtc/src/negotiation/bundleTopology.d.ts +107 -0
  232. package/lib/webrtc/src/negotiation/bundleTopology.js +380 -0
  233. package/lib/webrtc/src/negotiation/bundleTopology.js.map +1 -0
  234. package/lib/webrtc/src/negotiation/descriptionValidation.d.ts +51 -0
  235. package/lib/webrtc/src/negotiation/descriptionValidation.js +261 -0
  236. package/lib/webrtc/src/negotiation/descriptionValidation.js.map +1 -0
  237. package/lib/webrtc/src/negotiation/iceRestartRequest.d.ts +21 -0
  238. package/lib/webrtc/src/negotiation/iceRestartRequest.js +61 -0
  239. package/lib/webrtc/src/negotiation/iceRestartRequest.js.map +1 -0
  240. package/lib/webrtc/src/negotiation/internalState.d.ts +34 -0
  241. package/lib/webrtc/src/negotiation/internalState.js +21 -0
  242. package/lib/webrtc/src/negotiation/internalState.js.map +1 -0
  243. package/lib/webrtc/src/negotiation/negotiationNeeded.d.ts +44 -0
  244. package/lib/webrtc/src/negotiation/negotiationNeeded.js +118 -0
  245. package/lib/webrtc/src/negotiation/negotiationNeeded.js.map +1 -0
  246. package/lib/webrtc/src/negotiation/remoteCandidates.d.ts +86 -0
  247. package/lib/webrtc/src/negotiation/remoteCandidates.js +344 -0
  248. package/lib/webrtc/src/negotiation/remoteCandidates.js.map +1 -0
  249. package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +71 -0
  250. package/lib/webrtc/src/negotiation/remoteMediaApplication.js +398 -0
  251. package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -0
  252. package/lib/webrtc/src/negotiation/transportActivation.d.ts +59 -0
  253. package/lib/webrtc/src/negotiation/transportActivation.js +345 -0
  254. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -0
  255. package/lib/webrtc/src/negotiationTransaction.d.ts +233 -0
  256. package/lib/webrtc/src/negotiationTransaction.js +591 -0
  257. package/lib/webrtc/src/negotiationTransaction.js.map +1 -0
  258. package/lib/webrtc/src/nonstandard/dummyMedia.js.map +1 -1
  259. package/lib/webrtc/src/nonstandard/index.d.ts +1 -1
  260. package/lib/webrtc/src/nonstandard/index.js +1 -1
  261. package/lib/webrtc/src/nonstandard/index.js.map +1 -1
  262. package/lib/webrtc/src/nonstandard/navigator.js.map +1 -1
  263. package/lib/webrtc/src/nonstandard/recorder/writer/index.d.ts +1 -1
  264. package/lib/webrtc/src/nonstandard/recorder/writer/index.js.map +1 -1
  265. package/lib/webrtc/src/nonstandard/recorder/writer/webm.d.ts +2 -2
  266. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js +2 -2
  267. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js.map +1 -1
  268. package/lib/webrtc/src/nonstandard/userMedia/packetizer.d.ts +2 -2
  269. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js.map +1 -1
  270. package/lib/webrtc/src/nonstandard/userMedia.d.ts +2 -2
  271. package/lib/webrtc/src/nonstandard/userMedia.js +2 -2
  272. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  273. package/lib/webrtc/src/peerConnection.d.ts +132 -237
  274. package/lib/webrtc/src/peerConnection.js +971 -908
  275. package/lib/webrtc/src/peerConnection.js.map +1 -1
  276. package/lib/webrtc/src/polyfill/api.d.ts +5 -5
  277. package/lib/webrtc/src/polyfill/api.js.map +1 -1
  278. package/lib/webrtc/src/polyfill/index.js.map +1 -1
  279. package/lib/webrtc/src/polyfill/install.js +1 -1
  280. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  281. package/lib/webrtc/src/polyfill/mediaDevices.js.map +1 -1
  282. package/lib/webrtc/src/polyfill/registers/mp4Webm.js.map +1 -1
  283. package/lib/webrtc/src/polyfill/registers/rtpRtcp.js.map +1 -1
  284. package/lib/webrtc/src/polyfill/selectSettings.js.map +1 -1
  285. package/lib/webrtc/src/polyfill/sourceIo.js.map +1 -1
  286. package/lib/webrtc/src/sctpManager.d.ts +66 -2
  287. package/lib/webrtc/src/sctpManager.js +122 -5
  288. package/lib/webrtc/src/sctpManager.js.map +1 -1
  289. package/lib/webrtc/src/sdp.js.map +1 -1
  290. package/lib/webrtc/src/sdpManager.d.ts +55 -11
  291. package/lib/webrtc/src/sdpManager.js +364 -87
  292. package/lib/webrtc/src/sdpManager.js.map +1 -1
  293. package/lib/webrtc/src/secureTransportManager.d.ts +38 -25
  294. package/lib/webrtc/src/secureTransportManager.js +130 -34
  295. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  296. package/lib/webrtc/src/transceiverManager.d.ts +62 -18
  297. package/lib/webrtc/src/transceiverManager.js +264 -104
  298. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  299. package/lib/webrtc/src/transport/dtls.d.ts +11 -2
  300. package/lib/webrtc/src/transport/dtls.js +37 -13
  301. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  302. package/lib/webrtc/src/transport/ice.d.ts +254 -7
  303. package/lib/webrtc/src/transport/ice.js +608 -52
  304. package/lib/webrtc/src/transport/ice.js.map +1 -1
  305. package/lib/webrtc/src/transport/iceCandidateAttribute.d.ts +98 -0
  306. package/lib/webrtc/src/transport/iceCandidateAttribute.js +129 -0
  307. package/lib/webrtc/src/transport/iceCandidateAttribute.js.map +1 -0
  308. package/lib/webrtc/src/transport/sctp.d.ts +4 -1
  309. package/lib/webrtc/src/transport/sctp.js +83 -17
  310. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  311. package/lib/webrtc/src/utils.d.ts +3 -3
  312. package/lib/webrtc/src/utils.js +1 -1
  313. package/lib/webrtc/src/utils.js.map +1 -1
  314. package/package.json +13 -14
@@ -34,14 +34,16 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.Connection = void 0;
37
+ const timers = __importStar(require("node:timers/promises"));
37
38
  const crypto_1 = require("crypto");
38
39
  const net_1 = require("net");
39
- const timers = __importStar(require("node:timers/promises"));
40
40
  const common_1 = require("./imports/common");
41
41
  const candidate_1 = require("./candidate");
42
42
  const lookup_1 = require("./dns/lookup");
43
+ const exceptions_1 = require("./exceptions");
43
44
  const helper_1 = require("./helper");
44
45
  const iceBase_1 = require("./iceBase");
46
+ const resolveHostAddresses_1 = require("./internal/resolveHostAddresses");
45
47
  const const_1 = require("./stun/const");
46
48
  const message_1 = require("./stun/message");
47
49
  const protocol_1 = require("./stun/protocol");
@@ -125,24 +127,73 @@ class Connection {
125
127
  writable: true,
126
128
  value: false
127
129
  });
130
+ /**
131
+ * End-of-candidates arrived while earlier candidates were still resolving
132
+ * (mDNS). No candidate is accepted any more; `remoteCandidatesEnd` follows
133
+ * once those resolutions settle.
134
+ */
135
+ Object.defineProperty(this, "remoteCandidatesEndRequested", {
136
+ enumerable: true,
137
+ configurable: true,
138
+ writable: true,
139
+ value: false
140
+ });
141
+ /** mDNS resolutions of remote candidates that arrived before end-of-candidates. */
142
+ Object.defineProperty(this, "remoteResolutions", {
143
+ enumerable: true,
144
+ configurable: true,
145
+ writable: true,
146
+ value: new Set()
147
+ });
128
148
  Object.defineProperty(this, "localCandidatesEnd", {
129
149
  enumerable: true,
130
150
  configurable: true,
131
151
  writable: true,
132
152
  value: false
133
153
  });
154
+ /** connect() began this generation's checks (their outcome sets the state). */
155
+ Object.defineProperty(this, "checksBegun", {
156
+ enumerable: true,
157
+ configurable: true,
158
+ writable: true,
159
+ value: false
160
+ });
134
161
  Object.defineProperty(this, "generation", {
135
162
  enumerable: true,
136
163
  configurable: true,
137
164
  writable: true,
138
165
  value: -1
139
166
  });
167
+ /**
168
+ * Counts every reset of the remote generation: a local ICE restart and a
169
+ * remote-only one. Remote-side work (a candidate's mDNS lookup, the wait
170
+ * for end-of-candidates, consent, a nomination in flight) belongs to the
171
+ * value it started with. A remote-only restart leaves `generation` (the
172
+ * local gathering's) alone.
173
+ */
174
+ Object.defineProperty(this, "remoteGeneration", {
175
+ enumerable: true,
176
+ configurable: true,
177
+ writable: true,
178
+ value: 0
179
+ });
180
+ /**
181
+ * Local credentials STUN requests may use, by ufrag: the current ones, the
182
+ * generation the last restart replaced and a staged (provisional) one.
183
+ */
140
184
  Object.defineProperty(this, "userHistory", {
141
185
  enumerable: true,
142
186
  configurable: true,
143
187
  writable: true,
144
188
  value: {}
145
189
  });
190
+ /** restart() ran once (the constructor's first generation exists). */
191
+ Object.defineProperty(this, "restarted", {
192
+ enumerable: true,
193
+ configurable: true,
194
+ writable: true,
195
+ value: false
196
+ });
146
197
  Object.defineProperty(this, "tieBreaker", {
147
198
  enumerable: true,
148
199
  configurable: true,
@@ -180,12 +231,70 @@ class Connection {
180
231
  writable: true,
181
232
  value: false
182
233
  });
234
+ /**
235
+ * Aborted when the remote generation ends (restart, restartRemote, close):
236
+ * every check and nomination transaction of that generation stops with it.
237
+ *
238
+ * Every STUN request of the agent and what cancels it (a late result of an
239
+ * ended generation changes no state of the generation that replaced it):
240
+ * - `checkStart` (live check): its handle (`pair.handle`: checklist
241
+ * completed, replaced, other remote ufrag dropped) and this signal; an
242
+ * aborted check changes nothing.
243
+ * - `retryCheck` (487 role conflict / 401 retry): the handle of the check
244
+ * it replaces and this signal (the retry is a `checkStart`).
245
+ * - regular nomination in `checkStart` (toward an ICE-lite peer): the
246
+ * check's signal; `isStaleNomination` guards `nominating`, the pair state
247
+ * and `checkComplete`.
248
+ * - `nominateTcpPair`: this signal; `isStaleNomination`.
249
+ * - `checkProvisional` / `nominateProvisional`: `generation.checks`
250
+ * (`endProvisional()`, a replacement pranswer, close); `belongs()`.
251
+ * - `queryConsent`: a per-request `AbortController` and
252
+ * `stopConsentLifecycle()`; `consentSessionId`.
253
+ * - `serverReflexiveCandidate` (gathering): `protocol.close()`; otherwise
254
+ * it ends by its retransmission timeout, and `stale()` drops the
255
+ * candidate of an ended gather.
256
+ * - TURN client requests: the `closing` signal and `TurnProtocol.close()`.
257
+ * Regression tests: `tests/ice/check-cancel.test.ts`.
258
+ */
259
+ Object.defineProperty(this, "remoteChecks", {
260
+ enumerable: true,
261
+ configurable: true,
262
+ writable: true,
263
+ value: new AbortController()
264
+ });
183
265
  Object.defineProperty(this, "checkListDone", {
184
266
  enumerable: true,
185
267
  configurable: true,
186
268
  writable: true,
187
269
  value: false
188
270
  });
271
+ /** Resolves when the agent closes: work that awaits the network stops waiting. */
272
+ Object.defineProperty(this, "closedSignal", {
273
+ enumerable: true,
274
+ configurable: true,
275
+ writable: true,
276
+ value: void 0
277
+ });
278
+ Object.defineProperty(this, "signalClosed", {
279
+ enumerable: true,
280
+ configurable: true,
281
+ writable: true,
282
+ value: void 0
283
+ });
284
+ /** Aborted by close(): a TURN allocation still running is released. */
285
+ Object.defineProperty(this, "closing", {
286
+ enumerable: true,
287
+ configurable: true,
288
+ writable: true,
289
+ value: new AbortController()
290
+ });
291
+ /**
292
+ * Results for connect(). Known constraint (as in develop): a restart
293
+ * replaces the queue, so a connect() still waiting on the old one never
294
+ * settles (the agent is still collected). It cannot simply return, since
295
+ * the caller (webrtc's `TransactionActivation`) treats a returned start as
296
+ * a connected ICE transport.
297
+ */
189
298
  Object.defineProperty(this, "checkListState", {
190
299
  enumerable: true,
191
300
  configurable: true,
@@ -248,6 +357,20 @@ class Connection {
248
357
  writable: true,
249
358
  value: void 0
250
359
  });
360
+ /** ICE restart generation checked beside the selected current pair. */
361
+ Object.defineProperty(this, "provisional", {
362
+ enumerable: true,
363
+ configurable: true,
364
+ writable: true,
365
+ value: void 0
366
+ });
367
+ /** Last server-reflexive candidate each UDP socket advertised. */
368
+ Object.defineProperty(this, "reflexiveBySocket", {
369
+ enumerable: true,
370
+ configurable: true,
371
+ writable: true,
372
+ value: new WeakMap()
373
+ });
251
374
  Object.defineProperty(this, "onData", {
252
375
  enumerable: true,
253
376
  configurable: true,
@@ -354,7 +477,7 @@ class Connection {
354
477
  break;
355
478
  }
356
479
  const pairId = nominated.id;
357
- const generation = this.generation;
480
+ const generation = this.remoteGeneration;
358
481
  const remotePassword = this.remotePassword;
359
482
  const { localUsername, remoteUsername, iceControlling } = this;
360
483
  const request = this.buildRequest({
@@ -397,7 +520,7 @@ class Connection {
397
520
  if (this.nominated?.id !== pairId) {
398
521
  return;
399
522
  }
400
- if (this.generation !== generation) {
523
+ if (this.remoteGeneration !== generation) {
401
524
  return;
402
525
  }
403
526
  if (this.remotePassword !== remotePassword) {
@@ -456,11 +579,18 @@ class Connection {
456
579
  enumerable: true,
457
580
  configurable: true,
458
581
  writable: true,
459
- value: (pair) => (0, helper_1.cancelable)(async (r) => {
582
+ value: (pair) => (0, helper_1.cancelable)(async (r, _f, onCancel) => {
460
583
  // """
461
584
  // Starts a check.
462
585
  // """
463
586
  log("check start", pair.toJSON());
587
+ // Resolving the handle (the checklist completed or was replaced) stops
588
+ // the request's retransmissions too.
589
+ const checks = new AbortController();
590
+ onCancel.once(() => checks.abort());
591
+ // The remote generation ending (restart / close) stops it as well.
592
+ const signal = AbortSignal.any([checks.signal, this.remoteChecks.signal]);
593
+ const remoteGeneration = this.remoteGeneration;
464
594
  pair.updateState(iceBase_1.CandidatePairState.IN_PROGRESS);
465
595
  const result = {};
466
596
  const { remotePassword, remoteUsername, generation } = this;
@@ -478,7 +608,7 @@ class Connection {
478
608
  const startTime = performance.now();
479
609
  try {
480
610
  pair.requestsSent++;
481
- const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(remotePassword, "utf8"), this.checkRequestOptions(pair));
611
+ const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal });
482
612
  pair.responsesReceived++;
483
613
  // Calculate RTT
484
614
  const endTime = performance.now();
@@ -498,6 +628,12 @@ class Connection {
498
628
  result.addr = addr;
499
629
  }
500
630
  catch (error) {
631
+ // A cancelled check (its handle resolved, or the agent closed and
632
+ // cancelled its transactions) changes nothing.
633
+ if (signal.aborted || error instanceof exceptions_1.TransactionCancelled) {
634
+ r();
635
+ return;
636
+ }
501
637
  const exc = error;
502
638
  // 7.1.3.1. Failure Cases
503
639
  log("failure case", request.toJSON(), exc.response ? JSON.stringify(exc.response.toJSON(), null, 2) : error, {
@@ -513,13 +649,13 @@ class Connection {
513
649
  else if (request.attributesKeys.includes("ICE-CONTROLLING")) {
514
650
  this.switchRole(false);
515
651
  }
516
- await this.checkStart(pair).awaitable;
652
+ await this.retryCheck(pair, onCancel);
517
653
  r();
518
654
  return;
519
655
  }
520
656
  if (exc.response?.getAttributeValue("ERROR-CODE")[0] === 401) {
521
657
  log("retry 401", pair.toJSON());
522
- await this.checkStart(pair).awaitable;
658
+ await this.retryCheck(pair, onCancel);
523
659
  r();
524
660
  return;
525
661
  }
@@ -560,13 +696,26 @@ class Connection {
560
696
  });
561
697
  try {
562
698
  pair.requestsSent++;
563
- await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), this.checkRequestOptions(pair));
699
+ await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal });
564
700
  pair.responsesReceived++;
565
701
  }
566
702
  catch (error) {
703
+ // A nomination of a generation that ended (or a cancelled check)
704
+ // must not touch the state of the generation that replaced it.
705
+ if (signal.aborted ||
706
+ error instanceof exceptions_1.TransactionCancelled ||
707
+ this.isStaleNomination(pair, remoteGeneration)) {
708
+ r();
709
+ return;
710
+ }
567
711
  this.nominating = false;
568
712
  pair.updateState(iceBase_1.CandidatePairState.FAILED);
569
713
  this.checkComplete(pair);
714
+ r();
715
+ return;
716
+ }
717
+ if (this.isStaleNomination(pair, remoteGeneration)) {
718
+ r();
570
719
  return;
571
720
  }
572
721
  pair.nominated = true;
@@ -586,6 +735,9 @@ class Connection {
586
735
  }
587
736
  }
588
737
  });
738
+ this.closedSignal = new Promise((resolve) => {
739
+ this.signalClosed = resolve;
740
+ });
589
741
  this.options = {
590
742
  ...iceBase_1.defaultOptions,
591
743
  ...options,
@@ -662,6 +814,10 @@ class Connection {
662
814
  }
663
815
  async restart() {
664
816
  this.generation++;
817
+ this.remoteGeneration++;
818
+ const previous = this.restarted
819
+ ? { [this.localUsername]: this.localPassword }
820
+ : {};
665
821
  this.localUsername = (0, helper_1.randomString)(4);
666
822
  this.localPassword = (0, helper_1.randomString)(22);
667
823
  if (this.options.localPasswordPrefix) {
@@ -669,18 +825,30 @@ class Connection {
669
825
  this.options.localPasswordPrefix +
670
826
  this.localPassword.slice(this.options.localPasswordPrefix.length);
671
827
  }
672
- this.userHistory[this.localUsername] = this.localPassword;
828
+ // Only the replaced generation's credentials stay beside the new ones
829
+ // (a check the remote peer sent before it applied the restart is still
830
+ // answered); older generations and staged credentials are dropped, so
831
+ // the history does not grow with every restart.
832
+ this.userHistory = {
833
+ ...previous,
834
+ [this.localUsername]: this.localPassword,
835
+ };
836
+ this.restarted = true;
673
837
  this.remoteUsername = "";
674
838
  this.remotePassword = "";
675
839
  this.localCandidates = [];
676
840
  this._remoteCandidates = [];
677
841
  this.remoteCandidatesEnd = false;
842
+ this.remoteCandidatesEndRequested = false;
843
+ this.remoteResolutions.clear();
678
844
  this.localCandidatesEnd = false;
845
+ this.checksBegun = false;
679
846
  this.state = "new";
680
847
  this.lookup?.close?.();
681
848
  this.lookup = undefined;
682
849
  this.nominated = undefined;
683
850
  this.nominating = false;
851
+ this.cancelChecks();
684
852
  this.checkList = [];
685
853
  this.checkListDone = false;
686
854
  this.checkListState = new helper_1.PQueue();
@@ -697,6 +865,371 @@ class Connection {
697
865
  }
698
866
  // Tear down consent timers/transactions; new credentials require a new session.
699
867
  this.stopConsentLifecycle();
868
+ this.endProvisional();
869
+ }
870
+ /**
871
+ * Only the remote side restarted (new remote credentials in an answer to an
872
+ * offer that kept the local ones): the remote generation, its checks and
873
+ * the selected pair start over; local credentials and candidates stay.
874
+ */
875
+ restartRemote() {
876
+ this.remoteGeneration++;
877
+ this.remoteUsername = "";
878
+ this.remotePassword = "";
879
+ this._remoteCandidates = [];
880
+ this.remoteCandidatesEnd = false;
881
+ this.remoteCandidatesEndRequested = false;
882
+ this.remoteResolutions.clear();
883
+ this.checksBegun = false;
884
+ this.state = "new";
885
+ this.nominated = undefined;
886
+ this.nominating = false;
887
+ this.cancelChecks();
888
+ this.checkList = [];
889
+ this.checkListDone = false;
890
+ this.checkListState = new helper_1.PQueue();
891
+ this.earlyChecks = [];
892
+ this.earlyChecksDone = false;
893
+ this.stopConsentLifecycle();
894
+ this.endProvisional();
895
+ }
896
+ /**
897
+ * Stop the checks and nominations in flight for the checklist a restart
898
+ * replaces (or close ends), and start a signal for the next generation.
899
+ */
900
+ cancelChecks() {
901
+ this.remoteChecks.abort();
902
+ this.remoteChecks = new AbortController();
903
+ for (const pair of this.checkList)
904
+ pair.handle?.resolve?.();
905
+ }
906
+ /**
907
+ * Drop the provisional generation and stop the checks still in flight for
908
+ * it (their retransmissions would outlive it).
909
+ */
910
+ endProvisional() {
911
+ this.provisional?.checks.abort();
912
+ this.provisional = undefined;
913
+ }
914
+ /** Accept provisional checks without changing the selected current pair. */
915
+ stageLocalCredentials(usernameFragment, password) {
916
+ this.userHistory[usernameFragment] = password;
917
+ this.endProvisional();
918
+ this.provisional = {
919
+ localUsername: usernameFragment,
920
+ localPassword: password,
921
+ remoteCandidates: [],
922
+ remoteCandidatesEnd: false,
923
+ remoteCandidatesEndRequested: false,
924
+ resolutions: new Set(),
925
+ revision: 0,
926
+ pairs: [],
927
+ started: false,
928
+ checks: new AbortController(),
929
+ };
930
+ }
931
+ discardStagedLocalCredentials(usernameFragment) {
932
+ if (this.provisional?.localUsername === usernameFragment) {
933
+ this.endProvisional();
934
+ }
935
+ if (usernameFragment !== this.localUsername) {
936
+ delete this.userHistory[usernameFragment];
937
+ }
938
+ }
939
+ /** Remote credentials of the provisional generation (pranswer). */
940
+ setProvisionalRemoteParams({ usernameFragment, password, }) {
941
+ const generation = this.provisional;
942
+ if (!generation)
943
+ return;
944
+ if (generation.remoteUsername === usernameFragment &&
945
+ generation.remotePassword === password) {
946
+ return;
947
+ }
948
+ // A replacement pranswer starts a new provisional checklist; candidates
949
+ // still resolving for the replaced one are dropped by `revision`.
950
+ generation.remoteUsername = usernameFragment;
951
+ generation.remotePassword = password;
952
+ generation.remoteCandidates = [];
953
+ generation.remoteCandidatesEnd = false;
954
+ generation.remoteCandidatesEndRequested = false;
955
+ generation.resolutions.clear();
956
+ generation.revision++;
957
+ generation.checks.abort();
958
+ generation.checks = new AbortController();
959
+ generation.pairs = [];
960
+ generation.nominated = undefined;
961
+ generation.nominating = false;
962
+ }
963
+ async addProvisionalRemoteCandidate(remoteCandidate) {
964
+ const generation = this.provisional;
965
+ if (!generation)
966
+ return;
967
+ const revision = generation.revision;
968
+ const current = () => this.provisional === generation && generation.revision === revision;
969
+ if (!remoteCandidate) {
970
+ if (generation.remoteCandidatesEnd ||
971
+ generation.remoteCandidatesEndRequested) {
972
+ return;
973
+ }
974
+ // Candidates that arrived before end-of-candidates finish first.
975
+ generation.remoteCandidatesEndRequested = true;
976
+ if (generation.resolutions.size > 0) {
977
+ await Promise.allSettled([...generation.resolutions]);
978
+ if (!current())
979
+ return;
980
+ }
981
+ generation.remoteCandidatesEnd = true;
982
+ return;
983
+ }
984
+ // RFC 8838: a completed generation takes no further candidates.
985
+ if (generation.remoteCandidatesEnd ||
986
+ generation.remoteCandidatesEndRequested) {
987
+ return;
988
+ }
989
+ if (remoteCandidate.host.includes(".local")) {
990
+ try {
991
+ if (!this.lookup) {
992
+ this.lookup = new lookup_1.MdnsLookup();
993
+ }
994
+ const resolution = this.lookup.lookup(remoteCandidate.host);
995
+ generation.resolutions.add(resolution);
996
+ try {
997
+ remoteCandidate.host = await resolution;
998
+ }
999
+ finally {
1000
+ generation.resolutions.delete(resolution);
1001
+ }
1002
+ }
1003
+ catch (error) {
1004
+ return;
1005
+ }
1006
+ // The generation may have been replaced or completed while resolving.
1007
+ if (!current() || generation.remoteCandidatesEnd)
1008
+ return;
1009
+ }
1010
+ try {
1011
+ (0, iceBase_1.validateRemoteCandidate)(remoteCandidate);
1012
+ }
1013
+ catch (error) {
1014
+ return;
1015
+ }
1016
+ if (!current() ||
1017
+ generation.remoteCandidates.some((c) => c.host === remoteCandidate.host &&
1018
+ c.port === remoteCandidate.port &&
1019
+ c.transport.toLowerCase() === remoteCandidate.transport.toLowerCase())) {
1020
+ return;
1021
+ }
1022
+ generation.remoteCandidates.push(remoteCandidate);
1023
+ for (const protocol of this.protocols) {
1024
+ this.tryProvisionalPair(generation, protocol, remoteCandidate);
1025
+ }
1026
+ }
1027
+ /** Start checks for the provisional generation; the selected pair is kept. */
1028
+ startProvisionalChecks() {
1029
+ const generation = this.provisional;
1030
+ if (!generation || generation.started)
1031
+ return;
1032
+ generation.started = true;
1033
+ for (const remoteCandidate of generation.remoteCandidates) {
1034
+ for (const protocol of this.protocols) {
1035
+ this.tryProvisionalPair(generation, protocol, remoteCandidate);
1036
+ }
1037
+ }
1038
+ for (const pair of generation.pairs) {
1039
+ void this.checkProvisional(generation, pair);
1040
+ }
1041
+ }
1042
+ get provisionalNominated() {
1043
+ return this.provisional?.nominated;
1044
+ }
1045
+ tryProvisionalPair(generation, protocol, remoteCandidate) {
1046
+ if (!protocol.localCandidate?.canPairWith(remoteCandidate) ||
1047
+ (protocol.localCandidate.transport.toLowerCase() === "tcp" &&
1048
+ protocol.localCandidate.tcptype === "passive" &&
1049
+ remoteCandidate.type !== "prflx") ||
1050
+ generation.pairs.some((pair) => pair.protocol === protocol &&
1051
+ pair.remoteCandidate === remoteCandidate)) {
1052
+ return;
1053
+ }
1054
+ const pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
1055
+ // The provisional checklist admits the same pairs as the live one.
1056
+ if (this.options.filterCandidatePair &&
1057
+ !this.options.filterCandidatePair(pair)) {
1058
+ return;
1059
+ }
1060
+ pair.updateState(iceBase_1.CandidatePairState.WAITING);
1061
+ generation.pairs.push(pair);
1062
+ if (generation.started)
1063
+ void this.checkProvisional(generation, pair);
1064
+ }
1065
+ async checkProvisional(generation, pair, retry = true) {
1066
+ const revision = generation.revision;
1067
+ // A check belongs to one checklist: a replacement pranswer (new revision)
1068
+ // or a replaced generation makes its outcome meaningless.
1069
+ const belongs = () => this.provisional === generation &&
1070
+ generation.revision === revision &&
1071
+ generation.pairs.includes(pair);
1072
+ if (
1073
+ // An ICE-lite agent only answers checks (RFC 8445 §2.5), in the
1074
+ // provisional generation as in the live one.
1075
+ this.iceLite ||
1076
+ !belongs() ||
1077
+ !generation.started ||
1078
+ !generation.remoteUsername ||
1079
+ !generation.remotePassword ||
1080
+ [iceBase_1.CandidatePairState.IN_PROGRESS, iceBase_1.CandidatePairState.SUCCEEDED].includes(pair.state)) {
1081
+ return;
1082
+ }
1083
+ pair.updateState(iceBase_1.CandidatePairState.IN_PROGRESS);
1084
+ const nominate = this.iceControlling && !this.remoteIsLite;
1085
+ const request = this.buildRequest({
1086
+ nominate,
1087
+ localUsername: generation.localUsername,
1088
+ remoteUsername: generation.remoteUsername,
1089
+ iceControlling: this.iceControlling,
1090
+ localCandidate: pair.localCandidate,
1091
+ });
1092
+ try {
1093
+ pair.requestsSent++;
1094
+ const [, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(generation.remotePassword, "utf8"), {
1095
+ retransmissions: pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4,
1096
+ signal: generation.checks.signal,
1097
+ });
1098
+ pair.responsesReceived++;
1099
+ if (!belongs())
1100
+ return;
1101
+ if (addr[0] !== pair.remoteAddr[0] || addr[1] !== pair.remoteAddr[1]) {
1102
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
1103
+ return;
1104
+ }
1105
+ }
1106
+ catch (error) {
1107
+ if (!belongs())
1108
+ return;
1109
+ const code = error.response?.getAttributeValue("ERROR-CODE")?.[0];
1110
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
1111
+ if (code === 487 && retry) {
1112
+ this.switchRole(request.attributesKeys.includes("ICE-CONTROLLED"));
1113
+ pair.updateState(iceBase_1.CandidatePairState.WAITING);
1114
+ return this.checkProvisional(generation, pair, false);
1115
+ }
1116
+ return;
1117
+ }
1118
+ if (nominate || pair.remoteNominated)
1119
+ pair.nominated = true;
1120
+ pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
1121
+ if (!pair.nominated &&
1122
+ this.iceControlling &&
1123
+ !generation.nominated &&
1124
+ !generation.nominating) {
1125
+ // Regular nomination (the peer is ICE-lite, so the checks carried no
1126
+ // USE-CANDIDATE), as the live checklist does: nominate the first pair
1127
+ // that succeeded with a check that carries it.
1128
+ await this.nominateProvisional(generation, pair, belongs);
1129
+ }
1130
+ if (pair.nominated && !generation.nominated) {
1131
+ log("provisional nominated", pair.toJSON());
1132
+ generation.nominated = pair;
1133
+ }
1134
+ }
1135
+ async nominateProvisional(generation, pair, belongs) {
1136
+ generation.nominating = true;
1137
+ const request = this.buildRequest({
1138
+ nominate: true,
1139
+ localUsername: generation.localUsername,
1140
+ remoteUsername: generation.remoteUsername,
1141
+ iceControlling: this.iceControlling,
1142
+ localCandidate: pair.localCandidate,
1143
+ });
1144
+ try {
1145
+ pair.requestsSent++;
1146
+ await pair.protocol.request(request, pair.remoteAddr, Buffer.from(generation.remotePassword, "utf8"), {
1147
+ retransmissions: pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4,
1148
+ // endProvisional / a replacement pranswer stops it with the checks.
1149
+ signal: generation.checks.signal,
1150
+ });
1151
+ pair.responsesReceived++;
1152
+ if (belongs())
1153
+ pair.nominated = true;
1154
+ }
1155
+ catch (error) {
1156
+ log("provisional regular nomination failed", error);
1157
+ }
1158
+ finally {
1159
+ if (belongs())
1160
+ generation.nominating = false;
1161
+ }
1162
+ }
1163
+ /** Incoming check for the provisional ufrag; never touches the current checklist. */
1164
+ checkIncomingProvisional(generation, message, addr, protocol) {
1165
+ // Only checks from the remote credentials of the current checklist count
1166
+ // (a replacement pranswer replaced any earlier ones).
1167
+ const txUsername = message.getAttributeValue("USERNAME");
1168
+ const sender = typeof txUsername === "string"
1169
+ ? decodeTxUsername(txUsername).localUsername
1170
+ : undefined;
1171
+ if (generation.remoteUsername && sender !== generation.remoteUsername) {
1172
+ return;
1173
+ }
1174
+ const [host, port] = addr;
1175
+ let remoteCandidate = generation.remoteCandidates.find((c) => c.host === host && c.port === port);
1176
+ if (!remoteCandidate) {
1177
+ remoteCandidate = new candidate_1.Candidate((0, helper_1.randomString)(10), 1, protocol.localCandidate?.transport ?? "udp", message.getAttributeValue("PRIORITY"), host, port, "prflx", undefined, undefined, protocol.localCandidate?.transport === "tcp"
1178
+ ? (0, candidate_1.remoteTcpTypeForIncoming)(protocol.localCandidate.tcptype)
1179
+ : undefined, undefined, undefined);
1180
+ generation.remoteCandidates.push(remoteCandidate);
1181
+ }
1182
+ let pair = generation.pairs.find((p) => p.protocol === protocol && p.remoteCandidate === remoteCandidate);
1183
+ if (!pair) {
1184
+ pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
1185
+ pair.updateState(iceBase_1.CandidatePairState.WAITING);
1186
+ generation.pairs.push(pair);
1187
+ }
1188
+ pair.noteIncomingRequest(message.transactionIdHex);
1189
+ pair.requestsReceived++;
1190
+ pair.responsesSent++;
1191
+ if (message.attributesKeys.includes("USE-CANDIDATE") &&
1192
+ !this.iceControlling) {
1193
+ pair.remoteNominated = true;
1194
+ if (this.iceLite || pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
1195
+ pair.nominated = true;
1196
+ pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
1197
+ generation.nominated ?? (generation.nominated = pair);
1198
+ }
1199
+ }
1200
+ if (!this.iceLite &&
1201
+ [iceBase_1.CandidatePairState.WAITING, iceBase_1.CandidatePairState.FAILED].includes(pair.state)) {
1202
+ void this.checkProvisional(generation, pair);
1203
+ }
1204
+ }
1205
+ /** Called after restart, before re-gathering the chosen generation. */
1206
+ commitLocalCredentials(usernameFragment, password) {
1207
+ // The credentials restart() generated were never signalled: these replace them.
1208
+ if (this.localUsername !== usernameFragment) {
1209
+ delete this.userHistory[this.localUsername];
1210
+ }
1211
+ this.localUsername = usernameFragment;
1212
+ this.localPassword = password;
1213
+ this.userHistory[usernameFragment] = password;
1214
+ for (const protocol of this.protocols) {
1215
+ if (protocol.localCandidate) {
1216
+ protocol.localCandidate.ufrag = usernameFragment;
1217
+ }
1218
+ }
1219
+ }
1220
+ /**
1221
+ * Drop the remote candidates (and their pairs) that name a ufrag other than
1222
+ * `usernameFragment`: they belong to another remote generation and cannot
1223
+ * pass checks with its credentials. Candidates without a ufrag stay.
1224
+ */
1225
+ dropOtherRemoteGenerations(usernameFragment) {
1226
+ const stale = (candidate) => !!candidate.ufrag && candidate.ufrag !== usernameFragment;
1227
+ this._remoteCandidates = this._remoteCandidates.filter((candidate) => !stale(candidate));
1228
+ for (const pair of this.checkList) {
1229
+ if (stale(pair.remoteCandidate))
1230
+ pair.handle?.resolve?.();
1231
+ }
1232
+ this.checkList = this.checkList.filter((pair) => !stale(pair.remoteCandidate));
700
1233
  }
701
1234
  resetNominatedPair() {
702
1235
  log("resetNominatedPair");
@@ -712,9 +1245,24 @@ class Connection {
712
1245
  this.remotePassword = password;
713
1246
  }
714
1247
  // 4.1.1 Gathering Candidates
1248
+ /**
1249
+ * Gather the local candidates of the current generation.
1250
+ *
1251
+ * After an ICE restart everything the kept sockets already advertised is
1252
+ * advertised again synchronously, before this method first awaits: the host
1253
+ * candidates and the server-reflexive address each kept socket had. Only
1254
+ * work that needs a server follows (a fresh STUN query, a new TURN
1255
+ * allocation), so a caller may let it finish in the background.
1256
+ */
715
1257
  async gatherCandidates() {
716
1258
  if (!this.localCandidatesStart) {
717
1259
  this.localCandidatesStart = true;
1260
+ const generation = this.generation;
1261
+ // An ICE restart allocates TURN afresh, which is how a restart recovers
1262
+ // from an allocation that died: the previous one leaves the generation.
1263
+ const previousTurn = this.protocols.filter((protocol) => protocol.localCandidate?.type === "relay");
1264
+ this.protocols = this.protocols.filter((protocol) => !previousTurn.includes(protocol));
1265
+ void Promise.allSettled(previousTurn.map((protocol) => protocol.close()));
718
1266
  // ICE restart keeps transport protocols; re-advertise their host candidates
719
1267
  // with the new generation / ufrag before gathering additional addresses.
720
1268
  for (const protocol of this.protocols) {
@@ -722,26 +1270,57 @@ class Connection {
722
1270
  protocol.localCandidate.generation = this.generation;
723
1271
  protocol.localCandidate.ufrag = this.localUsername;
724
1272
  this.appendLocalCandidate(protocol.localCandidate);
1273
+ const reflexive = this.reflexiveBySocket.get(protocol);
1274
+ if (reflexive) {
1275
+ this.appendLocalCandidate(this.withGeneration(reflexive));
1276
+ }
725
1277
  }
726
1278
  }
727
- let address = (0, utils_1.getHostAddresses)(this.options.useIpv4, this.options.useIpv6, {
728
- useLinkLocalAddress: this.options.useLinkLocalAddress,
1279
+ // A family bound to an explicit interface address gathers only that
1280
+ // address, so the advertised host candidate is the socket's address.
1281
+ const address = (0, resolveHostAddresses_1.resolveHostAddresses)({
1282
+ enumerated: (0, utils_1.getHostAddresses)(this.options.useIpv4, this.options.useIpv6, {
1283
+ useLinkLocalAddress: this.options.useLinkLocalAddress,
1284
+ }),
1285
+ interfaceAddresses: this.options.interfaceAddresses,
1286
+ additionalHostAddresses: this.options.additionalHostAddresses,
1287
+ useIpv4: this.options.useIpv4,
1288
+ useIpv6: this.options.useIpv6,
1289
+ log,
729
1290
  });
730
- const { interfaceAddresses } = this.options;
731
- if (interfaceAddresses) {
732
- const filteredAddresses = address.filter((check) => Object.values(interfaceAddresses).includes(check));
733
- if (filteredAddresses.length) {
734
- address = filteredAddresses;
735
- }
736
- }
737
- if (this.options.additionalHostAddresses) {
738
- address = Array.from(new Set([...this.options.additionalHostAddresses, ...address]));
739
- }
740
- const candidatePromises = this.getCandidatePromises(address, this.options.stunGatherTimeout);
741
- await Promise.allSettled(candidatePromises);
1291
+ const candidatePromises = this.getCandidatePromises(address, this.options.stunGatherTimeout, generation);
1292
+ // close() ends the gathering at once: the continuations above close
1293
+ // whatever a server query still opens for a closed agent.
1294
+ await Promise.race([
1295
+ Promise.allSettled(candidatePromises),
1296
+ this.closedSignal,
1297
+ ]);
1298
+ // A later ICE restart (or close) owns the agent now: this gathering
1299
+ // neither completes that generation nor touches its state.
1300
+ if (!this.isGathering(generation))
1301
+ return;
742
1302
  this.localCandidatesEnd = true;
743
1303
  }
744
- this.setState("completed");
1304
+ // Gathering that finishes after connectivity checks began (an ICE restart
1305
+ // keeps gathering from its servers) must not overwrite their state: the
1306
+ // agent stays "new" while checking, and only the checks' outcome moves it.
1307
+ if (this.state === "new" && !this.checksBegun)
1308
+ this.setState("completed");
1309
+ }
1310
+ /**
1311
+ * Whether gathering started for `generation` still belongs to the agent:
1312
+ * no ICE restart replaced the generation and the agent is not closed.
1313
+ */
1314
+ isGathering(generation) {
1315
+ return this.generation === generation && this.state !== "closed";
1316
+ }
1317
+ /** A copy of `candidate` labelled with the current generation and ufrag. */
1318
+ withGeneration(candidate) {
1319
+ return new candidate_1.Candidate(candidate.foundation, candidate.component, candidate.transport, candidate.priority, candidate.host, candidate.port, candidate.type, candidate.relatedAddress, candidate.relatedPort, candidate.tcptype, this.generation, this.localUsername);
1320
+ }
1321
+ /** Whether gathering contacts a STUN or TURN server (more than re-advertising sockets). */
1322
+ get gathersFromServers() {
1323
+ return !!this.stunServer || !!this.turnServer;
745
1324
  }
746
1325
  appendLocalCandidate(candidate) {
747
1326
  this.localCandidates.push(candidate);
@@ -761,7 +1340,7 @@ class Connection {
761
1340
  // 7.2.1.1. Detecting and Repairing Role Conflicts
762
1341
  if (iceControlling && msg.attributesKeys.includes("ICE-CONTROLLING")) {
763
1342
  if (this.tieBreaker >= msg.getAttributeValue("ICE-CONTROLLING")) {
764
- this.respondError(msg, addr, protocol, [487, "Role Conflict"]);
1343
+ this.respondError(msg, addr, protocol, [487, "Role Conflict"], localPassword);
765
1344
  return;
766
1345
  }
767
1346
  else {
@@ -772,7 +1351,7 @@ class Connection {
772
1351
  msg.attributesKeys.includes("ICE-CONTROLLED")) {
773
1352
  if (this.iceLite ||
774
1353
  this.tieBreaker < msg.getAttributeValue("ICE-CONTROLLED")) {
775
- this.respondError(msg, addr, protocol, [487, "Role Conflict"]);
1354
+ this.respondError(msg, addr, protocol, [487, "Role Conflict"], localPassword);
776
1355
  return;
777
1356
  }
778
1357
  else {
@@ -793,6 +1372,13 @@ class Connection {
793
1372
  protocol.sendStun(response, addr).catch((e) => {
794
1373
  log("sendStun error", e);
795
1374
  });
1375
+ const provisional = this.provisional;
1376
+ if (provisional &&
1377
+ localUsername === provisional.localUsername &&
1378
+ localUsername !== this.localUsername) {
1379
+ this.checkIncomingProvisional(provisional, msg, addr, protocol);
1380
+ return;
1381
+ }
796
1382
  if (this.checkList.length === 0 && !this.earlyChecksDone) {
797
1383
  this.earlyChecks.push([msg, addr, protocol]);
798
1384
  }
@@ -838,10 +1424,14 @@ class Connection {
838
1424
  this.stopConsentLifecycle();
839
1425
  this.setState("failed");
840
1426
  }
841
- getCandidatePromises(addresses, timeout = 5) {
1427
+ getCandidatePromises(addresses, timeout = 5, generation = this.generation) {
842
1428
  const candidatePromises = [];
1429
+ // Each continuation below runs after an await: a socket or allocation it
1430
+ // opened for a replaced generation (or a closed agent) is closed, and
1431
+ // nothing is added to the current one.
1432
+ const stale = () => !this.isGathering(generation);
843
1433
  const { stunServer, turnServer } = this;
844
- const { turnUsername, turnPassword } = this.options;
1434
+ const { turnUsername, turnPassword, interfaceAddresses } = this.options;
845
1435
  const gatherIceLite = this.iceLite;
846
1436
  const gatherRelayOnly = !gatherIceLite &&
847
1437
  this.options.forceTurn &&
@@ -853,31 +1443,66 @@ class Connection {
853
1443
  if (this.protocols.find((protocol) => protocol.localIp === address)) {
854
1444
  return false;
855
1445
  }
1446
+ // A family bound to an interface address has one UDP host socket; its
1447
+ // localIp is the bound address, whose notation may differ (IPv6).
1448
+ if ((0, common_1.interfaceAddress)(socketTypeOf(address), interfaceAddresses) ===
1449
+ address &&
1450
+ this.protocols.some((protocol) => protocol instanceof protocol_1.StunProtocol &&
1451
+ protocol.localCandidate?.type === "host" &&
1452
+ (0, net_1.isIPv4)(protocol.localCandidate.host) === (0, net_1.isIPv4)(address))) {
1453
+ return false;
1454
+ }
856
1455
  return true;
857
1456
  });
1457
+ // An ICE restart keeps its UDP sockets. They are not re-created above, but
1458
+ // their server-reflexive address is part of the new generation too, so
1459
+ // the STUN query below runs for them as well.
1460
+ const reusedStunProtocols = this.protocols.filter((protocol) => protocol instanceof protocol_1.StunProtocol &&
1461
+ protocol.localCandidate?.type === "host" &&
1462
+ protocol.localCandidate.transport === "udp");
858
1463
  const localStunPromises = gatherRelayOnly
859
1464
  ? []
860
1465
  : addresses.map(async (address) => {
861
1466
  // # create transport
862
1467
  const protocol = new protocol_1.StunProtocol();
863
1468
  this.ensureProtocol(protocol);
1469
+ const boundInterface = (0, common_1.interfaceAddress)(socketTypeOf(address), interfaceAddresses);
864
1470
  try {
865
- await protocol.connectionMade((0, net_1.isIPv4)(address), this.options.portRange, this.options.interfaceAddresses);
866
- protocol.localIp = address;
1471
+ await protocol.connectionMade((0, net_1.isIPv4)(address), this.options.portRange, interfaceAddresses);
1472
+ if (stale()) {
1473
+ await protocol.close();
1474
+ return;
1475
+ }
1476
+ // # add host candidate
1477
+ // A socket bound to an interface address advertises that address:
1478
+ // the peer sends its checks there. A wildcard socket advertises
1479
+ // the gathered address (never 0.0.0.0 / ::).
1480
+ const [boundHost, boundPort] = protocol.getExtraInfo();
1481
+ let candidateHost = address;
1482
+ if (boundInterface) {
1483
+ candidateHost = stripZoneId(boundHost);
1484
+ if (candidateHost !== address) {
1485
+ log("host address differs from the bound interface address; advertise the bound one", address, candidateHost);
1486
+ }
1487
+ }
1488
+ const candidateAddress = [candidateHost, boundPort];
1489
+ protocol.localIp = candidateHost;
867
1490
  this.protocols.push(protocol);
868
1491
  log("protocol", protocol.localIp);
869
- // # add host candidate
870
- const candidateAddress = [
871
- address,
872
- protocol.getExtraInfo()[1],
873
- ];
874
1492
  protocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "udp", candidateAddress[0]), 1, "udp", (0, candidate_1.candidatePriority)("host", { transport: "udp" }), candidateAddress[0], candidateAddress[1], "host", undefined, undefined, undefined, this.generation, this.localUsername);
875
1493
  this.pairLocalProtocol(protocol);
876
1494
  this.appendLocalCandidate(protocol.localCandidate);
877
1495
  return protocol;
878
1496
  }
879
1497
  catch (error) {
880
- log("error protocol STUN", error);
1498
+ if (boundInterface) {
1499
+ // No host candidate for this family: advertising another
1500
+ // address than the socket's would mislead the peer.
1501
+ log("failed to bind UDP socket to interface address", boundInterface, error);
1502
+ }
1503
+ else {
1504
+ log("error protocol STUN", error);
1505
+ }
881
1506
  }
882
1507
  });
883
1508
  if (!gatherRelayOnly) {
@@ -892,6 +1517,10 @@ class Connection {
892
1517
  const passiveProtocol = new tcpProtocol_1.TcpPassiveProtocol();
893
1518
  this.ensureProtocol(passiveProtocol);
894
1519
  await passiveProtocol.connectionMade(address, this.options.portRange);
1520
+ if (stale()) {
1521
+ await passiveProtocol.close();
1522
+ return;
1523
+ }
895
1524
  passiveProtocol.localIp = address;
896
1525
  passiveProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
897
1526
  transport: "tcp",
@@ -904,6 +1533,10 @@ class Connection {
904
1533
  const activeProtocol = new tcpProtocol_1.TcpActiveProtocol();
905
1534
  this.ensureProtocol(activeProtocol);
906
1535
  await activeProtocol.connectionMade(address);
1536
+ if (stale()) {
1537
+ await activeProtocol.close();
1538
+ return;
1539
+ }
907
1540
  activeProtocol.localIp = address;
908
1541
  activeProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
909
1542
  transport: "tcp",
@@ -917,6 +1550,31 @@ class Connection {
917
1550
  candidatePromises.push(...tcpCandidatePromises);
918
1551
  }
919
1552
  if (!gatherIceLite && !gatherRelayOnly && stunServer) {
1553
+ // Sockets kept across an ICE restart query STUN again. The mapping they
1554
+ // already advertised is in the new generation from the start; a
1555
+ // different fresh mapping (the NAT rebound) is added to it.
1556
+ const reusedReflexivePromises = reusedStunProtocols
1557
+ .filter((protocol) => (0, net_1.isIPv4)(protocol.localCandidate.host))
1558
+ .map(async (protocol) => {
1559
+ let timer;
1560
+ const fresh = await Promise.race([
1561
+ (0, iceBase_1.serverReflexiveCandidate)(protocol, stunServer).catch(() => undefined),
1562
+ new Promise((resolve) => {
1563
+ timer = setTimeout(() => resolve(undefined), timeout * 1000);
1564
+ }),
1565
+ ]);
1566
+ clearTimeout(timer);
1567
+ if (stale())
1568
+ return;
1569
+ const previous = this.reflexiveBySocket.get(protocol);
1570
+ if (fresh &&
1571
+ (fresh.host !== previous?.host || fresh.port !== previous?.port)) {
1572
+ this.reflexiveBySocket.set(protocol, fresh);
1573
+ this.appendLocalCandidate(fresh);
1574
+ }
1575
+ return fresh ?? previous;
1576
+ });
1577
+ candidatePromises.push(...reusedReflexivePromises);
920
1578
  const stunCandidatePromises = localStunPromises.map(async (protocolPromise) => {
921
1579
  const protocol = await protocolPromise;
922
1580
  if (!protocol)
@@ -928,7 +1586,8 @@ class Connection {
928
1586
  const candidate = await (0, iceBase_1.serverReflexiveCandidate)(protocol, stunServer).catch((error) => {
929
1587
  log("error", error);
930
1588
  });
931
- if (candidate) {
1589
+ if (candidate && !stale()) {
1590
+ this.reflexiveBySocket.set(protocol, candidate);
932
1591
  this.appendLocalCandidate(candidate);
933
1592
  }
934
1593
  clearTimeout(timer);
@@ -959,8 +1618,10 @@ class Connection {
959
1618
  tlsOptions: this.options.turnTlsOptions,
960
1619
  connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
961
1620
  udpFamily: this.options.turnUdpFamily,
1621
+ signal: this.closing.signal,
962
1622
  }).catch(async (e) => {
963
- if (turnTransport === "udp") {
1623
+ // close() cancelled the allocation: no TCP fallback.
1624
+ if (turnTransport === "udp" && !this.closing.signal.aborted) {
964
1625
  return await (0, protocol_2.createStunOverTurnClient)({
965
1626
  address: turnServer,
966
1627
  username: turnUsername,
@@ -970,18 +1631,29 @@ class Connection {
970
1631
  interfaceAddresses: this.options.interfaceAddresses,
971
1632
  transport: "tcp",
972
1633
  connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
1634
+ signal: this.closing.signal,
973
1635
  });
974
1636
  }
975
1637
  else {
976
1638
  throw e;
977
1639
  }
978
1640
  });
1641
+ if (stale()) {
1642
+ // The allocation never joins a generation: release it (and its
1643
+ // refresh timer) instead of keeping a second one alive.
1644
+ await protocol.close();
1645
+ return;
1646
+ }
979
1647
  this.ensureProtocol(protocol);
980
1648
  this.protocols.push(protocol);
981
1649
  const candidateAddress = protocol.turn.relayedAddress;
982
1650
  const relatedAddress = protocol.turn.mappedAddress;
983
1651
  log("turn candidateAddress", candidateAddress);
984
1652
  protocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("relay", "udp", candidateAddress[0]), 1, "udp", (0, candidate_1.candidatePriority)("relay"), candidateAddress[0], candidateAddress[1], "relay", relatedAddress[0], relatedAddress[1], undefined, this.generation, this.localUsername);
1653
+ // An allocation that completes after the remote candidates arrived
1654
+ // (early signaling, or an ICE restart that allocates afresh) pairs
1655
+ // with them; a connect() already running schedules the new pairs.
1656
+ this.pairLocalProtocol(protocol);
985
1657
  this.appendLocalCandidate(protocol.localCandidate);
986
1658
  return protocol.localCandidate;
987
1659
  })().catch((error) => {
@@ -1007,6 +1679,7 @@ class Connection {
1007
1679
  if (!this.remoteUsername || !this.remotePassword) {
1008
1680
  throw new Error("Remote username or password is missing");
1009
1681
  }
1682
+ this.checksBegun = true;
1010
1683
  // # 5.7.1. Forming Candidate Pairs
1011
1684
  for (const c of this.remoteCandidates) {
1012
1685
  this.pairRemoteCandidate(c);
@@ -1110,8 +1783,10 @@ class Connection {
1110
1783
  return true;
1111
1784
  }
1112
1785
  }
1113
- // # if we expect more candidates, keep going
1114
- if (!this.remoteCandidatesEnd) {
1786
+ // # if we expect more candidates, keep going: remote ones until
1787
+ // end-of-candidates, local ones until this generation's gathering ends
1788
+ // (a relay candidate of an ICE restart can follow the remote ones).
1789
+ if (!this.remoteCandidatesEnd || !this.localCandidatesEnd) {
1115
1790
  return !this.checkListDone;
1116
1791
  }
1117
1792
  return false;
@@ -1177,6 +1852,10 @@ class Connection {
1177
1852
  // Close the connection.
1178
1853
  // """
1179
1854
  this.setState("closed");
1855
+ this.signalClosed();
1856
+ this.closing.abort();
1857
+ this.cancelChecks();
1858
+ this.endProvisional();
1180
1859
  // # stop consent freshness tests
1181
1860
  this.stopConsentLifecycle();
1182
1861
  // # stop check list
@@ -1200,6 +1879,14 @@ class Connection {
1200
1879
  this.state = state;
1201
1880
  this.stateChanged.execute(state);
1202
1881
  }
1882
+ /**
1883
+ * Known constraint (as in develop): candidates are not deduplicated. A
1884
+ * description applied again in the same generation (BUNDLE split and
1885
+ * merge after an ICE restart) adds its candidates and pairs a second time,
1886
+ * until the next restart. Deduplicating here alone breaks the pairs a
1887
+ * provisional generation dropped and the repeated add rebuilds; a fix needs
1888
+ * the pairing and provisional lifecycle together.
1889
+ */
1203
1890
  async addRemoteCandidate(remoteCandidate) {
1204
1891
  // """
1205
1892
  // Add a remote candidate or signal end-of-candidates.
@@ -1207,20 +1894,45 @@ class Connection {
1207
1894
  // :param remote_candidate: A :class:`Candidate` instance or `None`.
1208
1895
  // """
1209
1896
  if (!remoteCandidate) {
1897
+ if (this.remoteCandidatesEnd || this.remoteCandidatesEndRequested) {
1898
+ return;
1899
+ }
1900
+ // Candidates that arrived before end-of-candidates finish first.
1901
+ this.remoteCandidatesEndRequested = true;
1902
+ if (this.remoteResolutions.size > 0) {
1903
+ const generation = this.remoteGeneration;
1904
+ await Promise.allSettled([...this.remoteResolutions]);
1905
+ if (this.remoteGeneration !== generation)
1906
+ return;
1907
+ }
1210
1908
  this.remoteCandidatesEnd = true;
1211
1909
  return;
1212
1910
  }
1911
+ // RFC 8838: a completed generation takes no further candidates.
1912
+ if (this.remoteCandidatesEnd || this.remoteCandidatesEndRequested) {
1913
+ return;
1914
+ }
1213
1915
  if (remoteCandidate.host.includes(".local")) {
1916
+ const generation = this.remoteGeneration;
1214
1917
  try {
1215
1918
  if (!this.lookup) {
1216
1919
  this.lookup = new lookup_1.MdnsLookup();
1217
1920
  }
1218
- const host = await this.lookup.lookup(remoteCandidate.host);
1219
- remoteCandidate.host = host;
1921
+ const resolution = this.lookup.lookup(remoteCandidate.host);
1922
+ this.remoteResolutions.add(resolution);
1923
+ try {
1924
+ remoteCandidate.host = await resolution;
1925
+ }
1926
+ finally {
1927
+ this.remoteResolutions.delete(resolution);
1928
+ }
1220
1929
  }
1221
1930
  catch (error) {
1222
1931
  return;
1223
1932
  }
1933
+ // An ICE restart or completion while resolving ends this candidate's generation.
1934
+ if (this.remoteGeneration !== generation || this.remoteCandidatesEnd)
1935
+ return;
1224
1936
  }
1225
1937
  try {
1226
1938
  (0, iceBase_1.validateRemoteCandidate)(remoteCandidate);
@@ -1292,14 +2004,24 @@ class Connection {
1292
2004
  // concludes the ICE processing for that component. See Section 8.
1293
2005
  // So disallow overwriting of the pair nominated for that component
1294
2006
  if (pair.nominated &&
1295
- // remoteのgenerationをチェックする.localのgenerationは更新が間に合わないかもしれないのでチェックしない
1296
- (pair.remoteCandidate.generation != undefined
1297
- ? pair.remoteCandidate.generation === this.generation
1298
- : true) &&
2007
+ // The pair belongs to the live remote generation: it is in the
2008
+ // current checklist (a restart resets it, so a check still in flight
2009
+ // from a discarded generation cannot select its pair) and its remote
2010
+ // candidate names the live remote ufrag, if it names one. The SDP
2011
+ // `generation` attribute counts the peer's own restarts and is not
2012
+ // comparable with the local generation (a remote-only restart, or a
2013
+ // peer that numbers differently).
2014
+ this.checkList.includes(pair) &&
2015
+ (pair.remoteCandidate.ufrag == undefined ||
2016
+ pair.remoteCandidate.ufrag === this.remoteUsername) &&
1299
2017
  this.nominated == undefined) {
1300
2018
  log("nominated", pair.toJSON());
1301
2019
  this.nominated = pair;
1302
2020
  this.nominating = false;
2021
+ // RFC 7675 section 5.1: the successful connectivity check that
2022
+ // selected the pair is its initial consent, so data may flow at once
2023
+ // instead of waiting for the consent lifecycle to start.
2024
+ this.consentFresh = true;
1303
2025
  this.pruneTcpConnections(pair);
1304
2026
  // After resetNominatedPair / renomination while already connected,
1305
2027
  // restart consent freshness on the new selected pair.
@@ -1355,13 +2077,27 @@ class Connection {
1355
2077
  return;
1356
2078
  }
1357
2079
  }
1358
- if (!this.checkListDone) {
2080
+ // RFC 8838 §8: with trickle ICE the check list fails only once neither
2081
+ // side can add candidates any more; a relay candidate still being gathered
2082
+ // (or a remote one before end-of-candidates) may yet pair and succeed.
2083
+ if (!this.checkListDone &&
2084
+ this.localCandidatesEnd &&
2085
+ this.remoteCandidatesEnd) {
1359
2086
  log("ICE failed");
1360
2087
  this.checkListState.put(new Promise((r) => {
1361
2088
  r(iceBase_1.ICE_FAILED);
1362
2089
  }));
1363
2090
  }
1364
2091
  }
2092
+ /**
2093
+ * 487 / 401 retry of a check: the retry is cancelled with the check it
2094
+ * replaces (its handle) and, through checkStart, with the generation.
2095
+ */
2096
+ async retryCheck(pair, onCancel) {
2097
+ const retry = this.checkStart(pair);
2098
+ onCancel.once(() => retry.resolve());
2099
+ await retry.awaitable;
2100
+ }
1365
2101
  isTcpPair(pair) {
1366
2102
  return pair.localCandidate.transport.toLowerCase() === "tcp";
1367
2103
  }
@@ -1418,7 +2154,7 @@ class Connection {
1418
2154
  }
1419
2155
  nominateTcpPair(pair) {
1420
2156
  this.nominating = true;
1421
- const { generation } = this;
2157
+ const generation = this.remoteGeneration;
1422
2158
  const request = this.buildRequest({
1423
2159
  nominate: true,
1424
2160
  localUsername: pair.localCandidate.ufrag ?? this.localUsername,
@@ -1428,7 +2164,7 @@ class Connection {
1428
2164
  });
1429
2165
  pair.requestsSent++;
1430
2166
  pair.protocol
1431
- .request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), this.checkRequestOptions(pair))
2167
+ .request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal: this.remoteChecks.signal })
1432
2168
  .then(() => {
1433
2169
  if (this.isStaleNomination(pair, generation)) {
1434
2170
  return;
@@ -1450,7 +2186,7 @@ class Connection {
1450
2186
  /** The agent was closed or restarted while the nomination was in flight. */
1451
2187
  isStaleNomination(pair, generation) {
1452
2188
  return (this.state === "closed" ||
1453
- this.generation !== generation ||
2189
+ this.remoteGeneration !== generation ||
1454
2190
  !this.checkList.includes(pair));
1455
2191
  }
1456
2192
  addPair(pair) {
@@ -1491,7 +2227,10 @@ class Connection {
1491
2227
  pair.noteIncomingRequest(message.transactionIdHex);
1492
2228
  pair.requestsReceived++;
1493
2229
  pair.responsesSent++;
1494
- pair.localCandidate.ufrag = localUsername;
2230
+ // The pair's local candidate is the protocol's shared candidate of the
2231
+ // current generation. A late check addressed to an earlier ufrag (consent
2232
+ // on the old pair during an ICE restart) must not relabel it, or the next
2233
+ // description would advertise it under that old ufrag.
1495
2234
  log("Triggered Checks", message.toJSON(), pair.toJSON(), {
1496
2235
  localUsername: this.localUsername,
1497
2236
  remoteUsername: this.remoteUsername,
@@ -1538,7 +2277,16 @@ class Connection {
1538
2277
  this.addPair(pair);
1539
2278
  }
1540
2279
  }
2280
+ /**
2281
+ * Pair a local candidate gathered after remote candidates arrived (a late
2282
+ * TURN allocation, a slow host socket) with them.
2283
+ */
1541
2284
  pairLocalProtocol(protocol) {
2285
+ // RFC 8445 §8.1.2: once a pair is selected, the check list takes no more
2286
+ // Waiting pairs, so a candidate gathered later starts no check.
2287
+ if (this.nominated || this.checkListDone || this.state === "closed") {
2288
+ return;
2289
+ }
1542
2290
  for (const remoteCandidate of this.remoteCandidates) {
1543
2291
  this.tryPair(protocol, remoteCandidate);
1544
2292
  }
@@ -1574,11 +2322,16 @@ class Connection {
1574
2322
  }
1575
2323
  }
1576
2324
  }
1577
- respondError(request, addr, protocol, errorCode) {
2325
+ respondError(request, addr, protocol, errorCode,
2326
+ /**
2327
+ * The password of the local ufrag the request is addressed to: a check
2328
+ * for a staged (provisional) generation is verified with its password.
2329
+ */
2330
+ localPassword = this.localPassword) {
1578
2331
  const response = new message_1.Message(request.messageMethod, const_1.classes.ERROR, request.transactionId);
1579
2332
  response
1580
2333
  .setAttribute("ERROR-CODE", errorCode)
1581
- .addMessageIntegrity(Buffer.from(this.localPassword, "utf8"))
2334
+ .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
1582
2335
  .addFingerprint();
1583
2336
  protocol.sendStun(response, addr).catch((e) => {
1584
2337
  log("sendStun error", e);
@@ -1593,4 +2346,7 @@ const decodeTxUsername = (txUsername) => {
1593
2346
  const [remoteUsername, localUsername] = txUsername.split(":");
1594
2347
  return { remoteUsername, localUsername };
1595
2348
  };
2349
+ const socketTypeOf = (address) => ((0, net_1.isIPv4)(address) ? "udp4" : "udp6");
2350
+ /** Candidates carry no IPv6 zone id (e.g. `fe80::1%eth0`). */
2351
+ const stripZoneId = (address) => address.split("%")[0];
1596
2352
  //# sourceMappingURL=ice.js.map